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/pkcs/pfx.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"pfx.js","names":[],"sources":["../../src/pkcs/pfx.ts"],"sourcesContent":["/**\n * PKCS#12/PFX container creation and parsing.\n *\n * Builds and decodes PFX archives containing certificate bags, private-key bags,\n * optional PBES2 encryption, and PKCS#12 MAC integrity verification.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1.ts';\nimport type { DerElement } from '#micro509/internal/asn1/der.ts';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadSequenceChildren,\n\tsequence,\n\tsetOf,\n\ttlv,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport {\n\tdecryptPbes2,\n\tencryptPbes2,\n\tisWrongPasswordError,\n\ttype Pbes2EncryptionOptions,\n} from '#micro509/internal/crypto/pbes2.ts';\nimport { base64Encode } from '#micro509/internal/shared/base64.ts';\nimport { exportPkcs8Der } from '#micro509/keys/keys.ts';\nimport { pemEncode, splitPemBlocksOrThrow } from '#micro509/pem/pem.ts';\nimport { type ErrorResult, failureResult, type Micro509Error } from '#micro509/result/result.ts';\nimport { type ParsedCertificate, parseCertificateDerOrThrow } from '#micro509/x509/parse.ts';\nimport {\n\tcreatePkcs12MacData,\n\ttype ParsedPkcs12MacData,\n\ttype Pkcs12MacOptions,\n\tparsePkcs12MacData,\n} from './pkcs12-mac.ts';\n\nexport type * from './pkcs12-mac.ts';\n\n/** PEM string or DER bytes for a certificate to include in a PFX bag. */\nexport type PfxCertificateSource = string | Uint8Array | ParsedCertificate;\n/** A WebCrypto private key or raw PKCS#8 DER bytes for a PFX key bag. */\nexport type PfxPrivateKeySource = CryptoKey | Uint8Array;\n\n/** Optional metadata attached to a certificate or key bag inside a PFX. */\nexport interface PfxBagAttributesInput {\n\t/** Human-readable label stored as a BMPString attribute. */\n\treadonly friendlyName?: string;\n\t/** Opaque identifier linking a certificate bag to its corresponding key bag. */\n\treadonly localKeyId?: Uint8Array;\n}\n\n/** A certificate to embed in a PFX container. Input for {@linkcode createPfx}. */\nexport interface PfxCertificateBagInput {\n\t/** Certificate as PEM text or DER bytes. */\n\treadonly certificate: PfxCertificateSource;\n\t/** Optional bag-level attributes (friendly name, local key ID). */\n\treadonly attributes?: PfxBagAttributesInput;\n}\n\n/** A private key to embed in a PFX container. Input for {@linkcode createPfx}. */\nexport interface PfxPrivateKeyBagInput {\n\t/** Private key as a WebCrypto `CryptoKey` or raw PKCS#8 DER bytes. */\n\treadonly privateKey: PfxPrivateKeySource;\n\t/** Optional bag-level attributes (friendly name, local key ID). */\n\treadonly attributes?: PfxBagAttributesInput;\n}\n\n/** Input for {@linkcode createPfx}. */\nexport interface CreatePfxInput {\n\t/** Certificates to include as certBag entries. */\n\treadonly certificates?: readonly PfxCertificateBagInput[];\n\t/** Private keys to include as keyBag entries. */\n\treadonly privateKeys?: readonly PfxPrivateKeyBagInput[];\n\t/** PBES2 encryption settings for the key-bag ContentInfo. Omit for unencrypted. */\n\treadonly encryption?: PfxEncryptionOptions;\n\t/** PKCS#12 MAC integrity settings. Omit to skip MAC generation. */\n\treadonly mac?: Pkcs12MacOptions;\n}\n\n/** PBES2 encryption settings for PFX key-bag protection. Alias of {@linkcode Pbes2EncryptionOptions}. */\nexport type PfxEncryptionOptions = Pbes2EncryptionOptions;\n\n/** Options for {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport interface ParsePfxOptions {\n\t/** Password used to decrypt PBES2-encrypted ContentInfo entries. Also used for MAC verification when `macPassword` is omitted. */\n\treadonly password?: string;\n\t/** Separate password for MAC verification. Falls back to `password` when omitted. */\n\treadonly macPassword?: string;\n}\n\n/** DER, PEM, and base64 encodings of a PFX container produced by {@linkcode createPfx}. */\nexport interface PfxMaterial {\n\t/** Raw DER-encoded PFX bytes. */\n\treadonly der: Uint8Array;\n\t/** PEM-armored PFX (`-----BEGIN PKCS12-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armor). */\n\treadonly base64: string;\n}\n\n/** A single PKCS#12 bag attribute as decoded by {@linkcode parsePfxDer}. */\nexport interface ParsedPfxAttribute {\n\t/** Dotted-decimal OID identifying this attribute type. */\n\treadonly oid: string;\n\t/** Hex-encoded DER of each attribute value. */\n\treadonly valuesHex: readonly string[];\n}\n\n/** Decoded bag attributes for a single SafeBag inside a PFX. */\nexport interface ParsedPfxBagAttributes {\n\t/** All raw attributes as OID + hex-encoded values. */\n\treadonly entries: readonly ParsedPfxAttribute[];\n\t/** Decoded BMPString friendly-name attribute, if present. */\n\treadonly friendlyName?: string;\n\t/** Hex-encoded localKeyId attribute, if present. */\n\treadonly localKeyId?: string;\n}\n\n/**\n * Discriminated union of SafeBag types decoded from a PFX container.\n *\n * Use `kind` to narrow: `'certificate'` | `'privateKey'` | `'unknown'`.\n */\nexport type ParsedPfxBag =\n\t| {\n\t\t\t/** Bag contains an X.509 certificate. */\n\t\t\treadonly kind: 'certificate';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Parsed certificate from the certBag. */\n\t\t\treadonly certificate: ParsedCertificate;\n\t }\n\t| {\n\t\t\t/** Bag contains a PKCS#8 private key. */\n\t\t\treadonly kind: 'privateKey';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Raw DER-encoded PKCS#8 PrivateKeyInfo. */\n\t\t\treadonly pkcs8Der: Uint8Array;\n\t }\n\t| {\n\t\t\t/** Bag type not recognized by this library. */\n\t\t\treadonly kind: 'unknown';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Raw DER of the unrecognized bag value. */\n\t\t\treadonly valueDer: Uint8Array;\n\t };\n\n/** Fully decoded PFX container returned by {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */\nexport interface ParsedPfx {\n\t/** All SafeBags in the PFX, including unknown types. */\n\treadonly bags: readonly ParsedPfxBag[];\n\t/** Convenience: only the parsed certificates extracted from certBag entries. */\n\treadonly certificates: readonly ParsedCertificate[];\n\t/** Convenience: raw PKCS#8 DER of each private key extracted from keyBag entries. */\n\treadonly privateKeys: readonly Uint8Array[];\n\t/** MAC verification metadata, present when the PFX includes a MacData block. */\n\treadonly macData?: ParsedPkcs12MacData;\n}\n\n// ---------------------------------------------------------------------------\n// Result types for PFX parsing\n// ---------------------------------------------------------------------------\n\n/** Error codes returned by {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport type ParsePfxErrorCode = 'malformed' | 'invalid_password' | 'password_required';\n\n/** Error payload for a failed PFX parse. */\nexport interface ParsePfxFailure extends Micro509Error<ParsePfxErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */\nexport type ParsePfxResult =\n\t| {\n\t\t\t/** Parse succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** Decoded PFX container. */\n\t\t\treadonly value: ParsedPfx;\n\t }\n\t| ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\n// ---------------------------------------------------------------------------\n// Result types for PFX creation\n// ---------------------------------------------------------------------------\n\n/**\n * Caller-correctable failure code from {@linkcode createPfx}.\n *\n * The only parse boundary in creation is the certificate source: it is\n * normalized from untrusted PEM/DER. Private keys are either a WebCrypto\n * `CryptoKey` (platform errors stay throws) or raw PKCS#8 bytes passed through\n * unvalidated, so there is no distinct `invalid_private_key` failure to model.\n */\nexport type CreatePfxErrorCode = 'invalid_certificate';\n\n/** Error payload for a failed PFX creation. */\nexport interface CreatePfxFailure extends Micro509Error<CreatePfxErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode createPfx}. */\nexport type CreatePfxResult =\n\t| {\n\t\t\t/** Creation succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** DER, PEM, and base64 forms of the PFX container. */\n\t\t\treadonly value: PfxMaterial;\n\t }\n\t| ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure>;\n\n// ---------------------------------------------------------------------------\n// createPfx\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a PKCS#12/PFX archive containing certificates and/or private keys.\n *\n * When `encryption` is provided, the key-bag ContentInfo is PBES2-encrypted.\n * When `mac` is provided, a PKCS#12 MAC integrity block is appended.\n *\n * Returns a {@linkcode CreatePfxResult}: the container material on success, or a\n * typed `invalid_certificate` failure when a certificate source is not a single\n * PEM/DER certificate.\n *\n * @example\n * ```ts\n * import { createPfx, unwrap } from 'micro509';\n *\n * const result = await createPfx({\n * certificates: [{ certificate: certPem }],\n * privateKeys: [{ privateKey: keyPair.privateKey }],\n * encryption: { password: 's3cret' },\n * mac: { password: 's3cret' },\n * });\n * if (result.ok) {\n * const pfx = result.value; // pfx.der, pfx.pem, pfx.base64\n * }\n * // or, when inputs are already validated: const pfx = unwrap(result);\n * ```\n */\nexport async function createPfx(input: CreatePfxInput): Promise<CreatePfxResult> {\n\tconst certificateBags: Uint8Array[] = [];\n\tconst privateKeyBags: Uint8Array[] = [];\n\tfor (const certificate of input.certificates ?? []) {\n\t\t// normalizeCertificate parses untrusted PEM/DER and throws on malformed\n\t\t// input — a caller-correctable trust boundary, so map it to a typed failure.\n\t\tlet certificateDer: Uint8Array;\n\t\ttry {\n\t\t\tcertificateDer = normalizeCertificate(certificate.certificate);\n\t\t} catch {\n\t\t\treturn pfxCreationFailure(\n\t\t\t\t'invalid_certificate',\n\t\t\t\t'Each PFX certificate source must be a single PEM or DER certificate',\n\t\t\t);\n\t\t}\n\t\tcertificateBags.push(createCertificateBag(certificateDer, certificate.attributes));\n\t}\n\tfor (const privateKey of input.privateKeys ?? []) {\n\t\tprivateKeyBags.push(\n\t\t\tcreatePrivateKeyBag(await normalizePrivateKey(privateKey.privateKey), privateKey.attributes),\n\t\t);\n\t}\n\tconst contentInfos: Uint8Array[] = [];\n\tif (certificateBags.length > 0) {\n\t\tcontentInfos.push(createDataContentInfo(sequence(certificateBags)));\n\t}\n\tif (privateKeyBags.length > 0) {\n\t\tconst safeContents = sequence(privateKeyBags);\n\t\tcontentInfos.push(\n\t\t\tinput.encryption === undefined\n\t\t\t\t? createDataContentInfo(safeContents)\n\t\t\t\t: await createEncryptedDataContentInfo(safeContents, input.encryption),\n\t\t);\n\t}\n\tconst authenticatedSafe = sequence(contentInfos);\n\tconst macData =\n\t\tinput.mac === undefined ? undefined : await createPkcs12MacData(authenticatedSafe, input.mac);\n\tconst der = sequence([\n\t\tintegerFromNumber(3),\n\t\tcreateDataContentInfo(authenticatedSafe),\n\t\t...(macData === undefined ? [] : [macData.der]),\n\t]);\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tder,\n\t\t\tpem: pemEncode('PKCS12', der),\n\t\t\tbase64: base64Encode(der),\n\t\t},\n\t};\n}\n\n/** Shorthand for constructing a PFX creation failure result. */\nfunction pfxCreationFailure(\n\tcode: CreatePfxErrorCode,\n\tmessage: string,\n): ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure> {\n\treturn failureResult(code, message);\n}\n\n// ---------------------------------------------------------------------------\n// parsePfxDer / parsePfxPem — Result-returning\n// ---------------------------------------------------------------------------\n\n/**\n * Decodes a DER-encoded PKCS#12/PFX container into its constituent bags.\n *\n * Returns a result union — check `ok` before accessing `value`.\n * Encrypted containers require `options.password`. MAC verification uses\n * `options.macPassword` (falls back to `options.password`).\n *\n * @example\n * ```ts\n * import { parsePfxDer } from 'micro509';\n *\n * const result = await parsePfxDer(pfxBytes, { password: 's3cret' });\n * if (result.ok) {\n * console.log(result.value.certificates.length);\n * }\n * ```\n */\nexport async function parsePfxDer(\n\tder: Uint8Array,\n\toptions?: ParsePfxOptions,\n): Promise<ParsePfxResult> {\n\ttry {\n\t\tconst topLevel = readSequenceChildren(der, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (topLevel.length < 2 || topLevel.length > 3) {\n\t\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t\t}\n\t\tconst version = topLevel[0];\n\t\tconst authSafe = topLevel[1];\n\t\tif (version === undefined || authSafe === undefined || version.tag !== 0x02) {\n\t\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t\t}\n\t\tif (decodeIntegerNumber(version.value) !== 3) {\n\t\t\treturn pfxFailure('malformed', 'Unsupported PFX version');\n\t\t}\n\t\tconst authSafeDer = der.slice(authSafe.start - authSafe.headerLength, authSafe.end);\n\t\tconst authenticatedSafeOctets = extractContentInfoData(authSafeDer);\n\t\tconst macElement = topLevel[2];\n\t\tlet macData: ParsedPkcs12MacData | undefined;\n\t\tif (macElement !== undefined) {\n\t\t\tconst macResult = await parsePkcs12MacData(\n\t\t\t\tder.slice(macElement.start - macElement.headerLength, macElement.end),\n\t\t\t\tauthenticatedSafeOctets,\n\t\t\t\toptions?.macPassword ?? options?.password,\n\t\t\t);\n\t\t\tif (!macResult.ok) {\n\t\t\t\treturn pfxFailure('malformed', 'Malformed PFX MacData');\n\t\t\t}\n\t\t\tmacData = macResult.value;\n\t\t\tif (macData.verification === 'invalid') {\n\t\t\t\treturn pfxFailure('invalid_password', 'Invalid PFX MAC password or corrupted content');\n\t\t\t}\n\t\t}\n\t\tconst authenticatedSafe = readSequenceChildren(authenticatedSafeOctets);\n\t\tconst bags: ParsedPfxBag[] = [];\n\t\tfor (const contentInfo of authenticatedSafe) {\n\t\t\tconst contentInfoDer = authenticatedSafeOctets.slice(\n\t\t\t\tcontentInfo.start - contentInfo.headerLength,\n\t\t\t\tcontentInfo.end,\n\t\t\t);\n\t\t\tconst safeContentsResult = await extractSafeContents(contentInfoDer, options);\n\t\t\tif (safeContentsResult.error !== undefined) {\n\t\t\t\treturn safeContentsResult.error;\n\t\t\t}\n\t\t\tconst safeContents = safeContentsResult.data;\n\t\t\tfor (const bag of readSequenceChildren(safeContents)) {\n\t\t\t\tconst bagDer = safeContents.slice(bag.start - bag.headerLength, bag.end);\n\t\t\t\tbags.push(parseSafeBag(bagDer));\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: {\n\t\t\t\tbags,\n\t\t\t\tcertificates: bags.flatMap((bag) => (bag.kind === 'certificate' ? [bag.certificate] : [])),\n\t\t\t\tprivateKeys: bags.flatMap((bag) => (bag.kind === 'privateKey' ? [bag.pkcs8Der] : [])),\n\t\t\t\t...(macData === undefined ? {} : { macData }),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t}\n}\n\n/**\n * Decodes a PEM-armored PKCS#12/PFX container. Expects exactly one `PKCS12` block.\n *\n * Delegates to {@linkcode parsePfxDer} after PEM decoding.\n *\n * @example\n * ```ts\n * import { parsePfxPem } from 'micro509';\n *\n * const result = await parsePfxPem(pfxPemString, { password: 's3cret' });\n * if (result.ok) {\n * console.log(result.value.privateKeys.length);\n * }\n * ```\n */\nexport async function parsePfxPem(pem: string, options?: ParsePfxOptions): Promise<ParsePfxResult> {\n\ttry {\n\t\tconst blocks = splitPemBlocksOrThrow(pem).filter((block) => block.label === 'PKCS12');\n\t\tconst block = blocks[0];\n\t\tif (block === undefined || blocks.length !== 1) {\n\t\t\treturn pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block');\n\t\t}\n\t\treturn parsePfxDer(block.bytes, options);\n\t} catch {\n\t\treturn pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block');\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Private: PFX helpers\n// ---------------------------------------------------------------------------\n\n/** Shorthand for constructing a PFX parse failure result. */\nfunction pfxFailure(\n\tcode: ParsePfxErrorCode,\n\tmessage: string,\n): ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure> {\n\treturn failureResult(code, message);\n}\n\n/** Unwraps a `data` ContentInfo to its inner OCTET STRING payload. */\nfunction extractContentInfoData(contentInfoDer: Uint8Array): Uint8Array {\n\tconst contentInfoChildren = readSequenceChildren(contentInfoDer);\n\tconst contentType = contentInfoChildren[0];\n\tconst content = contentInfoChildren[1];\n\tif (\n\t\tcontentType === undefined ||\n\t\tcontent === undefined ||\n\t\tcontentInfoChildren.length !== 2 ||\n\t\tcontentType.tag !== 0x06\n\t) {\n\t\tthrow new Error('Malformed ContentInfo');\n\t}\n\tif (decodeObjectIdentifier(contentType.value) !== OIDS.pkcs7Data) {\n\t\tthrow new Error('Only passwordless data ContentInfo is supported');\n\t}\n\treturn extractContextOctetString(contentInfoDer, content);\n}\n\n/** Extracts SafeContents bytes from a ContentInfo, decrypting if EncryptedData. */\nasync function extractSafeContents(\n\tcontentInfoDer: Uint8Array,\n\toptions: ParsePfxOptions | undefined,\n): Promise<\n\t| {\n\t\t\treadonly data: Uint8Array;\n\t\t\treadonly error?: undefined;\n\t }\n\t| {\n\t\t\treadonly data?: undefined;\n\t\t\treadonly error: ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\t }\n> {\n\tconst contentInfoChildren = readSequenceChildren(contentInfoDer);\n\tconst contentType = contentInfoChildren[0];\n\tconst content = contentInfoChildren[1];\n\tif (\n\t\tcontentType === undefined ||\n\t\tcontent === undefined ||\n\t\tcontentInfoChildren.length !== 2 ||\n\t\tcontentType.tag !== 0x06\n\t) {\n\t\treturn { error: pfxFailure('malformed', 'Malformed ContentInfo') };\n\t}\n\tconst oid = decodeObjectIdentifier(contentType.value);\n\tif (oid === OIDS.pkcs7Data) {\n\t\treturn { data: extractContextOctetString(contentInfoDer, content) };\n\t}\n\tif (oid !== OIDS.pkcs7EncryptedData) {\n\t\treturn {\n\t\t\terror: pfxFailure('malformed', 'Unsupported PFX ContentInfo type'),\n\t\t};\n\t}\n\tif (options?.password === undefined) {\n\t\treturn {\n\t\t\terror: pfxFailure('password_required', 'Password required for encrypted PFX content'),\n\t\t};\n\t}\n\tconst encryptedData = extractContextChild(contentInfoDer, content);\n\tlet decrypted: Uint8Array;\n\ttry {\n\t\tdecrypted = await decryptEncryptedData(\n\t\t\tcontentInfoDer.slice(encryptedData.start - encryptedData.headerLength, encryptedData.end),\n\t\t\toptions.password,\n\t\t);\n\t} catch (error) {\n\t\tif (isWrongPasswordError(error)) {\n\t\t\treturn {\n\t\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX password or encrypted content'),\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\terror: pfxFailure('malformed', 'Malformed PFX encrypted content'),\n\t\t};\n\t}\n\ttry {\n\t\treadSequenceChildren(decrypted);\n\t} catch {\n\t\t// AES-CBC padding is unauthenticated: a wrong key passes the padding\n\t\t// check ~1/256 of the time and \"decrypts\" to random bytes that are not\n\t\t// a SafeContents SEQUENCE — a wrong password, not malformed input.\n\t\treturn {\n\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX password or encrypted content'),\n\t\t};\n\t}\n\treturn { data: decrypted };\n}\n\n/** Encodes a certBag SafeBag wrapping a DER certificate with optional attributes. */\nfunction createCertificateBag(\n\tcertificateDer: Uint8Array,\n\tattributes: PfxBagAttributesInput | undefined,\n): Uint8Array {\n\tconst certBag = sequence([\n\t\tobjectIdentifier(OIDS.x509CertificateBagType),\n\t\texplicitContext(0, octetString(certificateDer)),\n\t]);\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pkcs12CertBag),\n\t\texplicitContext(0, certBag),\n\t\t...encodeBagAttributes(attributes),\n\t]);\n}\n\n/** Encodes a keyBag SafeBag wrapping PKCS#8 DER with optional attributes. */\nfunction createPrivateKeyBag(\n\tpkcs8Der: Uint8Array,\n\tattributes: PfxBagAttributesInput | undefined,\n): Uint8Array {\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pkcs12KeyBag),\n\t\texplicitContext(0, pkcs8Der),\n\t\t...encodeBagAttributes(attributes),\n\t]);\n}\n\n/** Wraps raw bytes in a `pkcs7-data` ContentInfo SEQUENCE. */\nfunction createDataContentInfo(data: Uint8Array): Uint8Array {\n\treturn sequence([objectIdentifier(OIDS.pkcs7Data), explicitContext(0, octetString(data))]);\n}\n\n/** PBES2-encrypts data and wraps it in a `pkcs7-encryptedData` ContentInfo. */\nasync function createEncryptedDataContentInfo(\n\tdata: Uint8Array,\n\toptions: PfxEncryptionOptions,\n): Promise<Uint8Array> {\n\tconst encryption = await encryptPbes2(data, options);\n\tconst encryptedData = sequence([\n\t\tintegerFromNumber(0),\n\t\tsequence([\n\t\t\tobjectIdentifier(OIDS.pkcs7Data),\n\t\t\tencryption.algorithmIdentifierDer,\n\t\t\ttlv(0x80, encryption.encryptedData),\n\t\t]),\n\t]);\n\treturn sequence([objectIdentifier(OIDS.pkcs7EncryptedData), explicitContext(0, encryptedData)]);\n}\n\n/** DER-encodes optional friendlyName / localKeyId into a SET OF SEQUENCE. */\nfunction encodeBagAttributes(attributes: PfxBagAttributesInput | undefined): readonly Uint8Array[] {\n\tif (attributes === undefined) {\n\t\treturn [];\n\t}\n\tconst out: Uint8Array[] = [];\n\tif (attributes.friendlyName !== undefined) {\n\t\tout.push(\n\t\t\tsequence([objectIdentifier(OIDS.friendlyName), setOf([bmpString(attributes.friendlyName)])]),\n\t\t);\n\t}\n\tif (attributes.localKeyId !== undefined) {\n\t\tout.push(\n\t\t\tsequence([objectIdentifier(OIDS.localKeyId), setOf([octetString(attributes.localKeyId)])]),\n\t\t);\n\t}\n\treturn out.length === 0 ? [] : [setOf(out)];\n}\n\n/** Decodes a single SafeBag from DER into a {@linkcode ParsedPfxBag} discriminated union. */\nfunction parseSafeBag(der: Uint8Array): ParsedPfxBag {\n\tconst children = readSequenceChildren(der);\n\tconst bagId = children[0];\n\tconst bagValue = children[1];\n\tconst attributeSet = children[2];\n\tif (bagId === undefined || bagValue === undefined || children.length > 3) {\n\t\tthrow new Error('Malformed SafeBag');\n\t}\n\tconst bagOid = decodeObjectIdentifier(bagId.value);\n\tconst attributes = parseBagAttributes(der, attributeSet);\n\tif (bagOid === OIDS.pkcs12CertBag) {\n\t\tconst certBag = extractContextChild(der, bagValue);\n\t\tconst certBagDer = der.slice(certBag.start - certBag.headerLength, certBag.end);\n\t\tconst certBagChildren = readSequenceChildren(certBagDer);\n\t\tconst certType = certBagChildren[0];\n\t\tconst certValue = certBagChildren[1];\n\t\tif (\n\t\t\tcertType === undefined ||\n\t\t\tcertValue === undefined ||\n\t\t\tcertBagChildren.length !== 2 ||\n\t\t\tdecodeObjectIdentifier(certType.value) !== OIDS.x509CertificateBagType\n\t\t) {\n\t\t\tthrow new Error('Malformed certBag');\n\t\t}\n\t\tconst certificateDer = extractContextOctetString(certBagDer, certValue);\n\t\treturn {\n\t\t\tkind: 'certificate',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tcertificate: parseCertificateDerOrThrow(certificateDer),\n\t\t};\n\t}\n\tif (bagOid === OIDS.pkcs12KeyBag) {\n\t\tconst pkcs8 = extractContextChild(der, bagValue);\n\t\treturn {\n\t\t\tkind: 'privateKey',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tpkcs8Der: der.slice(pkcs8.start - pkcs8.headerLength, pkcs8.end),\n\t\t};\n\t}\n\tconst value = extractContextChild(der, bagValue);\n\treturn {\n\t\tkind: 'unknown',\n\t\tbagId: bagOid,\n\t\tattributes,\n\t\tvalueDer: der.slice(value.start - value.headerLength, value.end),\n\t};\n}\n\n/** Decodes the SET OF attributes attached to a SafeBag. */\nfunction parseBagAttributes(\n\tsource: Uint8Array,\n\tattributeSet: DerElement | undefined,\n): ParsedPfxBagAttributes {\n\tif (attributeSet === undefined) {\n\t\treturn { entries: [] };\n\t}\n\tconst entries: ParsedPfxAttribute[] = [];\n\tlet friendlyName: string | undefined;\n\tlet localKeyId: string | undefined;\n\tfor (const attribute of childrenOf(source, attributeSet)) {\n\t\tconst attributeDer = source.slice(attribute.start - attribute.headerLength, attribute.end);\n\t\tconst parts = readSequenceChildren(attributeDer);\n\t\tconst oid = parts[0];\n\t\tconst values = parts[1];\n\t\tif (oid === undefined || values === undefined || parts.length !== 2 || values.tag !== 0x31) {\n\t\t\tthrow new Error('Malformed PFX bag attribute');\n\t\t}\n\t\tconst attrOid = decodeObjectIdentifier(oid.value);\n\t\tconst rawValues = childrenOf(attributeDer, values).map((value) =>\n\t\t\tattributeDer.slice(value.start - value.headerLength, value.end),\n\t\t);\n\t\tentries.push({\n\t\t\toid: attrOid,\n\t\t\tvaluesHex: rawValues.map((value) => toHex(value)),\n\t\t});\n\t\tif (attrOid === OIDS.friendlyName) {\n\t\t\tconst firstValue = rawValues[0];\n\t\t\tif (friendlyName !== undefined || rawValues.length !== 1 || firstValue === undefined) {\n\t\t\t\tthrow new Error('Malformed friendlyName attribute');\n\t\t\t}\n\t\t\tfriendlyName = decodeBmpString(firstValue);\n\t\t\tcontinue;\n\t\t}\n\t\tif (attrOid === OIDS.localKeyId) {\n\t\t\tconst firstValue = rawValues[0];\n\t\t\tif (localKeyId !== undefined || rawValues.length !== 1 || firstValue === undefined) {\n\t\t\t\tthrow new Error('Malformed localKeyId attribute');\n\t\t\t}\n\t\t\tlocalKeyId = decodeLocalKeyId(firstValue);\n\t\t}\n\t}\n\treturn {\n\t\tentries,\n\t\t...(friendlyName === undefined ? {} : { friendlyName }),\n\t\t...(localKeyId === undefined ? {} : { localKeyId }),\n\t};\n}\n\nfunction decodeLocalKeyId(der: Uint8Array): string {\n\tconst element = readElement(der);\n\tif (element.tag !== 0x04) {\n\t\tthrow new Error('localKeyId must use OCTET STRING');\n\t}\n\treturn toHex(element.value);\n}\n\n/** Exports a `CryptoKey` to PKCS#8 DER, or passes raw bytes through. */\nasync function normalizePrivateKey(source: PfxPrivateKeySource): Promise<Uint8Array> {\n\tif (source instanceof CryptoKey) {\n\t\treturn exportPkcs8Der(source);\n\t}\n\treturn new Uint8Array(source);\n}\n\n/** Extracts DER bytes from a PEM string, or passes raw DER through. */\nfunction normalizeCertificate(source: PfxCertificateSource): Uint8Array {\n\tif (typeof source === 'string') {\n\t\tconst block = splitPemBlocksOrThrow(source).find(\n\t\t\t(candidate) => candidate.label === 'CERTIFICATE',\n\t\t);\n\t\tif (block === undefined) {\n\t\t\tthrow new Error('Certificate PEM required');\n\t\t}\n\t\treturn new Uint8Array(block.bytes);\n\t}\n\tif (source instanceof Uint8Array) {\n\t\treturn new Uint8Array(source);\n\t}\n\treturn new Uint8Array(source.der);\n}\n\n/** Decrypts a PKCS#7 EncryptedData structure using PBES2 with the given password. */\nasync function decryptEncryptedData(\n\tencryptedDataDer: Uint8Array,\n\tpassword: string,\n): Promise<Uint8Array> {\n\tconst topLevel = readSequenceChildren(encryptedDataDer);\n\tconst encryptedContentInfo = topLevel[1];\n\tif (topLevel.length !== 2 || encryptedContentInfo === undefined) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tconst version = topLevel[0];\n\tif (version === undefined || version.tag !== 0x02 || decodeIntegerNumber(version.value) !== 0) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tconst contentInfoDer = encryptedDataDer.slice(\n\t\tencryptedContentInfo.start - encryptedContentInfo.headerLength,\n\t\tencryptedContentInfo.end,\n\t);\n\tconst contentInfoChildren = readSequenceChildren(contentInfoDer);\n\tconst algorithm = contentInfoChildren[1];\n\tconst encryptedContent = contentInfoChildren[2];\n\tif (\n\t\talgorithm === undefined ||\n\t\tencryptedContent === undefined ||\n\t\tcontentInfoChildren.length !== 3 ||\n\t\tcontentInfoChildren[0]?.tag !== 0x06\n\t) {\n\t\tthrow new Error('Malformed EncryptedContentInfo');\n\t}\n\tif (encryptedContent.tag !== 0x80) {\n\t\tthrow new Error('Malformed encrypted content');\n\t}\n\treturn decryptPbes2(\n\t\tcontentInfoDer.slice(algorithm.start - algorithm.headerLength, algorithm.end),\n\t\tencryptedContent.value,\n\t\tpassword,\n\t);\n}\n\n/** Reads the first child of a context-tagged element, expecting an OCTET STRING. */\nfunction extractContextOctetString(source: Uint8Array, element: DerElement): Uint8Array {\n\tconst child = extractContextChild(source, element);\n\tif (child.tag !== 0x04) {\n\t\tthrow new Error('Expected OCTET STRING in context value');\n\t}\n\treturn child.value;\n}\n\n/** Reads the first child element inside a context-specific constructed wrapper. */\nfunction extractContextChild(source: Uint8Array, element: DerElement): DerElement {\n\tif ((element.tag & 0xe0) !== 0xa0) {\n\t\tthrow new Error('Expected context-specific constructed value');\n\t}\n\tconst children = childrenOf(source, element);\n\tconst child = children[0];\n\tif (children.length !== 1 || child === undefined) {\n\t\tthrow new Error('Expected context-specific wrapper with exactly one value');\n\t}\n\treturn child;\n}\n\n/** Encodes a JS string as an ASN.1 BMPString (UCS-2 big-endian, tag 0x1e). */\nfunction bmpString(value: string): Uint8Array {\n\tconst bytes = new Uint8Array(value.length * 2);\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tconst codePoint = value.charCodeAt(index);\n\t\tbytes[index * 2] = codePoint >> 8;\n\t\tbytes[index * 2 + 1] = codePoint & 0xff;\n\t}\n\treturn tlv(0x1e, bytes);\n}\n\n/** Decodes a DER-encoded BMPString (tag 0x1e) back to a JS string. */\nfunction decodeBmpString(der: Uint8Array): string {\n\tconst element = readElement(der);\n\tif (element.tag !== 0x1e) {\n\t\tthrow new Error('Expected BMPString');\n\t}\n\tif (element.value.length % 2 !== 0) {\n\t\tthrow new Error('BMPString must use an even number of bytes');\n\t}\n\tlet value = '';\n\tfor (let index = 0; index < element.value.length; index += 2) {\n\t\tconst left = element.value[index] ?? 0;\n\t\tconst right = element.value[index + 1] ?? 0;\n\t\tvalue += String.fromCharCode((left << 8) | right);\n\t}\n\treturn value;\n}\n"],"mappings":"o0BAqQA,eAAsB,EAAU,EAAiD,CAChF,IAAM,EAAgC,CAAC,EACjC,EAA+B,CAAC,EACtC,IAAK,IAAM,KAAe,EAAM,cAAgB,CAAC,EAAG,CAGnD,IAAI,EACJ,GAAI,CACH,EAAiB,EAAqB,EAAY,WAAW,CAC9D,MAAQ,CACP,OAAO,EACN,sBACA,qEACD,CACD,CACA,EAAgB,KAAK,EAAqB,EAAgB,EAAY,UAAU,CAAC,CAClF,CACA,IAAK,IAAM,KAAc,EAAM,aAAe,CAAC,EAC9C,EAAe,KACd,EAAoB,MAAM,EAAoB,EAAW,UAAU,EAAG,EAAW,UAAU,CAC5F,EAED,IAAM,EAA6B,CAAC,EAIpC,GAHI,EAAgB,OAAS,GAC5B,EAAa,KAAK,EAAsB,EAAS,CAAe,CAAC,CAAC,EAE/D,EAAe,OAAS,EAAG,CAC9B,IAAM,EAAe,EAAS,CAAc,EAC5C,EAAa,KACZ,EAAM,aAAe,IAAA,GAClB,EAAsB,CAAY,EA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D,EAE3E,OAAO,CACR,CAGA,SAAS,EAAU,EAA2B,CAC7C,IAAM,EAAQ,IAAI,WAAW,EAAM,OAAS,CAAC,EAC7C,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAM,OAAQ,GAAS,EAAG,CACrD,IAAM,EAAY,EAAM,WAAW,CAAK,EACxC,EAAM,EAAQ,GAAK,GAAa,EAChC,EAAM,EAAQ,EAAI,GAAK,EAAY,GACpC,CACA,OAAO,EAAI,GAAM,CAAK,CACvB,CAGA,SAAS,EAAgB,EAAyB,CACjD,IAAM,EAAU,EAAY,CAAG,EAC/B,GAAI,EAAQ,MAAQ,GACnB,MAAU,MAAM,oBAAoB,EAErC,GAAI,EAAQ,MAAM,OAAS,GAAM,EAChC,MAAU,MAAM,4CAA4C,EAE7D,IAAI,EAAQ,GACZ,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAQ,MAAM,OAAQ,GAAS,EAAG,CAC7D,IAAM,EAAO,EAAQ,MAAM,IAAU,EAC/B,EAAQ,EAAQ,MAAM,EAAQ,IAAM,EAC1C,GAAS,OAAO,aAAc,GAAQ,EAAK,CAAK,CACjD,CACA,OAAO,CACR"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"pkcs12-mac.js","names":[],"sources":["../../src/pkcs/pkcs12-mac.ts"],"sourcesContent":["/**\n * PKCS#12 MAC data creation and verification.\n *\n * Computes and verifies the password-based HMAC-SHA-256 integrity check\n * defined in PKCS#12 (RFC 7292), using the PKCS#12 key-derivation scheme.\n *\n * @module\n */\n\nimport {\n\ttype ErrorResult,\n\tfailureResult,\n\ttype Micro509Error,\n\trethrowIfInvariant,\n\tsuccessResult,\n} from '#micro509/result/result.ts';\nimport {\n\tdecodeNonNegativeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1.ts';\nimport {\n\tconcatBytes,\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport { describeHashAlgorithm } from '#micro509/internal/crypto/algorithm-names.ts';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto.ts';\n\n/** Input for {@linkcode createPkcs12MacData}. */\nexport interface Pkcs12MacOptions {\n\t/** Password used to derive the HMAC key via the PKCS#12 KDF. */\n\treadonly password: string;\n\t/** PKCS#12 KDF iteration count. Default: `2048`. */\n\treadonly iterations?: number;\n\t/** Random salt. Default: 16 cryptographically random bytes. */\n\treadonly salt?: Uint8Array;\n}\n\n/** Decoded PKCS#12 MacData block returned by {@linkcode parsePkcs12MacData}. */\nexport interface ParsedPkcs12MacData {\n\t/** OID of the digest algorithm (currently always SHA-256). */\n\treadonly digestAlgorithmOid: string;\n\t/** Human-readable digest algorithm name (currently `\"SHA-256\"`). */\n\treadonly digestAlgorithmName: string;\n\t/** Hex-encoded MAC digest value. */\n\treadonly digestHex: string;\n\t/** Hex-encoded salt bytes used during key derivation. */\n\treadonly saltHex: string;\n\t/** Number of PKCS#12 KDF iterations. */\n\treadonly iterations: number;\n\t/**\n\t * MAC verification outcome: `'unchecked'` when no password was supplied\n\t * during parsing, otherwise `'valid'` or `'invalid'`.\n\t */\n\treadonly verification: 'valid' | 'invalid' | 'unchecked';\n}\n\n/**\n * Computes a PKCS#12 HMAC-SHA-256 MAC over the AuthenticatedSafe and returns\n * the DER-encoded MacData block alongside its parsed representation.\n */\nexport async function createPkcs12MacData(\n\tauthenticatedSafe: Uint8Array,\n\toptions: Pkcs12MacOptions,\n): Promise<{\n\t/** DER-encoded MacData SEQUENCE. */\n\treadonly der: Uint8Array;\n\t/** Structured representation of the MAC parameters and digest. */\n\treadonly parsed: ParsedPkcs12MacData;\n}> {\n\tconst iterations = options.iterations ?? 2048;\n\tassertPkcs12MacIterations(iterations);\n\tconst salt = options.salt ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst mac = await computePkcs12Mac(authenticatedSafe, options.password, salt, iterations);\n\tconst der = sequence([\n\t\tsequence([sequence([objectIdentifier(OIDS.sha256), nullValue()]), octetString(mac)]),\n\t\toctetString(salt),\n\t\tintegerFromNumber(iterations),\n\t]);\n\treturn {\n\t\tder,\n\t\tparsed: {\n\t\t\tdigestAlgorithmOid: OIDS.sha256,\n\t\t\tdigestAlgorithmName: describeHashAlgorithm(OIDS.sha256),\n\t\t\tdigestHex: toHex(mac),\n\t\t\tsaltHex: toHex(salt),\n\t\t\titerations,\n\t\t\tverification: 'valid',\n\t\t},\n\t};\n}\n\n/** Machine-readable failure reason for {@linkcode parsePkcs12MacData}. */\nexport type ParsePkcs12MacDataErrorCode = 'malformed';\n\n/** Structured failure payload for MacData parsing. */\nexport interface ParsePkcs12MacDataFailure extends Micro509Error<ParsePkcs12MacDataErrorCode> {\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parsePkcs12MacData}. */\nexport type ParsePkcs12MacDataResult =\n\t| { readonly ok: true; readonly value: ParsedPkcs12MacData }\n\t| ErrorResult<ParsePkcs12MacDataErrorCode, Record<never, never>, ParsePkcs12MacDataFailure>;\n\n/**\n * Throwing core for {@linkcode parsePkcs12MacData}. When `password` is\n * provided, verifies the MAC and reports the outcome in `verification`.\n */\nexport async function parsePkcs12MacDataOrThrow(\n\tder: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\tpassword?: string,\n): Promise<ParsedPkcs12MacData> {\n\tconst top = readSequenceChildren(der);\n\tconst digestInfo = top[0];\n\tconst salt = top[1];\n\tconst iterations = top[2];\n\tif (\n\t\ttop.length !== 3 ||\n\t\tdigestInfo === undefined ||\n\t\tsalt === undefined ||\n\t\titerations === undefined ||\n\t\tsalt.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed MacData');\n\t}\n\tconst digestInfoDer = der.slice(digestInfo.start - digestInfo.headerLength, digestInfo.end);\n\tconst digestInfoChildren = readSequenceChildren(digestInfoDer);\n\tconst algorithm = digestInfoChildren[0];\n\tconst digest = digestInfoChildren[1];\n\tif (\n\t\tdigestInfoChildren.length !== 2 ||\n\t\talgorithm === undefined ||\n\t\tdigest === undefined ||\n\t\tdigest.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed DigestInfo');\n\t}\n\tconst algorithmDer = digestInfoDer.slice(algorithm.start - algorithm.headerLength, algorithm.end);\n\tconst algorithmChildren = readSequenceChildren(algorithmDer);\n\tconst algorithmOid = algorithmChildren[0];\n\tif (\n\t\talgorithmOid === undefined ||\n\t\t(algorithmChildren.length !== 1 && algorithmChildren.length !== 2)\n\t) {\n\t\tthrow new Error('MacData algorithm missing');\n\t}\n\tconst digestAlgorithmOid = decodeObjectIdentifier(algorithmOid.value);\n\tif (digestAlgorithmOid !== OIDS.sha256) {\n\t\tthrow new Error('Only SHA-256 PKCS#12 MAC is supported');\n\t}\n\tconst parsedIterations = decodeNonNegativeIntegerNumber(iterations.value, 'MacData iterations');\n\tassertPkcs12MacIterations(parsedIterations);\n\tif (password === undefined) {\n\t\treturn {\n\t\t\tdigestAlgorithmOid,\n\t\t\tdigestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),\n\t\t\tdigestHex: toHex(digest.value),\n\t\t\tsaltHex: toHex(salt.value),\n\t\t\titerations: parsedIterations,\n\t\t\tverification: 'unchecked',\n\t\t};\n\t}\n\tconst expected = await computePkcs12Mac(\n\t\tauthenticatedSafe,\n\t\tpassword,\n\t\tsalt.value,\n\t\tparsedIterations,\n\t);\n\treturn {\n\t\tdigestAlgorithmOid,\n\t\tdigestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),\n\t\tdigestHex: toHex(digest.value),\n\t\tsaltHex: toHex(salt.value),\n\t\titerations: parsedIterations,\n\t\tverification: equalBytes(expected, digest.value) ? 'valid' : 'invalid',\n\t};\n}\n\n/**\n * Decodes a DER-encoded MacData block. When `password` is provided, verifies\n * the MAC and reports the outcome in `verification`.\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parsePkcs12MacDataOrThrow}.\n */\nexport async function parsePkcs12MacData(\n\tder: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\tpassword?: string,\n): Promise<ParsePkcs12MacDataResult> {\n\ttry {\n\t\treturn successResult(await parsePkcs12MacDataOrThrow(der, authenticatedSafe, password));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult('malformed', error instanceof Error ? error.message : 'Malformed MacData');\n\t}\n}\n\nfunction assertPkcs12MacIterations(iterations: number): void {\n\tif (!Number.isSafeInteger(iterations) || iterations <= 0) {\n\t\tthrow new Error('MacData iterations must be a positive safe integer');\n\t}\n}\n\n/** Derives an HMAC-SHA-256 key via the PKCS#12 KDF and signs the AuthenticatedSafe. */\nasync function computePkcs12Mac(\n\tauthenticatedSafe: Uint8Array,\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n): Promise<Uint8Array> {\n\tconst keyBytes = await derivePkcs12Key(password, salt, iterations, 3, 32);\n\tconst key = await getCrypto().subtle.importKey(\n\t\t'raw',\n\t\ttoArrayBuffer(keyBytes),\n\t\t{ name: 'HMAC', hash: 'SHA-256' },\n\t\tfalse,\n\t\t['sign'],\n\t);\n\treturn new Uint8Array(\n\t\tawait getCrypto().subtle.sign('HMAC', key, toArrayBuffer(authenticatedSafe)),\n\t);\n}\n\n/** PKCS#12 key derivation (RFC 7292 Appendix B). `id` selects the purpose (3 = MAC key). */\nasync function derivePkcs12Key(\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n\tid: number,\n\tlength: number,\n): Promise<Uint8Array> {\n\tconst u = 32;\n\tconst v = 64;\n\tconst D = new Uint8Array(v).fill(id);\n\tconst passwordBytes = encodePkcs12Password(password);\n\tconst S = repeatToMultiple(salt, v);\n\tconst P = repeatToMultiple(passwordBytes, v);\n\tlet I = concatBytes([S, P]);\n\tconst blocks = Math.ceil(length / u);\n\tconst output = new Uint8Array(blocks * u);\n\tfor (let index = 0; index < blocks; index += 1) {\n\t\tlet A = await digestSha256(concatBytes([D, I]));\n\t\tfor (let round = 1; round < iterations; round += 1) {\n\t\t\tA = await digestSha256(A);\n\t\t}\n\t\toutput.set(A, index * u);\n\t\tif (I.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst B = repeatToLength(A, v);\n\t\tconst next = new Uint8Array(I.length);\n\t\tfor (let blockIndex = 0; blockIndex < I.length / v; blockIndex += 1) {\n\t\t\tconst block = I.slice(blockIndex * v, blockIndex * v + v);\n\t\t\taddBlockInPlace(block, B);\n\t\t\tnext.set(block, blockIndex * v);\n\t\t}\n\t\tI = next;\n\t}\n\treturn output.slice(0, length);\n}\n\n/** SHA-256 hash via WebCrypto. */\nasync function digestSha256(bytes: Uint8Array): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.digest('SHA-256', toArrayBuffer(bytes)));\n}\n\n/** Encodes a password as a null-terminated UCS-2 big-endian byte array (RFC 7292 B.1). */\nfunction encodePkcs12Password(password: string): Uint8Array {\n\tconst out = new Uint8Array((password.length + 1) * 2);\n\tfor (let index = 0; index < password.length; index += 1) {\n\t\tconst code = password.charCodeAt(index);\n\t\tout[index * 2] = code >> 8;\n\t\tout[index * 2 + 1] = code & 0xff;\n\t}\n\treturn out;\n}\n\n/** Repeats `bytes` to the nearest multiple of `size`. */\nfunction repeatToMultiple(bytes: Uint8Array, size: number): Uint8Array {\n\tif (bytes.length === 0) {\n\t\treturn new Uint8Array();\n\t}\n\treturn repeatToLength(bytes, size * Math.ceil(bytes.length / size));\n}\n\n/** Cyclically repeats `bytes` to fill exactly `length` bytes. */\nfunction repeatToLength(bytes: Uint8Array, length: number): Uint8Array {\n\tconst out = new Uint8Array(length);\n\tfor (let index = 0; index < length; index += 1) {\n\t\tout[index] = bytes[index % bytes.length] ?? 0;\n\t}\n\treturn out;\n}\n\n/** Big-endian add-with-carry of `addend` into `block`, modifying `block` in place. */\nfunction addBlockInPlace(block: Uint8Array, addend: Uint8Array): void {\n\tlet carry = 1;\n\tfor (let index = block.length - 1; index >= 0; index -= 1) {\n\t\tconst sum = (block[index] ?? 0) + (addend[index] ?? 0) + carry;\n\t\tblock[index] = sum & 0xff;\n\t\tcarry = sum >> 8;\n\t}\n}\n\n/** Constant-time byte comparison to avoid timing side-channels in MAC checks. */\nfunction equalBytes(left: Uint8Array, right: Uint8Array): boolean {\n\tif (left.length !== right.length) {\n\t\treturn false;\n\t}\n\tlet result = 0;\n\tfor (let index = 0; index < left.length; index += 1) {\n\t\tresult |= (left[index] ?? 0) ^ (right[index] ?? 0);\n\t}\n\treturn result === 0;\n}\n"],"mappings":"wkBAoEA,eAAsB,EACrB,EACA,EAME,CACF,IAAM,EAAa,EAAQ,YAAc,KACzC,EAA0B,CAAU,EACpC,IAAM,EAAO,EAAQ,MAAQ,EAAU,CAAC,CAAC,gBAAgB,IAAI,WAAW,EAAE,CAAC,EACrE,EAAM,MAAM,EAAiB,EAAmB,EAAQ,SAAU,EAAM,CAAU,EAMxF,MAAO,CACN,IANW,EAAS,CACpB,EAAS,CAAC,EAAS,CAAC,EAAiB,EAAK,MAAM,EAAG,EAAU,CAAC,CAAC,EAAG,EAAY,CAAG,CAAC,CAAC,EACnF,EAAY,CAAI,EAChB,EAAkB,CAAU,CAC7B,CAEG,EACF,OAAQ,CACP,mBAAoB,EAAK,OACzB,oBAAqB,EAAsB,EAAK,MAAM,EACtD,UAAW,EAAM,CAAG,EACpB,QAAS,EAAM,CAAI,EACnB,aACA,aAAc,OACf,CACD,CACD,CAmBA,eAAsB,EACrB,EACA,EACA,EAC+B,CAC/B,IAAM,EAAM,EAAqB,CAAG,EAC9B,EAAa,EAAI,GACjB,EAAO,EAAI,GACX,EAAa,EAAI,GACvB,GACC,EAAI,SAAW,GACf,IAAe,IAAA,IACf,IAAS,IAAA,IACT,IAAe,IAAA,IACf,EAAK,MAAQ,EAEb,MAAU,MAAM,mBAAmB,EAEpC,IAAM,EAAgB,EAAI,MAAM,EAAW,M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1
|
-
{"version":3,"file":"pkcs7.js","names":[],"sources":["../../src/pkcs/pkcs7.ts"],"sourcesContent":["/**\n * PKCS#7/CMS certificate bags and SignedData.\n *\n * Creates degenerate (signature-less) certificate bags, parses RFC 2315 / RFC 5652\n * SignedData structures, and verifies signer signatures including signed-attribute flows.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeIntegerNumber,\n\tdecodeObjectIdentifier,\n\tdecodeString,\n\thexToBytes,\n\trequireElement,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1.ts';\nimport type { DerElement } from '#micro509/internal/asn1/der.ts';\nimport {\n\tconcatBytes,\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tinteger,\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadRootElement,\n\treadSequenceChildren,\n\tsequence,\n\tsetOf,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport {\n\tdescribeHashAlgorithm,\n\tdescribeSignatureAlgorithm,\n} from '#micro509/internal/crypto/algorithm-names.ts';\nimport { verifySignedDataDetailed } from '#micro509/internal/crypto/sig-verify.ts';\nimport {\n\tencodeAlgorithmIdentifier,\n\tgetSignatureAlgorithm,\n\ttype SignatureAlgorithmIdentifier,\n\tsignBytes,\n} from '#micro509/internal/crypto/signing.ts';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto.ts';\nimport { base64Encode } from '#micro509/internal/shared/base64.ts';\nimport { compareDistinguishedNames } from '#micro509/internal/shared/dn.ts';\nimport { pemEncode, splitPemBlocksOrThrow } from '#micro509/pem/pem.ts';\nimport { type ErrorResult, failureResult, type Micro509Error } from '#micro509/result/result.ts';\nimport { type NameFieldKey, nameFieldKeyFromOid } from '#micro509/x509/name.ts';\nimport type {\n\tParsedCertificate,\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse.ts';\nimport { parseCertificateDerOrThrow } from '#micro509/x509/parse.ts';\nimport type { SignatureProfileInput } from '#micro509/x509/certificate.ts';\n\n/** PEM text (may contain multiple CERTIFICATE blocks), raw DER bytes, or an already-parsed certificate. */\nexport type Pkcs7CertificateSource = string | Uint8Array | ParsedCertificate;\n\n/** DER, PEM, and base64 encodings of a PKCS#7 certificate bag. */\nexport interface Pkcs7CertBagMaterial {\n\t/** Raw DER-encoded PKCS#7 structure. */\n\treadonly der: Uint8Array;\n\t/** PEM-armored PKCS#7 (`-----BEGIN PKCS7-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armor). */\n\treadonly base64: string;\n}\n\n/** Fields shared by every decoded SignerInfo, regardless of signed-attribute presence. */\ninterface ParsedPkcs7SignerInfoBase {\n\t/** CMS SignerInfo version (typically 1 for issuerAndSerialNumber). */\n\treadonly version: number;\n\t/** Parsed issuer distinguished name, if present (issuerAndSerialNumber signer identifier). */\n\treadonly issuer?: ParsedName;\n\t/** Hex-encoded serial number used to locate the signer certificate, if present. */\n\treadonly serialNumberHex?: string;\n\t/** Hex-encoded SubjectKeyIdentifier used to locate the signer certificate, if present. */\n\treadonly subjectKeyIdentifier?: string;\n\t/** OID of the digest algorithm used to hash the content. */\n\treadonly digestAlgorithmOid: string;\n\t/** Human-readable digest algorithm name (e.g. `\"SHA-256\"`). */\n\treadonly digestAlgorithmName: string;\n\t/** OID of the algorithm used to produce the signature. */\n\treadonly signatureAlgorithmOid: string;\n\t/** Human-readable signature algorithm name. */\n\treadonly signatureAlgorithmName: string;\n\t/** Raw DER of the signature AlgorithmIdentifier parameters, if present. */\n\treadonly signatureAlgorithmParametersDer?: Uint8Array;\n\t/** Hex-encoded raw signature bytes. */\n\treadonly signatureHex: string;\n\t/** Raw signature bytes. */\n\treadonly signature: Uint8Array;\n}\n\n/**\n * A single SignerInfo decoded from a PKCS#7 SignedData structure.\n *\n * Discriminated on `hasSignedAttrs`: when `true`, `signedAttrsDer` is always\n * present; when `false`, it cannot exist.\n */\nexport type ParsedPkcs7SignerInfo =\n\t| (ParsedPkcs7SignerInfoBase & {\n\t\t\t/** This SignerInfo includes authenticated (signed) attributes. */\n\t\t\treadonly hasSignedAttrs: true;\n\t\t\t/** Raw DER of signedAttrs with original IMPLICIT [0] tag (0xa0). */\n\t\t\treadonly signedAttrsDer: Uint8Array;\n\t })\n\t| (ParsedPkcs7SignerInfoBase & {\n\t\t\t/** This SignerInfo has no authenticated attributes. */\n\t\t\treadonly hasSignedAttrs: false;\n\t\t\t/** Never present without signed attributes. */\n\t\t\treadonly signedAttrsDer?: undefined;\n\t });\n\n/** Decoded PKCS#7 SignedData content, including certificates and signer info. */\nexport interface ParsedPkcs7SignedData {\n\t/** Original DER bytes when this object came from {@linkcode parsePkcs7SignedDataDer} or PEM parsing. */\n\treadonly der?: Uint8Array;\n\t/** Outer ContentInfo type OID (always `pkcs7-signedData`). */\n\treadonly contentTypeOid: string;\n\t/** SignedData version number. */\n\treadonly version: number;\n\t/** OIDs of digest algorithms declared in `digestAlgorithms`. */\n\treadonly digestAlgorithmOids: readonly string[];\n\t/** Human-readable digest algorithm names declared in `digestAlgorithms`. */\n\treadonly digestAlgorithmNames: readonly string[];\n\t/** OID of the encapsulated content type (e.g. `pkcs7-data`). */\n\treadonly encapsulatedContentTypeOid: string;\n\t/** Raw encapsulated content bytes. Absent in degenerate (certs-only) bags. */\n\treadonly encapsulatedContent?: Uint8Array;\n\t/** Certificates included in the SignedData certificate set. */\n\treadonly certificates: readonly ParsedCertificate[];\n\t/** Decoded signer info entries. Empty for degenerate cert bags. */\n\treadonly signerInfos: readonly ParsedPkcs7SignerInfo[];\n}\n\n// ---------------------------------------------------------------------------\n// Result types for PKCS#7 parsing\n// ---------------------------------------------------------------------------\n\n/** Error codes for PKCS#7 parse failures. */\nexport type ParsePkcs7ErrorCode = 'malformed' | 'not_signed_data';\n\n/** Error payload for a failed PKCS#7 parse. */\nexport interface ParsePkcs7Failure extends Micro509Error<ParsePkcs7ErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parsePkcs7SignedDataDer} / {@linkcode parsePkcs7SignedDataPem}. */\nexport type ParsePkcs7SignedDataResult =\n\t| {\n\t\t\t/** Parse succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** Decoded SignedData. */\n\t\t\treadonly value: ParsedPkcs7SignedData;\n\t }\n\t| ErrorResult<ParsePkcs7ErrorCode, Record<never, never>, ParsePkcs7Failure>;\n\n/** Success-or-failure result from {@linkcode parsePkcs7CertBagDer} / {@linkcode parsePkcs7CertBagPem}. */\nexport type ParsePkcs7CertBagResult =\n\t| {\n\t\t\t/** Parse succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** Parsed certificates from the cert bag. */\n\t\t\treadonly value: readonly ParsedCertificate[];\n\t }\n\t| ErrorResult<ParsePkcs7ErrorCode, Record<never, never>, ParsePkcs7Failure>;\n\n/** Error payload for a failed {@linkcode verifyPkcs7SignedData} call. */\nexport interface VerifyPkcs7SignedDataFailure\n\textends Micro509Error<\n\t\t| 'signer_not_found'\n\t\t| 'signature_invalid'\n\t\t| 'message_digest_mismatch'\n\t\t| 'content_missing'\n\t\t| ParsePkcs7ErrorCode\n\t> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode verifyPkcs7SignedData}. */\nexport type VerifyPkcs7SignedDataResult =\n\t| {\n\t\t\t/** Verification succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** The verified SignedData structure. */\n\t\t\treadonly value: ParsedPkcs7SignedData;\n\t }\n\t| ErrorResult<\n\t\t\t| 'signer_not_found'\n\t\t\t| 'signature_invalid'\n\t\t\t| 'message_digest_mismatch'\n\t\t\t| 'content_missing'\n\t\t\t| ParsePkcs7ErrorCode,\n\t\t\tRecord<never, never>,\n\t\t\tVerifyPkcs7SignedDataFailure\n\t >;\n\n// ---------------------------------------------------------------------------\n// createPkcs7CertBag\n// ---------------------------------------------------------------------------\n\n/** Caller-correctable failure code from {@linkcode createPkcs7CertBag}. */\nexport type CreatePkcs7CertBagErrorCode = 'invalid_certificate';\n\n/** Error payload for a failed PKCS#7 certificate bag creation. */\nexport interface CreatePkcs7CertBagFailure extends Micro509Error<CreatePkcs7CertBagErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode createPkcs7CertBag}. */\nexport type CreatePkcs7CertBagResult =\n\t| {\n\t\t\t/** Creation succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** DER, PEM, and base64 forms of the certificate bag. */\n\t\t\treadonly value: Pkcs7CertBagMaterial;\n\t }\n\t| ErrorResult<CreatePkcs7CertBagErrorCode, Record<never, never>, CreatePkcs7CertBagFailure>;\n\n/**\n * Creates a degenerate PKCS#7 SignedData structure containing only\n * certificates (no signers), returning DER, PEM, and base64 forms, or a\n * typed `invalid_certificate` failure when a certificate source is not\n * valid PEM/DER.\n */\nexport function createPkcs7CertBag(\n\tcertificates: readonly Pkcs7CertificateSource[],\n): CreatePkcs7CertBagResult {\n\t// normalizeCertificateSource parses untrusted PEM/DER and throws on malformed\n\t// input — a caller-correctable trust boundary, so map it to a typed failure.\n\tlet certificateDers: Uint8Array[];\n\ttry {\n\t\tcertificateDers = certificates.flatMap(normalizeCertificateSource);\n\t} catch {\n\t\treturn createCertBagFailure(\n\t\t\t'invalid_certificate',\n\t\t\t'Each PKCS#7 certificate source must be valid PEM or DER',\n\t\t);\n\t}\n\tconst signedData = sequence([\n\t\tintegerFromNumber(1),\n\t\tsetOf([]),\n\t\tsequence([objectIdentifier(OIDS.pkcs7Data)]),\n\t\texplicitContext(0, concatBytes(certificateDers)),\n\t\tsetOf([]),\n\t]);\n\tconst der = sequence([objectIdentifier(OIDS.pkcs7SignedData), explicitContext(0, signedData)]);\n\treturn {\n\t\tok: true,\n\t\tvalue: { der, pem: pemEncode('PKCS7', der), base64: base64Encode(der) },\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// createPkcs7SignedData\n// ---------------------------------------------------------------------------\n\n/** A single signer for {@linkcode createPkcs7SignedData}. */\nexport interface Pkcs7Signer {\n\t/**\n\t * Signer certificate (PEM text with one CERTIFICATE block, or raw DER).\n\t * Embedded in the SignedData certificate set and referenced by the\n\t * SignerInfo via issuerAndSerialNumber.\n\t */\n\treadonly certificate: Pkcs7CertificateSource;\n\t/** Private key matching the certificate's public key, used to sign. */\n\treadonly privateKey: CryptoKey;\n\t/**\n\t * Signature profile. Defaults to inferring the algorithm from the key\n\t * (e.g. ECDSA→ecdsa-with-SHA*, RSA→sha*WithRSAEncryption, Ed25519).\n\t * Pass `{ kind: 'rsa-pss' }` to force RSA-PSS padding for an RSA-PSS key.\n\t */\n\treadonly signature?: SignatureProfileInput;\n}\n\n/** Input for {@linkcode createPkcs7SignedData}. */\nexport interface CreatePkcs7SignedDataInput {\n\t/** Content to encapsulate and sign (the eContent). */\n\treadonly content: Uint8Array;\n\t/** One or more signers. Each produces a SignerInfo with signed attributes. */\n\treadonly signers: readonly Pkcs7Signer[];\n\t/**\n\t * Additional certificates to embed (e.g. intermediates). Signer\n\t * certificates are always embedded; duplicate DER is removed.\n\t */\n\treadonly additionalCertificates?: readonly Pkcs7CertificateSource[];\n\t/**\n\t * Encapsulated content type OID.\n\t * @default `'1.2.840.113549.1.7.1'` (pkcs7-data)\n\t */\n\treadonly encapsulatedContentTypeOid?: string;\n}\n\n/** DER, PEM, and base64 encodings of a PKCS#7 SignedData structure. */\nexport interface Pkcs7SignedDataMaterial {\n\t/** Raw DER-encoded PKCS#7 SignedData. */\n\treadonly der: Uint8Array;\n\t/** PEM-armored PKCS#7 (`-----BEGIN PKCS7-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armor). */\n\treadonly base64: string;\n}\n\n/** Caller-correctable failure codes from {@linkcode createPkcs7SignedData}. */\nexport type CreatePkcs7SignedDataErrorCode =\n\t| 'no_signers'\n\t| 'invalid_signer_certificate'\n\t| 'unsupported_signer_key';\n\n/** Error payload for a failed PKCS#7 SignedData creation. */\nexport interface CreatePkcs7SignedDataFailure\n\textends Micro509Error<CreatePkcs7SignedDataErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode createPkcs7SignedData}. */\nexport type CreatePkcs7SignedDataResult =\n\t| {\n\t\t\t/** Creation succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** DER, PEM, and base64 forms of the SignedData. */\n\t\t\treadonly value: Pkcs7SignedDataMaterial;\n\t }\n\t| ErrorResult<CreatePkcs7SignedDataErrorCode, Record<never, never>, CreatePkcs7SignedDataFailure>;\n\n/**\n * Creates a PKCS#7/CMS SignedData with one or more signers over `content`.\n *\n * Each signer uses the RFC 5652 Section 5.4 signed-attributes flow: the\n * signature covers a `SET OF` authenticated attributes carrying `contentType`\n * and `messageDigest` (the digest of the encapsulated content). The content is\n * embedded (attached signature), so the result verifies with\n * {@linkcode verifyPkcs7SignedData} without any external data.\n *\n * The content digest is derived from each signer's key (P-256/RSA-SHA256 →\n * SHA-256, P-384 → SHA-384, P-521 → SHA-512, Ed25519 → SHA-512 per RFC 8419).\n *\n * Returns a {@linkcode CreatePkcs7SignedDataResult}: DER, PEM, and base64\n * forms on success, or a typed failure for caller-correctable input (no\n * signers, a signer source that is not exactly one certificate, or an\n * unsupported signer key).\n */\nexport async function createPkcs7SignedData(\n\tinput: CreatePkcs7SignedDataInput,\n): Promise<CreatePkcs7SignedDataResult> {\n\tif (input.signers.length === 0) {\n\t\treturn createPkcs7Failure('no_signers', 'createPkcs7SignedData requires at least one signer');\n\t}\n\tconst encapsulatedContentTypeOid = input.encapsulatedContentTypeOid ?? OIDS.pkcs7Data;\n\n\t// Snapshot the caller-owned content into a private copy before any await.\n\t// Every signer's messageDigest and the emitted eContent must derive from the\n\t// same bytes; reading input.content across awaits could otherwise observe a\n\t// caller mutation and yield a SignedData whose digest disagrees with its own\n\t// encapsulated content.\n\tconst content = input.content.slice();\n\n\tconst certificateDers: Uint8Array[] = [];\n\tconst seenCertificates = new Set<string>();\n\tconst addCertificate = (der: Uint8Array): void => {\n\t\tconst hex = toHex(der);\n\t\tif (!seenCertificates.has(hex)) {\n\t\t\tseenCertificates.add(hex);\n\t\t\tcertificateDers.push(der);\n\t\t}\n\t};\n\n\tconst digestAlgorithmOids = new Set<string>();\n\tconst signerInfos: Uint8Array[] = [];\n\tfor (const signer of input.signers) {\n\t\tconst signerCertDers = normalizeCertificateSource(signer.certificate);\n\t\tconst signerCertDer = signerCertDers[0];\n\t\tif (signerCertDer === undefined || signerCertDers.length !== 1) {\n\t\t\treturn createPkcs7Failure(\n\t\t\t\t'invalid_signer_certificate',\n\t\t\t\t'Each PKCS#7 signer must provide exactly one certificate',\n\t\t\t);\n\t\t}\n\t\taddCertificate(signerCertDer);\n\t\t// parseCertificateDerOrThrow throws on malformed DER — a caller-correctable\n\t\t// input, so convert it to the typed invalid_signer_certificate failure\n\t\t// rather than rejecting the public Promise.\n\t\tlet certificate: ParsedCertificate;\n\t\ttry {\n\t\t\tcertificate = parseCertificateDerOrThrow(signerCertDer);\n\t\t} catch {\n\t\t\treturn createPkcs7Failure(\n\t\t\t\t'invalid_signer_certificate',\n\t\t\t\t'Each PKCS#7 signer certificate must be a parseable X.509 certificate',\n\t\t\t);\n\t\t}\n\t\t// getSignatureAlgorithm throws only for unsupported/misconfigured keys —\n\t\t// all caller-correctable, so map to a typed failure rather than propagate.\n\t\tlet signatureAlgorithm: SignatureAlgorithmIdentifier;\n\t\ttry {\n\t\t\tsignatureAlgorithm = getSignatureAlgorithm(signer.privateKey, signer.signature);\n\t\t} catch {\n\t\t\treturn createPkcs7Failure(\n\t\t\t\t'unsupported_signer_key',\n\t\t\t\t'Unsupported signer key or signature profile',\n\t\t\t);\n\t\t}\n\t\tconst digest = contentDigestForPrivateKey(signer.privateKey);\n\t\tif (digest === undefined) {\n\t\t\treturn createPkcs7Failure(\n\t\t\t\t'unsupported_signer_key',\n\t\t\t\t'Unsupported signer key algorithm for content digest',\n\t\t\t);\n\t\t}\n\t\tdigestAlgorithmOids.add(digest.digestOid);\n\t\tconst messageDigest = new Uint8Array(\n\t\t\tawait getCrypto().subtle.digest(digest.hashName, toArrayBuffer(content)),\n\t\t);\n\t\tconst { setForSigning, implicitForEmit } = buildSignedAttributes(\n\t\t\tencapsulatedContentTypeOid,\n\t\t\tmessageDigest,\n\t\t);\n\t\tconst signature = await signBytes(signer.privateKey, signatureAlgorithm, setForSigning);\n\t\tsignerInfos.push(\n\t\t\tsequence([\n\t\t\t\tintegerFromNumber(1),\n\t\t\t\tsequence([\n\t\t\t\t\thexToBytes(certificate.issuer.derHex),\n\t\t\t\t\tinteger(hexToBytes(certificate.serialNumberHex)),\n\t\t\t\t]),\n\t\t\t\tsequence([objectIdentifier(digest.digestOid), nullValue()]),\n\t\t\t\timplicitForEmit,\n\t\t\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\t\t\toctetString(signature),\n\t\t\t]),\n\t\t);\n\t}\n\n\tfor (const source of input.additionalCertificates ?? []) {\n\t\tfor (const der of normalizeCertificateSource(source)) {\n\t\t\taddCertificate(der);\n\t\t}\n\t}\n\n\t// SignedData version: 1 for id-data content, otherwise 3 (RFC 5652 Section 5.1).\n\tconst signedDataVersion = encapsulatedContentTypeOid === OIDS.pkcs7Data ? 1 : 3;\n\t// certificates [0] IMPLICIT CertificateSet — a DER SET OF must be canonically\n\t// ordered, so sort via setOf, then retag 0x31 -> 0xa0 for the IMPLICIT [0].\n\tconst certificateSet = new Uint8Array(setOf(certificateDers));\n\tcertificateSet[0] = 0xa0;\n\tconst signedData = sequence([\n\t\tintegerFromNumber(signedDataVersion),\n\t\tsetOf([...digestAlgorithmOids].map((oid) => sequence([objectIdentifier(oid), nullValue()]))),\n\t\tsequence([\n\t\t\tobjectIdentifier(encapsulatedContentTypeOid),\n\t\t\texplicitContext(0, octetString(content)),\n\t\t]),\n\t\tcertificateSet,\n\t\tsetOf(signerInfos),\n\t]);\n\tconst der = sequence([objectIdentifier(OIDS.pkcs7SignedData), explicitContext(0, signedData)]);\n\treturn {\n\t\tok: true,\n\t\tvalue: { der, pem: pemEncode('PKCS7', der), base64: base64Encode(der) },\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// parsePkcs7CertBag — Result-returning\n// ---------------------------------------------------------------------------\n\n/** Parses a DER-encoded PKCS#7 cert bag, returning the contained certificates. */\nexport function parsePkcs7CertBagDer(der: Uint8Array): ParsePkcs7CertBagResult {\n\tconst result = parsePkcs7SignedDataDer(der);\n\tif (!result.ok) {\n\t\treturn result;\n\t}\n\treturn { ok: true, value: result.value.certificates };\n}\n\n/** Parses a PEM-armored PKCS#7 cert bag. Expects exactly one `PKCS7` PEM block. */\nexport function parsePkcs7CertBagPem(pem: string): ParsePkcs7CertBagResult {\n\ttry {\n\t\tconst blocks = splitPemBlocksOrThrow(pem).filter((block) => block.label === 'PKCS7');\n\t\tif (blocks.length !== 1) {\n\t\t\treturn pkcs7Failure('malformed', 'Expected exactly one PKCS7 PEM block');\n\t\t}\n\t\tconst block = blocks[0];\n\t\tif (block === undefined) {\n\t\t\treturn pkcs7Failure('malformed', 'Missing PKCS7 block');\n\t\t}\n\t\treturn parsePkcs7CertBagDer(block.bytes);\n\t} catch {\n\t\treturn pkcs7Failure('malformed', 'Expected exactly one PKCS7 PEM block');\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// parsePkcs7SignedData — Result-returning\n// ---------------------------------------------------------------------------\n\n/** Decodes a DER-encoded PKCS#7 ContentInfo expecting `signedData` content type. */\nexport function parsePkcs7SignedDataDer(der: Uint8Array): ParsePkcs7SignedDataResult {\n\ttry {\n\t\tconst contentInfo = readSequenceChildren(der, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tconst contentType = contentInfo[0];\n\t\tconst content = contentInfo[1];\n\t\tif (\n\t\t\tcontentType === undefined ||\n\t\t\tcontent === undefined ||\n\t\t\tcontentInfo.length !== 2 ||\n\t\t\tcontentType.tag !== 0x06 ||\n\t\t\tcontent.tag !== 0xa0\n\t\t) {\n\t\t\treturn pkcs7Failure('malformed', 'Malformed PKCS#7 content info');\n\t\t}\n\t\tif (childrenOf(der, content).length !== 1) {\n\t\t\treturn pkcs7Failure('malformed', 'Malformed PKCS#7 content info');\n\t\t}\n\t\tconst contentTypeOid = decodeObjectIdentifier(contentType.value);\n\t\tif (contentTypeOid !== OIDS.pkcs7SignedData) {\n\t\t\treturn pkcs7Failure('not_signed_data', 'PKCS#7 content is not signedData');\n\t\t}\n\t\tconst signedData = childAt(der, content, 0, 'signedData');\n\t\tconst signedDataChildren = childrenOf(der, signedData);\n\t\tconst version = signedDataChildren[0];\n\t\tconst digestAlgorithms = signedDataChildren[1];\n\t\tconst encapContentInfo = signedDataChildren[2];\n\t\tconst trailingChildren = signedDataChildren.slice(3);\n\t\tconst signerInfos = trailingChildren[trailingChildren.length - 1];\n\t\tlet certificates: ReturnType<typeof readElement> | undefined;\n\t\tlet crls: ReturnType<typeof readElement> | undefined;\n\t\tfor (const child of trailingChildren.slice(0, -1)) {\n\t\t\tif (child?.tag === 0xa0) {\n\t\t\t\tif (crls !== undefined) {\n\t\t\t\t\treturn pkcs7Failure('malformed', 'SignedData certificates field must precede CRLs field');\n\t\t\t\t}\n\t\t\t\tif (certificates !== undefined) {\n\t\t\t\t\treturn pkcs7Failure('malformed', 'SignedData certificates field must not repeat');\n\t\t\t\t}\n\t\t\t\tcertificates = child;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (child?.tag === 0xa1) {\n\t\t\t\tif (crls !== undefined) {\n\t\t\t\t\treturn pkcs7Failure('malformed', 'SignedData CRLs field must not repeat');\n\t\t\t\t}\n\t\t\t\tcrls = child;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn pkcs7Failure('malformed', 'Malformed SignedData optional field');\n\t\t}\n\t\tif (\n\t\t\tversion === undefined ||\n\t\t\tdigestAlgorithms === undefined ||\n\t\t\tencapContentInfo === undefined ||\n\t\t\tsignerInfos === undefined ||\n\t\t\tsignerInfos.tag !== 0x31\n\t\t) {\n\t\t\treturn pkcs7Failure('malformed', 'Malformed SignedData');\n\t\t}\n\t\tconst encapDer = der.slice(\n\t\t\tencapContentInfo.start - encapContentInfo.headerLength,\n\t\t\tencapContentInfo.end,\n\t\t);\n\t\tconst encapChildren = readSequenceChildren(encapDer);\n\t\tconst encapType = encapChildren[0];\n\t\tconst encapContent = encapChildren[1];\n\t\tconst digestAlgorithmOids = parseDigestAlgorithms(der, digestAlgorithms);\n\t\tif (encapType === undefined) {\n\t\t\treturn pkcs7Failure('malformed', 'Malformed EncapsulatedContentInfo');\n\t\t}\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: {\n\t\t\t\tder: new Uint8Array(der),\n\t\t\t\tcontentTypeOid,\n\t\t\t\tversion: decodeIntegerNumber(version.value),\n\t\t\t\tdigestAlgorithmOids,\n\t\t\t\tdigestAlgorithmNames: digestAlgorithmOids.map((oid) => describeHashAlgorithm(oid)),\n\t\t\t\tencapsulatedContentTypeOid: decodeObjectIdentifier(encapType.value),\n\t\t\t\t...(encapContent === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tencapsulatedContent: extractEncapsulatedContent(encapDer, encapContent),\n\t\t\t\t\t\t}),\n\t\t\t\tcertificates: parseCertificateSet(der, certificates),\n\t\t\t\tsignerInfos: parseSignerInfos(der, signerInfos),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn pkcs7Failure('malformed', 'Malformed PKCS#7 structure');\n\t}\n}\n\n/** Decodes a PEM-armored PKCS#7 SignedData. Expects exactly one `PKCS7` PEM block. */\nexport function parsePkcs7SignedDataPem(pem: string): ParsePkcs7SignedDataResult {\n\ttry {\n\t\tconst blocks = splitPemBlocksOrThrow(pem).filter((block) => block.label === 'PKCS7');\n\t\tconst block = blocks[0];\n\t\tif (block === undefined || blocks.length !== 1) {\n\t\t\treturn pkcs7Failure('malformed', 'Expected exactly one PKCS7 PEM block');\n\t\t}\n\t\treturn parsePkcs7SignedDataDer(block.bytes);\n\t} catch {\n\t\treturn pkcs7Failure('malformed', 'Expected exactly one PKCS7 PEM block');\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// verifyPkcs7SignedData\n// ---------------------------------------------------------------------------\n\n/**\n * Verifies all signer signatures in a PKCS#7 SignedData structure.\n *\n * Accepts PEM text, raw DER, or an already-parsed {@linkcode ParsedPkcs7SignedData}.\n * For each signer, locates the matching certificate in the embedded set and\n * verifies the signature (including signed-attribute digest checks per RFC 5652 Section 5.4).\n *\n * @example\n * ```ts\n * import { verifyPkcs7SignedData } from 'micro509';\n *\n * const result = await verifyPkcs7SignedData(pkcs7Pem);\n * if (result.ok) {\n * console.log('all signers verified');\n * }\n * ```\n */\nexport async function verifyPkcs7SignedData(\n\tinput: string | Uint8Array | ParsedPkcs7SignedData,\n): Promise<VerifyPkcs7SignedDataResult> {\n\tlet parsed: ParsedPkcs7SignedData;\n\tif (typeof input === 'string') {\n\t\tconst result = parsePkcs7SignedDataPem(input);\n\t\tif (!result.ok) {\n\t\t\treturn result;\n\t\t}\n\t\tparsed = result.value;\n\t} else if (input instanceof Uint8Array) {\n\t\tconst result = parsePkcs7SignedDataDer(input);\n\t\tif (!result.ok) {\n\t\t\treturn result;\n\t\t}\n\t\tparsed = result.value;\n\t} else {\n\t\tif (!hasReparseablePkcs7SignedData(input)) {\n\t\t\treturn verifyPkcs7Failure('malformed', 'SignedData parsed input is malformed');\n\t\t}\n\t\tconst result = parsePkcs7SignedDataDer(new Uint8Array(input.der));\n\t\tif (!result.ok) {\n\t\t\treturn result;\n\t\t}\n\t\tparsed = result.value;\n\t}\n\tif (parsed.encapsulatedContent === undefined) {\n\t\treturn verifyPkcs7Failure('content_missing', 'SignedData encapsulated content is missing');\n\t}\n\tfor (const signerInfo of parsed.signerInfos) {\n\t\tconst signer = parsed.certificates.find((certificate) =>\n\t\t\tsignerIdentifierMatches(certificate, signerInfo),\n\t\t);\n\t\tif (signer === undefined) {\n\t\t\treturn verifyPkcs7Failure(\n\t\t\t\t'signer_not_found',\n\t\t\t\t'Signer certificate not found in SignedData certificates',\n\t\t\t);\n\t\t}\n\t\tif (signerInfo.hasSignedAttrs) {\n\t\t\tconst attrsResult = await verifySignedAttrs(\n\t\t\t\tsignerInfo,\n\t\t\t\tsigner,\n\t\t\t\tparsed.encapsulatedContent,\n\t\t\t\tparsed.encapsulatedContentTypeOid,\n\t\t\t);\n\t\t\tif (!attrsResult.ok) {\n\t\t\t\treturn attrsResult;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tlet verified: boolean;\n\t\ttry {\n\t\t\tconst verificationResult = await verifySignedDataDetailed(\n\t\t\t\tsignerInfo.signatureAlgorithmOid,\n\t\t\t\tsignerInfo.signatureAlgorithmParametersDer,\n\t\t\t\tsigner.publicKeyAlgorithmOid,\n\t\t\t\tsigner.publicKeyParametersOid,\n\t\t\t\tsigner.subjectPublicKeyInfoDer,\n\t\t\t\tsignerInfo.signature,\n\t\t\t\tparsed.encapsulatedContent,\n\t\t\t);\n\t\t\tif (!verificationResult.ok) {\n\t\t\t\tif (verificationResult.code === 'verification_error') {\n\t\t\t\t\treturn verifyPkcs7Failure('malformed', 'SignedData signature verification failed');\n\t\t\t\t}\n\t\t\t\treturn verifyPkcs7Failure('malformed', 'Unsupported signature algorithm in SignedData');\n\t\t\t}\n\t\t\tverified = verificationResult.valid;\n\t\t} catch {\n\t\t\treturn verifyPkcs7Failure('malformed', 'Unsupported signature algorithm in SignedData');\n\t\t}\n\t\tif (!verified) {\n\t\t\treturn verifyPkcs7Failure('signature_invalid', 'SignedData signature does not verify');\n\t\t}\n\t}\n\treturn { ok: true, value: parsed };\n}\n\n// ---------------------------------------------------------------------------\n// Private helpers\n// ---------------------------------------------------------------------------\n\n/** Shorthand for constructing a PKCS#7 parse failure result. */\nfunction pkcs7Failure(\n\tcode: ParsePkcs7ErrorCode,\n\tmessage: string,\n): ErrorResult<ParsePkcs7ErrorCode, Record<never, never>, ParsePkcs7Failure> {\n\treturn failureResult(code, message);\n}\n\n/** Shorthand for constructing a PKCS#7 verification failure result. */\nfunction verifyPkcs7Failure(\n\tcode:\n\t\t| 'signer_not_found'\n\t\t| 'signature_invalid'\n\t\t| 'message_digest_mismatch'\n\t\t| 'content_missing'\n\t\t| ParsePkcs7ErrorCode,\n\tmessage: string,\n): ErrorResult<\n\t| 'signer_not_found'\n\t| 'signature_invalid'\n\t| 'message_digest_mismatch'\n\t| 'content_missing'\n\t| ParsePkcs7ErrorCode,\n\tRecord<never, never>,\n\tVerifyPkcs7SignedDataFailure\n> {\n\treturn failureResult(code, message);\n}\n\n/** Shorthand for constructing a PKCS#7 certificate bag creation failure result. */\nfunction createCertBagFailure(\n\tcode: CreatePkcs7CertBagErrorCode,\n\tmessage: string,\n): ErrorResult<CreatePkcs7CertBagErrorCode, Record<never, never>, CreatePkcs7CertBagFailure> {\n\treturn failureResult(code, message);\n}\n\n/** Shorthand for constructing a PKCS#7 SignedData creation failure result. */\nfunction createPkcs7Failure(\n\tcode: CreatePkcs7SignedDataErrorCode,\n\tmessage: string,\n): ErrorResult<CreatePkcs7SignedDataErrorCode, Record<never, never>, CreatePkcs7SignedDataFailure> {\n\treturn failureResult(code, message);\n}\n\n/** Converts PEM text to an array of DER certificate blobs, or wraps raw DER. */\nfunction normalizeCertificateSource(source: Pkcs7CertificateSource): readonly Uint8Array[] {\n\tif (typeof source === 'string') {\n\t\treturn splitPemBlocksOrThrow(source)\n\t\t\t.filter((block) => block.label === 'CERTIFICATE')\n\t\t\t.map((block) => new Uint8Array(block.bytes));\n\t}\n\tif (source instanceof Uint8Array) {\n\t\treturn [new Uint8Array(source)];\n\t}\n\treturn [new Uint8Array(source.der)];\n}\n\n/** Type guard: key algorithm carries an RSA `hash`. */\nfunction signerHasHash(algorithm: KeyAlgorithm): algorithm is RsaHashedKeyAlgorithm {\n\treturn 'hash' in algorithm;\n}\n\n/** Type guard: key algorithm carries an EC `namedCurve`. */\nfunction signerHasNamedCurve(algorithm: KeyAlgorithm): algorithm is EcKeyAlgorithm {\n\treturn 'namedCurve' in algorithm;\n}\n\n/**\n * Resolves the content-digest hash and its OID for a signer key.\n *\n * Pairs each key with the digest used by its signature algorithm (RFC 5754):\n * P-256/RSA-SHA256 → SHA-256, P-384 → SHA-384, P-521 → SHA-512. Ed25519 uses\n * SHA-512 for the messageDigest attribute, per RFC 8419.\n */\nfunction contentDigestForPrivateKey(\n\tprivateKey: CryptoKey,\n):\n\t| { readonly hashName: 'SHA-256' | 'SHA-384' | 'SHA-512'; readonly digestOid: string }\n\t| undefined {\n\tconst algorithm = privateKey.algorithm;\n\tif (algorithm.name === 'ECDSA') {\n\t\tif (!signerHasNamedCurve(algorithm)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tswitch (algorithm.namedCurve) {\n\t\t\tcase 'P-256':\n\t\t\t\treturn { hashName: 'SHA-256', digestOid: OIDS.sha256 };\n\t\t\tcase 'P-384':\n\t\t\t\treturn { hashName: 'SHA-384', digestOid: OIDS.sha384 };\n\t\t\tcase 'P-521':\n\t\t\t\treturn { hashName: 'SHA-512', digestOid: OIDS.sha512 };\n\t\t\tdefault:\n\t\t\t\treturn undefined;\n\t\t}\n\t}\n\tif (algorithm.name === 'RSASSA-PKCS1-v1_5' || algorithm.name === 'RSA-PSS') {\n\t\tif (!signerHasHash(algorithm)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tswitch (algorithm.hash.name) {\n\t\t\tcase 'SHA-256':\n\t\t\t\treturn { hashName: 'SHA-256', digestOid: OIDS.sha256 };\n\t\t\tcase 'SHA-384':\n\t\t\t\treturn { hashName: 'SHA-384', digestOid: OIDS.sha384 };\n\t\t\tcase 'SHA-512':\n\t\t\t\treturn { hashName: 'SHA-512', digestOid: OIDS.sha512 };\n\t\t\tdefault:\n\t\t\t\treturn undefined;\n\t\t}\n\t}\n\tif (algorithm.name === 'Ed25519') {\n\t\treturn { hashName: 'SHA-512', digestOid: OIDS.sha512 };\n\t}\n\treturn undefined;\n}\n\n/**\n * Builds CMS signed attributes (contentType + messageDigest) in two forms:\n * `setForSigning` (SET OF, tag 0x31) is what the signature covers per RFC 5652\n * Section 5.4; `implicitForEmit` (IMPLICIT [0], tag 0xa0) is what goes in the\n * SignerInfo. The two differ only in the leading tag byte.\n */\nfunction buildSignedAttributes(\n\tcontentTypeOid: string,\n\tmessageDigest: Uint8Array,\n): { readonly setForSigning: Uint8Array; readonly implicitForEmit: Uint8Array } {\n\tconst setForSigning = setOf([\n\t\tsequence([objectIdentifier(OIDS.cmsContentType), setOf([objectIdentifier(contentTypeOid)])]),\n\t\tsequence([objectIdentifier(OIDS.cmsMessageDigest), setOf([octetString(messageDigest)])]),\n\t]);\n\tconst implicitForEmit = new Uint8Array(setForSigning);\n\timplicitForEmit[0] = 0xa0;\n\treturn { setForSigning, implicitForEmit };\n}\n\n/** Parses the IMPLICIT [0] certificate set from a SignedData structure. */\nfunction parseCertificateSet(\n\tsource: Uint8Array,\n\tcertificates: ReturnType<typeof readElement> | undefined,\n): readonly ParsedCertificate[] {\n\tif (certificates === undefined || certificates.tag !== 0xa0) {\n\t\treturn [];\n\t}\n\tconst parsed: ParsedCertificate[] = [];\n\tlet offset = certificates.start;\n\twhile (offset < certificates.end) {\n\t\tconst element = readElement(source, offset);\n\t\tparsed.push(parseCertificateDerOrThrow(source.slice(offset, element.end)));\n\t\toffset = element.end;\n\t}\n\treturn parsed;\n}\n\n/** Extracts the list of digest algorithm OIDs from the digestAlgorithms SET. */\nfunction parseDigestAlgorithms(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readElement>,\n): readonly string[] {\n\tconst digests: string[] = [];\n\tif (element.tag !== 0x31) {\n\t\tthrow new Error('digestAlgorithms must use SET');\n\t}\n\tfor (const child of childrenOf(source, element)) {\n\t\tif (child.tag !== 0x30) {\n\t\t\tthrow new Error('digestAlgorithm must use AlgorithmIdentifier SEQUENCE');\n\t\t}\n\t\tconst childDer = source.slice(child.start - child.headerLength, child.end);\n\t\tconst parts = readSequenceChildren(childDer);\n\t\tconst oid = parts[0];\n\t\tif (oid === undefined || parts.length < 1 || parts.length > 2 || oid.tag !== 0x06) {\n\t\t\tthrow new Error('Malformed digest AlgorithmIdentifier');\n\t\t}\n\t\tdigests.push(decodeObjectIdentifier(oid.value));\n\t}\n\treturn digests;\n}\n\n/** Decodes the signerInfos SET OF from a SignedData structure. */\nfunction parseSignerInfos(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readElement>,\n): readonly ParsedPkcs7SignerInfo[] {\n\tconst signers: ParsedPkcs7SignerInfo[] = [];\n\tfor (const signerInfo of childrenOf(source, element)) {\n\t\tconst signerDer = source.slice(signerInfo.start - signerInfo.headerLength, signerInfo.end);\n\t\tconst parts = readSequenceChildren(signerDer);\n\t\tconst version = parts[0];\n\t\tconst sid = parts[1];\n\t\tconst digestAlgorithm = parts[2];\n\t\tlet index = 3;\n\t\tconst signedAttrsElement = parts[index]?.tag === 0xa0 ? parts[index] : undefined;\n\t\tconst hasSignedAttrs = signedAttrsElement !== undefined;\n\t\tif (hasSignedAttrs) {\n\t\t\tindex += 1;\n\t\t}\n\t\tconst signatureAlgorithm = parts[index];\n\t\tconst signature = parts[index + 1];\n\t\tconst unauthenticatedAttributes = parts[index + 2];\n\t\tif (\n\t\t\tversion === undefined ||\n\t\t\tsid === undefined ||\n\t\t\tdigestAlgorithm === undefined ||\n\t\t\tsignatureAlgorithm === undefined ||\n\t\t\tsignature === undefined ||\n\t\t\tsignature.tag !== 0x04 ||\n\t\t\tparts.length > index + 3 ||\n\t\t\t(unauthenticatedAttributes !== undefined && unauthenticatedAttributes.tag !== 0xa1)\n\t\t) {\n\t\t\tthrow new Error('Malformed SignerInfo');\n\t\t}\n\t\tconst digestAlgorithmDer = signerDer.slice(\n\t\t\tdigestAlgorithm.start - digestAlgorithm.headerLength,\n\t\t\tdigestAlgorithm.end,\n\t\t);\n\t\tconst digestAlgorithmOid = decodeObjectIdentifier(\n\t\t\trequireElement(readSequenceChildren(digestAlgorithmDer)[0], 'digest algorithm OID').value,\n\t\t);\n\t\tconst signatureAlgorithmDer = signerDer.slice(\n\t\t\tsignatureAlgorithm.start - signatureAlgorithm.headerLength,\n\t\t\tsignatureAlgorithm.end,\n\t\t);\n\t\tconst signatureAlgorithmChildren = readSequenceChildren(signatureAlgorithmDer);\n\t\tconst signatureAlgorithmOid = decodeObjectIdentifier(\n\t\t\trequireElement(signatureAlgorithmChildren[0], 'signature algorithm OID').value,\n\t\t);\n\t\tconst signatureAlgorithmParams = signatureAlgorithmChildren[1];\n\t\tconst parsedSid = parseSignerIdentifier(signerDer.slice(sid.start - sid.headerLength, sid.end));\n\t\tsigners.push({\n\t\t\tversion: decodeIntegerNumber(version.value),\n\t\t\t...(parsedSid.issuer === undefined ? {} : { issuer: parsedSid.issuer }),\n\t\t\t...(parsedSid.serialNumberHex === undefined\n\t\t\t\t? {}\n\t\t\t\t: { serialNumberHex: parsedSid.serialNumberHex }),\n\t\t\t...(parsedSid.subjectKeyIdentifier === undefined\n\t\t\t\t? {}\n\t\t\t\t: { subjectKeyIdentifier: parsedSid.subjectKeyIdentifier }),\n\t\t\tdigestAlgorithmOid,\n\t\t\tdigestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),\n\t\t\tsignatureAlgorithmOid,\n\t\t\tsignatureAlgorithmName: describeSignatureAlgorithm(\n\t\t\t\tsignatureAlgorithmOid,\n\t\t\t\tsignatureAlgorithmParams === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: new Uint8Array(\n\t\t\t\t\t\t\tsignatureAlgorithmDer.slice(\n\t\t\t\t\t\t\t\tsignatureAlgorithmParams.start - signatureAlgorithmParams.headerLength,\n\t\t\t\t\t\t\t\tsignatureAlgorithmParams.end,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t),\n\t\t\t...(signatureAlgorithmParams === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tsignatureAlgorithmParametersDer: new Uint8Array(\n\t\t\t\t\t\t\tsignatureAlgorithmDer.slice(\n\t\t\t\t\t\t\t\tsignatureAlgorithmParams.start - signatureAlgorithmParams.headerLength,\n\t\t\t\t\t\t\t\tsignatureAlgorithmParams.end,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t}),\n\t\t\tsignatureHex: toHex(signature.value),\n\t\t\tsignature: new Uint8Array(signature.value),\n\t\t\t...(signedAttrsElement === undefined\n\t\t\t\t? { hasSignedAttrs: false as const }\n\t\t\t\t: {\n\t\t\t\t\t\thasSignedAttrs: true as const,\n\t\t\t\t\t\tsignedAttrsDer: new Uint8Array(\n\t\t\t\t\t\t\tsignerDer.slice(\n\t\t\t\t\t\t\t\tsignedAttrsElement.start - signedAttrsElement.headerLength,\n\t\t\t\t\t\t\t\tsignedAttrsElement.end,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t}),\n\t\t});\n\t}\n\treturn signers;\n}\n\n/** Unwraps the OCTET STRING inside the IMPLICIT [0] encapsulated content. */\nfunction extractEncapsulatedContent(\n\tencapDer: Uint8Array,\n\telement: ReturnType<typeof readElement>,\n): Uint8Array {\n\tif (element.tag !== 0xa0) {\n\t\tthrow new Error('Unexpected encapsulated content tag');\n\t}\n\tconst inner = readElement(encapDer, element.start);\n\tif (inner.tag !== 0x04) {\n\t\tthrow new Error('Expected encapsulated OCTET STRING');\n\t}\n\treturn inner.value;\n}\n\n/** Extracts issuer Name and serial number from an issuerAndSerialNumber SEQUENCE, or subjectKeyIdentifier from [0] IMPLICIT. */\nfunction parseSignerIdentifier(der: Uint8Array): {\n\treadonly issuer?: ParsedName;\n\treadonly serialNumberHex?: string;\n\treadonly subjectKeyIdentifier?: string;\n} {\n\tconst element = readRootElement(der, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t// [0] IMPLICIT SubjectKeyIdentifier\n\tif (element.tag === 0x80) {\n\t\tif (element.value.length === 0) {\n\t\t\tthrow new Error('SignerIdentifier subjectKeyIdentifier must not be empty');\n\t\t}\n\t\treturn {\n\t\t\tsubjectKeyIdentifier: toHex(element.value),\n\t\t};\n\t}\n\t// SEQUENCE { issuer Name, serialNumber INTEGER }\n\tif (element.tag === 0x30) {\n\t\tconst top = readSequenceChildren(der);\n\t\tconst issuerElement = top[0];\n\t\tconst serial = top[1];\n\t\tif (issuerElement === undefined || serial === undefined || top.length !== 2) {\n\t\t\tthrow new Error('SignerIdentifier issuerAndSerialNumber is malformed');\n\t\t}\n\t\tif (issuerElement.tag !== 0x30) {\n\t\t\tthrow new Error('SignerIdentifier issuer must use Name SEQUENCE');\n\t\t}\n\t\tif (serial.tag !== 0x02) {\n\t\t\tthrow new Error('SignerIdentifier serialNumber must use INTEGER');\n\t\t}\n\t\tassertImplicitSerialNumberEncoding(serial.value, 'SignerIdentifier serialNumber');\n\t\treturn {\n\t\t\tissuer: parseSignerIssuerName(der, issuerElement),\n\t\t\tserialNumberHex: toHex(serial.value),\n\t\t};\n\t}\n\tthrow new Error(`Unsupported SignerIdentifier tag: ${String(element.tag)}`);\n}\n\nconst textDecoder = new TextDecoder();\n\n/** Parses a Name SEQUENCE element from a PKCS#7 signer identifier into a {@linkcode ParsedName}. */\nfunction parseSignerIssuerName(source: Uint8Array, element: DerElement): ParsedName {\n\tconst derHex = toHex(source.slice(element.start - element.headerLength, element.end));\n\tconst rdns: ParsedRelativeDistinguishedName[] = [];\n\tconst allAttributes: ParsedNameAttribute[] = [];\n\tconst values: Partial<Record<NameFieldKey, string>> = {};\n\tfor (const setElement of childrenOf(source, element)) {\n\t\tconst rdnAttributes: ParsedNameAttribute[] = [];\n\t\tconst rdnValues: Partial<Record<NameFieldKey, string>> = {};\n\t\tfor (const attrSequence of childrenOf(source, setElement)) {\n\t\t\tconst parts = childrenOf(source, attrSequence);\n\t\t\tconst oidElement = requireElement(parts[0], 'signer issuer attribute OID');\n\t\t\tconst valueElement = requireElement(parts[1], 'signer issuer attribute value');\n\t\t\tconst oid = decodeObjectIdentifier(oidElement.value);\n\t\t\tlet fieldValue: string;\n\t\t\ttry {\n\t\t\t\tfieldValue = decodeString(valueElement.tag, valueElement.value);\n\t\t\t} catch {\n\t\t\t\tfieldValue = textDecoder.decode(valueElement.value);\n\t\t\t}\n\t\t\tconst fieldKey = nameFieldKeyFromOid(oid);\n\t\t\tconst attribute: ParsedNameAttribute =\n\t\t\t\tfieldKey !== undefined\n\t\t\t\t\t? { oid, key: fieldKey, valueTag: valueElement.tag, value: fieldValue }\n\t\t\t\t\t: { oid, valueTag: valueElement.tag, value: fieldValue };\n\t\t\trdnAttributes.push(attribute);\n\t\t\tallAttributes.push(attribute);\n\t\t\tif (fieldKey !== undefined) {\n\t\t\t\tif (rdnValues[fieldKey] === undefined) {\n\t\t\t\t\trdnValues[fieldKey] = fieldValue;\n\t\t\t\t}\n\t\t\t\tif (values[fieldKey] === undefined) {\n\t\t\t\t\tvalues[fieldKey] = fieldValue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\trdns.push({\n\t\t\tderHex: toHex(source.slice(setElement.start - setElement.headerLength, setElement.end)),\n\t\t\tattributes: rdnAttributes,\n\t\t\tvalues: rdnValues,\n\t\t});\n\t}\n\treturn { derHex, rdns, attributes: allAttributes, values };\n}\n\n/** Returns the nth child element inside a constructed ASN.1 element, or throws. */\nfunction childAt(source: Uint8Array, parent: DerElement, index: number, label: string): DerElement {\n\tlet offset = parent.start;\n\tlet currentIndex = 0;\n\twhile (offset < parent.end) {\n\t\tconst child = readElement(source, offset);\n\t\tif (currentIndex === index) {\n\t\t\treturn child;\n\t\t}\n\t\toffset = child.end;\n\t\tcurrentIndex += 1;\n\t}\n\tthrow new Error(`Missing ${label}`);\n}\n\n// ---------------------------------------------------------------------------\n// CMS signed attributes verification (RFC 5652 Section 5.4)\n// ---------------------------------------------------------------------------\n\n/** Maps a digest algorithm OID to the WebCrypto hash name. */\nfunction digestAlgorithmHash(digestAlgorithmOid: string): 'SHA-256' | 'SHA-384' | 'SHA-512' {\n\tswitch (digestAlgorithmOid) {\n\t\tcase OIDS.sha256:\n\t\t\treturn 'SHA-256';\n\t\tcase OIDS.sha384:\n\t\t\treturn 'SHA-384';\n\t\tcase OIDS.sha512:\n\t\t\treturn 'SHA-512';\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported digest algorithm OID: ${digestAlgorithmOid}`);\n\t}\n}\n\n/** Parses required signed attributes and enforces uniqueness + exact-one-value shape. */\nfunction parseSignedAttributeRequirements(signedAttrsDer: Uint8Array): {\n\treadonly messageDigest: Uint8Array;\n\treadonly contentTypeOid: string;\n} {\n\tconst outer = readElement(signedAttrsDer);\n\tlet messageDigest: Uint8Array | undefined;\n\tlet contentTypeOid: string | undefined;\n\tfor (const attr of childrenOf(signedAttrsDer, outer)) {\n\t\tconst attrDer = signedAttrsDer.slice(attr.start - attr.headerLength, attr.end);\n\t\tconst parts = readSequenceChildren(attrDer);\n\t\tconst oid = parts[0];\n\t\tconst values = parts[1];\n\t\tif (oid === undefined || values === undefined || parts.length !== 2 || values.tag !== 0x31) {\n\t\t\tthrow new Error('Malformed signedAttrs attribute');\n\t\t}\n\t\tconst attrOid = decodeObjectIdentifier(oid.value);\n\t\tconst valueElements = childrenOf(attrDer, values);\n\t\tif (attrOid === OIDS.cmsMessageDigest) {\n\t\t\tif (messageDigest !== undefined || valueElements.length !== 1) {\n\t\t\t\tthrow new Error('messageDigest attribute must appear exactly once with one value');\n\t\t\t}\n\t\t\tconst digestElement = valueElements[0];\n\t\t\tif (digestElement === undefined || digestElement.tag !== 0x04) {\n\t\t\t\tthrow new Error('messageDigest attribute value must use OCTET STRING');\n\t\t\t}\n\t\t\tmessageDigest = digestElement.value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (attrOid === OIDS.cmsContentType) {\n\t\t\tif (contentTypeOid !== undefined || valueElements.length !== 1) {\n\t\t\t\tthrow new Error('contentType attribute must appear exactly once with one value');\n\t\t\t}\n\t\t\tconst contentType = valueElements[0];\n\t\t\tif (contentType === undefined || contentType.tag !== 0x06) {\n\t\t\t\tthrow new Error('contentType attribute value must use OBJECT IDENTIFIER');\n\t\t\t}\n\t\t\tcontentTypeOid = decodeObjectIdentifier(contentType.value);\n\t\t}\n\t}\n\tif (messageDigest === undefined) {\n\t\tthrow new Error('Missing messageDigest attribute in signedAttrs');\n\t}\n\tif (contentTypeOid === undefined) {\n\t\tthrow new Error('Missing contentType attribute in signedAttrs');\n\t}\n\treturn { messageDigest, contentTypeOid };\n}\n\n/** Replaces the IMPLICIT [0] tag (0xa0) with SET OF (0x31) per RFC 5652 Section 5.4. */\nfunction retagSignedAttrsAsSet(signedAttrsDer: Uint8Array): Uint8Array {\n\t// Replace IMPLICIT [0] tag (0xa0) with SET OF tag (0x31) per RFC 5652 Section 5.4\n\tconst copy = new Uint8Array(signedAttrsDer);\n\tcopy[0] = 0x31;\n\treturn copy;\n}\n\n/** Constant-time byte comparison to avoid timing side-channels in digest checks. */\nfunction constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n\tif (a.length !== b.length) {\n\t\treturn false;\n\t}\n\tlet diff = 0;\n\tfor (let index = 0; index < a.length; index += 1) {\n\t\tdiff |= (a[index] ?? 0) ^ (b[index] ?? 0);\n\t}\n\treturn diff === 0;\n}\n\n/** Verifies a signed-attributes flow: digest match + signature over re-tagged attrs. */\nasync function verifySignedAttrs(\n\tsignerInfo: ParsedPkcs7SignerInfo,\n\tsigner: ParsedCertificate,\n\tencapsulatedContent: Uint8Array,\n\tencapsulatedContentTypeOid: string,\n): Promise<\n\t| { readonly ok: true }\n\t| ErrorResult<\n\t\t\t| 'signer_not_found'\n\t\t\t| 'signature_invalid'\n\t\t\t| 'message_digest_mismatch'\n\t\t\t| 'content_missing'\n\t\t\t| ParsePkcs7ErrorCode,\n\t\t\tRecord<never, never>,\n\t\t\tVerifyPkcs7SignedDataFailure\n\t >\n> {\n\tif (!signerInfo.hasSignedAttrs) {\n\t\treturn verifyPkcs7Failure('malformed', 'Missing signedAttrs DER');\n\t}\n\t// Step 1: Parse required signed attributes from signedAttrs\n\tlet signedAttributes: { readonly messageDigest: Uint8Array; readonly contentTypeOid: string };\n\ttry {\n\t\tassertImplicitSignedAttrsDer(signerInfo.signedAttrsDer);\n\t\tsignedAttributes = parseSignedAttributeRequirements(signerInfo.signedAttrsDer);\n\t} catch {\n\t\treturn verifyPkcs7Failure('malformed', 'Malformed signedAttrs in SignedData');\n\t}\n\tif (signedAttributes.contentTypeOid !== encapsulatedContentTypeOid) {\n\t\treturn verifyPkcs7Failure('malformed', 'SignedData contentType attribute does not match');\n\t}\n\t// Step 2: Compute digest of encapsulated content\n\tlet actualDigest: Uint8Array;\n\ttry {\n\t\tconst hash = digestAlgorithmHash(signerInfo.digestAlgorithmOid);\n\t\tactualDigest = new Uint8Array(\n\t\t\tawait getCrypto().subtle.digest(hash, toArrayBuffer(encapsulatedContent)),\n\t\t);\n\t} catch {\n\t\treturn verifyPkcs7Failure('malformed', 'Unsupported digest algorithm in SignedData');\n\t}\n\t// Step 3: Compare digests (constant-time)\n\tif (!constantTimeEqual(actualDigest, signedAttributes.messageDigest)) {\n\t\treturn verifyPkcs7Failure(\n\t\t\t'message_digest_mismatch',\n\t\t\t'Content digest does not match messageDigest attribute',\n\t\t);\n\t}\n\t// Step 4: Verify signature over re-tagged signedAttrs (0xa0 → 0x31 SET OF)\n\tlet signedData: Uint8Array;\n\ttry {\n\t\tsignedData = retagSignedAttrsAsSet(signerInfo.signedAttrsDer);\n\t} catch {\n\t\treturn verifyPkcs7Failure('malformed', 'Malformed signedAttrs in SignedData');\n\t}\n\tlet verified: boolean;\n\ttry {\n\t\tconst verificationResult = await verifySignedDataDetailed(\n\t\t\tsignerInfo.signatureAlgorithmOid,\n\t\t\tsignerInfo.signatureAlgorithmParametersDer,\n\t\t\tsigner.publicKeyAlgorithmOid,\n\t\t\tsigner.publicKeyParametersOid,\n\t\t\tsigner.subjectPublicKeyInfoDer,\n\t\t\tsignerInfo.signature,\n\t\t\tsignedData,\n\t\t);\n\t\tif (!verificationResult.ok) {\n\t\t\tif (verificationResult.code === 'verification_error') {\n\t\t\t\treturn verifyPkcs7Failure('malformed', 'SignedData signature verification failed');\n\t\t\t}\n\t\t\treturn verifyPkcs7Failure('malformed', 'Unsupported signature algorithm in SignedData');\n\t\t}\n\t\tverified = verificationResult.valid;\n\t} catch {\n\t\treturn verifyPkcs7Failure('malformed', 'Unsupported signature algorithm in SignedData');\n\t}\n\tif (!verified) {\n\t\treturn verifyPkcs7Failure(\n\t\t\t'signature_invalid',\n\t\t\t'SignedData signature over signedAttrs does not verify',\n\t\t);\n\t}\n\treturn { ok: true };\n}\n\nfunction signerIdentifierMatches(\n\tcertificate: ParsedCertificate,\n\tsignerInfo: ParsedPkcs7SignerInfo,\n): boolean {\n\tif (signerInfo.issuer !== undefined || signerInfo.serialNumberHex !== undefined) {\n\t\treturn (\n\t\t\tsignerInfo.issuer !== undefined &&\n\t\t\tsignerInfo.serialNumberHex !== undefined &&\n\t\t\tcertificate.serialNumberHex === signerInfo.serialNumberHex &&\n\t\t\tcompareDistinguishedNames(certificate.issuer, signerInfo.issuer)\n\t\t);\n\t}\n\treturn (\n\t\tsignerInfo.subjectKeyIdentifier !== undefined &&\n\t\tcertificate.subjectKeyIdentifier === signerInfo.subjectKeyIdentifier\n\t);\n}\n\nfunction assertImplicitSignedAttrsDer(signedAttrsDer: Uint8Array): void {\n\tif (readElement(signedAttrsDer).tag !== 0xa0) {\n\t\tthrow new Error('signedAttrs must use IMPLICIT [0] tag');\n\t}\n}\n\nfunction hasReparseablePkcs7SignedData(\n\tvalue: ParsedPkcs7SignedData,\n): value is ParsedPkcs7SignedData & { readonly der: Uint8Array } {\n\treturn 'der' in value && value.der instanceof Uint8Array;\n}\n\nfunction assertImplicitSerialNumberEncoding(bytes: Uint8Array, label: string): void {\n\tconst first = bytes[0];\n\tif (first === undefined) {\n\t\tthrow new Error(`${label} must not be empty`);\n\t}\n\tif ((first & 0x80) !== 0) {\n\t\tthrow new Error(`${label} must be non-negative`);\n\t}\n\tif (bytes.length > 1 && first === 0 && ((bytes[1] ?? 0) & 0x80) === 0) {\n\t\tthrow new Error(`${label} must use minimal encoding`);\n\t}\n}\n"],"mappings":"qtCA4OA,SAAgB,EACf,EAC2B,CAG3B,IAAI,EACJ,GAAI,CACH,EAAkB,EAAa,QAAQ,CAA0B,CAClE,MAAQ,CACP,OAAO,EACN,sBACA,yDACD,CACD,CACA,IAAM,EAAa,EAAS,CAC3B,EAAkB,CAAC,EACnB,EAAM,CAAC,CAAC,EACR,EAAS,CAAC,EAAiB,EAAK,SAAS,CAAC,CAAC,EAC3C,EAAgB,EAAG,EAAY,CAAe,CAAC,EAC/C,EAAM,CAAC,CAAC,CACT,CAAC,EACK,EAAM,EAAS,CAAC,EAAiB,EAAK,eAAe,EAAG,EAAgB,EAAG,CAAU,CAAC,CAAC,EAC7F,MAAO,CACN,GAAI,GACJ,MAAO,CAAE,MAAK,IAAK,EAAU,QAAS,CAAG,EAAG,OAAQ,EAAa,CAAG,CAAE,CACvE,CACD,CA4FA,eAAsB,GACrB,EACuC,CACvC,GAAI,EAAM,QAAQ,SAAW,EAC5B,OAAO,EAAmB,aAAc,oDAAoD,EAE7F,IAAM,EAA6B,EAAM,4BAA8B,EAAK,UAOtE,EAAU,EAAM,QAAQ,MAAM,EAE9B,EAAgC,CAAC,EACjC,EAAmB,IAAI,IACvB,EAAkB,GAA0B,CACjD,IAAM,EAAM,EAAM,CAAG,EAChB,EAAiB,IAAI,CAAG,IAC5B,EAAiB,IAAI,CAAG,EACxB,EAAgB,KAAK,CAAG,EAE1B,EAEM,EAAsB,IAAI,IAC1B,EAA4B,CAAC,EACnC,IAAK,IAAM,KAAU,EAAM,QAAS,CACnC,IAAM,EAAiB,EAA2B,EAAO,WAAW,EAC9D,EAAgB,EAAe,GACrC,GAAI,IAAkB,IAAA,IAAa,EAAe,SAAW,EAC5D,OAAO,EACN,6BACA,yDACD,EAED,EAAe,CAAa,EAI5B,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MAAQ,IACvC,MAAU,MAAM,uCAAuC,CAEzD,CAEA,SAAS,GACR,EACgE,CAChE,MAAO,QAAS,GAAS,EAAM,eAAe,UAC/C,CAEA,SAAS,GAAmC,EAAmB,EAAqB,CACnF,IAAM,EAAQ,EAAM,GACpB,GAAI,IAAU,IAAA,GACb,MAAU,MAAM,GAAG,EAAM,mBAAmB,EAE7C,GAAK,EAAQ,IACZ,MAAU,MAAM,GAAG,EAAM,sBAAsB,EAEhD,GAAI,EAAM,OAAS,GAAK,IAAU,GAAA,GAAO,EAAM,IAAM,GAAK,KACzD,MAAU,MAAM,GAAG,EAAM,2BAA2B,CAEtD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"result.js","names":[],"sources":["../../src/result/result.ts"],"sourcesContent":["/**\n * Internal result helper types and constructors shared by low-level modules.\n *\n * Mirrors the public result model without depending on the public barrel.\n *\n * @module\n */\n\n/**\n * Discriminated `ok` union: either `{ ok: true; value }` or `{ ok: false; error }`.\n *\n * Every fallible public API in micro509 returns a specialization of this type.\n */\nexport type Result<TValue, TError> =\n\t| {\n\t\t\t/** Operation succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** Successful payload. */\n\t\t\treadonly value: TValue;\n\t }\n\t| {\n\t\t\t/** Operation failed. */\n\t\t\treadonly ok: false;\n\t\t\t/** Structured error payload. */\n\t\t\treadonly error: TError;\n\t };\n\n/** Failed result with a flattened code/message/details surface for ergonomic matching. */\nexport interface ErrorResult<\n\tTCode extends string,\n\tTDetails,\n\tTError extends Micro509Error<TCode, TDetails>,\n> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n\t/** Structured error payload. */\n\treadonly error: TError;\n\t/** Machine-readable failure reason, mirrored from `error.code`. */\n\treadonly code: TCode;\n\t/** Human-readable diagnostic, mirrored from `error.message`. */\n\treadonly message: string;\n\t/** Optional structured context for the failure. */\n\treadonly details?: TDetails;\n}\n\n/** Like {@link ErrorResult} but also carries an index into the collection that was being processed. */\nexport interface IndexedErrorResult<\n\tTCode extends string,\n\tTDetails,\n\tTError extends IndexedMicro509Error<TCode, TDetails>,\n> extends ErrorResult<TCode, TDetails, TError> {\n\t/** Zero-based position of the failing item in the input collection. */\n\treadonly index?: number;\n}\n\n/** Base error shape carried by all failure results in the library. */\nexport interface Micro509Error<TCode extends string, TDetails = Record<never, never>> {\n\t/** Machine-readable failure reason (e.g. `'malformed'`, `'expired'`). */\n\treadonly code: TCode;\n\t/** Human-readable diagnostic message. */\n\treadonly message: string;\n\t/** Optional structured context for the failure. */\n\treadonly details?: TDetails;\n}\n\n/** Like {@link Micro509Error} but includes a positional index for collection-processing APIs. */\nexport interface IndexedMicro509Error<TCode extends string, TDetails = Record<never, never>>\n\textends Micro509Error<TCode, TDetails> {\n\t/** Zero-based position of the failing item in the input collection. */\n\treadonly index?: number;\n}\n\n/** Wraps a value in a success result (`{ ok: true, value }`). */\nexport function successResult<TValue>(value: TValue): {\n\treadonly ok: true;\n\treadonly value: TValue;\n} {\n\treturn { ok: true, value };\n}\n\n/**\n * Error thrown by {@link unwrap} when a result is a failure.\n *\n * Carries the structured {@link Micro509Error} payload so callers using the\n * throwing escape hatch still get the machine-readable `code` and any details.\n */\nexport interface ResultError<\n\tTError extends Micro509Error<string, unknown> = Micro509Error<string, unknown>,\n> extends Error {\n\t/** Machine-readable failure reason, mirrored from `error.code`. */\n\treadonly code: TError['code'];\n\t/** The structured error payload that produced this exception. */\n\treadonly error: TError;\n}\n\n/** Module-private brand so {@link isResultError} cannot be fooled by look-alike objects. */\nconst resultErrorBrand = Symbol('micro509.ResultError');\n\n/** Builds a {@link ResultError}: a branded `Error` (no class) carrying the structured failure. */\nfunction makeResultError<TError extends Micro509Error<string, unknown>>(\n\terror: TError,\n): ResultError<TError> {\n\treturn Object.assign(new Error(`${error.code}: ${error.message}`), {\n\t\tname: 'ResultError',\n\t\tcode: error.code,\n\t\terror,\n\t\t[resultErrorBrand]: true,\n\t});\n}\n\n/** Type guard: was `value` thrown by {@link unwrap}? Narrows to {@link ResultError}. */\nexport function isResultError(value: unknown): value is ResultError {\n\treturn value instanceof Error && resultErrorBrand in value;\n}\n\n/** A minimal fallible-result shape: `{ ok: true, value }` or `{ ok: false, error }`. */\nexport type UnwrappableResult<TValue, TError> =\n\t| { readonly ok: true; readonly value: TValue }\n\t| { readonly ok: false; readonly error: TError };\n\n/**\n * Explicit escape hatch: returns the success value, or throws a\n * {@link ResultError} carrying the structured failure.\n *\n * Use when you have already validated the input (or prefer exceptions) and the\n * Result ceremony is noise. Accepts any of the library's `*Result` types.\n */\nexport function unwrap<TValue, TError extends Micro509Error<string, unknown>>(\n\tresult: UnwrappableResult<TValue, TError>,\n): TValue {\n\tif (result.ok) {\n\t\treturn result.value;\n\t}\n\tthrow makeResultError(result.error);\n}\n\n/** Returns the success value, or `fallback` when the result is a failure. */\nexport function unwrapOr<TValue>(\n\tresult: UnwrappableResult<TValue, unknown>,\n\tfallback: TValue,\n): TValue {\n\treturn result.ok ? result.value : fallback;\n}\n\n/** JS error types that signal a programmer bug / broken invariant rather than malformed input. */\nconst invariantErrorTypes = [TypeError, RangeError, ReferenceError, SyntaxError] as const;\n\n/**\n * Rethrows `error` if it is an invariant/programmer error (`TypeError`,\n * `RangeError`, `ReferenceError`, `SyntaxError`); otherwise returns.\n *\n * Boundary wrappers that turn an expected failure into a `Result` should call\n * this first, so a genuine crash is never masked as a clean parse/decode\n * failure (AGENTS.md: throw only for invariants).\n */\nexport function rethrowIfInvariant(error: unknown): void {\n\tif (invariantErrorTypes.some((type) => error instanceof type)) {\n\t\tthrow error;\n\t}\n}\n\n/** Constructs a {@link Micro509Error} payload. */\nexport function micro509Error<TCode extends string, TDetails = Record<never, never>>(\n\tcode: TCode,\n\tmessage: string,\n\tdetails?: TDetails,\n): Micro509Error<TCode, TDetails> {\n\treturn {\n\t\tcode,\n\t\tmessage,\n\t\t...(details === undefined ? {} : { details }),\n\t};\n}\n\n/** Constructs an {@link IndexedMicro509Error} payload with an optional collection index. */\nexport function indexedMicro509Error<TCode extends string, TDetails = Record<never, never>>(\n\tcode: TCode,\n\tmessage: string,\n\tindex?: number,\n\tdetails?: TDetails,\n): IndexedMicro509Error<TCode, TDetails> {\n\treturn {\n\t\tcode,\n\t\tmessage,\n\t\t...(index === undefined ? {} : { index }),\n\t\t...(details === undefined ? {} : { details }),\n\t};\n}\n\n/** Wraps a {@link Micro509Error} in a flattened {@link ErrorResult}. */\nexport function errorResult<\n\tTCode extends string,\n\tTDetails,\n\tTError extends Micro509Error<TCode, TDetails>,\n>(error: TError): ErrorResult<TCode, TDetails, TError> {\n\treturn {\n\t\tok: false,\n\t\terror,\n\t\tcode: error.code,\n\t\tmessage: error.message,\n\t\t...(error.details === undefined ? {} : { details: error.details }),\n\t};\n}\n\n/**\n * Builds a flattened failure result in one step.\n *\n * Single source of truth for the `{ ok: false, error, code, message }` shape:\n * modules should construct failures with this instead of hand-rolling the\n * object literal. The `error` payload carries the redundant `ok: false`\n * discriminant so it matches the per-operation `*Failure` interfaces\n * (`interface XFailure extends Micro509Error<…> { ok: false }`).\n */\nexport function failureResult<TCode extends string, TDetails = Record<never, never>>(\n\tcode: TCode,\n\tmessage: string,\n\tdetails?: TDetails,\n): ErrorResult<TCode, TDetails, Micro509Error<TCode, TDetails> & { readonly ok: false }> {\n\treturn errorResult({ ok: false, ...micro509Error(code, message, details) });\n}\n\n/** Wraps an {@link IndexedMicro509Error} in a flattened {@link IndexedErrorResult}. */\nexport function indexedErrorResult<\n\tTCode extends string,\n\tTDetails,\n\tTError extends IndexedMicro509Error<TCode, TDetails>,\n>(error: TError): IndexedErrorResult<TCode, TDetails, TError> {\n\treturn {\n\t\tok: false,\n\t\terror,\n\t\tcode: error.code,\n\t\tmessage: error.message,\n\t\t...(error.details === undefined ? {} : { details: error.details }),\n\t\t...(error.index === undefined ? {} : { index: error.index }),\n\t};\n}\n"],"mappings":"AAyEA,SAAgB,EAAsB,EAGpC,CACD,MAAO,CAAE,GAAI,GAAM,OAAM,CAC1B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KACZ,QAAS,EAAM,QACf,GAAI,EAAM,UAAY,IAAA,GAAY,CAAC,EAAI,CAAE,QAAS,EAAM,OAAQ,EAChE,GAAI,EAAM,QAAU,IAAA,GAAY,CAAC,EAAI,CAAE,MAAO,EAAM,KAAM,CAC3D,CACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"chain.js","names":[],"sources":["../../src/revocation/chain.ts"],"sourcesContent":["/**\n * Chain-level revocation orchestration.\n *\n * Evaluates CRL and OCSP evidence for an entire validated certificate chain,\n * implementing the revocation checking portion of RFC 5280 §6.3.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#section-6.3 | RFC 5280 §6.3 CRL Validation}\n * @module\n */\n\nimport type { ParsedCertificate } from '#micro509/x509/parse.ts';\nimport { parseCertificateFromSource } from '#micro509/x509/parse.ts';\nimport {\n\tcheckCertificateRevocationAgainstCrl,\n\tparseCertificateRevocationListDerOrThrow,\n\tparseCertificateRevocationListPemOrThrow,\n\ttype ParsedCertificateRevocationList,\n\ttype RevocationReason,\n\trevocationReasonFromCode,\n} from './crl.ts';\nimport type { CrlSource } from './crl.ts';\nimport {\n\ttype OcspResponderRevocationPolicy,\n\ttype ParsedOcspResponse,\n\tparseOcspResponseDerOrThrow,\n\tparseOcspResponsePemOrThrow,\n\ttype ValidateOcspResponseFailure,\n\ttype ValidateOcspResponseResult,\n\tvalidateOcspResponse,\n} from './ocsp.ts';\n\nimport type { RevocationCertificateSource } from './revocation.ts';\n\nexport type { CrlSource };\n\n// ---------------------------------------------------------------------------\n// Input Types\n// ---------------------------------------------------------------------------\n\n/**\n * OCSP response in any supported format.\n *\n * Accepts PEM string or DER bytes. Used for\n * {@linkcode CheckChainRevocationInput.ocspResponses}.\n */\nexport type OcspResponseSource = string | Uint8Array;\n\n/**\n * Revocation checking policy for {@linkcode checkChainRevocation}.\n *\n * Controls how indeterminate results (missing evidence, expired CRLs) affect\n * the final {@linkcode CheckChainRevocationValue.decision | decision}.\n */\nexport interface RevocationPolicy {\n\t/**\n\t * How to handle indeterminate status.\n\t *\n\t * - `'hard-fail'`: indeterminate certificates cause denial (default)\n\t * - `'soft-fail'`: indeterminate certificates are allowed — an explicit\n\t * availability/compatibility choice\n\t *\n\t * Revocation checking itself is opt-in: no check runs unless evidence is\n\t * supplied. Once it is, indeterminate status denies by default.\n\t */\n\treadonly mode?: 'soft-fail' | 'hard-fail';\n\t/**\n\t * Evidence preference when multiple sources are available.\n\t *\n\t * Both evidence kinds are always evaluated, and a validated `revoked`\n\t * verdict from either source wins regardless of preference (fail-closed).\n\t * Preference only decides which source's `good` verdict is reported when\n\t * both yield one.\n\t *\n\t * - `'best-available'`: the source with the fresher evidence — the later\n\t * `thisUpdate` on the validated OCSP entry or CRL — is reported; ties\n\t * favor OCSP (default)\n\t * - `'ocsp'`: prefer OCSP over CRL\n\t * - `'crl'`: prefer CRL over OCSP\n\t */\n\treadonly prefer?: 'ocsp' | 'crl' | 'best-available';\n\t/**\n\t * Revocation policy for delegated OCSP responder certificates\n\t * (RFC 6960 §4.2.2.2.1). Supplied CRLs double as responder revocation\n\t * evidence. Defaults to `'honor-nocheck'`.\n\t */\n\treadonly ocspResponderRevocation?: OcspResponderRevocationPolicy;\n}\n\n/** Input for {@linkcode checkChainRevocation}. */\nexport interface CheckChainRevocationInput {\n\t/** Validated certificate chain (leaf first, root last). */\n\treadonly chain: readonly ParsedCertificate[];\n\t/** CRLs to evaluate. */\n\treadonly crls?: readonly CrlSource[];\n\t/** OCSP responses to evaluate. */\n\treadonly ocspResponses?: readonly OcspResponseSource[];\n\t/** Extra certs for indirect CRL issuers / delegated OCSP responders. */\n\treadonly extraCertificates?: readonly RevocationCertificateSource[];\n\t/**\n\t * Explicitly trusted OCSP responder certificates (RFC 6960 §4.2.2.2\n\t * criterion 1). A response signed by one of these is accepted without\n\t * delegated-responder issuance, EKU, and revocation checks.\n\t */\n\treadonly trustedOcspResponders?: readonly RevocationCertificateSource[];\n\t/** Evaluation time. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/** Revocation policy. */\n\treadonly policy?: RevocationPolicy;\n}\n\n// ---------------------------------------------------------------------------\n// Output Types\n// ---------------------------------------------------------------------------\n\n/**\n * Granular reasons why revocation status could not be determined.\n *\n * Returned in {@linkcode CertificateRevocationStatus.indeterminateReasons} when\n * `status` is `'indeterminate'`. Grouped by category:\n *\n * - **Evidence not found**: `no_applicable_crl`, `no_applicable_ocsp`\n * - **Scope mismatch**: `distribution_point_mismatch`, `issuer_name_mismatch`,\n * `reason_scope_mismatch`, `indirect_crl_scope_mismatch`, `reason_coverage_incomplete`\n * - **Signer trust**: `crl_signer_not_found`, `crl_signer_not_authorized`,\n * `crl_signer_revoked`, `crl_signer_indeterminate`, and OCSP equivalents\n * - **Freshness**: `crl_expired`, `ocsp_response_expired`\n */\nexport const REVOCATION_INDETERMINATE_REASONS = [\n\t// Evidence not found\n\t'no_applicable_crl',\n\t'no_applicable_ocsp',\n\t// Scope issues\n\t'distribution_point_mismatch',\n\t'issuer_name_mismatch',\n\t'reason_scope_mismatch',\n\t'indirect_crl_scope_mismatch',\n\t'reason_coverage_incomplete',\n\t// Signer trust issues\n\t'crl_signer_not_found',\n\t'crl_signer_not_authorized',\n\t'crl_signer_revoked',\n\t'crl_signer_indeterminate',\n\t'ocsp_responder_not_found',\n\t'ocsp_responder_not_authorized',\n\t'ocsp_responder_revoked',\n\t'ocsp_responder_indeterminate',\n\t// Freshness\n\t'crl_expired',\n\t'ocsp_response_expired',\n\t// OCSP specific\n\t'ocsp_status_unknown',\n] as const;\n\n/** See the doc comment above {@linkcode REVOCATION_INDETERMINATE_REASONS}. */\nexport type RevocationIndeterminateReason = (typeof REVOCATION_INDETERMINATE_REASONS)[number];\n\n/**\n * Identifies the source of revocation evidence.\n *\n * Included in {@linkcode CertificateRevocationStatus.source} when status is\n * `'good'` or `'revoked'` to indicate which CRL or OCSP response provided the answer.\n */\nexport interface RevocationSource {\n\t/** Whether evidence came from a CRL or OCSP response. */\n\treadonly kind: 'crl' | 'ocsp';\n\t/** Certificate that signed the evidence (CRL issuer or OCSP responder). */\n\treadonly signerCertificate?: ParsedCertificate;\n\t/** Identifier for debugging (e.g., CRL issuer DN or OCSP responder URL). */\n\treadonly evidenceIdentifier?: string;\n\t/**\n\t * `thisUpdate` of the evidence backing the verdict — the OCSP single\n\t * response entry or the freshest contributing CRL (an applied delta CRL\n\t * supersedes its base). This is the timestamp `'best-available'` compares.\n\t */\n\treadonly thisUpdate?: Date;\n}\n\n/**\n * Revocation evaluation result for a single certificate.\n *\n * One entry per certificate in {@linkcode CheckChainRevocationValue.certificates}.\n * The trust anchor is excluded (never checked for revocation).\n */\nexport type CertificateRevocationStatus =\n\t| {\n\t\t\t/** The certificate that was evaluated. */\n\t\t\treadonly certificate: ParsedCertificate;\n\t\t\t/** Evidence confirms the certificate is not revoked. */\n\t\t\treadonly status: 'good';\n\t\t\t/** Evidence that produced the verdict. */\n\t\t\treadonly source: RevocationSource;\n\t\t\t/** Never present on a `good` verdict. */\n\t\t\treadonly indeterminateReasons?: undefined;\n\t\t\t/** Never present on a `good` verdict. */\n\t\t\treadonly revocationInfo?: undefined;\n\t }\n\t| {\n\t\t\t/** The certificate that was evaluated. */\n\t\t\treadonly certificate: ParsedCertificate;\n\t\t\t/** Evidence confirms the certificate is revoked. */\n\t\t\treadonly status: 'revoked';\n\t\t\t/** Evidence that produced the verdict. */\n\t\t\treadonly source: RevocationSource;\n\t\t\t/** Revocation details from the CRL entry or OCSP response. */\n\t\t\treadonly revocationInfo: {\n\t\t\t\t/** When the certificate was revoked. */\n\t\t\t\treadonly revocationDate: Date;\n\t\t\t\t/** RFC 5280 CRLReason code, if provided by the CRL/OCSP response. */\n\t\t\t\treadonly reason?: RevocationReason;\n\t\t\t};\n\t\t\t/** Never present on a `revoked` verdict. */\n\t\t\treadonly indeterminateReasons?: undefined;\n\t }\n\t| {\n\t\t\t/** The certificate that was evaluated. */\n\t\t\treadonly certificate: ParsedCertificate;\n\t\t\t/** Revocation status could not be determined. */\n\t\t\treadonly status: 'indeterminate';\n\t\t\t/** Why status could not be determined. */\n\t\t\treadonly indeterminateReasons: readonly RevocationIndeterminateReason[];\n\t\t\t/** Never present on an `indeterminate` verdict. */\n\t\t\treadonly source?: undefined;\n\t\t\t/** Never present on an `indeterminate` verdict. */\n\t\t\treadonly revocationInfo?: undefined;\n\t };\n\n/**\n * Errors encountered while processing revocation evidence.\n *\n * Distinct from {@linkcode RevocationIndeterminateReason}: execution errors are\n * code failures (malformed CRL, unsupported extension) rather than evaluation\n * outcomes (CRL doesn't cover this certificate).\n *\n * Collected in {@linkcode CheckChainRevocationValue.executionErrors}.\n */\nexport interface RevocationExecutionError {\n\t/** Error category. */\n\treadonly kind: 'parse_error' | 'unsupported_extension' | 'internal_error';\n\t/** Human-readable error description. */\n\treadonly message: string;\n\t/** Which evidence caused the error (e.g., CRL issuer DN). */\n\treadonly evidenceIdentifier?: string;\n}\n\n/**\n * Detailed revocation check results.\n *\n * Returned as {@linkcode CheckChainRevocationResult.value} from\n * {@linkcode checkChainRevocation}. Contains both the policy decision and\n * detailed per-certificate findings for debugging.\n */\nexport interface CheckChainRevocationValue {\n\t/**\n\t * Final policy decision based on {@linkcode RevocationPolicy}.\n\t *\n\t * - `'allow'`: chain passes revocation check\n\t * - `'deny'`: chain fails (revoked certificate or hard-fail on indeterminate)\n\t */\n\treadonly decision: 'allow' | 'deny';\n\t/** Quick-access summary of problematic certificates. */\n\treadonly summary: {\n\t\t/** Certificates confirmed as revoked. */\n\t\treadonly revokedCertificates: readonly ParsedCertificate[];\n\t\t/** Certificates whose status could not be determined. */\n\t\treadonly indeterminateCertificates: readonly ParsedCertificate[];\n\t};\n\t/** Per-certificate evaluation results. See {@linkcode CertificateRevocationStatus}. */\n\treadonly certificates: readonly CertificateRevocationStatus[];\n\t/** Evidence that could not be processed. See {@linkcode RevocationExecutionError}. */\n\treadonly executionErrors?: readonly RevocationExecutionError[];\n}\n\n/** Result type for {@linkcode checkChainRevocation}. */\nexport type CheckChainRevocationResult = {\n\treadonly ok: true;\n\treadonly value: CheckChainRevocationValue;\n};\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Parses a CRL from various source formats.\n */\nfunction parseCrlFromSource(source: CrlSource): ParsedCertificateRevocationList {\n\tif (typeof source === 'object' && 'issuer' in source) {\n\t\treturn source;\n\t}\n\tif (typeof source === 'string') {\n\t\treturn parseCertificateRevocationListPemOrThrow(source);\n\t}\n\treturn parseCertificateRevocationListDerOrThrow(source);\n}\n\n/**\n * Parses a certificate from various source formats, returning undefined on failure.\n */\nfunction parseCertificateSafe(source: RevocationCertificateSource): ParsedCertificate | undefined {\n\ttry {\n\t\treturn parseCertificateFromSource(source);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Compares two certificates by DER bytes for identity.\n * Reference equality fails when same cert is parsed from different sources.\n */\nfunction sameCertificate(a: ParsedCertificate, b: ParsedCertificate): boolean {\n\tif (a.der.length !== b.der.length) return false;\n\tfor (let i = 0; i < a.der.length; i++) {\n\t\tif (a.der[i] !== b.der[i]) return false;\n\t}\n\treturn true;\n}\n\n/**\n * Searches for a certificate that could have signed the given CRL.\n * Matches by AKI/SKI or issuer/subject DN.\n */\nfunction findIndirectCrlIssuer(\n\tcrl: ParsedCertificateRevocationList,\n\textraCertificates: readonly RevocationCertificateSource[],\n\tchain: readonly ParsedCertificate[],\n): ParsedCertificate | undefined {\n\t// Combine extra certs with chain certs for searching\n\t// Chain certs are already parsed; extra certs may need parsing\n\tconst parsedExtras: ParsedCertificate[] = [];\n\tfor (const source of extraCertificates) {\n\t\tconst parsed = parseCertificateSafe(source);\n\t\tif (parsed !== undefined) {\n\t\t\tparsedExtras.push(parsed);\n\t\t}\n\t}\n\n\tconst candidates = [...parsedExtras, ...chain];\n\n\t// First pass: prefer AKI/SKI match (more specific)\n\tif (crl.authorityKeyIdentifier !== undefined) {\n\t\tfor (const candidate of candidates) {\n\t\t\tif (\n\t\t\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\t\t\tnormalizeHex(crl.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)\n\t\t\t) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: fall back to DN match\n\tfor (const candidate of candidates) {\n\t\tif (crl.issuer.derHex === candidate.subject.derHex) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/** Lowercases a hex string for bytewise comparison. */\nfunction normalizeHex(value: string): string {\n\treturn value.toLowerCase();\n}\n\n// ---------------------------------------------------------------------------\n// CRL Signer Validation (RFC 5280 §6.3.3)\n// ---------------------------------------------------------------------------\n\n/**\n * State machine for CRL signer validation with memoization.\n * - `visiting`: Currently being checked (cycle detection)\n * - `resolved-valid`: Signer is not revoked\n * - `resolved-revoked`: Signer is revoked\n * - `resolved-indeterminate`: Can't determine signer status\n */\ntype SignerValidationState =\n\t| 'visiting'\n\t| 'resolved-valid'\n\t| 'resolved-revoked'\n\t| 'resolved-indeterminate';\n\n/** Context for CRL signer validation with memoization cache. */\ninterface SignerValidationContext {\n\treadonly cache: Map<string, SignerValidationState>;\n\treadonly chain: readonly ParsedCertificate[];\n\treadonly crls: readonly CrlSource[];\n\treadonly extraCertificates: readonly RevocationCertificateSource[];\n\treadonly at: Date;\n}\n\n/**\n * Builds a unique cache key for a certificate.\n * Uses issuer DN + serial number which uniquely identifies a cert.\n */\nfunction certCacheKey(cert: ParsedCertificate): string {\n\treturn `${cert.issuer.derHex}:${cert.serialNumberHex}`;\n}\n\n/**\n * Validates that a CRL signer certificate is not revoked.\n * Uses memoization to avoid redundant checks and detect cycles.\n */\nasync function validateCrlSigner(\n\tsigner: ParsedCertificate,\n\tctx: SignerValidationContext,\n): Promise<SignerValidationState> {\n\t// Use issuer+serial as cache key (unique per certificate)\n\tconst key = certCacheKey(signer);\n\tconst cached = ctx.cache.get(key);\n\n\t// Cycle detection: if we're already visiting this signer, it's indeterminate\n\tif (cached === 'visiting') {\n\t\treturn 'resolved-indeterminate';\n\t}\n\n\t// Return cached result if already resolved\n\tif (cached !== undefined) {\n\t\treturn cached;\n\t}\n\n\t// Mark as visiting before recursive checks\n\tctx.cache.set(key, 'visiting');\n\n\t// Trust anchor (last in chain) is trusted by definition\n\tconst trustAnchor = ctx.chain[ctx.chain.length - 1];\n\tif (trustAnchor !== undefined && sameCertificate(signer, trustAnchor)) {\n\t\tctx.cache.set(key, 'resolved-valid');\n\t\treturn 'resolved-valid';\n\t}\n\n\t// If signer is in the validated chain, it's trusted\n\t// (Chain was already validated before revocation checking)\n\tconst isInChain = ctx.chain.some((c) => sameCertificate(c, signer));\n\tif (isInChain) {\n\t\tctx.cache.set(key, 'resolved-valid');\n\t\treturn 'resolved-valid';\n\t}\n\n\t// Signer is not in chain — need to check its revocation status\n\t// Find signer's issuer to perform revocation check\n\tconst signerIssuer = findSignerIssuer(signer, ctx);\n\tif (signerIssuer === undefined) {\n\t\tctx.cache.set(key, 'resolved-indeterminate');\n\t\treturn 'resolved-indeterminate';\n\t}\n\n\t// Check signer's revocation status (recursive)\n\tconst signerRevocation = await checkSignerRevocation(signer, signerIssuer, ctx);\n\tctx.cache.set(key, signerRevocation);\n\treturn signerRevocation;\n}\n\n/**\n * Finds the issuer certificate for a CRL signer.\n * Searches the chain and extraCertificates by AKI/SKI or DN matching.\n */\nfunction findSignerIssuer(\n\tsigner: ParsedCertificate,\n\tctx: SignerValidationContext,\n): ParsedCertificate | undefined {\n\t// Parse extra certificates\n\tconst parsedExtras: ParsedCertificate[] = [];\n\tfor (const source of ctx.extraCertificates) {\n\t\tconst parsed = parseCertificateSafe(source);\n\t\tif (parsed !== undefined) {\n\t\t\tparsedExtras.push(parsed);\n\t\t}\n\t}\n\n\tconst candidates = [...ctx.chain, ...parsedExtras];\n\n\tfor (const candidate of candidates) {\n\t\t// Match by AKI → SKI (preferred, more specific)\n\t\tif (\n\t\t\tsigner.authorityKeyIdentifier !== undefined &&\n\t\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\t\tnormalizeHex(signer.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)\n\t\t) {\n\t\t\treturn candidate;\n\t\t}\n\n\t\t// Match by issuer DN → subject DN\n\t\tif (signer.issuer.derHex === candidate.subject.derHex) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Checks if a CRL signer certificate is revoked by examining available CRLs.\n * Recursively validates the CRL signer of any CRL used to check revocation.\n */\nasync function checkSignerRevocation(\n\tsigner: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tctx: SignerValidationContext,\n): Promise<SignerValidationState> {\n\t// If the signer's issuer is in the validated chain, the signer is trusted\n\t// by virtue of being issued by a trusted CA. We only need to check if\n\t// it's explicitly revoked, not prove \"good\" status.\n\tconst issuerInChain = ctx.chain.some((c) => sameCertificate(c, issuer));\n\n\t// Try each CRL to check signer's revocation\n\tfor (const crlSource of ctx.crls) {\n\t\tlet crl: ParsedCertificateRevocationList;\n\t\ttry {\n\t\t\tcrl = parseCrlFromSource(crlSource);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check if this CRL can provide revocation info for the signer\n\t\tconst result = await checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: signer,\n\t\t\tissuerCertificate: issuer,\n\t\t\tcrl,\n\t\t\tat: ctx.at,\n\t\t});\n\n\t\tif (result.ok) {\n\t\t\tif (result.value.status === 'revoked') {\n\t\t\t\treturn 'resolved-revoked';\n\t\t\t}\n\t\t\tif (result.value.status === 'good') {\n\t\t\t\t// Before accepting this result, validate the CRL's signer\n\t\t\t\t// The CRL's signer is the issuer we just used\n\t\t\t\tconst crlSignerStatus = await validateCrlSigner(issuer, ctx);\n\t\t\t\tif (crlSignerStatus === 'resolved-valid') {\n\t\t\t\t\treturn 'resolved-valid';\n\t\t\t\t}\n\t\t\t\t// If CRL signer is revoked or indeterminate, can't trust this result\n\t\t\t}\n\t\t}\n\t}\n\n\t// If the signer's issuer is in the chain and we found no revocation,\n\t// trust the signer (issued by trusted CA, no evidence of revocation)\n\tif (issuerInChain) {\n\t\treturn 'resolved-valid';\n\t}\n\n\treturn 'resolved-indeterminate';\n}\n\n/** Builds the `revoked` CertificateRevocationStatus for a CRL hit. */\nfunction buildCrlRevokedStatus(\n\tcert: ParsedCertificate,\n\tsigner: ParsedCertificate,\n\tthisUpdate: Date,\n\trevocationDate: Date,\n\treasonCode?: RevocationReason,\n): CertificateRevocationStatus {\n\treturn {\n\t\tcertificate: cert,\n\t\tstatus: 'revoked',\n\t\tsource: { kind: 'crl', signerCertificate: signer, thisUpdate },\n\t\trevocationInfo: {\n\t\t\trevocationDate,\n\t\t\t...(reasonCode !== undefined ? { reason: reasonCode } : {}),\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// OCSP Evidence Evaluation (RFC 6960)\n// ---------------------------------------------------------------------------\n\n/** Per-certificate evidence evaluation outcome shared by the CRL and OCSP evaluators. */\ninterface EvidenceEvaluation {\n\treadonly status: CertificateRevocationStatus;\n\treadonly executionErrors: readonly RevocationExecutionError[];\n}\n\n/** Parses an OCSP response from PEM string or DER bytes. */\nfunction parseOcspResponseFromSource(source: OcspResponseSource): ParsedOcspResponse {\n\tif (typeof source === 'string') {\n\t\treturn parseOcspResponsePemOrThrow(source);\n\t}\n\treturn parseOcspResponseDerOrThrow(source);\n}\n\n/** Maps a {@linkcode validateOcspResponse} failure code to an indeterminate reason. */\nfunction ocspIndeterminateReasonFromFailure(\n\tcode: ValidateOcspResponseFailure['code'],\n): RevocationIndeterminateReason {\n\tswitch (code) {\n\t\tcase 'stale_response':\n\t\t\treturn 'ocsp_response_expired';\n\t\tcase 'responder_id_mismatch':\n\t\tcase 'responder_chain_invalid':\n\t\tcase 'ocsp_signing_missing':\n\t\t\treturn 'ocsp_responder_not_authorized';\n\t\tcase 'responder_revoked':\n\t\t\treturn 'ocsp_responder_revoked';\n\t\tcase 'signature_invalid':\n\t\tcase 'responder_revocation_unknown':\n\t\t\treturn 'ocsp_responder_indeterminate';\n\t\tcase 'response_status_invalid':\n\t\tcase 'issuer_mismatch':\n\t\tcase 'nonce_mismatch':\n\t\tcase 'request_mismatch':\n\t\t\treturn 'no_applicable_ocsp';\n\t}\n}\n\n/** Validation failures worth retrying with an explicit responder certificate. */\nconst OCSP_RESPONDER_FAILURE_CODES: ReadonlySet<ValidateOcspResponseFailure['code']> = new Set([\n\t'signature_invalid',\n\t'responder_id_mismatch',\n\t'responder_chain_invalid',\n\t'ocsp_signing_missing',\n]);\n\n/**\n * Validates an OCSP response, retrying with caller-provided extra certificates\n * as explicit responder certificates when embedded discovery fails.\n */\nasync function validateOcspResponseWithResponderFallback(\n\tresponse: ParsedOcspResponse,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tat: Date,\n): Promise<ValidateOcspResponseResult> {\n\tconst shared = {\n\t\tissuerCertificate: issuer,\n\t\tat,\n\t\t...(input.trustedOcspResponders !== undefined\n\t\t\t? { trustedOcspResponders: input.trustedOcspResponders }\n\t\t\t: {}),\n\t\t...(input.policy?.ocspResponderRevocation !== undefined\n\t\t\t? { responderRevocationPolicy: input.policy.ocspResponderRevocation }\n\t\t\t: {}),\n\t\t// Chain-level CRLs double as responder revocation evidence\n\t\t...(input.crls !== undefined ? { responderRevocationCrls: input.crls } : {}),\n\t};\n\tconst primary = await validateOcspResponse({ response, ...shared });\n\tif (primary.ok || !OCSP_RESPONDER_FAILURE_CODES.has(primary.code)) {\n\t\treturn primary;\n\t}\n\tfor (const source of input.extraCertificates ?? []) {\n\t\tconst responder = parseCertificateSafe(source);\n\t\tif (responder === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst retry = await validateOcspResponse({\n\t\t\tresponse,\n\t\t\t...shared,\n\t\t\tresponderCertificate: responder,\n\t\t});\n\t\tif (retry.ok) {\n\t\t\treturn retry;\n\t\t}\n\t}\n\treturn primary;\n}\n\n/**\n * Evaluates OCSP evidence for a single certificate (RFC 6960).\n *\n * Every response is fully validated — signature, responder binding and\n * authorization, and freshness — via {@linkcode validateOcspResponse} before\n * its status entry is trusted. Issuer binding of each CertID is enforced by\n * the validator, so a serial-number match on a validated response is\n * sufficient to attribute the entry to `cert`.\n */\nasync function evaluateOcspEvidence(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n): Promise<EvidenceEvaluation> {\n\tconst { ocspResponses = [], at = new Date() } = input;\n\tconst executionErrors: RevocationExecutionError[] = [];\n\tconst reasons = new Set<RevocationIndeterminateReason>();\n\n\tfor (const source of ocspResponses) {\n\t\tlet parsed: ParsedOcspResponse;\n\t\ttry {\n\t\t\tparsed = parseOcspResponseFromSource(source);\n\t\t} catch (e) {\n\t\t\texecutionErrors.push({\n\t\t\t\tkind: 'parse_error',\n\t\t\t\tmessage: e instanceof Error ? e.message : 'OCSP response parse failed',\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst entry = (parsed.responses ?? []).find(\n\t\t\t(single) =>\n\t\t\t\tnormalizeHex(single.certId.serialNumberHex) === normalizeHex(cert.serialNumberHex),\n\t\t);\n\t\tif (entry === undefined) {\n\t\t\tcontinue; // Response does not cover this certificate\n\t\t}\n\n\t\tconst validation = await validateOcspResponseWithResponderFallback(parsed, issuer, input, at);\n\t\tif (!validation.ok) {\n\t\t\treasons.add(ocspIndeterminateReasonFromFailure(validation.code));\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.certStatus === 'revoked') {\n\t\t\tconst reason = revocationReasonFromCode(entry.revocationReasonCode);\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'revoked',\n\t\t\t\t\tsource: { kind: 'ocsp', thisUpdate: entry.thisUpdate },\n\t\t\t\t\trevocationInfo: {\n\t\t\t\t\t\trevocationDate: entry.revokedAt ?? entry.thisUpdate,\n\t\t\t\t\t\t...(reason !== undefined ? { reason } : {}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\tif (entry.certStatus === 'good') {\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'good',\n\t\t\t\t\tsource: { kind: 'ocsp', thisUpdate: entry.thisUpdate },\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\treasons.add('ocsp_status_unknown');\n\t}\n\n\tif (reasons.size === 0) {\n\t\treasons.add('no_applicable_ocsp');\n\t}\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: [...reasons],\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n/**\n * Evaluates revocation status for a single certificate using available CRLs.\n * Returns both status and any execution errors encountered.\n *\n * Tries the chain issuer first; if that fails, searches extraCertificates\n * and chain for an indirect CRL issuer that matches the CRL's AKI or issuer DN.\n *\n * Also validates that CRL signers are not revoked (RFC 5280 §6.3.3).\n */\n// RFC 5280 ReasonFlags — all possible revocation reasons that CRLs can cover.\nconst ALL_REASON_FLAGS: readonly string[] = [\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];\n\nasync function evaluateCrlEvidence(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tsignerCtx: SignerValidationContext,\n): Promise<EvidenceEvaluation> {\n\tconst { crls = [], extraCertificates = [], chain = [], at = new Date() } = input;\n\tconst executionErrors: RevocationExecutionError[] = [];\n\tlet sawCrlSignerRevoked = false;\n\tlet sawCrlSignerIndeterminate = false;\n\tlet sawGood = false;\n\t// Signer and thisUpdate are tracked together so the reported\n\t// signerCertificate always belongs to the CRL whose freshness is reported.\n\tlet freshestGood: { readonly signer: ParsedCertificate; readonly thisUpdate: Date } | undefined;\n\tconst coveredReasons = new Set<string>();\n\n\t// Parse all CRLs and separate base CRLs from delta CRLs\n\tconst parsedCrls: ParsedCertificateRevocationList[] = [];\n\tfor (const crlSource of crls) {\n\t\ttry {\n\t\t\tparsedCrls.push(parseCrlFromSource(crlSource));\n\t\t} catch (e) {\n\t\t\texecutionErrors.push({\n\t\t\t\tkind: 'parse_error',\n\t\t\t\tmessage: e instanceof Error ? e.message : 'CRL parse failed',\n\t\t\t});\n\t\t}\n\t}\n\n\tconst baseCrls = parsedCrls.filter((crl) => crl.baseCrlNumber === undefined);\n\tconst deltaCrls = parsedCrls.filter((crl) => crl.baseCrlNumber !== undefined);\n\n\t// Helper to check CRL with given issuer and optional delta\n\tconst checkWithIssuer = async (\n\t\tcrl: ParsedCertificateRevocationList,\n\t\tdeltaCrl: ParsedCertificateRevocationList | undefined,\n\t\tcrlIssuer: ParsedCertificate,\n\t) => {\n\t\treturn checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: cert,\n\t\t\tissuerCertificate: crlIssuer,\n\t\t\tcrl,\n\t\t\t...(deltaCrl !== undefined ? { deltaCrl } : {}),\n\t\t\tat,\n\t\t});\n\t};\n\n\t// Process base CRLs (optionally paired with delta CRLs)\n\tfor (const baseCrl of baseCrls) {\n\t\t// Find applicable delta CRL for this base CRL (if any)\n\t\t// Delta CRL applies if it has the same issuer and crlNumber matches baseCrlNumber\n\t\tconst applicableDelta = deltaCrls.find(\n\t\t\t(d) =>\n\t\t\t\td.issuer.derHex === baseCrl.issuer.derHex &&\n\t\t\t\td.baseCrlNumber !== undefined &&\n\t\t\t\tbaseCrl.crlNumber !== undefined &&\n\t\t\t\tBigInt(d.baseCrlNumber) <= BigInt(baseCrl.crlNumber),\n\t\t);\n\n\t\t// Try chain issuer first\n\t\tlet result = await checkWithIssuer(baseCrl, applicableDelta, issuer);\n\t\tlet effectiveSigner = issuer;\n\n\t\t// Chain issuer failed — try to find indirect CRL issuer\n\t\tif (!result.ok) {\n\t\t\tconst indirectIssuer = findIndirectCrlIssuer(baseCrl, extraCertificates, chain);\n\t\t\tif (indirectIssuer !== undefined && !sameCertificate(indirectIssuer, issuer)) {\n\t\t\t\tresult = await checkWithIssuer(baseCrl, applicableDelta, indirectIssuer);\n\t\t\t\teffectiveSigner = indirectIssuer;\n\t\t\t}\n\t\t}\n\n\t\tif (!result.ok) {\n\t\t\tcontinue; // CRL doesn't apply to this certificate\n\t\t}\n\n\t\t// Validate CRL signer is not revoked before accepting result\n\t\tconst signerStatus = await validateCrlSigner(effectiveSigner, signerCtx);\n\t\tif (signerStatus === 'resolved-revoked') {\n\t\t\tsawCrlSignerRevoked = true;\n\t\t\tcontinue; // CRL signer revoked — can't trust this CRL\n\t\t}\n\t\tif (signerStatus === 'resolved-indeterminate') {\n\t\t\tsawCrlSignerIndeterminate = true;\n\t\t\tcontinue; // CRL signer status unknown — try other CRLs\n\t\t}\n\n\t\t// Evidence freshness: an applied delta CRL supersedes its base\n\t\tconst crlThisUpdate =\n\t\t\tapplicableDelta !== undefined &&\n\t\t\tapplicableDelta.thisUpdate.getTime() > baseCrl.thisUpdate.getTime()\n\t\t\t\t? applicableDelta.thisUpdate\n\t\t\t\t: baseCrl.thisUpdate;\n\n\t\t// CRL is valid — check result\n\t\tif (result.value.status === 'revoked') {\n\t\t\t// Immediately return revoked status\n\t\t\treturn {\n\t\t\t\tstatus: buildCrlRevokedStatus(\n\t\t\t\t\tcert,\n\t\t\t\t\teffectiveSigner,\n\t\t\t\t\tcrlThisUpdate,\n\t\t\t\t\tresult.value.revocationDate,\n\t\t\t\t\tresult.value.reasonCode,\n\t\t\t\t),\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\n\t\t// Status is 'good' — track which reasons this CRL covers\n\t\tsawGood = true;\n\t\tif (freshestGood === undefined || crlThisUpdate.getTime() > freshestGood.thisUpdate.getTime()) {\n\t\t\tfreshestGood = { signer: effectiveSigner, thisUpdate: crlThisUpdate };\n\t\t}\n\t\tconst crlReasons = baseCrl.issuingDistributionPoint?.onlySomeReasons?.flags;\n\t\tif (crlReasons === undefined) {\n\t\t\t// CRL covers all reasons\n\t\t\tfor (const reason of ALL_REASON_FLAGS) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t} else {\n\t\t\t// CRL only covers specific reasons\n\t\t\tfor (const reason of crlReasons) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return 'good' only if we saw at least one good result AND all reasons are covered\n\tif (sawGood && freshestGood !== undefined) {\n\t\tconst allReasonsCovered = ALL_REASON_FLAGS.every((r) => coveredReasons.has(r));\n\t\tif (allReasonsCovered) {\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'good',\n\t\t\t\t\tsource: {\n\t\t\t\t\t\tkind: 'crl',\n\t\t\t\t\t\tsignerCertificate: freshestGood.signer,\n\t\t\t\t\t\tthisUpdate: freshestGood.thisUpdate,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\t// Not all reasons covered — indeterminate\n\t\treturn {\n\t\t\tstatus: {\n\t\t\t\tcertificate: cert,\n\t\t\t\tstatus: 'indeterminate',\n\t\t\t\tindeterminateReasons: ['reason_coverage_incomplete'],\n\t\t\t},\n\t\t\texecutionErrors,\n\t\t};\n\t}\n\n\t// No applicable CRL found — determine most appropriate indeterminate reason\n\tconst reasons: RevocationIndeterminateReason[] = [];\n\tif (sawCrlSignerRevoked) {\n\t\treasons.push('crl_signer_revoked');\n\t} else if (sawCrlSignerIndeterminate) {\n\t\treasons.push('crl_signer_indeterminate');\n\t} else {\n\t\treasons.push('no_applicable_crl');\n\t}\n\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: reasons,\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n/**\n * Evaluates revocation status for a single certificate by combining OCSP and\n * CRL evidence.\n *\n * Both evidence kinds are always evaluated: a validated `revoked` verdict from\n * either source wins regardless of {@linkcode RevocationPolicy.prefer}\n * (fail-closed). Otherwise the preferred source's `good` verdict is reported —\n * for `'best-available'` the source with the later evidence `thisUpdate` wins,\n * ties favoring OCSP. If neither source is definitive, indeterminate reasons\n * from both are merged.\n */\nasync function evaluateCertificateRevocation(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tsignerCtx: SignerValidationContext,\n): Promise<EvidenceEvaluation> {\n\tconst prefer = input.policy?.prefer ?? 'best-available';\n\tconst ocsp = await evaluateOcspEvidence(cert, issuer, input);\n\tconst crl = await evaluateCrlEvidence(cert, issuer, input, signerCtx);\n\tconst executionErrors = [...ocsp.executionErrors, ...crl.executionErrors];\n\n\t// 'best-available' ranks by evidence freshness; the sort is stable, so\n\t// equal (or absent) thisUpdate keeps OCSP first.\n\tconst ordered =\n\t\tprefer === 'crl'\n\t\t\t? [crl, ocsp]\n\t\t\t: prefer === 'ocsp'\n\t\t\t\t? [ocsp, crl]\n\t\t\t\t: [ocsp, crl].sort(\n\t\t\t\t\t\t(a, b) =>\n\t\t\t\t\t\t\t(b.status.source?.thisUpdate?.getTime() ?? 0) -\n\t\t\t\t\t\t\t(a.status.source?.thisUpdate?.getTime() ?? 0),\n\t\t\t\t\t);\n\tconst revoked = ordered.find((evaluation) => evaluation.status.status === 'revoked');\n\tif (revoked !== undefined) {\n\t\treturn { status: revoked.status, executionErrors };\n\t}\n\tconst good = ordered.find((evaluation) => evaluation.status.status === 'good');\n\tif (good !== undefined) {\n\t\treturn { status: good.status, executionErrors };\n\t}\n\n\tconst reasons = new Set<RevocationIndeterminateReason>();\n\tfor (const evaluation of ordered) {\n\t\tfor (const reason of evaluation.status.indeterminateReasons ?? []) {\n\t\t\treasons.add(reason);\n\t\t}\n\t}\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: [...reasons],\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Function\n// ---------------------------------------------------------------------------\n\n/**\n * Checks revocation status for all certificates in a validated chain.\n *\n * Evaluates CRL and OCSP evidence against each certificate (except the trust\n * anchor), applies the revocation policy, and returns a unified decision.\n *\n * @example\n * ```ts\n * const result = await checkChainRevocation({\n * chain: validatedChain,\n * crls: [crl1, crl2],\n * ocspResponses: [ocspResponseDer],\n * policy: { mode: 'hard-fail' },\n * });\n * if (result.value.decision === 'deny') {\n * console.log('Revocation check failed');\n * }\n * ```\n */\nexport async function checkChainRevocation(\n\tinput: CheckChainRevocationInput,\n): Promise<CheckChainRevocationResult> {\n\tconst { chain, policy, crls = [], extraCertificates = [], at = new Date() } = input;\n\tconst mode = policy?.mode ?? 'hard-fail';\n\n\t// Empty chain → allow\n\tif (chain.length === 0) {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: {\n\t\t\t\tdecision: 'allow',\n\t\t\t\tsummary: { revokedCertificates: [], indeterminateCertificates: [] },\n\t\t\t\tcertificates: [],\n\t\t\t},\n\t\t};\n\t}\n\n\t// Create signer validation context with memoization cache\n\t// This cache is shared across all certificate checks in this chain evaluation\n\tconst signerCtx: SignerValidationContext = {\n\t\tcache: new Map(),\n\t\tchain,\n\t\tcrls,\n\t\textraCertificates,\n\t\tat,\n\t};\n\n\t// Skip trust anchor (last cert) — it's the trust base\n\tconst certsToCheck = chain.slice(0, -1);\n\tconst certificates: CertificateRevocationStatus[] = [];\n\tconst revokedCertificates: ParsedCertificate[] = [];\n\tconst indeterminateCertificates: ParsedCertificate[] = [];\n\tconst allExecutionErrors: RevocationExecutionError[] = [];\n\n\tfor (let i = 0; i < certsToCheck.length; i++) {\n\t\tconst cert = certsToCheck[i];\n\t\tconst issuer = chain[i + 1]; // Next cert in chain is the issuer\n\t\tif (cert === undefined || issuer === undefined) {\n\t\t\tcontinue; // Should never happen given loop bounds\n\t\t}\n\n\t\tconst { status, executionErrors } = await evaluateCertificateRevocation(\n\t\t\tcert,\n\t\t\tissuer,\n\t\t\tinput,\n\t\t\tsignerCtx,\n\t\t);\n\t\tcertificates.push(status);\n\t\tallExecutionErrors.push(...executionErrors);\n\n\t\tif (status.status === 'revoked') {\n\t\t\trevokedCertificates.push(cert);\n\t\t} else if (status.status === 'indeterminate') {\n\t\t\tindeterminateCertificates.push(cert);\n\t\t}\n\t}\n\n\t// Apply policy\n\tconst hasRevoked = revokedCertificates.length > 0;\n\tconst hasIndeterminate = indeterminateCertificates.length > 0;\n\tconst decision: 'allow' | 'deny' = hasRevoked\n\t\t? 'deny'\n\t\t: hasIndeterminate && mode === 'hard-fail'\n\t\t\t? 'deny'\n\t\t\t: 'allow';\n\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tdecision,\n\t\t\tsummary: { revokedCertificates, indeterminateCertificates },\n\t\t\tcertificates,\n\t\t\t...(allExecutionErrors.length > 0 ? { executionErrors: allExecutionErrors } : {}),\n\t\t},\n\t};\n}\n"],"mappings":"2WA+HA,MAAa,EAAmC,CAE/C,oBACA,qBAEA,8BACA,uBACA,wBACA,8BACA,6BAEA,uBACA,4BACA,qBACA,2BACA,2BACA,gCACA,yBACA,+BAEA,cACA,wBAEA,qBACD,EAsIA,SAAS,EAAmB,EAAoD,CAO/E,OANI,OAAO,GAAW,UAAY,WAAY,EACtC,EAEJ,OAAO,GAAW,SACd,EAAyC,CAAM,EAEhD,EAAyC,CAAM,CACvD,CAKA,SAAS,EAAqB,EAAoE,CACjG,GAAI,CACH,OAAO,EAA2B,CAAM,CACzC,MAAQ,CACP,MACD,CACD,CAMA,SAAS,EAAgB,EAAsB,EAA+B,CAC7E,GAAI,EAAE,IAAI,SAAW,EAAE,IAAI,OAAQ,MAAO,GAC1C,IAAK,IAAI,EAAI,EAAG,EAAI,EAAE,IAAI,OAA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