blob: 9d27e80ef60c73954b739abca7b850c5ba5718ed (
plain) (
blame)
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
|
export const API_KEY_PREFIX = "imemio_";
export function generateApiKey(): string {
const randomBytes = new Uint8Array(16);
crypto.getRandomValues(randomBytes);
const hexString = Array.from(randomBytes)
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
return `${API_KEY_PREFIX}${hexString}`;
}
export function extractKeyPrefix(apiKey: string): string {
if (!apiKey.startsWith(API_KEY_PREFIX)) {
throw new Error("Invalid API key format");
}
return apiKey.slice(API_KEY_PREFIX.length, API_KEY_PREFIX.length + 8);
}
export async function hashApiKey(apiKey: string): Promise<string> {
const encoder = new TextEncoder();
const data = encoder.encode(apiKey);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
}
export function isValidApiKeyFormat(apiKey: string): boolean {
if (!apiKey.startsWith(API_KEY_PREFIX)) {
return false;
}
const keyPart = apiKey.slice(API_KEY_PREFIX.length);
return keyPart.length === 32 && /^[0-9a-f]+$/i.test(keyPart);
}
|