|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const crypto = require('crypto'); |
| 4 | +const jwkToPem = require('jwk-to-pem'); |
| 5 | + |
| 6 | +/** |
| 7 | + * This function has all the merchentConfig properties getters and setters methods |
| 8 | + * |
| 9 | + * @param result |
| 10 | + */ |
| 11 | +function TokenVerification() { |
| 12 | + |
| 13 | +} |
| 14 | + |
| 15 | +function isPemFormattedString(input) { |
| 16 | + return typeof input === 'string' && /^-----BEGIN PUBLIC KEY-----[\S\s]*-----END PUBLIC KEY-----/.test(input); |
| 17 | + } |
| 18 | + |
| 19 | + function isBase64String(input) { |
| 20 | + return typeof input === 'string' && /^[a-zA-Z0-9+/=]*$/g.test(input); |
| 21 | + } |
| 22 | + |
| 23 | + function base64toPem(base64) { |
| 24 | + const urlDecoded = base64.replace(/-/g, '+').replace(/_/g, '/'); |
| 25 | + |
| 26 | + return [ |
| 27 | + '-----BEGIN PUBLIC KEY-----', |
| 28 | + ...urlDecoded.match(/.{1,64}/g), |
| 29 | + '-----END PUBLIC KEY-----', |
| 30 | + ].join('\n'); |
| 31 | + } |
| 32 | + |
| 33 | +TokenVerification.prototype.verifyToken = function verifyToken(publicKey, token) { |
| 34 | + if (typeof token !== 'object' || !token) throw new Error('Invalid token object'); |
| 35 | + if (!Object.prototype.hasOwnProperty.call(token, 'signature')) throw new Error('token.signature is missing'); |
| 36 | + if (!Object.prototype.hasOwnProperty.call(token, 'signedFields')) throw new Error('token.signedFields is missing'); |
| 37 | + |
| 38 | + let pem; |
| 39 | + if (typeof publicKey === 'object') pem = jwkToPem(publicKey); |
| 40 | + else if (isPemFormattedString(publicKey)) pem = publicKey; |
| 41 | + else if (isBase64String(publicKey)) pem = base64toPem(publicKey); |
| 42 | + else { |
| 43 | + throw new Error('Invalid publicKey parameter'); |
| 44 | + } |
| 45 | + |
| 46 | + const dataToVerify = token.signedFields.split(',').map(field => token[field]).join(','); |
| 47 | + return crypto.createVerify('RSA-SHA512').update(dataToVerify).verify(pem, token.signature, 'base64'); |
| 48 | +}; |
| 49 | + |
| 50 | +module.exports = TokenVerification; |
0 commit comments