How to get totp with Node.js


This post is written 15 months ago. Probably the information might be out of date.

As a developer working on debugging various functionalities and implementing Multi-Factor Authentication (MFA) using Amazon Cognito, I encountered the need to set up multiple users with Google Authenticator for testing. This process felt tedious and time-consuming, prompting me to seek a more efficient solution. To streamline the process and enhance productivity, I decided to create a Node.js script to generate Time-Based One-Time Passwords (TOTPs) programmatically.

Code

Here is the code To generate TOTP codes programmatically, we use the speakeasy library, which provides a straightforward way to generate TOTPs using various cryptographic algorithms. Here’s a simplified version of the Node.js script:

const speakeasy = require("speakeasy");

// value
const secrets = {
  user1: "aaaaaaaa",
  user2: "xxxxxxxx",
  user3: "yyyyyyyy",
  user4: "zzzzzzzz"
};

// Function to get TOTP for a given user
function getTotp(key) {
  const totpCode = speakeasy.totp({
    secret: secrets[key],
    encoding: "base32",
  });

  return totpCode;
}

// Command line argument handling
const args = process.argv.slice(2);
const keyIndex = args.indexOf("-key");

// Check if a valid key is provided as a command line argument
if (keyIndex !== -1 && args.length > keyIndex + 1) {
  const key = args[keyIndex + 1];
  const totpCode = getTotp(key);
  console.log(`TOTP Code for ${key}:`, totpCode);
} else {
  console.log("Usage: node totp.js -key <user>");
}
copied!

How to use

With the Node.js script in place, we can now effortlessly generate TOTPs for any user by simply providing their respective keys as command-line arguments.

For example:

$ node totp.js -key user1
TOTP Code for user1: 032312
copied!
buy me a coffee