jws.ts
This file
Path
src/utils/jwt/jws.ts
234 lines · 7.3 KiB · TypeScript
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–234why, one step back1/**2 * @module3 * JSON Web Signature (JWS)4 * https://datatracker.ietf.org/doc/html/rfc75155 */67import { getRuntimeKey } from '../../helper/adapter'8import { decodeBase64 } from '../encode'9import type { SignatureAlgorithm } from './jwa'10import { CryptoKeyUsage, JwtAlgorithmNotImplemented } from './types'11import { utf8Encoder } from './utf8'1213type KeyImporterAlgorithm = Parameters<typeof crypto.subtle.importKey>[2]14type KeyAlgorithm =15 | AlgorithmIdentifier16 | RsaHashedImportParams17 | (RsaPssParams & RsaHashedImportParams)18 | (EcdsaParams & EcKeyImportParams)19 | HmacImportParams2021// Extending the JsonWebKey interface to include the "kid" property.22// https://datatracker.ietf.org/doc/html/rfc7515#section-4.1.423export interface HonoJsonWebKey extends JsonWebKey {24 kid?: string25}2627export type SignatureKey = string | HonoJsonWebKey | CryptoKey2829export async function signing(30 privateKey: SignatureKey,31 alg: SignatureAlgorithm,32 data: BufferSource33): Promise<ArrayBuffer> {34 const algorithm = getKeyAlgorithm(alg)35 const cryptoKey = await importPrivateKey(privateKey, algorithm)36 return await crypto.subtle.sign(algorithm, cryptoKey, data)37}3839export async function verifying(40 publicKey: SignatureKey,41 alg: SignatureAlgorithm,42 signature: BufferSource,43 data: BufferSource44): Promise<boolean> {45 const algorithm = getKeyAlgorithm(alg)46 const cryptoKey = await importPublicKey(publicKey, algorithm)47 return await crypto.subtle.verify(algorithm, cryptoKey, signature, data)48}4950function pemToBinary(pem: string): Uint8Array<ArrayBuffer> {51 return decodeBase64(pem.replace(/-+(BEGIN|END).*?-+/g, '').replace(/\s/g, ''))52}5354async function importPrivateKey(key: SignatureKey, alg: KeyImporterAlgorithm): Promise<CryptoKey> {55 if (!crypto.subtle || !crypto.subtle.importKey) {56 throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')57 }58 if (isCryptoKey(key)) {59 if (key.type !== 'private' && key.type !== 'secret') {60 throw new Error(61 `unexpected key type: CryptoKey.type is ${key.type}, expected private or secret`62 )63 }64 return key65 }66 const usages = [CryptoKeyUsage.Sign]67 if (typeof key === 'object') {68 // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#json_web_key_import69 return await crypto.subtle.importKey('jwk', key, alg, false, usages)70 }71 if (key.includes('PRIVATE')) {72 // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#pkcs_8_import73 return await crypto.subtle.importKey('pkcs8', pemToBinary(key), alg, false, usages)74 }75 return await crypto.subtle.importKey('raw', utf8Encoder.encode(key), alg, false, usages)76}7778async function importPublicKey(key: SignatureKey, alg: KeyImporterAlgorithm): Promise<CryptoKey> {79 if (!crypto.subtle || !crypto.subtle.importKey) {80 throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')81 }82 if (isCryptoKey(key)) {83 if (key.type === 'public' || key.type === 'secret') {84 return key85 }86 key = await exportPublicJwkFrom(key)87 }88 if (typeof key === 'string' && key.includes('PRIVATE')) {89 // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#pkcs_8_import90 const privateKey = await crypto.subtle.importKey('pkcs8', pemToBinary(key), alg, true, [91 CryptoKeyUsage.Sign,92 ])93 key = await exportPublicJwkFrom(privateKey)94 }95 const usages = [CryptoKeyUsage.Verify]96 if (typeof key === 'object') {97 // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#json_web_key_import98 return await crypto.subtle.importKey('jwk', key, alg, false, usages)99 }100 if (key.includes('PUBLIC')) {101 // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#subjectpublickeyinfo_import102 return await crypto.subtle.importKey('spki', pemToBinary(key), alg, false, usages)103 }104 return await crypto.subtle.importKey('raw', utf8Encoder.encode(key), alg, false, usages)105}106107// https://datatracker.ietf.org/doc/html/rfc7517108async function exportPublicJwkFrom(privateKey: CryptoKey): Promise<JsonWebKey> {109 if (privateKey.type !== 'private') {110 throw new Error(`unexpected key type: ${privateKey.type}`)111 }112 if (!privateKey.extractable) {113 throw new Error('unexpected private key is unextractable')114 }115 const jwk = await crypto.subtle.exportKey('jwk', privateKey)116 const { kty } = jwk // common117 const { alg, e, n } = jwk // rsa118 const { crv, x, y } = jwk // elliptic-curve119 return { kty, alg, e, n, crv, x, y, key_ops: [CryptoKeyUsage.Verify] }120}121122function getKeyAlgorithm(name: SignatureAlgorithm): KeyAlgorithm {123 switch (name) {124 case 'HS256':125 return {126 name: 'HMAC',127 hash: {128 name: 'SHA-256',129 },130 } satisfies HmacImportParams131 case 'HS384':132 return {133 name: 'HMAC',134 hash: {135 name: 'SHA-384',136 },137 } satisfies HmacImportParams138 case 'HS512':139 return {140 name: 'HMAC',141 hash: {142 name: 'SHA-512',143 },144 } satisfies HmacImportParams145 case 'RS256':146 return {147 name: 'RSASSA-PKCS1-v1_5',148 hash: {149 name: 'SHA-256',150 },151 } satisfies RsaHashedImportParams152 case 'RS384':153 return {154 name: 'RSASSA-PKCS1-v1_5',155 hash: {156 name: 'SHA-384',157 },158 } satisfies RsaHashedImportParams159 case 'RS512':160 return {161 name: 'RSASSA-PKCS1-v1_5',162 hash: {163 name: 'SHA-512',164 },165 } satisfies RsaHashedImportParams166 case 'PS256':167 return {168 name: 'RSA-PSS',169 hash: {170 name: 'SHA-256',171 },172 saltLength: 32, // 256 >> 3173 } satisfies RsaPssParams & RsaHashedImportParams174 case 'PS384':175 return {176 name: 'RSA-PSS',177 hash: {178 name: 'SHA-384',179 },180 saltLength: 48, // 384 >> 3181 } satisfies RsaPssParams & RsaHashedImportParams182 case 'PS512':183 return {184 name: 'RSA-PSS',185 hash: {186 name: 'SHA-512',187 },188 saltLength: 64, // 512 >> 3,189 } satisfies RsaPssParams & RsaHashedImportParams190 case 'ES256':191 return {192 name: 'ECDSA',193 hash: {194 name: 'SHA-256',195 },196 namedCurve: 'P-256',197 } satisfies EcdsaParams & EcKeyImportParams198 case 'ES384':199 return {200 name: 'ECDSA',201 hash: {202 name: 'SHA-384',203 },204 namedCurve: 'P-384',205 } satisfies EcdsaParams & EcKeyImportParams206 case 'ES512':207 return {208 name: 'ECDSA',209 hash: {210 name: 'SHA-512',211 },212 namedCurve: 'P-521',213 } satisfies EcdsaParams & EcKeyImportParams214 case 'EdDSA':215 // Currently, supported only Safari and Deno, Node.js.216 // See: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/verify217 return {218 name: 'Ed25519',219 namedCurve: 'Ed25519',220 }221 default:222 throw new JwtAlgorithmNotImplemented(name)223 }224}225226function isCryptoKey(key: SignatureKey): key is CryptoKey {227 const runtime = getRuntimeKey()228 // @ts-expect-error CryptoKey hasn't exported to global in node v18229 if (runtime === 'node' && !!crypto.webcrypto) {230 // @ts-expect-error CryptoKey hasn't exported to global in node v18231 return key instanceof crypto.webcrypto.CryptoKey232 }233 return key instanceof CryptoKey234}