Contents
Mobile number has become the defacto user authentication mechanism in India and hence, OTP generation is a very common use case. otp-gen-agent is a Nano ID based small utility lib to generate OTP (one time password).
Why avoid Math.random()?
In the documentation for Math.random(); the note mentions
Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.
Read the blog, a real world scenario, Facebook JavaScript API; where the attacker was able to exploit the vulnerability.
Installation
npm install otp-gen-agent --save
Usage
Nano ID is a tiny, secure, URL-friendly, unique string ID generator for JavaScript.
- Small: 130 bytes (minified and gzipped). No dependencies. Size Limit controls the size.
- Safe: It uses hardware random generator. Can be used in clusters.
Read more in the section Security.
i) default
|
|
- Default OTP lenght is 6
- Default characters used to generate OTP is 0123456789
ii) custom otp generator
|
|
arguments:
- options: optional
- length: custom otp length
- chars: custom characters
You can customise the OTP length and also the characters to be used for OTP generation.
iii) bulk otp generator
|
|
|
|
arguments:
- num: number of OTPs to be generated in bulk
- opts: optional argument
- length: custom otp length (default: 6)
- chars: custom characters (default: 0123456789)
Useful in cases where number of OTPs to be generated is known before hand.
Conclusion
Nano ID uses the crypto module in Node.js and the Web Crypto API in browsers. These modules use unpredictable hardware random generator. otp-gen-agent
is a small utility lib based on Nano ID for generating otp.
✨ Thank you for reading and I hope you find it helpful. I sincerely request for your feedback in the comment’s section.