UNPKG

@sphereon/ssi-sdk-ext.x509-utils

Version:

Sphereon SSI-SDK plugin functions for X.509 Certificate handling.

1 lines 59.6 kB
{"version":3,"sources":["../src/index.ts","../src/types/index.ts","../src/x509/rsa-key.ts","../src/x509/crypto.ts","../src/x509/x509-utils.ts","../src/x509/rsa-signer.ts","../src/x509/x509-validator.ts"],"sourcesContent":["/**\n *\n * @packageDocumentation\n */\nexport * from './types'\nexport * from './x509'\n","export enum JwkKeyUse {\n Encryption = 'enc',\n Signature = 'sig',\n}\n\nexport type HashAlgorithm = 'SHA-256' | 'SHA-512'\n\nexport type KeyVisibility = 'public' | 'private'\n\nexport interface X509Opts {\n cn?: string // The certificate Common Name. Will be used as the KID for the private key. Uses alias if not provided.\n privateKeyPEM?: string // Optional as you also need to provide it in hex format, but advisable to use it\n certificatePEM?: string // Optional, as long as the certificate then is part of the certificateChainPEM\n certificateChainURL?: string // Certificate chain URL. If used this is where the certificateChainPEM will be hosted/found.\n certificateChainPEM?: string // Base64 (not url!) encoded DER certificate chain. Please provide even if certificateChainURL is used!\n}\n","// @ts-ignore\nimport { KeyUsage, CryptoKey, RsaHashedImportParams, RsaHashedKeyGenParams } from 'node'\n\n// @ts-ignore\nimport * as u8a from 'uint8arrays'\nconst { toString } = u8a\nimport type { HashAlgorithm } from '../types'\nimport { globalCrypto } from './crypto'\n\nimport { derToPEM } from './x509-utils'\nimport type { JsonWebKey } from '@sphereon/ssi-types'\n\nexport type RSASignatureSchemes = 'RSASSA-PKCS1-V1_5' | 'RSA-PSS'\n\nexport type RSAEncryptionSchemes = 'RSAES-PKCS-v1_5 ' | 'RSAES-OAEP'\n\nconst usage = (jwk: JsonWebKey): KeyUsage[] => {\n if (jwk.key_ops && jwk.key_ops.length > 0) {\n return jwk.key_ops as KeyUsage[]\n }\n if (jwk.use) {\n const usages: KeyUsage[] = []\n if (jwk.use.includes('sig')) {\n usages.push('sign', 'verify')\n } else if (jwk.use.includes('enc')) {\n usages.push('encrypt', 'decrypt')\n }\n if (usages.length > 0) {\n return usages\n }\n }\n if (jwk.kty === 'RSA') {\n if (jwk.d) {\n return jwk.alg?.toUpperCase()?.includes('QAEP') ? ['encrypt'] : ['sign']\n }\n return jwk.alg?.toUpperCase()?.includes('QAEP') ? ['decrypt'] : ['verify']\n }\n // \"decrypt\" | \"deriveBits\" | \"deriveKey\" | \"encrypt\" | \"sign\" | \"unwrapKey\" | \"verify\" | \"wrapKey\";\n return jwk.d && jwk.kty !== 'RSA' ? ['sign', 'decrypt', 'verify', 'encrypt'] : ['verify']\n}\n\nexport const signAlgorithmToSchemeAndHashAlg = (signingAlg: string) => {\n const alg = signingAlg.toUpperCase()\n let scheme: RSAEncryptionSchemes | RSASignatureSchemes\n if (alg.startsWith('RS')) {\n scheme = 'RSASSA-PKCS1-V1_5'\n } else if (alg.startsWith('PS')) {\n scheme = 'RSA-PSS'\n } else {\n throw Error(`Invalid signing algorithm supplied ${signingAlg}`)\n }\n\n const hashAlgorithm = `SHA-${alg.substring(2)}` as HashAlgorithm\n return { scheme, hashAlgorithm }\n}\n\nexport const cryptoSubtleImportRSAKey = async (\n jwk: JsonWebKey,\n scheme: RSAEncryptionSchemes | RSASignatureSchemes,\n hashAlgorithm?: HashAlgorithm,\n): Promise<CryptoKey> => {\n const hashName = hashAlgorithm ? hashAlgorithm : jwk.alg ? `SHA-${jwk.alg.substring(2)}` : 'SHA-256'\n\n const importParams: RsaHashedImportParams = { name: scheme, hash: hashName }\n return await globalCrypto(false).subtle.importKey('jwk', jwk as JsonWebKey, importParams, false, usage(jwk))\n}\n\nexport const generateRSAKeyAsPEM = async (\n scheme: RSAEncryptionSchemes | RSASignatureSchemes,\n hashAlgorithm?: HashAlgorithm,\n modulusLength?: number,\n): Promise<string> => {\n const hashName = hashAlgorithm ? hashAlgorithm : 'SHA-256'\n\n const params: RsaHashedKeyGenParams = {\n name: scheme,\n hash: hashName,\n modulusLength: modulusLength ? modulusLength : 2048,\n publicExponent: new Uint8Array([1, 0, 1]),\n }\n const keyUsage: KeyUsage[] = scheme === 'RSA-PSS' || scheme === 'RSASSA-PKCS1-V1_5' ? ['sign', 'verify'] : ['encrypt', 'decrypt']\n\n const keypair = await globalCrypto(false).subtle.generateKey(params, true, keyUsage)\n const pkcs8 = await globalCrypto(false).subtle.exportKey('pkcs8', keypair.privateKey)\n\n const uint8Array = new Uint8Array(pkcs8)\n return derToPEM(toString(uint8Array, 'base64pad'), 'RSA PRIVATE KEY')\n}\n","import { webcrypto } from 'node:crypto'\nexport const globalCrypto = (setGlobal: boolean, suppliedCrypto?: webcrypto.Crypto): webcrypto.Crypto => {\n let webcrypto: webcrypto.Crypto\n if (typeof suppliedCrypto !== 'undefined') {\n webcrypto = suppliedCrypto\n } else if (typeof crypto !== 'undefined') {\n webcrypto = crypto\n } else if (typeof global.crypto !== 'undefined') {\n webcrypto = global.crypto\n } else {\n // @ts-ignore\n if (typeof global.window?.crypto?.subtle !== 'undefined') {\n // @ts-ignore\n webcrypto = global.window.crypto\n } else {\n // @ts-ignore\n webcrypto = require('crypto') as webcrypto.Crypto\n }\n }\n if (setGlobal) {\n global.crypto = webcrypto\n }\n\n return webcrypto\n}\n","import { X509Certificate } from '@peculiar/x509'\nimport { Certificate } from 'pkijs'\n// @ts-ignore\nimport * as u8a from 'uint8arrays'\nconst { fromString, toString } = u8a\n// @ts-ignore\nimport keyto from '@trust/keyto'\nimport type { KeyVisibility } from '../types'\n\nimport type { JsonWebKey } from '@sphereon/ssi-types'\n// Based on (MIT licensed):\n// https://github.com/hildjj/node-posh/blob/master/lib/index.js\nexport function pemCertChainTox5c(cert: string, maxDepth?: number): string[] {\n if (!maxDepth) {\n maxDepth = 0\n }\n /*\n * Convert a PEM-encoded certificate to the version used in the x5c element\n * of a [JSON Web Key](http://tools.ietf.org/html/draft-ietf-jose-json-web-key).\n *\n * `cert` PEM-encoded certificate chain\n * `maxdepth` The maximum number of certificates to use from the chain.\n */\n\n const intermediate = cert\n .replace(/-----[^\\n]+\\n?/gm, ',')\n .replace(/\\n/g, '')\n .replace(/\\r/g, '')\n let x5c = intermediate.split(',').filter(function (c) {\n return c.length > 0\n })\n if (maxDepth > 0) {\n x5c = x5c.splice(0, maxDepth)\n }\n return x5c\n}\n\nexport function x5cToPemCertChain(x5c: string[], maxDepth?: number): string {\n if (!maxDepth) {\n maxDepth = 0\n }\n const length = maxDepth === 0 ? x5c.length : Math.min(maxDepth, x5c.length)\n let pem = ''\n for (let i = 0; i < length; i++) {\n pem += derToPEM(x5c[i], 'CERTIFICATE')\n }\n return pem\n}\n\nexport const pemOrDerToX509Certificate = (cert: string | Uint8Array | X509Certificate): Certificate => {\n let DER: string | undefined = typeof cert === 'string' ? cert : undefined\n if (typeof cert === 'object' && !(cert instanceof Uint8Array)) {\n // X509Certificate object\n return Certificate.fromBER(cert.rawData)\n } else if (typeof cert !== 'string') {\n return Certificate.fromBER(cert)\n } else if (cert.includes('CERTIFICATE')) {\n DER = PEMToDer(cert)\n }\n if (!DER) {\n throw Error('Invalid cert input value supplied. PEM, DER, Bytes and X509Certificate object are supported')\n }\n return Certificate.fromBER(fromString(DER, 'base64pad'))\n}\n\nexport const areCertificatesEqual = (cert1: Certificate, cert2: Certificate): boolean => {\n return cert1.signatureValue.isEqual(cert2.signatureValue)\n}\n\nexport const toKeyObject = (PEM: string, visibility: KeyVisibility = 'public') => {\n const jwk = PEMToJwk(PEM, visibility)\n const keyVisibility: KeyVisibility = jwk.d ? 'private' : 'public'\n const keyHex = keyVisibility === 'private' ? privateKeyHexFromPEM(PEM) : publicKeyHexFromPEM(PEM)\n\n return {\n pem: hexToPEM(keyHex, visibility),\n jwk,\n keyHex,\n keyType: keyVisibility,\n }\n}\n\nexport const jwkToPEM = (jwk: JsonWebKey, visibility: KeyVisibility = 'public'): string => {\n return keyto.from(jwk, 'jwk').toString('pem', visibility === 'public' ? 'public_pkcs8' : 'private_pkcs8')\n}\n\nexport const PEMToJwk = (pem: string, visibility: KeyVisibility = 'public'): JsonWebKey => {\n return keyto.from(pem, 'pem').toJwk(visibility)\n}\nexport const privateKeyHexFromPEM = (PEM: string) => {\n return PEMToHex(PEM)\n}\n\nexport const hexKeyFromPEMBasedJwk = (jwk: JsonWebKey, visibility: KeyVisibility = 'public'): string => {\n if (visibility === 'private') {\n return privateKeyHexFromPEM(jwkToPEM(jwk, 'private'))\n } else {\n return publicKeyHexFromPEM(jwkToPEM(jwk, 'public'))\n }\n}\n\nexport const publicKeyHexFromPEM = (PEM: string) => {\n const hex = PEMToHex(PEM)\n if (PEM.includes('CERTIFICATE')) {\n throw Error('Cannot directly deduce public Key from PEM Certificate yet')\n } else if (!PEM.includes('PRIVATE')) {\n return hex\n }\n const publicJwk = PEMToJwk(PEM, 'public')\n const publicPEM = jwkToPEM(publicJwk, 'public')\n return PEMToHex(publicPEM)\n}\n\nexport const PEMToHex = (PEM: string, headerKey?: string): string => {\n if (PEM.indexOf('-----BEGIN ') == -1) {\n throw Error(`PEM header not found: ${headerKey}`)\n }\n\n let strippedPem: string\n if (headerKey) {\n strippedPem = PEM.replace(new RegExp('^[^]*-----BEGIN ' + headerKey + '-----'), '')\n strippedPem = strippedPem.replace(new RegExp('-----END ' + headerKey + '-----[^]*$'), '')\n } else {\n strippedPem = PEM.replace(/^[^]*-----BEGIN [^-]+-----/, '')\n strippedPem = strippedPem.replace(/-----END [^-]+-----[^]*$/, '')\n }\n return base64ToHex(strippedPem, 'base64pad')\n}\n\nexport function PEMToBinary(pem: string): Uint8Array {\n const pemContents = pem\n .replace(/^[^]*-----BEGIN [^-]+-----/, '')\n .replace(/-----END [^-]+-----[^]*$/, '')\n .replace(/\\s/g, '')\n\n return fromString(pemContents, 'base64pad')\n}\n\n/**\n * Converts a base64 encoded string to hex string, removing any non-base64 characters, including newlines\n * @param input The input in base64, with optional newlines\n * @param inputEncoding\n */\nexport const base64ToHex = (input: string, inputEncoding?: 'base64' | 'base64pad' | 'base64url' | 'base64urlpad') => {\n const base64NoNewlines = input.replace(/[^0-9A-Za-z_\\-~\\/+=]*/g, '')\n return toString(fromString(base64NoNewlines, inputEncoding ? inputEncoding : 'base64pad'), 'base16')\n}\n\nexport const hexToBase64 = (input: number | object | string, targetEncoding?: 'base64' | 'base64pad' | 'base64url' | 'base64urlpad'): string => {\n let hex = typeof input === 'string' ? input : input.toString(16)\n if (hex.length % 2 === 1) {\n hex = `0${hex}`\n }\n return toString(fromString(hex, 'base16'), targetEncoding ? targetEncoding : 'base64pad')\n}\n\nexport const hexToPEM = (hex: string, type: KeyVisibility): string => {\n const base64 = hexToBase64(hex, 'base64pad')\n const headerKey = type === 'private' ? 'RSA PRIVATE KEY' : 'PUBLIC KEY'\n if (type === 'private') {\n const pem = derToPEM(base64, headerKey)\n try {\n PEMToJwk(pem) // We only use it to test the private key\n return pem\n } catch (error) {\n return derToPEM(base64, 'PRIVATE KEY')\n }\n }\n return derToPEM(base64, headerKey)\n}\n\nexport function PEMToDer(pem: string): string {\n return pem.replace(/(-----(BEGIN|END) CERTIFICATE-----|[\\n\\r])/g, '')\n}\n\nexport function derToPEM(cert: string, headerKey?: 'PUBLIC KEY' | 'RSA PRIVATE KEY' | 'PRIVATE KEY' | 'CERTIFICATE'): string {\n const key = headerKey ?? 'CERTIFICATE'\n if (cert.includes(key)) {\n // Was already in PEM it seems\n return cert\n }\n const matches = cert.match(/.{1,64}/g)\n if (!matches) {\n throw Error('Invalid cert input value supplied')\n }\n return `-----BEGIN ${key}-----\\n${matches.join('\\n')}\\n-----END ${key}-----\\n`\n}\n","// @ts-ignore\nimport * as u8a from 'uint8arrays'\nconst { fromString, toString } = u8a\nimport type { HashAlgorithm, KeyVisibility } from '../types'\nimport { globalCrypto } from './crypto'\nimport { cryptoSubtleImportRSAKey, RSAEncryptionSchemes, RSASignatureSchemes } from './rsa-key'\nimport { PEMToJwk } from './x509-utils'\nimport type { JsonWebKey } from '@sphereon/ssi-types'\n// @ts-ignore\nimport { CryptoKey, RsaPssParams, AlgorithmIdentifier } from 'node'\nexport class RSASigner {\n private readonly hashAlgorithm: HashAlgorithm\n private readonly jwk: JsonWebKey\n\n private key: CryptoKey | undefined\n private readonly scheme: RSAEncryptionSchemes | RSASignatureSchemes\n\n /**\n *\n * @param key Either in PEM or JWK format (no raw hex keys here!)\n * @param opts The algorithm and signature/encryption schemes\n */\n constructor(\n key: string | JsonWebKey,\n opts?: { hashAlgorithm?: HashAlgorithm; scheme?: RSAEncryptionSchemes | RSASignatureSchemes; visibility?: KeyVisibility },\n ) {\n if (typeof key === 'string') {\n this.jwk = PEMToJwk(key, opts?.visibility)\n } else {\n this.jwk = key\n }\n\n this.hashAlgorithm = opts?.hashAlgorithm ?? 'SHA-256'\n this.scheme = opts?.scheme ?? 'RSA-PSS'\n }\n\n private getImportParams(): AlgorithmIdentifier | RsaPssParams {\n if (this.scheme === 'RSA-PSS') {\n return { name: this.scheme, saltLength: 32 }\n }\n return { name: this.scheme /*, hash: this.hashAlgorithm*/ }\n }\n\n private async getKey(): Promise<CryptoKey> {\n if (!this.key) {\n this.key = await cryptoSubtleImportRSAKey(this.jwk, this.scheme, this.hashAlgorithm)\n }\n return this.key\n }\n\n private bufferToString(buf: ArrayBuffer) {\n const uint8Array = new Uint8Array(buf)\n return toString(uint8Array, 'base64url') // Needs to be base64url for JsonWebSignature2020. Don't change!\n }\n\n public async sign(data: Uint8Array): Promise<string> {\n const input = data\n const key = await this.getKey()\n const signature = this.bufferToString(await globalCrypto(false).subtle.sign(this.getImportParams(), key, input))\n if (!signature) {\n throw Error('Could not sign input data')\n }\n\n // base64url signature\n return signature\n }\n\n public async verify(data: string | Uint8Array, signature: string): Promise<boolean> {\n const jws = signature.includes('.') ? signature.split('.')[2] : signature\n\n const input = typeof data == 'string' ? fromString(data, 'utf-8') : data\n\n let key = await this.getKey()\n if (!key.usages.includes('verify')) {\n const verifyJwk = { ...this.jwk }\n delete verifyJwk.d\n delete verifyJwk.use\n delete verifyJwk.key_ops\n key = await cryptoSubtleImportRSAKey(verifyJwk, this.scheme, this.hashAlgorithm)\n }\n const verificationResult = await globalCrypto(false).subtle.verify(this.getImportParams(), key, fromString(jws, 'base64url'), input)\n return verificationResult\n }\n}\n","import { AsnParser } from '@peculiar/asn1-schema'\nimport { SubjectPublicKeyInfo } from '@peculiar/asn1-x509'\nimport { AlgorithmProvider, X509Certificate } from '@peculiar/x509'\n// import {calculateJwkThumbprint} from \"@sphereon/ssi-sdk-ext.key-utils\";\nimport { JWK } from '@sphereon/ssi-types'\nimport x509 from 'js-x509-utils'\nimport { AltName, AttributeTypeAndValue, Certificate, CryptoEngine, getCrypto, id_SubjectAltName, setEngine } from 'pkijs'\nimport { container } from 'tsyringe'\n// @ts-ignore\nimport * as u8a from 'uint8arrays'\nconst { fromString, toString } = u8a\nimport { globalCrypto } from './crypto'\nimport { areCertificatesEqual, derToPEM, pemOrDerToX509Certificate } from './x509-utils'\n\nexport type DNInfo = {\n DN: string\n attributes: Record<string, string>\n}\n\nexport type CertificateInfo = {\n certificate?: any // We need to fix the schema generator for this to be Certificate(Json) from pkijs\n notBefore: Date\n notAfter: Date\n publicKeyJWK?: any\n issuer: {\n dn: DNInfo\n }\n subject: {\n dn: DNInfo\n subjectAlternativeNames: SubjectAlternativeName[]\n }\n}\n\nexport type X509ValidationResult = {\n error: boolean\n critical: boolean\n message: string\n detailMessage?: string\n verificationTime: Date\n certificateChain?: Array<CertificateInfo>\n trustAnchor?: CertificateInfo\n client?: {\n // In case client id and scheme were passed in we return them for easy access. It means they are validated\n clientId: string\n clientIdScheme: ClientIdScheme\n }\n}\n\nconst defaultCryptoEngine = () => {\n const name = 'crypto'\n setEngine(name, new CryptoEngine({ name, crypto: globalCrypto(false) }))\n return getCrypto(true)\n}\n\nexport const getCertificateInfo = async (\n certificate: Certificate,\n opts?: {\n sanTypeFilter: SubjectAlternativeGeneralName | SubjectAlternativeGeneralName[]\n },\n): Promise<CertificateInfo> => {\n let publicKeyJWK: JWK | undefined\n try {\n publicKeyJWK = (await getCertificateSubjectPublicKeyJWK(certificate)) as JWK\n } catch (e) {}\n return {\n issuer: { dn: getIssuerDN(certificate) },\n subject: {\n dn: getSubjectDN(certificate),\n subjectAlternativeNames: getSubjectAlternativeNames(certificate, { typeFilter: opts?.sanTypeFilter }),\n },\n publicKeyJWK,\n notBefore: certificate.notBefore.value,\n notAfter: certificate.notAfter.value,\n // certificate\n } satisfies CertificateInfo\n}\n\nexport type X509CertificateChainValidationOpts = {\n // If no trust anchor is found, but the chain itself checks out, allow. (defaults to false:)\n allowNoTrustAnchorsFound?: boolean\n\n // Trust the supplied root from the chain, when no anchors are being passed in.\n trustRootWhenNoAnchors?: boolean\n // Do not perform a chain validation check if the chain only has a single value. This means only the certificate itself will be validated. No chain checks for CA certs will be performed. Only used when the cert has no issuer\n allowSingleNoCAChainElement?: boolean\n // WARNING: Do not use in production\n // Similar to regular trust anchors, but no validation is performed whatsoever. Do not use in production settings! Can be handy with self generated certificates as we perform many validations, making it hard to test with self-signed certs. Only applied in case a chain with 1 element is passed in to really make sure people do not abuse this option\n blindlyTrustedAnchors?: string[]\n\n disallowReversedChain?: boolean\n\n client?: {\n // If provided both are required. Validates the leaf certificate against the clientId and scheme\n clientId: string\n clientIdScheme: ClientIdScheme\n }\n}\n\nexport const validateX509CertificateChain = async ({\n chain: pemOrDerChain,\n trustAnchors,\n verificationTime = new Date(),\n opts = {\n // If no trust anchor is found, but the chain itself checks out, allow. (defaults to false:)\n allowNoTrustAnchorsFound: false,\n trustRootWhenNoAnchors: false,\n allowSingleNoCAChainElement: true,\n blindlyTrustedAnchors: [],\n disallowReversedChain: false,\n },\n}: {\n chain: (Uint8Array | string)[]\n trustAnchors?: string[]\n verificationTime?: Date\n opts?: X509CertificateChainValidationOpts\n}): Promise<X509ValidationResult> => {\n // We allow 1 reversal. We reverse by default as the implementation expects the root ca first, whilst x5c is the opposite. Reversed becomes true if the impl reverses the chain\n return await validateX509CertificateChainImpl({\n reversed: false,\n chain: [...pemOrDerChain].reverse(),\n trustAnchors,\n verificationTime,\n opts,\n })\n}\nconst validateX509CertificateChainImpl = async ({\n reversed,\n chain: pemOrDerChain,\n trustAnchors,\n verificationTime: verifyAt,\n opts,\n}: {\n reversed: boolean\n chain: (Uint8Array | string)[]\n trustAnchors?: string[]\n verificationTime: Date | string // string for REST API\n opts: X509CertificateChainValidationOpts\n}): Promise<X509ValidationResult> => {\n const verificationTime: Date = typeof verifyAt === 'string' ? new Date(verifyAt) : verifyAt\n const {\n allowNoTrustAnchorsFound = false,\n trustRootWhenNoAnchors = false,\n allowSingleNoCAChainElement = true,\n blindlyTrustedAnchors = [],\n disallowReversedChain = false,\n client,\n } = opts\n const trustedPEMs = trustRootWhenNoAnchors && !trustAnchors ? [pemOrDerChain[pemOrDerChain.length - 1]] : trustAnchors\n\n if (pemOrDerChain.length === 0) {\n return {\n error: true,\n critical: true,\n message: 'Certificate chain in DER or PEM format must not be empty',\n verificationTime,\n }\n }\n defaultCryptoEngine()\n\n // x5c always starts with the leaf cert at index 0 and then the cas. Our internal pkijs service expects it the other way around. Before calling this function the change has been revered\n const chain = await Promise.all(pemOrDerChain.map((raw) => parseCertificate(raw)))\n const x5cOrdereredChain = reversed ? [...chain] : [...chain].reverse()\n\n const trustedCerts = trustedPEMs ? await Promise.all(trustedPEMs.map((raw) => parseCertificate(raw))) : undefined\n const blindlyTrusted =\n (\n await Promise.all(\n blindlyTrustedAnchors.map((raw) => {\n try {\n return parseCertificate(raw)\n } catch (e) {\n // @ts-ignore\n console.log(`Failed to parse blindly trusted certificate ${raw}. Error: ${e.message}`)\n return undefined\n }\n }),\n )\n ).filter((cert): cert is ParsedCertificate => cert !== undefined) ?? []\n const leafCert = x5cOrdereredChain[0]\n\n const chainLength = chain.length\n var foundTrustAnchor: ParsedCertificate | undefined = undefined\n for (let i = 0; i < chainLength; i++) {\n const currentCert = chain[i]\n const previousCert = i > 0 ? chain[i - 1] : undefined\n const blindlyTrustedCert = blindlyTrusted.find((trusted) => areCertificatesEqual(trusted.certificate, currentCert.certificate))\n if (blindlyTrustedCert) {\n console.log(`Certificate chain validation success as single cert if blindly trusted. WARNING: ONLY USE FOR TESTING PURPOSES.`)\n return {\n error: false,\n critical: false,\n message: `Certificate chain validation success as single cert if blindly trusted. WARNING: ONLY USE FOR TESTING PURPOSES.`,\n detailMessage: `Blindly trusted certificate ${blindlyTrustedCert.certificateInfo.subject.dn.DN} was found in the chain.`,\n trustAnchor: blindlyTrustedCert?.certificateInfo,\n verificationTime,\n certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),\n ...(client && { client }),\n }\n }\n if (previousCert) {\n if (currentCert.x509Certificate.issuer !== previousCert.x509Certificate.subject) {\n if (!reversed && !disallowReversedChain) {\n return await validateX509CertificateChainImpl({\n reversed: true,\n chain: [...pemOrDerChain].reverse(),\n opts,\n verificationTime,\n trustAnchors,\n })\n }\n return {\n error: true,\n critical: true,\n certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),\n message: `Certificate chain validation failed for ${leafCert.certificateInfo.subject.dn.DN}.`,\n detailMessage: `The certificate ${currentCert.certificateInfo.subject.dn.DN} with issuer ${currentCert.x509Certificate.issuer}, is not signed by the previous certificate ${previousCert?.certificateInfo.subject.dn.DN} with subject string ${previousCert?.x509Certificate.subject}.`,\n verificationTime,\n ...(client && { client }),\n }\n }\n }\n const result = await currentCert.x509Certificate.verify(\n {\n date: verificationTime,\n publicKey: previousCert?.x509Certificate?.publicKey,\n },\n getCrypto()?.crypto ?? crypto ?? global.crypto,\n )\n if (!result) {\n // First cert needs to be self signed\n if (i == 0 && !reversed && !disallowReversedChain) {\n return await validateX509CertificateChainImpl({\n reversed: true,\n chain: [...pemOrDerChain].reverse(),\n opts,\n verificationTime,\n trustAnchors,\n })\n }\n\n return {\n error: true,\n critical: true,\n message: `Certificate chain validation failed for ${leafCert.certificateInfo.subject.dn.DN}.`,\n certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),\n detailMessage: `Verification of the certificate ${currentCert.certificateInfo.subject.dn.DN} with issuer ${\n currentCert.x509Certificate.issuer\n } failed. Public key: ${JSON.stringify(currentCert.certificateInfo.publicKeyJWK)}.`,\n verificationTime,\n ...(client && { client }),\n }\n }\n\n foundTrustAnchor = foundTrustAnchor ?? trustedCerts?.find((trusted) => isSameCertificate(trusted.x509Certificate, currentCert.x509Certificate))\n\n if (i === 0 && chainLength === 1 && allowSingleNoCAChainElement) {\n return {\n error: false,\n critical: false,\n message: `Certificate chain succeeded as allow single cert result is allowed: ${leafCert.certificateInfo.subject.dn.DN}.`,\n certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),\n trustAnchor: foundTrustAnchor?.certificateInfo,\n verificationTime,\n ...(client && { client }),\n }\n }\n }\n\n if (foundTrustAnchor?.certificateInfo || allowNoTrustAnchorsFound) {\n return {\n error: false,\n critical: false,\n message: `Certificate chain was valid`,\n certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),\n detailMessage: foundTrustAnchor\n ? `The leaf certificate ${leafCert.certificateInfo.subject.dn.DN} is part of a chain with trust anchor ${foundTrustAnchor?.certificateInfo.subject.dn.DN}.`\n : `The leaf certificate ${leafCert.certificateInfo.subject.dn.DN} and chain were valid, but no trust anchor has been found. Ignoring as user allowed (allowNoTrustAnchorsFound: ${allowNoTrustAnchorsFound}).)`,\n trustAnchor: foundTrustAnchor?.certificateInfo,\n verificationTime,\n ...(client && { client }),\n }\n }\n\n return {\n error: true,\n critical: true,\n message: `Certificate chain validation failed for ${leafCert.certificateInfo.subject.dn.DN}.`,\n certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),\n detailMessage: `No trust anchor was found in the chain. between (intermediate) CA ${\n x5cOrdereredChain[chain.length - 1].certificateInfo.subject.dn.DN\n } and leaf ${x5cOrdereredChain[0].certificateInfo.subject.dn.DN}.`,\n verificationTime,\n ...(client && { client }),\n }\n}\n\nconst isSameCertificate = (cert1: X509Certificate, cert2: X509Certificate): boolean => {\n return cert1.rawData.toString() === cert2.rawData.toString()\n}\n\nconst algorithmProvider: AlgorithmProvider = container.resolve(AlgorithmProvider)\nexport const getX509AlgorithmProvider = (): AlgorithmProvider => {\n return algorithmProvider\n}\n\nexport type ParsedCertificate = {\n publicKeyInfo: SubjectPublicKeyInfo\n publicKeyJwk?: JWK\n publicKeyRaw: Uint8Array\n // @ts-ignore\n publicKeyAlgorithm: Algorithm\n certificateInfo: CertificateInfo\n certificate: Certificate\n x509Certificate: X509Certificate\n}\n\nexport const parseCertificate = async (rawCert: string | Uint8Array): Promise<ParsedCertificate> => {\n const x509Certificate = new X509Certificate(rawCert)\n const publicKeyInfo = AsnParser.parse(x509Certificate.publicKey.rawData, SubjectPublicKeyInfo)\n const publicKeyRaw = new Uint8Array(publicKeyInfo.subjectPublicKey)\n let publicKeyJwk: JWK | undefined = undefined\n try {\n publicKeyJwk = (await getCertificateSubjectPublicKeyJWK(new Uint8Array(x509Certificate.rawData))) as JWK\n } catch (e: any) {\n console.error(e.message)\n }\n const certificate = pemOrDerToX509Certificate(rawCert)\n const certificateInfo = await getCertificateInfo(certificate)\n const publicKeyAlgorithm = getX509AlgorithmProvider().toWebAlgorithm(publicKeyInfo.algorithm)\n return {\n publicKeyAlgorithm,\n publicKeyInfo,\n publicKeyJwk,\n publicKeyRaw,\n certificateInfo,\n certificate,\n x509Certificate,\n }\n}\n/*\n\n/!**\n *\n * @param pemOrDerChain The order must be that the Certs signing another cert must come one after another. So first the signing cert, then any cert signing that cert and so on\n * @param trustedPEMs\n * @param verificationTime\n * @param opts\n *!/\nexport const validateX509CertificateChainOrg = async ({\n chain: pemOrDerChain,\n trustAnchors,\n verificationTime = new Date(),\n opts = {\n trustRootWhenNoAnchors: false,\n allowSingleNoCAChainElement: true,\n blindlyTrustedAnchors: [],\n },\n }: {\n chain: (Uint8Array | string)[]\n trustAnchors?: string[]\n verificationTime?: Date\n opts?: X509CertificateChainValidationOpts\n}): Promise<X509ValidationResult> => {\n const {\n trustRootWhenNoAnchors = false,\n allowSingleNoCAChainElement = true,\n blindlyTrustedAnchors = [],\n client\n } = opts\n const trustedPEMs = trustRootWhenNoAnchors && !trustAnchors ? [pemOrDerChain[pemOrDerChain.length - 1]] : trustAnchors\n\n if (pemOrDerChain.length === 0) {\n return {\n error: true,\n critical: true,\n message: 'Certificate chain in DER or PEM format must not be empty',\n verificationTime,\n }\n }\n\n // x5c always starts with the leaf cert at index 0 and then the cas. Our internal pkijs service expects it the other way around\n const certs = pemOrDerChain.map(pemOrDerToX509Certificate).reverse()\n const trustedCerts = trustedPEMs ? trustedPEMs.map(pemOrDerToX509Certificate) : undefined\n defaultCryptoEngine()\n\n if (pemOrDerChain.length === 1) {\n const singleCert = typeof pemOrDerChain[0] === 'string' ? pemOrDerChain[0] : u8a.toString(pemOrDerChain[0], 'base64pad')\n const cert = pemOrDerToX509Certificate(singleCert)\n if (client) {\n const validation = await validateCertificateChainMatchesClientIdScheme(cert, client.clientId, client.clientIdScheme)\n if (validation.error) {\n return validation\n }\n }\n if (blindlyTrustedAnchors.includes(singleCert)) {\n console.log(`Certificate chain validation success as single cert if blindly trusted. WARNING: ONLY USE FOR TESTING PURPOSES.`)\n return {\n error: false,\n critical: true,\n message: `Certificate chain validation success as single cert if blindly trusted. WARNING: ONLY USE FOR TESTING PURPOSES.`,\n verificationTime,\n certificateChain: [await getCertificateInfo(cert)],\n ...(client && {client}),\n }\n }\n if (allowSingleNoCAChainElement) {\n const subjectDN = getSubjectDN(cert).DN\n if (!getIssuerDN(cert).DN || getIssuerDN(cert).DN === subjectDN) {\n const passed = await cert.verify()\n return {\n error: !passed,\n critical: true,\n message: `Certificate chain validation for ${subjectDN}: ${passed ? 'successful' : 'failed'}.`,\n verificationTime,\n certificateChain: [await getCertificateInfo(cert)],\n ...(client && {client}),\n }\n }\n }\n }\n\n const validationEngine = new CertificateChainValidationEngine({\n certs /!*crls: [crl1], ocsps: [ocsp1], *!/,\n checkDate: verificationTime,\n trustedCerts,\n })\n\n try {\n const verification = await validationEngine.verify()\n if (!verification.result || !verification.certificatePath) {\n return {\n error: true,\n critical: true,\n message: verification.resultMessage !== '' ? verification.resultMessage : `Certificate chain validation failed.`,\n verificationTime,\n ...(client && {client}),\n }\n }\n const certPath = verification.certificatePath\n if (client) {\n const clientIdValidation = await validateCertificateChainMatchesClientIdScheme(certs[0], client.clientId, client.clientIdScheme)\n if (clientIdValidation.error) {\n return clientIdValidation\n }\n }\n let certInfos: Array<CertificateInfo> | undefined\n\n for (const certificate of certPath) {\n try {\n certInfos?.push(await getCertificateInfo(certificate))\n } catch (e: any) {\n console.log(`Error getting certificate info ${e.message}`)\n }\n }\n\n\n return {\n error: false,\n critical: false,\n message: `Certificate chain was valid`,\n verificationTime,\n certificateChain: certInfos,\n ...(client && {client}),\n }\n } catch (error: any) {\n return {\n error: true,\n critical: true,\n message: `Certificate chain was invalid, ${error.message ?? '<unknown error>'}`,\n verificationTime,\n ...(client && {client}),\n }\n }\n}\n*/\n\nconst rdnmap: Record<string, string> = {\n '2.5.4.6': 'C',\n '2.5.4.10': 'O',\n '2.5.4.11': 'OU',\n '2.5.4.3': 'CN',\n '2.5.4.7': 'L',\n '2.5.4.8': 'ST',\n '2.5.4.12': 'T',\n '2.5.4.42': 'GN',\n '2.5.4.43': 'I',\n '2.5.4.4': 'SN',\n '1.2.840.113549.1.9.1': 'E-mail',\n}\n\nexport const getIssuerDN = (cert: Certificate): DNInfo => {\n return {\n DN: getDNString(cert.issuer.typesAndValues),\n attributes: getDNObject(cert.issuer.typesAndValues),\n }\n}\n\nexport const getSubjectDN = (cert: Certificate): DNInfo => {\n return {\n DN: getDNString(cert.subject.typesAndValues),\n attributes: getDNObject(cert.subject.typesAndValues),\n }\n}\n\nconst getDNObject = (typesAndValues: AttributeTypeAndValue[]): Record<string, string> => {\n const DN: Record<string, string> = {}\n for (const typeAndValue of typesAndValues) {\n const type = rdnmap[typeAndValue.type] ?? typeAndValue.type\n DN[type] = typeAndValue.value.getValue()\n }\n return DN\n}\nconst getDNString = (typesAndValues: AttributeTypeAndValue[]): string => {\n return Object.entries(getDNObject(typesAndValues))\n .map(([key, value]) => `${key}=${value}`)\n .join(',')\n}\n\nexport const getCertificateSubjectPublicKeyJWK = async (pemOrDerCert: string | Uint8Array | Certificate): Promise<JWK> => {\n const pemOrDerStr =\n typeof pemOrDerCert === 'string'\n ? toString(fromString(pemOrDerCert, 'base64pad'), 'base64pad')\n : pemOrDerCert instanceof Uint8Array\n ? toString(pemOrDerCert, 'base64pad')\n : toString(fromString(pemOrDerCert.toString('base64'), 'base64pad'), 'base64pad')\n const pem = derToPEM(pemOrDerStr)\n const certificate = pemOrDerToX509Certificate(pem)\n var jwk: JWK | undefined\n try {\n const subtle = getCrypto(true).subtle\n const pk = await certificate.getPublicKey(undefined, defaultCryptoEngine())\n jwk = (await subtle.exportKey('jwk', pk)) as JWK | undefined\n } catch (error: any) {\n console.log(`Error in primary get JWK from cert:`, error?.message)\n }\n if (!jwk) {\n try {\n jwk = (await x509.toJwk(pem, 'pem')) as JWK\n } catch (error: any) {\n console.log(`Error in secondary get JWK from cert as well:`, error?.message)\n }\n }\n if (!jwk) {\n throw Error(`Failed to get JWK from certificate ${pem}`)\n }\n return jwk\n}\n\n/**\n * otherName [0] OtherName,\n * rfc822Name [1] IA5String,\n * dNSName [2] IA5String,\n * x400Address [3] ORAddress,\n * directoryName [4] Name,\n * ediPartyName [5] EDIPartyName,\n * uniformResourceIdentifier [6] IA5String,\n * iPAddress [7] OCTET STRING,\n * registeredID [8] OBJECT IDENTIFIER }\n */\nexport enum SubjectAlternativeGeneralName {\n rfc822Name = 1, // email\n dnsName = 2,\n uniformResourceIdentifier = 6,\n ipAddress = 7,\n}\n\nexport interface SubjectAlternativeName {\n value: string\n type: SubjectAlternativeGeneralName\n}\n\nexport type ClientIdScheme = 'x509_san_dns' | 'x509_san_uri'\n\nexport const assertCertificateMatchesClientIdScheme = (certificate: Certificate, clientId: string, clientIdScheme: ClientIdScheme): void => {\n const sans = getSubjectAlternativeNames(certificate, { clientIdSchemeFilter: clientIdScheme })\n const clientIdMatches = sans.find((san) => san.value === clientId)\n if (!clientIdMatches) {\n throw Error(\n `Client id scheme ${clientIdScheme} used had no matching subject alternative names in certificate with DN ${\n getSubjectDN(certificate).DN\n }. SANS: ${sans.map((san) => san.value).join(',')}`,\n )\n }\n}\n\nexport const validateCertificateChainMatchesClientIdScheme = async (\n certificate: Certificate,\n clientId: string,\n clientIdScheme: ClientIdScheme,\n): Promise<X509ValidationResult> => {\n const result = {\n error: true,\n critical: true,\n message: `Client Id ${clientId} was not present in certificate using scheme ${clientIdScheme}`,\n client: {\n clientId,\n clientIdScheme,\n },\n certificateChain: [await getCertificateInfo(certificate)],\n verificationTime: new Date(),\n }\n try {\n assertCertificateMatchesClientIdScheme(certificate, clientId, clientIdScheme)\n } catch (error) {\n return result\n }\n result.error = false\n result.message = `Client Id ${clientId} was present in certificate using scheme ${clientIdScheme}`\n return result\n}\n\nexport const getSubjectAlternativeNames = (\n certificate: Certificate,\n opts?: {\n typeFilter?: SubjectAlternativeGeneralName | SubjectAlternativeGeneralName[]\n // When a clientIdchemeFilter is passed in it will always override the above type filter\n clientIdSchemeFilter?: ClientIdScheme\n },\n): SubjectAlternativeName[] => {\n let typeFilter: SubjectAlternativeGeneralName[]\n if (opts?.clientIdSchemeFilter) {\n typeFilter =\n opts.clientIdSchemeFilter === 'x509_san_dns'\n ? [SubjectAlternativeGeneralName.dnsName]\n : [SubjectAlternativeGeneralName.uniformResourceIdentifier]\n } else if (opts?.typeFilter) {\n typeFilter = Array.isArray(opts.typeFilter) ? opts.typeFilter : [opts.typeFilter]\n } else {\n typeFilter = [SubjectAlternativeGeneralName.dnsName, SubjectAlternativeGeneralName.uniformResourceIdentifier]\n }\n const parsedValue = certificate.extensions?.find((ext) => ext.extnID === id_SubjectAltName)?.parsedValue as AltName\n if (!parsedValue) {\n return []\n }\n const altNames = parsedValue.toJSON().altNames\n return altNames\n .filter((altName) => typeFilter.includes(altName.type))\n .map((altName) => {\n return { type: altName.type, value: altName.value } satisfies SubjectAlternativeName\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;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