-
-
Notifications
You must be signed in to change notification settings - Fork 638
Expand file tree
/
Copy pathapi-key-auth.ts
More file actions
61 lines (50 loc) · 1.59 KB
/
api-key-auth.ts
File metadata and controls
61 lines (50 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import type { Context, MiddlewareHandler } from "hono"
import { HTTPException } from "hono/http-exception"
import { state } from "./state"
import { constantTimeEqual } from "./utils"
/**
* Extract API key from request headers
* Supports both OpenAI format (Authorization: Bearer token) and Anthropic format (x-api-key: token)
*/
function extractApiKey(c: Context): string | undefined {
// OpenAI format: Authorization header with Bearer prefix
const authHeader = c.req.header("authorization")
if (authHeader?.startsWith("Bearer ")) {
return authHeader.slice(7) // Remove 'Bearer ' prefix
}
// Anthropic format: x-api-key header
const anthropicKey = c.req.header("x-api-key")
if (anthropicKey) {
return anthropicKey
}
return undefined
}
/**
* API key authentication middleware
* Validates that the request contains a valid API key if API keys are configured
*/
export const apiKeyAuthMiddleware: MiddlewareHandler = async (c, next) => {
// If no API keys are configured, skip authentication
if (!state.apiKeys || state.apiKeys.length === 0) {
await next()
return
}
const providedKey = extractApiKey(c)
// If no API key is provided, return 401
if (!providedKey) {
throw new HTTPException(401, {
message: "Missing API key",
})
}
// Check if the provided key matches any of the configured keys
const isValidKey = state.apiKeys.some((key) =>
constantTimeEqual(key, providedKey),
)
if (!isValidKey) {
throw new HTTPException(401, {
message: "Invalid API key",
})
}
// Key is valid, continue with the request
await next()
}