9router/src/app/api/oauth/[provider]/[action]/route.js

344 lines
12 KiB
JavaScript
Raw Normal View History

2026-01-04 21:58:59 -05:00
import { NextResponse } from "next/server";
import {
getProvider,
generateAuthData,
exchangeTokens,
requestDeviceCode,
pollForToken
} from "@/lib/oauth/providers";
import { createProviderConnection } from "@/models";
import {
startCodexProxy,
stopCodexProxy,
registerCodexSession,
getCodexSessionStatus,
clearCodexSession,
startXaiProxy,
stopXaiProxy,
registerXaiSession,
getXaiSessionStatus,
clearXaiSession,
} from "@/lib/oauth/utils/server";
2026-01-04 21:58:59 -05:00
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;
}
}
2026-01-04 21:58:59 -05:00
/**
* Dynamic OAuth API Route
* Handles: authorize, exchange, device-code, poll
*/
// GET /api/oauth/[provider]/authorize - Generate auth URL
// GET /api/oauth/[provider]/device-code - Request device code (for device_code flow)
export async function GET(request, { params }) {
try {
const { provider, action } = await params;
const { searchParams } = new URL(request.url);
if (action === "authorize") {
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"]);
const meta = {};
searchParams.forEach((value, key) => { if (!reservedParams.has(key)) meta[key] = value; });
const authData = await generateAuthData(provider, redirectUri, Object.keys(meta).length ? meta : undefined);
2026-01-04 21:58:59 -05:00
return NextResponse.json(authData);
}
if (action === "start-proxy") {
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 });
}
const state = searchParams.get("state");
const codeVerifier = searchParams.get("code_verifier");
const redirectUri = searchParams.get("redirect_uri");
const result = provider === "xai"
? await startXaiProxy(Number(appPort))
: await startCodexProxy(Number(appPort));
let serverSide = false;
if (result.success && state && codeVerifier && redirectUri) {
serverSide = provider === "xai"
? registerXaiSession({ state, codeVerifier, redirectUri })
: registerCodexSession({ state, codeVerifier, redirectUri });
}
return NextResponse.json({ ...result, serverSide });
}
if (action === "poll-status") {
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 = provider === "xai" ? getXaiSessionStatus(state) : getCodexSessionStatus(state);
if (!session) return NextResponse.json({ status: "unknown" });
if (session.status === "done" || session.status === "error") {
const payload = { ...session };
if (provider === "xai") clearXaiSession(state);
else clearCodexSession(state);
return NextResponse.json(payload);
}
return NextResponse.json({ status: session.status });
}
if (action === "stop-proxy") {
if (!["codex", "xai"].includes(provider)) {
return NextResponse.json({ error: "Proxy only supported for codex/xai" }, { status: 400 });
}
if (provider === "xai") stopXaiProxy();
else stopCodexProxy();
return NextResponse.json({ success: true });
}
2026-01-04 21:58:59 -05:00
if (action === "device-code") {
const providerData = getProvider(provider);
if (providerData.flowType !== "device_code") {
return NextResponse.json({ error: "Provider does not support device code flow" }, { status: 400 });
}
const authData = await generateAuthData(provider, null);
const startUrl = searchParams.get("start_url");
const region = searchParams.get("region");
const authMethod = searchParams.get("auth_method");
const deviceOptions = provider === "kiro"
? {
...(startUrl ? { startUrl } : {}),
...(region ? { region } : {}),
...(authMethod ? { authMethod } : {}),
}
: undefined;
2026-01-04 21:58:59 -05:00
2026-02-20 05:05:46 -05:00
// Providers that don't use PKCE for device code
const noPkceDeviceProviders = ["github", "kiro", "kimi-coding", "kilocode", "codebuddy-cn", "qoder"];
2026-01-04 21:58:59 -05:00
let deviceData;
2026-02-20 05:05:46 -05:00
if (noPkceDeviceProviders.includes(provider)) {
deviceData = await requestDeviceCode(provider, undefined, deviceOptions);
2026-01-04 21:58:59 -05:00
} else {
2026-02-20 05:05:46 -05:00
// Qwen and other PKCE providers
deviceData = await requestDeviceCode(provider, authData.codeChallenge, deviceOptions);
2026-01-04 21:58:59 -05:00
}
return NextResponse.json({
...deviceData,
// Prefer the verifier the provider's requestDeviceCode generated for
// itself (qoder rolls its own PKCE pair); fall back to the generic one.
codeVerifier: deviceData.codeVerifier || authData.codeVerifier,
2026-01-04 21:58:59 -05:00
});
}
return NextResponse.json({ error: "Unknown action" }, { status: 400 });
} catch (error) {
console.log("OAuth GET error:", error);
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
// POST /api/oauth/[provider]/exchange - Exchange code for tokens and save
// POST /api/oauth/[provider]/poll - Poll for token (device_code flow)
export async function POST(request, { params }) {
try {
const { provider, action } = await params;
2026-02-22 09:44:11 -05:00
let body;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Invalid or empty request body" }, { status: 400 });
}
2026-01-04 21:58:59 -05:00
if (action === "exchange") {
const { code, redirectUri, codeVerifier, state, meta } = body;
2026-01-04 21:58:59 -05:00
Squashed commit of the following: commit 6561679f5c396bb07f5f7ba5bc5ec75e81c803a4 Author: OpenClaw Patch <patch@openclaw.local> Date: Tue May 19 16:26:01 2026 -0700 fix: never dedup access_token connections Access tokens should always create new entries. User decides which to keep (refresh-based OAuth vs no-expiry website token) and removes the other manually. commit d773451657999a2965ca4a094a7f0b7a54066693 Author: OpenClaw Patch <patch@openclaw.local> Date: Tue May 19 16:24:30 2026 -0700 fix: support ChatGPT website token format (account_id, plan_type) ChatGPT website access tokens use top-level 'account_id' and 'plan_type' fields, while OAuth id_tokens use nested claims under 'https://api.openai.com/auth'. Now both formats are handled, so workspace dedup works for website tokens too. commit cb895a5f6be59c51267874f11567646fa1f43016 Author: OpenClaw Patch <patch@openclaw.local> Date: Tue May 19 16:12:56 2026 -0700 fix: detect JWT in manual callback URL field When user pastes a JWT access token (starts with eyJ) in the 'paste callback URL' input field, skip URL parsing and send it directly to the exchange endpoint as the code. Fixes 'Failed to construct URL: Invalid URL' error. commit 29650d4a6732e3cf0958c9963b53209e41c8281e Author: OpenClaw Patch <patch@openclaw.local> Date: Tue May 19 15:37:02 2026 -0700 feat: auto-detect access token in OAuth exchange When the exchange endpoint receives a JWT (starts with eyJ) instead of an OAuth authorization code, it detects this and creates an access_token connection directly — skipping the OAuth token exchange flow. This lets users paste a ChatGPT access token where the OAuth code would normally go, and have it work automatically. commit e8e7c5709a783abd0c45246a44de1cc6abdba100 Author: OpenClaw Patch <patch@openclaw.local> Date: Tue May 19 15:14:48 2026 -0700 feat: workspace-aware dedup + ChatGPT access token import 1. Dedup now checks email AND workspace (chatgptAccountId) - Same email in different workspaces = separate connections - Backward compatible: non-workspace providers still dedup by email 2. New authType 'access_token' for ChatGPT website tokens - POST /api/oauth/codex/import-token accepts raw access tokens - Extracts email, workspace, plan from JWT claims - Deduplicates by email+workspace like OAuth - No refresh token needed (avoids OAuth relogin issues)
2026-05-20 03:38:47 -04:00
// Detect if "code" is actually a raw JWT access token (starts with eyJ)
if (code && code.startsWith("eyJ") && code.includes(".")) {
const { extractCodexAccountInfo } = await import("@/lib/oauth/providers");
const info = extractCodexAccountInfo(code);
// Also decode JWT directly for ChatGPT website tokens which use
// top-level account_id/plan_type instead of nested openai auth claims
let directPayload = {};
try {
const b64 = code.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
directPayload = JSON.parse(Buffer.from(padded, "base64").toString("utf8"));
} catch {}
const accountId = info.chatgptAccountId || directPayload.account_id;
const planType = info.chatgptPlanType || directPayload.plan_type;
const email = info.email || directPayload.email;
const providerSpecificData = { authMethod: "access_token" };
if (accountId) providerSpecificData.chatgptAccountId = accountId;
if (planType) providerSpecificData.chatgptPlanType = planType;
const connection = await createProviderConnection({
provider,
authType: "access_token",
accessToken: code,
email: email || null,
providerSpecificData,
testStatus: "active",
});
return NextResponse.json({
success: true,
connection: {
id: connection.id,
provider: connection.provider,
email: connection.email,
displayName: connection.displayName,
}
});
}
// Cline uses authorization_code without PKCE. Kimchi returns a browser token.
const noPkceExchangeProviders = ["cline", "kimchi"];
2026-02-20 05:05:46 -05:00
if (!code || !redirectUri || (!codeVerifier && !noPkceExchangeProviders.includes(provider))) {
2026-01-04 21:58:59 -05:00
return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
}
// Exchange code for tokens (meta carries provider-specific params, e.g. gitlab clientId/baseUrl)
const tokenData = await exchangeTokens(provider, code, redirectUri, codeVerifier, state, meta);
2026-01-04 21:58:59 -05:00
// Save to database
const connection = await createProviderConnection({
provider,
authType: "oauth",
...tokenData,
expiresAt: tokenData.expiresIn
? new Date(Date.now() + tokenData.expiresIn * 1000).toISOString()
: null,
testStatus: "active",
});
return NextResponse.json({
success: true,
connection: {
id: connection.id,
provider: connection.provider,
email: connection.email,
displayName: connection.displayName,
}
});
}
if (action === "poll") {
2026-01-15 06:29:47 -05:00
const { deviceCode, codeVerifier, extraData } = body;
2026-01-04 21:58:59 -05:00
if (!deviceCode) {
return NextResponse.json({ error: "Missing device code" }, { status: 400 });
}
2026-02-20 05:05:46 -05:00
// Providers that don't use PKCE for device code
const noPkceProviders = ["github", "kimi-coding", "kilocode", "codebuddy-cn"];
2026-01-04 21:58:59 -05:00
let result;
2026-02-20 05:05:46 -05:00
if (noPkceProviders.includes(provider)) {
2026-01-04 21:58:59 -05:00
result = await pollForToken(provider, deviceCode);
2026-01-15 06:29:47 -05:00
} else if (provider === "kiro") {
// Kiro needs extraData (clientId, clientSecret) from device code response
result = await pollForToken(provider, deviceCode, null, extraData);
} else if (provider === "qoder") {
// Qoder needs both the PKCE verifier (codeVerifier) and the machineId
// captured at device-code time (extraData._qoderMachineId) so
// mapTokens can persist it for COSY signing.
if (!codeVerifier) {
return NextResponse.json({ error: "Missing code verifier" }, { status: 400 });
}
result = await pollForToken(provider, deviceCode, codeVerifier, extraData);
2026-01-04 21:58:59 -05:00
} else {
2026-02-20 05:05:46 -05:00
// Qwen and other PKCE providers
2026-01-04 21:58:59 -05:00
if (!codeVerifier) {
return NextResponse.json({ error: "Missing code verifier" }, { status: 400 });
}
result = await pollForToken(provider, deviceCode, codeVerifier);
}
if (result.success) {
// Save to database
const connection = await createProviderConnection({
provider,
authType: "oauth",
...result.tokens,
expiresAt: result.tokens.expiresIn
? new Date(Date.now() + result.tokens.expiresIn * 1000).toISOString()
: null,
testStatus: "active",
});
return NextResponse.json({
success: true,
connection: {
id: connection.id,
provider: connection.provider,
}
});
}
2026-01-15 06:29:47 -05:00
// Still pending or error - don't create connection for pending states
const isPending = result.pending || result.error === "authorization_pending" || result.error === "slow_down";
2026-01-04 21:58:59 -05:00
return NextResponse.json({
success: false,
error: result.error,
errorDescription: result.errorDescription,
2026-01-15 06:29:47 -05:00
pending: isPending,
2026-01-04 21:58:59 -05:00
});
}
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 });
}
2026-01-04 21:58:59 -05:00
return NextResponse.json({ error: "Unknown action" }, { status: 400 });
} catch (error) {
console.log("OAuth POST error:", error);
return NextResponse.json({ error: error.message }, { status: 500 });
}
}