Skip to content
Myr

feat(jwt): jwt middleware (#169)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Minghe · committed by GitHub · parent 128970e · Browse files · 12 files+555 added−61 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

12 files+555 added−61 removed

  • tests:+218 added−21 removed
  • other:+337 added−40 removed

12 files+555 added−61 removed

modified:src/middleware/basic-auth/index.ts+1 added-1 removed
added:src/middleware/jwt/index.test.ts+66 added
added:src/middleware/jwt/index.ts+52 added
added:src/middleware/jwt/README.md+23 added
added:src/utils/jwt/index.ts+1 added
added:src/utils/jwt/jwt.test.ts+103 added
1import * as JWT from './jwt'2import { AlgorithmTypes, JwtTokenSignatureMismatched } from './types'34describe('JWT', () => {5 it('HS256 sign & verify & decode', async () => {6 const payload = { message: 'hello world' }7 const secret = 'a-secret'8 const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)9 const expected =10 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'11 expect(tok).toEqual(expected)1213 expect(await JWT.verify(tok, secret, AlgorithmTypes.HS256)).toBe(true)1415 expect(JWT.decode(tok)).toEqual({16 header: {17 alg: 'HS256',18 typ: 'JWT',19 },20 payload: {21 message: 'hello world',22 },23 })24 })2526 it('HS256 sign & verify', async () => {27 const payload = { message: 'hello world' }28 const secret = 'a-secret'29 const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)30 const expected =31 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'32 expect(tok).toEqual(expected)3334 let err = null35 let authorized = false36 try {37 authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)38 } catch (e) {39 err = e40 }41 expect(authorized).toBe(false)42 expect(err instanceof JwtTokenSignatureMismatched).toBe(true)43 })4445 it('HS512 sign & verify & decode', async () => {46 const payload = { message: 'hello world' }47 const secret = 'a-secret'48 const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS512)49 const expected =50 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.RqVLgExB_GXF1-9T-k4V4HjFmiuQKTEjVSiZd-YL0WERIlywZ7PfzAuTZSJU4gg8cscGamQa030cieEWrYcywg'51 expect(tok).toEqual(expected)5253 expect(await JWT.verify(tok, secret, AlgorithmTypes.HS512)).toBe(true)5455 expect(JWT.decode(tok)).toEqual({56 header: {57 alg: 'HS512',58 typ: 'JWT',59 },60 payload: {61 message: 'hello world',62 },63 })64 })6566 it('HS512 sign & verify', async () => {67 const payload = { message: 'hello world' }68 const secret = 'a-secret'69 const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS512)70 const expected =71 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.RqVLgExB_GXF1-9T-k4V4HjFmiuQKTEjVSiZd-YL0WERIlywZ7PfzAuTZSJU4gg8cscGamQa030cieEWrYcywg'72 expect(tok).toEqual(expected)7374 let err = null75 let authorized = false76 try {77 authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)78 } catch (e) {79 err = e80 }81 expect(authorized).toBe(false)82 expect(err instanceof JwtTokenSignatureMismatched).toBe(true)83 })8485 it('HS384 sign & verify', async () => {86 const payload = { message: 'hello world' }87 const secret = 'a-secret%你好'88 const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS384)89 const expected =90 'eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.C1Br1183Oy6O7th4NDCOaI9WB75i3FMCuYlv1tCL9HggsU89T-SNutghwhJykD3r'91 expect(tok).toEqual(expected)9293 let err = null94 let authorized = false95 try {96 authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)97 } catch (e) {98 err = e99 }100 expect(authorized).toBe(false)101 expect(err instanceof JwtTokenSignatureMismatched).toBe(true)102 })103})
added:src/utils/jwt/jwt.ts+141 added
1import {2 utf8ToUint8Array,3 encodeBase64URL,4 arrayBufferToBase64URL,5 decodeBase64URL,6} from '../../utils/encode'7import { AlgorithmTypes } from './types'8import {9 JwtTokenInvalid,10 JwtTokenNotBefore,11 JwtTokenExpired,12 JwtTokenSignatureMismatched,13 JwtAlorithmNotImplemented,14} from './types'1516interface AlgorithmParams {17 name: string18 namedCurve?: string19 hash?: {20 name: string21 }22}2324enum CryptoKeyFormat {25 RAW = 'raw',26 PKCS8 = 'pkcs8',27 SPKI = 'spki',28 JWK = 'jwk',29}3031enum CryptoKeyUsage {32 Ecrypt = 'encrypt',33 Decrypt = 'decrypt',34 Sign = 'sign',35 Verify = 'verify',36 Deriverkey = 'deriveKey',37 DeriveBits = 'deriveBits',38 WrapKey = 'wrapKey',39 UnwrapKey = 'unwrapKey',40}4142const param = (name: AlgorithmTypes): AlgorithmParams => {43 switch (name.toUpperCase()) {44 case 'HS256':45 return {46 name: 'HMAC',47 hash: {48 name: 'SHA-256',49 },50 }51 case 'HS384':52 return {53 name: 'HMAC',54 hash: {55 name: 'SHA-384',56 },57 }58 case 'HS512':59 return {60 name: 'HMAC',61 hash: {62 name: 'SHA-512',63 },64 }65 default:66 throw new JwtAlorithmNotImplemented(name)67 }68}6970const signing = async (71 data: string,72 secret: string,73 alg: AlgorithmTypes = AlgorithmTypes.HS25674): Promise<ArrayBuffer> => {75 const cryptoKey = await crypto.subtle.importKey(76 CryptoKeyFormat.RAW,77 utf8ToUint8Array(secret),78 param(alg),79 false,80 [CryptoKeyUsage.Sign]81 )82 return await crypto.subtle.sign(param(alg), cryptoKey, utf8ToUint8Array(data))83}8485export const sign = async (86 payload: unknown,87 secret: string,88 alg: AlgorithmTypes = AlgorithmTypes.HS25689): Promise<string> => {90 const encodedPayload = await encodeBase64URL(JSON.stringify(payload))91 const encodedHeader = await encodeBase64URL(JSON.stringify({ alg, typ: 'JWT' }))9293 const partialToken = `${encodedHeader}.${encodedPayload}`9495 const signature: string = await arrayBufferToBase64URL(await signing(partialToken, secret, alg))9697 return `${partialToken}.${signature}`98}99100export const verify = async (101 token: string,102 secret: string,103 alg: AlgorithmTypes = AlgorithmTypes.HS256104): Promise<boolean> => {105 const tokenParts = token.split('.')106 if (tokenParts.length !== 3) {107 throw new JwtTokenInvalid(token)108 }109110 const { payload } = decode(token)111 if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) {112 throw new JwtTokenNotBefore(token)113 }114 if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) {115 throw new JwtTokenExpired(token)116 }117118 const signature: string = await arrayBufferToBase64URL(119 await signing(tokenParts.slice(0, 2).join('.'), secret, alg)120 )121 if (signature !== tokenParts[2]) {122 throw new JwtTokenSignatureMismatched(token)123 }124125 return true126}127128// eslint-disable-next-line129export const decode = (token: string): { header: any; payload: any } => {130 try {131 const [h, p] = token.split('.')132 const header = JSON.parse(decodeBase64URL(h))133 const payload = JSON.parse(decodeBase64URL(p))134 return {135 header,136 payload,137 }138 } catch (e) {139 throw new JwtTokenInvalid(token)140 }141}
added:src/utils/jwt/types.ts+41 added
modified:src/utils/crypto.test.ts+1 added-21 removed
1import { sha256, sha1, decodeBase64, encodeBase64 } from '@/utils/crypto'1import { sha256, sha1 } from '@/utils/crypto'23describe('crypto', () => {4 it('sha256', async () => {5 expect(await sha256('hono')).toBe(
9 unmodified lines
15 expect(await sha1('hono')).toBe('28c7e86f5732391917876b45c06c626c04d77f39')16 expect(await sha1('炎')).toBe('d56e09ae2421b2b8a0b5ee5fdceaed663c8c9472')17 expect(await sha1('abcdedf')).not.toBe('abcdef')18 })1920 it('encodeBase64', () => {21 expect(encodeBase64('hooooooooo')).toBe('aG9vb29vb29vbw==')22 expect(encodeBase64('炎')).toBe('54KO')23 expect(encodeBase64('abcdef')).not.toBe('abcdedf')24 expect(encodeBase64('')).toBe('')25 expect(() => {26 encodeBase64(null)27 }).toThrow(TypeError)28 })2930 it('decodeBase64', async () => {31 expect(decodeBase64('aG9vb29vb29vbw==')).toBe('hooooooooo')32 expect(decodeBase64('54KO')).toBe('炎')33 expect(decodeBase64('abcdedf')).not.toBe('abcdef')34 expect(decodeBase64('')).toBe('')35 expect(() => {36 decodeBase64(null)37 }).toThrowError(TypeError)38 })19})
modified:src/utils/crypto.ts-39 removed
38 unmodified lines
39 console.error(`If you want to create hash ${algorithm.name}, polyfill "crypto" module.`)40 throw e41 }42}4344export const encodeBase64 = (str: string): string => {45 if (str === null) {46 throw new TypeError('1st argument of "encodeBase64" should not be null.')47 }48 try {49 const encoder = new TextEncoder()50 const bytes = encoder.encode(str)51 return btoa(String.fromCharCode(...bytes))52 } catch {}5354 try {55 const { Buffer } = require('buffer')56 return Buffer.from(str).toString('base64')57 } catch (e) {58 console.error('If you want to do "encodeBase64", polyfill "buffer" module.')59 throw e60 }61}6263export const decodeBase64 = (str: string): string => {64 if (str === null) {65 throw new TypeError('1st argument of "decodeBase64" should not be null.')66 }67 try {68 const text = atob(str)69 const bytes = new Uint8Array(text.split('').map((c) => c.charCodeAt(0)))70 const decoder = new TextDecoder()71 return decoder.decode(bytes)72 } catch {}7374 try {75 const { Buffer } = require('buffer')76 return Buffer.from(str, 'base64').toString()77 } catch (e) {78 console.error('If you want to do "decodeBase64", polyfill "buffer" module.')79 throw e80 }81}
added:src/utils/encode.test.ts+48 added
1import { decodeBase64, encodeBase64, encodeBase64URL, decodeBase64URL } from '@/utils/encode'23describe('encode', () => {4 describe('base64', () => {5 it('encodeBase64', () => {6 expect(encodeBase64('hooooooooo')).toBe('aG9vb29vb29vbw==')7 expect(encodeBase64('炎')).toBe('54KO')8 expect(encodeBase64('abcdef')).not.toBe('abcdedf')9 expect(encodeBase64('')).toBe('')10 expect(() => {11 encodeBase64(null)12 }).toThrow(TypeError)13 })1415 it('decodeBase64', async () => {16 expect(decodeBase64('aG9vb29vb29vbw==')).toBe('hooooooooo')17 expect(decodeBase64('54KO')).toBe('炎')18 expect(decodeBase64('abcdedf')).not.toBe('abcdef')19 expect(decodeBase64('')).toBe('')20 expect(() => {21 decodeBase64(null)22 }).toThrowError(TypeError)23 })24 })25 describe('base64url', () => {26 it('encodeBase64URL', () => {27 expect(encodeBase64URL('hooooooooo')).toBe('aG9vb29vb29vbw')28 expect(encodeBase64URL('http://github.com/honojs/hono')).toBe('aHR0cDovL2dpdGh1Yi5jb20vaG9ub2pzL2hvbm8')29 expect(encodeBase64URL('炎')).toBe('54KO')30 expect(encodeBase64URL('abcdef')).not.toBe('abcdedf')31 expect(encodeBase64URL('')).toBe('')32 expect(() => {33 encodeBase64URL(null)34 }).toThrow(TypeError)35 })3637 it('decodeBase64URL', async () => {38 expect(decodeBase64URL('aG9vb29vb29vbw')).toBe('hooooooooo')39 expect(decodeBase64URL('aHR0cDovL2dpdGh1Yi5jb20vaG9ub2pzL2hvbm8')).toBe('http://github.com/honojs/hono')40 expect(decodeBase64URL('54KO')).toBe('炎')41 expect(decodeBase64URL('abcdedf')).not.toBe('abcdef')42 expect(decodeBase64URL('')).toBe('')43 expect(() => {44 decodeBase64URL(null)45 }).toThrowError(TypeError)46 })47 })48})
added:src/utils/encode.ts+78 added
1export const encodeBase64 = (str: string): string => {2 if (str === null) {3 throw new TypeError('1st argument of "encodeBase64" should not be null.')4 }5 try {6 const encoder = new TextEncoder()7 const bytes = encoder.encode(str)8 return btoa(String.fromCharCode(...bytes))9 } catch {}1011 try {12 const { Buffer } = require('buffer')13 return Buffer.from(str).toString('base64')14 } catch (e) {15 console.error('If you want to do "encodeBase64", polyfill "buffer" module.')16 throw e17 }18}1920export const decodeBase64 = (str: string): string => {21 if (str === null) {22 throw new TypeError('1st argument of "decodeBase64" should not be null.')23 }24 try {25 const text = atob(str)26 const bytes = new Uint8Array(text.split('').map((c) => c.charCodeAt(0)))27 const decoder = new TextDecoder()28 return decoder.decode(bytes)29 } catch {}3031 try {32 const { Buffer } = require('buffer')33 return Buffer.from(str, 'base64').toString()34 } catch (e) {35 console.error('If you want to do "decodeBase64", polyfill "buffer" module.')36 throw e37 }38}3940export const encodeBase64URL = (str: string): string => {41 return encodeBase64(str).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')42}4344export const decodeBase64URL = (str: string): string => {45 const pad = (s: string) => {46 const diff = s.length % 447 if (diff === 2) {48 return `${s}==`49 }50 if (diff === 3) {51 return `${s}=`52 }53 return s54 }5556 return decodeBase64(pad(str).replace(/-/g, '+').replace('_', '/'))57}5859export const utf8ToUint8Array = (str: string): Uint8Array => {60 const encoder = new TextEncoder()61 return encoder.encode(str)62}6364export const arrayBufferToBase64 = async (buf: ArrayBuffer): Promise<string> => {65 if (typeof btoa === 'function') {66 return btoa(String.fromCharCode(...new Uint8Array(buf)))67 }6869 try {70 const { Buffer } = await import('buffer')71 return Buffer.from(String.fromCharCode(...new Uint8Array(buf))).toString('base64')72 } catch (e) {}73}7475export const arrayBufferToBase64URL = async (buf: ArrayBuffer) => {76 return (await arrayBufferToBase64(buf)).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')77}78