mimo 0.1.8: a Token Plan bought at the open platform shows on the card (yetone: 我明明已经订阅了啊为啥说我是 free 账号啊). The card read only the MiMo app's /user/xiaomi/subscription/self, which is empty for an account whose plan is the platform's Token Plan, so it said Free. The same passToken signs on at platform.xiaomimimo.com (401 loginUrl, sid api-platform, through /sts), whose /api/v1/tokenPlan/detail and /usage give the plan, its end (UTC), renewal and credits: the card's plan is the Token Plan when the app has none, and its credits are an aside window (they are spent by the tp- key, not this account's requests). A platform that can't be read leaves the card as it was. Tested against the reporter's real account (Token Plan Lite, 6.81M / 4.1B credits, the second read keeping the platform session); the new tests use its literal replies and 3 of them fail on 0.1.7.
This commit is contained in:
@@ -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-<region>.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:
|
||||
|
||||
+131
-7
@@ -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-<region>.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 }
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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" })
|
||||
|
||||
Reference in New Issue
Block a user