totpChecker.js 1.3 KB

12345678910111213141516171819202122232425262728293031
  1. import crypto from 'crypto';
  2. const RFC_4648 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
  3. export class TotpChecker {
  4. static async ValidateTotp(totpSecret, code) {
  5. if (!totpSecret && !code)
  6. return true;
  7. if ((!totpSecret && code) || (totpSecret && !code))
  8. return false;
  9. return true;
  10. }
  11. static EncodeBase32(input) {
  12. let secret = [];
  13. for (let i of input)
  14. secret.push(RFC_4648[i % RFC_4648.length]);
  15. return secret.join("");
  16. }
  17. static GenerateCode(optionsOrIssuer) {
  18. let options = typeof optionsOrIssuer === "string" ? { issuer: optionsOrIssuer } : optionsOrIssuer;
  19. options.digits = options.digits || 6;
  20. options.period = options.period || 30;
  21. options.algorithm = options.algorithm || "SHA-1";
  22. options.label = encodeURIComponent(options.label || options.issuer);
  23. options.secretLength = options.secretLength || 13;
  24. const secretStr = TotpChecker.EncodeBase32(crypto.randomBytes(options.secretLength));
  25. return {
  26. url: `otpauth://totp/${options.issuer}?issuer=${options.issuer}&secret=${secretStr}&digits=${options.digits}&period=${options.period}&algorithm=${options.algorithm}`,
  27. secret: secretStr
  28. };
  29. }
  30. }
  31. //# sourceMappingURL=totpChecker.js.map