-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
28 lines (23 loc) · 840 Bytes
/
auth.ts
File metadata and controls
28 lines (23 loc) · 840 Bytes
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
import { timingSafeEqual } from "node:crypto";
/**
* Validates the Authorization header from request headers against an expected secret.
* @param headers The request Headers object
* @param expectedSecret The expected secret from environment variables
* @returns true if authorized, false otherwise
*/
export function isAuthorized(headers: Headers, expectedSecret: string | undefined): boolean {
if (!expectedSecret) {
return false;
}
const authHeader = headers.get("Authorization");
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return false;
}
const token = authHeader.substring(7);
if (token.length !== expectedSecret.length) {
return false;
}
// we do that to prevent timing attacks
const encoder = new TextEncoder();
return timingSafeEqual(encoder.encode(token), encoder.encode(expectedSecret));
}