micro509 0.18.0 → 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.
Files changed (99) hide show
  1. package/CHANGELOG.md +88 -1
  2. package/dist/crypto/crypto.d.ts +11 -2
  3. package/dist/crypto/crypto.js +30 -17
  4. package/dist/crypto/crypto.js.map +1 -1
  5. package/dist/crypto.d.ts +2 -2
  6. package/dist/der/der.js.map +1 -1
  7. package/dist/index.d.ts +6 -5
  8. package/dist/internal/asn1/asn1.js +10 -2
  9. package/dist/internal/asn1/asn1.js.map +1 -1
  10. package/dist/internal/asn1/ber.js.map +1 -1
  11. package/dist/internal/asn1/decode-refusal.js.map +1 -1
  12. package/dist/internal/asn1/der.js.map +1 -1
  13. package/dist/internal/asn1/oids.js.map +1 -1
  14. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  15. package/dist/internal/crypto/ecdsa.js.map +1 -1
  16. package/dist/internal/crypto/hash.js.map +1 -1
  17. package/dist/internal/crypto/pbes2.js.map +1 -1
  18. package/dist/internal/crypto/prime-ec.js.map +1 -1
  19. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  20. package/dist/internal/crypto/sig-verify.d.ts +40 -0
  21. package/dist/internal/crypto/sig-verify.js +152 -65
  22. package/dist/internal/crypto/sig-verify.js.map +1 -1
  23. package/dist/internal/crypto/signing.js.map +1 -1
  24. package/dist/internal/jose/base64url.js.map +1 -1
  25. package/dist/internal/jose/json-data.js.map +1 -1
  26. package/dist/internal/jose/strict-json.js.map +1 -1
  27. package/dist/internal/shared/base64.js.map +1 -1
  28. package/dist/internal/shared/dn.js.map +1 -1
  29. package/dist/internal/shared/idna.js.map +1 -1
  30. package/dist/internal/shared/ip.js.map +1 -1
  31. package/dist/internal/shared/mailbox.js.map +1 -1
  32. package/dist/internal/shared/punycode.js.map +1 -1
  33. package/dist/internal/shared/uri-host.js.map +1 -1
  34. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  35. package/dist/internal/verify/policy-engine.js.map +1 -1
  36. package/dist/internal/verify/spki-distrust.js.map +1 -1
  37. package/dist/internal/verify/verify-path.js +222 -116
  38. package/dist/internal/verify/verify-path.js.map +1 -1
  39. package/dist/internal/x509/directory-name.js.map +1 -1
  40. package/dist/internal/x509/extension-bits.js.map +1 -1
  41. package/dist/internal/x509/extension-errors.js.map +1 -1
  42. package/dist/internal/x509/extension-registry.js.map +1 -1
  43. package/dist/internal/x509/general-name-profile.js.map +1 -1
  44. package/dist/internal/x509/general-name.js.map +1 -1
  45. package/dist/internal/x509/name-fields.js.map +1 -1
  46. package/dist/internal/x509/or-address.js.map +1 -1
  47. package/dist/jose/base64url.js.map +1 -1
  48. package/dist/jose/errors.js.map +1 -1
  49. package/dist/jose/jwe.js.map +1 -1
  50. package/dist/jose/jwks.js.map +1 -1
  51. package/dist/jose/jws.js.map +1 -1
  52. package/dist/jose/jwt.js.map +1 -1
  53. package/dist/jose/remote-jwks.js.map +1 -1
  54. package/dist/kdf/argon2-arithmetic.js.map +1 -1
  55. package/dist/kdf/argon2-core.js.map +1 -1
  56. package/dist/kdf/argon2-memory.js.map +1 -1
  57. package/dist/kdf/argon2-portable.js.map +1 -1
  58. package/dist/kdf/argon2.js.map +1 -1
  59. package/dist/keys/keys.js.map +1 -1
  60. package/dist/pem/pem.js.map +1 -1
  61. package/dist/pkcs/pfx.js.map +1 -1
  62. package/dist/pkcs/pkcs12-mac.js +1 -1
  63. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  64. package/dist/pkcs/pkcs7.d.ts +10 -0
  65. package/dist/pkcs/pkcs7.js +106 -88
  66. package/dist/pkcs/pkcs7.js.map +1 -1
  67. package/dist/result/result.js.map +1 -1
  68. package/dist/revocation/chain.d.ts +67 -13
  69. package/dist/revocation/chain.js +429 -301
  70. package/dist/revocation/chain.js.map +1 -1
  71. package/dist/revocation/crl.d.ts +65 -11
  72. package/dist/revocation/crl.js +492 -202
  73. package/dist/revocation/crl.js.map +1 -1
  74. package/dist/revocation/ocsp.d.ts +79 -24
  75. package/dist/revocation/ocsp.js +417 -231
  76. package/dist/revocation/ocsp.js.map +1 -1
  77. package/dist/revocation/revocation.d.ts +68 -13
  78. package/dist/revocation/revocation.js +194 -73
  79. package/dist/revocation/revocation.js.map +1 -1
  80. package/dist/revocation.d.ts +4 -4
  81. package/dist/ssh/ssh.js.map +1 -1
  82. package/dist/ssh/wire.js.map +1 -1
  83. package/dist/verify/identity.d.ts +2 -2
  84. package/dist/verify/identity.js +2 -2
  85. package/dist/verify/identity.js.map +1 -1
  86. package/dist/verify/verify.d.ts +84 -32
  87. package/dist/verify/verify.js +221 -171
  88. package/dist/verify/verify.js.map +1 -1
  89. package/dist/verify.d.ts +3 -2
  90. package/dist/x509/certificate.js.map +1 -1
  91. package/dist/x509/csr.js.map +1 -1
  92. package/dist/x509/extensions.js.map +1 -1
  93. package/dist/x509/fingerprint.js.map +1 -1
  94. package/dist/x509/name-text.js.map +1 -1
  95. package/dist/x509/name.js.map +1 -1
  96. package/dist/x509/parse.d.ts +6 -2
  97. package/dist/x509/parse.js +121 -121
  98. package/dist/x509/parse.js.map +1 -1
  99. package/package.json +11 -11
