micro509 0.17.0 → 0.18.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 (137) hide show
  1. package/CHANGELOG.md +123 -6
  2. package/README.md +3 -0
  3. package/dist/crypto/crypto.d.ts +2 -3
  4. package/dist/crypto.d.ts +6 -0
  5. package/dist/der/der.d.ts +14 -4
  6. package/dist/der/der.js +19 -19
  7. package/dist/der.d.ts +26 -2
  8. package/dist/der.js +4 -4
  9. package/dist/index.d.ts +82 -15
  10. package/dist/index.js +19 -19
  11. package/dist/internal/asn1/asn1.d.ts +1 -2
  12. package/dist/internal/asn1/der.d.ts +1 -2
  13. package/dist/internal/asn1/oids.js +71 -353
  14. package/dist/internal/asn1/oids.js.map +1 -1
  15. package/dist/internal/asn1/oids.json.js +357 -0
  16. package/dist/internal/asn1/oids.json.js.map +1 -0
  17. package/dist/internal/crypto/algorithm-names.js +1 -1
  18. package/dist/internal/crypto/pbes2.d.ts +1 -2
  19. package/dist/internal/crypto/pbes2.js +70 -70
  20. package/dist/internal/crypto/prime-ec.js +37 -0
  21. package/dist/internal/crypto/prime-ec.js.map +1 -0
  22. package/dist/internal/crypto/rsa-pss.js +50 -50
  23. package/dist/internal/crypto/sig-verify.d.ts +1 -2
  24. package/dist/internal/crypto/sig-verify.js +60 -60
  25. package/dist/internal/crypto/signing.d.ts +1 -2
  26. package/dist/internal/crypto/signing.js +26 -26
  27. package/dist/internal/jose/json-data.js +108 -0
  28. package/dist/internal/jose/json-data.js.map +1 -0
  29. package/dist/internal/jose/strict-json.d.ts +1 -2
  30. package/dist/internal/shared/dn.d.ts +1 -2
  31. package/dist/internal/shared/dn.js +1 -1
  32. package/dist/internal/shared/ip.d.ts +1 -2
  33. package/dist/internal/verify/name-constraints-engine.js +64 -64
  34. package/dist/internal/verify/policy-engine.js +1 -1
  35. package/dist/internal/verify/verify-path.d.ts +1 -2
  36. package/dist/internal/verify/verify-path.js +19 -19
  37. package/dist/internal/x509/directory-name.js +10 -10
  38. package/dist/internal/x509/extension-errors.d.ts +1 -2
  39. package/dist/internal/x509/extension-registry.js +18 -18
  40. package/dist/internal/x509/general-name-profile.js +9 -9
  41. package/dist/internal/x509/general-name.js +32 -32
  42. package/dist/internal/x509/name-fields.js +1 -1
  43. package/dist/jose/base64url.d.ts +4 -0
  44. package/dist/jose/base64url.js +14 -0
  45. package/dist/jose/base64url.js.map +1 -0
  46. package/dist/jose/errors.d.ts +9 -3
  47. package/dist/jose/errors.js.map +1 -1
  48. package/dist/jose/jwe.d.ts +64 -0
  49. package/dist/jose/jwe.js +188 -0
  50. package/dist/jose/jwe.js.map +1 -0
  51. package/dist/jose/jwks.d.ts +38 -10
  52. package/dist/jose/jwks.js +156 -96
  53. package/dist/jose/jwks.js.map +1 -1
  54. package/dist/jose/jws.d.ts +8 -6
  55. package/dist/jose/jws.js +216 -170
  56. package/dist/jose/jws.js.map +1 -1
  57. package/dist/jose/jwt.d.ts +8 -2
  58. package/dist/jose/jwt.js +98 -98
  59. package/dist/jose/remote-jwks.d.ts +1 -2
  60. package/dist/jose/remote-jwks.js +106 -108
  61. package/dist/jose/remote-jwks.js.map +1 -1
  62. package/dist/jose.d.ts +15 -4
  63. package/dist/jose.js +7 -5
  64. package/dist/kdf/argon2-arithmetic.js +15 -0
  65. package/dist/kdf/argon2-arithmetic.js.map +1 -0
  66. package/dist/kdf/argon2-core.js +486 -0
  67. package/dist/kdf/argon2-core.js.map +1 -0
  68. package/dist/kdf/argon2-memory.js +20 -0
  69. package/dist/kdf/argon2-memory.js.map +1 -0
  70. package/dist/kdf/argon2-portable.js +18 -0
  71. package/dist/kdf/argon2-portable.js.map +1 -0
  72. package/dist/kdf/argon2.d.ts +22 -11
  73. package/dist/kdf/argon2.js +32 -13
  74. package/dist/kdf/argon2.js.map +1 -1
  75. package/dist/kdf.d.ts +6 -0
  76. package/dist/keys/keys.d.ts +31 -6
  77. package/dist/keys/keys.js +315 -233
  78. package/dist/keys/keys.js.map +1 -1
  79. package/dist/keys.d.ts +11 -2
  80. package/dist/keys.js +2 -2
  81. package/dist/pem/pem.d.ts +1 -2
  82. package/dist/pem/pem.js +40 -25
  83. package/dist/pem/pem.js.map +1 -1
  84. package/dist/pem.d.ts +6 -0
  85. package/dist/pkcs/pfx.d.ts +2 -3
  86. package/dist/pkcs/pfx.js +142 -142
  87. package/dist/pkcs/pkcs12-mac.d.ts +1 -2
  88. package/dist/pkcs/pkcs12-mac.js +122 -122
  89. package/dist/pkcs/pkcs7.d.ts +14 -3
  90. package/dist/pkcs/pkcs7.js +268 -248
  91. package/dist/pkcs/pkcs7.js.map +1 -1
  92. package/dist/pkcs.d.ts +10 -1
  93. package/dist/pkcs.js +4 -4
  94. package/dist/result/result.d.ts +1 -2
  95. package/dist/result.d.ts +6 -0
  96. package/dist/revocation/chain.d.ts +2 -3
  97. package/dist/revocation/chain.js +52 -52
  98. package/dist/revocation/crl.d.ts +2 -3
  99. package/dist/revocation/crl.js +319 -319
  100. package/dist/revocation/crl.js.map +1 -1
  101. package/dist/revocation/ocsp.d.ts +2 -3
  102. package/dist/revocation/ocsp.js +395 -395
  103. package/dist/revocation/revocation.d.ts +2 -3
  104. package/dist/revocation/revocation.js +22 -22
  105. package/dist/revocation.d.ts +12 -3
  106. package/dist/revocation.js +4 -4
  107. package/dist/ssh/ssh.d.ts +2 -3
  108. package/dist/ssh/ssh.js +165 -170
  109. package/dist/ssh/ssh.js.map +1 -1
  110. package/dist/ssh/wire.d.ts +1 -2
  111. package/dist/ssh/wire.js +10 -10
  112. package/dist/ssh.d.ts +8 -0
  113. package/dist/verify/identity.d.ts +1 -2
  114. package/dist/verify/identity.js +31 -31
  115. package/dist/verify/name-constraints.d.ts +9 -2
  116. package/dist/verify/policy.d.ts +9 -2
  117. package/dist/verify/verify.d.ts +3 -4
  118. package/dist/verify/verify.js +121 -121
  119. package/dist/verify.d.ts +9 -0
  120. package/dist/x509/certificate.d.ts +4 -5
  121. package/dist/x509/certificate.js +40 -40
  122. package/dist/x509/csr.d.ts +3 -4
  123. package/dist/x509/csr.js +15 -15
  124. package/dist/x509/extensions.d.ts +1 -2
  125. package/dist/x509/extensions.js +165 -165
  126. package/dist/x509/extensions.js.map +1 -1
  127. package/dist/x509/fingerprint.d.ts +1 -2
  128. package/dist/x509/name-text.d.ts +1 -2
  129. package/dist/x509/name.d.ts +1 -2
  130. package/dist/x509/name.js +15 -15
  131. package/dist/x509/parse.d.ts +3 -4
  132. package/dist/x509/parse.js +423 -423
  133. package/dist/x509.d.ts +17 -4
  134. package/dist/x509.js +8 -8
  135. package/package.json +27 -34
  136. package/dist/internal/asn1/oids2.js +0 -75
  137. package/dist/internal/asn1/oids2.js.map +0 -1
