All files / lib/helpers verification.js

100% Statements 17/17
91.66% Branches 11/12
100% Functions 8/8
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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          4x         4x 4x 472x 472x 342x         130x             4x 15x         4x 13x   16x           4x 11x 11x                  
import { rootCertificates } from "node:tls";
import forge from "node-forge";
 
import rootCAs from "./rootCAs.json" with { type: "json" };
 
const getRootCAs = () => rootCertificates ?? rootCAs;
 
/**
 * @param {forge.pki.Certificate} chainRootInForgeFormat
 */
const verifyRootCert = (chainRootInForgeFormat) =>
	!!getRootCAs().find((rootCAInPem) => {
		try {
			const rootCAInForgeCert = forge.pki.certificateFromPem(rootCAInPem);
			return (
				forge.pki.certificateToPem(chainRootInForgeFormat) === rootCAInPem ||
				rootCAInForgeCert.issued(chainRootInForgeFormat)
			);
		} catch (e) {
			return false;
		}
	});
 
/**
 * @param {readonly forge.pki.Certificate[]} certs
 */
const verifyCaBundle = (certs) =>
	!!certs.find((cert, i) => certs[i + 1] && certs[i + 1]?.issued(cert));
 
/**
 * @param {readonly forge.pki.Certificate[]} certs
 */
const isCertsExpired = (certs) =>
	!!certs.find(
		({ validity: { notAfter, notBefore } }) =>
			notAfter.getTime() < Date.now() || notBefore.getTime() > Date.now(),
	);
 
/**
 * @param {readonly forge.pki.Certificate[]} certs
 */
const authenticateSignature = (certs) => {
	const root = certs.at(-1);
	return verifyCaBundle(certs) && root ? verifyRootCert(root) : false;
};
 
export {
	authenticateSignature,
	verifyCaBundle,
	verifyRootCert,
	isCertsExpired,
};