2023-08-26 14:09:08 +02:00
|
|
|
const tls = require('tls');
|
2023-08-09 23:33:36 +02:00
|
|
|
const middleware = require('./_common/middleware');
|
2023-06-21 00:01:45 +02:00
|
|
|
|
2023-08-13 14:57:48 +02:00
|
|
|
const fetchSiteCertificateHandler = async (urlString) => {
|
2023-07-10 00:23:50 +02:00
|
|
|
try {
|
2023-08-26 14:09:08 +02:00
|
|
|
const parsedUrl = new URL(urlString);
|
2023-08-13 14:57:48 +02:00
|
|
|
const options = {
|
|
|
|
host: parsedUrl.hostname,
|
2023-08-26 14:09:08 +02:00
|
|
|
port: parsedUrl.port || 443,
|
|
|
|
servername: parsedUrl.hostname,
|
|
|
|
rejectUnauthorized: false,
|
2023-08-13 14:57:48 +02:00
|
|
|
};
|
|
|
|
|
2023-08-26 14:09:08 +02:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const socket = tls.connect(options, () => {
|
|
|
|
if (!socket.authorized) {
|
|
|
|
return reject(new Error(`SSL handshake not authorized. Reason: ${socket.authorizationError}`));
|
2023-07-07 21:56:58 +02:00
|
|
|
}
|
2023-08-26 14:09:08 +02:00
|
|
|
|
|
|
|
const cert = socket.getPeerCertificate();
|
|
|
|
if (!cert || Object.keys(cert).length === 0) {
|
|
|
|
return reject(new Error(`
|
|
|
|
No certificate presented by the server.\n
|
|
|
|
The server is possibly not using SNI (Server Name Indication) to identify itself, and you are connecting to a hostname-aliased IP address.
|
|
|
|
Or it may be due to an invalid SSL certificate, or an incomplete SSL handshake at the time the cert is being read.`));
|
|
|
|
}
|
|
|
|
|
|
|
|
const { raw, issuerCertificate, ...certWithoutRaw } = cert;
|
|
|
|
resolve(certWithoutRaw);
|
|
|
|
socket.end();
|
2023-07-10 00:23:50 +02:00
|
|
|
});
|
|
|
|
|
2023-08-26 14:09:08 +02:00
|
|
|
socket.on('error', (error) => {
|
2023-08-09 23:33:36 +02:00
|
|
|
reject(new Error(`Error fetching site certificate: ${error.message}`));
|
2023-07-10 00:23:50 +02:00
|
|
|
});
|
2023-06-21 00:01:45 +02:00
|
|
|
});
|
|
|
|
|
2023-07-10 00:23:50 +02:00
|
|
|
} catch (error) {
|
2023-08-09 23:33:36 +02:00
|
|
|
throw new Error(error.message);
|
2023-07-10 00:23:50 +02:00
|
|
|
}
|
2023-06-21 00:01:45 +02:00
|
|
|
};
|
2023-08-09 23:33:36 +02:00
|
|
|
|
|
|
|
exports.handler = middleware(fetchSiteCertificateHandler);
|