feat(xiaomi-mimo): merge MiMo Desktop support into xiaomi-mimo as dual auth

Adds the Desktop-exclusive Preview models and the Xiaomi account-session
route to the existing xiaomi-mimo provider instead of a separate
xiaomi-desktop provider, so the dashboard shows one MiMo entry rather than
three overlapping ones.

Dual auth, same pattern as kimi — API key (sk-) covers the cloud API,
Desktop/OAuth adds the account session used by the Preview models:

- registry: category oauth, authModes [oauth, apikey], oauth block, the two
  mimo-x-*-preview models, and the invite signupUrl
- executor: routes Preview models to the account-service route with a Cookie
  session, everything else keeps the sourceFormat-matched transport
- oauth: custom ECDH encrypted-callback flow (X25519 -> SHA256 -> AES-256-GCM)
  with a loopback callback proxy, plus one-click import of the local Desktop
  auth.json
- usage: weekly quota from the account session

Fixes found while merging:

- the OAuth browser flow was dead: poll-status cleared the session before the
  client could POST /exchange, so every exchange returned 400
- a Claude-format client was sent to /v1/chat/completions instead of the
  declared /anthropic/v1/messages transport, because buildUrl ignored
  runtimeTransport
- stopXiaomiMimoProxy leaked every pending session (each holding an X25519
  private key) for the process lifetime
- the OAuth exchange did not persist the Desktop passToken, so the Preview
  models could never work after a browser sign-in

Removes dead code: the local engine token minting (mimoEngine, never called
on the request path), the model-catalog and usage routes, engineToken/
engineUrl plumbing, and an unread top-level usage block.

Adds tests/unit/xiaomi-mimo-{executor,oauth-session,oauth-proxy}.test.js —
the provider previously had none.
This commit is contained in:
叶炜朋 committed 2026-09-10 23:42:41 +07:00
1 parent 83af3f1853
commit 73cb89143c
21 files changed
+1828 -4

No files matched your search

