UNPKG

@iotize/tap

Version:

IoTize Device client for Javascript

16 lines (14 loc) 28 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@iotize/tap"),require("@iotize/tap/service/impl/group"),require("@iotize/common/error"),require("@iotize/tap/client/api"),require("rxjs"),require("@iotize/tap/service/impl/interface"),require("@iotize/common/debug"),require("@iotize/common/byte-converter"),require("@iotize/tap/crypto"),require("@iotize/common/crypto"),require("@iotize/common/utility"),require("@iotize/tap/client/impl"),require("@iotize/tap/service/impl/scram"),require("rxjs/operators"),require("@iotize/common/byte-stream")):"function"==typeof define&&define.amd?define("@iotize/tap/auth",["exports","@iotize/tap","@iotize/tap/service/impl/group","@iotize/common/error","@iotize/tap/client/api","rxjs","@iotize/tap/service/impl/interface","@iotize/common/debug","@iotize/common/byte-converter","@iotize/tap/crypto","@iotize/common/crypto","@iotize/common/utility","@iotize/tap/client/impl","@iotize/tap/service/impl/scram","rxjs/operators","@iotize/common/byte-stream"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).iotize=e.iotize||{},e.iotize.tap=e.iotize.tap||{},e.iotize.tap.auth={}),e.iotize.tap,e.iotize.tap.service.impl.group,e.error,e.iotize.tap.client.api,e.rxjs,e.iotize.tap.service.impl.interface,e.debug$1,e.byteConverter,e.iotize.tap.crypto,e.crypto$1,e.utility,e.iotize.tap.client.impl,e.iotize.tap.service.impl.scram,e.rxjs.operators,e.byteStream)}(this,(function(e,t,r,n,i,o,s,a,c,u,p,h,l,f,y,d){"use strict"; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */var v=function(e,t){return v=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},v(e,t)};function E(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}v(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function m(e,t){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){s.label=o[1];break}if(6===o[0]&&s.label<i[1]){s.label=i[1],i=o;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(o);break}i[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],n=0}finally{r=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,a])}}}Object.create;function _(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s}Object.create;var g=a.createDebugger("@iotize/tap/auth"),S={groupId:0,lifeTime:-1,name:"anonymous",startTime:void 0,profileId:0,profileName:"anonymous"};function b(e){return c.hexStringToBuffer(u.passwordHasher.hash(e).substring(0,32))}function w(e,t){if(e.length!==t.length)throw new Error("Length does not match between the two array. Cannot compute XOR");for(var r=new Uint8Array(e.length),n=0;n<r.length;n++)r[n]=e[n]^t[n];return r}var I=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},C="BasicAuth",T=function(){function e(e,t){void 0===t&&(t={hashPassword:!1}),this.tap=e,this.options=t}return Object.defineProperty(e.prototype,"hashPassword",{get:function(){var e;return(null===(e=this.options)||void 0===e?void 0:e.hashPassword)||!1},enumerable:!1,configurable:!0}),e.prototype.login=function(e){return I(this,void 0,void 0,(function(){var t,r,n;return m(this,(function(i){switch(i.label){case 0:return t=e.username,r=e.password,this.hashPassword?(g(C,"Using hash password login"),[4,this.tap.service.interface.loginWithHash({username:t,password:b(r)})]):[3,2];case 1:return n=i.sent(),[3,4];case 2:return g(C,"Using regular login"),[4,this.tap.service.interface.login({username:t,password:r})];case 3:n=i.sent(),i.label=4;case 4:return n.successful(),[2,{}]}}))}))},e.prototype.logout=function(){return I(this,void 0,void 0,(function(){return m(this,(function(e){switch(e.label){case 0:return[4,this.tap.service.interface.logout()];case 1:return e.sent().successful(),[2]}}))}))},e.prototype.changePassword=function(e,t){return I(this,void 0,void 0,(function(){var r;return m(this,(function(n){switch(n.label){case 0:return this.hashPassword?(r=b(e),[4,this.tap.service.group.changePasswordKey(t,r)]):[3,2];case 1:return n.sent().successful(),[3,4];case 2:return[4,this.tap.service.group.changePassword(t,e)];case 3:n.sent().successful(),n.label=4;case 4:return[2]}}))}))},e}(),A=function(e){function r(t,r,n){var i=e.call(this,t,r,void 0)||this;return i.request=n,i}return E(r,e),r.scramNotStartedYet=function(e){return new r(t.TapError.Code.ScramNotStartedYet,"SCRAM session has not been initialized yet. You cannot use secure communication.",e)},r.invalidScramKey=function(e){return new r(t.TapError.Code.InvalidScramKey,"SCRAM session key is not valid.",e)},r}(t.TapError),R=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},N="00000000000000000000000000000000",P="ScramInterceptor";function z(e){return e?c.bufferToHexString(e):""}var K=function(){function e(e){var t=this;this.scramService=e,this._ivFrameCounter=0,this._ivSupported=!0,this._options={encryption:!1,initializationVectorResetPeriod:100,keys:{},frameCounter:0},this._encryptedFrameConverter=new l.CryptedFrameConverter({next:function(){return t._options.frameCounter++}}),this.initializationVectorGenerator=function(e){var t=new Array(e).fill(0).map((function(e){return Math.floor(255*Math.random())}));return Uint8Array.from(t)}}return Object.defineProperty(e.prototype,"encryptionAlgo",{get:function(){if(!this._encryptionAlgo)throw l.TapClientError.illegalStateError("Encryption algo has not been set yet");return this._encryptionAlgo},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ivSupported",{set:function(e){this._ivSupported=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionKey",{get:function(){return this._options.keys.sessionKey},set:function(e){this._options.keys.sessionKey=e,this._options.frameCounter=0,this._options.keys.sessionKey?this.refreshEncryptionAlgo():this.pauseEncryption()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return h.deepCopy(this._options)},enumerable:!1,configurable:!0}),e.prototype.setEncryptionKeys=function(e){this._options.keys=e,this.refreshEncryptionAlgo()},e.prototype.getEncryptionKeys=function(){return this._options.keys},e.prototype.setFrameCounter=function(e){this._options.frameCounter=e},e.prototype.setInitializationVectorRefreshPeriod=function(e){this._options.initializationVectorResetPeriod=e},e.prototype.intercept=function(e,t){var r=e.request;return g(P,"exec "+l.TapRequestHelper.toString(r)+" (encryption:"+this._options.encryption+", frameCounter: "+this._options.frameCounter+" - skip "+e.skipEncryption+", key: "+z(this.sessionKey)+" iv decode: "+z(this._options.keys.ivDecode)+", iv encode: "+z(this._options.keys.ivEncode)+")"),(this._options.encryption&&!e.skipEncryption?this._sendWithEncryption(e,t).pipe(y.map((function(e){var t=e.rawBody();return{status:e.status,data:t}}))):t.handle(e)).pipe(y.tap((function(e){g(P,"Response to "+l.TapRequestHelper.toString(r)+" => "+e.status+" "+c.bufferToHexString(e.data))})))},e.prototype._sendWithEncryption=function(e,r){var n,s,a,c=this;if(!this._encryptedFrameConverter)return o.throwError(l.TapClientError.illegalStateError("Encrypted frame converter has not been specified yet"));if(1===this._options.initializationVectorResetPeriod){s=this.initializationVectorGenerator(16),this._setEncodeIV(s),g(P,"Changing initialization vector for every requests. New client IV: "+z(s));var u=this._buildEncryptedFrame(e),p=this.scramService.sendWithIVCall({request:u,iv:s});n=this._toCallObservable(Object.assign(Object.assign({},e),{skipEncryption:!0}),r,p).pipe(y.map((function(e){var r=e.body();return g(P,"Refreshing decoding initialization vector: "+z(r.iv)),c._setDecodeIV(r.iv),t.TapResponse.create(e.status,r.response)})))}else if(this._options.initializationVectorResetPeriod>1&&this._ivFrameCounter>=this._options.initializationVectorResetPeriod&&(a=e.request,l.TapRequestHelper.pathToString(a.header.path)!==O.resources.setInitializationVector.path))g(P,"_ivInterceptor refreshEncryptionInitializationVector is required "+this._ivFrameCounter+"/"+this._options.initializationVectorResetPeriod),this._refreshingInitializationVectorObs||(this._refreshingInitializationVectorObs=o.defer((function(){return R(c,void 0,void 0,(function(){return m(this,(function(e){switch(e.label){case 0:return e.trys.push([0,,2,3]),[4,this.refreshInitializationVectors()];case 1:return[2,e.sent()];case 2:return this._refreshingInitializationVectorObs=void 0,[7];case 3:return[2]}}))}))})).pipe(y.shareReplay({bufferSize:1,refCount:!0}))),n=this._refreshingInitializationVectorObs.pipe(y.mergeMap((function(t){var n=c._buildEncryptedFrame(e);return c._toCallObservable(e,r,c.scramService.sendCall(n))})));else{var h=this._buildEncryptedFrame(e);p=this.scramService.sendCall(h);n=this._toCallObservable(e,r,p)}return n.pipe(y.map((function(r){if(c._ivFrameCounter++,!r.isSuccessful()){if(r.codeRet()===i.ResultCode.SERVICE_UNAVAILABLE)throw A.scramNotStartedYet(e.request);if(r.codeRet()===i.ResultCode.BAD_REQUEST)throw A.invalidScramKey(e.request);r.successful()}var n=c.encryptionAlgo.decode(r.rawBody()),o=c._encryptedFrameConverter.decode(n),s=e.client.responseDecoder.decode(o),a=new t.TapResponse(s,e.request);return e.bodyDecoder&&a.setBodyDecoder(e.bodyDecoder),a})))},e.prototype._buildEncryptedFrame=function(e){var t=l.TapStreamWriter.create(10+e.request.payload.length).writeTapRequestFrame(e.request).toBytes,r=this._encryptedFrameConverter.encode(t);return this.encryptionAlgo.encode(r)},e.prototype._setEncodeIV=function(e){this._options.keys.ivEncode=e,this.refreshEncryptionAlgo()},e.prototype._setDecodeIV=function(e){this._options.keys.ivDecode=e,this.refreshEncryptionAlgo()},e.prototype._toCallObservable=function(e,r,n){var i=t.ServiceCallRunner.toTapRequest(n),o=t.ServiceCallRunner.resolveResponseBodyDecoder(n),s=o?{decode:o}:void 0;return r.handle(Object.assign(Object.assign({},e),{request:i,bodyDecoder:s})).pipe(y.map((function(r){return new t.TapResponse(r,e.request,s)})))},e.prototype.refreshInitializationVectors=function(){return R(this,void 0,void 0,(function(){var e,r,n,o;return m(this,(function(s){switch(s.label){case 0:e=this.initializationVectorGenerator(16),s.label=1;case 1:return s.trys.push([1,3,,4]),g(P,"Performing initialization vector refresh"),[4,this.scramService.setInitializationVector(e)];case 2:return r=s.sent().body(),this._options.keys.ivEncode=e,this._options.keys.ivDecode=r,this._ivFrameCounter=0,g(P,"Initialization vector refreshed: server "+z(r)+" client="+z(e)+")"),this.refreshEncryptionAlgo(),[3,4];case 3:if(n=s.sent(),g(P,"Cannot refresh initialization vector: "+n.message),n instanceof t.TapResponseStatusError&&((o=n.response.status)===i.ResultCode.NOT_IMPLEMENTED||o===i.ResultCode.NOT_FOUND))throw g(P,"Cannot initialize encryption vectors (firmware version does not support it). Error: "+n.message),this._ivSupported=!1,t.TapError.initializationVectorNotSupported(n);throw n;case 4:return[2]}}))}))},e.prototype.resumeEncryption=function(){g(P,"resume encryption"),this._options.encryption=!0},e.prototype.pauseEncryption=function(){g(P,"pause encryption"),this._options.encryption=!1},e.prototype.newSession=function(){return R(this,void 0,void 0,(function(){var e,r,n,i;return m(this,(function(o){switch(o.label){case 0:return o.trys.push([0,6,,7]),g(P,"Creating new encryption session"),this.clearSession(),[4,this.scramService.initialize()];case 1:if((e=o.sent()).successful(),r=e.body(),this.sessionKey=r,g(P,"Session key will be "+z(r)+" (length="+r.length+")"),!(this._options.initializationVectorResetPeriod>0))return[3,5];o.label=2;case 2:return o.trys.push([2,4,,5]),[4,this.refreshInitializationVectors()];case 3:return o.sent(),[3,5];case 4:if((n=o.sent()).code!==t.TapError.Code.InitializationVectorNotSupported)throw n;return[3,5];case 5:return[2,r];case 6:throw i=o.sent(),t.TapError.cannotStartScram(i);case 7:return[2]}}))}))},e.prototype.clearSession=function(){this.pauseEncryption(),this._options.keys.ivDecode=void 0,this._options.keys.ivEncode=void 0,this._options.keys.sessionKey=void 0,this._ivFrameCounter=0},e.prototype.refreshEncryptionAlgo=function(){if(this._options.keys.sessionKey){var e=new p.AesEcb128Converter({key:z(this._options.keys.sessionKey),ivDecode:this._options.keys.ivDecode?z(this._options.keys.ivDecode):N,ivEncode:this._options.keys.ivEncode?z(this._options.keys.ivEncode):N});this._encryptionAlgo=e}},e}(),O=new f.ScramService(void 0);var L=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},x=function(){function e(e){var t=this;this.tap=e,this.scramInterceptor=new K(this.tap.service.scram),this.tap.client.addInterceptor(this.scramInterceptor),this.tap.events.subscribe((function(e){if("tap-logout"===e.type)t.stop()}))}return Object.defineProperty(e.prototype,"isStarted",{get:function(){return this.scramInterceptor.options.encryption},enumerable:!1,configurable:!0}),e.prototype.setEncryptionKeys=function(e){this.scramInterceptor.setEncryptionKeys(e)},e.prototype.setEncryptedFrameCounter=function(e){this.scramInterceptor.setFrameCounter(e)},e.prototype.getEncryptionOptions=function(){return this.scramInterceptor.options},e.prototype.refreshEncryptionInitializationVector=function(){return this.scramInterceptor.refreshInitializationVectors()},e.prototype.setInitializationVectorRefreshPeriod=function(e){return this.scramInterceptor.setInitializationVectorRefreshPeriod(e)},e.prototype.start=function(){return L(this,void 0,void 0,(function(){var e;return m(this,(function(t){switch(t.label){case 0:return[4,this.scramInterceptor.newSession()];case 1:return e=t.sent(),this.scramInterceptor.resumeEncryption(),[2,e]}}))}))},e.prototype.stop=function(){this.scramInterceptor.clearSession()},e.prototype.pause=function(){this.scramInterceptor.pauseEncryption()},e.prototype.resume=function(){this.scramInterceptor.resumeEncryption()},Object.defineProperty(e.prototype,"sessionKey",{get:function(){return this.scramInterceptor.sessionKey},set:function(e){this.scramInterceptor.sessionKey=e},enumerable:!1,configurable:!0}),e}(),V=t.defineTapPropertyExtension("encryption",(function(e){return new x(e.tap)}));e.TapAuthError=function(e){function t(t,r,n){var i=e.call(this,r,t)||this;return i.cause=n,i}return E(t,e),t.tapRequestError=function(e,r){return new t(t.Code.TapRequestError,"Login failed. "+r.message,r)},t.tooManyLoginFailedError=function(e,r){return new t(t.Code.TooManyLoginAttempt,"Login failed due to too many login attempt. You must wait before trying to login again.",r)},t.invalidCredentialsError=function(e,r){return new t(t.Code.InvalidCredentials,"Login failed. Given username or password is not valid.",r)},t}(n.CodeError),function(e){var t;!function(e){e.InvalidServerProof="TapAuthErrorInvalidServerProof",e.ScramDisabled="TapAuthErrorScramDisabled",e.InvalidCredentials="TapAuthErrorInvalidCredentials",e.TooManyLoginAttempt="TapAuthErrorTooManyLoginAttempt",e.TapRequestError="TapAuthErrorTapRequestError"}(t=e.Code||(e.Code={}));var r=function(e){function r(r,n){var i=e.call(this,t.InvalidServerProof,"Login fail invalid server proof ('"+c.bufferToHexString(r)+"' != '"+c.bufferToHexString(n)+"') ")||this;return i.deviceServerProof=r,i.expectedServerProof=n,i}return E(r,e),r}(e);e.InvalidServerKey=r}(e.TapAuthError||(e.TapAuthError={}));var q=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},k="Scram";function B(){var e=new Array(j.USER_SALT_SIZE).fill(0).map((function(e){return Math.floor(255*Math.random())}));return 0===e[0]&&(e[0]=1),Uint8Array.from(e)}var j=function(){function r(e){this.tap=e,this.nonceGenerator=function(){return Math.floor(4294967295*Math.random())},this.saltGenerator=B}return r.prototype.changePassword=function(e,t,n){return void 0===n&&(n=this.saltGenerator()),q(this,void 0,void 0,(function(){var i,o,s;return m(this,(function(a){switch(a.label){case 0:return o={},[4,this.tap.service.scram.getHashIteration()];case 1:return o.iterationNumber=a.sent().body(),o.salt=n,i=o,s=r.createScramPasswordKey(e,i),g(k,"Changing password key: "+c.bufferToHexString(s)+" salt="+c.bufferToHexString(n)+"; iteration="+i.iterationNumber+' for user id "'+t+'"'),[4,this.tap.service.group.changePasswordKey(t,s)];case 2:return a.sent().successful(),[2]}}))}))},r.prototype.login=function(t){return q(this,void 0,void 0,(function(){var n,i,o,s,a,u,p,h;return m(this,(function(l){switch(l.label){case 0:return n=this.generateNonce(),g(k,"clientNonce",n),i={username:t.username,clientNonce:n},[4,this.tap.service.scram.login(i)];case 1:return o=l.sent().body(),s=r.computeKeys(t,o,n),(a={}).storedKey=s.storedKey,a.serverKey=s.serverKey,u=o.serverNonce,[4,this.tap.service.scram.loginProof(s.clientProof)];case 2:if(p=l.sent().body(),h=s.serverProof,c.bufferToHexString(h)!==c.bufferToHexString(p))throw new e.TapAuthError.InvalidServerKey(h,p);return a.clientNonce=n,a.key=r.computeSessionKey(n,u,o.salt,s.serverKey,s.storedKey),[2,a]}}))}))},r.createScramPasswordKey=function(e,t){var n=r.computeBaseKeys(e,t),i=new Uint8Array(t.salt),o=d.KaitaiStreamWriter.create(r.SCRAM_PASSWORD_LENGTH);return o.writeBytes(n.storedKey,r.KEY_SIZE).writeBytes(n.serverKey,r.KEY_SIZE).writeBytes(i,r.USER_SALT_SIZE),o.toBytes},r.computeBaseKeys=function(e,t){var n=b(e),i=r.saltedPassword(n,t.salt,t.iterationNumber),o=r.storedKey(i);g(k,"storeKey",c.bufferToHexString(o));var s=r.serverKey(i);return g(k,"serverKey",c.bufferToHexString(s)),{hashedPassword:n,saltedPassword:i,storedKey:o,serverKey:s}},r.computeKeys=function(e,t,n){var i=r.computeBaseKeys(e.password,t),o=r.clientProof(i.storedKey,n,t.serverNonce),s=r.serverProof(i.serverKey,n,t.serverNonce);return Object.assign(Object.assign({},i),{clientProof:o,serverProof:s})},r.prototype.logout=function(){return q(this,void 0,void 0,(function(){var e;return m(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,this.tap.service.interface.logout()];case 1:return r.sent().successful(),this.tap.encryption.stop(),[3,3];case 2:if(e=r.sent(),n.isCodeError(t.TapError.Code.ScramNotStartedYet,e)||n.isCodeError(t.TapError.Code.InvalidScramKey,e))return this.tap.encryption.stop(),[2];throw e;case 3:return[2]}}))}))},r.clientProof=function(e,t,n){return r.computeProof(e,t,n).subarray(0,r.KEY_SIZE)},r.serverProof=function(e,t,n){return r.computeProof(e,n,t).subarray(0,r.KEY_SIZE)},r.prototype.generateNonce=function(){return this.nonceGenerator()},r.saltedPassword=function(e,t,r){return u.pbkdf2(e,t,r)},r.storedKey=function(e){return r.HASH(e,r.CLIENT_KEY_LABEL,r.CLIENT_KEY_ITERATION_NUMBER)},r.serverKey=function(e){return r.HASH(e,r.SERVER_KEY_LABEL,r.SERVER_KEY_ITERATION_NUMBER)},r.HASH=function(e,t,n){return u.pbkdf2(e,t,n,r.KEY_SIZE/4)},r.computeProof=function(e,t,n){var i=d.KaitaiStreamWriter.create(e.length+r.CLIENT_NONCE_SIZE+r.SERVER_NONCE_SIZE);return i.writeU(t,r.CLIENT_NONCE_SIZE).writeBytes(e).writeU(n,r.SERVER_NONCE_SIZE),u.hmacSHA256(i.toBytes,e)},r.clientProofCheck=function(e,t){return w(e,t)},r.computeSessionKey=function(e,t,n,i,o){r.encodeLabel(r.COMMUNICATION_KEY_LABEL);var s=d.KaitaiStreamWriter.create(r.CLIENT_NONCE_SIZE+r.SERVER_NONCE_SIZE+n.length+i.length+o.length);return s.writeU(e,r.CLIENT_NONCE_SIZE).writeBytes(i).writeBytes(n).writeBytes(o).writeU(t,r.SERVER_NONCE_SIZE),u.hmacSHA256(s.toBytes,i).subarray(0,r.KEY_SIZE)},r.encodeLabel=function(e){return this.stringConverter.encode(e)},r}();j.CRC_LENGTH=4,j.CLIENT_NONCE_SIZE=4,j.SERVER_NONCE_SIZE=4,j.ITERATION_NUMBER_SIZE=4,j.COMMUNICATION_KEY_LABEL="CommunicationKey",j.CLIENT_KEY_LABEL="ClientKey",j.SERVER_KEY_LABEL="ServerKey",j.KEY_SIZE=16,j.CLIENT_KEY_ITERATION_NUMBER=2,j.SERVER_KEY_ITERATION_NUMBER=2,j.USER_SALT_SIZE=4,j.SCRAM_PASSWORD_LENGTH=2*j.KEY_SIZE+j.USER_SALT_SIZE,j.stringConverter=l.StringConverter.ascii();var D=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},M="TapAuth",H=function(){function r(e){this.tap=e,this._sessionState=new o.BehaviorSubject(S),this._sessionData=new o.BehaviorSubject({})}return Object.defineProperty(r.prototype,"sessionStateSnapshot",{get:function(){return this._sessionState.value},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"sessionState",{get:function(){return this._sessionState.asObservable()},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"sessionDataSnapshot",{get:function(){return this._sessionData.value},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"sessionData",{get:function(){return this._sessionData.asObservable()},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"service",{get:function(){return this.tap.service},enumerable:!1,configurable:!0}),r.prototype.setAuthMethod=function(e){this._auth=e},r.prototype.clearCache=function(){this._auth=void 0},r.prototype.login=function(r,o){return D(this,void 0,void 0,(function(){var s,a,c,u;return m(this,(function(p){switch(p.label){case 0:return g(M,"Tap login as "+r.username+"..."),[4,this.setupTapAuthEngineIfRequired()];case 1:s=p.sent(),p.label=2;case 2:return p.trys.push([2,6,,7]),[4,s.login(r)];case 3:return(a=p.sent())&&a.key&&(this.tap.encryption.sessionKey=a.key,this.tap.encryption.resume()),this._sessionData.next(a),(null==o?void 0:o.noRefreshSessionState)?[3,5]:[4,this.refreshSessionState({username:r.username})];case 4:p.sent(),p.label=5;case 5:return c={type:"tap-login"},this.tap.notifyEvent(c),[2,a];case 6:if(u=p.sent(),n.isCodeError(t.TapError.Code.ResponseStatusError,u)){if(u.response.status===i.ResultCode.NOT_ACCEPTABLE||u.response.status===i.ResultCode.UNAUTHORIZED)throw e.TapAuthError.invalidCredentialsError(r,u);if(u.response.status===i.ResultCode.SERVICE_UNAVAILABLE)throw e.TapAuthError.tooManyLoginFailedError(r,u)}throw e.TapAuthError.tapRequestError(r,u);case 7:return[2]}}))}))},r.prototype.logout=function(){return D(this,void 0,void 0,(function(){var e;return m(this,(function(t){switch(t.label){case 0:return g(M,"Tap logout..."),[4,this.setupTapAuthEngineIfRequired()];case 1:return[4,t.sent().logout()];case 2:return t.sent(),this._sessionState.next(S),this._sessionData.next({}),e={type:"tap-logout"},this.tap.notifyEvent(e),[2]}}))}))},r.prototype.refreshSessionState=function(e){return D(this,void 0,void 0,(function(){var t,r,n,i,o,s,a,c,u,p;return m(this,(function(h){switch(h.label){case 0:return g(M,"[TAP]","Refreshing session state (current="+this.sessionStateSnapshot.name+")..."),[4,this.service.interface.executeMultipleCalls([this.service.interface.getCurrentGroupIdCall(),this.service.interface.getCurrentProfileIdCall()])];case 1:return t=_.apply(void 0,[h.sent(),2]),r=t[0],n=t[1],i=r.body(),o=n.body(),i===this.sessionStateSnapshot.groupId?[3,3]:((s=Object.assign({},this.sessionStateSnapshot)).groupId=i,s.profileId=o,[4,this.service.interface.executeMultipleCalls([this.service.group.getSessionLifetimeCall(i),this.service.group.getNameCall(i),this.service.group.getNameCall(o)])]);case 2:return a=_.apply(void 0,[h.sent(),3]),c=a[0],u=a[1],p=a[2],s.name=(null==e?void 0:e.username)||u.body(),s.profileName=p.body(),s.lifeTime=c.body(),g(M,"[TAP]","Notifying new session state: "+s.name),this._sessionState.next(s),[3,4];case 3:g(M,"[TAP]","Session state did not changed: "+this.sessionStateSnapshot.name+" (id="+i+")"),h.label=4;case 4:return[2,this.sessionStateSnapshot]}}))}))},r.prototype.changePassword=function(e,t){return D(this,void 0,void 0,(function(){var r,n;return m(this,(function(i){switch(i.label){case 0:return void 0!==t?[3,2]:[4,this.service.interface.getCurrentGroupId()];case 1:return r=i.sent().body(),[3,3];case 2:r=t,i.label=3;case 3:return[4,this.setupTapAuthEngineIfRequired()];case 4:return[4,i.sent().changePassword(e,r)];case 5:return i.sent(),n={type:"tap-user-password-change",user:{id:r}},this.tap.notifyEvent(n),[2]}}))}))},r.prototype.setupTapAuthEngineIfRequired=function(){return D(this,void 0,void 0,(function(){var e;return m(this,(function(t){switch(t.label){case 0:return this._auth?[3,2]:(e=this,[4,this.setupTapAuthEngine()]);case 1:e._auth=t.sent(),t.label=2;case 2:return[2,this._auth]}}))}))},r.prototype.setupTapAuthEngine=function(){return D(this,void 0,void 0,(function(){var e;return m(this,(function(t){switch(t.label){case 0:return[4,this.service.interface.getSecurityOptions()];case 1:return e=t.sent().body(),g(M,"securityOptions "+JSON.stringify(e)),e.scramActivated?(g(M,"Setup with ScramAuth"),[2,new j(this.tap)]):(g(M,"Setup with BasicAuth"),[2,new T(this.tap,{hashPassword:e.hashPassword})])}}))}))},r}(),U=t.defineTapPropertyExtension("auth",(function(e){return new H(e.tap)}));e.BasicAuth=T,e.DEFAULT_SCRAM_SALT_GENERATOR=B,e.INITIAL_SESSION_STATE=S,e.ScramAuth=j,e.TapAuth=H,e.TapScramError=A,e._TAP_EXTENSION_AUTH_=U,e._TAP_EXTENSION_ENCRYPTION_=V,e.hashLoginPassword=b,e["ɵa"]=16,e["ɵb"]=w,Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=iotize-tap-auth.umd.min.js.map