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

@@ -11,10 +11,11 @@ export default function AddApiKeyModal({ isOpen, provider, providerName, isCompa
const NONE_PROXY_POOL_VALUE = "__none__";
const isOllamaLocal = provider === "ollama-local";
const isCookie = authType === "cookie";
const isXaiApiKey = provider === "xai" && !isCookie;
const credentialLabel = isCookie ? "Cookie Value" : "API Key";
const credentialPlaceholder = isCookie
? (provider === "grok-web" ? "sso=xxxxx... or just the raw value" : "eyJhbGciOi...")
: "";
: (isXaiApiKey ? "xai-..." : "");
const isAzure = provider === "azure";
const isCloudflareAi = provider === "cloudflare-ai";
@@ -228,6 +229,11 @@ export default function AddApiKeyModal({ isOpen, provider, providerName, isCompa
</div>
</div>
)}
{isXaiApiKey && (
<p className="text-xs text-text-muted">
Use a direct xAI API key from console.x.ai. This is separate from Grok Build OAuth.
</p>
)}
{isCookie && authHint && (
<p className="text-xs text-text-muted">
{authHint}

View File

@@ -65,10 +65,15 @@ export default function ConnectionRow({ connection, proxyPools, isOAuth, isFirst
}
};
const rowAuthType = connection.authType || (isOAuth ? "oauth" : "apikey");
const isOAuthConnection = rowAuthType === "oauth";
const isCookieConnection = rowAuthType === "cookie";
const authIcon = isCookieConnection ? "cookie" : isOAuthConnection ? "lock" : "key";
const authLabel = isOAuthConnection ? "OAuth" : isCookieConnection ? "Cookie" : "API Key";
const isEmail = (v) => typeof v === "string" && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);
const displayName = isOAuth
const displayName = isOAuthConnection
? (isEmail(connection.email) ? connection.email : (isEmail(connection.name) ? connection.name : (connection.name || connection.email || connection.displayName || "OAuth Account")))
: connection.name;
: (connection.name || connection.email || connection.displayName || "API Key");
// Use useState + useEffect for impure Date.now() to avoid calling during render
const [isCooldown, setIsCooldown] = useState(false);
@@ -130,7 +135,7 @@ export default function ConnectionRow({ connection, proxyPools, isOAuth, isFirst
</button>
</div>
<span className="material-symbols-outlined shrink-0 text-base text-text-muted">
{isOAuth ? "lock" : "key"}
{authIcon}
</span>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{displayName}</p>
@@ -138,6 +143,9 @@ export default function ConnectionRow({ connection, proxyPools, isOAuth, isFirst
<Badge variant={getStatusVariant()} size="sm" dot>
{connection.isActive === false ? "disabled" : (effectiveStatus || "Unknown")}
</Badge>
<Badge variant="default" size="sm">
{authLabel}
</Badge>
{hasAnyProxy && (
<Badge variant={proxyBadgeVariant} size="sm">
Proxy
@@ -259,4 +267,3 @@ ConnectionRow.propTypes = {
onEdit: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
};

View File

@@ -54,7 +54,11 @@ export default function ProviderDetailPage() {
const AG_RISK_STORAGE_KEY = "ag_risk_confirmed";
const triggerAddConnection = () => {
const openOAuthConnection = () => {
setShowOAuthModal(true);
};
const triggerOAuthConnection = () => {
if (providerId === "antigravity" && typeof window !== "undefined") {
const confirmed = window.localStorage.getItem(AG_RISK_STORAGE_KEY) === "true";
if (!confirmed) {
@@ -63,24 +67,36 @@ export default function ProviderDetailPage() {
}
}
if (isOAuth) {
setShowOAuthModal(true);
openOAuthConnection();
return;
}
setAddConnectionError("");
setShowAddApiKeyModal(true);
};
const triggerApiKeyConnection = () => {
setAddConnectionError("");
setShowAddApiKeyModal(true);
};
const triggerAddConnection = () => {
if (isOAuth) {
triggerOAuthConnection();
return;
}
triggerApiKeyConnection();
};
const handleAgRiskConfirm = () => {
if (typeof window !== "undefined") {
window.localStorage.setItem(AG_RISK_STORAGE_KEY, "true");
}
setShowAgRiskModal(false);
if (isOAuth) {
setShowOAuthModal(true);
openOAuthConnection();
return;
}
setAddConnectionError("");
setShowAddApiKeyModal(true);
triggerApiKeyConnection();
};
const providerInfo = providerNode
@@ -94,7 +110,9 @@ export default function ProviderDetailPage() {
type: providerNode.type,
}
: (OAUTH_PROVIDERS[providerId] || APIKEY_PROVIDERS[providerId] || FREE_PROVIDERS[providerId] || FREE_TIER_PROVIDERS[providerId] || WEB_COOKIE_PROVIDERS[providerId]);
const isOAuth = !!OAUTH_PROVIDERS[providerId] || !!FREE_PROVIDERS[providerId];
const authModes = providerInfo?.authModes || [];
const isOAuth = !!OAUTH_PROVIDERS[providerId] || !!FREE_PROVIDERS[providerId] || authModes.includes("oauth");
const supportsApiKeyAuth = !!APIKEY_PROVIDERS[providerId] || authModes.includes("apikey");
const isFreeNoAuth = !!FREE_PROVIDERS[providerId]?.noAuth;
const models = getModelsByProviderId(providerId);
const providerAlias = getProviderAlias(providerId);
@@ -102,6 +120,9 @@ export default function ProviderDetailPage() {
const isOpenAICompatible = isOpenAICompatibleProvider(providerId);
const isAnthropicCompatible = isAnthropicCompatibleProvider(providerId);
const isCompatible = isOpenAICompatible || isAnthropicCompatible;
const hasDualAuthModes = !isCompatible && isOAuth && supportsApiKeyAuth;
const oauthConnectionLabel = providerId === "xai" ? "Grok Build OAuth" : "OAuth";
const apiKeyConnectionLabel = providerId === "xai" ? "xAI API Key" : "API Key";
const thinkingConfig = AI_PROVIDERS[providerId]?.thinkingConfig || THINKING_CONFIG.extended;
const providerStorageAlias = isCompatible ? providerId : providerAlias;
@@ -1087,21 +1108,41 @@ export default function ProviderDetailPage() {
<div className="inline-flex items-center justify-center w-9 h-9 rounded-full bg-primary/10 text-primary shrink-0">
<span className="material-symbols-outlined text-[18px]">{isOAuth ? "lock" : "key"}</span>
</div>
<p className="text-sm text-text-muted">No connections yet</p>
<div className="min-w-0">
<p className="text-sm text-text-muted">No connections yet</p>
{hasDualAuthModes && (
<p className="text-xs text-text-muted">
Choose {oauthConnectionLabel} or {apiKeyConnectionLabel}.
</p>
)}
</div>
</div>
<div className="flex gap-2">
{!isCompatible && providerId === "iflow" && (
<Button size="sm" icon="cookie" variant="secondary" onClick={() => setShowIFlowCookieModal(true)}>
Cookie
</Button>
{hasDualAuthModes ? (
<>
<Button size="sm" icon="lock" variant="secondary" onClick={triggerOAuthConnection}>
{oauthConnectionLabel}
</Button>
<Button size="sm" icon="key" onClick={triggerApiKeyConnection}>
{apiKeyConnectionLabel}
</Button>
</>
) : (
<>
{!isCompatible && providerId === "iflow" && (
<Button size="sm" icon="cookie" variant="secondary" onClick={() => setShowIFlowCookieModal(true)}>
Cookie
</Button>
)}
<Button
size="sm"
icon="add"
onClick={triggerAddConnection}
>
{isCompatible ? "Add API Key" : (providerId === "iflow" ? "OAuth" : "Add Connection")}
</Button>
</>
)}
<Button
size="sm"
icon="add"
onClick={triggerAddConnection}
>
{isCompatible ? "Add API Key" : (providerId === "iflow" ? "OAuth" : "Add Connection")}
</Button>
</div>
</div>
) : (
@@ -1121,14 +1162,36 @@ export default function ProviderDetailPage() {
Cookie
</Button>
)}
<Button
size="sm"
icon="add"
onClick={triggerAddConnection}
className="w-full sm:w-auto"
>
Add
</Button>
{hasDualAuthModes ? (
<>
<Button
size="sm"
icon="lock"
variant="secondary"
onClick={triggerOAuthConnection}
className="w-full sm:w-auto"
>
{oauthConnectionLabel}
</Button>
<Button
size="sm"
icon="key"
onClick={triggerApiKeyConnection}
className="w-full sm:w-auto"
>
{apiKeyConnectionLabel}
</Button>
</>
) : (
<Button
size="sm"
icon="add"
onClick={triggerAddConnection}
className="w-full sm:w-auto"
>
Add
</Button>
)}
</div>
)}
</>

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);