summaryrefslogtreecommitdiffhomepage
path: root/packages/server/src/helpers/getCertificateInfo.ts
blob: 7f70ef11925512c76ba9ad12de8fd0f9e087332d (plain)
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { X509, zulutodate } from 'jsrsasign';

export type CertificateInfo = {
  issuer: { [key: string]: string };
  subject: { [key: string]: string };
  version: number;
  basicConstraintsCA: boolean;
  notBefore: Date;
  notAfter: Date;
  extendedKeyUsageIDs: string[];
};

type ExtInfo = {
  critical: boolean;
  oid: string;
  vidx: number;
};

interface x5cCertificate extends jsrsasign.X509 {
  version: number;
  foffset: number;
  aExtInfo: ExtInfo[];
}

/**
 * Extract PEM certificate info
 *
 * @param pemCertificate Result from call to `convertASN1toPEM(x5c[0])`
 */
export default function getCertificateInfo(pemCertificate: string): CertificateInfo {
  const subjectCert = new X509();
  subjectCert.readCertPEM(pemCertificate);

  // Break apart the Issuer
  const issuerString = subjectCert.getIssuerString();
  const issuerParts = issuerString.slice(1).split('/');

  const issuer: { [key: string]: string } = {};
  issuerParts.forEach(field => {
    const [key, val] = field.split('=');
    issuer[key] = val;
  });

  // Break apart the Subject
  let subjectRaw = '/';
  try {
    subjectRaw = subjectCert.getSubjectString();
  } catch (err) {
    // Don't throw on an error that indicates an empty subject
    if (err !== 'malformed RDN') {
      throw err;
    }
  }
  const subjectParts = subjectRaw.slice(1).split('/');

  const subject: { [key: string]: string } = {};
  subjectParts.forEach(field => {
    if (field) {
      const [key, val] = field.split('=');
      subject[key] = val;
    }
  });

  const { version } = subjectCert as x5cCertificate;
  const basicConstraintsCA = !!subjectCert.getExtBasicConstraints()?.cA;

  const toReturn: CertificateInfo = {
    issuer,
    subject,
    version,
    basicConstraintsCA,
    notBefore: zulutodate(subjectCert.getNotBefore()),
    notAfter: zulutodate(subjectCert.getNotAfter()),
    extendedKeyUsageIDs: subjectCert.getExtExtKeyUsageName() || [],
  };

  return toReturn;
}