@@ -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","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 { 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\tsize: 32,\n\t\thash: 'SHA-256',\n\t\tprime: 2n ** 256n - 2n ** 224n + 2n ** 192n + 2n ** 96n - 1n,\n\t\tb: 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn,\n\t},\n\t'P-384': {\n\t\tidentifier: 'nistp384',\n\t\tsize: 48,\n\t\thash: 'SHA-384',\n\t\tprime: 2n ** 384n - 2n ** 128n - 2n ** 96n + 2n ** 32n - 1n,\n\t\tb: 0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aefn,\n\t},\n\t'P-521': {\n\t\tidentifier: 'nistp521',\n\t\tsize: 66,\n\t\thash: 'SHA-512',\n\t\tprime: 2n ** 521n - 1n,\n\t\tb: 0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00n,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2LA,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,MAAM;EACN,OAAO,MAAM,OAAO,MAAM,OAAO,MAAM,OAAO,MAAM,MAAM;EAC1D,GAAG;CACJ;CACA,SA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C,SAAS4D,GAAK,GAAG,GAAGhG,EAAS,CAAC,CAAC,CAAC,CACxD,CAAC;EACF,SACC,OAAO,aAAaA,CAAQ;CAC9B;AACD;;;;;;;;;;;;AAaA,eAAsB,qBAAqB,GAA8C;CAUxF,OATI+F,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,MAAMM,EAAiBN,CAAG,IAAI,MAAMI,EAAgBJ,CAAG,GAChDA,EAAI,UAAU,IACH,CAAC,CAAC;AAC1D"}
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,QAAQA,CAAO,GAC3E,OAAOC,EAAQ,mBAAmB,sCAAsC;CAEzE,IAAMC,IACLF,EAAQ,sBAAsB,KAAA,IAC3B,OACAA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shErrorCode = "malformed" | "unsupported" | "limit_exceeded" | "key_mismatch" | "invalid_options";
3
- //# sourceMappingURL=wire.d.ts.map
2
+ export type SshErrorCode = "malformed" | "unsupported" | "limit_exceeded" | "key_mismatch" | "invalid_options";
package/dist/ssh/wire.js CHANGED
@@ -1,5 +1,5 @@
1
- import { throwMicro509Error as e } from "../result/result.js";
2
- import { concatBytes as t } from "../internal/asn1/der.js";
1
+ import { concatBytes as e } from "../internal/asn1/der.js";
2
+ import { throwMicro509Error as t } from "../result/result.js";
3
3
  // src/ssh/wire.ts
4
4
  const n = [
5
5
  "invalid_options",
@@ -13,8 +13,8 @@ function asSshErrorCode(e) {
13
13
  return n.find((t) => t === e);
14
14
  }
15
15
  /** Throws a `ResultError` carrying an {@linkcode SshErrorCode}. */
16
- function sshFail(t, n) {
17
- return e(t, n);
16
+ function sshFail(e, n) {
17
+ return t(e, n);
18
18
  }
19
19
  /** Creates an {@linkcode SshReader} over `data`. */
20
20
  function createSshReader(e) {
@@ -65,19 +65,19 @@ function sshUint32(e) {
65
65
  return new DataView(t.buffer).setUint32(0, e, !1), t;
66
66
  }
67
67
  /** Encodes a `string` (RFC 4251 §5). */
68
- function sshString(e) {
69
- return t([sshUint32(e.length), e]);
68
+ function sshString(t) {
69
+ return e([sshUint32(t.length), t]);
70
70
  }
71
71
  /** Encodes a US-ASCII or UTF-8 text `string`. */
72
72
  function sshTextString(e) {
73
73
  return sshString(new TextEncoder().encode(e));
74
74
  }
75
75
  /** Encodes a non-negative integer, given as a big-endian magnitude, as an `mpint` (RFC 4251 §5). */
76
- function sshMpint(e) {
77
- let n = e.findIndex((e) => e !== 0);
76
+ function sshMpint(t) {
77
+ let n = t.findIndex((e) => e !== 0);
78
78
  if (n === -1) return sshUint32(0);
79
- let r = e.subarray(n);
80
- return sshString((r[0] ?? 0) >= 128 ? t([Uint8Array.of(0), r]) : r);
79
+ let r = t.subarray(n);
80
+ return sshString((r[0] ?? 0) >= 128 ? e([Uint8Array.of(0), r]) : r);
81
81
  }
82
82
  /** Big-endian magnitude of a non-negative `bigint`. */
83
83
  function bigintToBytes(e, t) {
package/dist/ssh.d.ts CHANGED
@@ -1,3 +1,11 @@
1
+ /**
2
+ * Read and write OpenSSH public-key lines, unencrypted `openssh-key-v1`
3
+ * private keys, and `SHA256:` fingerprints.
4
+ *
5
+ * Start with {@linkcode importSshPublicKey} or {@linkcode importOpenSshPrivateKey}.
6
+ *
7
+ * @module micro509/ssh
8
+ */
1
9
  import { SshErrorCode } from "./ssh/wire.js";
2
10
  import { ImportedOpenSshPrivateKey, ImportedSshPublicKey, SshExportErrorCode, SshExportOptions, SshFailure, SshImportOptions, SshKeyAlgorithm, SshKeyType, SshResult, exportOpenSshPrivateKey, exportSshPublicKey, importOpenSshPrivateKey, importOpenSshPrivateKeyOrThrow, importSshPublicKey, importSshPublicKeyOrThrow, sshFingerprintSha256 } from "./ssh/ssh.js";
3
11
  export { type ImportedOpenSshPrivateKey, type ImportedSshPublicKey, type SshErrorCode, type SshExportErrorCode, type SshExportOptions, type SshFailure, type SshImportOptions, type SshKeyAlgorithm, type SshKeyType, type SshResult, exportOpenSshPrivateKey, exportSshPublicKey, importOpenSshPrivateKey, importOpenSshPrivateKeyOrThrow, importSshPublicKey, importSshPublicKeyOrThrow, sshFingerprintSha256 };
@@ -116,5 +116,4 @@ export declare function matchServiceIdentity(input: MatchServiceIdentityInput):
116
116
  * });
117
117
  * ```
118
118
  */
119
- export declare function matchCertificateServiceIdentity(rawCertificate: ParsedCertificate, serviceIdentity: ServiceIdentityInput): MatchServiceIdentityResult;
120
- //# sourceMappingURL=identity.d.ts.map
119
+ export declare function matchCertificateServiceIdentity(rawCertificate: ParsedCertificate, serviceIdentity: ServiceIdentityInput): MatchServiceIdentityResult;
@@ -1,9 +1,9 @@
1
- import { DECODE_REFUSAL_CODES as e, errorResult as t, micro509Error as n, successResult as r } from "../result/result.js";
2
- import { decodeRefusalOf as i } from "../internal/asn1/decode-refusal.js";
3
- import { presentedDomainToAscii as a, referenceDomainToAscii as o } from "../internal/shared/idna.js";
4
- import { decodeIpAddress as s, parseIpAddressToBytes as c } from "../internal/shared/ip.js";
5
- import { hostportHost as l, uriAuthorityHost as u } from "../internal/shared/uri-host.js";
6
- import { parsePresentedSrvName as d } from "../internal/x509/general-name-profile.js";
1
+ import { decodeRefusalOf as e } from "../internal/asn1/decode-refusal.js";
2
+ import { presentedDomainToAscii as t, referenceDomainToAscii as n } from "../internal/shared/idna.js";
3
+ import { decodeIpAddress as r, parseIpAddressToBytes as i } from "../internal/shared/ip.js";
4
+ import { hostportHost as a, uriAuthorityHost as o } from "../internal/shared/uri-host.js";
5
+ import { parsePresentedSrvName as s } from "../internal/x509/general-name-profile.js";
6
+ import { DECODE_REFUSAL_CODES as c, errorResult as l, micro509Error as u, successResult as d } from "../result/result.js";
7
7
  import { parseCertificateDerOrThrow as f } from "../x509/parse.js";
8
8
  // src/verify/identity.ts
9
9
  /**
@@ -62,7 +62,7 @@ function matchCertificateServiceIdentity(t, n) {
62
62
  try {
63
63
  r = f(new Uint8Array(t.der));
64
64
  } catch (t) {
65
- let n = i(t, e);
65
+ let n = e(t, c);
66
66
  return n === void 0 ? failure("subject_alt_name_mismatch", "certificate input is malformed") : failure(n.code, n.message);
67
67
  }
68
68
  switch (n.type) {
@@ -108,13 +108,13 @@ function matchIpServiceIdentity(e, t) {
108
108
  return n === void 0 ? malformedServiceIdentityFailure(e, "ip", t.value) : matchParsedIpServiceIdentity(e, n);
109
109
  }
110
110
  function matchParsedIpServiceIdentity(e, t) {
111
- let n = s(t), r = e.subjectAltNames?.filter((e) => e.type === "ip") ?? [], i = [];
112
- for (let a of r) {
113
- let r = tryParsePresentedIpAddress(a.value);
114
- if (r === void 0) return failure("subject_alt_name_mismatch", "IP address SAN is malformed", details(e.subject.values.commonName, n, `ip:${a.value}`));
115
- if (i.push(s(r)), sameIpAddressBytes(r, t)) return success();
111
+ let n = r(t), i = e.subjectAltNames?.filter((e) => e.type === "ip") ?? [], a = [];
112
+ for (let o of i) {
113
+ let i = tryParsePresentedIpAddress(o.value);
114
+ if (i === void 0) return failure("subject_alt_name_mismatch", "IP address SAN is malformed", details(e.subject.values.commonName, n, `ip:${o.value}`));
115
+ if (a.push(r(i)), sameIpAddressBytes(i, t)) return success();
116
116
  }
117
- return failure("subject_alt_name_mismatch", "IP address not present in SAN", details(e.subject.values.commonName, n, i.join(",")));
117
+ return failure("subject_alt_name_mismatch", "IP address not present in SAN", details(e.subject.values.commonName, n, a.join(",")));
118
118
  }
119
119
  function matchScopedServiceIdentity(e, t, n) {
120
120
  if (typeof t.value != "string") return malformedServiceIdentityFailure(e, t.type, t.value);
@@ -161,14 +161,14 @@ function normalizeDnsPattern(e) {
161
161
  * `undefined` for a name with URI delimiters or one that is not valid IDNA2008.
162
162
  */
163
163
  function tryNormalizeDnsName(e) {
164
- if (!(e.length === 0 || /[/:?#@[\]]/.test(e))) return o(e);
164
+ if (!(e.length === 0 || /[/:?#@[\]]/.test(e))) return n(e);
165
165
  }
166
166
  /** RFC 9525 §6.3 compares domain names and §6.4 compares IP addresses by their octets. */
167
167
  function matchesServiceHost(e, t) {
168
168
  return e.type === "ip" ? t.type === "ip" && sameIpAddressBytes(e.bytes, t.bytes) : t.type === "dns" && matchesDnsName(e.name, t.name);
169
169
  }
170
170
  function serviceHostText(e) {
171
- return e.type === "ip" ? s(e.bytes) : e.name;
171
+ return e.type === "ip" ? r(e.bytes) : e.name;
172
172
  }
173
173
  /** Returns which SAN types (dns, uri, srv) the certificate presents, used for CN-fallback suppression. */
174
174
  function presentedDnsIdentifierTypes(e) {
@@ -184,7 +184,7 @@ function presentedDnsIdentifierTypes(e) {
184
184
  function tryParseUriServiceIdentity(e, t) {
185
185
  let n = e.indexOf(":");
186
186
  if (n <= 0 || !/^[A-Za-z][A-Za-z0-9+.-]*$/.test(e.slice(0, n))) return;
187
- let r = e.slice(0, n).toLowerCase(), i = r === "sip" || r === "sips", a = uriServiceHost(i ? sipUriHost(e.slice(n + 1), t) : u(e, t), t === "presented" && !i);
187
+ let r = e.slice(0, n).toLowerCase(), i = r === "sip" || r === "sips", a = uriServiceHost(i ? sipUriHost(e.slice(n + 1), t) : o(e, t), t === "presented" && !i);
188
188
  return a === void 0 ? void 0 : {
189
189
  serviceType: r,
190
190
  host: a
@@ -201,10 +201,10 @@ const p = /^(?:[A-Za-z0-9\-_.!~*'()&=+$,;?/]|%[0-9A-Fa-f]{2})+(?::(?:[A-Za-z0-9\
201
201
  * SIP URI with a userpart as a SIP domain identity.
202
202
  */
203
203
  function sipUriHost(e, t) {
204
- let n = e.indexOf("@"), r = e.slice(n + 1), i = r.split(/[;?]/, 1)[0] ?? "", a = r.slice(i.length), o = a.includes("?") ? a.indexOf("?") : a.length, s = a.slice(0, o);
205
- if (n >= 0 && t === "presented" || n >= 0 && !p.test(e.slice(0, n)) || !m.test(s) || !h.test(a.slice(o)) || hasRepeatedParameter(s) || i.includes("%") || i.endsWith(":")) return { type: "invalid" };
206
- let c = l(i, t);
207
- return c.type === "ip" || c.type === "dns" && g.test(c.name) ? c : { type: "invalid" };
204
+ let n = e.indexOf("@"), r = e.slice(n + 1), i = r.split(/[;?]/, 1)[0] ?? "", o = r.slice(i.length), s = o.includes("?") ? o.indexOf("?") : o.length, c = o.slice(0, s);
205
+ if (n >= 0 && t === "presented" || n >= 0 && !p.test(e.slice(0, n)) || !m.test(c) || !h.test(o.slice(s)) || hasRepeatedParameter(c) || i.includes("%") || i.endsWith(":")) return { type: "invalid" };
206
+ let l = a(i, t);
207
+ return l.type === "ip" || l.type === "dns" && g.test(l.name) ? l : { type: "invalid" };
208
208
  }
209
209
  /** RFC 3261 §19.1.4 compares parameter names without regard to case. */
210
210
  function hasRepeatedParameter(e) {
@@ -215,15 +215,15 @@ function hasRepeatedParameter(e) {
215
215
  * RFC 9525 §6.3: a presented wildcard is the whole left-most label of the
216
216
  * domain name. RFC 5922 §7.2 prohibits wildcards for SIP domains.
217
217
  */
218
- function uriServiceHost(e, t) {
218
+ function uriServiceHost(e, n) {
219
219
  switch (e.type) {
220
220
  case "dns":
221
221
  case "ip": return e;
222
222
  case "regName": {
223
- let n = t && e.value.startsWith("*.") ? a(e.value.slice(2)) : void 0;
224
- return n === void 0 ? void 0 : {
223
+ let r = n && e.value.startsWith("*.") ? t(e.value.slice(2)) : void 0;
224
+ return r === void 0 ? void 0 : {
225
225
  type: "dns",
226
- name: `*.${n}`
226
+ name: `*.${r}`
227
227
  };
228
228
  }
229
229
  case "absent":
@@ -239,7 +239,7 @@ function tryParseSrvServiceIdentity(e, t) {
239
239
  if (!e.startsWith("_")) return;
240
240
  let n = e.indexOf(".");
241
241
  if (n <= 1 || n === e.length - 1) return;
242
- let r = e.slice(n + 1), i = t === "presented" && r.startsWith("*."), a = tryNormalizeDnsName(i ? r.slice(2) : r), o = a === void 0 ? void 0 : d(`${e.slice(0, n).toLowerCase()}.${a}`);
242
+ let r = e.slice(n + 1), i = t === "presented" && r.startsWith("*."), a = tryNormalizeDnsName(i ? r.slice(2) : r), o = a === void 0 ? void 0 : s(`${e.slice(0, n).toLowerCase()}.${a}`);
243
243
  return o === void 0 ? void 0 : {
244
244
  serviceType: o.service.slice(1),
245
245
  host: {
@@ -249,16 +249,16 @@ function tryParseSrvServiceIdentity(e, t) {
249
249
  };
250
250
  }
251
251
  /** Constructs a failure result with the given error code and diagnostic details. */
252
- function failure(e, r, i) {
253
- let a = {
252
+ function failure(e, t, n) {
253
+ let r = {
254
254
  ok: !1,
255
- ...n(e, r, i)
255
+ ...u(e, t, n)
256
256
  };
257
- return t(a);
257
+ return l(r);
258
258
  }
259
259
  /** Constructs a success result indicating the identity matched. */
260
260
  function success() {
261
- return r(void 0);
261
+ return d(void 0);
262
262
  }
263
263
  function malformedServiceIdentityFailure(e, t, n) {
264
264
  let r = typeof n == "string" ? n : "<malformed>";
@@ -266,7 +266,7 @@ function malformedServiceIdentityFailure(e, t, n) {
266
266
  }
267
267
  function tryParsePresentedIpAddress(e) {
268
268
  try {
269
- return c(e);
269
+ return i(e);
270
270
  } catch {
271
271
  return;
272
272
  }
@@ -1,3 +1,11 @@
1
+ /**
2
+ * Caller-supplied initial name constraints for path validation.
3
+ *
4
+ * These types let callers seed the permitted/excluded subtree state
5
+ * before RFC 5280 §6.1 certificate path processing begins.
6
+ *
7
+ * @module
8
+ */
1
9
  import { GeneralSubtree } from "../x509/extensions.js";
2
10
  /**
3
11
  * Input for `createNameConstraintValidationState`.
@@ -10,5 +18,4 @@ export interface InitialNameConstraintsInput {
10
18
  readonly permittedSubtrees?: readonly GeneralSubtree[];
11
19
  /** Subtrees that no subsequent subject name may fall within. Default: none. */
12
20
  readonly excludedSubtrees?: readonly GeneralSubtree[];
13
- }
14
- //# sourceMappingURL=name-constraints.d.ts.map
21
+ }
@@ -1,3 +1,11 @@
1
+ /**
2
+ * Certificate policy validation types (RFC 5280 §6.1 / RFC 9618).
3
+ *
4
+ * Caller-facing knobs for controlling policy processing and the constrained
5
+ * policy sets returned by successful path validation.
6
+ *
7
+ * @module
8
+ */
1
9
  import { PolicyQualifierInfo } from "../x509/extensions.js";
2
10
  /**
3
11
  * Input for the policy-validation engine.
@@ -41,5 +49,4 @@ export interface PolicyValidationOutcome {
41
49
  * of {@linkcode authorityConstrainedPolicies}.
42
50
  */
43
51
  readonly userConstrainedPolicies: readonly ConstrainedPolicy[];
44
- }
45
- //# sourceMappingURL=policy.d.ts.map
52
+ }
@@ -1,11 +1,11 @@
1
1
  import { DecodeRefusalCode, ErrorResult, IndexedErrorResult, IndexedMicro509Error, Micro509Error } from "../result/result.js";
2
- import { ParsedCertificate, ParsedCertificateSigningRequest, ParsedName } from "../x509/parse.js";
2
+ import { RevocationPolicy, TrustedOcspResponder } from "../revocation/chain.js";
3
3
  import { CrlSource } from "../revocation/crl.js";
4
4
  import { RevocationCertificateSource } from "../revocation/revocation.js";
5
- import { RevocationPolicy, TrustedOcspResponder } from "../revocation/chain.js";
6
5
  import { DnsServiceIdentityInput, IpServiceIdentityInput, MatchServiceIdentityErrorCode, MatchServiceIdentityFailure, MatchServiceIdentityFailureDetails, MatchServiceIdentityFailureResult, MatchServiceIdentityInput, MatchServiceIdentityResult, MatchServiceIdentitySuccess, ServiceIdentityInput, ServiceIdentityType, SrvServiceIdentityInput, UriServiceIdentityInput, matchCertificateServiceIdentity, matchServiceIdentity } from "./identity.js";
7
6
  import { InitialNameConstraintsInput } from "./name-constraints.js";
8
7
  import { ConstrainedPolicy, PolicyValidationInput, PolicyValidationOutcome } from "./policy.js";
8
+ import { ParsedCertificate, ParsedCertificateSigningRequest, ParsedName } from "../x509/parse.js";
9
9
  import { isSelfIssued } from "../internal/verify/verify-path.js";
10
10
  /** PEM string or DER bytes for a certificate. PEM may contain multiple blocks. */
11
11
  export type CertificateSource = string | Uint8Array;
@@ -488,5 +488,4 @@ export declare function validateForCodeSigning(input: ValidateForCodeSigningInpu
488
488
  * ```
489
489
  */
490
490
  export declare function validateForCa(input: ValidateForCaInput): Promise<VerifyChainResult>;
491
- export { type ConstrainedPolicy, type DnsServiceIdentityInput, type InitialNameConstraintsInput, type IpServiceIdentityInput, type MatchServiceIdentityErrorCode, type MatchServiceIdentityFailure, type MatchServiceIdentityFailureDetails, type MatchServiceIdentityFailureResult, type MatchServiceIdentityInput, type MatchServiceIdentityResult, type MatchServiceIdentitySuccess, type PolicyValidationInput, type PolicyValidationOutcome, type ServiceIdentityInput, type ServiceIdentityType, type SrvServiceIdentityInput, type UriServiceIdentityInput, isSelfIssued as isSelfIssuedCertificate, type matchCertificateServiceIdentity, type matchServiceIdentity };
492
- //# sourceMappingURL=verify.d.ts.map
491
+ export { type ConstrainedPolicy, type DnsServiceIdentityInput, type InitialNameConstraintsInput, type IpServiceIdentityInput, type MatchServiceIdentityErrorCode, type MatchServiceIdentityFailure, type MatchServiceIdentityFailureDetails, type MatchServiceIdentityFailureResult, type MatchServiceIdentityInput, type MatchServiceIdentityResult, type MatchServiceIdentitySuccess, type PolicyValidationInput, type PolicyValidationOutcome, type ServiceIdentityInput, type ServiceIdentityType, type SrvServiceIdentityInput, type UriServiceIdentityInput, isSelfIssued as isSelfIssuedCertificate, type matchCertificateServiceIdentity, type matchServiceIdentity };