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

15.0 KB
Raw Blame
/**
 * POST /api/v1/relay/chat/completions
 *
 * Serverless Relay Proxy endpoint.
 * Authenticates via relay token, applies rate limits, then proxies
 * to the internal OmniRoute chat completions pipeline.
 */

import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";
import { stripSensitiveResponseHeaders } from "@omniroute/open-sse/utils/upstreamResponseHeaders";
import { handleChat } from "@/sse/handlers/chat";
import { withChatAdmission } from "@/shared/middleware/withChatAdmission";
import { createInjectionGuard } from "@/middleware/promptInjectionGuard";
import { getRelayTokenByHash, checkRateLimit, recordRelayUsage } from "@/lib/db/relayProxies";
import {
  buildErrorBody,
  parseUpstreamError,
  sanitizeErrorMessage,
} from "@omniroute/open-sse/utils/error";
import {
  checkIpRateLimit,
  extractToken,
  getClientIp,
  hashToken,
  sanitizeForensicHeader,
} from "./relaySecurity";
import {
  getBifrostRoutingConfig,
  getRoutingFallbackHeader,
  getRoutingFallbackReasonHeader,
  resolveRelayRoutingBackend,
  shouldTryBifrostForRequest,
  type BifrostRoutingConfig,
} from "./routingBackend";
import { getProviderPluginManifestEntryForModel } from "@omniroute/open-sse/config/providerPluginManifestRegistry.ts";
import { getProviderPluginManifestHeader } from "@omniroute/open-sse/config/providerPluginManifestUrl.ts";
import { finalizeReadableStream } from "./streamFinalizer";
import { stripStaleEncodingHeaders } from "@omniroute/open-sse/utils/upstreamResponseHeaders.ts";
import {
  clearBifrostFailure,
  getActiveBifrostCooldown,
  recordBifrostFailure,
} from "./bifrostCooldown";
import type { RelayToken } from "@/lib/db/relayProxies";

const JSON_CORS_HEADERS = { ...CORS_HEADERS, "Content-Type": "application/json" } as const;

// `logger: null` — this relay forwards to handleChat, where the guardrail registry
// re-evaluates the request with the pino logger (#11936 dedupe). The bifrost sibling
// route keeps the default logger: it skips handleChat entirely.
const injectionGuard = createInjectionGuard({ logger: null });

type RelayUsageStatus = "success" | "error";

function recordUsage(
  tokenId: string,
  request: Request,
  startTime: number,
  clientIp: string,
  userAgent: string | null,
  status: RelayUsageStatus,
  statusCode: number
) {
  recordRelayUsage(tokenId, {
    requestId: request.headers.get("x-request-id") || undefined,
    status,
    statusCode,
    latencyMs: Date.now() - startTime,
    clientIp,
    userAgent,
  });
}

