@@ -18,6 +18,13 @@ function verifyBearerAuthFactory (options) {
1818 if ( _options . keys instanceof Set ) _options . keys = Array . from ( _options . keys )
1919 const { keys, errorResponse, contentType, bearerType, auth, addHook = true , verifyErrorLogLevel = 'error' } = _options
2020
21+ for ( let i = 0 , il = keys . length ; i < il ; ++ i ) {
22+ if ( typeof keys [ i ] !== 'string' ) {
23+ throw new Error ( 'options.keys has to contain only string entries' )
24+ }
25+ keys [ i ] = Buffer . from ( keys [ i ] )
26+ }
27+
2128 return function verifyBearerAuth ( request , reply , done ) {
2229 const header = request . raw . headers . authorization
2330 if ( ! header ) {
@@ -89,17 +96,19 @@ function verifyBearerAuthFactory (options) {
8996}
9097
9198function authenticate ( keys , key ) {
92- return keys . findIndex ( ( a ) => compare ( a , key ) ) !== - 1
99+ const b = Buffer . from ( key )
100+ return keys . findIndex ( ( a ) => compare ( a , b ) ) !== - 1
93101}
94102
95103// perform constant-time comparison to prevent timing attacks
96104function compare ( a , b ) {
97- try {
98- // may throw if they have different length, can't convert to Buffer, etc...
99- return crypto . timingSafeEqual ( Buffer . from ( a ) , Buffer . from ( b ) )
100- } catch {
105+ if ( a . length !== b . length ) {
106+ // Delay return with cryptographically secure timing check.
107+ crypto . timingSafeEqual ( a , a )
101108 return false
102109 }
110+
111+ return crypto . timingSafeEqual ( a , b )
103112}
104113
105114function plugin ( fastify , options , done ) {
0 commit comments