Documentation: Generating Time-Based OTP with JavaScript Library
This document details how to generate and retrieve a Time-Based One-Time Password (TOTP) using the otp-device-sync
JavaScript library. This method is ideal for use in automated testing scenarios that require two-factor authentication (2FA) with time-based OTP codes.
Installation
First, install the otp-device-sync
library from NPM:
npm install otp-device-sync
Importing the Function
The library provides a getTimeBasedCode
function for generating a time-based OTP. You can import this function directly:
import { getTimeBasedCode } from 'otp-device-sync';
Function Overview: getTimeBasedCode
Purpose: Retrieve a time-based OTP (TOTP) for a specific user and service.
Function Parameters
The getTimeBasedCode
function requires the following parameters:
- user:
string
(required)
The identifier for the TOTP user. This is often the user’s email or account name. - service:
string
(required)
The identifier for the service generating the OTP (e.g., service or application name). - options:
object
(required)verbose
:boolean
(optional) – Whentrue
, enables logging for debugging.registeredKey
:string
(required) – A unique API key to authenticate and authorize the OTP request.
Return Value
- Returns:
Promise<string>
The function returns a promise that resolves with the OTP code as a string if the request is successful.
Example Usage
The following example demonstrates how to retrieve a TOTP using the getTimeBasedCode
function:
import { getTimeBasedCode } from 'otp-device-sync';
(async () => {
try {
const otpCode = await getTimeBasedCode("user@example.com", "ServiceName", {
verbose: true,
registeredKey: "YOUR_REGISTERED_KEY"
});
console.log(`Retrieved TOTP: ${otpCode}`);
} catch (error) {
console.error(`Error retrieving TOTP: ${error.message}`);
}
})();
Key Points
- Time Sensitivity: The TOTP is valid only for a limited duration (typically 30 seconds). Retrieve and use it quickly to avoid expiration.
- Authentication: Ensure
registeredKey
is stored securely, as it is required to authenticate the request. - Error Handling: The function throws an error if there is an issue retrieving the OTP. Use try/catch blocks to manage errors effectively.
Verbose Mode
Setting verbose: true
in the options will enable logging for each step of the retrieval process, which is useful for debugging and tracking request progress.
Summary
With otp-device-sync
, you can streamline TOTP retrieval in your automated tests, simplifying 2FA testing workflows and enhancing test reliability. The getTimeBasedCode
function is designed to integrate seamlessly with testing frameworks, making it a valuable tool for automated end-to-end testing involving time-based OTPs.