({
apiKey,
getUserInfoFromApiKey = defaultGetUserInfoFromApiKey,
logger = defaultLogger,
}: ValidateAuthParams)
| 62 | * Previously this was not exported, making it impossible to test in isolation |
| 63 | */ |
| 64 | export async function validateApiKey({ |
| 65 | apiKey, |
| 66 | getUserInfoFromApiKey = defaultGetUserInfoFromApiKey, |
| 67 | logger = defaultLogger, |
| 68 | }: ValidateAuthParams): Promise<ValidatedUserInfo> { |
| 69 | const requestedFields = ['id', 'email'] as const |
| 70 | |
| 71 | try { |
| 72 | const authResult = await getUserInfoFromApiKey({ |
| 73 | apiKey, |
| 74 | fields: requestedFields, |
| 75 | logger, |
| 76 | }) |
| 77 | |
| 78 | if (!authResult) { |
| 79 | logger.error('❌ API key validation failed - invalid credentials') |
| 80 | throw createAuthError('Invalid API key') |
| 81 | } |
| 82 | |
| 83 | return authResult |
| 84 | } catch (error) { |
| 85 | const statusCode = getErrorStatusCode(error) |
| 86 | |
| 87 | if (isAuthenticationError(error)) { |
| 88 | logger.error('❌ API key validation failed - authentication error') |
| 89 | // Rethrow the original error to preserve statusCode for higher layers |
| 90 | throw error |
| 91 | } |
| 92 | |
| 93 | if (statusCode !== undefined && isRetryableStatusCode(statusCode)) { |
| 94 | logger.error( |
| 95 | { |
| 96 | error: error instanceof Error ? error.message : String(error), |
| 97 | statusCode, |
| 98 | }, |
| 99 | '❌ API key validation failed - network error', |
| 100 | ) |
| 101 | // Rethrow the original error to preserve statusCode for higher layers |
| 102 | throw error |
| 103 | } |
| 104 | |
| 105 | // Unknown error - wrap with statusCode for consistency |
| 106 | logger.error( |
| 107 | { |
| 108 | error: error instanceof Error ? error.message : String(error), |
| 109 | }, |
| 110 | '❌ API key validation failed - unknown error', |
| 111 | ) |
| 112 | throw createServerError('Authentication failed') |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | export interface UseAuthQueryDeps { |
| 117 | getUserCredentials?: () => User | null |
no test coverage detected