index.js
1.74 KB
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
84
85
86
87
88
var https = require('https');
function isEmpty(object) {
for (var prop in object) {
if (object.hasOwnProperty(prop)) return false;
}
return true;
}
function pemEncode(str, n) {
var ret = [];
for (var i = 1; i <= str.length; i++) {
ret.push(str[i - 1]);
var mod = i % n;
if (mod === 0) {
ret.push('\n');
}
}
var returnString = `-----BEGIN CERTIFICATE-----\n${ret.join('')}\n-----END CERTIFICATE-----`;
return returnString;
}
function getOptions(url, port, protocol) {
return {
hostname: url,
agent: false,
rejectUnauthorized: false,
ciphers: 'ALL',
port,
protocol
};
}
function validateUrl(url) {
if (url.length <= 0 || typeof url !== 'string') {
throw Error('A valid URL is required');
}
}
function handleRequest(options, resolve, reject) {
return https.get(options, function(res) {
var certificate = res.socket.getPeerCertificate();
if (isEmpty(certificate) || certificate === null) {
reject({ message: 'The website did not provide a certificate' });
} else {
if (certificate.raw) {
certificate.pemEncoded = pemEncode(certificate.raw.toString('base64'), 64);
}
resolve(certificate);
}
});
}
function get(url, timeout, port, protocol) {
validateUrl(url);
port = port || 443;
protocol = protocol || 'https:';
var options = getOptions(url, port, protocol);
return new Promise(function(resolve, reject) {
var req = handleRequest(options, resolve, reject);
if (timeout) {
req.setTimeout(timeout, function() {
reject({ message: 'Request timed out.' });
req.abort();
});
}
req.on('error', function(e) {
reject(e);
});
req.end();
});
}
module.exports = {
get: get
};