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 { 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); }