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:41:40 +07:00
parent 83af3f1853
commit 73cb89143c
21 changed files with 1828 additions and 4 deletions

View File

@@ -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}

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") {

View File

@@ -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 },
);
}
}

View File

@@ -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 },
);
}
}

View File

@@ -19,6 +19,10 @@ async function tryBunSqlite() {
async function tryBetterSqlite() {
// Skip on Bun — better-sqlite3 native bindings unsupported
if (process.versions.bun) return null;
// Skip on Node >= 24: the native addon SIGSEGVs on load there, which is a
// process-level crash the try/catch below cannot recover from. node:sqlite covers it.
const [nodeMajor] = process.versions.node.split(".").map(Number);
if (nodeMajor >= 24) return null;
try {
const { createBetterSqliteAdapter } = await import("./adapters/betterSqliteAdapter.js");
return createBetterSqliteAdapter(DATA_FILE);

View File

@@ -130,6 +130,21 @@ export const GROK_CLI_CONFIG = { ...PROVIDER_OAUTH["grok-cli"] };
// 3) Redirect → ${cb}?refreshToken=...&loginHost=...&isRedirect=true
// 4) POST ExchangeToken {ClientID, RefreshToken, ClientSecret:"-"} → {Result.AccessToken, ExpiresAt}
// 5) POST GetUserInfo (x-cloudide-token) → email/name
// Xiaomi MiMo Desktop OAuth — custom ECDH encrypted-callback flow (NOT standard OAuth2).
// 1) Client generates X25519 keypair
// 2) Browser opens ${platformUrl}/authorize?pk=<pubkey>&redirect_uri=http://localhost:<port>/&kn=mimocode&key_name=...
// 3) Redirect → http://localhost:<port>/?u=<base64 encrypted payload>
// 4) Decrypt: ECDH(shared) → SHA256 → AES-256-GCM
// Layout: [12-byte nonce][32-byte ephemeral pubkey][ciphertext][16-byte GCM tag]
// 5) Result JSON: { uid, sk, url }
export const XIAOMI_MIMO_CONFIG = {
platformUrl: process.env.MIMO_PLATFORM_URL || "https://platform.xiaomimimo.com",
defaultBaseUrl: "https://api.xiaomimimo.com/v1",
kn: "mimocode",
callbackPath: "/",
timeoutMs: 300000, // 5 minutes
};
export const TRAE_CONFIG = {
clientId: "ono9krqynydwx5",
clientSecret: "-",

View File

@@ -0,0 +1,123 @@
import crypto from "crypto";
import { XIAOMI_MIMO_CONFIG } from "../constants/oauth.js";
// ───────────────────────────────────────────────────────────────────────────
// Xiaomi MiMo OAuth helpers
// Custom ECDH + AES-256-GCM encrypted-callback flow (NOT standard OAuth2).
// ───────────────────────────────────────────────────────────────────────────
/**
* Generate an X25519 keypair for the OAuth handshake.
* @returns {{ publicKey: string, privateKeyDer: Buffer }}
* publicKey — base64 SPKI (for the `pk` URL param)
* privateKeyDer — PKCS8 DER Buffer (for ECDH later)
*/
export function generateKeyPair() {
const { publicKey, privateKey } = crypto.generateKeyPairSync("x25519");
const publicKeyDer = publicKey.export({ format: "der", type: "spki" });
// SPKI for X25519 is 44 bytes; the raw 32-byte key is the last 32 bytes.
// But the platform expects the full base64 SPKI — pass as-is.
const publicKeyB64 = publicKeyDer.toString("base64");
const privateKeyDer = privateKey.export({ format: "der", type: "pkcs8" });
return { publicKey: publicKeyB64, privateKeyDer };
}
/**
* Decrypt the `u` query parameter from the Xiaomi OAuth callback.
*
* Wire format (base64-decoded):
* bytes 0..11 — 12-byte AES-GCM nonce
* bytes 12..43 — 32-byte ephemeral public key (raw X25519)
* bytes 44..n-16 — ciphertext
* last 16 bytes — GCM auth tag
*
* Key derivation: SHA256(ECDH(clientPrivateKey, ephemeralPublicKey))
*
* @param {Buffer} privateKeyDer — PKCS8 DER private key from generateKeyPair()
* @param {string} encryptedB64 — the `u` query param value (base64)
* @returns {{ uid: string, sk: string, url?: string }}
*/
export function decryptCallback(privateKeyDer, encryptedB64) {
const raw = Buffer.from(encryptedB64, "base64");
if (raw.length < 12 + 32 + 16 + 1) {
throw new Error(`Encrypted payload too short: ${raw.length} bytes`);
}
const nonce = raw.subarray(0, 12);
const ephemeralPubRaw = raw.subarray(12, 44);
const ciphertextAndTag = raw.subarray(44);
const tag = ciphertextAndTag.subarray(ciphertextAndTag.length - 16);
const ciphertext = ciphertextAndTag.subarray(0, ciphertextAndTag.length - 16);
// Reconstruct the ephemeral public key as SPKI DER for Node crypto.
// X25519 SPKI prefix: 302a300506032b656e032100
const ephemeralPub = crypto.createPublicKey({
key: Buffer.concat([
Buffer.from("302a300506032b656e032100", "hex"),
ephemeralPubRaw,
]),
format: "der",
type: "spki",
});
const privateKey = crypto.createPrivateKey({
key: privateKeyDer,
format: "der",
type: "pkcs8",
});
const sharedSecret = crypto.diffieHellman({ privateKey, publicKey: ephemeralPub });
const derivedKey = crypto.createHash("sha256").update(sharedSecret).digest();
const decipher = crypto.createDecipheriv("aes-256-gcm", derivedKey, nonce);
decipher.setAuthTag(tag);
const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
const parsed = JSON.parse(decrypted.toString("utf-8"));
if (!parsed || typeof parsed !== "object") {
throw new Error("Decrypted payload is not a valid object");
}
return {
uid: parsed.uid || null,
sk: parsed.sk || null,
url: parsed.url || XIAOMI_MIMO_CONFIG.defaultBaseUrl,
};
}
/**
* Build the browser authorization URL.
* @param {string} publicKey — base64 SPKI from generateKeyPair()
* @param {string} redirectUri — e.g. http://localhost:12345/
* @param {string} [keyName] — optional stable key name
* @returns {string}
*/
export function buildAuthorizeUrl(publicKey, redirectUri, keyName) {
const params = new URLSearchParams({
pk: publicKey,
redirect_uri: redirectUri,
kn: XIAOMI_MIMO_CONFIG.kn,
});
if (keyName) params.set("key_name", keyName);
return `${XIAOMI_MIMO_CONFIG.platformUrl}/authorize?${params.toString()}`;
}
/**
* Get or create a stable key name for this installation.
* Stored in the 9Router data dir so re-auth reuses the same name.
*/
export function getKeyName() {
// Use a deterministic name based on machine — avoids needing filesystem writes
// in the OAuth provider layer. The platform treats key_name as a label only.
const machineId = crypto
.createHash("sha256")
.update(`${process.platform}-${process.env.COMPUTERNAME || process.env.HOSTNAME || "unknown"}`)
.digest("hex")
.slice(0, 8);
return `9router-xmd-${machineId}`;
}

View File

@@ -755,3 +755,185 @@ export function stopZedProxy() {
zedProxyPort = null;
}
// ───────────────────────────────────────────────────────────────────────────
// Xiaomi MiMo Desktop OAuth callback proxy
// Receives the ECDH-encrypted `u` param, decrypts it, stores the session.
// ───────────────────────────────────────────────────────────────────────────
let xiaomiMimoProxyServer = null;
let xiaomiMimoProxyPort = null;
let xiaomiMimoProxyTimeout = null;
const xiaomiMimoSessions = new Map();
export function registerXiaomiMimoSession({ state, privateKeyDer }) {
if (!state || !privateKeyDer) return false;
xiaomiMimoSessions.set(state, {
privateKeyDer,
status: "pending",
createdAt: Date.now(),
});
return true;
}
export function getXiaomiMimoSessionStatus(state) {
const s = xiaomiMimoSessions.get(state);
if (!s) return null;
// Don't leak the private key to the client
return { status: s.status, result: s.result || null, error: s.error || null };
}
export function clearXiaomiMimoSession(state) {
xiaomiMimoSessions.delete(state);
}
function renderXiaomiMimoResultPage(success, message) {
const color = success ? "#22c55e" : "#ef4444";
const icon = success ? "&#10003;" : "&#10007;";
const title = success ? "Authentication Successful" : "Authentication Failed";
return `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>${title}</title>
<style>
body { font-family: system-ui; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #f5f5f5; }
.container { text-align: center; padding: 2rem; background: white; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
.icon { color: ${color}; font-size: 3rem; }
h1 { margin: 1rem 0; font-size: 1.25rem; }
p { color: #666; font-size: 0.875rem; }
</style>
</head>
<body>
<div class="container">
<div class="icon">${icon}</div>
<h1>${title}</h1>
<p>${message || (success ? "You can close this tab and return to 9Router." : "Please try again.")}</p>
${success ? "<script>setTimeout(() => window.close(), 3000);</script>" : ""}
</div>
</body>
</html>`;
}
/**
* Start the Xiaomi Desktop OAuth callback proxy.
* @returns {Promise<{success: boolean, port?: number, callbackUrl?: string, reason?: string}>}
*/
export function startXiaomiMimoProxy() {
return new Promise((resolve) => {
if (xiaomiMimoProxyServer) {
resolve({
success: true,
port: xiaomiMimoProxyPort,
callbackUrl: `http://127.0.0.1:${xiaomiMimoProxyPort}/`,
});
return;
}
const server = http.createServer(async (req, res) => {
// Origin guard
if (!isLoopbackOrigin(req.headers.origin)) {
res.writeHead(403);
res.end("Forbidden");
return;
}
const url = new URL(req.url, "http://127.0.0.1");
const u = url.searchParams.get("u");
if (!u) {
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
res.end(renderXiaomiMimoResultPage(false, "Missing encrypted payload (u parameter)."));
return;
}
// Try each pending session's private key — the callback URL carries no
// state param, so we attempt decryption with every pending key.
const pendingSessions = [...xiaomiMimoSessions.entries()]
.filter(([, s]) => s.status === "pending");
if (pendingSessions.length === 0) {
res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
res.end(renderXiaomiMimoResultPage(false, "No active OAuth session. Please restart the login flow."));
return;
}
try {
const { decryptCallback } = await import("../providers/xiaomi-mimo.js");
let result = null;
let matchedState = null;
for (const [state, session] of pendingSessions) {
try {
result = decryptCallback(session.privateKeyDer, u);
matchedState = state;
break;
} catch {
// Wrong key for this session — try next
}
}
if (!result || !matchedState) {
throw new Error("Could not decrypt with any pending session key");
}
if (!result.sk) {
throw new Error("Decrypted payload missing sk (API key)");
}
// Store result only in the matched session
const session = xiaomiMimoSessions.get(matchedState);
if (session) {
session.status = "done";
session.result = {
uid: result.uid,
accessToken: result.sk,
baseUrl: result.url || "https://api.xiaomimimo.com/v1",
};
}
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(renderXiaomiMimoResultPage(true, "Xiaomi account linked. You can close this tab."));
console.log("[xiaomi-mimo oauth] callback decrypted, uid:", result.uid);
} catch (err) {
console.error("[xiaomi-mimo oauth] decrypt failed:", err.message);
for (const [, session] of pendingSessions) {
session.status = "error";
session.error = err.message;
}
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
res.end(renderXiaomiMimoResultPage(false, `Decryption failed: ${err.message}`));
}
});
server.on("error", (err) => {
console.log("[xiaomi-mimo oauth] listen error:", err.message);
resolve({ success: false, reason: err.message });
});
server.listen(0, "127.0.0.1", () => {
xiaomiMimoProxyServer = server;
xiaomiMimoProxyPort = server.address().port;
xiaomiMimoProxyTimeout = setTimeout(() => {
console.log("[xiaomi-mimo oauth] timeout, stopping");
stopXiaomiMimoProxy();
}, 300000);
console.log(`[xiaomi-mimo oauth] listening on port ${xiaomiMimoProxyPort}`);
resolve({
success: true,
port: xiaomiMimoProxyPort,
callbackUrl: `http://127.0.0.1:${xiaomiMimoProxyPort}/`,
});
});
});
}
export function stopXiaomiMimoProxy() {
console.log(`[xiaomi-mimo oauth] stopping (port ${xiaomiMimoProxyPort || "-"})`);
if (xiaomiMimoProxyTimeout) { clearTimeout(xiaomiMimoProxyTimeout); xiaomiMimoProxyTimeout = null; }
if (xiaomiMimoProxyServer) { xiaomiMimoProxyServer.close(); xiaomiMimoProxyServer = null; }
xiaomiMimoProxyPort = null;
// No callback can arrive once the listener is down, so drop every pending
// session — each holds an X25519 private key and they would otherwise
// accumulate for the process lifetime (one per /authorize call).
xiaomiMimoSessions.clear();
}

View File

@@ -0,0 +1,276 @@
"use client";
import { useState, useEffect } from "react";
import PropTypes from "prop-types";
import { Modal, Button } from "@/shared/components";
/**
* Xiaomi MiMo Auth Modal
*
* Auto-imports credentials from the local Xiaomi MiMo Desktop auth.json (~/.local/share/mimocode/auth.json).
* If auto-import fails, offers a one-click browser OAuth fallback.
* Reached only via the "Connect with OAuth" button — the API-key path uses the
* standard Add API Key modal, since Xiaomi MiMo supports both auth modes.
*/
export default function XiaomiMimoAuthModal({ isOpen, onSuccess, onClose }) {
const [phase, setPhase] = useState("detecting"); // detecting | found | not-found | importing | error
const [detectResult, setDetectResult] = useState(null);
const [error, setError] = useState(null);
const [oauthUrl, setOauthUrl] = useState(null);
const [oauthState, setOauthState] = useState(null);
// Auto-detect local credentials when modal opens
useEffect(() => {
if (!isOpen) return;
let cancelled = false;
(async () => {
setPhase("detecting");
setError(null);
setDetectResult(null);
setOauthUrl(null);
try {
const res = await fetch("/api/oauth/xiaomi-mimo/auto-import");
const data = await res.json();
if (cancelled) return;
if (data.found && data.apiKey) {
setDetectResult(data);
setPhase("found");
} else {
setPhase("not-found");
setError(data.error || "Xiaomi MiMo Desktop credentials not found on this machine.");
}
} catch {
if (!cancelled) {
setPhase("not-found");
setError("Failed to read local Xiaomi MiMo Desktop credentials.");
}
}
})();
return () => { cancelled = true; };
}, [isOpen]);
// Import the auto-detected key
const handleImport = async () => {
if (!detectResult?.apiKey) return;
setPhase("importing");
setError(null);
try {
const res = await fetch("/api/oauth/xiaomi-mimo/api-key", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
apiKey: detectResult.apiKey,
uid: detectResult.uid,
baseUrl: detectResult.baseUrl,
mimoPassToken: detectResult.mimoPassToken || null,
mimoUserId: detectResult.mimoUserId || null,
mimoCUserId: detectResult.mimoCUserId || null,
}),
});
const data = await res.json();
if (!res.ok || !data.success) {
throw new Error(data.error || "Import failed");
}
onSuccess?.(data.connection);
onClose();
} catch (err) {
setPhase("found");
setError(err.message);
}
};
// Start browser OAuth fallback
const handleStartOAuth = async () => {
setError(null);
try {
const state = crypto.randomUUID();
const res = await fetch(`/api/oauth/xiaomi-mimo/authorize?state=${state}`);
const data = await res.json();
if (data.authorizeUrl) {
setOauthUrl(data.authorizeUrl);
setOauthState(data.state);
window.open(data.authorizeUrl, "_blank", "width=600,height=700");
} else {
throw new Error(data.error || "Failed to start OAuth");
}
} catch (err) {
setError(err.message);
}
};
// Poll OAuth result
const handlePollOAuth = async () => {
if (!oauthState) return;
setError(null);
try {
const res = await fetch(`/api/oauth/xiaomi-mimo/poll-status?state=${oauthState}`);
const data = await res.json();
if (data.status === "done" && data.result) {
// Exchange to create the connection
const exRes = await fetch("/api/oauth/xiaomi-mimo/exchange", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ state: oauthState }),
});
const exData = await exRes.json();
if (exData.success) {
onSuccess?.(exData.connection);
onClose();
} else {
throw new Error(exData.error || "Exchange failed");
}
} else if (data.status === "error") {
throw new Error(data.error || "OAuth failed");
} else {
setError("Authorization not completed yet. Finish in the browser, then click Check Again.");
}
} catch (err) {
setError(err.message);
}
};
return (
<Modal isOpen={isOpen} title="Connect Xiaomi MiMo" onClose={onClose}>
<div className="flex flex-col gap-4">
{/* Detecting */}
{phase === "detecting" && (
<div className="text-center py-6">
<div className="size-16 mx-auto mb-4 rounded-full bg-primary/10 flex items-center justify-center">
<span className="material-symbols-outlined text-3xl text-primary animate-spin">
progress_activity
</span>
</div>
<h3 className="text-lg font-semibold mb-2">Reading local credentials...</h3>
<p className="text-sm text-text-muted">
Checking ~/.local/share/mimocode/auth.json
</p>
</div>
)}
{/* Found — one-click import */}
{phase === "found" && detectResult && (
<>
<div className="bg-green-50 dark:bg-green-900/20 p-3 rounded-lg border border-green-200 dark:border-green-800">
<div className="flex gap-2">
<span className="material-symbols-outlined text-green-600 dark:text-green-400">check_circle</span>
<div className="text-sm text-green-800 dark:text-green-200">
<p className="font-medium">Xiaomi MiMo Desktop credentials found!</p>
<p className="mt-1 opacity-80">
UID: {detectResult.uid || "—"} · Source: {detectResult.source?.split(/[\\/]/).pop()}
</p>
</div>
</div>
</div>
{error && (
<div className="bg-red-50 dark:bg-red-900/20 p-3 rounded-lg border border-red-200 dark:border-red-800">
<p className="text-sm text-red-600 dark:text-red-400">{error}</p>
</div>
)}
<div className="flex gap-2">
<Button onClick={handleImport} fullWidth>
Connect with Local Credentials
</Button>
<Button onClick={onClose} variant="ghost" fullWidth>
Cancel
</Button>
</div>
</>
)}
{/* Importing */}
{phase === "importing" && (
<div className="text-center py-6">
<div className="size-16 mx-auto mb-4 rounded-full bg-primary/10 flex items-center justify-center">
<span className="material-symbols-outlined text-3xl text-primary animate-spin">
progress_activity
</span>
</div>
<h3 className="text-lg font-semibold mb-2">Connecting...</h3>
</div>
)}
{/* Not found — offer OAuth fallback */}
{phase === "not-found" && (
<>
<div className="bg-amber-50 dark:bg-amber-900/20 p-3 rounded-lg border border-amber-200 dark:border-amber-800">
<div className="flex gap-2 items-start">
<span className="material-symbols-outlined text-amber-600 dark:text-amber-400">info</span>
<div className="text-sm text-amber-800 dark:text-amber-200">
<p className="font-medium">Local credentials not found</p>
<p className="mt-1 opacity-80">{error}</p>
<p className="mt-2 opacity-80">
Make sure Xiaomi MiMo Desktop is installed and you are signed in, then retry.
Or sign in via browser below.
</p>
</div>
</div>
</div>
{!oauthUrl ? (
<div className="flex gap-2">
<Button
onClick={() => {
setPhase("detecting");
// Re-trigger detect
fetch("/api/oauth/xiaomi-mimo/auto-import")
.then((r) => r.json())
.then((data) => {
if (data.found && data.apiKey) {
setDetectResult(data);
setPhase("found");
} else {
setPhase("not-found");
setError(data.error || "Still not found.");
}
})
.catch(() => setPhase("not-found"));
}}
variant="outline"
fullWidth
>
Retry Local Detect
</Button>
<Button onClick={handleStartOAuth} fullWidth>
Sign in via Browser
</Button>
</div>
) : (
<div className="flex flex-col gap-2">
<div className="bg-blue-50 dark:bg-blue-900/20 p-3 rounded-lg border border-blue-200 dark:border-blue-800">
<p className="text-sm text-blue-800 dark:text-blue-200">
Browser opened. Complete the Xiaomi sign-in, then click{" "}
<strong>Check Again</strong>.
</p>
</div>
<div className="flex gap-2">
<Button onClick={handlePollOAuth} fullWidth>
Check Again
</Button>
<Button onClick={onClose} variant="ghost" fullWidth>
Cancel
</Button>
</div>
</div>
)}
</>
)}
</div>
</Modal>
);
}
XiaomiMimoAuthModal.propTypes = {
isOpen: PropTypes.bool.isRequired,
onSuccess: PropTypes.func,
onClose: PropTypes.func.isRequired,
};

View File

@@ -28,6 +28,7 @@ export { default as KiroAuthModal } from "./KiroAuthModal";
export { default as KiroOAuthWrapper } from "./KiroOAuthWrapper";
export { default as KiroSocialOAuthModal } from "./KiroSocialOAuthModal";
export { default as CursorAuthModal } from "./CursorAuthModal";
export { default as XiaomiMimoAuthModal } from "./XiaomiMimoAuthModal";
export { default as IFlowCookieModal } from "./IFlowCookieModal";
export { default as GitLabAuthModal } from "./GitLabAuthModal";
export { default as EditConnectionModal } from "./EditConnectionModal";