3 lines
18 KiB
JavaScript
3 lines
18 KiB
JavaScript
import{aes as e,cryptico as t,RSAKey as s}from"@daotl/cryptico";import{buildAxiosFetch as i}from"@lifeomic/axios-fetch";import r from"axios";import{sm2 as a}from"sm-crypto";function n(s,i){const r=i.slice(0);e.ExpandKey(r);let a=t.string2bytes(s);a=t.pad16(a),e.Encrypt(a,r);let n=t.bytes2string(a);return n=t.b256to64(n),n}function o(e,t){const i=new s;return i.setPublic(t.n,t.e1),i.encrypt(e)}function c(e){const i=t.b64to256(e).split(","),r=new s;return r.setPrivate(i[0],i[0],i[0]),r}function h(e,s){const i={key:t.generateAESKey()},r=JSON.stringify(i),{contractID:a}=e,o={...e,contractID:void 0};return{action:s.decrypt(r),contractID:a,arg:n(JSON.stringify(o),i.key),requester:t.b256to64(`${s.n.toString(16)},${s.e.toString(16)},0`)}}const u=e=>Object.entries(e).map((([e,t])=>`${e}=${String(t)}`)).join("&");class l{baseUrl;sm2Key;fetch;constructor(e,t,s={}){this.baseUrl=e,this.sm2Key=t;const a=r.create({baseURL:"https://some-domain.com/api/",timeout:1e4,...s});this.fetch=i(a)}async requestWithSignature(e,t,s){return new Promise(((i,r)=>{const a=this.baseUrl+e,n=`${a}${e.includes("?")?"&":"?"}pubKey=${s?.publicKey??this.sm2Key.publicKey}`,o=this.sign(n.substring(n.indexOf("?")+1),s?.privateKey);this.fetch("post"===t?.method?.toLowerCase()?a:`${encodeURI(n)}&sign=${o}`,{...t,..."POST"===t?.method?{body:{...t?.body,sign:o}}:{}}).then((async e=>{const t=e;t.data=await e.text(),setTimeout((()=>{i(t)}),1)})).catch((e=>{setTimeout((()=>{r(e)}),1)}))}))}async retryRequestWithSignature(e,t,s,i){let r=new Error;for(let a=0;a<e;a++)try{return await this.requestWithSignature(t,s,i)}catch(t){if(a<e){console.log("1");continue}r=t}throw r}sign(e,t){return a.doSignature(e,t??this.sm2Key.privateKey,{hash:!0,der:!0})}ping(){return this.requestWithSignature("/SCManager?action=ping")}startContract(e){const t={action:"startContract",script:e};return this.requestWithSignature(`/SCManager?${u(t)}`)}startContractByYPK(e){return this.requestWithSignature(`/SCManager?${u({action:"startContractByYPK",...e,owner:this.sm2Key.publicKey,aim:"onStartContract",signature:a.doSignature(`Fixed|${e.path}|${this.sm2Key.publicKey}`,this.sm2Key.privateKey,{hash:!0,der:!0})})}`)}executeContract(e,t,s,{method:i="POST",withDynamicAnalysis:r=!1,withSignature:a=!1}={}){let n={};return n=void 0===r?{action:"executeContract",contractID:e,operation:t,arg:s}:{action:"executeContract",contractID:e,operation:t,withDynamicAnalysis:r,arg:s},a&&(n={...n,pubkey:this.sm2Key.publicKey,signature:this.sign(`${e}|${t}|${s??""}|${this.sm2Key.publicKey}`)}),this.retryRequestWithSignature(3,"/SCManager"+("GET"===i?`?${u(n)}`:""),{method:i,..."POST"===i?{body:n}:{}})}killContractProcess(e,t){const s={action:"killContractProcess",id:e};return t&&(s.requestID=t),this.requestWithSignature(`/SCManager?${u(s)}`)}killAllContract(){return this.requestWithSignature("/SCManager?action=killAllContract")}applyNodeRole(e){const t={action:"applyNodeRole",role:e};return this.requestWithSignature(`/SCManager?${u(t)}`)}authNodeRole(e,t,s){const i={action:"authNodeRole",isAccept:e,authorizedPubKey:t};return this.requestWithSignature(`/SCManager?${u(i)}`,void 0,s)}distributeContract(e,t,s){const i=a.doSignature(`DistributeContract|${t}|${this.sm2Key.publicKey}`,this.sm2Key.privateKey,{hash:!0,der:!0}),r=`/SCManager?${u({action:"distributeContract",nodeIDs:e,projectName:t,isPrivate:s,signature:i})}`,n=`${this.baseUrl+r}${r.includes("?")?"&":"?"}pubKey=${this.sm2Key.publicKey}`,o=a.doSignature(n.substring(n.indexOf("?")+1),this.sm2Key.privateKey,{hash:!0,der:!0});new EventSource(`${this.baseUrl}${r}&pubKey=${this.sm2Key.publicKey}&sign=${o}`).addEventListener("message",(function(e){}),!1)}saveFile(e){return this.requestWithSignature(`/SCManager?${u({action:"saveFile",...e})}`)}listProjectPermission(e){return this.requestWithSignature(`/SCManager?${u({action:"listProjectPermission",...e})}`)}startContractMultiPoint(e,t,s,i,r,a){const n={peersID:e,type:t,selectUnitNum:s,projectName:i,isPrivate:r,sponsorPeerID:a};return this.requestWithSignature(`/SCManager?${u({action:"startContractMultiPoint",...n})}`)}async loadNodeConfig(){const e=await this.requestWithSignature(`/SCManager?${u({action:"loadNodeConfig"})}`);return{...e,data:200===e.status&&e.data?JSON.parse(e.data).data:{}}}async updateConfig(e,t){return this.requestWithSignature(`/SCManager?${u({action:"updateConfig",key:e,val:t})}`)}async resetNodeManager(){const e=await this.requestWithSignature(`/SCManager?${u({action:"resetNodeManager"})}`);if(!e.data)return!1;return"success"===JSON.parse(e.data).data}lockEdit(){return this.requestWithSignature(`/SCManager?${u({action:"lockEdit"})}`)}unlockEdit(){return this.requestWithSignature(`/SCManager?${u({action:"unlockEdit"})}`)}addNode(e){return this.requestWithSignature(`?${u({action:"addNode",nodePubKey:e})}`)}applyRole(e){return this.requestWithSignature(`?${u({action:"applyRole",role:e})}`)}authNodeManager(e,t){return this.requestWithSignature(`?${u({action:"authNodeManager",isAccept:e,authorizedPubKey:t})}`)}listAllUsers(){return this.requestWithSignature(`?${u({action:"listAllUsers"})}`)}listNodes(){return this.requestWithSignature(`?${u({action:"listNodes"})}`)}async createTrustUnit(e,t){const s=`action=createTrustUnit&data=${JSON.stringify(e)}&msg=${t}&pubKey=04303718771b9323c204e607639f14469f9a94e55b0964a408ad3b3864b0493b645d7070da0d550f0c54b934275a8e88dedc3024467b0566db5c1108b1baeaae27`,i={action:"createTrustUnit",data:e,msg:t,pubKey:"04303718771b9323c204e607639f14469f9a94e55b0964a408ad3b3864b0493b645d7070da0d550f0c54b934275a8e88dedc3024467b0566db5c1108b1baeaae27",sign:a.doSignature(s,this.sm2Key.privateKey,{hash:!0,der:!0})};return await this.requestWithSignature("",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}listTrustUnits(){return this.requestWithSignature(`?${u({action:"listTrustUnits"})}`)}listContractProcess(){return this.requestWithSignature(`/SCManager?${u({action:"listContractProcess"})}`)}downloadContract(e,t,s){const i={action:"downloadContract",projectName:e,isPrivate:t,timestamp:s};return this.requestWithSignature(`/CMManager?${u(i)}`)}async configNode(e){if(!await this.resetNodeManager())return!1;const t=Object.entries(e).filter((([e,t])=>t));await Promise.all([...t.map((([e,t])=>this.updateConfig(e,t))),this.applyNodeRole("ContractProvider"),this.applyNodeRole("ContractUser"),this.applyNodeRole("ContractInstanceManager"),this.authNodeRole(!0,this.sm2Key.publicKey)]);const s=(await this.loadNodeConfig()).data;return!!s&&t.every((([e,t])=>s[function(e){if("dataChain"===e)return"bdledger";return e}(e)]===t))}}class d{handlerList=[];toSend="";isSending=!1;sendList=[];toReceive="";wssocket;constructor(e,t,s){console.log(`[createWS.js] createWssocket : ${e}`),s&&this.handlerList.push(s),this.monitor();const i=this,r=this.wssocket=new WebSocket(e);r.onerror=function(e){console.log(e)},r.onopen=t;const a=function(e){const t=JSON.parse(e.data);switch(t.action){case"sendNextSegment":i.sendNextSegment();break;case"sendSeg":i.receiveSeg(t);break;default:i.handlerList.forEach((t=>t(e,this)))}};r.onmessage=a;const n=function(){setTimeout((()=>{console.log("[createWS.js] try to reconnect");const s=i.wssocket=new WebSocket(e);s.onclose=n,s.onmessage=a,s.onopen=t}),1e3)};r.onclose=n}status(){return this.wssocket.readyState}sendNextSegment(){const e=this.toSend;if(e.length>1024){this.toSend=e.substr(1024);const t={isSegment:!0,data:e.substr(0,1024)};this.wssocket.send(JSON.stringify(t))}else{this.toSend="";const t={isSegment:!1,data:e};let s;this.wssocket.send(JSON.stringify(t)),this.isSending=!1,(s=this.sendList.pop())&&this.send(s)}}receiveSeg(e){if("start"===e.cid&&(this.toReceive=""),this.toReceive+=e.data,"done"===e.cid){console.log(`[receiveSeg] Received AllData:${this.toReceive}`);const e={data:this.toReceive};this.toReceive="",this.handlerList.forEach((t=>t(e,this.wssocket)))}}monitor(){if(!this.isSending){let e;(e=this.sendList.pop())&&this.send(e)}setTimeout((()=>this.monitor()),1e3)}send(e){if(this.isSending)this.sendList.push(e);else if(e.length>1024){this.isSending=!0,this.toSend=e.substr(1024);const t={isSegment:!0,data:e.substr(0,1024)};this.wssocket.send(JSON.stringify(t))}else this.wssocket.send(e)}addHandler(e){this.handlerList.push(e)}}class g{sm2Key;wssocket;promiseCallbackPairs={};sessionPromise;sessionResolve;loginPromise;loginResolve;constructor(e,t,s,i=a.generateKeyPairHex()){this.sm2Key=i,this.sessionPromise=new Promise(((e,t)=>{this.sessionResolve=e})),this.loginPromise=new Promise(((e,t)=>{this.loginResolve=e}));const r=this;this.wssocket=new d(e,t,(function(e,t){const i=JSON.parse(e.data);switch(i.action){case"onSessionID":r.sessionResolve(i.session);break;case"onLogin":{const e="string"==typeof i.status&&i.status.toLowerCase().includes("failed");r.loginResolve(!e)}}const a=i.responseID;let n;a&&(n=r.promiseCallbackPairs[a])&&(i?n.resolve(i):n.reject(i)),s(e,this)}))}status(){return this.wssocket.status()}sessionReceived(){return this.sessionPromise}async login(){const e=await this.sessionPromise,t={action:"login",pubKey:this.sm2Key.publicKey,signature:a.doSignature(e,this.sm2Key.privateKey,{hash:!0,der:!0})};return this.wssocket.send(JSON.stringify(t)),this.loginPromise}loggedIn(){return this.loginPromise}matchCID(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"matchCID",contractID:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}getMetabyCID(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"getMetabyCID",contractID:e,requestID:t};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}getMetabyReadme(e,t,s){const i=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,r={action:"getMetabyReadme",page:t,pageSize:s,keyword:e,requestID:i};return this.wssocket.send(JSON.stringify(r)),new Promise(((e,t)=>{this.promiseCallbackPairs[i]={resolve:e,reject:t}}))}getMetabyPubkey(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"getMetabyPubkey",pubkey:e,requestID:t};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}segmentWord(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={words:e,action:"segmentWord",requestID:t};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}getMetabyOwner(e,t,s){const i=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,r={action:"getMetabyOwner",owner:e,page:t,pageSize:s,requestID:i};return this.wssocket.send(JSON.stringify(r)),new Promise(((e,t)=>{this.promiseCallbackPairs[i]={resolve:e,reject:t}}))}getDependentContract(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"getDependentContract",requestID:t,contractName:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}queryContractLogByDate(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"queryContractLogByDate",requestID:t,start:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}queryDataByHash(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"queryDataByHash",requestID:t,hash:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}executeContract(e,t,s){const i=this.sm2Key,r=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,n="object"==typeof s?JSON.stringify(s):s+"",o={action:"executeContract",requestID:r,contractID:e,operation:t,arg:s,...i?{pubkey:i.publicKey,signature:a.doSignature(`${e}|${t}|${n}|${i.publicKey}`,i.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(o)),new Promise(((e,t)=>{this.promiseCallbackPairs[r]={resolve:e,reject:t}}))}getSessionID(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"getSessionID",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}listTheContractProcess(e){const t=this.sm2Key,s=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,i={action:"listTheContractProcess",requestID:s,contractID:e,...t?{pubkey:t.publicKey,signature:a.doSignature(`${e}|${t.publicKey}`,t.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(i)),new Promise(((e,t)=>{this.promiseCallbackPairs[s]={resolve:e,reject:t}}))}getMask(e){const t=this.sm2Key,s=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,i={action:"getMask",requestID:s,contractID:e,...t?{pubkey:t.publicKey,signature:a.doSignature(`${e}|${t.publicKey}`,t.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(i)),new Promise(((e,t)=>{this.promiseCallbackPairs[s]={resolve:e,reject:t}}))}setMask(e,t,s){const i=this.sm2Key,r=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,n={action:"setMask",requestID:r,contractID:e,operation:t,arg:s,...i?{pubkey:i.publicKey,signature:a.doSignature(`${e}|${i.publicKey}`,i.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(n)),new Promise(((e,t)=>{this.promiseCallbackPairs[r]={resolve:e,reject:t}}))}getMock(e){const t=this.sm2Key,s=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,i={action:"getMock",requestID:s,contractID:e,...t?{pubkey:t.publicKey,signature:a.doSignature(`${e}|${t.publicKey}`,t.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(i)),new Promise(((e,t)=>{this.promiseCallbackPairs[s]={resolve:e,reject:t}}))}setMock(e,t,s){const i=this.sm2Key,r=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,n={action:"setMock",requestID:r,contractID:e,operation:t,arg:s,...i?{pubkey:i.publicKey,signature:a.doSignature(`${e}|${i.publicKey}`,i.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(n)),new Promise(((e,t)=>{this.promiseCallbackPairs[r]={resolve:e,reject:t}}))}queryHashByOffset(e,t){const s=this.sm2Key,i=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,r={action:"queryHashByOffset",requestID:i,offset:e,count:t,...s?{pubkey:s.publicKey}:{}};return this.wssocket.send(JSON.stringify(r)),new Promise(((e,t)=>{this.promiseCallbackPairs[i]={resolve:e,reject:t}}))}loadNodeConfig(){const e=this.sm2Key,t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"loadNodeConfig",requestID:t,...e?{pubkey:e.publicKey,signature:a.doSignature(e.publicKey,e.privateKey,{hash:!0,der:!0})}:{}};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}queryUserStat(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"queryUserStat",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}listNodes(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"listNodes",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}killContractProcess(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"killContractProcess",requestID:t,id:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}distributeYPK(e,t){const s=this.sm2Key,i=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,r={action:"distributeYPK",requestID:i,pubKey:s.publicKey,projectName:e,nodeIDs:t,signature:a.doSignature(`DistributeYPK|${e}|${s.publicKey}`,s.privateKey,{hash:!0,der:!0})};return this.wssocket.send(JSON.stringify(r)),new Promise(((e,t)=>{this.promiseCallbackPairs[i]={resolve:e,reject:t}}))}listYPKs(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"listYPKs",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}deleteFile(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"deleteFile",requestID:t,file:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}startContractByYPK(e){const t=this.sm2Key,s=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,i={action:"startContractByYPK",isPrivate:!0,requestID:s,owner:t.publicKey,path:`/${e}`,signature:a.doSignature(`Fixed|${e}|${t.publicKey}`,t.privateKey)};return this.wssocket.send(JSON.stringify(i)),new Promise(((e,t)=>{this.promiseCallbackPairs[s]={resolve:e,reject:t}}))}initBDServer(e,t,s,i,r){const a=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,n={action:"initBDServer",requestID:a,host:e,username:t,password:s,name:i,sm2Key:JSON.stringify(this.sm2Key),clusterHost:r};return this.wssocket.send(JSON.stringify(n)),new Promise(((e,t)=>{this.promiseCallbackPairs[a]={resolve:e,reject:t}}))}initBDCluster(e,t,s,i,r,a){const n=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,o={action:"initBDCluster",requestID:n,host:e,username:t,password:s,name:i,sm2Key:r,agents:a};return this.wssocket.send(JSON.stringify(o)),new Promise(((e,t)=>{this.promiseCallbackPairs[n]={resolve:e,reject:t}}))}listCompiledFiles(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"listCompiledFiles",requestID:e,isPrivate:!0};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}getManagerPubkey(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"getManagerPubkey",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}getClusterName(){const e=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,t={action:"getClusterName",requestID:e};return this.wssocket.send(JSON.stringify(t)),new Promise(((t,s)=>{this.promiseCallbackPairs[e]={resolve:t,reject:s}}))}setClusterName(e){const t=`${(new Date).getTime()}_${Math.floor(1e4*Math.random())}`,s={action:"setClusterName",requestID:t,name:e};return this.wssocket.send(JSON.stringify(s)),new Promise(((e,s)=>{this.promiseCallbackPairs[t]={resolve:e,reject:s}}))}}export{l as HttpClient,g as WsClient,d as WsSocket,n as aesEncrypt,h as encryptReq,c as loadRSAKey,o as rsaEncrypt};
|
|
//# sourceMappingURL=index.mjs.map
|