Line data Source code
1 : import type {
2 : ApiKeyAuthHeader,
3 : AuthCredential,
4 : AuthHeader,
5 : LoggedInAuthHeader
6 : } from './authTypes'
7 :
8 2356 : const HEADER_CREDENTIAL = {
9 : Authorization: 'bearer',
10 : 'X-API-KEY': 'api-key'
11 : } as const satisfies Record<
12 : keyof LoggedInAuthHeader | keyof ApiKeyAuthHeader,
13 : AuthCredential
14 : >
15 :
16 : /** The credential kind an auth header carries; `none` when it carries neither. */
17 0 : export function authCredentialOf(header: AuthHeader | null): AuthCredential {
18 0 : if (header === null) return 'none'
19 0 : const headerKey = Object.keys(HEADER_CREDENTIAL).find((key) => key in header)
20 0 : return headerKey === undefined
21 : ? 'none'
22 : : HEADER_CREDENTIAL[headerKey as keyof typeof HEADER_CREDENTIAL]
23 : }
24 :
25 : /**
26 : * Delivers a credential kind to a diagnostics callback without letting the
27 : * callback affect the request: telemetry must fail open.
28 : */
29 312936 : export function notifyAuthCredential(
30 : callback: ((credential: AuthCredential) => void) | undefined,
31 : credential: AuthCredential
32 : ): void {
33 312936 : try {
34 312936 : callback?.(credential)
35 : } catch (error) {
36 0 : console.warn('onAuthCredential callback failed:', error)
37 : }
38 : }
|