UNPKG

@stacksjs/tlsx

Version:

A TLS/HTTPS library with automation.

9 lines (7 loc) 12.5 kB
import{b as c,q as N,r as V,s as T}from"../chunk-gcaqh7xy.js";import{B as g}from"../chunk-s5xt8spa.js";import{EventEmitter as M}from"events";function w(t){return t==null?[]:Array.isArray(t)?t:[t]}function q(t,e,n,s){var i,o=t[e],l=~s.string.indexOf(e)?n==null||n===!0?"":String(n):typeof n==="boolean"?n:~s.boolean.indexOf(e)?n==="false"?!1:n==="true"||(t._.push((i=+n,i*0===0)?i:n),!!n):(i=+n,i*0===0)?i:n;t[e]=o==null?l:Array.isArray(o)?o.concat(l):[o,l]}function B(t,e){t=t||[],e=e||{};var n,s,i,o,l,u={_:[]},r=0,a=0,m=0,h=t.length;let f=e.alias!==void 0,x=e.unknown!==void 0,O=e.default!==void 0;if(e.alias=e.alias||{},e.string=w(e.string),e.boolean=w(e.boolean),f)for(n in e.alias){s=e.alias[n]=w(e.alias[n]);for(r=0;r<s.length;r++)(e.alias[s[r]]=s.concat(n)).splice(r,1)}for(r=e.boolean.length;r-- >0;){s=e.alias[e.boolean[r]]||[];for(a=s.length;a-- >0;)e.boolean.push(s[a])}for(r=e.string.length;r-- >0;){s=e.alias[e.string[r]]||[];for(a=s.length;a-- >0;)e.string.push(s[a])}if(O){for(n in e.default)if(o=typeof e.default[n],s=e.alias[n]=e.alias[n]||[],e[o]!==void 0){e[o].push(n);for(r=0;r<s.length;r++)e[o].push(s[r])}}let v=x?Object.keys(e.alias):[];for(r=0;r<h;r++){if(i=t[r],i==="--"){u._=u._.concat(t.slice(++r));break}for(a=0;a<i.length;a++)if(i.charCodeAt(a)!==45)break;if(a===0)u._.push(i);else if(i.substring(a,a+3)==="no-"){if(o=i.substring(a+3),x&&!~v.indexOf(o))return e.unknown(i);u[o]=!1}else{for(m=a+1;m<i.length;m++)if(i.charCodeAt(m)===61)break;o=i.substring(a,m),l=i.substring(++m)||(r+1===h||(""+t[r+1]).charCodeAt(0)===45||t[++r]),s=a===2?[o]:o;for(m=0;m<s.length;m++){if(o=s[m],x&&!~v.indexOf(o))return e.unknown("-".repeat(a)+o);q(u,o,m+1<s.length||l,e)}}}if(O){for(n in e.default)if(u[n]===void 0)u[n]=e.default[n]}if(f)for(n in u){s=e.alias[n]||[];while(s.length>0)u[s.shift()]=u[n]}return u}var j=(t)=>t.replace(/[<[].+/,"").trim(),H=(t)=>{let e=/<([^>]+)>/g,n=/\[([^\]]+)\]/g,s=[],i=(u)=>{let r=!1,a=u[1];if(a.startsWith("..."))a=a.slice(3),r=!0;return{required:u[0].startsWith("<"),value:a,variadic:r}},o;while(o=e.exec(t))s.push(i(o));let l;while(l=n.exec(t))s.push(i(l));return s},G=(t)=>{let e={alias:{},boolean:[]};for(let[n,s]of t.entries()){if(s.names.length>1)e.alias[s.names[0]]=s.names.slice(1);if(s.isBoolean)if(s.negated){if(!t.some((o,l)=>{return l!==n&&o.names.some((u)=>s.names.includes(u))&&typeof o.required==="boolean"}))e.boolean.push(s.names[0])}else e.boolean.push(s.names[0])}return e},$=(t)=>{return t.sort((e,n)=>{return e.length>n.length?-1:1})[0]},A=(t,e)=>{return t.length>=e?t:`${t}${" ".repeat(e-t.length)}`},L=(t)=>{return t.replace(/([a-z])-([a-z])/g,(e,n,s)=>{return n+s.toUpperCase()})},R=(t,e,n)=>{let s=0,i=e.length,o=t,l;for(;s<i;++s)l=o[e[s]],o=o[e[s]]=s===i-1?n:l!=null?l:!!~e[s+1].indexOf(".")||!(+e[s+1]>-1)?{}:[]},U=(t,e)=>{for(let n of Object.keys(e)){let s=e[n];if(s.shouldTransform){if(t[n]=Array.prototype.concat.call([],t[n]),typeof s.transformFunction==="function")t[n]=t[n].map(s.transformFunction)}}},I=(t)=>{let e=/([^\\\/]+)$/.exec(t);return e?e[1]:""},_=(t)=>{return t.split(".").map((e,n)=>{return n===0?L(e):e}).join(".")};class p extends Error{constructor(t){super(t);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=new Error(t).stack}}class E{constructor(t,e,n){if(this.rawName=t,this.description=e,this.config=Object.assign({},n),t=t.replace(/\.\*/g,""),this.negated=!1,this.names=j(t).split(",").map((s)=>{let i=s.trim().replace(/^-{1,2}/,"");if(i.startsWith("no-"))this.negated=!0,i=i.replace(/^no-/,"");return _(i)}).sort((s,i)=>s.length>i.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(t.includes("<"))this.required=!0;else if(t.includes("["))this.required=!1;else this.isBoolean=!0}}var P=process.argv,F=`${process.platform}-${process.arch} node-${process.version}`;class y{constructor(t,e,n={},s){this.rawName=t,this.description=e,this.config=n,this.cli=s,this.options=[],this.aliasNames=[],this.name=j(t),this.args=H(t),this.examples=[]}usage(t){return this.usageText=t,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(t,e="-v, --version"){return this.versionNumber=t,this.option(e,"Display version number"),this}example(t){return this.examples.push(t),this}option(t,e,n){let s=new E(t,e,n);return this.options.push(s),this}alias(t){return this.aliasNames.push(t),this}action(t){return this.commandAction=t,this}isMatched(t){return this.name===t||this.aliasNames.includes(t)}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof k}hasOption(t){return t=t.split(".")[0],this.options.find((e)=>{return e.names.includes(t)})}outputHelp(){let{name:t,commands:e}=this.cli,{versionNumber:n,options:s,helpCallback:i}=this.cli.globalCommand,o=[{body:`${t}${n?`/${n}`:""}`}];if(o.push({title:"Usage",body:` $ ${t} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&e.length>0){let r=$(e.map((a)=>a.rawName));o.push({title:"Commands",body:e.map((a)=>{return` ${A(a.rawName,r.length)} ${a.description}`}).join(` `)}),o.push({title:"For more info, run any command with the `--help` flag",body:e.map((a)=>` $ ${t}${a.name===""?"":` ${a.name}`} --help`).join(` `)})}let u=this.isGlobalCommand?s:[...this.options,...s||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)u=u.filter((r)=>r.name!=="version");if(u.length>0){let r=$(u.map((a)=>a.rawName));o.push({title:"Options",body:u.map((a)=>{return` ${A(a.rawName,r.length)} ${a.description} ${a.config.default===void 0?"":`(default: ${a.config.default})`}`}).join(` `)})}if(this.examples.length>0)o.push({title:"Examples",body:this.examples.map((r)=>{if(typeof r==="function")return r(t);return r}).join(` `)});if(i)o=i(o)||o;console.log(o.map((r)=>{return r.title?`${r.title}: ${r.body}`:r.body}).join(` `))}outputVersion(){let{name:t}=this.cli,{versionNumber:e}=this.cli.globalCommand;if(e)console.log(`${t}/${e} ${F}`)}checkRequiredArgs(){let t=this.args.filter((e)=>e.required).length;if(this.cli.args.length<t)throw new p(`missing required args for command \`${this.rawName}\``)}checkUnknownOptions(){let{options:t,globalCommand:e}=this.cli;if(!this.config.allowUnknownOptions){for(let n of Object.keys(t))if(n!=="--"&&!this.hasOption(n)&&!e.hasOption(n))throw new p(`Unknown option \`${n.length>1?`--${n}`:`-${n}`}\``)}}checkOptionValue(){let{options:t,globalCommand:e}=this.cli,n=[...e.options,...this.options];for(let s of n){let i=t[s.name.split(".")[0]];if(s.required){let o=n.some((l)=>l.negated&&l.names.includes(s.name));if(i===!0||i===!1&&!o)throw new p(`option \`${s.rawName}\` value is missing`)}}}}class k extends y{constructor(t){super("@@global@@","",{},t)}}var d=Object.assign;class C extends M{constructor(t=""){super();this.name=t,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new k(this),this.globalCommand.usage("<command> [options]")}usage(t){return this.globalCommand.usage(t),this}command(t,e,n){let s=new y(t,e||"",n,this);return s.globalCommand=this.globalCommand,this.commands.push(s),s}option(t,e,n){return this.globalCommand.option(t,e,n),this}help(t){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=t,this.showHelpOnExit=!0,this}version(t,e="-v, --version"){return this.globalCommand.version(t,e),this.showVersionOnExit=!0,this}example(t){return this.globalCommand.example(t),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:t,options:e},n,s){if(this.args=t,this.options=e,n)this.matchedCommand=n;if(s)this.matchedCommandName=s;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}parse(t=P,{run:e=!0}={}){if(this.rawArgs=t,!this.name)this.name=t[1]?I(t[1]):"cli";let n=!0;for(let i of this.commands){let o=this.mri(t.slice(2),i),l=o.args[0];if(i.isMatched(l)){n=!1;let u=d(d({},o),{args:o.args.slice(1)});this.setParsedInfo(u,i,l),this.emit(`command:${l}`,i)}}if(n){for(let i of this.commands)if(i.name===""){n=!1;let o=this.mri(t.slice(2),i);this.setParsedInfo(o,i),this.emit("command:!",i)}}if(n){let i=this.mri(t.slice(2));this.setParsedInfo(i)}if(this.options.help&&this.showHelpOnExit)this.outputHelp(),e=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),e=!1,this.unsetMatchedCommand();let s={args:this.args,options:this.options};if(e)this.runMatchedCommand();if(!this.matchedCommand&&this.args[0])this.emit("command:*");return s}mri(t,e){let n=[...this.globalCommand.options,...e?e.options:[]],s=G(n),i=[],o=t.indexOf("--");if(o>-1)i=t.slice(o+1),t=t.slice(0,o);let l=B(t,s);l=Object.keys(l).reduce((h,f)=>{return d(d({},h),{[_(f)]:l[f]})},{_:[]});let u=l._,r={"--":i},a=e&&e.config.ignoreOptionDefaultValue?e.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,m=Object.create(null);for(let h of n){if(!a&&h.config.default!==void 0)for(let f of h.names)r[f]=h.config.default;if(Array.isArray(h.config.type)){if(m[h.name]===void 0)m[h.name]=Object.create(null),m[h.name].shouldTransform=!0,m[h.name].transformFunction=h.config.type[0]}}for(let h of Object.keys(l))if(h!=="_"){let f=h.split(".");R(r,f,l[h]),U(r,m)}return{args:u,options:r}}runMatchedCommand(){let{args:t,options:e,matchedCommand:n}=this;if(!n||!n.commandAction)return;n.checkUnknownOptions(),n.checkOptionValue(),n.checkRequiredArgs();let s=[];return n.args.forEach((i,o)=>{if(i.variadic)s.push(t.slice(o));else s.push(t[o])}),s.push(e),n.commandAction.apply(this,s)}}var D="0.10.0";var b=new C("tlsx");b.command("secure [domain]","Auto generate a self-signed SSL certificate for one or multiple domains").option("-k, --key-path <key>","Output key file name",{default:c.keyPath}).option("-c, --cert-path <cert>","Output certificate file name",{default:c.certPath}).option("-ca, --ca-path <ca>","Output CA file name",{default:c.caCertPath}).option("-d, --domains <domains>","Additional domains (comma-separated)").option("--alt-name-ips <ips>","Alternative Name IPs (comma-separated)",{default:c.altNameIPs.join(",")}).option("--alt-name-uris <uris>","Alternative Name URIs (comma-separated)",{default:c.altNameURIs.join(",")}).option("--common-name <name>","Common Name for the certificate",{default:c.commonName}).option("--country-name <name>","Country Name for the certificate",{default:c.countryName}).option("--state-name <name>","State Name for the certificate",{default:c.stateName}).option("--locality-name <name>","Locality Name for the certificate",{default:c.localityName}).option("--organization-name <name>","Organization Name for the certificate",{default:c.organizationName}).option("--validity-days <days>","Validity Days for the certificate",{default:c.validityDays}).option("--verbose","Enable verbose logging",{default:c.verbose}).usage("tlsx secure [domain] [options]").example("tlsx secure example.com --output /etc/ssl").example('tlsx secure example.com -d "api.example.com,*.example.com"').example('tlsx secure -d "example.com,api.example.com"').example('tlsx secure stacks.localhost -d "stacks2.local,stacks3.localhost,stacks4.test"').action(async(t,e)=>{let n=e||{},s=[];if(t)s.push(t);if(n.domains)s.push(...n.domains.split(",").map((r)=>r.trim()));if(s.length===0&&c?.domain)s.push(c.domain);if(s.length===0)throw new Error("No domains specified. Use either positional argument or --domains option");let i=n.altNameIPs?n.altNameIPs.split(",").map((r)=>r.trim()):c.altNameIPs,o=n.altNameURIs?n.altNameURIs.split(",").map((r)=>r.trim()):c.altNameURIs;g.info(`Generating a self-signed SSL certificate for: ${s.join(", ")}`),g.debug("Options:",{...n,domains:s});let l=await N(),u=await V({domain:s[0],domains:s,commonName:n.commonName??c.commonName??s[0],altNameIPs:i,altNameURIs:o,countryName:n.countryName||c.countryName,stateName:n.stateName||c.stateName,localityName:n.localityName||c.localityName,organizationName:n.organizationName||c.organizationName,validityDays:Number(n.validityDays)||c.validityDays,rootCA:{certificate:l.certificate,privateKey:l.privateKey}});await T(u,l.certificate),g.success("Certificate generated successfully")});b.version(D);b.help();b.parse();