micro509 0.8.0 → 0.10.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 +4 -4
- package/dist/index.js +15 -15
- package/dist/internal/asn1/asn1.js +145 -186
- package/dist/internal/asn1/asn1.js.map +1 -0
- package/dist/internal/asn1/der.js +210 -227
- package/dist/internal/asn1/der.js.map +1 -0
- package/dist/internal/asn1/oids.js +297 -101
- package/dist/internal/asn1/oids.js.map +1 -0
- package/dist/internal/asn1/oids2.js +69 -0
- package/dist/internal/asn1/oids2.js.map +1 -0
- package/dist/internal/crypto/algorithm-names.js +37 -35
- package/dist/internal/crypto/algorithm-names.js.map +1 -0
- package/dist/internal/crypto/ecdsa.js +25 -28
- package/dist/internal/crypto/ecdsa.js.map +1 -0
- package/dist/internal/crypto/hash.js +56 -117
- package/dist/internal/crypto/hash.js.map +1 -0
- package/dist/internal/crypto/pbes2.js +122 -133
- package/dist/internal/crypto/pbes2.js.map +1 -0
- package/dist/internal/crypto/rsa-pss.js +118 -124
- package/dist/internal/crypto/rsa-pss.js.map +1 -0
- package/dist/internal/crypto/sig-verify.js +87 -99
- package/dist/internal/crypto/sig-verify.js.map +1 -0
- package/dist/internal/crypto/signing.d.ts +12 -8
- package/dist/internal/crypto/signing.js +53 -55
- package/dist/internal/crypto/signing.js.map +1 -0
- package/dist/internal/crypto/webcrypto.js +5 -3
- package/dist/internal/crypto/webcrypto.js.map +1 -0
- package/dist/internal/shared/base64.js +10 -9
- package/dist/internal/shared/base64.js.map +1 -0
- package/dist/internal/shared/dn.js +50 -57
- package/dist/internal/shared/dn.js.map +1 -0
- package/dist/internal/shared/ip.js +43 -53
- package/dist/internal/shared/ip.js.map +1 -0
- package/dist/internal/verify/name-constraints-engine.js +211 -239
- package/dist/internal/verify/name-constraints-engine.js.map +1 -0
- package/dist/internal/verify/policy-engine.js +228 -247
- package/dist/internal/verify/policy-engine.js.map +1 -0
- package/dist/internal/verify/verify-path.js +213 -228
- package/dist/internal/verify/verify-path.js.map +1 -0
- package/dist/internal/x509/extension-bits.js +62 -59
- package/dist/internal/x509/extension-bits.js.map +1 -0
- package/dist/internal/x509/extension-registry.js +133 -164
- package/dist/internal/x509/extension-registry.js.map +1 -0
- package/dist/internal/x509/name-fields.js +35 -41
- package/dist/internal/x509/name-fields.js.map +1 -0
- package/dist/keys/keys.d.ts +626 -447
- package/dist/keys/keys.js +652 -404
- package/dist/keys/keys.js.map +1 -0
- package/dist/keys.d.ts +2 -2
- package/dist/keys.js +2 -2
- package/dist/pem/pem.d.ts +46 -46
- package/dist/pem/pem.js +62 -81
- package/dist/pem/pem.js.map +1 -0
- package/dist/pem.js +2 -2
- package/dist/pkcs/pfx.d.ts +96 -80
- package/dist/pkcs/pfx.js +191 -231
- package/dist/pkcs/pfx.js.map +1 -0
- package/dist/pkcs/pkcs12-mac.d.ts +20 -18
- package/dist/pkcs/pkcs12-mac.js +90 -111
- package/dist/pkcs/pkcs12-mac.js.map +1 -0
- package/dist/pkcs/pkcs7.d.ts +118 -69
- package/dist/pkcs/pkcs7.js +401 -443
- package/dist/pkcs/pkcs7.js.map +1 -0
- package/dist/pkcs.d.ts +2 -2
- package/dist/pkcs.js +4 -4
- package/dist/result/result.d.ts +37 -32
- package/dist/result/result.js +46 -44
- package/dist/result/result.js.map +1 -0
- package/dist/result.js +2 -2
- package/dist/revocation/chain.d.ts +138 -119
- package/dist/revocation/chain.js +248 -281
- package/dist/revocation/chain.js.map +1 -0
- package/dist/revocation/crl.d.ts +125 -123
- package/dist/revocation/crl.js +653 -745
- package/dist/revocation/crl.js.map +1 -0
- package/dist/revocation/ocsp.d.ts +183 -177
- package/dist/revocation/ocsp.js +581 -638
- package/dist/revocation/ocsp.js.map +1 -0
- package/dist/revocation/revocation.d.ts +26 -26
- package/dist/revocation/revocation.js +104 -125
- package/dist/revocation/revocation.js.map +1 -0
- package/dist/revocation.js +5 -5
- package/dist/verify/identity.d.ts +42 -42
- package/dist/verify/identity.js +158 -167
- package/dist/verify/identity.js.map +1 -0
- package/dist/verify/name-constraints.d.ts +7 -7
- package/dist/verify/policy.d.ts +10 -10
- package/dist/verify/verify.d.ts +163 -163
- package/dist/verify/verify.js +396 -392
- package/dist/verify/verify.js.map +1 -0
- package/dist/verify.js +3 -3
- package/dist/x509/certificate.d.ts +117 -117
- package/dist/x509/certificate.js +51 -60
- package/dist/x509/certificate.js.map +1 -0
- package/dist/x509/csr.d.ts +25 -25
- package/dist/x509/csr.js +26 -30
- package/dist/x509/csr.js.map +1 -0
- package/dist/x509/extensions.d.ts +228 -184
- package/dist/x509/extensions.js +175 -200
- package/dist/x509/extensions.js.map +1 -0
- package/dist/x509/name.d.ts +94 -93
- package/dist/x509/name.js +30 -29
- package/dist/x509/name.js.map +1 -0
- package/dist/x509/parse.d.ts +185 -185
- package/dist/x509/parse.js +638 -676
- package/dist/x509/parse.js.map +1 -0
- package/dist/x509.js +6 -6
- package/package.json +79 -41
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"verify-path.js","names":[],"sources":["../../../src/internal/verify/verify-path.ts"],"sourcesContent":["/**\n * Internal certificate path-building and signature-check helpers.\n *\n * Loads and parses candidate certificates, ranks issuer candidates by AKI/root\n * affinity, matches against bare {@linkcode TrustAnchor}s, and performs the\n * depth-first chain search used by the public verify APIs in `verify.ts`.\n *\n * @module\n */\n\nimport { toHex } from '#micro509/internal/asn1/asn1';\nimport { verifySignedDataDetailed } from '#micro509/internal/crypto/sig-verify';\nimport { canonicalDnKey, compareDistinguishedNames } from '#micro509/internal/shared/dn';\nimport type {\n\tCertificateSource,\n\tTrustAnchor,\n\tVerifyChainFailure,\n\tVerifyErrorCode,\n\tVerifyFailureDetails,\n} from '#micro509/verify/verify';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificatesFromSource } from '#micro509/x509/parse';\n\n/** Outcome of verifying one certificate's signature against its issuer's key. */\nexport type VerifyCertificateSignatureResult =\n\t| { readonly ok: true; readonly valid: boolean }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly code: 'signature_invalid' | 'unsupported_signature_algorithm_parameters';\n\t\t\treadonly reason: string;\n\t };\n\n/** Result of the internal chain-building search. */\nexport interface InternalBuildResult {\n\t/** Deepest chain found (leaf-to-root order), may be partial if no root was reached. */\n\treadonly chain: readonly ParsedCertificate[];\n\t/** `true` when the chain terminates at a trusted root or anchor. */\n\treadonly foundTrustedRoot: boolean;\n\t/** Chain index where no issuer candidate existed, when the search dead-ended. */\n\treadonly missingIssuerAt?: number;\n\t/** Best failure encountered during the search, for diagnostic reporting. */\n\treadonly failure?: VerifyChainFailure;\n}\n\n/** Result of attempting to match a certificate against bare trust anchors. */\ninterface TrustAnchorMatchResult {\n\t/** `true` if a trust anchor verified the certificate's signature. */\n\treadonly matched: boolean;\n\t/** Failure to report when matching was attempted but signature verification failed. */\n\treadonly failure?: VerifyChainFailure;\n}\n\ntype IssuerCandidateEvaluation =\n\t| { readonly ok: true; readonly nextCaBelowCount: number }\n\t| { readonly ok: false; readonly failure: VerifyChainFailure };\n\n/** Loose input for constructing failure detail objects during path building. */\nexport interface VerifyPathFailureDetailsInput {\n\t/** Common name of the certificate under evaluation, if known. */\n\treadonly subjectCommonName?: string | undefined;\n\t/** Common name of the expected issuer, if known. */\n\treadonly issuerCommonName?: string | undefined;\n\t/** Description of what the check expected. */\n\treadonly expected?: string | undefined;\n\t/** Description of what the check actually observed. */\n\treadonly actual?: string | undefined;\n\t/** Common names of every certificate in the candidate chain. */\n\treadonly chainCommonNames?: readonly string[] | undefined;\n}\n\n/** Callbacks injected by the caller to construct failure objects during path building. */\nexport interface VerifyPathCallbacks {\n\t/** Constructs a {@linkcode VerifyChainFailure} from a code, message, chain index, and details. */\n\treadonly failure: (\n\t\tcode: VerifyErrorCode,\n\t\tmessage: string,\n\t\tindex?: number,\n\t\tdetails?: VerifyFailureDetails,\n\t) => VerifyChainFailure;\n\t/** Constructs a {@linkcode VerifyFailureDetails} from loose inputs. */\n\treadonly detail: (input: VerifyPathFailureDetailsInput) => VerifyFailureDetails;\n}\n\n/** Returns `true` if `at` falls within the certificate's notBefore/notAfter window (inclusive). */\nexport function isWithinValidity(certificate: ParsedCertificate, at: Date): boolean {\n\treturn (\n\t\tcertificate.notBefore.getTime() <= at.getTime() &&\n\t\tat.getTime() <= certificate.notAfter.getTime()\n\t);\n}\n\n/** Returns `true` if the certificate's subject and issuer DNs are semantically equal (RFC 5280 §7.1). */\nexport function isSelfIssued(certificate: ParsedCertificate): boolean {\n\treturn compareDistinguishedNames(certificate.subject, certificate.issuer);\n}\n\n/** Counts non-self-issued CA certificates in positions 0..(index-1) for pathLength checking. */\nexport function countCaCertificatesBelowParsed(\n\tchain: readonly ParsedCertificate[],\n\tindex: number,\n): number {\n\tlet total = 0;\n\tfor (let cursor = 1; cursor < index; cursor += 1) {\n\t\tconst certificate = chain[cursor];\n\t\tif (certificate?.basicConstraints?.ca === true && !isSelfIssued(certificate)) {\n\t\t\ttotal += 1;\n\t\t}\n\t}\n\treturn total;\n}\n\n/** Parses an array of PEM/DER sources into parsed certificates, expanding multi-block PEM. */\nexport function loadCertificates(\n\tsources: readonly CertificateSource[],\n): readonly ParsedCertificate[] {\n\tconst loaded: ParsedCertificate[] = [];\n\tfor (const source of sources) {\n\t\tloaded.push(...expandSource(source));\n\t}\n\treturn loaded;\n}\n\n/** Parses exactly one certificate from a PEM/DER source. Throws if the source contains zero or multiple certificates. */\nexport function loadSingleCertificate(source: CertificateSource): ParsedCertificate {\n\tconst loaded = expandSource(source);\n\tconst first = loaded[0];\n\tif (first === undefined) {\n\t\tthrow new Error('No certificate found');\n\t}\n\tif (loaded.length !== 1) {\n\t\tthrow new Error('Expected a single certificate source');\n\t}\n\treturn first;\n}\n\n/** Verifies that `certificate` was signed by `issuer`'s public key. */\nexport async function verifyCertificateSignature(\n\tcertificate: ParsedCertificate,\n\tissuer: ParsedCertificate,\n): Promise<VerifyCertificateSignatureResult> {\n\tconst result = await verifySignedDataDetailed(\n\t\tcertificate.signatureAlgorithmOid,\n\t\tcertificate.signatureAlgorithmParametersDer,\n\t\tissuer.publicKeyAlgorithmOid,\n\t\tissuer.publicKeyParametersOid,\n\t\tissuer.subjectPublicKeyInfoDer,\n\t\tcertificate.signatureValue,\n\t\tcertificate.tbsCertificateDer,\n\t);\n\tif (!result.ok && result.code === 'verification_error') {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: 'signature_invalid',\n\t\t\treason: result.reason,\n\t\t};\n\t}\n\treturn result;\n}\n\n/**\n * Depth-first chain search from leaf to root. Tries all issuer candidates,\n * checking validity, CA constraints, AKI, pathLength, and signatures at each\n * step. Returns the first fully anchored path or the deepest partial path\n * with the best failure encountered.\n */\nexport async function buildChainInternal(\n\tleaf: ParsedCertificate,\n\tintermediates: readonly ParsedCertificate[],\n\troots: readonly ParsedCertificate[],\n\ttrustAnchors: readonly TrustAnchor[],\n\tat: Date,\n\tcallbacks: VerifyPathCallbacks,\n): Promise<InternalBuildResult> {\n\tconst candidates = [...intermediates, ...roots];\n\tconst subjectIndex = new Map<string, ParsedCertificate[]>();\n\tconst order = new Map<string, number>();\n\tconst rootFingerprints = new Set(roots.map((candidate) => fingerprint(candidate)));\n\tconst anchorIndex = new Map<string, TrustAnchor[]>();\n\tfor (const anchor of trustAnchors) {\n\t\tconst key = canonicalDnKey(anchor.subject);\n\t\tconst existing = anchorIndex.get(key);\n\t\tif (existing === undefined) {\n\t\t\tanchorIndex.set(key, [anchor]);\n\t\t} else {\n\t\t\texisting.push(anchor);\n\t\t}\n\t}\n\tlet sawUntrustedAnchor = false;\n\tlet deepestPath: readonly ParsedCertificate[] = [leaf];\n\tlet deepestMissingIssuerAt: number | undefined;\n\tlet preferredFailure: VerifyChainFailure | undefined;\n\tconst deadEnds = new Set<string>();\n\n\tcandidates.forEach((candidate, index) => {\n\t\tconst key = canonicalDnKey(candidate.subject);\n\t\tconst existing = subjectIndex.get(key);\n\t\tif (existing === undefined) {\n\t\t\tsubjectIndex.set(key, [candidate]);\n\t\t} else {\n\t\t\texisting.push(candidate);\n\t\t}\n\t\torder.set(fingerprint(candidate), index);\n\t});\n\n\tconst maxDepth = candidates.length + 1;\n\tconst startFingerprint = fingerprint(leaf);\n\tconst success = await search(leaf, [leaf], new Set([startFingerprint]), 0);\n\tif (success !== undefined) {\n\t\treturn { chain: success, foundTrustedRoot: true };\n\t}\n\tif (preferredFailure !== undefined) {\n\t\treturn {\n\t\t\tchain: deepestPath,\n\t\t\tfoundTrustedRoot: false,\n\t\t\tfailure: preferredFailure,\n\t\t};\n\t}\n\tif (sawUntrustedAnchor) {\n\t\treturn { chain: deepestPath, foundTrustedRoot: false };\n\t}\n\treturn deepestMissingIssuerAt === undefined\n\t\t? { chain: deepestPath, foundTrustedRoot: false }\n\t\t: {\n\t\t\t\tchain: deepestPath,\n\t\t\t\tfoundTrustedRoot: false,\n\t\t\t\tmissingIssuerAt: deepestMissingIssuerAt,\n\t\t\t};\n\n\tasync function search(\n\t\tcurrent: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tif (rootFingerprints.has(fingerprint(current))) {\n\t\t\treturn path;\n\t\t}\n\t\tconst matchedAnchor = await matchTrustAnchor(current, anchorIndex, callbacks, path.length - 1);\n\t\tif (matchedAnchor.failure !== undefined) {\n\t\t\trecordFailure(matchedAnchor.failure, path);\n\t\t}\n\t\tif (matchedAnchor.matched) {\n\t\t\treturn path;\n\t\t}\n\t\tif (path.length > maxDepth) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst visitedKey = [...visited].sort().join(',');\n\t\tconst memoKey = `${fingerprint(current)}:${caBelowCount}:${visitedKey}`;\n\t\tif (deadEnds.has(memoKey)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst issuers = rankIssuerCandidates(\n\t\t\tcurrent,\n\t\t\tsubjectIndex.get(canonicalDnKey(current.issuer)) ?? [],\n\t\t\torder,\n\t\t\trootFingerprints,\n\t\t);\n\t\tif (issuers.length === 0) {\n\t\t\trecordMissingIssuers(current, path);\n\t\t\tdeadEnds.add(memoKey);\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst issuerPath = await searchIssuerCandidates(current, issuers, path, visited, caBelowCount);\n\t\tif (issuerPath !== undefined) return issuerPath;\n\n\t\tdeadEnds.add(memoKey);\n\t\tupdateDeepest(path);\n\t\treturn undefined;\n\t}\n\n\tfunction recordMissingIssuers(\n\t\tcurrent: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t): void {\n\t\tif (isSelfIssued(current)) {\n\t\t\tupdateDeepest(path);\n\t\t\tsawUntrustedAnchor = true;\n\t\t} else if (updateDeepest(path)) {\n\t\t\tdeepestMissingIssuerAt = path.length - 1;\n\t\t}\n\t}\n\n\t/** Searches ranked issuer candidates until one produces a trusted path. */\n\tasync function searchIssuerCandidates(\n\t\tcurrent: ParsedCertificate,\n\t\tissuers: readonly ParsedCertificate[],\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tfor (const issuer of issuers) {\n\t\t\tconst result = await searchIssuerCandidate(current, issuer, path, visited, caBelowCount);\n\t\t\tif (result !== undefined) return result;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tasync function searchIssuerCandidate(\n\t\tcurrent: ParsedCertificate,\n\t\tissuer: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tconst issuerFingerprint = fingerprint(issuer);\n\t\tif (visited.has(issuerFingerprint)) return undefined;\n\t\tconst candidate = await evaluateIssuerCandidate(\n\t\t\tcurrent,\n\t\t\tissuer,\n\t\t\tpath,\n\t\t\tcaBelowCount,\n\t\t\tat,\n\t\t\tcallbacks,\n\t\t);\n\t\tif (!candidate.ok) {\n\t\t\trecordFailure(candidate.failure, path);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst nextVisited = new Set(visited);\n\t\tnextVisited.add(issuerFingerprint);\n\t\treturn await search(issuer, [...path, issuer], nextVisited, candidate.nextCaBelowCount);\n\t}\n\n\tfunction updateDeepest(path: readonly ParsedCertificate[]): boolean {\n\t\tif (path.length > deepestPath.length) {\n\t\t\tdeepestPath = path;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tfunction recordFailure(\n\t\tcandidateFailure: VerifyChainFailure,\n\t\tpath: readonly ParsedCertificate[],\n\t): void {\n\t\tif (preferredFailure === undefined || path.length > deepestPath.length) {\n\t\t\tpreferredFailure = candidateFailure;\n\t\t\tdeepestPath = path;\n\t\t}\n\t}\n}\n\n/** Applies issuer constraints and signature verification to one path candidate. */\nasync function evaluateIssuerCandidate(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tpath: readonly ParsedCertificate[],\n\tcaBelowCount: number,\n\tat: Date,\n\tcallbacks: VerifyPathCallbacks,\n): Promise<IssuerCandidateEvaluation> {\n\tconst issuerConstraints = evaluateIssuerConstraints(\n\t\tcurrent,\n\t\tissuer,\n\t\tpath,\n\t\tcaBelowCount,\n\t\tat,\n\t\tcallbacks,\n\t);\n\tif (!issuerConstraints.ok) {\n\t\treturn issuerConstraints;\n\t}\n\tconst signatureResult = await verifyCertificateSignature(current, issuer);\n\tif (!signatureResult.ok) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\tsignatureResult.code,\n\t\t\t\tsignatureResult.reason,\n\t\t\t\tpath.length - 1,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\t\tactual: signatureResult.reason,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\tif (!signatureResult.valid) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'signature_invalid',\n\t\t\t\t'certificate signature does not verify',\n\t\t\t\tpath.length - 1,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\treturn issuerConstraints;\n}\n\nfunction evaluateIssuerConstraints(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tpath: readonly ParsedCertificate[],\n\tcaBelowCount: number,\n\tat: Date,\n\tcallbacks: VerifyPathCallbacks,\n): IssuerCandidateEvaluation {\n\tif (!isWithinValidity(issuer, at)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'certificate_expired',\n\t\t\t\t'certificate not valid at requested time',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: issuer.subject.values.commonName,\n\t\t\t\t\texpected: describeDateTime(at),\n\t\t\t\t\tactual: `${describeDateTime(issuer.notBefore)}..${describeDateTime(issuer.notAfter)}`,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\tif (issuer.basicConstraints?.ca !== true) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'ca_required',\n\t\t\t\t'issuer must be a CA certificate',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({ subjectCommonName: issuer.subject.values.commonName }),\n\t\t\t),\n\t\t};\n\t}\n\treturn evaluateIssuerKeyConstraints(current, issuer, path, caBelowCount, callbacks);\n}\n\nfunction evaluateIssuerKeyConstraints(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tpath: readonly ParsedCertificate[],\n\tcaBelowCount: number,\n\tcallbacks: VerifyPathCallbacks,\n): IssuerCandidateEvaluation {\n\tif (issuer.keyUsage !== undefined && !issuer.keyUsage.flags.includes('keyCertSign')) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'key_cert_sign_required',\n\t\t\t\t'issuer missing keyCertSign',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({ subjectCommonName: issuer.subject.values.commonName }),\n\t\t\t),\n\t\t};\n\t}\n\tif (authorityKeyIdentifierMismatch(current, issuer)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'authority_key_identifier_mismatch',\n\t\t\t\t'authorityKeyIdentifier does not match issuer subjectKeyIdentifier',\n\t\t\t\tpath.length - 1,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\t\texpected: issuer.subjectKeyIdentifier,\n\t\t\t\t\tactual: current.authorityKeyIdentifier,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\tconst nextCaBelowCount =\n\t\tcaBelowCount +\n\t\t(current.basicConstraints?.ca === true && !isSelfIssued(current) && path.length > 1 ? 1 : 0);\n\tconst pathLength = issuer.basicConstraints?.pathLength;\n\tif (isNonNegativeInteger(pathLength) && nextCaBelowCount > pathLength) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'path_length_exceeded',\n\t\t\t\t'path length constraint exceeded',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: issuer.subject.values.commonName,\n\t\t\t\t\texpected: String(pathLength),\n\t\t\t\t\tactual: String(nextCaBelowCount),\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\treturn { ok: true, nextCaBelowCount };\n}\n\nexport function authorityKeyIdentifierMismatch(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n): boolean {\n\treturn (\n\t\tcurrent.authorityKeyIdentifier !== undefined &&\n\t\tissuer.subjectKeyIdentifier !== undefined &&\n\t\tcurrent.authorityKeyIdentifier !== issuer.subjectKeyIdentifier\n\t);\n}\n\n/** Expands a PEM (possibly multi-block) or DER source into parsed certificates. */\nfunction expandSource(source: CertificateSource): readonly ParsedCertificate[] {\n\treturn parseCertificatesFromSource(source);\n}\n\n/** Filters and sorts issuer candidates: AKI match first, then roots, then input order. */\nfunction rankIssuerCandidates(\n\tcurrent: ParsedCertificate,\n\tcandidates: readonly ParsedCertificate[],\n\torder: ReadonlyMap<string, number>,\n\trootFingerprints: ReadonlySet<string>,\n): readonly ParsedCertificate[] {\n\tconst aki = current.authorityKeyIdentifier;\n\tconst filtered = [...candidates].filter((candidate) => isIssuerOf(candidate, current));\n\tconst fps = new Map<ParsedCertificate, string>();\n\tfor (const candidate of filtered) {\n\t\tfps.set(candidate, fingerprint(candidate));\n\t}\n\treturn filtered.sort((left, right) => {\n\t\tconst akiScore = compareBooleans(matchesAki(left, aki), matchesAki(right, aki));\n\t\tif (akiScore !== 0) {\n\t\t\treturn akiScore;\n\t\t}\n\t\tconst leftFp = fps.get(left) ?? '';\n\t\tconst rightFp = fps.get(right) ?? '';\n\t\tconst rootScore = compareBooleans(rootFingerprints.has(leftFp), rootFingerprints.has(rightFp));\n\t\tif (rootScore !== 0) {\n\t\t\treturn rootScore;\n\t\t}\n\t\treturn (\n\t\t\t(order.get(leftFp) ?? Number.MAX_SAFE_INTEGER) -\n\t\t\t(order.get(rightFp) ?? Number.MAX_SAFE_INTEGER)\n\t\t);\n\t});\n}\n\n/** Returns `true` if the candidate's SKI matches the given authority key identifier. */\nfunction matchesAki(candidate: ParsedCertificate, aki: string | undefined): boolean {\n\treturn (\n\t\taki !== undefined &&\n\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\tcandidate.subjectKeyIdentifier === aki\n\t);\n}\n\n/** Sort comparator: `true` sorts before `false`. Returns -1, 0, or 1. */\nfunction compareBooleans(left: boolean, right: boolean): number {\n\tif (left === right) {\n\t\treturn 0;\n\t}\n\treturn left ? -1 : 1;\n}\n\n/** Returns `true` if `issuer`'s subject DN semantically matches `child`'s issuer DN (RFC 5280 §7.1). */\nfunction isIssuerOf(issuer: ParsedCertificate, child: ParsedCertificate): boolean {\n\treturn compareDistinguishedNames(child.issuer, issuer.subject);\n}\n\n/** Attempts to verify `certificate` against each bare trust anchor whose subject DN matches. */\nasync function matchTrustAnchor(\n\tcertificate: ParsedCertificate,\n\tanchorIndex: ReadonlyMap<string, readonly TrustAnchor[]>,\n\tcallbacks: VerifyPathCallbacks,\n\tindex: number,\n): Promise<TrustAnchorMatchResult> {\n\tconst anchors = anchorIndex.get(canonicalDnKey(certificate.issuer));\n\tif (anchors === undefined) {\n\t\treturn { matched: false };\n\t}\n\tlet firstFailure: VerifyChainFailure | undefined;\n\tfor (const anchor of anchors) {\n\t\tif (trustAnchorAkiMismatch(certificate, anchor)) continue;\n\t\tconst verified = await verifyTrustAnchorSignature(certificate, anchor);\n\t\tif (!verified.ok) {\n\t\t\t// Capture the first failure but continue trying other anchors\n\t\t\tif (firstFailure === undefined) {\n\t\t\t\tfirstFailure = callbacks.failure(\n\t\t\t\t\tverified.code,\n\t\t\t\t\tverified.reason,\n\t\t\t\t\tindex,\n\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: verified.reason,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (!verified.valid) {\n\t\t\tif (firstFailure === undefined) {\n\t\t\t\tfirstFailure = callbacks.failure(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'certificate signature does not verify',\n\t\t\t\t\tindex,\n\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: 'certificate signature does not verify',\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\treturn { matched: true };\n\t}\n\treturn firstFailure !== undefined\n\t\t? { matched: false, failure: firstFailure }\n\t\t: { matched: false };\n}\n\nfunction trustAnchorAkiMismatch(certificate: ParsedCertificate, anchor: TrustAnchor): boolean {\n\treturn (\n\t\tanchor.subjectKeyIdentifier !== undefined &&\n\t\tcertificate.authorityKeyIdentifier !== undefined &&\n\t\tanchor.subjectKeyIdentifier !== certificate.authorityKeyIdentifier\n\t);\n}\n\nasync function verifyTrustAnchorSignature(\n\tcertificate: ParsedCertificate,\n\tanchor: TrustAnchor,\n): Promise<VerifyCertificateSignatureResult> {\n\tconst verificationResult = await verifySignedDataDetailed(\n\t\tcertificate.signatureAlgorithmOid,\n\t\tcertificate.signatureAlgorithmParametersDer,\n\t\tanchor.publicKeyAlgorithmOid,\n\t\tanchor.publicKeyParametersOid,\n\t\tanchor.subjectPublicKeyInfoDer,\n\t\tcertificate.signatureValue,\n\t\tcertificate.tbsCertificateDer,\n\t);\n\treturn !verificationResult.ok && verificationResult.code === 'verification_error'\n\t\t? { ok: false, code: 'signature_invalid', reason: verificationResult.reason }\n\t\t: verificationResult;\n}\n\nfunction describeDateTime(value: Date): string {\n\treturn Number.isNaN(value.getTime()) ? '<invalid date>' : value.toISOString();\n}\n\nfunction isNonNegativeInteger(value: number | undefined): value is number {\n\treturn value !== undefined && Number.isInteger(value) && value >= 0;\n}\n\n/** Cache for computed fingerprints to avoid repeated toHex() calls. */\nconst fingerprintCache = new WeakMap<ParsedCertificate, string>();\n\n/** Returns a hex fingerprint of the certificate's raw DER, used for cycle detection and dedup. */\nfunction fingerprint(certificate: ParsedCertificate): string {\n\tlet cached = fingerprintCache.get(certificate);\n\tif (cached === undefined) {\n\t\tcached = toHex(certificate.der);\n\t\tfingerprintCache.set(certificate, cached);\n\t}\n\treturn cached;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoFA,SAAgB,iBAAiB,GAAgC,GAAmB;CACnF,O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R"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { bitString, readRootElement } from "../asn1/der.js";
|
|
1
|
+
import { bitString as e, readRootElement as t } from "../asn1/der.js";
|
|
2
2
|
//#region src/internal/x509/extension-bits.ts
|
|
3
3
|
/**
|
|
4
4
|
* BIT STRING helpers for {@linkcode KeyUsage} and {@linkcode DistributionPointReason} flags.
|
|
@@ -8,8 +8,16 @@ import { bitString, readRootElement } from "../asn1/der.js";
|
|
|
8
8
|
*
|
|
9
9
|
* @module
|
|
10
10
|
*/
|
|
11
|
+
/**
|
|
12
|
+
* Decoded BIT STRING flags with DER conformance metadata.
|
|
13
|
+
*
|
|
14
|
+
* `flags` contains the recognized flag values with any non-zero padding bits
|
|
15
|
+
* masked out. `nonZeroPadding` is `true` when the original BIT STRING encoding
|
|
16
|
+
* had non-zero bits in positions that DER (X.690 §11.2.2) requires to be zero.
|
|
17
|
+
* Verification layers can use this signal to reject non-conformant encodings.
|
|
18
|
+
*/
|
|
11
19
|
/** Canonical bit-position order for Key Usage flags (RFC 5280 §4.2.1.3). */
|
|
12
|
-
const
|
|
20
|
+
const n = [
|
|
13
21
|
"digitalSignature",
|
|
14
22
|
"nonRepudiation",
|
|
15
23
|
"keyEncipherment",
|
|
@@ -19,9 +27,7 @@ const KEY_USAGE_ORDER = [
|
|
|
19
27
|
"cRLSign",
|
|
20
28
|
"encipherOnly",
|
|
21
29
|
"decipherOnly"
|
|
22
|
-
]
|
|
23
|
-
/** Canonical bit-position order for DistributionPoint reason flags (RFC 5280 §4.2.1.13). */
|
|
24
|
-
const DISTRIBUTION_POINT_REASON_ORDER = [
|
|
30
|
+
], r = [
|
|
25
31
|
"keyCompromise",
|
|
26
32
|
"cACompromise",
|
|
27
33
|
"affiliationChanged",
|
|
@@ -36,19 +42,19 @@ const DISTRIBUTION_POINT_REASON_ORDER = [
|
|
|
36
42
|
*
|
|
37
43
|
* @param usages Flags to set. Bit positions follow RFC 5280 §4.2.1.3 order.
|
|
38
44
|
*/
|
|
39
|
-
function encodeKeyUsageExtension(
|
|
40
|
-
|
|
41
|
-
return
|
|
45
|
+
function encodeKeyUsageExtension(t) {
|
|
46
|
+
let r = encodeBitFlags(t, (e) => indexInOrder(n, e, "key usage"));
|
|
47
|
+
return e(r.bytes, r.unusedBits);
|
|
42
48
|
}
|
|
43
49
|
/**
|
|
44
50
|
* Decode a DER-encoded Key Usage BIT STRING into an array of {@linkcode KeyUsage} flags.
|
|
45
51
|
*
|
|
46
52
|
* @param bytes DER of the keyUsage extension value (BIT STRING).
|
|
47
53
|
*/
|
|
48
|
-
function parseKeyUsageExtension(
|
|
49
|
-
|
|
50
|
-
if (
|
|
51
|
-
return requireCanonicalBitFlags(decodeBitFlags(
|
|
54
|
+
function parseKeyUsageExtension(e) {
|
|
55
|
+
let r = t(e, { maxDepth: 64 });
|
|
56
|
+
if (r.tag !== 3) throw Error("keyUsage must be a BIT STRING");
|
|
57
|
+
return requireCanonicalBitFlags(decodeBitFlags(r.value, n, 0), "keyUsage");
|
|
52
58
|
}
|
|
53
59
|
/**
|
|
54
60
|
* Encode {@linkcode DistributionPointReason} flags as BIT STRING content bytes
|
|
@@ -56,9 +62,9 @@ function parseKeyUsageExtension(bytes) {
|
|
|
56
62
|
*
|
|
57
63
|
* @param reasons Reason flags to encode.
|
|
58
64
|
*/
|
|
59
|
-
function encodeDistributionPointReasonFlagsContent(
|
|
60
|
-
|
|
61
|
-
return Uint8Array.of(
|
|
65
|
+
function encodeDistributionPointReasonFlagsContent(e) {
|
|
66
|
+
let t = encodeBitFlags(e, (e) => indexInOrder(r, e, "distribution point reason") + 1);
|
|
67
|
+
return Uint8Array.of(t.unusedBits, ...t.bytes);
|
|
62
68
|
}
|
|
63
69
|
/**
|
|
64
70
|
* Decode BIT STRING content bytes into {@linkcode DistributionPointReason} flags.
|
|
@@ -66,67 +72,64 @@ function encodeDistributionPointReasonFlagsContent(reasons) {
|
|
|
66
72
|
* @param value Raw content bytes (unusedBits prefix + flag bytes).
|
|
67
73
|
* @returns Decoded reason flags, preserving empty-but-present values and padding metadata.
|
|
68
74
|
*/
|
|
69
|
-
function parseDistributionPointReasonFlagsContent(
|
|
70
|
-
return requireCanonicalBitFlags(decodeBitFlags(
|
|
75
|
+
function parseDistributionPointReasonFlagsContent(e) {
|
|
76
|
+
return requireCanonicalBitFlags(decodeBitFlags(e, r, 1), "DistributionPoint reasons");
|
|
71
77
|
}
|
|
72
78
|
/** Pack named flags into a minimal byte array with DER BIT STRING unused-bits count. */
|
|
73
|
-
function encodeBitFlags(
|
|
74
|
-
if (
|
|
75
|
-
bytes: /* @__PURE__ */ new Uint8Array(
|
|
79
|
+
function encodeBitFlags(e, t) {
|
|
80
|
+
if (e.length === 0) return {
|
|
81
|
+
bytes: /* @__PURE__ */ new Uint8Array(),
|
|
76
82
|
unusedBits: 0
|
|
77
83
|
};
|
|
78
|
-
let
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
bits.push(bit);
|
|
83
|
-
if (bit > highestBit) highestBit = bit;
|
|
84
|
+
let n = -1, r = [];
|
|
85
|
+
for (let i of e) {
|
|
86
|
+
let e = t(i);
|
|
87
|
+
r.push(e), e > n && (n = e);
|
|
84
88
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
const bitIndex = bit % 8;
|
|
90
|
-
bytes[byteIndex] = (bytes[byteIndex] ?? 0) | 1 << 7 - bitIndex;
|
|
89
|
+
let i = Math.floor(n / 8) + 1, a = new Uint8Array(i);
|
|
90
|
+
for (let e of r) {
|
|
91
|
+
let t = Math.floor(e / 8), n = e % 8;
|
|
92
|
+
a[t] = (a[t] ?? 0) | 1 << 7 - n;
|
|
91
93
|
}
|
|
92
94
|
return {
|
|
93
|
-
bytes,
|
|
94
|
-
unusedBits: (8 - (
|
|
95
|
+
bytes: a,
|
|
96
|
+
unusedBits: (8 - (n + 1) % 8) % 8
|
|
95
97
|
};
|
|
96
98
|
}
|
|
97
99
|
/** Unpack set bits from a BIT STRING content into named flags from a candidate list. */
|
|
98
|
-
function decodeBitFlags(
|
|
99
|
-
if (
|
|
100
|
-
|
|
101
|
-
if (
|
|
102
|
-
|
|
103
|
-
if (
|
|
104
|
-
let
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
for (let
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
if (
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
if (candidate !== void 0) flags.push(candidate);
|
|
100
|
+
function decodeBitFlags(e, t, n) {
|
|
101
|
+
if (e.length === 0) throw Error("Empty BIT STRING");
|
|
102
|
+
let r = e[0] ?? 0;
|
|
103
|
+
if (r > 7) throw Error("Invalid BIT STRING");
|
|
104
|
+
let i = e.slice(1);
|
|
105
|
+
if (i.length === 0 && r !== 0) throw Error("Invalid BIT STRING");
|
|
106
|
+
let a = !1;
|
|
107
|
+
r > 0 && i.length > 0 && (a = ((i[i.length - 1] ?? 0) & (1 << r) - 1) != 0);
|
|
108
|
+
let o = [];
|
|
109
|
+
for (let e = 0; e < t.length; e += 1) {
|
|
110
|
+
let r = e + n, a = Math.floor(r / 8);
|
|
111
|
+
if (a >= i.length) break;
|
|
112
|
+
if ((i[a] ?? 0) & 1 << 7 - r % 8) {
|
|
113
|
+
let n = t[e];
|
|
114
|
+
n !== void 0 && o.push(n);
|
|
114
115
|
}
|
|
115
116
|
}
|
|
116
117
|
return {
|
|
117
|
-
flags,
|
|
118
|
-
nonZeroPadding
|
|
118
|
+
flags: o,
|
|
119
|
+
nonZeroPadding: a
|
|
119
120
|
};
|
|
120
121
|
}
|
|
121
|
-
function requireCanonicalBitFlags(
|
|
122
|
-
if (
|
|
123
|
-
return
|
|
122
|
+
function requireCanonicalBitFlags(e, t) {
|
|
123
|
+
if (e.nonZeroPadding) throw Error(`${t} BIT STRING must not set padding bits`);
|
|
124
|
+
return e;
|
|
124
125
|
}
|
|
125
126
|
/** Look up the bit position of a flag in its canonical order array. Throws on unknown flags. */
|
|
126
|
-
function indexInOrder(
|
|
127
|
-
|
|
128
|
-
if (
|
|
129
|
-
return
|
|
127
|
+
function indexInOrder(e, t, n) {
|
|
128
|
+
let r = e.indexOf(t);
|
|
129
|
+
if (r < 0) throw Error(`Unsupported ${n}: ${t}`);
|
|
130
|
+
return r;
|
|
130
131
|
}
|
|
131
132
|
//#endregion
|
|
132
133
|
export { encodeDistributionPointReasonFlagsContent, encodeKeyUsageExtension, parseDistributionPointReasonFlagsContent, parseKeyUsageExtension };
|
|
134
|
+
|
|
135
|
+
//# sourceMappingURL=extension-bits.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension-bits.js","names":[],"sources":["../../../src/internal/x509/extension-bits.ts"],"sourcesContent":["/**\n * BIT STRING helpers for {@linkcode KeyUsage} and {@linkcode DistributionPointReason} flags.\n *\n * Centralizes the bit-position ordering so certificate builders and parsers\n * produce identical wire encodings.\n *\n * @module\n */\n\n/**\n * Decoded BIT STRING flags with DER conformance metadata.\n *\n * `flags` contains the recognized flag values with any non-zero padding bits\n * masked out. `nonZeroPadding` is `true` when the original BIT STRING encoding\n * had non-zero bits in positions that DER (X.690 §11.2.2) requires to be zero.\n * Verification layers can use this signal to reject non-conformant encodings.\n */\nimport { bitString, DEFAULT_MAX_DER_DEPTH, readRootElement } from '#micro509/internal/asn1/der';\nimport type { DistributionPointReason, KeyUsage, ParsedBitFlags } from '#micro509/x509/extensions';\n\nexport type { ParsedBitFlags };\n\n/** Canonical bit-position order for Key Usage flags (RFC 5280 §4.2.1.3). */\nconst KEY_USAGE_ORDER = [\n\t'digitalSignature',\n\t'nonRepudiation',\n\t'keyEncipherment',\n\t'dataEncipherment',\n\t'keyAgreement',\n\t'keyCertSign',\n\t'cRLSign',\n\t'encipherOnly',\n\t'decipherOnly',\n] as const satisfies readonly KeyUsage[];\n\n/** Canonical bit-position order for DistributionPoint reason flags (RFC 5280 §4.2.1.13). */\nconst DISTRIBUTION_POINT_REASON_ORDER = [\n\t'keyCompromise',\n\t'cACompromise',\n\t'affiliationChanged',\n\t'superseded',\n\t'cessationOfOperation',\n\t'certificateHold',\n\t'privilegeWithdrawn',\n\t'aACompromise',\n] as const satisfies readonly DistributionPointReason[];\n\n/**\n * Encode an array of {@linkcode KeyUsage} flags into a DER BIT STRING.\n *\n * @param usages Flags to set. Bit positions follow RFC 5280 §4.2.1.3 order.\n */\nexport function encodeKeyUsageExtension(usages: readonly KeyUsage[]): Uint8Array {\n\tconst encoded = encodeBitFlags(usages, (usage) =>\n\t\tindexInOrder(KEY_USAGE_ORDER, usage, 'key usage'),\n\t);\n\treturn bitString(encoded.bytes, encoded.unusedBits);\n}\n\n/**\n * Decode a DER-encoded Key Usage BIT STRING into an array of {@linkcode KeyUsage} flags.\n *\n * @param bytes DER of the keyUsage extension value (BIT STRING).\n */\nexport function parseKeyUsageExtension(bytes: Uint8Array): ParsedBitFlags<KeyUsage> {\n\tconst bitStringElement = readRootElement(bytes, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (bitStringElement.tag !== 0x03) {\n\t\tthrow new Error('keyUsage must be a BIT STRING');\n\t}\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(bitStringElement.value, KEY_USAGE_ORDER, 0),\n\t\t'keyUsage',\n\t);\n}\n\n/**\n * Encode {@linkcode DistributionPointReason} flags as BIT STRING content bytes\n * (unusedBits prefix + flag bytes), suitable for wrapping in an implicit context tag.\n *\n * @param reasons Reason flags to encode.\n */\nexport function encodeDistributionPointReasonFlagsContent(\n\treasons: readonly DistributionPointReason[],\n): Uint8Array {\n\tconst encoded = encodeBitFlags(\n\t\treasons,\n\t\t(reason) =>\n\t\t\tindexInOrder(DISTRIBUTION_POINT_REASON_ORDER, reason, 'distribution point reason') + 1,\n\t);\n\treturn Uint8Array.of(encoded.unusedBits, ...encoded.bytes);\n}\n\n/**\n * Decode BIT STRING content bytes into {@linkcode DistributionPointReason} flags.\n *\n * @param value Raw content bytes (unusedBits prefix + flag bytes).\n * @returns Decoded reason flags, preserving empty-but-present values and padding metadata.\n */\nexport function parseDistributionPointReasonFlagsContent(\n\tvalue: Uint8Array,\n): ParsedBitFlags<DistributionPointReason> {\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(value, DISTRIBUTION_POINT_REASON_ORDER, 1),\n\t\t'DistributionPoint reasons',\n\t);\n}\n\n/** Pack named flags into a minimal byte array with DER BIT STRING unused-bits count. */\nfunction encodeBitFlags<T extends string>(\n\tvalues: readonly T[],\n\tbitForValue: (value: T) => number,\n): {\n\treadonly bytes: Uint8Array;\n\treadonly unusedBits: number;\n} {\n\tif (values.length === 0) {\n\t\treturn { bytes: new Uint8Array(0), unusedBits: 0 };\n\t}\n\tlet highestBit = -1;\n\tconst bits: number[] = [];\n\tfor (const value of values) {\n\t\tconst bit = bitForValue(value);\n\t\tbits.push(bit);\n\t\tif (bit > highestBit) {\n\t\t\thighestBit = bit;\n\t\t}\n\t}\n\tconst byteLength = Math.floor(highestBit / 8) + 1;\n\tconst bytes = new Uint8Array(byteLength);\n\tfor (const bit of bits) {\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tconst bitIndex = bit % 8;\n\t\tconst current = bytes[byteIndex] ?? 0;\n\t\tbytes[byteIndex] = current | (1 << (7 - bitIndex));\n\t}\n\tconst totalBits = highestBit + 1;\n\tconst unusedBits = (8 - (totalBits % 8)) % 8;\n\treturn {\n\t\tbytes,\n\t\tunusedBits,\n\t};\n}\n\n/** Unpack set bits from a BIT STRING content into named flags from a candidate list. */\nfunction decodeBitFlags<T extends string>(\n\tvalue: Uint8Array,\n\tcandidates: readonly T[],\n\tbitOffset: number,\n): ParsedBitFlags<T> {\n\tif (value.length === 0) {\n\t\tthrow new Error('Empty BIT STRING');\n\t}\n\tconst unusedBits = value[0] ?? 0;\n\tif (unusedBits > 7) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\tconst bytes = value.slice(1);\n\tif (bytes.length === 0 && unusedBits !== 0) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\t// Detect non-zero padding bits in the unused positions of the last byte.\n\t// DER X.690 §11.2.2 requires these to be zero. Rather than rejecting here\n\t// (which would break interop with real-world non-conformant certificates),\n\t// we record the violation so verification layers can decide.\n\tlet nonZeroPadding = false;\n\tif (unusedBits > 0 && bytes.length > 0) {\n\t\tconst lastByte = bytes[bytes.length - 1] ?? 0;\n\t\tconst paddingMask = (1 << unusedBits) - 1;\n\t\tnonZeroPadding = (lastByte & paddingMask) !== 0;\n\t}\n\tconst flags: T[] = [];\n\tfor (let index = 0; index < candidates.length; index += 1) {\n\t\tconst bit = index + bitOffset;\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tif (byteIndex >= bytes.length) {\n\t\t\tbreak;\n\t\t}\n\t\tconst byte = bytes[byteIndex] ?? 0;\n\t\tconst bitIndex = bit % 8;\n\t\tif ((byte & (1 << (7 - bitIndex))) !== 0) {\n\t\t\tconst candidate = candidates[index];\n\t\t\tif (candidate !== undefined) {\n\t\t\t\tflags.push(candidate);\n\t\t\t}\n\t\t}\n\t}\n\treturn { flags, nonZeroPadding };\n}\n\nfunction requireCanonicalBitFlags<T extends string>(\n\tparsed: ParsedBitFlags<T>,\n\tlabel: string,\n): ParsedBitFlags<T> {\n\tif (parsed.nonZeroPadding) {\n\t\tthrow new Error(`${label} BIT STRING must not set padding bits`);\n\t}\n\treturn parsed;\n}\n\n/** Look up the bit position of a flag in its canonical order array. Throws on unknown flags. */\nfunction indexInOrder<T extends string>(order: readonly T[], value: T, label: string): number {\n\tconst index = order.indexOf(value);\n\tif (index < 0) {\n\t\tthrow new Error(`Unsupported ${label}: ${value}`);\n\t}\n\treturn index;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuBA,MAAM,IAAkB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,GAGM,IAAkC;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAOA,SAAgB,wBAAwB,GAAyC;CAChF,IAAM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a,EAAM,MAAM;CAC/B,IAAI,IAAa,GAChB,MAAU,MAAM,oBAAoB;CAErC,IAAM,IAAQ,EAAM,MAAM,CAAC;CAC3B,IAAI,EAAM,WAAW,KAAK,MAAe,GACxC,MAAU,MAAM,oBAAoB;CAMrC,IAAI,IAAiB;CACrB,AAAI,IAAa,KAAK,EAAM,SAAS,MAGpC,MAFiB,EAAM,EAAM,SAAS,MAAM,MACvB,KAAK,KAAc,MACM;CAE/C,IAAM,IAAa,CAAC;CACpB,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAW,QAAQ,KAAS,GAAG;EAC1D,IAAM,IAAM,IAAQ,GACd,IAAY,KAAK,MAAM,IAAM,CAAC;EACpC,IAAI,KAAa,EAAM,QACtB;EAID,KAFa,EAAM,MAAc,KAEpB,KAAM,IADF,IAAM,GACmB;GACzC,IAAM,IAAY,EAAW;GAC7B,AAAI,MAAc,KAAA,KACjB,EAAM,KAAK,CAAS;EAEtB;CACD;CACA,OAAO;EAAE;EAAO;CAAe;AAChC;AAEA,SAAS,yBACR,GACA,GACoB;CACpB,IAAI,EAAO,gBACV,MAAU,MAAM,GAAG,EAAM,sCAAsC;CAEhE,OAAO;AACR;;AAGA,SAAS,aAA+B,GAAqB,GAAU,GAAuB;CAC7F,IAAM,IAAQ,EAAM,QAAQ,CAAK;CACjC,IAAI,IAAQ,GACX,MAAU,MAAM,eAAe,EAAM,IAAI,GAAO;CAEjD,OAAO;AACR"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { implicitPrimitiveContext, octetString, readRootElement, sequence } from "../asn1/der.js";
|
|
2
|
-
import { hexToBytes, toHex } from "../asn1/asn1.js";
|
|
3
|
-
import { OIDS } from "../asn1/
|
|
4
|
-
import { encodeAuthorityInfoAccess, encodeBasicConstraints, encodeCertificatePolicies, encodeCrlDistributionPoints, encodeExtendedKeyUsage, encodeInhibitAnyPolicy, encodeKeyUsage, encodeNameConstraints, encodePolicyConstraints, encodePolicyMappings, encodeSubjectAltName } from "../../x509/extensions.js";
|
|
5
|
-
import { parseAuthorityInfoAccess, parseAuthorityKeyIdentifier, parseBasicConstraints, parseCertificatePolicies, parseCrlDistributionPoints, parseExtendedKeyUsage, parseInhibitAnyPolicy, parseKeyUsage, parseNameConstraints, parsePolicyConstraints, parsePolicyMappings, parseSubjectAltNames } from "../../x509/parse.js";
|
|
1
|
+
import { implicitPrimitiveContext as e, octetString as t, readRootElement as n, sequence as r } from "../asn1/der.js";
|
|
2
|
+
import { hexToBytes as i, toHex as a } from "../asn1/asn1.js";
|
|
3
|
+
import { OIDS as o } from "../asn1/oids2.js";
|
|
4
|
+
import { encodeAuthorityInfoAccess as s, encodeBasicConstraints as c, encodeCertificatePolicies as l, encodeCrlDistributionPoints as u, encodeExtendedKeyUsage as d, encodeInhibitAnyPolicy as f, encodeKeyUsage as p, encodeNameConstraints as m, encodePolicyConstraints as h, encodePolicyMappings as g, encodeSubjectAltName as _ } from "../../x509/extensions.js";
|
|
5
|
+
import { parseAuthorityInfoAccess as v, parseAuthorityKeyIdentifier as y, parseBasicConstraints as b, parseCertificatePolicies as x, parseCrlDistributionPoints as S, parseExtendedKeyUsage as C, parseInhibitAnyPolicy as w, parseKeyUsage as T, parseNameConstraints as E, parsePolicyConstraints as D, parsePolicyMappings as O, parseSubjectAltNames as k } from "../../x509/parse.js";
|
|
6
6
|
//#region src/internal/x509/extension-registry.ts
|
|
7
7
|
/**
|
|
8
8
|
* Internal extension registry for certificate and CSR parsing.
|
|
@@ -20,172 +20,142 @@ import { parseAuthorityInfoAccess, parseAuthorityKeyIdentifier, parseBasicConstr
|
|
|
20
20
|
* when the concrete generic type is known, avoiding the correlated-union problem
|
|
21
21
|
* that would arise from calling `decode` and `applyParsed` through a union type.
|
|
22
22
|
*/
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
const BASIC_CONSTRAINTS_EXTENSION_DEFINITION = defineExtensionDefinition({
|
|
26
|
-
oid: OIDS.basicConstraints,
|
|
23
|
+
const A = /* @__PURE__ */ new Map(), j = defineExtensionDefinition({
|
|
24
|
+
oid: o.basicConstraints,
|
|
27
25
|
contexts: ["certificate", "csr"],
|
|
28
|
-
defaultCritical:
|
|
29
|
-
decode: (
|
|
30
|
-
encode: (
|
|
31
|
-
applyParsed: (
|
|
32
|
-
|
|
26
|
+
defaultCritical: !0,
|
|
27
|
+
decode: (e) => b(e),
|
|
28
|
+
encode: (e) => c(e),
|
|
29
|
+
applyParsed: (e, t) => {
|
|
30
|
+
e.basicConstraints = t;
|
|
33
31
|
}
|
|
34
|
-
})
|
|
35
|
-
|
|
36
|
-
const KEY_USAGE_EXTENSION_DEFINITION = defineExtensionDefinition({
|
|
37
|
-
oid: OIDS.keyUsage,
|
|
32
|
+
}), M = defineExtensionDefinition({
|
|
33
|
+
oid: o.keyUsage,
|
|
38
34
|
contexts: ["certificate", "csr"],
|
|
39
|
-
defaultCritical:
|
|
40
|
-
decode: (
|
|
41
|
-
encode: (
|
|
42
|
-
applyParsed: (
|
|
43
|
-
|
|
35
|
+
defaultCritical: !0,
|
|
36
|
+
decode: (e) => T(e),
|
|
37
|
+
encode: (e) => p(e),
|
|
38
|
+
applyParsed: (e, t) => {
|
|
39
|
+
e.keyUsage = t;
|
|
44
40
|
}
|
|
45
|
-
})
|
|
46
|
-
|
|
47
|
-
const EXTENDED_KEY_USAGE_EXTENSION_DEFINITION = defineExtensionDefinition({
|
|
48
|
-
oid: OIDS.extendedKeyUsage,
|
|
41
|
+
}), N = defineExtensionDefinition({
|
|
42
|
+
oid: o.extendedKeyUsage,
|
|
49
43
|
contexts: ["certificate", "csr"],
|
|
50
|
-
defaultCritical:
|
|
51
|
-
decode: (
|
|
52
|
-
encode: (
|
|
53
|
-
applyParsed: (
|
|
54
|
-
|
|
44
|
+
defaultCritical: !1,
|
|
45
|
+
decode: (e) => C(e),
|
|
46
|
+
encode: (e) => d(e),
|
|
47
|
+
applyParsed: (e, t) => {
|
|
48
|
+
e.extendedKeyUsage = t;
|
|
55
49
|
}
|
|
56
|
-
})
|
|
57
|
-
|
|
58
|
-
const SUBJECT_ALT_NAME_EXTENSION_DEFINITION = defineExtensionDefinition({
|
|
59
|
-
oid: OIDS.subjectAltName,
|
|
50
|
+
}), P = defineExtensionDefinition({
|
|
51
|
+
oid: o.subjectAltName,
|
|
60
52
|
contexts: ["certificate", "csr"],
|
|
61
|
-
defaultCritical:
|
|
62
|
-
decode: (
|
|
63
|
-
encode: (
|
|
64
|
-
applyParsed: (
|
|
65
|
-
|
|
53
|
+
defaultCritical: !1,
|
|
54
|
+
decode: (e) => k(e),
|
|
55
|
+
encode: (e) => r(e.map(_)),
|
|
56
|
+
applyParsed: (e, t) => {
|
|
57
|
+
e.subjectAltNames = t;
|
|
66
58
|
}
|
|
67
|
-
})
|
|
68
|
-
|
|
69
|
-
const NAME_CONSTRAINTS_EXTENSION_DEFINITION = defineExtensionDefinition({
|
|
70
|
-
oid: OIDS.nameConstraints,
|
|
59
|
+
}), F = defineExtensionDefinition({
|
|
60
|
+
oid: o.nameConstraints,
|
|
71
61
|
contexts: ["certificate", "csr"],
|
|
72
|
-
defaultCritical:
|
|
73
|
-
decode: (
|
|
74
|
-
encode: (
|
|
75
|
-
applyParsed: (
|
|
76
|
-
|
|
62
|
+
defaultCritical: !0,
|
|
63
|
+
decode: (e) => E(e),
|
|
64
|
+
encode: (e) => m(e),
|
|
65
|
+
applyParsed: (e, t) => {
|
|
66
|
+
e.nameConstraints = t;
|
|
77
67
|
}
|
|
78
|
-
})
|
|
79
|
-
|
|
80
|
-
const CERTIFICATE_POLICIES_EXTENSION_DEFINITION = defineExtensionDefinition({
|
|
81
|
-
oid: OIDS.certificatePolicies,
|
|
68
|
+
}), I = defineExtensionDefinition({
|
|
69
|
+
oid: o.certificatePolicies,
|
|
82
70
|
contexts: ["certificate", "csr"],
|
|
83
|
-
defaultCritical:
|
|
84
|
-
decode: (
|
|
85
|
-
encode: (
|
|
86
|
-
applyParsed: (
|
|
87
|
-
|
|
71
|
+
defaultCritical: !1,
|
|
72
|
+
decode: (e) => x(e),
|
|
73
|
+
encode: (e) => l(e),
|
|
74
|
+
applyParsed: (e, t) => {
|
|
75
|
+
e.certificatePolicies = t;
|
|
88
76
|
}
|
|
89
|
-
})
|
|
90
|
-
|
|
91
|
-
const POLICY_MAPPINGS_EXTENSION_DEFINITION = defineExtensionDefinition({
|
|
92
|
-
oid: OIDS.policyMappings,
|
|
77
|
+
}), L = defineExtensionDefinition({
|
|
78
|
+
oid: o.policyMappings,
|
|
93
79
|
contexts: ["certificate", "csr"],
|
|
94
|
-
defaultCritical:
|
|
95
|
-
decode: (
|
|
96
|
-
encode: (
|
|
97
|
-
applyParsed: (
|
|
98
|
-
|
|
80
|
+
defaultCritical: !0,
|
|
81
|
+
decode: (e) => O(e),
|
|
82
|
+
encode: (e) => g(e),
|
|
83
|
+
applyParsed: (e, t) => {
|
|
84
|
+
e.policyMappings = t;
|
|
99
85
|
}
|
|
100
|
-
})
|
|
101
|
-
|
|
102
|
-
const POLICY_CONSTRAINTS_EXTENSION_DEFINITION = defineExtensionDefinition({
|
|
103
|
-
oid: OIDS.policyConstraints,
|
|
86
|
+
}), R = defineExtensionDefinition({
|
|
87
|
+
oid: o.policyConstraints,
|
|
104
88
|
contexts: ["certificate", "csr"],
|
|
105
|
-
defaultCritical:
|
|
106
|
-
decode: (
|
|
107
|
-
encode: (
|
|
108
|
-
applyParsed: (
|
|
109
|
-
|
|
89
|
+
defaultCritical: !0,
|
|
90
|
+
decode: (e) => D(e),
|
|
91
|
+
encode: (e) => h(e),
|
|
92
|
+
applyParsed: (e, t) => {
|
|
93
|
+
e.policyConstraints = t;
|
|
110
94
|
}
|
|
111
|
-
})
|
|
112
|
-
|
|
113
|
-
const INHIBIT_ANY_POLICY_EXTENSION_DEFINITION = defineExtensionDefinition({
|
|
114
|
-
oid: OIDS.inhibitAnyPolicy,
|
|
95
|
+
}), z = defineExtensionDefinition({
|
|
96
|
+
oid: o.inhibitAnyPolicy,
|
|
115
97
|
contexts: ["certificate", "csr"],
|
|
116
|
-
defaultCritical:
|
|
117
|
-
decode: (
|
|
118
|
-
encode: (
|
|
119
|
-
applyParsed: (
|
|
120
|
-
|
|
98
|
+
defaultCritical: !0,
|
|
99
|
+
decode: (e) => w(e),
|
|
100
|
+
encode: (e) => f(e),
|
|
101
|
+
applyParsed: (e, t) => {
|
|
102
|
+
e.inhibitAnyPolicy = t;
|
|
121
103
|
}
|
|
122
|
-
})
|
|
123
|
-
|
|
124
|
-
const AUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION = defineExtensionDefinition({
|
|
125
|
-
oid: OIDS.authorityInfoAccess,
|
|
104
|
+
}), B = defineExtensionDefinition({
|
|
105
|
+
oid: o.authorityInfoAccess,
|
|
126
106
|
contexts: ["certificate", "csr"],
|
|
127
|
-
defaultCritical:
|
|
128
|
-
decode: (
|
|
129
|
-
encode: (
|
|
130
|
-
applyParsed: (
|
|
131
|
-
|
|
107
|
+
defaultCritical: !1,
|
|
108
|
+
decode: (e) => v(e),
|
|
109
|
+
encode: (e) => s(e),
|
|
110
|
+
applyParsed: (e, t) => {
|
|
111
|
+
e.authorityInfoAccess = t;
|
|
132
112
|
}
|
|
133
|
-
})
|
|
134
|
-
|
|
135
|
-
const CRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION = defineExtensionDefinition({
|
|
136
|
-
oid: OIDS.cRLDistributionPoints,
|
|
113
|
+
}), V = defineExtensionDefinition({
|
|
114
|
+
oid: o.cRLDistributionPoints,
|
|
137
115
|
contexts: ["certificate", "csr"],
|
|
138
|
-
defaultCritical:
|
|
139
|
-
decode: (
|
|
140
|
-
encode: (
|
|
141
|
-
applyParsed: (
|
|
142
|
-
|
|
116
|
+
defaultCritical: !1,
|
|
117
|
+
decode: (e) => S(e),
|
|
118
|
+
encode: (e) => u(e),
|
|
119
|
+
applyParsed: (e, t) => {
|
|
120
|
+
e.crlDistributionPoints = t;
|
|
143
121
|
}
|
|
144
|
-
})
|
|
145
|
-
|
|
146
|
-
const SUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION = defineExtensionDefinition({
|
|
147
|
-
oid: OIDS.subjectKeyIdentifier,
|
|
122
|
+
}), H = defineExtensionDefinition({
|
|
123
|
+
oid: o.subjectKeyIdentifier,
|
|
148
124
|
contexts: ["certificate"],
|
|
149
|
-
defaultCritical:
|
|
150
|
-
autoGenerated:
|
|
151
|
-
decode: (
|
|
152
|
-
encode: (
|
|
153
|
-
applyParsed: (
|
|
154
|
-
|
|
125
|
+
defaultCritical: !1,
|
|
126
|
+
autoGenerated: !0,
|
|
127
|
+
decode: (e) => decodeSubjectKeyIdentifier(e),
|
|
128
|
+
encode: (e) => t(normalizeKeyIdentifier(e)),
|
|
129
|
+
applyParsed: (e, t) => {
|
|
130
|
+
e.subjectKeyIdentifier = t;
|
|
155
131
|
}
|
|
156
|
-
})
|
|
157
|
-
|
|
158
|
-
const AUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION = defineExtensionDefinition({
|
|
159
|
-
oid: OIDS.authorityKeyIdentifier,
|
|
132
|
+
}), U = defineExtensionDefinition({
|
|
133
|
+
oid: o.authorityKeyIdentifier,
|
|
160
134
|
contexts: ["certificate"],
|
|
161
|
-
defaultCritical:
|
|
162
|
-
autoGenerated:
|
|
163
|
-
decode: (
|
|
164
|
-
encode: (
|
|
165
|
-
applyParsed: (
|
|
166
|
-
|
|
135
|
+
defaultCritical: !1,
|
|
136
|
+
autoGenerated: !0,
|
|
137
|
+
decode: (e) => y(e),
|
|
138
|
+
encode: (t) => r([e(0, normalizeKeyIdentifier(t))]),
|
|
139
|
+
applyParsed: (e, t) => {
|
|
140
|
+
t !== void 0 && (e.authorityKeyIdentifier = t);
|
|
167
141
|
}
|
|
168
|
-
})
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
/** OID-keyed lookup for known extension definitions. */
|
|
186
|
-
const EXTENSION_DEFINITION_MAP = new Map(CERT_CSR_EXTENSION_DEFINITIONS.map((definition) => [definition.oid, definition]));
|
|
187
|
-
function getExtensionDefinition(oid) {
|
|
188
|
-
return EXTENSION_DEFINITION_MAP.get(oid);
|
|
142
|
+
}), W = [
|
|
143
|
+
j,
|
|
144
|
+
M,
|
|
145
|
+
N,
|
|
146
|
+
P,
|
|
147
|
+
F,
|
|
148
|
+
I,
|
|
149
|
+
L,
|
|
150
|
+
R,
|
|
151
|
+
z,
|
|
152
|
+
B,
|
|
153
|
+
V,
|
|
154
|
+
H,
|
|
155
|
+
U
|
|
156
|
+
], G = new Map(W.map((e) => [e.oid, e]));
|
|
157
|
+
function getExtensionDefinition(e) {
|
|
158
|
+
return G.get(e);
|
|
189
159
|
}
|
|
190
160
|
/**
|
|
191
161
|
* If `oid` matches a known extension valid in `context`, decode its DER
|
|
@@ -193,13 +163,11 @@ function getExtensionDefinition(oid) {
|
|
|
193
163
|
*
|
|
194
164
|
* @returns `true` if the extension was recognized and applied.
|
|
195
165
|
*/
|
|
196
|
-
function decodeAndApplyKnownExtension(
|
|
197
|
-
|
|
198
|
-
if (
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
applier(accumulator, valueDer);
|
|
202
|
-
return true;
|
|
166
|
+
function decodeAndApplyKnownExtension(e, t, n, r) {
|
|
167
|
+
let i = getExtensionDefinition(t);
|
|
168
|
+
if (i === void 0 || !i.contexts.includes(e)) return !1;
|
|
169
|
+
let a = A.get(t);
|
|
170
|
+
return a === void 0 ? !1 : (a(n, r), !0);
|
|
203
171
|
}
|
|
204
172
|
/**
|
|
205
173
|
* Identity helper that narrows the type of an {@linkcode ExtensionDefinition} literal
|
|
@@ -209,21 +177,22 @@ function decodeAndApplyKnownExtension(context, oid, accumulator, valueDer) {
|
|
|
209
177
|
* `decodeAndApplyKnownExtension` can call it through the union-typed
|
|
210
178
|
* `KnownExtensionDefinition` without hitting TypeScript's correlated-union limitation.
|
|
211
179
|
*/
|
|
212
|
-
function defineExtensionDefinition(
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
});
|
|
216
|
-
return definition;
|
|
180
|
+
function defineExtensionDefinition(e) {
|
|
181
|
+
return A.set(e.oid, (t, n) => {
|
|
182
|
+
e.applyParsed(t, e.decode(n));
|
|
183
|
+
}), e;
|
|
217
184
|
}
|
|
218
185
|
/** Accept hex string or Uint8Array and return raw bytes. */
|
|
219
|
-
function normalizeKeyIdentifier(
|
|
220
|
-
return typeof
|
|
186
|
+
function normalizeKeyIdentifier(e) {
|
|
187
|
+
return typeof e == "string" ? i(e) : e;
|
|
221
188
|
}
|
|
222
189
|
/** Decode an SKI extension value DER to a hex string. */
|
|
223
|
-
function decodeSubjectKeyIdentifier(
|
|
224
|
-
|
|
225
|
-
if (
|
|
226
|
-
return
|
|
190
|
+
function decodeSubjectKeyIdentifier(e) {
|
|
191
|
+
let t = n(e, { maxDepth: 64 });
|
|
192
|
+
if (t.tag !== 4) throw Error("SubjectKeyIdentifier must be an OCTET STRING");
|
|
193
|
+
return a(t.value);
|
|
227
194
|
}
|
|
228
195
|
//#endregion
|
|
229
|
-
export { AUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION, AUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION, BASIC_CONSTRAINTS_EXTENSION_DEFINITION, CERTIFICATE_POLICIES_EXTENSION_DEFINITION, CERT_CSR_EXTENSION_DEFINITIONS, CRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION, EXTENDED_KEY_USAGE_EXTENSION_DEFINITION, INHIBIT_ANY_POLICY_EXTENSION_DEFINITION, KEY_USAGE_EXTENSION_DEFINITION, NAME_CONSTRAINTS_EXTENSION_DEFINITION, POLICY_CONSTRAINTS_EXTENSION_DEFINITION, POLICY_MAPPINGS_EXTENSION_DEFINITION, SUBJECT_ALT_NAME_EXTENSION_DEFINITION, SUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION, decodeAndApplyKnownExtension, getExtensionDefinition };
|
|
196
|
+
export { B as AUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION, U as AUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION, j as BASIC_CONSTRAINTS_EXTENSION_DEFINITION, I as CERTIFICATE_POLICIES_EXTENSION_DEFINITION, W as CERT_CSR_EXTENSION_DEFINITIONS, V as CRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION, N as EXTENDED_KEY_USAGE_EXTENSION_DEFINITION, z as INHIBIT_ANY_POLICY_EXTENSION_DEFINITION, M as KEY_USAGE_EXTENSION_DEFINITION, F as NAME_CONSTRAINTS_EXTENSION_DEFINITION, R as POLICY_CONSTRAINTS_EXTENSION_DEFINITION, L as POLICY_MAPPINGS_EXTENSION_DEFINITION, P as SUBJECT_ALT_NAME_EXTENSION_DEFINITION, H as SUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION, decodeAndApplyKnownExtension, getExtensionDefinition };
|
|
197
|
+
|
|
198
|
+
//# sourceMappingURL=extension-registry.js.map
|