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

5.1 KB
Raw Blame
/**
 * Endpoint Category Definitions — API key endpoint restrictions.
 *
 * Each category maps a stable ID to a set of `/v1/` route prefixes.
 * The `resolveEndpointCategory()` function maps an incoming request path
 * to its category for policy enforcement.
 *
 * Empty `allowedEndpoints` on a key = all endpoints allowed (backward compatible).
 *
 * @module shared/constants/endpointCategories
 */

export interface EndpointCategory {
  id: string;
  label: string;
  description: string;
  prefixes: string[];
}

export const ENDPOINT_CATEGORIES: readonly EndpointCategory[] = [
  {
    id: "chat",
    label: "Chat / Messages",
    description: "Chat completions, text completions, messages, and responses",
    prefixes: ["/v1/chat/completions", "/v1/completions", "/v1/messages", "/v1/responses"],
  },
  {
    id: "search",
    label: "Web Search",
    description: "Web search and search analytics",
    prefixes: ["/v1/search"],
  },
  {
    id: "embeddings",
    label: "Embeddings",
    description: "Text embeddings generation",
    prefixes: ["/v1/embeddings", "/v1/multimodal-embeddings"],
  },
  {
    id: "images",
    label: "Images",
    description: "Image generation, editing and upscaling",
    prefixes: ["/v1/images"],
  },
  {
    id: "audio",
    label: "Audio / Speech",
    description: "Text-to-speech and speech-to-text",
    prefixes: ["/v1/audio"],
  },
  {
    id: "elevenlabs",
    label: "ElevenLabs Voice",
    description: "Native ElevenLabs speech-to-text, text-to-speech and voices",
    prefixes: ["/v1/speech-to-text", "/v1/text-to-speech", "/v1/voices"],
  },
  {
    id: "video",
    label: "Video",
    description: "Video generation",
    prefixes: ["/v1/videos"],
  },
  {
    id: "music",
    label: "Music",
    description: "Music generation",
    prefixes: ["/v1/music"],
  },
  {
    id: "rerank",
    label: "Rerank",
    description: "Document reranking",
    prefixes: ["/v1/rerank"],
  },
  {
    id: "models",
    label: "Models",
    description: "List available models (read-only)",
    prefixes: ["/v1/models"],
  },
  {
    id: "moderations",
    label: "Moderations",
    description: "Content moderation",
    prefixes: ["/v1/moderations"],
  },
  {
    id: "ocr",
    label: "OCR",
    description: "Optical character recognition",
    prefixes: ["/v1/ocr"],
  },
  {
    id: "batches",
    label: "Batch Processing",
    description: "Batch API operations",
    prefixes: ["/v1/batches"],
  },
  {
    id: "files",
    label: "Files",
    description: "File upload and management",
    prefixes: ["/v1/files"],
  },
  {
    id: "web-fetch",
    label: "Web Fetch",
    description: "Web page fetching",
    prefixes: ["/v1/web"],
  },
  {
    id: "agents",
    label: "Agents / A2A",
    description: "Agent-to-agent protocol and task execution",
    prefixes: ["/v1/agents"],
  },
] as const;

/**
 * Sorted longest-prefix-first so the most specific match wins
 * (e.g. `/v1/chat/completions` before `/v1/chat`).
 */
const SORTED_PREFIXES: readonly { prefix: string; categoryId: string }[] =
  ENDPOINT_CATEGORIES.flatMap((cat) =>
    cat.prefixes.map((prefix) => ({ prefix, categoryId: cat.id }))
  ).sort((a, b) => b.prefix.length - a.prefix.length);

/**
 * Map a request pathname to its endpoint category ID.
 * Returns `null` if the path doesn't match any category (e.g. management routes).
 */
export function resolveEndpointCategory(pathname: string): string | null {
  for (const { prefix, categoryId } of SORTED_PREFIXES) {
    if (pathname === prefix || pathname.startsWith(prefix + "/")) {
      return categoryId;
    }
  }
  return null;
}

/**
 * Short alias spellings `next.config.mjs` rewrites onto `/api/v1/…`, mapped to
 * the `/v1/…` path the category table speaks. Mirrors that rewrite table.
 */
const ENDPOINT_ALIAS_REWRITES: readonly { source: string; canonical: string }[] = [
  { source: "/chat/completions", canonical: "/v1/chat/completions" },
  { source: "/responses", canonical: "/v1/responses" },
  { source: "/models", canonical: "/v1/models" },
  // `/codex/:path*` folds its sub-path onto the Responses route, which still
  // resolves to the same category once the prefix is mapped.
  { source: "/codex", canonical: "/v1/responses" },
];

/**
 * Rewrite a client-facing alias path onto the canonical `/v1/…` form that
 * `resolveEndpointCategory()` understands.
 *
 * A route handler sees the client's original URL — Next never rewrites
 * `request.url` — so a request that arrived as `/chat/completions`, `/models`
 * or `/codex/…` matched no prefix at all and the endpoint check was skipped
 * entirely (#13685). The `/api/v1/…` (App Router) and doubled `/v1/v1/…`
 * spellings of the same endpoint fold onto `/v1/…` here as well. Anything
 * already canonical, or belonging to no category, comes back unchanged.
 */
export function resolveCanonicalEndpointPath(pathname: string): string {
  const path = pathname.replace(/^\/api(?=\/v1\/)/, "").replace(/^\/v1\/v1(?=\/|$)/, "/v1");

  for (const { source, canonical } of ENDPOINT_ALIAS_REWRITES) {
    if (path === source || path.startsWith(source + "/")) {
      return canonical + path.slice(source.length);
    }
  }

  return path;
}