UNPKG

@ycmd/creds

Version:

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

20 lines (19 loc) 11.5 kB
import { createCommand } from '@ycmd/run'; import { addCwd } from '@ycmd/utils'; import { relative } from 'node:path'; import { getComment, jsonToFile } from '@lsk4/stringify'; import { map, mapSeries } from 'fishbird'; import { unlink, mkdir, readdir } from 'fs/promises'; import { createLogger } from '@lsk4/log'; import { Err } from '@lsk4/err'; import G from 'axios'; import _ from 'libsodium-wrappers'; import { existsSync } from 'node:fs'; import { resolve } from 'path'; import { readFile } from 'node:fs/promises'; var A=Object.defineProperty;var n=(a,e)=>A(a,"name",{value:e,configurable:!0}),P=(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=createLogger("creds");var y=class{static{n(this,"Service");}client;log=createLogger(this.constructor.name);constructor(e){this.assign(e),this.checkConfig(),this.client=this.createClient(e.clientOptions);}createClient(e={}){return G.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(o){this.log.error("[ERR] Old hooks removing failed:",Err.getMessage(o));}await map(t,async(o,r)=>{try{await this.uploadHook(o),this.log.info(`[OK] Hook ${r} uploaded`);}catch(i){this.log.error(`[ERR] Hook ${r} not uploaded:`,Err.getMessage(i));}});}async uploadAll(e){if(!e)throw new Err("!env");let{secrets:t={},variables:o={},files:r=[]}=e;await this.uploadHooks(e),await map(Object.entries(t),async([i,s])=>{try{await this.uploadSecret(i,s),this.log.info(`[OK] Secret ${i} uploaded`);}catch(c){this.log.error(`[ERR] Secret ${i} not uploaded as secret, because`,Err.getMessage(c)),this.log.trace(c);}}),await map(Object.entries(o),async([i,s])=>{try{await this.uploadVariable(i,s),this.log.info(`[OK] Variable ${i} uploaded`);}catch(c){this.log.error(`[ERR] Variable ${i} not uploaded as variable, because`,Err.getMessage(c)),this.log.trace(c);}}),await map(Object.values(r),async({name:i,credType:s,content:c})=>{let l=i,f=c;try{if(s==="variable")await this.uploadVariable(l,f);else if(s==="secret")await this.uploadSecret(l,f);else if(s==="skip"){this.log.debug(`[SKIP] File ${l} uploaded as ${s}`);return}else throw new Err("unknown credType",{credType:s});this.log.info(`[OK] File ${l} uploaded as ${s}`);}catch(h){this.log.error(`[ERR] File ${l} not uploaded as ${s}, because`,Err.getMessage(h)),this.log.trace(h);}});}};var k=class extends y{static{n(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 o=`https://${this.server||"api.github.com"}/repos/${this.getProjectPath()}`;return G.create({baseURL:o,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:o}=await this.client({method:"get",url:"/actions/secrets/public-key"}).catch(h=>{throw new Err(h.message,{data:h?.response?.data})}),r=typeof t=="string"?t:t.value;if(!o?.key)throw new Err("!publicKey");if(!o?.key_id)throw new Err("!publicKeyId");await _.ready;let i=_,s=i.from_base64(o.key,i.base64_variants.ORIGINAL),c=i.from_string(r),l=i.crypto_box_seal(c,s),f=i.to_base64(l,i.base64_variants.ORIGINAL);await this.client({method:"put",url:`/actions/secrets/${e}`,data:{encrypted_value:f,key_id:o.key_id}});}async uploadVariable(e,t){let o=typeof t=="string"?t:t.value,{data:r,status:i}=await this.client({method:"get",url:`/actions/variables/${e}`}).catch(s=>s?.response);i===404&&await this.client({method:"post",url:"/actions/variables",data:{name:e,value:o}}),i===200&&r.name.toLowerCase()===e.toLowerCase()&&await this.client({method:"patch",url:`/actions/variables/${e}`,data:{name:e,value:o}});}uploadHook(){throw new Err("Github hooks not supported yet")}};var N=!0,E=class extends y{static{n(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 G.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,o={}){let r=typeof t=="string"?t:t.value,i=t?.type||o?.type||"file",s=!!(t?.protected??o?.protected??!1),{data:c}=await this.client({method:"get",url:`/variables/${e}`}).catch(l=>{return {data:{value:"@lskjs/creds"}}});if(c.value&&c.value.indexOf("@lskjs/creds")===-1&&!N){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:r,variable_type:i,protected:s,...o}});}async uploadSecret(e,t,o={}){return this.uploadVariableOrSecret(e,t,{type:"file",protected:!!(o.protected??!0)})}async uploadVariable(e,t,o={}){return this.uploadVariableOrSecret(e,t,{type:"env_var",protected:!!(o.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 R(a,{removeCache:e}={}){try{let t=P(a);return e&&delete P.cache[P.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(r){throw Err.getCode(r)==="ERR_MODULE_NOT_FOUND"?new Err(`${a} not found`,r):new Err("importErr",r)}throw new Err("requireErr",t)}}n(R,"importRequire");async function x(a){let e=`${a}/config.js`,t=await R(e);return {path:e,config:t.default||t}}n(x,"loadConfig");async function O(a,e={}){let{path:t,config:o}=await x(a),r=o.service?.serviceName;if(!r)throw new Err("!serviceName",{data:{configPath:t}});let i,s={...o.service,...e,config:o};if(r==="github")i=new k(s);else if(r==="gitlab")i=new E(s);else throw new Err("incorrect serviceName",{serviceName:r});return i}n(O,"createService");async function S(a,e={}){let t=e.log||w,o=e.buildDir||`${a}/build`,r=await O(a,e);await unlink(`${o}`).catch(()=>{}),await mkdir(o,{recursive:!0});let{config:i}=r,{files:s=[]}=i;await mapSeries(s,async c=>{let{filename:l,handler:f}=c,h=await f(c,i),{credType:v,name:C}=c,I=getComment({filename:l,values:[["File type",c.type],["Cred type",v],["Cred name",C],["Server",r.getServiceHostname()],["Project",r.getProjectPath()],["Project ID",r.getProjectId()],["Project Url",r.getProjectUrl()],["CI/CD Setting",r.getProjectCICDSettingURL()]],footer:r.getProjectCredsUrl()&&` Auto generated by ${r.getProjectCredsUrl()} If you want to change something, please contact admin repo: ${r.getProjectCredsOwner()}. `.trim()}),V=c.format||c.type,L=`${o}/${l}`,{status:B}=await jsonToFile(L,h,{format:V,compare:!e.force,comment:I}),F=relative(process.cwd(),L);t.info(`[${B}] ${r.getProjectPath()} (${C})[${v}] => ${F}`);});}n(S,"build");async function b(a){let e=await readdir(a,{withFileTypes:!0});return (await map(e,async o=>o.isDirectory()?[{name:o.name,dir:resolve(a),filename:resolve(a,o.name)},...await b(resolve(a,o.name))]:[])).flat()}n(b,"getDirs");async function H(a,e={}){let t=await b(a),o=(await map(t,async r=>{let{filename:i}=r;return await existsSync(`${i}/index.js`)?r:null})).filter(Boolean);return mapSeries(o,async({filename:r})=>{await S(r,e).catch(i=>{w.error(`Build error ${r}: `,Err.getMessage(i)),w.error(i);});})}n(H,"buildDeep");async function D(a,e){let t=e.buildDir||`${a}/build`,o=await O(a,e),{config:r}=o,{files:i=[],variables:s,secrets:c,hooks:l}=r,f=await map(i,async h=>{let{filename:v}=h,C=await readFile(`${t}/${v}`).then(I=>I.toString());return {...h,content:C}});await o.uploadAll({files:f,variables:s,secrets:c,hooks:l});}n(D,"upload");async function T(a,e={}){let t=await b(a),o=(await map(t,async r=>{let{filename:i}=r;return await existsSync(`${i}/index.js`)?r:null})).filter(Boolean);return mapSeries(o,async({filename:r})=>{await D(r,e).catch(i=>{w.error(`Build error ${r}: `,Err.getMessage(i)),w.error(i);});})}n(T,"uploadDeep");createCommand({command:"creds <dir> [--force] [--deep] [--build] [--upload]",builder:a=>a.options({build:{alias:["b"],describe:"build creds",type:"boolean",default:!0},upload:{alias:["u"],describe:"upload creds",type:"boolean",default:!1},recursive:{alias:["r"],describe:"find in subdirs",type:"boolean",default:!1},force:{alias:["f"],describe:"force to run",type:"boolean",default:!1}}),describe:"build and/or upload creds",async main({cwd:a,argv:e,log:t}){let o=e.dir||".",r=addCwd(o,{cwd:a}),{build:i,upload:s,recursive:c,force:l}=e;c?(i&&await H(r,{force:l,log:t}),s&&await T(r,{force:l,log:t})):(i&&await S(r,{force:l,log:t}),s&&await D(r,{force:l,log:t}));}}); //# sourceMappingURL=out.js.map //# sourceMappingURL=index.js.map