All files / src/integrations hapi.js

68.97% Statements 20/29
53.85% Branches 14/26
77.78% Functions 7/9
71.43% Lines 20/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 622x 2x   2x                                 2x 1x 1x 1x 1x 1x   1x         2x 1x       1x 1x   1x   1x         1x       1x 1x         1x        
import { ArgumentError } from '../errors';
import { JwksClient } from '../JwksClient';
 
const handleSigningKeyError = (err, cb) => {
  // If we didn't find a match, can't provide a key.
  if (err && err.name === 'SigningKeyNotFoundError') {
    return cb(err, null, null);
  }
 
  // If an error occured like rate limiting or HTTP issue, we'll bubble up the error.
  if (err) {
    return cb(err, null, null);
  }
};
 
/**
 * Call hapiJwt2Key as a Promise
 * @param {object} options 
 * @returns {Promise}
 */
module.exports.hapiJwt2KeyAsync = (options) => {
  const secretProvider = module.exports.hapiJwt2Key(options);
  return function(decoded) {
    return new Promise((resolve, reject) => {
      const cb = (err, key) => {
        (!key || err) ? reject(err) : resolve({ key });
      };
      secretProvider(decoded, cb);
    });
  };
}; 
 
module.exports.hapiJwt2Key = (options) => {
  Iif (options === null || options === undefined) {
    throw new ArgumentError('An options object must be provided when initializing hapiJwt2Key');
  }
 
  const client = new JwksClient(options);
  const onError = options.handleSigningKeyError || handleSigningKeyError;
 
  return function secretProvider(decoded, cb) {
    // We cannot find a signing certificate if there is no header (no kid).
    Iif (!decoded || !decoded.header) {
      return cb(new Error('Cannot find a signing certificate if there is no header'), null, null);
    }
 
    // Only RS256 is supported.
    Iif (decoded.header.alg !== 'RS256') {
      return cb(new Error('Unsupported algorithm ' + decoded.header.alg + ' supplied. node-jwks-rsa supports only RS256'), null, null);
    }
 
    client.getSigningKey(decoded.header.kid, (err, key) => {
      Iif (err) {
        return onError(err, (newError) => cb(newError, null, null));
      }
 
      // Provide the key.
      return cb(null, key.publicKey || key.rsaPublicKey, key);
    });
  };
};