forked from Vero-protocol/vero-core-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrelayer-auth.ts
More file actions
54 lines (44 loc) · 1.32 KB
/
Copy pathrelayer-auth.ts
File metadata and controls
54 lines (44 loc) · 1.32 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
import type { IncomingMessage } from "http";
export interface RelayerAuthOptions {
apiKeys?: string[];
jwtSecret?: string;
}
export interface VerifyClientInfo {
origin: string;
req: IncomingMessage;
secure: boolean;
}
export type VerifyClientCallback = (result: boolean, code?: number, message?: string) => void;
export interface AuthResult {
allowed: boolean;
statusCode?: number;
message?: string;
}
function extractApiKey(req: IncomingMessage): string | null {
const authHeader = req.headers["authorization"];
if (authHeader) {
const parts = (Array.isArray(authHeader) ? authHeader[0] : authHeader).split(" ");
if (parts.length === 2 && parts[0].toLowerCase() === "bearer") {
return parts[1];
}
}
const apiKeyHeader = req.headers["x-api-key"];
if (apiKeyHeader) {
return Array.isArray(apiKeyHeader) ? apiKeyHeader[0] : apiKeyHeader;
}
return null;
}
export class RelayerAuth {
private readonly apiKeys: Set<string>;
constructor(options: RelayerAuthOptions = {}) {
this.apiKeys = new Set(options.apiKeys ?? []);
}
verifyClient(info: VerifyClientInfo, cb: VerifyClientCallback): void {
const key = extractApiKey(info.req);
if (key && this.apiKeys.has(key)) {
cb(true);
return;
}
cb(false, 401, "Unauthorized: missing or invalid API key");
}
}