+113 -2
View File
@@ -1,3 +1,4 @@
import crypto from "crypto";
import { NextResponse } from "next/server";
import {
getProvider,
@@ -7,6 +8,7 @@ import {
pollForToken
} from "@/lib/oauth/providers";
import { createProviderConnection } from "@/models";
import { readDesktopPassToken } from "open-sse/shared/mimoAccount.js";
import {
startCodexProxy,
stopCodexProxy,
@@ -33,6 +35,11 @@ import {
registerZedSession,
getZedSessionStatus,
clearZedSession,
startXiaomiMimoProxy,
stopXiaomiMimoProxy,
registerXiaomiMimoSession,
getXiaomiMimoSessionStatus,
clearXiaomiMimoSession,
} from "@/lib/oauth/utils/server";
import { detectIdeInstalled } from "@/lib/oauth/utils/ideDetect";
import { ZED_HOSTED_CONFIG } from "@/lib/oauth/constants/oauth";
@@ -89,6 +96,32 @@ export async function GET(request, { params }) {
const { searchParams } = new URL(request.url);
if (action === "authorize") {
// Xiaomi Desktop: custom ECDH flow — generate keypair, start proxy, return authorize URL
if (provider === "xiaomi-mimo") {
const { generateKeyPair, buildAuthorizeUrl, getKeyName } = await import("@/lib/oauth/providers/xiaomi-mimo");
const { publicKey, privateKeyDer } = generateKeyPair();
const state = searchParams.get("state") || crypto.randomUUID();
// Start the callback proxy (or reuse if already running)
const proxyResult = await startXiaomiMimoProxy();
if (!proxyResult.success) {
return NextResponse.json({ error: `Failed to start callback server: ${proxyResult.reason}` }, { status: 500 });
}
// Register the session with the private key for decryption
registerXiaomiMimoSession({ state, privateKeyDer });
const redirectUri = proxyResult.callbackUrl;
const authorizeUrl = buildAuthorizeUrl(publicKey, redirectUri, getKeyName());
return NextResponse.json({
state,
authorizeUrl,
redirectUri,
port: proxyResult.port,
});
}
const redirectUri = searchParams.get("redirect_uri") || "http://localhost:8080/callback";
// Collect provider-specific meta params (e.g. gitlab passes baseUrl, clientId, clientSecret)
const reservedParams = new Set(["redirect_uri"]);
@@ -120,6 +153,10 @@ export async function GET(request, { params }) {
const result = await startZedProxy(searchParams.get("native_app_port") || ZED_HOSTED_CONFIG.defaultNativeAppPort);
return NextResponse.json(result);
}
if (provider === "xiaomi-mimo") {
const result = await startXiaomiMimoProxy();
return NextResponse.json(result);
}
if (!["codex", "xai"].includes(provider)) {
return NextResponse.json({ error: "Proxy only supported for codex/xai/trae/windsurf/zed" }, { status: 400 });
}
@@ -153,10 +190,21 @@ export async function GET(request, { params }) {
else if (provider === "zed") session = getZedSessionStatus(state);
else if (provider === "xai") session = getXaiSessionStatus(state);
else if (provider === "codex") session = getCodexSessionStatus(state);
else return NextResponse.json({ error: "Poll only supported for codex/xai/trae/windsurf/zed" }, { status: 400 });
else if (provider === "xiaomi-mimo") session = getXiaomiMimoSessionStatus(state);
else return NextResponse.json({ error: "Poll only supported for codex/xai/trae/windsurf/zed/xiaomi-mimo" }, { status: 400 });
if (!session) return NextResponse.json({ status: "unknown" });
if (session.status === "done" || session.status === "error") {
const payload = { ...session };
if (provider === "xiaomi-mimo") {
// Unlike the others this does not auto-exchange server-side, so a
// finished session must survive until the client POSTs /exchange —
// that call clears it. A failed one is cleared here instead.
if (session.status === "error") {
clearXiaomiMimoSession(state);
stopXiaomiMimoProxy();
}
return NextResponse.json(payload);
}
if (provider === "trae") clearTraeSession(state);
else if (provider === "windsurf") clearWindsurfSession(state);
else if (provider === "zed") clearZedSession(state);
@@ -173,7 +221,8 @@ export async function GET(request, { params }) {
else if (provider === "zed") stopZedProxy();
else if (provider === "xai") stopXaiProxy();
else if (provider === "codex") stopCodexProxy();
else return NextResponse.json({ error: "Proxy only supported for codex/xai/trae/windsurf/zed" }, { status: 400 });
else if (provider === "xiaomi-mimo") stopXiaomiMimoProxy();
else return NextResponse.json({ error: "Proxy only supported for codex/xai/trae/windsurf/zed/xiaomi-mimo" }, { status: 400 });
return NextResponse.json({ success: true });
}
@@ -268,6 +317,68 @@ export async function POST(request, { params }) {
if (action === "exchange") {
const { code, redirectUri, codeVerifier, state, meta } = body;
// Xiaomi MiMo: no token exchange needed — the callback already decrypted the sk.
// Just read the session result and create the connection.
if (provider === "xiaomi-mimo") {
if (!state) {
return NextResponse.json({ error: "Missing state" }, { status: 400 });
}
const session = getXiaomiMimoSessionStatus(state);
if (!session || session.status !== "done" || !session.result) {
return NextResponse.json(
{ error: session?.error || "OAuth session not completed. Please restart the login flow." },
{ status: 400 },
);
}
const { uid, accessToken, baseUrl } = session.result;
// Desktop-exclusive Preview models authenticate with the account-session
// passToken, which only lives in MiMo Desktop's cookie store — attach it
// to the connection so those models work right after OAuth.
let passToken = null;
try {
passToken = await readDesktopPassToken();
} catch {
// Desktop not installed / cookie DB locked — preview models stay unavailable.
}
try {
const connection = await createProviderConnection({
provider: "xiaomi-mimo",
authType: "oauth",
accessToken,
refreshToken: null,
expiresAt: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString(),
email: uid ? `${uid}@xiaomi` : null,
displayName: uid ? `Xiaomi ${uid}` : "Xiaomi MiMo",
providerSpecificData: {
uid: uid || null,
baseUrl: baseUrl || "https://api.xiaomimimo.com/v1",
authMethod: "oauth",
mimoPassToken: passToken?.passToken || null,
mimoUserId: passToken?.userId || null,
mimoCUserId: passToken?.cUserId || null,
},
testStatus: "active",
});
clearXiaomiMimoSession(state);
stopXiaomiMimoProxy();
return NextResponse.json({
success: true,
connection: {
id: connection.id,
provider: connection.provider,
email: connection.email,
displayName: connection.displayName,
},
});
} catch (err) {
clearXiaomiMimoSession(state);
stopXiaomiMimoProxy();
return NextResponse.json({ error: err.message }, { status: 500 });
}
}
// Trae/Windsurf: code is either a raw callback URL or a pasted token.
// exchangeTokens() handles both paths; no PKCE, skip codex JWT extraction.
if (provider === "trae" || provider === "windsurf") {