micro509 0.18.0 → 0.19.1

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.
Files changed (113) hide show
  1. package/CHANGELOG.md +109 -1
  2. package/dist/crypto/crypto.d.ts +11 -2
  3. package/dist/crypto/crypto.js +30 -17
  4. package/dist/crypto/crypto.js.map +1 -1
  5. package/dist/crypto.d.ts +2 -2
  6. package/dist/der/der.js.map +1 -1
  7. package/dist/index.d.ts +7 -6
  8. package/dist/internal/asn1/asn1.js +10 -2
  9. package/dist/internal/asn1/asn1.js.map +1 -1
  10. package/dist/internal/asn1/ber.js.map +1 -1
  11. package/dist/internal/asn1/decode-refusal.js.map +1 -1
  12. package/dist/internal/asn1/der.js.map +1 -1
  13. package/dist/internal/asn1/oids.js.map +1 -1
  14. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  15. package/dist/internal/crypto/ecdsa.js.map +1 -1
  16. package/dist/internal/crypto/hash.js +64 -64
  17. package/dist/internal/crypto/hash.js.map +1 -1
  18. package/dist/internal/crypto/pbes2.js +3 -3
  19. package/dist/internal/crypto/pbes2.js.map +1 -1
  20. package/dist/internal/crypto/prime-ec.js.map +1 -1
  21. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  22. package/dist/internal/crypto/sig-verify.d.ts +40 -0
  23. package/dist/internal/crypto/sig-verify.js +152 -65
  24. package/dist/internal/crypto/sig-verify.js.map +1 -1
  25. package/dist/internal/crypto/signing.js.map +1 -1
  26. package/dist/internal/jose/base64url.js.map +1 -1
  27. package/dist/internal/jose/json-data.js.map +1 -1
  28. package/dist/internal/jose/strict-json.js.map +1 -1
  29. package/dist/internal/shared/base64.js.map +1 -1
  30. package/dist/internal/shared/dn.js +1 -1
  31. package/dist/internal/shared/dn.js.map +1 -1
  32. package/dist/internal/shared/idna-tables.js +3 -3
  33. package/dist/internal/shared/idna.js.map +1 -1
  34. package/dist/internal/shared/ip.js.map +1 -1
  35. package/dist/internal/shared/mailbox.js.map +1 -1
  36. package/dist/internal/shared/punycode.js +1 -1
  37. package/dist/internal/shared/punycode.js.map +1 -1
  38. package/dist/internal/shared/uri-host.js.map +1 -1
  39. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  40. package/dist/internal/verify/policy-engine.js.map +1 -1
  41. package/dist/internal/verify/spki-distrust.js.map +1 -1
  42. package/dist/internal/verify/verify-path.js +222 -116
  43. package/dist/internal/verify/verify-path.js.map +1 -1
  44. package/dist/internal/x509/directory-name.js.map +1 -1
  45. package/dist/internal/x509/extension-bits.js.map +1 -1
  46. package/dist/internal/x509/extension-errors.js.map +1 -1
  47. package/dist/internal/x509/extension-registry.js.map +1 -1
  48. package/dist/internal/x509/general-name-profile.js.map +1 -1
  49. package/dist/internal/x509/general-name.js.map +1 -1
  50. package/dist/internal/x509/name-fields.js.map +1 -1
  51. package/dist/internal/x509/or-address.js.map +1 -1
  52. package/dist/jose/base64url.js.map +1 -1
  53. package/dist/jose/errors.js.map +1 -1
  54. package/dist/jose/jwe.js.map +1 -1
  55. package/dist/jose/jwks.js.map +1 -1
  56. package/dist/jose/jws.js.map +1 -1
  57. package/dist/jose/jwt.js.map +1 -1
  58. package/dist/jose/remote-jwks.js.map +1 -1
  59. package/dist/kdf/argon2-arithmetic.js.map +1 -1
  60. package/dist/kdf/argon2-core.js.map +1 -1
  61. package/dist/kdf/argon2-memory.js.map +1 -1
  62. package/dist/kdf/argon2-portable.js +1 -1
  63. package/dist/kdf/argon2-portable.js.map +1 -1
  64. package/dist/kdf/argon2.js +2 -2
  65. package/dist/kdf/argon2.js.map +1 -1
  66. package/dist/keys/keys.d.ts +7 -2
  67. package/dist/keys/keys.js +10 -6
  68. package/dist/keys/keys.js.map +1 -1
  69. package/dist/pem/pem.d.ts +20 -7
  70. package/dist/pem/pem.js +24 -20
  71. package/dist/pem/pem.js.map +1 -1
  72. package/dist/pem.d.ts +2 -2
  73. package/dist/pkcs/pfx.js.map +1 -1
  74. package/dist/pkcs/pkcs12-mac.js +3 -3
  75. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  76. package/dist/pkcs/pkcs7.d.ts +10 -0
  77. package/dist/pkcs/pkcs7.js +106 -88
  78. package/dist/pkcs/pkcs7.js.map +1 -1
  79. package/dist/result/result.js.map +1 -1
  80. package/dist/revocation/chain.d.ts +67 -13
  81. package/dist/revocation/chain.js +429 -301
  82. package/dist/revocation/chain.js.map +1 -1
  83. package/dist/revocation/crl.d.ts +65 -11
  84. package/dist/revocation/crl.js +472 -182
  85. package/dist/revocation/crl.js.map +1 -1
  86. package/dist/revocation/ocsp.d.ts +79 -24
  87. package/dist/revocation/ocsp.js +417 -231
  88. package/dist/revocation/ocsp.js.map +1 -1
  89. package/dist/revocation/revocation.d.ts +68 -13
  90. package/dist/revocation/revocation.js +194 -73
  91. package/dist/revocation/revocation.js.map +1 -1
  92. package/dist/revocation.d.ts +4 -4
  93. package/dist/ssh/ssh.js.map +1 -1
  94. package/dist/ssh/wire.js.map +1 -1
  95. package/dist/verify/identity.d.ts +2 -2
  96. package/dist/verify/identity.js +2 -2
  97. package/dist/verify/identity.js.map +1 -1
  98. package/dist/verify/verify.d.ts +84 -32
  99. package/dist/verify/verify.js +221 -175
  100. package/dist/verify/verify.js.map +1 -1
  101. package/dist/verify.d.ts +3 -2
  102. package/dist/x509/certificate.js.map +1 -1
  103. package/dist/x509/csr.js.map +1 -1
  104. package/dist/x509/extensions.js +1 -1
  105. package/dist/x509/extensions.js.map +1 -1
  106. package/dist/x509/fingerprint.js.map +1 -1
  107. package/dist/x509/name-text.js +1 -1
  108. package/dist/x509/name-text.js.map +1 -1
  109. package/dist/x509/name.js.map +1 -1
  110. package/dist/x509/parse.d.ts +6 -2
  111. package/dist/x509/parse.js +121 -121
  112. package/dist/x509/parse.js.map +1 -1
  113. package/package.json +16 -16
