micro509 0.16.0 → 0.17.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.
@@ -0,0 +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,SAAS;EACR,YAAY;EACZ,MAAM;EACN,MAAM;EACN,OAAO,MAAM,OAAO,MAAM,OAAO,MAAM,MAAM,MAAM,MAAM;EACzD,GAAG;CACJ;CACA,SAAS;EACR,YAAY;EACZ,MAAM;EACN,MAAM;EACN,OAAO,MAAM,OAAO;EACpB,GAAG;CACJ;AACD,GAEMC,IAAc;CAAC;CAAS;CAAS;AAAO,GAExCC,IAAwB;CAC7B,uBAAuB;CACvB,uBAAuB;CACvB,uBAAuB;AACxB;AAuCA,SAAS,qBAAqB,GA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AY,MAAMM,EAAiBN,CAAG,IAAI,MAAMI,EAAgBJ,CAAG,GAChDA,EAAI,UAAU,IACH,CAAC,CAAC;AAC1D"}
@@ -0,0 +1,3 @@
1
+ /** Machine-readable failure reason of the SSH key import functions. */
2
+ export type SshErrorCode = "malformed" | "unsupported" | "limit_exceeded" | "key_mismatch" | "invalid_options";
3
+ //# sourceMappingURL=wire.d.ts.map
@@ -0,0 +1,105 @@
1
+ import { throwMicro509Error as e } from "../result/result.js";
2
+ import { concatBytes as t } from "../internal/asn1/der.js";
3
+ // src/ssh/wire.ts
4
+ const n = [
5
+ "invalid_options",
6
+ "malformed",
7
+ "unsupported",
8
+ "limit_exceeded",
9
+ "key_mismatch"
10
+ ];
11
+ /** The {@linkcode SshErrorCode} spelled `code`, if it is one. */
12
+ function asSshErrorCode(e) {
13
+ return n.find((t) => t === e);
14
+ }
15
+ /** Throws a `ResultError` carrying an {@linkcode SshErrorCode}. */
16
+ function sshFail(t, n) {
17
+ return e(t, n);
18
+ }
19
+ /** Creates an {@linkcode SshReader} over `data`. */
20
+ function createSshReader(e) {
21
+ let t = 0, remaining = () => e.length - t, raw = (n) => {
22
+ if (n > remaining()) return sshFail("malformed", "SSH data is truncated");
23
+ let r = e.subarray(t, t + n);
24
+ return t += n, r;
25
+ }, uint32 = () => {
26
+ let e = raw(4);
27
+ return new DataView(e.buffer, e.byteOffset, 4).getUint32(0, !1);
28
+ }, string = (e) => {
29
+ let t = uint32();
30
+ return t > e ? sshFail("limit_exceeded", `SSH string of ${t} bytes exceeds ${e}`) : raw(t);
31
+ };
32
+ return {
33
+ remaining,
34
+ uint32,
35
+ raw,
36
+ string,
37
+ name: () => {
38
+ let e = string(64);
39
+ return e.length === 0 || e.some((e) => e < 33 || e > 126) ? sshFail("malformed", "SSH name is not printable US-ASCII") : String.fromCharCode(...e);
40
+ },
41
+ text: (e) => {
42
+ let t = string(e);
43
+ return t.includes(0) ? sshFail("malformed", "SSH text contains a NUL byte") : decodeUtf8(t);
44
+ },
45
+ mpint: (e) => {
46
+ let t = string(e), n = t[0], r = t[1];
47
+ return n === void 0 ? sshFail("malformed", "SSH key integer is zero") : n >= 128 ? sshFail("malformed", "SSH key integer is negative") : n === 0 ? r === void 0 || r < 128 ? sshFail("malformed", "SSH integer has a redundant leading zero byte") : t.subarray(1) : t;
48
+ }
49
+ };
50
+ }
51
+ /** Strict UTF-8 decode; invalid sequences are malformed input. */
52
+ function decodeUtf8(e) {
53
+ try {
54
+ return new TextDecoder("utf-8", {
55
+ fatal: !0,
56
+ ignoreBOM: !0
57
+ }).decode(e);
58
+ } catch {
59
+ return sshFail("malformed", "SSH text is not valid UTF-8");
60
+ }
61
+ }
62
+ /** Encodes a `uint32` (RFC 4251 §5). */
63
+ function sshUint32(e) {
64
+ let t = /* @__PURE__ */ new Uint8Array(4);
65
+ return new DataView(t.buffer).setUint32(0, e, !1), t;
66
+ }
67
+ /** Encodes a `string` (RFC 4251 §5). */
68
+ function sshString(e) {
69
+ return t([sshUint32(e.length), e]);
70
+ }
71
+ /** Encodes a US-ASCII or UTF-8 text `string`. */
72
+ function sshTextString(e) {
73
+ return sshString(new TextEncoder().encode(e));
74
+ }
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);
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);
81
+ }
82
+ /** Big-endian magnitude of a non-negative `bigint`. */
83
+ function bigintToBytes(e, t) {
84
+ let n = e.toString(16);
85
+ n.length % 2 == 1 && (n = `0${n}`);
86
+ let r = new Uint8Array(n.length / 2);
87
+ for (let e = 0; e < r.length; e++) r[e] = Number.parseInt(n.slice(e * 2, e * 2 + 2), 16);
88
+ if (t === void 0) return r;
89
+ if (r.length > t) return sshFail("malformed", "SSH integer is larger than its field");
90
+ let i = new Uint8Array(t);
91
+ return i.set(r, t - r.length), i;
92
+ }
93
+ /** The non-negative `bigint` of a big-endian magnitude. */
94
+ function bytesToBigint(e) {
95
+ let t = 0n;
96
+ for (let n of e) t = t << 8n | BigInt(n);
97
+ return t;
98
+ }
99
+ /** Whether two byte strings are equal. */
100
+ function bytesEqual(e, t) {
101
+ return e.length === t.length && e.every((e, n) => e === t[n]);
102
+ }
103
+ export { asSshErrorCode, bigintToBytes, bytesEqual, bytesToBigint, createSshReader, decodeUtf8, sshFail, sshMpint, sshString, sshTextString, sshUint32 };
104
+
105
+ //# sourceMappingURL=wire.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire.js","names":["SSH_ERROR_CODES","candidate","code","throwMicro509Error","message","offset","data","length","view","bytes","maxLength","byte","first","second","value","concatBytes","text","start","magnitude","significant","hex","index","padded","left","right"],"sources":["../../src/ssh/wire.ts"],"sourcesContent":["import { concatBytes } from '#micro509/internal/asn1/der';\nimport { throwMicro509Error } from '#micro509/result/result';\n\n/** Machine-readable failure reason of the SSH key import functions. */\nexport type SshErrorCode =\n\t| 'malformed'\n\t| 'unsupported'\n\t| 'limit_exceeded'\n\t| 'key_mismatch'\n\t| 'invalid_options';\n\nconst SSH_ERROR_CODES = [\n\t'invalid_options',\n\t'malformed',\n\t'unsupported',\n\t'limit_exceeded',\n\t'key_mismatch',\n] as const satisfies readonly SshErrorCode[];\n\n/** The {@linkcode SshErrorCode} spelled `code`, if it is one. */\nexport function asSshErrorCode(code: string): SshErrorCode | undefined {\n\treturn SSH_ERROR_CODES.find((candidate) => candidate === code);\n}\n\n/** Throws a `ResultError` carrying an {@linkcode SshErrorCode}. */\nexport function sshFail(code: SshErrorCode, message: string): never {\n\treturn throwMicro509Error<SshErrorCode>(code, message);\n}\n\nconst MAX_NAME_BYTES = 64;\n\n/** Cursor over one SSH-encoded buffer (RFC 4251 §5). Every read is bounds-checked. */\nexport interface SshReader {\n\t/** Bytes not yet consumed. */\n\treadonly remaining: () => number;\n\t/** The next `uint32`. */\n\treadonly uint32: () => number;\n\t/** The next `length` raw bytes, as a view into the input. */\n\treadonly raw: (length: number) => Uint8Array;\n\t/** The next `string`, as a view into the input. */\n\treadonly string: (maxLength: number) => Uint8Array;\n\t/** The next `string` as a printable US-ASCII name of at most 64 bytes. */\n\treadonly name: () => string;\n\t/** The next `string` as UTF-8 text without NUL. */\n\treadonly text: (maxLength: number) => string;\n\t/** The next `mpint`, as a positive magnitude without leading zero bytes. */\n\treadonly mpint: (maxLength: number) => Uint8Array;\n}\n\n/** Creates an {@linkcode SshReader} over `data`. */\nexport function createSshReader(data: Uint8Array): SshReader {\n\tlet offset = 0;\n\tconst remaining = (): number => data.length - offset;\n\tconst raw = (length: number): Uint8Array => {\n\t\tif (length > remaining()) {\n\t\t\treturn sshFail('malformed', 'SSH data is truncated');\n\t\t}\n\t\tconst view = data.subarray(offset, offset + length);\n\t\toffset += length;\n\t\treturn view;\n\t};\n\tconst uint32 = (): number => {\n\t\tconst bytes = raw(4);\n\t\treturn new DataView(bytes.buffer, bytes.byteOffset, 4).getUint32(0, false);\n\t};\n\tconst string = (maxLength: number): Uint8Array => {\n\t\tconst length = uint32();\n\t\tif (length > maxLength) {\n\t\t\treturn sshFail('limit_exceeded', `SSH string of ${length} bytes exceeds ${maxLength}`);\n\t\t}\n\t\treturn raw(length);\n\t};\n\tconst name = (): string => {\n\t\tconst bytes = string(MAX_NAME_BYTES);\n\t\tif (bytes.length === 0 || bytes.some((byte) => byte < 0x21 || byte > 0x7e)) {\n\t\t\treturn sshFail('malformed', 'SSH name is not printable US-ASCII');\n\t\t}\n\t\treturn String.fromCharCode(...bytes);\n\t};\n\tconst text = (maxLength: number): string => {\n\t\tconst bytes = string(maxLength);\n\t\tif (bytes.includes(0)) {\n\t\t\treturn sshFail('malformed', 'SSH text contains a NUL byte');\n\t\t}\n\t\treturn decodeUtf8(bytes);\n\t};\n\tconst mpint = (maxLength: number): Uint8Array => {\n\t\tconst bytes = string(maxLength);\n\t\tconst first = bytes[0];\n\t\tconst second = bytes[1];\n\t\tif (first === undefined) {\n\t\t\treturn sshFail('malformed', 'SSH key integer is zero');\n\t\t}\n\t\tif (first >= 0x80) {\n\t\t\treturn sshFail('malformed', 'SSH key integer is negative');\n\t\t}\n\t\tif (first === 0) {\n\t\t\tif (second === undefined || second < 0x80) {\n\t\t\t\treturn sshFail('malformed', 'SSH integer has a redundant leading zero byte');\n\t\t\t}\n\t\t\treturn bytes.subarray(1);\n\t\t}\n\t\treturn bytes;\n\t};\n\treturn { remaining, uint32, raw, string, name, text, mpint };\n}\n\n/** Strict UTF-8 decode; invalid sequences are malformed input. */\nexport function decodeUtf8(bytes: Uint8Array): string {\n\ttry {\n\t\treturn new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\n\t} catch {\n\t\treturn sshFail('malformed', 'SSH text is not valid UTF-8');\n\t}\n}\n\n/** Encodes a `uint32` (RFC 4251 §5). */\nexport function sshUint32(value: number): Uint8Array {\n\tconst bytes = new Uint8Array(4);\n\tnew DataView(bytes.buffer).setUint32(0, value, false);\n\treturn bytes;\n}\n\n/** Encodes a `string` (RFC 4251 §5). */\nexport function sshString(bytes: Uint8Array): Uint8Array {\n\treturn concatBytes([sshUint32(bytes.length), bytes]);\n}\n\n/** Encodes a US-ASCII or UTF-8 text `string`. */\nexport function sshTextString(text: string): Uint8Array {\n\treturn sshString(new TextEncoder().encode(text));\n}\n\n/** Encodes a non-negative integer, given as a big-endian magnitude, as an `mpint` (RFC 4251 §5). */\nexport function sshMpint(magnitude: Uint8Array): Uint8Array {\n\tconst start = magnitude.findIndex((byte) => byte !== 0);\n\tif (start === -1) {\n\t\treturn sshUint32(0);\n\t}\n\tconst significant = magnitude.subarray(start);\n\tconst needsSignByte = (significant[0] ?? 0) >= 0x80;\n\treturn sshString(needsSignByte ? concatBytes([Uint8Array.of(0), significant]) : significant);\n}\n\n/** Big-endian magnitude of a non-negative `bigint`. */\nexport function bigintToBytes(value: bigint, length?: number): Uint8Array {\n\tlet hex = value.toString(16);\n\tif (hex.length % 2 === 1) {\n\t\thex = `0${hex}`;\n\t}\n\tconst bytes = new Uint8Array(hex.length / 2);\n\tfor (let index = 0; index < bytes.length; index++) {\n\t\tbytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);\n\t}\n\tif (length === undefined) {\n\t\treturn bytes;\n\t}\n\tif (bytes.length > length) {\n\t\treturn sshFail('malformed', 'SSH integer is larger than its field');\n\t}\n\tconst padded = new Uint8Array(length);\n\tpadded.set(bytes, length - bytes.length);\n\treturn padded;\n}\n\n/** The non-negative `bigint` of a big-endian magnitude. */\nexport function bytesToBigint(bytes: Uint8Array): bigint {\n\tlet value = 0n;\n\tfor (const byte of bytes) {\n\t\tvalue = (value << 8n) | BigInt(byte);\n\t}\n\treturn value;\n}\n\n/** Whether two byte strings are equal. */\nexport function bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n\treturn left.length === right.length && left.every((byte, index) => byte === right[index]);\n}\n"],"mappings":";;;AAWA,MAAMA,IAAkB;CACvB;CACA;CACA;CACA;CACA;AACD;;AAGA,SAAgB,eAAe,GAAwC;CACtE,OAAOA,EAAgB,MAAM,MAAcC,MAAcC,CAAI;AAC9D;;AAGA,SAAgB,QAAQ,GAAoB,GAAwB;CACnE,OAAOC,EAAiCD,GAAME,CAAO;AACtD;;AAuBA,SAAgB,gBAAgB,GAA6B;CAC5D,IAAIC,IAAS,GACP,kBAA0BC,EAAK,SAASD,GACxC,OAAO,MAA+B;EAC3C,IAAIE,IAAS,UAAU,GACtB,OAAO,QAAQ,aAAa,uBAAuB;EAEpD,IAAMC,IAAOF,EAAK,SAASD,GAAQA,IAASE,CAAM;EAElD,OADA,KAAUA,GACHC;CACR,GACM,eAAuB;EAC5B,IAAMC,IAAQ,IAAI,CAAC;EACnB,OAAO,IAAI,SAASA,EAAM,QAAQA,EAAM,YAAY,CAAC,CAAC,CAAC,UAAU,GAAG,EAAK;CAC1E,GACM,UAAU,MAAkC;EACjD,IAAMF,IAAS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import { ImportedOpenSshPrivateKey, ImportedSshPublicKey, SshExportErrorCode, SshExportOptions, SshFailure, SshImportOptions, SshKeyAlgorithm, SshKeyType, SshResult, exportOpenSshPrivateKey, exportSshPublicKey, importOpenSshPrivateKey, importOpenSshPrivateKeyOrThrow, importSshPublicKey, importSshPublicKeyOrThrow, sshFingerprintSha256 } from "./ssh/ssh.js";
3
+ 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 };
package/dist/ssh.js ADDED
@@ -0,0 +1 @@
1
+ export { exportOpenSshPrivateKey, exportSshPublicKey, importOpenSshPrivateKey, importOpenSshPrivateKeyOrThrow, importSshPublicKey, importSshPublicKeyOrThrow, sshFingerprintSha256 } from "./ssh/ssh.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "micro509",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "The zero-dependency TypeScript PKI toolkit for real certificate workflows.",
5
5
  "keywords": ["x509", "certificate", "csr", "pem", "der", "jwk", "importmapify"],
