Created
July 18, 2022 23:08
-
-
Save jhonywalkeer/607bff5dd75b471fd1e8e6742db3e9a3 to your computer and use it in GitHub Desktop.
It involves making an HTTPS request of the HEAD type and comparing the expiration date of the certificate obtained from the response object and the successful status of the SSL transaction (handshake) as reported by the underlying socket.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const https = require('https'); | |
const validator = require('validator'); | |
const getDaysBetween = (validFrom, validTo) => { | |
return Math.round(Math.abs(+validFrom - +validTo) / 8.64e7); | |
}; | |
const getDaysRemaining = (validFrom, validTo) => { | |
const daysRemaining = getDaysBetween(validFrom, validTo); | |
if (new Date(validTo).getTime() < new Date().getTime()) { | |
return -daysRemaining; | |
} | |
return daysRemaining; | |
}; | |
const getSSLCertificateInfo = host => { | |
if(!validator.isFQDN(host)) { | |
return Promise.reject(new Error('Invalid host.')); | |
} | |
const options = { | |
agent: false, | |
method: 'HEAD', | |
port: 443, | |
rejectUnauthorized: false, | |
hostname: host | |
}; | |
return new Promise((resolve, reject) => { | |
try { | |
const req = https.request(options, res => { | |
const crt = res.connection.getPeerCertificate(), | |
vFrom = crt.valid_from, vTo = crt.valid_to; | |
var validTo = new Date(vTo); | |
resolve({ | |
daysRemaining: getDaysRemaining(new Date(), validTo), | |
valid: res.socket.authorized || false, | |
validFrom: new Date(vFrom).toISOString(), | |
validTo: validTo.toISOString() | |
}); | |
}); | |
req.on('error', reject); | |
req.end(); | |
} catch (e) { | |
reject(e); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment