diff --git a/packages/minimax/README.md b/packages/minimax/README.md index bfd4e21..0318506 100644 --- a/packages/minimax/README.md +++ b/packages/minimax/README.md @@ -161,6 +161,18 @@ 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. +## The China site's account host + +The China site's account API (the usage card, the check-in, the account +and its membership) is on `agent.minimaxi.com`, and `agent.minimax.cn` +serves the same API with the same sign-in. A call `agent.minimaxi.com` +gives no HTTP answer to (a TLS error such as "unable to get issuer +certificate", a refused or reset connection) is sent once to +`agent.minimax.cn`. Any answer from `agent.minimaxi.com` — a 401, another +status, an error in the body, a redirect — and a timeout are kept as they +are, never sent again. When both hosts can't be reached, the error names +both and why. + ## Models When you are signed in, the models come from MiniMax Code's live model diff --git a/packages/minimax/fake.mjs b/packages/minimax/fake.mjs index 5534c83..84e1c68 100644 --- a/packages/minimax/fake.mjs +++ b/packages/minimax/fake.mjs @@ -26,7 +26,7 @@ export function fakeMiniMax() { const was = {} for (const [id, s] of Object.entries(_internal.SITES)) { was[id] = { ...s } - Object.assign(s, { account: origin, llm: origin, agent: origin, platform: origin }) + Object.assign(s, { account: origin, llm: origin, agent: origin, platform: origin, ...(s.agentFallback ? { agentFallback: origin } : {}) }) } _internal.renewing.clear() _internal.renewed.clear() diff --git a/packages/minimax/fallback.test.mjs b/packages/minimax/fallback.test.mjs new file mode 100644 index 0000000..38a0ca4 --- /dev/null +++ b/packages/minimax/fallback.test.mjs @@ -0,0 +1,127 @@ +// The China site's account API is on agent.minimaxi.com and on +// agent.minimax.cn, with the same tokens. When agent.minimaxi.com can't be +// reached at all (a TLS error: youyo.p_10001's "unable to get issuer +// certificate", plugins#757), the call goes once to agent.minimax.cn. An +// HTTP answer from agent.minimaxi.com — a 401, a 404, a 5xx, a business +// error in its body, a redirect — is the answer, and is never sent again. +// +// agent.minimaxi.com is played by a TLS server whose leaf was issued by an +// intermediate the client has never seen (testdata/leaf.pem, served alone), +// so its fetch fails the way the reporter's did; agent.minimax.cn by the +// usual fake. +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import { readFileSync } from "node:fs" +import { join } from "node:path" +import { MiniMaxCodeAuthPlugin, MiniMaxCodeGlobalAuthPlugin, _internal } from "./index.mjs" +import { fakeMiniMax, json } from "./fake.mjs" + +const td = join(import.meta.dir, "testdata") +let f, tls +afterEach(() => { + tls?.stop(true) + tls = undefined + f?.close() +}) + +const auth = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3600_000, accountId: "a@example.com" } +const china = () => _internal.SITES["minimax-code"] + +// a TLS server whose chain the client can't verify; seen counts what +// reached it over TLS (nothing should) +function untrusted() { + const seen = [] + tls = Bun.serve({ + port: 0, + hostname: "127.0.0.1", + tls: { cert: readFileSync(join(td, "leaf.pem"), "utf8"), key: readFileSync(join(td, "leaf.key"), "utf8") }, + fetch(req) { + seen.push(new URL(req.url).pathname) + return new Response("reached", { status: 500 }) + }, + }) + return { origin: `https://127.0.0.1:${tls.port}`, seen } +} + +function account(f) { + f.route("GET /v1/api/user/info", () => 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: [] } })) + f.route("POST /matrix/api/v1/commerce/get_membership_info", () => json({ base_resp: { status_code: 0 }, data: {} })) +} + +test("the account card is read from agent.minimax.cn when agent.minimaxi.com's chain doesn't verify", async () => { + f = fakeMiniMax() + account(f) + const bad = untrusted() + china().agent = bad.origin + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => auth) + expect(u.error).toBeUndefined() + expect(u.user).toBe("a@example.com") + expect(f.seen.some((r) => r.path === "/v1/api/user/info")).toBe(true) + expect(bad.seen).toEqual([]) +}) + +test("the check-in is claimed on agent.minimax.cn when agent.minimaxi.com can't be reached", async () => { + f = fakeMiniMax() + const bad = untrusted() + china().agent = bad.origin + f.route("GET /minimax-cloud/api/v1/signin/status", () => json({ base_resp: { status_code: 0 }, data: { days: Array.from({ length: 7 }, (_, i) => ({ day_no: i + 1, points: 10, status: i === 0 ? 2 : 1, is_today: i === 0 })) } })) + f.route("POST /minimax-cloud/api/v1/signin/claim", () => json({ base_resp: { status_code: 0 }, data: { claim_result: 1, points: 10 } })) + const hooks = await MiniMaxCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) + const c = await hooks.auth.checkin(async () => ({ ...auth, realUserID: "u-42" })) + expect(c).toEqual({ outcome: "claimed", credit: 10, streak: 1 }) + expect(bad.seen).toEqual([]) + expect(f.seen.filter((r) => r.path === "/minimax-cloud/api/v1/signin/status").length).toBe(1) +}) + +test("a call both hosts fail names both", async () => { + f = fakeMiniMax() + const bad = untrusted() + china().agent = bad.origin + china().agentFallback = bad.origin.replace("127.0.0.1", "localhost") + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => auth) + expect(u.error).toMatch(/127\.0\.0\.1:\d+ couldn't be reached \(.+\), nor localhost:\d+ \(.+\)/) + expect(u.signIn).toBe("kept") +}) + +// Each answer agent.minimaxi.com gives is the answer: the fallback host +// sees nothing. +for (const [name, reply] of [ + ["a 401", () => json({ error: "invalid access token" }, 401)], + ["a 404", () => new Response("not found", { status: 404 })], + ["a 502", () => new Response("bad gateway", { status: 502 })], + ["a business error", () => json({ statusInfo: { code: 0 }, base_resp: { status_code: 1004, status_msg: "denied" } })], + ["a redirect to another site", () => new Response(null, { status: 307, headers: { Location: "https://agent.minimax.io/v1/api/user/info" } })], +]) { + test(`${name} from agent.minimaxi.com is not sent to agent.minimax.cn`, async () => { + f = fakeMiniMax() + const fb = fakeMiniMax() + try { + // fb is agent.minimax.cn; f plays agent.minimaxi.com + china().agent = f.origin + china().agentFallback = fb.origin + f.route("GET /v1/api/user/info", reply) + f.route("POST /oauth2/token", () => json({ error: "invalid_grant" }, 400)) + account(fb) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + await hooks.auth.usage(async () => auth) + expect(f.seen.some((r) => r.path === "/v1/api/user/info")).toBe(true) + expect(fb.seen.filter((r) => r.path !== "/oauth2/token")).toEqual([]) + } finally { + fb.close() + } + }) +} + +test("the international site has no fallback host", async () => { + f = fakeMiniMax() + const bad = untrusted() + _internal.SITES["minimax-code-global"].agent = bad.origin + const hooks = await MiniMaxCodeGlobalAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => auth) + expect(u.error).toBeDefined() + expect(u.error).not.toMatch(/nor /) + expect(f.seen.filter((r) => r.path === "/v1/api/user/info")).toEqual([]) +}) diff --git a/packages/minimax/index.mjs b/packages/minimax/index.mjs index aecacdf..7d34b21 100644 --- a/packages/minimax/index.mjs +++ b/packages/minimax/index.mjs @@ -41,6 +41,7 @@ const SITES = { account: "https://account.minimax.cn", // OAuth llm: "https://agent.minimax.cn", // chats and the model list agent: "https://agent.minimaxi.com", // the account and its membership + agentFallback: "https://agent.minimax.cn", // the same account API, when agent.minimaxi.com can't be reached platform: "https://www.minimaxi.com", // the M Plan's windows }, "minimax-code-global": { @@ -474,9 +475,53 @@ function checked(env, what) { return env } +// unreached is a fetch that never got an HTTP answer: a TLS error (an +// issuer certificate it couldn't get, an expired or unknown chain), a +// refused or reset connection, a name that didn't resolve. A timeout or an +// abort is not one, and neither is a redirect to the other site. +function unreached(e) { + if (e instanceof OtherSite) return false + const name = e?.name ?? e?.cause?.name + return name !== "TimeoutError" && name !== "AbortError" +} + +// whyUnreached is a fetch error as one line, its code first when it has +// one (Bun puts it on the error, Node on its cause). +function whyUnreached(e) { + const code = e?.code ?? e?.cause?.code + const msg = e?.cause?.message ?? e?.message ?? String(e) + return code && !String(msg).includes(code) ? `${code}: ${msg}` : String(msg) +} + +// accountCall sends one call of the account API. The China site serves +// that API on agent.minimaxi.com and on agent.minimax.cn, with the same +// tokens and the same answers. A call agent.minimaxi.com can't be reached +// for is sent once to agent.minimax.cn: its chain (WoTrus DV Server CA +// under USERTrust) failed with "unable to get issuer certificate" on one +// Windows machine for hours while agent.minimax.cn's verified +// (youyo.p_10001, plugins#757). Only a call that got no HTTP answer goes +// again: a 401, any other status, a business error in the body, a +// redirect and a timeout are the answer, and are never sent twice. async function accountCall(site, path, opts, what) { - const { url, init } = signed(site, path, opts) - const res = await siteFetch(site, url, { ...init, signal: AbortSignal.timeout(15000) }, what) + const signal = AbortSignal.timeout(15000) + const origin = opts?.origin ?? site.agent + const send = (o) => { + const { url, init } = signed(site, path, { ...opts, origin: o }) + return siteFetch(site, url, { ...init, signal }, what) + } + let res + try { + res = await send(origin) + } catch (e) { + const alt = origin === site.agent ? site.agentFallback : undefined + if (!alt || alt === origin || !unreached(e)) throw e + try { + res = await send(alt) + } catch (e2) { + if (!unreached(e2)) throw e2 + throw new Error(`${what}: ${new URL(origin).host} couldn't be reached (${whyUnreached(e)}), nor ${new URL(alt).host} (${whyUnreached(e2)})`) + } + } 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 Object.assign(new Error(`${what}: HTTP ${res.status}`), { status: res.status }) let env diff --git a/packages/minimax/package.json b/packages/minimax/package.json index 7107d7d..aeedd15 100644 --- a/packages/minimax/package.json +++ b/packages/minimax/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-minimax-auth", - "version": "0.2.2", + "version": "0.2.3", "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": "./opencode.mjs", diff --git a/packages/minimax/testdata/leaf.key b/packages/minimax/testdata/leaf.key new file mode 100644 index 0000000..7581198 --- /dev/null +++ b/packages/minimax/testdata/leaf.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCHN+ABr888cmyc +ESly+fNqhpPi0PXnJ031LVC11KaC8qa31JWc9+EMho9mXkJ0VnOf4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4sxeQP555fpb/eFH+4XaOnGDGKwxpMkKNMl +oLQ8C6lgqXUZTZrorPf8Igqcgbo4kIqel/H5uIS3YMyYuQ5S6KxP5k7BAoGBAK3D +o2z/nWRb4v0D4VxqDBOWqr9ww6XF3eFsXNDxKpZDcJd7a5Hho4VLB6ilsI56dTeq +AfYy6SpBCBpZ5mnMLTRRovA8GyKTzWEGYcbny6W5/FoG5unbsjeRf0TNypoffvpO +jzdWjdpTOZD0eg+rNKk+8AmIc4NhjKFZwyBC+zy1AoGAUZTkoUGqXZmhVRokhO7r +vS6PAHwg9dxGHMkMJ41+Yj4HekRuZ29sRzUsttGn8/gtKjH1L+a58fyUXuoOEkWz +Iwn2UZgKT/7+vNeGolMs4KZyiBuYPJbfoc4CCKuih+uKqM7i6VtbFIve0wo9NbnI +oZjhkgwfjyZAV7m3QNh13C8= +-----END PRIVATE KEY----- diff --git a/packages/minimax/testdata/leaf.pem b/packages/minimax/testdata/leaf.pem new file mode 100644 index 0000000..a95abe6 --- /dev/null +++ b/packages/minimax/testdata/leaf.pem @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIC8zCCAdugAwIBAgIUCkAr5KnjmaUJ7NsxbJQyNtOg4DYwDQYJKoZIhvcNAQEL +BQAwHDEaMBgGA1UEAwwRVGVzdCBJbnRlcm1lZGlhdGUwIBcNMjYxMTA1MDgzNjMz +WhgPMjEyNjEwMTIwODM2MzNaMBQxEjAQBgNVBAMMCTEyNy4wLjAuMTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAIc34AGvzzxybJwRKXL582qGk+LQ9ecn +TfUtULXUpoLyprfUlZz34QyGj2ZeQnRWc5/gWHx3VJZMLJqHNRz7n0MqY/KE/l3S +N8Ssouq9LDil07sAQCaG9PX2YTGCZhnq5zBssWbvpDJECgtTSLc7MgjkTDAjp5NL +7cU8iGgDSGXRL/PrS4yntZBZKvcsCUuouPiklZcsqkcMnQpb6qtliHYgBS4fRtou +MUxhXEU622YV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