A Nest module wrapper for XOTP.
nestjs-xotp
provides a convenient way to use the XOTP library within your NestJS applications. It fully leverages NestJS's powerful dependency injection system, making it easy to manage, generate, and validate OTPs (Time-based One-Time Passwords - TOTP, and HMAC-based One-Time Passwords - HOTP) for robust security within your services.
npm i xotp nestjs-xotp
Integrate XOTPModule
into your NestJS application by importing it into your AppModule
and configuring it using the forRoot()
method.
See the options reference section for the options with which you can customize the module!
import { Module } from '@nestjs/common';
import { XOTPModule } from 'nestjs-xotp';
@Module({
imports: [
XOTPModule.forRoot({
// Optional: Your XOTP configuration options go here
}),
],
})
export class AppModule {}
If your configuration depends on dynamic values, like environment variables or data from another module, use forRootAsync()
:
import { Module } from '@nestjs/common';
import { XOTPModule } from 'nestjs-xotp';
@Module({
imports: [
XOTPModule.forRootAsync({
useFactory: () => ({
// Your XOTP configuration options, dynamically provided
}),
}),
],
})
export class AppModule {}
Once XOTPModule
is configured, you can easily inject XOTPService into any of your NestJS services or controllers:
import { Injectable } from '@nestjs/common';
import { XOTPService } from 'nestjs-xotp';
@Injectable()
export class MyService {
constructor(private readonly xotpService: XOTPService) {}
}
Here are some common ways to use the XOTPService for OTP operations:
Create a new Time-based One-Time Password:
getOtp(): string {
return this.xotpService.totp.generate({
secret: this.xotpService.secret.from('A_STRONG_SECRET_KEY'),
});
}
Validate an OTP provided by a user:
authenticate(userOTP: string): boolean {
return this.xotpService.totp.validate({
token: userOTP,
secret: this.xotpService.secret.from('YOUR_SECRET_KEY'),
});
}
Get the keyURI from which create a QR Code. Users can then scan the QR Code by authenticator apps like Google Authenticator!
getKeyUri(): string {
return this.xotpService.totp.keyUri({
secret: this.xotpService.secret.from('A_STRONG_SECRET_KEY'),
account: 'Nestjs-XOTP',
});
}
The nestjs-xotp module accepts an optional configuration object. These options mirror those available in the underlying XOTP library and apply globally to both TOTP and HOTP services. If you don't know what each one does, refer to the main xotp options!
{
"digits": 6,
"window": 1,
"algorithm": "sha1",
"duration": 30,
"issuer": "xotp"
}
You can set distinct options for TOTP or HOTP services individually. For instance, to change only the digit length for HOTP tokens:
{
"digits": 6,
"hotp": {
"digits": 4
}
}
nestjs-xotp
is MIT licensed