Skip to content

Instantly share code, notes, and snippets.

@markodayan
Created November 17, 2021 20:31
Show Gist options
  • Save markodayan/f5912199662f7b48f7c1f56f11048722 to your computer and use it in GitHub Desktop.
Save markodayan/f5912199662f7b48f7c1f56f11048722 to your computer and use it in GitHub Desktop.
Timing Attack protection in Nestjs project
import { BasicStrategy as Strategy } from 'passport-http';
import { Injectable, InternalServerErrorException, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ConfigService } from '@nestjs/config';
import { timingSafeEqual } from 'crypto';
@Injectable()
export class AdminBasicStrategy extends PassportStrategy(Strategy) {
constructor(private readonly configService: ConfigService) {
super();
}
public validate = async (username: string, password: string): Promise<boolean> => {
const adminUsername = this.configService.get<string>('ADMIN_USER');
const adminPassword = this.configService.get<string>('ADMIN_PASSWORD');
if (!adminUsername || !adminPassword) {
throw new InternalServerErrorException('Missing configuration on AdminBasicStrategy');
}
if (
adminUsername.length === username.length &&
adminPassword.length === password.length &&
timingSafeEqual(Buffer.from(adminUsername), Buffer.from(username)) &&
timingSafeEqual(Buffer.from(adminPassword), Buffer.from(password))
) {
return true;
}
throw new UnauthorizedException();
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment