feat(xai): add xAI Grok provider with OAuth + API key auth + image

Adapted from PR #1286 (mugnimaestra/feat/xai-grok-provider) to match
existing app architecture. Includes:

- OAuth 2.0 with PKCE on loopback port 56121 (Grok Build)
- API key auth path (console.x.ai)
- Token refresh wiring (open-sse + sse tokenRefresh)
- Dashboard OAuth modal with fixed-port flow + manual code fallback
- Provider registry entries (OAuth + API key)
- xAI image generation via OpenAI-compatible adapter
  (grok-2-image-1212 model, no size/quality/style params)

Excludes (intentionally, to match app patterns):
- Custom xAI Responses executor (DefaultExecutor handles /chat/completions)
- xAI-specific translators (app uses OpenAI as intermediate format)
- Image edits (not supported by current imageGenerationCore)
- Video endpoints (app has no video subsystem yet)
- CLI xai-login command

Refs decolua#1286

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Muhammad Mugni Hadi
2026-05-21 10:18:12 +07:00
committed by decolua
parent 0654d7bb35
commit d976f4cc87
21 changed files with 1058 additions and 72 deletions

View File

@@ -13,8 +13,52 @@ import {
registerCodexSession,
getCodexSessionStatus,
clearCodexSession,
startXaiProxy,
stopXaiProxy,
registerXaiSession,
getXaiSessionStatus,
clearXaiSession,
} from "@/lib/oauth/utils/server";
async function completeXaiManualCode(code, state) {
const session = state ? getXaiSessionStatus(state) : null;
if (!session) {
throw new Error("xAI OAuth session not found; restart the login flow and paste the code again");
}
if (!code) throw new Error("Missing xAI authorization code");
try {
const tokenData = await exchangeTokens(
"xai",
code,
session.redirectUri,
session.codeVerifier,
state
);
const connection = await createProviderConnection({
provider: "xai",
authType: "oauth",
...tokenData,
expiresAt: tokenData.expiresIn
? new Date(Date.now() + tokenData.expiresIn * 1000).toISOString()
: null,
testStatus: "active",
});
clearXaiSession(state);
stopXaiProxy();
return {
id: connection.id,
provider: connection.provider,
email: connection.email,
displayName: connection.displayName,
};
} catch (err) {
clearXaiSession(state);
stopXaiProxy();
throw err;
}
}
/**
* Dynamic OAuth API Route
* Handles: authorize, exchange, device-code, poll
@@ -33,53 +77,58 @@ export async function GET(request, { params }) {
const reservedParams = new Set(["redirect_uri"]);
const meta = {};
searchParams.forEach((value, key) => { if (!reservedParams.has(key)) meta[key] = value; });
const authData = generateAuthData(provider, redirectUri, Object.keys(meta).length ? meta : undefined);
const authData = await generateAuthData(provider, redirectUri, Object.keys(meta).length ? meta : undefined);
return NextResponse.json(authData);
}
if (action === "start-proxy") {
if (provider !== "codex") {
return NextResponse.json({ error: "Proxy only supported for codex" }, { status: 400 });
if (!["codex", "xai"].includes(provider)) {
return NextResponse.json({ error: "Proxy only supported for codex/xai" }, { status: 400 });
}
const appPort = searchParams.get("app_port");
if (!appPort) {
return NextResponse.json({ error: "Missing app_port" }, { status: 400 });
}
// Optional server-side mode params: register session for auto-exchange
const state = searchParams.get("state");
const codeVerifier = searchParams.get("code_verifier");
const redirectUri = searchParams.get("redirect_uri");
const result = await startCodexProxy(Number(appPort));
const result = provider === "xai"
? await startXaiProxy(Number(appPort))
: await startCodexProxy(Number(appPort));
let serverSide = false;
if (result.success && state && codeVerifier && redirectUri) {
serverSide = registerCodexSession({ state, codeVerifier, redirectUri });
serverSide = provider === "xai"
? registerXaiSession({ state, codeVerifier, redirectUri })
: registerCodexSession({ state, codeVerifier, redirectUri });
}
return NextResponse.json({ ...result, serverSide });
}
if (action === "poll-status") {
if (provider !== "codex") {
return NextResponse.json({ error: "Poll only supported for codex" }, { status: 400 });
if (!["codex", "xai"].includes(provider)) {
return NextResponse.json({ error: "Poll only supported for codex/xai" }, { status: 400 });
}
const state = searchParams.get("state");
if (!state) {
return NextResponse.json({ error: "Missing state" }, { status: 400 });
}
const session = getCodexSessionStatus(state);
const session = provider === "xai" ? getXaiSessionStatus(state) : getCodexSessionStatus(state);
if (!session) return NextResponse.json({ status: "unknown" });
if (session.status === "done" || session.status === "error") {
const payload = { ...session };
clearCodexSession(state);
if (provider === "xai") clearXaiSession(state);
else clearCodexSession(state);
return NextResponse.json(payload);
}
return NextResponse.json({ status: session.status });
}
if (action === "stop-proxy") {
if (provider !== "codex") {
return NextResponse.json({ error: "Proxy only supported for codex" }, { status: 400 });
if (!["codex", "xai"].includes(provider)) {
return NextResponse.json({ error: "Proxy only supported for codex/xai" }, { status: 400 });
}
stopCodexProxy();
if (provider === "xai") stopXaiProxy();
else stopCodexProxy();
return NextResponse.json({ success: true });
}
@@ -89,7 +138,7 @@ export async function GET(request, { params }) {
return NextResponse.json({ error: "Provider does not support device code flow" }, { status: 400 });
}
const authData = generateAuthData(provider, null);
const authData = await generateAuthData(provider, null);
const startUrl = searchParams.get("start_url");
const region = searchParams.get("region");
const authMethod = searchParams.get("auth_method");
@@ -267,6 +316,15 @@ export async function POST(request, { params }) {
});
}
if (action === "manual-code") {
if (provider !== "xai") {
return NextResponse.json({ error: "Manual code only supported for xai" }, { status: 400 });
}
const { code, state } = body;
const connection = await completeXaiManualCode(String(code || "").trim(), String(state || "").trim());
return NextResponse.json({ success: true, connection });
}
return NextResponse.json({ error: "Unknown action" }, { status: 400 });
} catch (error) {
console.log("OAuth POST error:", error);