fix: refactor GenerateTOTP

This commit is contained in:
exactlyaron 2025-01-23 00:24:20 +00:00
parent 3822c6c520
commit e804555278

View file

@ -6,7 +6,6 @@
import Operation from "../Operation.mjs";
import otp from "otp";
import ToBase32 from "./ToBase32.mjs";
/**
* Generate TOTP operation
@ -18,7 +17,6 @@ class GenerateTOTP extends Operation {
*/
constructor() {
super();
this.name = "Generate TOTP";
this.module = "Default";
this.description = "The Time-based One-Time Password algorithm (TOTP) is an algorithm that computes a one-time password from a shared secret key and the current time. It has been adopted as Internet Engineering Task Force standard RFC 6238, is the cornerstone of Initiative For Open Authentication (OAUTH), and is used in a number of two-factor authentication systems. A TOTP is an HOTP where the counter is the current time.<br><br>Enter the secret as the input or leave it blank for a random secret to be generated. T0 and T1 are in seconds.";
@ -60,14 +58,24 @@ class GenerateTOTP extends Operation {
* @returns {string}
*/
run(input, args) {
const otpObj = otp({
const secretStr = new TextDecoder("utf-8").decode(input).trim();
// uppercase it and remove spaces. If input is empty, let otp generate a random key.
const secret = secretStr ?
secretStr.toUpperCase().replace(/\s+/g, "") : // e.g. "ok53 fvlf" -> "OK53FVLF"
"";
// Construct the OTP object. If secret is "", otp will auto-generate one.
const otpObj = new otp({
name: args[0],
keySize: args[1],
codeLength: args[2],
secret: (new ToBase32).run(input, []).split("=")[0],
secret: secret,
epoch: args[3],
timeSlice: args[4]
});
// Return TOTP URI and code
return `URI: ${otpObj.totpURL}\n\nPassword: ${otpObj.totp()}`;
}