UNPKG

@interopio/gateway-server

Version:

[![npm version](https://img.shields.io/npm/v/@interopio/gateway-server.svg)](https://www.npmjs.com/package/@interopio/gateway-server)

17 lines (14 loc) 9.17 kB
var ce=Object.defineProperty;var b=(e,t)=>{for(var n in t)ce(e,n,{get:t[n],enumerable:!0})};var q={};b(q,{ARGON2_VERSION:()=>V,ARGON2_VERSION_10:()=>M,ARGON2_VERSION_13:()=>B,DEFAULT_ALGORITHM:()=>ge,DEFAULT_HASH_LENGTH:()=>J,DEFAULT_MEMORY:()=>L,DEFAULT_PARALLELISM:()=>F,DEFAULT_PASSES:()=>k,DEFAULT_SALT_LENGTH:()=>D,createHash:()=>I,decode:()=>W,encode:()=>G,hash:()=>ue,verify:()=>pe});var H={};b(H,{createSalt:()=>E});import{getRandomValues as le}from"node:crypto";function E(e){return le(Buffer.alloc(e))}var C;async function me(){if(C===void 0)try{let e=await import("node:crypto");if(!e.argon2)throw new Error("argon2 not available");C=e.argon2}catch{throw new Error("argon2 is not available in this Node.js version. Node.js 24.7.0 or later is required for Argon2 password encoding. Please upgrade Node.js or use a different authentication method.")}return C}var M=16,B=19,V=B,ge="argon2id",D=16,J=32,F=4,L=65536,k=3;function W(e){let t=e.split("$");if(t.length<4)throw new Error("Invalid encoded Argon2 hash");let n=1,r=t[n++];if(r!=="argon2d"&&r!=="argon2i"&&r!=="argon2id")throw new Error("Invalid Argon2 type");let s=M;t[n].startsWith("v=")&&(s=parseInt(t[n].substring(2),10),n++);let a={},g=t[n++].split(",");for(let l of g){let[m,o]=l.split("=");switch(m){case"m":a.memory=parseInt(o,10);break;case"t":a.passes=parseInt(o,10);break;case"p":a.parallelism=parseInt(o,10);break}}a.nonce=Buffer.from(t[n++],"base64url");let i=Buffer.from(t[n++],"base64url");return{algorithm:r,version:s,parameters:a,hash:i}}function G(e){let{algorithm:t,version:n,parameters:r,hash:s}=e;return`$${t}$v=${n}$m=${r.memory},t=${r.passes},p=${r.parallelism}$${r.nonce.toString("base64url")}$${s.toString("base64url")}`}async function I(e,t,n,r){let s=r?.nonce??E(D),a=r?.memory??L,g=r?.passes??k,i=r?.parallelism??F,l={message:t,tagLength:n,nonce:s,memory:a,passes:g,parallelism:i},m=await me();return new Promise((o,p)=>{m(e,l,(d,h)=>{d?p(d):h?o(Buffer.from(h)):p(new Error("argon2 returned no result"))})})}async function ue(e,t){let n=t?.algorithm??"argon2id",r=t?.saltLength??D,s=t?.hashLength??J,a=t?.parallelism??F,g=t?.memory??L,i=t?.passes??k,l=E(r),m={memory:g,passes:i,parallelism:a,nonce:l},o=await I(n,e,s,m);return G({algorithm:n,version:V,parameters:m,hash:o})}async function pe(e,t){try{let n=W(e),r=await I(n.algorithm,t,n.hash.length,n.parameters);return n.hash.equals(r)}catch{return!1}}var Y={};b(Y,{sendCommand:()=>de});import fe from"net";function de(e,t,n={}){let{timeout:r=5e3}=n,s=e?.path?{path:e.path}:{port:e?.port??0},a=e?.path??`port ${e?.port}`;return new Promise((g,i)=>{let l=fe.connect(s,()=>{l.write(JSON.stringify(t))}),m=setTimeout(()=>{l.destroy(),i(new Error(`Connection timed out after ${r}`))},r);l.on("data",o=>{clearTimeout(m);try{let p=JSON.parse(o.toString());p.error?i(new Error(p.error)):g(p.result)}catch{g(o.toString())}l.end()}),l.on("error",o=>{clearTimeout(m),o.code==="ENOENT"||o.code==="ECONNREFUSED"?i(new Error(`Cannot connect to gateway at ${a}. Make sure the gateway server is running and the path is correct.`,{cause:o})):i(o)})})}var Z={};b(Z,{DEFAULT_CA_NAME:()=>X,generateCert:()=>Ae,generateRootCA:()=>we});import{KEYUTIL as w,KJUR as z,datetozulu as $}from"jsrsasign";import{userInfo as he,hostname as ye}from"node:os";import{randomBytes as be}from"node:crypto";var N=`${he().username}@${ye()}`;function Q(){return be(16).toString("hex")}var P="io.Gateway Dev CA",X=`${P} ${N}`;function we(e){let t=e?.name||X,n=e?.passphrase,r=w.generateKeypair("EC","secp384r1"),s=r.prvKeyObj,a=r.pubKeyObj,g=n?w.getPEM(s,"PKCS8PRV",n,"AES-256-CBC"):w.getPEM(s,"PKCS8PRV"),l=new z.asn1.x509.Certificate({version:3,serial:{hex:Q()},issuer:{str:`/CN=${t}/O=${P}/OU=${N}`},subject:{str:`/CN=${t}/O=${P}/OU=${N}`},notbefore:$(new Date(Date.now()-60*1e3),!1,!1),notafter:$(new Date(Date.now()+10*365*24*60*60*1e3),!1,!1),sbjpubkey:a,ext:[{extname:"basicConstraints",critical:!0,cA:!0},{extname:"keyUsage",critical:!0,names:["keyCertSign"]}],sigalg:"SHA384withECDSA",cakey:s}).getPEM();return{key:g,cert:l}}function Ae(e,t,n,r=!1,s=7){let a=w.generateKeypair("EC","secp256r1"),g=a.prvKeyObj,i=a.pubKeyObj,l=w.getPEM(g,"PKCS8PRV"),m=[],o=r?"dev-user":"localhost";for(let u of n)if(u.toLowerCase().startsWith("ip:"))m.push({ip:u.substring(3)});else if(u.toLowerCase().startsWith("email:"))m.push({rfc822:u.substring(6)});else{let S=u.toLowerCase().startsWith("dns:");if(r)o=S?u.substring(4):u;else{let x=S?u.substring(4):u;m.push({dns:x}),m.length===1&&(o=x)}}let p=[{extname:"basicConstraints",cA:!1},{extname:"keyUsage",critical:!0,names:["digitalSignature","keyEncipherment"]},{extname:"extKeyUsage",array:[r?"clientAuth":"serverAuth"]}];m.length>0&&p.push({extname:"subjectAltName",array:m});let h=new z.asn1.x509.Certificate({version:3,serial:{hex:Q()},issuer:{str:t},subject:{str:`/CN=${o}/O=${P}/OU=${N}`},notbefore:$(new Date(Date.now()-60*1e3),!1,!1),notafter:$(new Date(Date.now()+s*24*60*60*1e3),!1,!1),sbjpubkey:i,ext:p,sigalg:"SHA256withECDSA",cakey:e}).getPEM();return{key:l,cert:h}}var ne={};b(ne,{buildSea:()=>ve});import{access as re,copyFile as Se,readdir as xe,readFile as j,writeFile as ee}from"node:fs/promises";import{execFile as Ee}from"node:child_process";import{promisify as $e}from"node:util";import{createHash as Ne}from"node:crypto";import{basename as Pe,resolve as A}from"node:path";var y=$e(Ee);function R(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}async function ve(e,t){let n=t?.outDir??"./build",r=t?.config?.executable??process.execPath,s=R(e),a=R(t?.version??""),g=R(n.replace(/\\/g,"/")),{stdout:i}=await y(r,["-e",` const { mkdirSync } = require('node:fs'); const path = require('node:path'); const appVersion = '${a}'.trim(); const dirName = '${s}' + (appVersion ? '-v' + appVersion : '') + '.' + process.platform + '-' + process.arch; const dir = path.resolve('${g}', dirName); mkdirSync(dir, { recursive: true }); process.stdout.write(JSON.stringify({ dirName, nodeVersion: process.version, platform: process.platform, arch: process.arch })); `.trim()]),{dirName:l,nodeVersion:m,platform:o,arch:p}=JSON.parse(i),d;if(t?.esbuild){let c;try{c=await import("esbuild")}catch{throw new Error(`esbuild is required to bundle the entry point. Install it with: npm install --save-dev esbuild `)}d=`${n}/${e}.js`,await c.build({format:"cjs",target:"node20",platform:"node",bundle:!0,external:["esbuild","postject"],loader:{".md":"file",".d.ts":"file"},assetNames:`${l}/[name]`,entryNames:"[name]",outdir:n,minify:!0,logLevel:"info",...t.esbuild})}else if(t?.config?.main)d=A(t.config.main);else throw new Error("Either esbuild options (with entryPoints) or config.main must be provided.");let h=A(`${n}/${e}.sea.node-${m}-${o}-${p}.blob`),u=A(`${n}/${e}.sea-config.${l}.json`),S={disableExperimentalSEAWarning:!0,useSnapshot:!1,useCodeCache:!1,...t?.config,main:A(d),output:h};await ee(u,JSON.stringify(S,null,2));let x=A(n,l),v=o==="win32",O=o==="darwin",se=v?`${e}.exe`:e,f=`${x}/${se}`,oe=await j(d),U=`${n}/${Pe(d)}.sha`,K=Ne("sha256").update(oe).digest("hex"),_=!1;try{let[c]=await Promise.all([j(U,"utf8"),re(f)]);_=c===K}catch{}if(_)return console.log("SEA build skipped - esbuild output unchanged and target exists"),f;if(await y(r,["--experimental-sea-config",u]),await Se(r,f),v)try{let c=await te();c&&(console.log(`Found signtool at: ${c}`),await y(c,["remove","/s",f]),console.log(`Signature removed from ${f} executable`))}catch(c){console.warn("Failed to remove signature:",c.message)}else if(O)try{await y("codesign",["--remove-signature",f]),console.log(`Signature removed from ${f} executable`)}catch(c){console.warn("Failed to remove signature:",c.message)}let T;try{({inject:T}=await import("postject"))}catch{throw new Error(`postject is required to build a SEA. Install it with: npm install --save-dev postject `)}let ae=await j(h),ie=["NODE","SEA","FUSE","fce680ab2cc467b6e072b8b5df1996b2"].join("_");if(await T(f,"NODE_SEA_BLOB",ae,{overwrite:!0,sentinelFuse:ie,...O?{machoSegmentName:"NODE_SEA"}:{}}),v)try{let c=await te();c&&(console.log(`Signing executable with signtool at: ${c}`),await y(c,["sign","/fd","SHA256",f]),console.log("Executable signed successfully"))}catch(c){console.warn("Failed to sign executable:",c.message)}else if(O)try{await y("codesign",["--sign","-",f]),console.log("Executable signed successfully")}catch(c){console.warn("Failed to sign executable:",c.message)}return await ee(U,K),f}async function te(){let e="C:\\Program Files (x86)\\Windows Kits\\10\\bin";try{let n=(await xe(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&/^10\.0\.\d+\.\d+$/.test(r.name)).map(r=>r.name).sort((r,s)=>{let a=r.split(".").map(Number),g=s.split(".").map(Number);for(let i=0;i<a.length;i++)if(a[i]!==g[i])return g[i]-a[i];return 0});for(let r of n){let s=`${e}\\${r}\\${process.arch}\\signtool.exe`;try{return await re(s),s}catch{}}return console.warn("signtool.exe not found in any Windows SDK version"),null}catch(t){return console.warn(`Windows SDK not found at ${e}: ${t.message}`),null}}export{q as argon2,ne as build,H as keygen,Y as manage,Z as mkcert}; //# sourceMappingURL=tools.js.map