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
Provenance
- Commit
3ed40d5- Tree
0b03de7- Author
Minghe <h.minghe@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
128970e
12 files changed+555 added−61 removed
modified:src/middleware/basic-auth/index.ts+1 added-1 removed
12344567871 unmodified linesimport type { Context } from '@/context'import type { Next } from '@/hono'import { timingSafeEqual } from '@/utils/buffer'import { decodeBase64 } from '@/utils/crypto'import { decodeBase64 } from '@/utils/encode'
const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/const USER_PASS_REGEXP = /^([^:]*):(.*)$/
71 unmodified linesadded:src/middleware/jwt/index.test.ts+66 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import { Hono } from '@/hono'import { jwt } from '@/middleware/jwt'
describe('Jwt Auth by Middleware', () => { const crypto = global.crypto beforeAll(() => { global.crypto = require('crypto').webcrypto }) afterAll(() => { global.crypto = crypto })
const app = new Hono()
app.use( '/auth/*', jwt({ secret: 'a-secret' }) )
app.use( '/auth-unicode/*', jwt({ secret: 'a-secret'}) )
app.get('/auth/*', () => new Response('auth')) app.get('/auth-unicode/*', () => new Response('auth'))
it('Should not authorize', async () => { const req = new Request('http://localhost/auth/a') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(401) expect(await res.text()).toBe('Unauthorized') })
it('Should authorize', async () => { const credential = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE' const req = new Request('http://localhost/auth/a') req.headers.set('Authorization', `Bearer ${credential}`) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth') })
it('Should authorize Unicode', async () => { const credential = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'
const req = new Request('http://localhost/auth-unicode/a') req.headers.set('Authorization', `Basic ${credential}`) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth') })
it('Should authorize Unicode', async () => { const invalidToken = 'ssyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'
const req = new Request('http://localhost/auth-unicode/a') req.headers.set('Authorization', `Basic ${invalidToken}`) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(401) })})added:src/middleware/jwt/index.ts+52 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152import type { Context } from '@/context'import type { Next } from '@/hono'import { Jwt } from '@/utils/jwt'
export const jwt = (options: { secret: string; alg?: string }) => { if (!options) { throw new Error('JWT auth middleware requires options for "secret') }
return async (ctx: Context, next: Next) => { const credentials = ctx.req.headers.get('Authorization') if (!credentials) { ctx.res = new Response('Unauthorized', { status: 401, headers: { 'WWW-Authenticate': 'Basic ${options.secret}', }, }) return }
const parts = credentials.split(/\s+/) if (parts.length !== 2) { ctx.res = new Response('Unauthorized', { status: 401, headers: { 'WWW-Authenticate': 'Basic ${options.secret}', }, }) return }
let authorized = false let msg = '' try { authorized = await Jwt.verify(parts[1], options.secret) } catch (e) { msg = `${e}` } if (authorized) { return next() } ctx.res = new Response('Unauthorized', { status: 401, statusText: msg, headers: { 'WWW-Authenticate': 'Bearer ${options.secret}', }, }) return }}added:src/middleware/jwt/README.md+23 added
1234567891011121314151617181920212223# JWT Middleware
## Usage
```jsimport { Hono } from 'hono'import { jwt } from 'hono/jwt'
const app = new Hono()
app.use( '/auth/*', jwt({ secret: 'it-is-very-secret' }))
app.get('/auth/page', (c) => { return c.text('You are authorized')})
app.fire()```added:src/utils/jwt/index.ts+1 added
1export * as Jwt from './jwt'added:src/utils/jwt/jwt.test.ts+103 added
1+import * as JWT from './jwt'2+import { AlgorithmTypes, JwtTokenSignatureMismatched } from './types'3+4+describe('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)12+13+ expect(await JWT.verify(tok, secret, AlgorithmTypes.HS256)).toBe(true)14+15+ expect(JWT.decode(tok)).toEqual({16+ header: {17+ alg: 'HS256',18+ typ: 'JWT',19+ },20+ payload: {21+ message: 'hello world',22+ },23+ })24+ })25+26+ 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)33+34+ 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+ })44+45+ 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)52+53+ expect(await JWT.verify(tok, secret, AlgorithmTypes.HS512)).toBe(true)54+55+ expect(JWT.decode(tok)).toEqual({56+ header: {57+ alg: 'HS512',58+ typ: 'JWT',59+ },60+ payload: {61+ message: 'hello world',62+ },63+ })64+ })65+66+ 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)73+74+ 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+ })84+85+ 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)92+93+ 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
1+import {2+ utf8ToUint8Array,3+ encodeBase64URL,4+ arrayBufferToBase64URL,5+ decodeBase64URL,6+} from '../../utils/encode'7+import { AlgorithmTypes } from './types'8+import {9+ JwtTokenInvalid,10+ JwtTokenNotBefore,11+ JwtTokenExpired,12+ JwtTokenSignatureMismatched,13+ JwtAlorithmNotImplemented,14+} from './types'15+16+interface AlgorithmParams {17+ name: string18+ namedCurve?: string19+ hash?: {20+ name: string21+ }22+}23+24+enum CryptoKeyFormat {25+ RAW = 'raw',26+ PKCS8 = 'pkcs8',27+ SPKI = 'spki',28+ JWK = 'jwk',29+}30+31+enum 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+}41+42+const 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+}69+70+const 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+}84+85+export 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' }))92+93+ const partialToken = `${encodedHeader}.${encodedPayload}`94+95+ const signature: string = await arrayBufferToBase64URL(await signing(partialToken, secret, alg))96+97+ return `${partialToken}.${signature}`98+}99+100+export 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+ }109+110+ 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+ }117+118+ 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+ }124+125+ return true126+}127+128+// eslint-disable-next-line129+export 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
1234567891011121314151617181920212223242526272829303132333435363738394041export class JwtAlorithmNotImplemented extends Error { constructor(token: string) { super(`invalid JWT token: ${token}`) this.name = 'JwtAlorithmNotImplemented' }}
export class JwtTokenInvalid extends Error { constructor(token: string) { super(`invalid JWT token: ${token}`) this.name = 'JwtTokenInvalid' }}
export class JwtTokenNotBefore extends Error { constructor(token: string) { super(`token (${token}) is being used before it's valid`) this.name = 'JwtTokenNotBefore' }}
export class JwtTokenExpired extends Error { constructor(token: string) { super(`token (${token}) expired`) this.name = 'JwtTokenExpired' }}
export class JwtTokenSignatureMismatched extends Error { constructor(token: string) { super(`token(${token}) signature mismatched`) this.name = 'JwtTokenSignatureMismatched' }}
export enum AlgorithmTypes { HS256 = 'HS256', HS384 = 'HS384', HS512 = 'HS512',}
modified:src/utils/crypto.test.ts+1 added-21 removed
1-import { sha256, sha1, decodeBase64, encodeBase64 } from '@/utils/crypto'1+import { sha256, sha1 } from '@/utils/crypto'2 3 describe('crypto', () => {4 it('sha256', async () => {5 expect(await sha256('hono')).toBe(9 unmodified lines15 expect(await sha1('hono')).toBe('28c7e86f5732391917876b45c06c626c04d77f39')16 expect(await sha1('炎')).toBe('d56e09ae2421b2b8a0b5ee5fdceaed663c8c9472')17 expect(await sha1('abcdedf')).not.toBe('abcdef')18 })19-20- 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- })29-30- 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 lines39 console.error(`If you want to create hash ${algorithm.name}, polyfill "crypto" module.`)40 throw e41 }42 }43-44-export 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 {}53-54- 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-}62-63-export 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 {}73-74- 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
1+import { decodeBase64, encodeBase64, encodeBase64URL, decodeBase64URL } from '@/utils/encode'2+3+describe('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+ })14+15+ 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+ })36+37+ 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
1+export 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 {}10+11+ 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+}19+20+export 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 {}30+31+ 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+}39+40+export const encodeBase64URL = (str: string): string => {41+ return encodeBase64(str).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')42+}43+44+export 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+ }55+56+ return decodeBase64(pad(str).replace(/-/g, '+').replace('_', '/'))57+}58+59+export const utf8ToUint8Array = (str: string): Uint8Array => {60+ const encoder = new TextEncoder()61+ return encoder.encode(str)62+}63+64+export const arrayBufferToBase64 = async (buf: ArrayBuffer): Promise<string> => {65+ if (typeof btoa === 'function') {66+ return btoa(String.fromCharCode(...new Uint8Array(buf)))67+ }68+69+ try {70+ const { Buffer } = await import('buffer')71+ return Buffer.from(String.fromCharCode(...new Uint8Array(buf))).toString('base64')72+ } catch (e) {}73+}74+75+export const arrayBufferToBase64URL = async (buf: ArrayBuffer) => {76+ return (await arrayBufferToBase64(buf)).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')77+}78+