micro509 0.7.2 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +5 -5
- package/dist/index.js +15 -1
- package/dist/internal/asn1/asn1.js +280 -2
- package/dist/internal/asn1/der.js +378 -2
- package/dist/internal/asn1/oids.js +103 -2
- package/dist/internal/crypto/algorithm-names.js +58 -2
- package/dist/internal/crypto/ecdsa.js +68 -2
- package/dist/internal/crypto/hash.js +286 -2
- package/dist/internal/crypto/pbes2.js +213 -2
- package/dist/internal/crypto/rsa-pss.js +184 -2
- package/dist/internal/crypto/sig-verify.js +192 -2
- package/dist/internal/crypto/signing.d.ts +1 -2
- package/dist/internal/crypto/signing.js +123 -2
- package/dist/internal/crypto/webcrypto.js +14 -2
- package/dist/internal/shared/base64.js +16 -2
- package/dist/internal/shared/dn.js +84 -2
- package/dist/internal/shared/ip.js +164 -2
- package/dist/internal/verify/name-constraints-engine.js +450 -2
- package/dist/internal/verify/policy-engine.js +382 -2
- package/dist/internal/verify/verify-path.js +298 -2
- package/dist/internal/x509/extension-bits.js +132 -2
- package/dist/internal/x509/extension-registry.js +229 -2
- package/dist/internal/x509/name-fields.js +93 -2
- package/dist/keys/keys.d.ts +380 -13
- package/dist/keys/keys.js +1247 -5
- package/dist/keys.d.ts +2 -2
- package/dist/keys.js +2 -1
- package/dist/pem/pem.d.ts +2 -2
- package/dist/pem/pem.js +172 -6
- package/dist/pem.js +2 -1
- package/dist/pkcs/pfx.d.ts +4 -5
- package/dist/pkcs/pfx.js +395 -2
- package/dist/pkcs/pkcs12-mac.d.ts +2 -2
- package/dist/pkcs/pkcs12-mac.js +175 -2
- package/dist/pkcs/pkcs7.d.ts +1 -2
- package/dist/pkcs/pkcs7.js +653 -2
- package/dist/pkcs.d.ts +2 -2
- package/dist/pkcs.js +4 -1
- package/dist/result/result.d.ts +1 -2
- package/dist/result/result.js +111 -2
- package/dist/result.js +2 -1
- package/dist/revocation/chain.d.ts +4 -5
- package/dist/revocation/chain.js +536 -2
- package/dist/revocation/crl.d.ts +2 -2
- package/dist/revocation/crl.js +1119 -2
- package/dist/revocation/ocsp.d.ts +5 -4
- package/dist/revocation/ocsp.js +958 -2
- package/dist/revocation/revocation.d.ts +1 -2
- package/dist/revocation/revocation.js +261 -2
- package/dist/revocation.d.ts +2 -2
- package/dist/revocation.js +5 -1
- package/dist/verify/identity.d.ts +1 -2
- package/dist/verify/identity.js +270 -2
- package/dist/verify/name-constraints.d.ts +1 -2
- package/dist/verify/policy.d.ts +1 -2
- package/dist/verify/verify.d.ts +1 -2
- package/dist/verify/verify.js +764 -2
- package/dist/verify.js +3 -1
- package/dist/x509/certificate.d.ts +1 -2
- package/dist/x509/certificate.js +151 -2
- package/dist/x509/csr.d.ts +1 -2
- package/dist/x509/csr.js +71 -2
- package/dist/x509/extensions.d.ts +1 -2
- package/dist/x509/extensions.js +387 -2
- package/dist/x509/name.d.ts +1 -2
- package/dist/x509/name.js +173 -2
- package/dist/x509/parse.d.ts +84 -2
- package/dist/x509/parse.js +1090 -2
- package/dist/x509.d.ts +2 -2
- package/dist/x509.js +6 -1
- package/package.json +74 -34
- package/dist/internal/asn1/asn1.js.map +0 -1
- package/dist/internal/asn1/der.js.map +0 -1
- package/dist/internal/asn1/oids.js.map +0 -1
- package/dist/internal/crypto/algorithm-names.js.map +0 -1
- package/dist/internal/crypto/ecdsa.js.map +0 -1
- package/dist/internal/crypto/hash.js.map +0 -1
- package/dist/internal/crypto/pbes2.d.ts +0 -23
- package/dist/internal/crypto/pbes2.js.map +0 -1
- package/dist/internal/crypto/rsa-pss.js.map +0 -1
- package/dist/internal/crypto/sig-verify.js.map +0 -1
- package/dist/internal/crypto/signing.js.map +0 -1
- package/dist/internal/crypto/webcrypto.js.map +0 -1
- package/dist/internal/shared/base64.js.map +0 -1
- package/dist/internal/shared/dn.js.map +0 -1
- package/dist/internal/shared/ip.js.map +0 -1
- package/dist/internal/verify/name-constraints-engine.js.map +0 -1
- package/dist/internal/verify/policy-engine.js.map +0 -1
- package/dist/internal/verify/verify-path.js.map +0 -1
- package/dist/internal/x509/extension-bits.js.map +0 -1
- package/dist/internal/x509/extension-registry.js.map +0 -1
- package/dist/internal/x509/name-fields.js.map +0 -1
- package/dist/keys/keys.js.map +0 -1
- package/dist/pem/pem.js.map +0 -1
- package/dist/pkcs/pfx.js.map +0 -1
- package/dist/pkcs/pkcs12-mac.js.map +0 -1
- package/dist/pkcs/pkcs7.js.map +0 -1
- package/dist/result/result.js.map +0 -1
- package/dist/revocation/chain.js.map +0 -1
- package/dist/revocation/crl.js.map +0 -1
- package/dist/revocation/ocsp.js.map +0 -1
- package/dist/revocation/revocation.js.map +0 -1
- package/dist/verify/identity.js.map +0 -1
- package/dist/verify/verify.js.map +0 -1
- package/dist/x509/certificate.js.map +0 -1
- package/dist/x509/csr.js.map +0 -1
- package/dist/x509/extensions.js.map +0 -1
- package/dist/x509/name.js.map +0 -1
- package/dist/x509/parse.js.map +0 -1
package/dist/verify/verify.js
CHANGED
|
@@ -1,2 +1,764 @@
|
|
|
1
|
-
import{OIDS as e}from"../internal/asn1/oids.js";import{errorResult as t,indexedErrorResult as n,indexedMicro509Error as r,micro509Error as i}from"../result/result.js";import{parseIpAddressToBytes as a}from"../internal/shared/ip.js";import{parseCertificateDerOrThrow as o,parseCertificateSigningRequestDerOrThrow as s,parseCertificateSigningRequestPemOrThrow as c}from"../x509/parse.js";import{verifySignedDataDetailed as l}from"../internal/crypto/sig-verify.js";import{createNameConstraintValidationState as ee,evaluateNameConstraints as te}from"../internal/verify/name-constraints-engine.js";import{createPolicyValidationState as ne,evaluatePolicyChain as re}from"../internal/verify/policy-engine.js";import{buildChainInternal as u,countCaCertificatesBelowParsed as d,isSelfIssued as f,isWithinValidity as p,loadCertificates as m,loadSingleCertificate as h,verifyCertificateSignature as g}from"../internal/verify/verify-path.js";import{checkChainRevocation as ie}from"../revocation/chain.js";import{matchServiceIdentity as _}from"./identity.js";const v=[`no_trusted_root`,`issuer_not_found`,`signature_invalid`,`certificate_expired`,`ca_required`,`key_cert_sign_required`,`path_length_exceeded`,`authority_key_identifier_mismatch`,`extended_key_usage_invalid`,`subject_alt_name_mismatch`,`common_name_fallback_suppressed`,`self_signed_leaf_not_allowed`,`unrecognized_critical_extension`,`intermediate_eku_constraint`,`explicit_policy_required`,`initial_policy_set_not_satisfied`,`unsupported_initial_name_constraints`,`unsupported_name_constraints`,`name_constraints_violated`,`unsupported_signature_algorithm_parameters`,`certificate_revoked`,`revocation_indeterminate`],y=new Set([e.basicConstraints,e.keyUsage,e.extendedKeyUsage,e.subjectAltName,e.nameConstraints,e.authorityKeyIdentifier,e.subjectKeyIdentifier,e.authorityInfoAccess,e.cRLDistributionPoints,e.certificatePolicies,e.policyMappings,e.policyConstraints,e.inhibitAnyPolicy]);async function b(e){let t,n,r;try{t=h(e.leaf),n=m(e.intermediates??[]),r=m(e.roots)}catch(e){return I(`issuer_not_found`,`certificate source is malformed or leaf source does not contain exactly one certificate`,0,J({actual:e instanceof Error?e.message:`certificate source is malformed`}))}let i=e.trustAnchors??[],a=e.at??new Date,o=await u(t,n,r,i,a,{failure:I,detail:J}),s=o.chain;if(!o.foundTrustedRoot)return o.failure===void 0?o.missingIssuerAt===void 0?I(`no_trusted_root`,`no trusted root found`,void 0,J({chainCommonNames:s.map(e=>e.subject.values.commonName??`<unnamed>`)})):I(`issuer_not_found`,`issuer certificate not found`,o.missingIssuerAt,ue(s,o.missingIssuerAt)):o.failure;let c=s[s.length-1];return c===void 0?I(`no_trusted_root`,`no trusted root found`):{ok:!0,value:{leaf:t,chain:s,root:c}}}async function x(e){let t=await b(e);return t.ok?t:L(t)}async function ae(e){let t=e.chain,n=e.at??new Date,r=fe(e,t.length);if(!r.ok)return r;let i=t[0];if(i===void 0)return I(`issuer_not_found`,`chain is empty`,0);if(t.length===1&&f(i)&&e.allowSelfSignedLeaf!==!0)return I(`self_signed_leaf_not_allowed`,`self-signed leaf not allowed`,0,J({subjectCommonName:i.subject.values.commonName}));for(let e=0;e<t.length;e+=1){let r=t[e];if(r===void 0)return I(`issuer_not_found`,`chain element missing`,e);if(!p(r,n))return I(`certificate_expired`,`certificate not valid at requested time`,e,J({subjectCommonName:r.subject.values.commonName,expected:z(n),actual:`${z(r.notBefore)}..${z(r.notAfter)}`}));let i=F(r);if(i!==void 0)return I(`unrecognized_critical_extension`,`certificate contains unrecognized critical extension ${i}`,e,J({subjectCommonName:r.subject.values.commonName,actual:i}));if(e===t.length-1)continue;let a=t[e+1];if(a===void 0)return I(`issuer_not_found`,`issuer missing`,e);let o=await g(r,a);if(!o.ok)return I(o.code,o.reason,e,J({subjectCommonName:r.subject.values.commonName,issuerCommonName:a.subject.values.commonName,actual:o.reason}));if(!o.valid)return I(`signature_invalid`,`certificate signature does not verify`,e,J({subjectCommonName:r.subject.values.commonName,issuerCommonName:a.subject.values.commonName}));if(a.basicConstraints?.ca!==!0)return I(`ca_required`,`issuer must be a CA certificate`,e+1,J({subjectCommonName:a.subject.values.commonName}));if(a.keyUsage!==void 0&&!a.keyUsage.flags.includes(`keyCertSign`))return I(`key_cert_sign_required`,`issuer missing keyCertSign`,e+1,J({subjectCommonName:a.subject.values.commonName}));if(r.authorityKeyIdentifier!==void 0&&a.subjectKeyIdentifier!==void 0&&r.authorityKeyIdentifier!==a.subjectKeyIdentifier)return I(`authority_key_identifier_mismatch`,`authorityKeyIdentifier does not match issuer subjectKeyIdentifier`,e,J({subjectCommonName:r.subject.values.commonName,issuerCommonName:a.subject.values.commonName,expected:a.subjectKeyIdentifier,actual:r.authorityKeyIdentifier}))}for(let e=1;e<t.length;e+=1){let n=t[e];if(n===void 0)return I(`issuer_not_found`,`chain element missing`,e);let r=d(t,e),i=n.basicConstraints?.pathLength;if(H(i)&&r>i)return I(`path_length_exceeded`,`path length constraint exceeded`,e,J({subjectCommonName:n.subject.values.commonName,expected:String(i),actual:String(r)}))}let a=re(t,r.value.policy);if(!a.ok)return I(a.error.code,a.error.message,0,J({expected:a.error.details?.expected,actual:a.error.details?.actual}));let o=te(t,r.value.nameConstraints);return o.ok?A(i,e,a.value):o}async function S(e){let t;try{t=B(e.chain)}catch(e){return L(I(`signature_invalid`,`certificate input is malformed`,0,J({actual:e instanceof Error?e.message:`certificate input is malformed`})))}let n=await ae({...e,chain:t});return n.ok?R(n.policyValidation):L(n)}async function C(e){let t=await x({leaf:e.leaf,roots:e.roots,...e.intermediates!==void 0&&{intermediates:e.intermediates},...e.trustAnchors!==void 0&&{trustAnchors:e.trustAnchors},...e.at!==void 0&&{at:e.at}});if(!t.ok)return t;let n=await S({chain:t.value.chain,...e.at!==void 0&&{at:e.at},...e.purpose!==void 0&&{purpose:e.purpose},...q(e),...e.allowSelfSignedLeaf!==void 0&&{allowSelfSignedLeaf:e.allowSelfSignedLeaf}});if(!n.ok)return n;if(e.serviceIdentity!==void 0){let n=j(t.value.leaf,e.serviceIdentity);if(!n.ok)return L(n)}if(e.revocation!==void 0){let n=await ie({chain:t.value.chain,...e.revocation.crls===void 0?{}:{crls:e.revocation.crls},...e.revocation.ocspResponses===void 0?{}:{ocspResponses:e.revocation.ocspResponses},...e.revocation.extraCertificates===void 0?{}:{extraCertificates:e.revocation.extraCertificates},...e.revocation.trustedOcspResponders===void 0?{}:{trustedOcspResponders:e.revocation.trustedOcspResponders},...e.revocation.policy===void 0?{}:{policy:e.revocation.policy},...e.at===void 0?{}:{at:e.at}});if(n.value.decision===`deny`){let e=n.value.summary.revokedCertificates[0];if(e!==void 0)return L(I(`certificate_revoked`,`certificate revoked: ${e.subject.values.commonName??`unknown`}`,void 0,J({subjectCommonName:e.subject.values.commonName})));let t=n.value.summary.indeterminateCertificates[0],r=n.value.certificates.find(e=>e.status===`indeterminate`)?.indeterminateReasons;return L(I(`revocation_indeterminate`,`revocation status indeterminate: ${t?.subject.values.commonName??`unknown`}`,void 0,J({subjectCommonName:t?.subject.values.commonName,actual:r?.join(`, `)})))}}return{ok:!0,value:{...t.value,policyValidation:n.value.policyValidation}}}async function oe(e){let t;try{t=typeof e==`string`?c(e):s(new Uint8Array(e))}catch(e){return U(`signature_invalid`,`certificate request input is malformed`,J({actual:e instanceof Error?e.message:`certificate request input is malformed`}))}let n;try{n=await l(t.signatureAlgorithmOid,t.signatureAlgorithmParametersDer,t.publicKeyAlgorithmOid,t.publicKeyParametersOid,t.subjectPublicKeyInfoDer,t.signatureValue,t.certificationRequestInfoDer)}catch(e){return U(`signature_invalid`,`certificate request input is malformed`,J({subjectCommonName:t.subject.values.commonName,actual:e instanceof Error?e.message:`certificate request input is malformed`}))}return n.ok?n.valid?{ok:!0,value:t}:U(`signature_invalid`,`certificate request signature does not verify`,J({subjectCommonName:t.subject.values.commonName})):U(n.code===`verification_error`?`signature_invalid`:n.code,n.reason,J({subjectCommonName:t.subject.values.commonName,actual:n.reason}))}function w(e,t){let n;try{n=B(e)}catch{return W(`leaf_eku_missing`,`certificate input is malformed`,0)}let r=n[0];if(r===void 0)return W(`leaf_eku_missing`,`chain is empty`,0);if(r.extendedKeyUsage!==void 0&&!r.extendedKeyUsage.includes(t))return W(`leaf_eku_missing`,`leaf certificate does not include EKU ${t}`,0);for(let e=1;e<n.length;e+=1){let r=n[e];if(r!==void 0&&r.extendedKeyUsage!==void 0&&!r.extendedKeyUsage.includes(t))return W(`intermediate_eku_constraint`,`intermediate CA at index ${String(e)} constrains EKU and does not include ${t}`,e)}return{ok:!0,value:void 0}}function se(e){let t;try{t=V(e)}catch{throw Error(`certificate input is malformed`)}return{subject:t.subject,subjectPublicKeyInfoDer:t.subjectPublicKeyInfoDer,publicKeyAlgorithmOid:t.publicKeyAlgorithmOid,...t.publicKeyParametersOid===void 0?{}:{publicKeyParametersOid:t.publicKeyParametersOid},...t.subjectKeyIdentifier===void 0?{}:{subjectKeyIdentifier:t.subjectKeyIdentifier}}}function T(e){return{leaf:e.leaf,roots:e.roots,...e.intermediates!==void 0&&{intermediates:e.intermediates},...e.trustAnchors!==void 0&&{trustAnchors:e.trustAnchors},...e.at!==void 0&&{at:e.at},...q(e)}}async function E(e){let t=await P(e,`serverAuth`);if(!t.ok)return t;if(e.serviceIdentity!==void 0){let n=j(t.value.leaf,e.serviceIdentity);if(!n.ok)return L(n)}return t}async function D(e){return P(e,`clientAuth`)}async function O(e){return P(e,`codeSigning`)}async function k(e){return C({...T(e),purpose:`ca`})}function A(e,t,n){let r=t.purpose;if(r!==void 0){if(r===`ca`){if(e.basicConstraints?.ca!==!0)return I(`ca_required`,`leaf is not a CA certificate`,0,J({subjectCommonName:e.subject.values.commonName}))}else if(e.extendedKeyUsage!==void 0&&!e.extendedKeyUsage.includes(r))return I(`extended_key_usage_invalid`,`leaf missing EKU ${r}`,0,J({subjectCommonName:e.subject.values.commonName,expected:r,actual:e.extendedKeyUsage.map(de).join(`,`)}))}return{ok:!0,policyValidation:n}}function j(e,t){let n=M(t);if(!n.ok)return n;let r=_({certificate:V(e),serviceIdentity:t});if(r.ok)return{ok:!0};let i=r.error;return i.code===`service_identity_mismatch`?{ok:!1,code:`subject_alt_name_mismatch`,message:i.message,index:0,...i.details===void 0?{}:{details:i.details}}:i.code!==`subject_alt_name_mismatch`&&i.code!==`common_name_fallback_suppressed`?I(`subject_alt_name_mismatch`,`service identity input is malformed`,0,J({expected:t.value,actual:i.code})):{ok:!1,code:i.code,message:i.message,index:0,...i.details===void 0?{}:{details:i.details}}}function M(e){if(!$(e))return I(`subject_alt_name_mismatch`,`service identity input is malformed`,0);if(e.type!==`dns`&&e.type!==`ip`&&e.type!==`uri`&&e.type!==`srv`)return I(`subject_alt_name_mismatch`,`service identity input is malformed`,0,J({actual:String(e.type)}));if(typeof e.value!=`string`)return I(`subject_alt_name_mismatch`,`service identity input is malformed`,0,J({actual:e.type}));if(e.type===`ip`)try{a(e.value)}catch{return I(`subject_alt_name_mismatch`,`service identity input is malformed`,0,J({expected:e.value,actual:`ip`}))}return{ok:!0}}function N(e,t){let n=w(e.value.chain,t);return n.ok?e:L(I(n.code===`leaf_eku_missing`?`extended_key_usage_invalid`:`intermediate_eku_constraint`,n.message,n.index))}async function P(e,t){let n=await C(T(e));return n.ok?N(n,t):n}function F(e){for(let t of e.extensions)if(t.critical&&!y.has(t.oid))return t.oid}function I(e,t,n,i){return{ok:!1,...r(e,t,n,i)}}function L(e){return n(e)}function R(e){return{ok:!0,value:{policyValidation:e}}}function z(e){return Number.isNaN(e.getTime())?`<invalid date>`:e.toISOString()}function B(e){return e.map(V)}function V(e){return o(new Uint8Array(e.der))}function H(e){return e!==void 0&&Number.isInteger(e)&&e>=0}function U(e,n,r){return t({ok:!1,...i(e,n,r)})}function W(e,t,i){return n({ok:!1,...r(e,t,i),index:i})}function G(e){let t=Y(e.initialPolicySet),n=Y(e.policy?.initialPolicySet);return{...t===void 0?{}:{initialPolicySet:t},...e.requireExplicitPolicy===void 0?{}:{requireExplicitPolicy:e.requireExplicitPolicy},...e.inhibitPolicyMapping===void 0?{}:{inhibitPolicyMapping:e.inhibitPolicyMapping},...e.inhibitAnyPolicy===void 0?{}:{inhibitAnyPolicy:e.inhibitAnyPolicy},...n===void 0?{}:{initialPolicySet:n},...e.policy?.requireExplicitPolicy===void 0?{}:{requireExplicitPolicy:e.policy.requireExplicitPolicy},...e.policy?.inhibitPolicyMapping===void 0?{}:{inhibitPolicyMapping:e.policy.inhibitPolicyMapping},...e.policy?.inhibitAnyPolicy===void 0?{}:{inhibitAnyPolicy:e.policy.inhibitAnyPolicy}}}function K(e){return{...e.permittedSubtrees===void 0?{}:{permittedSubtrees:e.permittedSubtrees},...e.excludedSubtrees===void 0?{}:{excludedSubtrees:e.excludedSubtrees},...e.nameConstraints?.permittedSubtrees===void 0?{}:{permittedSubtrees:e.nameConstraints.permittedSubtrees},...e.nameConstraints?.excludedSubtrees===void 0?{}:{excludedSubtrees:e.nameConstraints.excludedSubtrees}}}function q(e){let t=G(e),n=K(e);return{...ce(t)?{policy:t}:{},...le(n)?{nameConstraints:n}:{}}}function ce(e){return e.initialPolicySet!==void 0||e.requireExplicitPolicy!==void 0||e.inhibitPolicyMapping!==void 0||e.inhibitAnyPolicy!==void 0}function le(e){return e.permittedSubtrees!==void 0||e.excludedSubtrees!==void 0}function ue(e,t){let n=e[t];return J({subjectCommonName:n?.subject.values.commonName,issuerCommonName:n?.issuer.values.commonName,chainCommonNames:e.map(e=>e.subject.values.commonName??`<unnamed>`)})}function de(e){return typeof e==`string`?e:e.value}function J(e){return{...e.subjectCommonName===void 0?{}:{subjectCommonName:e.subjectCommonName},...e.issuerCommonName===void 0?{}:{issuerCommonName:e.issuerCommonName},...e.expected===void 0?{}:{expected:e.expected},...e.actual===void 0?{}:{actual:e.actual},...e.chainCommonNames===void 0?{}:{chainCommonNames:e.chainCommonNames},...e.presentedIdentifierTypes===void 0?{}:{presentedIdentifierTypes:e.presentedIdentifierTypes},...e.commonNameFallbackReason===void 0?{}:{commonNameFallbackReason:e.commonNameFallbackReason}}}function fe(e,t){let n=ne(G(e),t),r=X(K(e));return r.ok?{ok:!0,value:{policy:n,nameConstraints:ee(r.value)}}:r}function Y(e){return e===void 0||e===`any`||Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:[]}function X(e){let t=Z(e.permittedSubtrees,`permittedSubtrees`);if(!t.ok)return t;let n=Z(e.excludedSubtrees,`excludedSubtrees`);return n.ok?{ok:!0,value:e}:n}function Z(e,t){if(e===void 0)return{ok:!0};if(!Array.isArray(e))return Q(t);for(let t of e){let e=pe(t);if(e!==void 0)return Q(e)}return{ok:!0}}function pe(e){if(!$(e))return`invalid subtree`;let t=e.base;if(!$(t)||typeof t.type!=`string`)return`invalid subtree`;switch(t.type){case`dns`:case`email`:case`uri`:return typeof t.value==`string`?void 0:t.type;case`directoryName`:return typeof t.derHex==`string`?void 0:t.type;case`ip`:return t.addressBytes instanceof Uint8Array&&t.maskBytes instanceof Uint8Array?void 0:t.type;case`otherName`:case`x400Address`:case`ediPartyName`:case`registeredID`:return t.type;default:return t.type}}function Q(e){return I(`unsupported_initial_name_constraints`,`initial name constraints use unsupported or malformed forms`,void 0,J({actual:e}))}function $(e){return typeof e==`object`&&!!e}export{v as VERIFY_ERROR_CODES,x as buildCandidatePath,w as checkExtendedKeyUsage,se as trustAnchorFromCertificate,S as validateCandidatePath,k as validateForCa,O as validateForCodeSigning,D as validateForTlsClient,E as validateForTlsServer,C as verifyCertificateChain,oe as verifyCertificateSigningRequest};
|
|
2
|
-
|
|
1
|
+
import { OIDS } from "../internal/asn1/oids.js";
|
|
2
|
+
import { errorResult, indexedErrorResult, indexedMicro509Error, micro509Error } from "../result/result.js";
|
|
3
|
+
import { parseIpAddressToBytes } from "../internal/shared/ip.js";
|
|
4
|
+
import { parseCertificateDerOrThrow, parseCertificateSigningRequestDerOrThrow, parseCertificateSigningRequestPemOrThrow } from "../x509/parse.js";
|
|
5
|
+
import { verifySignedDataDetailed } from "../internal/crypto/sig-verify.js";
|
|
6
|
+
import { createNameConstraintValidationState, evaluateNameConstraints } from "../internal/verify/name-constraints-engine.js";
|
|
7
|
+
import { createPolicyValidationState, evaluatePolicyChain } from "../internal/verify/policy-engine.js";
|
|
8
|
+
import { buildChainInternal, countCaCertificatesBelowParsed, isSelfIssued, isWithinValidity, loadCertificates, loadSingleCertificate, verifyCertificateSignature } from "../internal/verify/verify-path.js";
|
|
9
|
+
import { checkChainRevocation } from "../revocation/chain.js";
|
|
10
|
+
import { matchServiceIdentity } from "./identity.js";
|
|
11
|
+
//#region src/verify/verify.ts
|
|
12
|
+
/**
|
|
13
|
+
* Public certificate and CSR verification APIs.
|
|
14
|
+
*
|
|
15
|
+
* Builds and validates certificate paths per RFC 5280 §6, enforcing purpose
|
|
16
|
+
* constraints, policy state, name constraints, and optional service identity
|
|
17
|
+
* checks against a leaf certificate.
|
|
18
|
+
*
|
|
19
|
+
* Three levels of granularity:
|
|
20
|
+
* - {@linkcode buildCandidatePath} — signature-verified path only
|
|
21
|
+
* - {@linkcode validateCandidatePath} — time/constraint/policy validation on a pre-built path
|
|
22
|
+
* - {@linkcode verifyCertificateChain} — all-in-one build + validate
|
|
23
|
+
*
|
|
24
|
+
* Purpose-scoped convenience wrappers: {@linkcode validateForTlsServer},
|
|
25
|
+
* {@linkcode validateForTlsClient}, {@linkcode validateForCodeSigning}, {@linkcode validateForCa}.
|
|
26
|
+
*
|
|
27
|
+
* @module
|
|
28
|
+
*/
|
|
29
|
+
/**
|
|
30
|
+
* Discriminant for every failure a verify operation can produce.
|
|
31
|
+
*
|
|
32
|
+
* - `no_trusted_root` — chain could not be anchored to any root or {@linkcode TrustAnchor}.
|
|
33
|
+
* - `issuer_not_found` — an intermediate's issuer was not in the candidate set.
|
|
34
|
+
* - `signature_invalid` — a certificate's signature failed cryptographic verification.
|
|
35
|
+
* - `certificate_expired` — a certificate's notBefore/notAfter window excludes the validation time.
|
|
36
|
+
* - `ca_required` — an issuer lacks `basicConstraints.ca = true`.
|
|
37
|
+
* - `key_cert_sign_required` — an issuer has keyUsage but omits `keyCertSign`.
|
|
38
|
+
* - `path_length_exceeded` — the number of CA certificates below an issuer exceeds its pathLength.
|
|
39
|
+
* - `authority_key_identifier_mismatch` — a certificate's AKI does not match the issuer's SKI.
|
|
40
|
+
* - `extended_key_usage_invalid` — the leaf certificate lacks the required EKU for the requested purpose.
|
|
41
|
+
* - `subject_alt_name_mismatch` — no SAN entry matches the requested service identity.
|
|
42
|
+
* - `common_name_fallback_suppressed` — CN fallback was attempted but suppressed (SAN present or disabled).
|
|
43
|
+
* - `self_signed_leaf_not_allowed` — the leaf is self-signed and `allowSelfSignedLeaf` was not set.
|
|
44
|
+
* - `unrecognized_critical_extension` — a certificate contains a critical extension the verifier cannot process.
|
|
45
|
+
* - `intermediate_eku_constraint` — an intermediate CA's EKU set does not include the required purpose.
|
|
46
|
+
* - `explicit_policy_required` — `requireExplicitPolicy` was set but no acceptable policy was found.
|
|
47
|
+
* - `initial_policy_set_not_satisfied` — the chain's policies do not intersect `initialPolicySet`.
|
|
48
|
+
* - `unsupported_initial_name_constraints` — caller-supplied initial name constraints use unsupported or malformed forms.
|
|
49
|
+
* - `unsupported_name_constraints` — a certificate's nameConstraints use an unsupported form.
|
|
50
|
+
* - `name_constraints_violated` — a subject name violates a permitted/excluded subtree.
|
|
51
|
+
* - `unsupported_signature_algorithm_parameters` — the signature algorithm uses unrecognized parameters.
|
|
52
|
+
* - `certificate_revoked` — revocation evidence confirms a chain certificate is revoked.
|
|
53
|
+
* - `revocation_indeterminate` — revocation status could not be determined under a hard-fail policy.
|
|
54
|
+
*/
|
|
55
|
+
const VERIFY_ERROR_CODES = [
|
|
56
|
+
"no_trusted_root",
|
|
57
|
+
"issuer_not_found",
|
|
58
|
+
"signature_invalid",
|
|
59
|
+
"certificate_expired",
|
|
60
|
+
"ca_required",
|
|
61
|
+
"key_cert_sign_required",
|
|
62
|
+
"path_length_exceeded",
|
|
63
|
+
"authority_key_identifier_mismatch",
|
|
64
|
+
"extended_key_usage_invalid",
|
|
65
|
+
"subject_alt_name_mismatch",
|
|
66
|
+
"common_name_fallback_suppressed",
|
|
67
|
+
"self_signed_leaf_not_allowed",
|
|
68
|
+
"unrecognized_critical_extension",
|
|
69
|
+
"intermediate_eku_constraint",
|
|
70
|
+
"explicit_policy_required",
|
|
71
|
+
"initial_policy_set_not_satisfied",
|
|
72
|
+
"unsupported_initial_name_constraints",
|
|
73
|
+
"unsupported_name_constraints",
|
|
74
|
+
"name_constraints_violated",
|
|
75
|
+
"unsupported_signature_algorithm_parameters",
|
|
76
|
+
"certificate_revoked",
|
|
77
|
+
"revocation_indeterminate"
|
|
78
|
+
];
|
|
79
|
+
/**
|
|
80
|
+
* OIDs of extensions this verifier processes during path validation.
|
|
81
|
+
* Per RFC 5280 §6.1, certificates with unrecognized critical extensions
|
|
82
|
+
* that are not in this set must be rejected.
|
|
83
|
+
*/
|
|
84
|
+
const PROCESSED_EXTENSION_OIDS = /* @__PURE__ */ new Set([
|
|
85
|
+
OIDS.basicConstraints,
|
|
86
|
+
OIDS.keyUsage,
|
|
87
|
+
OIDS.extendedKeyUsage,
|
|
88
|
+
OIDS.subjectAltName,
|
|
89
|
+
OIDS.nameConstraints,
|
|
90
|
+
OIDS.authorityKeyIdentifier,
|
|
91
|
+
OIDS.subjectKeyIdentifier,
|
|
92
|
+
OIDS.authorityInfoAccess,
|
|
93
|
+
OIDS.cRLDistributionPoints,
|
|
94
|
+
OIDS.certificatePolicies,
|
|
95
|
+
OIDS.policyMappings,
|
|
96
|
+
OIDS.policyConstraints,
|
|
97
|
+
OIDS.inhibitAnyPolicy
|
|
98
|
+
]);
|
|
99
|
+
/**
|
|
100
|
+
* Discovers and signature-verifies a candidate certification path from a
|
|
101
|
+
* leaf certificate to a trusted root or trust anchor. Does NOT validate
|
|
102
|
+
* time, constraints, or leaf policy — use {@linkcode validateCandidatePath}
|
|
103
|
+
* for that, or {@linkcode verifyCertificateChain} for the all-in-one API.
|
|
104
|
+
*/
|
|
105
|
+
async function buildCandidatePathRaw(input) {
|
|
106
|
+
let leaf;
|
|
107
|
+
let intermediates;
|
|
108
|
+
let roots;
|
|
109
|
+
try {
|
|
110
|
+
leaf = loadSingleCertificate(input.leaf);
|
|
111
|
+
intermediates = loadCertificates(input.intermediates ?? []);
|
|
112
|
+
roots = loadCertificates(input.roots);
|
|
113
|
+
} catch (error) {
|
|
114
|
+
return failure("issuer_not_found", "certificate source is malformed or leaf source does not contain exactly one certificate", 0, detail({ actual: error instanceof Error ? error.message : "certificate source is malformed" }));
|
|
115
|
+
}
|
|
116
|
+
const anchors = input.trustAnchors ?? [];
|
|
117
|
+
const at = input.at ?? /* @__PURE__ */ new Date();
|
|
118
|
+
const buildResult = await buildChainInternal(leaf, intermediates, roots, anchors, at, {
|
|
119
|
+
failure,
|
|
120
|
+
detail
|
|
121
|
+
});
|
|
122
|
+
const chain = buildResult.chain;
|
|
123
|
+
if (!buildResult.foundTrustedRoot) {
|
|
124
|
+
if (buildResult.failure !== void 0) return buildResult.failure;
|
|
125
|
+
if (buildResult.missingIssuerAt !== void 0) return failure("issuer_not_found", "issuer certificate not found", buildResult.missingIssuerAt, buildFailureDetails(chain, buildResult.missingIssuerAt));
|
|
126
|
+
return failure("no_trusted_root", "no trusted root found", void 0, detail({ chainCommonNames: chain.map((certificate) => certificate.subject.values.commonName ?? "<unnamed>") }));
|
|
127
|
+
}
|
|
128
|
+
const root = chain[chain.length - 1];
|
|
129
|
+
if (root === void 0) return failure("no_trusted_root", "no trusted root found");
|
|
130
|
+
return {
|
|
131
|
+
ok: true,
|
|
132
|
+
value: {
|
|
133
|
+
leaf,
|
|
134
|
+
chain,
|
|
135
|
+
root
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Builds a signature-verified path from a leaf certificate to a trusted root.
|
|
141
|
+
*
|
|
142
|
+
* Parses the supplied certificates, walks the issuer chain, signature-checks
|
|
143
|
+
* each link, and returns the first valid path. Does not enforce time, constraints,
|
|
144
|
+
* or leaf purpose — call {@linkcode validateCandidatePath} or use the all-in-one
|
|
145
|
+
* {@linkcode verifyCertificateChain} for full validation.
|
|
146
|
+
*
|
|
147
|
+
* @example
|
|
148
|
+
* ```ts
|
|
149
|
+
* import { buildCandidatePath } from 'micro509';
|
|
150
|
+
*
|
|
151
|
+
* const result = await buildCandidatePath({
|
|
152
|
+
* leaf: leafPem,
|
|
153
|
+
* intermediates: [intermediatePem],
|
|
154
|
+
* roots: [rootPem],
|
|
155
|
+
* });
|
|
156
|
+
* if (result.ok) {
|
|
157
|
+
* console.log('path length:', result.value.chain.length);
|
|
158
|
+
* }
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
161
|
+
async function buildCandidatePath(input) {
|
|
162
|
+
const result = await buildCandidatePathRaw(input);
|
|
163
|
+
return result.ok ? result : verifyFailureResult(result);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Validates a pre-built candidate path: time window, critical extensions,
|
|
167
|
+
* inter-certificate signatures, CA/keyUsage/AKI constraints, pathLength,
|
|
168
|
+
* policy processing, name constraints, and leaf purpose checks.
|
|
169
|
+
*
|
|
170
|
+
* The chain must be in leaf-to-root order. The root (last entry) is
|
|
171
|
+
* assumed trusted and not re-verified.
|
|
172
|
+
*/
|
|
173
|
+
async function validateCandidatePathRaw(input) {
|
|
174
|
+
const chain = input.chain;
|
|
175
|
+
const at = input.at ?? /* @__PURE__ */ new Date();
|
|
176
|
+
const validationStateResult = buildValidationState(input, chain.length);
|
|
177
|
+
if (!validationStateResult.ok) return validationStateResult;
|
|
178
|
+
const leaf = chain[0];
|
|
179
|
+
if (leaf === void 0) return failure("issuer_not_found", "chain is empty", 0);
|
|
180
|
+
if (chain.length === 1 && isSelfIssued(leaf)) {
|
|
181
|
+
if (input.allowSelfSignedLeaf !== true) return failure("self_signed_leaf_not_allowed", "self-signed leaf not allowed", 0, detail({ subjectCommonName: leaf.subject.values.commonName }));
|
|
182
|
+
}
|
|
183
|
+
for (let index = 0; index < chain.length; index += 1) {
|
|
184
|
+
const current = chain[index];
|
|
185
|
+
if (current === void 0) return failure("issuer_not_found", "chain element missing", index);
|
|
186
|
+
if (!isWithinValidity(current, at)) return failure("certificate_expired", "certificate not valid at requested time", index, detail({
|
|
187
|
+
subjectCommonName: current.subject.values.commonName,
|
|
188
|
+
expected: describeDateTime(at),
|
|
189
|
+
actual: `${describeDateTime(current.notBefore)}..${describeDateTime(current.notAfter)}`
|
|
190
|
+
}));
|
|
191
|
+
const unprocessedCritical = findUnprocessedCriticalExtension(current);
|
|
192
|
+
if (unprocessedCritical !== void 0) return failure("unrecognized_critical_extension", `certificate contains unrecognized critical extension ${unprocessedCritical}`, index, detail({
|
|
193
|
+
subjectCommonName: current.subject.values.commonName,
|
|
194
|
+
actual: unprocessedCritical
|
|
195
|
+
}));
|
|
196
|
+
if (index === chain.length - 1) continue;
|
|
197
|
+
const issuer = chain[index + 1];
|
|
198
|
+
if (issuer === void 0) return failure("issuer_not_found", "issuer missing", index);
|
|
199
|
+
const signatureResult = await verifyCertificateSignature(current, issuer);
|
|
200
|
+
if (!signatureResult.ok) return failure(signatureResult.code, signatureResult.reason, index, detail({
|
|
201
|
+
subjectCommonName: current.subject.values.commonName,
|
|
202
|
+
issuerCommonName: issuer.subject.values.commonName,
|
|
203
|
+
actual: signatureResult.reason
|
|
204
|
+
}));
|
|
205
|
+
if (!signatureResult.valid) return failure("signature_invalid", "certificate signature does not verify", index, detail({
|
|
206
|
+
subjectCommonName: current.subject.values.commonName,
|
|
207
|
+
issuerCommonName: issuer.subject.values.commonName
|
|
208
|
+
}));
|
|
209
|
+
if (issuer.basicConstraints?.ca !== true) return failure("ca_required", "issuer must be a CA certificate", index + 1, detail({ subjectCommonName: issuer.subject.values.commonName }));
|
|
210
|
+
if (issuer.keyUsage !== void 0 && !issuer.keyUsage.flags.includes("keyCertSign")) return failure("key_cert_sign_required", "issuer missing keyCertSign", index + 1, detail({ subjectCommonName: issuer.subject.values.commonName }));
|
|
211
|
+
if (current.authorityKeyIdentifier !== void 0 && issuer.subjectKeyIdentifier !== void 0 && current.authorityKeyIdentifier !== issuer.subjectKeyIdentifier) return failure("authority_key_identifier_mismatch", "authorityKeyIdentifier does not match issuer subjectKeyIdentifier", index, detail({
|
|
212
|
+
subjectCommonName: current.subject.values.commonName,
|
|
213
|
+
issuerCommonName: issuer.subject.values.commonName,
|
|
214
|
+
expected: issuer.subjectKeyIdentifier,
|
|
215
|
+
actual: current.authorityKeyIdentifier
|
|
216
|
+
}));
|
|
217
|
+
}
|
|
218
|
+
for (let index = 1; index < chain.length; index += 1) {
|
|
219
|
+
const current = chain[index];
|
|
220
|
+
if (current === void 0) return failure("issuer_not_found", "chain element missing", index);
|
|
221
|
+
const maxCaBelow = countCaCertificatesBelowParsed(chain, index);
|
|
222
|
+
const pathLength = current.basicConstraints?.pathLength;
|
|
223
|
+
if (isNonNegativeInteger(pathLength) && maxCaBelow > pathLength) return failure("path_length_exceeded", "path length constraint exceeded", index, detail({
|
|
224
|
+
subjectCommonName: current.subject.values.commonName,
|
|
225
|
+
expected: String(pathLength),
|
|
226
|
+
actual: String(maxCaBelow)
|
|
227
|
+
}));
|
|
228
|
+
}
|
|
229
|
+
const policyResult = evaluatePolicyChain(chain, validationStateResult.value.policy);
|
|
230
|
+
if (!policyResult.ok) return failure(policyResult.error.code, policyResult.error.message, 0, detail({
|
|
231
|
+
expected: policyResult.error.details?.expected,
|
|
232
|
+
actual: policyResult.error.details?.actual
|
|
233
|
+
}));
|
|
234
|
+
const nameConstraintResult = evaluateNameConstraints(chain, validationStateResult.value.nameConstraints);
|
|
235
|
+
if (!nameConstraintResult.ok) return nameConstraintResult;
|
|
236
|
+
return validateLeaf(leaf, input, policyResult.value);
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Validates a pre-built certificate chain for time, constraints, policy, and
|
|
240
|
+
* optionally leaf purpose. Wrap the result of {@linkcode buildCandidatePath}.
|
|
241
|
+
*/
|
|
242
|
+
async function validateCandidatePath(input) {
|
|
243
|
+
let normalizedChain;
|
|
244
|
+
try {
|
|
245
|
+
normalizedChain = normalizeValidationChain(input.chain);
|
|
246
|
+
} catch (error) {
|
|
247
|
+
return verifyFailureResult(failure("signature_invalid", "certificate input is malformed", 0, detail({ actual: error instanceof Error ? error.message : "certificate input is malformed" })));
|
|
248
|
+
}
|
|
249
|
+
const result = await validateCandidatePathRaw({
|
|
250
|
+
...input,
|
|
251
|
+
chain: normalizedChain
|
|
252
|
+
});
|
|
253
|
+
return result.ok ? validateCandidatePathSuccessResult(result.policyValidation) : verifyFailureResult(result);
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* All-in-one certificate chain verification: builds a candidate path then
|
|
257
|
+
* validates time, constraints, policy, purpose, and optional service identity.
|
|
258
|
+
*
|
|
259
|
+
* Equivalent to calling {@linkcode buildCandidatePath} followed by
|
|
260
|
+
* {@linkcode validateCandidatePath} (plus identity matching when configured).
|
|
261
|
+
*
|
|
262
|
+
* @example
|
|
263
|
+
* ```ts
|
|
264
|
+
* import { verifyCertificateChain } from 'micro509';
|
|
265
|
+
*
|
|
266
|
+
* const result = await verifyCertificateChain({
|
|
267
|
+
* leaf: serverCertPem,
|
|
268
|
+
* intermediates: [intermediatePem],
|
|
269
|
+
* roots: [rootCaPem],
|
|
270
|
+
* purpose: 'serverAuth',
|
|
271
|
+
* serviceIdentity: { type: 'dns', value: 'example.com' },
|
|
272
|
+
* });
|
|
273
|
+
* if (!result.ok) {
|
|
274
|
+
* console.error(result.error.code, result.error.message);
|
|
275
|
+
* }
|
|
276
|
+
* ```
|
|
277
|
+
*/
|
|
278
|
+
async function verifyCertificateChain(input) {
|
|
279
|
+
const buildResult = await buildCandidatePath({
|
|
280
|
+
leaf: input.leaf,
|
|
281
|
+
roots: input.roots,
|
|
282
|
+
...input.intermediates !== void 0 && { intermediates: input.intermediates },
|
|
283
|
+
...input.trustAnchors !== void 0 && { trustAnchors: input.trustAnchors },
|
|
284
|
+
...input.at !== void 0 && { at: input.at }
|
|
285
|
+
});
|
|
286
|
+
if (!buildResult.ok) return buildResult;
|
|
287
|
+
const validateResult = await validateCandidatePath({
|
|
288
|
+
chain: buildResult.value.chain,
|
|
289
|
+
...input.at !== void 0 && { at: input.at },
|
|
290
|
+
...input.purpose !== void 0 && { purpose: input.purpose },
|
|
291
|
+
...copyValidationInputs(input),
|
|
292
|
+
...input.allowSelfSignedLeaf !== void 0 && { allowSelfSignedLeaf: input.allowSelfSignedLeaf }
|
|
293
|
+
});
|
|
294
|
+
if (!validateResult.ok) return validateResult;
|
|
295
|
+
if (input.serviceIdentity !== void 0) {
|
|
296
|
+
const serviceIdentityResult = validateServiceIdentity(buildResult.value.leaf, input.serviceIdentity);
|
|
297
|
+
if (!serviceIdentityResult.ok) return verifyFailureResult(serviceIdentityResult);
|
|
298
|
+
}
|
|
299
|
+
if (input.revocation !== void 0) {
|
|
300
|
+
const revocationResult = await checkChainRevocation({
|
|
301
|
+
chain: buildResult.value.chain,
|
|
302
|
+
...input.revocation.crls !== void 0 ? { crls: input.revocation.crls } : {},
|
|
303
|
+
...input.revocation.ocspResponses !== void 0 ? { ocspResponses: input.revocation.ocspResponses } : {},
|
|
304
|
+
...input.revocation.extraCertificates !== void 0 ? { extraCertificates: input.revocation.extraCertificates } : {},
|
|
305
|
+
...input.revocation.trustedOcspResponders !== void 0 ? { trustedOcspResponders: input.revocation.trustedOcspResponders } : {},
|
|
306
|
+
...input.revocation.policy !== void 0 ? { policy: input.revocation.policy } : {},
|
|
307
|
+
...input.at !== void 0 ? { at: input.at } : {}
|
|
308
|
+
});
|
|
309
|
+
if (revocationResult.value.decision === "deny") {
|
|
310
|
+
const firstRevoked = revocationResult.value.summary.revokedCertificates[0];
|
|
311
|
+
if (firstRevoked !== void 0) return verifyFailureResult(failure("certificate_revoked", `certificate revoked: ${firstRevoked.subject.values.commonName ?? "unknown"}`, void 0, detail({ subjectCommonName: firstRevoked.subject.values.commonName })));
|
|
312
|
+
const firstIndeterminate = revocationResult.value.summary.indeterminateCertificates[0];
|
|
313
|
+
const indeterminateReasons = revocationResult.value.certificates.find((c) => c.status === "indeterminate")?.indeterminateReasons;
|
|
314
|
+
return verifyFailureResult(failure("revocation_indeterminate", `revocation status indeterminate: ${firstIndeterminate?.subject.values.commonName ?? "unknown"}`, void 0, detail({
|
|
315
|
+
subjectCommonName: firstIndeterminate?.subject.values.commonName,
|
|
316
|
+
actual: indeterminateReasons?.join(", ")
|
|
317
|
+
})));
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return {
|
|
321
|
+
ok: true,
|
|
322
|
+
value: {
|
|
323
|
+
...buildResult.value,
|
|
324
|
+
policyValidation: validateResult.value.policyValidation
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Verifies the self-signature of a PKCS#10 certificate signing request.
|
|
330
|
+
*
|
|
331
|
+
* Parses the CSR from PEM or DER, then checks that its signature is valid
|
|
332
|
+
* against its own embedded public key.
|
|
333
|
+
*
|
|
334
|
+
* @example
|
|
335
|
+
* ```ts
|
|
336
|
+
* import { verifyCertificateSigningRequest } from 'micro509';
|
|
337
|
+
*
|
|
338
|
+
* const result = await verifyCertificateSigningRequest(csrPem);
|
|
339
|
+
* if (result.ok) {
|
|
340
|
+
* console.log('subject:', result.value.subject.values.commonName);
|
|
341
|
+
* }
|
|
342
|
+
* ```
|
|
343
|
+
*/
|
|
344
|
+
async function verifyCertificateSigningRequest(input) {
|
|
345
|
+
let parsed;
|
|
346
|
+
try {
|
|
347
|
+
parsed = typeof input === "string" ? parseCertificateSigningRequestPemOrThrow(input) : parseCertificateSigningRequestDerOrThrow(new Uint8Array(input));
|
|
348
|
+
} catch (error) {
|
|
349
|
+
return verifyRequestFailureResult("signature_invalid", "certificate request input is malformed", detail({ actual: error instanceof Error ? error.message : "certificate request input is malformed" }));
|
|
350
|
+
}
|
|
351
|
+
let signatureResult;
|
|
352
|
+
try {
|
|
353
|
+
signatureResult = await verifySignedDataDetailed(parsed.signatureAlgorithmOid, parsed.signatureAlgorithmParametersDer, parsed.publicKeyAlgorithmOid, parsed.publicKeyParametersOid, parsed.subjectPublicKeyInfoDer, parsed.signatureValue, parsed.certificationRequestInfoDer);
|
|
354
|
+
} catch (error) {
|
|
355
|
+
return verifyRequestFailureResult("signature_invalid", "certificate request input is malformed", detail({
|
|
356
|
+
subjectCommonName: parsed.subject.values.commonName,
|
|
357
|
+
actual: error instanceof Error ? error.message : "certificate request input is malformed"
|
|
358
|
+
}));
|
|
359
|
+
}
|
|
360
|
+
if (!signatureResult.ok) return verifyRequestFailureResult(signatureResult.code === "verification_error" ? "signature_invalid" : signatureResult.code, signatureResult.reason, detail({
|
|
361
|
+
subjectCommonName: parsed.subject.values.commonName,
|
|
362
|
+
actual: signatureResult.reason
|
|
363
|
+
}));
|
|
364
|
+
if (!signatureResult.valid) return verifyRequestFailureResult("signature_invalid", "certificate request signature does not verify", detail({ subjectCommonName: parsed.subject.values.commonName }));
|
|
365
|
+
return {
|
|
366
|
+
ok: true,
|
|
367
|
+
value: parsed
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Standalone EKU check against a verified certificate chain.
|
|
372
|
+
* Validates that the leaf has the requested purpose and that
|
|
373
|
+
* intermediate CA EKU constraints (if present) permit it.
|
|
374
|
+
*
|
|
375
|
+
* @example
|
|
376
|
+
* ```ts
|
|
377
|
+
* import { checkExtendedKeyUsage } from 'micro509';
|
|
378
|
+
*
|
|
379
|
+
* const result = checkExtendedKeyUsage(chain, 'serverAuth');
|
|
380
|
+
* if (!result.ok) {
|
|
381
|
+
* console.error(result.error.code, result.error.message);
|
|
382
|
+
* }
|
|
383
|
+
* ```
|
|
384
|
+
*/
|
|
385
|
+
function checkExtendedKeyUsage(chain, purpose) {
|
|
386
|
+
let normalizedChain;
|
|
387
|
+
try {
|
|
388
|
+
normalizedChain = normalizeValidationChain(chain);
|
|
389
|
+
} catch {
|
|
390
|
+
return ekuCheckFailureResult("leaf_eku_missing", "certificate input is malformed", 0);
|
|
391
|
+
}
|
|
392
|
+
const leaf = normalizedChain[0];
|
|
393
|
+
if (leaf === void 0) return ekuCheckFailureResult("leaf_eku_missing", "chain is empty", 0);
|
|
394
|
+
if (leaf.extendedKeyUsage !== void 0 && !leaf.extendedKeyUsage.includes(purpose)) return ekuCheckFailureResult("leaf_eku_missing", `leaf certificate does not include EKU ${purpose}`, 0);
|
|
395
|
+
for (let index = 1; index < normalizedChain.length; index += 1) {
|
|
396
|
+
const intermediate = normalizedChain[index];
|
|
397
|
+
if (intermediate === void 0) continue;
|
|
398
|
+
if (intermediate.extendedKeyUsage !== void 0 && !intermediate.extendedKeyUsage.includes(purpose)) return ekuCheckFailureResult("intermediate_eku_constraint", `intermediate CA at index ${String(index)} constrains EKU and does not include ${purpose}`, index);
|
|
399
|
+
}
|
|
400
|
+
return {
|
|
401
|
+
ok: true,
|
|
402
|
+
value: void 0
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
/** Extracts a {@linkcode TrustAnchor} from a parsed certificate, copying the subject, SPKI, and key identifiers. */
|
|
406
|
+
function trustAnchorFromCertificate(certificate) {
|
|
407
|
+
let normalizedCertificate;
|
|
408
|
+
try {
|
|
409
|
+
normalizedCertificate = reparseCertificateForTrust(certificate);
|
|
410
|
+
} catch {
|
|
411
|
+
throw new Error("certificate input is malformed");
|
|
412
|
+
}
|
|
413
|
+
return {
|
|
414
|
+
subject: normalizedCertificate.subject,
|
|
415
|
+
subjectPublicKeyInfoDer: normalizedCertificate.subjectPublicKeyInfoDer,
|
|
416
|
+
publicKeyAlgorithmOid: normalizedCertificate.publicKeyAlgorithmOid,
|
|
417
|
+
...normalizedCertificate.publicKeyParametersOid === void 0 ? {} : { publicKeyParametersOid: normalizedCertificate.publicKeyParametersOid },
|
|
418
|
+
...normalizedCertificate.subjectKeyIdentifier === void 0 ? {} : { subjectKeyIdentifier: normalizedCertificate.subjectKeyIdentifier }
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
/** Extracts defined optional fields from a base input for safe forwarding. */
|
|
422
|
+
function baseChainInput(input) {
|
|
423
|
+
return {
|
|
424
|
+
leaf: input.leaf,
|
|
425
|
+
roots: input.roots,
|
|
426
|
+
...input.intermediates !== void 0 && { intermediates: input.intermediates },
|
|
427
|
+
...input.trustAnchors !== void 0 && { trustAnchors: input.trustAnchors },
|
|
428
|
+
...input.at !== void 0 && { at: input.at },
|
|
429
|
+
...copyValidationInputs(input)
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Validates a certificate chain for TLS server use:
|
|
434
|
+
* chain verification + `serverAuth` EKU (leaf + intermediate propagation)
|
|
435
|
+
* + DNS/IP identity matching.
|
|
436
|
+
*
|
|
437
|
+
* @example
|
|
438
|
+
* ```ts
|
|
439
|
+
* import { validateForTlsServer } from 'micro509';
|
|
440
|
+
*
|
|
441
|
+
* const result = await validateForTlsServer({
|
|
442
|
+
* leaf: serverCertPem,
|
|
443
|
+
* roots: [rootCaPem],
|
|
444
|
+
* serviceIdentity: { type: 'dns', value: 'example.com' },
|
|
445
|
+
* });
|
|
446
|
+
* if (result.ok) {
|
|
447
|
+
* console.log('valid for', result.value.leaf.subject.values.commonName);
|
|
448
|
+
* }
|
|
449
|
+
* ```
|
|
450
|
+
*/
|
|
451
|
+
async function validateForTlsServer(input) {
|
|
452
|
+
const result = await verifyChainForExtendedKeyUsageProfile(input, "serverAuth");
|
|
453
|
+
if (!result.ok) return result;
|
|
454
|
+
if (input.serviceIdentity !== void 0) {
|
|
455
|
+
const serviceIdentityResult = validateServiceIdentity(result.value.leaf, input.serviceIdentity);
|
|
456
|
+
if (!serviceIdentityResult.ok) return verifyFailureResult(serviceIdentityResult);
|
|
457
|
+
}
|
|
458
|
+
return result;
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Validates a certificate chain for TLS client use:
|
|
462
|
+
* chain verification + `clientAuth` EKU (leaf + intermediate propagation).
|
|
463
|
+
*
|
|
464
|
+
* @example
|
|
465
|
+
* ```ts
|
|
466
|
+
* import { validateForTlsClient } from 'micro509';
|
|
467
|
+
*
|
|
468
|
+
* const result = await validateForTlsClient({
|
|
469
|
+
* leaf: clientCertPem,
|
|
470
|
+
* roots: [rootCaPem],
|
|
471
|
+
* });
|
|
472
|
+
* ```
|
|
473
|
+
*/
|
|
474
|
+
function validateForTlsClient(input) {
|
|
475
|
+
return verifyChainForExtendedKeyUsageProfile(input, "clientAuth");
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Validates a certificate chain for code signing:
|
|
479
|
+
* chain verification + `codeSigning` EKU (leaf + intermediate propagation).
|
|
480
|
+
*
|
|
481
|
+
* @example
|
|
482
|
+
* ```ts
|
|
483
|
+
* import { validateForCodeSigning } from 'micro509';
|
|
484
|
+
*
|
|
485
|
+
* const result = await validateForCodeSigning({
|
|
486
|
+
* leaf: codeSigningCertPem,
|
|
487
|
+
* roots: [rootCaPem],
|
|
488
|
+
* });
|
|
489
|
+
* ```
|
|
490
|
+
*/
|
|
491
|
+
function validateForCodeSigning(input) {
|
|
492
|
+
return verifyChainForExtendedKeyUsageProfile(input, "codeSigning");
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Validates a certificate chain for CA use:
|
|
496
|
+
* chain verification + `basicConstraints.ca` check on the leaf.
|
|
497
|
+
*
|
|
498
|
+
* @example
|
|
499
|
+
* ```ts
|
|
500
|
+
* import { validateForCa } from 'micro509';
|
|
501
|
+
*
|
|
502
|
+
* const result = await validateForCa({
|
|
503
|
+
* leaf: intermediateCertPem,
|
|
504
|
+
* roots: [rootCaPem],
|
|
505
|
+
* });
|
|
506
|
+
* ```
|
|
507
|
+
*/
|
|
508
|
+
function validateForCa(input) {
|
|
509
|
+
return verifyCertificateChain({
|
|
510
|
+
...baseChainInput(input),
|
|
511
|
+
purpose: "ca"
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
/** Enforces purpose-specific constraints on the leaf certificate (CA flag or EKU). */
|
|
515
|
+
function validateLeaf(leaf, input, policyValidation) {
|
|
516
|
+
const purpose = input.purpose;
|
|
517
|
+
if (purpose !== void 0) {
|
|
518
|
+
if (purpose === "ca") {
|
|
519
|
+
if (leaf.basicConstraints?.ca !== true) return failure("ca_required", "leaf is not a CA certificate", 0, detail({ subjectCommonName: leaf.subject.values.commonName }));
|
|
520
|
+
} else if (leaf.extendedKeyUsage !== void 0 && !leaf.extendedKeyUsage.includes(purpose)) return failure("extended_key_usage_invalid", `leaf missing EKU ${purpose}`, 0, detail({
|
|
521
|
+
subjectCommonName: leaf.subject.values.commonName,
|
|
522
|
+
expected: purpose,
|
|
523
|
+
actual: leaf.extendedKeyUsage.map(formatEku).join(",")
|
|
524
|
+
}));
|
|
525
|
+
}
|
|
526
|
+
return {
|
|
527
|
+
ok: true,
|
|
528
|
+
policyValidation
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
/** Matches the leaf's SAN against the requested service identity. */
|
|
532
|
+
function validateServiceIdentity(leaf, serviceIdentity) {
|
|
533
|
+
const malformedInput = validateServiceIdentityInput(serviceIdentity);
|
|
534
|
+
if (!malformedInput.ok) return malformedInput;
|
|
535
|
+
const result = matchServiceIdentity({
|
|
536
|
+
certificate: reparseCertificateForTrust(leaf),
|
|
537
|
+
serviceIdentity
|
|
538
|
+
});
|
|
539
|
+
if (result.ok) return { ok: true };
|
|
540
|
+
const error = result.error;
|
|
541
|
+
if (error.code === "service_identity_mismatch") return {
|
|
542
|
+
ok: false,
|
|
543
|
+
code: "subject_alt_name_mismatch",
|
|
544
|
+
message: error.message,
|
|
545
|
+
index: 0,
|
|
546
|
+
...error.details === void 0 ? {} : { details: error.details }
|
|
547
|
+
};
|
|
548
|
+
if (error.code !== "subject_alt_name_mismatch" && error.code !== "common_name_fallback_suppressed") return failure("subject_alt_name_mismatch", "service identity input is malformed", 0, detail({
|
|
549
|
+
expected: serviceIdentity.value,
|
|
550
|
+
actual: error.code
|
|
551
|
+
}));
|
|
552
|
+
return {
|
|
553
|
+
ok: false,
|
|
554
|
+
code: error.code,
|
|
555
|
+
message: error.message,
|
|
556
|
+
index: 0,
|
|
557
|
+
...error.details === void 0 ? {} : { details: error.details }
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
function validateServiceIdentityInput(serviceIdentity) {
|
|
561
|
+
if (!isRecord(serviceIdentity)) return failure("subject_alt_name_mismatch", "service identity input is malformed", 0);
|
|
562
|
+
if (serviceIdentity.type !== "dns" && serviceIdentity.type !== "ip" && serviceIdentity.type !== "uri" && serviceIdentity.type !== "srv") return failure("subject_alt_name_mismatch", "service identity input is malformed", 0, detail({ actual: String(serviceIdentity.type) }));
|
|
563
|
+
if (typeof serviceIdentity.value !== "string") return failure("subject_alt_name_mismatch", "service identity input is malformed", 0, detail({ actual: serviceIdentity.type }));
|
|
564
|
+
if (serviceIdentity.type === "ip") try {
|
|
565
|
+
parseIpAddressToBytes(serviceIdentity.value);
|
|
566
|
+
} catch {
|
|
567
|
+
return failure("subject_alt_name_mismatch", "service identity input is malformed", 0, detail({
|
|
568
|
+
expected: serviceIdentity.value,
|
|
569
|
+
actual: "ip"
|
|
570
|
+
}));
|
|
571
|
+
}
|
|
572
|
+
return { ok: true };
|
|
573
|
+
}
|
|
574
|
+
/** Applies an EKU check to a successfully verified chain and maps failures to verify error codes. */
|
|
575
|
+
function applyEkuCheck(result, purpose) {
|
|
576
|
+
const ekuCheck = checkExtendedKeyUsage(result.value.chain, purpose);
|
|
577
|
+
if (!ekuCheck.ok) return verifyFailureResult(failure(ekuCheck.code === "leaf_eku_missing" ? "extended_key_usage_invalid" : "intermediate_eku_constraint", ekuCheck.message, ekuCheck.index));
|
|
578
|
+
return result;
|
|
579
|
+
}
|
|
580
|
+
/** Verifies a chain then checks that all certificates permit the given EKU purpose. */
|
|
581
|
+
async function verifyChainForExtendedKeyUsageProfile(input, purpose) {
|
|
582
|
+
const result = await verifyCertificateChain(baseChainInput(input));
|
|
583
|
+
if (!result.ok) return result;
|
|
584
|
+
return applyEkuCheck(result, purpose);
|
|
585
|
+
}
|
|
586
|
+
/** Returns the OID of the first critical extension not in {@linkcode PROCESSED_EXTENSION_OIDS}, or `undefined`. */
|
|
587
|
+
function findUnprocessedCriticalExtension(certificate) {
|
|
588
|
+
for (const extension of certificate.extensions) if (extension.critical && !PROCESSED_EXTENSION_OIDS.has(extension.oid)) return extension.oid;
|
|
589
|
+
}
|
|
590
|
+
/** Constructs a {@linkcode VerifyChainFailure} with the given code, message, optional chain index, and details. */
|
|
591
|
+
function failure(code, message, index, details) {
|
|
592
|
+
return {
|
|
593
|
+
ok: false,
|
|
594
|
+
...indexedMicro509Error(code, message, index, details)
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
/** Wraps a {@linkcode VerifyChainFailure} into the standard indexed error result shape. */
|
|
598
|
+
function verifyFailureResult(error) {
|
|
599
|
+
return indexedErrorResult(error);
|
|
600
|
+
}
|
|
601
|
+
/** Wraps a policy outcome into the validate-candidate-path success result shape. */
|
|
602
|
+
function validateCandidatePathSuccessResult(policyValidation) {
|
|
603
|
+
return {
|
|
604
|
+
ok: true,
|
|
605
|
+
value: { policyValidation }
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
/** Describes a date in ISO format, or `'<invalid date>'` if invalid. */
|
|
609
|
+
function describeDateTime(value) {
|
|
610
|
+
return Number.isNaN(value.getTime()) ? "<invalid date>" : value.toISOString();
|
|
611
|
+
}
|
|
612
|
+
function normalizeValidationChain(chain) {
|
|
613
|
+
return chain.map(reparseCertificateForTrust);
|
|
614
|
+
}
|
|
615
|
+
function reparseCertificateForTrust(certificate) {
|
|
616
|
+
return parseCertificateDerOrThrow(new Uint8Array(certificate.der));
|
|
617
|
+
}
|
|
618
|
+
/** Returns `true` if the value is a non-negative integer (including zero). */
|
|
619
|
+
function isNonNegativeInteger(value) {
|
|
620
|
+
return value !== void 0 && Number.isInteger(value) && value >= 0;
|
|
621
|
+
}
|
|
622
|
+
/** Constructs a CSR verification failure result. */
|
|
623
|
+
function verifyRequestFailureResult(code, message, details) {
|
|
624
|
+
return errorResult({
|
|
625
|
+
ok: false,
|
|
626
|
+
...micro509Error(code, message, details)
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
/** Constructs an EKU check failure result at the given chain index. */
|
|
630
|
+
function ekuCheckFailureResult(code, message, index) {
|
|
631
|
+
return indexedErrorResult({
|
|
632
|
+
ok: false,
|
|
633
|
+
...indexedMicro509Error(code, message, index),
|
|
634
|
+
index
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
/** Merges flat and nested policy fields, with nested taking precedence. */
|
|
638
|
+
function resolvePolicyValidationInput(input) {
|
|
639
|
+
const flatInitialPolicySet = normalizeInitialPolicySet(input.initialPolicySet);
|
|
640
|
+
const nestedInitialPolicySet = normalizeInitialPolicySet(input.policy?.initialPolicySet);
|
|
641
|
+
return {
|
|
642
|
+
...flatInitialPolicySet === void 0 ? {} : { initialPolicySet: flatInitialPolicySet },
|
|
643
|
+
...input.requireExplicitPolicy === void 0 ? {} : { requireExplicitPolicy: input.requireExplicitPolicy },
|
|
644
|
+
...input.inhibitPolicyMapping === void 0 ? {} : { inhibitPolicyMapping: input.inhibitPolicyMapping },
|
|
645
|
+
...input.inhibitAnyPolicy === void 0 ? {} : { inhibitAnyPolicy: input.inhibitAnyPolicy },
|
|
646
|
+
...nestedInitialPolicySet === void 0 ? {} : { initialPolicySet: nestedInitialPolicySet },
|
|
647
|
+
...input.policy?.requireExplicitPolicy === void 0 ? {} : { requireExplicitPolicy: input.policy.requireExplicitPolicy },
|
|
648
|
+
...input.policy?.inhibitPolicyMapping === void 0 ? {} : { inhibitPolicyMapping: input.policy.inhibitPolicyMapping },
|
|
649
|
+
...input.policy?.inhibitAnyPolicy === void 0 ? {} : { inhibitAnyPolicy: input.policy.inhibitAnyPolicy }
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
/** Merges flat and nested name-constraint fields, with nested taking precedence. */
|
|
653
|
+
function resolveInitialNameConstraintsInput(input) {
|
|
654
|
+
return {
|
|
655
|
+
...input.permittedSubtrees === void 0 ? {} : { permittedSubtrees: input.permittedSubtrees },
|
|
656
|
+
...input.excludedSubtrees === void 0 ? {} : { excludedSubtrees: input.excludedSubtrees },
|
|
657
|
+
...input.nameConstraints?.permittedSubtrees === void 0 ? {} : { permittedSubtrees: input.nameConstraints.permittedSubtrees },
|
|
658
|
+
...input.nameConstraints?.excludedSubtrees === void 0 ? {} : { excludedSubtrees: input.nameConstraints.excludedSubtrees }
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
/** Extracts the resolved policy and name-constraint inputs for forwarding. */
|
|
662
|
+
function copyValidationInputs(input) {
|
|
663
|
+
const policy = resolvePolicyValidationInput(input);
|
|
664
|
+
const nameConstraints = resolveInitialNameConstraintsInput(input);
|
|
665
|
+
return {
|
|
666
|
+
...hasPolicyValidationInput(policy) ? { policy } : {},
|
|
667
|
+
...hasInitialNameConstraintsInput(nameConstraints) ? { nameConstraints } : {}
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
/** Returns `true` if any policy validation field is defined. */
|
|
671
|
+
function hasPolicyValidationInput(input) {
|
|
672
|
+
return input.initialPolicySet !== void 0 || input.requireExplicitPolicy !== void 0 || input.inhibitPolicyMapping !== void 0 || input.inhibitAnyPolicy !== void 0;
|
|
673
|
+
}
|
|
674
|
+
/** Returns `true` if any initial name constraint field is defined. */
|
|
675
|
+
function hasInitialNameConstraintsInput(input) {
|
|
676
|
+
return input.permittedSubtrees !== void 0 || input.excludedSubtrees !== void 0;
|
|
677
|
+
}
|
|
678
|
+
/** Constructs failure details with subject/issuer CNs and full chain CN list. */
|
|
679
|
+
function buildFailureDetails(chain, index) {
|
|
680
|
+
const certificate = chain[index];
|
|
681
|
+
return detail({
|
|
682
|
+
subjectCommonName: certificate?.subject.values.commonName,
|
|
683
|
+
issuerCommonName: certificate?.issuer.values.commonName,
|
|
684
|
+
chainCommonNames: chain.map((entry) => entry.subject.values.commonName ?? "<unnamed>")
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
/** Formats an EKU value as a human-readable string (name or raw OID). */
|
|
688
|
+
function formatEku(value) {
|
|
689
|
+
return typeof value === "string" ? value : value.value;
|
|
690
|
+
}
|
|
691
|
+
/** Strips `undefined` values from a loose input to produce a clean {@linkcode VerifyFailureDetails}. */
|
|
692
|
+
function detail(input) {
|
|
693
|
+
return {
|
|
694
|
+
...input.subjectCommonName === void 0 ? {} : { subjectCommonName: input.subjectCommonName },
|
|
695
|
+
...input.issuerCommonName === void 0 ? {} : { issuerCommonName: input.issuerCommonName },
|
|
696
|
+
...input.expected === void 0 ? {} : { expected: input.expected },
|
|
697
|
+
...input.actual === void 0 ? {} : { actual: input.actual },
|
|
698
|
+
...input.chainCommonNames === void 0 ? {} : { chainCommonNames: input.chainCommonNames },
|
|
699
|
+
...input.presentedIdentifierTypes === void 0 ? {} : { presentedIdentifierTypes: input.presentedIdentifierTypes },
|
|
700
|
+
...input.commonNameFallbackReason === void 0 ? {} : { commonNameFallbackReason: input.commonNameFallbackReason }
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
/** Initializes policy and name-constraint validation state for a chain walk. */
|
|
704
|
+
function buildValidationState(input, chainLength) {
|
|
705
|
+
const policy = createPolicyValidationState(resolvePolicyValidationInput(input), chainLength);
|
|
706
|
+
const initialNameConstraintsValidation = validateInitialNameConstraintsInput(resolveInitialNameConstraintsInput(input));
|
|
707
|
+
if (!initialNameConstraintsValidation.ok) return initialNameConstraintsValidation;
|
|
708
|
+
return {
|
|
709
|
+
ok: true,
|
|
710
|
+
value: {
|
|
711
|
+
policy,
|
|
712
|
+
nameConstraints: createNameConstraintValidationState(initialNameConstraintsValidation.value)
|
|
713
|
+
}
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
function normalizeInitialPolicySet(initialPolicySet) {
|
|
717
|
+
if (initialPolicySet === void 0 || initialPolicySet === "any") return initialPolicySet;
|
|
718
|
+
if (!Array.isArray(initialPolicySet)) return [];
|
|
719
|
+
return initialPolicySet.every((policyIdentifier) => typeof policyIdentifier === "string") ? initialPolicySet : [];
|
|
720
|
+
}
|
|
721
|
+
function validateInitialNameConstraintsInput(input) {
|
|
722
|
+
const permittedValidation = validateInitialNameConstraintSubtrees(input.permittedSubtrees, "permittedSubtrees");
|
|
723
|
+
if (!permittedValidation.ok) return permittedValidation;
|
|
724
|
+
const excludedValidation = validateInitialNameConstraintSubtrees(input.excludedSubtrees, "excludedSubtrees");
|
|
725
|
+
if (!excludedValidation.ok) return excludedValidation;
|
|
726
|
+
return {
|
|
727
|
+
ok: true,
|
|
728
|
+
value: input
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
function validateInitialNameConstraintSubtrees(subtrees, label) {
|
|
732
|
+
if (subtrees === void 0) return { ok: true };
|
|
733
|
+
if (!Array.isArray(subtrees)) return invalidInitialNameConstraintsFailure(label);
|
|
734
|
+
for (const subtree of subtrees) {
|
|
735
|
+
const invalidForm = describeInvalidInitialNameConstraintForm(subtree);
|
|
736
|
+
if (invalidForm !== void 0) return invalidInitialNameConstraintsFailure(invalidForm);
|
|
737
|
+
}
|
|
738
|
+
return { ok: true };
|
|
739
|
+
}
|
|
740
|
+
function describeInvalidInitialNameConstraintForm(subtree) {
|
|
741
|
+
if (!isRecord(subtree)) return "invalid subtree";
|
|
742
|
+
const base = subtree.base;
|
|
743
|
+
if (!isRecord(base) || typeof base.type !== "string") return "invalid subtree";
|
|
744
|
+
switch (base.type) {
|
|
745
|
+
case "dns":
|
|
746
|
+
case "email":
|
|
747
|
+
case "uri": return typeof base.value === "string" ? void 0 : base.type;
|
|
748
|
+
case "directoryName": return typeof base.derHex === "string" ? void 0 : base.type;
|
|
749
|
+
case "ip": return base.addressBytes instanceof Uint8Array && base.maskBytes instanceof Uint8Array ? void 0 : base.type;
|
|
750
|
+
case "otherName":
|
|
751
|
+
case "x400Address":
|
|
752
|
+
case "ediPartyName":
|
|
753
|
+
case "registeredID": return base.type;
|
|
754
|
+
default: return base.type;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
function invalidInitialNameConstraintsFailure(actual) {
|
|
758
|
+
return failure("unsupported_initial_name_constraints", "initial name constraints use unsupported or malformed forms", void 0, detail({ actual }));
|
|
759
|
+
}
|
|
760
|
+
function isRecord(value) {
|
|
761
|
+
return typeof value === "object" && value !== null;
|
|
762
|
+
}
|
|
763
|
+
//#endregion
|
|
764
|
+
export { VERIFY_ERROR_CODES, buildCandidatePath, checkExtendedKeyUsage, trustAnchorFromCertificate, validateCandidatePath, validateForCa, validateForCodeSigning, validateForTlsClient, validateForTlsServer, verifyCertificateChain, verifyCertificateSigningRequest };
|