-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.js
83 lines (66 loc) · 2.58 KB
/
index.js
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const axios = require('axios')
const shortid = require('shortid')
// import algo-methods
const { aesEncrypt, aesDecrypt } = require('./algorithms/aes')
const { RSAEncrypt, RSADecrypt } = require('./algorithms/rsa')
/**
* @description initialize the Kuda wrapper function
* @param {object} param => publicKeyPath, privateKeyPath, clientKey
* @return {function} request function
*/
function Kuda (param) {
if (!param) return console.log('Error: publicKey, privateKey, clientKey are required!')
let { publicKey, privateKey } = param
publicKey = publicKey.toString()
privateKey = privateKey.toString()
const { clientKey } = param
if (!publicKey) return console.log('Error: publicKey is required!')
if (!privateKey) return console.log('Error: privateKey is required!')
if (!clientKey) return console.log('Error: clientKey is required!')
const password = `${clientKey}-${shortid.generate().substring(0, 5)}`
/**
* makes an encrypted call to Kuda API
* @param {object} params => serviceType, requestRef, data
* @param {function} callback gets called with the result(data) object
* @return {object} data return decrypted data response object
*/
async function request (params, callback) {
if (!params) return console.log('Error: serviceType, requestRef and data are required!')
const { serviceType, requestRef, data } = params
const payload = JSON.stringify({
serviceType,
requestRef,
data
})
try {
// aes encrypt payload with password
const encryptedPayload = await aesEncrypt(payload, password)
// rsa encrypt password with public key
const encryptedPassword = await RSAEncrypt(password, publicKey)
// make encrypted api request to Kuda Bank
const { data: encryptedResponse } = await axios.post('https://kuda-openapi.kuda.com/v1', {
data: encryptedPayload
}, {
headers: {
password: encryptedPassword
}
})
// plaintext = RSA decrypt password with our privateKey
const plaintext = await RSADecrypt(encryptedResponse.password, privateKey).toString()
// data = AES decrypt data with plaintext
let data = await aesDecrypt(encryptedResponse.data, plaintext)
if (typeof data === 'string') data = JSON.parse(data)
// console.log('encrypted response:', JSON.stringify({
// encryptedResponse,
// plaintext,
// data: JSON.parse(data)
// }, null, 2))
if (callback) return callback(data)
return data
} catch (err) {
console.log(err.stack)
}
}
return request
}
module.exports = Kuda