@@ -1 +1 @@
1
- {"version":3,"file":"revocation.js","names":["REVOCATION_INDETERMINATE_REASON_CODES","parsedCertificate","certificate","uris","seen","accessDescription","uri","candidates","configuredByUri","configuredResponder","input","existing","evidence","checkedSources","entry","normalizedCertificate","error","ocspGoodResult","crlGoodResult","crlCoveredReasons","indeterminateEvidence","result","reason","unrecognizedReason","coversAllDistributionPointReasons","refusal","decodeRefusalOf","DECODE_REFUSAL_CODES","checkCertificateRevocationAgainstCrl","response","validateOcspResponse","matchedResponse","revocationReasonFromCode","parseCertificateDerOrThrow","parseCertificateFromSource","value"],"sources":["../../src/revocation/revocation.ts"],"sourcesContent":["/**\n * Revocation orchestration: evaluates CRL and OCSP evidence to produce a\n * unified `good`/`revoked`/`indeterminate` status for a certificate.\n *\n * @module\n */\n\nimport { DECODE_REFUSAL_CODES, decodeRefusalOf } from '#micro509/internal/asn1/decode-refusal';\nimport type { DecodeRefusalCode, Result } from '#micro509/result/result';\nimport { rethrowIfInvariant } from '#micro509/result/result';\nimport type {\n\tCrlApplicabilityFailureReason,\n\tCrlSource,\n\tParsedRevocationReason,\n\tUnrecognizedReasonCodePolicy,\n} from '#micro509/revocation/crl';\nimport {\n\tassertCrlMaxAge,\n\tcheckCertificateRevocationAgainstCrl,\n\tcoversAllDistributionPointReasons,\n\trevocationReasonFromCode,\n} from '#micro509/revocation/crl';\nimport type {\n\tOcspCertificateSource,\n\tOcspRequestSource,\n\tParsedOcspResponse,\n\tValidateOcspResponseInput,\n} from '#micro509/revocation/ocsp';\nimport { validateOcspResponse } from '#micro509/revocation/ocsp';\nimport type { DistributionPointReason } from '#micro509/x509/extensions';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificateDerOrThrow, parseCertificateFromSource } from '#micro509/x509/parse';\n\nexport type * from '#micro509/revocation/crl';\nexport type * from '#micro509/revocation/ocsp';\n\n/** Unified revocation outcome across CRL and OCSP evidence. */\nexport type RevocationStatus = 'good' | 'revoked' | 'indeterminate';\n\n/** Which revocation mechanism produced the evidence. */\nexport type RevocationEvidenceKind = 'crl' | 'ocsp';\n/** PEM string, DER bytes, or already-parsed certificate. */\nexport type RevocationCertificateSource = string | Uint8Array | ParsedCertificate;\n/** Where the OCSP responder URI came from. */\nexport type OcspResponderSource = 'configured' | 'authorityInfoAccess';\n/** PEM or DER bytes of a pre-configured OCSP responder certificate. */\nexport type ConfiguredOcspResponderCertificate = string | Uint8Array;\n\n/** A manually-configured OCSP responder endpoint. */\nexport interface ConfiguredOcspResponder {\n\t/** OCSP responder URI (typically `http://...`). */\n\treadonly uri: string;\n\t/** Known responder certificate — skips embedded-certificate discovery. */\n\treadonly responderCertificate?: ConfiguredOcspResponderCertificate;\n}\n\n/** One candidate OCSP responder resolved by {@linkcode resolveOcspResponderCandidates}. */\nexport interface OcspResponderCandidate {\n\t/** Whether this candidate came from configuration or the certificate's AIA extension. */\n\treadonly source: OcspResponderSource;\n\t/** OCSP responder URI. */\n\treadonly uri: string;\n\t/** Pre-known responder certificate, if available. */\n\treadonly responderCertificate?: ConfiguredOcspResponderCertificate;\n}\n\n/** Input for {@linkcode resolveOcspResponderCandidates}. */\nexport interface ResolveOcspResponderCandidatesInput {\n\t/** Certificate whose AIA extension will be inspected for OCSP URIs. */\n\treadonly certificate: RevocationCertificateSource;\n\t/** Manually-configured responders — checked before AIA-derived ones. */\n\treadonly configuredResponders?: readonly ConfiguredOcspResponder[];\n}\n\n/** CRL-based revocation evidence for {@linkcode CheckCertificateRevocationInput.evidence}. */\nexport interface RevocationCrlEvidenceInput {\n\t/** Discriminator for the CRL evidence variant. */\n\treadonly kind: 'crl';\n\t/** Complete (base) CRL. */\n\treadonly crl: CrlSource;\n\t/** Optional delta CRL for more recent revocation information. */\n\treadonly deltaCrl?: CrlSource;\n}\n\n/** OCSP-based revocation evidence for {@linkcode CheckCertificateRevocationInput.evidence}. */\nexport interface RevocationOcspEvidenceInput {\n\t/** Discriminator for the OCSP evidence variant. */\n\treadonly kind: 'ocsp';\n\t/** OCSP response to validate. */\n\treadonly response: string | Uint8Array | ParsedOcspResponse;\n\t/** Original OCSP request — enables nonce and coverage checks. */\n\treadonly request?: OcspRequestSource;\n\t/** Explicit responder certificate — overrides embedded certificate discovery. */\n\treadonly responderCertificate?: OcspCertificateSource;\n}\n\n/** Discriminated union of CRL and OCSP evidence inputs. */\nexport type RevocationEvidenceInput = RevocationCrlEvidenceInput | RevocationOcspEvidenceInput;\n\n/** Input for {@linkcode checkCertificateRevocation}. */\nexport interface CheckCertificateRevocationInput {\n\t/** Certificate whose revocation status to determine. */\n\treadonly certificate: RevocationCertificateSource;\n\t/** Issuer of `certificate`. */\n\treadonly issuerCertificate: RevocationCertificateSource;\n\t/** CRL and/or OCSP evidence to evaluate. Returns `indeterminate` if empty. */\n\treadonly evidence?: readonly RevocationEvidenceInput[];\n\t/** Evaluation time. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/** Clock-skew tolerance in milliseconds. It also widens `crlMaxAgeMs`. */\n\treadonly clockSkewMs?: number;\n\t/** Maximum age of each CRL's `thisUpdate` in milliseconds. Unbounded by default. See {@linkcode ValidateCertificateRevocationListInput.maxAgeMs}. */\n\treadonly crlMaxAgeMs?: number;\n\t/**\n\t * OCSP client profile for every OCSP evidence entry. See\n\t * {@linkcode ValidateOcspResponseInput.profile}. Defaults to `'rfc6960'`.\n\t */\n\treadonly ocspProfile?: ValidateOcspResponseInput['profile'];\n\t/**\n\t * Treatment of CRL or OCSP evidence whose CRLReason is unrecognized. See\n\t * {@linkcode UnrecognizedReasonCodePolicy}. `'reject'` turns that evidence\n\t * into `reason_code_unrecognized`, which also keeps other evidence from\n\t * settling the status as `good`. Defaults to `'revoked'`.\n\t */\n\treadonly unrecognizedReasonCode?: UnrecognizedReasonCodePolicy;\n}\n\n/** Error codes that {@linkcode checkCertificateRevocation} may surface inside an `indeterminate` result. */\nexport type CheckCertificateRevocationErrorCode =\n\t| 'revocation_evidence_missing'\n\t| 'revocation_status_indeterminate'\n\t| DecodeRefusalCode;\n\n/** Every {@linkcode RevocationIndeterminateReasonCode}, as a runtime array. */\nexport const REVOCATION_INDETERMINATE_REASON_CODES = [\n\t'certificate_status_missing',\n\t'certificate_status_unknown',\n\t'crl_sign_not_permitted',\n\t'issuer_mismatch',\n\t'next_update_missing',\n\t'non_applicable',\n\t'nonce_mismatch',\n\t'ocsp_signing_missing',\n\t'reason_code_unrecognized',\n\t'reason_coverage_incomplete',\n\t'request_mismatch',\n\t'responder_id_mismatch',\n\t'responder_chain_invalid',\n\t'responder_revoked',\n\t'responder_revocation_unknown',\n\t'response_status_invalid',\n\t'signature_invalid',\n\t'stale_crl',\n\t'stale_response',\n\t'unsupported',\n\t'limit_exceeded',\n] as const;\n\n/** Why a particular piece of evidence could not produce a definitive `good`/`revoked` answer. */\nexport type RevocationIndeterminateReasonCode =\n\t(typeof REVOCATION_INDETERMINATE_REASON_CODES)[number];\n\n/** One piece of evidence that failed to produce a definitive revocation answer. */\nexport interface RevocationIndeterminateEvidence {\n\t/** Whether this evidence was CRL or OCSP. */\n\treadonly kind: RevocationEvidenceKind;\n\t/** Machine-readable reason code. */\n\treadonly code: RevocationIndeterminateReasonCode;\n\t/** Human-readable explanation. */\n\treadonly message: string;\n\t/** CRL-specific applicability failure reason, when `kind` is `'crl'`. */\n\treadonly reason?: CrlApplicabilityFailureReason;\n}\n\n/** Diagnostic details attached to an `indeterminate` revocation result. */\nexport interface CheckCertificateRevocationFailureDetails {\n\t/** Which evidence kinds were attempted (`'crl'`, `'ocsp'`, or both). */\n\treadonly checkedSources: readonly RevocationEvidenceKind[];\n\t/** Per-evidence explanations of why no definitive answer was reached. */\n\treadonly indeterminateEvidence: readonly RevocationIndeterminateEvidence[];\n}\n\n/** Revocation status could not be determined from the provided evidence. */\nexport interface RevocationCheckIndeterminateValue {\n\t/** Status is indeterminate. */\n\treadonly status: Extract<RevocationStatus, 'indeterminate'>;\n\t/** Why revocation status is indeterminate. */\n\treadonly code: CheckCertificateRevocationErrorCode;\n\t/** Human-readable diagnostic message. */\n\treadonly message: string;\n\t/** What evidence was attempted and why each failed. */\n\treadonly details: CheckCertificateRevocationFailureDetails;\n}\n\n/** Certificate is not revoked according to the checked evidence. */\nexport interface RevocationCheckGoodValue {\n\t/** Certificate is not revoked. */\n\treadonly status: Extract<RevocationStatus, 'good'>;\n\t/** Which evidence kind confirmed the good status. */\n\treadonly kind: RevocationEvidenceKind;\n\t/** Human-readable diagnostic message. */\n\treadonly message: string;\n}\n\n/** Certificate is revoked according to the checked evidence. */\nexport interface RevocationCheckRevokedValue {\n\t/** Certificate is revoked. */\n\treadonly status: Extract<RevocationStatus, 'revoked'>;\n\t/** Which evidence kind reported the revocation. */\n\treadonly kind: RevocationEvidenceKind;\n\t/** Human-readable diagnostic message. */\n\treadonly message: string;\n\t/** When the certificate was revoked (from CRL entry or OCSP response). */\n\treadonly revokedAt?: Date;\n\t/** CRL reason (from CRL evidence). */\n\treadonly revocationReason?: ParsedRevocationReason;\n\t/** CRL reason code (from OCSP evidence). */\n\treadonly revocationReasonCode?: bigint;\n}\n\n/** Discriminated union of `good`, `revoked`, and `indeterminate` revocation outcomes. */\nexport type CheckCertificateRevocationValue =\n\t| RevocationCheckGoodValue\n\t| RevocationCheckRevokedValue\n\t| RevocationCheckIndeterminateValue;\n\n/**\n * Result of {@linkcode checkCertificateRevocation}. Always succeeds (`ok: true`) —\n * the `value.status` discriminator carries the actual outcome.\n */\nexport type CheckCertificateRevocationResult = Result<CheckCertificateRevocationValue, never>;\n\n/** Internal intermediate result from evaluating a single piece of revocation evidence. */\ntype RevocationEvidenceCheck =\n\t| {\n\t\t\treadonly status: 'good';\n\t\t\treadonly result: RevocationCheckGoodValue;\n\t\t\t/** RFC 5280 §6.3.3(d) reasons this CRL covered; absent for OCSP (which is definitive). */\n\t\t\treadonly coveredReasons?: readonly DistributionPointReason[];\n\t }\n\t| { readonly status: 'revoked'; readonly result: RevocationCheckRevokedValue }\n\t| { readonly status: 'indeterminate'; readonly detail: RevocationIndeterminateEvidence };\n\n/** Extracts OCSP responder URIs from the certificate's Authority Information Access extension. */\nexport function getCertificateOcspResponderUris(\n\tcertificate: RevocationCertificateSource,\n): readonly string[] {\n\tlet parsedCertificate: ParsedCertificate;\n\ttry {\n\t\tparsedCertificate = normalizeCertificate(certificate);\n\t} catch {\n\t\treturn [];\n\t}\n\tconst uris: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const accessDescription of parsedCertificate.authorityInfoAccess ?? []) {\n\t\tif (accessDescription.method !== 'ocsp' || accessDescription.location.type !== 'uri') {\n\t\t\tcontinue;\n\t\t}\n\t\tconst uri = accessDescription.location.value;\n\t\tif (seen.has(uri)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(uri);\n\t\turis.push(uri);\n\t}\n\treturn uris;\n}\n\n/**\n * Merges configured OCSP responders with those discovered from the certificate's\n * AIA extension. Configured responders take priority; duplicates are deduplicated by URI.\n */\nexport function resolveOcspResponderCandidates(\n\tinput: ResolveOcspResponderCandidatesInput,\n): readonly OcspResponderCandidate[] {\n\tconst candidates: OcspResponderCandidate[] = [];\n\tconst configuredByUri = new Map<string, ConfiguredOcspResponder>();\n\tfor (const configuredResponder of input.configuredResponders ?? []) {\n\t\tconst existing = configuredByUri.get(configuredResponder.uri);\n\t\tif (\n\t\t\texisting === undefined ||\n\t\t\t(existing.responderCertificate === undefined &&\n\t\t\t\tconfiguredResponder.responderCertificate !== undefined)\n\t\t) {\n\t\t\tconfiguredByUri.set(configuredResponder.uri, configuredResponder);\n\t\t}\n\t}\n\tconst seen = new Set<string>();\n\tfor (const configuredResponder of configuredByUri.values()) {\n\t\tseen.add(configuredResponder.uri);\n\t\tcandidates.push({\n\t\t\tsource: 'configured',\n\t\t\turi: configuredResponder.uri,\n\t\t\t...(configuredResponder.responderCertificate === undefined\n\t\t\t\t? {}\n\t\t\t\t: { responderCertificate: configuredResponder.responderCertificate }),\n\t\t});\n\t}\n\tfor (const uri of getCertificateOcspResponderUris(input.certificate)) {\n\t\tif (seen.has(uri)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(uri);\n\t\tcandidates.push({\n\t\t\tsource: 'authorityInfoAccess',\n\t\t\turi,\n\t\t});\n\t}\n\treturn candidates;\n}\n\n/**\n * Evaluates all provided CRL and OCSP evidence to determine the certificate's\n * revocation status. Returns the first `revoked` if any, else the first `good`,\n * else `indeterminate` with diagnostic details about each indeterminate evidence.\n *\n * @example\n * ```ts\n * import { checkCertificateRevocation } from 'micro509';\n *\n * const result = await checkCertificateRevocation({\n * certificate: leafPem,\n * issuerCertificate: caPem,\n * evidence: [{ kind: 'crl', crl: crlPem }],\n * });\n * if (result.ok && result.value.status === 'revoked') {\n * console.log('revoked at', result.value.revokedAt);\n * }\n * ```\n */\nexport async function checkCertificateRevocation(\n\tinput: CheckCertificateRevocationInput,\n): Promise<CheckCertificateRevocationResult> {\n\tassertCrlMaxAge(input.crlMaxAgeMs);\n\tconst evidence = input.evidence ?? [];\n\tconst checkedSources = evidence.map((entry) => entry.kind);\n\tif (evidence.length === 0) {\n\t\treturn revocationSuccess({\n\t\t\tstatus: 'indeterminate',\n\t\t\tcode: 'revocation_evidence_missing',\n\t\t\tmessage: 'No CRL or OCSP evidence provided',\n\t\t\tdetails: {\n\t\t\t\tcheckedSources,\n\t\t\t\tindeterminateEvidence: [],\n\t\t\t},\n\t\t});\n\t}\n\tlet normalizedCertificate: ParsedCertificate;\n\ttry {\n\t\tnormalizedCertificate = normalizeCertificate(input.certificate);\n\t} catch (error) {\n\t\treturn undecodableCertificateResult(error, checkedSources);\n\t}\n\tlet ocspGoodResult: RevocationCheckGoodValue | undefined;\n\tlet crlGoodResult: RevocationCheckGoodValue | undefined;\n\tconst crlCoveredReasons = new Set<string>();\n\tconst indeterminateEvidence: RevocationIndeterminateEvidence[] = [];\n\tfor (const entry of evidence) {\n\t\tconst result = await checkRevocationEvidenceEntry(input, entry, normalizedCertificate);\n\t\tif (result.status === 'revoked') {\n\t\t\treturn revocationSuccess(result.result);\n\t\t}\n\t\tif (result.status === 'good') {\n\t\t\tif (result.coveredReasons === undefined) {\n\t\t\t\tocspGoodResult ??= result.result;\n\t\t\t} else {\n\t\t\t\tcrlGoodResult ??= result.result;\n\t\t\t\tfor (const reason of result.coveredReasons) {\n\t\t\t\t\tcrlCoveredReasons.add(reason);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tindeterminateEvidence.push(result.detail);\n\t}\n\treturn settleRevocationEvidence(\n\t\tocspGoodResult,\n\t\tcrlGoodResult,\n\t\tcrlCoveredReasons,\n\t\tindeterminateEvidence,\n\t\tcheckedSources,\n\t);\n}\n\n/** The result once no evidence revoked the certificate outright. */\nfunction settleRevocationEvidence(\n\tocspGoodResult: RevocationCheckGoodValue | undefined,\n\tcrlGoodResult: RevocationCheckGoodValue | undefined,\n\tcrlCoveredReasons: Set<string>,\n\tindeterminateEvidence: RevocationIndeterminateEvidence[],\n\tcheckedSources: readonly RevocationEvidenceKind[],\n): CheckCertificateRevocationResult {\n\tconst unrecognizedReason = indeterminateEvidence.some(\n\t\t(entry) => entry.code === 'reason_code_unrecognized',\n\t);\n\t// An OCSP good is per-certificate and definitive. A CRL good is definitive\n\t// only once the applicable CRLs together cover every revocation reason.\n\tif (ocspGoodResult !== undefined && !unrecognizedReason) {\n\t\treturn revocationSuccess(ocspGoodResult);\n\t}\n\tif (\n\t\tcrlGoodResult !== undefined &&\n\t\t!unrecognizedReason &&\n\t\tcoversAllDistributionPointReasons(crlCoveredReasons)\n\t) {\n\t\treturn revocationSuccess(crlGoodResult);\n\t}\n\tif (crlGoodResult !== undefined && !coversAllDistributionPointReasons(crlCoveredReasons)) {\n\t\tindeterminateEvidence.push({\n\t\t\tkind: 'crl',\n\t\t\tcode: 'reason_coverage_incomplete',\n\t\t\tmessage: 'CRL evidence covers only some revocation reasons',\n\t\t});\n\t}\n\treturn revocationSuccess({\n\t\tstatus: 'indeterminate',\n\t\tcode: 'revocation_status_indeterminate',\n\t\tmessage: 'No revocation evidence established certificate status',\n\t\tdetails: {\n\t\t\tcheckedSources,\n\t\t\tindeterminateEvidence,\n\t\t},\n\t});\n}\n\nfunction undecodableCertificateResult(\n\terror: unknown,\n\tcheckedSources: readonly RevocationEvidenceKind[],\n): CheckCertificateRevocationResult {\n\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\treturn revocationSuccess({\n\t\tstatus: 'indeterminate',\n\t\tcode: refusal?.code ?? 'revocation_status_indeterminate',\n\t\tmessage: refusal?.message ?? 'Certificate input is malformed',\n\t\tdetails: {\n\t\t\tcheckedSources,\n\t\t\tindeterminateEvidence: [],\n\t\t},\n\t});\n}\n\nasync function checkRevocationEvidenceEntry(\n\tinput: CheckCertificateRevocationInput,\n\tevidence: RevocationEvidenceInput,\n\tcertificate: ParsedCertificate,\n): Promise<RevocationEvidenceCheck> {\n\ttry {\n\t\treturn evidence.kind === 'crl'\n\t\t\t? await checkCertificateRevocationWithCrl(input, evidence, certificate)\n\t\t\t: await checkCertificateRevocationWithOcsp(input, evidence, certificate);\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn {\n\t\t\tstatus: 'indeterminate',\n\t\t\tdetail: {\n\t\t\t\tkind: evidence.kind,\n\t\t\t\tcode: refusal?.code ?? 'signature_invalid',\n\t\t\t\tmessage: refusal?.message ?? `${evidence.kind.toUpperCase()} evidence input is malformed`,\n\t\t\t},\n\t\t};\n\t}\n}\n\n/** Evaluates a single CRL evidence entry via {@linkcode checkCertificateRevocationAgainstCrl}. */\nasync function checkCertificateRevocationWithCrl(\n\tinput: CheckCertificateRevocationInput,\n\tevidence: RevocationCrlEvidenceInput,\n\tcertificate: ParsedCertificate,\n): Promise<RevocationEvidenceCheck> {\n\tconst result = await checkCertificateRevocationAgainstCrl({\n\t\tcertificate,\n\t\tissuerCertificate: input.issuerCertificate,\n\t\tcrl: evidence.crl,\n\t\t...(evidence.deltaCrl === undefined ? {} : { deltaCrl: evidence.deltaCrl }),\n\t\t...(input.at === undefined ? {} : { at: input.at }),\n\t\t...(input.clockSkewMs === undefined ? {} : { clockSkewMs: input.clockSkewMs }),\n\t\t...(input.crlMaxAgeMs === undefined ? {} : { maxAgeMs: input.crlMaxAgeMs }),\n\t\t...(input.unrecognizedReasonCode === undefined\n\t\t\t? {}\n\t\t\t: { unrecognizedReasonCode: input.unrecognizedReasonCode }),\n\t});\n\tif (result.ok) {\n\t\tif (result.value.status === 'revoked') {\n\t\t\treturn {\n\t\t\t\tstatus: 'revoked',\n\t\t\t\tresult: {\n\t\t\t\t\tstatus: 'revoked',\n\t\t\t\t\tkind: 'crl',\n\t\t\t\t\tmessage: 'Certificate is revoked according to CRL evidence',\n\t\t\t\t\trevokedAt: result.value.revocationDate,\n\t\t\t\t\t...(result.value.reasonCode === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { revocationReason: result.value.reasonCode }),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tstatus: 'good',\n\t\t\tresult: {\n\t\t\t\tstatus: 'good',\n\t\t\t\tkind: 'crl',\n\t\t\t\tmessage: 'Certificate is not revoked according to CRL evidence',\n\t\t\t},\n\t\t\tcoveredReasons: result.value.coveredReasons,\n\t\t};\n\t}\n\treturn {\n\t\tstatus: 'indeterminate',\n\t\tdetail: {\n\t\t\tkind: 'crl',\n\t\t\tcode: result.code,\n\t\t\tmessage: result.message,\n\t\t\t...(result.details?.reason === undefined ? {} : { reason: result.details.reason }),\n\t\t},\n\t};\n}\n\n/** Evaluates a single OCSP evidence entry via {@linkcode validateOcspResponse}. */\nasync function checkCertificateRevocationWithOcsp(\n\tinput: CheckCertificateRevocationInput,\n\tevidence: RevocationOcspEvidenceInput,\n\tcertificate: ParsedCertificate,\n): Promise<RevocationEvidenceCheck> {\n\tconst response = await validateOcspResponse({\n\t\tresponse: evidence.response,\n\t\tissuerCertificate: input.issuerCertificate,\n\t\t...(evidence.request === undefined ? {} : { request: evidence.request }),\n\t\t...(evidence.responderCertificate === undefined\n\t\t\t? {}\n\t\t\t: { responderCertificate: evidence.responderCertificate }),\n\t\t...(input.at === undefined ? {} : { at: input.at }),\n\t\t...(input.clockSkewMs === undefined ? {} : { clockSkewMs: input.clockSkewMs }),\n\t\t...(input.ocspProfile === undefined ? {} : { profile: input.ocspProfile }),\n\t});\n\tif (!response.ok) {\n\t\treturn {\n\t\t\tstatus: 'indeterminate',\n\t\t\tdetail: {\n\t\t\t\tkind: 'ocsp',\n\t\t\t\tcode: response.code,\n\t\t\t\tmessage: response.message,\n\t\t\t},\n\t\t};\n\t}\n\tconst matchedResponse = response.value.responses?.find(\n\t\t(entry) =>\n\t\t\tnormalizeHex(entry.certId.serialNumberHex) === normalizeHex(certificate.serialNumberHex),\n\t);\n\tif (matchedResponse === undefined) {\n\t\treturn {\n\t\t\tstatus: 'indeterminate',\n\t\t\tdetail: {\n\t\t\t\tkind: 'ocsp',\n\t\t\t\tcode: 'certificate_status_missing',\n\t\t\t\tmessage: 'OCSP response does not include certificate status for the target certificate',\n\t\t\t},\n\t\t};\n\t}\n\tif (matchedResponse.certStatus === 'revoked') {\n\t\tif (\n\t\t\tinput.unrecognizedReasonCode === 'reject' &&\n\t\t\ttypeof revocationReasonFromCode(matchedResponse.revocationReasonCode) === 'object'\n\t\t) {\n\t\t\treturn {\n\t\t\t\tstatus: 'indeterminate',\n\t\t\t\tdetail: {\n\t\t\t\t\tkind: 'ocsp',\n\t\t\t\t\tcode: 'reason_code_unrecognized',\n\t\t\t\t\tmessage: `OCSP response carries unrecognized reason code ${String(matchedResponse.revocationReasonCode)}`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tstatus: 'revoked',\n\t\t\tresult: {\n\t\t\t\tstatus: 'revoked',\n\t\t\t\tkind: 'ocsp',\n\t\t\t\tmessage: 'Certificate is revoked according to OCSP evidence',\n\t\t\t\t...(matchedResponse.revokedAt === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { revokedAt: matchedResponse.revokedAt }),\n\t\t\t\t...(matchedResponse.revocationReasonCode === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { revocationReasonCode: matchedResponse.revocationReasonCode }),\n\t\t\t},\n\t\t};\n\t}\n\tif (matchedResponse.certStatus === 'good') {\n\t\treturn {\n\t\t\tstatus: 'good',\n\t\t\tresult: {\n\t\t\t\tstatus: 'good',\n\t\t\t\tkind: 'ocsp',\n\t\t\t\tmessage: 'Certificate is not revoked according to OCSP evidence',\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\tstatus: 'indeterminate',\n\t\tdetail: {\n\t\t\tkind: 'ocsp',\n\t\t\tcode: 'certificate_status_unknown',\n\t\t\tmessage: 'OCSP responder returned certificate status unknown',\n\t\t},\n\t};\n}\n\n/** Accepts PEM, DER, or already-parsed certificate and returns a parsed certificate. */\nfunction normalizeCertificate(certificate: RevocationCertificateSource): ParsedCertificate {\n\treturn hasParsedCertificateShape(certificate)\n\t\t? parseCertificateDerOrThrow(new Uint8Array(certificate.der))\n\t\t: parseCertificateFromSource(certificate);\n}\n\nfunction hasParsedCertificateShape(value: RevocationCertificateSource): value is ParsedCertificate {\n\treturn typeof value !== 'string' && 'subjectPublicKeyInfoDer' in value;\n}\n\n/** Lowercases a hex string for bytewise serial-number comparison. */\nfunction normalizeHex(value: string): string {\n\treturn value.toLowerCase();\n}\n\n/** Wraps a value into a successful `CheckCertificateRevocationResult`. */\nfunction revocationSuccess(\n\tvalue: CheckCertificateRevocationValue,\n): CheckCertificateRevocationResult {\n\treturn { ok: true, value };\n}\n"],"mappings":";;;;;;;;;;;;;AAsIA,MAAaA,IAAwC;CACpD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;AAwFA,SAAgB,gCACf,GACoB;CACpB,IAAIC;CACJ,IAAI;EACH,IAAoB,qBAAqBC,CAAW;CACrD,QAAQ;EACP,OAAO,CAAC;CACT;CACA,IAAMC,IAAiB,CAAC,GAClBC,oBAAO,IAAI,IAAY;CAC7B,KAAK,IAAMC,KAAqBJ,EAAkB,uBAAuB,CAAC,GAAG;EAC5E,IAAII,EAAkB,WAAW,UAAUA,EAAkB,SAAS,SAAS,OAC9E;EAED,IAAMC,IAAMD,EAAkB,SAAS;EACvC,AAAID,EAAK,IAAIE,CAAG,MAGhBF,EAAK,IAAIE,CAAG,GACZH,EAAK,KAAKG,CAAG;CACd;CACA,OAAOH;AACR;;;;;AAMA,SAAgB,+BACf,GACoC;CACpC,IAAMI,IAAuC,CAAC,GACxCC,oBAAkB,IAAI,IAAqC;CACjE,KAAK,IAAMC,KAAuBC,EAAM,wBAAwB,CAAC,GAAG;EACnE,IAAMC,IAAWH,EAAgB,I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EACV;CACD,IAEM;EACN,QAAQ;EACR,QAAQ;GACP,MAAM;GACN,MAAM;GACN,SAAS;EACV;CACD;AACD;;AAGA,SAAS,qBAAqB,GAA6D;CAC1F,OAAO,0BAA0B7B,CAAW,IACzC+B,EAA2B,IAAI,WAAW/B,EAAY,GAAG,CAAC,IAC1DgC,EAA2BhC,CAAW;AAC1C;AAEA,SAAS,0BAA0B,GAAgE;CAClG,OAAO,OAAOiC,KAAU,YAAY,6BAA6BA;AAClE;;AAGA,SAAS,aAAa,GAAuB;CAC5C,OAAOA,EAAM,YAAY;AAC1B;;AAGA,SAAS,kBACR,GACmC;CACnC,OAAO;EAAE,IAAI;EAAM;CAAM;AAC1B"}
1
+ {"version":3,"file":"revocation.js","names":["decodeRefusalOf","callerVerification","resolveSignatureVerifiers","DECODE_REFUSAL_CODES","rethrowIfInvariant","assertClockSkew","assertCrlMaxAge","checkCertificateRevocationAgainstCrlsBy","coversAllDistributionPointReasons","distinctSignedCrls","normalizeCrl","revocationReasonFromCode","signedCrlKey","validateOcspResponseWith","parseCertificateDerOrThrow","parseCertificateFromSource","REVOCATION_INDETERMINATE_REASON_CODES","certificate","parsedCertificate","uris","seen","accessDescription","uri","input","candidates","configuredByUri","configuredResponder","existing","callerInput","evidence","checkedSources","entry","normalizedCertificate","error","ocspGoodResult","crlGoodResult","crlCoveredReasons","indeterminateEvidence","result","reason","unrecognizedReason","refusal","parsed","deltaCrls","crl","budget","checkedCompleteCrls","checks","index","entryChecks","completeCrl","check","checked","key","kind","source","outcome","response","matchedResponse","value"],"sources":["../../src/revocation/revocation.ts"],"sourcesContent":["/**\n * Revocation orchestration: evaluates CRL and OCSP evidence to produce a\n * unified `good`/`revoked`/`indeterminate` status for a certificate.\n *\n * @module\n */\n\nimport { DECODE_REFUSAL_CODES, decodeRefusalOf } from '#micro509/internal/asn1/decode-refusal';\nimport type { SignatureVerifiers } from '#micro509/internal/crypto/sig-verify';\nimport {\n\tcallerVerification,\n\tresolveSignatureVerifiers,\n} from '#micro509/internal/crypto/sig-verify';\nimport type { DecodeFailureCode, Result } from '#micro509/result/result';\nimport { rethrowIfInvariant } from '#micro509/result/result';\nimport type {\n\tCheckCertificateRevocationAgainstCrlResult,\n\tCrlApplicabilityFailureReason,\n\tCrlSource,\n\tDeltaCrlBudget,\n\tParsedCertificateRevocationList,\n\tParsedRevocationReason,\n\tSupersededDeltaCrlPolicy,\n\tUnrecognizedReasonCodePolicy,\n} from '#micro509/revocation/crl';\nimport {\n\tassertClockSkew,\n\tassertCrlMaxAge,\n\tcheckCertificateRevocationAgainstCrlsBy,\n\tcoversAllDistributionPointReasons,\n\tDELTA_CRL_ATTEMPTS_PER_CALL,\n\tdistinctSignedCrls,\n\tnormalizeCrl,\n\trevocationReasonFromCode,\n\tsignedCrlKey,\n} from '#micro509/revocation/crl';\nimport type {\n\tOcspCertificateSource,\n\tOcspRequestSource,\n\tOcspResponderRevocationPolicy,\n\tParsedOcspResponse,\n\tRevocationSkipReason,\n\tValidateOcspResponseInput,\n} from '#micro509/revocation/ocsp';\nimport { validateOcspResponseWith } from '#micro509/revocation/ocsp';\nimport type { DistributionPointReason } from '#micro509/x509/extensions';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificateDerOrThrow, parseCertificateFromSource } from '#micro509/x509/parse';\n\nexport type * from '#micro509/revocation/crl';\nexport type * from '#micro509/revocation/ocsp';\n\n/** Unified revocation outcome across CRL and OCSP evidence. */\nexport type RevocationStatus = 'good' | 'revoked' | 'indeterminate' | 'skipped';\n\n/** Which revocation mechanism produced the evidence. */\nexport type RevocationEvidenceKind = 'crl' | 'ocsp';\n/** PEM string, DER bytes, or already-parsed certificate. */\nexport type RevocationCertificateSource = string | Uint8Array | ParsedCertificate;\n/** Where the OCSP responder URI came from. */\nexport type OcspResponderSource = 'configured' | 'authorityInfoAccess';\n/** PEM or DER bytes of a pre-configured OCSP responder certificate. */\nexport type ConfiguredOcspResponderCertificate = string | Uint8Array;\n\n/** A manually-configured OCSP responder endpoint. */\nexport interface ConfiguredOcspResponder {\n\t/** OCSP responder URI (typically `http://...`). */\n\treadonly uri: string;\n\t/** Known responder certificate — skips embedded-certificate discovery. */\n\treadonly responderCertificate?: ConfiguredOcspResponderCertificate;\n}\n\n/** One candidate OCSP responder resolved by {@linkcode resolveOcspResponderCandidates}. */\nexport interface OcspResponderCandidate {\n\t/** Whether this candidate came from configuration or the certificate's AIA extension. */\n\treadonly source: OcspResponderSource;\n\t/** OCSP responder URI. */\n\treadonly uri: string;\n\t/** Pre-known responder certificate, if available. */\n\treadonly responderCertificate?: ConfiguredOcspResponderCertificate;\n}\n\n/** Input for {@linkcode resolveOcspResponderCandidates}. */\nexport interface ResolveOcspResponderCandidatesInput {\n\t/** Certificate whose AIA extension will be inspected for OCSP URIs. */\n\treadonly certificate: RevocationCertificateSource;\n\t/** Manually-configured responders — checked before AIA-derived ones. */\n\treadonly configuredResponders?: readonly ConfiguredOcspResponder[];\n}\n\n/** CRL-based revocation evidence for {@linkcode CheckCertificateRevocationInput.evidence}. */\nexport interface RevocationCrlEvidenceInput {\n\t/** Discriminator for the CRL evidence variant. */\n\treadonly kind: 'crl';\n\t/** Complete (base) CRL. */\n\treadonly crl: CrlSource;\n\t/** Optional delta CRL for more recent revocation information. */\n\treadonly deltaCrl?: CrlSource;\n}\n\n/** OCSP-based revocation evidence for {@linkcode CheckCertificateRevocationInput.evidence}. */\nexport interface RevocationOcspEvidenceInput {\n\t/** Discriminator for the OCSP evidence variant. */\n\treadonly kind: 'ocsp';\n\t/** OCSP response to validate. */\n\treadonly response: string | Uint8Array | ParsedOcspResponse;\n\t/** Original OCSP request — enables nonce and coverage checks. */\n\treadonly request?: OcspRequestSource;\n\t/** Explicit responder certificate — overrides embedded certificate discovery. */\n\treadonly responderCertificate?: OcspCertificateSource;\n}\n\n/** Discriminated union of CRL and OCSP evidence inputs. */\nexport type RevocationEvidenceInput = RevocationCrlEvidenceInput | RevocationOcspEvidenceInput;\n\n/** Input for {@linkcode checkCertificateRevocation}. */\nexport interface CheckCertificateRevocationInput {\n\t/** Certificate whose revocation status to determine. */\n\treadonly certificate: RevocationCertificateSource;\n\t/** Issuer of `certificate`. */\n\treadonly issuerCertificate: RevocationCertificateSource;\n\t/** CRL and/or OCSP evidence to evaluate. Returns `indeterminate` if empty. */\n\treadonly evidence?: readonly RevocationEvidenceInput[];\n\t/** Evaluation time. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/**\n\t * Clock-skew tolerance in milliseconds. It also widens `crlMaxAgeMs`.\n\t * Throws `RangeError` when negative or not finite.\n\t */\n\treadonly clockSkewMs?: number;\n\t/** Maximum age of each CRL's `thisUpdate` in milliseconds. Unbounded by default. See {@linkcode ValidateCertificateRevocationListInput.maxAgeMs}. */\n\treadonly crlMaxAgeMs?: number;\n\t/**\n\t * OCSP client profile for every OCSP evidence entry. See\n\t * {@linkcode ValidateOcspResponseInput.profile}. Defaults to `'rfc6960'`.\n\t */\n\treadonly ocspProfile?: ValidateOcspResponseInput['profile'];\n\t/**\n\t * Revocation policy for delegated OCSP responders. The CRLs in `evidence`,\n\t * delta CRLs included, serve as their revocation evidence. See\n\t * {@linkcode OcspResponderRevocationPolicy}. Defaults to\n\t * `'nocheck-or-evidence'`.\n\t */\n\treadonly ocspResponderRevocation?: OcspResponderRevocationPolicy;\n\t/**\n\t * Treatment of CRL or OCSP evidence whose CRLReason is unrecognized. See\n\t * {@linkcode UnrecognizedReasonCodePolicy}. `'reject'` turns that evidence\n\t * into `reason_code_unrecognized`, which also keeps other evidence from\n\t * settling the status as `good`. Defaults to `'revoked'`.\n\t */\n\treadonly unrecognizedReasonCode?: UnrecognizedReasonCodePolicy;\n\t/**\n\t * Treatment of delta CRLs in `evidence` that the attempt limits leave unread\n\t * although one already read supersedes them, for the certificate and its\n\t * delegated OCSP responders. See {@linkcode SupersededDeltaCrlPolicy}.\n\t * Defaults to `'indeterminate'`.\n\t */\n\treadonly unreadSupersededDeltaCrls?: SupersededDeltaCrlPolicy;\n\t/**\n\t * Caller verifiers for signature algorithms micro509 does not verify through\n\t * WebCrypto, keyed by dotted-decimal signature algorithm OID, for the CRL and\n\t * OCSP evidence. A key that micro509 verifies natively, a key that is no OID,\n\t * or a value that is no function throws `RangeError`.\n\t */\n\treadonly signatureVerifiers?: SignatureVerifiers;\n}\n\n/** Error codes that {@linkcode checkCertificateRevocation} may surface inside an `indeterminate` result. */\nexport type CheckCertificateRevocationErrorCode =\n\t| 'revocation_evidence_missing'\n\t| 'revocation_status_indeterminate'\n\t| DecodeFailureCode;\n\n/** Every {@linkcode RevocationIndeterminateReasonCode}, as a runtime array. */\nexport const REVOCATION_INDETERMINATE_REASON_CODES = [\n\t'certificate_status_missing',\n\t'certificate_status_unknown',\n\t'crl_sign_not_permitted',\n\t'delta_crl_retry_limit_exceeded',\n\t'delta_crl_unusable',\n\t'issuer_mismatch',\n\t'malformed',\n\t'next_update_missing',\n\t'non_applicable',\n\t'nonce_mismatch',\n\t'ocsp_signing_missing',\n\t'reason_code_unrecognized',\n\t'reason_coverage_incomplete',\n\t'request_mismatch',\n\t'responder_id_mismatch',\n\t'responder_chain_invalid',\n\t'responder_revoked',\n\t'responder_revocation_unknown',\n\t'response_status_invalid',\n\t'signature_invalid',\n\t'stale_crl',\n\t'stale_response',\n\t'unsupported',\n\t'limit_exceeded',\n] as const;\n\n/** Why a particular piece of evidence could not produce a definitive `good`/`revoked` answer. */\nexport type RevocationIndeterminateReasonCode =\n\t(typeof REVOCATION_INDETERMINATE_REASON_CODES)[number];\n\n/** One piece of evidence that failed to produce a definitive revocation answer. */\nexport interface RevocationIndeterminateEvidence {\n\t/** Whether this evidence was CRL or OCSP. */\n\treadonly kind: RevocationEvidenceKind;\n\t/** Machine-readable reason code. */\n\treadonly code: RevocationIndeterminateReasonCode;\n\t/** Human-readable explanation. */\n\treadonly message: string;\n\t/** CRL-specific applicability failure reason, when `kind` is `'crl'`. */\n\treadonly reason?: CrlApplicabilityFailureReason;\n}\n\n/** Diagnostic details attached to an `indeterminate` revocation result. */\nexport interface CheckCertificateRevocationFailureDetails {\n\t/** Which evidence kinds were attempted (`'crl'`, `'ocsp'`, or both). */\n\treadonly checkedSources: readonly RevocationEvidenceKind[];\n\t/** Per-evidence explanations of why no definitive answer was reached. */\n\treadonly indeterminateEvidence: readonly RevocationIndeterminateEvidence[];\n}\n\n/** Revocation status could not be determined from the provided evidence. */\nexport interface RevocationCheckIndeterminateValue {\n\t/** Status is indeterminate. */\n\treadonly status: Extract<RevocationStatus, 'indeterminate'>;\n\t/** Why revocation status is indeterminate. */\n\treadonly code: CheckCertificateRevocationErrorCode;\n\t/** Human-readable diagnostic message. */\n\treadonly message: string;\n\t/** What evidence was attempted and why each failed. */\n\treadonly details: CheckCertificateRevocationFailureDetails;\n}\n\n/** Certificate is not revoked according to the checked evidence. */\nexport interface RevocationCheckGoodValue {\n\t/** Certificate is not revoked. */\n\treadonly status: Extract<RevocationStatus, 'good'>;\n\t/** Which evidence kind confirmed the good status. */\n\treadonly kind: RevocationEvidenceKind;\n\t/** Human-readable diagnostic message. */\n\treadonly message: string;\n}\n\n/** Certificate is revoked according to the checked evidence. */\nexport interface RevocationCheckRevokedValue {\n\t/** Certificate is revoked. */\n\treadonly status: Extract<RevocationStatus, 'revoked'>;\n\t/** Which evidence kind reported the revocation. */\n\treadonly kind: RevocationEvidenceKind;\n\t/** Human-readable diagnostic message. */\n\treadonly message: string;\n\t/** When the certificate was revoked (from CRL entry or OCSP response). */\n\treadonly revokedAt?: Date;\n\t/** CRL reason (from CRL evidence). */\n\treadonly revocationReason?: ParsedRevocationReason;\n\t/** CRL reason code (from OCSP evidence). */\n\treadonly revocationReasonCode?: bigint;\n}\n\n/**\n * The certificate carries noRevAvail, so no evidence was consulted (RFC 9608\n * §4). A CRL never lists such a certificate (RFC 9608 §2), so its absence from\n * one shows nothing.\n */\nexport interface RevocationCheckSkippedValue {\n\t/** Status is skipped. */\n\treadonly status: Extract<RevocationStatus, 'skipped'>;\n\t/** The extension that exempts the certificate. */\n\treadonly skipReason: Extract<RevocationSkipReason, 'no_rev_avail'>;\n\t/** Human-readable diagnostic message. */\n\treadonly message: string;\n}\n\n/** Discriminated union of `good`, `revoked`, `indeterminate`, and `skipped` revocation outcomes. */\nexport type CheckCertificateRevocationValue =\n\t| RevocationCheckGoodValue\n\t| RevocationCheckRevokedValue\n\t| RevocationCheckIndeterminateValue\n\t| RevocationCheckSkippedValue;\n\n/**\n * Result of {@linkcode checkCertificateRevocation}. Always succeeds (`ok: true`) —\n * the `value.status` discriminator carries the actual outcome.\n */\nexport type CheckCertificateRevocationResult = Result<CheckCertificateRevocationValue, never>;\n\n/** Internal intermediate result from evaluating a single piece of revocation evidence. */\ntype RevocationEvidenceCheck =\n\t| {\n\t\t\treadonly status: 'good';\n\t\t\treadonly result: RevocationCheckGoodValue;\n\t\t\t/** RFC 5280 §6.3.3(d) reasons this CRL covered; absent for OCSP (which is definitive). */\n\t\t\treadonly coveredReasons?: readonly DistributionPointReason[];\n\t }\n\t| { readonly status: 'revoked'; readonly result: RevocationCheckRevokedValue }\n\t| { readonly status: 'indeterminate'; readonly detail: RevocationIndeterminateEvidence };\n\n/** Extracts OCSP responder URIs from the certificate's Authority Information Access extension. */\nexport function getCertificateOcspResponderUris(\n\tcertificate: RevocationCertificateSource,\n): readonly string[] {\n\tlet parsedCertificate: ParsedCertificate;\n\ttry {\n\t\tparsedCertificate = normalizeCertificate(certificate);\n\t} catch {\n\t\treturn [];\n\t}\n\tconst uris: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const accessDescription of parsedCertificate.authorityInfoAccess ?? []) {\n\t\tif (accessDescription.method !== 'ocsp' || accessDescription.location.type !== 'uri') {\n\t\t\tcontinue;\n\t\t}\n\t\tconst uri = accessDescription.location.value;\n\t\tif (seen.has(uri)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(uri);\n\t\turis.push(uri);\n\t}\n\treturn uris;\n}\n\n/**\n * Merges configured OCSP responders with those discovered from the certificate's\n * AIA extension. Configured responders take priority; duplicates are deduplicated by URI.\n */\nexport function resolveOcspResponderCandidates(\n\tinput: ResolveOcspResponderCandidatesInput,\n): readonly OcspResponderCandidate[] {\n\tconst candidates: OcspResponderCandidate[] = [];\n\tconst configuredByUri = new Map<string, ConfiguredOcspResponder>();\n\tfor (const configuredResponder of input.configuredResponders ?? []) {\n\t\tconst existing = configuredByUri.get(configuredResponder.uri);\n\t\tif (\n\t\t\texisting === undefined ||\n\t\t\t(existing.responderCertificate === undefined &&\n\t\t\t\tconfiguredResponder.responderCertificate !== undefined)\n\t\t) {\n\t\t\tconfiguredByUri.set(configuredResponder.uri, configuredResponder);\n\t\t}\n\t}\n\tconst seen = new Set<string>();\n\tfor (const configuredResponder of configuredByUri.values()) {\n\t\tseen.add(configuredResponder.uri);\n\t\tcandidates.push({\n\t\t\tsource: 'configured',\n\t\t\turi: configuredResponder.uri,\n\t\t\t...(configuredResponder.responderCertificate === undefined\n\t\t\t\t? {}\n\t\t\t\t: { responderCertificate: configuredResponder.responderCertificate }),\n\t\t});\n\t}\n\tfor (const uri of getCertificateOcspResponderUris(input.certificate)) {\n\t\tif (seen.has(uri)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(uri);\n\t\tcandidates.push({\n\t\t\tsource: 'authorityInfoAccess',\n\t\t\turi,\n\t\t});\n\t}\n\treturn candidates;\n}\n\n/**\n * Evaluates all provided CRL and OCSP evidence to determine the certificate's\n * revocation status. Returns the first `revoked` if any. Otherwise an OCSP\n * `good` settles the status, then a CRL `good` once the CRLs together cover\n * every revocation reason, else `indeterminate` with diagnostic details about\n * each indeterminate evidence.\n * Each CRL in `evidence` counts as a delta CRL when it carries the delta CRL\n * indicator and as a complete CRL otherwise, whichever field holds it. Each\n * distinct complete CRL is checked once, updated by the newest delta CRL\n * among them that applies to it, as `checkChainRevocation` does, within the\n * same attempt limits, which the CRL checks of delegated OCSP responders\n * share. A delta CRL that cannot settle the status records\n * `delta_crl_unusable` in `details.indeterminateEvidence`, and a candidate\n * the limits leave unread that counts under `unreadSupersededDeltaCrls`\n * records `delta_crl_retry_limit_exceeded` there; either keeps other evidence\n * from settling the status as `good`. Unless other evidence revokes the\n * certificate, the result is then `indeterminate` with the top-level code\n * `revocation_status_indeterminate`.\n * A certificate carrying noRevAvail is `skipped` without consulting evidence\n * (RFC 9608 §4). One carrying id-pkix-ocsp-nocheck is still checked against\n * the evidence, which may list it as revoked.\n *\n * @example\n * ```ts\n * import { checkCertificateRevocation } from 'micro509';\n *\n * const result = await checkCertificateRevocation({\n * certificate: leafPem,\n * issuerCertificate: caPem,\n * evidence: [{ kind: 'crl', crl: crlPem }],\n * });\n * if (result.ok && result.value.status === 'revoked') {\n * console.log('revoked at', result.value.revokedAt);\n * }\n * ```\n */\nexport async function checkCertificateRevocation(\n\tcallerInput: CheckCertificateRevocationInput,\n): Promise<CheckCertificateRevocationResult> {\n\tconst input = { ...callerInput, at: callerInput.at ?? new Date() };\n\tassertCrlMaxAge(input.crlMaxAgeMs);\n\tassertClockSkew(input.clockSkewMs);\n\tresolveSignatureVerifiers(input.signatureVerifiers);\n\tconst evidence = input.evidence ?? [];\n\tconst checkedSources = evidence.map((entry) => entry.kind);\n\tif (carriesNoRevAvail(input.certificate)) {\n\t\treturn revocationSuccess({\n\t\t\tstatus: 'skipped',\n\t\t\tskipReason: 'no_rev_avail',\n\t\t\tmessage: 'Certificate carries noRevAvail, so no revocation evidence applies',\n\t\t});\n\t}\n\tif (evidence.length === 0) {\n\t\treturn revocationSuccess({\n\t\t\tstatus: 'indeterminate',\n\t\t\tcode: 'revocation_evidence_missing',\n\t\t\tmessage: 'No CRL or OCSP evidence provided',\n\t\t\tdetails: {\n\t\t\t\tcheckedSources,\n\t\t\t\tindeterminateEvidence: [],\n\t\t\t},\n\t\t});\n\t}\n\tlet normalizedCertificate: ParsedCertificate;\n\ttry {\n\t\tnormalizedCertificate = normalizeCertificate(input.certificate);\n\t} catch (error) {\n\t\treturn undecodableCertificateResult(error, checkedSources);\n\t}\n\tlet ocspGoodResult: RevocationCheckGoodValue | undefined;\n\tlet crlGoodResult: RevocationCheckGoodValue | undefined;\n\tconst crlCoveredReasons = new Set<string>();\n\tconst indeterminateEvidence: RevocationIndeterminateEvidence[] = [];\n\tfor (const result of await checkRevocationEvidence(input, evidence, normalizedCertificate)) {\n\t\tif (result.status === 'revoked') {\n\t\t\treturn revocationSuccess(result.result);\n\t\t}\n\t\tif (result.status === 'good') {\n\t\t\tif (result.coveredReasons === undefined) {\n\t\t\t\tocspGoodResult ??= result.result;\n\t\t\t} else {\n\t\t\t\tcrlGoodResult ??= result.result;\n\t\t\t\tfor (const reason of result.coveredReasons) {\n\t\t\t\t\tcrlCoveredReasons.add(reason);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tindeterminateEvidence.push(result.detail);\n\t}\n\treturn settleRevocationEvidence(\n\t\tocspGoodResult,\n\t\tcrlGoodResult,\n\t\tcrlCoveredReasons,\n\t\tindeterminateEvidence,\n\t\tcheckedSources,\n\t);\n}\n\n/** The result once no evidence revoked the certificate outright. */\nfunction settleRevocationEvidence(\n\tocspGoodResult: RevocationCheckGoodValue | undefined,\n\tcrlGoodResult: RevocationCheckGoodValue | undefined,\n\tcrlCoveredReasons: Set<string>,\n\tindeterminateEvidence: RevocationIndeterminateEvidence[],\n\tcheckedSources: readonly RevocationEvidenceKind[],\n): CheckCertificateRevocationResult {\n\tconst unrecognizedReason = indeterminateEvidence.some(\n\t\t(entry) =>\n\t\t\tentry.code === 'reason_code_unrecognized' ||\n\t\t\tentry.code === 'delta_crl_unusable' ||\n\t\t\tentry.code === 'delta_crl_retry_limit_exceeded',\n\t);\n\t// An OCSP good is per-certificate and definitive. A CRL good is definitive\n\t// only once the applicable CRLs together cover every revocation reason.\n\tif (ocspGoodResult !== undefined && !unrecognizedReason) {\n\t\treturn revocationSuccess(ocspGoodResult);\n\t}\n\tif (\n\t\tcrlGoodResult !== undefined &&\n\t\t!unrecognizedReason &&\n\t\tcoversAllDistributionPointReasons(crlCoveredReasons)\n\t) {\n\t\treturn revocationSuccess(crlGoodResult);\n\t}\n\tif (crlGoodResult !== undefined && !coversAllDistributionPointReasons(crlCoveredReasons)) {\n\t\tindeterminateEvidence.push({\n\t\t\tkind: 'crl',\n\t\t\tcode: 'reason_coverage_incomplete',\n\t\t\tmessage: 'CRL evidence covers only some revocation reasons',\n\t\t});\n\t}\n\treturn revocationSuccess({\n\t\tstatus: 'indeterminate',\n\t\tcode: 'revocation_status_indeterminate',\n\t\tmessage: 'No revocation evidence established certificate status',\n\t\tdetails: {\n\t\t\tcheckedSources,\n\t\t\tindeterminateEvidence,\n\t\t},\n\t});\n}\n\nfunction undecodableCertificateResult(\n\terror: unknown,\n\tcheckedSources: readonly RevocationEvidenceKind[],\n): CheckCertificateRevocationResult {\n\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\treturn revocationSuccess({\n\t\tstatus: 'indeterminate',\n\t\tcode: refusal?.code ?? 'malformed',\n\t\tmessage: refusal?.message ?? 'Certificate input is malformed',\n\t\tdetails: {\n\t\t\tcheckedSources,\n\t\t\tindeterminateEvidence: [],\n\t\t},\n\t});\n}\n\n/** The checks of `evidence` in order, up to the first that revokes `certificate`. */\nasync function checkRevocationEvidence(\n\tinput: CheckCertificateRevocationInput,\n\tevidence: readonly RevocationEvidenceInput[],\n\tcertificate: ParsedCertificate,\n): Promise<readonly RevocationEvidenceCheck[]> {\n\tconst parsed = evidence.map((entry) =>\n\t\tentry.kind === 'crl' ? parseCrlEvidence(entry) : undefined,\n\t);\n\tconst deltaCrls = distinctSignedCrls(\n\t\tparsed.flatMap((entry) =>\n\t\t\t[entry?.crl, entry?.deltaCrl].flatMap((crl) =>\n\t\t\t\tcrl?.kind === 'parsed' && crl.crl.baseCrlNumber !== undefined ? [crl.crl] : [],\n\t\t\t),\n\t\t),\n\t);\n\tconst budget: DeltaCrlBudget = { remaining: DELTA_CRL_ATTEMPTS_PER_CALL };\n\tconst checkedCompleteCrls = new Set<string>();\n\tconst checks: RevocationEvidenceCheck[] = [];\n\tfor (const [index, entry] of evidence.entries()) {\n\t\tconst entryChecks =\n\t\t\tentry.kind === 'ocsp'\n\t\t\t\t? [await checkCertificateRevocationWithOcsp(input, entry, certificate, budget)]\n\t\t\t\t: await checkCrlEvidenceEntry(parsed[index], checkedCompleteCrls, (completeCrl) =>\n\t\t\t\t\t\tcheckCertificateRevocationWithCrl(input, completeCrl, deltaCrls, certificate, budget),\n\t\t\t\t\t);\n\t\tchecks.push(...entryChecks);\n\t\tif (entryChecks.some((check) => check.status === 'revoked')) return checks;\n\t}\n\treturn checks;\n}\n\n/**\n * The checks of one CRL evidence entry: its CRLs that do not decode, then\n * `check` on each complete CRL not in `checked`, up to the first that revokes.\n */\nasync function checkCrlEvidenceEntry(\n\tentry: ReturnType<typeof parseCrlEvidence> | undefined,\n\tchecked: Set<string>,\n\tcheck: (completeCrl: ParsedCertificateRevocationList) => Promise<RevocationEvidenceCheck>,\n): Promise<readonly RevocationEvidenceCheck[]> {\n\tif (entry === undefined) return [];\n\tconst checks = [entry.deltaCrl, entry.crl].flatMap((crl) =>\n\t\tcrl?.kind === 'indeterminate' ? [crl.check] : [],\n\t);\n\tfor (const completeCrl of completeCrlsOf(entry)) {\n\t\tconst key = signedCrlKey(completeCrl);\n\t\tif (checked.has(key)) continue;\n\t\tchecked.add(key);\n\t\tconst result = await check(completeCrl);\n\t\tchecks.push(result);\n\t\tif (result.status === 'revoked') break;\n\t}\n\treturn checks;\n}\n\n/**\n * The CRLs of one evidence entry to check as complete CRLs: its `crl`, and\n * its `deltaCrl` when that carries no delta CRL indicator. A delta CRL in\n * `crl` is still checked, which reports it as no complete CRL.\n */\nfunction completeCrlsOf(\n\tentry: ReturnType<typeof parseCrlEvidence>,\n): readonly ParsedCertificateRevocationList[] {\n\treturn [\n\t\t...(entry.crl.kind === 'parsed' ? [entry.crl.crl] : []),\n\t\t...(entry.deltaCrl?.kind === 'parsed' && entry.deltaCrl.crl.baseCrlNumber === undefined\n\t\t\t? [entry.deltaCrl.crl]\n\t\t\t: []),\n\t];\n}\n\nfunction undecodableEvidence(\n\tkind: RevocationEvidenceKind,\n\terror: unknown,\n): RevocationEvidenceCheck {\n\trethrowIfInvariant(error);\n\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\treturn {\n\t\tstatus: 'indeterminate',\n\t\tdetail: {\n\t\t\tkind,\n\t\t\tcode: refusal?.code ?? 'malformed',\n\t\t\tmessage: refusal?.message ?? `${kind.toUpperCase()} evidence input is malformed`,\n\t\t},\n\t};\n}\n\n/** One CRL that decoded, or why it does not. */\ntype ParsedCrlEvidence =\n\t| { readonly kind: 'parsed'; readonly crl: ParsedCertificateRevocationList }\n\t| { readonly kind: 'indeterminate'; readonly check: RevocationEvidenceCheck };\n\n/** A CRL evidence entry's complete and delta CRLs, each decoded on its own. */\nfunction parseCrlEvidence(entry: RevocationCrlEvidenceInput): {\n\treadonly crl: ParsedCrlEvidence;\n\treadonly deltaCrl: ParsedCrlEvidence | undefined;\n} {\n\treturn {\n\t\tcrl: parseOneCrl(entry.crl),\n\t\tdeltaCrl: entry.deltaCrl === undefined ? undefined : parseOneCrl(entry.deltaCrl),\n\t};\n}\n\nfunction parseOneCrl(source: CrlSource): ParsedCrlEvidence {\n\ttry {\n\t\treturn { kind: 'parsed', crl: normalizeCrl(source) };\n\t} catch (error) {\n\t\treturn { kind: 'indeterminate', check: undecodableEvidence('crl', error) };\n\t}\n}\n\n/**\n * Checks one complete CRL from `evidence`, updated by the newest delta CRL\n * among every delta CRL in `evidence` that applies to it, as chain revocation\n * does. A delta CRL that cannot settle the status yields `delta_crl_unusable`.\n */\nasync function checkCertificateRevocationWithCrl(\n\tinput: CheckCertificateRevocationInput,\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tdeltaCrls: readonly ParsedCertificateRevocationList[],\n\tcertificate: ParsedCertificate,\n\tbudget: DeltaCrlBudget,\n): Promise<RevocationEvidenceCheck> {\n\tconst outcome = await checkCertificateRevocationAgainstCrlsBy(\n\t\tcertificate,\n\t\tcompleteCrl,\n\t\tdeltaCrls,\n\t\t{ kind: 'certificate', certificate: input.issuerCertificate },\n\t\t{\n\t\t\t...(input.at === undefined ? {} : { at: input.at }),\n\t\t\t...(input.clockSkewMs === undefined ? {} : { clockSkewMs: input.clockSkewMs }),\n\t\t\t...(input.crlMaxAgeMs === undefined ? {} : { maxAgeMs: input.crlMaxAgeMs }),\n\t\t\t...(input.unrecognizedReasonCode === undefined\n\t\t\t\t? {}\n\t\t\t\t: { unrecognizedReasonCode: input.unrecognizedReasonCode }),\n\t\t\t...(input.unreadSupersededDeltaCrls === undefined\n\t\t\t\t? {}\n\t\t\t\t: { unreadSupersededDeltaCrls: input.unreadSupersededDeltaCrls }),\n\t\t},\n\t\tcallerVerification(input.signatureVerifiers),\n\t\t[budget],\n\t);\n\tif (outcome.kind === 'checked') return crlEvidenceCheck(outcome.result);\n\treturn {\n\t\tstatus: 'indeterminate',\n\t\tdetail:\n\t\t\toutcome.reason === 'retry_limit'\n\t\t\t\t? {\n\t\t\t\t\t\tkind: 'crl',\n\t\t\t\t\t\tcode: 'delta_crl_retry_limit_exceeded',\n\t\t\t\t\t\tmessage: 'A delta CRL candidate remained unread after the attempt limit',\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tkind: 'crl',\n\t\t\t\t\t\tcode: 'delta_crl_unusable',\n\t\t\t\t\t\tmessage: 'An applicable delta CRL could not settle the certificate status',\n\t\t\t\t\t},\n\t};\n}\n\n/** The evidence check for one CRL result. */\nfunction crlEvidenceCheck(\n\tresult: CheckCertificateRevocationAgainstCrlResult,\n): RevocationEvidenceCheck {\n\tif (result.ok) {\n\t\tif (result.value.status === 'revoked') {\n\t\t\treturn {\n\t\t\t\tstatus: 'revoked',\n\t\t\t\tresult: {\n\t\t\t\t\tstatus: 'revoked',\n\t\t\t\t\tkind: 'crl',\n\t\t\t\t\tmessage: 'Certificate is revoked according to CRL evidence',\n\t\t\t\t\trevokedAt: result.value.revocationDate,\n\t\t\t\t\t...(result.value.reasonCode === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { revocationReason: result.value.reasonCode }),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tstatus: 'good',\n\t\t\tresult: {\n\t\t\t\tstatus: 'good',\n\t\t\t\tkind: 'crl',\n\t\t\t\tmessage: 'Certificate is not revoked according to CRL evidence',\n\t\t\t},\n\t\t\tcoveredReasons: result.value.coveredReasons,\n\t\t};\n\t}\n\treturn {\n\t\tstatus: 'indeterminate',\n\t\tdetail: {\n\t\t\tkind: 'crl',\n\t\t\tcode: result.code,\n\t\t\tmessage: result.message,\n\t\t\t...(result.details?.reason === undefined ? {} : { reason: result.details.reason }),\n\t\t},\n\t};\n}\n\n/** The {@linkcode validateOcspResponseWith} input for one OCSP evidence entry. */\nfunction ocspEvidenceValidationInput(\n\tinput: CheckCertificateRevocationInput,\n\tevidence: RevocationOcspEvidenceInput,\n): ValidateOcspResponseInput {\n\treturn {\n\t\tresponse: evidence.response,\n\t\tissuerCertificate: input.issuerCertificate,\n\t\t...(evidence.request === undefined ? {} : { request: evidence.request }),\n\t\t...(evidence.responderCertificate === undefined\n\t\t\t? {}\n\t\t\t: { responderCertificate: evidence.responderCertificate }),\n\t\t...(input.at === undefined ? {} : { at: input.at }),\n\t\t...(input.clockSkewMs === undefined ? {} : { clockSkewMs: input.clockSkewMs }),\n\t\t...(input.ocspProfile === undefined ? {} : { profile: input.ocspProfile }),\n\t\t...(input.ocspResponderRevocation === undefined\n\t\t\t? {}\n\t\t\t: { responderRevocationPolicy: input.ocspResponderRevocation }),\n\t\tresponderRevocationCrls: (input.evidence ?? []).flatMap((entry) =>\n\t\t\tentry.kind !== 'crl'\n\t\t\t\t? []\n\t\t\t\t: entry.deltaCrl === undefined\n\t\t\t\t\t? [entry.crl]\n\t\t\t\t\t: [entry.crl, entry.deltaCrl],\n\t\t),\n\t\t...(input.crlMaxAgeMs === undefined\n\t\t\t? {}\n\t\t\t: { responderRevocationCrlMaxAgeMs: input.crlMaxAgeMs }),\n\t\t...(input.unrecognizedReasonCode === undefined\n\t\t\t? {}\n\t\t\t: { responderRevocationUnrecognizedReasonCode: input.unrecognizedReasonCode }),\n\t\t...(input.unreadSupersededDeltaCrls === undefined\n\t\t\t? {}\n\t\t\t: { responderRevocationUnreadSupersededDeltaCrls: input.unreadSupersededDeltaCrls }),\n\t\t...(input.signatureVerifiers === undefined\n\t\t\t? {}\n\t\t\t: { signatureVerifiers: input.signatureVerifiers }),\n\t};\n}\n\n/**\n * Evaluates a single OCSP evidence entry via {@linkcode validateOcspResponseWith},\n * spending delta CRL checks of a delegated responder from `budget`.\n */\nasync function checkCertificateRevocationWithOcsp(\n\tinput: CheckCertificateRevocationInput,\n\tevidence: RevocationOcspEvidenceInput,\n\tcertificate: ParsedCertificate,\n\tbudget: DeltaCrlBudget,\n): Promise<RevocationEvidenceCheck> {\n\tconst response = await validateOcspResponseWith(ocspEvidenceValidationInput(input, evidence), {\n\t\tverifiers: resolveSignatureVerifiers(input.signatureVerifiers),\n\t\tdeltaBudget: budget,\n\t});\n\tif (!response.ok) {\n\t\treturn {\n\t\t\tstatus: 'indeterminate',\n\t\t\tdetail: {\n\t\t\t\tkind: 'ocsp',\n\t\t\t\tcode: response.code,\n\t\t\t\tmessage: response.message,\n\t\t\t},\n\t\t};\n\t}\n\tconst matchedResponse = response.value.responses?.find(\n\t\t(entry) =>\n\t\t\tnormalizeHex(entry.certId.serialNumberHex) === normalizeHex(certificate.serialNumberHex),\n\t);\n\tif (matchedResponse === undefined) {\n\t\treturn {\n\t\t\tstatus: 'indeterminate',\n\t\t\tdetail: {\n\t\t\t\tkind: 'ocsp',\n\t\t\t\tcode: 'certificate_status_missing',\n\t\t\t\tmessage: 'OCSP response does not include certificate status for the target certificate',\n\t\t\t},\n\t\t};\n\t}\n\tif (matchedResponse.certStatus === 'revoked') {\n\t\tif (\n\t\t\tinput.unrecognizedReasonCode === 'reject' &&\n\t\t\ttypeof revocationReasonFromCode(matchedResponse.revocationReasonCode) === 'object'\n\t\t) {\n\t\t\treturn {\n\t\t\t\tstatus: 'indeterminate',\n\t\t\t\tdetail: {\n\t\t\t\t\tkind: 'ocsp',\n\t\t\t\t\tcode: 'reason_code_unrecognized',\n\t\t\t\t\tmessage: `OCSP response carries unrecognized reason code ${String(matchedResponse.revocationReasonCode)}`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tstatus: 'revoked',\n\t\t\tresult: {\n\t\t\t\tstatus: 'revoked',\n\t\t\t\tkind: 'ocsp',\n\t\t\t\tmessage: 'Certificate is revoked according to OCSP evidence',\n\t\t\t\t...(matchedResponse.revokedAt === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { revokedAt: matchedResponse.revokedAt }),\n\t\t\t\t...(matchedResponse.revocationReasonCode === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { revocationReasonCode: matchedResponse.revocationReasonCode }),\n\t\t\t},\n\t\t};\n\t}\n\tif (matchedResponse.certStatus === 'good') {\n\t\treturn {\n\t\t\tstatus: 'good',\n\t\t\tresult: {\n\t\t\t\tstatus: 'good',\n\t\t\t\tkind: 'ocsp',\n\t\t\t\tmessage: 'Certificate is not revoked according to OCSP evidence',\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\tstatus: 'indeterminate',\n\t\tdetail: {\n\t\t\tkind: 'ocsp',\n\t\t\tcode: 'certificate_status_unknown',\n\t\t\tmessage: 'OCSP responder returned certificate status unknown',\n\t\t},\n\t};\n}\n\n/** Accepts PEM, DER, or already-parsed certificate and returns a parsed certificate. */\nfunction normalizeCertificate(certificate: RevocationCertificateSource): ParsedCertificate {\n\treturn hasParsedCertificateShape(certificate)\n\t\t? parseCertificateDerOrThrow(new Uint8Array(certificate.der))\n\t\t: parseCertificateFromSource(certificate);\n}\n\n/** Whether `source` parses and carries noRevAvail in its signed DER. */\nfunction carriesNoRevAvail(source: RevocationCertificateSource): boolean {\n\ttry {\n\t\treturn normalizeCertificate(source).noRevAvail === true;\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn false;\n\t}\n}\n\nfunction hasParsedCertificateShape(value: RevocationCertificateSource): value is ParsedCertificate {\n\treturn typeof value !== 'string' && 'subjectPublicKeyInfoDer' in value;\n}\n\n/** Lowercases a hex string for bytewise serial-number comparison. */\nfunction normalizeHex(value: string): string {\n\treturn value.toLowerCase();\n}\n\n/** Wraps a value into a successful `CheckCertificateRevocationResult`. */\nfunction revocationSuccess(\n\tvalue: CheckCertificateRevocationValue,\n): CheckCertificateRevocationResult {\n\treturn { ok: true, value };\n}\n"],"mappings":";;;;;;;;;;;;;;AA8KA,MAAagB,IAAwC;CACpD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;AAuGA,SAAgB,gCACfC,GACoB;CACpB,IAAIC;CACJ,IAAI;EACHA,IAAoB,qBAAqBD,CAAW;CACrD,QAAQ;EACP,OAAO,CAAC;CACT;CACA,IAAME,IAAiB,CAAC,GAClBC,oBAAO,IAAI,IAAY;CAC7B,KAAK,IAAMC,KAAqBH,EAAkB,uBAAuB,CAAC,GAAG;EAC5E,IAAIG,EAAkB,WAAW,UAAUA,EAAkB,SAAS,SAAS,OAC9E;EAED,IAAMC,IAAMD,EAAkB,SAAS;EACnCD,EAAK,IAAIE,CAAG,MAGhBF,EAAK,IAAIE,CAAG,GACZH,EAAK,KAAKG,CAAG;CACd;CACA,OAAOH;AACR;;;;;AAMA,SAAgB,+BACfI,GACoC;CACpC,IAAMC,IAAuC,CAAC,GACxCC,oBAAkB,IAAI,IAAqC;CACjE,KAAK,IAAMC,KAAuBH,EAAM,wBAAwB,CAAC,GAAG;EACnE,IAAMI,IAAWF,EAAgB,IAAIC,EAAoB,GAAG;EAC5D,CACCC,MAAa,KAAA,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ificateRevocationStatus, CheckChainRevocationInput, CheckChainRevocationResult, CheckChainRevocationValue, OcspResponseSource, REVOCATION_INDETERMINATE_REASONS, RevocationExecutionError, RevocationIndeterminateReason, RevocationParseError, RevocationPolicy, RevocationProcessingError, RevocationSource, TrustedOcspResponder, checkChainRevocation } from "./revocation/chain.js";
11
- import { CertificateRevocationListMaterial, CheckCertificateRevocationAgainstCrlErrorCode, CheckCertificateRevocationAgainstCrlFailure, CheckCertificateRevocationAgainstCrlFailureDetails, CheckCertificateRevocationAgainstCrlGoodValue, CheckCertificateRevocationAgainstCrlInput, CheckCertificateRevocationAgainstCrlResult, CheckCertificateRevocationAgainstCrlRevokedValue, CheckCertificateRevocationAgainstCrlValue, CreateCertificateRevocationListInput, CrlApplicabilityFailureReason, CrlCertificateSource, CrlEncoderErrorCode, CrlSource, ParseCertificateRevocationListErrorCode, ParseCertificateRevocationListFailure, ParseCertificateRevocationListResult, ParsedCertificateRevocationList, ParsedRevocationReason, ParsedRevokedCertificate, RevocationReason, RevokedCertificateInput, UnrecognizedReasonCodePolicy, UnrecognizedRevocationReason, ValidateCertificateRevocationListFailure, ValidateCertificateRevocationListInput, ValidateCertificateRevocationListResult, VerifyCertificateRevocationListSignatureFailure, VerifyCertificateRevocationListSignatureResult, checkCertificateRevocationAgainstCrl, createCertificateRevocationList, isCertificateRevoked, parseCertificateRevocationListDer, parseCertificateRevocationListDerOrThrow, parseCertificateRevocationListPem, parseCertificateRevocationListPemOrThrow, revocationReasonFromCode, validateCertificateRevocationList, verifyCertificateRevocationListSignature } from "./revocation/crl.js";
12
- import { CreateOcspCertStatusInput, CreateOcspRequestInput, CreateOcspRequestItemInput, CreateOcspResponseInput, CreateOcspSingleResponseInput, OcspCertStatus, OcspCertificateSource, OcspEncoderErrorCode, OcspHashAlgorithm, OcspRequestMaterial, OcspRequestSource, OcspResponderRevocationPolicy, OcspResponseMaterial, OcspResponseStatus, ParseOcspRequestErrorCode, ParseOcspRequestFailure, ParseOcspRequestResult, ParseOcspResponseErrorCode, ParseOcspResponseFailure, ParseOcspResponseResult, ParsedOcspCertId, ParsedOcspCertStatus, ParsedOcspRequest, ParsedOcspResponderId, ParsedOcspResponse, ParsedOcspSingleResponse, ValidateOcspResponseErrorCode, ValidateOcspResponseFailure, ValidateOcspResponseInput, ValidateOcspResponseResult, VerifyOcspResponseSignatureFailure, VerifyOcspResponseSignatureResult, createOcspRequest, createOcspResponse, hasOcspNoCheckExtension, parseOcspRequestDer, parseOcspRequestDerOrThrow, parseOcspRequestPem, parseOcspRequestPemOrThrow, parseOcspResponseDer, parseOcspResponseDerOrThrow, parseOcspResponsePem, parseOcspResponsePemOrThrow, validateOcspResponse, verifyOcspResponseSignature } from "./revocation/ocsp.js";
13
- import { CheckCertificateRevocationErrorCode, CheckCertificateRevocationFailureDetails, CheckCertificateRevocationInput, CheckCertificateRevocationResult, CheckCertificateRevocationValue, ConfiguredOcspResponder, ConfiguredOcspResponderCertificate, OcspResponderCandidate, OcspResponderSource, REVOCATION_INDETERMINATE_REASON_CODES, ResolveOcspResponderCandidatesInput, RevocationCertificateSource, RevocationCheckGoodValue, RevocationCheckIndeterminateValue, RevocationCheckRevokedValue, RevocationCrlEvidenceInput, RevocationEvidenceInput, RevocationEvidenceKind, RevocationIndeterminateEvidence, RevocationIndeterminateReasonCode, RevocationOcspEvidenceInput, RevocationStatus, checkCertificateRevocation, getCertificateOcspResponderUris, resolveOcspResponderCandidates } from "./revocation/revocation.js";
11
+ import { CertificateRevocationListMaterial, CheckCertificateRevocationAgainstCrlErrorCode, CheckCertificateRevocationAgainstCrlFailure, CheckCertificateRevocationAgainstCrlFailureDetails, CheckCertificateRevocationAgainstCrlGoodValue, CheckCertificateRevocationAgainstCrlInput, CheckCertificateRevocationAgainstCrlResult, CheckCertificateRevocationAgainstCrlRevokedValue, CheckCertificateRevocationAgainstCrlValue, CreateCertificateRevocationListInput, CrlApplicabilityFailureReason, CrlCertificateSource, CrlEncoderErrorCode, CrlSource, ParseCertificateRevocationListErrorCode, ParseCertificateRevocationListFailure, ParseCertificateRevocationListResult, ParsedCertificateRevocationList, ParsedRevocationReason, ParsedRevokedCertificate, RevocationReason, RevokedCertificateInput, SupersededDeltaCrlPolicy, UnrecognizedReasonCodePolicy, UnrecognizedRevocationReason, ValidateCertificateRevocationListFailure, ValidateCertificateRevocationListInput, ValidateCertificateRevocationListResult, VerifyCertificateRevocationListSignatureFailure, VerifyCertificateRevocationListSignatureOptions, VerifyCertificateRevocationListSignatureResult, checkCertificateRevocationAgainstCrl, createCertificateRevocationList, isCertificateRevoked, parseCertificateRevocationListDer, parseCertificateRevocationListDerOrThrow, parseCertificateRevocationListPem, parseCertificateRevocationListPemOrThrow, revocationReasonFromCode, validateCertificateRevocationList, verifyCertificateRevocationListSignature } from "./revocation/crl.js";
12
+ import { CreateOcspCertStatusInput, CreateOcspRequestInput, CreateOcspRequestItemInput, CreateOcspResponseInput, CreateOcspSingleResponseInput, OcspCertStatus, OcspCertificateSource, OcspEncoderErrorCode, OcspHashAlgorithm, OcspRequestMaterial, OcspRequestSource, OcspResponderRevocationPolicy, OcspResponseMaterial, OcspResponseStatus, ParseOcspRequestErrorCode, ParseOcspRequestFailure, ParseOcspRequestResult, ParseOcspResponseErrorCode, ParseOcspResponseFailure, ParseOcspResponseResult, ParsedOcspCertId, ParsedOcspCertStatus, ParsedOcspRequest, ParsedOcspResponderId, ParsedOcspResponse, ParsedOcspSingleResponse, RevocationSkipReason, ValidateOcspResponseErrorCode, ValidateOcspResponseFailure, ValidateOcspResponseInput, ValidateOcspResponseResult, VerifyOcspResponseSignatureFailure, VerifyOcspResponseSignatureOptions, VerifyOcspResponseSignatureResult, createOcspRequest, createOcspResponse, hasOcspNoCheckExtension, parseOcspRequestDer, parseOcspRequestDerOrThrow, parseOcspRequestPem, parseOcspRequestPemOrThrow, parseOcspResponseDer, parseOcspResponseDerOrThrow, parseOcspResponsePem, parseOcspResponsePemOrThrow, validateOcspResponse, verifyOcspResponseSignature } from "./revocation/ocsp.js";
13
+ import { CheckCertificateRevocationErrorCode, CheckCertificateRevocationFailureDetails, CheckCertificateRevocationInput, CheckCertificateRevocationResult, CheckCertificateRevocationValue, ConfiguredOcspResponder, ConfiguredOcspResponderCertificate, OcspResponderCandidate, OcspResponderSource, REVOCATION_INDETERMINATE_REASON_CODES, ResolveOcspResponderCandidatesInput, RevocationCertificateSource, RevocationCheckGoodValue, RevocationCheckIndeterminateValue, RevocationCheckRevokedValue, RevocationCheckSkippedValue, RevocationCrlEvidenceInput, RevocationEvidenceInput, RevocationEvidenceKind, RevocationIndeterminateEvidence, RevocationIndeterminateReasonCode, RevocationOcspEvidenceInput, RevocationStatus, checkCertificateRevocation, getCertificateOcspResponderUris, resolveOcspResponderCandidates } from "./revocation/revocation.js";
14
14
  import { IssuingDistributionPoint, IssuingDistributionPointBase, IssuingDistributionPointForAttributeCerts, IssuingDistributionPointForCaCerts, IssuingDistributionPointForUserCerts } from "./x509/extensions.js";
15
15
  import { ParsedIssuingDistributionPoint, ParsedIssuingDistributionPointBase, ParsedIssuingDistributionPointScope } from "./x509/parse.js";
16
- export { type CertificateRevocationListMaterial, type CertificateRevocationStatus, type CheckCertificateRevocationAgainstCrlErrorCode, type CheckCertificateRevocationAgainstCrlFailure, type CheckCertificateRevocationAgainstCrlFailureDetails, type CheckCertificateRevocationAgainstCrlGoodValue, type CheckCertificateRevocationAgainstCrlInput, type CheckCertificateRevocationAgainstCrlResult, type CheckCertificateRevocationAgainstCrlRevokedValue, type CheckCertificateRevocationAgainstCrlValue, type CheckCertificateRevocationErrorCode, type CheckCertificateRevocationFailureDetails, type CheckCertificateRevocationInput, type CheckCertificateRevocationResult, type CheckCertificateRevocationValue, type CheckChainRevocationInput, type CheckChainRevocationResult, type CheckChainRevocationValue, type ConfiguredOcspResponder, type ConfiguredOcspResponderCertificate, type CreateCertificateRevocationListInput, type CreateOcspCertStatusInput, type CreateOcspRequestInput, type CreateOcspRequestItemInput, type CreateOcspResponseInput, type CreateOcspSingleResponseInput, type CrlApplicabilityFailureReason, type CrlCertificateSource, type CrlEncoderErrorCode, type CrlSource, type IssuingDistributionPoint, type IssuingDistributionPointBase, type IssuingDistributionPointForAttributeCerts, type IssuingDistributionPointForCaCerts, type IssuingDistributionPointForUserCerts, type OcspCertStatus, type OcspCertificateSource, type OcspEncoderErrorCode, type OcspHashAlgorithm, type OcspRequestMaterial, type OcspRequestSource, type OcspResponderCandidate, type OcspResponderRevocationPolicy, type OcspResponderSource, type OcspResponseMaterial, type OcspResponseSource, type OcspResponseStatus, type ParseCertificateRevocationListErrorCode, type ParseCertificateRevocationListFailure, type ParseCertificateRevocationListResult, type ParseOcspRequestErrorCode, type ParseOcspRequestFailure, type ParseOcspRequestResult, type ParseOcspResponseErrorCode, type ParseOcspResponseFailure, type ParseOcspResponseResult, type ParsedCertificateRevocationList, type ParsedIssuingDistributionPoint, type ParsedIssuingDistributionPointBase, type ParsedIssuingDistributionPointScope, type ParsedOcspCertId, type ParsedOcspCertStatus, type ParsedOcspRequest, type ParsedOcspResponderId, type ParsedOcspResponse, type ParsedOcspSingleResponse, type ParsedRevocationReason, type ParsedRevokedCertificate, REVOCATION_INDETERMINATE_REASONS, REVOCATION_INDETERMINATE_REASON_CODES, type ResolveOcspResponderCandidatesInput, type RevocationCertificateSource, type RevocationCheckGoodValue, type RevocationCheckIndeterminateValue, type RevocationCheckRevokedValue, type RevocationCrlEvidenceInput, type RevocationEvidenceInput, type RevocationEvidenceKind, type RevocationExecutionError, type RevocationIndeterminateEvidence, type RevocationIndeterminateReason, type RevocationIndeterminateReasonCode, type RevocationOcspEvidenceInput, type RevocationParseError, type RevocationPolicy, type RevocationProcessingError, type RevocationReason, type RevocationSource, type RevocationStatus, type RevokedCertificateInput, type TrustedOcspResponder, type UnrecognizedReasonCodePolicy, type UnrecognizedRevocationReason, type ValidateCertificateRevocationListFailure, type ValidateCertificateRevocationListInput, type ValidateCertificateRevocationListResult, type ValidateOcspResponseErrorCode, type ValidateOcspResponseFailure, type ValidateOcspResponseInput, type ValidateOcspResponseResult, type VerifyCertificateRevocationListSignatureFailure, type VerifyCertificateRevocationListSignatureResult, type VerifyOcspResponseSignatureFailure, type VerifyOcspResponseSignatureResult, checkCertificateRevocation, checkCertificateRevocationAgainstCrl, checkChainRevocation, createCertificateRevocationList, createOcspRequest, createOcspResponse, getCertificateOcspResponderUris, hasOcspNoCheckExtension, isCertificateRevoked, parseCertificateRevocationListDer, parseCertificateRevocationListDerOrThrow, parseCertificateRevocationListPem, parseCertificateRevocationListPemOrThrow, parseOcspRequestDer, parseOcspRequestDerOrThrow, parseOcspRequestPem, parseOcspRequestPemOrThrow, parseOcspResponseDer, parseOcspResponseDerOrThrow, parseOcspResponsePem, parseOcspResponsePemOrThrow, resolveOcspResponderCandidates, revocationReasonFromCode, validateCertificateRevocationList, validateOcspResponse, verifyCertificateRevocationListSignature, verifyOcspResponseSignature };
16
+ export { type CertificateRevocationListMaterial, type CertificateRevocationStatus, type CheckCertificateRevocationAgainstCrlErrorCode, type CheckCertificateRevocationAgainstCrlFailure, type CheckCertificateRevocationAgainstCrlFailureDetails, type CheckCertificateRevocationAgainstCrlGoodValue, type CheckCertificateRevocationAgainstCrlInput, type CheckCertificateRevocationAgainstCrlResult, type CheckCertificateRevocationAgainstCrlRevokedValue, type CheckCertificateRevocationAgainstCrlValue, type CheckCertificateRevocationErrorCode, type CheckCertificateRevocationFailureDetails, type CheckCertificateRevocationInput, type CheckCertificateRevocationResult, type CheckCertificateRevocationValue, type CheckChainRevocationInput, type CheckChainRevocationResult, type CheckChainRevocationValue, type ConfiguredOcspResponder, type ConfiguredOcspResponderCertificate, type CreateCertificateRevocationListInput, type CreateOcspCertStatusInput, type CreateOcspRequestInput, type CreateOcspRequestItemInput, type CreateOcspResponseInput, type CreateOcspSingleResponseInput, type CrlApplicabilityFailureReason, type CrlCertificateSource, type CrlEncoderErrorCode, type CrlSource, type IssuingDistributionPoint, type IssuingDistributionPointBase, type IssuingDistributionPointForAttributeCerts, type IssuingDistributionPointForCaCerts, type IssuingDistributionPointForUserCerts, type OcspCertStatus, type OcspCertificateSource, type OcspEncoderErrorCode, type OcspHashAlgorithm, type OcspRequestMaterial, type OcspRequestSource, type OcspResponderCandidate, type OcspResponderRevocationPolicy, type OcspResponderSource, type OcspResponseMaterial, type OcspResponseSource, type OcspResponseStatus, type ParseCertificateRevocationListErrorCode, type ParseCertificateRevocationListFailure, type ParseCertificateRevocationListResult, type ParseOcspRequestErrorCode, type ParseOcspRequestFailure, type ParseOcspRequestResult, type ParseOcspResponseErrorCode, type ParseOcspResponseFailure, type ParseOcspResponseResult, type ParsedCertificateRevocationList, type ParsedIssuingDistributionPoint, type ParsedIssuingDistributionPointBase, type ParsedIssuingDistributionPointScope, type ParsedOcspCertId, type ParsedOcspCertStatus, type ParsedOcspRequest, type ParsedOcspResponderId, type ParsedOcspResponse, type ParsedOcspSingleResponse, type ParsedRevocationReason, type ParsedRevokedCertificate, REVOCATION_INDETERMINATE_REASONS, REVOCATION_INDETERMINATE_REASON_CODES, type ResolveOcspResponderCandidatesInput, type RevocationCertificateSource, type RevocationCheckGoodValue, type RevocationCheckIndeterminateValue, type RevocationCheckRevokedValue, type RevocationCheckSkippedValue, type RevocationCrlEvidenceInput, type RevocationEvidenceInput, type RevocationEvidenceKind, type RevocationExecutionError, type RevocationIndeterminateEvidence, type RevocationIndeterminateReason, type RevocationIndeterminateReasonCode, type RevocationOcspEvidenceInput, type RevocationParseError, type RevocationPolicy, type RevocationProcessingError, type RevocationReason, type RevocationSkipReason, type RevocationSource, type RevocationStatus, type RevokedCertificateInput, type SupersededDeltaCrlPolicy, type TrustedOcspResponder, type UnrecognizedReasonCodePolicy, type UnrecognizedRevocationReason, type ValidateCertificateRevocationListFailure, type ValidateCertificateRevocationListInput, type ValidateCertificateRevocationListResult, type ValidateOcspResponseErrorCode, type ValidateOcspResponseFailure, type ValidateOcspResponseInput, type ValidateOcspResponseResult, type VerifyCertificateRevocationListSignatureFailure, type VerifyCertificateRevocationListSignatureOptions, type VerifyCertificateRevocationListSignatureResult, type VerifyOcspResponseSignatureFailure, type VerifyOcspResponseSignatureOptions, type VerifyOcspResponseSignatureResult, checkCertificateRevocation, checkCertificateRevocationAgainstCrl, checkChainRevocation, createCertificateRevocationList, createOcspRequest, createOcspResponse, getCertificateOcspResponderUris, hasOcspNoCheckExtension, isCertificateRevoked, parseCertificateRevocationListDer, parseCertificateRevocationListDerOrThrow, parseCertificateRevocationListPem, parseCertificateRevocationListPemOrThrow, parseOcspRequestDer, parseOcspRequestDerOrThrow, parseOcspRequestPem, parseOcspRequestPemOrThrow, parseOcspResponseDer, parseOcspResponseDerOrThrow, parseOcspResponsePem, parseOcspResponsePemOrThrow, resolveOcspResponderCandidates, revocationReasonFromCode, validateCertificateRevocationList, validateOcspResponse, verifyCertificateRevocationListSignature, verifyOcspResponseSignature };
@@ -1 +1 @@
1
- {"version":3,"file":"ssh.js","names":["MAX_PRIVATE_KEY_FILE_BYTES","MAX_MPINT_BYTES","MAX_STRING_BYTES","MAX_RSA_MODULUS_BITS","PRIVATE_KEY_LABEL","AUTH_MAGIC","character","SSH_KEY_TYPES","candidate","name","CURVES","PRIME_EC_CURVES","CURVE_NAMES","ECDSA_KEY_TYPE_CURVES","options","sshFail","minRsaModulusBits","acceptCompressedEcPoints","rsa","rsaScheme","rsaHash","value","material","magnitude","base64Encode","bytes","padded","base64Decode","result","factor","base","modulus","remaining","exponent","curve","xValue","bytesToBigint","x","prime","rhs","b","root","wantOdd","prefix","y","bigintToBytes","size","point","first","reader","second","e","n","order","bits","createSshReader","blob","keyType","concatBytes","type","sshTextString","sshMpint","sshString","bytesEqual","left","right","d","p","q","importPublicJwkOrThrow","importPrivateJwkOrThrow","envelope","error","rethrowIfInvariant","getCrypto","challenge","params","signature","subtle","privateKey","publicKey","digest","toArrayBuffer","input","maxBytes","decodeUtf8","PUBLIC_KEY_LINE","text","match","typeToken","encoded","comment","envelopeType","pub","secret","iqmp","padding","byte","index","binary","pemDecodeOrThrow","magic","cipher","kdf","keyCount","section","inner","privateMaterial","successResult","run","isResultError","code","asSshErrorCode","failureResult","unwrap","throwMicro509Error","message","key","jwk","member","algorithmName","exportPublicJwk","line","exportPrivateJwk","fields","checkInt","unpadded","sshUint32","paddingLength","file","pemEncode"],"sources":["../../src/ssh/ssh.ts"],"sourcesContent":["/**\n * OpenSSH public-key lines, unencrypted `openssh-key-v1` private keys, and\n * `SHA256:` fingerprints for RSA, Ed25519, and ECDSA on P-256, P-384 and P-521.\n *\n * Keys move through the existing WebCrypto, JWK and PKCS#8/SPKI APIs of\n * `micro509/keys`. Nothing here opens a connection, speaks the SSH transport,\n * reads SSH certificates, evaluates `authorized_keys` options, or decrypts a\n * private key.\n *\n * The `ssh-rsa` key type names the RSA public-key encoding (RFC 4253 §6.6). It\n * does not select a signature hash: RFC 8332 §3 keeps the `ssh-rsa` key format\n * for the `rsa-sha2-256` and `rsa-sha2-512` signature algorithms. Importing an\n * `ssh-rsa` key enables no SHA-1 signature.\n *\n * @example\n * ```ts\n * import { generateKeyPair, unwrap } from 'micro509';\n * import {\n * \texportOpenSshPrivateKey,\n * \texportSshPublicKey,\n * \timportOpenSshPrivateKey,\n * } from 'micro509/ssh';\n *\n * const keys = await generateKeyPair({ kind: 'ed25519' });\n * const line = await exportSshPublicKey(keys.publicKey, { comment: 'me@host' });\n * const pem = await exportOpenSshPrivateKey(keys.privateKey, { comment: 'me@host' });\n * const imported = unwrap(await importOpenSshPrivateKey(pem));\n * console.log(line, imported.fingerprint);\n * ```\n *\n * @module\n */\n\nimport { toArrayBuffer } from '#micro509/internal/asn1/asn1';\nimport { concatBytes } from '#micro509/internal/asn1/der';\nimport { PRIME_EC_CURVES } from '#micro509/internal/crypto/prime-ec';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport { base64Decode, base64Encode } from '#micro509/internal/shared/base64';\nimport type {\n\tEcNamedCurve,\n\tImportEcKeyInput,\n\tImportEd25519KeyInput,\n\tImportRsaKeyInput,\n\tRsaHash,\n\tRsaSignatureScheme,\n} from '#micro509/keys/keys';\nimport {\n\texportPrivateJwk,\n\texportPublicJwk,\n\timportPrivateJwkOrThrow,\n\timportPublicJwkOrThrow,\n} from '#micro509/keys/keys';\nimport { pemDecodeOrThrow, pemEncode } from '#micro509/pem/pem';\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport {\n\tfailureResult,\n\tisResultError,\n\trethrowIfInvariant,\n\tsuccessResult,\n\tthrowMicro509Error,\n\tunwrap,\n} from '#micro509/result/result';\nimport type { SshErrorCode, SshReader } from '#micro509/ssh/wire';\nimport {\n\tasSshErrorCode,\n\tbigintToBytes,\n\tbytesEqual,\n\tbytesToBigint,\n\tcreateSshReader,\n\tdecodeUtf8,\n\tsshFail,\n\tsshMpint,\n\tsshString,\n\tsshTextString,\n\tsshUint32,\n} from '#micro509/ssh/wire';\n\nexport type { SshErrorCode } from '#micro509/ssh/wire';\n\n/** SSH public-key type names (RFC 4253 §6.6, RFC 5656 §6.2, RFC 8709 §4) this module reads and writes. */\nexport type SshKeyType =\n\t| 'ssh-rsa'\n\t| 'ssh-ed25519'\n\t| 'ecdsa-sha2-nistp256'\n\t| 'ecdsa-sha2-nistp384'\n\t| 'ecdsa-sha2-nistp521';\n\n/** Algorithm family of an SSH key, discriminated by `kind`. */\nexport type SshKeyAlgorithm =\n\t| {\n\t\t\t/** RSA. */\n\t\t\treadonly kind: 'rsa';\n\t\t\t/** Modulus size in bits. */\n\t\t\treadonly modulusBits: number;\n\t }\n\t| {\n\t\t\t/** ECDSA. */\n\t\t\treadonly kind: 'ecdsa';\n\t\t\t/** NIST curve. */\n\t\t\treadonly curve: EcNamedCurve;\n\t }\n\t| {\n\t\t\t/** Ed25519. */\n\t\t\treadonly kind: 'ed25519';\n\t };\n\n/** Structured failure payload of the SSH key import functions. */\nexport interface SshFailure extends Micro509Error<SshErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/**\n * Success-or-failure result of the SSH key import functions.\n *\n * `code` is `'malformed'` for structurally invalid input, `'unsupported'` for a\n * valid construct this module does not read (encrypted keys, multi-key files,\n * other key types, RSA below the minimum size, compressed points unless\n * accepted), `'limit_exceeded'` for an implementation bound, and\n * `'key_mismatch'` when the declared key types or the embedded public and\n * private keys disagree. No message contains private key material.\n */\nexport type SshResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| ErrorResult<SshErrorCode, Record<never, never>, SshFailure>;\n\n/** Policy options of the SSH key import functions. */\nexport interface SshImportOptions {\n\t/**\n\t * Smallest accepted RSA modulus in bits, an integer from 1 to 16384. Default: `2048`.\n\t *\n\t * The standards leave key strength to the relying party. RFC 8332 §5.1 calls\n\t * 2048 bits prudent; OpenSSH itself accepts 1024.\n\t */\n\treadonly minRsaModulusBits?: number;\n\t/**\n\t * Accept SEC 1 compressed ECDSA points. Default: `false`.\n\t *\n\t * RFC 5656 §3.1 allows point compression; OpenSSH reads and writes only\n\t * uncompressed points.\n\t */\n\treadonly acceptCompressedEcPoints?: boolean;\n\t/**\n\t * WebCrypto parameters of an imported RSA key. Default: PKCS#1 v1.5 with\n\t * SHA-256. These choose how the `CryptoKey` signs; they do not change the\n\t * `ssh-rsa` key encoding.\n\t */\n\treadonly rsa?: {\n\t\t/** Signature padding scheme. */\n\t\treadonly scheme?: RsaSignatureScheme;\n\t\t/** Signature hash. */\n\t\treadonly hash?: RsaHash;\n\t};\n}\n\n/** Public key read from an OpenSSH public-key line. */\nexport interface ImportedSshPublicKey {\n\t/** SSH key type name. */\n\treadonly keyType: SshKeyType;\n\t/** Algorithm family and size. */\n\treadonly algorithm: SshKeyAlgorithm;\n\t/** Extractable WebCrypto key with `verify` usage. */\n\treadonly publicKey: CryptoKey;\n\t/** The line's trailing comment; empty when absent. */\n\treadonly comment: string;\n\t/** `SHA256:` fingerprint of the public-key blob. */\n\treadonly fingerprint: string;\n}\n\n/** Key pair read from an `openssh-key-v1` private-key file. */\nexport interface ImportedOpenSshPrivateKey extends ImportedSshPublicKey {\n\t/** Extractable WebCrypto private key with `sign` usage. */\n\treadonly privateKey: CryptoKey;\n}\n\n/** Options of {@linkcode exportSshPublicKey} and {@linkcode exportOpenSshPrivateKey}. */\nexport interface SshExportOptions {\n\t/** Comment to attach, at most 8192 UTF-8 bytes. Must be well-formed Unicode without CR, LF or NUL. Default: empty. */\n\treadonly comment?: string;\n}\n\n/** Machine-readable failure reason of the SSH key export functions. */\nexport type SshExportErrorCode =\n\t| 'invalid_key'\n\t| 'unsupported_algorithm'\n\t| 'not_extractable'\n\t| 'invalid_comment';\n\nconst MAX_PUBLIC_KEY_LINE_BYTES = 16 * 1024;\nconst MAX_PRIVATE_KEY_FILE_BYTES = 32 * 1024;\nconst MAX_MPINT_BYTES = 2049;\nconst MAX_STRING_BYTES = 8192;\nconst MAX_RSA_MODULUS_BITS = 16384;\nconst DEFAULT_MIN_RSA_MODULUS_BITS = 2048;\nconst PRIVATE_KEY_LABEL = 'OPENSSH PRIVATE KEY';\nconst AUTH_MAGIC = Uint8Array.from('openssh-key-v1', (character) => character.charCodeAt(0));\nconst NO_CIPHER_BLOCK_SIZE = 8;\nconst ED25519_KEY_BYTES = 32;\n\nconst SSH_KEY_TYPES = [\n\t'ssh-rsa',\n\t'ssh-ed25519',\n\t'ecdsa-sha2-nistp256',\n\t'ecdsa-sha2-nistp384',\n\t'ecdsa-sha2-nistp521',\n] as const satisfies readonly SshKeyType[];\n\nfunction asSshKeyType(name: string): SshKeyType | undefined {\n\treturn SSH_KEY_TYPES.find((candidate) => candidate === name);\n}\n\ninterface CurveInfo {\n\treadonly identifier: 'nistp256' | 'nistp384' | 'nistp521';\n\treadonly size: number;\n\treadonly hash: 'SHA-256' | 'SHA-384' | 'SHA-512';\n\treadonly prime: bigint;\n\treadonly b: bigint;\n}\n\nconst CURVES = {\n\t'P-256': {\n\t\tidentifier: 'nistp256',\n\t\thash: 'SHA-256',\n\t\t...PRIME_EC_CURVES['P-256'],\n\t},\n\t'P-384': {\n\t\tidentifier: 'nistp384',\n\t\thash: 'SHA-384',\n\t\t...PRIME_EC_CURVES['P-384'],\n\t},\n\t'P-521': {\n\t\tidentifier: 'nistp521',\n\t\thash: 'SHA-512',\n\t\t...PRIME_EC_CURVES['P-521'],\n\t},\n} as const satisfies Record<EcNamedCurve, CurveInfo>;\n\nconst CURVE_NAMES = ['P-256', 'P-384', 'P-521'] as const satisfies readonly EcNamedCurve[];\n\nconst ECDSA_KEY_TYPE_CURVES = {\n\t'ecdsa-sha2-nistp256': 'P-256',\n\t'ecdsa-sha2-nistp384': 'P-384',\n\t'ecdsa-sha2-nistp521': 'P-521',\n} as const satisfies Record<Exclude<SshKeyType, 'ssh-rsa' | 'ssh-ed25519'>, EcNamedCurve>;\n\ntype SshPublicMaterial =\n\t| { readonly kind: 'rsa'; readonly e: Uint8Array; readonly n: Uint8Array }\n\t| {\n\t\t\treadonly kind: 'ecdsa';\n\t\t\treadonly curve: EcNamedCurve;\n\t\t\treadonly x: Uint8Array;\n\t\t\treadonly y: Uint8Array;\n\t }\n\t| { readonly kind: 'ed25519'; readonly x: Uint8Array };\n\ntype SshPrivateMaterial =\n\t| {\n\t\t\treadonly kind: 'rsa';\n\t\t\treadonly pub: Extract<SshPublicMaterial, { kind: 'rsa' }>;\n\t\t\treadonly d: Uint8Array;\n\t\t\treadonly p: Uint8Array;\n\t\t\treadonly q: Uint8Array;\n\t\t\treadonly iqmp: Uint8Array;\n\t }\n\t| {\n\t\t\treadonly kind: 'ecdsa';\n\t\t\treadonly pub: Extract<SshPublicMaterial, { kind: 'ecdsa' }>;\n\t\t\treadonly d: Uint8Array;\n\t }\n\t| {\n\t\t\treadonly kind: 'ed25519';\n\t\t\treadonly pub: Extract<SshPublicMaterial, { kind: 'ed25519' }>;\n\t\t\treadonly seed: Uint8Array;\n\t };\n\ninterface ResolvedImportOptions {\n\treadonly minRsaModulusBits: number;\n\treadonly acceptCompressedEcPoints: boolean;\n\treadonly rsaScheme: RsaSignatureScheme;\n\treadonly rsaHash: RsaHash;\n}\n\nfunction resolveImportOptions(options: SshImportOptions): ResolvedImportOptions {\n\tif (typeof options !== 'object' || options === null || Array.isArray(options)) {\n\t\treturn sshFail('invalid_options', 'SSH import options must be an object');\n\t}\n\tconst minRsaModulusBits =\n\t\toptions.minRsaModulusBits === undefined\n\t\t\t? DEFAULT_MIN_RSA_MODULUS_BITS\n\t\t\t: options.minRsaModulusBits;\n\tif (\n\t\t!Number.isSafeInteger(minRsaModulusBits) ||\n\t\tminRsaModulusBits < 1 ||\n\t\tminRsaModulusBits > MAX_RSA_MODULUS_BITS\n\t) {\n\t\treturn sshFail('invalid_options', 'minRsaModulusBits must be an integer from 1 to 16384');\n\t}\n\tconst acceptCompressedEcPoints =\n\t\toptions.acceptCompressedEcPoints === undefined ? false : options.acceptCompressedEcPoints;\n\tif (typeof acceptCompressedEcPoints !== 'boolean') {\n\t\treturn sshFail('invalid_options', 'acceptCompressedEcPoints must be a boolean');\n\t}\n\tconst rsa = options.rsa === undefined ? {} : options.rsa;\n\tif (typeof rsa !== 'object' || rsa === null || Array.isArray(rsa)) {\n\t\treturn sshFail('invalid_options', 'rsa must be an object');\n\t}\n\tconst rsaScheme = rsa.scheme === undefined ? 'pkcs1-v1_5' : rsa.scheme;\n\tconst rsaHash = rsa.hash === undefined ? 'SHA-256' : rsa.hash;\n\tif (rsaScheme !== 'pkcs1-v1_5' && rsaScheme !== 'pss') {\n\t\treturn sshFail('invalid_options', 'Unsupported RSA signature scheme');\n\t}\n\tif (rsaHash !== 'SHA-256' && rsaHash !== 'SHA-384' && rsaHash !== 'SHA-512') {\n\t\treturn sshFail('invalid_options', 'Unsupported RSA signature hash');\n\t}\n\treturn { minRsaModulusBits, acceptCompressedEcPoints, rsaScheme, rsaHash };\n}\n\nfunction unhandledKey(value: never): never {\n\tthrow new Error(`Unhandled SSH key: ${String(value)}`);\n}\n\nfunction keyTypeOf(material: SshPublicMaterial): SshKeyType {\n\tswitch (material.kind) {\n\t\tcase 'rsa':\n\t\t\treturn 'ssh-rsa';\n\t\tcase 'ed25519':\n\t\t\treturn 'ssh-ed25519';\n\t\tcase 'ecdsa':\n\t\t\treturn `ecdsa-sha2-${CURVES[material.curve].identifier}`;\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\nfunction bitLength(magnitude: Uint8Array): number {\n\treturn (magnitude.length - 1) * 8 + 32 - Math.clz32(magnitude[0] ?? 0);\n}\n\nfunction algorithmOf(material: SshPublicMaterial): SshKeyAlgorithm {\n\tswitch (material.kind) {\n\t\tcase 'rsa':\n\t\t\treturn { kind: 'rsa', modulusBits: bitLength(material.n) };\n\t\tcase 'ecdsa':\n\t\t\treturn { kind: 'ecdsa', curve: material.curve };\n\t\tcase 'ed25519':\n\t\t\treturn { kind: 'ed25519' };\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n\treturn base64Encode(bytes).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction fromBase64Url(value: string): Uint8Array {\n\tconst padded = value.replace(/-/g, '+').replace(/_/g, '/');\n\treturn base64Decode(padded.padEnd(Math.ceil(padded.length / 4) * 4, '='));\n}\n\nfunction modPow(base: bigint, exponent: bigint, modulus: bigint): bigint {\n\tlet result = 1n;\n\tlet factor = base % modulus;\n\tlet remaining = exponent;\n\twhile (remaining > 0n) {\n\t\tif ((remaining & 1n) === 1n) {\n\t\t\tresult = (result * factor) % modulus;\n\t\t}\n\t\tfactor = (factor * factor) % modulus;\n\t\tremaining >>= 1n;\n\t}\n\treturn result;\n}\n\nfunction decompressPoint(curve: EcNamedCurve, prefix: number, x: Uint8Array): Uint8Array {\n\tconst { prime, b, size } = CURVES[curve];\n\tconst xValue = bytesToBigint(x);\n\tif (xValue >= prime) {\n\t\treturn sshFail('malformed', 'ECDSA point coordinate is out of range');\n\t}\n\tconst rhs = ((((xValue * xValue - 3n) * xValue + b) % prime) + prime) % prime;\n\tconst root = modPow(rhs, (prime + 1n) / 4n, prime);\n\tif ((root * root) % prime !== rhs) {\n\t\treturn sshFail('malformed', 'ECDSA point is not on the curve');\n\t}\n\tconst wantOdd = prefix === 0x03;\n\tconst y = ((root & 1n) === 1n) === wantOdd ? root : prime - root;\n\treturn bigintToBytes(y, size);\n}\n\nfunction readPoint(\n\tcurve: EcNamedCurve,\n\tpoint: Uint8Array,\n\toptions: ResolvedImportOptions,\n): { readonly x: Uint8Array; readonly y: Uint8Array } {\n\tconst { size } = CURVES[curve];\n\tconst prefix = point[0];\n\tif (prefix === 0x04 && point.length === 1 + 2 * size) {\n\t\treturn { x: point.subarray(1, 1 + size), y: point.subarray(1 + size) };\n\t}\n\tif ((prefix === 0x02 || prefix === 0x03) && point.length === 1 + size) {\n\t\tif (!options.acceptCompressedEcPoints) {\n\t\t\treturn sshFail('unsupported', 'Compressed ECDSA points need acceptCompressedEcPoints');\n\t\t}\n\t\tconst x = point.subarray(1);\n\t\treturn { x, y: decompressPoint(curve, prefix, x) };\n\t}\n\treturn sshFail('malformed', 'ECDSA point encoding is invalid');\n}\n\nfunction readRsaPublic(\n\treader: SshReader,\n\torder: 'e-n' | 'n-e',\n\toptions: ResolvedImportOptions,\n): Extract<SshPublicMaterial, { kind: 'rsa' }> {\n\tconst first = reader.mpint(MAX_MPINT_BYTES);\n\tconst second = reader.mpint(MAX_MPINT_BYTES);\n\tconst [e, n] = order === 'e-n' ? [first, second] : [second, first];\n\tconst bits = bitLength(n);\n\tif (bits > MAX_RSA_MODULUS_BITS) {\n\t\treturn sshFail('limit_exceeded', `RSA modulus of ${bits} bits exceeds ${MAX_RSA_MODULUS_BITS}`);\n\t}\n\tif (bits < options.minRsaModulusBits) {\n\t\treturn sshFail(\n\t\t\t'unsupported',\n\t\t\t`RSA modulus of ${bits} bits is below ${options.minRsaModulusBits}`,\n\t\t);\n\t}\n\tconst exponent = bytesToBigint(e);\n\tif (exponent < 3n || (exponent & 1n) === 0n || exponent >= bytesToBigint(n)) {\n\t\treturn sshFail('malformed', 'RSA public exponent is invalid');\n\t}\n\treturn { kind: 'rsa', e, n };\n}\n\nfunction readEcdsaPublic(\n\treader: SshReader,\n\tcurve: EcNamedCurve,\n\toptions: ResolvedImportOptions,\n): Extract<SshPublicMaterial, { kind: 'ecdsa' }> {\n\tif (reader.name() !== CURVES[curve].identifier) {\n\t\treturn sshFail('key_mismatch', 'ECDSA curve identifier disagrees with the key type');\n\t}\n\tconst point = reader.string(MAX_STRING_BYTES);\n\treturn { kind: 'ecdsa', curve, ...readPoint(curve, point, options) };\n}\n\nfunction readEd25519Public(reader: SshReader): Extract<SshPublicMaterial, { kind: 'ed25519' }> {\n\tconst x = reader.string(MAX_STRING_BYTES);\n\tif (x.length !== ED25519_KEY_BYTES) {\n\t\treturn sshFail('malformed', 'Ed25519 public key is not 32 bytes');\n\t}\n\treturn { kind: 'ed25519', x };\n}\n\nfunction decodePublicBlob(blob: Uint8Array, options: ResolvedImportOptions): SshPublicMaterial {\n\tconst reader = createSshReader(blob);\n\tconst keyType = asSshKeyType(reader.name());\n\tif (keyType === undefined) {\n\t\treturn sshFail('unsupported', 'Unsupported SSH key type');\n\t}\n\tlet material: SshPublicMaterial;\n\tswitch (keyType) {\n\t\tcase 'ssh-rsa':\n\t\t\tmaterial = readRsaPublic(reader, 'e-n', options);\n\t\t\tbreak;\n\t\tcase 'ssh-ed25519':\n\t\t\tmaterial = readEd25519Public(reader);\n\t\t\tbreak;\n\t\tcase 'ecdsa-sha2-nistp256':\n\t\tcase 'ecdsa-sha2-nistp384':\n\t\tcase 'ecdsa-sha2-nistp521': {\n\t\t\tmaterial = readEcdsaPublic(reader, ECDSA_KEY_TYPE_CURVES[keyType], options);\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\treturn unhandledKey(keyType);\n\t}\n\tif (reader.remaining() !== 0) {\n\t\treturn sshFail('malformed', 'SSH public key has trailing data');\n\t}\n\treturn material;\n}\n\nfunction ecPoint(material: Extract<SshPublicMaterial, { kind: 'ecdsa' }>): Uint8Array {\n\treturn concatBytes([Uint8Array.of(0x04), material.x, material.y]);\n}\n\nfunction encodePublicBlob(material: SshPublicMaterial): Uint8Array {\n\tconst type = sshTextString(keyTypeOf(material));\n\tswitch (material.kind) {\n\t\tcase 'rsa':\n\t\t\treturn concatBytes([type, sshMpint(material.e), sshMpint(material.n)]);\n\t\tcase 'ed25519':\n\t\t\treturn concatBytes([type, sshString(material.x)]);\n\t\tcase 'ecdsa':\n\t\t\treturn concatBytes([\n\t\t\t\ttype,\n\t\t\t\tsshTextString(CURVES[material.curve].identifier),\n\t\t\t\tsshString(ecPoint(material)),\n\t\t\t]);\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\nfunction samePublicMaterial(left: SshPublicMaterial, right: SshPublicMaterial): boolean {\n\treturn bytesEqual(encodePublicBlob(left), encodePublicBlob(right));\n}\n\nfunction publicJwk(material: SshPublicMaterial): JsonWebKey {\n\tswitch (material.kind) {\n\t\tcase 'rsa':\n\t\t\treturn { kty: 'RSA', n: toBase64Url(material.n), e: toBase64Url(material.e) };\n\t\tcase 'ecdsa':\n\t\t\treturn {\n\t\t\t\tkty: 'EC',\n\t\t\t\tcrv: material.curve,\n\t\t\t\tx: toBase64Url(material.x),\n\t\t\t\ty: toBase64Url(material.y),\n\t\t\t};\n\t\tcase 'ed25519':\n\t\t\treturn { kty: 'OKP', crv: 'Ed25519', x: toBase64Url(material.x) };\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\nfunction privateJwk(material: SshPrivateMaterial): JsonWebKey {\n\tswitch (material.kind) {\n\t\tcase 'rsa': {\n\t\t\tconst d = bytesToBigint(material.d);\n\t\t\tconst p = bytesToBigint(material.p);\n\t\t\tconst q = bytesToBigint(material.q);\n\t\t\treturn {\n\t\t\t\t...publicJwk(material.pub),\n\t\t\t\td: toBase64Url(material.d),\n\t\t\t\tp: toBase64Url(material.p),\n\t\t\t\tq: toBase64Url(material.q),\n\t\t\t\tdp: toBase64Url(bigintToBytes(d % (p - 1n))),\n\t\t\t\tdq: toBase64Url(bigintToBytes(d % (q - 1n))),\n\t\t\t\tqi: toBase64Url(material.iqmp),\n\t\t\t};\n\t\t}\n\t\tcase 'ecdsa':\n\t\t\treturn {\n\t\t\t\t...publicJwk(material.pub),\n\t\t\t\td: toBase64Url(bigintToBytes(bytesToBigint(material.d), CURVES[material.pub.curve].size)),\n\t\t\t};\n\t\tcase 'ed25519':\n\t\t\treturn { ...publicJwk(material.pub), d: toBase64Url(material.seed) };\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\ntype WebCryptoImportInput = ImportRsaKeyInput | ImportEcKeyInput | ImportEd25519KeyInput;\n\nfunction importInputFor(\n\tmaterial: SshPublicMaterial,\n\toptions: ResolvedImportOptions,\n): WebCryptoImportInput {\n\tswitch (material.kind) {\n\t\tcase 'rsa':\n\t\t\treturn { kind: 'rsa', scheme: options.rsaScheme, hash: options.rsaHash };\n\t\tcase 'ecdsa':\n\t\t\treturn { kind: 'ecdsa', curve: material.curve };\n\t\tcase 'ed25519':\n\t\t\treturn { kind: 'ed25519' };\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\nfunction signParams(\n\tmaterial: SshPublicMaterial,\n\toptions: ResolvedImportOptions,\n): AlgorithmIdentifier | RsaPssParams | EcdsaParams {\n\tswitch (material.kind) {\n\t\tcase 'rsa':\n\t\t\treturn options.rsaScheme === 'pss'\n\t\t\t\t? { name: 'RSA-PSS', saltLength: 32 }\n\t\t\t\t: { name: 'RSASSA-PKCS1-v1_5' };\n\t\tcase 'ecdsa':\n\t\t\treturn { name: 'ECDSA', hash: CURVES[material.curve].hash };\n\t\tcase 'ed25519':\n\t\t\treturn { name: 'Ed25519' };\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\nasync function importPublicMaterial(\n\tmaterial: SshPublicMaterial,\n\toptions: ResolvedImportOptions,\n): Promise<CryptoKey> {\n\treturn await importPublicJwkOrThrow(publicJwk(material), importInputFor(material, options));\n}\n\nasync function importPrivateMaterial(\n\tmaterial: SshPrivateMaterial,\n\tenvelope: SshPublicMaterial,\n\toptions: ResolvedImportOptions,\n): Promise<CryptoKey> {\n\ttry {\n\t\treturn await importPrivateJwkOrThrow(privateJwk(material), importInputFor(envelope, options));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn sshFail('key_mismatch', 'Private key material is invalid for the embedded public key');\n\t}\n}\n\nasync function assertKeyPairConsistent(\n\tprivateKey: CryptoKey,\n\tpublicKey: CryptoKey,\n\tmaterial: SshPublicMaterial,\n\toptions: ResolvedImportOptions,\n): Promise<void> {\n\tconst { subtle } = getCrypto();\n\tconst challenge = getCrypto().getRandomValues(new Uint8Array(32));\n\tconst params = signParams(material, options);\n\tconst signature = await subtle.sign(params, privateKey, challenge);\n\tif (!(await subtle.verify(params, publicKey, signature, challenge))) {\n\t\tsshFail('key_mismatch', 'Private key does not match the embedded public key');\n\t}\n}\n\nasync function sha256Fingerprint(blob: Uint8Array): Promise<string> {\n\tconst digest = new Uint8Array(await getCrypto().subtle.digest('SHA-256', toArrayBuffer(blob)));\n\treturn `SHA256:${base64Encode(digest).replace(/=+$/, '')}`;\n}\n\nfunction textOf(input: string | Uint8Array, maxBytes: number): string {\n\tif (typeof input === 'string') {\n\t\tif (input.length > maxBytes) {\n\t\t\treturn sshFail('limit_exceeded', `SSH key input exceeds ${maxBytes} bytes`);\n\t\t}\n\t\tconst bytes = new TextEncoder().encode(input);\n\t\tif (bytes.length > maxBytes) {\n\t\t\treturn sshFail('limit_exceeded', `SSH key input exceeds ${maxBytes} bytes`);\n\t\t}\n\t\treturn input;\n\t}\n\tif (input.length > maxBytes) {\n\t\treturn sshFail('limit_exceeded', `SSH key input exceeds ${maxBytes} bytes`);\n\t}\n\treturn decodeUtf8(input);\n}\n\nconst PUBLIC_KEY_LINE = /^([^ \\t]+)[ \\t]+([A-Za-z0-9+/]+={0,2})(?:[ \\t]+(.*))?$/s;\n\nasync function decodePublicKeyLine(\n\tinput: string | Uint8Array,\n\toptions: ResolvedImportOptions,\n): Promise<ImportedSshPublicKey> {\n\tconst text = textOf(input, MAX_PUBLIC_KEY_LINE_BYTES).replace(/\\r?\\n$/, '');\n\tif (/[\\r\\n]/.test(text)) {\n\t\treturn sshFail('malformed', 'SSH public key must be a single line');\n\t}\n\tconst match = PUBLIC_KEY_LINE.exec(text);\n\tif (match === null) {\n\t\treturn sshFail('malformed', 'SSH public key line is not \"<type> <base64> [comment]\"');\n\t}\n\tconst [, typeToken = '', encoded = '', comment = ''] = match;\n\tassertImportedComment(comment);\n\tconst keyType = asSshKeyType(typeToken);\n\tif (keyType === undefined) {\n\t\treturn sshFail('unsupported', 'Unsupported SSH key type');\n\t}\n\tconst blob = base64Decode(encoded);\n\tconst material = decodePublicBlob(blob, options);\n\tif (keyTypeOf(material) !== keyType) {\n\t\treturn sshFail('key_mismatch', 'Line key type disagrees with the key blob');\n\t}\n\treturn {\n\t\tkeyType,\n\t\talgorithm: algorithmOf(material),\n\t\tpublicKey: await importPublicMaterial(material, options),\n\t\tcomment,\n\t\tfingerprint: await sha256Fingerprint(encodePublicBlob(material)),\n\t};\n}\n\nfunction readPrivateMaterial(\n\treader: SshReader,\n\tenvelopeType: SshKeyType,\n\toptions: ResolvedImportOptions,\n): SshPrivateMaterial {\n\tconst declared = reader.name();\n\tif (declared !== envelopeType) {\n\t\treturn sshFail('key_mismatch', 'Private section key type disagrees with the public key');\n\t}\n\tswitch (envelopeType) {\n\t\tcase 'ssh-rsa': {\n\t\t\tconst pub = readRsaPublic(reader, 'n-e', options);\n\t\t\tconst d = reader.mpint(MAX_MPINT_BYTES);\n\t\t\tconst iqmp = reader.mpint(MAX_MPINT_BYTES);\n\t\t\tconst p = reader.mpint(MAX_MPINT_BYTES);\n\t\t\tconst q = reader.mpint(MAX_MPINT_BYTES);\n\t\t\treturn { kind: 'rsa', pub, d, iqmp, p, q };\n\t\t}\n\t\tcase 'ssh-ed25519': {\n\t\t\tconst pub = readEd25519Public(reader);\n\t\t\tconst secret = reader.string(MAX_STRING_BYTES);\n\t\t\tif (secret.length !== 2 * ED25519_KEY_BYTES) {\n\t\t\t\treturn sshFail('malformed', 'Ed25519 private key is not 64 bytes');\n\t\t\t}\n\t\t\tif (!bytesEqual(secret.subarray(ED25519_KEY_BYTES), pub.x)) {\n\t\t\t\treturn sshFail('key_mismatch', 'Ed25519 private key suffix differs from the public key');\n\t\t\t}\n\t\t\treturn { kind: 'ed25519', pub, seed: secret.subarray(0, ED25519_KEY_BYTES) };\n\t\t}\n\t\tcase 'ecdsa-sha2-nistp256':\n\t\tcase 'ecdsa-sha2-nistp384':\n\t\tcase 'ecdsa-sha2-nistp521': {\n\t\t\tconst pub = readEcdsaPublic(reader, ECDSA_KEY_TYPE_CURVES[envelopeType], options);\n\t\t\tconst d = reader.mpint(MAX_MPINT_BYTES);\n\t\t\tif (d.length > CURVES[pub.curve].size) {\n\t\t\t\treturn sshFail('malformed', 'ECDSA private scalar is larger than the curve order');\n\t\t\t}\n\t\t\treturn { kind: 'ecdsa', pub, d };\n\t\t}\n\t\tdefault:\n\t\t\treturn unhandledKey(envelopeType);\n\t}\n}\n\nfunction assertRsaConsistent(material: Extract<SshPrivateMaterial, { kind: 'rsa' }>): void {\n\tconst n = bytesToBigint(material.pub.n);\n\tconst e = bytesToBigint(material.pub.e);\n\tconst d = bytesToBigint(material.d);\n\tconst p = bytesToBigint(material.p);\n\tconst q = bytesToBigint(material.q);\n\tconst iqmp = bytesToBigint(material.iqmp);\n\tif (p < 3n || q < 3n || p * q !== n) {\n\t\tsshFail('key_mismatch', 'RSA primes do not multiply to the modulus');\n\t}\n\tif (d >= n || (d * e) % (p - 1n) !== 1n || (d * e) % (q - 1n) !== 1n) {\n\t\tsshFail('key_mismatch', 'RSA private exponent does not match the public exponent');\n\t}\n\tif (iqmp >= p || (iqmp * q) % p !== 1n) {\n\t\tsshFail('key_mismatch', 'RSA coefficient is not the inverse of q modulo p');\n\t}\n}\n\nfunction assertPadding(reader: SshReader): void {\n\tconst padding = reader.raw(reader.remaining());\n\tif (padding.length >= NO_CIPHER_BLOCK_SIZE) {\n\t\tsshFail('malformed', 'OpenSSH private key padding is too long');\n\t}\n\tpadding.forEach((byte, index) => {\n\t\tif (byte !== index + 1) {\n\t\t\tsshFail('malformed', 'OpenSSH private key padding is invalid');\n\t\t}\n\t});\n}\n\nasync function decodePrivateKey(\n\tinput: string | Uint8Array,\n\toptions: ResolvedImportOptions,\n): Promise<ImportedOpenSshPrivateKey> {\n\tconst text = textOf(input, MAX_PRIVATE_KEY_FILE_BYTES);\n\tconst binary = pemDecodeOrThrow(PRIVATE_KEY_LABEL, text);\n\ttry {\n\t\treturn await decodePrivateBinary(binary, options);\n\t} finally {\n\t\tbinary.fill(0);\n\t}\n}\n\nasync function decodePrivateBinary(\n\tbinary: Uint8Array,\n\toptions: ResolvedImportOptions,\n): Promise<ImportedOpenSshPrivateKey> {\n\tconst reader = createSshReader(binary);\n\tconst magic = reader.raw(AUTH_MAGIC.length + 1);\n\tif (\n\t\t!bytesEqual(magic.subarray(0, AUTH_MAGIC.length), AUTH_MAGIC) ||\n\t\tmagic[AUTH_MAGIC.length] !== 0\n\t) {\n\t\treturn sshFail('malformed', 'Missing openssh-key-v1 magic');\n\t}\n\tconst cipher = reader.name();\n\tconst kdf = reader.name();\n\tif (cipher !== 'none' || kdf !== 'none') {\n\t\treturn sshFail('unsupported', 'Encrypted OpenSSH private keys are not supported');\n\t}\n\tif (reader.string(MAX_STRING_BYTES).length !== 0) {\n\t\treturn sshFail('malformed', 'KDF options must be empty for kdf none');\n\t}\n\tconst keyCount = reader.uint32();\n\tif (keyCount === 0) {\n\t\treturn sshFail('malformed', 'OpenSSH private key file holds no keys');\n\t}\n\tif (keyCount > 1) {\n\t\treturn sshFail('unsupported', 'OpenSSH private key files with several keys are not supported');\n\t}\n\tconst publicBlob = reader.string(MAX_STRING_BYTES);\n\tconst envelope = decodePublicBlob(publicBlob, options);\n\tconst section = reader.string(MAX_PRIVATE_KEY_FILE_BYTES);\n\tif (reader.remaining() !== 0) {\n\t\treturn sshFail('malformed', 'OpenSSH private key file has trailing data');\n\t}\n\tif (section.length === 0 || section.length % NO_CIPHER_BLOCK_SIZE !== 0) {\n\t\treturn sshFail('malformed', 'OpenSSH private section is not a multiple of the block size');\n\t}\n\tconst inner = createSshReader(section);\n\tconst firstCheck = inner.uint32();\n\tconst secondCheck = inner.uint32();\n\tif (firstCheck !== secondCheck) {\n\t\treturn sshFail('malformed', 'OpenSSH check integers differ');\n\t}\n\tconst privateMaterial = readPrivateMaterial(inner, keyTypeOf(envelope), options);\n\tconst comment = inner.text(MAX_STRING_BYTES);\n\tassertImportedComment(comment);\n\tassertPadding(inner);\n\tif (!samePublicMaterial(envelope, privateMaterial.pub)) {\n\t\treturn sshFail('key_mismatch', 'Private section public key differs from the file public key');\n\t}\n\tif (privateMaterial.kind === 'rsa') {\n\t\tassertRsaConsistent(privateMaterial);\n\t}\n\tconst publicKey = await importPublicMaterial(envelope, options);\n\tconst privateKey = await importPrivateMaterial(privateMaterial, envelope, options);\n\tawait assertKeyPairConsistent(privateKey, publicKey, envelope, options);\n\treturn {\n\t\tkeyType: keyTypeOf(envelope),\n\t\talgorithm: algorithmOf(envelope),\n\t\tpublicKey,\n\t\tprivateKey,\n\t\tcomment,\n\t\tfingerprint: await sha256Fingerprint(encodePublicBlob(envelope)),\n\t};\n}\n\nasync function toSshResult<T>(run: () => Promise<T>): Promise<SshResult<T>> {\n\ttry {\n\t\treturn successResult(await run());\n\t} catch (error) {\n\t\tif (isResultError(error)) {\n\t\t\tconst code = asSshErrorCode(error.code);\n\t\t\tif (code !== undefined) {\n\t\t\t\treturn failureResult<SshErrorCode>(code, error.error.message);\n\t\t\t}\n\t\t}\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult<SshErrorCode>(\n\t\t\t'malformed',\n\t\t\terror instanceof Error ? error.message : 'Malformed SSH key',\n\t\t);\n\t}\n}\n\n/**\n * Import an OpenSSH public-key line (`<type> <base64> [comment]`).\n *\n * Reads `ssh-rsa`, `ssh-ed25519`, and `ecdsa-sha2-nistp256/384/521` keys as\n * written by `ssh-keygen` into `.pub` files. The line key type must equal the\n * type inside the blob (RFC 4253 §6.6), an ECDSA curve identifier must equal\n * its key type suffix (RFC 5656 §3.1), and trailing data after the blob is\n * rejected. Fields are separated by spaces or tabs, one trailing line break\n * is allowed, and everything after the base64 field is the comment.\n * `authorized_keys` options and SSH certificate types are not read.\n *\n * Input is capped at 16 KiB and RSA moduli at 16384 bits. `input` is never\n * modified.\n *\n * @param input - The line as text or UTF-8 bytes\n * @param options - Policy options; see {@linkcode SshImportOptions}\n * @returns The WebCrypto verification key, its comment and its SHA-256 fingerprint\n *\n * @see {@linkcode importSshPublicKeyOrThrow} for the throwing variant\n * @see {@linkcode exportSshPublicKey} for the inverse operation\n */\nexport function importSshPublicKey(\n\tinput: string | Uint8Array,\n\toptions: SshImportOptions = {},\n): Promise<SshResult<ImportedSshPublicKey>> {\n\treturn toSshResult(() => decodePublicKeyLine(input, resolveImportOptions(options)));\n}\n\n/**\n * Throwing variant of {@linkcode importSshPublicKey}.\n *\n * @throws {ResultError} Carrying an {@linkcode SshErrorCode} as `code`\n */\nexport async function importSshPublicKeyOrThrow(\n\tinput: string | Uint8Array,\n\toptions: SshImportOptions = {},\n): Promise<ImportedSshPublicKey> {\n\treturn unwrap(await importSshPublicKey(input, options));\n}\n\n/**\n * Import an unencrypted single-key `openssh-key-v1` private key file.\n *\n * Accepts the `-----BEGIN OPENSSH PRIVATE KEY-----` PEM that `ssh-keygen`\n * writes for RSA, Ed25519 and ECDSA P-256/P-384/P-521 keys. The cipher and\n * KDF must both be `none` with empty KDF options; any other value returns\n * `unsupported`, as does a file holding several keys. The check integers,\n * the `1, 2, 3, ...` padding, the block alignment, and the absence of trailing\n * bytes are verified, and RSA integers must be canonical positive `mpint`s.\n *\n * The public key embedded in the file must equal the public half of the\n * private section and its key type, or the result is `key_mismatch`. The\n * private material is then checked cryptographically: for RSA, `p·q = n`,\n * `d·e ≡ 1` modulo both `p-1` and `q-1`, and `iqmp·q ≡ 1 (mod p)`; for every\n * key, a signature made with the private key must verify under the embedded\n * public key. For Ed25519 the 32-byte suffix of the private field must equal\n * the public key.\n *\n * Both keys are returned extractable. The decoded binary copy of the file is\n * zeroed before returning. JavaScript strings, including the PEM text and the\n * JWK members used for the import, cannot be zeroed, and `input` is never\n * modified.\n *\n * @param input - The PEM file as text or UTF-8 bytes, at most 32 KiB\n * @param options - Policy options; see {@linkcode SshImportOptions}\n *\n * @see {@linkcode importOpenSshPrivateKeyOrThrow} for the throwing variant\n * @see {@linkcode exportOpenSshPrivateKey} for the inverse operation\n */\nexport function importOpenSshPrivateKey(\n\tinput: string | Uint8Array,\n\toptions: SshImportOptions = {},\n): Promise<SshResult<ImportedOpenSshPrivateKey>> {\n\treturn toSshResult(() => decodePrivateKey(input, resolveImportOptions(options)));\n}\n\n/**\n * Throwing variant of {@linkcode importOpenSshPrivateKey}.\n *\n * @throws {ResultError} Carrying an {@linkcode SshErrorCode} as `code`\n */\nexport async function importOpenSshPrivateKeyOrThrow(\n\tinput: string | Uint8Array,\n\toptions: SshImportOptions = {},\n): Promise<ImportedOpenSshPrivateKey> {\n\treturn unwrap(await importOpenSshPrivateKey(input, options));\n}\n\nfunction exportFail(code: SshExportErrorCode, message: string): never {\n\treturn throwMicro509Error<SshExportErrorCode>(code, message);\n}\n\nfunction validCommentText(comment: string): boolean {\n\treturn typeof comment === 'string' && comment.isWellFormed() && !/[\\r\\n\\0]/.test(comment);\n}\n\nfunction oversizedComment(comment: string): boolean {\n\treturn (\n\t\tcomment.length > MAX_STRING_BYTES || new TextEncoder().encode(comment).length > MAX_STRING_BYTES\n\t);\n}\n\nfunction assertImportedComment(comment: string): void {\n\tif (!validCommentText(comment)) {\n\t\tsshFail('malformed', 'Comment must be well-formed Unicode without CR, LF or NUL');\n\t}\n\tif (oversizedComment(comment)) {\n\t\tsshFail('limit_exceeded', 'Comment exceeds 8192 UTF-8 bytes');\n\t}\n}\n\nfunction assertComment(comment: string): void {\n\tif (!validCommentText(comment) || oversizedComment(comment)) {\n\t\texportFail(\n\t\t\t'invalid_comment',\n\t\t\t'Comment must be well-formed Unicode without CR, LF or NUL and at most 8192 UTF-8 bytes',\n\t\t);\n\t}\n}\n\nfunction assertExportable(key: CryptoKey, type: KeyType): void {\n\tif (key.type !== type) {\n\t\texportFail('invalid_key', `Expected a ${type} key`);\n\t}\n\tif (!key.extractable) {\n\t\texportFail('not_extractable', 'The key must be extractable');\n\t}\n}\n\nfunction jwkBytes(\n\tjwk: JsonWebKey,\n\tmember: 'n' | 'e' | 'd' | 'p' | 'q' | 'qi' | 'x' | 'y',\n): Uint8Array {\n\tconst value = jwk[member];\n\tif (typeof value !== 'string') {\n\t\tthrow new Error(`WebCrypto key export lacks JWK member ${member}`);\n\t}\n\treturn fromBase64Url(value);\n}\n\nfunction publicMaterialFromJwk(jwk: JsonWebKey, algorithmName: string): SshPublicMaterial {\n\tif (jwk.kty === 'RSA') {\n\t\treturn { kind: 'rsa', e: jwkBytes(jwk, 'e'), n: jwkBytes(jwk, 'n') };\n\t}\n\tif (jwk.kty === 'OKP' && jwk.crv === 'Ed25519' && algorithmName === 'Ed25519') {\n\t\treturn { kind: 'ed25519', x: jwkBytes(jwk, 'x') };\n\t}\n\tif (jwk.kty === 'EC' && algorithmName === 'ECDSA') {\n\t\tconst curve = CURVE_NAMES.find((name) => name === jwk.crv);\n\t\tif (curve !== undefined) {\n\t\t\treturn { kind: 'ecdsa', curve, x: jwkBytes(jwk, 'x'), y: jwkBytes(jwk, 'y') };\n\t\t}\n\t}\n\treturn exportFail(\n\t\t'unsupported_algorithm',\n\t\t'Only RSA, ECDSA P-256/384/521 and Ed25519 are supported',\n\t);\n}\n\n/**\n * Export a public key as an OpenSSH public-key line.\n *\n * Writes `<type> <base64> [comment]` with padded base64 and no trailing line\n * break, the form `ssh-keygen` puts in `.pub` files. ECDSA points are written\n * uncompressed. The key must be an extractable RSA, ECDSA (P-256, P-384,\n * P-521) or Ed25519 public `CryptoKey`.\n *\n * @throws {ResultError} Carrying an {@linkcode SshExportErrorCode} as `code`\n *\n * @see {@linkcode importSshPublicKey} for the inverse operation\n */\nexport async function exportSshPublicKey(\n\tpublicKey: CryptoKey,\n\toptions: SshExportOptions = {},\n): Promise<string> {\n\tconst comment = options.comment === undefined ? '' : options.comment;\n\tassertComment(comment);\n\tassertExportable(publicKey, 'public');\n\tconst material = publicMaterialFromJwk(\n\t\tawait exportPublicJwk(publicKey),\n\t\tpublicKey.algorithm.name,\n\t);\n\tconst line = `${keyTypeOf(material)} ${base64Encode(encodePublicBlob(material))}`;\n\treturn comment === '' ? line : `${line} ${comment}`;\n}\n\n/**\n * Export a private key as an unencrypted `openssh-key-v1` PEM file.\n *\n * The file holds one key, cipher `none` and KDF `none`, with the check\n * integers drawn from the WebCrypto random source and the public key derived\n * from the private key. `ssh-keygen` reads it directly. Check integers are\n * random, so compare keys, not file bytes, between two exports.\n *\n * The private `CryptoKey` must be extractable. The binary encoding is zeroed\n * after the PEM text is built; the returned string and the JWK used for the\n * export cannot be zeroed.\n *\n * @throws {ResultError} Carrying an {@linkcode SshExportErrorCode} as `code`\n *\n * @see {@linkcode importOpenSshPrivateKey} for the inverse operation\n */\nexport async function exportOpenSshPrivateKey(\n\tprivateKey: CryptoKey,\n\toptions: SshExportOptions = {},\n): Promise<string> {\n\tconst comment = options.comment === undefined ? '' : options.comment;\n\tassertComment(comment);\n\tassertExportable(privateKey, 'private');\n\tconst jwk = await exportPrivateJwk(privateKey);\n\tconst material = publicMaterialFromJwk(jwk, privateKey.algorithm.name);\n\tconst fields = privateFields(material, jwk);\n\tconst checkInt = getCrypto().getRandomValues(new Uint32Array(1))[0] ?? 0;\n\tconst unpadded = concatBytes([\n\t\tsshUint32(checkInt),\n\t\tsshUint32(checkInt),\n\t\tsshTextString(keyTypeOf(material)),\n\t\tfields,\n\t\tsshTextString(comment),\n\t]);\n\tconst paddingLength =\n\t\t(NO_CIPHER_BLOCK_SIZE - (unpadded.length % NO_CIPHER_BLOCK_SIZE)) % NO_CIPHER_BLOCK_SIZE;\n\tconst section = concatBytes([\n\t\tunpadded,\n\t\tUint8Array.from({ length: paddingLength }, (_, index) => index + 1),\n\t]);\n\tconst file = concatBytes([\n\t\tAUTH_MAGIC,\n\t\tUint8Array.of(0),\n\t\tsshTextString('none'),\n\t\tsshTextString('none'),\n\t\tsshUint32(0),\n\t\tsshUint32(1),\n\t\tsshString(encodePublicBlob(material)),\n\t\tsshString(section),\n\t]);\n\ttry {\n\t\treturn pemEncode(PRIVATE_KEY_LABEL, file);\n\t} finally {\n\t\tunpadded.fill(0);\n\t\tsection.fill(0);\n\t\tfile.fill(0);\n\t\tfields.fill(0);\n\t}\n}\n\nfunction privateFields(material: SshPublicMaterial, jwk: JsonWebKey): Uint8Array {\n\tswitch (material.kind) {\n\t\tcase 'rsa':\n\t\t\treturn concatBytes([\n\t\t\t\tsshMpint(material.n),\n\t\t\t\tsshMpint(material.e),\n\t\t\t\tsshMpint(jwkBytes(jwk, 'd')),\n\t\t\t\tsshMpint(jwkBytes(jwk, 'qi')),\n\t\t\t\tsshMpint(jwkBytes(jwk, 'p')),\n\t\t\t\tsshMpint(jwkBytes(jwk, 'q')),\n\t\t\t]);\n\t\tcase 'ecdsa':\n\t\t\treturn concatBytes([\n\t\t\t\tsshTextString(CURVES[material.curve].identifier),\n\t\t\t\tsshString(ecPoint(material)),\n\t\t\t\tsshMpint(jwkBytes(jwk, 'd')),\n\t\t\t]);\n\t\tcase 'ed25519':\n\t\t\treturn concatBytes([\n\t\t\t\tsshString(material.x),\n\t\t\t\tsshString(concatBytes([jwkBytes(jwk, 'd'), material.x])),\n\t\t\t]);\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\n/**\n * The `SHA256:` fingerprint `ssh-keygen -l -E sha256` prints for a key.\n *\n * It is the SHA-256 digest of the SSH public-key blob (RFC 4253 §6.6 layout),\n * base64-encoded without padding and prefixed with `SHA256:`. It differs from a\n * certificate fingerprint and from a digest of the SPKI encoding. Pass a\n * public or private `CryptoKey`, or the raw blob bytes (the decoded base64\n * field of a public-key line). A private key must be extractable.\n *\n * @throws {ResultError} Carrying an {@linkcode SshExportErrorCode} when a `CryptoKey` cannot be encoded\n */\nexport async function sshFingerprintSha256(key: CryptoKey | Uint8Array): Promise<string> {\n\tif (key instanceof Uint8Array) {\n\t\treturn await sha256Fingerprint(key);\n\t}\n\tif (key.type === 'secret') {\n\t\texportFail('invalid_key', 'Expected a public or private key');\n\t}\n\tassertExportable(key, key.type);\n\tconst jwk = key.type === 'private' ? await exportPrivateJwk(key) : await exportPublicJwk(key);\n\tconst material = publicMaterialFromJwk(jwk, key.algorithm.name);\n\treturn await sha256Fingerprint(encodePublicBlob(material));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4LA,MACMA,IAA6B,OAC7BC,IAAkB,MAClBC,IAAmB,MACnBC,IAAuB,OAEvBC,IAAoB,uBACpBC,IAAa,WAAW,KAAK,mBAAmB,MAAcC,EAAU,WAAW,CAAC,CAAC,GAIrFC,IAAgB;CACrB;CACA;CACA;CACA;CACA;AACD;AAEA,SAAS,aAAa,GAAsC;CAC3D,OAAOA,EAAc,MAAM,MAAcC,MAAcC,CAAI;AAC5D;AAUA,MAAMC,IAAS;CACd,SAAS;EACR,YAAY;EACZ,MAAM;EACN,GAAGC,EAAgB;CACpB;CACA,SAAS;EACR,YAAY;EACZ,MAAM;EACN,GAAGA,EAAgB;CACpB;CACA,SAAS;EACR,YAAY;EACZ,MAAM;EACN,GAAGA,EAAgB;CACpB;AACD,GAEMC,IAAc;CAAC;CAAS;CAAS;AAAO,GAExCC,IAAwB;CAC7B,uBAAuB;CACvB,uBAAuB;CACvB,uBAAuB;AACxB;AAuCA,SAAS,qBAAqB,GAAkD;CAC/E,IAAI,OAAOC,KAAY,aAAYA,KAAoB,MAAM,QAA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A,EAAI,UAAU,IACH,CAAC,CAAC;AAC1D"}
1
+ {"version":3,"file":"ssh.js","names":["toArrayBuffer","concatBytes","PRIME_EC_CURVES","getCrypto","base64Decode","base64Encode","exportPrivateJwk","exportPublicJwk","importPrivateJwkOrThrow","importPublicJwkOrThrow","pemDecodeOrThrow","pemEncode","failureResult","isResultError","rethrowIfInvariant","successResult","throwMicro509Error","unwrap","asSshErrorCode","bigintToBytes","bytesEqual","bytesToBigint","createSshReader","decodeUtf8","sshFail","sshMpint","sshString","sshTextString","sshUint32","MAX_PRIVATE_KEY_FILE_BYTES","MAX_MPINT_BYTES","MAX_STRING_BYTES","MAX_RSA_MODULUS_BITS","PRIVATE_KEY_LABEL","AUTH_MAGIC","character","SSH_KEY_TYPES","name","candidate","CURVES","CURVE_NAMES","ECDSA_KEY_TYPE_CURVES","options","minRsaModulusBits","acceptCompressedEcPoints","rsa","rsaScheme","rsaHash","value","material","magnitude","bytes","padded","base","exponent","modulus","result","factor","remaining","curve","prefix","x","prime","b","size","xValue","rhs","root","wantOdd","y","point","reader","order","first","second","e","n","bits","blob","keyType","type","left","right","d","p","q","envelope","error","privateKey","publicKey","subtle","challenge","params","signature","digest","input","maxBytes","PUBLIC_KEY_LINE","text","match","typeToken","encoded","comment","envelopeType","pub","secret","iqmp","padding","byte","index","binary","magic","cipher","kdf","keyCount","section","inner","privateMaterial","run","code","message","key","jwk","member","algorithmName","line","fields","checkInt","unpadded","paddingLength","_","file"],"sources":["../../src/ssh/ssh.ts"],"sourcesContent":["/**\n * OpenSSH public-key lines, unencrypted `openssh-key-v1` private keys, and\n * `SHA256:` fingerprints for RSA, Ed25519, and ECDSA on P-256, P-384 and P-521.\n *\n * Keys move through the existing WebCrypto, JWK and PKCS#8/SPKI APIs of\n * `micro509/keys`. Nothing here opens a connection, speaks the SSH transport,\n * reads SSH certificates, evaluates `authorized_keys` options, or decrypts a\n * private key.\n *\n * The `ssh-rsa` key type names the RSA public-key encoding (RFC 4253 §6.6). It\n * does not select a signature hash: RFC 8332 §3 keeps the `ssh-rsa` key format\n * for the `rsa-sha2-256` and `rsa-sha2-512` signature algorithms. Importing an\n * `ssh-rsa` key enables no SHA-1 signature.\n *\n * @example\n * ```ts\n * import { generateKeyPair, unwrap } from 'micro509';\n * import {\n * \texportOpenSshPrivateKey,\n * \texportSshPublicKey,\n * \timportOpenSshPrivateKey,\n * } from 'micro509/ssh';\n *\n * const keys = await generateKeyPair({ kind: 'ed25519' });\n * const line = await exportSshPublicKey(keys.publicKey, { comment: 'me@host' });\n * const pem = await exportOpenSshPrivateKey(keys.privateKey, { comment: 'me@host' });\n * const imported = unwrap(await importOpenSshPrivateKey(pem));\n * console.log(line, imported.fingerprint);\n * ```\n *\n * @module\n */\n\nimport { toArrayBuffer } from '#micro509/internal/asn1/asn1';\nimport { concatBytes } from '#micro509/internal/asn1/der';\nimport { PRIME_EC_CURVES } from '#micro509/internal/crypto/prime-ec';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport { base64Decode, base64Encode } from '#micro509/internal/shared/base64';\nimport type {\n\tEcNamedCurve,\n\tImportEcKeyInput,\n\tImportEd25519KeyInput,\n\tImportRsaKeyInput,\n\tRsaHash,\n\tRsaSignatureScheme,\n} from '#micro509/keys/keys';\nimport {\n\texportPrivateJwk,\n\texportPublicJwk,\n\timportPrivateJwkOrThrow,\n\timportPublicJwkOrThrow,\n} from '#micro509/keys/keys';\nimport { pemDecodeOrThrow, pemEncode } from '#micro509/pem/pem';\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport {\n\tfailureResult,\n\tisResultError,\n\trethrowIfInvariant,\n\tsuccessResult,\n\tthrowMicro509Error,\n\tunwrap,\n} from '#micro509/result/result';\nimport type { SshErrorCode, SshReader } from '#micro509/ssh/wire';\nimport {\n\tasSshErrorCode,\n\tbigintToBytes,\n\tbytesEqual,\n\tbytesToBigint,\n\tcreateSshReader,\n\tdecodeUtf8,\n\tsshFail,\n\tsshMpint,\n\tsshString,\n\tsshTextString,\n\tsshUint32,\n} from '#micro509/ssh/wire';\n\nexport type { SshErrorCode } from '#micro509/ssh/wire';\n\n/** SSH public-key type names (RFC 4253 §6.6, RFC 5656 §6.2, RFC 8709 §4) this module reads and writes. */\nexport type SshKeyType =\n\t| 'ssh-rsa'\n\t| 'ssh-ed25519'\n\t| 'ecdsa-sha2-nistp256'\n\t| 'ecdsa-sha2-nistp384'\n\t| 'ecdsa-sha2-nistp521';\n\n/** Algorithm family of an SSH key, discriminated by `kind`. */\nexport type SshKeyAlgorithm =\n\t| {\n\t\t\t/** RSA. */\n\t\t\treadonly kind: 'rsa';\n\t\t\t/** Modulus size in bits. */\n\t\t\treadonly modulusBits: number;\n\t }\n\t| {\n\t\t\t/** ECDSA. */\n\t\t\treadonly kind: 'ecdsa';\n\t\t\t/** NIST curve. */\n\t\t\treadonly curve: EcNamedCurve;\n\t }\n\t| {\n\t\t\t/** Ed25519. */\n\t\t\treadonly kind: 'ed25519';\n\t };\n\n/** Structured failure payload of the SSH key import functions. */\nexport interface SshFailure extends Micro509Error<SshErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/**\n * Success-or-failure result of the SSH key import functions.\n *\n * `code` is `'malformed'` for structurally invalid input, `'unsupported'` for a\n * valid construct this module does not read (encrypted keys, multi-key files,\n * other key types, RSA below the minimum size, compressed points unless\n * accepted), `'limit_exceeded'` for an implementation bound, and\n * `'key_mismatch'` when the declared key types or the embedded public and\n * private keys disagree. No message contains private key material.\n */\nexport type SshResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| ErrorResult<SshErrorCode, Record<never, never>, SshFailure>;\n\n/** Policy options of the SSH key import functions. */\nexport interface SshImportOptions {\n\t/**\n\t * Smallest accepted RSA modulus in bits, an integer from 1 to 16384. Default: `2048`.\n\t *\n\t * The standards leave key strength to the relying party. RFC 8332 §5.1 calls\n\t * 2048 bits prudent; OpenSSH itself accepts 1024.\n\t */\n\treadonly minRsaModulusBits?: number;\n\t/**\n\t * Accept SEC 1 compressed ECDSA points. Default: `false`.\n\t *\n\t * RFC 5656 §3.1 allows point compression; OpenSSH reads and writes only\n\t * uncompressed points.\n\t */\n\treadonly acceptCompressedEcPoints?: boolean;\n\t/**\n\t * WebCrypto parameters of an imported RSA key. Default: PKCS#1 v1.5 with\n\t * SHA-256. These choose how the `CryptoKey` signs; they do not change the\n\t * `ssh-rsa` key encoding.\n\t */\n\treadonly rsa?: {\n\t\t/** Signature padding scheme. */\n\t\treadonly scheme?: RsaSignatureScheme;\n\t\t/** Signature hash. */\n\t\treadonly hash?: RsaHash;\n\t};\n}\n\n/** Public key read from an OpenSSH public-key line. */\nexport interface ImportedSshPublicKey {\n\t/** SSH key type name. */\n\treadonly keyType: SshKeyType;\n\t/** Algorithm family and size. */\n\treadonly algorithm: SshKeyAlgorithm;\n\t/** Extractable WebCrypto key with `verify` usage. */\n\treadonly publicKey: CryptoKey;\n\t/** The line's trailing comment; empty when absent. */\n\treadonly comment: string;\n\t/** `SHA256:` fingerprint of the public-key blob. */\n\treadonly fingerprint: string;\n}\n\n/** Key pair read from an `openssh-key-v1` private-key file. */\nexport interface ImportedOpenSshPrivateKey extends ImportedSshPublicKey {\n\t/** Extractable WebCrypto private key with `sign` usage. */\n\treadonly privateKey: CryptoKey;\n}\n\n/** Options of {@linkcode exportSshPublicKey} and {@linkcode exportOpenSshPrivateKey}. */\nexport interface SshExportOptions {\n\t/** Comment to attach, at most 8192 UTF-8 bytes. Must be well-formed Unicode without CR, LF or NUL. Default: empty. */\n\treadonly comment?: string;\n}\n\n/** Machine-readable failure reason of the SSH key export functions. */\nexport type SshExportErrorCode =\n\t| 'invalid_key'\n\t| 'unsupported_algorithm'\n\t| 'not_extractable'\n\t| 'invalid_comment';\n\nconst MAX_PUBLIC_KEY_LINE_BYTES = 16 * 1024;\nconst MAX_PRIVATE_KEY_FILE_BYTES = 32 * 1024;\nconst MAX_MPINT_BYTES = 2049;\nconst MAX_STRING_BYTES = 8192;\nconst MAX_RSA_MODULUS_BITS = 16384;\nconst DEFAULT_MIN_RSA_MODULUS_BITS = 2048;\nconst PRIVATE_KEY_LABEL = 'OPENSSH PRIVATE KEY';\nconst AUTH_MAGIC = Uint8Array.from('openssh-key-v1', (character) => character.charCodeAt(0));\nconst NO_CIPHER_BLOCK_SIZE = 8;\nconst ED25519_KEY_BYTES = 32;\n\nconst SSH_KEY_TYPES = [\n\t'ssh-rsa',\n\t'ssh-ed25519',\n\t'ecdsa-sha2-nistp256',\n\t'ecdsa-sha2-nistp384',\n\t'ecdsa-sha2-nistp521',\n] as const satisfies readonly SshKeyType[];\n\nfunction asSshKeyType(name: string): SshKeyType | undefined {\n\treturn SSH_KEY_TYPES.find((candidate) => candidate === name);\n}\n\ninterface CurveInfo {\n\treadonly identifier: 'nistp256' | 'nistp384' | 'nistp521';\n\treadonly size: number;\n\treadonly hash: 'SHA-256' | 'SHA-384' | 'SHA-512';\n\treadonly prime: bigint;\n\treadonly b: bigint;\n}\n\nconst CURVES = {\n\t'P-256': {\n\t\tidentifier: 'nistp256',\n\t\thash: 'SHA-256',\n\t\t...PRIME_EC_CURVES['P-256'],\n\t},\n\t'P-384': {\n\t\tidentifier: 'nistp384',\n\t\thash: 'SHA-384',\n\t\t...PRIME_EC_CURVES['P-384'],\n\t},\n\t'P-521': {\n\t\tidentifier: 'nistp521',\n\t\thash: 'SHA-512',\n\t\t...PRIME_EC_CURVES['P-521'],\n\t},\n} as const satisfies Record<EcNamedCurve, CurveInfo>;\n\nconst CURVE_NAMES = ['P-256', 'P-384', 'P-521'] as const satisfies readonly EcNamedCurve[];\n\nconst ECDSA_KEY_TYPE_CURVES = {\n\t'ecdsa-sha2-nistp256': 'P-256',\n\t'ecdsa-sha2-nistp384': 'P-384',\n\t'ecdsa-sha2-nistp521': 'P-521',\n} as const satisfies Record<Exclude<SshKeyType, 'ssh-rsa' | 'ssh-ed25519'>, EcNamedCurve>;\n\ntype SshPublicMaterial =\n\t| { readonly kind: 'rsa'; readonly e: Uint8Array; readonly n: Uint8Array }\n\t| {\n\t\t\treadonly kind: 'ecdsa';\n\t\t\treadonly curve: EcNamedCurve;\n\t\t\treadonly x: Uint8Array;\n\t\t\treadonly y: Uint8Array;\n\t }\n\t| { readonly kind: 'ed25519'; readonly x: Uint8Array };\n\ntype SshPrivateMaterial =\n\t| {\n\t\t\treadonly kind: 'rsa';\n\t\t\treadonly pub: Extract<SshPublicMaterial, { kind: 'rsa' }>;\n\t\t\treadonly d: Uint8Array;\n\t\t\treadonly p: Uint8Array;\n\t\t\treadonly q: Uint8Array;\n\t\t\treadonly iqmp: Uint8Array;\n\t }\n\t| {\n\t\t\treadonly kind: 'ecdsa';\n\t\t\treadonly pub: Extract<SshPublicMaterial, { kind: 'ecdsa' }>;\n\t\t\treadonly d: Uint8Array;\n\t }\n\t| {\n\t\t\treadonly kind: 'ed25519';\n\t\t\treadonly pub: Extract<SshPublicMaterial, { kind: 'ed25519' }>;\n\t\t\treadonly seed: Uint8Array;\n\t };\n\ninterface ResolvedImportOptions {\n\treadonly minRsaModulusBits: number;\n\treadonly acceptCompressedEcPoints: boolean;\n\treadonly rsaScheme: RsaSignatureScheme;\n\treadonly rsaHash: RsaHash;\n}\n\nfunction resolveImportOptions(options: SshImportOptions): ResolvedImportOptions {\n\tif (typeof options !== 'object' || options === null || Array.isArray(options)) {\n\t\treturn sshFail('invalid_options', 'SSH import options must be an object');\n\t}\n\tconst minRsaModulusBits =\n\t\toptions.minRsaModulusBits === undefined\n\t\t\t? DEFAULT_MIN_RSA_MODULUS_BITS\n\t\t\t: options.minRsaModulusBits;\n\tif (\n\t\t!Number.isSafeInteger(minRsaModulusBits) ||\n\t\tminRsaModulusBits < 1 ||\n\t\tminRsaModulusBits > MAX_RSA_MODULUS_BITS\n\t) {\n\t\treturn sshFail('invalid_options', 'minRsaModulusBits must be an integer from 1 to 16384');\n\t}\n\tconst acceptCompressedEcPoints =\n\t\toptions.acceptCompressedEcPoints === undefined ? false : options.acceptCompressedEcPoints;\n\tif (typeof acceptCompressedEcPoints !== 'boolean') {\n\t\treturn sshFail('invalid_options', 'acceptCompressedEcPoints must be a boolean');\n\t}\n\tconst rsa = options.rsa === undefined ? {} : options.rsa;\n\tif (typeof rsa !== 'object' || rsa === null || Array.isArray(rsa)) {\n\t\treturn sshFail('invalid_options', 'rsa must be an object');\n\t}\n\tconst rsaScheme = rsa.scheme === undefined ? 'pkcs1-v1_5' : rsa.scheme;\n\tconst rsaHash = rsa.hash === undefined ? 'SHA-256' : rsa.hash;\n\tif (rsaScheme !== 'pkcs1-v1_5' && rsaScheme !== 'pss') {\n\t\treturn sshFail('invalid_options', 'Unsupported RSA signature scheme');\n\t}\n\tif (rsaHash !== 'SHA-256' && rsaHash !== 'SHA-384' && rsaHash !== 'SHA-512') {\n\t\treturn sshFail('invalid_options', 'Unsupported RSA signature hash');\n\t}\n\treturn { minRsaModulusBits, acceptCompressedEcPoints, rsaScheme, rsaHash };\n}\n\nfunction unhandledKey(value: never): never {\n\tthrow new Error(`Unhandled SSH key: ${String(value)}`);\n}\n\nfunction keyTypeOf(material: SshPublicMaterial): SshKeyType {\n\tswitch (material.kind) {\n\t\tcase 'rsa':\n\t\t\treturn 'ssh-rsa';\n\t\tcase 'ed25519':\n\t\t\treturn 'ssh-ed25519';\n\t\tcase 'ecdsa':\n\t\t\treturn `ecdsa-sha2-${CURVES[material.curve].identifier}`;\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\nfunction bitLength(magnitude: Uint8Array): number {\n\treturn (magnitude.length - 1) * 8 + 32 - Math.clz32(magnitude[0] ?? 0);\n}\n\nfunction algorithmOf(material: SshPublicMaterial): SshKeyAlgorithm {\n\tswitch (material.kind) {\n\t\tcase 'rsa':\n\t\t\treturn { kind: 'rsa', modulusBits: bitLength(material.n) };\n\t\tcase 'ecdsa':\n\t\t\treturn { kind: 'ecdsa', curve: material.curve };\n\t\tcase 'ed25519':\n\t\t\treturn { kind: 'ed25519' };\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n\treturn base64Encode(bytes).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction fromBase64Url(value: string): Uint8Array {\n\tconst padded = value.replace(/-/g, '+').replace(/_/g, '/');\n\treturn base64Decode(padded.padEnd(Math.ceil(padded.length / 4) * 4, '='));\n}\n\nfunction modPow(base: bigint, exponent: bigint, modulus: bigint): bigint {\n\tlet result = 1n;\n\tlet factor = base % modulus;\n\tlet remaining = exponent;\n\twhile (remaining > 0n) {\n\t\tif ((remaining & 1n) === 1n) {\n\t\t\tresult = (result * factor) % modulus;\n\t\t}\n\t\tfactor = (factor * factor) % modulus;\n\t\tremaining >>= 1n;\n\t}\n\treturn result;\n}\n\nfunction decompressPoint(curve: EcNamedCurve, prefix: number, x: Uint8Array): Uint8Array {\n\tconst { prime, b, size } = CURVES[curve];\n\tconst xValue = bytesToBigint(x);\n\tif (xValue >= prime) {\n\t\treturn sshFail('malformed', 'ECDSA point coordinate is out of range');\n\t}\n\tconst rhs = ((((xValue * xValue - 3n) * xValue + b) % prime) + prime) % prime;\n\tconst root = modPow(rhs, (prime + 1n) / 4n, prime);\n\tif ((root * root) % prime !== rhs) {\n\t\treturn sshFail('malformed', 'ECDSA point is not on the curve');\n\t}\n\tconst wantOdd = prefix === 0x03;\n\tconst y = ((root & 1n) === 1n) === wantOdd ? root : prime - root;\n\treturn bigintToBytes(y, size);\n}\n\nfunction readPoint(\n\tcurve: EcNamedCurve,\n\tpoint: Uint8Array,\n\toptions: ResolvedImportOptions,\n): { readonly x: Uint8Array; readonly y: Uint8Array } {\n\tconst { size } = CURVES[curve];\n\tconst prefix = point[0];\n\tif (prefix === 0x04 && point.length === 1 + 2 * size) {\n\t\treturn { x: point.subarray(1, 1 + size), y: point.subarray(1 + size) };\n\t}\n\tif ((prefix === 0x02 || prefix === 0x03) && point.length === 1 + size) {\n\t\tif (!options.acceptCompressedEcPoints) {\n\t\t\treturn sshFail('unsupported', 'Compressed ECDSA points need acceptCompressedEcPoints');\n\t\t}\n\t\tconst x = point.subarray(1);\n\t\treturn { x, y: decompressPoint(curve, prefix, x) };\n\t}\n\treturn sshFail('malformed', 'ECDSA point encoding is invalid');\n}\n\nfunction readRsaPublic(\n\treader: SshReader,\n\torder: 'e-n' | 'n-e',\n\toptions: ResolvedImportOptions,\n): Extract<SshPublicMaterial, { kind: 'rsa' }> {\n\tconst first = reader.mpint(MAX_MPINT_BYTES);\n\tconst second = reader.mpint(MAX_MPINT_BYTES);\n\tconst [e, n] = order === 'e-n' ? [first, second] : [second, first];\n\tconst bits = bitLength(n);\n\tif (bits > MAX_RSA_MODULUS_BITS) {\n\t\treturn sshFail('limit_exceeded', `RSA modulus of ${bits} bits exceeds ${MAX_RSA_MODULUS_BITS}`);\n\t}\n\tif (bits < options.minRsaModulusBits) {\n\t\treturn sshFail(\n\t\t\t'unsupported',\n\t\t\t`RSA modulus of ${bits} bits is below ${options.minRsaModulusBits}`,\n\t\t);\n\t}\n\tconst exponent = bytesToBigint(e);\n\tif (exponent < 3n || (exponent & 1n) === 0n || exponent >= bytesToBigint(n)) {\n\t\treturn sshFail('malformed', 'RSA public exponent is invalid');\n\t}\n\treturn { kind: 'rsa', e, n };\n}\n\nfunction readEcdsaPublic(\n\treader: SshReader,\n\tcurve: EcNamedCurve,\n\toptions: ResolvedImportOptions,\n): Extract<SshPublicMaterial, { kind: 'ecdsa' }> {\n\tif (reader.name() !== CURVES[curve].identifier) {\n\t\treturn sshFail('key_mismatch', 'ECDSA curve identifier disagrees with the key type');\n\t}\n\tconst point = reader.string(MAX_STRING_BYTES);\n\treturn { kind: 'ecdsa', curve, ...readPoint(curve, point, options) };\n}\n\nfunction readEd25519Public(reader: SshReader): Extract<SshPublicMaterial, { kind: 'ed25519' }> {\n\tconst x = reader.string(MAX_STRING_BYTES);\n\tif (x.length !== ED25519_KEY_BYTES) {\n\t\treturn sshFail('malformed', 'Ed25519 public key is not 32 bytes');\n\t}\n\treturn { kind: 'ed25519', x };\n}\n\nfunction decodePublicBlob(blob: Uint8Array, options: ResolvedImportOptions): SshPublicMaterial {\n\tconst reader = createSshReader(blob);\n\tconst keyType = asSshKeyType(reader.name());\n\tif (keyType === undefined) {\n\t\treturn sshFail('unsupported', 'Unsupported SSH key type');\n\t}\n\tlet material: SshPublicMaterial;\n\tswitch (keyType) {\n\t\tcase 'ssh-rsa':\n\t\t\tmaterial = readRsaPublic(reader, 'e-n', options);\n\t\t\tbreak;\n\t\tcase 'ssh-ed25519':\n\t\t\tmaterial = readEd25519Public(reader);\n\t\t\tbreak;\n\t\tcase 'ecdsa-sha2-nistp256':\n\t\tcase 'ecdsa-sha2-nistp384':\n\t\tcase 'ecdsa-sha2-nistp521': {\n\t\t\tmaterial = readEcdsaPublic(reader, ECDSA_KEY_TYPE_CURVES[keyType], options);\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\treturn unhandledKey(keyType);\n\t}\n\tif (reader.remaining() !== 0) {\n\t\treturn sshFail('malformed', 'SSH public key has trailing data');\n\t}\n\treturn material;\n}\n\nfunction ecPoint(material: Extract<SshPublicMaterial, { kind: 'ecdsa' }>): Uint8Array {\n\treturn concatBytes([Uint8Array.of(0x04), material.x, material.y]);\n}\n\nfunction encodePublicBlob(material: SshPublicMaterial): Uint8Array {\n\tconst type = sshTextString(keyTypeOf(material));\n\tswitch (material.kind) {\n\t\tcase 'rsa':\n\t\t\treturn concatBytes([type, sshMpint(material.e), sshMpint(material.n)]);\n\t\tcase 'ed25519':\n\t\t\treturn concatBytes([type, sshString(material.x)]);\n\t\tcase 'ecdsa':\n\t\t\treturn concatBytes([\n\t\t\t\ttype,\n\t\t\t\tsshTextString(CURVES[material.curve].identifier),\n\t\t\t\tsshString(ecPoint(material)),\n\t\t\t]);\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\nfunction samePublicMaterial(left: SshPublicMaterial, right: SshPublicMaterial): boolean {\n\treturn bytesEqual(encodePublicBlob(left), encodePublicBlob(right));\n}\n\nfunction publicJwk(material: SshPublicMaterial): JsonWebKey {\n\tswitch (material.kind) {\n\t\tcase 'rsa':\n\t\t\treturn { kty: 'RSA', n: toBase64Url(material.n), e: toBase64Url(material.e) };\n\t\tcase 'ecdsa':\n\t\t\treturn {\n\t\t\t\tkty: 'EC',\n\t\t\t\tcrv: material.curve,\n\t\t\t\tx: toBase64Url(material.x),\n\t\t\t\ty: toBase64Url(material.y),\n\t\t\t};\n\t\tcase 'ed25519':\n\t\t\treturn { kty: 'OKP', crv: 'Ed25519', x: toBase64Url(material.x) };\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\nfunction privateJwk(material: SshPrivateMaterial): JsonWebKey {\n\tswitch (material.kind) {\n\t\tcase 'rsa': {\n\t\t\tconst d = bytesToBigint(material.d);\n\t\t\tconst p = bytesToBigint(material.p);\n\t\t\tconst q = bytesToBigint(material.q);\n\t\t\treturn {\n\t\t\t\t...publicJwk(material.pub),\n\t\t\t\td: toBase64Url(material.d),\n\t\t\t\tp: toBase64Url(material.p),\n\t\t\t\tq: toBase64Url(material.q),\n\t\t\t\tdp: toBase64Url(bigintToBytes(d % (p - 1n))),\n\t\t\t\tdq: toBase64Url(bigintToBytes(d % (q - 1n))),\n\t\t\t\tqi: toBase64Url(material.iqmp),\n\t\t\t};\n\t\t}\n\t\tcase 'ecdsa':\n\t\t\treturn {\n\t\t\t\t...publicJwk(material.pub),\n\t\t\t\td: toBase64Url(bigintToBytes(bytesToBigint(material.d), CURVES[material.pub.curve].size)),\n\t\t\t};\n\t\tcase 'ed25519':\n\t\t\treturn { ...publicJwk(material.pub), d: toBase64Url(material.seed) };\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\ntype WebCryptoImportInput = ImportRsaKeyInput | ImportEcKeyInput | ImportEd25519KeyInput;\n\nfunction importInputFor(\n\tmaterial: SshPublicMaterial,\n\toptions: ResolvedImportOptions,\n): WebCryptoImportInput {\n\tswitch (material.kind) {\n\t\tcase 'rsa':\n\t\t\treturn { kind: 'rsa', scheme: options.rsaScheme, hash: options.rsaHash };\n\t\tcase 'ecdsa':\n\t\t\treturn { kind: 'ecdsa', curve: material.curve };\n\t\tcase 'ed25519':\n\t\t\treturn { kind: 'ed25519' };\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\nfunction signParams(\n\tmaterial: SshPublicMaterial,\n\toptions: ResolvedImportOptions,\n): AlgorithmIdentifier | RsaPssParams | EcdsaParams {\n\tswitch (material.kind) {\n\t\tcase 'rsa':\n\t\t\treturn options.rsaScheme === 'pss'\n\t\t\t\t? { name: 'RSA-PSS', saltLength: 32 }\n\t\t\t\t: { name: 'RSASSA-PKCS1-v1_5' };\n\t\tcase 'ecdsa':\n\t\t\treturn { name: 'ECDSA', hash: CURVES[material.curve].hash };\n\t\tcase 'ed25519':\n\t\t\treturn { name: 'Ed25519' };\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\nasync function importPublicMaterial(\n\tmaterial: SshPublicMaterial,\n\toptions: ResolvedImportOptions,\n): Promise<CryptoKey> {\n\treturn await importPublicJwkOrThrow(publicJwk(material), importInputFor(material, options));\n}\n\nasync function importPrivateMaterial(\n\tmaterial: SshPrivateMaterial,\n\tenvelope: SshPublicMaterial,\n\toptions: ResolvedImportOptions,\n): Promise<CryptoKey> {\n\ttry {\n\t\treturn await importPrivateJwkOrThrow(privateJwk(material), importInputFor(envelope, options));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn sshFail('key_mismatch', 'Private key material is invalid for the embedded public key');\n\t}\n}\n\nasync function assertKeyPairConsistent(\n\tprivateKey: CryptoKey,\n\tpublicKey: CryptoKey,\n\tmaterial: SshPublicMaterial,\n\toptions: ResolvedImportOptions,\n): Promise<void> {\n\tconst { subtle } = getCrypto();\n\tconst challenge = getCrypto().getRandomValues(new Uint8Array(32));\n\tconst params = signParams(material, options);\n\tconst signature = await subtle.sign(params, privateKey, challenge);\n\tif (!(await subtle.verify(params, publicKey, signature, challenge))) {\n\t\tsshFail('key_mismatch', 'Private key does not match the embedded public key');\n\t}\n}\n\nasync function sha256Fingerprint(blob: Uint8Array): Promise<string> {\n\tconst digest = new Uint8Array(await getCrypto().subtle.digest('SHA-256', toArrayBuffer(blob)));\n\treturn `SHA256:${base64Encode(digest).replace(/=+$/, '')}`;\n}\n\nfunction textOf(input: string | Uint8Array, maxBytes: number): string {\n\tif (typeof input === 'string') {\n\t\tif (input.length > maxBytes) {\n\t\t\treturn sshFail('limit_exceeded', `SSH key input exceeds ${maxBytes} bytes`);\n\t\t}\n\t\tconst bytes = new TextEncoder().encode(input);\n\t\tif (bytes.length > maxBytes) {\n\t\t\treturn sshFail('limit_exceeded', `SSH key input exceeds ${maxBytes} bytes`);\n\t\t}\n\t\treturn input;\n\t}\n\tif (input.length > maxBytes) {\n\t\treturn sshFail('limit_exceeded', `SSH key input exceeds ${maxBytes} bytes`);\n\t}\n\treturn decodeUtf8(input);\n}\n\nconst PUBLIC_KEY_LINE = /^([^ \\t]+)[ \\t]+([A-Za-z0-9+/]+={0,2})(?:[ \\t]+(.*))?$/s;\n\nasync function decodePublicKeyLine(\n\tinput: string | Uint8Array,\n\toptions: ResolvedImportOptions,\n): Promise<ImportedSshPublicKey> {\n\tconst text = textOf(input, MAX_PUBLIC_KEY_LINE_BYTES).replace(/\\r?\\n$/, '');\n\tif (/[\\r\\n]/.test(text)) {\n\t\treturn sshFail('malformed', 'SSH public key must be a single line');\n\t}\n\tconst match = PUBLIC_KEY_LINE.exec(text);\n\tif (match === null) {\n\t\treturn sshFail('malformed', 'SSH public key line is not \"<type> <base64> [comment]\"');\n\t}\n\tconst [, typeToken = '', encoded = '', comment = ''] = match;\n\tassertImportedComment(comment);\n\tconst keyType = asSshKeyType(typeToken);\n\tif (keyType === undefined) {\n\t\treturn sshFail('unsupported', 'Unsupported SSH key type');\n\t}\n\tconst blob = base64Decode(encoded);\n\tconst material = decodePublicBlob(blob, options);\n\tif (keyTypeOf(material) !== keyType) {\n\t\treturn sshFail('key_mismatch', 'Line key type disagrees with the key blob');\n\t}\n\treturn {\n\t\tkeyType,\n\t\talgorithm: algorithmOf(material),\n\t\tpublicKey: await importPublicMaterial(material, options),\n\t\tcomment,\n\t\tfingerprint: await sha256Fingerprint(encodePublicBlob(material)),\n\t};\n}\n\nfunction readPrivateMaterial(\n\treader: SshReader,\n\tenvelopeType: SshKeyType,\n\toptions: ResolvedImportOptions,\n): SshPrivateMaterial {\n\tconst declared = reader.name();\n\tif (declared !== envelopeType) {\n\t\treturn sshFail('key_mismatch', 'Private section key type disagrees with the public key');\n\t}\n\tswitch (envelopeType) {\n\t\tcase 'ssh-rsa': {\n\t\t\tconst pub = readRsaPublic(reader, 'n-e', options);\n\t\t\tconst d = reader.mpint(MAX_MPINT_BYTES);\n\t\t\tconst iqmp = reader.mpint(MAX_MPINT_BYTES);\n\t\t\tconst p = reader.mpint(MAX_MPINT_BYTES);\n\t\t\tconst q = reader.mpint(MAX_MPINT_BYTES);\n\t\t\treturn { kind: 'rsa', pub, d, iqmp, p, q };\n\t\t}\n\t\tcase 'ssh-ed25519': {\n\t\t\tconst pub = readEd25519Public(reader);\n\t\t\tconst secret = reader.string(MAX_STRING_BYTES);\n\t\t\tif (secret.length !== 2 * ED25519_KEY_BYTES) {\n\t\t\t\treturn sshFail('malformed', 'Ed25519 private key is not 64 bytes');\n\t\t\t}\n\t\t\tif (!bytesEqual(secret.subarray(ED25519_KEY_BYTES), pub.x)) {\n\t\t\t\treturn sshFail('key_mismatch', 'Ed25519 private key suffix differs from the public key');\n\t\t\t}\n\t\t\treturn { kind: 'ed25519', pub, seed: secret.subarray(0, ED25519_KEY_BYTES) };\n\t\t}\n\t\tcase 'ecdsa-sha2-nistp256':\n\t\tcase 'ecdsa-sha2-nistp384':\n\t\tcase 'ecdsa-sha2-nistp521': {\n\t\t\tconst pub = readEcdsaPublic(reader, ECDSA_KEY_TYPE_CURVES[envelopeType], options);\n\t\t\tconst d = reader.mpint(MAX_MPINT_BYTES);\n\t\t\tif (d.length > CURVES[pub.curve].size) {\n\t\t\t\treturn sshFail('malformed', 'ECDSA private scalar is larger than the curve order');\n\t\t\t}\n\t\t\treturn { kind: 'ecdsa', pub, d };\n\t\t}\n\t\tdefault:\n\t\t\treturn unhandledKey(envelopeType);\n\t}\n}\n\nfunction assertRsaConsistent(material: Extract<SshPrivateMaterial, { kind: 'rsa' }>): void {\n\tconst n = bytesToBigint(material.pub.n);\n\tconst e = bytesToBigint(material.pub.e);\n\tconst d = bytesToBigint(material.d);\n\tconst p = bytesToBigint(material.p);\n\tconst q = bytesToBigint(material.q);\n\tconst iqmp = bytesToBigint(material.iqmp);\n\tif (p < 3n || q < 3n || p * q !== n) {\n\t\tsshFail('key_mismatch', 'RSA primes do not multiply to the modulus');\n\t}\n\tif (d >= n || (d * e) % (p - 1n) !== 1n || (d * e) % (q - 1n) !== 1n) {\n\t\tsshFail('key_mismatch', 'RSA private exponent does not match the public exponent');\n\t}\n\tif (iqmp >= p || (iqmp * q) % p !== 1n) {\n\t\tsshFail('key_mismatch', 'RSA coefficient is not the inverse of q modulo p');\n\t}\n}\n\nfunction assertPadding(reader: SshReader): void {\n\tconst padding = reader.raw(reader.remaining());\n\tif (padding.length >= NO_CIPHER_BLOCK_SIZE) {\n\t\tsshFail('malformed', 'OpenSSH private key padding is too long');\n\t}\n\tpadding.forEach((byte, index) => {\n\t\tif (byte !== index + 1) {\n\t\t\tsshFail('malformed', 'OpenSSH private key padding is invalid');\n\t\t}\n\t});\n}\n\nasync function decodePrivateKey(\n\tinput: string | Uint8Array,\n\toptions: ResolvedImportOptions,\n): Promise<ImportedOpenSshPrivateKey> {\n\tconst text = textOf(input, MAX_PRIVATE_KEY_FILE_BYTES);\n\tconst binary = pemDecodeOrThrow(PRIVATE_KEY_LABEL, text);\n\ttry {\n\t\treturn await decodePrivateBinary(binary, options);\n\t} finally {\n\t\tbinary.fill(0);\n\t}\n}\n\nasync function decodePrivateBinary(\n\tbinary: Uint8Array,\n\toptions: ResolvedImportOptions,\n): Promise<ImportedOpenSshPrivateKey> {\n\tconst reader = createSshReader(binary);\n\tconst magic = reader.raw(AUTH_MAGIC.length + 1);\n\tif (\n\t\t!bytesEqual(magic.subarray(0, AUTH_MAGIC.length), AUTH_MAGIC) ||\n\t\tmagic[AUTH_MAGIC.length] !== 0\n\t) {\n\t\treturn sshFail('malformed', 'Missing openssh-key-v1 magic');\n\t}\n\tconst cipher = reader.name();\n\tconst kdf = reader.name();\n\tif (cipher !== 'none' || kdf !== 'none') {\n\t\treturn sshFail('unsupported', 'Encrypted OpenSSH private keys are not supported');\n\t}\n\tif (reader.string(MAX_STRING_BYTES).length !== 0) {\n\t\treturn sshFail('malformed', 'KDF options must be empty for kdf none');\n\t}\n\tconst keyCount = reader.uint32();\n\tif (keyCount === 0) {\n\t\treturn sshFail('malformed', 'OpenSSH private key file holds no keys');\n\t}\n\tif (keyCount > 1) {\n\t\treturn sshFail('unsupported', 'OpenSSH private key files with several keys are not supported');\n\t}\n\tconst publicBlob = reader.string(MAX_STRING_BYTES);\n\tconst envelope = decodePublicBlob(publicBlob, options);\n\tconst section = reader.string(MAX_PRIVATE_KEY_FILE_BYTES);\n\tif (reader.remaining() !== 0) {\n\t\treturn sshFail('malformed', 'OpenSSH private key file has trailing data');\n\t}\n\tif (section.length === 0 || section.length % NO_CIPHER_BLOCK_SIZE !== 0) {\n\t\treturn sshFail('malformed', 'OpenSSH private section is not a multiple of the block size');\n\t}\n\tconst inner = createSshReader(section);\n\tconst firstCheck = inner.uint32();\n\tconst secondCheck = inner.uint32();\n\tif (firstCheck !== secondCheck) {\n\t\treturn sshFail('malformed', 'OpenSSH check integers differ');\n\t}\n\tconst privateMaterial = readPrivateMaterial(inner, keyTypeOf(envelope), options);\n\tconst comment = inner.text(MAX_STRING_BYTES);\n\tassertImportedComment(comment);\n\tassertPadding(inner);\n\tif (!samePublicMaterial(envelope, privateMaterial.pub)) {\n\t\treturn sshFail('key_mismatch', 'Private section public key differs from the file public key');\n\t}\n\tif (privateMaterial.kind === 'rsa') {\n\t\tassertRsaConsistent(privateMaterial);\n\t}\n\tconst publicKey = await importPublicMaterial(envelope, options);\n\tconst privateKey = await importPrivateMaterial(privateMaterial, envelope, options);\n\tawait assertKeyPairConsistent(privateKey, publicKey, envelope, options);\n\treturn {\n\t\tkeyType: keyTypeOf(envelope),\n\t\talgorithm: algorithmOf(envelope),\n\t\tpublicKey,\n\t\tprivateKey,\n\t\tcomment,\n\t\tfingerprint: await sha256Fingerprint(encodePublicBlob(envelope)),\n\t};\n}\n\nasync function toSshResult<T>(run: () => Promise<T>): Promise<SshResult<T>> {\n\ttry {\n\t\treturn successResult(await run());\n\t} catch (error) {\n\t\tif (isResultError(error)) {\n\t\t\tconst code = asSshErrorCode(error.code);\n\t\t\tif (code !== undefined) {\n\t\t\t\treturn failureResult<SshErrorCode>(code, error.error.message);\n\t\t\t}\n\t\t}\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult<SshErrorCode>(\n\t\t\t'malformed',\n\t\t\terror instanceof Error ? error.message : 'Malformed SSH key',\n\t\t);\n\t}\n}\n\n/**\n * Import an OpenSSH public-key line (`<type> <base64> [comment]`).\n *\n * Reads `ssh-rsa`, `ssh-ed25519`, and `ecdsa-sha2-nistp256/384/521` keys as\n * written by `ssh-keygen` into `.pub` files. The line key type must equal the\n * type inside the blob (RFC 4253 §6.6), an ECDSA curve identifier must equal\n * its key type suffix (RFC 5656 §3.1), and trailing data after the blob is\n * rejected. Fields are separated by spaces or tabs, one trailing line break\n * is allowed, and everything after the base64 field is the comment.\n * `authorized_keys` options and SSH certificate types are not read.\n *\n * Input is capped at 16 KiB and RSA moduli at 16384 bits. `input` is never\n * modified.\n *\n * @param input - The line as text or UTF-8 bytes\n * @param options - Policy options; see {@linkcode SshImportOptions}\n * @returns The WebCrypto verification key, its comment and its SHA-256 fingerprint\n *\n * @see {@linkcode importSshPublicKeyOrThrow} for the throwing variant\n * @see {@linkcode exportSshPublicKey} for the inverse operation\n */\nexport function importSshPublicKey(\n\tinput: string | Uint8Array,\n\toptions: SshImportOptions = {},\n): Promise<SshResult<ImportedSshPublicKey>> {\n\treturn toSshResult(() => decodePublicKeyLine(input, resolveImportOptions(options)));\n}\n\n/**\n * Throwing variant of {@linkcode importSshPublicKey}.\n *\n * @throws {ResultError} Carrying an {@linkcode SshErrorCode} as `code`\n */\nexport async function importSshPublicKeyOrThrow(\n\tinput: string | Uint8Array,\n\toptions: SshImportOptions = {},\n): Promise<ImportedSshPublicKey> {\n\treturn unwrap(await importSshPublicKey(input, options));\n}\n\n/**\n * Import an unencrypted single-key `openssh-key-v1` private key file.\n *\n * Accepts the `-----BEGIN OPENSSH PRIVATE KEY-----` PEM that `ssh-keygen`\n * writes for RSA, Ed25519 and ECDSA P-256/P-384/P-521 keys. The cipher and\n * KDF must both be `none` with empty KDF options; any other value returns\n * `unsupported`, as does a file holding several keys. The check integers,\n * the `1, 2, 3, ...` padding, the block alignment, and the absence of trailing\n * bytes are verified, and RSA integers must be canonical positive `mpint`s.\n *\n * The public key embedded in the file must equal the public half of the\n * private section and its key type, or the result is `key_mismatch`. The\n * private material is then checked cryptographically: for RSA, `p·q = n`,\n * `d·e ≡ 1` modulo both `p-1` and `q-1`, and `iqmp·q ≡ 1 (mod p)`; for every\n * key, a signature made with the private key must verify under the embedded\n * public key. For Ed25519 the 32-byte suffix of the private field must equal\n * the public key.\n *\n * Both keys are returned extractable. The decoded binary copy of the file is\n * zeroed before returning. JavaScript strings, including the PEM text and the\n * JWK members used for the import, cannot be zeroed, and `input` is never\n * modified.\n *\n * @param input - The PEM file as text or UTF-8 bytes, at most 32 KiB\n * @param options - Policy options; see {@linkcode SshImportOptions}\n *\n * @see {@linkcode importOpenSshPrivateKeyOrThrow} for the throwing variant\n * @see {@linkcode exportOpenSshPrivateKey} for the inverse operation\n */\nexport function importOpenSshPrivateKey(\n\tinput: string | Uint8Array,\n\toptions: SshImportOptions = {},\n): Promise<SshResult<ImportedOpenSshPrivateKey>> {\n\treturn toSshResult(() => decodePrivateKey(input, resolveImportOptions(options)));\n}\n\n/**\n * Throwing variant of {@linkcode importOpenSshPrivateKey}.\n *\n * @throws {ResultError} Carrying an {@linkcode SshErrorCode} as `code`\n */\nexport async function importOpenSshPrivateKeyOrThrow(\n\tinput: string | Uint8Array,\n\toptions: SshImportOptions = {},\n): Promise<ImportedOpenSshPrivateKey> {\n\treturn unwrap(await importOpenSshPrivateKey(input, options));\n}\n\nfunction exportFail(code: SshExportErrorCode, message: string): never {\n\treturn throwMicro509Error<SshExportErrorCode>(code, message);\n}\n\nfunction validCommentText(comment: string): boolean {\n\treturn typeof comment === 'string' && comment.isWellFormed() && !/[\\r\\n\\0]/.test(comment);\n}\n\nfunction oversizedComment(comment: string): boolean {\n\treturn (\n\t\tcomment.length > MAX_STRING_BYTES || new TextEncoder().encode(comment).length > MAX_STRING_BYTES\n\t);\n}\n\nfunction assertImportedComment(comment: string): void {\n\tif (!validCommentText(comment)) {\n\t\tsshFail('malformed', 'Comment must be well-formed Unicode without CR, LF or NUL');\n\t}\n\tif (oversizedComment(comment)) {\n\t\tsshFail('limit_exceeded', 'Comment exceeds 8192 UTF-8 bytes');\n\t}\n}\n\nfunction assertComment(comment: string): void {\n\tif (!validCommentText(comment) || oversizedComment(comment)) {\n\t\texportFail(\n\t\t\t'invalid_comment',\n\t\t\t'Comment must be well-formed Unicode without CR, LF or NUL and at most 8192 UTF-8 bytes',\n\t\t);\n\t}\n}\n\nfunction assertExportable(key: CryptoKey, type: KeyType): void {\n\tif (key.type !== type) {\n\t\texportFail('invalid_key', `Expected a ${type} key`);\n\t}\n\tif (!key.extractable) {\n\t\texportFail('not_extractable', 'The key must be extractable');\n\t}\n}\n\nfunction jwkBytes(\n\tjwk: JsonWebKey,\n\tmember: 'n' | 'e' | 'd' | 'p' | 'q' | 'qi' | 'x' | 'y',\n): Uint8Array {\n\tconst value = jwk[member];\n\tif (typeof value !== 'string') {\n\t\tthrow new Error(`WebCrypto key export lacks JWK member ${member}`);\n\t}\n\treturn fromBase64Url(value);\n}\n\nfunction publicMaterialFromJwk(jwk: JsonWebKey, algorithmName: string): SshPublicMaterial {\n\tif (jwk.kty === 'RSA') {\n\t\treturn { kind: 'rsa', e: jwkBytes(jwk, 'e'), n: jwkBytes(jwk, 'n') };\n\t}\n\tif (jwk.kty === 'OKP' && jwk.crv === 'Ed25519' && algorithmName === 'Ed25519') {\n\t\treturn { kind: 'ed25519', x: jwkBytes(jwk, 'x') };\n\t}\n\tif (jwk.kty === 'EC' && algorithmName === 'ECDSA') {\n\t\tconst curve = CURVE_NAMES.find((name) => name === jwk.crv);\n\t\tif (curve !== undefined) {\n\t\t\treturn { kind: 'ecdsa', curve, x: jwkBytes(jwk, 'x'), y: jwkBytes(jwk, 'y') };\n\t\t}\n\t}\n\treturn exportFail(\n\t\t'unsupported_algorithm',\n\t\t'Only RSA, ECDSA P-256/384/521 and Ed25519 are supported',\n\t);\n}\n\n/**\n * Export a public key as an OpenSSH public-key line.\n *\n * Writes `<type> <base64> [comment]` with padded base64 and no trailing line\n * break, the form `ssh-keygen` puts in `.pub` files. ECDSA points are written\n * uncompressed. The key must be an extractable RSA, ECDSA (P-256, P-384,\n * P-521) or Ed25519 public `CryptoKey`.\n *\n * @throws {ResultError} Carrying an {@linkcode SshExportErrorCode} as `code`\n *\n * @see {@linkcode importSshPublicKey} for the inverse operation\n */\nexport async function exportSshPublicKey(\n\tpublicKey: CryptoKey,\n\toptions: SshExportOptions = {},\n): Promise<string> {\n\tconst comment = options.comment === undefined ? '' : options.comment;\n\tassertComment(comment);\n\tassertExportable(publicKey, 'public');\n\tconst material = publicMaterialFromJwk(\n\t\tawait exportPublicJwk(publicKey),\n\t\tpublicKey.algorithm.name,\n\t);\n\tconst line = `${keyTypeOf(material)} ${base64Encode(encodePublicBlob(material))}`;\n\treturn comment === '' ? line : `${line} ${comment}`;\n}\n\n/**\n * Export a private key as an unencrypted `openssh-key-v1` PEM file.\n *\n * The file holds one key, cipher `none` and KDF `none`, with the check\n * integers drawn from the WebCrypto random source and the public key derived\n * from the private key. `ssh-keygen` reads it directly. Check integers are\n * random, so compare keys, not file bytes, between two exports.\n *\n * The private `CryptoKey` must be extractable. The binary encoding is zeroed\n * after the PEM text is built; the returned string and the JWK used for the\n * export cannot be zeroed.\n *\n * @throws {ResultError} Carrying an {@linkcode SshExportErrorCode} as `code`\n *\n * @see {@linkcode importOpenSshPrivateKey} for the inverse operation\n */\nexport async function exportOpenSshPrivateKey(\n\tprivateKey: CryptoKey,\n\toptions: SshExportOptions = {},\n): Promise<string> {\n\tconst comment = options.comment === undefined ? '' : options.comment;\n\tassertComment(comment);\n\tassertExportable(privateKey, 'private');\n\tconst jwk = await exportPrivateJwk(privateKey);\n\tconst material = publicMaterialFromJwk(jwk, privateKey.algorithm.name);\n\tconst fields = privateFields(material, jwk);\n\tconst checkInt = getCrypto().getRandomValues(new Uint32Array(1))[0] ?? 0;\n\tconst unpadded = concatBytes([\n\t\tsshUint32(checkInt),\n\t\tsshUint32(checkInt),\n\t\tsshTextString(keyTypeOf(material)),\n\t\tfields,\n\t\tsshTextString(comment),\n\t]);\n\tconst paddingLength =\n\t\t(NO_CIPHER_BLOCK_SIZE - (unpadded.length % NO_CIPHER_BLOCK_SIZE)) % NO_CIPHER_BLOCK_SIZE;\n\tconst section = concatBytes([\n\t\tunpadded,\n\t\tUint8Array.from({ length: paddingLength }, (_, index) => index + 1),\n\t]);\n\tconst file = concatBytes([\n\t\tAUTH_MAGIC,\n\t\tUint8Array.of(0),\n\t\tsshTextString('none'),\n\t\tsshTextString('none'),\n\t\tsshUint32(0),\n\t\tsshUint32(1),\n\t\tsshString(encodePublicBlob(material)),\n\t\tsshString(section),\n\t]);\n\ttry {\n\t\treturn pemEncode(PRIVATE_KEY_LABEL, file);\n\t} finally {\n\t\tunpadded.fill(0);\n\t\tsection.fill(0);\n\t\tfile.fill(0);\n\t\tfields.fill(0);\n\t}\n}\n\nfunction privateFields(material: SshPublicMaterial, jwk: JsonWebKey): Uint8Array {\n\tswitch (material.kind) {\n\t\tcase 'rsa':\n\t\t\treturn concatBytes([\n\t\t\t\tsshMpint(material.n),\n\t\t\t\tsshMpint(material.e),\n\t\t\t\tsshMpint(jwkBytes(jwk, 'd')),\n\t\t\t\tsshMpint(jwkBytes(jwk, 'qi')),\n\t\t\t\tsshMpint(jwkBytes(jwk, 'p')),\n\t\t\t\tsshMpint(jwkBytes(jwk, 'q')),\n\t\t\t]);\n\t\tcase 'ecdsa':\n\t\t\treturn concatBytes([\n\t\t\t\tsshTextString(CURVES[material.curve].identifier),\n\t\t\t\tsshString(ecPoint(material)),\n\t\t\t\tsshMpint(jwkBytes(jwk, 'd')),\n\t\t\t]);\n\t\tcase 'ed25519':\n\t\t\treturn concatBytes([\n\t\t\t\tsshString(material.x),\n\t\t\t\tsshString(concatBytes([jwkBytes(jwk, 'd'), material.x])),\n\t\t\t]);\n\t\tdefault:\n\t\t\treturn unhandledKey(material);\n\t}\n}\n\n/**\n * The `SHA256:` fingerprint `ssh-keygen -l -E sha256` prints for a key.\n *\n * It is the SHA-256 digest of the SSH public-key blob (RFC 4253 §6.6 layout),\n * base64-encoded without padding and prefixed with `SHA256:`. It differs from a\n * certificate fingerprint and from a digest of the SPKI encoding. Pass a\n * public or private `CryptoKey`, or the raw blob bytes (the decoded base64\n * field of a public-key line). A private key must be extractable.\n *\n * @throws {ResultError} Carrying an {@linkcode SshExportErrorCode} when a `CryptoKey` cannot be encoded\n */\nexport async function sshFingerprintSha256(key: CryptoKey | Uint8Array): Promise<string> {\n\tif (key instanceof Uint8Array) {\n\t\treturn await sha256Fingerprint(key);\n\t}\n\tif (key.type === 'secret') {\n\t\texportFail('invalid_key', 'Expected a public or private key');\n\t}\n\tassertExportable(key, key.type);\n\tconst jwk = key.type === 'private' ? await exportPrivateJwk(key) : await exportPublicJwk(key);\n\tconst material = publicMaterialFromJwk(jwk, key.algorithm.name);\n\treturn await sha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AEA,SAAS,cAAc7E,GAA6ByE,GAA6B;CAChF,QAAQzE,EAAS,MAAjB;EACC,KAAK,OACJ,OAAOhD,EAAY;GAClBwB,EAASwB,EAAS,CAAC;GACnBxB,EAASwB,EAAS,CAAC;GACnBxB,EAAS,SAASiG,GAAK,GAAG,CAAC;GAC3BjG,EAAS,SAASiG,GAAK,IAAI,CAAC;GAC5BjG,EAAS,SAASiG,GAAK,GAAG,CAAC;GAC3BjG,EAAS,SAASiG,GAAK,GAAG,CAAC;EAC5B,CAAC;EACF,KAAK,SACJ,OAAOzH,EAAY;GAClB0B,EAAcY,EAAOU,EAAS,MAAM,CAAC,UAAU;GAC/CvB,EAAU,QAAQuB,CAAQ,CAAC;GAC3BxB,EAAS,SAASiG,GAAK,GAAG,CAAC;EAC5B,CAAC;EACF,KAAK,WACJ,OAAOzH,EAAY,CAClByB,EAAUuB,EAAS,CAAC,GACpBvB,EAAUzB,EAAY,CAAC,SAASyH,GAAK,GAAG,GAAGzE,EAAS,CAAC,CAAC,CAAC,CACxD,CAAC;EACF,SACC,OAAO,aAAaA,CAAQ;CAC9B;AACD;;;;;;;;;;;;AAaA,eAAsB,qBAAqBwE,GAA8C;CAUxF,OATIA,aAAe,aACX,MAAM,kBAAkBA,CAAG,KAE/BA,EAAI,SAAS,YAChB,WAAW,eAAe,kCAAkC,GAE7D,iBAAiBA,GAAKA,EAAI,IAAI,GAGvB,MAAM,kBAAkB,iBADd,sBADLA,EAAI,SAAS,YAAY,MAAMnH,EAAiBmH,CAAG,IAAI,MAAMlH,EAAgBkH,CAAG,GAChDA,EAAI,UAAU,IACH,CAAC,CAAC;AAC1D"}
@@ -1 +1 @@
1
- {"version":3,"file":"wire.js","names":["SSH_ERROR_CODES","candidate","code","throwMicro509Error","message","offset","data","length","view","bytes","maxLength","byte","first","second","value","concatBytes","text","start","magnitude","significant","hex","index","padded","left","right"],"sources":["../../src/ssh/wire.ts"],"sourcesContent":["import { concatBytes } from '#micro509/internal/asn1/der';\nimport { throwMicro509Error } from '#micro509/result/result';\n\n/** Machine-readable failure reason of the SSH key import functions. */\nexport type SshErrorCode =\n\t| 'malformed'\n\t| 'unsupported'\n\t| 'limit_exceeded'\n\t| 'key_mismatch'\n\t| 'invalid_options';\n\nconst SSH_ERROR_CODES = [\n\t'invalid_options',\n\t'malformed',\n\t'unsupported',\n\t'limit_exceeded',\n\t'key_mismatch',\n] as const satisfies readonly SshErrorCode[];\n\n/** The {@linkcode SshErrorCode} spelled `code`, if it is one. */\nexport function asSshErrorCode(code: string): SshErrorCode | undefined {\n\treturn SSH_ERROR_CODES.find((candidate) => candidate === code);\n}\n\n/** Throws a `ResultError` carrying an {@linkcode SshErrorCode}. */\nexport function sshFail(code: SshErrorCode, message: string): never {\n\treturn throwMicro509Error<SshErrorCode>(code, message);\n}\n\nconst MAX_NAME_BYTES = 64;\n\n/** Cursor over one SSH-encoded buffer (RFC 4251 §5). Every read is bounds-checked. */\nexport interface SshReader {\n\t/** Bytes not yet consumed. */\n\treadonly remaining: () => number;\n\t/** The next `uint32`. */\n\treadonly uint32: () => number;\n\t/** The next `length` raw bytes, as a view into the input. */\n\treadonly raw: (length: number) => Uint8Array;\n\t/** The next `string`, as a view into the input. */\n\treadonly string: (maxLength: number) => Uint8Array;\n\t/** The next `string` as a printable US-ASCII name of at most 64 bytes. */\n\treadonly name: () => string;\n\t/** The next `string` as UTF-8 text without NUL. */\n\treadonly text: (maxLength: number) => string;\n\t/** The next `mpint`, as a positive magnitude without leading zero bytes. */\n\treadonly mpint: (maxLength: number) => Uint8Array;\n}\n\n/** Creates an {@linkcode SshReader} over `data`. */\nexport function createSshReader(data: Uint8Array): SshReader {\n\tlet offset = 0;\n\tconst remaining = (): number => data.length - offset;\n\tconst raw = (length: number): Uint8Array => {\n\t\tif (length > remaining()) {\n\t\t\treturn sshFail('malformed', 'SSH data is truncated');\n\t\t}\n\t\tconst view = data.subarray(offset, offset + length);\n\t\toffset += length;\n\t\treturn view;\n\t};\n\tconst uint32 = (): number => {\n\t\tconst bytes = raw(4);\n\t\treturn new DataView(bytes.buffer, bytes.byteOffset, 4).getUint32(0, false);\n\t};\n\tconst string = (maxLength: number): Uint8Array => {\n\t\tconst length = uint32();\n\t\tif (length > maxLength) {\n\t\t\treturn sshFail('limit_exceeded', `SSH string of ${length} bytes exceeds ${maxLength}`);\n\t\t}\n\t\treturn raw(length);\n\t};\n\tconst name = (): string => {\n\t\tconst bytes = string(MAX_NAME_BYTES);\n\t\tif (bytes.length === 0 || bytes.some((byte) => byte < 0x21 || byte > 0x7e)) {\n\t\t\treturn sshFail('malformed', 'SSH name is not printable US-ASCII');\n\t\t}\n\t\treturn String.fromCharCode(...bytes);\n\t};\n\tconst text = (maxLength: number): string => {\n\t\tconst bytes = string(maxLength);\n\t\tif (bytes.includes(0)) {\n\t\t\treturn sshFail('malformed', 'SSH text contains a NUL byte');\n\t\t}\n\t\treturn decodeUtf8(bytes);\n\t};\n\tconst mpint = (maxLength: number): Uint8Array => {\n\t\tconst bytes = string(maxLength);\n\t\tconst first = bytes[0];\n\t\tconst second = bytes[1];\n\t\tif (first === undefined) {\n\t\t\treturn sshFail('malformed', 'SSH key integer is zero');\n\t\t}\n\t\tif (first >= 0x80) {\n\t\t\treturn sshFail('malformed', 'SSH key integer is negative');\n\t\t}\n\t\tif (first === 0) {\n\t\t\tif (second === undefined || second < 0x80) {\n\t\t\t\treturn sshFail('malformed', 'SSH integer has a redundant leading zero byte');\n\t\t\t}\n\t\t\treturn bytes.subarray(1);\n\t\t}\n\t\treturn bytes;\n\t};\n\treturn { remaining, uint32, raw, string, name, text, mpint };\n}\n\n/** Strict UTF-8 decode; invalid sequences are malformed input. */\nexport function decodeUtf8(bytes: Uint8Array): string {\n\ttry {\n\t\treturn new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\n\t} catch {\n\t\treturn sshFail('malformed', 'SSH text is not valid UTF-8');\n\t}\n}\n\n/** Encodes a `uint32` (RFC 4251 §5). */\nexport function sshUint32(value: number): Uint8Array {\n\tconst bytes = new Uint8Array(4);\n\tnew DataView(bytes.buffer).setUint32(0, value, false);\n\treturn bytes;\n}\n\n/** Encodes a `string` (RFC 4251 §5). */\nexport function sshString(bytes: Uint8Array): Uint8Array {\n\treturn concatBytes([sshUint32(bytes.length), bytes]);\n}\n\n/** Encodes a US-ASCII or UTF-8 text `string`. */\nexport function sshTextString(text: string): Uint8Array {\n\treturn sshString(new TextEncoder().encode(text));\n}\n\n/** Encodes a non-negative integer, given as a big-endian magnitude, as an `mpint` (RFC 4251 §5). */\nexport function sshMpint(magnitude: Uint8Array): Uint8Array {\n\tconst start = magnitude.findIndex((byte) => byte !== 0);\n\tif (start === -1) {\n\t\treturn sshUint32(0);\n\t}\n\tconst significant = magnitude.subarray(start);\n\tconst needsSignByte = (significant[0] ?? 0) >= 0x80;\n\treturn sshString(needsSignByte ? concatBytes([Uint8Array.of(0), significant]) : significant);\n}\n\n/** Big-endian magnitude of a non-negative `bigint`. */\nexport function bigintToBytes(value: bigint, length?: number): Uint8Array {\n\tlet hex = value.toString(16);\n\tif (hex.length % 2 === 1) {\n\t\thex = `0${hex}`;\n\t}\n\tconst bytes = new Uint8Array(hex.length / 2);\n\tfor (let index = 0; index < bytes.length; index++) {\n\t\tbytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);\n\t}\n\tif (length === undefined) {\n\t\treturn bytes;\n\t}\n\tif (bytes.length > length) {\n\t\treturn sshFail('malformed', 'SSH integer is larger than its field');\n\t}\n\tconst padded = new Uint8Array(length);\n\tpadded.set(bytes, length - bytes.length);\n\treturn padded;\n}\n\n/** The non-negative `bigint` of a big-endian magnitude. */\nexport function bytesToBigint(bytes: Uint8Array): bigint {\n\tlet value = 0n;\n\tfor (const byte of bytes) {\n\t\tvalue = (value << 8n) | BigInt(byte);\n\t}\n\treturn value;\n}\n\n/** Whether two byte strings are equal. */\nexport function bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n\treturn left.length === right.length && left.every((byte, index) => by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IAAQZ,EAAM,QAAQ,KACzC,EAAMY,KAAS,OAAO,SAASD,EAAI,MAAMC,IAAQ,GAAGA,IAAQ,IAAI,CAAC,GAAG,EAAE;CAEvE,IAAId,MAAW,KAAA,GACd,OAAOE;CAER,IAAIA,EAAM,SAASF,GAClB,OAAO,QAAQ,aAAa,sCAAsC;CAEnE,IAAMe,IAAS,IAAI,WAAWf,CAAM;CAEpC,OADAe,EAAO,IAAIb,GAAOF,IAASE,EAAM,MAAM,GAChCa;AACR;;AAGA,SAAgB,cAAc,GAA2B;CACxD,IAAIR,IAAQ;CACZ,KAAK,IAAMH,KAAQF,GAClB,IAASK,KAAS,KAAM,OAAOH,CAAI;CAEpC,OAAOG;AACR;;AAGA,SAAgB,WAAW,GAAkB,GAA4B;CACxE,OAAOS,EAAK,WAAWC,EAAM,UAAUD,EAAK,OAAO,GAAM,MAAUZ,MAASa,EAAMH,EAAM;AACzF"}
1
+ {"version":3,"file":"wire.js","names":["concatBytes","throwMicro509Error","SSH_ERROR_CODES","code","candidate","message","data","offset","length","view","bytes","maxLength","byte","first","second","value","text","magnitude","start","significant","hex","index","padded","left","right"],"sources":["../../src/ssh/wire.ts"],"sourcesContent":["import { concatBytes } from '#micro509/internal/asn1/der';\nimport { throwMicro509Error } from '#micro509/result/result';\n\n/** Machine-readable failure reason of the SSH key import functions. */\nexport type SshErrorCode =\n\t| 'malformed'\n\t| 'unsupported'\n\t| 'limit_exceeded'\n\t| 'key_mismatch'\n\t| 'invalid_options';\n\nconst SSH_ERROR_CODES = [\n\t'invalid_options',\n\t'malformed',\n\t'unsupported',\n\t'limit_exceeded',\n\t'key_mismatch',\n] as const satisfies readonly SshErrorCode[];\n\n/** The {@linkcode SshErrorCode} spelled `code`, if it is one. */\nexport function asSshErrorCode(code: string): SshErrorCode | undefined {\n\treturn SSH_ERROR_CODES.find((candidate) => candidate === code);\n}\n\n/** Throws a `ResultError` carrying an {@linkcode SshErrorCode}. */\nexport function sshFail(code: SshErrorCode, message: string): never {\n\treturn throwMicro509Error<SshErrorCode>(code, message);\n}\n\nconst MAX_NAME_BYTES = 64;\n\n/** Cursor over one SSH-encoded buffer (RFC 4251 §5). Every read is bounds-checked. */\nexport interface SshReader {\n\t/** Bytes not yet consumed. */\n\treadonly remaining: () => number;\n\t/** The next `uint32`. */\n\treadonly uint32: () => number;\n\t/** The next `length` raw bytes, as a view into the input. */\n\treadonly raw: (length: number) => Uint8Array;\n\t/** The next `string`, as a view into the input. */\n\treadonly string: (maxLength: number) => Uint8Array;\n\t/** The next `string` as a printable US-ASCII name of at most 64 bytes. */\n\treadonly name: () => string;\n\t/** The next `string` as UTF-8 text without NUL. */\n\treadonly text: (maxLength: number) => string;\n\t/** The next `mpint`, as a positive magnitude without leading zero bytes. */\n\treadonly mpint: (maxLength: number) => Uint8Array;\n}\n\n/** Creates an {@linkcode SshReader} over `data`. */\nexport function createSshReader(data: Uint8Array): SshReader {\n\tlet offset = 0;\n\tconst remaining = (): number => data.length - offset;\n\tconst raw = (length: number): Uint8Array => {\n\t\tif (length > remaining()) {\n\t\t\treturn sshFail('malformed', 'SSH data is truncated');\n\t\t}\n\t\tconst view = data.subarray(offset, offset + length);\n\t\toffset += length;\n\t\treturn view;\n\t};\n\tconst uint32 = (): number => {\n\t\tconst bytes = raw(4);\n\t\treturn new DataView(bytes.buffer, bytes.byteOffset, 4).getUint32(0, false);\n\t};\n\tconst string = (maxLength: number): Uint8Array => {\n\t\tconst length = uint32();\n\t\tif (length > maxLength) {\n\t\t\treturn sshFail('limit_exceeded', `SSH string of ${length} bytes exceeds ${maxLength}`);\n\t\t}\n\t\treturn raw(length);\n\t};\n\tconst name = (): string => {\n\t\tconst bytes = string(MAX_NAME_BYTES);\n\t\tif (bytes.length === 0 || bytes.some((byte) => byte < 0x21 || byte > 0x7e)) {\n\t\t\treturn sshFail('malformed', 'SSH name is not printable US-ASCII');\n\t\t}\n\t\treturn String.fromCharCode(...bytes);\n\t};\n\tconst text = (maxLength: number): string => {\n\t\tconst bytes = string(maxLength);\n\t\tif (bytes.includes(0)) {\n\t\t\treturn sshFail('malformed', 'SSH text contains a NUL byte');\n\t\t}\n\t\treturn decodeUtf8(bytes);\n\t};\n\tconst mpint = (maxLength: number): Uint8Array => {\n\t\tconst bytes = string(maxLength);\n\t\tconst first = bytes[0];\n\t\tconst second = bytes[1];\n\t\tif (first === undefined) {\n\t\t\treturn sshFail('malformed', 'SSH key integer is zero');\n\t\t}\n\t\tif (first >= 0x80) {\n\t\t\treturn sshFail('malformed', 'SSH key integer is negative');\n\t\t}\n\t\tif (first === 0) {\n\t\t\tif (second === undefined || second < 0x80) {\n\t\t\t\treturn sshFail('malformed', 'SSH integer has a redundant leading zero byte');\n\t\t\t}\n\t\t\treturn bytes.subarray(1);\n\t\t}\n\t\treturn bytes;\n\t};\n\treturn { remaining, uint32, raw, string, name, text, mpint };\n}\n\n/** Strict UTF-8 decode; invalid sequences are malformed input. */\nexport function decodeUtf8(bytes: Uint8Array): string {\n\ttry {\n\t\treturn new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\n\t} catch {\n\t\treturn sshFail('malformed', 'SSH text is not valid UTF-8');\n\t}\n}\n\n/** Encodes a `uint32` (RFC 4251 §5). */\nexport function sshUint32(value: number): Uint8Array {\n\tconst bytes = new Uint8Array(4);\n\tnew DataView(bytes.buffer).setUint32(0, value, false);\n\treturn bytes;\n}\n\n/** Encodes a `string` (RFC 4251 §5). */\nexport function sshString(bytes: Uint8Array): Uint8Array {\n\treturn concatBytes([sshUint32(bytes.length), bytes]);\n}\n\n/** Encodes a US-ASCII or UTF-8 text `string`. */\nexport function sshTextString(text: string): Uint8Array {\n\treturn sshString(new TextEncoder().encode(text));\n}\n\n/** Encodes a non-negative integer, given as a big-endian magnitude, as an `mpint` (RFC 4251 §5). */\nexport function sshMpint(magnitude: Uint8Array): Uint8Array {\n\tconst start = magnitude.findIndex((byte) => byte !== 0);\n\tif (start === -1) {\n\t\treturn sshUint32(0);\n\t}\n\tconst significant = magnitude.subarray(start);\n\tconst needsSignByte = (significant[0] ?? 0) >= 0x80;\n\treturn sshString(needsSignByte ? concatBytes([Uint8Array.of(0), significant]) : significant);\n}\n\n/** Big-endian magnitude of a non-negative `bigint`. */\nexport function bigintToBytes(value: bigint, length?: number): Uint8Array {\n\tlet hex = value.toString(16);\n\tif (hex.length % 2 === 1) {\n\t\thex = `0${hex}`;\n\t}\n\tconst bytes = new Uint8Array(hex.length / 2);\n\tfor (let index = 0; index < bytes.length; index++) {\n\t\tbytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);\n\t}\n\tif (length === undefined) {\n\t\treturn bytes;\n\t}\n\tif (bytes.length > length) {\n\t\treturn sshFail('malformed', 'SSH integer is larger than its field');\n\t}\n\tconst padded = new Uint8Array(length);\n\tpadded.set(bytes, length - bytes.length);\n\treturn padded;\n}\n\n/** The non-negative `bigint` of a big-endian magnitude. */\nexport function bytesToBigint(bytes: Uint8Array): bigint {\n\tlet value = 0n;\n\tfor (const byte of bytes) {\n\t\tvalue = (value << 8n) | BigInt(byte);\n\t}\n\treturn value;\n}\n\n/** Whether two byte strings are equal. */\nexport function bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n\treturn left.length === right.length && left.every((byte, index) => byte === right[index]);\n}\n"],"mappings":";;;AAWA,MAAME,IAAkB;CACvB;CACA;CACA;CACA;CACA;AACD;;AAGA,SAAgB,eAAeC,GAAwC;CACtE,OAAOD,EAAgB,MAAME,MAAcA,MAAcD,CAAI;AAC9D;;AAGA,SAAgB,QAAQA,GAAoBE,GAAwB;CACnE,OAAOJ,EAAiCE,GAAME,CAAO;AACtD;;AAuBA,SAAgB,gBAAgBC,GAA6B;CAC5D,IAAIC,IAAS,GACP,kBAA0BD,EAAK,SAASC,GACxC,OAAOC,MAA+B;EAC3C,IAAIA,IAAS,UAAU,GACtB,OAAO,QAAQ,aAAa,uBAAuB;EAEpD,IAAMC,IAAOH,EAAK,SAASC,GAAQA,IAASC,CAAM;EAElD,OAD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