6
6
  "homepage": "https://micro509.kjanat.dev",
@@ -40,6 +40,14 @@
40
40
  "types": "./dist/der.d.ts",
41
41
  "default": "./dist/der.js"
42
42
  },
43
+ "./jose": {
44
+ "types": "./dist/jose.d.ts",
45
+ "default": "./dist/jose.js"
46
+ },
47
+ "./kdf": {
48
+ "types": "./dist/kdf.d.ts",
49
+ "default": "./dist/kdf.js"
50
+ },
43
51
  "./keys": {
44
52
  "types": "./dist/keys.d.ts",
45
53
  "default": "./dist/keys.js"
@@ -60,6 +68,10 @@
60
68
  "types": "./dist/revocation.d.ts",
61
69
  "default": "./dist/revocation.js"
62
70
  },
71
+ "./ssh": {
72
+ "types": "./dist/ssh.d.ts",
73
+ "default": "./dist/ssh.js"
74
+ },
63
75
  "./verify": {
64
76
  "types": "./dist/verify.d.ts",
65
77
  "default": "./dist/verify.js"
@@ -117,6 +129,7 @@
117
129
  "test": "BIN=\"${BIN:-bun}\"; AGENT=\"${AGENT:-1}\" $BIN test --concurrent",
118
130
  "test:35433": "PR=\"35433\"; (command -v \"bun-${PR}\" >/dev/null || bunx bun-pr \"${PR}\") && BIN=\"bun-${PR}\" bun --silent run test",
119
131
  "test:coverage": "run -q test --coverage",
132
+ "test:coverage:native": "node --experimental-test-coverage --test-coverage-include=src/kdf/argon2.ts --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/native.lcov --test test/native/argon2.node.mjs",
120
133
  "test:differential": "BIN=\"${BIN:-bun}\"; $BIN test test/differential.test.ts test/differential-fuzz.test.ts",
121
134
  "test:pkits": "BIN=\"${BIN:-bun}\"; $BIN test test/pkits.test.ts",
122
135
  "test:watch": "BIN=\"${BIN:-bun}\"; $BIN run test --watch",
@@ -150,8 +163,9 @@
150
163
  "dprint-plugin-malva": "catalog:dprint",
151
164
  "dprint-plugin-markup": "catalog:dprint",
152
165
  "dprint-plugin-yaml": "catalog:dprint",
153
- "dreamcli": "npm:@kjanat/dreamcli@^4.1.0",
166
+ "dreamcli": "npm:@kjanat/dreamcli@^5.0.0",
154
167
  "importmapify": "catalog:deno",
168
+ "jose": "^6.2.13",
155
169
  "playwright": "^1.63.0",
156
170
  "publint": "catalog:build",
157
171
  "rolldown-plugin-wasm": "catalog:build",
@@ -196,7 +210,7 @@
196
210
  "npm": "12.2.1"
197
211
  },
198
212
  "catalog": {
199
- "@kjanat/dreamcli": "npm:@kjanat/dreamcli@^4.1.0",
213
+ "@kjanat/dreamcli": "npm:@kjanat/dreamcli@^5.0.0",
200
214
  "biome": "npm:@biomejs/biome@^2.5.14",
201
215
  "dprint": "^0.64.0",
202
216
  "runner-run": "^0.28.0",
@@ -236,7 +250,7 @@
236
250
  "tar": "^7.5.22",
237
251
  "vite-robots-txt": "^1.0.0",
238
252
  "vite-svg-to-ico": "^5.0.0",
239
- "vitepress": "2.0.0-alpha.20"
253
+ "vitepress": "2.0.0-alpha.21"
240
254
  },
241
255
  "ts": {
242
256
  "@arethetypeswrong/core": "^0.18.4",