Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

38.1 KB
Raw Blame
import { NextResponse } from "next/server";
import { timingSafeEqual } from "crypto";
import {
  getProvider,
  generateAuthData,
  exchangeTokens,
  finalizeTokens,
  requestDeviceCode,
  pollForToken,
  resolveBrowserOAuthRedirectUri,
} from "@/lib/oauth/providers";
import {
  persistOAuthConnection,
  buildOAuthConnectionCreatePayload,
  buildOAuthTokenUpdate,
  findExistingOAuthConnectionMatch,
} from "@/lib/oauth/connectionPersistence";
import { createDeviceFlowTicket, getDeviceFlowTicketStatus } from "@/lib/oauth/deviceFlowTickets";
import {
  createProviderConnection,
  updateProviderConnection,
  getProviderConnections,
  isCloudEnabled,
  resolveProxyForProvider,
} from "@/models";
import { getConsistentMachineId } from "@/shared/utils/machineId";
import { isValidGheUrl } from "@/shared/validation/providerSpecificData";
import { AWS_REGION_PATTERN } from "@/lib/oauth/constants/oauth";
import {
  antigravityDegradedProjectState,
  antigravityPersistStatus,
} from "@/lib/oauth/antigravityProjectGate";
import { syncToCloud } from "@/lib/cloudSync";
import { startLocalServer } from "@/lib/oauth/utils/server";
import { runWithProxyContextOrDirect } from "@omniroute/open-sse/utils/proxyFetch.ts";
import {
  jsonObjectSchema,
  oauthDeviceCompleteSchema,
  oauthExchangeSchema,
  oauthImportTokenSchema,
  oauthPollSchema,
} from "@/shared/validation/schemas";
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
import { GITLAB_DUO_OAUTH_SETUP_MESSAGE } from "@/shared/constants/gitlabDuoSetupMessage";
import { keychainImportOnlyGuard } from "./keychainImportOnly";
import { buildRemoteOAuthHint } from "./remoteOAuthHint";

// Persist one callback server per provider across Next.js HMR reloads.
if (!globalThis.__pkceCallbackStates) {
  globalThis.__pkceCallbackStates = {};
}

/** Providers that use the PKCE browser callback flow (like Codex). */
const PKCE_CALLBACK_PROVIDERS = new Set(["codex", "xai-oauth", "grok-cli", "openference"]);

/**
 * Providers whose device flow runs in the user's browser (auth.openai.com blocks
 * datacenter IPs but allows CORS), so the server never polls — it only persists
 * the final tokens via the `device-complete` action. See src/lib/oauth/codexDeviceFlow.ts.
 */
const BROWSER_DEVICE_FLOW_PROVIDERS = new Set(["codex"]);

/** Device Code providers whose token grant does not use a PKCE verifier. */
const NO_PKCE_DEVICE_CODE_PROVIDERS = new Set([
  "github",
  "kimi-coding",
  "kilocode",
  "codebuddy-cn",
  "codebuddy-intl",
  "workbuddy",
  "grok-cli",
  "ghe-copilot",
  "muse-code",
]);

/**
 * Providers whose PKCE flow has been retired but whose import-token path is
 * still active. Returning 410 Gone on `authorize` / `start-callback-server` /
 * `poll-callback` (instead of 400) tells callers the action is permanently
 * gone and points them at /import-token.
 */
const RETIRED_PKCE_PROVIDERS = new Set(["devin-desktop", "devin-cli"]);

/** Providers that allow direct import of a raw API token (no OAuth exchange). */
const IMPORT_TOKEN_PROVIDERS = new Set(["devin-desktop", "devin-cli", "grok-cli", "claude"]);

/**
 * #10143: re-importing a token onto an existing connection must keep its persisted
 * device identity, or the account presents to the upstream as a new device.
 */
function keepDeviceIdentity<T extends { providerSpecificData?: Record<string, unknown> }>(
  tokenData: T,
  existing: { providerSpecificData?: Record<string, unknown> | null } | undefined
): T {
  const cliUserID = existing?.providerSpecificData?.cliUserID;
  if (typeof cliUserID !== "string" || !tokenData.providerSpecificData) return tokenData;
  return { ...tokenData, providerSpecificData: { ...tokenData.providerSpecificData, cliUserID } };
}

/**
 * Constant-time string comparison to prevent timing-oracle attacks (CWE-208).
 * Handles null/undefined safely and different-length strings.
 */
