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

6.3 KB
Raw Blame
import { NextResponse } from "next/server";
import {
  getApiKeys,
  getApiKeysCount,
  createApiKey,
  updateApiKeyPermissions,
} from "@/lib/db/apiKeys";
import { isCloudEnabled } from "@/lib/db/settings";
import { getConsistentMachineId } from "@/shared/utils/machineId";
import { syncToCloud } from "@/lib/cloudSync";
import { createKeySchema } from "@/shared/validation/schemas";
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
import { isApiKeyRevealEnabled, maskStoredApiKey } from "@/lib/apiKeyExposure";
import {
  requireCredentialForManagementScopedKey,
  requireManagementAuth,
} from "@/lib/api/requireManagementAuth";
import { normalizeSelfServiceScopesForCreate } from "@/shared/constants/selfServiceScopes";
import * as log from "@/sse/utils/logger";

function parsePagination(request: Request) {
  const url = new URL(request.url);
  const limitValue = url.searchParams.get("limit");
  const offsetValue = url.searchParams.get("offset");

  const parsedLimit = limitValue ? Number.parseInt(limitValue, 10) : undefined;
  const parsedOffset = offsetValue ? Number.parseInt(offsetValue, 10) : 0;

  const limit =
    Number.isInteger(parsedLimit) && parsedLimit && parsedLimit > 0 ? parsedLimit : null;
  const offset = Number.isInteger(parsedOffset) && parsedOffset > 0 ? parsedOffset : 0;

  return { limit, offset };
}

/**
 * The permission flags a create request sets on top of the defaults, or `null` when it sets none
 * (the key then keeps the defaults and no follow-up update runs).
 */
function createPermissionOverrides(data: {
  noLog?: boolean;
  allowUsageCommand?: boolean;
  usageLimitEnabled?: boolean;
  dailyUsageLimitUsd?: number | null;
  weeklyUsageLimitUsd?: number | null;
  chaosModeEnabled?: boolean;
}) {
  const overrides = {
    ...(data.noLog === true && { noLog: true }),
    ...(data.allowUsageCommand === true && { allowUsageCommand: true }),
    ...(data.usageLimitEnabled === true && { usageLimitEnabled: true }),
    ...(data.dailyUsageLimitUsd !== undefined && { dailyUsageLimitUsd: data.dailyUsageLimitUsd }),
    ...(data.weeklyUsageLimitUsd !== undefined && {
      weeklyUsageLimitUsd: data.weeklyUsageLimitUsd,
    }),
    ...(data.chaosModeEnabled === true && { chaosModeEnabled: true }),
  };
  return Object.keys(overrides).length > 0 ? overrides : null;
}

// GET /api/keys - List API keys
export async function GET(request: Request) {
  const authError = await requireManagementAuth(request);
  if (authError) return authError;

  try {
    const { limit, offset } = parsePagination(request);
    const dbLimit = limit ?? undefined;
    const total = getApiKeysCount();
    const keys = await getApiKeys(dbLimit, offset);
    const maskedKeys = keys.map((k) => ({
      ...k,
      key: maskStoredApiKey(k.key),
    }));

    return NextResponse.json({
      keys: maskedKeys,
      total,
      allowKeyReveal: isApiKeyRevealEnabled(),
    });
  } catch (error) {
    log.error("keys", "Error fetching keys", error);
    return NextResponse.json({ error: "Failed to fetch keys" }, { status: 500 });
  }
}

// POST /api/keys - Create new API key
export async function POST(request) {
  const authError = await requireManagementAuth(request);
  if (authError) return authError;

  try {
    const body = await request.json();

    // Zod validation
    const validation = validateBody(createKeySchema, body);
    if (isValidationFailure(validation)) {
      return NextResponse.json({ error: validation.error }, { status: 400 });
    }
    const {
      name,
      modelAccessMode,
      allowedModels,
      allowedCombos,
      noLog,
      scopes,
      allowedConnections,
      allowUsageCommand,
      usageLimitEnabled,
      dailyUsageLimitUsd,
      weeklyUsageLimitUsd,
      chaosModeEnabled,
      expiresAt,
    } = validation.data;

    const normalizedScopes = normalizeSelfServiceScopesForCreate(scopes);
    const scopeAuthError = await requireCredentialForManagementScopedKey(request, normalizedScopes);
    if (scopeAuthError) return scopeAuthError;

    // Always get machineId from server
    const machineId = await getConsistentMachineId();
    const apiKey = await createApiKey(name, machineId, normalizedScopes, {
      modelAccessMode,
      allowedModels,
      allowedCombos,
      allowedConnections,
      expiresAt,
    });
    const permissionOverrides = createPermissionOverrides(validation.data);
    if (permissionOverrides) await updateApiKeyPermissions(apiKey.id, permissionOverrides);

    // Auto sync to Cloud if enabled — fire-and-forget. Cloud sync is a
    // background side-effect, not part of the key-creation contract, and it
    // performs an outbound network call. Awaiting it here blocked the HTTP
    // response on a slow/unreachable Cloud endpoint (e.g. a fresh/offline
    // install with a misconfigured or unreachable CLOUD_URL): the request
    // would hang until the fetch settled or timed out (#6570). Errors inside
    // syncKeysToCloudIfEnabled() are already caught and logged internally, so
    // this is safe to leave unawaited.
    void syncKeysToCloudIfEnabled();

    return NextResponse.json(
      {
        key: apiKey.key,
        name: apiKey.name,
        id: apiKey.id,
        machineId: apiKey.machineId,
        modelAccessMode: apiKey.modelAccessMode,
        allowedModels: apiKey.allowedModels,
        allowedCombos: apiKey.allowedCombos,
        allowedConnections: apiKey.allowedConnections,
        noLog: noLog === true,
        allowUsageCommand: allowUsageCommand === true,
        usageLimitEnabled: usageLimitEnabled === true,
        dailyUsageLimitUsd: dailyUsageLimitUsd ?? null,
        weeklyUsageLimitUsd: weeklyUsageLimitUsd ?? null,
        chaosModeEnabled: chaosModeEnabled === true,
        expiresAt: expiresAt ?? null,
        streamDefaultMode: "legacy",
        compressionEnabled: true,
        cacheDefaultMode: "legacy",
      },
      { status: 201 }
    );
  } catch (error) {
    log.error("keys", "Error creating key", error);
    return NextResponse.json({ error: "Failed to create key" }, { status: 500 });
  }
}

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

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