Skip to content
Myr

jwt.ts

This file

Path

src/utils/jwt/jwt.ts

292 lines · 8.3 KiB · TypeScript

Last changed by

fix(jwt): throw JwtTokenInvalid when the signature is not valid base64url (#5379)Neil Daquioagbefore adoption52febbc

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–176why, one step back
1/**
2 * @module3 * JSON Web Token (JWT)4 * https://datatracker.ietf.org/doc/html/rfc75195 */67import { decodeBase64Url, encodeBase64Url } from '../../utils/encode'8import { AlgorithmTypes } from './jwa'9import type { AsymmetricAlgorithm, SignatureAlgorithm, SymmetricAlgorithm } from './jwa'10import { signing, verifying } from './jws'11import type { HonoJsonWebKey, SignatureKey } from './jws'12import {13 JwtAlgorithmMismatch,14 JwtAlgorithmNotAllowed,15 JwtAlgorithmRequired,16 JwtHeaderInvalid,17 JwtHeaderRequiresKid,18 JwtPayloadRequiresAud,19 JwtSymmetricAlgorithmNotAllowed,20 JwtTokenAudience,21 JwtTokenExpired,22 JwtTokenInvalid,23 JwtTokenIssuedAt,24 JwtTokenIssuer,25 JwtTokenNotBefore,26 JwtTokenSignatureMismatched,27} from './types'28import type { JWTPayload } from './types'29import { utf8Decoder, utf8Encoder } from './utf8'3031const encodeJwtPart = (part: unknown): string =>32 encodeBase64Url(utf8Encoder.encode(JSON.stringify(part)).buffer).replace(/=/g, '')33const encodeSignaturePart = (buf: ArrayBufferLike): string => encodeBase64Url(buf).replace(/=/g, '')3435const decodeJwtPart = (part: string): TokenHeader | JWTPayload | undefined =>36 JSON.parse(utf8Decoder.decode(decodeBase64Url(part)))3738export interface TokenHeader {39 alg: SignatureAlgorithm40 typ?: 'JWT'41 kid?: string42}4344export function isTokenHeader(obj: unknown): obj is TokenHeader {45 if (typeof obj === 'object' && obj !== null) {46 const objWithAlg = obj as { [key: string]: unknown }47 return (48 'alg' in objWithAlg &&49 Object.values(AlgorithmTypes).includes(objWithAlg.alg as AlgorithmTypes) &&50 (!('typ' in objWithAlg) || objWithAlg.typ === 'JWT')51 )52 }53 return false54}5556export const sign = async (57 payload: JWTPayload,58 privateKey: SignatureKey,59 alg: SignatureAlgorithm = 'HS256'60): Promise<string> => {61 const encodedPayload = encodeJwtPart(payload)62 let encodedHeader63 if (typeof privateKey === 'object' && 'alg' in privateKey) {64 alg = privateKey.alg as SignatureAlgorithm65 encodedHeader = encodeJwtPart({ alg, typ: 'JWT', kid: privateKey.kid })66 } else {67 encodedHeader = encodeJwtPart({ alg, typ: 'JWT' })68 }6970 const partialToken = `${encodedHeader}.${encodedPayload}`7172 const signaturePart = await signing(privateKey, alg, utf8Encoder.encode(partialToken))73 const signature = encodeSignaturePart(signaturePart)7475 return `${partialToken}.${signature}`76}7778export type VerifyOptions = {79 /** The expected issuer used for verifying the token */80 iss?: string | RegExp81 /** Verify the `nbf` claim (default: `true`) */82 nbf?: boolean83 /** Verify the `exp` claim (default: `true`) */84 exp?: boolean85 /** Verify the `iat` claim (default: `true`) */86 iat?: boolean87 /** Acceptable audience(s) for the token */88 aud?: string | string[] | RegExp89}9091export type VerifyOptionsWithAlg = {92 /** The algorithm used for decoding the token */93 alg: SignatureAlgorithm94} & VerifyOptions9596export const verify = async (97 token: string,98 publicKey: SignatureKey,99 algOrOptions: SignatureAlgorithm | VerifyOptionsWithAlg100): Promise<JWTPayload> => {101 if (!algOrOptions) {102 throw new JwtAlgorithmRequired()103 }104105 const {106 alg,107 iss,108 nbf = true,109 exp = true,110 iat = true,111 aud,112 } = typeof algOrOptions === 'string' ? { alg: algOrOptions } : algOrOptions113114 if (!alg) {115 throw new JwtAlgorithmRequired()116 }117118 const tokenParts = token.split('.')119 if (tokenParts.length !== 3) {120 throw new JwtTokenInvalid(token)121 }122123 const { header, payload } = decode(token)124 if (!isTokenHeader(header)) {125 throw new JwtHeaderInvalid(header)126 }127 if (header.alg !== alg) {128 throw new JwtAlgorithmMismatch(alg, header.alg)129 }130 const now = Math.floor(Date.now() / 1000)131 if (nbf && payload.nbf !== undefined) {132 if (typeof payload.nbf !== 'number' || !Number.isFinite(payload.nbf) || payload.nbf > now) {133 throw new JwtTokenNotBefore(token)134 }135 }136 if (exp && payload.exp !== undefined) {137 if (typeof payload.exp !== 'number' || !Number.isFinite(payload.exp) || payload.exp <= now) {138 throw new JwtTokenExpired(token)139 }140 }141 if (iat && payload.iat !== undefined) {142 if (typeof payload.iat !== 'number' || !Number.isFinite(payload.iat) || now < payload.iat) {143 throw new JwtTokenIssuedAt(now, payload.iat)144 }145 }146 if (iss) {147 if (!payload.iss) {148 throw new JwtTokenIssuer(iss, null)149 }150 if (typeof iss === 'string' && payload.iss !== iss) {151 throw new JwtTokenIssuer(iss, payload.iss)152 }153 if (iss instanceof RegExp && !iss.test(payload.iss)) {154 throw new JwtTokenIssuer(iss, payload.iss)155 }156 }157158 if (aud) {159 if (!payload.aud) {160 throw new JwtPayloadRequiresAud(payload)161 }162163 const audiences = Array.isArray(payload.aud) ? payload.aud : [payload.aud]164 const matched = audiences.some((payloadAud): boolean =>165 aud instanceof RegExp166 ? aud.test(payloadAud)167 : typeof aud === 'string'168 ? payloadAud === aud169 : Array.isArray(aud) && aud.includes(payloadAud)170 )171 if (!matched) {172 throw new JwtTokenAudience(aud, payload.aud)173 }174 }175176 const headerPayload = token.substring(0, token.lastIndexOf('.'))

fix(jwt): throw JwtTokenInvalid when the signature is not valid base64url (#5379)Neil Daquioagbefore adoption52febbc

lines 177–183why, one step back
177 let signature: Uint8Array<ArrayBuffer>
178 try {179 signature = decodeBase64Url(tokenParts[2])180 } catch {181 throw new JwtTokenInvalid(token)182 }183 const verified = await verifying(publicKey, alg, signature, utf8Encoder.encode(headerPayload))

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 184–292why, one step back
184 if (!verified) {
185 throw new JwtTokenSignatureMismatched(token)186 }187188 return payload189}190191// Symmetric algorithms that are not allowed for JWK verification192const symmetricAlgorithms: SymmetricAlgorithm[] = [193 AlgorithmTypes.HS256,194 AlgorithmTypes.HS384,195 AlgorithmTypes.HS512,196]197198export const verifyWithJwks = async (199 token: string,200 options: {201 keys?: HonoJsonWebKey[]202 jwks_uri?: string203 verification?: VerifyOptions204 allowedAlgorithms: readonly AsymmetricAlgorithm[]205 },206 init?: RequestInit207): Promise<JWTPayload> => {208 const verifyOpts = options.verification || {}209210 const header = decodeHeader(token)211212 if (!isTokenHeader(header)) {213 throw new JwtHeaderInvalid(header)214 }215 if (!header.kid) {216 throw new JwtHeaderRequiresKid(header)217 }218219 // Reject symmetric algorithms (HS256, HS384, HS512) to prevent algorithm confusion attacks220 if (symmetricAlgorithms.includes(header.alg as SymmetricAlgorithm)) {221 throw new JwtSymmetricAlgorithmNotAllowed(header.alg)222 }223224 // Validate against allowed algorithms225 if (!options.allowedAlgorithms.includes(header.alg as AsymmetricAlgorithm)) {226 throw new JwtAlgorithmNotAllowed(header.alg, options.allowedAlgorithms)227 }228229 let verifyKeys = options.keys ? [...options.keys] : undefined230231 if (options.jwks_uri) {232 const response = await fetch(options.jwks_uri, init)233 if (!response.ok) {234 throw new Error(`failed to fetch JWKS from ${options.jwks_uri}`)235 }236 const data = (await response.json()) as { keys?: JsonWebKey[] }237 if (!data.keys) {238 throw new Error('invalid JWKS response. "keys" field is missing')239 }240 if (!Array.isArray(data.keys)) {241 throw new Error('invalid JWKS response. "keys" field is not an array')242 }243 verifyKeys ??= []244 verifyKeys.push(...(data.keys as HonoJsonWebKey[]))245 } else if (!verifyKeys) {246 throw new Error('verifyWithJwks requires options for either "keys" or "jwks_uri" or both')247 }248249 const matchingKey = verifyKeys.find((key) => key.kid === header.kid)250 if (!matchingKey) {251 throw new JwtTokenInvalid(token)252 }253254 // Verify that JWK's alg matches JWT header's alg when JWK has alg field255 if (matchingKey.alg && matchingKey.alg !== header.alg) {256 throw new JwtAlgorithmMismatch(matchingKey.alg, header.alg)257 }258259 return await verify(token, matchingKey, {260 alg: header.alg,261 ...verifyOpts,262 })263}264265export const decode = (token: string): { header: TokenHeader; payload: JWTPayload } => {266 const parts = token.split('.')267 if (parts.length !== 3) {268 throw new JwtTokenInvalid(token)269 }270 try {271 const header = decodeJwtPart(parts[0]) as TokenHeader272 const payload = decodeJwtPart(parts[1]) as JWTPayload273 return {274 header,275 payload,276 }277 } catch {278 throw new JwtTokenInvalid(token)279 }280}281282export const decodeHeader = (token: string): TokenHeader => {283 const parts = token.split('.')284 if (parts.length !== 3) {285 throw new JwtTokenInvalid(token)286 }287 try {288 return decodeJwtPart(parts[0]) as TokenHeader289 } catch {290 throw new JwtTokenInvalid(token)291 }292}