Skip to content

Commit 0a8e5d2

Browse files
authored
Merge pull request #33 from gnongsie/master
Adding Flex Token Verification logic
2 parents 40d3e68 + 3dc8f29 commit 0a8e5d2

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

generator/cybersource-javascript-template/index.mustache

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@
5858
*/</emitJSDoc>
5959
<importPath>: <importPath></apis></apiInfo>
6060
};
61+
62+
exports.TokenVerification = require('./utilities/flex/TokenVerification.js');
6163

6264
return exports;<={{ }}=>
6365
}));
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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

Comments
 (0)