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:
叶炜朋
2026-09-10 23:42:41 +07:00
parent 83af3f1853
commit 73cb89143c
21 changed files with 1828 additions and 4 deletions
@@ -5,7 +5,7 @@ import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { getProviderIconSrc, markProviderIconMissing } from "@/shared/utils/providerIcon";
import { Card, Button, Badge, Input, Modal, CardSkeleton, OAuthModal, KiroOAuthWrapper, CursorAuthModal, IFlowCookieModal, GitLabAuthModal, Toggle, Select, EditConnectionModal, NoAuthProxyCard, ConfirmModal } from "@/shared/components";
import { Card, Button, Badge, Input, Modal, CardSkeleton, OAuthModal, KiroOAuthWrapper, CursorAuthModal, XiaomiMimoAuthModal, IFlowCookieModal, GitLabAuthModal, Toggle, Select, EditConnectionModal, NoAuthProxyCard, ConfirmModal } from "@/shared/components";
import { OAUTH_PROVIDERS, APIKEY_PROVIDERS, FREE_PROVIDERS, FREE_TIER_PROVIDERS, WEB_COOKIE_PROVIDERS, getProviderAlias, isOpenAICompatibleProvider, isAnthropicCompatibleProvider, AI_PROVIDERS } from "@/shared/constants/providers";
import { getModelsByProviderId, getModelKind } from "@/shared/constants/models";
import { getThinkingLevels } from "open-sse/providers/thinkingLevels.js";
@@ -45,6 +45,7 @@ export default function ProviderDetailPage() {
const [providerNode, setProviderNode] = useState(null);
const [proxyPools, setProxyPools] = useState([]);
const [showOAuthModal, setShowOAuthModal] = useState(false);
const [showXiaomiMimoModal, setShowXiaomiMimoModal] = useState(false);
const [showIFlowCookieModal, setShowIFlowCookieModal] = useState(false);
const [showAddApiKeyModal, setShowAddApiKeyModal] = useState(false);
const [addConnectionError, setAddConnectionError] = useState("");
@@ -98,6 +99,11 @@ export default function ProviderDetailPage() {
return;
}
}
// Xiaomi Desktop: auto-import local credentials first, OAuth as fallback
if (providerId === "xiaomi-mimo") {
setShowXiaomiMimoModal(true);
return;
}
if (isOAuth) {
openOAuthConnection();
return;
@@ -1796,6 +1802,13 @@ export default function ProviderDetailPage() {
onClose={() => setShowOAuthModal(false)}
/>
)}
{/* Xiaomi Desktop: auto-import local credentials modal */}
<XiaomiMimoAuthModal
isOpen={showXiaomiMimoModal}
onSuccess={handleOAuthSuccess}
onClose={() => setShowXiaomiMimoModal(false)}
/>
{providerId === "iflow" && (
<IFlowCookieModal
isOpen={showIFlowCookieModal}
+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") {
@@ -0,0 +1,136 @@
import { NextResponse } from "next/server";
import { createProviderConnection } from "@/models";
/**
* POST /api/oauth/xiaomi-mimo/api-key
* Import a Xiaomi MiMo API key manually (or from auto-import).
* The key is validated against the models endpoint, then stored.
*
* Body: { apiKey, uid?, baseUrl? }
*/
export async function POST(request) {
try {
const { apiKey, uid, baseUrl, mimoPassToken, mimoUserId, mimoCUserId } = await request.json();
if (!apiKey || typeof apiKey !== "string" || !apiKey.trim()) {
return NextResponse.json(
{ error: "API key is required" },
{ status: 400 },
);
}
const key = apiKey.trim();
if (!key.startsWith("sk-")) {
return NextResponse.json(
{ error: "Invalid key format — expected sk- prefix" },
{ status: 400 },
);
}
const effectiveBaseUrl = (baseUrl || "https://api.xiaomimimo.com/v1").replace(/\/+$/, "");
// Validate the key against the models endpoint
let validated = false;
let modelCount = 0;
try {
const resp = await fetch(`${effectiveBaseUrl}/models`, {
method: "GET",
headers: {
Authorization: `Bearer ${key}`,
"X-Mimo-Source": "mimocode-cli",
},
signal: AbortSignal.timeout(10000),
});
if (resp.ok) {
const data = await resp.json();
modelCount = Array.isArray(data?.data) ? data.data.length : 0;
validated = true;
}
} catch {
// Network error — still allow import (key may be valid but network blocked)
}
if (!validated) {
// Soft-fail: store the key but mark as untested
console.log("[xiaomi-mimo] key validation failed, storing as untested");
}
// Dedup: if a connection with the same uid or same key already exists, update it
const { getProviderConnections, updateProviderConnection } = await import("@/models");
const existing = (await getProviderConnections()).find(
(c) => c.provider === "xiaomi-mimo" && (
(uid && c.email === `${uid}@xiaomi`) ||
c.accessToken === key
),
);
if (existing) {
const updated = await updateProviderConnection(existing.id, {
accessToken: key,
providerSpecificData: {
...existing.providerSpecificData,
uid: uid || existing.providerSpecificData?.uid || null,
baseUrl: effectiveBaseUrl,
// Per-account session credential — enables multi-account rotation.
mimoPassToken: mimoPassToken || existing.providerSpecificData?.mimoPassToken || null,
mimoUserId: mimoUserId || existing.providerSpecificData?.mimoUserId || null,
mimoCUserId: mimoCUserId || existing.providerSpecificData?.mimoCUserId || null,
modelCount,
},
testStatus: validated ? "active" : existing.testStatus,
});
return NextResponse.json({
success: true,
validated,
modelCount,
updated: true,
connection: {
id: existing.id,
provider: existing.provider,
email: existing.email,
displayName: existing.displayName,
},
});
}
const connection = await createProviderConnection({
provider: "xiaomi-mimo",
authType: "api_key",
accessToken: key,
refreshToken: null,
// API keys don't expire on a fixed schedule; use a long horizon
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: effectiveBaseUrl,
authMethod: "api_key",
provider: "API Key",
modelCount,
// Per-account session credential — enables multi-account rotation.
mimoPassToken: mimoPassToken || null,
mimoUserId: mimoUserId || null,
mimoCUserId: mimoCUserId || null,
},
testStatus: validated ? "active" : "untested",
});
return NextResponse.json({
success: true,
validated,
modelCount,
connection: {
id: connection.id,
provider: connection.provider,
email: connection.email,
displayName: connection.displayName,
},
});
} catch (error) {
console.log("Xiaomi MiMo API key import error:", error);
return NextResponse.json(
{ error: "API key import failed" },
{ status: 500 },
);
}
}
@@ -0,0 +1,140 @@
import { NextResponse } from "next/server";
import { readFile, access, constants } from "fs/promises";
import { homedir } from "os";
import { join } from "path";
import { readDesktopPassToken } from "open-sse/shared/mimoAccount.js";
/**
* GET /api/oauth/xiaomi-mimo/auto-import
* Auto-detect Xiaomi MiMo credentials from local auth.json.
*
* Sources (in priority order):
* 1. ~/.local/share/mimocode/auth.json → xiaomi field
* 2. %APPDATA%/Xiaomi MiMo/... → (future: Desktop keychain)
*
* auth.json shape:
* {
* "xiaomi": {
* "type": "api",
* "key": "sk-xxxx",
* "metadata": { "uid": "...", "base_url": "https://api.xiaomimimo.com/v1" }
* }
* }
*/
function getCandidatePaths() {
const home = homedir();
const paths = [];
// MiMoCode / MiMo Desktop shared data dir (cross-platform XDG)
paths.push(join(home, ".local", "share", "mimocode", "auth.json"));
// Windows: also check USERPROFILE-based XDG
if (process.platform === "win32") {
const appData = process.env.APPDATA || join(home, "AppData", "Roaming");
// Desktop's own storage (may have separate credentials in the future)
paths.push(join(appData, "Xiaomi MiMo", "auth.json"));
}
// macOS
if (process.platform === "darwin") {
paths.push(
join(home, "Library", "Application Support", "mimocode", "auth.json"),
);
}
return paths;
}
/**
* GET /api/oauth/xiaomi-mimo/auto-import
*/
export async function GET() {
try {
const candidates = getCandidatePaths();
let authPath = null;
for (const candidate of candidates) {
try {
await access(candidate, constants.R_OK);
authPath = candidate;
break;
} catch {
// Try next candidate
}
}
if (!authPath) {
return NextResponse.json({
found: false,
error: `Xiaomi MiMo Desktop auth file not found. Checked:\n${candidates.join("\n")}\n\nMake sure Xiaomi MiMo Desktop is installed and you are signed in.`,
});
}
const raw = await readFile(authPath, "utf-8");
let auth;
try {
auth = JSON.parse(raw);
} catch {
return NextResponse.json({
found: false,
error: "auth.json is not valid JSON. Please sign in to Xiaomi MiMo Desktop again.",
});
}
const xiaomi = auth?.xiaomi;
if (!xiaomi || !xiaomi.key) {
return NextResponse.json({
found: false,
error: "No Xiaomi credentials found in auth.json. Please sign in to Xiaomi MiMo Desktop.",
});
}
// Validate key format
const key = String(xiaomi.key).trim();
if (!key.startsWith("sk-")) {
return NextResponse.json({
found: false,
error: "Xiaomi key does not appear to be a valid API key (expected sk- prefix).",
});
}
const metadata = xiaomi.metadata || {};
const uid = metadata.uid || null;
const baseUrl = metadata.base_url || "https://api.xiaomimimo.com/v1";
// Account-session passToken from Desktop's cookie store. Persisting it per
// connection is what lets multiple Xiaomi accounts rotate independently.
// (null while Desktop is running — its cookie DB is exclusively locked.)
let mimoPassToken = null;
let mimoUserId = null;
let mimoCUserId = null;
try {
const pt = await readDesktopPassToken();
if (pt) {
mimoPassToken = pt.passToken;
mimoUserId = pt.userId;
mimoCUserId = pt.cUserId;
}
} catch (e) {
console.log("[xiaomi-mimo] passToken read failed (non-fatal):", e.message);
}
return NextResponse.json({
found: true,
apiKey: key,
uid,
baseUrl,
source: authPath,
mimoPassToken,
mimoUserId,
mimoCUserId,
});
} catch (error) {
console.log("Xiaomi MiMo auto-import error:", error);
return NextResponse.json(
{ found: false, error: error.message },
{ status: 500 },
);
}
}