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
|
export type ApiKeyValidationResult =
| {
valid: true;
userId: string;
apiKeyId: string;
}
| {
valid: false;
error: string;
};
export interface ApiKeyValidator {
validate(apiKey: string): Promise<ApiKeyValidationResult>;
}
export class EdgeFunctionApiKeyValidator implements ApiKeyValidator {
private supabaseUrl: string;
private supabaseAnonKey: string;
constructor(supabaseUrl: string, supabaseAnonKey: string) {
this.supabaseUrl = supabaseUrl;
this.supabaseAnonKey = supabaseAnonKey;
}
async validate(apiKey: string): Promise<ApiKeyValidationResult> {
try {
const response = await fetch(
`${this.supabaseUrl}/functions/v1/validate-api-key`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.supabaseAnonKey}`,
},
body: JSON.stringify({ apiKey }),
},
);
if (!response.ok) {
const errorData = (await response.json()) as { error?: string };
return { valid: false, error: errorData.error ?? "Validation failed" };
}
const data = (await response.json()) as {
userId: string;
apiKeyId: string;
};
return {
valid: true,
userId: data.userId,
apiKeyId: data.apiKeyId,
};
} catch {
return { valid: false, error: "Failed to validate API key" };
}
}
}
|