fa-toolkit
Version:
a devtool for fast app
1 lines • 16.3 kB
JavaScript
"use strict";function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _regeneratorRuntime(){_regeneratorRuntime=function(){return a};var a={},e=Object.prototype,u=e.hasOwnProperty,c=Object.defineProperty||function(e,t,r){e[t]=r.value},t="function"==typeof Symbol?Symbol:{},n=t.iterator||"@@iterator",r=t.asyncIterator||"@@asyncIterator",i=t.toStringTag||"@@toStringTag";function o(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{o({},"")}catch(e){o=function(e,t,r){return e[t]=r}}function s(e,t,r,n){var i,o,a,s,t=t&&t.prototype instanceof p?t:p,t=Object.create(t.prototype),n=new _(n||[]);return c(t,"_invoke",{value:(i=e,o=r,a=n,s="suspendedStart",function(e,t){if("executing"===s)throw new Error("Generator is already running");if("completed"===s){if("throw"===e)throw t;return E()}for(a.method=e,a.arg=t;;){var r=a.delegate;if(r){var n=function e(t,r){var n=r.method,i=t.iterator[n];if(void 0===i)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=void 0,e(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;i=f(i,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var i=i.arg;return i?i.done?(r[t.resultName]=i.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=void 0),r.delegate=null,g):i:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}(r,a);if(n){if(n===g)continue;return n}}if("next"===a.method)a.sent=a._sent=a.arg;else if("throw"===a.method){if("suspendedStart"===s)throw s="completed",a.arg;a.dispatchException(a.arg)}else"return"===a.method&&a.abrupt("return",a.arg);s="executing";n=f(i,o,a);if("normal"===n.type){if(s=a.done?"completed":"suspendedYield",n.arg===g)continue;return{value:n.arg,done:a.done}}"throw"===n.type&&(s="completed",a.method="throw",a.arg=n.arg)}})}),t}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}a.wrap=s;var g={};function p(){}function l(){}function h(){}var d={};o(d,n,function(){return this});t=Object.getPrototypeOf,t=t&&t(t(b([])));t&&t!==e&&u.call(t,n)&&(d=t);var y=h.prototype=p.prototype=Object.create(d);function v(e){["next","throw","return"].forEach(function(t){o(e,t,function(e){return this._invoke(t,e)})})}function S(a,s){var t;c(this,"_invoke",{value:function(r,n){function e(){return new s(function(e,t){!function t(e,r,n,i){e=f(a[e],a,r);if("throw"!==e.type){var o=e.arg,r=o.value;return r&&"object"==_typeof(r)&&u.call(r,"__await")?s.resolve(r.__await).then(function(e){t("next",e,n,i)},function(e){t("throw",e,n,i)}):s.resolve(r).then(function(e){o.value=e,n(o)},function(e){return t("throw",e,n,i)})}i(e.arg)}(r,n,e,t)})}return t=t?t.then(e,e):e()}})}function m(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function w(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function _(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(m,this),this.reset(!0)}function b(t){if(t){var e=t[n];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,e=function e(){for(;++r<t.length;)if(u.call(t,r))return e.value=t[r],e.done=!1,e;return e.value=void 0,e.done=!0,e};return e.next=e}}return{next:E}}function E(){return{value:void 0,done:!0}}return c(y,"constructor",{value:l.prototype=h,configurable:!0}),c(h,"constructor",{value:l,configurable:!0}),l.displayName=o(h,i,"GeneratorFunction"),a.isGeneratorFunction=function(e){e="function"==typeof e&&e.constructor;return!!e&&(e===l||"GeneratorFunction"===(e.displayName||e.name))},a.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,h):(e.__proto__=h,o(e,i,"GeneratorFunction")),e.prototype=Object.create(y),e},a.awrap=function(e){return{__await:e}},v(S.prototype),o(S.prototype,r,function(){return this}),a.AsyncIterator=S,a.async=function(e,t,r,n,i){void 0===i&&(i=Promise);var o=new S(s(e,t,r,n),i);return a.isGeneratorFunction(t)?o:o.next().then(function(e){return e.done?e.value:o.next()})},v(y),o(y,i,"Generator"),o(y,n,function(){return this}),o(y,"toString",function(){return"[object Generator]"}),a.keys=function(e){var t,r=Object(e),n=[];for(t in r)n.push(t);return n.reverse(),function e(){for(;n.length;){var t=n.pop();if(t in r)return e.value=t,e.done=!1,e}return e.done=!0,e}},a.values=b,_.prototype={constructor:_,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(w),!e)for(var t in this)"t"===t.charAt(0)&&u.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(r){if(this.done)throw r;var n=this;function e(e,t){return o.type="throw",o.arg=r,n.next=e,t&&(n.method="next",n.arg=void 0),!!t}for(var t=this.tryEntries.length-1;0<=t;--t){var i=this.tryEntries[t],o=i.completion;if("root"===i.tryLoc)return e("end");if(i.tryLoc<=this.prev){var a=u.call(i,"catchLoc"),s=u.call(i,"finallyLoc");if(a&&s){if(this.prev<i.catchLoc)return e(i.catchLoc,!0);if(this.prev<i.finallyLoc)return e(i.finallyLoc)}else if(a){if(this.prev<i.catchLoc)return e(i.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return e(i.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;0<=r;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&u.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var i=n;break}}var o=(i=i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc?null:i)?i.completion:{};return o.type=e,o.arg=t,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(o)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),g},finish:function(e){for(var t=this.tryEntries.length-1;0<=t;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),w(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;0<=t;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n,i=r.completion;return"throw"===i.type&&(n=i.arg,w(r)),n}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:b(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),g}},a}function asyncGeneratorStep(e,t,r,n,i,o,a){try{var s=e[o](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,i)}function _asyncToGenerator(s){return function(){var e=this,a=arguments;return new Promise(function(t,r){var n=s.apply(e,a);function i(e){asyncGeneratorStep(n,t,r,i,o,"next",e)}function o(e){asyncGeneratorStep(n,t,r,i,o,"throw",e)}i(void 0)})}}var path=require("path"),fs=require("fs"),crypto=require("crypto"),JsZip=require("jszip"),sign=require("./bundle"),jsrsasign=require("jsrsasign"),signature=require("./signature"),zipUtils=require("./zip-utils"),bundle=require("./bundle"),dssSignUtils=require("./dss-sign-utils"),CONSTANTS=require("./constants"),DIGEST_PATH="META-INF/CERT",DIGEST_JSON="hash.json",COMPRESS_OPTS={type:"nodebuffer",compression:"DEFLATE",compressionOptions:{level:9}};function generatePkgDef(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:[],r=[];return e.forEach(function(e){var t=e.resource,e=e.name;r.push({pkgName:"".concat(e,".srpk"),fileList:[],root:t})}),{mainPkg:{pkgName:"rpk",fileList:[]},subPkgs:e.length?[{pkgName:"base.srpk",fileList:[]}].concat(r):[]}}function addResourceToPkg(e,i,o,a){e.forEach(function(t){var r,e=fs.readFileSync(path.join(i,t)),n=[t,e,sign.getBufferSha256(e)];addResource.apply(void 0,[o].concat(n)),a.length&&(r=!0,a.slice(1).forEach(function(e){t.startsWith(e.root)&&(addResource.apply(void 0,[e].concat(n)),r=!1)}),r&&addResource.apply(void 0,[a[0]].concat(n)))})}function signZipResource(e,t){return _signZipResource.apply(this,arguments)}function _signZipResource(){return(_signZipResource=_asyncToGenerator(_regeneratorRuntime().mark(function e(t,r){var n,i,o;return _regeneratorRuntime().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n={},t.forEach(function(e){var t=e.fileBuildPath,e=e.fileContentDigest;return n[t]=e.toString("hex")}),(o=new JsZip).file(DIGEST_JSON,JSON.stringify({algorithm:"SHA-256",digests:n})),e.next=6,o.generateAsync(COMPRESS_OPTS);case 6:return i=e.sent,o={name:DIGEST_JSON,hash:sign.getBufferSha256(i)},e.next=10,sign.signZipResource(i,[o],r);case 10:return e.abrupt("return",e.sent);case 11:case"end":return e.stop()}},e)}))).apply(this,arguments)}function signPkgZip(e,t){return _signPkgZip.apply(this,arguments)}function _signPkgZip(){return(_signPkgZip=_asyncToGenerator(_regeneratorRuntime().mark(function e(t,r){var n,i,o,a;return _regeneratorRuntime().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.fileList,i=new JsZip,o=n.map(function(e){return{name:e.fileBuildPath,hash:e.fileContentDigest}}),e.next=5,signZipResource(n,r);case 5:return a=e.sent,i.file(DIGEST_PATH,a),o.unshift({name:DIGEST_PATH,hash:sign.getBufferSha256(a)}),a=Object.assign({},COMPRESS_OPTS),n.forEach(function(e){var t=e.fileBuildPath,e=e.fileContentBuffer;i.file(t,e)}),e.next=12,i.generateAsync(a);case 12:return a=e.sent,e.next=15,sign.signZipResource(a,o,r);case 15:return e.abrupt("return",e.sent);case 16:case"end":return e.stop()}},e)}))).apply(this,arguments)}function signPkgs(e,t,r,n){return _signPkgs.apply(this,arguments)}function _signPkgs(){return(_signPkgs=_asyncToGenerator(_regeneratorRuntime().mark(function e(r,t,n,i){var o,a,s,u,c,f;return _regeneratorRuntime().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,signPkgZip(n,t);case 2:if(o=e.sent,i.length){e.next=5;break}return e.abrupt("return",{rpkBuffer:o});case 5:return a=new JsZip,s=[],c=i.map(function(e){return signPkgZip(e,t)}),u=Object.assign({},COMPRESS_OPTS),e.next=12,Promise.all(c).catch(function(){new Error("ERROR: Rpk sign failed!")});case 12:return e.sent.forEach(function(e,t){t=i[t],t="".concat(r,".").concat(t.pkgName);e.length,a.file(t,e),s.push({name:t,hash:sign.getBufferSha256(e)})}),c="".concat(r,".").concat(n.pkgName),a.file(c,o),s.push({name:c,hash:sign.getBufferSha256(o)}),e.next=19,a.generateAsync(u);case 19:return f=e.sent,e.next=22,sign.signZipResource(f,s,t);case 22:return f=e.sent,e.abrupt("return",{rpksBuffer:f,rpkBuffer:o});case 24:case"end":return e.stop()}},e)}))).apply(this,arguments)}function signFullApk(e,t){return _signFullApk.apply(this,arguments)}function _signFullApk(){return(_signFullApk=_asyncToGenerator(_regeneratorRuntime().mark(function e(t,r){var n;return _regeneratorRuntime().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=fs.readFileSync(r),e.next=3,sign.signZipResource(n,[],t);case 3:return n=e.sent,e.abrupt("return",{apkBuffer:n});case 5:case"end":return e.stop()}},e)}))).apply(this,arguments)}function addResource(e,t,r,n){e.fileList.push({fileBuildPath:t,fileContentBuffer:r,fileContentDigest:n})}function parseDirDeep(e){return function r(n,i){var o=[],a=path.posix.join(n,i);return fs.readdirSync(a).forEach(function(e){var t=path.posix.join(a,e),e=path.posix.join(i,e);fs.statSync(t).isFile()?o.push(e):o=o.concat(r(n,e))}),o}(e,".")}function getResources(e){return parseDirDeep(e).filter(function(e){return e!==DIGEST_PATH})}function getCertTime(e){var t=e.match(/^(\d{2}|\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(|\.\d+)Z$/);if(t){var r,n,i,o,a=t[1],s=parseInt(a);return 2===a.length&&(50<=s&&s<100?s=1900+s:0<=s&&s<50&&(s=2e3+s)),r=parseInt(t[2])-1,n=parseInt(t[3]),i=parseInt(t[4]),o=parseInt(t[5]),e=parseInt(t[6]),a=0,""!==(t=t[7])&&(t=(t.substr(1)+"00").substr(0,3),a=parseInt(t)),Date.UTC(s,r,n,i,o,e,a)}throw new Error("Your certificate is Invalid.")}function checkValidity(e){var t=new jsrsasign.X509;t.readCertPEM(String(e));var r=getCertTime(t.getNotAfter()),e=getCertTime(t.getNotBefore()),t=Number(new Date);return{validityDays:Number(r-t)/864e5,isInvalid:0<Number(e)-t}}function getApkSignInfo(e){var t={signOnline:!1,onlineConfig:null},r=new jsrsasign.X509;r.readCertPEM(e.toString());var n=jsrsasign.KEYUTIL.getPEM(r.getPublicKey()),i=Buffer.from(signature.Base64.unarmor(e)),r=Buffer.alloc(i.length+4);return r.writeInt32LE(i.length,0),i.copy(r,4),t.cert={content:e,obj:{len:r.length,buffer:r},pemBuffer:Buffer.from(signature.Base64.unarmor(n))},t}function getSignInfo(e,t,r){return _getSignInfo.apply(this,arguments)}function _getSignInfo(){return(_getSignInfo=_asyncToGenerator(_regeneratorRuntime().mark(function e(t,r,n){var i,o,a,s,u,c=arguments;return _regeneratorRuntime().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(o={signOnline:null!=n,privateKey:r,onlineConfig:n},(i=3<c.length&&void 0!==c[3]?c[3]:{})&&i.dssHost&&i.dssKey)return e.next=5,dssSignUtils.generateCertificate(i);e.next=7;break;case 5:t=e.sent,o.type=i.signType&&"dss_v3"===i.signType?i.signType:"dss";case 7:return(u=new jsrsasign.X509).readCertPEM(t.toString()),a=jsrsasign.KEYUTIL.getPEM(u.getPublicKey()),s=Buffer.from(signature.Base64.unarmor(t)),(u=Buffer.alloc(s.length+4)).writeInt32LE(s.length,0),s.copy(u,4),o.cert={content:t,obj:{len:u.length,buffer:u},pemBuffer:Buffer.from(signature.Base64.unarmor(a))},e.abrupt("return",o);case 16:case"end":return e.stop()}},e)}))).apply(this,arguments)}function countFp(e){var t=new jsrsasign.X509;t.readCertPEM(e);t=t.getSignatureValueHex(),t=Buffer.from(t,"hex").toString("base64"),t=bundle.getBufferSha256(t);return Buffer.from(t).toString("hex")}function countSignatureDigest(e){e=Buffer.from(signature.Base64.unarmor(e)),e=bundle.getBufferSha256(e);return Buffer.from(e).toString("hex")}function verifyDigest(e,t,r){var n;switch(r.digestId){case CONSTANTS.CRYPT_TYPE_RSA_SHA256:n="RSA-SHA256";break;case CONSTANTS.CRYPT_TYPE_RSA_SHA512:n="RSA-SHA512";break;default:n=void 0}if(!n)return console.error("unknown algorithm!"),!1;var i=t.sections.footer.startIndex+zipUtils.EOCD_CENTRAL_DIR_OFFSET_FIELD_OFFSET;return e.writeInt32LE(t.sections.sign.previous,i),bundle.processChunk(e,t.sections.header,n),bundle.processChunk(e,t.sections.central,n),bundle.processChunk(e,t.sections.footer,n),0===bundle.getChunkDigest(t).compare(r.digest)}function getSignedZipCertFp(e){return getSignedZipSignObj(e).certFingerPrint}function getSignedZipSignObj(e){if(!e||!fs.existsSync(e))throw new Error("No rpk file : "+e);var t=fs.readFileSync(e);if(!zipUtils.checkZipBuffer(t))throw new Error("Get File Certificate Error!");var r=zipUtils.parserZip(t,!0);if(!r.sections.sign.tag)throw new Error("No sign block!");var n=bundle.getFullPackageSignBlock(t,r.sections.sign),e=bundle.getDigestAndCert(n);if(!e)throw new Error("Get Certificate error!");if(!verifySignature(t,n,e.certString))throw new Error("Verify signature error!");if(!verifyDigest(t,r,e))throw new Error("Verify digest error!");return{certFingerPrint:countFp(e.certString),signDigest:countSignatureDigest(e.certString)}}function verifySignature(e,t,r){var n,i=t.signatures.data[0],o=t.signDataBuffer.buffer;switch(i.id){case CONSTANTS.CRYPT_TYPE_RSA_SHA256:n="RSA-SHA256";break;case CONSTANTS.CRYPT_TYPE_RSA_SHA512:n="RSA-SHA512";break;default:n=void 0}if(!n)return console.error("unknown algorithm!"),!1;t=crypto.createVerify(n);return t.update(o),t.verify(r,i.buffer)}function getCertFp(e){if(fs.existsSync(e))return countFp(fs.readFileSync(e).toString());console.error("error : certificate.pem is not exist!")}exports.generatePkgDef=generatePkgDef,exports.addResourceToPkg=addResourceToPkg,exports.signPkgs=signPkgs,exports.DIGEST_PATH=DIGEST_PATH,exports.getResources=getResources,exports.checkValidity=checkValidity,exports.getSignInfo=getSignInfo,exports.getApkSignInfo=getApkSignInfo,exports.getSignedZipCertFp=getSignedZipCertFp,exports.getSignedZipSignObj=getSignedZipSignObj,exports.getCertFp=getCertFp,exports.countSignatureDigest=countSignatureDigest,exports.signFullApk=signFullApk;