-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Expand file tree
/
Copy pathapiKeyValidation.ts
More file actions
65 lines (57 loc) · 1.72 KB
/
apiKeyValidation.ts
File metadata and controls
65 lines (57 loc) · 1.72 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
62
63
64
65
/**
* Validates an Anthropic API key format
* @param apiKey The API key to validate
* @returns true if the API key is valid, false otherwise
*/
export function isValidAnthropicApiKey(
apiKey: string | null | undefined,
): boolean {
if (!apiKey || typeof apiKey !== "string") {
return false;
}
// Anthropic API keys must start with "sk-ant-" and have additional characters
return apiKey.startsWith("sk-ant-") && apiKey.length > "sk-ant-".length;
}
/**
* Validates an OpenAI API key format
* @param apiKey The API key to validate
* @returns true if the API key is valid, false otherwise
*/
export function isValidOpenAIApiKey(
apiKey: string | null | undefined,
): boolean {
if (!apiKey || typeof apiKey !== "string") {
return false;
}
return apiKey.startsWith("sk-") && apiKey.length > "sk-".length;
}
/**
* Gets a user-friendly error message for invalid API keys
* @param apiKey The API key that failed validation
* @param provider The provider name (e.g., "Anthropic", "OpenAI")
* @returns A descriptive error message
*/
export function getApiKeyValidationError(
apiKey: string | null | undefined,
provider: "anthropic" | "openai" = "anthropic",
): string {
if (!apiKey || typeof apiKey !== "string") {
return "API key is required";
}
if (provider === "anthropic") {
if (!apiKey.startsWith("sk-ant-")) {
return 'API key must start with "sk-ant-"';
}
if (apiKey.length <= "sk-ant-".length) {
return "API key is too short";
}
} else if (provider === "openai") {
if (!apiKey.startsWith("sk-")) {
return 'API key must start with "sk-"';
}
if (apiKey.length <= "sk-".length) {
return "API key is too short";
}
}
return "Invalid API key format";
}