fix: refactor GenerateTOTP to use optauth

This commit is contained in:
exactlyaron 2025-01-23 11:28:04 +00:00
parent 7eb9e08ad2
commit 672cb5dea4

View file

@ -5,15 +5,14 @@
*/ */
import Operation from "../Operation.mjs"; import Operation from "../Operation.mjs";
import otp from "otp"; import * as OTPAuth from "otpauth";
/** /**
* Generate TOTP operation * Generate TOTP operation
*/ */
class GenerateTOTP extends Operation { class GenerateTOTP extends Operation {
/** /**
* GenerateTOTP constructor *
*/ */
constructor() { constructor() {
super(); super();
@ -29,11 +28,6 @@ class GenerateTOTP extends Operation {
"type": "string", "type": "string",
"value": "" "value": ""
}, },
{
"name": "Key size",
"type": "number",
"value": 32
},
{ {
"name": "Code length", "name": "Code length",
"type": "number", "type": "number",
@ -53,32 +47,27 @@ class GenerateTOTP extends Operation {
} }
/** /**
* @param {ArrayBuffer} input *
* @param {Object[]} args
* @returns {string}
*/ */
run(input, args) { run(input, args) {
const secretStr = new TextDecoder("utf-8").decode(input).trim(); const secretStr = new TextDecoder("utf-8").decode(input).trim();
const secret = secretStr ? secretStr.toUpperCase().replace(/\s+/g, "") : "";
// uppercase it and remove spaces. If input is empty, let otp generate a random key. const totp = new OTPAuth.TOTP({
const secret = secretStr ? issuer: "",
secretStr.toUpperCase().replace(/\s+/g, "") : // e.g. "ok53 fvlf" -> "OK53FVLF" label: args[0],
""; algorithm: "SHA1",
digits: args[1],
// Construct the OTP object. If secret is "", otp will auto-generate one. period: args[3],
const otpObj = new otp({ epoch: args[2] * 1000, // Convert seconds to milliseconds
name: args[0], secret: OTPAuth.Secret.fromBase32(secret)
keySize: args[1],
codeLength: args[2],
secret: secret,
epoch: args[3],
timeSlice: args[4]
}); });
// Return TOTP URI and code const uri = totp.toString();
return `URI: ${otpObj.totpURL}\n\nPassword: ${otpObj.totp()}`; const code = totp.generate();
}
return `URI: ${uri}\n\nPassword: ${code}`;
}
} }
export default GenerateTOTP; export default GenerateTOTP;