async function forwardToBifrost(
  request: Request,
  body: unknown,
  token: RelayToken,
  config: BifrostRoutingConfig,
  backend: ReturnType<typeof resolveRelayRoutingBackend>,
  startTime: number,
  clientIp: string,
  userAgent: string | null
): Promise<Response> {
  const wantsStream =
    Boolean((body as { stream?: boolean } | null)?.stream) && config.streamingEnabled;
  const upstreamHeaders: Record<string, string> = {
    "Content-Type": "application/json",
    "x-relay-token-id": token.id,
    "x-relay-client-ip": clientIp,
    ...getProviderPluginManifestHeader(new URL(request.url).origin),
  };
  const requestId = request.headers.get("x-request-id");
  if (requestId) upstreamHeaders["x-request-id"] = requestId;
  if (config.apiKey) {
    upstreamHeaders.Authorization = `Bearer ${config.apiKey}`;
  }

  const ac = new AbortController();
  let timedOut = false;
  const tid = setTimeout(() => {
    timedOut = true;
    ac.abort();
  }, config.timeoutMs);

  try {
    const upstream = await fetch(`${config.baseUrl}/v1/chat/completions`, {
      method: "POST",
      headers: upstreamHeaders,
      body: JSON.stringify(body),
      signal: ac.signal,
    });

    // Same strip as the bifrost sibling: an echoed upstream credential or
    // set-cookie must not reach the relay-token holder (GHSA-9m72-44hg-w32g).
    const headers = stripSensitiveResponseHeaders(upstream.headers);
    headers.set("X-Routed-By", "bifrost");
    headers.set("X-Routing-Backend", "bifrost");
    headers.set("X-Relay-Token", token.tokenPrefix + "...");
    if (!wantsStream) {
      headers.set("Content-Type", upstream.headers.get("Content-Type") ?? "application/json");
    }

    // Issue #1: Bifrost (or the upstream behind it) may return plain text or HTML
    // on a non-OK status (e.g. 502 from a sidecar, "invalid character 'd'" style
    // proxy errors). Forwarding `upstream.body` raw leaks non-JSON into a client
    // that expects OpenAI-shaped JSON, producing client-side parse failures.
    // Normalize any non-OK response through parseUpstreamError + buildErrorBody so
    // the client always receives a valid JSON error. (Hard rule #12.)
    if (!upstream.ok) {
      const parsed = await parseUpstreamError(upstream, null);
      const errorBody = buildErrorBody(
        parsed.statusCode,
        sanitizeErrorMessage(parsed.message),
        parsed.responseBody
      );
      const errorHeaders = stripStaleEncodingHeaders(headers);
      errorHeaders.set("Content-Type", "application/json");
      if (parsed.retryAfterMs && parsed.retryAfterMs > 0) {
        errorHeaders.set("Retry-After", String(Math.ceil(parsed.retryAfterMs / 1000)));
      }
      clearTimeout(tid);
      recordUsage(token.id, request, startTime, clientIp, userAgent, "error", parsed.statusCode);
      return new Response(JSON.stringify(errorBody), {
        status: parsed.statusCode,
        headers: errorHeaders,
      });
    }

    if (wantsStream && upstream.body) {
      const stream = finalizeReadableStream(upstream.body, (error) => {
        clearTimeout(tid);
        const statusCode = timedOut ? 504 : upstream.status;
        if (error && backend === "auto") {
          recordBifrostFailure(
            config.baseUrl,
            timedOut
              ? `Bifrost sidecar stream timed out after ${config.timeoutMs}ms`
              : "bifrost-stream-error"
          );
        }
        recordUsage(
          token.id,
          request,
          startTime,
          clientIp,
          userAgent,
          error || statusCode >= 500 ? "error" : "success",
          statusCode
        );
      });

      return new Response(stream, {
        status: upstream.status,
        headers,
      });
    }

    clearTimeout(tid);
    recordUsage(
      token.id,
      request,
      startTime,
      clientIp,
      userAgent,
      // upstream.ok is guaranteed true here (the !upstream.ok branch above returns early).
      "success",
      upstream.status
    );

    return new Response(upstream.body, {
      status: upstream.status,
      headers,
    });
  } catch (error) {
    clearTimeout(tid);
    const isAbort = error instanceof Error && error.name === "AbortError";
    throw new Error(
      isAbort
        ? `Bifrost sidecar timed out after ${config.timeoutMs}ms`
        : `Bifrost sidecar unreachable: ${error instanceof Error ? error.message : String(error)}`
    );
  }
}

export async function OPTIONS() {
  return handleCorsOptions();
}

