Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Refresh Token Authentication API #65

Merged
merged 12 commits into from
Feb 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@
"devDependencies": {
"@biomejs/biome": "1.9.4",
"@cloudflare/vitest-pool-workers": "^0.5.41",
"@cloudflare/workers-types": "^4.20241218.0",
"@cloudflare/workers-types": "^4.20250204.0",
"@commitlint/cli": "^19.6.1",
"@commitlint/config-conventional": "^19.6.0",
"@types/bcryptjs": "^2.4.6",
"dotenv": "^16.4.7",
"drizzle-kit": "^0.28.1",
"husky": "^9.1.7",
"vitest": "^2.1.9",
"wrangler": "^3.98.0"
"wrangler": "^3.108.1"
}
}
462 changes: 373 additions & 89 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

78 changes: 78 additions & 0 deletions src/handlers/auth/users/RefreshToken.Handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import type { ISanitizedAuthDTO } from '@src/dtos/Auth.DTO'
import { AppError } from '@src/errors/AppErrors.Error'
import { WebCryptoAES } from '@src/lib/webCryptoAES'
import { RefreshTokenRepository } from '@src/repositories/auth/RefreshToken.Repository'
import { JWTManager } from '@src/services/auth/jwtManager/JWTManager.Service'
import { RefreshTokenService } from '@src/services/auth/refreshToken/RefreshToken.Service'
import type { Presenter } from '@src/types/presenter'
import { factory } from '@src/utils/factory'
import type { TypedResponse } from 'hono'
import { getCookie, setCookie } from 'hono/cookie'
import { logger } from 'hono/logger'
import type { StatusCode } from 'hono/utils/http-status'

export const RefreshTokenHandler = factory.createHandlers(
logger(),
async (
c
): Promise<TypedResponse<Presenter<ISanitizedAuthDTO>, StatusCode>> => {
const refreshTokenRepository = new RefreshTokenRepository(c.env.DB)
const jwtManager = new JWTManager({
USER_SECRET_KEY: c.env.USER_SECRET_KEY,
REFRESH_SECRET_KEY: c.env.REFRESH_SECRET_KEY,
AUTH_ISSUER: c.env.AUTH_ISSUER
})
const webCryptoAES = new WebCryptoAES({
secret: c.env.REFRESH_AES_KEY
})
const refreshTokenService = new RefreshTokenService(
refreshTokenRepository,
c.env.AUTH_ISSUER,
c.env.USER_SECRET_KEY,
c.env.REFRESH_SECRET_KEY,
jwtManager,
webCryptoAES
)

const accessToken = await c.req.json().catch(() => {
throw new AppError({
name: 'Bad Request',
message: 'Invalid JSON format in request body'
})
})

const userAgent = c.req.header('User-Agent')

const refreshToken = getCookie(c, 'refreshToken')

const data = { refreshToken, userAgent, ...accessToken }

const user = await refreshTokenService.execute(data)

setCookie(c, 'refreshToken', user.token.refreshToken, {
secure: true,
httpOnly: true,
sameSite: 'Strict',
maxAge: 60 * 60 * 24 * 27,
path: '/users/auth/refresh'
})

return c.json(
{
success: true,
message: 'Token refreshed successfully',
data: {
id: user.id,
name: user.name,
username: user.username,
email: user.email ? user.email : undefined,
token: {
accessToken: user.token.accessToken,
expiresIn: user.token.expiresIn
}
}
},
200
)
}
)
2 changes: 2 additions & 0 deletions src/routers/auth.router.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { EnableOtpHandler } from '@src/handlers/auth/users/EnableOTP.Handler'
import { GenerateOtpAuthUrlHandler } from '@src/handlers/auth/users/GenerateOtpAuth.Handler'
import { OtpAuthHandler } from '@src/handlers/auth/users/OTPAuth.Handler'
import { RefreshTokenHandler } from '@src/handlers/auth/users/RefreshToken.Handler'
import { UserAuthHandler } from '@src/handlers/auth/users/UserAuth.Handler'
import { authenticateToken } from '@src/middleware/Auth.middleware'
import { Hono } from 'hono'
Expand All @@ -9,6 +10,7 @@ const authRouters = new Hono()

