Skip to content
Myr

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

4 files+98 added−125 removed

modified:src/middleware/basic-auth/index.ts+2 added-2 removed
modified:src/utils/jwt/jwt.ts+24 added-17 removed
1import {2 utf8ToUint8Array,3 encodeBase64URL,4 arrayBufferToBase64URL,5 decodeBase64URL,6} from '../../utils/encode'1import { encodeBase64Url, decodeBase64Url } from '../../utils/encode'2import { AlgorithmTypes } from './types'3import {4 JwtTokenInvalid,5 JwtTokenNotBefore,
27 unmodified lines
33 WrapKey = 'wrapKey',34 UnwrapKey = 'unwrapKey',35}3637const utf8Encoder = new TextEncoder()38const utf8Decoder = new TextDecoder()3940const encodeJwtPart = (part: unknown): string =>41 encodeBase64Url(utf8Encoder.encode(JSON.stringify(part))).replace(/=/g, '')42const encodeSignaturePart = (buf: ArrayBufferLike): string => encodeBase64Url(buf).replace(/=/g, '')4344const decodeJwtPart = (part: string): unknown =>45 JSON.parse(utf8Decoder.decode(decodeBase64Url(part)))4647const param = (name: AlgorithmTypes): AlgorithmParams => {48 switch (name.toUpperCase()) {49 case 'HS256':50 return {
29 unmodified lines
80 if (!crypto.subtle || !crypto.subtle.importKey) {81 throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')82 }8384 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}9495export 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' })102103 const partialToken = `${encodedHeader}.${encodedPayload}`10499 const signature: string = await arrayBufferToBase64URL(await signing(partialToken, secret, alg))105 const signaturePart = await signing(partialToken, secret, alg)106 const signature = encodeSignaturePart(signaturePart)107108 return `${partialToken}.${signature}`109}110
14 unmodified lines
125 if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) {126 throw new JwtTokenExpired(token)127 }128122 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 }135136 return true
2 unmodified lines
139// eslint-disable-next-line140export 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 lines
modified:src/utils/encode.test.ts+54 added-63 removed
modified:src/utils/encode.ts+18 added-43 removed