mimo 0.1.6: magpie renews the sign-in ahead of time through auth.refresh

auth.refresh with refreshLead 10 minutes before the day's session ends:
the account signs on again, once per account (the request path joins it),
and the new session (access, expires) is given. A passToken Xiaomi no
longer takes is signIn "expired"; any other failure throws and is retried.

The check before each request stays for OpenCode, which doesn't call the
hook (magpie 0.1.684+ does). refresh.test.mjs fails without the change;
HOME=$(mktemp -d) bun test passes (396 across the repo).
This commit is contained in:
yetone
2026-10-03 12:07:22 +08:00
parent ce009e60c6
commit 7dd0b4e0b4
4 changed files with 159 additions and 22 deletions
+7 -1
View File
@@ -29,7 +29,13 @@ Chat completions go to `https://mimo-server-<region>.xiaomimimo.com/api/route/ch
`mimo-auto`, the app's default model, is requested as `mimo-pro`.
The session is renewed with the passToken a day after it was issued. A model
The session is renewed with the passToken a day after it was issued.
magpie (0.1.684 and later) does it ahead of time through `auth.refresh`, ten
minutes before that day is out (`refreshLead`), once for the account and
before its requests, models and usage ask for it; a passToken Xiaomi no
longer takes marks the account for a new sign-in. The check before each
request stays for OpenCode, which doesn't call `auth.refresh`, and one
sign-on at a time serves both. A model
request the server turns away (a 401) is answered as the server answered it,
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
+59 -20
View File
@@ -18,6 +18,7 @@ const APP_VERSION = "26.929.292248"
const SOURCE = "mimocode-cli-free"
const UA = "miNative PC/Normal Windows_NT/10.0.26100 SDKV/1.0.0 DEVT/PC DEVS/Windows APP/miaccount_desktop APPV/0.1.0"
const RENEW_AFTER = 24 * 60 * 60 * 1000 // the app signs on again after a day
const LEAD_MS = 10 * 60 * 1000 // this close to it, magpie signs on again ahead of time (auth.refresh)
const SIGN_IN_LIFE = 10 * 60 * 1000
const MODEL = { release_date: "2026-07-01", attachment: true, tool_call: true, limit: { context: 1_000_000, output: 128_000 }, modalities: { input: ["text", "image"], output: ["text"] } }
@@ -338,8 +339,11 @@ function serverTime(v) {
export const MimoAuthPlugin = async ({ client }) => {
// renewals under way, one to an account: two accounts signing on at
// once each keep their own session
// once each keep their own session. renewed is the last session each
// account got here, so magpie's auth.refresh handed a sign-in from
// before it gives that one rather than signing on again.
const renewing = new Map()
const renewed = new Map()
const save = async (auth) => {
try {
@@ -347,6 +351,28 @@ export const MimoAuthPlugin = async ({ client }) => {
} catch {}
}
// renew signs the account on again, once at a time: those who come
// while it runs wait for it. keep saves the new session (the request
// path); magpie's auth.refresh saves what it gives itself.
const renew = (a, keep) => {
const who = String(a.creds.userId ?? "")
let r = renewing.get(who)
if (!r) {
r = (async () => {
const s = await session(a.creds, a.creds.base)
const issued = Date.now()
const got = { creds: a.creds, cookies: s.cookies, expires: issued + RENEW_AFTER, renewed: true }
renewed.set(who, got)
if (keep) await save(toAuth(a.creds, s.cookies, issued))
return got
})().finally(() => {
renewing.delete(who)
})
renewing.set(who, r)
}
return r
}
// fresh is the account with a live session, signed on again when it is
// older than the app lets one get, or when force is set (the server
// turned the last one away); renewed when it was signed on again, which
@@ -355,26 +381,34 @@ export const MimoAuthPlugin = async ({ client }) => {
const a = fromAuth(await getAuth())
if (!a) throw new Error("Xiaomi MiMo: not signed in")
if (!force && Object.keys(a.cookies).length && Date.now() < a.expires) return a
const who = String(a.creds.userId ?? "")
let r = renewing.get(who)
if (!r) {
r = (async () => {
try {
const s = await session(a.creds, a.creds.base)
const issued = Date.now()
await save(toAuth(a.creds, s.cookies, issued))
return { creds: a.creds, cookies: s.cookies, expires: issued + RENEW_AFTER, renewed: true }
} catch (e) {
// a hiccup: the session in hand may still do
if (!(e instanceof Lapsed) && !force && Object.keys(a.cookies).length) return a
throw e
}
})().finally(() => {
renewing.delete(who)
})
renewing.set(who, r)
try {
return await renew(a, true)
} catch (e) {
// a hiccup: the session in hand may still do
if (!(e instanceof Lapsed) && !force && Object.keys(a.cookies).length) return a
throw e
}
}
// refresh is magpie's auth.refresh: the session signed on again
// LEAD_MS before the app would, as the fields that changed (the Xiaomi
// account in refresh stays as it is). A passToken Xiaomi no longer takes
// is signIn "expired"; any other failure throws as it is.
const refresh = async (auth) => {
const a = fromAuth(auth)
if (!a) return undefined
const last = renewed.get(String(a.creds.userId ?? ""))
// signed on again here already, the store not yet saying so
if (last && last.expires > a.expires && Date.now() < last.expires - LEAD_MS) {
return { access: JSON.stringify(last.cookies), expires: last.expires }
}
try {
const s = await renew(a, false)
return { access: JSON.stringify(s.cookies), expires: s.expires }
} catch (e) {
if (e instanceof Lapsed) throw Object.assign(new Error(e.message), { signIn: "expired" })
throw e
}
return r
}
// page asks the MiMo server for one of the account's pages, signing on
@@ -472,6 +506,11 @@ export const MimoAuthPlugin = async ({ client }) => {
auth: {
provider: ID,
usage,
// magpie signs the account on again LEAD_MS before the day is out,
// once, before its requests, models and usage ask; fresh's check
// before each request stays for OpenCode, which doesn't call this
refreshLead: LEAD_MS,
refresh,
loader: async (getAuth) => {
const a = fromAuth(await getAuth())
if (!a) return {}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-mimo-auth",
"version": "0.1.5",
"version": "0.1.6",
"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",
+92
View File
@@ -0,0 +1,92 @@
// magpie's auth.refresh: the session signed on again ahead of time, as the
// fields that changed, once for the account with the request path's own
// renewal, and a passToken Xiaomi no longer takes is signIn "expired".
import { afterEach, expect, test } from "bun:test"
import { MimoAuthPlugin } from "./index.mjs"
const real = globalThis.fetch
afterEach(() => (globalThis.fetch = real))
const BASE = "https://mimo-server-sgp.xiaomimimo.com/api"
const CREDS = JSON.stringify({ userId: "42", passToken: "pt", deviceId: "pc_1", region: "SGP", base: BASE })
const account = (expires) => ({ type: "oauth", refresh: CREDS, access: JSON.stringify({ serviceToken: "st-1", userId: "42" }), expires, accountId: "42" })
// serve answers the sign-on (/user/xiaomi/me) with me, and a chat with 200;
// signOns counts the sign-ons, saves what the plugin saved itself
function serve(me = () => signedOn("st-2")) {
const s = { signOns: 0, saves: [], chats: [] }
globalThis.fetch = async (url, init = {}) => {
const u = new URL(String(url))
if (u.pathname.endsWith("/user/xiaomi/me")) {
s.signOns++
await new Promise((r) => setTimeout(r, 30))
return me()
}
s.chats.push(new Headers(init.headers).get("Cookie"))
return new Response("{}", { headers: { "content-type": "application/json" } })
}
s.client = { auth: { set: async ({ body }) => s.saves.push(body) } }
return s
}
const signedOn = (token) => new Response(JSON.stringify({ code: 0, data: { userId: "42" } }), { headers: { "set-cookie": `serviceToken=${token}; Path=/` } })
test("signs on again and gives the new session, saving nothing itself", async () => {
const s = serve()
const hooks = await MimoAuthPlugin({ client: s.client })
expect(hooks.auth.refreshLead).toBe(10 * 60 * 1000)
const before = Date.now()
const got = await hooks.auth.refresh(account(Date.now() + 60_000))
expect(Object.keys(got).sort()).toEqual(["access", "expires"])
expect(JSON.parse(got.access)).toEqual({ serviceToken: "st-2" })
expect(got.expires).toBeGreaterThanOrEqual(before + 24 * 3600 * 1000)
expect(s.signOns).toBe(1)
expect(s.saves).toEqual([])
// handed the old sign-in again before magpie's save landed, it gives the
// session it got rather than signing on again
expect(await hooks.auth.refresh(account(Date.now() + 60_000))).toEqual(got)
expect(s.signOns).toBe(1)
})
test("one sign-on with a request renewing at the same time", async () => {
const s = serve()
const hooks = await MimoAuthPlugin({ client: s.client })
const stale = account(Date.now() - 1)
const opts = await hooks.auth.loader(async () => stale)
const [got, res] = await Promise.all([
hooks.auth.refresh(stale),
opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: '{"model":"mimo-pro"}' }),
])
expect(s.signOns).toBe(1)
expect(JSON.parse(got.access)).toEqual({ serviceToken: "st-2" })
expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed")
expect(s.chats).toEqual(["serviceToken=st-2"])
})
test("a passToken Xiaomi no longer takes is signIn expired", async () => {
const s = serve(() => new Response("<html>sign in</html>", { status: 200 }))
const hooks = await MimoAuthPlugin({ client: s.client })
const e = await hooks.auth.refresh(account(Date.now() + 60_000)).catch((e) => e)
expect(e).toBeInstanceOf(Error)
expect(e.signIn).toBe("expired")
expect(e.message).toContain("sign in again")
})
test("any other failure throws plainly", async () => {
const s = serve(() => {
throw new TypeError("connection reset")
})
const hooks = await MimoAuthPlugin({ client: s.client })
const e = await hooks.auth.refresh(account(Date.now() + 60_000)).catch((e) => e)
expect(e).toBeInstanceOf(Error)
expect(e.signIn).toBeUndefined()
expect(e.message).toContain("connection reset")
})
test("nothing to renew with is undefined", async () => {
const s = serve()
const hooks = await MimoAuthPlugin({ client: s.client })
expect(await hooks.auth.refresh({ type: "api", key: "k" })).toBeUndefined()
expect(await hooks.auth.refresh({ type: "oauth", refresh: "not json", access: "{}", expires: 1 })).toBeUndefined()
expect(await hooks.auth.refresh({ type: "oauth", refresh: JSON.stringify({ userId: "42" }), access: "{}", expires: 1 })).toBeUndefined()
expect(s.signOns).toBe(0)
})