Skip to content
Myr

jwt.test.ts

This file

Path

src/utils/jwt/jwt.test.ts

1,788 lines 路 57.8 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

1/* eslint-disable @typescript-eslint/ban-ts-comment */2import { vi } from 'vitest'3import { encodeBase64, encodeBase64Url } from '../encode'4import { AlgorithmTypes } from './jwa'5import type { HonoJsonWebKey } from './jws'6import { signing } from './jws'7import * as JWT from './jwt'8import { verifyWithJwks } from './jwt'9import {10  JwtAlgorithmMismatch,11  JwtAlgorithmNotAllowed,12  JwtAlgorithmNotImplemented,13  JwtAlgorithmRequired,14  JwtPayloadRequiresAud,15  JwtSymmetricAlgorithmNotAllowed,16  JwtTokenAudience,17  JwtTokenExpired,18  JwtTokenInvalid,19  JwtTokenIssuedAt,20  JwtTokenIssuer,21  JwtTokenNotBefore,22  JwtTokenSignatureMismatched,23} from './types'24import { utf8Encoder } from './utf8'2526describe('isTokenHeader', () => {27  it('should return true for valid TokenHeader', () => {28    const validTokenHeader: JWT.TokenHeader = {29      alg: AlgorithmTypes.HS256,30      typ: 'JWT',31    }3233    expect(JWT.isTokenHeader(validTokenHeader)).toBe(true)34  })3536  it('should return false for invalid TokenHeader', () => {37    const invalidTokenHeader = {38      alg: 'invalid',39      typ: 'JWT',40    }4142    expect(JWT.isTokenHeader(invalidTokenHeader)).toBe(false)43  })4445  it('returns true even if the typ field is absent in a TokenHeader', () => {46    const validTokenHeader: JWT.TokenHeader = {47      alg: AlgorithmTypes.HS256,48    }4950    expect(JWT.isTokenHeader(validTokenHeader)).toBe(true)51  })5253  it('returns false when the typ field is present but empty', () => {54    const invalidTokenHeader = {55      alg: AlgorithmTypes.HS256,56      typ: '',57    }5859    expect(JWT.isTokenHeader(invalidTokenHeader)).toBe(false)60  })61})6263describe('JWT', () => {64  it('JwtAlgorithmNotImplemented', async () => {65    const payload = { message: 'hello world' }66    const secret = 'a-secret'67    const alg = ''68    let tok = ''69    let err: JwtAlgorithmNotImplemented70    try {71      tok = await JWT.sign(payload, secret, alg as AlgorithmTypes)72    } catch (e) {73      err = e as JwtAlgorithmNotImplemented74    }75    expect(tok).toBe('')76    // @ts-ignore77    expect(err).toEqual(new JwtAlgorithmNotImplemented(alg))78  })7980  it('JwtTokenInvalid', async () => {81    const tok = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ'82    const secret = 'a-secret'83    let err: JwtTokenInvalid84    let authorized85    try {86      authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)87    } catch (e) {88      err = e as JwtTokenInvalid89    }90    // @ts-ignore91    expect(err).toEqual(new JwtTokenInvalid(tok))92    expect(authorized).toBeUndefined()93  })9495  it('JwtTokenInvalid for a signature that is not valid base64url', async () => {96    const tok = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.@@@@'97    const err = await JWT.verify(tok, 'a-secret', AlgorithmTypes.HS256).catch((e: unknown) => e)98    expect(err).toBeInstanceOf(JwtTokenInvalid)99    expect(err).toHaveProperty('message', `invalid JWT token: ${tok}`)100  })101102  it('JwtTokenSignatureMismatched for an empty signature', async () => {103    const tok = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.'104    const err = await JWT.verify(tok, 'a-secret', AlgorithmTypes.HS256).catch((e: unknown) => e)105    expect(err).toBeInstanceOf(JwtTokenSignatureMismatched)106    expect(err).toHaveProperty('message', `token(${tok}) signature mismatched`)107  })108109  it('JwtTokenNotBefore', async () => {110    const tok =111      'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2NjQ2MDYzMzQsImV4cCI6MTY2NDYwOTkzNCwibmJmIjoiMzEwNDYwNjI2NCJ9.hpSDT_cfkxeiLWEpWVT8TDxFP3dFi27q1K7CcMcLXHc'112    const secret = 'a-secret'113    let err: JwtTokenNotBefore114    let authorized115    try {116      authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)117    } catch (e) {118      err = e as JwtTokenNotBefore119    }120    // @ts-ignore121    expect(err).toEqual(new JwtTokenNotBefore(tok))122    expect(authorized).toBeUndefined()123  })124125  describe('JwtTokenNotBefore with malformed nbf claim', () => {126    it('rejects token with nbf as a non-numeric string', async () => {127      const secret = 'a-secret'128      const tok = await JWT.sign(129        // @ts-expect-error - testing malformed payload (nbf must be number)130        { message: 'hello', nbf: 'tomorrow' },131        secret,132        AlgorithmTypes.HS256133      )134135      let err136      let authorized137      try {138        authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)139      } catch (e) {140        err = e141      }142      expect(err).toEqual(new JwtTokenNotBefore(tok))143      expect(authorized).toBeUndefined()144    })145146    it('rejects token with nbf = Infinity (parsed from 1e400 in JSON)', async () => {147      // JSON.stringify converts Infinity to null, so hand-craft the payload.148      const secret = 'a-secret'149      const encode = (s: string) => encodeBase64Url(utf8Encoder.encode(s).buffer).replace(/=/g, '')150      const encodedHeader = encode('{"alg":"HS256","typ":"JWT"}')151      const encodedPayload = encode('{"message":"hello","nbf":1e400}')152      const signingInput = `${encodedHeader}.${encodedPayload}`153      const signatureBuffer = await signing(154        secret,155        AlgorithmTypes.HS256,156        utf8Encoder.encode(signingInput)157      )158      const tok = `${signingInput}.${encodeBase64Url(signatureBuffer).replace(/=/g, '')}`159160      let err161      let authorized162      try {163        authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)164      } catch (e) {165        err = e166      }167      expect(err).toEqual(new JwtTokenNotBefore(tok))168      expect(authorized).toBeUndefined()169    })170  })171172  it('JwtTokenExpired', async () => {173    const tok =174      'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MzMwNDYxMDAsImV4cCI6MTYzMzA0NjQwMH0.H-OI1TWAbmK8RonvcpPaQcNvOKS9sxinEOsgKwjoiVo'175    const secret = 'a-secret'176    let err177    let authorized178    try {179      authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)180    } catch (e) {181      err = e182    }183    expect(err).toEqual(new JwtTokenExpired(tok))184    expect(authorized).toBeUndefined()185  })186187  it('JwtTokenExpired after Y2038', async () => {188    const postY2038 = 2147483648 // 2038-01-19 03:14:08 UTC189    vi.useFakeTimers().setSystemTime(new Date(postY2038 * 1000))190191    const expIn2025 = 1735689600 // 2025-01-01 00:00:00 UTC192    const payload = { message: 'hello', exp: expIn2025 }193    const secret = 'a-secret'194    const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)195196    let err197    let authorized198    try {199      authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)200    } catch (e) {201      err = e202    }203    expect(err).toEqual(new JwtTokenExpired(tok))204    expect(authorized).toBeUndefined()205206    vi.useRealTimers()207  })208209  describe('JwtTokenExpired with malformed exp claim', () => {210    it('rejects token with exp = 0 (epoch zero)', async () => {211      const secret = 'a-secret'212      const tok = await JWT.sign({ message: 'hello', exp: 0 }, secret, AlgorithmTypes.HS256)213214      let err215      let authorized216      try {217        authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)218      } catch (e) {219        err = e220      }221      expect(err).toEqual(new JwtTokenExpired(tok))222      expect(authorized).toBeUndefined()223    })224225    it('rejects token with exp as a non-numeric string', async () => {226      const secret = 'a-secret'227      const tok = await JWT.sign(228        // @ts-expect-error - testing malformed payload (exp must be number)229        { message: 'hello', exp: 'tomorrow' },230        secret,231        AlgorithmTypes.HS256232      )233234      let err235      let authorized236      try {237        authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)238      } catch (e) {239        err = e240      }241      expect(err).toEqual(new JwtTokenExpired(tok))242      expect(authorized).toBeUndefined()243    })244245    it('rejects token with exp = Infinity (parsed from 1e400 in JSON)', async () => {246      // JSON.stringify converts Infinity to null, so hand-craft the payload.247      const secret = 'a-secret'248      const encode = (s: string) => encodeBase64Url(utf8Encoder.encode(s).buffer).replace(/=/g, '')249      const encodedHeader = encode('{"alg":"HS256","typ":"JWT"}')250      const encodedPayload = encode('{"message":"hello","exp":1e400}')251      const signingInput = `${encodedHeader}.${encodedPayload}`252      const signatureBuffer = await signing(253        secret,254        AlgorithmTypes.HS256,255        utf8Encoder.encode(signingInput)256      )257      const tok = `${signingInput}.${encodeBase64Url(signatureBuffer).replace(/=/g, '')}`258259      let err260      let authorized261      try {262        authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)263      } catch (e) {264        err = e265      }266      expect(err).toEqual(new JwtTokenExpired(tok))267      expect(authorized).toBeUndefined()268    })269  })270271  it('JwtTokenIssuedAt', async () => {272    const now = 1633046400273    vi.useFakeTimers().setSystemTime(new Date().setTime(now * 1000))274275    const iat = now + 1000 // after 1s276    const payload = { role: 'api_role', iat }277    const secret = 'a-secret'278    const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)279280    let err281    let authorized282    try {283      authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)284    } catch (e) {285      err = e286    }287    expect(err).toEqual(new JwtTokenIssuedAt(now, iat))288    expect(authorized).toBeUndefined()289  })290291  describe('JwtTokenIssuedAt with malformed iat claim', () => {292    it('rejects token with iat as a non-numeric string', async () => {293      const now = 1633046400294      vi.useFakeTimers().setSystemTime(new Date(now * 1000))295296      const secret = 'a-secret'297      const tok = await JWT.sign(298        // @ts-expect-error - testing malformed payload (iat must be number)299        { message: 'hello', iat: 'tomorrow' },300        secret,301        AlgorithmTypes.HS256302      )303304      let err305      let authorized306      try {307        authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)308      } catch (e) {309        err = e310      }311      expect(err).toEqual(new JwtTokenIssuedAt(now, 'tomorrow' as unknown as number))312      expect(authorized).toBeUndefined()313314      vi.useRealTimers()315    })316317    it('rejects token with iat = Infinity (parsed from 1e400 in JSON)', async () => {318      // JSON.stringify converts Infinity to null, so hand-craft the payload.319      const now = 1633046400320      vi.useFakeTimers().setSystemTime(new Date(now * 1000))321322      const secret = 'a-secret'323      const encode = (s: string) => encodeBase64Url(utf8Encoder.encode(s).buffer).replace(/=/g, '')324      const encodedHeader = encode('{"alg":"HS256","typ":"JWT"}')325      const encodedPayload = encode('{"message":"hello","iat":1e400}')326      const signingInput = `${encodedHeader}.${encodedPayload}`327      const signatureBuffer = await signing(328        secret,329        AlgorithmTypes.HS256,330        utf8Encoder.encode(signingInput)331      )332      const tok = `${signingInput}.${encodeBase64Url(signatureBuffer).replace(/=/g, '')}`333334      let err335      let authorized336      try {337        authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)338      } catch (e) {339        err = e340      }341      expect(err).toEqual(new JwtTokenIssuedAt(now, Infinity))342      expect(authorized).toBeUndefined()343344      vi.useRealTimers()345    })346  })347348  it('JwtTokenIssuer (none)', async () => {349    const tok =350      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MzMwNDY0MDB9.Ha3tPZzmnLGyFfZYd7GSV0iCn2F9kbZffFVZcTe5kJo'351    const secret = 'a-secret'352    let err353    let authorized354    try {355      authorized = await JWT.verify(tok, secret, {356        alg: AlgorithmTypes.HS256,357        iss: 'some',358      })359    } catch (e) {360      err = e361    }362    expect(err).toEqual(new JwtTokenIssuer('some', null))363    expect(authorized).toBeUndefined()364  })365366  it('JwtTokenIssuer (wrong - string)', async () => {367    const tok =368      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MzMwNDY0MDAsImlzcyI6ImZha2UtaXNzdWVyIn0.miyPU40DBvhxpAUsndssJOMBsP1aqc8JClGnriPHfXk'369    const secret = 'a-secret'370    let err371    let authorized372    try {373      authorized = await JWT.verify(tok, secret, {374        alg: AlgorithmTypes.HS256,375        iss: 'expected-issuer',376      })377    } catch (e) {378      err = e379    }380    expect(err).toEqual(new JwtTokenIssuer('expected-issuer', 'fake-issuer'))381    expect(authorized).toBeUndefined()382  })383384  it('JwtTokenIssuer (wrong - RegExp)', async () => {385    const tok =386      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MzMwNDY0MDAsImlzcyI6ImhleSJ9.Q0NJwoj-meWy42pFFrPNlREe2lOagWioJUjR4eJCx0k'387    const secret = 'a-secret'388    let err389    let authorized390    try {391      authorized = await JWT.verify(tok, secret, {392        alg: AlgorithmTypes.HS256,393        iss: /^(hello|hi)$/,394      })395    } catch (e) {396      err = e397    }398    expect(err).toEqual(new JwtTokenIssuer(/^(hello|hi)$/, 'hey'))399    expect(authorized).toBeUndefined()400  })401402  it('JwtTokenIssuer (correct - string)', async () => {403    const tok =404      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MzMwNDY0MDAsImlzcyI6ImNvcnJlY3QtaXNzdWVyIn0.gF8S6M2QcfTTscgxeyihNk28JAOa8mfL1bXPb3_E3rk'405    const secret = 'a-secret'406    let err407    let authorized408    try {409      authorized = await JWT.verify(tok, secret, {410        alg: AlgorithmTypes.HS256,411        iss: 'correct-issuer',412      })413    } catch (e) {414      err = e415    }416    expect(err).toBeUndefined()417    expect(authorized?.iss).toEqual('correct-issuer')418  })419420  it('JwtTokenIssuer (correct - RegExp)', async () => {421    const tok =422      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MzMwNDY0MDAsImlzcyI6ImhlbGxvIn0.5DDuValGGQu4EfS3DY7C4hwwHyTNSTD93K_YEjBzgAc'423    const secret = 'a-secret'424    let err425    let authorized426    try {427      authorized = await JWT.verify(tok, secret, {428        alg: AlgorithmTypes.HS256,429        iss: /^(hello|hi)$/,430      })431    } catch (e) {432      err = e433    }434    expect(err).toBeUndefined()435    expect(authorized?.iss).toEqual('hello')436  })437438  it('JwtPayloadRequireAud', async () => {439    const tok =440      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2lzc3Vlci5leGFtcGxlIiwiaWF0IjoxfQ.3Yd0dDicCKA6zu_G6AvxMX_fRH5wMz9gMCedOsYNAGc'441    const secret = 'a-secret'442    let err443    let authorized444    try {445      authorized = await JWT.verify(tok, secret, {446        alg: AlgorithmTypes.HS256,447        aud: 'correct-audience',448      })449    } catch (e) {450      err = e451    }452    expect(err).toEqual(new JwtPayloadRequiresAud({ iss: 'https://issuer.example', iat: 1 }))453    expect(authorized).toBeUndefined()454  })455456  it('JwtTokenAudience(correct string - string)', async () => {457    const tok =458      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2lzc3Vlci5leGFtcGxlIiwiYXVkIjoiY29ycmVjdC1hdWRpZW5jZSIsImlhdCI6MX0.z8T6szX-k66de4xB9OFbpWAOfx0RTqKSUPBcdpSY5nk'459    const secret = 'a-secret'460    let err461    let authorized462    try {463      authorized = await JWT.verify(tok, secret, {464        alg: AlgorithmTypes.HS256,465        aud: 'correct-audience',466      })467    } catch (e) {468      err = e469    }470    expect(err).toBeUndefined()471    expect(authorized?.aud).toEqual('correct-audience')472  })473474  it('JwtTokenAudience(correct string - string[])', async () => {475    const tok =476      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2lzc3Vlci5leGFtcGxlIiwiYXVkIjoiY29ycmVjdC1hdWRpZW5jZSIsImlhdCI6MX0.z8T6szX-k66de4xB9OFbpWAOfx0RTqKSUPBcdpSY5nk'477    const secret = 'a-secret'478    let err479    let authorized480    try {481      authorized = await JWT.verify(tok, secret, {482        alg: AlgorithmTypes.HS256,483        aud: ['correct-audience', 'other-audience'],484      })485    } catch (e) {486      err = e487    }488    expect(err).toBeUndefined()489    expect(authorized?.aud).toEqual('correct-audience')490  })491492  it('JwtTokenAudience(correct string - RegExp)', async () => {493    const tok =494      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2lzc3Vlci5leGFtcGxlIiwiYXVkIjoiY29ycmVjdC1hdWRpZW5jZSIsImlhdCI6MX0.z8T6szX-k66de4xB9OFbpWAOfx0RTqKSUPBcdpSY5nk'495    const secret = 'a-secret'496    let err497    let authorized498    try {499      authorized = await JWT.verify(tok, secret, {500        alg: AlgorithmTypes.HS256,501        aud: /^correct-audience$/,502      })503    } catch (e) {504      err = e505    }506    expect(err).toBeUndefined()507    expect(authorized?.aud).toEqual('correct-audience')508  })509510  it('JwtTokenAudience(correct string[] - string)', async () => {511    const tok =512      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2lzc3Vlci5leGFtcGxlIiwiYXVkIjpbImNvcnJlY3QtYXVkaWVuY2UiLCJvdGhlci1hdWRpZW5jZSJdLCJpYXQiOjF9.l73pNR5zMMAyuoN3f32hKtRJkoxZNzgTcVBZ2A2EsJY'513    const secret = 'a-secret'514    let err515    let authorized516    try {517      authorized = await JWT.verify(tok, secret, {518        alg: AlgorithmTypes.HS256,519        aud: 'correct-audience',520      })521    } catch (e) {522      err = e523    }524    expect(err).toBeUndefined()525    expect(authorized?.aud).toEqual(['correct-audience', 'other-audience'])526  })527528  it('JwtTokenAudience(correct string[] - string[])', async () => {529    const tok =530      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2lzc3Vlci5leGFtcGxlIiwiYXVkIjpbImNvcnJlY3QtYXVkaWVuY2UiLCJvdGhlci1hdWRpZW5jZSJdLCJpYXQiOjF9.l73pNR5zMMAyuoN3f32hKtRJkoxZNzgTcVBZ2A2EsJY'531    const secret = 'a-secret'532    let err533    let authorized534    try {535      authorized = await JWT.verify(tok, secret, {536        alg: AlgorithmTypes.HS256,537        aud: ['correct-audience', 'test'],538      })539    } catch (e) {540      err = e541    }542    expect(err).toBeUndefined()543    expect(authorized?.aud).toEqual(['correct-audience', 'other-audience'])544  })545546  it('JwtTokenAudience(correct string[] - RegExp)', async () => {547    const tok =548      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2lzc3Vlci5leGFtcGxlIiwiYXVkIjpbImNvcnJlY3QtYXVkaWVuY2UiLCJvdGhlci1hdWRpZW5jZSJdLCJpYXQiOjF9.l73pNR5zMMAyuoN3f32hKtRJkoxZNzgTcVBZ2A2EsJY'549    const secret = 'a-secret'550    let err551    let authorized552    try {553      authorized = await JWT.verify(tok, secret, {554        alg: AlgorithmTypes.HS256,555        aud: /^correct-audience$/,556      })557    } catch (e) {558      err = e559    }560    expect(err).toBeUndefined()561    expect(authorized?.aud).toEqual(['correct-audience', 'other-audience'])562  })563564  it('JwtTokenAudience(wrong string - string)', async () => {565    const tok =566      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2lzc3Vlci5leGFtcGxlIiwiYXVkIjoid3JvbmctYXVkaWVuY2UiLCJpYXQiOjF9.2vTYLiYL5r6qN-iRQ0VSfXh4ioLFtNzo0qc-OoPZmow'567    const secret = 'a-secret'568    let err569    let authorized570    try {571      authorized = await JWT.verify(tok, secret, {572        alg: AlgorithmTypes.HS256,573        aud: 'correct-audience',574      })575    } catch (e) {576      err = e577    }578    expect(err).toEqual(new JwtTokenAudience('correct-audience', 'wrong-audience'))579    expect(authorized).toBeUndefined()580  })581582  it('JwtTokenAudience(wrong string - string[])', async () => {583    const tok =584      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2lzc3Vlci5leGFtcGxlIiwiYXVkIjoid3JvbmctYXVkaWVuY2UiLCJpYXQiOjF9.2vTYLiYL5r6qN-iRQ0VSfXh4ioLFtNzo0qc-OoPZmow'585    const secret = 'a-secret'586    let err587    let authorized588    try {589      authorized = await JWT.verify(tok, secret, {590        alg: AlgorithmTypes.HS256,591        aud: ['correct-audience', 'other-audience'],592      })593    } catch (e) {594      err = e595    }596    expect(err).toEqual(597      new JwtTokenAudience(['correct-audience', 'other-audience'], 'wrong-audience')598    )599    expect(authorized).toBeUndefined()600  })601602  it('JwtTokenAudience(wrong string - RegExp)', async () => {603    const tok =604      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2lzc3Vlci5leGFtcGxlIiwiYXVkIjoid3JvbmctYXVkaWVuY2UiLCJpYXQiOjF9.2vTYLiYL5r6qN-iRQ0VSfXh4ioLFtNzo0qc-OoPZmow'605    const secret = 'a-secret'606    let err607    let authorized608    try {609      authorized = await JWT.verify(tok, secret, {610        alg: AlgorithmTypes.HS256,611        aud: /^correct-audience$/,612      })613    } catch (e) {614      err = e615    }616    expect(err).toEqual(new JwtTokenAudience(/^correct-audience$/, 'wrong-audience'))617    expect(authorized).toBeUndefined()618  })619620  it('JwtTokenAudience(wrong string[] - string)', async () => {621    const tok =622      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2lzc3Vlci5leGFtcGxlIiwiYXVkIjpbIndyb25nLWF1ZGllbmNlIiwib3RoZXItYXVkaWVuY2UiXSwiaWF0IjoxfQ.YTAM1xtKP4AeEeQSFQ81rcJM1leW_uDayQcTE6LxoP0'623    const secret = 'a-secret'624    let err625    let authorized626    try {627      authorized = await JWT.verify(tok, secret, {628        alg: AlgorithmTypes.HS256,629        aud: 'correct-audience',630      })631    } catch (e) {632      err = e633    }634    expect(err).toEqual(635      new JwtTokenAudience('correct-audience', ['wrong-audience', 'other-audience'])636    )637    expect(authorized).toBeUndefined()638  })639640  it('JwtTokenAudience(wrong string[] - string[])', async () => {641    const tok =642      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2lzc3Vlci5leGFtcGxlIiwiYXVkIjpbIndyb25nLWF1ZGllbmNlIiwib3RoZXItYXVkaWVuY2UiXSwiaWF0IjoxfQ.YTAM1xtKP4AeEeQSFQ81rcJM1leW_uDayQcTE6LxoP0'643    const secret = 'a-secret'644    let err645    let authorized646    try {647      authorized = await JWT.verify(tok, secret, {648        alg: AlgorithmTypes.HS256,649        aud: ['correct-audience', 'test'],650      })651    } catch (e) {652      err = e653    }654    expect(err).toEqual(655      new JwtTokenAudience(['correct-audience', 'test'], ['wrong-audience', 'other-audience'])656    )657    expect(authorized).toBeUndefined()658  })659660  it('JwtTokenAudience(wrong string[] - RegExp)', async () => {661    const tok =662      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2lzc3Vlci5leGFtcGxlIiwiYXVkIjpbIndyb25nLWF1ZGllbmNlIiwib3RoZXItYXVkaWVuY2UiXSwiaWF0IjoxfQ.YTAM1xtKP4AeEeQSFQ81rcJM1leW_uDayQcTE6LxoP0'663    const secret = 'a-secret'664    let err665    let authorized666    try {667      authorized = await JWT.verify(tok, secret, {668        alg: AlgorithmTypes.HS256,669        aud: /^correct-audience$/,670      })671    } catch (e) {672      err = e673    }674    expect(err).toEqual(675      new JwtTokenAudience(/^correct-audience$/, ['wrong-audience', 'other-audience'])676    )677    expect(authorized).toBeUndefined()678  })679680  it('JwtTokenAudience (no aud option and wrong aud in payload)', async () => {681    const tok =682      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2lzc3Vlci5leGFtcGxlIiwiYXVkIjoid3JvbmctYXVkaWVuY2UiLCJpYXQiOjF9.2vTYLiYL5r6qN-iRQ0VSfXh4ioLFtNzo0qc-OoPZmow'683    const secret = 'a-secret'684    let err685    let authorized686    try {687      authorized = await JWT.verify(tok, secret, {688        alg: AlgorithmTypes.HS256,689      })690    } catch (e) {691      err = e692    }693    expect(err).toBeUndefined()694    expect(authorized?.aud).toEqual('wrong-audience')695  })696697  it('HS256 sign & verify & decode', async () => {698    const payload = { message: 'hello world' }699    const secret = 'a-secret'700    const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)701    const expected =702      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'703    expect(tok).toEqual(expected)704705    const verifiedPayload = await JWT.verify(tok, secret, AlgorithmTypes.HS256)706    expect(verifiedPayload).not.toBeUndefined()707    expect(verifiedPayload).toEqual(payload)708709    expect(JWT.decode(tok)).toEqual({710      header: {711        alg: 'HS256',712        typ: 'JWT',713      },714      payload: {715        message: 'hello world',716      },717    })718  })719720  it('HS256 sign & verify', async () => {721    const payload = { message: 'hello world' }722    const secret = 'a-secret'723    const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)724    const expected =725      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'726    expect(tok).toEqual(expected)727728    let err = null729    let authorized730    try {731      authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)732    } catch (e) {733      err = e734    }735    expect(authorized).toBeUndefined()736    expect(err instanceof JwtTokenSignatureMismatched).toBe(true)737  })738739  it('HS512 sign & verify & decode', async () => {740    const payload = { message: 'hello world' }741    const secret = 'a-secret'742    const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS512)743    const expected =744      'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.RqVLgExB_GXF1-9T-k4V4HjFmiuQKTEjVSiZd-YL0WERIlywZ7PfzAuTZSJU4gg8cscGamQa030cieEWrYcywg'745    expect(tok).toEqual(expected)746747    const verifiedPayload = await JWT.verify(tok, secret, AlgorithmTypes.HS512)748    expect(verifiedPayload).not.toBeUndefined()749    expect(verifiedPayload).toEqual(payload)750751    expect(JWT.decode(tok)).toEqual({752      header: {753        alg: 'HS512',754        typ: 'JWT',755      },756      payload: {757        message: 'hello world',758      },759    })760  })761762  it('HS512 sign & verify', async () => {763    const payload = { message: 'hello world' }764    const secret = 'a-secret'765    const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS512)766    const expected =767      'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.RqVLgExB_GXF1-9T-k4V4HjFmiuQKTEjVSiZd-YL0WERIlywZ7PfzAuTZSJU4gg8cscGamQa030cieEWrYcywg'768    expect(tok).toEqual(expected)769770    let err = null771    let authorized772    try {773      authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS512)774    } catch (e) {775      err = e776    }777    expect(authorized).toBeUndefined()778    expect(err instanceof JwtTokenSignatureMismatched).toBe(true)779  })780781  it('HS384 sign & verify', async () => {782    const payload = { message: 'hello world' }783    const secret = 'a-secret%浣犲ソ'784    const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS384)785    const expected =786      'eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.C1Br1183Oy6O7th4NDCOaI9WB75i3FMCuYlv1tCL9HggsU89T-SNutghwhJykD3r'787    expect(tok).toEqual(expected)788789    let err = null790    let authorized791    try {792      authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS384)793    } catch (e) {794      err = e795    }796    expect(authorized).toBeUndefined()797    expect(err instanceof JwtTokenSignatureMismatched).toBe(true)798  })799800  it('sign & verify & decode with a custom secret', async () => {801    const payload = { message: 'hello world' }802    const algorithm = {803      name: 'HMAC',804      hash: {805        name: 'SHA-256',806      },807    }808    const secret = await crypto.subtle.importKey(809      'raw',810      Buffer.from('cefb73234d5fae4bf27662900732b52943e8d53e871fe0f353da95de4599c21d', 'hex'),811      algorithm,812      false,813      ['sign', 'verify']814    )815    const tok = await JWT.sign(payload, secret)816    const expected =817      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.qunGhchNXH_unqWXN6hB0Elhzr5SykSXVhklLti1aFI'818    expect(tok).toEqual(expected)819820    const verifiedPayload = await JWT.verify(tok, secret, AlgorithmTypes.HS256)821    expect(verifiedPayload).not.toBeUndefined()822    expect(verifiedPayload).toEqual(payload)823824    const invalidSecret = await crypto.subtle.importKey(825      'raw',826      Buffer.from('cefb73234d5fae4bf27662900732b52943e8d53e871fe0f353da95de41111111', 'hex'),827      algorithm,828      false,829      ['sign', 'verify']830    )831    let err = null832    let authorized833    try {834      authorized = await JWT.verify(tok, invalidSecret, AlgorithmTypes.HS256)835    } catch (e) {836      err = e837    }838    expect(authorized).toBeUndefined()839    expect(err instanceof JwtTokenSignatureMismatched).toBe(true)840  })841842  const rsTestCases = [843    {844      alg: AlgorithmTypes.RS256,845      hash: 'SHA-256',846    },847    {848      alg: AlgorithmTypes.RS384,849      hash: 'SHA-384',850    },851    {852      alg: AlgorithmTypes.RS512,853      hash: 'SHA-512',854    },855  ]856  for (const tc of rsTestCases) {857    it(`${tc.alg} sign & verify`, async () => {858      const alg = tc.alg859      const payload = { message: 'hello world' }860      const keyPair = await generateRSAKey(tc.hash)861      const pemPrivateKey = await exportPEMPrivateKey(keyPair.privateKey)862      const pemPublicKey = await exportPEMPublicKey(keyPair.publicKey)863      const jwkPublicKey = await exportJWK(keyPair.publicKey)864865      const tok = await JWT.sign(payload, pemPrivateKey, alg)866      expect(await JWT.verify(tok, pemPublicKey, alg)).toEqual(payload)867      expect(await JWT.verify(tok, pemPrivateKey, alg)).toEqual(payload)868      expect(await JWT.verify(tok, jwkPublicKey, alg)).toEqual(payload)869870      const keyPair2 = await generateRSAKey(tc.hash)871      const unexpectedPemPublicKey = await exportPEMPublicKey(keyPair2.publicKey)872873      let err = null874      let authorized875      try {876        authorized = await JWT.verify(tok, unexpectedPemPublicKey, alg)877      } catch (e) {878        err = e879      }880      expect(authorized).toBeUndefined()881      expect(err instanceof JwtTokenSignatureMismatched).toBe(true)882    })883884    it(`${tc.alg} sign & verify w/ CryptoKey`, async () => {885      const alg = tc.alg886      const payload = { message: 'hello world' }887      const keyPair = await generateRSAKey(tc.hash)888889      const tok = await JWT.sign(payload, keyPair.privateKey, alg)890      expect(await JWT.verify(tok, keyPair.privateKey, alg)).toEqual(payload)891      expect(await JWT.verify(tok, keyPair.publicKey, alg)).toEqual(payload)892    })893  }894895  const psTestCases = [896    {897      alg: AlgorithmTypes.PS256,898      hash: 'SHA-256',899    },900    {901      alg: AlgorithmTypes.PS384,902      hash: 'SHA-384',903    },904    {905      alg: AlgorithmTypes.PS512,906      hash: 'SHA-512',907    },908  ]909  for (const tc of psTestCases) {910    it(`${tc.alg} sign & verify`, async () => {911      const alg = tc.alg912      const payload = { message: 'hello world' }913      const keyPair = await generateRSAPSSKey(tc.hash)914      const pemPrivateKey = await exportPEMPrivateKey(keyPair.privateKey)915      const pemPublicKey = await exportPEMPublicKey(keyPair.publicKey)916      const jwkPublicKey = await exportJWK(keyPair.publicKey)917918      const tok = await JWT.sign(payload, pemPrivateKey, alg)919      expect(await JWT.verify(tok, pemPublicKey, alg)).toEqual(payload)920      expect(await JWT.verify(tok, pemPrivateKey, alg)).toEqual(payload)921      expect(await JWT.verify(tok, jwkPublicKey, alg)).toEqual(payload)922923      const keyPair2 = await generateRSAPSSKey(tc.hash)924      const unexpectedPemPublicKey = await exportPEMPublicKey(keyPair2.publicKey)925926      let err = null927      let authorized928      try {929        authorized = await JWT.verify(tok, unexpectedPemPublicKey, alg)930      } catch (e) {931        err = e932      }933      expect(authorized).toBeUndefined()934      expect(err instanceof JwtTokenSignatureMismatched).toBe(true)935    })936937    it(`${tc.alg} sign & verify w/ CryptoKey`, async () => {938      const alg = tc.alg939      const payload = { message: 'hello world' }940      const keyPair = await generateRSAPSSKey(tc.hash)941942      const tok = await JWT.sign(payload, keyPair.privateKey, alg)943      expect(await JWT.verify(tok, keyPair.privateKey, alg)).toEqual(payload)944      expect(await JWT.verify(tok, keyPair.publicKey, alg)).toEqual(payload)945    })946  }947948  const esTestCases = [949    {950      alg: AlgorithmTypes.ES256,951      namedCurve: 'P-256',952    },953    {954      alg: AlgorithmTypes.ES384,955      namedCurve: 'P-384',956    },957    {958      alg: AlgorithmTypes.ES512,959      namedCurve: 'P-521',960    },961  ]962  for (const tc of esTestCases) {963    it(`${tc.alg} sign & verify`, async () => {964      const alg = tc.alg965      const payload = { message: 'hello world' }966      const keyPair = await generateECDSAKey(tc.namedCurve)967      const pemPrivateKey = await exportPEMPrivateKey(keyPair.privateKey)968      const pemPublicKey = await exportPEMPublicKey(keyPair.publicKey)969      const jwkPublicKey = await exportJWK(keyPair.publicKey)970971      const tok = await JWT.sign(payload, pemPrivateKey, alg)972      expect(await JWT.verify(tok, pemPublicKey, alg)).toEqual(payload)973      expect(await JWT.verify(tok, pemPrivateKey, alg)).toEqual(payload)974      expect(await JWT.verify(tok, jwkPublicKey, alg)).toEqual(payload)975976      const keyPair2 = await generateECDSAKey(tc.namedCurve)977      const unexpectedPemPublicKey = await exportPEMPublicKey(keyPair2.publicKey)978979      let err = null980      let authorized981      try {982        authorized = await JWT.verify(tok, unexpectedPemPublicKey, alg)983      } catch (e) {984        err = e985      }986      expect(authorized).toBeUndefined()987      expect(err instanceof JwtTokenSignatureMismatched).toBe(true)988    })989990    it(`${tc.alg} sign & verify w/ CryptoKey`, async () => {991      const alg = tc.alg992      const payload = { message: 'hello world' }993      const keyPair = await generateECDSAKey(tc.namedCurve)994995      const tok = await JWT.sign(payload, keyPair.privateKey, alg)996      expect(await JWT.verify(tok, keyPair.privateKey, alg)).toEqual(payload)997      expect(await JWT.verify(tok, keyPair.publicKey, alg)).toEqual(payload)998    })999  }10001001  it('EdDSA sign & verify', async () => {1002    const alg = 'EdDSA'1003    const payload = { message: 'hello world' }1004    const keyPair = await generateEd25519Key()1005    const pemPrivateKey = await exportPEMPrivateKey(keyPair.privateKey)1006    const pemPublicKey = await exportPEMPublicKey(keyPair.publicKey)1007    const jwkPublicKey = await exportJWK(keyPair.publicKey)10081009    const tok = await JWT.sign(payload, pemPrivateKey, alg)1010    expect(await JWT.verify(tok, pemPublicKey, alg)).toEqual(payload)1011    expect(await JWT.verify(tok, pemPrivateKey, alg)).toEqual(payload)1012    expect(await JWT.verify(tok, jwkPublicKey, alg)).toEqual(payload)10131014    const keyPair2 = await generateEd25519Key()1015    const unexpectedPemPublicKey = await exportPEMPublicKey(keyPair2.publicKey)10161017    let err = null1018    let authorized1019    try {1020      authorized = await JWT.verify(tok, unexpectedPemPublicKey, alg)1021    } catch (e) {1022      err = e1023    }1024    expect(authorized).toBeUndefined()1025    expect(err instanceof JwtTokenSignatureMismatched).toBe(true)1026  })10271028  it('EdDSA sign & verify w/ CryptoKey', async () => {1029    const alg = 'EdDSA'1030    const payload = { message: 'hello world' }1031    const keyPair = await generateEd25519Key()10321033    const tok = await JWT.sign(payload, keyPair.privateKey, alg)1034    expect(await JWT.verify(tok, keyPair.privateKey, alg)).toEqual(payload)1035    expect(await JWT.verify(tok, keyPair.publicKey, alg)).toEqual(payload)1036  })1037})10381039describe('verifyWithJwks header.alg fallback', () => {1040  it('Should use header.alg as fallback when matchingKey.alg is missing', async () => {1041    // Setup: Create a JWT signed with RS256 (asymmetric algorithm)1042    const payload = { message: 'hello world' }1043    const headerAlg = 'RS256'1044    const kid = 'dummy'10451046    // Generate RSA key pair1047    const keyPair = await crypto.subtle.generateKey(1048      {1049        name: 'RSASSA-PKCS1-v1_5',1050        modulusLength: 2048,1051        publicExponent: new Uint8Array([1, 0, 1]),1052        hash: 'SHA-256',1053      },1054      true,1055      ['sign', 'verify']1056    )10571058    // Create JWT (signed with RS256)1059    const header = { alg: headerAlg, typ: 'JWT', kid }1060    const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1061    const encodedHeader = encode(header)1062    const encodedPayload = encode(payload)1063    const signingInput = `${encodedHeader}.${encodedPayload}`10641065    // Sign with private key1066    const signatureBuffer = await signing(1067      keyPair.privateKey,1068      headerAlg,1069      utf8Encoder.encode(signingInput)1070    )1071    const signature = encodeBase64Url(signatureBuffer)10721073    const token = `${encodedHeader}.${encodedPayload}.${signature}`10741075    // Export public key as JWK without alg property1076    const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)1077    const keyWithoutAlg = {1078      ...jwk,1079      kid,1080      use: 'sig',1081    }1082    delete keyWithoutAlg.alg // intentionally omit alg10831084    const keys = [keyWithoutAlg]10851086    // Execute: Verify the JWT token signed with RS256 with allowedAlgorithms required1087    const result = await verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })10881089    // If verification succeeds, it means header.alg was used1090    expect(result).toEqual(payload)1091  })1092})10931094describe('verifyWithJwks security', () => {1095  it('Should reject symmetric algorithm HS256', async () => {1096    const payload = { message: 'hello world' }1097    const secret = 'secret'1098    const kid = 'dummy'10991100    // Create JWT (signed with HS256)1101    const header = { alg: 'HS256', typ: 'JWT', kid }1102    const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1103    const encodedHeader = encode(header)1104    const encodedPayload = encode(payload)1105    const signingInput = `${encodedHeader}.${encodedPayload}`11061107    const signatureBuffer = await signing(secret, 'HS256', utf8Encoder.encode(signingInput))1108    const signature = encodeBase64Url(signatureBuffer)11091110    const token = `${encodedHeader}.${encodedPayload}.${signature}`11111112    const keys = [1113      {1114        kty: 'oct',1115        kid,1116        k: encodeBase64Url(utf8Encoder.encode(secret).buffer),1117        use: 'sig',1118        alg: 'HS256',1119      },1120    ]11211122    // HS256 is rejected before allowedAlgorithms check (symmetric algorithm rejection)1123    await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })).rejects.toThrow(1124      JwtSymmetricAlgorithmNotAllowed1125    )1126  })11271128  it('Should reject symmetric algorithm HS384', async () => {1129    const payload = { message: 'hello world' }1130    const secret = 'secret'1131    const kid = 'dummy'11321133    const header = { alg: 'HS384', typ: 'JWT', kid }1134    const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1135    const encodedHeader = encode(header)1136    const encodedPayload = encode(payload)1137    const signingInput = `${encodedHeader}.${encodedPayload}`11381139    const signatureBuffer = await signing(secret, 'HS384', utf8Encoder.encode(signingInput))1140    const signature = encodeBase64Url(signatureBuffer)11411142    const token = `${encodedHeader}.${encodedPayload}.${signature}`11431144    const keys = [1145      {1146        kty: 'oct',1147        kid,1148        k: encodeBase64Url(utf8Encoder.encode(secret).buffer),1149        use: 'sig',1150        alg: 'HS384',1151      },1152    ]11531154    // HS384 is rejected before allowedAlgorithms check (symmetric algorithm rejection)1155    await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })).rejects.toThrow(1156      JwtSymmetricAlgorithmNotAllowed1157    )1158  })11591160  it('Should reject symmetric algorithm HS512', async () => {1161    const payload = { message: 'hello world' }1162    const secret = 'secret'1163    const kid = 'dummy'11641165    const header = { alg: 'HS512', typ: 'JWT', kid }1166    const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1167    const encodedHeader = encode(header)1168    const encodedPayload = encode(payload)1169    const signingInput = `${encodedHeader}.${encodedPayload}`11701171    const signatureBuffer = await signing(secret, 'HS512', utf8Encoder.encode(signingInput))1172    const signature = encodeBase64Url(signatureBuffer)11731174    const token = `${encodedHeader}.${encodedPayload}.${signature}`11751176    const keys = [1177      {1178        kty: 'oct',1179        kid,1180        k: encodeBase64Url(utf8Encoder.encode(secret).buffer),1181        use: 'sig',1182        alg: 'HS512',1183      },1184    ]11851186    // HS512 is rejected before allowedAlgorithms check (symmetric algorithm rejection)1187    await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })).rejects.toThrow(1188      JwtSymmetricAlgorithmNotAllowed1189    )1190  })11911192  it('Should reject algorithm mismatch between JWK and JWT header', async () => {1193    const payload = { message: 'hello world' }1194    const kid = 'dummy'11951196    // Generate RS256 key pair1197    const keyPair = await crypto.subtle.generateKey(1198      {1199        name: 'RSASSA-PKCS1-v1_5',1200        modulusLength: 2048,1201        publicExponent: new Uint8Array([1, 0, 1]),1202        hash: 'SHA-256',1203      },1204      true,1205      ['sign', 'verify']1206    )12071208    // Create JWT with RS384 in header (mismatch with RS256 key)1209    const header = { alg: 'RS384', typ: 'JWT', kid }1210    const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1211    const encodedHeader = encode(header)1212    const encodedPayload = encode(payload)1213    const signingInput = `${encodedHeader}.${encodedPayload}`12141215    // Sign with RS256 key (but header says RS384)1216    const signatureBuffer = await signing(1217      keyPair.privateKey,1218      'RS256',1219      utf8Encoder.encode(signingInput)1220    )1221    const signature = encodeBase64Url(signatureBuffer)12221223    const token = `${encodedHeader}.${encodedPayload}.${signature}`12241225    // Export public key as JWK with RS256 alg1226    const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)1227    const keyWithAlg = {1228      ...jwk,1229      kid,1230      use: 'sig',1231      alg: 'RS256', // JWK says RS256, but header says RS3841232    }12331234    const keys = [keyWithAlg]12351236    // RS384 in header doesn't match RS256 in JWK alg field1237    await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['RS384'] })).rejects.toThrow(1238      JwtAlgorithmMismatch1239    )1240  })12411242  it('Should allow asymmetric algorithm RS256 with matching alg', async () => {1243    const payload = { message: 'hello world' }1244    const kid = 'dummy'12451246    const keyPair = await crypto.subtle.generateKey(1247      {1248        name: 'RSASSA-PKCS1-v1_5',1249        modulusLength: 2048,1250        publicExponent: new Uint8Array([1, 0, 1]),1251        hash: 'SHA-256',1252      },1253      true,1254      ['sign', 'verify']1255    )12561257    const header = { alg: 'RS256', typ: 'JWT', kid }1258    const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1259    const encodedHeader = encode(header)1260    const encodedPayload = encode(payload)1261    const signingInput = `${encodedHeader}.${encodedPayload}`12621263    const signatureBuffer = await signing(1264      keyPair.privateKey,1265      'RS256',1266      utf8Encoder.encode(signingInput)1267    )1268    const signature = encodeBase64Url(signatureBuffer)12691270    const token = `${encodedHeader}.${encodedPayload}.${signature}`12711272    const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)1273    const keyWithAlg = {1274      ...jwk,1275      kid,1276      use: 'sig',1277      alg: 'RS256',1278    }12791280    const keys = [keyWithAlg]12811282    const result = await verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })1283    expect(result).toEqual(payload)1284  })12851286  it('Should reject algorithm confusion attack (HS256 with RSA public key)', async () => {1287    // This test simulates the algorithm confusion attack where an attacker1288    // tries to use HS256 with a public RSA key as the HMAC secret1289    const payload = { message: 'hello world' }1290    const kid = 'dummy'12911292    // Generate RSA key pair (normally used for RS256)1293    const keyPair = await crypto.subtle.generateKey(1294      {1295        name: 'RSASSA-PKCS1-v1_5',1296        modulusLength: 2048,1297        publicExponent: new Uint8Array([1, 0, 1]),1298        hash: 'SHA-256',1299      },1300      true,1301      ['sign', 'verify']1302    )13031304    // Attacker creates a JWT with HS256 in header1305    const header = { alg: 'HS256', typ: 'JWT', kid }1306    const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1307    const encodedHeader = encode(header)1308    const encodedPayload = encode(payload)1309    const signingInput = `${encodedHeader}.${encodedPayload}`13101311    // Export public key as JWK (which would be used in a real attack)1312    const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)13131314    // Attacker would sign with the public key bytes as HMAC secret1315    // We don't need to actually sign for this test - just verify rejection1316    const signatureBuffer = await signing('fake-secret', 'HS256', utf8Encoder.encode(signingInput))1317    const signature = encodeBase64Url(signatureBuffer)13181319    const token = `${encodedHeader}.${encodedPayload}.${signature}`13201321    // JWK has RS256 alg, but JWT header has HS256 (confusion attack)1322    const keyWithAlg = {1323      ...jwk,1324      kid,1325      use: 'sig',1326      alg: 'RS256',1327    }13281329    const keys = [keyWithAlg]13301331    // Should reject because HS256 is a symmetric algorithm (checked before allowedAlgorithms)1332    await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })).rejects.toThrow(1333      JwtSymmetricAlgorithmNotAllowed1334    )1335  })1336})13371338describe('verifyWithJwks algorithm whitelist', () => {1339  it('Should reject algorithm not in whitelist', async () => {1340    const payload = { message: 'hello world' }1341    const kid = 'dummy'13421343    // Generate RS256 key pair1344    const keyPair = await crypto.subtle.generateKey(1345      {1346        name: 'RSASSA-PKCS1-v1_5',1347        modulusLength: 2048,1348        publicExponent: new Uint8Array([1, 0, 1]),1349        hash: 'SHA-256',1350      },1351      true,1352      ['sign', 'verify']1353    )13541355    // Create JWT with RS2561356    const header = { alg: 'RS256', typ: 'JWT', kid }1357    const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1358    const encodedHeader = encode(header)1359    const encodedPayload = encode(payload)1360    const signingInput = `${encodedHeader}.${encodedPayload}`13611362    const signatureBuffer = await signing(1363      keyPair.privateKey,1364      'RS256',1365      utf8Encoder.encode(signingInput)1366    )1367    const signature = encodeBase64Url(signatureBuffer)13681369    const token = `${encodedHeader}.${encodedPayload}.${signature}`13701371    const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)1372    const keyWithAlg = {1373      ...jwk,1374      kid,1375      use: 'sig',1376      alg: 'RS256',1377    }13781379    const keys = [keyWithAlg]13801381    // RS256 is not in the whitelist (only ES256 is allowed)1382    await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['ES256'] })).rejects.toThrow(1383      JwtAlgorithmNotAllowed1384    )1385  })13861387  it('Should accept algorithm in whitelist', async () => {1388    const payload = { message: 'hello world' }1389    const kid = 'dummy'13901391    // Generate RS256 key pair1392    const keyPair = await crypto.subtle.generateKey(1393      {1394        name: 'RSASSA-PKCS1-v1_5',1395        modulusLength: 2048,1396        publicExponent: new Uint8Array([1, 0, 1]),1397        hash: 'SHA-256',1398      },1399      true,1400      ['sign', 'verify']1401    )14021403    // Create JWT with RS2561404    const header = { alg: 'RS256', typ: 'JWT', kid }1405    const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1406    const encodedHeader = encode(header)1407    const encodedPayload = encode(payload)1408    const signingInput = `${encodedHeader}.${encodedPayload}`14091410    const signatureBuffer = await signing(1411      keyPair.privateKey,1412      'RS256',1413      utf8Encoder.encode(signingInput)1414    )1415    const signature = encodeBase64Url(signatureBuffer)14161417    const token = `${encodedHeader}.${encodedPayload}.${signature}`14181419    const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)1420    const keyWithAlg = {1421      ...jwk,1422      kid,1423      use: 'sig',1424      alg: 'RS256',1425    }14261427    const keys = [keyWithAlg]14281429    // RS256 is in the whitelist1430    const result = await verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256', 'ES256'] })1431    expect(result).toEqual(payload)1432  })14331434  // Note: Tests for "whitelist not specified" and "empty whitelist" were removed1435  // because allowedAlgorithms is now required (not optional).1436  // This is a breaking change that enforces explicit algorithm specification for security.14371438  it('Should reject symmetric algorithm (HS256) in JWT header', async () => {1439    // This test verifies that symmetric algorithms are rejected even when1440    // using verifyWithJwks with asymmetric algorithm whitelist.1441    // Note: HS256 cannot be added to allowedAlgorithms due to type constraints (AsymmetricAlgorithm[])1442    const payload = { message: 'hello world' }1443    const secret = 'secret'1444    const kid = 'dummy'14451446    // Create JWT with HS2561447    const header = { alg: 'HS256', typ: 'JWT', kid }1448    const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1449    const encodedHeader = encode(header)1450    const encodedPayload = encode(payload)1451    const signingInput = `${encodedHeader}.${encodedPayload}`14521453    const signatureBuffer = await signing(secret, 'HS256', utf8Encoder.encode(signingInput))1454    const signature = encodeBase64Url(signatureBuffer)14551456    const token = `${encodedHeader}.${encodedPayload}.${signature}`14571458    const keys = [1459      {1460        kty: 'oct',1461        kid,1462        k: encodeBase64Url(utf8Encoder.encode(secret).buffer),1463        use: 'sig',1464        alg: 'HS256',1465      },1466    ]14671468    // HS256 in JWT header should be rejected as symmetric algorithm1469    // (symmetric algorithm check happens before allowedAlgorithms check)1470    await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })).rejects.toThrow(1471      JwtSymmetricAlgorithmNotAllowed1472    )1473  })1474})14751476describe('verifyWithJwks key handling', () => {1477  it('Should not mutate provided keys when JWKS is fetched repeatedly', async () => {1478    const localKeys: HonoJsonWebKey[] = [1479      {1480        kty: 'RSA',1481        kid: 'local-key',1482        alg: 'RS256',1483        e: 'AQAB',1484        n: 'sXchAZo4YqB7f1_g8U9RVcdpShUMHbOWcZHhGXLiCFYI8aAizI0s5momkMumZ5qX6Ch12yvDqOiiMHDLecxB2S7RMyCV2wAPOQgpdnXl16rDpD6PEw24kTx5cDIeEJD7BqXc9Ejo4kKDAdAm8YGtS-wGGyRyvE4s46HoPazTA7k',1485        use: 'sig',1486      },1487    ]14881489    const originalKeys = structuredClone(localKeys)1490    const originalFetch = globalThis.fetch1491    const header = Buffer.from(1492      JSON.stringify({ alg: 'RS256', typ: 'JWT', kid: 'unknown-key' })1493    ).toString('base64url')1494    const payload = Buffer.from(JSON.stringify({})).toString('base64url')1495    const token = `${header}.${payload}.x`14961497    try {1498      globalThis.fetch = (async () => {1499        return new Response(1500          JSON.stringify({1501            keys: [1502              { ...localKeys[0], kid: 'remote-key' },1503              { ...localKeys[0], kid: 'remote-key' },1504            ],1505          }),1506          { status: 200, headers: { 'content-type': 'application/json' } }1507        )1508      }) as typeof globalThis.fetch15091510      await expect(1511        verifyWithJwks(token, {1512          keys: localKeys,1513          jwks_uri: 'https://example.invalid/.well-known/jwks.json',1514          allowedAlgorithms: ['RS256'],1515        })1516      ).rejects.toThrow(JwtTokenInvalid)15171518      await expect(1519        verifyWithJwks(token, {1520          keys: localKeys,1521          jwks_uri: 'https://example.invalid/.well-known/jwks.json',1522          allowedAlgorithms: ['RS256'],1523        })1524      ).rejects.toThrow(JwtTokenInvalid)1525    } finally {1526      globalThis.fetch = originalFetch1527    }15281529    expect(localKeys).toEqual(originalKeys)1530  })1531})15321533async function exportPEMPrivateKey(key: CryptoKey): Promise<string> {1534  const exported = await crypto.subtle.exportKey('pkcs8', key)1535  const pem = `-----BEGIN PRIVATE KEY-----\n${encodeBase64(exported)}\n-----END PRIVATE KEY-----`1536  return pem1537}15381539async function exportPEMPublicKey(key: CryptoKey): Promise<string> {1540  const exported = await crypto.subtle.exportKey('spki', key)1541  const pem = `-----BEGIN PUBLIC KEY-----\n${encodeBase64(exported)}\n-----END PUBLIC KEY-----`1542  return pem1543}15441545async function exportJWK(key: CryptoKey): Promise<JsonWebKey> {1546  return await crypto.subtle.exportKey('jwk', key)1547}15481549async function generateRSAKey(hash: string): Promise<CryptoKeyPair> {1550  return await crypto.subtle.generateKey(1551    {1552      hash,1553      modulusLength: 2048,1554      publicExponent: new Uint8Array([1, 0, 1]),1555      name: 'RSASSA-PKCS1-v1_5',1556    },1557    true,1558    ['sign', 'verify']1559  )1560}15611562async function generateRSAPSSKey(hash: string): Promise<CryptoKeyPair> {1563  return await crypto.subtle.generateKey(1564    {1565      hash,1566      modulusLength: 2048,1567      publicExponent: new Uint8Array([1, 0, 1]),1568      name: 'RSA-PSS',1569    },1570    true,1571    ['sign', 'verify']1572  )1573}15741575async function generateECDSAKey(namedCurve: string): Promise<CryptoKeyPair> {1576  return await crypto.subtle.generateKey(1577    {1578      name: 'ECDSA',1579      namedCurve,1580    },1581    true,1582    ['sign', 'verify']1583  )1584}15851586async function generateEd25519Key(): Promise<CryptoKeyPair> {1587  return await crypto.subtle.generateKey(1588    {1589      name: 'Ed25519',1590      namedCurve: 'Ed25519',1591    },1592    true,1593    ['sign', 'verify']1594  )1595}15961597describe('Security: Algorithm Confusion Attack Prevention', () => {1598  it('Should throw JwtAlgorithmRequired error when alg is not specified in verify()', async () => {1599    const payload = { message: 'hello world' }1600    const secret = 'a-secret'1601    const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)16021603    let err: JwtAlgorithmRequired | undefined1604    let authorized1605    try {1606      // @ts-expect-error - intentionally testing without alg parameter1607      authorized = await JWT.verify(tok, secret)1608    } catch (e) {1609      err = e as JwtAlgorithmRequired1610    }1611    expect(err).toBeInstanceOf(JwtAlgorithmRequired)1612    expect(err?.message).toBe('JWT verification requires "alg" option to be specified')1613    expect(authorized).toBeUndefined()1614  })16151616  it('Should throw JwtAlgorithmRequired error when alg is undefined in options object', async () => {1617    const payload = { message: 'hello world' }1618    const secret = 'a-secret'1619    const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)16201621    let err: JwtAlgorithmRequired | undefined1622    let authorized1623    try {1624      // @ts-expect-error - intentionally testing with undefined alg1625      authorized = await JWT.verify(tok, secret, { alg: undefined })1626    } catch (e) {1627      err = e as JwtAlgorithmRequired1628    }1629    expect(err).toBeInstanceOf(JwtAlgorithmRequired)1630    expect(authorized).toBeUndefined()1631  })16321633  it('Should prevent algorithm confusion attack (RS256 token verified with HS256 using public key)', async () => {1634    // Generate RSA key pair1635    const keyPair = await crypto.subtle.generateKey(1636      {1637        name: 'RSASSA-PKCS1-v1_5',1638        modulusLength: 2048,1639        publicExponent: new Uint8Array([1, 0, 1]),1640        hash: 'SHA-256',1641      },1642      true,1643      ['sign', 'verify']1644    )16451646    const payload = { message: 'hello world' }16471648    // Sign token with RS256 using private key1649    const tok = await JWT.sign(payload, keyPair.privateKey, AlgorithmTypes.RS256)16501651    // Verify should succeed with RS256 and public key1652    const verified = await JWT.verify(tok, keyPair.publicKey, AlgorithmTypes.RS256)1653    expect(verified).toEqual(payload)16541655    // Attempting to verify with HS256 using the public key should fail with algorithm mismatch1656    // This simulates the algorithm confusion attack scenario1657    let err: Error | undefined1658    let maliciousResult1659    try {1660      maliciousResult = await JWT.verify(tok, keyPair.publicKey, AlgorithmTypes.HS256)1661    } catch (e) {1662      err = e as Error1663    }1664    // The verification should fail because the header.alg (RS256) doesn't match options.alg (HS256)1665    expect(maliciousResult).toBeUndefined()1666    expect(err).toBeInstanceOf(JwtAlgorithmMismatch)1667  })16681669  it('Should throw JwtAlgorithmMismatch when header.alg does not match options.alg', async () => {1670    const payload = { message: 'hello world' }1671    const secret = 'a-secret'16721673    // Sign with HS5121674    const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS512)16751676    // Try to verify with HS256 (wrong algorithm)1677    let err: Error | undefined1678    let result1679    try {1680      result = await JWT.verify(tok, secret, AlgorithmTypes.HS256)1681    } catch (e) {1682      err = e as Error1683    }16841685    expect(result).toBeUndefined()1686    expect(err).toBeInstanceOf(JwtAlgorithmMismatch)1687  })16881689  it('Should require explicit alg specification to prevent default fallback attack', async () => {1690    const payload = { message: 'hello world' }1691    const secret = 'a-secret'16921693    // Create a token with HS2561694    const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)16951696    // Verify with explicit HS256 should work1697    const verified = await JWT.verify(tok, secret, AlgorithmTypes.HS256)1698    expect(verified).toEqual(payload)16991700    // Verify without alg should throw error (no default fallback)1701    let err: Error | undefined1702    try {1703      // @ts-expect-error - intentionally testing without alg parameter1704      await JWT.verify(tok, secret)1705    } catch (e) {1706      err = e as Error1707    }1708    expect(err).toBeInstanceOf(JwtAlgorithmRequired)1709  })1710})17111712describe('JWT decode token format validation', () => {1713  it('decode should throw JwtTokenInvalid for token with 2 parts', () => {1714    const malformed = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8ifQ'1715    expect(() => JWT.decode(malformed)).toThrow(JwtTokenInvalid)1716  })17171718  it('decode should throw JwtTokenInvalid for token with 1 part', () => {1719    expect(() => JWT.decode('eyJhbGciOiJIUzI1NiJ9')).toThrow(JwtTokenInvalid)1720  })17211722  it('decode should throw JwtTokenInvalid for token with 4 parts', () => {1723    const fourParts = 'a.b.c.d'1724    expect(() => JWT.decode(fourParts)).toThrow(JwtTokenInvalid)1725  })17261727  it('decode should throw JwtTokenInvalid for empty string', () => {1728    expect(() => JWT.decode('')).toThrow(JwtTokenInvalid)1729  })17301731  it('decodeHeader should throw JwtTokenInvalid for token with 2 parts', () => {1732    const malformed = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8ifQ'1733    expect(() => JWT.decodeHeader(malformed)).toThrow(JwtTokenInvalid)1734  })17351736  it('decodeHeader should throw JwtTokenInvalid for empty string', () => {1737    expect(() => JWT.decodeHeader('')).toThrow(JwtTokenInvalid)1738  })17391740  it('decode should work for valid 3-part token', async () => {1741    const secret = 'a-secret'1742    const tok = await JWT.sign({ message: 'hello' }, secret, AlgorithmTypes.HS256)1743    const decoded = JWT.decode(tok)1744    expect(decoded.header.alg).toBe('HS256')1745    expect(decoded.payload).toEqual({ message: 'hello' })1746  })17471748  it('decodeHeader should work for valid 3-part token', async () => {1749    const secret = 'a-secret'1750    const tok = await JWT.sign({ message: 'hello' }, secret, AlgorithmTypes.HS256)1751    const header = JWT.decodeHeader(tok)1752    expect(header.alg).toBe('HS256')1753    expect(header.typ).toBe('JWT')1754  })1755})17561757describe('PEM parsing', async () => {1758  const keyPair = await crypto.subtle.generateKey(1759    {1760      name: 'Ed25519',1761    },1762    true,1763    ['sign', 'verify']1764  )17651766  const exported = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey)1767  const base64Key = Buffer.from(exported).toString('base64')1768  const privateKey = `-----BEGIN PRIVATE KEY-----\n${base64Key}\n-----END PRIVATE KEY-----`17691770  it('should sign & verify with a normal private PEM key', async () => {1771    const payload = { sub: '123' }17721773    const token = await JWT.sign(payload, privateKey, 'EdDSA')1774    const verified = await JWT.verify(token, privateKey, 'EdDSA')17751776    expect(verified).toEqual(payload)1777  })17781779  it('should sign & verify with a single-line private PEM key', async () => {1780    const singleLinePrivateKey = privateKey.replace(/\n/g, '')1781    const payload = { sub: '123' }17821783    const token = await JWT.sign(payload, singleLinePrivateKey, 'EdDSA')1784    const verified = await JWT.verify(token, privateKey, 'EdDSA')17851786    expect(verified).toEqual(payload)1787  })1788})