micro509 0.17.1 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +165 -6
- package/dist/crypto/crypto.d.ts +12 -4
- package/dist/crypto/crypto.js +30 -17
- package/dist/crypto/crypto.js.map +1 -1
- package/dist/crypto.d.ts +8 -2
- package/dist/der/der.d.ts +14 -4
- package/dist/der/der.js +19 -19
- package/dist/der/der.js.map +1 -1
- package/dist/der.d.ts +26 -2
- package/dist/der.js +4 -4
- package/dist/index.d.ts +84 -16
- package/dist/index.js +19 -19
- package/dist/internal/asn1/asn1.d.ts +1 -2
- package/dist/internal/asn1/asn1.js +10 -2
- package/dist/internal/asn1/asn1.js.map +1 -1
- package/dist/internal/asn1/ber.js.map +1 -1
- package/dist/internal/asn1/decode-refusal.js.map +1 -1
- package/dist/internal/asn1/der.d.ts +1 -2
- package/dist/internal/asn1/der.js.map +1 -1
- package/dist/internal/asn1/oids.js +71 -353
- package/dist/internal/asn1/oids.js.map +1 -1
- package/dist/internal/asn1/oids.json.js +357 -0
- package/dist/internal/asn1/oids.json.js.map +1 -0
- package/dist/internal/crypto/algorithm-names.js +1 -1
- package/dist/internal/crypto/algorithm-names.js.map +1 -1
- package/dist/internal/crypto/ecdsa.js.map +1 -1
- package/dist/internal/crypto/hash.js.map +1 -1
- package/dist/internal/crypto/pbes2.d.ts +1 -2
- package/dist/internal/crypto/pbes2.js +70 -70
- package/dist/internal/crypto/pbes2.js.map +1 -1
- package/dist/internal/crypto/prime-ec.js +37 -0
- package/dist/internal/crypto/prime-ec.js.map +1 -0
- package/dist/internal/crypto/rsa-pss.js +50 -50
- package/dist/internal/crypto/rsa-pss.js.map +1 -1
- package/dist/internal/crypto/sig-verify.d.ts +41 -2
- package/dist/internal/crypto/sig-verify.js +125 -38
- package/dist/internal/crypto/sig-verify.js.map +1 -1
- package/dist/internal/crypto/signing.d.ts +1 -2
- package/dist/internal/crypto/signing.js +26 -26
- package/dist/internal/crypto/signing.js.map +1 -1
- package/dist/internal/jose/base64url.js.map +1 -1
- package/dist/internal/jose/json-data.js +108 -0
- package/dist/internal/jose/json-data.js.map +1 -0
- package/dist/internal/jose/strict-json.d.ts +1 -2
- package/dist/internal/jose/strict-json.js.map +1 -1
- package/dist/internal/shared/base64.js.map +1 -1
- package/dist/internal/shared/dn.d.ts +1 -2
- package/dist/internal/shared/dn.js +1 -1
- package/dist/internal/shared/dn.js.map +1 -1
- package/dist/internal/shared/idna.js.map +1 -1
- package/dist/internal/shared/ip.d.ts +1 -2
- package/dist/internal/shared/ip.js.map +1 -1
- package/dist/internal/shared/mailbox.js.map +1 -1
- package/dist/internal/shared/punycode.js.map +1 -1
- package/dist/internal/shared/uri-host.js.map +1 -1
- package/dist/internal/verify/name-constraints-engine.js +64 -64
- package/dist/internal/verify/name-constraints-engine.js.map +1 -1
- package/dist/internal/verify/policy-engine.js +1 -1
- package/dist/internal/verify/policy-engine.js.map +1 -1
- package/dist/internal/verify/spki-distrust.js.map +1 -1
- package/dist/internal/verify/verify-path.d.ts +1 -2
- package/dist/internal/verify/verify-path.js +234 -128
- package/dist/internal/verify/verify-path.js.map +1 -1
- package/dist/internal/x509/directory-name.js +10 -10
- package/dist/internal/x509/directory-name.js.map +1 -1
- package/dist/internal/x509/extension-bits.js.map +1 -1
- package/dist/internal/x509/extension-errors.d.ts +1 -2
- package/dist/internal/x509/extension-errors.js.map +1 -1
- package/dist/internal/x509/extension-registry.js +18 -18
- package/dist/internal/x509/extension-registry.js.map +1 -1
- package/dist/internal/x509/general-name-profile.js +9 -9
- package/dist/internal/x509/general-name-profile.js.map +1 -1
- package/dist/internal/x509/general-name.js +32 -32
- package/dist/internal/x509/general-name.js.map +1 -1
- package/dist/internal/x509/name-fields.js +1 -1
- package/dist/internal/x509/name-fields.js.map +1 -1
- package/dist/internal/x509/or-address.js.map +1 -1
- package/dist/jose/base64url.d.ts +4 -0
- package/dist/jose/base64url.js +14 -0
- package/dist/jose/base64url.js.map +1 -0
- package/dist/jose/errors.d.ts +9 -3
- package/dist/jose/errors.js.map +1 -1
- package/dist/jose/jwe.d.ts +64 -0
- package/dist/jose/jwe.js +188 -0
- package/dist/jose/jwe.js.map +1 -0
- package/dist/jose/jwks.d.ts +38 -10
- package/dist/jose/jwks.js +156 -96
- package/dist/jose/jwks.js.map +1 -1
- package/dist/jose/jws.d.ts +8 -6
- package/dist/jose/jws.js +216 -170
- package/dist/jose/jws.js.map +1 -1
- package/dist/jose/jwt.d.ts +8 -2
- package/dist/jose/jwt.js +98 -98
- package/dist/jose/jwt.js.map +1 -1
- package/dist/jose/remote-jwks.d.ts +1 -2
- package/dist/jose/remote-jwks.js +106 -108
- package/dist/jose/remote-jwks.js.map +1 -1
- package/dist/jose.d.ts +15 -4
- package/dist/jose.js +7 -5
- package/dist/kdf/argon2-arithmetic.js.map +1 -1
- package/dist/kdf/argon2-core.js.map +1 -1
- package/dist/kdf/argon2-memory.js.map +1 -1
- package/dist/kdf/argon2-portable.js.map +1 -1
- package/dist/kdf/argon2.d.ts +7 -2
- package/dist/kdf/argon2.js.map +1 -1
- package/dist/kdf.d.ts +6 -0
- package/dist/keys/keys.d.ts +31 -6
- package/dist/keys/keys.js +315 -233
- package/dist/keys/keys.js.map +1 -1
- package/dist/keys.d.ts +11 -2
- package/dist/keys.js +2 -2
- package/dist/pem/pem.d.ts +1 -2
- package/dist/pem/pem.js +40 -25
- package/dist/pem/pem.js.map +1 -1
- package/dist/pem.d.ts +6 -0
- package/dist/pkcs/pfx.d.ts +2 -3
- package/dist/pkcs/pfx.js +142 -142
- package/dist/pkcs/pfx.js.map +1 -1
- package/dist/pkcs/pkcs12-mac.d.ts +1 -2
- package/dist/pkcs/pkcs12-mac.js +122 -122
- package/dist/pkcs/pkcs12-mac.js.map +1 -1
- package/dist/pkcs/pkcs7.d.ts +24 -3
- package/dist/pkcs/pkcs7.js +294 -256
- package/dist/pkcs/pkcs7.js.map +1 -1
- package/dist/pkcs.d.ts +10 -1
- package/dist/pkcs.js +4 -4
- package/dist/result/result.d.ts +1 -2
- package/dist/result/result.js.map +1 -1
- package/dist/result.d.ts +6 -0
- package/dist/revocation/chain.d.ts +69 -16
- package/dist/revocation/chain.js +431 -303
- package/dist/revocation/chain.js.map +1 -1
- package/dist/revocation/crl.d.ts +67 -14
- package/dist/revocation/crl.js +656 -366
- package/dist/revocation/crl.js.map +1 -1
- package/dist/revocation/ocsp.d.ts +78 -24
- package/dist/revocation/ocsp.js +622 -436
- package/dist/revocation/ocsp.js.map +1 -1
- package/dist/revocation/revocation.d.ts +68 -14
- package/dist/revocation/revocation.js +195 -74
- package/dist/revocation/revocation.js.map +1 -1
- package/dist/revocation.d.ts +14 -5
- package/dist/revocation.js +4 -4
- package/dist/ssh/ssh.d.ts +2 -3
- package/dist/ssh/ssh.js +165 -170
- package/dist/ssh/ssh.js.map +1 -1
- package/dist/ssh/wire.d.ts +1 -2
- package/dist/ssh/wire.js +10 -10
- package/dist/ssh/wire.js.map +1 -1
- package/dist/ssh.d.ts +8 -0
- package/dist/verify/identity.d.ts +3 -4
- package/dist/verify/identity.js +33 -33
- package/dist/verify/identity.js.map +1 -1
- package/dist/verify/name-constraints.d.ts +9 -2
- package/dist/verify/policy.d.ts +9 -2
- package/dist/verify/verify.d.ts +85 -34
- package/dist/verify/verify.js +276 -226
- package/dist/verify/verify.js.map +1 -1
- package/dist/verify.d.ts +12 -2
- package/dist/x509/certificate.d.ts +4 -5
- package/dist/x509/certificate.js +40 -40
- package/dist/x509/certificate.js.map +1 -1
- package/dist/x509/csr.d.ts +3 -4
- package/dist/x509/csr.js +15 -15
- package/dist/x509/csr.js.map +1 -1
- package/dist/x509/extensions.d.ts +1 -2
- package/dist/x509/extensions.js +165 -165
- package/dist/x509/extensions.js.map +1 -1
- package/dist/x509/fingerprint.d.ts +1 -2
- package/dist/x509/fingerprint.js.map +1 -1
- package/dist/x509/name-text.d.ts +1 -2
- package/dist/x509/name-text.js.map +1 -1
- package/dist/x509/name.d.ts +1 -2
- package/dist/x509/name.js +15 -15
- package/dist/x509/name.js.map +1 -1
- package/dist/x509/parse.d.ts +9 -6
- package/dist/x509/parse.js +394 -394
- package/dist/x509/parse.js.map +1 -1
- package/dist/x509.d.ts +17 -4
- package/dist/x509.js +8 -8
- package/package.json +32 -33
- package/dist/internal/asn1/oids2.js +0 -75
- package/dist/internal/asn1/oids2.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rsa-pss.js","names":["_exhaustive","hash","hashOid","parameters","hashAlgorithmIdentifier","sequence","explicitContext","objectIdentifier","OIDS","integerFromNumber","parametersDer","element","readRootElement","error","rethrowDecodeRefusal","DECODE_LIMIT_CODES","state","child","childrenOf","alreadySeen","fieldName","integerLabel","supportedHash","mgfHash","supported","children","source","label","requireElement","integerElement","decodeNonNegativeIntegerNumber","oid","decodeObjectIdentifier","oidElement","nullValue"],"sources":["../../../src/internal/crypto/rsa-pss.ts"],"sourcesContent":["/**\n * RSA-PSS `AlgorithmIdentifier` parameter parsing, validation, and encoding.\n *\n * Only the three hash-matched profiles (SHA-256/384/512 with MGF1 and matching salt\n * length) are accepted; SHA-1 defaults and mismatched MGF hashes are rejected.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeNonNegativeIntegerNumber,\n\tdecodeObjectIdentifier,\n\trequireElement,\n} from '#micro509/internal/asn1/asn1';\nimport { DECODE_LIMIT_CODES, rethrowDecodeRefusal } from '#micro509/internal/asn1/decode-refusal';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\treadRootElement,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\n\n/** Hash algorithm accepted for RSA-PSS signatures in this library. */\nexport type RsaPssHash = 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n/**\n * One of the three supported RSA-PSS parameter profiles.\n *\n * Hash, MGF1 hash, and salt length are always matched (e.g. SHA-256 / SHA-256 / 32).\n */\nexport type RsaPssParameters =\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-256';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-256';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 32;\n\t\t\t/** Trailer field (always 0xBC per RFC 8017 Appendix A.2.3). */\n\t\t\treadonly trailerField: 1;\n\t }\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-384';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-384';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 48;\n\t\t\t/** Trailer field (always 0xBC per RFC 8017 Appendix A.2.3). */\n\t\t\treadonly trailerField: 1;\n\t }\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-512';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-512';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 64;\n\t\t\t/** Trailer field (always 0xBC per RFC 8017 Appendix A.2.3). */\n\t\t\treadonly trailerField: 1;\n\t };\n\n/** Machine-readable reason why an RSA-PSS parameter set is not supported. */\nexport type UnsupportedRsaPssParametersReason =\n\t| 'default_hash_sha1'\n\t| 'unsupported_hash'\n\t| 'unsupported_mgf_algorithm'\n\t| 'unsupported_mgf_hash'\n\t| 'mgf_hash_mismatch'\n\t| 'unsupported_salt_length'\n\t| 'unsupported_trailer_field';\n\n/** Success branch of {@linkcode ParsedRsaPssParametersResult}. */\nexport interface ParsedRsaPssParametersSuccess {\n\t/** Discriminant for the success branch. */\n\treadonly ok: true;\n\t/** The validated RSA-PSS parameter profile. */\n\treadonly value: RsaPssParameters;\n}\n\n/** Failure: valid ASN.1 but an unsupported parameter combination. */\nexport interface ParsedRsaPssParametersUnsupported {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'unsupported_rsa_pss_parameters';\n\t/** Which specific parameter is unsupported. */\n\treadonly reason: UnsupportedRsaPssParametersReason;\n}\n\n/** Failure: the DER encoding is structurally invalid. */\nexport interface ParsedRsaPssParametersMalformed {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'malformed_rsa_pss_parameters';\n\t/** Human-readable description of the structural defect. */\n\treadonly reason: string;\n}\n\n/** Result of {@linkcode parseRsaPssParameters}: success, unsupported, or malformed. */\nexport type ParsedRsaPssParametersResult =\n\t| ParsedRsaPssParametersSuccess\n\t| ParsedRsaPssParametersUnsupported\n\t| ParsedRsaPssParametersMalformed;\n\n/** Parsed MGF AlgorithmIdentifier from an RSA-PSS parameter SEQUENCE. */\ninterface ParsedMaskGenAlgorithm {\n\t/** OID of the mask generation function (expected: id-mgf1). */\n\treadonly oid: string;\n\t/** OID of the hash algorithm used by MGF1, if present. */\n\treadonly hashOid?: string;\n}\n\ninterface MutableRsaPssParameterState {\n\thashOid: string;\n\tmaskGenAlgorithm: ParsedMaskGenAlgorithm;\n\tsaltLength: number;\n\ttrailerField: number;\n\tsawHash: boolean;\n\tsawMaskGen: boolean;\n\tsawSaltLength: boolean;\n\tsawTrailerField: boolean;\n}\n\n/** RFC 8017 Appendix A.2.3 default salt length when hash is SHA-1. */\nconst SHA1_SALT_LENGTH = 20;\n\n/** Return the canonical {@linkcode RsaPssParameters} profile for a given hash algorithm. */\nexport function rsaPssParametersForHash(hash: RsaPssHash): RsaPssParameters {\n\tswitch (hash) {\n\t\tcase 'SHA-256':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-256',\n\t\t\t\tmgfHash: 'SHA-256',\n\t\t\t\tsaltLength: 32,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tcase 'SHA-384':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-384',\n\t\t\t\tmgfHash: 'SHA-384',\n\t\t\t\tsaltLength: 48,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tcase 'SHA-512':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-512',\n\t\t\t\tmgfHash: 'SHA-512',\n\t\t\t\tsaltLength: 64,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = hash;\n\t\t\tthrow new Error(`Unhandled RsaPssHash: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** DER-encode an {@linkcode RsaPssParameters} profile as an ASN.1 RSASSA-PSS-params SEQUENCE. */\nexport function encodeRsaPssParameters(parameters: RsaPssParameters): Uint8Array {\n\tconst hashOid = hashOidForName(parameters.hash);\n\tconst hashAlgorithmIdentifier = encodeHashAlgorithmIdentifier(hashOid);\n\treturn sequence([\n\t\texplicitContext(0, hashAlgorithmIdentifier),\n\t\texplicitContext(\n\t\t\t1,\n\t\t\tsequence([objectIdentifier(OIDS.mgf1), encodeHashAlgorithmIdentifier(hashOid)]),\n\t\t),\n\t\texplicitContext(2, integerFromNumber(parameters.saltLength)),\n\t\t...(parameters.trailerField === 1\n\t\t\t? []\n\t\t\t: [explicitContext(3, integerFromNumber(parameters.trailerField))]),\n\t]);\n}\n\n/**\n * Parse and validate DER-encoded RSASSA-PSS-params.\n *\n * Returns a typed result: success with a supported profile, unsupported with\n * a reason code, or malformed with an error message.\n *\n * @throws `limit_exceeded` on an OID sub-identifier over 64 octets.\n */\nexport function parseRsaPssParameters(\n\tparametersDer: Uint8Array | undefined,\n): ParsedRsaPssParametersResult {\n\tif (parametersDer === undefined) {\n\t\treturn unsupportedResult('default_hash_sha1');\n\t}\n\n\ttry {\n\t\tconst element = readRootElement(parametersDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (element.tag !== 0x30) {\n\t\t\tthrow new Error('RSA-PSS parameters must be a SEQUENCE');\n\t\t}\n\t\tconst state = parseRsaPssParameterFields(parametersDer, element);\n\t\treturn validateRsaPssParameterProfile(state);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: 'malformed_rsa_pss_parameters',\n\t\t\treason: error instanceof Error ? error.message : 'Malformed RSA-PSS parameters',\n\t\t};\n\t}\n}\n\n/** Parses the optional context-specific RSA-PSS fields into their defaulted state. */\nfunction parseRsaPssParameterFields(\n\tparametersDer: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n): MutableRsaPssParameterState {\n\tconst state: MutableRsaPssParameterState = {\n\t\thashOid: OIDS.sha1,\n\t\tmaskGenAlgorithm: { oid: OIDS.mgf1, hashOid: OIDS.sha1 },\n\t\tsaltLength: SHA1_SALT_LENGTH,\n\t\ttrailerField: 1,\n\t\tsawHash: false,\n\t\tsawMaskGen: false,\n\t\tsawSaltLength: false,\n\t\tsawTrailerField: false,\n\t};\n\tfor (const child of childrenOf(parametersDer, element)) {\n\t\tparseRsaPssParameterField(parametersDer, child, state);\n\t}\n\treturn state;\n}\n\nfunction parseRsaPssParameterField(\n\tparametersDer: Uint8Array,\n\tchild: ReturnType<typeof readRootElement>,\n\tstate: MutableRsaPssParameterState,\n): void {\n\tswitch (child.tag) {\n\t\tcase 0xa0:\n\t\t\tif (state.sawHash) throw new Error('RSA-PSS parameters contain duplicate hashAlgorithm');\n\t\t\tstate.hashOid = parseHashAlgorithmIdentifier(\n\t\t\t\tparametersDer,\n\t\t\t\trequireSingleExplicitChild(parametersDer, child, 'hashAlgorithm'),\n\t\t\t\t'hashAlgorithm',\n\t\t\t);\n\t\t\tstate.sawHash = true;\n\t\t\treturn;\n\t\tcase 0xa1:\n\t\t\tif (state.sawMaskGen)\n\t\t\t\tthrow new Error('RSA-PSS parameters contain duplicate maskGenAlgorithm');\n\t\t\tstate.maskGenAlgorithm = parseMaskGenAlgorithmIdentifier(\n\t\t\t\tparametersDer,\n\t\t\t\trequireSingleExplicitChild(parametersDer, child, 'maskGenAlgorithm'),\n\t\t\t);\n\t\t\tstate.sawMaskGen = true;\n\t\t\treturn;\n\t\tcase 0xa2:\n\t\t\tstate.saltLength = parseUniqueRsaPssIntegerField(\n\t\t\t\tparametersDer,\n\t\t\t\tchild,\n\t\t\t\tstate.sawSaltLength,\n\t\t\t\t'saltLength',\n\t\t\t\t'RSA-PSS saltLength',\n\t\t\t);\n\t\t\tstate.sawSaltLength = true;\n\t\t\treturn;\n\t\tcase 0xa3:\n\t\t\tstate.trailerField = parseUniqueRsaPssIntegerField(\n\t\t\t\tparametersDer,\n\t\t\t\tchild,\n\t\t\t\tstate.sawTrailerField,\n\t\t\t\t'trailerField',\n\t\t\t\t'RSA-PSS trailerField',\n\t\t\t);\n\t\t\tstate.sawTrailerField = true;\n\t\t\treturn;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`RSA-PSS parameters contain unexpected field tag 0x${child.tag.toString(16)}`,\n\t\t\t);\n\t}\n}\n\nfunction parseUniqueRsaPssIntegerField(\n\tparametersDer: Uint8Array,\n\tchild: ReturnType<typeof readRootElement>,\n\talreadySeen: boolean,\n\tfieldName: string,\n\tintegerLabel: string,\n): number {\n\tif (alreadySeen) throw new Error(`RSA-PSS parameters contain duplicate ${fieldName}`);\n\treturn parseExplicitInteger(parametersDer, child, fieldName, integerLabel);\n}\n\nfunction validateRsaPssParameterProfile(\n\tstate: MutableRsaPssParameterState,\n): ParsedRsaPssParametersResult {\n\tconst supportedHash = hashNameFromOid(state.hashOid);\n\tif (supportedHash === undefined) {\n\t\treturn state.hashOid === OIDS.sha1\n\t\t\t? unsupportedResult('default_hash_sha1')\n\t\t\t: unsupportedResult('unsupported_hash');\n\t}\n\tif (state.maskGenAlgorithm.oid !== OIDS.mgf1)\n\t\treturn unsupportedResult('unsupported_mgf_algorithm');\n\tconst mgfHash = hashNameFromOid(state.maskGenAlgorithm.hashOid);\n\tif (mgfHash === undefined) return unsupportedResult('unsupported_mgf_hash');\n\tif (mgfHash !== supportedHash) return unsupportedResult('mgf_hash_mismatch');\n\tconst supported = rsaPssParametersForHash(supportedHash);\n\tif (state.saltLength !== supported.saltLength)\n\t\treturn unsupportedResult('unsupported_salt_length');\n\tif (state.trailerField !== 1) return unsupportedResult('unsupported_trailer_field');\n\treturn { ok: true, value: supported };\n}\n\n/** Unwrap an explicit context tag and assert it contains exactly one child element. */\nfunction requireSingleExplicitChild(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n): ReturnType<typeof readRootElement> {\n\tconst children = childrenOf(source, element);\n\tif (children.length !== 1) {\n\t\tthrow new Error(`RSA-PSS ${label} must wrap exactly one value`);\n\t}\n\treturn requireElement(children[0], `RSA-PSS ${label}`);\n}\n\n/** Extract a non-negative integer from an explicit context-tagged wrapper. */\nfunction parseExplicitInteger(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n\tintegerLabel: string,\n): number {\n\tconst integerElement = requireSingleExplicitChild(source, element, label);\n\tif (integerElement.tag !== 0x02) {\n\t\tthrow new Error(`RSA-PSS ${label} must be an INTEGER`);\n\t}\n\treturn decodeNonNegativeIntegerNumber(integerElement.value, integerLabel);\n}\n\n/** Parse an AlgorithmIdentifier SEQUENCE and return the algorithm OID. */\nfunction parseHashAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n): string {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error(`RSA-PSS ${label} must be a SEQUENCE`);\n\t}\n\tconst children = childrenOf(source, element);\n\tif (children.length === 0 || children.length > 2) {\n\t\tthrow new Error(`Malformed RSA-PSS ${label} AlgorithmIdentifier`);\n\t}\n\tconst oid = requireElement(children[0], `${label} OID`);\n\tif (oid.tag !== 0x06) {\n\t\tthrow new Error(`Malformed RSA-PSS ${label} AlgorithmIdentifier`);\n\t}\n\tif (children.length === 2 && requireElement(children[1], `${label} parameters`).tag !== 0x05) {\n\t\tthrow new Error(`RSA-PSS ${label} AlgorithmIdentifier parameters must be NULL when present`);\n\t}\n\treturn decodeObjectIdentifier(oid.value);\n}\n\n/** Parse an MGF AlgorithmIdentifier SEQUENCE into OID and optional inner hash OID. */\nfunction parseMaskGenAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n): ParsedMaskGenAlgorithm {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('RSA-PSS maskGenAlgorithm must be a SEQUENCE');\n\t}\n\tconst children = childrenOf(source, element);\n\tif (children.length === 0 || children.length > 2) {\n\t\tthrow new Error('Malformed RSA-PSS maskGenAlgorithm AlgorithmIdentifier');\n\t}\n\tconst oidElement = requireElement(children[0], 'maskGenAlgorithm OID');\n\tif (oidElement.tag !== 0x06) {\n\t\tthrow new Error('Malformed RSA-PSS maskGenAlgorithm AlgorithmIdentifier');\n\t}\n\tconst oid = decodeObjectIdentifier(oidElement.value);\n\tif (oid !== OIDS.mgf1) {\n\t\treturn { oid };\n\t}\n\tconst parameters = requireElement(children[1], 'maskGenAlgorithm parameters');\n\treturn { oid, hashOid: parseHashAlgorithmIdentifier(source, parameters, 'MGF1 hashAlgorithm') };\n}\n\n/** DER-encode a hash AlgorithmIdentifier as `SEQUENCE { OID, NULL }`. */\nfunction encodeHashAlgorithmIdentifier(oid: string): Uint8Array {\n\treturn sequence([objectIdentifier(oid), nullValue()]);\n}\n\n/** Map a hash algorithm name to its ASN.1 OID string. */\nfunction hashOidForName(hash: RsaPssHash): string {\n\tswitch (hash) {\n\t\tcase 'SHA-256':\n\t\t\treturn OIDS.sha256;\n\t\tcase 'SHA-384':\n\t\t\treturn OIDS.sha384;\n\t\tcase 'SHA-512':\n\t\t\treturn OIDS.sha512;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = hash;\n\t\t\tthrow new Error(`Unhandled RsaPssHash: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** Reverse-map a hash OID to a supported {@linkcode RsaPssHash} name, or `undefined` if unsupported. */\nfunction hashNameFromOid(oid: string | undefined): RsaPssHash | undefined {\n\tswitch (oid) {\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\treturn undefined;\n\t}\n}\n\n/** Build an unsupported-parameters failure result. */\nfunction unsupportedResult(\n\treason: UnsupportedRsaPssParametersReason,\n): ParsedRsaPssParametersUnsupported {\n\treturn {\n\t\tok: false,\n\t\tcode: 'unsupported_rsa_pss_parameters',\n\t\treason,\n\t};\n}\n"],"mappings":";;;;;AAsIA,SAAgB,wBAAwB,GAAoC;CAC3E,QAAQC,GAAR;EACC,KAAK,WACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,YAAY;GACZ,cAAc;EACf;EACD,KAAK,WACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,YAAY;GACZ,cAAc;EACf;EACD,KAAK,WACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,YAAY;GACZ,cAAc;EACf;EACD,SAEC,MAAU,MAAM,yBAAyB,OAAOD,CAAW,GAAG;CAEhE;AACD;;AAGA,SAAgB,uBAAuB,GAA0C;CAChF,IAAME,IAAU,eAAeC,EAAW,IAAI,GACxCC,IAA0B,8BAA8BF,CAAO;CACrE,OAAOG,EAAS;EACfC,EAAgB,GAAGF,CAAuB;EAC1CE,EACC,GACAD,EAAS,CAACE,EAAiBC,EAAK,IAAI,GAAG,8BAA8BN,CAAO,CAAC,CAAC,CAC/E;EACAI,EAAgB,GAAGG,EAAkBN,EAAW,UAAU,CAAC;EAC3D,GAAIA,EAAW,iBAAiB,IAC7B,CAAC,IACD,CAACG,EAAgB,GAAGG,EAAkBN,EAAW,YAAY,CAAC,CAAC;CACnE,CAAC;AACF;;;;;;;;;AAUA,SAAgB,sBACf,GAC+B;CAC/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OA,EAAK;EACb,SAEC,MAAU,MAAM,yBAAyB,OAAOR,CAAW,GAAG;CAEhE;AACD;;AAGA,SAAS,gBAAgB,GAAiD;CACzE,QAAQ+B,GAAR;EACC,KAAKvB,EAAK,QACT,OAAO;EACR,KAAKA,EAAK,QACT,OAAO;EACR,KAAKA,EAAK,QACT,OAAO;EACR,SACC;CACF;AACD;;AAGA,SAAS,kBACR,GACoC;CACpC,OAAO;EACN,IAAI;EACJ,MAAM;EACN;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"rsa-pss.js","names":["_exhaustive","childrenOf","decodeNonNegativeIntegerNumber","decodeObjectIdentifier","requireElement","DECODE_LIMIT_CODES","rethrowDecodeRefusal","explicitContext","integerFromNumber","nullValue","objectIdentifier","readRootElement","sequence","OIDS","hash","parameters","hashOid","hashAlgorithmIdentifier","parametersDer","element","error","state","child","alreadySeen","fieldName","integerLabel","supportedHash","mgfHash","supported","source","label","children","integerElement","oid","oidElement","reason"],"sources":["../../../src/internal/crypto/rsa-pss.ts"],"sourcesContent":["/**\n * RSA-PSS `AlgorithmIdentifier` parameter parsing, validation, and encoding.\n *\n * Only the three hash-matched profiles (SHA-256/384/512 with MGF1 and matching salt\n * length) are accepted; SHA-1 defaults and mismatched MGF hashes are rejected.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeNonNegativeIntegerNumber,\n\tdecodeObjectIdentifier,\n\trequireElement,\n} from '#micro509/internal/asn1/asn1';\nimport { DECODE_LIMIT_CODES, rethrowDecodeRefusal } from '#micro509/internal/asn1/decode-refusal';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\treadRootElement,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\n\n/** Hash algorithm accepted for RSA-PSS signatures in this library. */\nexport type RsaPssHash = 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n/**\n * One of the three supported RSA-PSS parameter profiles.\n *\n * Hash, MGF1 hash, and salt length are always matched (e.g. SHA-256 / SHA-256 / 32).\n */\nexport type RsaPssParameters =\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-256';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-256';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 32;\n\t\t\t/** Trailer field (always 0xBC per RFC 8017 Appendix A.2.3). */\n\t\t\treadonly trailerField: 1;\n\t }\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-384';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-384';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 48;\n\t\t\t/** Trailer field (always 0xBC per RFC 8017 Appendix A.2.3). */\n\t\t\treadonly trailerField: 1;\n\t }\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-512';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-512';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 64;\n\t\t\t/** Trailer field (always 0xBC per RFC 8017 Appendix A.2.3). */\n\t\t\treadonly trailerField: 1;\n\t };\n\n/** Machine-readable reason why an RSA-PSS parameter set is not supported. */\nexport type UnsupportedRsaPssParametersReason =\n\t| 'default_hash_sha1'\n\t| 'unsupported_hash'\n\t| 'unsupported_mgf_algorithm'\n\t| 'unsupported_mgf_hash'\n\t| 'mgf_hash_mismatch'\n\t| 'unsupported_salt_length'\n\t| 'unsupported_trailer_field';\n\n/** Success branch of {@linkcode ParsedRsaPssParametersResult}. */\nexport interface ParsedRsaPssParametersSuccess {\n\t/** Discriminant for the success branch. */\n\treadonly ok: true;\n\t/** The validated RSA-PSS parameter profile. */\n\treadonly value: RsaPssParameters;\n}\n\n/** Failure: valid ASN.1 but an unsupported parameter combination. */\nexport interface ParsedRsaPssParametersUnsupported {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'unsupported_rsa_pss_parameters';\n\t/** Which specific parameter is unsupported. */\n\treadonly reason: UnsupportedRsaPssParametersReason;\n}\n\n/** Failure: the DER encoding is structurally invalid. */\nexport interface ParsedRsaPssParametersMalformed {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'malformed_rsa_pss_parameters';\n\t/** Human-readable description of the structural defect. */\n\treadonly reason: string;\n}\n\n/** Result of {@linkcode parseRsaPssParameters}: success, unsupported, or malformed. */\nexport type ParsedRsaPssParametersResult =\n\t| ParsedRsaPssParametersSuccess\n\t| ParsedRsaPssParametersUnsupported\n\t| ParsedRsaPssParametersMalformed;\n\n/** Parsed MGF AlgorithmIdentifier from an RSA-PSS parameter SEQUENCE. */\ninterface ParsedMaskGenAlgorithm {\n\t/** OID of the mask generation function (expected: id-mgf1). */\n\treadonly oid: string;\n\t/** OID of the hash algorithm used by MGF1, if present. */\n\treadonly hashOid?: string;\n}\n\ninterface MutableRsaPssParameterState {\n\thashOid: string;\n\tmaskGenAlgorithm: ParsedMaskGenAlgorithm;\n\tsaltLength: number;\n\ttrailerField: number;\n\tsawHash: boolean;\n\tsawMaskGen: boolean;\n\tsawSaltLength: boolean;\n\tsawTrailerField: boolean;\n}\n\n/** RFC 8017 Appendix A.2.3 default salt length when hash is SHA-1. */\nconst SHA1_SALT_LENGTH = 20;\n\n/** Return the canonical {@linkcode RsaPssParameters} profile for a given hash algorithm. */\nexport function rsaPssParametersForHash(hash: RsaPssHash): RsaPssParameters {\n\tswitch (hash) {\n\t\tcase 'SHA-256':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-256',\n\t\t\t\tmgfHash: 'SHA-256',\n\t\t\t\tsaltLength: 32,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tcase 'SHA-384':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-384',\n\t\t\t\tmgfHash: 'SHA-384',\n\t\t\t\tsaltLength: 48,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tcase 'SHA-512':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-512',\n\t\t\t\tmgfHash: 'SHA-512',\n\t\t\t\tsaltLength: 64,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = hash;\n\t\t\tthrow new Error(`Unhandled RsaPssHash: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** DER-encode an {@linkcode RsaPssParameters} profile as an ASN.1 RSASSA-PSS-params SEQUENCE. */\nexport function encodeRsaPssParameters(parameters: RsaPssParameters): Uint8Array {\n\tconst hashOid = hashOidForName(parameters.hash);\n\tconst hashAlgorithmIdentifier = encodeHashAlgorithmIdentifier(hashOid);\n\treturn sequence([\n\t\texplicitContext(0, hashAlgorithmIdentifier),\n\t\texplicitContext(\n\t\t\t1,\n\t\t\tsequence([objectIdentifier(OIDS.mgf1), encodeHashAlgorithmIdentifier(hashOid)]),\n\t\t),\n\t\texplicitContext(2, integerFromNumber(parameters.saltLength)),\n\t\t...(parameters.trailerField === 1\n\t\t\t? []\n\t\t\t: [explicitContext(3, integerFromNumber(parameters.trailerField))]),\n\t]);\n}\n\n/**\n * Parse and validate DER-encoded RSASSA-PSS-params.\n *\n * Returns a typed result: success with a supported profile, unsupported with\n * a reason code, or malformed with an error message.\n *\n * @throws `limit_exceeded` on an OID sub-identifier over 64 octets.\n */\nexport function parseRsaPssParameters(\n\tparametersDer: Uint8Array | undefined,\n): ParsedRsaPssParametersResult {\n\tif (parametersDer === undefined) {\n\t\treturn unsupportedResult('default_hash_sha1');\n\t}\n\n\ttry {\n\t\tconst element = readRootElement(parametersDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (element.tag !== 0x30) {\n\t\t\tthrow new Error('RSA-PSS parameters must be a SEQUENCE');\n\t\t}\n\t\tconst state = parseRsaPssParameterFields(parametersDer, element);\n\t\treturn validateRsaPssParameterProfile(state);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: 'malformed_rsa_pss_parameters',\n\t\t\treason: error instanceof Error ? error.message : 'Malformed RSA-PSS parameters',\n\t\t};\n\t}\n}\n\n/** Parses the optional context-specific RSA-PSS fields into their defaulted state. */\nfunction parseRsaPssParameterFields(\n\tparametersDer: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n): MutableRsaPssParameterState {\n\tconst state: MutableRsaPssParameterState = {\n\t\thashOid: OIDS.sha1,\n\t\tmaskGenAlgorithm: { oid: OIDS.mgf1, hashOid: OIDS.sha1 },\n\t\tsaltLength: SHA1_SALT_LENGTH,\n\t\ttrailerField: 1,\n\t\tsawHash: false,\n\t\tsawMaskGen: false,\n\t\tsawSaltLength: false,\n\t\tsawTrailerField: false,\n\t};\n\tfor (const child of childrenOf(parametersDer, element)) {\n\t\tparseRsaPssParameterField(parametersDer, child, state);\n\t}\n\treturn state;\n}\n\nfunction parseRsaPssParameterField(\n\tparametersDer: Uint8Array,\n\tchild: ReturnType<typeof readRootElement>,\n\tstate: MutableRsaPssParameterState,\n): void {\n\tswitch (child.tag) {\n\t\tcase 0xa0:\n\t\t\tif (state.sawHash) throw new Error('RSA-PSS parameters contain duplicate hashAlgorithm');\n\t\t\tstate.hashOid = parseHashAlgorithmIdentifier(\n\t\t\t\tparametersDer,\n\t\t\t\trequireSingleExplicitChild(parametersDer, child, 'hashAlgorithm'),\n\t\t\t\t'hashAlgorithm',\n\t\t\t);\n\t\t\tstate.sawHash = true;\n\t\t\treturn;\n\t\tcase 0xa1:\n\t\t\tif (state.sawMaskGen)\n\t\t\t\tthrow new Error('RSA-PSS parameters contain duplicate maskGenAlgorithm');\n\t\t\tstate.maskGenAlgorithm = parseMaskGenAlgorithmIdentifier(\n\t\t\t\tparametersDer,\n\t\t\t\trequireSingleExplicitChild(parametersDer, child, 'maskGenAlgorithm'),\n\t\t\t);\n\t\t\tstate.sawMaskGen = true;\n\t\t\treturn;\n\t\tcase 0xa2:\n\t\t\tstate.saltLength = parseUniqueRsaPssIntegerField(\n\t\t\t\tparametersDer,\n\t\t\t\tchild,\n\t\t\t\tstate.sawSaltLength,\n\t\t\t\t'saltLength',\n\t\t\t\t'RSA-PSS saltLength',\n\t\t\t);\n\t\t\tstate.sawSaltLength = true;\n\t\t\treturn;\n\t\tcase 0xa3:\n\t\t\tstate.trailerField = parseUniqueRsaPssIntegerField(\n\t\t\t\tparametersDer,\n\t\t\t\tchild,\n\t\t\t\tstate.sawTrailerField,\n\t\t\t\t'trailerField',\n\t\t\t\t'RSA-PSS trailerField',\n\t\t\t);\n\t\t\tstate.sawTrailerField = true;\n\t\t\treturn;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`RSA-PSS parameters contain unexpected field tag 0x${child.tag.toString(16)}`,\n\t\t\t);\n\t}\n}\n\nfunction parseUniqueRsaPssIntegerField(\n\tparametersDer: Uint8Array,\n\tchild: ReturnType<typeof readRootElement>,\n\talreadySeen: boolean,\n\tfieldName: string,\n\tintegerLabel: string,\n): number {\n\tif (alreadySeen) throw new Error(`RSA-PSS parameters contain duplicate ${fieldName}`);\n\treturn parseExplicitInteger(parametersDer, child, fieldName, integerLabel);\n}\n\nfunction validateRsaPssParameterProfile(\n\tstate: MutableRsaPssParameterState,\n): ParsedRsaPssParametersResult {\n\tconst supportedHash = hashNameFromOid(state.hashOid);\n\tif (supportedHash === undefined) {\n\t\treturn state.hashOid === OIDS.sha1\n\t\t\t? unsupportedResult('default_hash_sha1')\n\t\t\t: unsupportedResult('unsupported_hash');\n\t}\n\tif (state.maskGenAlgorithm.oid !== OIDS.mgf1)\n\t\treturn unsupportedResult('unsupported_mgf_algorithm');\n\tconst mgfHash = hashNameFromOid(state.maskGenAlgorithm.hashOid);\n\tif (mgfHash === undefined) return unsupportedResult('unsupported_mgf_hash');\n\tif (mgfHash !== supportedHash) return unsupportedResult('mgf_hash_mismatch');\n\tconst supported = rsaPssParametersForHash(supportedHash);\n\tif (state.saltLength !== supported.saltLength)\n\t\treturn unsupportedResult('unsupported_salt_length');\n\tif (state.trailerField !== 1) return unsupportedResult('unsupported_trailer_field');\n\treturn { ok: true, value: supported };\n}\n\n/** Unwrap an explicit context tag and assert it contains exactly one child element. */\nfunction requireSingleExplicitChild(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n): ReturnType<typeof readRootElement> {\n\tconst children = childrenOf(source, element);\n\tif (children.length !== 1) {\n\t\tthrow new Error(`RSA-PSS ${label} must wrap exactly one value`);\n\t}\n\treturn requireElement(children[0], `RSA-PSS ${label}`);\n}\n\n/** Extract a non-negative integer from an explicit context-tagged wrapper. */\nfunction parseExplicitInteger(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n\tintegerLabel: string,\n): number {\n\tconst integerElement = requireSingleExplicitChild(source, element, label);\n\tif (integerElement.tag !== 0x02) {\n\t\tthrow new Error(`RSA-PSS ${label} must be an INTEGER`);\n\t}\n\treturn decodeNonNegativeIntegerNumber(integerElement.value, integerLabel);\n}\n\n/** Parse an AlgorithmIdentifier SEQUENCE and return the algorithm OID. */\nfunction parseHashAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n): string {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error(`RSA-PSS ${label} must be a SEQUENCE`);\n\t}\n\tconst children = childrenOf(source, element);\n\tif (children.length === 0 || children.length > 2) {\n\t\tthrow new Error(`Malformed RSA-PSS ${label} AlgorithmIdentifier`);\n\t}\n\tconst oid = requireElement(children[0], `${label} OID`);\n\tif (oid.tag !== 0x06) {\n\t\tthrow new Error(`Malformed RSA-PSS ${label} AlgorithmIdentifier`);\n\t}\n\tif (children.length === 2 && requireElement(children[1], `${label} parameters`).tag !== 0x05) {\n\t\tthrow new Error(`RSA-PSS ${label} AlgorithmIdentifier parameters must be NULL when present`);\n\t}\n\treturn decodeObjectIdentifier(oid.value);\n}\n\n/** Parse an MGF AlgorithmIdentifier SEQUENCE into OID and optional inner hash OID. */\nfunction parseMaskGenAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n): ParsedMaskGenAlgorithm {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('RSA-PSS maskGenAlgorithm must be a SEQUENCE');\n\t}\n\tconst children = childrenOf(source, element);\n\tif (children.length === 0 || children.length > 2) {\n\t\tthrow new Error('Malformed RSA-PSS maskGenAlgorithm AlgorithmIdentifier');\n\t}\n\tconst oidElement = requireElement(children[0], 'maskGenAlgorithm OID');\n\tif (oidElement.tag !== 0x06) {\n\t\tthrow new Error('Malformed RSA-PSS maskGenAlgorithm AlgorithmIdentifier');\n\t}\n\tconst oid = decodeObjectIdentifier(oidElement.value);\n\tif (oid !== OIDS.mgf1) {\n\t\treturn { oid };\n\t}\n\tconst parameters = requireElement(children[1], 'maskGenAlgorithm parameters');\n\treturn { oid, hashOid: parseHashAlgorithmIdentifier(source, parameters, 'MGF1 hashAlgorithm') };\n}\n\n/** DER-encode a hash AlgorithmIdentifier as `SEQUENCE { OID, NULL }`. */\nfunction encodeHashAlgorithmIdentifier(oid: string): Uint8Array {\n\treturn sequence([objectIdentifier(oid), nullValue()]);\n}\n\n/** Map a hash algorithm name to its ASN.1 OID string. */\nfunction hashOidForName(hash: RsaPssHash): string {\n\tswitch (hash) {\n\t\tcase 'SHA-256':\n\t\t\treturn OIDS.sha256;\n\t\tcase 'SHA-384':\n\t\t\treturn OIDS.sha384;\n\t\tcase 'SHA-512':\n\t\t\treturn OIDS.sha512;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = hash;\n\t\t\tthrow new Error(`Unhandled RsaPssHash: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** Reverse-map a hash OID to a supported {@linkcode RsaPssHash} name, or `undefined` if unsupported. */\nfunction hashNameFromOid(oid: string | undefined): RsaPssHash | undefined {\n\tswitch (oid) {\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\treturn undefined;\n\t}\n}\n\n/** Build an unsupported-parameters failure result. */\nfunction unsupportedResult(\n\treason: UnsupportedRsaPssParametersReason,\n): ParsedRsaPssParametersUnsupported {\n\treturn {\n\t\tok: false,\n\t\tcode: 'unsupported_rsa_pss_parameters',\n\t\treason,\n\t};\n}\n"],"mappings":";;;;;AAsIA,SAAgB,wBAAwBc,GAAoC;CAC3E,QAAQA,GAAR;EACC,KAAK,WACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,YAAY;GACZ,cAAc;EACf;EACD,KAAK,WACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,YAAY;GACZ,cAAc;EACf;EACD,KAAK,WACJ,OAAO;GACN,MAAM;GACN,SAAS;GACT,YAAY;GACZ,cAAc;EACf;EACD,SAEC,MAAU,MAAM,yBAAyB,OAAOd,CAAW,GAAG;CAEhE;AACD;;AAGA,SAAgB,uBAAuBe,GAA0C;CAChF,IAAMC,IAAU,eAAeD,EAAW,IAAI,GACxCE,IAA0B,8BAA8BD,CAAO;CACrE,OAAOJ,EAAS;EACfL,EAAgB,GAAGU,CAAuB;EAC1CV,EACC,GACAK,EAAS,CAACF,EAAiBG,EAAK,IAAI,GAAG,8BAA8BG,CAAO,CAAC,CAAC,CAC/E;EACAT,EAAgB,GAAGC,EAAkBO,EAAW,UAAU,CAAC;EAC3D,GAAIA,EAAW,iBAAiB,IAC7B,CAAC,IACD,CAACR,EAAgB,GAAGC,EAAkBO,EAAW,YAAY,CAAC,CAAC;CACnE,CAAC;AAC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ACC,KAAK,WACJ,OAAOD,EAAK;EACb,KAAK,WACJ,OAAOA,EAAK;EACb,KAAK,WACJ,OAAOA,EAAK;EACb,SAEC,MAAU,MAAM,yBAAyB,OAAOb,CAAW,GAAG;CAEhE;AACD;;AAGA,SAAS,gBAAgBiC,GAAiD;CACzE,QAAQA,GAAR;EACC,KAAKpB,EAAK,QACT,OAAO;EACR,KAAKA,EAAK,QACT,OAAO;EACR,KAAKA,EAAK,QACT,OAAO;EACR,SACC;CACF;AACD;;AAGA,SAAS,kBACRsB,GACoC;CACpC,OAAO;EACN,IAAI;EACJ,MAAM;EACNA;CACD;AACD"}
|
|
@@ -1,3 +1,43 @@
|
|
|
1
|
+
/** One signature handed to a {@linkcode SignatureVerifier}. */
|
|
2
|
+
export interface SignatureVerifierInput {
|
|
3
|
+
/** The signature algorithm as carried beside the signature. */
|
|
4
|
+
readonly signatureAlgorithm: {
|
|
5
|
+
/** Dotted-decimal signature algorithm OID. */
|
|
6
|
+
readonly oid: string;
|
|
7
|
+
/** DER algorithm parameters, when the signature carries them. */
|
|
8
|
+
readonly parametersDer?: Uint8Array;
|
|
9
|
+
};
|
|
10
|
+
/** DER `SubjectPublicKeyInfo` of the signer. */
|
|
11
|
+
readonly signerSpkiDer: Uint8Array;
|
|
12
|
+
/**
|
|
13
|
+
* DER parameters to verify with: RFC 5280 §6.1 `working_public_key_parameters`.
|
|
14
|
+
* These are the signer's own key parameters, or the parameters it inherits along
|
|
15
|
+
* the certification path when its own are absent or NULL (RFC 5280 §6.1.4 (e),
|
|
16
|
+
* RFC 3279 §2.3.2). Absent when the path leaves none.
|
|
17
|
+
*/
|
|
18
|
+
readonly signerPublicKeyParametersDer?: Uint8Array;
|
|
19
|
+
/** The signature bytes as carried. */
|
|
20
|
+
readonly signature: Uint8Array;
|
|
21
|
+
/**
|
|
22
|
+
* Unused bits in the final octet of `signature`, from a `signatureValue`
|
|
23
|
+
* BIT STRING. `0` for a signature carried as octets.
|
|
24
|
+
*/
|
|
25
|
+
readonly signatureUnusedBits: number;
|
|
26
|
+
/** The exact bytes the signature covers. */
|
|
27
|
+
readonly data: Uint8Array;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Caller-supplied verification for a signature algorithm micro509 does not run
|
|
31
|
+
* through WebCrypto. Resolves `true` only for a valid signature. A rejection is
|
|
32
|
+
* reported as a verification error.
|
|
33
|
+
*/
|
|
34
|
+
export type SignatureVerifier = (input: SignatureVerifierInput) => Promise<boolean>;
|
|
35
|
+
/**
|
|
36
|
+
* Caller verifiers keyed by dotted-decimal signature algorithm OID. A key that
|
|
37
|
+
* micro509 verifies natively throws `RangeError`, so a caller verifier never
|
|
38
|
+
* replaces WebCrypto verification.
|
|
39
|
+
*/
|
|
40
|
+
export type SignatureVerifiers = Readonly<Record<string, SignatureVerifier>>;
|
|
1
41
|
/** Failure: the signature algorithm or its parameters are not supported. */
|
|
2
42
|
export interface VerifySignatureConfigFailure {
|
|
3
43
|
/** Discriminant for the failure branch. */
|
|
@@ -24,5 +64,4 @@ export interface VerifySignedDataSuccess {
|
|
|
24
64
|
readonly valid: boolean;
|
|
25
65
|
}
|
|
26
66
|
/** Result of a full signature verification: validity, unsupported params, or a runtime verification failure. */
|
|
27
|
-
export type VerifySignedDataResult = VerifySignedDataSuccess | VerifySignatureConfigFailure | VerifySignedDataFailure;
|
|
28
|
-
//# sourceMappingURL=sig-verify.d.ts.map
|
|
67
|
+
export type VerifySignedDataResult = VerifySignedDataSuccess | VerifySignatureConfigFailure | VerifySignedDataFailure;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { parseRsaPssParameters as
|
|
7
|
-
import { getCrypto as
|
|
8
|
-
import { importSpkiDerOrThrow as
|
|
1
|
+
import { canonicalizeOid as e, toArrayBuffer as t } from "../asn1/asn1.js";
|
|
2
|
+
import { DECODE_LIMIT_CODES as n, rethrowDecodeRefusal as r } from "../asn1/decode-refusal.js";
|
|
3
|
+
import { readElement as i, readSequenceChildren as a } from "../asn1/der.js";
|
|
4
|
+
import { OIDS as o } from "../asn1/oids.js";
|
|
5
|
+
import { alternateEcdsaSignatureEncoding as s, derEcdsaSignatureToRaw as c } from "./ecdsa.js";
|
|
6
|
+
import { parseRsaPssParameters as l } from "./rsa-pss.js";
|
|
7
|
+
import { getCrypto as u } from "./webcrypto.js";
|
|
8
|
+
import { importSpkiDerOrThrow as d } from "../../keys/keys.js";
|
|
9
9
|
// src/internal/crypto/sig-verify.ts
|
|
10
10
|
/**
|
|
11
11
|
* Signature-verification helpers that resolve parsed algorithm OIDs into WebCrypto
|
|
@@ -13,6 +13,64 @@ import { importSpkiDerOrThrow as l } from "../../keys/keys.js";
|
|
|
13
13
|
*
|
|
14
14
|
* @module
|
|
15
15
|
*/
|
|
16
|
+
const f = /* @__PURE__ */ new Set([
|
|
17
|
+
o.sha256WithRSAEncryption,
|
|
18
|
+
o.sha384WithRSAEncryption,
|
|
19
|
+
o.sha512WithRSAEncryption,
|
|
20
|
+
o.rsassaPss,
|
|
21
|
+
o.ecdsaWithSHA256,
|
|
22
|
+
o.ecdsaWithSHA384,
|
|
23
|
+
o.ecdsaWithSHA512,
|
|
24
|
+
o.ed25519
|
|
25
|
+
]);
|
|
26
|
+
/**
|
|
27
|
+
* Validates caller verifiers and indexes them by canonical OID.
|
|
28
|
+
*
|
|
29
|
+
* @throws RangeError for a key that is no encodable OID, a natively verified
|
|
30
|
+
* algorithm, or a value that is no function.
|
|
31
|
+
*/
|
|
32
|
+
function resolveSignatureVerifiers(e) {
|
|
33
|
+
let t = /* @__PURE__ */ new Map();
|
|
34
|
+
if (e === void 0) return t;
|
|
35
|
+
for (let [n, r] of Object.entries(e)) {
|
|
36
|
+
let e = canonicalVerifierOid(n);
|
|
37
|
+
if (f.has(e)) throw RangeError(`signatureVerifiers cannot replace native verification of ${n}`);
|
|
38
|
+
if (typeof r != "function") throw RangeError(`signatureVerifiers value for ${n} is not a function`);
|
|
39
|
+
if (t.has(e)) throw RangeError(`signatureVerifiers names ${e} twice`);
|
|
40
|
+
t.set(e, r);
|
|
41
|
+
}
|
|
42
|
+
return t;
|
|
43
|
+
}
|
|
44
|
+
function canonicalVerifierOid(t) {
|
|
45
|
+
if (!/^\d+(?:\.\d+)+$/.test(t)) throw RangeError(`signatureVerifiers key is not an OID: ${t}`);
|
|
46
|
+
try {
|
|
47
|
+
return e(t);
|
|
48
|
+
} catch (e) {
|
|
49
|
+
throw r(e, n), RangeError(`signatureVerifiers key is not an OID: ${t}`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** No caller verifiers: every signature goes through WebCrypto. */
|
|
53
|
+
const p = { verifiers: /* @__PURE__ */ new Map() };
|
|
54
|
+
/** Caller verification with `verifiers` and the signer's own key parameters. */
|
|
55
|
+
function callerVerification(e) {
|
|
56
|
+
return { verifiers: resolveSignatureVerifiers(e) };
|
|
57
|
+
}
|
|
58
|
+
/** DER key parameters, or `undefined` when they are absent or NULL (RFC 5280 §6.1.4 (e)). */
|
|
59
|
+
function explicitParameters(e) {
|
|
60
|
+
if (e !== void 0) return e.length === 2 && e[0] === 5 && e[1] === 0 ? void 0 : e;
|
|
61
|
+
}
|
|
62
|
+
/** The AlgorithmIdentifier parameters of a SubjectPublicKeyInfo; a malformed one has none. */
|
|
63
|
+
function spkiAlgorithmParametersDer(e) {
|
|
64
|
+
try {
|
|
65
|
+
let [t] = a(e);
|
|
66
|
+
if (t === void 0) return;
|
|
67
|
+
let n = e.subarray(t.start - t.headerLength, t.end), [, r] = a(n);
|
|
68
|
+
return r === void 0 ? void 0 : n.subarray(r.start - r.headerLength, r.end);
|
|
69
|
+
} catch (e) {
|
|
70
|
+
r(e, n);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
16
74
|
/** Non-throwing variant of {@linkcode getVerifySignatureConfig} — returns a typed result union. */
|
|
17
75
|
function getVerifySignatureConfigResult(e, t, n, r, i = "issuer") {
|
|
18
76
|
switch (e) {
|
|
@@ -106,53 +164,82 @@ function requireEcPublicKey(e, t, n, r = "issuer") {
|
|
|
106
164
|
}
|
|
107
165
|
}
|
|
108
166
|
/**
|
|
109
|
-
*
|
|
110
|
-
* {@linkcode VerifySignedDataResult}
|
|
111
|
-
*
|
|
167
|
+
* Verifies a signature against the signer's SPKI and the signed bytes. Returns
|
|
168
|
+
* a typed {@linkcode VerifySignedDataResult} for unsupported algorithms and
|
|
169
|
+
* runtime verification failures.
|
|
112
170
|
*
|
|
113
171
|
* Tries both DER and raw ECDSA encodings when the first attempt fails.
|
|
114
172
|
*
|
|
115
173
|
* @throws `limit_exceeded` on algorithm parameters or a public key that exceed
|
|
116
174
|
* a micro509 decoding limit.
|
|
117
175
|
*/
|
|
118
|
-
async function verifySignedDataDetailed(
|
|
119
|
-
let
|
|
120
|
-
if (!
|
|
176
|
+
async function verifySignedDataDetailed(e, t, i, a, o, s, c, l, u = p) {
|
|
177
|
+
let f = getVerifySignatureConfigResult(e, t, i, a);
|
|
178
|
+
if (!f.ok) {
|
|
179
|
+
let n = u.verifiers.get(e);
|
|
180
|
+
if (n === void 0) return f;
|
|
181
|
+
let r = u.workingParameters === void 0 ? explicitParameters(spkiAlgorithmParametersDer(o)) : u.workingParameters.parametersDer;
|
|
182
|
+
return await runCallerVerifier(n, {
|
|
183
|
+
signatureAlgorithm: {
|
|
184
|
+
oid: e,
|
|
185
|
+
...t === void 0 ? {} : { parametersDer: new Uint8Array(t) }
|
|
186
|
+
},
|
|
187
|
+
signerSpkiDer: new Uint8Array(o),
|
|
188
|
+
...r === void 0 ? {} : { signerPublicKeyParametersDer: new Uint8Array(r) },
|
|
189
|
+
signature: new Uint8Array(s),
|
|
190
|
+
signatureUnusedBits: c,
|
|
191
|
+
data: new Uint8Array(l)
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
if (c !== 0) return {
|
|
195
|
+
ok: !0,
|
|
196
|
+
valid: !1
|
|
197
|
+
};
|
|
121
198
|
try {
|
|
122
|
-
return await verifyWithConfiguredKey(await
|
|
123
|
-
} catch (
|
|
124
|
-
return
|
|
199
|
+
return await verifyWithConfiguredKey(await d(o, f.value.importAlgorithm), f.value, s, l, "auto");
|
|
200
|
+
} catch (e) {
|
|
201
|
+
return r(e, n), verificationError(e instanceof Error ? e.message : "signature verification failed");
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
async function runCallerVerifier(e, t) {
|
|
205
|
+
try {
|
|
206
|
+
return {
|
|
207
|
+
ok: !0,
|
|
208
|
+
valid: await e(t) === !0
|
|
209
|
+
};
|
|
210
|
+
} catch (e) {
|
|
211
|
+
return verificationError(e instanceof Error ? `signature verifier failed: ${e.message}` : "signature verifier failed");
|
|
125
212
|
}
|
|
126
213
|
}
|
|
127
214
|
/** Execute verification for imported SPKI and caller-owned keys with the same configuration. */
|
|
128
|
-
async function verifyWithConfiguredKey(
|
|
215
|
+
async function verifyWithConfiguredKey(e, i, a, o, l) {
|
|
129
216
|
try {
|
|
130
|
-
if (
|
|
131
|
-
|
|
132
|
-
} catch (
|
|
133
|
-
return
|
|
217
|
+
if (l === "der" && i.ecdsaRawSignatureBytes !== void 0) try {
|
|
218
|
+
a = c(a, i.ecdsaRawSignatureBytes / 2);
|
|
219
|
+
} catch (e) {
|
|
220
|
+
return r(e, n), {
|
|
134
221
|
ok: !0,
|
|
135
222
|
valid: !1
|
|
136
223
|
};
|
|
137
224
|
}
|
|
138
|
-
let d =
|
|
139
|
-
if (await d.verify(
|
|
225
|
+
let d = u().subtle, f = t(a), p = t(o);
|
|
226
|
+
if (await d.verify(i.verifyParams, e, f, p)) return {
|
|
140
227
|
ok: !0,
|
|
141
228
|
valid: !0
|
|
142
229
|
};
|
|
143
|
-
if (
|
|
144
|
-
let
|
|
145
|
-
if (
|
|
230
|
+
if (l === "auto" && i.ecdsaRawSignatureBytes !== void 0) {
|
|
231
|
+
let n = s(a, i.ecdsaRawSignatureBytes / 2);
|
|
232
|
+
if (n !== void 0) return {
|
|
146
233
|
ok: !0,
|
|
147
|
-
valid: await d.verify(
|
|
234
|
+
valid: await d.verify(i.verifyParams, e, t(n), p)
|
|
148
235
|
};
|
|
149
236
|
}
|
|
150
237
|
return {
|
|
151
238
|
ok: !0,
|
|
152
239
|
valid: !1
|
|
153
240
|
};
|
|
154
|
-
} catch (
|
|
155
|
-
return
|
|
241
|
+
} catch (e) {
|
|
242
|
+
return r(e, n), verificationError(e instanceof Error ? e.message : "signature verification failed");
|
|
156
243
|
}
|
|
157
244
|
}
|
|
158
245
|
/** Resolve a caller-owned key without exporting it, then run the shared verifier. */
|
|
@@ -185,18 +272,18 @@ async function verifySignedDataWithKeyDetailed(e, t, n, r, i, a) {
|
|
|
185
272
|
}
|
|
186
273
|
/** Parse RSA-PSS algorithm parameters and build a verification config, or return failure. */
|
|
187
274
|
function requireRsaPssVerifyConfig(e, t, n) {
|
|
188
|
-
let r =
|
|
275
|
+
let r = l(e);
|
|
189
276
|
return r.ok ? requireRsaPublicKey(t, r.value.hash, "pss", n, r.value.saltLength) : unsupported("RSA-PSS", r.reason);
|
|
190
277
|
}
|
|
191
278
|
/** RFC 4055 §5 requires generators to encode NULL and implementations to accept absent parameters too. */
|
|
192
|
-
function requireDerNullOrAbsentSignatureAlgorithmParameters(
|
|
193
|
-
if (
|
|
279
|
+
function requireDerNullOrAbsentSignatureAlgorithmParameters(e, t) {
|
|
280
|
+
if (e === void 0) return;
|
|
194
281
|
let a = "signature AlgorithmIdentifier parameters must be DER NULL or absent";
|
|
195
282
|
try {
|
|
196
|
-
let
|
|
197
|
-
return
|
|
198
|
-
} catch (
|
|
199
|
-
return
|
|
283
|
+
let n = i(e);
|
|
284
|
+
return n.tag !== 5 || n.length !== 0 || n.end !== e.length ? unsupported(t, a) : void 0;
|
|
285
|
+
} catch (e) {
|
|
286
|
+
return r(e, n), unsupported(t, a);
|
|
200
287
|
}
|
|
201
288
|
}
|
|
202
289
|
function requireAbsentSignatureAlgorithmParameters(e, t) {
|
|
@@ -224,6 +311,6 @@ function verificationError(e) {
|
|
|
224
311
|
reason: e
|
|
225
312
|
};
|
|
226
313
|
}
|
|
227
|
-
export { getVerifySignatureConfigResult, requireEcPublicKey, requireRsaPublicKey, verifySignedDataDetailed, verifySignedDataWithKeyDetailed };
|
|
314
|
+
export { p as NO_CALLER_VERIFICATION, callerVerification, explicitParameters, getVerifySignatureConfigResult, requireEcPublicKey, requireRsaPublicKey, resolveSignatureVerifiers, spkiAlgorithmParametersDer, verifySignedDataDetailed, verifySignedDataWithKeyDetailed };
|
|
228
315
|
|
|
229
316
|
//# sourceMappingURL=sig-verify.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sig-verify.js","names":["signatureAlgorithmOid","OIDS","parameters","signatureAlgorithmParametersDer","publicKeyAlgorithmOid","context","publicKeyParametersOid","algorithmOid","scheme","saltLength","parametersOid","config","importSpkiDerOrThrow","subjectPublicKeyInfoDer","signature","signedData","error","rethrowDecodeRefusal","DECODE_LIMIT_CODES","encoding","derEcdsaSignatureToRaw","subtle","getCrypto","signatureView","toArrayBuffer","dataView","key","alternate","alternateEcdsaSignatureEncoding","algorithm","oid","curveOid","parametersDer","data","parseRsaPssParameters","reason","element","readElement"],"sources":["../../../src/internal/crypto/sig-verify.ts"],"sourcesContent":["/**\n * Signature-verification helpers that resolve parsed algorithm OIDs into WebCrypto\n * verification configuration for higher-level validators.\n *\n * @module\n */\n\nimport { toArrayBuffer } from '#micro509/internal/asn1/asn1';\nimport { DECODE_LIMIT_CODES, rethrowDecodeRefusal } from '#micro509/internal/asn1/decode-refusal';\nimport { readElement } from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport {\n\talternateEcdsaSignatureEncoding,\n\tderEcdsaSignatureToRaw,\n} from '#micro509/internal/crypto/ecdsa';\nimport { parseRsaPssParameters } from '#micro509/internal/crypto/rsa-pss';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport type { PublicKeyImportInput, RsaHash, RsaSignatureScheme } from '#micro509/keys/keys';\nimport { importSpkiDerOrThrow } from '#micro509/keys/keys';\n\nexport {\n\talternateEcdsaSignatureEncoding,\n\tconcatFixedWidth,\n\tderEcdsaSignatureToRaw,\n\trawEcdsaSignatureToDer,\n} from '#micro509/internal/crypto/ecdsa';\n\n/** Resolved WebCrypto parameters needed to verify a signature. */\nexport interface VerifySignatureConfig {\n\t/** Algorithm descriptor for importing the signer's public key via {@linkcode importSpkiDer}. */\n\treadonly importAlgorithm: PublicKeyImportInput;\n\t/** WebCrypto `verify()` algorithm parameter. */\n\treadonly verifyParams: Algorithm | EcdsaParams | RsaPssParams;\n\t/** When set, raw ECDSA signatures are this many bytes and may need DER/raw conversion. */\n\treadonly ecdsaRawSignatureBytes?: number;\n}\n\n/** Failure: the signature algorithm or its parameters are not supported. */\nexport interface VerifySignatureConfigFailure {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'unsupported_signature_algorithm_parameters';\n\t/** Human-readable explanation of why the algorithm is unsupported. */\n\treadonly reason: string;\n}\n\n/** Failure: signature verification could not run to completion. */\nexport interface VerifySignedDataFailure {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'verification_error';\n\t/** Human-readable explanation of the verification failure. */\n\treadonly reason: string;\n}\n\n/** Success branch of {@linkcode VerifySignatureConfigResult}. */\nexport interface VerifySignatureConfigSuccess {\n\t/** Discriminant for the success branch. */\n\treadonly ok: true;\n\t/** The resolved verification configuration. */\n\treadonly value: VerifySignatureConfig;\n}\n\n/** Result of resolving signature algorithm OIDs into a {@linkcode VerifySignatureConfig}. */\nexport type VerifySignatureConfigResult =\n\t| VerifySignatureConfigSuccess\n\t| VerifySignatureConfigFailure;\n\n/** Success branch of {@linkcode VerifySignedDataResult}. */\nexport interface VerifySignedDataSuccess {\n\t/** Discriminant for the success branch. */\n\treadonly ok: true;\n\t/** Whether the cryptographic signature is valid for the given data and key. */\n\treadonly valid: boolean;\n}\n\n/** Result of a full signature verification: validity, unsupported params, or a runtime verification failure. */\nexport type VerifySignedDataResult =\n\t| VerifySignedDataSuccess\n\t| VerifySignatureConfigFailure\n\t| VerifySignedDataFailure;\n\n/**\n * Resolve algorithm OIDs into a {@linkcode VerifySignatureConfig}.\n *\n * Throws on unsupported algorithms. Use {@linkcode getVerifySignatureConfigResult} for\n * a non-throwing variant.\n */\nexport function getVerifySignatureConfig(\n\tsignatureAlgorithmOid: string,\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tpublicKeyParametersOid: string | undefined,\n\tcontext = 'issuer',\n): VerifySignatureConfig {\n\tconst result = getVerifySignatureConfigResult(\n\t\tsignatureAlgorithmOid,\n\t\tsignatureAlgorithmParametersDer,\n\t\tpublicKeyAlgorithmOid,\n\t\tpublicKeyParametersOid,\n\t\tcontext,\n\t);\n\tif (!result.ok) {\n\t\tthrow new Error(result.reason);\n\t}\n\treturn result.value;\n}\n\n/** Non-throwing variant of {@linkcode getVerifySignatureConfig} — returns a typed result union. */\nexport function getVerifySignatureConfigResult(\n\tsignatureAlgorithmOid: string,\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tpublicKeyParametersOid: string | undefined,\n\tcontext = 'issuer',\n): VerifySignatureConfigResult {\n\tswitch (signatureAlgorithmOid) {\n\t\tcase OIDS.sha256WithRSAEncryption: {\n\t\t\tconst parameters = requireDerNullOrAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'SHA-256 with RSA',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireRsaPublicKey(publicKeyAlgorithmOid, 'SHA-256', 'pkcs1-v1_5', context);\n\t\t}\n\t\tcase OIDS.sha384WithRSAEncryption: {\n\t\t\tconst parameters = requireDerNullOrAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'SHA-384 with RSA',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireRsaPublicKey(publicKeyAlgorithmOid, 'SHA-384', 'pkcs1-v1_5', context);\n\t\t}\n\t\tcase OIDS.sha512WithRSAEncryption: {\n\t\t\tconst parameters = requireDerNullOrAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'SHA-512 with RSA',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireRsaPublicKey(publicKeyAlgorithmOid, 'SHA-512', 'pkcs1-v1_5', context);\n\t\t}\n\t\tcase OIDS.rsassaPss:\n\t\t\treturn requireRsaPssVerifyConfig(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\tpublicKeyAlgorithmOid,\n\t\t\t\tcontext,\n\t\t\t);\n\t\tcase OIDS.ecdsaWithSHA256: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'ECDSA with SHA-256',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireEcPublicKey(publicKeyAlgorithmOid, publicKeyParametersOid, 'SHA-256', context);\n\t\t}\n\t\tcase OIDS.ecdsaWithSHA384: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'ECDSA with SHA-384',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireEcPublicKey(publicKeyAlgorithmOid, publicKeyParametersOid, 'SHA-384', context);\n\t\t}\n\t\tcase OIDS.ecdsaWithSHA512: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'ECDSA with SHA-512',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireEcPublicKey(publicKeyAlgorithmOid, publicKeyParametersOid, 'SHA-512', context);\n\t\t}\n\t\tcase OIDS.ed25519: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'Ed25519',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\tif (publicKeyAlgorithmOid !== OIDS.ed25519) {\n\t\t\t\treturn unsupported('Ed25519', `requires Ed25519 ${context} public key`);\n\t\t\t}\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ed25519' },\n\t\t\t\tverifyParams: { name: 'Ed25519' },\n\t\t\t});\n\t\t}\n\t\tdefault:\n\t\t\treturn unsupported(signatureAlgorithmOid, 'unrecognized signature algorithm OID');\n\t}\n}\n\n/** Validate that the public key OID is `rsaEncryption` and return an RSA verification config result. */\nexport function requireRsaPublicKey(\n\talgorithmOid: string,\n\thash: RsaHash,\n\tscheme: RsaSignatureScheme = 'pkcs1-v1_5',\n\tcontext = 'issuer',\n\tsaltLength?: number,\n): VerifySignatureConfigResult {\n\tif (algorithmOid !== OIDS.rsaEncryption) {\n\t\treturn unsupported('RSA', `requires RSA ${context} public key`);\n\t}\n\tconst verifyParams: Algorithm | RsaPssParams =\n\t\tscheme === 'pss'\n\t\t\t? { name: 'RSA-PSS', saltLength: saltLength ?? 0 }\n\t\t\t: { name: 'RSASSA-PKCS1-v1_5' };\n\treturn ok({ importAlgorithm: { kind: 'rsa', hash, scheme }, verifyParams });\n}\n\n/** Validate that the public key OID is `ecPublicKey`, resolve the curve, and return an ECDSA verification config result. */\nexport function requireEcPublicKey(\n\talgorithmOid: string,\n\tparametersOid: string | undefined,\n\thash: string,\n\tcontext = 'issuer',\n): VerifySignatureConfigResult {\n\tif (algorithmOid !== OIDS.ecPublicKey) {\n\t\treturn unsupported('ECDSA', `requires EC ${context} public key`);\n\t}\n\tswitch (parametersOid) {\n\t\tcase OIDS.prime256v1:\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ecdsa', curve: 'P-256' },\n\t\t\t\tverifyParams: { name: 'ECDSA', hash },\n\t\t\t\tecdsaRawSignatureBytes: 64,\n\t\t\t});\n\t\tcase OIDS.secp384r1:\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ecdsa', curve: 'P-384' },\n\t\t\t\tverifyParams: { name: 'ECDSA', hash },\n\t\t\t\tecdsaRawSignatureBytes: 96,\n\t\t\t});\n\t\tcase OIDS.secp521r1:\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ecdsa', curve: 'P-521' },\n\t\t\t\tverifyParams: { name: 'ECDSA', hash },\n\t\t\t\tecdsaRawSignatureBytes: 132,\n\t\t\t});\n\t\tdefault:\n\t\t\treturn unsupported('ECDSA', `unsupported EC curve OID: ${parametersOid ?? 'missing'}`);\n\t}\n}\n\n/** Return the raw ECDSA signature byte count (r + s) for a given curve OID, if supported. */\nexport function curveBytes(parametersOid: string | undefined): number | undefined {\n\tswitch (parametersOid) {\n\t\tcase OIDS.prime256v1:\n\t\t\treturn 64;\n\t\tcase OIDS.secp384r1:\n\t\t\treturn 96;\n\t\tcase OIDS.secp521r1:\n\t\t\treturn 132;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Verify a signature against the signer's SPKI and the signed TBS bytes.\n *\n * Throws on unsupported algorithms. Use {@linkcode verifySignedDataDetailed} for\n * a non-throwing variant.\n */\nexport async function verifySignedData(\n\tsignatureAlgorithmOid: string,\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tpublicKeyParametersOid: string | undefined,\n\tsubjectPublicKeyInfoDer: Uint8Array,\n\tsignature: Uint8Array,\n\tsignedData: Uint8Array,\n): Promise<boolean> {\n\tconst result = await verifySignedDataDetailed(\n\t\tsignatureAlgorithmOid,\n\t\tsignatureAlgorithmParametersDer,\n\t\tpublicKeyAlgorithmOid,\n\t\tpublicKeyParametersOid,\n\t\tsubjectPublicKeyInfoDer,\n\t\tsignature,\n\t\tsignedData,\n\t);\n\tif (!result.ok) {\n\t\tthrow new Error(result.reason);\n\t}\n\treturn result.valid;\n}\n\n/**\n * Non-throwing variant of {@linkcode verifySignedData} — returns a typed\n * {@linkcode VerifySignedDataResult} instead of throwing on unsupported algorithms\n * or runtime verification failures.\n *\n * Tries both DER and raw ECDSA encodings when the first attempt fails.\n *\n * @throws `limit_exceeded` on algorithm parameters or a public key that exceed\n * a micro509 decoding limit.\n */\nexport async function verifySignedDataDetailed(\n\tsignatureAlgorithmOid: string,\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tpublicKeyParametersOid: string | undefined,\n\tsubjectPublicKeyInfoDer: Uint8Array,\n\tsignature: Uint8Array,\n\tsignedData: Uint8Array,\n): Promise<VerifySignedDataResult> {\n\tconst config = getVerifySignatureConfigResult(\n\t\tsignatureAlgorithmOid,\n\t\tsignatureAlgorithmParametersDer,\n\t\tpublicKeyAlgorithmOid,\n\t\tpublicKeyParametersOid,\n\t);\n\tif (!config.ok) {\n\t\treturn config;\n\t}\n\ttry {\n\t\tconst key = await importSpkiDerOrThrow(subjectPublicKeyInfoDer, config.value.importAlgorithm);\n\t\treturn await verifyWithConfiguredKey(key, config.value, signature, signedData, 'auto');\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\treturn verificationError(\n\t\t\terror instanceof Error ? error.message : 'signature verification failed',\n\t\t);\n\t}\n}\n\n/** Execute verification for imported SPKI and caller-owned keys with the same configuration. */\nasync function verifyWithConfiguredKey(\n\tkey: CryptoKey,\n\tconfig: VerifySignatureConfig,\n\tsignature: Uint8Array,\n\tsignedData: Uint8Array,\n\tencoding: 'auto' | 'raw' | 'der',\n): Promise<VerifySignedDataResult> {\n\ttry {\n\t\tif (encoding === 'der' && config.ecdsaRawSignatureBytes !== undefined) {\n\t\t\ttry {\n\t\t\t\tsignature = derEcdsaSignatureToRaw(signature, config.ecdsaRawSignatureBytes / 2);\n\t\t\t} catch (error) {\n\t\t\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\t\t\treturn { ok: true, valid: false };\n\t\t\t}\n\t\t}\n\t\tconst subtle = getCrypto().subtle;\n\t\tconst signatureView = toArrayBuffer(signature);\n\t\tconst dataView = toArrayBuffer(signedData);\n\t\tif (await subtle.verify(config.verifyParams, key, signatureView, dataView)) {\n\t\t\treturn { ok: true, valid: true };\n\t\t}\n\t\tif (encoding === 'auto' && config.ecdsaRawSignatureBytes !== undefined) {\n\t\t\tconst alternate = alternateEcdsaSignatureEncoding(\n\t\t\t\tsignature,\n\t\t\t\tconfig.ecdsaRawSignatureBytes / 2,\n\t\t\t);\n\t\t\tif (alternate !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tok: true,\n\t\t\t\t\tvalid: await subtle.verify(config.verifyParams, key, toArrayBuffer(alternate), dataView),\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn { ok: true, valid: false };\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\treturn verificationError(\n\t\t\terror instanceof Error ? error.message : 'signature verification failed',\n\t\t);\n\t}\n}\n\n/** Resolve a caller-owned key without exporting it, then run the shared verifier. */\nexport async function verifySignedDataWithKeyDetailed(\n\tkey: CryptoKey,\n\tsignatureAlgorithmOid: string,\n\tparametersDer: Uint8Array | undefined,\n\tsignature: Uint8Array,\n\tdata: Uint8Array,\n\tencoding: 'raw' | 'der',\n): Promise<VerifySignedDataResult> {\n\tif (key.type !== 'public' || !key.usages.includes('verify')) {\n\t\treturn verificationError('Signature verification requires a public key with verify usage');\n\t}\n\tconst algorithm = key.algorithm;\n\tlet oid: string;\n\tlet curveOid: string | undefined;\n\tswitch (algorithm.name) {\n\t\tcase 'RSASSA-PKCS1-v1_5':\n\t\tcase 'RSA-PSS':\n\t\t\toid = OIDS.rsaEncryption;\n\t\t\tbreak;\n\t\tcase 'ECDSA':\n\t\t\toid = OIDS.ecPublicKey;\n\t\t\tif ('namedCurve' in algorithm) {\n\t\t\t\tswitch (algorithm.namedCurve) {\n\t\t\t\t\tcase 'P-256':\n\t\t\t\t\t\tcurveOid = OIDS.prime256v1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'P-384':\n\t\t\t\t\t\tcurveOid = OIDS.secp384r1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'P-521':\n\t\t\t\t\t\tcurveOid = OIDS.secp521r1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'Ed25519':\n\t\t\toid = OIDS.ed25519;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn unsupported(algorithm.name, 'unsupported public key algorithm');\n\t}\n\tconst config = getVerifySignatureConfigResult(\n\t\tsignatureAlgorithmOid,\n\t\tparametersDer,\n\t\toid,\n\t\tcurveOid,\n\t);\n\tif (!config.ok) return config;\n\tif (encoding !== 'raw' && encoding !== 'der') {\n\t\treturn unsupported(signatureAlgorithmOid, 'signature encoding must be raw or der');\n\t}\n\tif (encoding === 'der' && config.value.ecdsaRawSignatureBytes === undefined) {\n\t\treturn unsupported(signatureAlgorithmOid, 'DER signature encoding requires ECDSA');\n\t}\n\tif (algorithm.name !== config.value.verifyParams.name) {\n\t\treturn unsupported(signatureAlgorithmOid, 'signature scheme does not match the public key');\n\t}\n\tif (config.value.importAlgorithm.kind === 'rsa') {\n\t\tif (\n\t\t\t!('hash' in algorithm) ||\n\t\t\ttypeof algorithm.hash !== 'object' ||\n\t\t\talgorithm.hash === null ||\n\t\t\t!('name' in algorithm.hash) ||\n\t\t\talgorithm.hash.name !== config.value.importAlgorithm.hash\n\t\t) {\n\t\t\treturn unsupported(signatureAlgorithmOid, 'signature hash does not match the RSA public key');\n\t\t}\n\t}\n\treturn await verifyWithConfiguredKey(key, config.value, signature, data, encoding);\n}\n\n/** Parse RSA-PSS algorithm parameters and build a verification config, or return failure. */\nfunction requireRsaPssVerifyConfig(\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tcontext: string,\n): VerifySignatureConfigResult {\n\tconst parameters = parseRsaPssParameters(signatureAlgorithmParametersDer);\n\tif (!parameters.ok) {\n\t\treturn unsupported('RSA-PSS', parameters.reason);\n\t}\n\treturn requireRsaPublicKey(\n\t\tpublicKeyAlgorithmOid,\n\t\tparameters.value.hash,\n\t\t'pss',\n\t\tcontext,\n\t\tparameters.value.saltLength,\n\t);\n}\n\n/** RFC 4055 §5 requires generators to encode NULL and implementations to accept absent parameters too. */\nfunction requireDerNullOrAbsentSignatureAlgorithmParameters(\n\tparametersDer: Uint8Array | undefined,\n\talgorithm: string,\n): VerifySignatureConfigFailure | undefined {\n\tif (parametersDer === undefined) {\n\t\treturn undefined;\n\t}\n\tconst reason = 'signature AlgorithmIdentifier parameters must be DER NULL or absent';\n\ttry {\n\t\tconst element = readElement(parametersDer);\n\t\tif (element.tag !== 0x05 || element.length !== 0 || element.end !== parametersDer.length) {\n\t\t\treturn unsupported(algorithm, reason);\n\t\t}\n\t\treturn undefined;\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\treturn unsupported(algorithm, reason);\n\t}\n}\n\nfunction requireAbsentSignatureAlgorithmParameters(\n\tparametersDer: Uint8Array | undefined,\n\talgorithm: string,\n): VerifySignatureConfigFailure | undefined {\n\tif (parametersDer !== undefined) {\n\t\treturn unsupported(algorithm, 'signature AlgorithmIdentifier parameters must be absent');\n\t}\n\treturn undefined;\n}\n\n/** Wrap a config in a success result. */\nfunction ok(value: VerifySignatureConfig): VerifySignatureConfigSuccess {\n\treturn { ok: true, value };\n}\n\n/** Build an unsupported-algorithm failure result. */\nfunction unsupported(algorithm: string, reason: string): VerifySignatureConfigFailure {\n\treturn {\n\t\tok: false,\n\t\tcode: 'unsupported_signature_algorithm_parameters',\n\t\treason: `${algorithm} parameters unsupported: ${reason}`,\n\t};\n}\n\nfunction verificationError(reason: string): VerifySignedDataFailure {\n\treturn {\n\t\tok: false,\n\t\tcode: 'verification_error',\n\t\treason,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+GA,SAAgB,+BACf,GACA,GACA,GACA,GACA,IAAU,UACoB;CAC9B,QAAQA,GAAR;EACC,KAAKC,EAAK,yBAAyB;GAClC,IAAMC,IAAa,mDAClBC,GACA,kBACD;GAIA,OAHID,MAAe,KAAA,IAGZ,oBAAoBE,GAAuB,WAAW,cAAcC,CAAO,IAF1EH;EAGT;EACA,KAAKD,EAAK,yBAAyB;GAClC,IAAMC,IAAa,mDAClBC,GACA,kBACD;GAIA,OAHID,MAAe,KAAA,IAGZ,oBAAoBE,GAAuB,WAAW,cAAcC,CAAO,IAF1EH;EAGT;EACA,KAAKD,EAAK,yBAAyB;GAClC,IAAMC,IAAa,mDAClBC,GACA,kBACD;GAIA,OAHID,MAAe,KAAA,IAGZ,oBAAoBE,GAAuB,WAAW,cAAcC,CAAO,IAF1EH;EAGT;EACA,KAAKD,EAAK,WACT,OAAO,0BACNE,GACAC,GACAC,CACD;EACD,KAAKJ,EAAK,iBAAiB;GAC1B,IAAMC,IAAa,0CAClBC,GACA,oBACD;GAIA,OAHID,MAAe,KAAA,IAGZ,mBAAmBE,GAAuBE,GAAwB,WAAWD,CAAO,IAFnFH;EAGT;EACA,KAAKD,EAAK,iBAAiB;GAC1B,IAAMC,IAAa,0CAClBC,GACA,oBACD;GAIA,OAHID,MAAe,KAAA,IAGZ,mBAAmBE,GAAuBE,GAAwB,WAAWD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bzE,YAAYnB,GAAuB,gDAAgD,IARpEW;AAsBxB;;AAGA,SAAS,0BACR,GACA,GACA,GAC8B;CAC9B,IAAMT,IAAagC,EAAsB/B,CAA+B;CAIxE,OAHKD,EAAW,KAGT,oBACNE,GACAF,EAAW,MAAM,MACjB,OACAG,GACAH,EAAW,MAAM,UAClB,IARQ,YAAY,WAAWA,EAAW,MAAM;AASjD;;AAGA,SAAS,mDACR,GACA,GAC2C;CAC3C,IAAI8B,MAAkB,KAAA,GACrB;CAED,IAAMG,IAAS;CACf,IAAI;EACH,IAAMC,IAAUC,EAAYL,CAAa;EAIzC,OAHII,EAAQ,QAAQ,KAAQA,EAAQ,WAAW,KAAKA,EAAQ,QAAQJ,EAAc,SAC1E,YAAYH,GAAWM,CAAM,IAErC;CACD,SAASnB,GAAO;EAEf,OADAC,EAAqBD,GAAOE,CAAkB,GACvC,YAAYW,GAAWM,CAAM;CACrC;AACD;AAEA,SAAS,0CACR,GACA,GAC2C;CAC3C,IAAIH,MAAkB,KAAA,GACrB,OAAO,YAAYH,GAAW,yDAAyD;AAGzF;;AAGA,SAAS,GAAG,GAA4D;CACvE,OAAO;EAAE,IAAI;EAAM;CAAM;AAC1B;;AAGA,SAAS,YAAY,GAAmB,GAA8C;CACrF,OAAO;EACN,IAAI;EACJ,MAAM;EACN,QAAQ,GAAGA,EAAU,2BAA2BM;CACjD;AACD;AAEA,SAAS,kBAAkB,GAAyC;CACnE,OAAO;EACN,IAAI;EACJ,MAAM;EACN;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"sig-verify.js","names":["canonicalizeOid","toArrayBuffer","DECODE_LIMIT_CODES","rethrowDecodeRefusal","readElement","readSequenceChildren","OIDS","alternateEcdsaSignatureEncoding","derEcdsaSignatureToRaw","parseRsaPssParameters","getCrypto","importSpkiDerOrThrow","NATIVE_SIGNATURE_ALGORITHMS","verifiers","resolved","oid","verifier","canonical","error","NO_CALLER_VERIFICATION","parametersDer","spkiDer","algorithm","algorithmDer","parameters","signatureAlgorithmOid","signatureAlgorithmParametersDer","publicKeyAlgorithmOid","publicKeyParametersOid","context","algorithmOid","hash","scheme","saltLength","parametersOid","subjectPublicKeyInfoDer","signature","signatureUnusedBits","signedData","caller","config","signerParametersDer","input","key","encoding","subtle","signatureView","dataView","alternate","data","curveOid","reason","element","value"],"sources":["../../../src/internal/crypto/sig-verify.ts"],"sourcesContent":["/**\n * Signature-verification helpers that resolve parsed algorithm OIDs into WebCrypto\n * verification configuration for higher-level validators.\n *\n * @module\n */\n\nimport { canonicalizeOid, toArrayBuffer } from '#micro509/internal/asn1/asn1';\nimport { DECODE_LIMIT_CODES, rethrowDecodeRefusal } from '#micro509/internal/asn1/decode-refusal';\nimport { readElement, readSequenceChildren } from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport {\n\talternateEcdsaSignatureEncoding,\n\tderEcdsaSignatureToRaw,\n} from '#micro509/internal/crypto/ecdsa';\nimport { parseRsaPssParameters } from '#micro509/internal/crypto/rsa-pss';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport type { PublicKeyImportInput, RsaHash, RsaSignatureScheme } from '#micro509/keys/keys';\nimport { importSpkiDerOrThrow } from '#micro509/keys/keys';\n\nexport {\n\talternateEcdsaSignatureEncoding,\n\tconcatFixedWidth,\n\tderEcdsaSignatureToRaw,\n\trawEcdsaSignatureToDer,\n} from '#micro509/internal/crypto/ecdsa';\n\n/** One signature handed to a {@linkcode SignatureVerifier}. */\nexport interface SignatureVerifierInput {\n\t/** The signature algorithm as carried beside the signature. */\n\treadonly signatureAlgorithm: {\n\t\t/** Dotted-decimal signature algorithm OID. */\n\t\treadonly oid: string;\n\t\t/** DER algorithm parameters, when the signature carries them. */\n\t\treadonly parametersDer?: Uint8Array;\n\t};\n\t/** DER `SubjectPublicKeyInfo` of the signer. */\n\treadonly signerSpkiDer: Uint8Array;\n\t/**\n\t * DER parameters to verify with: RFC 5280 §6.1 `working_public_key_parameters`.\n\t * These are the signer's own key parameters, or the parameters it inherits along\n\t * the certification path when its own are absent or NULL (RFC 5280 §6.1.4 (e),\n\t * RFC 3279 §2.3.2). Absent when the path leaves none.\n\t */\n\treadonly signerPublicKeyParametersDer?: Uint8Array;\n\t/** The signature bytes as carried. */\n\treadonly signature: Uint8Array;\n\t/**\n\t * Unused bits in the final octet of `signature`, from a `signatureValue`\n\t * BIT STRING. `0` for a signature carried as octets.\n\t */\n\treadonly signatureUnusedBits: number;\n\t/** The exact bytes the signature covers. */\n\treadonly data: Uint8Array;\n}\n\n/**\n * Caller-supplied verification for a signature algorithm micro509 does not run\n * through WebCrypto. Resolves `true` only for a valid signature. A rejection is\n * reported as a verification error.\n */\nexport type SignatureVerifier = (input: SignatureVerifierInput) => Promise<boolean>;\n\n/**\n * Caller verifiers keyed by dotted-decimal signature algorithm OID. A key that\n * micro509 verifies natively throws `RangeError`, so a caller verifier never\n * replaces WebCrypto verification.\n */\nexport type SignatureVerifiers = Readonly<Record<string, SignatureVerifier>>;\n\nconst NATIVE_SIGNATURE_ALGORITHMS: ReadonlySet<string> = new Set([\n\tOIDS.sha256WithRSAEncryption,\n\tOIDS.sha384WithRSAEncryption,\n\tOIDS.sha512WithRSAEncryption,\n\tOIDS.rsassaPss,\n\tOIDS.ecdsaWithSHA256,\n\tOIDS.ecdsaWithSHA384,\n\tOIDS.ecdsaWithSHA512,\n\tOIDS.ed25519,\n]);\n\n/**\n * Validates caller verifiers and indexes them by canonical OID.\n *\n * @throws RangeError for a key that is no encodable OID, a natively verified\n * algorithm, or a value that is no function.\n */\nexport function resolveSignatureVerifiers(\n\tverifiers: SignatureVerifiers | undefined,\n): ReadonlyMap<string, SignatureVerifier> {\n\tconst resolved = new Map<string, SignatureVerifier>();\n\tif (verifiers === undefined) return resolved;\n\tfor (const [oid, verifier] of Object.entries(verifiers)) {\n\t\tconst canonical = canonicalVerifierOid(oid);\n\t\tif (NATIVE_SIGNATURE_ALGORITHMS.has(canonical)) {\n\t\t\tthrow new RangeError(`signatureVerifiers cannot replace native verification of ${oid}`);\n\t\t}\n\t\tif (typeof verifier !== 'function') {\n\t\t\tthrow new RangeError(`signatureVerifiers value for ${oid} is not a function`);\n\t\t}\n\t\tif (resolved.has(canonical)) {\n\t\t\tthrow new RangeError(`signatureVerifiers names ${canonical} twice`);\n\t\t}\n\t\tresolved.set(canonical, verifier);\n\t}\n\treturn resolved;\n}\n\nfunction canonicalVerifierOid(oid: string): string {\n\tif (!/^\\d+(?:\\.\\d+)+$/.test(oid)) {\n\t\tthrow new RangeError(`signatureVerifiers key is not an OID: ${oid}`);\n\t}\n\ttry {\n\t\treturn canonicalizeOid(oid);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\tthrow new RangeError(`signatureVerifiers key is not an OID: ${oid}`);\n\t}\n}\n\n/** The caller verifiers for one signature, and the key parameters a certification path gives its signer. */\nexport interface CallerVerification {\n\t/** Resolved caller verifiers, keyed by canonical signature algorithm OID. */\n\treadonly verifiers: ReadonlyMap<string, SignatureVerifier>;\n\t/**\n\t * RFC 5280 §6.1 `working_public_key_parameters` of the signer along its path.\n\t * Omitted to use the parameters in the signer's own SubjectPublicKeyInfo.\n\t */\n\treadonly workingParameters?: { readonly parametersDer: Uint8Array | undefined };\n}\n\n/** No caller verifiers: every signature goes through WebCrypto. */\nexport const NO_CALLER_VERIFICATION: CallerVerification = { verifiers: new Map() };\n\n/** Caller verification with `verifiers` and the signer's own key parameters. */\nexport function callerVerification(verifiers: SignatureVerifiers | undefined): CallerVerification {\n\treturn { verifiers: resolveSignatureVerifiers(verifiers) };\n}\n\n/** DER key parameters, or `undefined` when they are absent or NULL (RFC 5280 §6.1.4 (e)). */\nexport function explicitParameters(parametersDer: Uint8Array | undefined): Uint8Array | undefined {\n\tif (parametersDer === undefined) return undefined;\n\treturn parametersDer.length === 2 && parametersDer[0] === 0x05 && parametersDer[1] === 0x00\n\t\t? undefined\n\t\t: parametersDer;\n}\n\n/** The AlgorithmIdentifier parameters of a SubjectPublicKeyInfo; a malformed one has none. */\nexport function spkiAlgorithmParametersDer(spkiDer: Uint8Array): Uint8Array | undefined {\n\ttry {\n\t\tconst [algorithm] = readSequenceChildren(spkiDer);\n\t\tif (algorithm === undefined) return undefined;\n\t\tconst algorithmDer = spkiDer.subarray(algorithm.start - algorithm.headerLength, algorithm.end);\n\t\tconst [, parameters] = readSequenceChildren(algorithmDer);\n\t\treturn parameters === undefined\n\t\t\t? undefined\n\t\t\t: algorithmDer.subarray(parameters.start - parameters.headerLength, parameters.end);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\treturn undefined;\n\t}\n}\n\n/** Resolved WebCrypto parameters needed to verify a signature. */\nexport interface VerifySignatureConfig {\n\t/** Algorithm descriptor for importing the signer's public key via {@linkcode importSpkiDer}. */\n\treadonly importAlgorithm: PublicKeyImportInput;\n\t/** WebCrypto `verify()` algorithm parameter. */\n\treadonly verifyParams: Algorithm | EcdsaParams | RsaPssParams;\n\t/** When set, raw ECDSA signatures are this many bytes and may need DER/raw conversion. */\n\treadonly ecdsaRawSignatureBytes?: number;\n}\n\n/** Failure: the signature algorithm or its parameters are not supported. */\nexport interface VerifySignatureConfigFailure {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'unsupported_signature_algorithm_parameters';\n\t/** Human-readable explanation of why the algorithm is unsupported. */\n\treadonly reason: string;\n}\n\n/** Failure: signature verification could not run to completion. */\nexport interface VerifySignedDataFailure {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'verification_error';\n\t/** Human-readable explanation of the verification failure. */\n\treadonly reason: string;\n}\n\n/** Success branch of {@linkcode VerifySignatureConfigResult}. */\nexport interface VerifySignatureConfigSuccess {\n\t/** Discriminant for the success branch. */\n\treadonly ok: true;\n\t/** The resolved verification configuration. */\n\treadonly value: VerifySignatureConfig;\n}\n\n/** Result of resolving signature algorithm OIDs into a {@linkcode VerifySignatureConfig}. */\nexport type VerifySignatureConfigResult =\n\t| VerifySignatureConfigSuccess\n\t| VerifySignatureConfigFailure;\n\n/** Success branch of {@linkcode VerifySignedDataResult}. */\nexport interface VerifySignedDataSuccess {\n\t/** Discriminant for the success branch. */\n\treadonly ok: true;\n\t/** Whether the cryptographic signature is valid for the given data and key. */\n\treadonly valid: boolean;\n}\n\n/** Result of a full signature verification: validity, unsupported params, or a runtime verification failure. */\nexport type VerifySignedDataResult =\n\t| VerifySignedDataSuccess\n\t| VerifySignatureConfigFailure\n\t| VerifySignedDataFailure;\n\n/**\n * Resolve algorithm OIDs into a {@linkcode VerifySignatureConfig}.\n *\n * Throws on unsupported algorithms. Use {@linkcode getVerifySignatureConfigResult} for\n * a non-throwing variant.\n */\nexport function getVerifySignatureConfig(\n\tsignatureAlgorithmOid: string,\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tpublicKeyParametersOid: string | undefined,\n\tcontext = 'issuer',\n): VerifySignatureConfig {\n\tconst result = getVerifySignatureConfigResult(\n\t\tsignatureAlgorithmOid,\n\t\tsignatureAlgorithmParametersDer,\n\t\tpublicKeyAlgorithmOid,\n\t\tpublicKeyParametersOid,\n\t\tcontext,\n\t);\n\tif (!result.ok) {\n\t\tthrow new Error(result.reason);\n\t}\n\treturn result.value;\n}\n\n/** Non-throwing variant of {@linkcode getVerifySignatureConfig} — returns a typed result union. */\nexport function getVerifySignatureConfigResult(\n\tsignatureAlgorithmOid: string,\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tpublicKeyParametersOid: string | undefined,\n\tcontext = 'issuer',\n): VerifySignatureConfigResult {\n\tswitch (signatureAlgorithmOid) {\n\t\tcase OIDS.sha256WithRSAEncryption: {\n\t\t\tconst parameters = requireDerNullOrAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'SHA-256 with RSA',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireRsaPublicKey(publicKeyAlgorithmOid, 'SHA-256', 'pkcs1-v1_5', context);\n\t\t}\n\t\tcase OIDS.sha384WithRSAEncryption: {\n\t\t\tconst parameters = requireDerNullOrAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'SHA-384 with RSA',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireRsaPublicKey(publicKeyAlgorithmOid, 'SHA-384', 'pkcs1-v1_5', context);\n\t\t}\n\t\tcase OIDS.sha512WithRSAEncryption: {\n\t\t\tconst parameters = requireDerNullOrAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'SHA-512 with RSA',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireRsaPublicKey(publicKeyAlgorithmOid, 'SHA-512', 'pkcs1-v1_5', context);\n\t\t}\n\t\tcase OIDS.rsassaPss:\n\t\t\treturn requireRsaPssVerifyConfig(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\tpublicKeyAlgorithmOid,\n\t\t\t\tcontext,\n\t\t\t);\n\t\tcase OIDS.ecdsaWithSHA256: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'ECDSA with SHA-256',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireEcPublicKey(publicKeyAlgorithmOid, publicKeyParametersOid, 'SHA-256', context);\n\t\t}\n\t\tcase OIDS.ecdsaWithSHA384: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'ECDSA with SHA-384',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireEcPublicKey(publicKeyAlgorithmOid, publicKeyParametersOid, 'SHA-384', context);\n\t\t}\n\t\tcase OIDS.ecdsaWithSHA512: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'ECDSA with SHA-512',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\treturn requireEcPublicKey(publicKeyAlgorithmOid, publicKeyParametersOid, 'SHA-512', context);\n\t\t}\n\t\tcase OIDS.ed25519: {\n\t\t\tconst parameters = requireAbsentSignatureAlgorithmParameters(\n\t\t\t\tsignatureAlgorithmParametersDer,\n\t\t\t\t'Ed25519',\n\t\t\t);\n\t\t\tif (parameters !== undefined) {\n\t\t\t\treturn parameters;\n\t\t\t}\n\t\t\tif (publicKeyAlgorithmOid !== OIDS.ed25519) {\n\t\t\t\treturn unsupported('Ed25519', `requires Ed25519 ${context} public key`);\n\t\t\t}\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ed25519' },\n\t\t\t\tverifyParams: { name: 'Ed25519' },\n\t\t\t});\n\t\t}\n\t\tdefault:\n\t\t\treturn unsupported(signatureAlgorithmOid, 'unrecognized signature algorithm OID');\n\t}\n}\n\n/** Validate that the public key OID is `rsaEncryption` and return an RSA verification config result. */\nexport function requireRsaPublicKey(\n\talgorithmOid: string,\n\thash: RsaHash,\n\tscheme: RsaSignatureScheme = 'pkcs1-v1_5',\n\tcontext = 'issuer',\n\tsaltLength?: number,\n): VerifySignatureConfigResult {\n\tif (algorithmOid !== OIDS.rsaEncryption) {\n\t\treturn unsupported('RSA', `requires RSA ${context} public key`);\n\t}\n\tconst verifyParams: Algorithm | RsaPssParams =\n\t\tscheme === 'pss'\n\t\t\t? { name: 'RSA-PSS', saltLength: saltLength ?? 0 }\n\t\t\t: { name: 'RSASSA-PKCS1-v1_5' };\n\treturn ok({ importAlgorithm: { kind: 'rsa', hash, scheme }, verifyParams });\n}\n\n/** Validate that the public key OID is `ecPublicKey`, resolve the curve, and return an ECDSA verification config result. */\nexport function requireEcPublicKey(\n\talgorithmOid: string,\n\tparametersOid: string | undefined,\n\thash: string,\n\tcontext = 'issuer',\n): VerifySignatureConfigResult {\n\tif (algorithmOid !== OIDS.ecPublicKey) {\n\t\treturn unsupported('ECDSA', `requires EC ${context} public key`);\n\t}\n\tswitch (parametersOid) {\n\t\tcase OIDS.prime256v1:\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ecdsa', curve: 'P-256' },\n\t\t\t\tverifyParams: { name: 'ECDSA', hash },\n\t\t\t\tecdsaRawSignatureBytes: 64,\n\t\t\t});\n\t\tcase OIDS.secp384r1:\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ecdsa', curve: 'P-384' },\n\t\t\t\tverifyParams: { name: 'ECDSA', hash },\n\t\t\t\tecdsaRawSignatureBytes: 96,\n\t\t\t});\n\t\tcase OIDS.secp521r1:\n\t\t\treturn ok({\n\t\t\t\timportAlgorithm: { kind: 'ecdsa', curve: 'P-521' },\n\t\t\t\tverifyParams: { name: 'ECDSA', hash },\n\t\t\t\tecdsaRawSignatureBytes: 132,\n\t\t\t});\n\t\tdefault:\n\t\t\treturn unsupported('ECDSA', `unsupported EC curve OID: ${parametersOid ?? 'missing'}`);\n\t}\n}\n\n/** Return the raw ECDSA signature byte count (r + s) for a given curve OID, if supported. */\nexport function curveBytes(parametersOid: string | undefined): number | undefined {\n\tswitch (parametersOid) {\n\t\tcase OIDS.prime256v1:\n\t\t\treturn 64;\n\t\tcase OIDS.secp384r1:\n\t\t\treturn 96;\n\t\tcase OIDS.secp521r1:\n\t\t\treturn 132;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Verifies a signature against the signer's SPKI and the signed bytes. Returns\n * a typed {@linkcode VerifySignedDataResult} for unsupported algorithms and\n * runtime verification failures.\n *\n * Tries both DER and raw ECDSA encodings when the first attempt fails.\n *\n * @throws `limit_exceeded` on algorithm parameters or a public key that exceed\n * a micro509 decoding limit.\n */\nexport async function verifySignedDataDetailed(\n\tsignatureAlgorithmOid: string,\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tpublicKeyParametersOid: string | undefined,\n\tsubjectPublicKeyInfoDer: Uint8Array,\n\tsignature: Uint8Array,\n\tsignatureUnusedBits: number,\n\tsignedData: Uint8Array,\n\tcaller: CallerVerification = NO_CALLER_VERIFICATION,\n): Promise<VerifySignedDataResult> {\n\tconst config = getVerifySignatureConfigResult(\n\t\tsignatureAlgorithmOid,\n\t\tsignatureAlgorithmParametersDer,\n\t\tpublicKeyAlgorithmOid,\n\t\tpublicKeyParametersOid,\n\t);\n\tif (!config.ok) {\n\t\tconst verifier = caller.verifiers.get(signatureAlgorithmOid);\n\t\tif (verifier === undefined) {\n\t\t\treturn config;\n\t\t}\n\t\tconst signerParametersDer =\n\t\t\tcaller.workingParameters === undefined\n\t\t\t\t? explicitParameters(spkiAlgorithmParametersDer(subjectPublicKeyInfoDer))\n\t\t\t\t: caller.workingParameters.parametersDer;\n\t\treturn await runCallerVerifier(verifier, {\n\t\t\tsignatureAlgorithm: {\n\t\t\t\toid: signatureAlgorithmOid,\n\t\t\t\t...(signatureAlgorithmParametersDer === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { parametersDer: new Uint8Array(signatureAlgorithmParametersDer) }),\n\t\t\t},\n\t\t\tsignerSpkiDer: new Uint8Array(subjectPublicKeyInfoDer),\n\t\t\t...(signerParametersDer === undefined\n\t\t\t\t? {}\n\t\t\t\t: { signerPublicKeyParametersDer: new Uint8Array(signerParametersDer) }),\n\t\t\tsignature: new Uint8Array(signature),\n\t\t\tsignatureUnusedBits,\n\t\t\tdata: new Uint8Array(signedData),\n\t\t});\n\t}\n\tif (signatureUnusedBits !== 0) {\n\t\treturn { ok: true, valid: false };\n\t}\n\ttry {\n\t\tconst key = await importSpkiDerOrThrow(subjectPublicKeyInfoDer, config.value.importAlgorithm);\n\t\treturn await verifyWithConfiguredKey(key, config.value, signature, signedData, 'auto');\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\treturn verificationError(\n\t\t\terror instanceof Error ? error.message : 'signature verification failed',\n\t\t);\n\t}\n}\n\nasync function runCallerVerifier(\n\tverifier: SignatureVerifier,\n\tinput: SignatureVerifierInput,\n): Promise<VerifySignedDataResult> {\n\ttry {\n\t\treturn { ok: true, valid: (await verifier(input)) === true };\n\t} catch (error) {\n\t\treturn verificationError(\n\t\t\terror instanceof Error\n\t\t\t\t? `signature verifier failed: ${error.message}`\n\t\t\t\t: 'signature verifier failed',\n\t\t);\n\t}\n}\n\n/** Execute verification for imported SPKI and caller-owned keys with the same configuration. */\nasync function verifyWithConfiguredKey(\n\tkey: CryptoKey,\n\tconfig: VerifySignatureConfig,\n\tsignature: Uint8Array,\n\tsignedData: Uint8Array,\n\tencoding: 'auto' | 'raw' | 'der',\n): Promise<VerifySignedDataResult> {\n\ttry {\n\t\tif (encoding === 'der' && config.ecdsaRawSignatureBytes !== undefined) {\n\t\t\ttry {\n\t\t\t\tsignature = derEcdsaSignatureToRaw(signature, config.ecdsaRawSignatureBytes / 2);\n\t\t\t} catch (error) {\n\t\t\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\t\t\treturn { ok: true, valid: false };\n\t\t\t}\n\t\t}\n\t\tconst subtle = getCrypto().subtle;\n\t\tconst signatureView = toArrayBuffer(signature);\n\t\tconst dataView = toArrayBuffer(signedData);\n\t\tif (await subtle.verify(config.verifyParams, key, signatureView, dataView)) {\n\t\t\treturn { ok: true, valid: true };\n\t\t}\n\t\tif (encoding === 'auto' && config.ecdsaRawSignatureBytes !== undefined) {\n\t\t\tconst alternate = alternateEcdsaSignatureEncoding(\n\t\t\t\tsignature,\n\t\t\t\tconfig.ecdsaRawSignatureBytes / 2,\n\t\t\t);\n\t\t\tif (alternate !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tok: true,\n\t\t\t\t\tvalid: await subtle.verify(config.verifyParams, key, toArrayBuffer(alternate), dataView),\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn { ok: true, valid: false };\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\treturn verificationError(\n\t\t\terror instanceof Error ? error.message : 'signature verification failed',\n\t\t);\n\t}\n}\n\n/** Resolve a caller-owned key without exporting it, then run the shared verifier. */\nexport async function verifySignedDataWithKeyDetailed(\n\tkey: CryptoKey,\n\tsignatureAlgorithmOid: string,\n\tparametersDer: Uint8Array | undefined,\n\tsignature: Uint8Array,\n\tdata: Uint8Array,\n\tencoding: 'raw' | 'der',\n): Promise<VerifySignedDataResult> {\n\tif (key.type !== 'public' || !key.usages.includes('verify')) {\n\t\treturn verificationError('Signature verification requires a public key with verify usage');\n\t}\n\tconst algorithm = key.algorithm;\n\tlet oid: string;\n\tlet curveOid: string | undefined;\n\tswitch (algorithm.name) {\n\t\tcase 'RSASSA-PKCS1-v1_5':\n\t\tcase 'RSA-PSS':\n\t\t\toid = OIDS.rsaEncryption;\n\t\t\tbreak;\n\t\tcase 'ECDSA':\n\t\t\toid = OIDS.ecPublicKey;\n\t\t\tif ('namedCurve' in algorithm) {\n\t\t\t\tswitch (algorithm.namedCurve) {\n\t\t\t\t\tcase 'P-256':\n\t\t\t\t\t\tcurveOid = OIDS.prime256v1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'P-384':\n\t\t\t\t\t\tcurveOid = OIDS.secp384r1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'P-521':\n\t\t\t\t\t\tcurveOid = OIDS.secp521r1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'Ed25519':\n\t\t\toid = OIDS.ed25519;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn unsupported(algorithm.name, 'unsupported public key algorithm');\n\t}\n\tconst config = getVerifySignatureConfigResult(\n\t\tsignatureAlgorithmOid,\n\t\tparametersDer,\n\t\toid,\n\t\tcurveOid,\n\t);\n\tif (!config.ok) return config;\n\tif (encoding !== 'raw' && encoding !== 'der') {\n\t\treturn unsupported(signatureAlgorithmOid, 'signature encoding must be raw or der');\n\t}\n\tif (encoding === 'der' && config.value.ecdsaRawSignatureBytes === undefined) {\n\t\treturn unsupported(signatureAlgorithmOid, 'DER signature encoding requires ECDSA');\n\t}\n\tif (algorithm.name !== config.value.verifyParams.name) {\n\t\treturn unsupported(signatureAlgorithmOid, 'signature scheme does not match the public key');\n\t}\n\tif (config.value.importAlgorithm.kind === 'rsa') {\n\t\tif (\n\t\t\t!('hash' in algorithm) ||\n\t\t\ttypeof algorithm.hash !== 'object' ||\n\t\t\talgorithm.hash === null ||\n\t\t\t!('name' in algorithm.hash) ||\n\t\t\talgorithm.hash.name !== config.value.importAlgorithm.hash\n\t\t) {\n\t\t\treturn unsupported(signatureAlgorithmOid, 'signature hash does not match the RSA public key');\n\t\t}\n\t}\n\treturn await verifyWithConfiguredKey(key, config.value, signature, data, encoding);\n}\n\n/** Parse RSA-PSS algorithm parameters and build a verification config, or return failure. */\nfunction requireRsaPssVerifyConfig(\n\tsignatureAlgorithmParametersDer: Uint8Array | undefined,\n\tpublicKeyAlgorithmOid: string,\n\tcontext: string,\n): VerifySignatureConfigResult {\n\tconst parameters = parseRsaPssParameters(signatureAlgorithmParametersDer);\n\tif (!parameters.ok) {\n\t\treturn unsupported('RSA-PSS', parameters.reason);\n\t}\n\treturn requireRsaPublicKey(\n\t\tpublicKeyAlgorithmOid,\n\t\tparameters.value.hash,\n\t\t'pss',\n\t\tcontext,\n\t\tparameters.value.saltLength,\n\t);\n}\n\n/** RFC 4055 §5 requires generators to encode NULL and implementations to accept absent parameters too. */\nfunction requireDerNullOrAbsentSignatureAlgorithmParameters(\n\tparametersDer: Uint8Array | undefined,\n\talgorithm: string,\n): VerifySignatureConfigFailure | undefined {\n\tif (parametersDer === undefined) {\n\t\treturn undefined;\n\t}\n\tconst reason = 'signature AlgorithmIdentifier parameters must be DER NULL or absent';\n\ttry {\n\t\tconst element = readElement(parametersDer);\n\t\tif (element.tag !== 0x05 || element.length !== 0 || element.end !== parametersDer.length) {\n\t\t\treturn unsupported(algorithm, reason);\n\t\t}\n\t\treturn undefined;\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\treturn unsupported(algorithm, reason);\n\t}\n}\n\nfunction requireAbsentSignatureAlgorithmParameters(\n\tparametersDer: Uint8Array | undefined,\n\talgorithm: string,\n): VerifySignatureConfigFailure | undefined {\n\tif (parametersDer !== undefined) {\n\t\treturn unsupported(algorithm, 'signature AlgorithmIdentifier parameters must be absent');\n\t}\n\treturn undefined;\n}\n\n/** Wrap a config in a success result. */\nfunction ok(value: VerifySignatureConfig): VerifySignatureConfigSuccess {\n\treturn { ok: true, value };\n}\n\n/** Build an unsupported-algorithm failure result. */\nfunction unsupported(algorithm: string, reason: string): VerifySignatureConfigFailure {\n\treturn {\n\t\tok: false,\n\t\tcode: 'unsupported_signature_algorithm_parameters',\n\t\treason: `${algorithm} parameters unsupported: ${reason}`,\n\t};\n}\n\nfunction verificationError(reason: string): VerifySignedDataFailure {\n\treturn {\n\t\tok: false,\n\t\tcode: 'verification_error',\n\t\treason,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsEA,MAAMY,oBAAmD,IAAI,IAAI;CAChEN,EAAK;CACLA,EAAK;CACLA,EAAK;CACLA,EAAK;CACLA,EAAK;CACLA,EAAK;CACLA,EAAK;CACLA,EAAK;AACN,CAAC;;;;;;;AAQD,SAAgB,0BACfO,GACyC;CACzC,IAAMC,oBAAW,IAAI,IAA+B;CACpD,I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