feat: add API key authentication for AI proxy endpoints
- Add API_KEY config (env var) to all entry points - requireAuth helper checks Authorization: Bearer or x-api-key header - Auth applied to /v1/chat/completions, /v1/messages, /v1/models - When API_KEY is empty/unset, auth is disabled (backward compatible) - Update wrangler.toml with API_KEY variable documentation Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
2be57c0838
commit
c0a02279bd
@@ -39,6 +39,21 @@ const RELAY_TIMEOUT_MS = Number.parseInt(
|
||||
const SERVER_START_TIME = Date.now();
|
||||
const RELAY_VERSION = "1.0.0";
|
||||
|
||||
// ─── API Key Authentication ─────────────────────────────────────────────────────
|
||||
|
||||
const API_KEY = process.env.API_KEY ?? "";
|
||||
|
||||
function requireAuth(req: Request): Response | null {
|
||||
if (!API_KEY) return null;
|
||||
const header = req.headers.get("authorization") ?? req.headers.get("x-api-key") ?? "";
|
||||
const key = header.replace(/^Bearer\s+/i, "").trim();
|
||||
if (key === API_KEY) return null;
|
||||
return new Response(
|
||||
JSON.stringify({ error: { message: "Unauthorized", type: "auth_error" } }),
|
||||
{ status: 401, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" } },
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Middleware instances (singletons — persist across warm invocations) ─────────
|
||||
|
||||
const rateLimiter = createRateLimiter({
|
||||
@@ -400,6 +415,8 @@ export default {
|
||||
if (url.pathname === "/v1/chat/completions") {
|
||||
if (req.method === "OPTIONS") return createCorsPreflightResponse();
|
||||
if (req.method !== "POST") return new Response("Method Not Allowed", { status: 405 });
|
||||
const authErr = requireAuth(req);
|
||||
if (authErr) return authErr;
|
||||
try {
|
||||
const body = await req.json();
|
||||
return handleChatCompletion(body);
|
||||
@@ -415,6 +432,8 @@ export default {
|
||||
if (url.pathname === "/v1/messages") {
|
||||
if (req.method === "OPTIONS") return createCorsPreflightResponse();
|
||||
if (req.method !== "POST") return new Response("Method Not Allowed", { status: 405 });
|
||||
const authErr = requireAuth(req);
|
||||
if (authErr) return authErr;
|
||||
try {
|
||||
const body = await req.json();
|
||||
return handleAnthropicMessages(body);
|
||||
@@ -428,6 +447,8 @@ export default {
|
||||
|
||||
// Models list
|
||||
if (url.pathname === "/v1/models" && req.method === "GET") {
|
||||
const authErr = requireAuth(req);
|
||||
if (authErr) return authErr;
|
||||
const models = listModels().map((id) => ({
|
||||
id,
|
||||
object: "model",
|
||||
|
||||
Reference in New Issue
Block a user