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

7.1 KB
Raw Blame
import crypto from "node:crypto";
import { CLAUDE_CONFIG } from "../constants/oauth";
import { getClaudeCodeVersion } from "@omniroute/open-sse/executors/claudeIdentity.ts";
import { validateClaudeOAuthInline } from "@/lib/providers/validation/anthropicFormat";

const SETUP_TOKEN_PREFIX = "sk-ant-oat";

const BOOTSTRAP_FETCH_TIMEOUT_MS = 10_000;

// Best-effort: failure must not block OAuth — the access token is valid.
async function fetchClaudeBootstrap(accessToken) {
  const ctrl = new AbortController();
  const timer = setTimeout(() => ctrl.abort(), BOOTSTRAP_FETCH_TIMEOUT_MS);
  try {
    const res = await fetch("https://api.anthropic.com/api/claude_cli/bootstrap", {
      method: "GET",
      headers: {
        Authorization: `Bearer ${accessToken}`,
        Accept: "application/json",
        "User-Agent": `claude-cli/${getClaudeCodeVersion()} (external, cli)`,
        "anthropic-beta": "oauth-2025-04-20",
      },
      signal: ctrl.signal,
    });
    if (!res.ok) return null;
    const data = await res.json();
    const acct = data?.oauth_account;
    if (!acct || typeof acct !== "object") return null;
    return {
      account_uuid: acct.account_uuid || null,
      account_email: acct.account_email || null,
      organization_uuid: acct.organization_uuid || null,
      organization_name: acct.organization_name || null,
      organization_type: acct.organization_type || null,
      organization_rate_limit_tier: acct.organization_rate_limit_tier || null,
    };
  } catch {
    return null;
  } finally {
    clearTimeout(timer);
  }
}

function toRecord(value: unknown): Record<string, unknown> {
  return value && typeof value === "object" && !Array.isArray(value)
    ? (value as Record<string, unknown>)
    : {};
}

function firstNonEmptyString(...values: unknown[]): string | undefined {
  for (const value of values) {
    if (typeof value !== "string") {
      continue;
    }

    const trimmed = value.trim();
    if (trimmed) {
      return trimmed;
    }
  }

  return undefined;
}

function extractPlanFromPayload(payload: unknown): string | undefined {
  const data = toRecord(payload);
  const billing = toRecord(data.billing);

  return firstNonEmptyString(data.account_tier, data.plan, data.subscription_type, billing.plan);
}

function extractClaudePlan(tokens: unknown, extra: unknown): string | undefined {
  const extraData = toRecord(extra);

  return firstNonEmptyString(
    extractPlanFromPayload(tokens),
    extractPlanFromPayload(extraData.userInfo),
    extractPlanFromPayload(extra)
  );
}

function newProviderSpecificData(): Record<string, unknown> {
  return {
    // Generated once at provisioning; preserved across token refresh.
    cliUserID: crypto.randomBytes(32).toString("hex"),
    autoSync: true,
  };
}

class ClaudeSetupTokenError extends Error {
  readonly status = 400;
}

/**
 * `claude setup-token` mints a 1-year OAuth token scoped to `user:inference` only:
 * no refresh token, and bootstrap/profile answer 403, so there is no email or
 * account UUID to learn. A live one-token request is therefore the only proof
 * the token works, and it runs before anything is stored.
 */
async function importSetupToken(token: unknown) {
  const accessToken = typeof token === "string" ? token.trim() : "";
  if (!accessToken.startsWith(SETUP_TOKEN_PREFIX)) {
    throw new ClaudeSetupTokenError(
      `Expected a token from \`claude setup-token\` (starts with ${SETUP_TOKEN_PREFIX})`
    );
  }
  const check = await validateClaudeOAuthInline({ apiKey: accessToken, modelId: null });
  if (!check.valid) {
    throw new ClaudeSetupTokenError(
      `Could not verify this setup token with Anthropic (${check.error})`
    );
  }
  return {
    name: "Setup token",
    accessToken,
    refreshToken: null,
    expiresIn: null,
    providerSpecificData: newProviderSpecificData(),
  };
}

export const claude = {
  config: CLAUDE_CONFIG,
  flowType: "authorization_code_pkce",
  buildAuthUrl: (config, _redirectUri, state, codeChallenge) => {
    const params = new URLSearchParams({
      code: "true",
      client_id: config.clientId,
      response_type: "code",
      redirect_uri: config.redirectUri,
      scope: config.scopes.join(" "),
      code_challenge: codeChallenge,
      code_challenge_method: config.codeChallengeMethod,
      state: state,
      // prompt=login forces Anthropic IdP to RE-AUTHENTICATE the user on each
      // OAuth flow instead of silently reusing the browser session. Prevents
      // the "session takeover" that invalidates the previous account's
      // refresh_token family on the same client_id. Same pattern that unlocked
      // multi-account Codex — applied defensively here because Anthropic's
      // OAuth uses the same client_id across all accounts AND the user reports
      // Claude tokens expiring in multi-account scenarios.
      prompt: "login",
    });
    return `${config.authorizeUrl}?${params.toString()}`;
  },
  exchangeToken: async (config, code, _redirectUri, codeVerifier, state) => {
    let authCode = code;
    let codeState = "";
    if (authCode.includes("#")) {
      const parts = authCode.split("#");
      authCode = parts[0];
      codeState = parts[1] || "";
    }

    const response = await fetch(config.tokenUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        code: authCode,
        state: codeState || state,
        grant_type: "authorization_code",
        client_id: config.clientId,
        redirect_uri: config.redirectUri,
        code_verifier: codeVerifier,
      }),
    });

    if (!response.ok) {
      const error = await response.text();
      throw new Error(`Token exchange failed: ${error}`);
    }

    return await response.json();
  },
  // Runs after exchangeToken; result is passed as `extra` to mapTokens.
  postExchange: async (tokens) => {
    if (!tokens?.access_token) return null;
    return await fetchClaudeBootstrap(tokens.access_token);
  },
  importToken: importSetupToken,
  mapTokens: (tokens, extra) => {
    const plan = extractClaudePlan(tokens, extra);
    const bs = extra || {};
    const providerSpecificData: any = newProviderSpecificData();
    if (bs.account_uuid) providerSpecificData.accountUUID = bs.account_uuid;
    if (bs.organization_uuid) providerSpecificData.organizationUUID = bs.organization_uuid;
    if (bs.organization_name) providerSpecificData.organizationName = bs.organization_name;
    if (bs.organization_type) providerSpecificData.organizationType = bs.organization_type;
    if (bs.organization_rate_limit_tier)
      providerSpecificData.organizationRateLimitTier = bs.organization_rate_limit_tier;
    if (plan) providerSpecificData.plan = plan;

    const result: any = {
      accessToken: tokens.access_token,
      refreshToken: tokens.refresh_token,
      expiresIn: tokens.expires_in,
      scope: tokens.scope,
    };
    if (bs.account_email) {
      result.email = bs.account_email;
      result.displayName = bs.account_email;
    }
    if (Object.keys(providerSpecificData).length > 0) {
      result.providerSpecificData = providerSpecificData;
    }
    return result;
  },
};