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 kB
JavaScript
function t(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}Object.defineProperty(exports,"__esModule",{value:!0});var e=t(require("crypto"));exports.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 e.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(),a=()=>String.fromCharCode(Math.floor(26*Math.random())+97),n=()=>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},a).join(""))).replace(/U{(\d+)}/g,((t,e)=>Array.from({length:e},n).join("")))}(e.template||"N{6}"),a=e.ttl?Date.now()+1e3*e.ttl:1/0,n=JSON.stringify({otp:r,expiresAt:a}),o=this.encryptOtp(t,n);return this.enableSet&&this.hashSet.add(o),{otp:r,hash:o}}verify(t,e,r){try{const{otp:a,expiresAt:n}=this.decryptOtp(e,t),o=this.enableSet&&!this.hashSet.has(e),h=n<Date.now();if(o||h)return!1;const i=a===r;return i&&this.hashSet.delete(e),i}catch(t){return console.error(t),!1}}encryptOtp(t,r){const a=this.deriveKey(t),n=e.default.randomBytes(this.ivLength),o=e.default.createCipheriv(this.algorithm,a,n),h=o.update(r,"utf8","hex")+o.final("hex");return n.toString("hex")+":"+h}decryptOtp(t,r){const a=this.deriveKey(r),[n,o]=t.split(":"),h=Buffer.from(n,"hex"),i=e.default.createDecipheriv(this.algorithm,a,h),s=i.update(o,"hex","utf8")+i.final("utf8");return JSON.parse(s)}deriveKey(t){return e.default.createHash("sha256").update(this.secretSalt+t).digest()}};
;