@@ -1 +1 @@
1
- {"version":3,"file":"pkcs7.js","names":["CONTENT_INFO_PEM_LABELS","certificateDers","certificates","der","error","refusal","decodeRefusalOf","DECODE_REFUSAL_CODES","certificateSet","setOf","signedData","sequence","integerFromNumber","objectIdentifier","OIDS","explicitContext","pemEncode","base64Encode","input","encapsulatedContentTypeOid","content","seenCertificates","hex","toHex","digestAlgorithmOids","signerInfos","signer","built","source","parseCertificateDerOrThrow","signedDataVersion","oid","octetString","signerCertDers","signerCertDer","certificate","signatureAlgorithm","getSignatureAlgorithm","getVerifySignatureConfigResult","digest","getCrypto","toArrayBuffer","signature","signBytes","setForSigning","hexToBytes","integer","implicitForEmit","encodeAlgorithmIdentifier","result","blocks","splitPemBlocksOrThrow","pem","label","block","contentInfo","readSequenceChildren","contentType","childrenOf","contentTypeOid","decodeObjectIdentifier","signedDataChildren","version","digestAlgorithms","encapContentInfo","trailingChildren","optionalFields","encapDer","encapChildren","encapType","encapContent","decodeIntegerNumber","describeHashAlgorithm","crls","child","children","expectedContentTypeOid","signedAttributes","options","readElement","parsedResult","parsed","signers","signerInfo","verificationResult","verifySignedDataDetailed","failureResult","code","message","algorithm","privateKey","messageDigest","choices","choice","formatOid","requireElement","element","digests","childDer","parts","signerDer","sid","digestAlgorithm","index","signedAttrsElement","unauthenticatedAttributes","digestAlgorithmOid","signatureAlgorithmDer","signatureAlgorithmChildren","signatureAlgorithmOid","signatureAlgorithmParams","describeSignatureAlgorithm","algorithmDer","inner","readRootElement","top","issuerElement","serial","derHex","rdns","allAttributes","values","setElement","rdnAttributes","rdnValues","attrSequence","oidElement","valueElement","fieldValue","decodeString","fieldKey","nameFieldKeyFromOid","attribute","offset","parent","currentIndex","outer","signedAttrsDer","fields","attr","attrDer","attrOid","valueElements","existing","value","copy","a","b","diff","actualDigest","hash","verified","identifier","compareDistinguishedNames","first","bytes"],"sources":["../../src/pkcs/pkcs7.ts"],"sourcesContent":["/**\n * PKCS#7/CMS certificate bags and SignedData.\n *\n * Creates degenerate (signature-less) certificate bags, parses RFC 5652\n * SignedData (and the RFC 2315 form whose contentInfo content is an OCTET\n * STRING), and verifies signer signatures including signed-attribute flows.\n * A CertificateSet is decoded as RFC 5652 §10.2.2 CertificateChoices, so an\n * attribute certificate or other-format entry is preserved rather than dropped.\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';\nimport { DECODE_REFUSAL_CODES, decodeRefusalOf } from '#micro509/internal/asn1/decode-refusal';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tinteger,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadRootElement,\n\treadSequenceChildren,\n\tsequence,\n\tsetOf,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport {\n\tdescribeHashAlgorithm,\n\tdescribeSignatureAlgorithm,\n} from '#micro509/internal/crypto/algorithm-names';\nimport {\n\tgetVerifySignatureConfigResult,\n\tverifySignedDataDetailed,\n} from '#micro509/internal/crypto/sig-verify';\nimport type { SignatureAlgorithmIdentifier } from '#micro509/internal/crypto/signing';\nimport {\n\tencodeAlgorithmIdentifier,\n\tgetSignatureAlgorithm,\n\tsignBytes,\n} from '#micro509/internal/crypto/signing';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport { compareDistinguishedNames } from '#micro509/internal/shared/dn';\nimport { pemEncode, splitPemBlocksOrThrow } from '#micro509/pem/pem';\nimport type {\n\tDecodeFailureCode,\n\tDecodeRefusalCode,\n\tErrorResult,\n\tMicro509Error,\n} from '#micro509/result/result';\nimport { failureResult, rethrowIfInvariant } from '#micro509/result/result';\nimport type { SignatureProfileInput } from '#micro509/x509/certificate';\nimport type { NameFieldKey } from '#micro509/x509/name';\nimport { nameFieldKeyFromOid } from '#micro509/x509/name';\nimport type {\n\tParsedCertificate,\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse';\nimport { parseCertificateDerOrThrow } from '#micro509/x509/parse';\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/** RFC 7468 Section 8 armors an RFC 2315 ContentInfo; Section 9 armors an RFC 5652 one. */\nconst CONTENT_INFO_PEM_LABELS = ['PKCS7', 'CMS'] as const;\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/**\n * RFC 5652 §5.3 `SignerIdentifier ::= CHOICE { issuerAndSerialNumber,\n * subjectKeyIdentifier [0] }`, which locates the signer's certificate.\n */\nexport type ParsedSignerIdentifier =\n\t| {\n\t\t\t/** Issuer name plus serial number. */\n\t\t\treadonly type: 'issuerAndSerialNumber';\n\t\t\t/** Parsed issuer distinguished name. */\n\t\t\treadonly issuer: ParsedName;\n\t\t\t/** Hex-encoded certificate serial number. */\n\t\t\treadonly serialNumberHex: string;\n\t }\n\t| {\n\t\t\t/** SubjectKeyIdentifier (`[0]`). */\n\t\t\treadonly type: 'subjectKeyIdentifier';\n\t\t\t/** Hex-encoded SubjectKeyIdentifier of the signer certificate. */\n\t\t\treadonly subjectKeyIdentifier: string;\n\t };\n\n/** Fields shared by every decoded SignerInfo, regardless of signed-attribute presence. */\nexport interface ParsedPkcs7SignerInfoBase {\n\t/** CMS SignerInfo version (typically 1 for issuerAndSerialNumber). */\n\treadonly version: number;\n\t/** Which of the two RFC 5652 §5.3 SignerIdentifier alternatives this SignerInfo uses. */\n\treadonly signerIdentifier: ParsedSignerIdentifier;\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\ninterface ParsedSignedDataOptionalFields {\n\treadonly certificates?: DerElement;\n\treadonly crls?: DerElement;\n}\n\ninterface ParsedSignedAttributeFields {\n\tmessageDigest?: Uint8Array;\n\tcontentTypeOid?: string;\n}\n\n/**\n * One RFC 5652 §10.2.2 CertificateChoices alternative.\n *\n * X.509 is the only alternative this library decodes. The rest keep their DER,\n * including the context tag, so a CertificateSet round-trips and a caller can\n * tell an X.509-only bag from one carrying attribute certificates. RFC 5652\n * marks `extendedCertificate` and `attributeCertificateV1` obsolete.\n */\nexport type ParsedCertificateChoice =\n\t| {\n\t\t\t/** X.509 certificate (untagged `Certificate`). */\n\t\t\treadonly type: 'certificate';\n\t\t\t/** The decoded certificate. */\n\t\t\treadonly certificate: ParsedCertificate;\n\t }\n\t| {\n\t\t\t/** PKCS #6 extended certificate (`[0]`), obsolete. */\n\t\t\treadonly type: 'extendedCertificate';\n\t\t\t/** Raw DER of the element, including its context tag. */\n\t\t\treadonly der: Uint8Array;\n\t }\n\t| {\n\t\t\t/** Version 1 X.509 attribute certificate (`[1]`), obsolete. */\n\t\t\treadonly type: 'attributeCertificateV1';\n\t\t\t/** Raw DER of the element, including its context tag. */\n\t\t\treadonly der: Uint8Array;\n\t }\n\t| {\n\t\t\t/** Version 2 X.509 attribute certificate (`[2]`). */\n\t\t\treadonly type: 'attributeCertificateV2';\n\t\t\t/** Raw DER of the element, including its context tag. */\n\t\t\treadonly der: Uint8Array;\n\t }\n\t| {\n\t\t\t/** Any other certificate format (`[3] OtherCertificateFormat`). */\n\t\t\treadonly type: 'other';\n\t\t\t/** `otherCertFormat` OID identifying the format. */\n\t\t\treadonly formatOid: string;\n\t\t\t/** Raw DER of the element, including its context tag. */\n\t\t\treadonly der: Uint8Array;\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/** RFC 5652 §10.2.2 CertificateChoices entries from the SignedData certificate set. */\n\treadonly certificateChoices: readonly ParsedCertificateChoice[];\n\t/** Decoded signer info entries. Empty for degenerate cert bags. */\n\treadonly signerInfos: readonly ParsedPkcs7SignerInfo[];\n}\n\n// Result types for PKCS#7 parsing\n\n/**\n * Error codes for PKCS#7 parse failures.\n *\n * `unsupported` is a signer issuer name value micro509 does not decode, a\n * TeletexString octet outside the X.690 §8.23.5.2 initial state.\n * `limit_exceeded` is an implementation limit: an OBJECT IDENTIFIER\n * sub-identifier encoded in more than 64 octets, a tag number of 2^53 or more,\n * or DER nested deeper than 64 levels.\n */\nexport type ParsePkcs7ErrorCode = DecodeFailureCode | '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/**\n * Error codes for {@linkcode verifyPkcs7SignedData} failures.\n *\n * `detached_content_required` means the SignedData carries no `eContent`\n * (detached signature or degenerate cert bag) and no external content was\n * supplied via {@linkcode VerifyPkcs7SignedDataOptions}.\n * `no_signers` means the SignedData carries no SignerInfo to verify.\n */\nexport type VerifyPkcs7SignedDataErrorCode =\n\t| 'invalid_options'\n\t| 'content_type_mismatch'\n\t| 'signed_attributes_required'\n\t| 'signed_attributes_forbidden'\n\t| 'no_signers'\n\t| 'signer_not_found'\n\t| 'signature_invalid'\n\t| 'message_digest_mismatch'\n\t| 'detached_content_required'\n\t| ParsePkcs7ErrorCode;\n\n/** Error payload for a failed {@linkcode verifyPkcs7SignedData} call. */\nexport interface VerifyPkcs7SignedDataFailure\n\textends Micro509Error<VerifyPkcs7SignedDataErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Options for {@linkcode verifyPkcs7SignedData}. */\nexport interface VerifyPkcs7SignedDataOptions {\n\t/** Expected eContentType OID. Defaults to id-data (1.2.840.113549.1.7.1). */\n\treadonly expectedContentTypeOid?: string;\n\t/**\n\t * Signed-attribute policy for every signer. Defaults to 'required'.\n\t * 'allowed' accepts either form for id-data; 'forbidden' accepts only bare\n\t * id-data signatures. RFC 5652 §5.3 always requires attributes for other types.\n\t */\n\treadonly signedAttributes?: 'required' | 'allowed' | 'forbidden';\n\t/**\n\t * External content for a detached SignedData (RFC 5652 Section 5.2, absent `eContent`).\n\t * Required to verify a detached signature; ignored when the SignedData embeds its own content.\n\t */\n\treadonly content?: Uint8Array;\n}\n\n/** A SignerInfo paired with the certificate that verified its signature. */\nexport interface VerifiedPkcs7Signer {\n\t/** The SignerInfo whose signature verified. */\n\treadonly signerInfo: ParsedPkcs7SignerInfo;\n\t/** The certificate from the SignedData certificate set that verified it. */\n\treadonly certificate: ParsedCertificate;\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\t\t/** One entry per SignerInfo, in SignedData order. */\n\t\t\treadonly signers: readonly VerifiedPkcs7Signer[];\n\t }\n\t| ErrorResult<VerifyPkcs7SignedDataErrorCode, Record<never, never>, VerifyPkcs7SignedDataFailure>;\n\n// createPkcs7CertBag\n\n/** Caller-correctable failure code from {@linkcode createPkcs7CertBag}. */\nexport type CreatePkcs7CertBagErrorCode = 'invalid_certificate' | DecodeRefusalCode;\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\tfor (const der of certificateDers) {\n\t\t\tparseCertificateDerOrThrow(der);\n\t\t}\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? createCertBagFailure(\n\t\t\t\t\t'invalid_certificate',\n\t\t\t\t\t'Each PKCS#7 certificate source must be valid PEM or DER',\n\t\t\t\t)\n\t\t\t: createCertBagFailure(refusal.code, refusal.message);\n\t}\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(1),\n\t\tsetOf([]),\n\t\tsequence([objectIdentifier(OIDS.pkcs7Data)]),\n\t\tcertificateSet,\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// createPkcs7SignedData\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\t/**\n\t * Omit `eContent` from `encapContentInfo` (RFC 5652 Section 5.2 detached\n\t * form). The signature still covers `content` via the messageDigest signed\n\t * attribute, but the bytes are not embedded — the verifier must supply them\n\t * externally (e.g. git x509 commit signing, S/MIME detached signatures).\n\t * @default false\n\t */\n\treadonly detached?: boolean;\n}\n\n/** DER, PEM, and base64 encodings of a PKCS#7/CMS SignedData structure. */\nexport interface Pkcs7SignedDataMaterial {\n\t/** Raw DER-encoded SignedData ContentInfo. */\n\treadonly der: Uint8Array;\n\t/**\n\t * PEM-armored ContentInfo. A version 1 SignedData carries the `PKCS7`\n\t * label; a version 3 one is outside RFC 2315, whose SignedData version\n\t * \"shall be 1\", so it carries the RFC 7468 Section 9 `CMS` label.\n\t */\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| 'invalid_certificate'\n\t| 'signer_certificate_key_mismatch'\n\t| 'unsupported_signer_key'\n\t| DecodeRefusalCode;\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). By default the\n * content is embedded (attached signature), so the result verifies with\n * {@linkcode verifyPkcs7SignedData} without any external data. With\n * `detached: true` the `eContent` is omitted (RFC 5652 Section 5.2) and the\n * verifier must supply the content externally.\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, a signer\n * certificate whose public key cannot verify the signer key's algorithm, 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 built = await buildPkcs7SignerInfo(signer, content, encapsulatedContentTypeOid);\n\t\tif (!built.ok) return built;\n\t\taddCertificate(built.certificateDer);\n\t\tdigestAlgorithmOids.add(built.digestOid);\n\t\tsignerInfos.push(built.signerInfoDer);\n\t}\n\n\tfor (const source of input.additionalCertificates ?? []) {\n\t\ttry {\n\t\t\tfor (const der of normalizeCertificateSource(source)) {\n\t\t\t\tparseCertificateDerOrThrow(der);\n\t\t\t\taddCertificate(der);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\t\treturn refusal === undefined\n\t\t\t\t? createPkcs7Failure(\n\t\t\t\t\t\t'invalid_certificate',\n\t\t\t\t\t\t'Each additional PKCS#7 certificate source must be valid PEM or DER',\n\t\t\t\t\t)\n\t\t\t\t: createPkcs7Failure(refusal.code, refusal.message);\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)]))),\n\t\tinput.detached === true\n\t\t\t? sequence([objectIdentifier(encapsulatedContentTypeOid)])\n\t\t\t: sequence([\n\t\t\t\t\tobjectIdentifier(encapsulatedContentTypeOid),\n\t\t\t\t\texplicitContext(0, octetString(content)),\n\t\t\t\t]),\n\t\tcertificateSet,\n\t\tsetOf(signerInfos),\n\t]);\n\tconst der = sequence([objectIdentifier(OIDS.pkcs7SignedData), explicitContext(0, signedData)]);\n\t// RFC 7468 Section 8 requires PKCS7-labelled data to be an RFC 2315\n\t// ContentInfo, whose SignedData version \"shall be 1\"; version 3 is described\n\t// only by RFC 5652, which Section 9 armors as CMS.\n\tconst label = signedDataVersion === 1 ? 'PKCS7' : 'CMS';\n\treturn {\n\t\tok: true,\n\t\tvalue: { der, pem: pemEncode(label, der), base64: base64Encode(der) },\n\t};\n}\n\n/** One built SignerInfo plus what the SignedData envelope needs from it. */\ntype Pkcs7SignerInfoBuild =\n\t| {\n\t\t\t/** Build succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** DER-encoded SignerInfo. */\n\t\t\treadonly signerInfoDer: Uint8Array;\n\t\t\t/** Digest algorithm OID for the digestAlgorithms SET. */\n\t\t\treadonly digestOid: string;\n\t\t\t/** Signer certificate DER for the certificate set. */\n\t\t\treadonly certificateDer: Uint8Array;\n\t }\n\t| ErrorResult<CreatePkcs7SignedDataErrorCode, Record<never, never>, CreatePkcs7SignedDataFailure>;\n\n/**\n * Builds one signer's SignerInfo over `content` (RFC 5652 Section 5.4\n * signed-attributes flow). Every throwing step here reacts to\n * caller-correctable input — malformed PEM/DER, unsupported key — so each is\n * mapped to a typed failure rather than rejecting the public Promise.\n */\nasync function buildPkcs7SignerInfo(\n\tsigner: Pkcs7Signer,\n\tcontent: Uint8Array,\n\tencapsulatedContentTypeOid: string,\n): Promise<Pkcs7SignerInfoBuild> {\n\t// normalizeCertificateSource throws on malformed PEM (stray or truncated markers).\n\tlet signerCertDers: readonly Uint8Array[];\n\ttry {\n\t\tsignerCertDers = normalizeCertificateSource(signer.certificate);\n\t} catch {\n\t\treturn createPkcs7Failure(\n\t\t\t'invalid_signer_certificate',\n\t\t\t'Each PKCS#7 signer certificate source must be valid PEM or DER',\n\t\t);\n\t}\n\tconst signerCertDer = signerCertDers[0];\n\tif (signerCertDer === undefined || signerCertDers.length !== 1) {\n\t\treturn createPkcs7Failure(\n\t\t\t'invalid_signer_certificate',\n\t\t\t'Each PKCS#7 signer must provide exactly one certificate',\n\t\t);\n\t}\n\tlet certificate: ParsedCertificate;\n\ttry {\n\t\tcertificate = parseCertificateDerOrThrow(signerCertDer);\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? createPkcs7Failure(\n\t\t\t\t\t'invalid_signer_certificate',\n\t\t\t\t\t'Each PKCS#7 signer certificate must be a parseable X.509 certificate',\n\t\t\t\t)\n\t\t\t: createPkcs7Failure(refusal.code, refusal.message);\n\t}\n\t// getSignatureAlgorithm throws only for unsupported/misconfigured keys.\n\tlet signatureAlgorithm: SignatureAlgorithmIdentifier;\n\ttry {\n\t\tsignatureAlgorithm = getSignatureAlgorithm(signer.privateKey, signer.signature);\n\t} catch {\n\t\treturn createPkcs7Failure(\n\t\t\t'unsupported_signer_key',\n\t\t\t'Unsupported signer key or signature profile',\n\t\t);\n\t}\n\t// RFC 8410 §12: \"the same public key cannot be used for both ECDH and EdDSA\",\n\t// so a SignerInfo must not name a certificate whose subject public key cannot\n\t// verify the algorithm the signer key produces.\n\tif (\n\t\t!getVerifySignatureConfigResult(\n\t\t\tsignatureAlgorithm.algorithmOid,\n\t\t\tsignatureAlgorithm.parameters,\n\t\t\tcertificate.publicKeyAlgorithmOid,\n\t\t\tcertificate.publicKeyParametersOid,\n\t\t\t'signer',\n\t\t).ok\n\t) {\n\t\treturn createPkcs7Failure(\n\t\t\t'signer_certificate_key_mismatch',\n\t\t\t'Each PKCS#7 signer certificate must carry a public key that verifies the signer key algorithm',\n\t\t);\n\t}\n\tconst digest = contentDigestForPrivateKey(signer.privateKey);\n\tif (digest === undefined) {\n\t\treturn createPkcs7Failure(\n\t\t\t'unsupported_signer_key',\n\t\t\t'Unsupported signer key algorithm for content digest',\n\t\t);\n\t}\n\tconst messageDigest = new Uint8Array(\n\t\tawait getCrypto().subtle.digest(digest.hashName, toArrayBuffer(content)),\n\t);\n\tconst { setForSigning, implicitForEmit } = buildSignedAttributes(\n\t\tencapsulatedContentTypeOid,\n\t\tmessageDigest,\n\t);\n\tlet signature: Uint8Array;\n\ttry {\n\t\tsignature = await signBytes(signer.privateKey, signatureAlgorithm, setForSigning);\n\t} catch {\n\t\treturn createPkcs7Failure(\n\t\t\t'unsupported_signer_key',\n\t\t\t'Signer key could not produce a PKCS#7 signature',\n\t\t);\n\t}\n\treturn {\n\t\tok: true,\n\t\tsignerInfoDer: sequence([\n\t\t\tintegerFromNumber(1),\n\t\t\tsequence([\n\t\t\t\thexToBytes(certificate.issuer.derHex),\n\t\t\t\tinteger(hexToBytes(certificate.serialNumberHex)),\n\t\t\t]),\n\t\t\tsequence([objectIdentifier(digest.digestOid)]),\n\t\t\timplicitForEmit,\n\t\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\t\toctetString(signature),\n\t\t]),\n\t\tdigestOid: digest.digestOid,\n\t\tcertificateDer: signerCertDer,\n\t};\n}\n\n// parsePkcs7CertBag — Result-returning\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: x509CertificatesOf(result.value.certificateChoices) };\n}\n\n/** The DER of the single `PKCS7` or `CMS` block in `pem`, or a typed failure. */\nfunction contentInfoPemBytes(\n\tpem: string,\n):\n\t| { readonly ok: true; readonly bytes: Uint8Array }\n\t| ErrorResult<ParsePkcs7ErrorCode, Record<never, never>, ParsePkcs7Failure> {\n\ttry {\n\t\tconst blocks = splitPemBlocksOrThrow(pem).filter((block) =>\n\t\t\tCONTENT_INFO_PEM_LABELS.some((label) => label === block.label),\n\t\t);\n\t\tconst block = blocks[0];\n\t\tif (block === undefined || blocks.length !== 1) {\n\t\t\treturn pkcs7Failure('malformed', 'Expected exactly one PKCS7 or CMS PEM block');\n\t\t}\n\t\treturn { ok: true, bytes: block.bytes };\n\t} catch {\n\t\treturn pkcs7Failure('malformed', 'Expected exactly one PKCS7 or CMS PEM block');\n\t}\n}\n\n/** Parses a PEM-armored PKCS#7/CMS cert bag. Expects exactly one `PKCS7` or `CMS` PEM block. */\nexport function parsePkcs7CertBagPem(pem: string): ParsePkcs7CertBagResult {\n\tconst block = contentInfoPemBytes(pem);\n\tif (!block.ok) return block;\n\treturn parsePkcs7CertBagDer(block.bytes);\n}\n\n// parsePkcs7SignedData — Result-returning\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 (contentType === undefined || contentInfo.length > 2 || contentType.tag !== 0x06) {\n\t\t\treturn pkcs7Failure('malformed', 'Malformed PKCS#7 content info');\n\t\t}\n\t\tif (content !== undefined && (content.tag !== 0xa0 || 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\tif (content === undefined) {\n\t\t\treturn pkcs7Failure('malformed', 'PKCS#7 signedData content info carries no content');\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\tconst optionalFields = parseSignedDataOptionalFields(trailingChildren.slice(0, -1));\n\t\tif (!optionalFields.ok) return optionalFields;\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 || encapChildren.length > 2 || encapType.tag !== 0x06) {\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\tcertificateChoices: parseCertificateSet(der, optionalFields.value.certificates),\n\t\t\t\tsignerInfos: parseSignerInfos(der, signerInfos),\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? pkcs7Failure('malformed', 'Malformed PKCS#7 structure')\n\t\t\t: pkcs7Failure(refusal.code, refusal.message);\n\t}\n}\n\nfunction parseSignedDataOptionalFields(\n\tchildren: readonly DerElement[],\n):\n\t| { readonly ok: true; readonly value: ParsedSignedDataOptionalFields }\n\t| ErrorResult<ParsePkcs7ErrorCode, Record<never, never>, ParsePkcs7Failure> {\n\tlet certificates: DerElement | undefined;\n\tlet crls: DerElement | undefined;\n\tfor (const child of children) {\n\t\tif (child.tag === 0xa0) {\n\t\t\tif (crls !== undefined)\n\t\t\t\treturn pkcs7Failure('malformed', 'SignedData certificates field must precede CRLs field');\n\t\t\tif (certificates !== undefined)\n\t\t\t\treturn pkcs7Failure('malformed', 'SignedData certificates field must not repeat');\n\t\t\tcertificates = child;\n\t\t\tcontinue;\n\t\t}\n\t\tif (child.tag === 0xa1) {\n\t\t\tif (crls !== undefined)\n\t\t\t\treturn pkcs7Failure('malformed', 'SignedData CRLs field must not repeat');\n\t\t\tcrls = child;\n\t\t\tcontinue;\n\t\t}\n\t\treturn pkcs7Failure('malformed', 'Malformed SignedData optional field');\n\t}\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\t...(certificates === undefined ? {} : { certificates }),\n\t\t\t...(crls === undefined ? {} : { crls }),\n\t\t},\n\t};\n}\n\n/** Decodes a PEM-armored PKCS#7/CMS SignedData. Expects exactly one `PKCS7` or `CMS` PEM block. */\nexport function parsePkcs7SignedDataPem(pem: string): ParsePkcs7SignedDataResult {\n\tconst block = contentInfoPemBytes(pem);\n\tif (!block.ok) return block;\n\treturn parsePkcs7SignedDataDer(block.bytes);\n}\n\n// verifyPkcs7SignedData\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 * Defaults to id-data and requires signed attributes on every signer. Select\n * `expectedContentTypeOid` from the application's protocol, not the input envelope.\n * Legacy bare id-data signatures require `signedAttributes: 'allowed'` or 'forbidden'.\n * Non-id-data always requires attributes (RFC 5652 §5.3).\n *\n * For a detached SignedData (absent `eContent`), pass the externally-held\n * content via `options.content`; without it, verification fails with the\n * typed `detached_content_required` code. When the SignedData embeds its own\n * content, that embedded content is verified and `options.content` is ignored.\n *\n * @example\n * ```ts\n * import { verifyPkcs7SignedData } from 'micro509';\n *\n * const result = await verifyPkcs7SignedData(pkcs7Pem);\n * if (result.ok) {\n * for (const { signerInfo, certificate } of result.signers) {\n * console.log(signerInfo.digestAlgorithmOid, certificate.subject);\n * }\n * }\n *\n * // Detached signature: supply the content externally\n * const detached = await verifyPkcs7SignedData(cmsBlob, { content: signedBytes });\n * ```\n */\nexport async function verifyPkcs7SignedData(\n\tinput: string | Uint8Array | ParsedPkcs7SignedData,\n\toptions: VerifyPkcs7SignedDataOptions = {},\n): Promise<VerifyPkcs7SignedDataResult> {\n\t// Snapshot application policy before asynchronous signature verification.\n\tlet expectedContentTypeOid: string;\n\tconst signedAttributes = options.signedAttributes ?? 'required';\n\tif (!['required', 'allowed', 'forbidden'].includes(signedAttributes)) {\n\t\treturn verifyPkcs7Failure('invalid_options', 'Unknown signed-attribute policy');\n\t}\n\ttry {\n\t\texpectedContentTypeOid = decodeObjectIdentifier(\n\t\t\treadElement(objectIdentifier(options.expectedContentTypeOid ?? OIDS.pkcs7Data)).value,\n\t\t);\n\t} catch {\n\t\treturn verifyPkcs7Failure('invalid_options', 'Expected content type must be an OID');\n\t}\n\tconst parsedResult = normalizePkcs7SignedDataForVerification(input);\n\tif (!parsedResult.ok) return parsedResult;\n\tconst parsed = parsedResult.value;\n\t// Snapshot caller-owned external content before any await so every signer\n\t// verifies against the same bytes (mirrors the create-side content copy).\n\tconst content = parsed.encapsulatedContent ?? options.content?.slice();\n\tif (content === undefined) {\n\t\treturn verifyPkcs7Failure(\n\t\t\t'detached_content_required',\n\t\t\t'SignedData has no encapsulated content; supply the detached content via options.content',\n\t\t);\n\t}\n\tif (parsed.signerInfos.length === 0) {\n\t\treturn verifyPkcs7Failure('no_signers', 'SignedData contains no signer information');\n\t}\n\tif (parsed.encapsulatedContentTypeOid !== expectedContentTypeOid) {\n\t\treturn verifyPkcs7Failure('content_type_mismatch', 'Unexpected SignedData content type');\n\t}\n\tfor (const signer of parsed.signerInfos) {\n\t\tif (\n\t\t\t!signer.hasSignedAttrs &&\n\t\t\t(signedAttributes === 'required' || parsed.encapsulatedContentTypeOid !== OIDS.pkcs7Data)\n\t\t) {\n\t\t\treturn verifyPkcs7Failure('signed_attributes_required', 'Signed attributes are required');\n\t\t}\n\t\tif (signer.hasSignedAttrs && signedAttributes === 'forbidden') {\n\t\t\treturn verifyPkcs7Failure('signed_attributes_forbidden', 'Signed attributes are forbidden');\n\t\t}\n\t}\n\tconst signers: VerifiedPkcs7Signer[] = [];\n\tfor (const signerInfo of parsed.signerInfos) {\n\t\tconst result = await verifyPkcs7SignerInfo(parsed, signerInfo, content);\n\t\tif (!result.ok) return result;\n\t\tsigners.push({ signerInfo, certificate: result.certificate });\n\t}\n\treturn { ok: true, value: parsed, signers };\n}\n\n/** Normalizes encoded or parsed SignedData into a freshly parsed verification input. */\nfunction normalizePkcs7SignedDataForVerification(\n\tinput: string | Uint8Array | ParsedPkcs7SignedData,\n): ParsePkcs7SignedDataResult | VerifyPkcs7SignedDataResult {\n\tif (typeof input === 'string') return parsePkcs7SignedDataPem(input);\n\tif (input instanceof Uint8Array) return parsePkcs7SignedDataDer(input);\n\tif (!hasReparseablePkcs7SignedData(input)) {\n\t\treturn verifyPkcs7Failure('malformed', 'SignedData parsed input is malformed');\n\t}\n\treturn parsePkcs7SignedDataDer(new Uint8Array(input.der));\n}\n\n/** Resolves and verifies one signer entry in a parsed PKCS#7 SignedData value. */\nasync function verifyPkcs7SignerInfo(\n\tparsed: ParsedPkcs7SignedData,\n\tsignerInfo: ParsedPkcs7SignerInfo,\n\tcontent: Uint8Array,\n): Promise<\n\t| { readonly ok: true; readonly certificate: ParsedCertificate }\n\t| Extract<VerifyPkcs7SignedDataResult, { readonly ok: false }>\n> {\n\tconst signer = x509CertificatesOf(parsed.certificateChoices).find((certificate) =>\n\t\tsignerIdentifierMatches(certificate, signerInfo),\n\t);\n\tif (signer === undefined) {\n\t\treturn verifyPkcs7Failure(\n\t\t\t'signer_not_found',\n\t\t\t'Signer certificate not found in SignedData certificates',\n\t\t);\n\t}\n\tconst result = signerInfo.hasSignedAttrs\n\t\t? await verifySignedAttrs(signerInfo, signer, content, parsed.encapsulatedContentTypeOid)\n\t\t: await verifyPkcs7BareSignerInfo(signerInfo, signer, content);\n\treturn result.ok ? { ok: true, certificate: signer } : result;\n}\n\nasync function verifyPkcs7BareSignerInfo(\n\tsignerInfo: ParsedPkcs7SignerInfo,\n\tsigner: ParsedCertificate,\n\tcontent: Uint8Array,\n): Promise<{ readonly ok: true } | Extract<VerifyPkcs7SignedDataResult, { readonly ok: false }>> {\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\tcontent,\n\t\t);\n\t\tif (!verificationResult.ok) {\n\t\t\treturn verificationResult.code === 'verification_error'\n\t\t\t\t? verifyPkcs7Failure('malformed', 'SignedData signature verification failed')\n\t\t\t\t: verifyPkcs7Failure('malformed', 'Unsupported signature algorithm in SignedData');\n\t\t}\n\t\treturn verificationResult.valid\n\t\t\t? { ok: true }\n\t\t\t: verifyPkcs7Failure('signature_invalid', 'SignedData signature does not verify');\n\t} catch (error) {\n\t\treturn signatureVerificationThrowFailure(error);\n\t}\n}\n\n// Private helpers\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. */\n/** A signer's signature verification that threw: its decode refusal, else `malformed`. */\nfunction signatureVerificationThrowFailure(\n\terror: unknown,\n): ErrorResult<VerifyPkcs7SignedDataErrorCode, Record<never, never>, VerifyPkcs7SignedDataFailure> {\n\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\treturn refusal === undefined\n\t\t? verifyPkcs7Failure('malformed', 'Unsupported signature algorithm in SignedData')\n\t\t: verifyPkcs7Failure(refusal.code, refusal.message);\n}\n\nfunction verifyPkcs7Failure(\n\tcode: VerifyPkcs7SignedDataErrorCode,\n\tmessage: string,\n): ErrorResult<VerifyPkcs7SignedDataErrorCode, Record<never, never>, VerifyPkcs7SignedDataFailure> {\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\tconst blocks = splitPemBlocksOrThrow(source)\n\t\t\t.filter((block) => block.label === 'CERTIFICATE')\n\t\t\t.map((block) => new Uint8Array(block.bytes));\n\t\tif (blocks.length === 0) {\n\t\t\tthrow new Error('Certificate PEM required');\n\t\t}\n\t\treturn blocks;\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 * ECDSA curve pairing follows RFC 5753 §8: P-256 → SHA-256, P-384 → SHA-384,\n * P-521 → SHA-512. RSA uses the hash bound to the key.\n * Digest OIDs are from RFC 5754 §2.\n * Ed25519 uses 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/** The X.509 subset of a decoded CertificateSet. */\nfunction x509CertificatesOf(\n\tchoices: readonly ParsedCertificateChoice[],\n): readonly ParsedCertificate[] {\n\treturn choices.flatMap((choice) => (choice.type === 'certificate' ? [choice.certificate] : []));\n}\n\n/**\n * `otherCertFormat` from an `other [3] IMPLICIT OtherCertificateFormat` entry.\n *\n * The IMPLICIT tag replaces the SEQUENCE tag, so the OID and the `ANY DEFINED BY`\n * value are direct children of the `[3]` element.\n */\nfunction parseOtherCertificateFormatOid(source: Uint8Array, element: DerElement): string {\n\tconst formatOid = requireElement(childrenOf(source, element)[0], 'otherCertFormat');\n\tif (formatOid.tag !== 0x06) {\n\t\tthrow new Error('otherCertFormat must be an OBJECT IDENTIFIER');\n\t}\n\treturn decodeObjectIdentifier(formatOid.value);\n}\n\n/** Decodes one RFC 5652 §10.2.2 CertificateChoices alternative. */\nfunction parseCertificateChoice(\n\tsource: Uint8Array,\n\telement: DerElement,\n\tder: Uint8Array,\n): ParsedCertificateChoice {\n\tswitch (element.tag) {\n\t\tcase 0x30:\n\t\t\treturn { type: 'certificate', certificate: parseCertificateDerOrThrow(der) };\n\t\tcase 0xa0:\n\t\t\treturn { type: 'extendedCertificate', der };\n\t\tcase 0xa1:\n\t\t\treturn { type: 'attributeCertificateV1', der };\n\t\tcase 0xa2:\n\t\t\treturn { type: 'attributeCertificateV2', der };\n\t\tcase 0xa3:\n\t\t\treturn {\n\t\t\t\ttype: 'other',\n\t\t\t\tformatOid: parseOtherCertificateFormatOid(source, element),\n\t\t\t\tder,\n\t\t\t};\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported CertificateChoices tag: ${element.tag}`);\n\t}\n}\n\n/**\n * Parses the IMPLICIT [0] certificate set from a SignedData structure as\n * RFC 5652 §10.2.3 `CertificateSet ::= SET OF CertificateChoices`.\n */\nfunction parseCertificateSet(\n\tsource: Uint8Array,\n\tcertificates: ReturnType<typeof readElement> | undefined,\n): readonly ParsedCertificateChoice[] {\n\tif (certificates === undefined || certificates.tag !== 0xa0) {\n\t\treturn [];\n\t}\n\treturn childrenOf(source, certificates).map((element) =>\n\t\tparseCertificateChoice(\n\t\t\tsource,\n\t\t\telement,\n\t\t\tsource.slice(element.start - element.headerLength, element.end),\n\t\t),\n\t);\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\treturn childrenOf(source, element).map((signerInfo) => parseSignerInfo(source, signerInfo));\n}\n\nfunction parseSignerInfo(source: Uint8Array, signerInfo: DerElement): ParsedPkcs7SignerInfo {\n\tconst signerDer = source.slice(signerInfo.start - signerInfo.headerLength, signerInfo.end);\n\tconst parts = readSequenceChildren(signerDer);\n\tconst version = parts[0];\n\tconst sid = parts[1];\n\tconst digestAlgorithm = parts[2];\n\tlet index = 3;\n\tconst signedAttrsElement = parts[index]?.tag === 0xa0 ? parts[index] : undefined;\n\tif (signedAttrsElement !== undefined) index += 1;\n\tconst signatureAlgorithm = parts[index];\n\tconst signature = parts[index + 1];\n\tconst unauthenticatedAttributes = parts[index + 2];\n\tif (\n\t\tversion === undefined ||\n\t\tsid === undefined ||\n\t\tdigestAlgorithm === undefined ||\n\t\tsignatureAlgorithm === undefined ||\n\t\tsignature === undefined ||\n\t\tsignature.tag !== 0x04 ||\n\t\tparts.length > index + 3 ||\n\t\t(unauthenticatedAttributes !== undefined && unauthenticatedAttributes.tag !== 0xa1)\n\t) {\n\t\tthrow new Error('Malformed SignerInfo');\n\t}\n\tconst digestAlgorithmOid = parsePkcs7AlgorithmOid(\n\t\tsignerDer,\n\t\tdigestAlgorithm,\n\t\t'digest algorithm OID',\n\t);\n\tconst signatureAlgorithmDer = signerDer.slice(\n\t\tsignatureAlgorithm.start - signatureAlgorithm.headerLength,\n\t\tsignatureAlgorithm.end,\n\t);\n\tconst signatureAlgorithmChildren = readSequenceChildren(signatureAlgorithmDer);\n\tconst signatureAlgorithmOid = decodeObjectIdentifier(\n\t\trequireElement(signatureAlgorithmChildren[0], 'signature algorithm OID').value,\n\t);\n\tconst signatureAlgorithmParams = signatureAlgorithmChildren[1];\n\treturn {\n\t\tversion: decodeIntegerNumber(version.value),\n\t\tsignerIdentifier: parseSignerIdentifier(signerDer.slice(sid.start - sid.headerLength, sid.end)),\n\t\tdigestAlgorithmOid,\n\t\tdigestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),\n\t\tsignatureAlgorithmOid,\n\t\tsignatureAlgorithmName: describeSignatureAlgorithm(\n\t\t\tsignatureAlgorithmOid,\n\t\t\tsignatureAlgorithmParams === undefined\n\t\t\t\t? undefined\n\t\t\t\t: new Uint8Array(\n\t\t\t\t\t\tsignatureAlgorithmDer.slice(\n\t\t\t\t\t\t\tsignatureAlgorithmParams.start - signatureAlgorithmParams.headerLength,\n\t\t\t\t\t\t\tsignatureAlgorithmParams.end,\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t),\n\t\t...(signatureAlgorithmParams === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tsignatureAlgorithmParametersDer: new Uint8Array(\n\t\t\t\t\t\tsignatureAlgorithmDer.slice(\n\t\t\t\t\t\t\tsignatureAlgorithmParams.start - signatureAlgorithmParams.headerLength,\n\t\t\t\t\t\t\tsignatureAlgorithmParams.end,\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\tsignatureHex: toHex(signature.value),\n\t\tsignature: new Uint8Array(signature.value),\n\t\t...(signedAttrsElement === undefined\n\t\t\t? { hasSignedAttrs: false as const }\n\t\t\t: {\n\t\t\t\t\thasSignedAttrs: true as const,\n\t\t\t\t\tsignedAttrsDer: new Uint8Array(\n\t\t\t\t\t\tsignerDer.slice(\n\t\t\t\t\t\t\tsignedAttrsElement.start - signedAttrsElement.headerLength,\n\t\t\t\t\t\t\tsignedAttrsElement.end,\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t};\n}\n\nfunction parsePkcs7AlgorithmOid(source: Uint8Array, element: DerElement, label: string): string {\n\tconst algorithmDer = source.slice(element.start - element.headerLength, element.end);\n\treturn decodeObjectIdentifier(requireElement(readSequenceChildren(algorithmDer)[0], label).value);\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\tif (inner.end !== element.end) {\n\t\tthrow new Error('Encapsulated content must hold exactly one element');\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): ParsedSignerIdentifier {\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\ttype: 'subjectKeyIdentifier',\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\ttype: 'issuerAndSerialNumber',\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\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\tconst fieldValue = decodeString(valueElement.tag, valueElement.value);\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// CMS signed attributes verification (RFC 5652 Section 5.4)\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\tconst fields: ParsedSignedAttributeFields = {};\n\tfor (const attr of childrenOf(signedAttrsDer, outer)) {\n\t\tparseSignedAttributeRequirement(signedAttrsDer, attr, fields);\n\t}\n\tif (fields.messageDigest === undefined) {\n\t\tthrow new Error('Missing messageDigest attribute in signedAttrs');\n\t}\n\tif (fields.contentTypeOid === undefined) {\n\t\tthrow new Error('Missing contentType attribute in signedAttrs');\n\t}\n\treturn { messageDigest: fields.messageDigest, contentTypeOid: fields.contentTypeOid };\n}\n\nfunction parseSignedAttributeRequirement(\n\tsignedAttrsDer: Uint8Array,\n\tattr: DerElement,\n\tfields: ParsedSignedAttributeFields,\n): void {\n\tconst attrDer = signedAttrsDer.slice(attr.start - attr.headerLength, attr.end);\n\tconst parts = readSequenceChildren(attrDer);\n\tconst oid = parts[0];\n\tconst values = parts[1];\n\tif (oid === undefined || values === undefined || parts.length !== 2 || values.tag !== 0x31) {\n\t\tthrow new Error('Malformed signedAttrs attribute');\n\t}\n\tconst attrOid = decodeObjectIdentifier(oid.value);\n\tconst valueElements = childrenOf(attrDer, values);\n\tif (attrOid === OIDS.cmsMessageDigest) {\n\t\tfields.messageDigest = parseUniqueSignedAttributeOctetString(\n\t\t\tfields.messageDigest,\n\t\t\tvalueElements,\n\t\t\t'messageDigest',\n\t\t);\n\t}\n\tif (attrOid === OIDS.cmsContentType) {\n\t\tfields.contentTypeOid = parseUniqueSignedAttributeOid(\n\t\t\tfields.contentTypeOid,\n\t\t\tvalueElements,\n\t\t\t'contentType',\n\t\t);\n\t}\n}\n\nfunction parseUniqueSignedAttributeOctetString(\n\texisting: Uint8Array | undefined,\n\tvalueElements: readonly DerElement[],\n\tlabel: string,\n): Uint8Array {\n\tif (existing !== undefined || valueElements.length !== 1) {\n\t\tthrow new Error(`${label} attribute must appear exactly once with one value`);\n\t}\n\tconst value = requireElement(valueElements[0], `${label} attribute value`);\n\tif (value.tag !== 0x04) {\n\t\tthrow new Error(`${label} attribute value must use OCTET STRING`);\n\t}\n\treturn value.value;\n}\n\nfunction parseUniqueSignedAttributeOid(\n\texisting: string | undefined,\n\tvalueElements: readonly DerElement[],\n\tlabel: string,\n): string {\n\tif (existing !== undefined || valueElements.length !== 1) {\n\t\tthrow new Error(`${label} attribute must appear exactly once with one value`);\n\t}\n\tconst value = requireElement(valueElements[0], `${label} attribute value`);\n\tif (value.tag !== 0x06) {\n\t\tthrow new Error(`${label} attribute value must use OBJECT IDENTIFIER`);\n\t}\n\treturn decodeObjectIdentifier(value.value);\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\tcontent: Uint8Array,\n\tencapsulatedContentTypeOid: string,\n): Promise<\n\t| { readonly ok: true }\n\t| ErrorResult<VerifyPkcs7SignedDataErrorCode, Record<never, never>, VerifyPkcs7SignedDataFailure>\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 (error) {\n\t\trethrowIfInvariant(error);\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? verifyPkcs7Failure('malformed', 'Malformed signedAttrs in SignedData')\n\t\t\t: verifyPkcs7Failure(refusal.code, refusal.message);\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 the content (embedded, or external for detached)\n\tlet actualDigest: Uint8Array;\n\ttry {\n\t\tconst hash = digestAlgorithmHash(signerInfo.digestAlgorithmOid);\n\t\tactualDigest = new Uint8Array(await getCrypto().subtle.digest(hash, toArrayBuffer(content)));\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 (error) {\n\t\treturn signatureVerificationThrowFailure(error);\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\tconst identifier = signerInfo.signerIdentifier;\n\tif (identifier.type === 'issuerAndSerialNumber') {\n\t\treturn (\n\t\t\tcertificate.serialNumberHex === identifier.serialNumberHex &&\n\t\t\tcompareDistinguishedNames(certificate.issuer, identifier.issuer)\n\t\t);\n\t}\n\treturn certificate.subjectKeyIdentifier === identifier.subjectKeyIdentifier;\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA,MAAMA,IAA0B,CAAC,SAAS,KAAK;;;;;;;AAsR/C,SAAgB,mBACf,GAC2B;CAG3B,IAAIC;CACJ,IAAI;EACH,IAAkBC,EAAa,QAAQ,0BAA0B;EACjE,KAAK,IAAMC,KAAOF,GACjB,EAA2B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,EAAM;CACpB,IAAID,MAAU,KAAA,GACb,MAAU,MAAM,GAAGrG,EAAM,mBAAmB;CAE7C,IAAKqG,IAAQ,KACZ,MAAU,MAAM,GAAGrG,EAAM,sBAAsB;CAEhD,IAAIsG,EAAM,SAAS,KAAKD,MAAU,KAAA,GAAOC,EAAM,MAAM,KAAK,MACzD,MAAU,MAAM,GAAGtG,EAAM,2BAA2B;AAEtD"}
1
+ {"version":3,"file":"pkcs7.js","names":["childrenOf","decodeIntegerNumber","decodeObjectIdentifier","decodeString","hexToBytes","requireElement","toArrayBuffer","toHex","decodeRefusalOf","explicitContext","integer","integerFromNumber","objectIdentifier","octetString","readElement","readRootElement","readSequenceChildren","sequence","setOf","OIDS","describeHashAlgorithm","describeSignatureAlgorithm","callerVerification","getVerifySignatureConfigResult","verifySignedDataDetailed","encodeAlgorithmIdentifier","getSignatureAlgorithm","signBytes","getCrypto","base64Encode","compareDistinguishedNames","pemEncode","splitPemBlocksOrThrow","DECODE_REFUSAL_CODES","failureResult","rethrowIfInvariant","nameFieldKeyFromOid","parseCertificateDerOrThrow","CONTENT_INFO_PEM_LABELS","certificates","certificateDers","der","error","refusal","certificateSet","signedData","input","encapsulatedContentTypeOid","content","seenCertificates","hex","digestAlgorithmOids","signerInfos","signer","built","source","signedDataVersion","oid","signerCertDers","signerCertDer","certificate","signatureAlgorithm","digest","setForSigning","implicitForEmit","signature","result","pem","blocks","block","label","contentInfo","contentType","contentTypeOid","signedDataChildren","version","digestAlgorithms","encapContentInfo","trailingChildren","optionalFields","encapDer","encapChildren","encapType","encapContent","children","crls","child","options","policy","expectedContentTypeOid","signedAttributes","verification","parsedResult","parsed","signers","signerInfo","verificationResult","code","message","algorithm","privateKey","messageDigest","choices","choice","element","formatOid","digests","childDer","parts","signerDer","sid","digestAlgorithm","index","signedAttrsElement","unauthenticatedAttributes","digestAlgorithmOid","signatureAlgorithmDer","signatureAlgorithmChildren","signatureAlgorithmOid","signatureAlgorithmParams","algorithmDer","inner","top","issuerElement","serial","derHex","rdns","allAttributes","values","setElement","rdnAttributes","rdnValues","attrSequence","oidElement","valueElement","fieldValue","fieldKey","attribute","parent","offset","currentIndex","signedAttrsDer","outer","fields","attr","attrDer","attrOid","valueElements","existing","value","copy","a","b","diff","actualDigest","hash","verified","identifier","bytes","first"],"sources":["../../src/pkcs/pkcs7.ts"],"sourcesContent":["/**\n * PKCS#7/CMS certificate bags and SignedData.\n *\n * Creates degenerate (signature-less) certificate bags, parses RFC 5652\n * SignedData (and the RFC 2315 form whose contentInfo content is an OCTET\n * STRING), and verifies signer signatures including signed-attribute flows.\n * A CertificateSet is decoded as RFC 5652 §10.2.2 CertificateChoices, so an\n * attribute certificate or other-format entry is preserved rather than dropped.\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';\nimport { DECODE_REFUSAL_CODES, decodeRefusalOf } from '#micro509/internal/asn1/decode-refusal';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tinteger,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadRootElement,\n\treadSequenceChildren,\n\tsequence,\n\tsetOf,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport {\n\tdescribeHashAlgorithm,\n\tdescribeSignatureAlgorithm,\n} from '#micro509/internal/crypto/algorithm-names';\nimport type { CallerVerification, SignatureVerifiers } from '#micro509/internal/crypto/sig-verify';\nimport {\n\tcallerVerification,\n\tgetVerifySignatureConfigResult,\n\tverifySignedDataDetailed,\n} from '#micro509/internal/crypto/sig-verify';\nimport type { SignatureAlgorithmIdentifier } from '#micro509/internal/crypto/signing';\nimport {\n\tencodeAlgorithmIdentifier,\n\tgetSignatureAlgorithm,\n\tsignBytes,\n} from '#micro509/internal/crypto/signing';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport { compareDistinguishedNames } from '#micro509/internal/shared/dn';\nimport { pemEncode, splitPemBlocksOrThrow } from '#micro509/pem/pem';\nimport type {\n\tDecodeFailureCode,\n\tDecodeRefusalCode,\n\tErrorResult,\n\tMicro509Error,\n} from '#micro509/result/result';\nimport { failureResult, rethrowIfInvariant } from '#micro509/result/result';\nimport type { SignatureProfileInput } from '#micro509/x509/certificate';\nimport type { NameFieldKey } from '#micro509/x509/name';\nimport { nameFieldKeyFromOid } from '#micro509/x509/name';\nimport type {\n\tParsedCertificate,\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse';\nimport { parseCertificateDerOrThrow } from '#micro509/x509/parse';\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/** RFC 7468 Section 8 armors an RFC 2315 ContentInfo; Section 9 armors an RFC 5652 one. */\nconst CONTENT_INFO_PEM_LABELS = ['PKCS7', 'CMS'] as const;\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/**\n * RFC 5652 §5.3 `SignerIdentifier ::= CHOICE { issuerAndSerialNumber,\n * subjectKeyIdentifier [0] }`, which locates the signer's certificate.\n */\nexport type ParsedSignerIdentifier =\n\t| {\n\t\t\t/** Issuer name plus serial number. */\n\t\t\treadonly type: 'issuerAndSerialNumber';\n\t\t\t/** Parsed issuer distinguished name. */\n\t\t\treadonly issuer: ParsedName;\n\t\t\t/** Hex-encoded certificate serial number. */\n\t\t\treadonly serialNumberHex: string;\n\t }\n\t| {\n\t\t\t/** SubjectKeyIdentifier (`[0]`). */\n\t\t\treadonly type: 'subjectKeyIdentifier';\n\t\t\t/** Hex-encoded SubjectKeyIdentifier of the signer certificate. */\n\t\t\treadonly subjectKeyIdentifier: string;\n\t };\n\n/** Fields shared by every decoded SignerInfo, regardless of signed-attribute presence. */\nexport interface ParsedPkcs7SignerInfoBase {\n\t/** CMS SignerInfo version (typically 1 for issuerAndSerialNumber). */\n\treadonly version: number;\n\t/** Which of the two RFC 5652 §5.3 SignerIdentifier alternatives this SignerInfo uses. */\n\treadonly signerIdentifier: ParsedSignerIdentifier;\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\ninterface ParsedSignedDataOptionalFields {\n\treadonly certificates?: DerElement;\n\treadonly crls?: DerElement;\n}\n\ninterface ParsedSignedAttributeFields {\n\tmessageDigest?: Uint8Array;\n\tcontentTypeOid?: string;\n}\n\n/**\n * One RFC 5652 §10.2.2 CertificateChoices alternative.\n *\n * X.509 is the only alternative this library decodes. The rest keep their DER,\n * including the context tag, so a CertificateSet round-trips and a caller can\n * tell an X.509-only bag from one carrying attribute certificates. RFC 5652\n * marks `extendedCertificate` and `attributeCertificateV1` obsolete.\n */\nexport type ParsedCertificateChoice =\n\t| {\n\t\t\t/** X.509 certificate (untagged `Certificate`). */\n\t\t\treadonly type: 'certificate';\n\t\t\t/** The decoded certificate. */\n\t\t\treadonly certificate: ParsedCertificate;\n\t }\n\t| {\n\t\t\t/** PKCS #6 extended certificate (`[0]`), obsolete. */\n\t\t\treadonly type: 'extendedCertificate';\n\t\t\t/** Raw DER of the element, including its context tag. */\n\t\t\treadonly der: Uint8Array;\n\t }\n\t| {\n\t\t\t/** Version 1 X.509 attribute certificate (`[1]`), obsolete. */\n\t\t\treadonly type: 'attributeCertificateV1';\n\t\t\t/** Raw DER of the element, including its context tag. */\n\t\t\treadonly der: Uint8Array;\n\t }\n\t| {\n\t\t\t/** Version 2 X.509 attribute certificate (`[2]`). */\n\t\t\treadonly type: 'attributeCertificateV2';\n\t\t\t/** Raw DER of the element, including its context tag. */\n\t\t\treadonly der: Uint8Array;\n\t }\n\t| {\n\t\t\t/** Any other certificate format (`[3] OtherCertificateFormat`). */\n\t\t\treadonly type: 'other';\n\t\t\t/** `otherCertFormat` OID identifying the format. */\n\t\t\treadonly formatOid: string;\n\t\t\t/** Raw DER of the element, including its context tag. */\n\t\t\treadonly der: Uint8Array;\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/** RFC 5652 §10.2.2 CertificateChoices entries from the SignedData certificate set. */\n\treadonly certificateChoices: readonly ParsedCertificateChoice[];\n\t/** Decoded signer info entries. Empty for degenerate cert bags. */\n\treadonly signerInfos: readonly ParsedPkcs7SignerInfo[];\n}\n\n// Result types for PKCS#7 parsing\n\n/**\n * Error codes for PKCS#7 parse failures.\n *\n * `unsupported` is a signer issuer name value micro509 does not decode, a\n * TeletexString octet outside the X.690 §8.23.5.2 initial state.\n * `limit_exceeded` is an implementation limit: an OBJECT IDENTIFIER\n * sub-identifier encoded in more than 64 octets, a tag number of 2^53 or more,\n * or DER nested deeper than 64 levels.\n */\nexport type ParsePkcs7ErrorCode = DecodeFailureCode | '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/**\n * Error codes for {@linkcode verifyPkcs7SignedData} failures.\n *\n * `detached_content_required` means the SignedData carries no `eContent`\n * (detached signature or degenerate cert bag) and no external content was\n * supplied via {@linkcode VerifyPkcs7SignedDataOptions}.\n * `no_signers` means the SignedData carries no SignerInfo to verify.\n */\nexport type VerifyPkcs7SignedDataErrorCode =\n\t| 'invalid_options'\n\t| 'content_type_mismatch'\n\t| 'signed_attributes_required'\n\t| 'signed_attributes_forbidden'\n\t| 'no_signers'\n\t| 'signer_not_found'\n\t| 'signature_invalid'\n\t| 'message_digest_mismatch'\n\t| 'detached_content_required'\n\t| ParsePkcs7ErrorCode;\n\n/** Error payload for a failed {@linkcode verifyPkcs7SignedData} call. */\nexport interface VerifyPkcs7SignedDataFailure\n\textends Micro509Error<VerifyPkcs7SignedDataErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Options for {@linkcode verifyPkcs7SignedData}. */\nexport interface VerifyPkcs7SignedDataOptions {\n\t/** Expected eContentType OID. Defaults to id-data (1.2.840.113549.1.7.1). */\n\treadonly expectedContentTypeOid?: string;\n\t/**\n\t * Signed-attribute policy for every signer. Defaults to 'required'.\n\t * 'allowed' accepts either form for id-data; 'forbidden' accepts only bare\n\t * id-data signatures. RFC 5652 §5.3 always requires attributes for other types.\n\t */\n\treadonly signedAttributes?: 'required' | 'allowed' | 'forbidden';\n\t/**\n\t * External content for a detached SignedData (RFC 5652 Section 5.2, absent `eContent`).\n\t * Required to verify a detached signature; ignored when the SignedData embeds its own content.\n\t */\n\treadonly content?: Uint8Array;\n\t/**\n\t * Caller verifiers for signature algorithms micro509 does not verify through\n\t * WebCrypto, keyed by dotted-decimal signature algorithm OID. One runs only\n\t * where a SignerInfo signature would otherwise use unsupported algorithm\n\t * parameters, with the parameters in the signer certificate. A key that\n\t * micro509 verifies natively, a key that is no OID, or a value that is no\n\t * function fails with `invalid_options`.\n\t */\n\treadonly signatureVerifiers?: SignatureVerifiers;\n}\n\n/** A SignerInfo paired with the certificate that verified its signature. */\nexport interface VerifiedPkcs7Signer {\n\t/** The SignerInfo whose signature verified. */\n\treadonly signerInfo: ParsedPkcs7SignerInfo;\n\t/** The certificate from the SignedData certificate set that verified it. */\n\treadonly certificate: ParsedCertificate;\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\t\t/** One entry per SignerInfo, in SignedData order. */\n\t\t\treadonly signers: readonly VerifiedPkcs7Signer[];\n\t }\n\t| ErrorResult<VerifyPkcs7SignedDataErrorCode, Record<never, never>, VerifyPkcs7SignedDataFailure>;\n\n// createPkcs7CertBag\n\n/** Caller-correctable failure code from {@linkcode createPkcs7CertBag}. */\nexport type CreatePkcs7CertBagErrorCode = 'invalid_certificate' | DecodeRefusalCode;\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\tfor (const der of certificateDers) {\n\t\t\tparseCertificateDerOrThrow(der);\n\t\t}\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? createCertBagFailure(\n\t\t\t\t\t'invalid_certificate',\n\t\t\t\t\t'Each PKCS#7 certificate source must be valid PEM or DER',\n\t\t\t\t)\n\t\t\t: createCertBagFailure(refusal.code, refusal.message);\n\t}\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(1),\n\t\tsetOf([]),\n\t\tsequence([objectIdentifier(OIDS.pkcs7Data)]),\n\t\tcertificateSet,\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// createPkcs7SignedData\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\t/**\n\t * Omit `eContent` from `encapContentInfo` (RFC 5652 Section 5.2 detached\n\t * form). The signature still covers `content` via the messageDigest signed\n\t * attribute, but the bytes are not embedded — the verifier must supply them\n\t * externally (e.g. git x509 commit signing, S/MIME detached signatures).\n\t * @default false\n\t */\n\treadonly detached?: boolean;\n}\n\n/** DER, PEM, and base64 encodings of a PKCS#7/CMS SignedData structure. */\nexport interface Pkcs7SignedDataMaterial {\n\t/** Raw DER-encoded SignedData ContentInfo. */\n\treadonly der: Uint8Array;\n\t/**\n\t * PEM-armored ContentInfo. A version 1 SignedData carries the `PKCS7`\n\t * label; a version 3 one is outside RFC 2315, whose SignedData version\n\t * \"shall be 1\", so it carries the RFC 7468 Section 9 `CMS` label.\n\t */\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| 'invalid_certificate'\n\t| 'signer_certificate_key_mismatch'\n\t| 'unsupported_signer_key'\n\t| DecodeRefusalCode;\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). By default the\n * content is embedded (attached signature), so the result verifies with\n * {@linkcode verifyPkcs7SignedData} without any external data. With\n * `detached: true` the `eContent` is omitted (RFC 5652 Section 5.2) and the\n * verifier must supply the content externally.\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, a signer\n * certificate whose public key cannot verify the signer key's algorithm, 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 = new Uint8Array(input.content);\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 built = await buildPkcs7SignerInfo(signer, content, encapsulatedContentTypeOid);\n\t\tif (!built.ok) return built;\n\t\taddCertificate(built.certificateDer);\n\t\tdigestAlgorithmOids.add(built.digestOid);\n\t\tsignerInfos.push(built.signerInfoDer);\n\t}\n\n\tfor (const source of input.additionalCertificates ?? []) {\n\t\ttry {\n\t\t\tfor (const der of normalizeCertificateSource(source)) {\n\t\t\t\tparseCertificateDerOrThrow(der);\n\t\t\t\taddCertificate(der);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\t\treturn refusal === undefined\n\t\t\t\t? createPkcs7Failure(\n\t\t\t\t\t\t'invalid_certificate',\n\t\t\t\t\t\t'Each additional PKCS#7 certificate source must be valid PEM or DER',\n\t\t\t\t\t)\n\t\t\t\t: createPkcs7Failure(refusal.code, refusal.message);\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)]))),\n\t\tinput.detached === true\n\t\t\t? sequence([objectIdentifier(encapsulatedContentTypeOid)])\n\t\t\t: sequence([\n\t\t\t\t\tobjectIdentifier(encapsulatedContentTypeOid),\n\t\t\t\t\texplicitContext(0, octetString(content)),\n\t\t\t\t]),\n\t\tcertificateSet,\n\t\tsetOf(signerInfos),\n\t]);\n\tconst der = sequence([objectIdentifier(OIDS.pkcs7SignedData), explicitContext(0, signedData)]);\n\t// RFC 7468 Section 8 requires PKCS7-labelled data to be an RFC 2315\n\t// ContentInfo, whose SignedData version \"shall be 1\"; version 3 is described\n\t// only by RFC 5652, which Section 9 armors as CMS.\n\tconst label = signedDataVersion === 1 ? 'PKCS7' : 'CMS';\n\treturn {\n\t\tok: true,\n\t\tvalue: { der, pem: pemEncode(label, der), base64: base64Encode(der) },\n\t};\n}\n\n/** One built SignerInfo plus what the SignedData envelope needs from it. */\ntype Pkcs7SignerInfoBuild =\n\t| {\n\t\t\t/** Build succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** DER-encoded SignerInfo. */\n\t\t\treadonly signerInfoDer: Uint8Array;\n\t\t\t/** Digest algorithm OID for the digestAlgorithms SET. */\n\t\t\treadonly digestOid: string;\n\t\t\t/** Signer certificate DER for the certificate set. */\n\t\t\treadonly certificateDer: Uint8Array;\n\t }\n\t| ErrorResult<CreatePkcs7SignedDataErrorCode, Record<never, never>, CreatePkcs7SignedDataFailure>;\n\n/**\n * Builds one signer's SignerInfo over `content` (RFC 5652 Section 5.4\n * signed-attributes flow). Every throwing step here reacts to\n * caller-correctable input — malformed PEM/DER, unsupported key — so each is\n * mapped to a typed failure rather than rejecting the public Promise.\n */\nasync function buildPkcs7SignerInfo(\n\tsigner: Pkcs7Signer,\n\tcontent: Uint8Array,\n\tencapsulatedContentTypeOid: string,\n): Promise<Pkcs7SignerInfoBuild> {\n\t// normalizeCertificateSource throws on malformed PEM (stray or truncated markers).\n\tlet signerCertDers: readonly Uint8Array[];\n\ttry {\n\t\tsignerCertDers = normalizeCertificateSource(signer.certificate);\n\t} catch {\n\t\treturn createPkcs7Failure(\n\t\t\t'invalid_signer_certificate',\n\t\t\t'Each PKCS#7 signer certificate source must be valid PEM or DER',\n\t\t);\n\t}\n\tconst signerCertDer = signerCertDers[0];\n\tif (signerCertDer === undefined || signerCertDers.length !== 1) {\n\t\treturn createPkcs7Failure(\n\t\t\t'invalid_signer_certificate',\n\t\t\t'Each PKCS#7 signer must provide exactly one certificate',\n\t\t);\n\t}\n\tlet certificate: ParsedCertificate;\n\ttry {\n\t\tcertificate = parseCertificateDerOrThrow(signerCertDer);\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? createPkcs7Failure(\n\t\t\t\t\t'invalid_signer_certificate',\n\t\t\t\t\t'Each PKCS#7 signer certificate must be a parseable X.509 certificate',\n\t\t\t\t)\n\t\t\t: createPkcs7Failure(refusal.code, refusal.message);\n\t}\n\t// getSignatureAlgorithm throws only for unsupported/misconfigured keys.\n\tlet signatureAlgorithm: SignatureAlgorithmIdentifier;\n\ttry {\n\t\tsignatureAlgorithm = getSignatureAlgorithm(signer.privateKey, signer.signature);\n\t} catch {\n\t\treturn createPkcs7Failure(\n\t\t\t'unsupported_signer_key',\n\t\t\t'Unsupported signer key or signature profile',\n\t\t);\n\t}\n\t// RFC 8410 §12: \"the same public key cannot be used for both ECDH and EdDSA\",\n\t// so a SignerInfo must not name a certificate whose subject public key cannot\n\t// verify the algorithm the signer key produces.\n\tif (\n\t\t!getVerifySignatureConfigResult(\n\t\t\tsignatureAlgorithm.algorithmOid,\n\t\t\tsignatureAlgorithm.parameters,\n\t\t\tcertificate.publicKeyAlgorithmOid,\n\t\t\tcertificate.publicKeyParametersOid,\n\t\t\t'signer',\n\t\t).ok\n\t) {\n\t\treturn createPkcs7Failure(\n\t\t\t'signer_certificate_key_mismatch',\n\t\t\t'Each PKCS#7 signer certificate must carry a public key that verifies the signer key algorithm',\n\t\t);\n\t}\n\tconst digest = contentDigestForPrivateKey(signer.privateKey);\n\tif (digest === undefined) {\n\t\treturn createPkcs7Failure(\n\t\t\t'unsupported_signer_key',\n\t\t\t'Unsupported signer key algorithm for content digest',\n\t\t);\n\t}\n\tconst messageDigest = new Uint8Array(\n\t\tawait getCrypto().subtle.digest(digest.hashName, toArrayBuffer(content)),\n\t);\n\tconst { setForSigning, implicitForEmit } = buildSignedAttributes(\n\t\tencapsulatedContentTypeOid,\n\t\tmessageDigest,\n\t);\n\tlet signature: Uint8Array;\n\ttry {\n\t\tsignature = await signBytes(signer.privateKey, signatureAlgorithm, setForSigning);\n\t} catch {\n\t\treturn createPkcs7Failure(\n\t\t\t'unsupported_signer_key',\n\t\t\t'Signer key could not produce a PKCS#7 signature',\n\t\t);\n\t}\n\treturn {\n\t\tok: true,\n\t\tsignerInfoDer: sequence([\n\t\t\tintegerFromNumber(1),\n\t\t\tsequence([\n\t\t\t\thexToBytes(certificate.issuer.derHex),\n\t\t\t\tinteger(hexToBytes(certificate.serialNumberHex)),\n\t\t\t]),\n\t\t\tsequence([objectIdentifier(digest.digestOid)]),\n\t\t\timplicitForEmit,\n\t\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\t\toctetString(signature),\n\t\t]),\n\t\tdigestOid: digest.digestOid,\n\t\tcertificateDer: signerCertDer,\n\t};\n}\n\n// parsePkcs7CertBag — Result-returning\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: x509CertificatesOf(result.value.certificateChoices) };\n}\n\n/** The DER of the single `PKCS7` or `CMS` block in `pem`, or a typed failure. */\nfunction contentInfoPemBytes(\n\tpem: string,\n):\n\t| { readonly ok: true; readonly bytes: Uint8Array }\n\t| ErrorResult<ParsePkcs7ErrorCode, Record<never, never>, ParsePkcs7Failure> {\n\ttry {\n\t\tconst blocks = splitPemBlocksOrThrow(pem).filter((block) =>\n\t\t\tCONTENT_INFO_PEM_LABELS.some((label) => label === block.label),\n\t\t);\n\t\tconst block = blocks[0];\n\t\tif (block === undefined || blocks.length !== 1) {\n\t\t\treturn pkcs7Failure('malformed', 'Expected exactly one PKCS7 or CMS PEM block');\n\t\t}\n\t\treturn { ok: true, bytes: block.bytes };\n\t} catch {\n\t\treturn pkcs7Failure('malformed', 'Expected exactly one PKCS7 or CMS PEM block');\n\t}\n}\n\n/** Parses a PEM-armored PKCS#7/CMS cert bag. Expects exactly one `PKCS7` or `CMS` PEM block. */\nexport function parsePkcs7CertBagPem(pem: string): ParsePkcs7CertBagResult {\n\tconst block = contentInfoPemBytes(pem);\n\tif (!block.ok) return block;\n\treturn parsePkcs7CertBagDer(block.bytes);\n}\n\n// parsePkcs7SignedData — Result-returning\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 (contentType === undefined || contentInfo.length > 2 || contentType.tag !== 0x06) {\n\t\t\treturn pkcs7Failure('malformed', 'Malformed PKCS#7 content info');\n\t\t}\n\t\tif (content !== undefined && (content.tag !== 0xa0 || 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\tif (content === undefined) {\n\t\t\treturn pkcs7Failure('malformed', 'PKCS#7 signedData content info carries no content');\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\tconst optionalFields = parseSignedDataOptionalFields(trailingChildren.slice(0, -1));\n\t\tif (!optionalFields.ok) return optionalFields;\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 || encapChildren.length > 2 || encapType.tag !== 0x06) {\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\tcertificateChoices: parseCertificateSet(der, optionalFields.value.certificates),\n\t\t\t\tsignerInfos: parseSignerInfos(der, signerInfos),\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? pkcs7Failure('malformed', 'Malformed PKCS#7 structure')\n\t\t\t: pkcs7Failure(refusal.code, refusal.message);\n\t}\n}\n\nfunction parseSignedDataOptionalFields(\n\tchildren: readonly DerElement[],\n):\n\t| { readonly ok: true; readonly value: ParsedSignedDataOptionalFields }\n\t| ErrorResult<ParsePkcs7ErrorCode, Record<never, never>, ParsePkcs7Failure> {\n\tlet certificates: DerElement | undefined;\n\tlet crls: DerElement | undefined;\n\tfor (const child of children) {\n\t\tif (child.tag === 0xa0) {\n\t\t\tif (crls !== undefined)\n\t\t\t\treturn pkcs7Failure('malformed', 'SignedData certificates field must precede CRLs field');\n\t\t\tif (certificates !== undefined)\n\t\t\t\treturn pkcs7Failure('malformed', 'SignedData certificates field must not repeat');\n\t\t\tcertificates = child;\n\t\t\tcontinue;\n\t\t}\n\t\tif (child.tag === 0xa1) {\n\t\t\tif (crls !== undefined)\n\t\t\t\treturn pkcs7Failure('malformed', 'SignedData CRLs field must not repeat');\n\t\t\tcrls = child;\n\t\t\tcontinue;\n\t\t}\n\t\treturn pkcs7Failure('malformed', 'Malformed SignedData optional field');\n\t}\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\t...(certificates === undefined ? {} : { certificates }),\n\t\t\t...(crls === undefined ? {} : { crls }),\n\t\t},\n\t};\n}\n\n/** Decodes a PEM-armored PKCS#7/CMS SignedData. Expects exactly one `PKCS7` or `CMS` PEM block. */\nexport function parsePkcs7SignedDataPem(pem: string): ParsePkcs7SignedDataResult {\n\tconst block = contentInfoPemBytes(pem);\n\tif (!block.ok) return block;\n\treturn parsePkcs7SignedDataDer(block.bytes);\n}\n\n// verifyPkcs7SignedData\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 * Defaults to id-data and requires signed attributes on every signer. Select\n * `expectedContentTypeOid` from the application's protocol, not the input envelope.\n * Legacy bare id-data signatures require `signedAttributes: 'allowed'` or 'forbidden'.\n * Non-id-data always requires attributes (RFC 5652 §5.3).\n *\n * For a detached SignedData (absent `eContent`), pass the externally-held\n * content via `options.content`; without it, verification fails with the\n * typed `detached_content_required` code. When the SignedData embeds its own\n * content, that embedded content is verified and `options.content` is ignored.\n *\n * @example\n * ```ts\n * import { verifyPkcs7SignedData } from 'micro509';\n *\n * const result = await verifyPkcs7SignedData(pkcs7Pem);\n * if (result.ok) {\n * for (const { signerInfo, certificate } of result.signers) {\n * console.log(signerInfo.digestAlgorithmOid, certificate.subject);\n * }\n * }\n *\n * // Detached signature: supply the content externally\n * const detached = await verifyPkcs7SignedData(cmsBlob, { content: signedBytes });\n * ```\n */\nexport async function verifyPkcs7SignedData(\n\tinput: string | Uint8Array | ParsedPkcs7SignedData,\n\toptions: VerifyPkcs7SignedDataOptions = {},\n): Promise<VerifyPkcs7SignedDataResult> {\n\t// Snapshot application policy before asynchronous signature verification.\n\tconst policy = resolvePkcs7VerifyPolicy(options);\n\tif (!policy.ok) return policy;\n\tconst { expectedContentTypeOid, signedAttributes, verification } = policy;\n\tconst parsedResult = normalizePkcs7SignedDataForVerification(input);\n\tif (!parsedResult.ok) return parsedResult;\n\tconst parsed = parsedResult.value;\n\t// Snapshot caller-owned external content before any await so every signer\n\t// verifies against the same bytes (mirrors the create-side content copy).\n\tconst content =\n\t\tparsed.encapsulatedContent ??\n\t\t(options.content === undefined ? undefined : new Uint8Array(options.content));\n\tif (content === undefined) {\n\t\treturn verifyPkcs7Failure(\n\t\t\t'detached_content_required',\n\t\t\t'SignedData has no encapsulated content; supply the detached content via options.content',\n\t\t);\n\t}\n\tif (parsed.signerInfos.length === 0) {\n\t\treturn verifyPkcs7Failure('no_signers', 'SignedData contains no signer information');\n\t}\n\tif (parsed.encapsulatedContentTypeOid !== expectedContentTypeOid) {\n\t\treturn verifyPkcs7Failure('content_type_mismatch', 'Unexpected SignedData content type');\n\t}\n\tfor (const signer of parsed.signerInfos) {\n\t\tif (\n\t\t\t!signer.hasSignedAttrs &&\n\t\t\t(signedAttributes === 'required' || parsed.encapsulatedContentTypeOid !== OIDS.pkcs7Data)\n\t\t) {\n\t\t\treturn verifyPkcs7Failure('signed_attributes_required', 'Signed attributes are required');\n\t\t}\n\t\tif (signer.hasSignedAttrs && signedAttributes === 'forbidden') {\n\t\t\treturn verifyPkcs7Failure('signed_attributes_forbidden', 'Signed attributes are forbidden');\n\t\t}\n\t}\n\tconst signers: VerifiedPkcs7Signer[] = [];\n\tfor (const signerInfo of parsed.signerInfos) {\n\t\tconst result = await verifyPkcs7SignerInfo(parsed, signerInfo, content, verification);\n\t\tif (!result.ok) return result;\n\t\tsigners.push({ signerInfo, certificate: result.certificate });\n\t}\n\treturn { ok: true, value: parsed, signers };\n}\n\n/** Normalizes encoded or parsed SignedData into a freshly parsed verification input. */\nfunction normalizePkcs7SignedDataForVerification(\n\tinput: string | Uint8Array | ParsedPkcs7SignedData,\n): ParsePkcs7SignedDataResult | VerifyPkcs7SignedDataResult {\n\tif (typeof input === 'string') return parsePkcs7SignedDataPem(input);\n\tif (input instanceof Uint8Array) return parsePkcs7SignedDataDer(input);\n\tif (!hasReparseablePkcs7SignedData(input)) {\n\t\treturn verifyPkcs7Failure('malformed', 'SignedData parsed input is malformed');\n\t}\n\treturn parsePkcs7SignedDataDer(new Uint8Array(input.der));\n}\n\n/** Resolves and verifies one signer entry in a parsed PKCS#7 SignedData value. */\n/** Validates the caller policy in {@linkcode VerifyPkcs7SignedDataOptions}. */\nfunction resolvePkcs7VerifyPolicy(options: VerifyPkcs7SignedDataOptions):\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly expectedContentTypeOid: string;\n\t\t\treadonly signedAttributes: NonNullable<VerifyPkcs7SignedDataOptions['signedAttributes']>;\n\t\t\treadonly verification: CallerVerification;\n\t }\n\t| Extract<VerifyPkcs7SignedDataResult, { readonly ok: false }> {\n\tconst signedAttributes = options.signedAttributes ?? 'required';\n\tif (!['required', 'allowed', 'forbidden'].includes(signedAttributes)) {\n\t\treturn verifyPkcs7Failure('invalid_options', 'Unknown signed-attribute policy');\n\t}\n\tlet expectedContentTypeOid: string;\n\ttry {\n\t\texpectedContentTypeOid = decodeObjectIdentifier(\n\t\t\treadElement(objectIdentifier(options.expectedContentTypeOid ?? OIDS.pkcs7Data)).value,\n\t\t);\n\t} catch {\n\t\treturn verifyPkcs7Failure('invalid_options', 'Expected content type must be an OID');\n\t}\n\ttry {\n\t\tconst verification = callerVerification(options.signatureVerifiers);\n\t\treturn { ok: true, expectedContentTypeOid, signedAttributes, verification };\n\t} catch (error) {\n\t\tif (error instanceof RangeError) return verifyPkcs7Failure('invalid_options', error.message);\n\t\tthrow error;\n\t}\n}\n\nasync function verifyPkcs7SignerInfo(\n\tparsed: ParsedPkcs7SignedData,\n\tsignerInfo: ParsedPkcs7SignerInfo,\n\tcontent: Uint8Array,\n\tverification: CallerVerification,\n): Promise<\n\t| { readonly ok: true; readonly certificate: ParsedCertificate }\n\t| Extract<VerifyPkcs7SignedDataResult, { readonly ok: false }>\n> {\n\tconst signer = x509CertificatesOf(parsed.certificateChoices).find((certificate) =>\n\t\tsignerIdentifierMatches(certificate, signerInfo),\n\t);\n\tif (signer === undefined) {\n\t\treturn verifyPkcs7Failure(\n\t\t\t'signer_not_found',\n\t\t\t'Signer certificate not found in SignedData certificates',\n\t\t);\n\t}\n\tconst result = signerInfo.hasSignedAttrs\n\t\t? await verifySignedAttrs(\n\t\t\t\tsignerInfo,\n\t\t\t\tsigner,\n\t\t\t\tcontent,\n\t\t\t\tparsed.encapsulatedContentTypeOid,\n\t\t\t\tverification,\n\t\t\t)\n\t\t: await verifyPkcs7BareSignerInfo(signerInfo, signer, content, verification);\n\treturn result.ok ? { ok: true, certificate: signer } : result;\n}\n\nasync function verifyPkcs7BareSignerInfo(\n\tsignerInfo: ParsedPkcs7SignerInfo,\n\tsigner: ParsedCertificate,\n\tcontent: Uint8Array,\n\tverification: CallerVerification,\n): Promise<{ readonly ok: true } | Extract<VerifyPkcs7SignedDataResult, { readonly ok: false }>> {\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\t0,\n\t\t\tcontent,\n\t\t\tverification,\n\t\t);\n\t\tif (!verificationResult.ok) {\n\t\t\treturn verificationResult.code === 'verification_error'\n\t\t\t\t? verifyPkcs7Failure('malformed', 'SignedData signature verification failed')\n\t\t\t\t: verifyPkcs7Failure('malformed', 'Unsupported signature algorithm in SignedData');\n\t\t}\n\t\treturn verificationResult.valid\n\t\t\t? { ok: true }\n\t\t\t: verifyPkcs7Failure('signature_invalid', 'SignedData signature does not verify');\n\t} catch (error) {\n\t\treturn signatureVerificationThrowFailure(error);\n\t}\n}\n\n// Private helpers\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. */\n/** A signer's signature verification that threw: its decode refusal, else `malformed`. */\nfunction signatureVerificationThrowFailure(\n\terror: unknown,\n): ErrorResult<VerifyPkcs7SignedDataErrorCode, Record<never, never>, VerifyPkcs7SignedDataFailure> {\n\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\treturn refusal === undefined\n\t\t? verifyPkcs7Failure('malformed', 'Unsupported signature algorithm in SignedData')\n\t\t: verifyPkcs7Failure(refusal.code, refusal.message);\n}\n\nfunction verifyPkcs7Failure(\n\tcode: VerifyPkcs7SignedDataErrorCode,\n\tmessage: string,\n): ErrorResult<VerifyPkcs7SignedDataErrorCode, Record<never, never>, VerifyPkcs7SignedDataFailure> {\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\tconst blocks = splitPemBlocksOrThrow(source)\n\t\t\t.filter((block) => block.label === 'CERTIFICATE')\n\t\t\t.map((block) => new Uint8Array(block.bytes));\n\t\tif (blocks.length === 0) {\n\t\t\tthrow new Error('Certificate PEM required');\n\t\t}\n\t\treturn blocks;\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 * ECDSA curve pairing follows RFC 5753 §8: P-256 → SHA-256, P-384 → SHA-384,\n * P-521 → SHA-512. RSA uses the hash bound to the key.\n * Digest OIDs are from RFC 5754 §2.\n * Ed25519 uses 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/** The X.509 subset of a decoded CertificateSet. */\nfunction x509CertificatesOf(\n\tchoices: readonly ParsedCertificateChoice[],\n): readonly ParsedCertificate[] {\n\treturn choices.flatMap((choice) => (choice.type === 'certificate' ? [choice.certificate] : []));\n}\n\n/**\n * `otherCertFormat` from an `other [3] IMPLICIT OtherCertificateFormat` entry.\n *\n * The IMPLICIT tag replaces the SEQUENCE tag, so the OID and the `ANY DEFINED BY`\n * value are direct children of the `[3]` element.\n */\nfunction parseOtherCertificateFormatOid(source: Uint8Array, element: DerElement): string {\n\tconst formatOid = requireElement(childrenOf(source, element)[0], 'otherCertFormat');\n\tif (formatOid.tag !== 0x06) {\n\t\tthrow new Error('otherCertFormat must be an OBJECT IDENTIFIER');\n\t}\n\treturn decodeObjectIdentifier(formatOid.value);\n}\n\n/** Decodes one RFC 5652 §10.2.2 CertificateChoices alternative. */\nfunction parseCertificateChoice(\n\tsource: Uint8Array,\n\telement: DerElement,\n\tder: Uint8Array,\n): ParsedCertificateChoice {\n\tswitch (element.tag) {\n\t\tcase 0x30:\n\t\t\treturn { type: 'certificate', certificate: parseCertificateDerOrThrow(der) };\n\t\tcase 0xa0:\n\t\t\treturn { type: 'extendedCertificate', der };\n\t\tcase 0xa1:\n\t\t\treturn { type: 'attributeCertificateV1', der };\n\t\tcase 0xa2:\n\t\t\treturn { type: 'attributeCertificateV2', der };\n\t\tcase 0xa3:\n\t\t\treturn {\n\t\t\t\ttype: 'other',\n\t\t\t\tformatOid: parseOtherCertificateFormatOid(source, element),\n\t\t\t\tder,\n\t\t\t};\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported CertificateChoices tag: ${element.tag}`);\n\t}\n}\n\n/**\n * Parses the IMPLICIT [0] certificate set from a SignedData structure as\n * RFC 5652 §10.2.3 `CertificateSet ::= SET OF CertificateChoices`.\n */\nfunction parseCertificateSet(\n\tsource: Uint8Array,\n\tcertificates: ReturnType<typeof readElement> | undefined,\n): readonly ParsedCertificateChoice[] {\n\tif (certificates === undefined || certificates.tag !== 0xa0) {\n\t\treturn [];\n\t}\n\treturn childrenOf(source, certificates).map((element) =>\n\t\tparseCertificateChoice(\n\t\t\tsource,\n\t\t\telement,\n\t\t\tsource.slice(element.start - element.headerLength, element.end),\n\t\t),\n\t);\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\treturn childrenOf(source, element).map((signerInfo) => parseSignerInfo(source, signerInfo));\n}\n\nfunction parseSignerInfo(source: Uint8Array, signerInfo: DerElement): ParsedPkcs7SignerInfo {\n\tconst signerDer = source.slice(signerInfo.start - signerInfo.headerLength, signerInfo.end);\n\tconst parts = readSequenceChildren(signerDer);\n\tconst version = parts[0];\n\tconst sid = parts[1];\n\tconst digestAlgorithm = parts[2];\n\tlet index = 3;\n\tconst signedAttrsElement = parts[index]?.tag === 0xa0 ? parts[index] : undefined;\n\tif (signedAttrsElement !== undefined) index += 1;\n\tconst signatureAlgorithm = parts[index];\n\tconst signature = parts[index + 1];\n\tconst unauthenticatedAttributes = parts[index + 2];\n\tif (\n\t\tversion === undefined ||\n\t\tsid === undefined ||\n\t\tdigestAlgorithm === undefined ||\n\t\tsignatureAlgorithm === undefined ||\n\t\tsignature === undefined ||\n\t\tsignature.tag !== 0x04 ||\n\t\tparts.length > index + 3 ||\n\t\t(unauthenticatedAttributes !== undefined && unauthenticatedAttributes.tag !== 0xa1)\n\t) {\n\t\tthrow new Error('Malformed SignerInfo');\n\t}\n\tconst digestAlgorithmOid = parsePkcs7AlgorithmOid(\n\t\tsignerDer,\n\t\tdigestAlgorithm,\n\t\t'digest algorithm OID',\n\t);\n\tconst signatureAlgorithmDer = signerDer.slice(\n\t\tsignatureAlgorithm.start - signatureAlgorithm.headerLength,\n\t\tsignatureAlgorithm.end,\n\t);\n\tconst signatureAlgorithmChildren = readSequenceChildren(signatureAlgorithmDer);\n\tconst signatureAlgorithmOid = decodeObjectIdentifier(\n\t\trequireElement(signatureAlgorithmChildren[0], 'signature algorithm OID').value,\n\t);\n\tconst signatureAlgorithmParams = signatureAlgorithmChildren[1];\n\treturn {\n\t\tversion: decodeIntegerNumber(version.value),\n\t\tsignerIdentifier: parseSignerIdentifier(signerDer.slice(sid.start - sid.headerLength, sid.end)),\n\t\tdigestAlgorithmOid,\n\t\tdigestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),\n\t\tsignatureAlgorithmOid,\n\t\tsignatureAlgorithmName: describeSignatureAlgorithm(\n\t\t\tsignatureAlgorithmOid,\n\t\t\tsignatureAlgorithmParams === undefined\n\t\t\t\t? undefined\n\t\t\t\t: new Uint8Array(\n\t\t\t\t\t\tsignatureAlgorithmDer.slice(\n\t\t\t\t\t\t\tsignatureAlgorithmParams.start - signatureAlgorithmParams.headerLength,\n\t\t\t\t\t\t\tsignatureAlgorithmParams.end,\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t),\n\t\t...(signatureAlgorithmParams === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tsignatureAlgorithmParametersDer: new Uint8Array(\n\t\t\t\t\t\tsignatureAlgorithmDer.slice(\n\t\t\t\t\t\t\tsignatureAlgorithmParams.start - signatureAlgorithmParams.headerLength,\n\t\t\t\t\t\t\tsignatureAlgorithmParams.end,\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\tsignatureHex: toHex(signature.value),\n\t\tsignature: new Uint8Array(signature.value),\n\t\t...(signedAttrsElement === undefined\n\t\t\t? { hasSignedAttrs: false as const }\n\t\t\t: {\n\t\t\t\t\thasSignedAttrs: true as const,\n\t\t\t\t\tsignedAttrsDer: new Uint8Array(\n\t\t\t\t\t\tsignerDer.slice(\n\t\t\t\t\t\t\tsignedAttrsElement.start - signedAttrsElement.headerLength,\n\t\t\t\t\t\t\tsignedAttrsElement.end,\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t};\n}\n\nfunction parsePkcs7AlgorithmOid(source: Uint8Array, element: DerElement, label: string): string {\n\tconst algorithmDer = source.slice(element.start - element.headerLength, element.end);\n\treturn decodeObjectIdentifier(requireElement(readSequenceChildren(algorithmDer)[0], label).value);\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\tif (inner.end !== element.end) {\n\t\tthrow new Error('Encapsulated content must hold exactly one element');\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): ParsedSignerIdentifier {\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\ttype: 'subjectKeyIdentifier',\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\ttype: 'issuerAndSerialNumber',\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\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\tconst fieldValue = decodeString(valueElement.tag, valueElement.value);\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// CMS signed attributes verification (RFC 5652 Section 5.4)\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\tconst fields: ParsedSignedAttributeFields = {};\n\tfor (const attr of childrenOf(signedAttrsDer, outer)) {\n\t\tparseSignedAttributeRequirement(signedAttrsDer, attr, fields);\n\t}\n\tif (fields.messageDigest === undefined) {\n\t\tthrow new Error('Missing messageDigest attribute in signedAttrs');\n\t}\n\tif (fields.contentTypeOid === undefined) {\n\t\tthrow new Error('Missing contentType attribute in signedAttrs');\n\t}\n\treturn { messageDigest: fields.messageDigest, contentTypeOid: fields.contentTypeOid };\n}\n\nfunction parseSignedAttributeRequirement(\n\tsignedAttrsDer: Uint8Array,\n\tattr: DerElement,\n\tfields: ParsedSignedAttributeFields,\n): void {\n\tconst attrDer = signedAttrsDer.slice(attr.start - attr.headerLength, attr.end);\n\tconst parts = readSequenceChildren(attrDer);\n\tconst oid = parts[0];\n\tconst values = parts[1];\n\tif (oid === undefined || values === undefined || parts.length !== 2 || values.tag !== 0x31) {\n\t\tthrow new Error('Malformed signedAttrs attribute');\n\t}\n\tconst attrOid = decodeObjectIdentifier(oid.value);\n\tconst valueElements = childrenOf(attrDer, values);\n\tif (attrOid === OIDS.cmsMessageDigest) {\n\t\tfields.messageDigest = parseUniqueSignedAttributeOctetString(\n\t\t\tfields.messageDigest,\n\t\t\tvalueElements,\n\t\t\t'messageDigest',\n\t\t);\n\t}\n\tif (attrOid === OIDS.cmsContentType) {\n\t\tfields.contentTypeOid = parseUniqueSignedAttributeOid(\n\t\t\tfields.contentTypeOid,\n\t\t\tvalueElements,\n\t\t\t'contentType',\n\t\t);\n\t}\n}\n\nfunction parseUniqueSignedAttributeOctetString(\n\texisting: Uint8Array | undefined,\n\tvalueElements: readonly DerElement[],\n\tlabel: string,\n): Uint8Array {\n\tif (existing !== undefined || valueElements.length !== 1) {\n\t\tthrow new Error(`${label} attribute must appear exactly once with one value`);\n\t}\n\tconst value = requireElement(valueElements[0], `${label} attribute value`);\n\tif (value.tag !== 0x04) {\n\t\tthrow new Error(`${label} attribute value must use OCTET STRING`);\n\t}\n\treturn value.value;\n}\n\nfunction parseUniqueSignedAttributeOid(\n\texisting: string | undefined,\n\tvalueElements: readonly DerElement[],\n\tlabel: string,\n): string {\n\tif (existing !== undefined || valueElements.length !== 1) {\n\t\tthrow new Error(`${label} attribute must appear exactly once with one value`);\n\t}\n\tconst value = requireElement(valueElements[0], `${label} attribute value`);\n\tif (value.tag !== 0x06) {\n\t\tthrow new Error(`${label} attribute value must use OBJECT IDENTIFIER`);\n\t}\n\treturn decodeObjectIdentifier(value.value);\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\tcontent: Uint8Array,\n\tencapsulatedContentTypeOid: string,\n\tverification: CallerVerification,\n): Promise<\n\t| { readonly ok: true }\n\t| ErrorResult<VerifyPkcs7SignedDataErrorCode, Record<never, never>, VerifyPkcs7SignedDataFailure>\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 (error) {\n\t\trethrowIfInvariant(error);\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? verifyPkcs7Failure('malformed', 'Malformed signedAttrs in SignedData')\n\t\t\t: verifyPkcs7Failure(refusal.code, refusal.message);\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 the content (embedded, or external for detached)\n\tlet actualDigest: Uint8Array;\n\ttry {\n\t\tconst hash = digestAlgorithmHash(signerInfo.digestAlgorithmOid);\n\t\tactualDigest = new Uint8Array(await getCrypto().subtle.digest(hash, toArrayBuffer(content)));\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\t0,\n\t\t\tsignedData,\n\t\t\tverification,\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 (error) {\n\t\treturn signatureVerificationThrowFailure(error);\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\tconst identifier = signerInfo.signerIdentifier;\n\tif (identifier.type === 'issuerAndSerialNumber') {\n\t\treturn (\n\t\t\tcertificate.serialNumberHex === identifier.serialNumberHex &&\n\t\t\tcompareDistinguishedNames(certificate.issuer, identifier.issuer)\n\t\t);\n\t}\n\treturn certificate.subjectKeyIdentifier === identifier.subjectKeyIdentifier;\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(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,2BAA2B;AAEtD"}
@@ -1 +1 @@
1
- {"version":3,"file":"result.js","names":["resultErrorBrand","error","value","result","fallback","invariantErrorTypes","type","details","code","message","index","DECODE_REFUSAL_CODES"],"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 * Exception form of a {@link Micro509Error}: a branded {@link Error} carrying the structured\n * {@linkcode code}, `message`, and any `details`.\n *\n * Thrown by {@link unwrap} for a failed result and by {@link throwMicro509Error} when a builder\n * rejects invalid construction input. Detect with {@link isResultError}.\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 {@linkcode 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 {@link ResultError} carrying the structured failure.\n *\n * Use when you have already validated the input (or prefer exceptions) and the Result ceremony is noise.\n * 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 {@linkcode 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 {@link error} if it is an invariant/programmer error ({@link TypeError}, {@link RangeError},\n * {@link ReferenceError}, {@link SyntaxError}); otherwise returns.\n *\n * Boundary wrappers that turn an expected failure into a `Result` should call this first, so a genuine crash\n * is never masked as a clean parse/decode failure.\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/**\n * Throws a {@link ResultError} carrying a typed {@link Micro509Error}.\n *\n * The direct-throw counterpart to {@link unwrap}, for builders that reject\n * invalid construction input. Callers branch on `error.code` via\n * {@link isResultError} instead of matching message strings.\n */\nexport function throwMicro509Error<TCode extends string, TDetails = Record<never, never>>(\n\tcode: TCode,\n\tmessage: string,\n\tdetails?: TDetails,\n): never {\n\tthrow makeResultError(micro509Error(code, message, details));\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\n/**\n * Codes a parse boundary returns for input it refuses without calling it\n * malformed: `unsupported` for a construct micro509 does not decode, and\n * `limit_exceeded` for an implementation limit of micro509's own.\n */\nexport const DECODE_REFUSAL_CODES = ['unsupported', 'limit_exceeded'] as const;\n\n/** One of {@linkcode DECODE_REFUSAL_CODES}. */\nexport type DecodeRefusalCode = (typeof DECODE_REFUSAL_CODES)[number];\n\n/** The codes a parse boundary returns for input it cannot decode: `malformed` and every {@linkcode DecodeRefusalCode}. */\nexport type DecodeFailureCode = 'malformed' | DecodeRefusalCode;\n"],"mappings":";;AAyEA,SAAgB,cAAsB,GAGpC;CACD,OAAO;EAAE,IAAI;EAAM;CAAM;AAC1B;;AAmBA,MAAMA,IAAmB,OAAO,sBAAsB;;AAGtD,SAAS,gBACR,GACsB;CACtB,OAAO,OAAO,OAAO,gBAAI,MAAM,GAAGC,EAAM,KAAK,IAAIA,EAAM,SAAS,GAAG;EAClE,MAAM;EACN,MAAMA,EAAM;EACZ;GACCD,IAAmB;CACrB,CAAC;AACF;;AAGA,SAAgB,cAAc,GAAsC;CACnE,OAAOE,aAAiB,SAASF,KAAoBE;AACtD;;;;;;;AAaA,SAAgB,OACf,GACS;CACT,IAAIC,EAAO,IACV,OAAOA,EAAO;CAEf,MAAM,gBAAgBA,EAAO,KAAK;AACnC;;AAGA,SAAgB,SACf,GACA,GACS;CACT,OAAOA,EAAO,KAAKA,EAAO,QAAQC;AACnC;;AAGA,MAAMC,IAAsB;CAAC;CAAW;CAAY;CAAgB;AAAW;;;;;;;;AAS/E,SAAgB,mBAAmB,GAAsB;CACxD,IAAIA,EAAoB,MAAM,MAASJ,aAAiBK,CAAI,GAC3D,MAAML;AAER;;AAGA,SAAgB,cACf,GACA,GACA,GACiC;CACjC,OAAO;EACN;EACA;EACA,GAAIM,MAAY,KAAA,IAAY,CAAC,IAAI,EAAE,WAAQ;CAC5C;AACD;;;;;;;;AASA,SAAgB,mBACf,GACA,GACA,GACQ;CACR,MAAM,gBAAgB,cAAcC,GAAMC,GAASF,CAAO,CAAC;AAC5D;;AAGA,SAAgB,qBACf,GACA,GACA,GACA,GACwC;CACxC,OAAO;EACN;EACA;EACA,GAAIG,MAAU,KAAA,IAAY,CAAC,IAAI,EAAE,SAAM;EACvC,GAAIH,MAAY,KAAA,IAAY,CAAC,IAAI,EAAE,WAAQ;CAC5C;AACD;;AAGA,SAAgB,YAId,GAAqD;CACtD,OAAO;EACN,IAAI;EACJ;EACA,MAAMN,EAAM;EACZ,SAASA,EAAM;EACf,GAAIA,EAAM,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAASA,EAAM,QAAQ;CACjE;AACD;;;;;;;;;;AAWA,SAAgB,cACf,GACA,GACA,GACwF;CACxF,OAAO,YAAY;EAAE,IAAI;EAAO,GAAG,cAAcO,GAAMC,GAASF,CAAO;CAAE,CAAC;AAC3E;;AAGA,SAAgB,mBAId,GAA4D;CAC7D,OAAO;EACN,IAAI;EACJ;EACA,MAAMN,EAAM;EACZ,SAASA,EAAM;EACf,GAAIA,EAAM,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAASA,EAAM,QAAQ;EAChE,GAAIA,EAAM,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAOA,EAAM,MAAM;CAC3D;AACD;;;;;;AAOA,MAAaU,IAAuB,CAAC,eAAe,gBAAgB"}
1
+ {"version":3,"file":"result.js","names":["value","resultErrorBrand","error","result","fallback","invariantErrorTypes","type","code","message","details","index","DECODE_REFUSAL_CODES"],"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 * Exception form of a {@link Micro509Error}: a branded {@link Error} carrying the structured\n * {@linkcode code}, `message`, and any `details`.\n *\n * Thrown by {@link unwrap} for a failed result and by {@link throwMicro509Error} when a builder\n * rejects invalid construction input. Detect with {@link isResultError}.\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 {@linkcode 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 {@link ResultError} carrying the structured failure.\n *\n * Use when you have already validated the input (or prefer exceptions) and the Result ceremony is noise.\n * 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 {@linkcode 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 {@link error} if it is an invariant/programmer error ({@link TypeError}, {@link RangeError},\n * {@link ReferenceError}, {@link SyntaxError}); otherwise returns.\n *\n * Boundary wrappers that turn an expected failure into a `Result` should call this first, so a genuine crash\n * is never masked as a clean parse/decode failure.\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/**\n * Throws a {@link ResultError} carrying a typed {@link Micro509Error}.\n *\n * The direct-throw counterpart to {@link unwrap}, for builders that reject\n * invalid construction input. Callers branch on `error.code` via\n * {@link isResultError} instead of matching message strings.\n */\nexport function throwMicro509Error<TCode extends string, TDetails = Record<never, never>>(\n\tcode: TCode,\n\tmessage: string,\n\tdetails?: TDetails,\n): never {\n\tthrow makeResultError(micro509Error(code, message, details));\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\n/**\n * Codes a parse boundary returns for input it refuses without calling it\n * malformed: `unsupported` for a construct micro509 does not decode, and\n * `limit_exceeded` for an implementation limit of micro509's own.\n */\nexport const DECODE_REFUSAL_CODES = ['unsupported', 'limit_exceeded'] as const;\n\n/** One of {@linkcode DECODE_REFUSAL_CODES}. */\nexport type DecodeRefusalCode = (typeof DECODE_REFUSAL_CODES)[number];\n\n/** The codes a parse boundary returns for input it cannot decode: `malformed` and every {@linkcode DecodeRefusalCode}. */\nexport type DecodeFailureCode = 'malformed' | DecodeRefusalCode;\n"],"mappings":";;AAyEA,SAAgB,cAAsBA,GAGpC;CACD,OAAO;EAAE,IAAI;EAAMA;CAAM;AAC1B;;AAmBA,MAAMC,IAAmB,OAAO,sBAAsB;;AAGtD,SAAS,gBACRC,GACsB;CACtB,OAAO,OAAO,OAAO,gBAAI,MAAM,GAAGA,EAAM,KAAK,IAAIA,EAAM,SAAS,GAAG;EAClE,MAAM;EACN,MAAMA,EAAM;EACZA;GACCD,IAAmB;CACrB,CAAC;AAC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