-
Notifications
You must be signed in to change notification settings - Fork 2
/
encrypt.js
78 lines (69 loc) · 2.17 KB
/
encrypt.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
var NodeRSA = require('node-rsa');
var axios = require('axios');
var encryptData = function (data, key, callback) {
var pem = key.replace(/RSA PUBLIC KEY/g, 'PUBLIC KEY');
try {
var publicKey = new NodeRSA(pem, 'pkcs8-public-pem');
var cipherText = publicKey.encrypt(data, 'base64');
return callback(null, cipherText);
} catch (err) {
return callback(err);
}
};
var authGithub = function(pro, token) {
var domain = 'org';
if (pro) { domain = 'com'; }
return axios({
method: 'post',
url: 'https://api.travis-ci.' + domain + '/auth/github',
headers: {
'User-Agent': 'vtex-travis-encrypt/1.0.0',
Accept: 'application/vnd.travis-ci.2+json'
},
data: {
github_token: token
}
});
}
var getRepoKey = function(pro, ownerName, name, access_token) {
var domain = 'org';
if (pro) { domain = 'com'; }
return axios({
url: 'https://api.travis-ci.' + domain + '/repos/' + ownerName + '/' + name + '/key',
headers: {
'User-Agent': 'vtex-travis-encrypt/1.0.0',
Accept: 'application/vnd.travis-ci.2+json',
Authorization: 'token ' + access_token,
}
});
}
var showErrors = function(res, callback) {
res.config.headers.Authorization = 'travis-encrypt: field removed for security reasons';
callback(JSON.stringify(res));
}
var encryptPublicRepo = function(ownerName, name, data, token, callback) {
authGithub(false, token)
.then(function(res) {
return getRepoKey(false, ownerName, name, res.data.access_token);
})
.catch(function(res) { showErrors(res, callback); })
.then(function(res) {
encryptData(data, res.data.key, callback);
})
.catch(function(res) { showErrors(res, callback); });
}
var encryptPrivateRepo = function(ownerName, name, data, token, callback) {
authGithub(true, token)
.then(function(res) {
return getRepoKey(true, ownerName, name, res.data.access_token);
})
.catch(function(res) { showErrors(res, callback); })
.then(function(res) {
encryptData(data, res.data.key, callback);
})
.catch(function(res) { showErrors(res, callback); });
}
module.exports = {
privateRepo: encryptPrivateRepo,
publicRepo: encryptPublicRepo
};