From af4a0b365dddb5f8bfb1450d22c7acf4b311ddc5 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 9 Oct 2026 01:50:45 +0800 Subject: [PATCH] =?UTF-8?q?mimo=200.1.9:=20an=20account=20with=20a=20Token?= =?UTF-8?q?=20Plan=20and=20no=20app=20membership=20gets=20answers=20(yeton?= =?UTF-8?q?e:=202=20=E4=B8=AA=E6=A8=A1=E5=9E=8B=E4=B8=AD=E6=9C=89=202=20?= =?UTF-8?q?=E4=B8=AA=E6=B2=A1=E6=9C=89=E5=93=8D=E5=BA=94).=20The=20app's?= =?UTF-8?q?=20/route=20answers=20such=20an=20account=20403=20membership=5F?= =?UTF-8?q?required=20("=E6=9C=AA=E5=BC=80=E9=80=9A=E4=BC=9A=E5=91=98?= =?UTF-8?q?=E6=88=96=E4=BC=9A=E5=91=98=E5=B7=B2=E5=88=B0=E6=9C=9F=EF=BC=8C?= =?UTF-8?q?=E8=AF=B7=E8=AE=A2=E9=98=85=E5=90=8E=E4=BD=BF=E7=94=A8")=20for?= =?UTF-8?q?=20every=20model.=20The=20plugin=20now=20reads=20the=20plan's?= =?UTF-8?q?=20tp-=20key=20and=20endpoint=20from=20the=20open=20platform=20?= =?UTF-8?q?with=20the=20same=20passToken=20(/tokenPlan/apiKey's=20openaiBa?= =?UTF-8?q?seUrl,=20/tokenPlan/apiKey/raw),=20sends=20the=20request=20ther?= =?UTF-8?q?e=20with=20Bearer=20=20and=20no=20cookies,=20mimo-pro/mimo?= =?UTF-8?q?-flash=20asked=20as=20mimo-v2.6-pro/mimo-v2.6-flash,=20and=20go?= =?UTF-8?q?es=20straight=20to=20the=20plan=20for=20an=20hour=20after.=20A?= =?UTF-8?q?=20key=20the=20plan=20turns=20away=20(401)=20is=20read=20again?= =?UTF-8?q?=20next=20time;=20no=20plan=20or=20no=20key=20passes=20the=20ap?= =?UTF-8?q?p's=20403=20through=20as=20it=20was.=20The=20usage=20card's=20T?= =?UTF-8?q?oken=20Plan=20window=20is=20the=20account's=20allowance,=20not?= =?UTF-8?q?=20an=20aside,=20when=20there=20is=20no=20app=20plan.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tested on the owner's real account (Token Plan Lite, no app membership): mimo-pro, mimo-flash (streamed) and mimo-auto answered 200 through the loader's fetch; usage shows Token Plan Lite with the "Token Plan" window. bun test (990 pass) and scripts/check.mjs under a temp HOME; 3 of the new tests fail on 0.1.8. --- packages/mimo/README.md | 30 ++++++++-- packages/mimo/index.mjs | 107 ++++++++++++++++++++++++++++++++--- packages/mimo/package.json | 2 +- packages/mimo/usage.test.mjs | 71 ++++++++++++++++++++++- 4 files changed, 193 insertions(+), 17 deletions(-) diff --git a/packages/mimo/README.md b/packages/mimo/README.md index c6c20c2..47d3aa2 100644 --- a/packages/mimo/README.md +++ b/packages/mimo/README.md @@ -41,16 +41,34 @@ as magpie's built-in MiMo account did; reading usage renews the session once when the server turns it away. If the passToken no longer works, sign in again. +### An account with a Token Plan and no app membership + +The app's server answers such an account's requests, every model, with +403 `membership_required` ("未开通会员或会员已到期,请订阅后使用"). The +plugin then asks the account's Token Plan instead. The passToken signs on +at the open platform (platform.xiaomimimo.com, sid `api-platform`), which +gives the plan's `tp-` key (`/tokenPlan/apiKey/raw`) and its endpoint +(`openaiBaseUrl` of `/tokenPlan/apiKey`, e.g. +`https://token-plan-cn.xiaomimimo.com/v1`). The request goes there with +`Authorization: Bearer ` and no cookies, with `mimo-pro` asked as +`mimo-v2.6-pro` and `mimo-flash` as `mimo-v2.6-flash`. For an hour after, +the account's requests go straight to the plan; then the app is asked +first again, in case a membership was bought. A key reset at the platform +(the plan's 401) is read again on the next request. An account with no +Token Plan, or a plan with no key yet (the platform's Token Plan page +makes one), gets the app's 403 as it is. + ## Usage magpie's Usage card shows the MiMo app's plan and its week's allowance. A Token Plan bought at the open platform (platform.xiaomimimo.com) is a -plan of its own: its credits are spent by its `tp-` API key at -`token-plan-.xiaomimimo.com`, not by this account's requests. The -same passToken signs on at the platform (sid `api-platform`), so the card -shows the Token Plan too, as its credits beside the week's allowance, and -as the card's plan when the account has no app plan. To spend the Token -Plan, add magpie's "Xiaomi MiMo" provider with its `tp-` key. +plan of its own, spent by its `tp-` API key at +`token-plan-.xiaomimimo.com`. The same passToken signs on at the +platform (sid `api-platform`), so the card shows the Token Plan too. With +an app plan, its credits are an aside beside the week's allowance: this +account's requests go to the app. With no app plan, the Token Plan is the +card's plan and its credits are the account's allowance, since its +requests go to the plan (above). ## Where the sign-in is kept diff --git a/packages/mimo/index.mjs b/packages/mimo/index.mjs index da82adc..4214382 100644 --- a/packages/mimo/index.mjs +++ b/packages/mimo/index.mjs @@ -2,7 +2,11 @@ // signed in on account.xiaomi.com's long-poll page (a QR code for the // Xiaomi phone app, or the password), whose passToken signs it on at the // MiMo server, which answers with session cookies. Model requests are -// chat completions at the server's /route, carrying those cookies. +// chat completions at the server's /route, carrying those cookies. An +// account with no app membership but a Token Plan at the open platform +// (the server answers membership_required) is asked at the Token Plan's +// endpoint instead, with the plan's tp- key, which the same passToken +// reads from the platform. import { randomBytes } from "node:crypto" import { STATUS_CODES } from "node:http" @@ -27,6 +31,10 @@ const MODELS = { "mimo-flash": { name: "MiMo Flash", ...MODEL }, } +// the Token Plan's names for the app's models; any other passes as it is +const TP_MODELS = { "mimo-pro": "mimo-v2.6-pro", "mimo-flash": "mimo-v2.6-flash" } +const TP_LIFE = 60 * 60 * 1000 // this long, an account the app refused is asked at its Token Plan + const baseOf = (region) => HOSTS[String(region ?? "").trim().toUpperCase()] ?? "" const deviceId = () => "pc_" + randomBytes(16).toString("hex") const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) @@ -536,8 +544,9 @@ export const MimoAuthPlugin = async ({ client }) => { } const c = self?.current const out = { plan: "Free" } - const tp = await tokenPlan(getAuth) - if (c && typeof c === "object") { + const app = c && typeof c === "object" + const tp = await tokenPlan(getAuth, app) + if (app) { const text = (v) => (typeof v === "string" ? v.trim() : "") out.plan = text(c.title) || TIERS[c.planTier] || text(c.planCode) || "MiMo" const until = serverTime(c.endTime) @@ -579,7 +588,7 @@ export const MimoAuthPlugin = async ({ client }) => { // read (the app's card goes on without it). Its credits are spent by // its tp- key, not by this account's requests, so they are an aside. const platform = new Map() // userId -> the platform's session cookies - const tokenPlan = async (getAuth) => { + const tokenPlan = async (getAuth, app) => { const a = fromAuth(await getAuth()) if (!a) return null const who = String(a.creds.userId) @@ -600,11 +609,13 @@ export const MimoAuthPlugin = async ({ client }) => { const it = items.find((x) => x?.name === "month_total_token") ?? items.find((x) => x?.name === "plan_total_token") if (Number.isFinite(it?.used) && Number(it?.limit) > 0) { out.window = { - name: "Token Plan · API key", + name: app ? "Token Plan · API key" : "Token Plan", used: Math.max(0, Math.min(100, (100 * it.used) / it.limit)), display: `${credits(it.used)} / ${credits(it.limit)} credits`, - aside: true, } + // with an app plan, the account's requests go to the app: the + // Token Plan's credits are its key's, an aside + if (app) out.window.aside = true if (out.until) out.window.resetsAt = out.until } } catch {} @@ -615,6 +626,41 @@ export const MimoAuthPlugin = async ({ client }) => { } } + // planKey is the account's Token Plan as {key, base, at}: its tp- key + // and OpenAI base URL, or null when it has no live plan or no key (the + // platform's page makes one; magpie doesn't make it for them) + const planKeys = new Map() // userId -> {key, base, at} + const planKey = async (a) => { + const who = String(a.creds.userId) + const had = planKeys.get(who) + if (had && Date.now() - had.at < TP_LIFE) return had + planKeys.delete(who) + try { + let c = platform.get(who) + const read = async (path) => { + const r = await platformPage(a.creds, path, c) + c = r.cookies + platform.set(who, c) + return r.data + } + const p = await read("/tokenPlan/detail") + if (!p?.planName || p.expired !== false) return null + const k = await read("/tokenPlan/apiKey") + const base = typeof k?.openaiBaseUrl === "string" && /^https:\/\/[^/]+\.xiaomimimo\.com\//.test(k.openaiBaseUrl) ? k.openaiBaseUrl.replace(/\/+$/, "") : "" + if (!base) return null + const key = await read("/tokenPlan/apiKey/raw") + if (typeof key !== "string" || !key.startsWith("tp-")) return null + const got = { key, base, at: Date.now() } + planKeys.set(who, got) + return got + } catch { + platform.delete(who) + return null + } + } + // onPlan is the accounts the app refused (membership_required), and when + const onPlan = new Map() + return { config: async (config) => { config.provider ??= {} @@ -667,6 +713,35 @@ export const MimoAuthPlugin = async ({ client }) => { const message = `${who}: the Xiaomi MiMo sign-in has expired — sign in again` return said(new Response(JSON.stringify({ error: { message, type: "api_error", code: null } }), { status: 502, headers: { "content-type": "application/json" } }), "expired") } + const who = String(s.creds.userId) + const method = init.method ?? req?.method ?? "POST" + // the account's Token Plan, at its own endpoint with its key: + // what the app's /route was asked for, as the plan names it + const toPlan = async () => { + const tp = await planKey(s) + if (!tp) return null + let b = body + if (typeof b === "string") { + try { + const j = JSON.parse(b) + if (TP_MODELS[j?.model]) b = JSON.stringify({ ...j, model: TP_MODELS[j.model] }) + } catch {} + } + const rest = new URL(url).pathname.replace(/^.*?\/route(?=\/|$)/, "") + const h = new Headers(init.headers ?? req?.headers) + for (const k of ["cookie", "x-mimo-source", "x-client-version", "user-agent"]) h.delete(k) + h.set("Authorization", "Bearer " + tp.key) + const res = await fetch(tp.base + rest, { ...init, method, headers: h, body: b }) + // the key was reset at the platform: read it again next time + if (res.status === 401) planKeys.delete(who) + return said(res, s.renewed ? "renewed" : "kept") + } + const since = onPlan.get(who) + if (since && Date.now() - since < TP_LIFE) { + const res = await toPlan() + if (res) return res + onPlan.delete(who) + } const headers = new Headers(init.headers ?? req?.headers) headers.delete("authorization") headers.set("Cookie", cookieHeader(s.cookies)) @@ -676,7 +751,25 @@ export const MimoAuthPlugin = async ({ client }) => { // the server's answer goes through as it is, a 401 too, as the // built-in's did: it took the lapse off only when it signed on // again, whatever the server then answered - const res = await fetch(url, { ...init, method: init.method ?? req?.method ?? "POST", headers, body }) + const res = await fetch(url, { ...init, method, headers, body }) + if (res.status === 403) { + const text = await res.text() + let code + try { + code = JSON.parse(text)?.error?.code + } catch {} + if (code === "membership_required") { + const tp = await toPlan() + if (tp) { + onPlan.set(who, Date.now()) + return tp + } + } + const h = new Headers(res.headers) + h.delete("content-encoding") + h.delete("content-length") + return said(new Response(text, { status: res.status, statusText: res.statusText, headers: h }), s.renewed ? "renewed" : "kept") + } return said(res, s.renewed ? "renewed" : "kept") }, } diff --git a/packages/mimo/package.json b/packages/mimo/package.json index 12a218e..65fc88e 100644 --- a/packages/mimo/package.json +++ b/packages/mimo/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-mimo-auth", - "version": "0.1.8", + "version": "0.1.9", "description": "OpenCode provider plugin for Xiaomi MiMo: the MiMo app's Xiaomi-account sign-in, MiMo Pro and MiMo Flash", "type": "module", "main": "./index.mjs", diff --git a/packages/mimo/usage.test.mjs b/packages/mimo/usage.test.mjs index bf18205..6b467c2 100644 --- a/packages/mimo/usage.test.mjs +++ b/packages/mimo/usage.test.mjs @@ -120,7 +120,7 @@ const TP_USAGE = '{"code":0,"message":"","data":{"monthUsage":{"percent":0.0017, const TP_WINDOW = { name: "Token Plan · API key", used: (100 * 6809408) / 4100000000, display: "6.81M / 4.1B credits", aside: true, resetsAt: "2026-11-06T23:59:59.000Z" } function platformOf(detail = DETAIL) { - const p = { signOns: 0, cookies: [] } + const p = { signOns: 0, cookies: [], key: "tp-one" } p.serve = (u, h) => { if (u.host === "account.xiaomi.com") { p.signOns++ @@ -139,16 +139,20 @@ function platformOf(detail = DETAIL) { if (!c.includes("api-platform_serviceToken=pst")) return json({ code: 401, loginUrl: LOGIN }, 401) if (u.pathname === "/api/v1/tokenPlan/detail") return new Response(detail, { headers: { "Content-Type": "application/json" } }) if (u.pathname === "/api/v1/tokenPlan/usage") return new Response(TP_USAGE, { headers: { "Content-Type": "application/json" } }) + if (u.pathname === "/api/v1/tokenPlan/apiKey") return json({ code: 0, data: { id: 1, redactedApiKey: "tp-c****", openaiBaseUrl: "https://token-plan-cn.xiaomimimo.com/v1", anthropicBaseUrl: "https://token-plan-cn.xiaomimimo.com/anthropic" } }) + if (u.pathname === "/api/v1/tokenPlan/apiKey/raw") return json({ code: 0, data: p.key }) return json({ code: 404 }, 404) } return p } -test("no app plan but a Token Plan at the open platform: the card is the Token Plan's, its credits an aside", async () => { +test("no app plan but a Token Plan at the open platform: the card is the Token Plan's, its credits the allowance", async () => { const tp = platformOf() const noPlan = (path) => (path === "/api/user/usage" ? json({ code: 0, data: { percent: 0.0, resetDate: null, resetAt: null } }) : json({ code: 0, data: { groupCode: null, current: null, subscriptions: [] } })) const p = await plugin(account(), noPlan, tp.serve) - const want = { plan: "Token Plan Lite", until: "2026-11-06T23:59:59.000Z", renew: "auto", windows: [TP_WINDOW], signIn: "kept" } + // the account's requests go to the Token Plan (the app refuses them), so its credits are no aside + const { aside, ...own } = TP_WINDOW + const want = { plan: "Token Plan Lite", until: "2026-11-06T23:59:59.000Z", renew: "auto", windows: [{ ...own, name: "Token Plan" }], signIn: "kept" } expect(await p.usage()).toEqual(want) // the platform's session is kept: the next read doesn't sign on again expect(await p.usage()).toEqual(want) @@ -301,3 +305,64 @@ test("the allowance's page refused after the plan's read marks the account", asy }) expect(await p.usage()).toEqual({ plan: "MiMo 高阶", until: "2026-10-31T16:00:00.000Z", renew: "auto", error: "42: the Xiaomi MiMo sign-in has expired — sign in again", signIn: "expired" }) }) + +// an account with no app membership but a Token Plan, as the reporter's +// (Lite, 2026-10-09): the app's /route answers every model 403 +// membership_required, and the plan's endpoint takes its tp- key +const REFUSED = '{"error":{"message":"未开通会员或会员已到期,请订阅后使用","type":"permission_error","code":"membership_required","biz_code":30012}}' + +async function planFetch(platform, plan) { + const asked = [] + globalThis.fetch = async (url, init = {}) => { + const u = new URL(String(url)) + const h = new Headers(init.headers) + if (u.host === "platform.xiaomimimo.com" || u.host === "account.xiaomi.com") return platform.serve(u, h) + asked.push({ host: u.host, path: u.pathname, auth: h.get("Authorization"), cookie: h.get("Cookie"), model: JSON.parse(init.body).model }) + if (u.host === "token-plan-cn.xiaomimimo.com") return plan(h) + return new Response(REFUSED, { status: 403, headers: { "Content-Type": "application/json;charset=UTF-8" } }) + } + const hooks = await MimoAuthPlugin({ client: { auth: { set: async () => {} } } }) + const auth = account() + const l = await hooks.auth.loader(async () => auth) + const ask = (model) => l.fetch(l.baseURL + "/chat/completions", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model, messages: [] }) }) + return { ask, asked } +} + +test("the app refusing an account with no membership: the request goes to its Token Plan with its key, as the plan names the model", async () => { + const tp = platformOf() + const { ask, asked } = await planFetch(tp, (h) => json({ choices: [] })) + let res = await ask("mimo-pro") + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect(asked).toEqual([ + { host: "mimo-server-sgp.xiaomimimo.com", path: "/api/route/chat/completions", auth: null, cookie: "serviceToken=st-1; userId=42", model: "mimo-pro" }, + { host: "token-plan-cn.xiaomimimo.com", path: "/v1/chat/completions", auth: "Bearer tp-one", cookie: null, model: "mimo-v2.6-pro" }, + ]) + // from then on straight to the plan, the key not read again + asked.length = 0 + res = await ask("mimo-flash") + expect(res.status).toBe(200) + expect(asked.map((a) => `${a.host} ${a.model}`)).toEqual(["token-plan-cn.xiaomimimo.com mimo-v2.6-flash"]) + expect(tp.signOns).toBe(1) +}) + +test("a key reset at the platform is read again after the plan turns the old one away", async () => { + const tp = platformOf() + const { ask, asked } = await planFetch(tp, (h) => (h.get("Authorization") === "Bearer " + tp.key ? json({ choices: [] }) : json({ error: { message: "Invalid API Key" } }, 401))) + expect((await ask("mimo-pro")).status).toBe(200) + tp.key = "tp-two" + expect((await ask("mimo-pro")).status).toBe(401) + expect((await ask("mimo-pro")).status).toBe(200) + expect(asked.filter((a) => a.host.startsWith("token-plan")).map((a) => a.auth)).toEqual(["Bearer tp-one", "Bearer tp-one", "Bearer tp-two"]) +}) + +test("no Token Plan, or one with no key: the app's refusal goes through as it is", async () => { + for (const tp of [platformOf('{"code":0,"message":"","data":null}'), Object.assign(platformOf(), { key: null })]) { + const { ask, asked } = await planFetch(tp, () => json({ choices: [] })) + const res = await ask("mimo-pro") + expect(res.status).toBe(403) + expect(await res.text()).toBe(REFUSED) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect(asked.every((a) => a.host.startsWith("mimo-server"))).toBe(true) + } +})