generate-passphrase
Version:
Zero dependency module - Secure random passphrase
21 lines (20 loc) • 2.13 kB
JavaScript
;var e=require("node:crypto"),t=require("node:fs"),r=require("node:path");
/**
* @module generate-passphrase
* @author Reinaldy Rafli <aldy505@proton.me>
* @license MIT
*/
const n=require("node:url").fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:document.currentScript&&document.currentScript.src||new URL("index.cjs",document.baseURI).href),o=r.dirname(n);let s,a;function u(){return(void 0===a||a>=s.length)&&(s=e.randomBytes(256),a=0),a+=1,s[a]}function i(e,t=!1){if(t)return Math.floor(Math.random()*e);let r=u();for(;void 0===r||r>=256-256%e;)r=u();return r%e}const c=t.readFileSync(r.resolve(o,"./words.txt"),"utf8").split("\n");function l(t=!1){const r=t?Math.floor(Math.random()*c.length):e.randomInt(0,c.length);return c[r]}
/**
* Generate a passphrase with options
* @param {GenerateOptions} options - The options
* @returns {string} - A passphrase
* @see Usage https://github.com/aldy505/generate-passphrase#how-to-use-this
*/function p(e={}){const t={length:4,separator:"-",numbers:!0,uppercase:!1,titlecase:!1,pattern:void 0,fast:!1},r=Object.assign(Object.assign({},t),e);if(r.length<=0)throw new Error("Length should be 1 or bigger. It should not be zero or lower.");const n=[],o=[...r.pattern?r.pattern.toUpperCase():function(e,t,r=!1){const n=t?"NWW":"WWW";let o="";for(let t=0;t<e;t++)o+=n[i(2,r)];return o}(r.length,r.numbers,r.fast)];for(const e of o)if("N"===e)n.push(u());else{if("W"!==e)throw new Error("Unknown pattern found. Use N or W instead.");{const e=l(r.fast);r.uppercase?n.push(e.toUpperCase()):r.titlecase?n.push(e.replace(/\w\S*/g,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))):n.push(e)}}return n.join(r.separator)}
/**
* Generate multiple passphrase with the same options
* @param {number} amount - The number of passphrase returned
* @param {GenerateOptions} options - The options
* @returns {string[]} - Array of passphrases
* @see Usage https://github.com/aldy505/generate-passphrase#how-to-use-this
*/exports.generate=p,exports.generateMultiple=function(e,t={}){const r=[];for(let n=0;n<e;n++)r[n]=p(t);return r};