@@ -19,13 +19,49 @@ export const extractBearerToken = (header: string | undefined): string | undefin
1919 return token ? token : undefined
2020}
2121
22+ export const extractBasicAuth = (
23+ header : string | undefined ,
24+ ) : { username : string ; password : string } | undefined => {
25+ if ( ! header ) return undefined
26+ const match = header . trim ( ) . match ( / ^ B a s i c \s + ( .+ ) $ / i)
27+ const token = match ?. [ 1 ] ?. trim ( )
28+ if ( ! token ) return undefined
29+ try {
30+ const decoded = Buffer . from ( token , 'base64' ) . toString ( 'utf8' )
31+ const separatorIndex = decoded . indexOf ( ':' )
32+ if ( separatorIndex === - 1 ) return undefined
33+ const username = decoded . slice ( 0 , separatorIndex )
34+ const password = decoded . slice ( separatorIndex + 1 )
35+ if ( ! username || ! password ) return undefined
36+ return { username, password }
37+ } catch {
38+ return undefined
39+ }
40+ }
41+
42+ const timingSafeEqualString = ( a : string , b : string ) : boolean => {
43+ const bufferA = Buffer . from ( a )
44+ const bufferB = Buffer . from ( b )
45+ if ( bufferA . length !== bufferB . length ) return false
46+ return timingSafeEqual ( bufferA , bufferB )
47+ }
48+
2249export const isAuthorized = ( req : IncomingMessage , token : string ) : boolean => {
2350 const provided = extractBearerToken ( req . headers . authorization )
2451 if ( ! provided ) return false
25- const a = Buffer . from ( provided )
26- const b = Buffer . from ( token )
27- if ( a . length !== b . length ) return false
28- return timingSafeEqual ( a , b )
52+ return timingSafeEqualString ( provided , token )
53+ }
54+
55+ export const isBasicAuthorized = (
56+ req : IncomingMessage ,
57+ expected : { username : string ; password : string } ,
58+ ) : boolean => {
59+ const provided = extractBasicAuth ( req . headers . authorization )
60+ if ( ! provided ) return false
61+ return (
62+ timingSafeEqualString ( provided . username , expected . username ) &&
63+ timingSafeEqualString ( provided . password , expected . password )
64+ )
2965}
3066
3167export const applyCorsHeaders = (
0 commit comments