All files / lib certificateDetails.js

100% Statements 20/20
100% Branches 4/4
100% Functions 7/7
100% Lines 18/18

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 54 55 56 57 58 59 60 61 62 63 64                      2x 36x         167x 157x 157x               2x 18x 18x                     2x 12x 18x 12x                 2x 2x 1x   1x 1x 1x          
import forge from "node-forge";
 
import {
	extractSignature,
	getMessageFromSignature,
	preparePDF,
} from "./helpers/index.js";
 
/**
 * @param {readonly forge.pki.CertificateField[]} attrs
 */
const mapEntityAtrributes = (attrs) =>
	attrs.reduce(
		/**
		 * @param {Record<string, unknown>} agg
		 */
		(agg, { name, value }) => {
			if (!name) return agg;
			agg[name] = value;
			return agg;
		},
		{},
	);
 
/**
 * @param {forge.pki.Certificate} cert
 */
const extractSingleCertificateDetails = (cert) => {
	const { issuer, subject, validity } = cert;
	return {
		issuedBy: mapEntityAtrributes(issuer.attributes),
		issuedTo: mapEntityAtrributes(subject.attributes),
		validityPeriod: validity,
		pemCertificate: forge.pki.certificateToPem(cert),
	};
};
 
/**
 * @param {readonly forge.pki.Certificate[]} certs
 */
const extractCertificatesDetails = (certs) =>
	certs.map(extractSingleCertificateDetails).map((cert, i) => {
		if (i) return cert;
		return {
			clientCertificate: true,
			...cert,
		};
	});
 
/**
 * @param {Uint8Array} pdf
 */
const getCertificatesInfoFromPDF = (pdf) => {
	const pdfBuffer = preparePDF(pdf);
	const { signatureStr } = extractSignature(pdfBuffer);
 
	return signatureStr.map((signature) => {
		const { certificates } = getMessageFromSignature(signature);
		return extractCertificatesDetails(certificates);
	});
};
 
export { extractCertificatesDetails, getCertificatesInfoFromPDF };