Created
March 8, 2022 00:51
-
-
Save gregalia/eb7a3937dae5e1f5184879bda3187d89 to your computer and use it in GitHub Desktop.
Node Cert Check
This file contains hidden or 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 tls = require('tls'); | |
// HT: https://medium.com/@keithwan.programming/doing-ssl-certificate-expiry-alert-in-node-js-1714ef15621 | |
const HOSTNAME = 'amazon.com'; | |
const EXPIRATION_DAYS_THRESHOLD = 60; | |
function checkCertExpiry({ cert, days }) { | |
const msDay = 24 * 3600 * 1000; | |
const expiration = new Date(cert.valid_to).getTime(); | |
const threshold = Date.now() + days * msDay; | |
const daysToExpiry = Math.floor((expiration - Date.now()) / msDay); | |
const warn = expiration < threshold; | |
return { expiration, threshold, daysToExpiry, warn }; | |
} | |
const socket = tls.connect( | |
{ | |
host: HOSTNAME, | |
port: 443, | |
servername: HOSTNAME, | |
}, | |
() => { | |
const peerCertificate = socket.getPeerCertificate({ detailed: true }); | |
const expiryObj = checkCertExpiry({ | |
cert: peerCertificate, | |
days: EXPIRATION_DAYS_THRESHOLD, | |
}); | |
// console.log(peerCertificate); | |
const { | |
issuer: { O }, | |
subject: { CN }, | |
serialNumber, | |
subjectaltname, | |
} = peerCertificate; | |
// warn = CN.includes(HOSTNAME) || subjectaltname.includes(HOSTNAME); | |
console.log({ O, CN, serialNumber, subjectaltname, ...expiryObj }); | |
socket.destroy(); | |
} | |
); | |
socket.on('error', (err) => { | |
console.log('Error: ' + err.message); | |
}); | |
socket.on('close', () => {}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment