From bf01ffc4d98174108868a707bc55551cc965ef11 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 7 Oct 2026 00:49:43 +0800 Subject: [PATCH] =?UTF-8?q?mimo=200.1.8:=20a=20Token=20Plan=20bought=20at?= =?UTF-8?q?=20the=20open=20platform=20shows=20on=20the=20card=20(yetone:?= =?UTF-8?q?=20=E6=88=91=E6=98=8E=E6=98=8E=E5=B7=B2=E7=BB=8F=E8=AE=A2?= =?UTF-8?q?=E9=98=85=E4=BA=86=E5=95=8A=E4=B8=BA=E5=95=A5=E8=AF=B4=E6=88=91?= =?UTF-8?q?=E6=98=AF=20free=20=E8=B4=A6=E5=8F=B7=E5=95=8A).=20The=20card?= =?UTF-8?q?=20read=20only=20the=20MiMo=20app's=20/user/xiaomi/subscription?= =?UTF-8?q?/self,=20which=20is=20empty=20for=20an=20account=20whose=20plan?= =?UTF-8?q?=20is=20the=20platform's=20Token=20Plan,=20so=20it=20said=20Fre?= =?UTF-8?q?e.=20The=20same=20passToken=20signs=20on=20at=20platform.xiaomi?= =?UTF-8?q?mimo.com=20(401=20loginUrl,=20sid=20api-platform,=20through=20/?= =?UTF-8?q?sts),=20whose=20/api/v1/tokenPlan/detail=20and=20/usage=20give?= =?UTF-8?q?=20the=20plan,=20its=20end=20(UTC),=20renewal=20and=20credits:?= =?UTF-8?q?=20the=20card's=20plan=20is=20the=20Token=20Plan=20when=20the?= =?UTF-8?q?=20app=20has=20none,=20and=20its=20credits=20are=20an=20aside?= =?UTF-8?q?=20window=20(they=20are=20spent=20by=20the=20tp-=20key,=20not?= =?UTF-8?q?=20this=20account's=20requests).=20A=20platform=20that=20can't?= =?UTF-8?q?=20be=20read=20leaves=20the=20card=20as=20it=20was.=20Tested=20?= =?UTF-8?q?against=20the=20reporter's=20real=20account=20(Token=20Plan=20L?= =?UTF-8?q?ite,=206.81M=20/=204.1B=20credits,=20the=20second=20read=20keep?= =?UTF-8?q?ing=20the=20platform=20session);=20the=20new=20tests=20use=20it?= =?UTF-8?q?s=20literal=20replies=20and=203=20of=20them=20fail=20on=200.1.7?= =?UTF-8?q?.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/mimo/README.md | 11 +++ packages/mimo/index.mjs | 138 +++++++++++++++++++++++++++++++++-- packages/mimo/package.json | 2 +- packages/mimo/usage.test.mjs | 80 +++++++++++++++++++- 4 files changed, 222 insertions(+), 9 deletions(-) diff --git a/packages/mimo/README.md b/packages/mimo/README.md index fe18c1a..c6c20c2 100644 --- a/packages/mimo/README.md +++ b/packages/mimo/README.md @@ -41,6 +41,17 @@ 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. +## 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. + ## Where the sign-in is kept In OpenCode's `auth.json`, or magpie's `plugin-auth.json`, as an OAuth sign-in: diff --git a/packages/mimo/index.mjs b/packages/mimo/index.mjs index 76ab16c..da82adc 100644 --- a/packages/mimo/index.mjs +++ b/packages/mimo/index.mjs @@ -152,6 +152,71 @@ async function session(creds, base) { return { cookies, me: me.data } } +// The open platform (platform.xiaomimimo.com) sells the Token Plan, a plan +// of its own spent with its tp- API key at token-plan-.xiaomimimo.com, +// not through the app's /route. The same Xiaomi account signs on there as at +// the MiMo server: a page asked with no session answers 401 with a +// serviceLogin URL (sid api-platform), which the passToken follows back +// through the platform's /sts to the page. +const PLATFORM = "https://platform.xiaomimimo.com" + +// platformPage is one of the platform's /api/v1 pages, as {cookies, data}: +// cookies the session it was read with (given in, else signed on afresh), +// data the page's; null data is a page the account can't read. +async function platformPage(creds, path, cookies) { + const signal = AbortSignal.timeout(20_000) + const url = PLATFORM + "/api/v1" + path + const ask = async (c) => { + const res = await fetch(url, { headers: c ? { Cookie: c } : {}, redirect: "manual", signal }) + return { res, text: await res.text() } + } + const data = (text) => { + try { + const v = JSON.parse(text) + return v?.code === 0 ? (v.data ?? null) : undefined + } catch {} + } + if (cookies) { + const { res, text } = await ask(cookieHeader(cookies)) + const d = res.status === 200 ? data(text) : undefined + if (d !== undefined) return { cookies, data: d } + } + let { res, text } = await ask("") + let login + try { + login = JSON.parse(text)?.loginUrl + } catch {} + if (res.status !== 401 || typeof login !== "string" || !login.startsWith(ACCOUNT + "/")) { + throw new Error(`Xiaomi MiMo platform ${path}: ${vendorError(text, statusLine(res.status))}`) + } + const jar = new Jar() + for (const [k, v] of [["userId", creds.userId], ["passToken", creds.passToken], ["cUserId", creds.cUserId], + ["deviceId", creds.deviceId], ["pass_ua", "pc"], ["uLocale", "zh_CN"]]) { + if (v) jar.seed(ACCOUNT, k, v) + } + let at = login + for (let hop = 0; ; hop++) { + if (hop > 10) throw new Error("Xiaomi MiMo platform sign-in: too many redirects") + const c = jar.header(at) + res = await fetch(at, { headers: c ? { Cookie: c } : {}, redirect: "manual", signal }) + jar.take(res, at) + const loc = res.headers.get("location") + if (res.status < 300 || res.status >= 400 || !loc) break + await res.arrayBuffer().catch(() => {}) + const next = new URL(loc, at) + // the followup is written http://; the session's cookies go back over https + if (next.protocol === "http:" && next.host === new URL(PLATFORM).host) next.protocol = "https:" + at = next.href + } + text = await res.text() + const d = res.status === 200 ? data(text) : undefined + // back on Xiaomi's sign-in page: the passToken doesn't sign on here + if (d === undefined) throw new Error(`Xiaomi MiMo platform ${path}: the Xiaomi account didn't sign on (${statusLine(res.status)})`) + const got = {} + for (const c of jar.for(PLATFORM + "/")) got[c.name] = c.value + return { cookies: got, data: d } +} + // cookieHeader is a session as a Cookie header, in a steady order function cookieHeader(cookies) { const first = ["serviceToken", "userId", "cUserId"] @@ -290,6 +355,14 @@ async function signedInWith(p, device) { // date is no plan), and /user/xiaomi/subscription/self, the plan in force // and when it ends. An account with no plan is on MiMo's free offer. +// credits is a count of the Token Plan's credits, short: 6.81M, 4.1B +function credits(n) { + for (const [d, u] of [[1e9, "B"], [1e6, "M"], [1e3, "K"]]) { + if (n >= d) return `${Number((n / d).toPrecision(3))}${u}` + } + return String(n) +} + // the app's names for its plans' tiers const TIERS = { 1: "Starter", 2: "Plus", 3: "Pro", 4: "Ultra" } @@ -463,6 +536,7 @@ export const MimoAuthPlugin = async ({ client }) => { } const c = self?.current const out = { plan: "Free" } + const tp = await tokenPlan(getAuth) if (c && typeof c === "object") { const text = (v) => (typeof v === "string" ? v.trim() : "") out.plan = text(c.title) || TIERS[c.planTier] || text(c.planCode) || "MiMo" @@ -470,6 +544,11 @@ export const MimoAuthPlugin = async ({ client }) => { if (until) out.until = until if (c.renewalMode === "MONTHLY" || c.renewalMode === "YEARLY") out.renew = "auto" else if (c.renewalMode === "ONE_TIME") out.renew = "off" + } else if (tp) { + // no app plan: the account's plan is the platform's Token Plan + out.plan = tp.plan + if (tp.until) out.until = tp.until + out.renew = tp.renew } let use try { @@ -477,20 +556,65 @@ export const MimoAuthPlugin = async ({ client }) => { } catch (e) { if (e instanceof SignInGone) out.error = e.message // the plan alone, when the week's allowance can't be read - return { ...out, signIn: read.signIn } + return { ...out, ...(tp?.window && { windows: [tp.window] }), signIn: read.signIn } } out.signIn = read.signIn const percent = use?.percent const reset = use?.resetDate + const windows = [] // no plan: the free offer shows no allowance - if (typeof percent !== "number" || typeof reset !== "string") return out - const w = { name: "7 days", used: Math.max(0, Math.min(100, 100 - percent)), span: 7 * 24 * 3600 } - const at = serverTime(reset) - if (at) w.resetsAt = at - out.windows = [w] + if (typeof percent === "number" && typeof reset === "string") { + const w = { name: "7 days", used: Math.max(0, Math.min(100, 100 - percent)), span: 7 * 24 * 3600 } + const at = serverTime(reset) + if (at) w.resetsAt = at + windows.push(w) + } + if (tp?.window) windows.push(tp.window) + if (windows.length) out.windows = windows return out } + // tokenPlan is the account's Token Plan at the open platform, as + // {plan, until, renew, window}, or null: none, or the platform can't be + // 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 a = fromAuth(await getAuth()) + if (!a) return null + const who = String(a.creds.userId) + try { + const d = await platformPage(a.creds, "/tokenPlan/detail", platform.get(who)) + platform.set(who, d.cookies) + const p = d.data + const name = typeof p?.planName === "string" ? p.planName.trim() : "" + if (!name || p.expired !== false) return null + const out = { plan: `Token Plan ${name}`, renew: p.enableAutoRenew || p.hasAutoRenewSubscribed ? "auto" : "off" } + // the platform's times are UTC ("有效期至 2026-11-06 23:59:59 (UTC)") + const end = /^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/.test(p.currentPeriodEnd ?? "") ? Date.parse(p.currentPeriodEnd.replace(" ", "T") + "Z") : NaN + if (!isNaN(end)) out.until = new Date(end).toISOString() + try { + const u = await platformPage(a.creds, "/tokenPlan/usage", d.cookies) + platform.set(who, u.cookies) + const items = [...(u.data?.monthUsage?.items ?? []), ...(u.data?.usage?.items ?? [])] + 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", + used: Math.max(0, Math.min(100, (100 * it.used) / it.limit)), + display: `${credits(it.used)} / ${credits(it.limit)} credits`, + aside: true, + } + if (out.until) out.window.resetsAt = out.until + } + } catch {} + return out + } catch { + platform.delete(who) + return null + } + } + return { config: async (config) => { config.provider ??= {} @@ -585,4 +709,4 @@ export const MimoAuthPlugin = async ({ client }) => { } // for tests -export const _internal = { serverTime, vendorError } +export const _internal = { serverTime, vendorError, credits } diff --git a/packages/mimo/package.json b/packages/mimo/package.json index 57ace2e..12a218e 100644 --- a/packages/mimo/package.json +++ b/packages/mimo/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-mimo-auth", - "version": "0.1.7", + "version": "0.1.8", "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 0a55fb9..bf18205 100644 --- a/packages/mimo/usage.test.mjs +++ b/packages/mimo/usage.test.mjs @@ -19,10 +19,15 @@ const account = (expires = Date.now() + 3_600_000) => ({ accountId: "42", }) -async function plugin(auth, serve) { +// the open platform with no Token Plan to read: its pages turn away an +// account they can't sign on +const noPlatform = () => json({ code: 401 }, 401) + +async function plugin(auth, serve, platform = noPlatform) { const seen = [] globalThis.fetch = async (url, init = {}) => { const u = new URL(String(url)) + if (u.host === "platform.xiaomimimo.com" || u.host === "account.xiaomi.com") return platform(u, new Headers(init.headers)) seen.push(u.pathname) return serve(u.pathname, new Headers(init.headers)) } @@ -88,6 +93,7 @@ test("two accounts signing on at once each keep their own session", async () => const asked = [] globalThis.fetch = async (url, init = {}) => { const u = new URL(String(url)) + if (u.host === "platform.xiaomimimo.com") return noPlatform() if (u.pathname.endsWith("/user/xiaomi/me")) { await new Promise((r) => setTimeout(r, 30)) const uid = u.host[0].toUpperCase() @@ -105,6 +111,78 @@ test("two accounts signing on at once each keep their own session", async () => for (const x of asked) expect(x).toContain(x.startsWith("a.") ? "serviceToken=st-A" : "serviceToken=st-B") }) +// the open platform's Token Plan, as the reporter's account answered +// (Lite, 2026-10-07): a page asked with no session is 401 with a +// serviceLogin URL, which the passToken follows through /sts back to it +const LOGIN = "https://account.xiaomi.com/pass/serviceLogin?callback=https%3A%2F%2Fplatform.xiaomimimo.com%2Fsts%3Fsign%3DsJaoCJbfw5dWz7lcIbXMHnGQnS0%253D%26followup%3Dhttp%253A%252F%252Fplatform.xiaomimimo.com%252Fapi%252Fv1%252FtokenPlan%252Fdetail&sid=api-platform&_group=DEFAULT" +const DETAIL = '{"code":0,"message":"","data":{"planCode":"lite","planName":"Lite","currentPeriodEnd":"2026-11-06 23:59:59","expired":false,"enableAutoRenew":true,"autoRenewDiscount":null,"hasAutoRenewSubscribed":true,"clawEnabled":false,"clawPeriodEnd":null,"clawPurchased":false}}' +const TP_USAGE = '{"code":0,"message":"","data":{"monthUsage":{"percent":0.0017,"items":[{"name":"month_total_token","used":6809408,"limit":4100000000,"percent":0.0017}]},"usage":{"percent":0.00,"items":[{"name":"plan_total_token","used":6809408,"limit":4100000000,"percent":0.00},{"name":"compensation_total_token","used":0,"limit":0,"percent":0}]}}}' +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: [] } + p.serve = (u, h) => { + if (u.host === "account.xiaomi.com") { + p.signOns++ + expect(h.get("Cookie")).toContain("passToken=pt") + expect(u.searchParams.get("sid")).toBe("api-platform") + return new Response("", { status: 302, headers: { location: "https://platform.xiaomimimo.com/sts?sign=x&followup=" + encodeURIComponent("http://platform.xiaomimimo.com/api/v1/tokenPlan/detail") } }) + } + if (u.pathname === "/sts") { + const r = new Response("", { status: 307, headers: { location: "http://platform.xiaomimimo.com/api/v1/tokenPlan/detail" } }) + r.headers.append("set-cookie", "api-platform_serviceToken=pst; Path=/; HttpOnly") + r.headers.append("set-cookie", "userId=42; Domain=xiaomimimo.com; Path=/") + return r + } + const c = h.get("Cookie") ?? "" + p.cookies.push(c) + 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" } }) + 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 () => { + 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" } + 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) + expect(tp.signOns).toBe(1) +}) + +test("an app plan stays the card's plan, the Token Plan's credits beside its week", async () => { + const p = await plugin(account(), (path) => (path === "/api/user/usage" ? json(USAGE) : json(SELF)), platformOf().serve) + expect(await p.usage()).toEqual({ + plan: "MiMo 高阶", + until: "2026-10-31T16:00:00.000Z", + renew: "auto", + windows: [{ name: "7 days", used: 30, span: 604800, resetsAt: "2026-10-04T16:00:00.000Z" }, TP_WINDOW], + signIn: "kept", + }) +}) + +test("no Token Plan, an expired one, or a platform that can't be read: the free offer as before", async () => { + const noPlan = (path) => (path === "/api/user/usage" ? json({ code: 0, data: { percent: 100, resetDate: null } }) : json({ code: 0, data: { current: null } })) + for (const detail of ['{"code":0,"message":"","data":null}', DETAIL.replace('"expired":false', '"expired":true')]) { + const p = await plugin(account(), noPlan, platformOf(detail).serve) + expect(await p.usage()).toEqual({ plan: "Free", signIn: "kept" }) + } + const p = await plugin(account(), noPlan, () => json({ message: "down" }, 503)) + expect(await p.usage()).toEqual({ plan: "Free", signIn: "kept" }) +}) + +test("credits, short", () => { + expect(_internal.credits(6809408)).toBe("6.81M") + expect(_internal.credits(4100000000)).toBe("4.1B") + expect(_internal.credits(1500)).toBe("1.5K") + expect(_internal.credits(0)).toBe("0") +}) + test("a failure is the page's and the server's word", async () => { let p = await plugin(account(), () => json({ code: 10001, msg: "no such user" })) expect(await p.usage()).toEqual({ error: "Xiaomi MiMo /user/xiaomi/subscription/self: code 10001 no such user", signIn: "kept" })