authRouters.post('/users/login', ...UserAuthHandler)
authRouters.post('/users/otp/login', ...OtpAuthHandler)
authRouters.post('/users/auth/refresh', ...RefreshTokenHandler)
authRouters.put('/users/:id/otp', ...EnableOtpHandler)
authRouters.post(
'/users/:id/otp/secret',
Expand Down
237 changes: 237 additions & 0 deletions src/services/auth/refreshToken/RefreshToken.Service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
import type { IAuthReturnDTO, StoreRefreshTokenInput } from '@src/dtos/Auth.DTO'
import type {
IRefreshTokenDTO,
IRefreshTokenParamsDTO
} from '@src/dtos/RefreshToken.DTO'
import type { IUsersDTO } from '@src/dtos/User.DTO'
import { RefreshToken } from '@src/entities/RefreshToken.Entity'
import { AppError } from '@src/errors/AppErrors.Error'
import type { WebCryptoAES } from '@src/lib/webCryptoAES'
import type { RefreshTokenRepository } from '@src/repositories/auth/RefreshToken.Repository'
import { refreshTokenSchema } from '@src/validations/auth/RefreshToken.Validation'
import { decode, verify } from 'hono/jwt'
import type { TokenHeader } from 'hono/utils/jwt/jwt'
import {
type JWTPayload,
JwtTokenSignatureMismatched
} from 'hono/utils/jwt/types'
import type { JWTManager } from '../jwtManager/JWTManager.Service'

export class RefreshTokenService {
public constructor(
private readonly refreshTokenRepository: RefreshTokenRepository,
private readonly AUTH_ISSUER: string,
private readonly USER_SECRET_KEY: string,
private readonly REFRESH_SECRET_KEY: string,
private readonly jwtManager: JWTManager,
private readonly webCryptoAES: WebCryptoAES
) {}

public async execute(data: IRefreshTokenParamsDTO): Promise<IAuthReturnDTO> {
this.validationInput(data)

await this.verifySignature(data.accessToken, 'accessToken')
await this.verifySignature(data.refreshToken, 'refreshToken')

const { refreshToken, accessToken } = this.decodeTokens(data)

this.validateToken(refreshToken)
this.validateToken(accessToken)

this.checkTokensSubMatch(accessToken.payload.sub, refreshToken.payload.sub)

this.checkTokenExp(refreshToken.payload.exp, accessToken.payload.exp)

const user = await this.getRefreshToken(refreshToken.payload.sub)

await this.checkTokensMatch(data.refreshToken, user.refreshToken[0].token)

const newToken = await this.jwtManager.generateToken({
id: user.id,
name: user.name,
username: user.username
})

const hashedNewToken = await this.hashNewToken(newToken.refreshToken)

await this.refreshTokenRepository.update({
...user.refreshToken[0],
revoked: true
})

await this.storeRefreshToken({
expiresAt: newToken.accessTokenExp,
refreshToken: hashedNewToken,
userAgent: data.userAgent,
userId: user.id
})

return {
id: user.id,
name: user.name,
username: user.username,
email: user.email ? user.email : undefined,
token: {
accessToken: newToken.accessToken,
refreshToken: newToken.refreshToken,
expiresIn: newToken.accessTokenExp
}
}
}

private checkTokensSubMatch(
accessTokenSub: unknown,
refreshTokenSub: unknown
): asserts refreshTokenSub is string {
if (
typeof accessTokenSub !== 'string' ||
typeof refreshTokenSub !== 'string' ||
refreshTokenSub !== accessTokenSub
) {
throw new AppError({
name: 'Forbidden',
message: 'Action Denied!'
})
}
}

private async verifySignature(
token: string,
type: 'refreshToken' | 'accessToken'
): Promise<void> {
try {
const secret =
type === 'refreshToken' ? this.REFRESH_SECRET_KEY : this.USER_SECRET_KEY

await verify(token, secret)
} catch (error) {
if (error instanceof JwtTokenSignatureMismatched) {
throw new AppError({
name: 'Unauthorized',
message: 'Access Denied!'
})
}
}
}

private async storeRefreshToken(data: StoreRefreshTokenInput): Promise<void> {
const refreshTokenData = {
revoked: false,
token: data.refreshToken,
userAgent: data.userAgent,
userId: data.userId,
expiresAt: new Date(data.expiresAt * 1000).toISOString()
}
const refreshToken = new RefreshToken(refreshTokenData)

await this.refreshTokenRepository.create(refreshToken)
}

private async checkTokensMatch(
clientToken: string,
dbToken: string
): Promise<void> {
const decryptedToken = await this.webCryptoAES.decryptSymetric(dbToken)

const isValid = clientToken === decryptedToken.plainText

if (!isValid) {
throw new AppError({
name: 'Unauthorized',
message: 'Access Denied!'
})
}
}

private async hashNewToken(refreshToken: string): Promise<string> {
const encryptedClientToken =
await this.webCryptoAES.encryptSymetric(refreshToken)

if (!encryptedClientToken.cipherText || encryptedClientToken.error) {
throw new AppError({
name: 'Internal Server Error',
message: 'Internal Server Error'
})
}

return encryptedClientToken.cipherText
}

private async getRefreshToken(
userId: string
): Promise<IUsersDTO & { refreshToken: IRefreshTokenDTO[] }> {
const user = await this.refreshTokenRepository.findManyByOr({
id: userId,
revoked: false,
noExpired: true
})

if (user === null) {
throw new AppError({
name: 'Forbidden',
message: 'Action Denied!'
})
}

return user
}

private checkTokenExp(
refreshTokenExp?: number,
accessTokenExp?: number
): void {
const now = Math.floor(Date.now() / 1000)

if (
!refreshTokenExp ||
!accessTokenExp ||
refreshTokenExp < now ||
accessTokenExp > now
) {
throw new AppError({
name: 'Unauthorized',
message: 'Invalid Token!'
})
}
}

private validateToken(data: {
header: TokenHeader
payload: JWTPayload
}): void {
if (
!data.payload.iss ||
!data.payload.sub ||
data.payload.iss !== this.AUTH_ISSUER
) {
throw new AppError({
name: 'Forbidden',
message: 'Action Denied!'
})
}
}

private decodeTokens(data: IRefreshTokenParamsDTO): {
refreshToken: { header: TokenHeader; payload: JWTPayload }
accessToken: { header: TokenHeader; payload: JWTPayload }
} {
const refreshToken = decode(data.refreshToken)
const accessToken = decode(data.accessToken)
return { refreshToken, accessToken }
}

private validationInput(data: IRefreshTokenParamsDTO): void {
const isValidData = refreshTokenSchema.check(data)

if (!isValidData.success) {
throw new AppError({
name: 'Bad Request',
message: 'Validation failed',
cause: {
field: isValidData.field,
cause: `is not ${isValidData.failedValidator}`
}
})
}
}
}
12 changes: 12 additions & 0 deletions src/validations/auth/RefreshToken.Validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { validator } from '@src/lib/validator'

export const refreshTokenSchema = validator.schema(
{
accessToken: validator.string().max(300).min(1),
refreshToken: validator.string().max(256).min(8),
userAgent: validator.string().max(256).nullable()
},
{
strict: true
}
)
Loading