function safeEqual(a: string | null | undefined, b: string | null | undefined): boolean {
  if (a == null || b == null) return a === b;
  const ba = Buffer.from(String(a));
  const bb = Buffer.from(String(b));
  if (ba.length !== bb.length) return false;
  return timingSafeEqual(ba, bb);
}

/**
 * Resolve the externally reachable base URL for public share links. Prefers the
 * configured public base URL; otherwise derives it from forwarded headers so the
 * link points at the host the operator actually serves (not an internal origin).
 */
function resolvePublicBaseUrl(request: Request): string {
  const env = process.env.NEXT_PUBLIC_BASE_URL || process.env.OMNIROUTE_PUBLIC_BASE_URL;
  if (env && env.trim()) return env.trim().replace(/\/+$/, "");
  const host = request.headers.get("x-forwarded-host") || request.headers.get("host");
  const proto = request.headers.get("x-forwarded-proto") || "https";
  if (host) return `${proto}://${host}`;
  return new URL(request.url).origin;
}

// /api/oauth/ is a PUBLIC prefix, so the pipeline leaves auth to this handler, and on a
// PUBLIC path isAuthenticated() takes any valid client API key. These actions start logins
// and create or overwrite provider connections, so they need the same management credential
// as the other connection routes (the import routes next to this one already do).
async function requireOAuthRouteAuth(request: Request) {
  return requireManagementAuth(request, { invalidApiKeyStatus: 401 });
}

/**
 * Dynamic OAuth API Route
 * Handles: authorize, exchange, device-code, poll, start-callback-server, poll-callback
 */

