refactor: Refactoring base64 logic for JWT (#999)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* allow base64 encode decode RFC 3548 format * refactoring to encode JWT signature part * added test case that already exists * fixed basic-auth middleware to decode base64
authored by Kei Kamikawa · committed by GitHub · parent c0af3d0 · Browse files · 4 files·+98 added−125 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Takumi Akiyama <t.akiym@gmail.com>
Diff stats
4 files+98 added−125 removed
- tests:+54 added−63 removed
- other:+44 added−62 removed
Provenance
- Commit
bbdc64b- Tree
6608729- Author
Kei Kamikawa <Code-Hex@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
c0af3d0
4 files changed+98 added−125 removed
modified:src/middleware/basic-auth/index.ts+2 added-2 removed
4 unmodified lines56789910111213141516161718192046 unmodified lines4 unmodified linesimport { decodeBase64 } from '../../utils/encode'
const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/const USER_PASS_REGEXP = /^([^:]*):(.*)$/
const utf8Decoder = new TextDecoder()const auth = (req: HonoRequest) => { const match = CREDENTIALS_REGEXP.exec(req.headers.get('Authorization') || '') if (!match) { return undefined }
const userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1])) const userPass = USER_PASS_REGEXP.exec(utf8Decoder.decode(decodeBase64(match[1])))
if (!userPass) { return undefined }46 unmodified linesmodified:src/utils/jwt/jwt.ts+24 added-17 removed
1-import {2- utf8ToUint8Array,3- encodeBase64URL,4- arrayBufferToBase64URL,5- decodeBase64URL,6-} from '../../utils/encode'1+import { encodeBase64Url, decodeBase64Url } from '../../utils/encode'2 import { AlgorithmTypes } from './types'3 import {4 JwtTokenInvalid,5 JwtTokenNotBefore,27 unmodified lines33 WrapKey = 'wrapKey',34 UnwrapKey = 'unwrapKey',35 }36 37+const utf8Encoder = new TextEncoder()38+const utf8Decoder = new TextDecoder()39+40+const encodeJwtPart = (part: unknown): string =>41+ encodeBase64Url(utf8Encoder.encode(JSON.stringify(part))).replace(/=/g, '')42+const encodeSignaturePart = (buf: ArrayBufferLike): string => encodeBase64Url(buf).replace(/=/g, '')43+44+const decodeJwtPart = (part: string): unknown =>45+ JSON.parse(utf8Decoder.decode(decodeBase64Url(part)))46+47 const param = (name: AlgorithmTypes): AlgorithmParams => {48 switch (name.toUpperCase()) {49 case 'HS256':50 return {29 unmodified lines80 if (!crypto.subtle || !crypto.subtle.importKey) {81 throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')82 }83 84+ const utf8Encoder = new TextEncoder()85 const cryptoKey = await crypto.subtle.importKey(86 CryptoKeyFormat.RAW,81- utf8ToUint8Array(secret),87+ utf8Encoder.encode(secret),88 param(alg),89 false,90 [CryptoKeyUsage.Sign]91 )86- return await crypto.subtle.sign(param(alg), cryptoKey, utf8ToUint8Array(data))92+ return await crypto.subtle.sign(param(alg), cryptoKey, utf8Encoder.encode(data))93 }94 95 export const sign = async (96 payload: unknown,97 secret: string,98 alg: AlgorithmTypes = AlgorithmTypes.HS25699 ): Promise<string> => {94- const encodedPayload = await encodeBase64URL(JSON.stringify(payload))95- const encodedHeader = await encodeBase64URL(JSON.stringify({ alg, typ: 'JWT' }))100+ const encodedPayload = encodeJwtPart(payload)101+ const encodedHeader = encodeJwtPart({ alg, typ: 'JWT' })102 103 const partialToken = `${encodedHeader}.${encodedPayload}`104 99- const signature: string = await arrayBufferToBase64URL(await signing(partialToken, secret, alg))105+ const signaturePart = await signing(partialToken, secret, alg)106+ const signature = encodeSignaturePart(signaturePart)107 108 return `${partialToken}.${signature}`109 }110 14 unmodified lines125 if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) {126 throw new JwtTokenExpired(token)127 }128 122- const signature: string = await arrayBufferToBase64URL(123- await signing(tokenParts.slice(0, 2).join('.'), secret, alg)124- )125- if (signature !== tokenParts[2]) {129+ const signaturePart = tokenParts.slice(0, 2).join('.')130+ const signature = await signing(signaturePart, secret, alg)131+ const encodedSignature = encodeSignaturePart(signature)132+ if (encodedSignature !== tokenParts[2]) {133 throw new JwtTokenSignatureMismatched(token)134 }135 136 return true2 unmodified lines139 // eslint-disable-next-line140 export const decode = (token: string): { header: any; payload: any } => {141 try {142 const [h, p] = token.split('.')136- const header = JSON.parse(decodeBase64URL(h))137- const payload = JSON.parse(decodeBase64URL(p))143+ const header = decodeJwtPart(h)144+ const payload = decodeJwtPart(p)145 return {146 header,147 payload,148 }4 unmodified linesmodified:src/utils/encode.test.ts+54 added-63 removed
123456782310111213141516171819202145623242526272829303132333435363738394041424344454647789101112131449505152535455565758596061621516171819202122232425266465666768272829303132333435363738394041424344454647484950515253545556575859606162/* eslint-disable @typescript-eslint/ban-ts-comment */import { utf8ToUint8Array, decodeBase64, encodeBase64, encodeBase64URL, decodeBase64URL,} from './encode'import { decodeBase64Url, encodeBase64Url } from './encode'
describe('encode', () => { describe('base64', () => { it('encodeBase64', () => { expect(encodeBase64('hooooooooo')).toBe('aG9vb29vb29vbw==') expect(encodeBase64('炎')).toBe('54KO') expect(encodeBase64('abcdef')).not.toBe('abcdedf') expect(encodeBase64('')).toBe('') expect(() => { // @ts-ignore encodeBase64(null) }).toThrow(TypeError) })const toURLBase64 = (base64String: string): string => base64String.replace(/\+|\//g, (m) => ({ '+': '-', '/': '_' }[m] ?? m))
it('decodeBase64', async () => { expect(decodeBase64('aG9vb29vb29vbw==')).toBe('hooooooooo') expect(decodeBase64('54KO')).toBe('炎') expect(decodeBase64('abcdedf')).not.toBe('abcdef') expect(decodeBase64('')).toBe('') expect(() => { // @ts-ignore decodeBase64(null) }).toThrowError(TypeError) }) }) describe('base64url', () => { it('encodeBase64URL', () => { expect(encodeBase64URL('hooooooooo')).toBe('aG9vb29vb29vbw') expect(encodeBase64URL('http://github.com/honojs/hono')).toBe( 'aHR0cDovL2dpdGh1Yi5jb20vaG9ub2pzL2hvbm8' ) expect(encodeBase64URL('炎')).toBe('54KO') expect(encodeBase64URL('abcdef')).not.toBe('abcdedf') expect(encodeBase64URL('')).toBe('') expect(() => { // @ts-ignore encodeBase64URL(null) }).toThrow(TypeError) })const str2UInt8Array = (s: string): Uint8Array => { const buffer = new Uint8Array(new ArrayBuffer(s.length)) for (let i = 0; i < buffer.byteLength; i++) { buffer[i] = s.charCodeAt(i) } return buffer}
it('decodeBase64URL', async () => { expect(decodeBase64URL('aG9vb29vb29vbw')).toBe('hooooooooo') expect(decodeBase64URL('aHR0cDovL2dpdGh1Yi5jb20vaG9ub2pzL2hvbm8')).toBe( 'http://github.com/honojs/hono' ) expect(decodeBase64URL('54KO')).toBe('炎') expect(decodeBase64URL('abcdedf')).not.toBe('abcdef') expect(decodeBase64URL('')).toBe('') expect(() => { // @ts-ignore decodeBase64URL(null) }).toThrowError(TypeError) }) })describe('base64', () => { const utf8Encoder = new TextEncoder() describe.each([ // basic [utf8Encoder.encode('Hello, 世界'), 'SGVsbG8sIOS4lueVjA=='], [utf8Encoder.encode('炎'), '54KO'], [utf8Encoder.encode('🔥'), '8J+UpQ=='], [ utf8Encoder.encode('http://github.com/honojs/hono'), 'aHR0cDovL2dpdGh1Yi5jb20vaG9ub2pzL2hvbm8=', ],
describe('utf8ToUint8Array', () => { it('should be equal', () => { const k = 'a-secret-key' const arr = utf8ToUint8Array(k) expect(String(arr)).toEqual('97,45,115,101,99,114,101,116,45,107,101,121') // RFC 3548 examples [str2UInt8Array('\x14\xfb\x9c\x03\xd9\x7e'), 'FPucA9l+'], [str2UInt8Array('\x14\xfb\x9c\x03\xd9'), 'FPucA9k='], [str2UInt8Array('\x14\xfb\x9c\x03'), 'FPucAw=='],
// RFC 4648 examples [str2UInt8Array(''), ''], [str2UInt8Array('f'), 'Zg=='], [str2UInt8Array('fo'), 'Zm8='], [str2UInt8Array('foo'), 'Zm9v'], [str2UInt8Array('foob'), 'Zm9vYg=='], [str2UInt8Array('fooba'), 'Zm9vYmE='], [str2UInt8Array('foobar'), 'Zm9vYmFy'],
// Wikipedia examples [str2UInt8Array('sure.'), 'c3VyZS4='], [str2UInt8Array('sure'), 'c3VyZQ=='], [str2UInt8Array('sur'), 'c3Vy'], [str2UInt8Array('su'), 'c3U='], [str2UInt8Array('leasure.'), 'bGVhc3VyZS4='], [str2UInt8Array('easure.'), 'ZWFzdXJlLg=='], [str2UInt8Array('asure.'), 'YXN1cmUu'], [str2UInt8Array('sure.'), 'c3VyZS4='], ])('%s, %s', (stdDecoded, stdEncoded) => { it('encode', () => { const got = encodeBase64Url(stdDecoded) const want = toURLBase64(stdEncoded) expect(got).toStrictEqual(want) }) it('decode', () => { const got = decodeBase64Url(toURLBase64(stdEncoded)) const want = stdDecoded expect(got).toStrictEqual(want) }) })})modified:src/utils/encode.ts+18 added-43 removed
123456712341011121314151617185672021891011121314242526272829303132331516171819202122233536242538394041424344454647484950export const encodeBase64 = (str: string): string => { if (str === null) { throw new TypeError('1st argument of "encodeBase64" should not be null.') } const encoder = new TextEncoder() const bytes = encoder.encode(str) return btoa(String.fromCharCode(...bytes))export const decodeBase64Url = (str: string): Uint8Array => { return decodeBase64(str.replace(/_|-/g, (m) => ({ _: '/', '-': '+' }[m] ?? m)))}
export const decodeBase64 = (str: string): string => { if (str === null) { throw new TypeError('1st argument of "decodeBase64" should not be null.') } const text = atob(str) const bytes = new Uint8Array(text.split('').map((c) => c.charCodeAt(0))) const decoder = new TextDecoder() return decoder.decode(bytes)}export const encodeBase64Url = (buf: ArrayBufferLike): string => encodeBase64(buf).replace(/\/|\+/g, (m) => ({ '/': '_', '+': '-' }[m] ?? m))
export const encodeBase64URL = (str: string): string => { return encodeBase64(str).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')// This approach is written in MDN.// btoa does not support utf-8 characters. So we need a little bit hack.export const encodeBase64 = (buf: ArrayBufferLike): string => { const binary = String.fromCharCode(...new Uint8Array(buf)) return btoa(binary)}
export const decodeBase64URL = (str: string): string => { const pad = (s: string) => { const diff = s.length % 4 if (diff === 2) { return `${s}==` } if (diff === 3) { return `${s}=` } return s// atob does not support utf-8 characters. So we need a little bit hack.export const decodeBase64 = (str: string): Uint8Array => { const binary = atob(str) const bytes = new Uint8Array(new ArrayBuffer(binary.length)) const half = binary.length / 2 for (let i = 0, j = binary.length - 1; i <= half; i++, j--) { bytes[i] = binary.charCodeAt(i) bytes[j] = binary.charCodeAt(j) }
return decodeBase64(pad(str).replace(/-/g, '+').replace('_', '/')) return bytes}
export const utf8ToUint8Array = (str: string): Uint8Array => { const encoder = new TextEncoder() return encoder.encode(str)}
export const arrayBufferToBase64 = async (buf: ArrayBuffer): Promise<string> => { return btoa(String.fromCharCode(...new Uint8Array(buf)))}
export const arrayBufferToBase64URL = async (buf: ArrayBuffer) => { return (await arrayBufferToBase64(buf)).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')}