UNPKG

@ycmd/creds

Version:

LSK.js CLI Creds is the easiest way to manage GitHub / Gitlab secrets and credentials

11 lines (9 loc) 8.41 kB
import { Err } from '@lsk4/err'; import { createLogger } from '@lsk4/log'; import _ from 'axios'; import E from 'libsodium-wrappers'; import { map } from 'fishbird'; var N=Object.defineProperty;var h=(a,e)=>N(a,"name",{value:e,configurable:!0}),v=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var w=class{static{h(this,"Service");}client;log=createLogger(this.constructor.name);constructor(e){this.assign(e),this.checkConfig(),this.client=this.createClient(e.clientOptions);}createClient(e={}){return _.create(e)}assign(e){Object.assign(this,e);}checkConfig(){throw new Err("NOT_IMPLEMENTED","checkConfig method not implemented")}getServiceHostname(){throw new Err("NOT_IMPLEMENTED","getServiceHostname method not implemented")}getProjectUrl(){throw new Err("NOT_IMPLEMENTED","getProjectUrl method not implemented")}getProjectCICDSettingURL(){throw new Err("NOT_IMPLEMENTED","getProjectCICDSettingURL method not implemented")}getProjectPath(){let e=this.projectPath;if(!e)throw new Err("!projectPath");return e}getProjectId(){return this.projectId}getProjectCredsUrl(){let e=this.projectCredsUrl;if(!e)throw new Err("!projectCredsUrl");return e}getProjectCredsOwner(){let e=this.projectCredsOwner;if(!e)throw new Err("!projectCredsOwner");return e}async uploadSecret(e,t){throw new Err("NOT_IMPLEMENTED","uploadSecret method not implemented")}async uploadVariable(e,t){throw new Err("NOT_IMPLEMENTED","uploadVariable method not implemented")}async removeOldHooks(){}async uploadHook(e){}async uploadHooks(e){if(!e)throw new Err("!env");let{hooks:t=[]}=e;try{await this.removeOldHooks();}catch(r){this.log.error("[ERR] Old hooks removing failed:",Err.getMessage(r));}await map(t,async(r,s)=>{try{await this.uploadHook(r),this.log.info(`[OK] Hook ${s} uploaded`);}catch(o){this.log.error(`[ERR] Hook ${s} not uploaded:`,Err.getMessage(o));}});}async uploadAll(e){if(!e)throw new Err("!env");let{secrets:t={},variables:r={},files:s=[]}=e;await this.uploadHooks(e),await map(Object.entries(t),async([o,i])=>{try{await this.uploadSecret(o,i),this.log.info(`[OK] Secret ${o} uploaded`);}catch(n){this.log.error(`[ERR] Secret ${o} not uploaded as secret, because`,Err.getMessage(n)),this.log.trace(n);}}),await map(Object.entries(r),async([o,i])=>{try{await this.uploadVariable(o,i),this.log.info(`[OK] Variable ${o} uploaded`);}catch(n){this.log.error(`[ERR] Variable ${o} not uploaded as variable, because`,Err.getMessage(n)),this.log.trace(n);}}),await map(Object.values(s),async({name:o,credType:i,content:n})=>{let l=o,j=n;try{if(i==="variable")await this.uploadVariable(l,j);else if(i==="secret")await this.uploadSecret(l,j);else if(i==="skip"){this.log.debug(`[SKIP] File ${l} uploaded as ${i}`);return}else throw new Err("unknown credType",{credType:i});this.log.info(`[OK] File ${l} uploaded as ${i}`);}catch(m){this.log.error(`[ERR] File ${l} not uploaded as ${i}, because`,Err.getMessage(m)),this.log.trace(m);}});}};var C=class extends w{static{h(this,"GithubService");}projectName;projectPath;projectCredsUrl;projectCredsOwner;token;server;log=createLogger(this.constructor.name);constructor(e){super(e),this.assign(e),this.checkConfig(),this.client=this.createClient(e.clientOptions);}checkConfig(){if(!this.projectName)throw new Err("!projectName");if(!this.projectPath)throw new Err("!projectPath");if(!this.projectCredsUrl)throw new Err("!projectCredsUrl");if(!this.projectCredsOwner)throw new Err("!projectCredsOwner");if(!this.token)throw new Err("!token")}createClient(e={}){let r=`https://${this.server||"api.github.com"}/repos/${this.getProjectPath()}`;return _.create({baseURL:r,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28"},...e})}getServiceHostname(){return "github.com"}getProjectPath(){return this.projectPath}getProjectUrl(){return `https://${this.getServiceHostname()}/${this.getProjectPath()}`}getProjectCICDSettingURL(){return `${this.getProjectUrl()}/settings/secrets/actions`}async uploadSecret(e,t){let{data:r}=await this.client({method:"get",url:"/actions/secrets/public-key"}).catch(m=>{throw new Err(m.message,{data:m?.response?.data})}),s=typeof t=="string"?t:t.value;if(!r?.key)throw new Err("!publicKey");if(!r?.key_id)throw new Err("!publicKeyId");await E.ready;let o=E,i=o.from_base64(r.key,o.base64_variants.ORIGINAL),n=o.from_string(s),l=o.crypto_box_seal(n,i),j=o.to_base64(l,o.base64_variants.ORIGINAL);await this.client({method:"put",url:`/actions/secrets/${e}`,data:{encrypted_value:j,key_id:r.key_id}});}async uploadVariable(e,t){let r=typeof t=="string"?t:t.value,{data:s,status:o}=await this.client({method:"get",url:`/actions/variables/${e}`}).catch(i=>i?.response);o===404&&await this.client({method:"post",url:"/actions/variables",data:{name:e,value:r}}),o===200&&s.name.toLowerCase()===e.toLowerCase()&&await this.client({method:"patch",url:`/actions/variables/${e}`,data:{name:e,value:r}});}uploadHook(){throw new Err("Github hooks not supported yet")}};var O=!0,k=class extends w{static{h(this,"GitlabService");}projectId;projectName;projectPath;projectCredsUrl;projectCredsOwner;token;server;force=!0;log=createLogger(this.constructor.name);constructor(e){super(e),this.assign(e),this.checkConfig(),this.client=this.createClient(e.clientOptions);}checkConfig(){if(!this.projectId)throw new Err("!projectId");if(!this.server)throw new Err("!server");if(!this.projectName)throw new Err("!projectName");if(!this.projectPath)throw new Err("!projectPath");if(!this.projectCredsUrl)throw new Err("!projectCredsUrl");if(!this.projectCredsOwner)throw new Err("!projectCredsOwner");if(!this.token)throw new Err("!token")}createClient(e={}){return _.create({baseURL:`https://${this.server}/api/v4/projects/${this.projectId}`,headers:{"PRIVATE-TOKEN":this.token},...e})}getServiceHostname(){return this.server}getProjectUrl(){return `https://${this.getServiceHostname()}/${this.projectPath}`}getProjectCICDSettingURL(){return `${this.getProjectUrl()}/-/settings/ci_cd`}async uploadVariableOrSecret(e,t,r={}){let s=typeof t=="string"?t:t.value,o=t?.type||r?.type||"file",i=!!(t?.protected??r?.protected??!1),{data:n}=await this.client({method:"get",url:`/variables/${e}`}).catch(l=>{return {data:{value:"@lskjs/creds"}}});if(n.value&&n.value.indexOf("@lskjs/creds")===-1&&!O){this.log.warn(`[IGNORE] Project ${this.projectId} ${e}`);return}await this.client({method:"delete",url:`/variables/${e}`}).catch(()=>{}),await this.client({method:"post",url:"/variables",data:{key:e,value:s,variable_type:o,protected:i,...r}});}async uploadSecret(e,t,r={}){return this.uploadVariableOrSecret(e,t,{type:"file",protected:!!(r.protected??!0)})}async uploadVariable(e,t,r={}){return this.uploadVariableOrSecret(e,t,{type:"env_var",protected:!!(r.protected??!1)})}async uploadEnv(){throw this.log.warn("GitLab uploading env doesn't supported"),new Err("NOT_IMPLEMENTED")}async removeOldHooks(){let{data:e}=await this.client({method:"get",url:"/hooks"}).catch(t=>{return {data:{value:"@lskjs/creds"}}});await map(e,async({id:t})=>{await this.client({method:"delete",url:`/hooks/${t}`});});}async uploadHook(e){await this.client({method:"post",url:"/hooks",data:e});}};async function b(a,{removeCache:e}={}){try{let t=v(a);return e&&delete v.cache[v.resolve(a)],t}catch(t){if(Err.getCode(t)==="MODULE_NOT_FOUND")throw new Err(`${a} not found`,t);if(Err.getCode(t).startsWith("Dynamic require of")||Err.getCode(t).startsWith("ReferenceError: module is not defined in ES module scope"))try{return await import(a)}catch(s){throw Err.getCode(s)==="ERR_MODULE_NOT_FOUND"?new Err(`${a} not found`,s):new Err("importErr",s)}throw new Err("requireErr",t)}}h(b,"importRequire");async function P(a){let e=`${a}/config.js`,t=await b(e);return {path:e,config:t.default||t}}h(P,"loadConfig");async function je(a,e={}){let{path:t,config:r}=await P(a),s=r.service?.serviceName;if(!s)throw new Err("!serviceName",{data:{configPath:t}});let o,i={...r.service,...e,config:r};if(s==="github")o=new C(i);else if(s==="gitlab")o=new k(i);else throw new Err("incorrect serviceName",{serviceName:s});return o}h(je,"createService"); export { je as createService }; //# sourceMappingURL=out.js.map //# sourceMappingURL=createService.js.map