async function postHandler(request: Request) {
  const startTime = Date.now();
  const { forensic: clientIp, throttleKey } = getClientIp(request);
  const userAgent = sanitizeForensicHeader(request.headers.get("user-agent"));

  try {
    // 1. Authenticate
    const rawToken = extractToken(request);
    if (!rawToken) {
      return new Response(JSON.stringify(buildErrorBody(401, "Missing relay token")), {
        status: 401,
        headers: JSON_CORS_HEADERS,
      });
    }

    const tokenHash = hashToken(rawToken);
    const token = getRelayTokenByHash(tokenHash);
    if (!token) {
      recordRelayUsage("unknown", {
        requestId: request.headers.get("x-request-id") || undefined,
        status: "auth_failed",
        statusCode: 401,
        latencyMs: Date.now() - startTime,
        clientIp,
        userAgent,
      });
      return new Response(JSON.stringify(buildErrorBody(401, "Invalid relay token")), {
        status: 401,
        headers: JSON_CORS_HEADERS,
      });
    }

    // Check expiration
    if (token.expiresAt && Math.floor(Date.now() / 1000) > token.expiresAt) {
      return new Response(JSON.stringify(buildErrorBody(401, "Relay token expired")), {
        status: 401,
        headers: JSON_CORS_HEADERS,
      });
    }

    // 2a. Per-(token,IP) gate — bounds the blast radius of a leaked token.
    const ipCheck = checkIpRateLimit(token.id, throttleKey);
    if (!ipCheck.allowed) {
      recordRelayUsage(token.id, {
        requestId: request.headers.get("x-request-id") || undefined,
        status: "rate_limited",
        statusCode: 429,
        latencyMs: Date.now() - startTime,
        clientIp,
        userAgent,
      });
      return new Response(JSON.stringify(buildErrorBody(429, "Per-IP rate limit exceeded")), {
        status: 429,
        headers: {
          ...JSON_CORS_HEADERS,
          "Retry-After": String(ipCheck.resetIn),
          "X-RateLimit-Scope": "ip",
        },
      });
    }

    // 2b. Per-token rate limit check
    const rateCheck = checkRateLimit(token.id, token);
    if (!rateCheck.allowed) {
      recordRelayUsage(token.id, {
        requestId: request.headers.get("x-request-id") || undefined,
        status: "rate_limited",
        statusCode: 429,
        latencyMs: Date.now() - startTime,
        clientIp,
        userAgent,
      });
      return new Response(JSON.stringify(buildErrorBody(429, "Rate limit exceeded")), {
        status: 429,
        headers: {
          ...JSON_CORS_HEADERS,
          "Retry-After": String(rateCheck.resetIn),
          "X-RateLimit-Remaining": "0",
        },
      });
    }

    // 3. Clone request and forward to internal handler
    const cloned = request.clone();

    let parsedBody: unknown = null;

    // Prompt injection guard (same as main endpoint)
    try {
      parsedBody = await cloned.json().catch(() => null);
      if (parsedBody) {
        const { blocked, result } = injectionGuard(parsedBody);
        if (blocked) {
          recordRelayUsage(token.id, {
            requestId: request.headers.get("x-request-id") || undefined,
            status: "error",
            statusCode: 400,
            latencyMs: Date.now() - startTime,
            clientIp,
            userAgent,
          });
          const injectionBody = buildErrorBody(
            400,
            "Request blocked: potential prompt injection detected"
          );
          return new Response(
            JSON.stringify({
              ...injectionBody,
              detections: result.detections.length,
            }),
            { status: 400, headers: JSON_CORS_HEADERS }
          );
        }

        // Check allowed models
        const allowedModels: string[] = JSON.parse(token.allowedModels);
        if (allowedModels.length > 0 && !allowedModels.includes("*")) {
          const model = (parsedBody as { model?: string }).model || "";
          const allowed = allowedModels.some(
            (p) => model === p || (p.endsWith("*") && model.startsWith(p.slice(0, -1)))
          );
          if (!allowed) {
            // Echo the requested model string back through buildErrorBody so any
            // accidental path/stack leakage in `model` is sanitized.
            return new Response(
              JSON.stringify(
                buildErrorBody(403, `Model "${model}" not allowed by this relay token`)
              ),
              { status: 403, headers: JSON_CORS_HEADERS }
            );
          }
        }
      }
    } catch {
      // Continue even if guard fails
    }

    const backend = resolveRelayRoutingBackend();
    const bifrostConfig = getBifrostRoutingConfig();
    let bifrostFallbackReason: string | null = null;
    const bifrostDecision = shouldTryBifrostForRequest(
      backend,
      bifrostConfig,
      parsedBody,
      (model) => getProviderPluginManifestEntryForModel(model)?.sidecar ?? null
    );
    if (bifrostDecision.fallbackReason) {
      bifrostFallbackReason = bifrostDecision.fallbackReason;
    }
    if (bifrostDecision.tryBifrost) {
      const cooldown = backend === "auto" ? getActiveBifrostCooldown(bifrostConfig.baseUrl) : null;
      if (cooldown) {
        bifrostFallbackReason = `bifrost-cooldown; remaining=${cooldown.remainingMs}`;
      } else {
        try {
          const bifrostResponse = await forwardToBifrost(
            request,
            parsedBody,
            token,
            bifrostConfig,
            backend,
            startTime,
            clientIp,
            userAgent
          );
          clearBifrostFailure(bifrostConfig.baseUrl);
          return bifrostResponse;
        } catch (error) {
          const message = error instanceof Error ? error.message : String(error);
          if (backend === "bifrost") {
            recordUsage(token.id, request, startTime, clientIp, userAgent, "error", 502);
            return new Response(JSON.stringify(buildErrorBody(502, message)), {
              status: 502,
              headers: {
                ...JSON_CORS_HEADERS,
                "X-Bifrost-Fallback": "/api/v1/relay/chat/completions",
              },
            });
          }
          recordBifrostFailure(bifrostConfig.baseUrl, message);
          bifrostFallbackReason = "bifrost-error";
        }
      }
    }

    // 4. Proxy to internal handler
    const originalRequest = new Request(
      request.url.replace("/relay/chat/completions", "/chat/completions"),
      request
    );
    const response = await handleChat(originalRequest);

    // 5. Record usage (async, don't block response)
    const latencyMs = Date.now() - startTime;
    recordRelayUsage(token.id, {
      requestId: request.headers.get("x-request-id") || undefined,
      status: response.status < 500 ? "success" : "error",
      statusCode: response.status,
      latencyMs,
      clientIp,
      userAgent,
    });

    // Add relay headers
    const newHeaders = new Headers(response.headers);
    newHeaders.set("X-Relay-Token", token.tokenPrefix + "...");
    newHeaders.set("X-Routing-Backend", "ts");
    const routingFallback = getRoutingFallbackHeader(backend, bifrostConfig);
    if (routingFallback) {
      // #5526 helper gates emission (auto + enabled); #5519 dynamic cooldown/error
      // reason wins as the value when set, else falls back to the static "bifrost".
      newHeaders.set("X-Routing-Fallback", bifrostFallbackReason ?? routingFallback);
      // #6872: stable, machine-readable companion header — one of the 4 enum
      // reason codes, or unset when the legacy value has no specific reason.
      const fallbackReasonCode = getRoutingFallbackReasonHeader(bifrostFallbackReason);
      if (fallbackReasonCode) {
        newHeaders.set("X-Routing-Fallback-Reason", fallbackReasonCode);
      }
    }

    return new Response(response.body, {
      status: response.status,
      headers: newHeaders,
    });
  } catch (error) {
    // buildErrorBody() routes through sanitizeErrorMessage(), which strips
    // stack traces and absolute file paths. Hard rule #12.
    const message = error instanceof Error ? error.message : "Unknown error";
    return new Response(JSON.stringify(buildErrorBody(500, message)), {
      status: 500,
      headers: JSON_CORS_HEADERS,
    });
  }
}

export const POST = withChatAdmission(postHandler);