// 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: Request,
  { params }: { params: Promise<{ provider: string; action: string }> }
) {
  // Phase 1 hotfix (2026-05-29): retired PKCE flows return 410 Gone BEFORE auth.
  // The action permanently does not exist for these providers regardless of who
  // is asking — answering 401 first would mislead callers into thinking the
  // route is gated rather than gone. See spec
  try {
    const earlyParams = await params;
    if (
      RETIRED_PKCE_PROVIDERS.has(earlyParams.provider) &&
      (earlyParams.action === "authorize" ||
        earlyParams.action === "start-callback-server" ||
        earlyParams.action === "poll-callback")
    ) {
      return NextResponse.json(
        {
          error:
            `Browser OAuth disabled for ${earlyParams.provider} — use import-token via ` +
            `/api/oauth/${earlyParams.provider}/import-token. ` +
            `Paste an existing Devin API key from an authenticated Devin session. Key export availability and steps vary by Devin version and account.`,
        },
        { status: 410 }
      );
    }
    // Keychain-import-only providers (e.g. zed) have no OAuth flow — return a
    // clear 400 pointing at the Import button instead of a 500 (#6041).
    const kio = keychainImportOnlyGuard(earlyParams.provider, earlyParams.action);
    if (kio) return kio;
  } catch {
    /* fall through to normal handling */
  }

  const authResponse = await requireOAuthRouteAuth(request);
  if (authResponse) return authResponse;

  try {
    const { provider, action } = await params;
    const { searchParams } = new URL(request.url);

    if (action === "authorize") {
      const requestedRedirectUri =
        searchParams.get("redirect_uri") || "http://localhost:8080/callback";
      const redirectUri = resolveBrowserOAuthRedirectUri(provider, requestedRedirectUri);
      const authData = generateAuthData(provider, redirectUri);
      if (provider === "qoder" && !authData.authUrl) {
        return NextResponse.json({
          ...authData,
          supported: false,
          error:
            "Qoder browser OAuth is experimental and disabled by default. Configure QODER_OAUTH_* environment variables or use a Personal Access Token.",
        });
      }
      // #3861 / #8688: GitLab Duo needs a self-registered OAuth app. Without a client_id,
      // buildAuthUrl returns null — surface a clear setup message instead of a 500.
      // Same copy is shown in the OAuthModal setup step *before* authorize (#8688).
      if (provider === "gitlab-duo" && !authData.authUrl) {
        return NextResponse.json({
          ...authData,
          supported: false,
          error: GITLAB_DUO_OAUTH_SETUP_MESSAGE,
        });
      }
      return NextResponse.json(authData);
    }

    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 = generateAuthData(provider, null);
      const startUrl = searchParams.get("startUrl");
      const region = searchParams.get("region") || "us-east-1";
      const gheUrl = searchParams.get("gheUrl");
      if (gheUrl && !isValidGheUrl(gheUrl)) {
        return NextResponse.json({ error: "gheUrl must be a valid HTTPS URL" }, { status: 400 });
      }

      // Resolve proxy for this provider (provider-level → global → direct)
      const proxy = await resolveProxyForProvider(provider);

      // Request device code (through proxy if configured)
      let deviceData;
      if (
        NO_PKCE_DEVICE_CODE_PROVIDERS.has(provider) ||
        provider === "kiro" ||
        provider === "amazon-q"
      ) {
        // These providers don't use PKCE for device code.
        if (provider === "ghe-copilot" && gheUrl) {
          // GHE Copilot targets the enterprise host configured via gheUrl
          const providerOverrideConfig = {
            ...providerData.config,
            gheUrl,
          };
          deviceData = await runWithProxyContextOrDirect(proxy, () =>
            (requestDeviceCode as any)(provider, null, providerOverrideConfig)
          );
        } else if ((provider === "kiro" || provider === "amazon-q") && startUrl) {
          // GHSA-7x63: `region` is interpolated into the AWS OIDC endpoint URLs
          // below, which requestDeviceCode() then fetches. Validate it against the
          // canonical AWS region shape before it can steer the outbound host to an
          // attacker-chosen target (userinfo/fragment tricks → SSRF / metadata).
          if (!AWS_REGION_PATTERN.test(region)) {
            return NextResponse.json(
              { error: "region must be a valid AWS region (e.g. us-east-1)" },
              { status: 400 }
            );
          }
          const providerOverrideConfig = {
            ...providerData.config,
            startUrl,
            region,
            skipIssuerUrlForRegistration: true,
            registerClientUrl: `https://oidc.${region}.amazonaws.com/client/register`,
            deviceAuthUrl: `https://oidc.${region}.amazonaws.com/device_authorization`,
            tokenUrl: `https://oidc.${region}.amazonaws.com/token`,
            ssoOidcEndpoint: `https://oidc.${region}.amazonaws.com`,
          };

          deviceData = await runWithProxyContextOrDirect(proxy, () =>
            (requestDeviceCode as any)(provider, null, providerOverrideConfig)
          );
        } else {
          deviceData = await runWithProxyContextOrDirect(proxy, () =>
            (requestDeviceCode as any)(provider)
          );
        }
      } else {
        // Qwen and other providers use PKCE
        deviceData = await runWithProxyContextOrDirect(proxy, () =>
          requestDeviceCode(provider, authData.codeChallenge)
        );
      }

      return NextResponse.json({
        ...deviceData,
        codeVerifier: authData.codeVerifier,
      });
    }

    if (action === "start-callback-server") {
      return await handleStartCallbackServer(provider, searchParams, request);
    }

    if (action === "public-link-status") {
      // Dashboard polls this (authenticated) to learn when the external visitor
      // finished the device flow, so it can notify + refresh the connections.
      const token = searchParams.get("token");
      if (!token) {
        return NextResponse.json({ error: "Missing token" }, { status: 400 });
      }
      const { status, result } = getDeviceFlowTicketStatus(token);
      return NextResponse.json({ status, connection: result });
    }

    return NextResponse.json({ error: "Unknown action" }, { status: 400 });
  } catch (error) {
    console.error("OAuth GET error:", error);
    // Surface the SANITIZED upstream reason instead of a generic 500 that hides WHY the flow failed.
    // device-code providers (qwen → qwen.ai, codebuddy-cn → copilot.tencent.com) throw a descriptive
    // message ("Device code request failed: …", "CodeBuddy state request failed (403)") that was being
    // swallowed, so a geo-block / upstream outage looked identical to a real server bug in the UI.
    const detail = sanitizeErrorMessage(error instanceof Error ? error.message : String(error));
    return NextResponse.json({ error: detail || "Internal server error" }, { status: 500 });
  }
}

/**
 * Start a provider-configured PKCE callback server.
 * Returns the auth URL and stores codeVerifier for later exchange.
 */
