UNPKG

node-less-otp

Version:

A super lightweight library for generating and verifying one-time passwords (OTPs) without the database interaction and additional dependencies.

2 lines (1 loc) 2.24 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("crypto")):"function"==typeof define&&define.amd?define(["exports","crypto"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).LessOtp={},t.crypto)}(this,(function(t,e){"use strict";function r(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var n=r(e);t.LessOtp=class{hashSet=(()=>new Set)();constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.secretSalt=t.secretSalt||function(){const t=Math.floor(17*Math.random())+16;return n.default.randomBytes(t).toString("hex")}(),this.algorithm=t.algorithm||"aes-256-cbc",this.ivLength=t.ivLength||16,this.enableSet=t.enableSet??true}gen(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=function(t){const e=function(t){return/^(N{\d+}|L{\d+}|U{\d+}|A{\d+}|M{\d+})+$/.test(t)}(t);if(!e)throw new Error("Invalid template format");const r=()=>Math.floor(10*Math.random()).toString(),n=()=>String.fromCharCode(Math.floor(26*Math.random())+97),o=()=>String.fromCharCode(Math.floor(26*Math.random())+65);return t.replace(/N{(\d+)}/g,((t,e)=>Array.from({length:e},r).join(""))).replace(/L{(\d+)}/g,((t,e)=>Array.from({length:e},n).join(""))).replace(/U{(\d+)}/g,((t,e)=>Array.from({length:e},o).join("")))}(e.template||"N{6}"),n=e.ttl?Date.now()+1e3*e.ttl:1/0,o=JSON.stringify({otp:r,expiresAt:n}),a=this.encryptOtp(t,o);return this.enableSet&&this.hashSet.add(a),{otp:r,hash:a}}verify(t,e,r){try{const{otp:n,expiresAt:o}=this.decryptOtp(e,t),a=this.enableSet&&!this.hashSet.has(e),i=o<Date.now();if(a||i)return!1;const h=n===r;return h&&this.hashSet.delete(e),h}catch(t){return console.error(t),!1}}encryptOtp(t,e){const r=this.deriveKey(t),o=n.default.randomBytes(this.ivLength),a=n.default.createCipheriv(this.algorithm,r,o),i=a.update(e,"utf8","hex")+a.final("hex");return o.toString("hex")+":"+i}decryptOtp(t,e){const r=this.deriveKey(e),[o,a]=t.split(":"),i=Buffer.from(o,"hex"),h=n.default.createDecipheriv(this.algorithm,r,i),s=h.update(a,"hex","utf8")+h.final("utf8");return JSON.parse(s)}deriveKey(t){return n.default.createHash("sha256").update(this.secretSalt+t).digest()}},Object.defineProperty(t,"__esModule",{value:!0})}));