UNPKG

generate-passphrase

Version:

Zero dependency module - Secure random passphrase

20 lines (19 loc) 1.98 kB
import t from"node:crypto";import{readFileSync as r}from"node:fs";import{dirname as o,resolve as e}from"node:path";import{fileURLToPath as n}from"node:url"; /** * @module generate-passphrase * @author Reinaldy Rafli <aldy505@proton.me> * @license MIT */let s,a;function p(){return(void 0===a||a>=s.length)&&(s=t.randomBytes(256),a=0),a+=1,s[a]}function f(t,r=!1){if(r)return Math.floor(Math.random()*t);let o=p();for(;void 0===o||o>=256-256%t;)o=p();return o%t}const i=r(e(o(n(import.meta.url)),"./words.txt"),"utf8").split("\n");function u(r=!1){const o=r?Math.floor(Math.random()*i.length):t.randomInt(0,i.length);return i[o]} /** * 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 c(t={}){const r={length:4,separator:"-",numbers:!0,uppercase:!1,titlecase:!1,pattern:void 0,fast:!1},o=Object.assign(Object.assign({},r),t);if(o.length<=0)throw new Error("Length should be 1 or bigger. It should not be zero or lower.");const e=[],n=[...o.pattern?o.pattern.toUpperCase():function(t,r,o=!1){const e=r?"NWW":"WWW";let n="";for(let r=0;r<t;r++)n+=e[f(2,o)];return n}(o.length,o.numbers,o.fast)];for(const t of n)if("N"===t)e.push(p());else{if("W"!==t)throw new Error("Unknown pattern found. Use N or W instead.");{const t=u(o.fast);o.uppercase?e.push(t.toUpperCase()):o.titlecase?e.push(t.replace(/\w\S*/g,(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()))):e.push(t)}}return e.join(o.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 */function l(t,r={}){const o=[];for(let e=0;e<t;e++)o[e]=c(r);return o}export{c as generate,l as generateMultiple};