async function handleStartCallbackServer(
  provider: string,
  searchParams: URLSearchParams,
  request?: Request
) {
  if (!PKCE_CALLBACK_PROVIDERS.has(provider)) {
    return NextResponse.json(
      { error: `Callback server not supported for provider: ${provider}` },
      { status: 400 }
    );
  }

  const callbackStates = globalThis.__pkceCallbackStates;

  // Clean up existing server if any
  if (callbackStates[provider]?.close) {
    try {
      callbackStates[provider].close();
    } catch (e) {
      /* ignore */
    }
  }
  delete callbackStates[provider];

  try {
    const providerData = getProvider(provider);
    const serverPort = providerData.fixedPort || 0;
    const callbackPath = providerData.callbackPath || "/callback";
    const callbackHost = providerData.callbackHost || "localhost";
    const { port, close } = await startLocalServer((params) => {
      if (callbackStates[provider]) {
        callbackStates[provider].callbackParams = params;
      }
    }, serverPort);

    const redirectUri = `http://${callbackHost}:${port}${callbackPath}`;
    const authData = generateAuthData(provider, redirectUri);

    callbackStates[provider] = {
      callbackParams: null,
      close,
      port,
      redirectUri,
      codeVerifier: authData.codeVerifier,
      state: authData.state,
      startedAt: Date.now(),
    };

    // Auto-cleanup after 5 minutes
    const startedAt = Date.now();
    setTimeout(() => {
      if (callbackStates[provider]?.startedAt === startedAt) {
        try {
          close();
        } catch (e) {
          /* ignore */
        }
        delete callbackStates[provider];
      }
    }, 300000);

    // #7523: the PKCE callback server listens on the SERVER's loopback
    // (localhost:PORT). When the operator drives the OAuth flow from a
    // *different* machine (OmniRoute running on a remote host/VPS), the
    // provider redirects the browser to the operator's own localhost:PORT,
    // not the server's — so the final confirmation screen hangs forever.
    // Detect a non-loopback Host and surface the reverse-tunnel instruction
    // (or steer to the paste/import flow) instead of a silent hang.
    const hostHeader =
      request?.headers.get("x-forwarded-host") || request?.headers.get("host") || null;
    const remoteHint = buildRemoteOAuthHint(hostHeader, port);

    return NextResponse.json({
      authUrl: authData.authUrl,
      codeVerifier: authData.codeVerifier,
      redirectUri,
      serverPort: port,
      ...remoteHint,
    });
  } catch (error) {
    console.error("OAuth start-callback-server error:", error);
    return NextResponse.json({ error: "Internal server error" }, { 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: Request,
  { params }: { params: Promise<{ provider: string; action: string }> }
) {
  // Phase 1 hotfix (2026-05-29): retired PKCE flows return 410 Gone BEFORE auth.
  // See GET handler comment.
  try {
    const earlyParams = await params;
    if (
      RETIRED_PKCE_PROVIDERS.has(earlyParams.provider) &&
      earlyParams.action === "poll-callback"
    ) {
      return NextResponse.json(
        {
          error:
            `Browser OAuth disabled for ${earlyParams.provider} — use import-token via ` +
            `/api/oauth/${earlyParams.provider}/import-token. ` +
            `Paste an existing Devin API key from an authenticated Devin session. Key export availability and steps vary by Devin version and account.`,
        },
        { status: 410 }
      );
    }
    // Keychain-import-only providers (e.g. zed) have no OAuth flow (#6041).
    const kio = keychainImportOnlyGuard(earlyParams.provider, earlyParams.action);
    if (kio) return kio;
  } catch {
    /* fall through to normal handling */
  }

  const authResponse = await requireOAuthRouteAuth(request);
  if (authResponse) return authResponse;

  try {
    const { provider, action } = await params;

    // Phase 1 hotfix (2026-05-29): retired PKCE flows return 410 Gone before
    // body parsing. Devin Desktop/CLI `poll-callback` is permanently retired;
    // use /import-token (handled later in this same handler) instead.
    if (RETIRED_PKCE_PROVIDERS.has(provider) && action === "poll-callback") {
      return NextResponse.json(
        {
          error:
            `Browser OAuth disabled for ${provider} — use import-token via ` +
            `/api/oauth/${provider}/import-token. ` +
            `Paste an existing Devin API key from an authenticated Devin session. Key export availability and steps vary by Devin version and account.`,
        },
        { status: 410 }
      );
    }

    let rawBody: any = {};
    try {
      rawBody = await request.json();
    } catch {
      if (action !== "poll-callback") {
        return NextResponse.json(
          {
            error: {
              message: "Invalid request",
              details: [{ field: "body", message: "Invalid JSON body" }],
            },
          },
          { status: 400 }
        );
      }
    }

    let body: any = rawBody;
    if (action === "exchange") {
      const validation = validateBody(oauthExchangeSchema, rawBody);
      if (isValidationFailure(validation)) {
        return NextResponse.json({ error: validation.error }, { status: 400 });
      }
      body = validation.data;
    } else if (action === "poll") {
      const validation = validateBody(oauthPollSchema, rawBody);
      if (isValidationFailure(validation)) {
        return NextResponse.json({ error: validation.error }, { status: 400 });
      }
      body = validation.data;
    } else if (action === "poll-callback") {
      const validation = validateBody(jsonObjectSchema, rawBody || {});
      if (isValidationFailure(validation)) {
        return NextResponse.json({ error: validation.error }, { status: 400 });
      }
      body = validation.data;
    } else if (action === "import-token") {
      const validation = validateBody(oauthImportTokenSchema, rawBody);
      if (isValidationFailure(validation)) {
        return NextResponse.json({ error: validation.error }, { status: 400 });
      }
      body = validation.data;
    } else if (action === "device-complete") {
      const validation = validateBody(oauthDeviceCompleteSchema, rawBody);
      if (isValidationFailure(validation)) {
        return NextResponse.json({ error: validation.error }, { status: 400 });
      }
      body = validation.data;
    }

    if (action === "exchange") {
      const { code, redirectUri, connectionId, codeVerifier, state } = body;
      const normalizedState = typeof state === "string" && state.length > 0 ? state : undefined;
      const providerData = getProvider(provider);

      // Capability check, not a bare flowType equality: grok-cli keeps flowType
      // "device_code" as its primary flow (#7358) while ALSO exposing a browser
      // PKCE login via supportsBrowserPkce (#7013 rework) — its exchange still
      // needs a codeVerifier when the browser method was used. Other providers
      // are untouched since only grok-cli sets supportsBrowserPkce.
      if (
        (providerData.flowType === "authorization_code_pkce" || providerData.supportsBrowserPkce) &&
        !codeVerifier
      ) {
        return NextResponse.json(
          {
            error: {
              message: "Invalid request",
              details: [
                {
                  field: "codeVerifier",
                  message: `Code verifier is required for ${provider} OAuth exchange`,
                },
              ],
            },
          },
          { status: 400 }
        );
      }

      // Resolve proxy for this provider (provider-level → global → direct)
      const proxy = await resolveProxyForProvider(provider);

      // Exchange code for tokens (through proxy if configured)
      const tokenData = await runWithProxyContextOrDirect(proxy, () =>
        exchangeTokens(provider, code, redirectUri, codeVerifier, normalizedState)
      );

      // #11284: when Cloud Code projectId discovery failed at connect time,
      // SAVE the connection but mark it degraded (maintainer direction on
      // #11284) — the refresh token stays stored and request-time bootstrap
      // self-heals the row once Google assigns a project.
      const degradedProject = antigravityDegradedProjectState(provider, tokenData);

      // Normalize: if name is missing, use email or displayName as fallback so accounts
      // always show a real label (e.g. [email protected]) instead of "Account #abc123"
      if (!tokenData.name && (tokenData.email || tokenData.displayName)) {
        tokenData.name = tokenData.email || tokenData.displayName;
      }

      // Upsert: update existing connection if same provider+email, else create new
      const expiresAt = tokenData.expiresIn
        ? new Date(Date.now() + tokenData.expiresIn * 1000).toISOString()
        : null;

      let connection: any;
      // Update-in-place when we can identify the account: by email, or by an
      // explicit connectionId from a re-auth (providers whose token response
      // has no email — kimi-coding — would otherwise DUPLICATE the connection
      // on every re-auth; #16984).
      if (tokenData.email || connectionId) {
        const existing = await getProviderConnections({ provider });
        // Codex accounts sharing an email require workspaceId/chatgptUserId
        // agreement to be treated as the same account (#7737).
        const match = findExistingOAuthConnectionMatch(existing, provider, tokenData, connectionId);
        const matchId = typeof match?.id === "string" ? match.id : null;
        if (matchId) {
          connection = await updateProviderConnection(matchId, {
            ...buildOAuthTokenUpdate(tokenData, expiresAt),
            ...antigravityPersistStatus(degradedProject),
            isActive: true,
          });
        }
      }
      if (!connection) {
        connection = await createProviderConnection(
          buildOAuthConnectionCreatePayload(provider, tokenData, expiresAt, degradedProject)
        );
      }

      // Auto sync to Cloud if enabled
      await syncToCloudIfEnabled();

      return NextResponse.json({
        success: true,
        ...(degradedProject ? { warning: degradedProject.warning } : {}),
        connection: {
          id: connection.id,
          provider: connection.provider,
          email: connection.email,
          displayName: connection.displayName,
        },
      });
    }

    if (action === "poll") {
      const { deviceCode, connectionId, codeVerifier, extraData } = body;

      // Resolve proxy for this provider (provider-level → global → direct)
      const proxy = await resolveProxyForProvider(provider);

      // Poll for token (through proxy if configured)
      let result;
      if (provider === "ghe-copilot") {
        // GHE Copilot needs gheUrl threaded through poll → postExchange
        const gheUrl =
          extraData && typeof extraData === "object" ? (extraData as any).gheUrl : undefined;
        if (typeof gheUrl === "string" && gheUrl && !isValidGheUrl(gheUrl)) {
          return NextResponse.json({ error: "gheUrl must be a valid HTTPS URL" }, { status: 400 });
        }
        result = await runWithProxyContextOrDirect(proxy, () =>
          (pollForToken as any)(provider, deviceCode, null, gheUrl ? { gheUrl } : undefined)
        );
      } else if (NO_PKCE_DEVICE_CODE_PROVIDERS.has(provider)) {
        // Non-PKCE device providers do not receive a code verifier.
        result = await runWithProxyContextOrDirect(proxy, () =>
          (pollForToken as any)(provider, deviceCode)
        );
      } else if (provider === "kiro" || provider === "amazon-q") {
        // Kiro needs extraData (clientId, clientSecret) from device code response
        result = await runWithProxyContextOrDirect(proxy, () =>
          (pollForToken as any)(provider, deviceCode, null, extraData)
        );
      } else {
        // Qwen and other providers use PKCE
        if (!codeVerifier) {
          return NextResponse.json({ error: "Missing code verifier" }, { status: 400 });
        }
        result = await runWithProxyContextOrDirect(proxy, () =>
          (pollForToken as any)(provider, deviceCode, codeVerifier)
        );
      }

      if (result.success) {
        // Normalize: if name is missing, use email as fallback display label
        if (!result.tokens.name && (result.tokens.email || result.tokens.displayName)) {
          result.tokens.name = result.tokens.email || result.tokens.displayName;
        }

        // Upsert: update existing connection if same provider+email, else create new
        const expiresAt = result.tokens.expiresIn
          ? new Date(Date.now() + result.tokens.expiresIn * 1000).toISOString()
          : null;

        let connection: any;
        // Email-less providers: honor an explicit connectionId re-auth signal
        // (#16984) — see the exchange branch comment above.
        if (result.tokens.email || connectionId) {
          const existing = await getProviderConnections({ provider });
          // Codex accounts sharing an email require workspaceId/chatgptUserId
          // agreement to be treated as the same account (#7737).
          const match = findExistingOAuthConnectionMatch(
            existing,
            provider,
            result.tokens,
            connectionId
          );
          const matchId = typeof match?.id === "string" ? match.id : null;
          if (matchId) {
            connection = await updateProviderConnection(matchId, {
              ...buildOAuthTokenUpdate(result.tokens, expiresAt),
              testStatus: "active",
              isActive: true,
            });
          }
        }
        if (!connection) {
          connection = await createProviderConnection(
            buildOAuthConnectionCreatePayload(provider, result.tokens, expiresAt)
          );
        }

        // Auto sync to Cloud if enabled
        await syncToCloudIfEnabled();

        return NextResponse.json({
          success: true,
          connection: {
            id: connection.id,
            provider: connection.provider,
          },
        });
      }

      // Still pending or error - don't create connection for pending states
      const isPending =
        result.pending || result.error === "authorization_pending" || result.error === "slow_down";

      return NextResponse.json({
        success: false,
        error: result.error,
        errorDescription: result.errorDescription,
        pending: isPending,
      });
    }

    if (action === "poll-callback") {
      const { connectionId } = body;

      // poll-callback is supported for all PKCE callback providers
      if (!PKCE_CALLBACK_PROVIDERS.has(provider)) {
        return NextResponse.json(
          {
            error: `poll-callback only supported for PKCE callback providers: ${[...PKCE_CALLBACK_PROVIDERS].join(", ")}`,
          },
          { status: 400 }
        );
      }

      const callbackStates = globalThis.__pkceCallbackStates;

      if (!callbackStates[provider]) {
        return NextResponse.json({
          success: false,
          error: "no_server",
          errorDescription: "Callback server not running",
        });
      }

      if (!callbackStates[provider].callbackParams) {
        return NextResponse.json({ success: false, pending: true });
      }

      // Callback received! Extract code and exchange for tokens
      const params = callbackStates[provider].callbackParams;
      const { redirectUri, codeVerifier, state, close } = callbackStates[provider];

      // Clean up server
      try {
        close();
      } catch (e) {
        /* ignore */
      }
      delete callbackStates[provider];

      if (params.error) {
        return NextResponse.json({
          success: false,
          error: params.error,
          errorDescription: params.error_description,
        });
      }

      if (!params.code) {
        return NextResponse.json({
          success: false,
          error: "no_code",
          errorDescription: "No authorization code received",
        });
      }

      if (!safeEqual(params.state, state)) {
        return NextResponse.json({
          success: false,
          error: "invalid_state",
          errorDescription: "OAuth state mismatch",
        });
      }

      try {
        // Resolve proxy for this provider
        const proxy = await resolveProxyForProvider(provider);

        // Exchange code for tokens (through proxy if configured)
        const tokenData = await runWithProxyContextOrDirect(proxy, () =>
          exchangeTokens(provider, params.code, redirectUri, codeVerifier, params.state)
        );

        // #11284: when Cloud Code projectId discovery failed at connect time,
        // SAVE the connection but mark it degraded (maintainer direction).
        const degradedProject = antigravityDegradedProjectState(provider, tokenData);

        // Normalize: if name is missing, use email as fallback display label
        if (!tokenData.name && (tokenData.email || tokenData.displayName)) {
          tokenData.name = tokenData.email || tokenData.displayName;
        }

        // Upsert: update existing connection if same provider+email, else create new
        const expiresAt = tokenData.expiresIn
          ? new Date(Date.now() + tokenData.expiresIn * 1000).toISOString()
          : null;

        let connection: any;
        // Email-less providers: honor an explicit connectionId re-auth signal
        // (#16984) — see the exchange branch comment above.
        if (tokenData.email || connectionId) {
          const existing = await getProviderConnections({ provider });
          // Codex accounts sharing an email require workspaceId/chatgptUserId
          // agreement to be treated as the same account (#7737).
          const match = findExistingOAuthConnectionMatch(
            existing,
            provider,
            tokenData,
            connectionId
          );
          const matchId = typeof match?.id === "string" ? match.id : null;
          if (matchId) {
            connection = await updateProviderConnection(matchId, {
              ...buildOAuthTokenUpdate(tokenData, expiresAt),
              ...antigravityPersistStatus(degradedProject),
              isActive: true,
            });
          }
        }
        if (!connection) {
          connection = await createProviderConnection(
            buildOAuthConnectionCreatePayload(provider, tokenData, expiresAt, degradedProject)
          );
        }

        await syncToCloudIfEnabled();

        return NextResponse.json({
          success: true,
          ...(degradedProject ? { warning: degradedProject.warning } : {}),
          connection: {
            id: connection.id,
            provider: connection.provider,
            email: connection.email,
            displayName: connection.displayName,
          },
        });
      } catch (exchangeErr: any) {
        console.error("OAuth exchange error:", exchangeErr);
        const detail = sanitizeErrorMessage(
          exchangeErr instanceof Error ? exchangeErr.message : String(exchangeErr)
        );
        return NextResponse.json(
          { success: false, error: detail || "Internal server error" },
          { status: 500 }
        );
      }
    }

    if (action === "import-token") {
      const { token, connectionId } = body;

      if (!IMPORT_TOKEN_PROVIDERS.has(provider)) {
        return NextResponse.json(
          {
            error: `import-token not supported for provider: ${provider}. Supported: ${[...IMPORT_TOKEN_PROVIDERS].join(", ")}`,
          },
          { status: 400 }
        );
      }

      try {
        // Map the raw token via the provider's mapTokens() — skips the HTTP exchange entirely.
        // Providers that must verify the token upstream first expose an async importToken().
        const providerData = getProvider(provider);
        const tokenData = providerData.importToken
          ? await providerData.importToken(token)
          : providerData.mapTokens({ accessToken: token });

        // Normalize: if name is missing, use email as fallback display label
        if (!tokenData.name && (tokenData.email || tokenData.displayName)) {
          tokenData.name = tokenData.email || tokenData.displayName;
        }

        const expiresAt = tokenData.expiresIn
          ? new Date(Date.now() + tokenData.expiresIn * 1000).toISOString()
          : null;

        // Tokens without an identity (e.g. a Claude setup-token) match on the token itself,
        // so re-pasting the same token updates its connection instead of duplicating it.
        let connection: any;
        const existing = await getProviderConnections({ provider });
        const match = existing.find((c: any) => {
          if (c.id && safeEqual(connectionId, c.id)) return true;
          if (c.authType !== "oauth") return false;
          return tokenData.email
            ? safeEqual(c.email, tokenData.email)
            : safeEqual(c.accessToken, tokenData.accessToken);
        });
        const matchId = typeof match?.id === "string" ? match.id : null;
        if (matchId) {
          connection = await updateProviderConnection(matchId, {
            ...buildOAuthTokenUpdate(keepDeviceIdentity(tokenData, match), expiresAt),
            testStatus: "active",
            isActive: true,
          });
        }
        if (!connection) {
          connection = await createProviderConnection(
            buildOAuthConnectionCreatePayload(provider, tokenData, expiresAt)
          );
        }

        await syncToCloudIfEnabled();

        return NextResponse.json({
          success: true,
          connection: {
            id: connection.id,
            provider: connection.provider,
            email: connection.email,
            displayName: connection.displayName,
          },
        });
      } catch (importErr: any) {
        return NextResponse.json(
          { success: false, error: sanitizeErrorMessage(importErr.message) || "Import failed" },
          { status: Number.isInteger(importErr?.status) ? importErr.status : 500 }
        );
      }
    }

    if (action === "public-link") {
      // Generate a single-use, short-lived public link so a third party can
      // complete the Codex device flow in their own browser (see Fase 6).
      if (!BROWSER_DEVICE_FLOW_PROVIDERS.has(provider)) {
        return NextResponse.json(
          {
            error: `public-link not supported for provider: ${provider}. Supported: ${[...BROWSER_DEVICE_FLOW_PROVIDERS].join(", ")}`,
          },
          { status: 400 }
        );
      }

      const connectionId =
        rawBody && typeof rawBody.connectionId === "string" ? rawBody.connectionId : undefined;
      const { token, expiresAt } = createDeviceFlowTicket(provider, connectionId);

      return NextResponse.json({
        url: `${resolvePublicBaseUrl(request)}/connect/codex/${token}`,
        token,
        expiresAt: new Date(expiresAt).toISOString(),
      });
    }

    if (action === "device-complete") {
      // The browser-driven Codex device flow already performed the device
      // authorization + token exchange against auth.openai.com (the server's
      // datacenter IP is blocked by Cloudflare, so it cannot). Here we only map
      // the final tokens and persist the connection — no HTTP exchange/poll.
      if (!BROWSER_DEVICE_FLOW_PROVIDERS.has(provider)) {
        return NextResponse.json(
          {
            error: `device-complete not supported for provider: ${provider}. Supported: ${[...BROWSER_DEVICE_FLOW_PROVIDERS].join(", ")}`,
          },
          { status: 400 }
        );
      }

      const {
        access_token: accessToken,
        refresh_token: refreshToken,
        id_token: idToken,
        expires_in: expiresIn,
        connectionId,
      } = body;

      let tokenData: any;
      try {
        tokenData = await finalizeTokens(provider, {
          access_token: accessToken,
          refresh_token: refreshToken,
          id_token: idToken,
          expires_in: expiresIn,
        });
      } catch (finalizeErr: any) {
        return NextResponse.json(
          {
            success: false,
            error: sanitizeErrorMessage(finalizeErr?.message) || "Failed to finalize tokens",
          },
          { status: 500 }
        );
      }

      const connection = await persistOAuthConnection(provider, tokenData, connectionId);

      return NextResponse.json({
        success: true,
        connection: {
          id: connection.id,
          provider: connection.provider,
          email: connection.email,
          displayName: connection.displayName,
        },
      });
    }

    return NextResponse.json({ error: "Unknown action" }, { status: 400 });
  } catch (error) {
    console.error("OAuth POST error:", error);
    const detail = sanitizeErrorMessage(error instanceof Error ? error.message : String(error));
    return NextResponse.json({ error: detail || "Internal server error" }, { status: 500 });
  }
}

/**
 * Sync to Cloud if enabled
 */
async function syncToCloudIfEnabled() {
  try {
    const cloudEnabled = await isCloudEnabled();
    if (!cloudEnabled) return;

    const machineId = await getConsistentMachineId();
    await syncToCloud(machineId);
  } catch (error) {
    console.log("Error syncing to cloud after OAuth:", error);
  }
}