vaultwarden-alternativa-bit.../web-vault/js/app.min.js

1 line
240 KiB
JavaScript

angular.module("bit",["ui.router","ngMessages","angular-jwt","ui.bootstrap.showErrors","toastr","angulartics","angular-promise-polyfill","bit.directives","bit.filters","bit.services","bit.global","bit.accounts","bit.vault","bit.settings","bit.tools","bit.organization","bit.reports"]),angular.module("bit").constant("appSettings",{apiUri:"/api",identityUri:"/identity",iconsUri:"https://icons.bitwarden.com",stripeKey:"pk_live_bpN0P37nMxrMQkcaHXtAybJk",braintreeKey:"production_qfbsv8kc_njj2zjtyngtjmbjd",selfHosted:!1,version:"1.22.0",environment:"Production"}),angular.module("bit.accounts",["ui.bootstrap","ngCookies"]),angular.module("bit.directives",[]),angular.module("bit.filters",[]),angular.module("bit.global",[]),angular.module("bit.organization",["ui.bootstrap"]),angular.module("bit.reports",["toastr","ngSanitize"]),angular.module("bit.services",["ngResource","ngStorage","angular-jwt"]),angular.module("bit.settings",["ui.bootstrap","toastr"]),angular.module("bit.tools",["ui.bootstrap","toastr"]),angular.module("bit.vault",["ui.bootstrap","ngclipboard"]),angular.module("bit").factory("apiInterceptor",["$injector","$q","toastr","appSettings","utilsService",function(e,t,n,o,r){return{request:function(e){return e.url.indexOf(o.apiUri+"/")>-1&&(e.headers["Device-Type"]=r.getDeviceType()),e},response:function(o){return 401!==o.status&&403!==o.status||(e.get("authService").logOut(),e.get("$state").go("frontend.login.info").then(function(){n.warning("Your login session has expired.","Logged out")})),o||t.when(o)},responseError:function(o){return 401!==o.status&&403!==o.status||(e.get("authService").logOut(),e.get("$state").go("frontend.login.info").then(function(){n.warning("Your login session has expired.","Logged out")})),t.reject(o)}}}]),angular.module("bit").config(["$stateProvider","$urlRouterProvider","$httpProvider","jwtInterceptorProvider","jwtOptionsProvider","$uibTooltipProvider","toastrConfig","$locationProvider","$qProvider","appSettings",function(e,t,n,o,r,a,i,s,l,c){var u;angular.extend(c,window.bitwardenAppSettings),l.errorOnUnhandledRejections(!1),s.hashPrefix(""),o.tokenGetter=["options","tokenService","authService",function(e,t,n){if(-1!==e.url.indexOf(c.apiUri+"/")){if(u)return u;var o=t.getToken();if(o){if(!t.tokenNeedsRefresh(o))return o;var r=n.refreshAccessToken();if(r)return u=r.then(function(e){return u=null,e||o})}}}],angular.extend(i,{closeButton:!0,progressBar:!0,showMethod:"slideDown",target:".toast-target"}),a.options({popupDelay:600,appendToBody:!0}),(-1!==navigator.userAgent.indexOf("MSIE")||navigator.appVersion.indexOf("Trident/")>0)&&(n.defaults.headers.get||(n.defaults.headers.get={}),n.defaults.headers.get["Cache-Control"]="no-cache",n.defaults.headers.get.Pragma="no-cache"),n.interceptors.push("apiInterceptor"),n.interceptors.push("jwtInterceptor"),t.otherwise("/"),e.state("backend",{templateUrl:"app/views/backendLayout.html",abstract:!0,data:{authorize:!0}}).state("backend.user",{templateUrl:"app/views/userLayout.html",abstract:!0}).state("backend.user.vault",{url:"^/vault",templateUrl:"app/vault/views/vault.html",controller:"vaultController",data:{pageTitle:"My Vault",controlSidebar:!0},params:{refreshFromServer:!1}}).state("backend.user.settings",{url:"^/settings",templateUrl:"app/settings/views/settings.html",controller:"settingsController",data:{pageTitle:"Settings"}}).state("backend.user.settingsDomains",{url:"^/settings/domains",templateUrl:"app/settings/views/settingsDomains.html",controller:"settingsDomainsController",data:{pageTitle:"Domain Settings"}}).state("backend.user.settingsTwoStep",{url:"^/settings/two-step",templateUrl:"app/settings/views/settingsTwoStep.html",controller:"settingsTwoStepController",data:{pageTitle:"Two-step Login"}}).state("backend.user.settingsCreateOrg",{url:"^/settings/create-organization",templateUrl:"app/settings/views/settingsCreateOrganization.html",controller:"settingsCreateOrganizationController",data:{pageTitle:"Create Organization"}}).state("backend.user.settingsBilling",{url:"^/settings/billing",templateUrl:"app/settings/views/settingsBilling.html",controller:"settingsBillingController",data:{pageTitle:"Billing"}}).state("backend.user.settingsPremium",{url:"^/settings/premium",templateUrl:"app/settings/views/settingsPremium.html",controller:"settingsPremiumController",data:{pageTitle:"Go Premium"}}).state("backend.user.tools",{url:"^/tools",templateUrl:"app/tools/views/tools.html",controller:"toolsController",data:{pageTitle:"Tools"}}).state("backend.user.reportsBreach",{url:"^/reports/breach",templateUrl:"app/reports/views/reportsBreach.html",controller:"reportsBreachController",data:{pageTitle:"Data Breach Report"}}).state("backend.user.apps",{url:"^/apps",templateUrl:"app/views/apps.html",controller:"appsController",data:{pageTitle:"Get the Apps"}}).state("backend.org",{templateUrl:"app/views/organizationLayout.html",abstract:!0}).state("backend.org.dashboard",{url:"^/organization/:orgId",templateUrl:"app/organization/views/organizationDashboard.html",controller:"organizationDashboardController",data:{pageTitle:"Organization Dashboard"}}).state("backend.org.people",{url:"/organization/:orgId/people?viewEvents&search",templateUrl:"app/organization/views/organizationPeople.html",controller:"organizationPeopleController",data:{pageTitle:"Organization People"}}).state("backend.org.collections",{url:"/organization/:orgId/collections?search",templateUrl:"app/organization/views/organizationCollections.html",controller:"organizationCollectionsController",data:{pageTitle:"Organization Collections"}}).state("backend.org.settings",{url:"/organization/:orgId/settings",templateUrl:"app/organization/views/organizationSettings.html",controller:"organizationSettingsController",data:{pageTitle:"Organization Settings"}}).state("backend.org.billing",{url:"/organization/:orgId/billing",templateUrl:"app/organization/views/organizationBilling.html",controller:"organizationBillingController",data:{pageTitle:"Organization Billing"}}).state("backend.org.vault",{url:"/organization/:orgId/vault?viewEvents&search",templateUrl:"app/organization/views/organizationVault.html",controller:"organizationVaultController",data:{pageTitle:"Organization Vault"}}).state("backend.org.groups",{url:"/organization/:orgId/groups?search",templateUrl:"app/organization/views/organizationGroups.html",controller:"organizationGroupsController",data:{pageTitle:"Organization Groups"}}).state("backend.org.events",{url:"/organization/:orgId/events",templateUrl:"app/organization/views/organizationEvents.html",controller:"organizationEventsController",data:{pageTitle:"Organization Events"}}).state("frontend",{templateUrl:"app/views/frontendLayout.html",abstract:!0,data:{authorize:!1}}).state("frontend.login",{templateUrl:"app/accounts/views/accountsLogin.html",controller:"accountsLoginController",params:{returnState:null,email:null,premium:null,org:null},data:{bodyClass:"login-page"}}).state("frontend.login.info",{url:"^/?org&premium&email",templateUrl:"app/accounts/views/accountsLoginInfo.html",data:{pageTitle:"Log In"}}).state("frontend.login.twoFactor",{url:"^/two-step?org&premium&email",templateUrl:"app/accounts/views/accountsLoginTwoFactor.html",data:{pageTitle:"Log In (Two-step)"}}).state("frontend.logout",{url:"^/logout",controller:"accountsLogoutController",data:{authorize:!0}}).state("frontend.passwordHint",{url:"^/password-hint",templateUrl:"app/accounts/views/accountsPasswordHint.html",controller:"accountsPasswordHintController",data:{pageTitle:"Master Password Hint",bodyClass:"login-page"}}).state("frontend.recover",{url:"^/recover",templateUrl:"app/accounts/views/accountsRecover.html",controller:"accountsRecoverController",data:{pageTitle:"Recover Account",bodyClass:"login-page"}}).state("frontend.recover-delete",{url:"^/recover-delete",templateUrl:"app/accounts/views/accountsRecoverDelete.html",controller:"accountsRecoverDeleteController",data:{pageTitle:"Delete Account",bodyClass:"login-page"}}).state("frontend.verify-recover-delete",{url:"^/verify-recover-delete?userId&token&email",templateUrl:"app/accounts/views/accountsVerifyRecoverDelete.html",controller:"accountsVerifyRecoverDeleteController",data:{pageTitle:"Confirm Delete Account",bodyClass:"login-page"}}).state("frontend.register",{url:"^/register?org&premium",templateUrl:"app/accounts/views/accountsRegister.html",controller:"accountsRegisterController",params:{returnState:null,email:null,org:null,premium:null},data:{pageTitle:"Register",bodyClass:"register-page"}}).state("frontend.organizationAccept",{url:"^/accept-organization?organizationId&organizationUserId&token&email&organizationName",templateUrl:"app/accounts/views/accountsOrganizationAccept.html",controller:"accountsOrganizationAcceptController",data:{pageTitle:"Accept Organization Invite",bodyClass:"login-page",skipAuthorize:!0}}).state("frontend.verifyEmail",{url:"^/verify-email?userId&token",templateUrl:"app/accounts/views/accountsVerifyEmail.html",controller:"accountsVerifyEmailController",data:{pageTitle:"Verifying Email",bodyClass:"login-page",skipAuthorize:!0}})}]).run(["$rootScope","authService","$state",function(e,t,n){e.$on("$stateChangeSuccess",function(){$("html, body").animate({scrollTop:0},200)}),e.$on("$stateChangeStart",function(o,r,a){if(!r.data||!r.data.authorize){if(r.data&&r.data.skipAuthorize)return;if(!t.isAuthenticated())return;return o.preventDefault(),void n.go("backend.user.vault")}if(!t.isAuthenticated())return o.preventDefault(),t.logOut(),void n.go("frontend.login.info");r.name.indexOf("backend.org.")>-1&&a.orgId&&(e.vaultCiphers=e.vaultGroupings=null,t.getUserProfile().then(function(e){var t=e.organizations;t&&a.orgId in t&&2===t[a.orgId].status&&2!==t[a.orgId].type||(o.preventDefault(),n.go("backend.user.vault"))}))})}]),angular.module("bit").constant("constants",{rememberedEmailCookieName:"bit.rememberedEmail",encType:{AesCbc256_B64:0,AesCbc128_HmacSha256_B64:1,AesCbc256_HmacSha256_B64:2,Rsa2048_OaepSha256_B64:3,Rsa2048_OaepSha1_B64:4,Rsa2048_OaepSha256_HmacSha256_B64:5,Rsa2048_OaepSha1_HmacSha256_B64:6},orgUserType:{owner:0,admin:1,user:2},orgUserStatus:{invited:0,accepted:1,confirmed:2},twoFactorProvider:{u2f:4,yubikey:3,duo:2,authenticator:0,email:1,remember:5},cipherType:{login:1,secureNote:2,card:3,identity:4},fieldType:{text:0,hidden:1,boolean:2},deviceType:{android:0,ios:1,chromeExt:2,firefoxExt:3,operaExt:4,edgeExt:5,windowsDesktop:6,macOsDesktop:7,linuxDesktop:8,chrome:9,firefox:10,opera:11,edge:12,ie:13,unknown:14,uwp:16,safari:17,vivaldi:18,vivaldiExt:19},eventType:{User_LoggedIn:1e3,User_ChangedPassword:1001,User_Enabled2fa:1002,User_Disabled2fa:1003,User_Recovered2fa:1004,User_FailedLogIn:1005,User_FailedLogIn2fa:1006,Cipher_Created:1100,Cipher_Updated:1101,Cipher_Deleted:1102,Cipher_AttachmentCreated:1103,Cipher_AttachmentDeleted:1104,Cipher_Shared:1105,Cipher_UpdatedCollections:1106,Collection_Created:1300,Collection_Updated:1301,Collection_Deleted:1302,Group_Created:1400,Group_Updated:1401,Group_Deleted:1402,OrganizationUser_Invited:1500,OrganizationUser_Confirmed:1501,OrganizationUser_Updated:1502,OrganizationUser_Removed:1503,OrganizationUser_UpdatedGroups:1504,Organization_Updated:1600},twoFactorProviderInfo:[{type:0,name:"Authenticator App",description:"Use an authenticator app (such as Authy or Google Authenticator) to generate time-based verification codes.",enabled:!1,active:!0,free:!0,image:"authapp.png",displayOrder:0,priority:1,requiresUsb:!1},{type:3,name:"YubiKey OTP Security Key",description:"Use a YubiKey to access your account. Works with YubiKey 4, 4 Nano, 4C, and NEO devices.",enabled:!1,active:!0,image:"yubico.png",displayOrder:1,priority:3,requiresUsb:!0},{type:2,name:"Duo",description:"Verify with Duo Security using the Duo Mobile app, SMS, phone call, or U2F security key.",enabled:!1,active:!0,image:"duo.png",displayOrder:2,priority:2,requiresUsb:!1},{type:4,name:"FIDO U2F Security Key",description:"Use any FIDO U2F enabled security key to access your account.",enabled:!1,active:!0,image:"fido.png",displayOrder:3,priority:4,requiresUsb:!0},{type:1,name:"Email",description:"Verification codes will be emailed to you.",enabled:!1,active:!0,free:!0,image:"gmail.png",displayOrder:4,priority:0,requiresUsb:!1}],plans:{free:{basePrice:0,noAdditionalSeats:!0,noPayment:!0,upgradeSortOrder:-1},families:{basePrice:1,annualBasePrice:12,baseSeats:5,noAdditionalSeats:!0,annualPlanType:"familiesAnnually",upgradeSortOrder:1},teams:{basePrice:5,annualBasePrice:60,monthlyBasePrice:8,baseSeats:5,seatPrice:2,annualSeatPrice:24,monthlySeatPrice:2.5,monthPlanType:"teamsMonthly",annualPlanType:"teamsAnnually",upgradeSortOrder:2},enterprise:{seatPrice:3,annualSeatPrice:36,monthlySeatPrice:4,monthPlanType:"enterpriseMonthly",annualPlanType:"enterpriseAnnually",upgradeSortOrder:3}},storageGb:{price:.33,monthlyPrice:.5,yearlyPrice:4},premium:{price:10,yearlyPrice:10}}),angular.module("bit.accounts").controller("accountsLoginController",["$scope","$rootScope","$cookies","apiService","cryptoService","authService","$state","constants","$analytics","$uibModal","$timeout","$window","$filter","toastr",function(e,t,n,o,r,a,i,s,l,c,u,d,p,m){e.state=i,e.twoFactorProviderConstants=s.twoFactorProvider,e.rememberTwoFactor={checked:!1};var g=!0;e.returnState=i.params.returnState,e.stateEmail=i.params.email,!e.returnState&&i.params.org?e.returnState={name:"backend.user.settingsCreateOrg",params:{plan:i.params.org}}:!e.returnState&&i.params.premium&&(e.returnState={name:"backend.user.settingsPremium"}),!(i.current.name.indexOf("twoFactor")>-1)||e.twoFactorProviders&&e.twoFactorProviders.length||i.go("frontend.login.info",{returnState:e.returnState});var f,h,v=n.get(s.rememberedEmailCookieName);function y(){e.returnState?i.go(e.returnState.name,e.returnState.params):i.go("backend.user.vault")}function b(){var t;if(g=!0,e.twoFactorProvider===s.twoFactorProvider.duo)t=e.twoFactorProviders[s.twoFactorProvider.duo],d.Duo.init({host:t.Host,sig_request:t.Signature,submit_callback:function(t){var n=$(t).find('input[name="sig_response"]').val();e.twoFactor(n)}});else if(e.twoFactorProvider===s.twoFactorProvider.u2f){g=!1,t=e.twoFactorProviders[s.twoFactorProvider.u2f],function t(n){if(g)return;if(n.length<1||e.twoFactorProvider!==s.twoFactorProvider.u2f)return;console.log("listening for u2f key...");d.u2f.sign(n[0].appId,n[0].challenge,[{version:n[0].version,keyHandle:n[0].keyHandle}],function(o){if(e.twoFactorProvider===s.twoFactorProvider.u2f)return o.errorCode?(console.log(o.errorCode),void u(function(){t(n)},5===o.errorCode?0:1e3)):void e.twoFactor(JSON.stringify(o))},10)}(JSON.parse(t.Challenges))}else e.twoFactorProvider===s.twoFactorProvider.email&&(t=e.twoFactorProviders[s.twoFactorProvider.email],e.twoFactorEmail=t.Email,Object.keys(e.twoFactorProviders).length>1&&e.sendEmail(!1))}v||e.stateEmail?(e.model={email:e.stateEmail||v,rememberEmail:null!==v},u(function(){$("#masterPassword").focus()})):u(function(){$("#email").focus()}),e.twoFactorProviders=null,e.twoFactorProvider=null,e.login=function(t){e.loginPromise=a.logIn(t.email,t.masterPassword).then(function(o){if(t.rememberEmail){var r=new Date;r.setFullYear(r.getFullYear()+10),n.put(s.rememberedEmailCookieName,t.email,{expires:r})}else n.remove(s.rememberedEmailCookieName);o&&Object.keys(o).length>0?(f=t.email,h=t.masterPassword,e.twoFactorProviders=function(e){if(t=!1,n=navigator.userAgent||navigator.vendor||window.opera,(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(n)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(n.substr(0,4)))&&(t=!0),!t&&!navigator.userAgent.match(/iPad/i))return e;var t,n;for(var o=Object.keys(e),r=0;r<o.length;r++){var a=p("filter")(s.twoFactorProviderInfo,{type:o[r],active:!0,requiresUsb:!1});a.length||delete e[o[r]]}return e}(o),e.twoFactorProvider=function(e){for(var t=Object.keys(e),n=null,o=-1,r=0;r<t.length;r++){var a=p("filter")(s.twoFactorProviderInfo,{type:t[r],active:!0});if(a.length&&a[0].priority>o){if(a[0].type===s.twoFactorProvider.u2f&&!u2f.isSupported)continue;n=a[0].type,o=a[0].priority}}if(null===n)return null;return parseInt(n)}(e.twoFactorProviders),l.eventTrack("Logged In To Two-step"),i.go("frontend.login.twoFactor",{returnState:e.returnState}).then(function(){u(function(){$("#code").focus(),b()})})):(l.eventTrack("Logged In"),y()),t.masterPassword=""})},e.twoFactor=function(t){e.twoFactorProvider!==s.twoFactorProvider.email&&e.twoFactorProvider!==s.twoFactorProvider.authenticator||(t=t.replace(" ","")),e.twoFactorPromise=a.logIn(f,h,t,e.twoFactorProvider,e.rememberTwoFactor.checked||!1),e.twoFactorPromise.then(function(){l.eventTrack("Logged In From Two-step"),y()},function(){e.twoFactorProvider===s.twoFactorProvider.u2f&&b()})},e.anotherMethod=function(){c.open({animation:!0,templateUrl:"app/accounts/views/accountsTwoFactorMethods.html",controller:"accountsTwoFactorMethodsController",resolve:{providers:function(){return e.twoFactorProviders}}}).result.then(function(t){e.twoFactorProvider=t,u(function(){$("#code").focus(),b()})})},e.sendEmail=function(t){if(e.twoFactorProvider===s.twoFactorProvider.email)return r.makeKeyAndHash(f,h).then(function(e){return o.twoFactor.sendEmailLogin({email:f,masterPasswordHash:e.hash}).$promise}).then(function(){t&&m.success("Verification email sent to "+e.twoFactorEmail+".")},function(){m.error("Could not send verification email.")})},e.$on("$destroy",function(){g=!0})}]),angular.module("bit.accounts").controller("accountsLogoutController",["$scope","authService","$state","$analytics",function(e,t,n,o){t.logOut(),o.eventTrack("Logged Out"),n.go("frontend.login.info")}]),angular.module("bit.accounts").controller("accountsOrganizationAcceptController",["$scope","$state","apiService","authService","toastr","$analytics",function(e,t,n,o,r,a){e.state={name:t.current.name,params:t.params},t.params.organizationId&&t.params.organizationUserId&&t.params.token&&t.params.email&&t.params.organizationName?e.$on("$viewContentLoaded",function(){o.isAuthenticated()?(e.accepting=!0,n.organizationUsers.accept({orgId:t.params.organizationId,id:t.params.organizationUserId},{token:t.params.token},function(){a.eventTrack("Accepted Invitation"),t.go("backend.user.vault",null,{location:"replace"}).then(function(){r.success("You can access this organization once an administrator confirms your membership. We'll send an email when that happens.","Invite Accepted",{timeOut:1e4})})},function(){a.eventTrack("Failed To Accept Invitation"),t.go("backend.user.vault",null,{location:"replace"}).then(function(){r.error("Unable to accept invitation.","Error")})})):e.loading=!1}):t.go("frontend.login.info").then(function(){r.error("Invalid parameters.")})}]),angular.module("bit.accounts").controller("accountsPasswordHintController",["$scope","$rootScope","apiService","$analytics",function(e,t,n,o){e.success=!1,e.submit=function(t){e.submitPromise=n.accounts.postPasswordHint({email:t.email},function(){o.eventTrack("Requested Password Hint"),e.success=!0}).$promise}}]),angular.module("bit.accounts").controller("accountsRecoverController",["$scope","apiService","cryptoService","$analytics",function(e,t,n,o){e.success=!1,e.submit=function(r){var a=r.email.toLowerCase();e.submitPromise=n.makeKeyAndHash(r.email,r.masterPassword).then(function(e){return t.twoFactor.recover({email:a,masterPasswordHash:e.hash,recoveryCode:r.code.replace(/\s/g,"").toLowerCase()}).$promise}).then(function(){o.eventTrack("Recovered 2FA"),e.success=!0})}}]),angular.module("bit.accounts").controller("accountsRecoverDeleteController",["$scope","$rootScope","apiService","$analytics",function(e,t,n,o){e.success=!1,e.submit=function(t){e.submitPromise=n.accounts.postDeleteRecover({email:t.email},function(){o.eventTrack("Started Delete Recovery"),e.success=!0}).$promise}}]),angular.module("bit.accounts").controller("accountsRegisterController",["$scope","$location","apiService","cryptoService","validationService","$analytics","$state","$timeout",function(e,t,n,o,r,a,i,s){var l=t.search(),c=i.params;e.createOrg=c.org,!c.returnState&&c.org?e.returnState={name:"backend.user.settingsCreateOrg",params:{plan:i.params.org}}:!c.returnState&&c.premium?e.returnState={name:"backend.user.settingsPremium",params:{plan:i.params.org}}:e.returnState=c.returnState,e.success=!1,e.model={email:l.email?l.email:c.email},e.readOnlyEmail=null!==c.email,s(function(){e.model.email?$("#name").focus():$("#email").focus()}),e.registerPromise=null,e.register=function(t){var i=!1;if(e.model.masterPassword.length<8&&(r.addError(t,"MasterPassword","Master password must be at least 8 characters long.",!0),i=!0),e.model.masterPassword!==e.model.confirmMasterPassword&&(r.addError(t,"ConfirmMasterPassword","Master password confirmation does not match.",!0),i=!0),!i){var s,l,c=e.model.email.toLowerCase();e.registerPromise=o.makeKeyAndHash(c,e.model.masterPassword).then(function(e){return s=e,l=o.makeEncKey(e.key),o.makeKeyPair(l.encKey)}).then(function(t){var o={name:e.model.name,email:c,masterPasswordHash:s.hash,masterPasswordHint:e.model.masterPasswordHint,key:l.encKeyEnc,keys:{publicKey:t.publicKey,encryptedPrivateKey:t.privateKeyEnc}};return n.accounts.register(o).$promise},function(e){return r.addError(t,null,"Problem generating keys.",!0),!1}).then(function(t){!1!==t&&(e.success=!0,a.eventTrack("Registered"))})}}}]),angular.module("bit.accounts").controller("accountsTwoFactorMethodsController",["$scope","$uibModalInstance","$analytics","providers","constants",function(e,t,n,o,r){function a(t){for(var n=0;n<r.twoFactorProviderInfo.length;n++)r.twoFactorProviderInfo[n].type===t&&e.providers.push(r.twoFactorProviderInfo[n])}n.eventTrack("accountsTwoFactorMethodsController",{category:"Modal"}),e.providers=[],o.hasOwnProperty(r.twoFactorProvider.authenticator)&&a(r.twoFactorProvider.authenticator),o.hasOwnProperty(r.twoFactorProvider.yubikey)&&a(r.twoFactorProvider.yubikey),o.hasOwnProperty(r.twoFactorProvider.email)&&a(r.twoFactorProvider.email),o.hasOwnProperty(r.twoFactorProvider.duo)&&a(r.twoFactorProvider.duo),o.hasOwnProperty(r.twoFactorProvider.u2f)&&u2f.isSupported&&a(r.twoFactorProvider.u2f),e.choose=function(e){t.close(e.type)},e.close=function(){t.dismiss("close")}}]),angular.module("bit.accounts").controller("accountsVerifyEmailController",["$scope","$state","apiService","toastr","$analytics",function(e,t,n,o,r){t.params.userId&&t.params.token?e.$on("$viewContentLoaded",function(){n.accounts.verifyEmailToken({},{token:t.params.token,userId:t.params.userId},function(){r.eventTrack("Verified Email"),t.go("frontend.login.info",null,{location:"replace"}).then(function(){o.success("Your email has been verified. Thank you.","Success")})},function(){t.go("frontend.login.info",null,{location:"replace"}).then(function(){o.error("Unable to verify email.","Error")})})}):t.go("frontend.login.info").then(function(){o.error("Invalid parameters.")})}]),angular.module("bit.accounts").controller("accountsVerifyRecoverDeleteController",["$scope","$state","apiService","toastr","$analytics",function(e,t,n,o,r){t.params.userId&&t.params.token&&t.params.email?(e.email=t.params.email,e.delete=function(){confirm("Are you sure you want to delete this account? This cannot be undone.")&&(e.deleting=!0,n.accounts.postDeleteRecoverToken({},{token:t.params.token,userId:t.params.userId},function(){r.eventTrack("Recovered Delete"),t.go("frontend.login.info",null,{location:"replace"}).then(function(){o.success("Your account has been deleted. You can register a new account again if you like.","Success")})},function(){t.go("frontend.login.info",null,{location:"replace"}).then(function(){o.error("Unable to delete account.","Error")})}))}):t.go("frontend.login.info").then(function(){o.error("Invalid parameters.")})}]),angular.module("bit.directives").directive("apiField",function(){var e=function(e,t,n,o){o.$registerApiError=function(){o.$setValidity("api",!1)},o.$validators.apiValidate=function(){return o.$setValidity("api",!0),!0}};return{require:"ngModel",restrict:"A",compile:function(t,n){if(!n.name||""===n.name)throw"api-field element does not have a valid name attribute";return e}}}),angular.module("bit.directives").directive("apiForm",["$rootScope","validationService","$timeout",function(e,t,n){return{require:"form",restrict:"A",link:function(e,o,r,a){var i=r.apiForm||null;void 0!==i&&e.$watch(i,function(e,o,r){if(!r||!r.then)return;e.$errors=null,e.$loading=!0,r.then(function(t){n(function(){e.$loading=!1})},function(r){n(function(){e.$loading=!1,"string"==typeof r?t.addError(e,null,r,!0):t.addErrors(e,r),o.$broadcast("show-errors-check-validity"),$("html, body").animate({scrollTop:0},200)})})}.bind(null,a,e))}}}]),angular.module("bit.directives").directive("fallbackSrc",function(){return function(e,t,n){var o=$(t);o.bind("error",function(e){o.attr("src",n.fallbackSrc)})}}),angular.module("bit.directives").directive("letterAvatar",function(){return{restrict:"AE",replace:!0,scope:{data:"@"},link:function(e,t,n){var o={charCount:n.charcount||2,data:n.data,textColor:n.textcolor||"#ffffff",bgColor:n.bgcolor,height:n.avheight||45,width:n.avwidth||45,fontSize:n.fontsize||20,fontWeight:n.fontweight||300,fontFamily:n.fontfamily||"Open Sans, HelveticaNeue-Light, Helvetica Neue Light, Helvetica Neue, Helvetica, Arial, Lucida Grande, sans-serif",round:n.round||"true",dynamic:n.dynamic||"true",class:n.avclass||"",border:n.avborder||"false",borderStyle:n.borderstyle||"3px solid white"};function r(){var n=null,r=e.data.toUpperCase();o.charCount>1&&(n=function(e,t){var n=e.split(" ");if(n&&n.length>1){for(var o="",r=0;r<t;r++)o+=n[r].substr(0,1);return o}return null}(r,o.charCount)),n||(n=r.substr(0,o.charCount));var a,i,s,l,c,u,d,p,m=(a=n,i=o.textColor,s=o.fontFamily,l=o.fontWeight,c=o.fontSize,angular.element('<text text-anchor="middle"></text>').attr({y:"50%",x:"50%",dy:"0.35em","pointer-events":"auto",fill:i,"font-family":s}).text(a).css({"font-weight":l,"font-size":c+"px"})),g=o.bgColor?o.bgColor:function(e){var t=0,n=0;for(n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);var o="#";for(n=0;n<3;n++)o+=("00"+(t>>8*n&255).toString(16)).substr(-2);return o}(r),f=(u=o.width,d=o.height,p=g,angular.element("<svg></svg>").attr({xmlns:"http://www.w3.org/2000/svg","pointer-events":"none",width:u,height:d}).css({"background-color":p,width:u+"px",height:d+"px"}));f.append(m);var h=angular.element("<div>").append(f).html(),v="data:image/svg+xml;base64,"+window.btoa(unescape(encodeURIComponent(h))),y=angular.element("<img>").attr({src:v,title:e.data});"true"===o.round&&y.css("border-radius","50%"),"true"===o.border&&y.css("border",o.borderStyle),o.class&&y.addClass(o.class),"true"===o.dynamic?(t.empty(),t.append(y)):t.replaceWith(y)}"true"===o.dynamic?e.$watch("data",function(){r()}):r()}}}),angular.module("bit.directives").directive("masterPassword",["cryptoService","authService",function(e,t){return{require:"ngModel",restrict:"A",link:function(n,o,r,a){t.getUserProfile().then(function(t){a.$parsers.unshift(function(n){if(n)return e.makeKey(n,t.email).then(function(t){var o=t.keyB64===e.getKey().keyB64;return a.$setValidity("masterPassword",o),o?n:void 0})}),a.$formatters.unshift(function(n){if(n)return e.makeKey(n,t.email).then(function(t){var o=t.keyB64===e.getKey().keyB64;return a.$setValidity("masterPassword",o),n})})})}}}]),angular.module("bit.directives").directive("pageTitle",["$rootScope","$timeout","appSettings",function(e,t,n){return{link:function(n,o){e.$on("$stateChangeStart",function(e,n,r,a,i){var s="bitwarden Web Vault";n.data&&n.data.pageTitle&&(s=n.data.pageTitle+" - "+s),t(function(){o.text(s)})})}}}]),angular.module("bit.directives").directive("passwordMeter",function(){return{template:'<div class="progress {{outerClass}}"><div class="progress-bar progress-bar-{{valueClass}}" role="progressbar" aria-valuenow="{{value}}" aria-valuemin="0" aria-valuemax="100" ng-style="{width : ( value + \'%\' ) }"><span class="sr-only">{{value}}%</span></div></div>',restrict:"A",scope:{password:"=passwordMeter",username:"=passwordMeterUsername",outerClass:"@?"},link:function(e){var t=function(e){e.value=function(e,t){if(!t||t===e)return 0;var n=t.length;return e&&""!==e&&(-1!==e.indexOf(t)&&(n-=15),-1!==t.indexOf(e)&&(n-=e.length)),t.length>0&&t.length<=4?n+=t.length:t.length>=5&&t.length<=7?n+=6:t.length>=8&&t.length<=15?n+=12:t.length>=16&&(n+=18),t.match(/[a-z]/)&&(n+=1),t.match(/[A-Z]/)&&(n+=5),t.match(/\d/)&&(n+=5),t.match(/.*\d.*\d.*\d/)&&(n+=5),t.match(/[!,@,#,$,%,^,&,*,?,_,~]/)&&(n+=5),t.match(/.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~]/)&&(n+=5),t.match(/(?=.*[a-z])(?=.*[A-Z])/)&&(n+=2),t.match(/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/)&&(n+=2),t.match(/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!,@,#,$,%,^,&,*,?,_,~])/)&&(n+=2),n=Math.round(2*n),Math.max(0,Math.min(100,n))}(e.username,e.password),e.valueClass=function(e){switch(Math.round(e/33)){case 0:case 1:return"danger";case 2:return"warning";case 3:return"success"}}(e.value)};e.$watch("password",function(){t(e)}),e.$watch("username",function(){t(e)})}}}),angular.module("bit.directives").directive("passwordViewer",function(){return{restrict:"A",link:function(e,t,n){var o=n.passwordViewer;o&&(t.onclick=function(e){},t.on("click",function(e){var n=$(o);n&&"password"===n.attr("type")?(t.removeClass("fa-eye").addClass("fa-eye-slash"),n.attr("type","text")):n&&"text"===n.attr("type")&&(t.removeClass("fa-eye-slash").addClass("fa-eye"),n.attr("type","password"))}))}}}),angular.module("bit.directives").directive("stopClick",function(){return function(e,t,n){$(t).click(function(e){e.preventDefault()})}}),angular.module("bit.directives").directive("stopProp",function(){return function(e,t,n){$(t).click(function(e){e.stopPropagation()})}}),angular.module("bit.directives").directive("totp",["$timeout","$q",function(e,t){return{template:'<div class="totp{{(low ? \' low\' : \'\')}}" ng-if="code"><span class="totp-countdown"><span class="totp-sec">{{sec}}</span><svg><g><circle class="totp-circle inner" r="12.6" cy="16" cx="16" style="stroke-dashoffset: {{dash}}px;"></circle><circle class="totp-circle outer" r="14" cy="16" cx="16"></circle></g></svg></span><span class="totp-code" id="totp-code">{{codeFormatted}}</span><a href="#" stop-click class="btn btn-link" ngclipboard ngclipboard-error="clipboardError(e)" data-clipboard-text="{{code}}" uib-tooltip="Copy Code" tooltip-placement="right"><i class="fa fa-clipboard"></i></a></div>',restrict:"A",scope:{key:"=totp"},link:function(n){var o=null,r=new function(){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",n=function(e,t,n){return t+1>=e.length&&(e=Array(t+1-e.length).join(n)+e),e},o=function(e){return parseInt(e,16)},r=function(e){for(var t=new Uint8Array(e.length/2),n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substr(n,2),16);return t},a=function(t){return r(function(t){t=t.toUpperCase();var o,r="";for(o=0;o<t.length;o++)e.indexOf(t[o])<0||(r+=t[o]);t=r;var a="",i="";for(o=0;o<t.length;o++){var s=e.indexOf(t.charAt(o));s<0||(a+=n(s.toString(2),5,"0"))}for(o=0;o+4<=a.length;o+=4){var l=a.substr(o,4);i+=parseInt(l,2).toString(16)}return i}(t))},i=function(e,t){return window.crypto.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-1"}},!1,["sign"]).then(function(e){return window.crypto.subtle.sign({name:"HMAC",hash:{name:"SHA-1"}},e,t)}).then(function(e){return function(e){for(var t=new Uint8Array(e),n=[],o=0;o<t.length;o++)n.push((t[o]>>>4).toString(16)),n.push((15&t[o]).toString(16));return n.join("")}(e)}).catch(function(e){return null})};this.getCode=function(e){var s,l=Math.round((new Date).getTime()/1e3),c=n(((s=Math.floor(l/30))<15.5?"0":"")+Math.round(s).toString(16),16,"0"),u=r(c),d=a(e);return d.length&&u.length?i(d,u).then(function(e){if(!e)return null;var t=o(e.substring(e.length-1)),n=(o(e.substr(2*t,8))&o("7fffffff"))+"";return n=n.substr(n.length-6,6)}):t(function(e,t){e(null)})}},a=function(t){r.getCode(t.key).then(function(n){e(function(){n?(t.codeFormatted=n.substring(0,3)+" "+n.substring(3),t.code=n):(t.code=null,o&&clearInterval(o))})})},i=function(t){e(function(){var e=Math.round((new Date).getTime()/1e3)%30,n=30-e;t.sec=n,t.dash=(2.62*e).toFixed(2),t.low=n<=7,0===e&&a(t)})};n.$watch("key",function(){if(!n.key)return n.code=null,void(o&&clearInterval(o));a(n),i(n),o&&clearInterval(o),o=setInterval(function(){i(n)},1e3)}),n.$on("$destroy",function(){o&&clearInterval(o)}),n.clipboardError=function(e){alert("Your web browser does not support easy clipboard copying.")}}}}]),angular.module("bit.filters").filter("enumLabelClass",function(){return function(e,t){if("number"!=typeof e)return e.toString();var n;switch(t){case"OrgUserStatus":switch(e){case 0:n="label-default";break;case 1:n="label-warning";break;case 2:default:n="label-success"}break;default:n="label-default"}return n}}),angular.module("bit.filters").filter("enumName",function(){return function(e,t){if("number"!=typeof e)return e.toString();var n;switch(t){case"OrgUserStatus":switch(e){case 0:n="Invited";break;case 1:n="Accepted";break;case 2:default:n="Confirmed"}break;case"OrgUserType":switch(e){case 0:n="Owner";break;case 1:n="Admin";break;case 2:default:n="User"}break;default:n=e.toString()}return n}}),angular.module("bit.global").controller("appsController",["$scope","$state",function(e,t){}]),angular.module("bit.global").controller("mainController",["$scope","$state","authService","appSettings","toastr","$window","$document","cryptoService","$uibModal","apiService",function(e,t,n,o,r,a,i,s,l,c){var u,d,p,m=this;m.skinClass=o.selfHosted?"skin-blue-light":"skin-blue",m.bodyClass="",m.usingControlSidebar=m.openControlSidebar=!1,m.searchVaultText=null,m.version=o.version,m.outdatedBrowser=-1!==a.navigator.userAgent.indexOf("MSIE")||-1!==a.navigator.userAgent.indexOf("SamsungBrowser"),e.currentYear=(new Date).getFullYear(),e.$on("$viewContentLoaded",function(){n.getUserProfile().then(function(e){m.userProfile=e}),$.AdminLTE&&($.AdminLTE.layout&&($.AdminLTE.layout.fix(),$.AdminLTE.layout.fixSidebar()),$.AdminLTE.pushMenu&&$.AdminLTE.pushMenu.expandOnHover(),i.off("click",".sidebar li a"))}),e.$on("$stateChangeSuccess",function(e,t,n,o,r){m.usingEncKey=!!s.getEncKey(),m.searchVaultText=null,t.data.bodyClass?m.bodyClass=t.data.bodyClass:(m.bodyClass="",m.usingControlSidebar=!!t.data.controlSidebar,m.openControlSidebar=m.usingControlSidebar&&i.width()>768)}),e.$on("setSearchVaultText",function(e,t){m.searchVaultText=t}),e.addCipher=function(){e.$broadcast("vaultAddCipher")},e.addFolder=function(){e.$broadcast("vaultAddFolder")},e.addOrganizationCipher=function(){e.$broadcast("organizationVaultAddCipher")},e.addOrganizationCollection=function(){e.$broadcast("organizationCollectionsAdd")},e.inviteOrganizationUser=function(){e.$broadcast("organizationPeopleInvite")},e.addOrganizationGroup=function(){e.$broadcast("organizationGroupsAdd")},e.updateKey=function(){l.open({animation:!0,templateUrl:"app/settings/views/settingsUpdateKey.html",controller:"settingsUpdateKeyController"})},e.verifyEmail=function(){e.sendingVerify||(e.sendingVerify=!0,c.accounts.verifyEmail({},null).$promise.then(function(){r.success("Verification email sent."),e.sendingVerify=!1,e.verifyEmailSent=!0}).catch(function(){r.success("Verification email failed."),e.sendingVerify=!1}))},e.updateBrowser=function(){a.open("https://browser-update.org/update.html","_blank")};var g={scrollbarWidth:function(){if(!u){var e=$("body");e.addClass("bit-position-body-scrollbar-measure"),u=a.innerWidth-e[0].clientWidth,u=isFinite(u)?u:0,e.removeClass("bit-position-body-scrollbar-measure")}return u},scrollbarInfo:function(){return{width:g.scrollbarWidth(),visible:i.height()>$(a).height()}}};$(window).on("show.bs.dropdown",function(e){var t=p=$(e.target),n=t.data("appendTo");if(!n)return!0;d=t.find(".dropdown-menu"),$(n).append(d.detach());var o=t.offset(),r={display:"block",top:o.top+t.outerHeight()-("body"!==n?$(window).scrollTop():0)};if(d.hasClass("dropdown-menu-right")){var i=g.scrollbarInfo(),s=0;i.visible&&i.width&&(s=i.width),r.right=a.innerWidth-s-(o.left+t.prop("offsetWidth"))+"px",r.left="auto"}else r.left=o.left+"px",r.right="auto";d.css(r)}),$(window).on("hide.bs.dropdown",function(e){if(!d)return!0;$(e.target).append(d.detach()),d.hide(),d=null,p=null}),e.$on("removeAppendedDropdownMenu",function(e,t){if(!d&&!p)return!0;p.append(d.detach()),d.hide(),d=null,p=null})}]),angular.module("bit.global").controller("paidOrgRequiredController",["$scope","$state","$uibModalInstance","$analytics","$uibModalStack","orgId","constants","authService",function(e,t,n,o,r,a,i,s){o.eventTrack("paidOrgRequiredController",{category:"Modal"}),s.getUserProfile().then(function(t){e.admin=t.organizations[a].type!==i.orgUserType.user}),e.go=function(){e.admin&&(o.eventTrack("Get Paid Org"),t.go("backend.org.billing",{orgId:a}).then(function(){r.dismissAll()}))},e.close=function(){n.dismiss("close")}}]),angular.module("bit.global").controller("premiumRequiredController",["$scope","$state","$uibModalInstance","$analytics","$uibModalStack",function(e,t,n,o,r){o.eventTrack("premiumRequiredController",{category:"Modal"}),e.go=function(){o.eventTrack("Get Premium"),t.go("backend.user.settingsPremium").then(function(){r.dismissAll()})},e.close=function(){n.dismiss("close")}}]),angular.module("bit.global").controller("sideNavController",["$scope","$state","authService","toastr","$analytics","constants","appSettings",function(e,t,n,o,r,a,i){e.$state=t,e.params=t.params,e.orgs=[],e.name="",i.selfHosted?(e.orgIconBgColor="#ffffff",e.orgIconBorder="3px solid #a0a0a0",e.orgIconTextColor="#333333"):(e.orgIconBgColor="#2c3b41",e.orgIconBorder="3px solid #1a2226",e.orgIconTextColor="#ffffff"),n.getUserProfile().then(function(n){if(e.name=n.extended&&n.extended.name?n.extended.name:n.email,n.organizations)if(t.includes("backend.org")&&t.params.orgId in n.organizations)e.orgProfile=n.organizations[t.params.orgId];else{var o=[];for(var r in n.organizations)n.organizations.hasOwnProperty(r)&&(n.organizations[r].enabled||n.organizations[r].type<2)&&o.push(n.organizations[r]);e.orgs=o}}),e.viewOrganization=function(e){e.type!==a.orgUserType.user?(r.eventTrack("View Organization From Side Nav"),t.go("backend.org.dashboard",{orgId:e.id})):o.error("You cannot manage this organization.")},e.searchVault=function(){t.go("backend.user.vault")},e.searchOrganizationVault=function(){t.go("backend.org.vault",{orgId:t.params.orgId})},e.isOrgOwner=function(e){return e&&e.type===a.orgUserType.owner}}]),angular.module("bit.global").controller("topNavController",["$scope",function(e){e.toggleControlSidebar=function(){var e=$("body");e.hasClass("control-sidebar-open")?e.removeClass("control-sidebar-open"):e.addClass("control-sidebar-open")}}]),angular.module("bit.organization").controller("organizationBillingAdjustSeatsController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","add",function(e,t,n,o,r,a,i){r.eventTrack("organizationBillingAdjustSeatsController",{category:"Modal"}),e.add=i,e.seatAdjustment=0,e.submit=function(){var s={seatAdjustment:e.seatAdjustment};i||(s.seatAdjustment*=-1),e.submitPromise=o.organizations.putSeat({id:t.params.orgId},s).$promise.then(function(t){i?(r.eventTrack("Added Seats"),a.success("You have added "+e.seatAdjustment+" seats.")):(r.eventTrack("Removed Seats"),a.success("You have removed "+e.seatAdjustment+" seats.")),n.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationBillingAdjustStorageController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","add",function(e,t,n,o,r,a,i){r.eventTrack("organizationBillingAdjustStorageController",{category:"Modal"}),e.add=i,e.storageAdjustment=0,e.submit=function(){var s={storageGbAdjustment:e.storageAdjustment};i||(s.storageGbAdjustment*=-1),e.submitPromise=o.organizations.putStorage({id:t.params.orgId},s).$promise.then(function(t){i?(r.eventTrack("Added Organization Storage"),a.success("You have added "+e.storageAdjustment+" GB.")):(r.eventTrack("Removed Organization Storage"),a.success("You have removed "+e.storageAdjustment+" GB.")),n.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationBillingChangePaymentController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","existingPaymentMethod",function(e,t,n,o,r,a,i){r.eventTrack("organizationBillingChangePaymentController",{category:"Modal"}),e.existingPaymentMethod=i,e.paymentMethod="card",e.showPaymentOptions=!0,e.hidePaypal=!0,e.card={},e.bank={},e.changePaymentMethod=function(t){e.paymentMethod=t},e.submit=function(){var s=null;if("card"===e.paymentMethod)s=stripe.card.createToken(e.card);else{if("bank"!==e.paymentMethod)return;e.bank.currency="USD",e.bank.country="US",s=stripe.bankAccount.createToken(e.bank)}e.submitPromise=s.then(function(e){var n={paymentToken:e.id};return o.organizations.putPayment({id:t.params.orgId},n).$promise},function(e){throw e.message}).then(function(t){e.card=null,i?(r.eventTrack("Changed Organization Payment Method"),a.success("You have changed your payment method.")):(r.eventTrack("Added Organization Payment Method"),a.success("You have added a payment method.")),n.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationBillingChangePlanController",["$scope","$state","apiService","$uibModalInstance","toastr","$analytics",function(e,t,n,o,r,a){a.eventTrack("organizationBillingChangePlanController",{category:"Modal"}),e.submit=function(){},e.close=function(){o.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationBillingController",["$scope","apiService","$state","$uibModal","toastr","$analytics","appSettings","tokenService","$window",function(e,t,n,o,r,a,i,s,l){e.selfHosted=i.selfHosted,e.charges=[],e.paymentSource=null,e.plan=null,e.subscription=null,e.loading=!0;function c(){t.organizations.getBilling({id:n.params.orgId},function(t){e.loading=!1,e.noSubscription=0===t.PlanType,e.canAdjustSeats=t.PlanType>1;var n=0;if(e.expiration=t.Expiration,t.License,e.plan={name:t.Plan,type:t.PlanType,seats:t.Seats},e.storage=null,e&&t.MaxStorageGb&&(e.storage={currentGb:t.StorageGb||0,maxGb:t.MaxStorageGb,currentName:t.StorageName||"0 GB"},e.storage.percentage=+(e.storage.currentGb/e.storage.maxGb*100).toFixed(2)),e.subscription=null,t.Subscription&&(e.subscription={trialEndDate:t.Subscription.TrialEndDate,cancelledDate:t.Subscription.CancelledDate,status:t.Subscription.Status,cancelled:t.Subscription.Cancelled,markedForCancel:!t.Subscription.Cancelled&&t.Subscription.CancelAtEndDate}),e.nextInvoice=null,t.UpcomingInvoice&&(e.nextInvoice={date:t.UpcomingInvoice.Date,amount:t.UpcomingInvoice.Amount}),t.Subscription&&t.Subscription.Items)for(e.subscription.items=[],n=0;n<t.Subscription.Items.length;n++)e.subscription.items.push({amount:t.Subscription.Items[n].Amount,name:t.Subscription.Items[n].Name,interval:t.Subscription.Items[n].Interval,qty:t.Subscription.Items[n].Quantity});e.paymentSource=null,t.PaymentSource&&(e.paymentSource={type:t.PaymentSource.Type,description:t.PaymentSource.Description,cardBrand:t.PaymentSource.CardBrand,needsVerification:t.PaymentSource.NeedsVerification});var o=[];for(n=0;n<t.Charges.length;n++)o.push({date:t.Charges[n].CreatedDate,paymentSource:t.Charges[n].PaymentSource?t.Charges[n].PaymentSource.Description:"-",amount:t.Charges[n].Amount,status:t.Charges[n].Status,failureMessage:t.Charges[n].FailureMessage,refunded:t.Charges[n].Refunded,partiallyRefunded:t.Charges[n].PartiallyRefunded,refundedAmount:t.Charges[n].RefundedAmount,invoiceId:t.Charges[n].InvoiceId});e.charges=o})}e.expiration=null,e.$on("$viewContentLoaded",function(){c()}),e.changePayment=function(){e.selfHosted||o.open({animation:!0,templateUrl:"app/settings/views/settingsBillingChangePayment.html",controller:"organizationBillingChangePaymentController",resolve:{existingPaymentMethod:function(){return e.paymentSource?e.paymentSource.description:null}}}).result.then(function(){c()})},e.changePlan=function(){e.selfHosted||o.open({animation:!0,templateUrl:"app/organization/views/organizationBillingChangePlan.html",controller:"organizationBillingChangePlanController",resolve:{plan:function(){return e.plan}}}).result.then(function(){c()})},e.adjustSeats=function(t){!e.selfHosted&&e.canAdjustSeats&&o.open({animation:!0,templateUrl:"app/organization/views/organizationBillingAdjustSeats.html",controller:"organizationBillingAdjustSeatsController",resolve:{add:function(){return t}}}).result.then(function(){c()})},e.adjustStorage=function(t){e.selfHosted||o.open({animation:!0,templateUrl:"app/settings/views/settingsBillingAdjustStorage.html",controller:"organizationBillingAdjustStorageController",resolve:{add:function(){return t}}}).result.then(function(){c()})},e.verifyBank=function(){e.selfHosted||o.open({animation:!0,templateUrl:"app/organization/views/organizationBillingVerifyBank.html",controller:"organizationBillingVerifyBankController"}).result.then(function(){c()})},e.cancel=function(){e.selfHosted||confirm("Are you sure you want to cancel? All users will lose access to the organization at the end of this billing cycle.")&&t.organizations.putCancel({id:n.params.orgId},{}).$promise.then(function(e){a.eventTrack("Canceled Plan"),r.success("Organization subscription has been canceled."),c()})},e.reinstate=function(){e.selfHosted||confirm("Are you sure you want to remove the cancellation request and reinstate this organization?")&&t.organizations.putReinstate({id:n.params.orgId},{}).$promise.then(function(e){a.eventTrack("Reinstated Plan"),r.success("Organization cancellation request has been removed."),c()})},e.updateLicense=function(){e.selfHosted&&o.open({animation:!0,templateUrl:"app/settings/views/settingsBillingUpdateLicense.html",controller:"organizationBillingUpdateLicenseController"}).result.then(function(){c()})},e.license=function(){if(!e.selfHosted){var o=prompt("Enter your installation id");o&&""!==o&&t.organizations.getLicense({id:n.params.orgId,installationId:o},function(e){var t=JSON.stringify(e,null,2),n=new Blob([t]);if(window.navigator.msSaveOrOpenBlob)window.navigator.msSaveBlob(n,"bitwarden_organization_license.json");else{var o=window.document.createElement("a");o.href=window.URL.createObjectURL(n,{type:"text/plain"}),o.download="bitwarden_organization_license.json",document.body.appendChild(o),o.click(),document.body.removeChild(o)}},function(e){400===e.status?r.error("Invalid installation id."):r.error("Unable to generate license.")})}},e.viewInvoice=function(t){if(!e.selfHosted){var o=i.apiUri+"/organizations/"+n.params.orgId+"/billing-invoice/"+t.invoiceId+"?access_token="+s.getToken();l.open(o)}}}]),angular.module("bit.organization").controller("organizationBillingUpdateLicenseController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","validationService",function(e,t,n,o,r,a,i){r.eventTrack("organizationBillingUpdateLicenseController",{category:"Modal"}),e.submit=function(s){var l=document.getElementById("file").files;if(l&&l.length){var c=new FormData;c.append("license",l[0]),e.submitPromise=o.organizations.putLicense({id:t.params.orgId},c).$promise.then(function(e){r.eventTrack("Updated License"),a.success("You have updated your license."),n.close()})}else i.addError(s,"file","Select a license file.",!0)},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationBillingVerifyBankController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr",function(e,t,n,o,r,a){r.eventTrack("organizationBillingVerifyBankController",{category:"Modal"}),e.submit=function(){var i={amount1:e.amount1,amount2:e.amount2};e.submitPromise=o.organizations.postVerifyBank({id:t.params.orgId},i).$promise.then(function(e){r.eventTrack("Verified Bank Account"),a.success("You have successfully verified your bank account."),n.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationCollectionsAddController",["$scope","$state","$uibModalInstance","apiService","cipherService","$analytics","authService",function(e,t,n,o,r,a,i){a.eventTrack("organizationCollectionsAddController",{category:"Modal"});var s=0;e.groups=[],e.selectedGroups={},e.loading=!0,e.useGroups=!1,n.opened.then(function(){return i.getUserProfile()}).then(function(n){if(n.organizations){var r=n.organizations[t.params.orgId];e.useGroups=!!r.useGroups}return e.useGroups?o.groups.listOrganization({orgId:t.params.orgId}).$promise:null}).then(function(t){if(t){for(var n=[],o=0;o<t.Data.length;o++)n.push({id:t.Data[o].Id,name:t.Data[o].Name,accessAll:t.Data[o].AccessAll}),t.Data[o].AccessAll||s++;e.groups=n,e.loading=!1}else e.loading=!1}),e.toggleGroupSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.groups.length;o++)n[e.groups[o].id]={id:e.groups[o].id,readOnly:e.groups[o].id in e.selectedGroups&&e.selectedGroups[e.groups[o].id].readOnly};e.selectedGroups=n},e.toggleGroupSelection=function(t){t in e.selectedGroups?delete e.selectedGroups[t]:e.selectedGroups[t]={id:t,readOnly:!1}},e.toggleGroupReadOnlySelection=function(t){t.id in e.selectedGroups&&(e.selectedGroups[t.id].readOnly=!t.accessAll&&!e.selectedGroups[t.id].readOnly)},e.groupSelected=function(t){return t.id in e.selectedGroups||t.accessAll},e.allSelected=function(){return Object.keys(e.selectedGroups).length>=s},e.submit=function(i){var s=r.encryptCollection(i,t.params.orgId);if(e.useGroups)for(var l in s.groups=[],e.selectedGroups)if(e.selectedGroups.hasOwnProperty(l))for(var c=0;c<e.groups.length;c++)if(e.groups[c].id===e.selectedGroups[l].id){e.groups[c].accessAll||s.groups.push(e.selectedGroups[l]);break}e.submitPromise=o.collections.post({orgId:t.params.orgId},s,function(e){a.eventTrack("Created Collection");var o=r.decryptCollection(e,t.params.orgId,!0);n.close(o)}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationCollectionsController",["$scope","$state","apiService","$uibModal","cipherService","$filter","toastr","$analytics","$uibModalStack",function(e,t,n,o,r,a,i,s,l){e.collections=[],e.loading=!0,e.$on("$viewContentLoaded",function(){n.collections.listOrganization({orgId:t.params.orgId},function(n){e.collections=r.decryptCollections(n.Data,t.params.orgId,!0),e.loading=!1,t.params.search&&(l.dismissAll(),e.filterSearch=t.params.search,$("#filterSearch").focus())})}),e.$on("organizationCollectionsAdd",function(t,n){e.add()}),e.add=function(){o.open({animation:!0,templateUrl:"app/organization/views/organizationCollectionsAdd.html",controller:"organizationCollectionsAddController"}).result.then(function(t){e.collections.push(t)})},e.edit=function(t){o.open({animation:!0,templateUrl:"app/organization/views/organizationCollectionsEdit.html",controller:"organizationCollectionsEditController",resolve:{id:function(){return t.id}}}).result.then(function(t){var n=a("filter")(e.collections,{id:t.id},!0);n&&n.length>0&&(n[0].name=t.name)})},e.users=function(e){o.open({animation:!0,templateUrl:"app/organization/views/organizationCollectionsUsers.html",controller:"organizationCollectionsUsersController",size:"lg",resolve:{collection:function(){return e}}}).result.then(function(){})},e.groups=function(e){o.open({animation:!0,templateUrl:"app/organization/views/organizationCollectionsGroups.html",controller:"organizationCollectionsGroupsController",resolve:{collection:function(){return e}}}).result.then(function(){})},e.delete=function(o){confirm("Are you sure you want to delete this collection ("+o.name+")?")&&n.collections.del({orgId:t.params.orgId,id:o.id},function(){var t=e.collections.indexOf(o);t>-1&&e.collections.splice(t,1),s.eventTrack("Deleted Collection"),i.success(o.name+" has been deleted.","Collection Deleted")},function(){i.error(o.name+" was not able to be deleted.","Error")})}}]),angular.module("bit.organization").controller("organizationCollectionsEditController",["$scope","$state","$uibModalInstance","apiService","cipherService","$analytics","id","authService",function(e,t,n,o,r,a,i,s){a.eventTrack("organizationCollectionsEditController",{category:"Modal"});var l=0;e.collection={},e.groups=[],e.selectedGroups={},e.loading=!0,e.useGroups=!1,n.opened.then(function(){return o.collections.getDetails({orgId:t.params.orgId,id:i}).$promise}).then(function(t){e.collection=r.decryptCollection(t);var n={};if(t.Groups)for(var o=0;o<t.Groups.length;o++)n[t.Groups[o].Id]={id:t.Groups[o].Id,readOnly:t.Groups[o].ReadOnly};return e.selectedGroups=n,s.getUserProfile()}).then(function(n){if(n.organizations){var r=n.organizations[t.params.orgId];e.useGroups=!!r.useGroups}return e.useGroups?o.groups.listOrganization({orgId:t.params.orgId}).$promise:null}).then(function(t){if(t){for(var n=[],o=0;o<t.Data.length;o++)n.push({id:t.Data[o].Id,name:t.Data[o].Name,accessAll:t.Data[o].AccessAll}),t.Data[o].AccessAll||l++;e.groups=n,e.loading=!1}else e.loading=!1}),e.toggleGroupSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.groups.length;o++)n[e.groups[o].id]={id:e.groups[o].id,readOnly:e.groups[o].id in e.selectedGroups&&e.selectedGroups[e.groups[o].id].readOnly};e.selectedGroups=n},e.toggleGroupSelection=function(t){t in e.selectedGroups?delete e.selectedGroups[t]:e.selectedGroups[t]={id:t,readOnly:!1}},e.toggleGroupReadOnlySelection=function(t){t.id in e.selectedGroups&&(e.selectedGroups[t.id].readOnly=!t.accessAll&&!e.selectedGroups[t.id].readOnly)},e.groupSelected=function(t){return t.id in e.selectedGroups||t.accessAll},e.allSelected=function(){return Object.keys(e.selectedGroups).length>=l},e.submit=function(s){var l=r.encryptCollection(s,t.params.orgId);if(e.useGroups)for(var c in l.groups=[],e.selectedGroups)if(e.selectedGroups.hasOwnProperty(c))for(var u=0;u<e.groups.length;u++)if(e.groups[u].id===e.selectedGroups[c].id){e.groups[u].accessAll||l.groups.push(e.selectedGroups[c]);break}e.submitPromise=o.collections.put({orgId:t.params.orgId,id:i},l,function(e){a.eventTrack("Edited Collection");var o=r.decryptCollection(e,t.params.orgId,!0);n.close(o)}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationCollectionsUsersController",["$scope","$state","$uibModalInstance","apiService","cipherService","$analytics","collection","toastr",function(e,t,n,o,r,a,i,s){a.eventTrack("organizationCollectionsUsersController",{category:"Modal"}),e.loading=!0,e.collection=i,e.users=[],n.opened.then(function(){e.loading=!1,o.collections.listUsers({orgId:t.params.orgId,id:i.id},function(t){if(t&&t.Data.length){for(var n=[],o=0;o<t.Data.length;o++)n.push({organizationUserId:t.Data[o].OrganizationUserId,name:t.Data[o].Name,email:t.Data[o].Email,type:t.Data[o].Type,status:t.Data[o].Status,readOnly:t.Data[o].ReadOnly,accessAll:t.Data[o].AccessAll});e.users=n}})}),e.remove=function(n){confirm("Are you sure you want to remove this user ("+n.email+") from this collection ("+i.name+")?")&&o.collections.delUser({orgId:t.params.orgId,id:i.id,orgUserId:n.organizationUserId},null,function(){s.success(n.email+" has been removed.","User Removed"),a.eventTrack("Removed User From Collection");var t=e.users.indexOf(n);t>-1&&e.users.splice(t,1)},function(){s.error("Unable to remove user.","Error")})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationDashboardController",["$scope","authService","$state","appSettings",function(e,t,n,o){e.selfHosted=o.selfHosted,e.$on("$viewContentLoaded",function(){t.getUserProfile().then(function(t){t.organizations&&(e.orgProfile=t.organizations[n.params.orgId])})}),e.goBilling=function(){n.go("backend.org.billing",{orgId:n.params.orgId})}}]),angular.module("bit.organization").controller("organizationDeleteController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics",function(e,t,n,o,r,a,i,s){s.eventTrack("organizationDeleteController",{category:"Modal"}),e.submit=function(){e.submitPromise=r.hashPassword(e.masterPassword).then(function(e){return n.organizations.del({id:t.params.orgId},{masterPasswordHash:e}).$promise}).then(function(){return o.dismiss("cancel"),a.removeProfileOrganization(t.params.orgId),s.eventTrack("Deleted Organization"),t.go("backend.user.vault")}).then(function(){i.success("This organization and all associated data has been deleted.","Organization Deleted")})},e.close=function(){o.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationEventsController",["$scope","$state","apiService","$uibModal","$filter","toastr","$analytics","constants","eventService","$compile","$sce",function(e,t,n,o,r,a,i,s,l,c,u){e.events=[],e.orgUsers=[],e.loading=!0,e.continuationToken=null;var d=l.getDefaultDateFilters();e.filterStart=d.start,e.filterEnd=d.end,e.$on("$viewContentLoaded",function(){n.organizationUsers.list({orgId:t.params.orgId}).$promise.then(function(t){var n=[];for(p=0;p<t.Data.length;p++){var o={id:t.Data[p].Id,userId:t.Data[p].UserId,name:t.Data[p].Name,email:t.Data[p].Email};n.push(o);var r=o.name||o.email;m[o.userId]=r,g[o.id]=r}return e.orgUsers=n,f(!0)})}),e.refresh=function(){f(!0)},e.next=function(){f(!1)};var p=0,m={},g={};function f(o){var r=l.formatDateFilters(e.filterStart,e.filterEnd);if(!r.error)return o&&(e.continuationToken=null,e.events=[]),e.loading=!0,n.events.listOrganization({orgId:t.params.orgId,start:r.start,end:r.end,continuationToken:e.continuationToken}).$promise.then(function(t){e.continuationToken=t.ContinuationToken;var n=[];for(p=0;p<t.Data.length;p++){var o=t.Data[p].ActingUserId||t.Data[p].UserId,r=l.getEventInfo(t.Data[p]),a=c("<span>"+r.message+"</span>")(e);n.push({message:u.trustAsHtml(a[0].outerHTML),appIcon:r.appIcon,appName:r.appName,userId:o,userName:o&&m[o]||"-",date:t.Data[p].Date,ip:t.Data[p].IpAddress})}e.events&&e.events.length>0?e.events=e.events.concat(n):e.events=n,e.loading=!1});alert(r.error)}}]),angular.module("bit.organization").controller("organizationGroupsAddController",["$scope","$state","$uibModalInstance","apiService","cipherService","$analytics",function(e,t,n,o,r,a){a.eventTrack("organizationGroupsAddController",{category:"Modal"}),e.collections=[],e.selectedCollections={},e.loading=!0,n.opened.then(function(){return o.collections.listOrganization({orgId:t.params.orgId}).$promise}).then(function(n){e.collections=r.decryptCollections(n.Data,t.params.orgId,!0),e.loading=!1}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.collections.length;o++)n[e.collections[o].id]={id:e.collections[o].id,readOnly:e.collections[o].id in e.selectedCollections&&e.selectedCollections[e.collections[o].id].readOnly};e.selectedCollections=n},e.toggleCollectionSelection=function(t){t in e.selectedCollections?delete e.selectedCollections[t]:e.selectedCollections[t]={id:t,readOnly:!1}},e.toggleCollectionReadOnlySelection=function(t){t in e.selectedCollections&&(e.selectedCollections[t].readOnly=!e.selectedCollections[t].readOnly)},e.collectionSelected=function(t){return t.id in e.selectedCollections},e.allSelected=function(){return Object.keys(e.selectedCollections).length===e.collections.length},e.submit=function(r){var i={name:r.name,accessAll:!!r.accessAll,externalId:r.externalId};if(!i.accessAll)for(var s in i.collections=[],e.selectedCollections)e.selectedCollections.hasOwnProperty(s)&&i.collections.push(e.selectedCollections[s]);e.submitPromise=o.groups.post({orgId:t.params.orgId},i,function(e){a.eventTrack("Created Group"),n.close({id:e.Id,name:e.Name})}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationGroupsController",["$scope","$state","apiService","$uibModal","$filter","toastr","$analytics","$uibModalStack",function(e,t,n,o,r,a,i,s){e.groups=[],e.loading=!0,e.$on("$viewContentLoaded",function(){n.groups.listOrganization({orgId:t.params.orgId},function(n){for(var o=[],r=0;r<n.Data.length;r++)o.push({id:n.Data[r].Id,name:n.Data[r].Name});e.groups=o,e.loading=!1,t.params.search&&(s.dismissAll(),e.filterSearch=t.params.search,$("#filterSearch").focus())})}),e.$on("organizationGroupsAdd",function(t,n){e.add()}),e.add=function(){o.open({animation:!0,templateUrl:"app/organization/views/organizationGroupsAdd.html",controller:"organizationGroupsAddController"}).result.then(function(t){e.groups.push(t)})},e.edit=function(t){o.open({animation:!0,templateUrl:"app/organization/views/organizationGroupsEdit.html",controller:"organizationGroupsEditController",resolve:{id:function(){return t.id}}}).result.then(function(t){var n=r("filter")(e.groups,{id:t.id},!0);n&&n.length>0&&(n[0].name=t.name)})},e.users=function(e){o.open({animation:!0,templateUrl:"app/organization/views/organizationGroupsUsers.html",controller:"organizationGroupsUsersController",size:"lg",resolve:{group:function(){return e}}}).result.then(function(){})},e.delete=function(o){confirm("Are you sure you want to delete this group ("+o.name+")?")&&n.groups.del({orgId:t.params.orgId,id:o.id},function(){var t=e.groups.indexOf(o);t>-1&&e.groups.splice(t,1),i.eventTrack("Deleted Group"),a.success(o.name+" has been deleted.","Group Deleted")},function(){a.error(o.name+" was not able to be deleted.","Error")})}}]),angular.module("bit.organization").controller("organizationGroupsEditController",["$scope","$state","$uibModalInstance","apiService","cipherService","$analytics","id",function(e,t,n,o,r,a,i){a.eventTrack("organizationGroupsEditController",{category:"Modal"}),e.collections=[],e.selectedCollections={},e.loading=!0,n.opened.then(function(){return o.groups.getDetails({orgId:t.params.orgId,id:i}).$promise}).then(function(n){e.group={id:i,name:n.Name,externalId:n.ExternalId,accessAll:n.AccessAll};var r={};if(n.Collections)for(var a=0;a<n.Collections.length;a++)r[n.Collections[a].Id]={id:n.Collections[a].Id,readOnly:n.Collections[a].ReadOnly};return e.selectedCollections=r,o.collections.listOrganization({orgId:t.params.orgId}).$promise}).then(function(n){e.collections=r.decryptCollections(n.Data,t.params.orgId,!0),e.loading=!1}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.collections.length;o++)n[e.collections[o].id]={id:e.collections[o].id,readOnly:e.collections[o].id in e.selectedCollections&&e.selectedCollections[e.collections[o].id].readOnly};e.selectedCollections=n},e.toggleCollectionSelection=function(t){t in e.selectedCollections?delete e.selectedCollections[t]:e.selectedCollections[t]={id:t,readOnly:!1}},e.toggleCollectionReadOnlySelection=function(t){t in e.selectedCollections&&(e.selectedCollections[t].readOnly=!e.selectedCollections[t].readOnly)},e.collectionSelected=function(t){return t.id in e.selectedCollections},e.allSelected=function(){return Object.keys(e.selectedCollections).length===e.collections.length},e.submit=function(){var r={name:e.group.name,accessAll:!!e.group.accessAll,externalId:e.group.externalId};if(!r.accessAll)for(var s in r.collections=[],e.selectedCollections)e.selectedCollections.hasOwnProperty(s)&&r.collections.push(e.selectedCollections[s]);e.submitPromise=o.groups.put({orgId:t.params.orgId,id:i},r,function(e){a.eventTrack("Edited Group"),n.close({id:e.Id,name:e.Name})}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationGroupsUsersController",["$scope","$state","$uibModalInstance","apiService","$analytics","group","toastr",function(e,t,n,o,r,a,i){r.eventTrack("organizationGroupUsersController",{category:"Modal"}),e.loading=!0,e.group=a,e.users=[],n.opened.then(function(){return o.groups.listUsers({orgId:t.params.orgId,id:a.id}).$promise}).then(function(t){var n=[];if(t&&t.Data.length)for(var o=0;o<t.Data.length;o++)n.push({organizationUserId:t.Data[o].OrganizationUserId,name:t.Data[o].Name,email:t.Data[o].Email,type:t.Data[o].Type,status:t.Data[o].Status,accessAll:t.Data[o].AccessAll});e.users=n,e.loading=!1}),e.remove=function(n){confirm("Are you sure you want to remove this user ("+n.email+") from this group ("+a.name+")?")&&o.groups.delUser({orgId:t.params.orgId,id:a.id,orgUserId:n.organizationUserId},null,function(){i.success(n.email+" has been removed.","User Removed"),r.eventTrack("Removed User From Group");var t=e.users.indexOf(n);t>-1&&e.users.splice(t,1)},function(){i.error("Unable to remove user.","Error")})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationPeopleController",["$scope","$state","$uibModal","cryptoService","apiService","authService","toastr","$analytics","$filter","$uibModalStack",function(e,t,n,o,r,a,i,s,l,c){function u(){r.organizationUsers.list({orgId:t.params.orgId},function(n){for(var o=[],r=0;r<n.Data.length;r++){var a={id:n.Data[r].Id,userId:n.Data[r].UserId,name:n.Data[r].Name,email:n.Data[r].Email,status:n.Data[r].Status,type:n.Data[r].Type,accessAll:n.Data[r].AccessAll};o.push(a)}if(e.users=o,t.params.search&&(c.dismissAll(),e.filterSearch=t.params.search,$("#filterSearch").focus()),t.params.viewEvents){c.dismissAll();var i=l("filter")(e.users,{id:t.params.viewEvents});i&&i.length&&e.events(i[0])}})}e.users=[],e.useGroups=!1,e.useEvents=!1,e.$on("$viewContentLoaded",function(){u(),a.getUserProfile().then(function(n){if(n.organizations){var o=n.organizations[t.params.orgId];e.useGroups=!!o.useGroups,e.useEvents=!!o.useEvents}})}),e.reinvite=function(e){r.organizationUsers.reinvite({orgId:t.params.orgId,id:e.id},null,function(){s.eventTrack("Reinvited User"),i.success(e.email+" has been invited again.","User Invited")},function(){i.error("Unable to invite user.","Error")})},e.delete=function(n){confirm("Are you sure you want to remove this user ("+n.email+")?")&&r.organizationUsers.del({orgId:t.params.orgId,id:n.id},null,function(){s.eventTrack("Deleted User"),i.success(n.email+" has been removed.","User Removed");var t=e.users.indexOf(n);t>-1&&e.users.splice(t,1)},function(){i.error("Unable to remove user.","Error")})},e.confirm=function(e){r.users.getPublicKey({id:e.userId},function(n){var a=o.getOrgKey(t.params.orgId);if(a){var l=o.rsaEncrypt(a.key,n.PublicKey);r.organizationUsers.confirm({orgId:t.params.orgId,id:e.id},{key:l},function(){e.status=2,s.eventTrack("Confirmed User"),i.success(e.email+" has been confirmed.","User Confirmed")},function(){i.error("Unable to confirm user.","Error")})}else i.error("Unable to confirm user.","Error")},function(){i.error("Unable to confirm user.","Error")})},e.$on("organizationPeopleInvite",function(t,n){e.invite()}),e.invite=function(){n.open({animation:!0,templateUrl:"app/organization/views/organizationPeopleInvite.html",controller:"organizationPeopleInviteController"}).result.then(function(){u()})},e.edit=function(e){n.open({animation:!0,templateUrl:"app/organization/views/organizationPeopleEdit.html",controller:"organizationPeopleEditController",resolve:{orgUser:function(){return e}}}).result.then(function(){u()})},e.groups=function(e){n.open({animation:!0,templateUrl:"app/organization/views/organizationPeopleGroups.html",controller:"organizationPeopleGroupsController",resolve:{orgUser:function(){return e}}}).result.then(function(){})},e.events=function(e){n.open({animation:!0,templateUrl:"app/organization/views/organizationPeopleEvents.html",controller:"organizationPeopleEventsController",resolve:{orgUser:function(){return e},orgId:function(){return t.params.orgId}}})}}]),angular.module("bit.organization").controller("organizationPeopleEditController",["$scope","$state","$uibModalInstance","apiService","cipherService","orgUser","$analytics",function(e,t,n,o,r,a,i){i.eventTrack("organizationPeopleEditController",{category:"Modal"}),e.loading=!0,e.collections=[],e.selectedCollections={},n.opened.then(function(){o.collections.listOrganization({orgId:t.params.orgId},function(n){e.collections=r.decryptCollections(n.Data,t.params.orgId,!0),e.loading=!1}),o.organizationUsers.get({orgId:t.params.orgId,id:a.id},function(t){var n={};if(t&&t.Collections)for(var o=0;o<t.Collections.length;o++)n[t.Collections[o].Id]={id:t.Collections[o].Id,readOnly:t.Collections[o].ReadOnly};e.email=a.email,e.type=t.Type,e.accessAll=t.AccessAll,e.selectedCollections=n})}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.collections.length;o++)n[e.collections[o].id]={id:e.collections[o].id,readOnly:e.collections[o].id in e.selectedCollections&&e.selectedCollections[e.collections[o].id].readOnly};e.selectedCollections=n},e.toggleCollectionSelection=function(t){t in e.selectedCollections?delete e.selectedCollections[t]:e.selectedCollections[t]={id:t,readOnly:!1}},e.toggleCollectionReadOnlySelection=function(t){t in e.selectedCollections&&(e.selectedCollections[t].readOnly=!e.selectedCollections[t].readOnly)},e.collectionSelected=function(t){return t.id in e.selectedCollections},e.allSelected=function(){return Object.keys(e.selectedCollections).length===e.collections.length},e.submitPromise=null,e.submit=function(r){var s=[];if(!e.accessAll)for(var l in e.selectedCollections)e.selectedCollections.hasOwnProperty(l)&&s.push(e.selectedCollections[l]);e.submitPromise=o.organizationUsers.put({orgId:t.params.orgId,id:a.id},{type:e.type,collections:s,accessAll:e.accessAll},function(){i.eventTrack("Edited User"),n.close()}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationPeopleEventsController",["$scope","apiService","$uibModalInstance","orgUser","$analytics","eventService","orgId","$compile","$sce",function(e,t,n,o,r,a,i,s,l){r.eventTrack("organizationPeopleEventsController",{category:"Modal"}),e.email=o.email,e.events=[],e.loading=!0,e.continuationToken=null;var c=a.getDefaultDateFilters();function u(n){var r=a.formatDateFilters(e.filterStart,e.filterEnd);if(!r.error)return n&&(e.continuationToken=null,e.events=[]),e.loading=!0,t.events.listOrganizationUser({orgId:i,id:o.id,start:r.start,end:r.end,continuationToken:e.continuationToken}).$promise.then(function(t){e.continuationToken=t.ContinuationToken;for(var n=[],o=0;o<t.Data.length;o++){var r=a.getEventInfo(t.Data[o]),i=s("<span>"+r.message+"</span>")(e);n.push({message:l.trustAsHtml(i[0].outerHTML),appIcon:r.appIcon,appName:r.appName,date:t.Data[o].Date,ip:t.Data[o].IpAddress})}e.events&&e.events.length>0?e.events=e.events.concat(n):e.events=n,e.loading=!1});alert(r.error)}e.filterStart=c.start,e.filterEnd=c.end,n.opened.then(function(){u(!0)}),e.refresh=function(){u(!0)},e.next=function(){u(!1)},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationPeopleGroupsController",["$scope","$state","$uibModalInstance","apiService","orgUser","$analytics",function(e,t,n,o,r,a){a.eventTrack("organizationPeopleGroupsController",{category:"Modal"}),e.loading=!0,e.groups=[],e.selectedGroups={},e.orgUser=r,n.opened.then(function(){return o.groups.listOrganization({orgId:t.params.orgId}).$promise}).then(function(n){for(var a=[],i=0;i<n.Data.length;i++)a.push({id:n.Data[i].Id,name:n.Data[i].Name});return e.groups=a,o.organizationUsers.listGroups({orgId:t.params.orgId,id:r.id}).$promise}).then(function(t){var n={};if(t)for(var o=0;o<t.length;o++)n[t[o]]=!0;e.selectedGroups=n,e.loading=!1}),e.toggleGroupSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.groups.length;o++)n[e.groups[o].id]=!0;e.selectedGroups=n},e.toggleGroupSelection=function(t){t in e.selectedGroups?delete e.selectedGroups[t]:e.selectedGroups[t]=!0},e.groupSelected=function(t){return t.id in e.selectedGroups},e.allSelected=function(){return Object.keys(e.selectedGroups).length===e.groups.length},e.submitPromise=null,e.submit=function(i){var s=[];for(var l in e.selectedGroups)e.selectedGroups.hasOwnProperty(l)&&s.push(l);e.submitPromise=o.organizationUsers.putGroups({orgId:t.params.orgId,id:r.id},{groupIds:s},function(){a.eventTrack("Edited User Groups"),n.close()}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationPeopleInviteController",["$scope","$state","$uibModalInstance","apiService","cipherService","$analytics",function(e,t,n,o,r,a){a.eventTrack("organizationPeopleInviteController",{category:"Modal"}),e.loading=!0,e.collections=[],e.selectedCollections={},e.model={type:"User"},n.opened.then(function(){o.collections.listOrganization({orgId:t.params.orgId},function(n){e.collections=r.decryptCollections(n.Data,t.params.orgId,!0),e.loading=!1})}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.collections.length;o++)n[e.collections[o].id]={id:e.collections[o].id,readOnly:e.collections[o].id in e.selectedCollections&&e.selectedCollections[e.collections[o].id].readOnly};e.selectedCollections=n},e.toggleCollectionSelection=function(t){t in e.selectedCollections?delete e.selectedCollections[t]:e.selectedCollections[t]={id:t,readOnly:!1}},e.toggleCollectionReadOnlySelection=function(t){t in e.selectedCollections&&(e.selectedCollections[t].readOnly=!e.selectedCollections[t].readOnly)},e.collectionSelected=function(t){return t.id in e.selectedCollections},e.allSelected=function(){return Object.keys(e.selectedCollections).length===e.collections.length},e.submitPromise=null,e.submit=function(r){var i=[];if(!r.accessAll)for(var s in e.selectedCollections)e.selectedCollections.hasOwnProperty(s)&&i.push(e.selectedCollections[s]);var l=r.emails.trim().split(/\s*,\s*/);e.submitPromise=o.organizationUsers.invite({orgId:t.params.orgId},{emails:l,type:r.type,collections:i,accessAll:r.accessAll},function(){a.eventTrack("Invited User"),n.close()}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationSettingsController",["$scope","$state","apiService","toastr","authService","$uibModal","$analytics","appSettings",function(e,t,n,o,r,a,i,s){e.selfHosted=s.selfHosted,e.model={},e.$on("$viewContentLoaded",function(){n.organizations.get({id:t.params.orgId},function(t){e.model={name:t.Name,billingEmail:t.BillingEmail,businessName:t.BusinessName,businessAddress1:t.BusinessAddress1,businessAddress2:t.BusinessAddress2,businessAddress3:t.BusinessAddress3,businessCountry:t.BusinessCountry,businessTaxNumber:t.BusinessTaxNumber}})}),e.generalSave=function(){e.selfHosted||(e.generalPromise=n.organizations.put({id:t.params.orgId},e.model,function(e){r.updateProfileOrganization(e).then(function(e){i.eventTrack("Updated Organization Settings"),o.success("Organization has been updated.","Success!")})}).$promise)},e.import=function(){a.open({animation:!0,templateUrl:"app/tools/views/toolsImport.html",controller:"organizationSettingsImportController"})},e.export=function(){a.open({animation:!0,templateUrl:"app/tools/views/toolsExport.html",controller:"organizationSettingsExportController"})},e.delete=function(){a.open({animation:!0,templateUrl:"app/organization/views/organizationDelete.html",controller:"organizationDeleteController"})}}]),angular.module("bit.organization").controller("organizationSettingsExportController",["$scope","apiService","$uibModalInstance","cipherService","$q","toastr","$analytics","$state","constants",function(e,t,n,o,r,a,i,s,l){function c(){var e=new Date;return"bitwarden_org_export_"+(e.getFullYear()+""+u(e.getMonth()+1,2)+u(e.getDate(),2)+u(e.getHours(),2)+u(e.getMinutes(),2)+u(e.getSeconds(),2))+".csv"}function u(e,t,n){return n=n||"0",(e+="").length>=t?e:new Array(t-e.length+1).join(n)+e}i.eventTrack("organizationSettingsExportController",{category:"Modal"}),e.export=function(n){e.startedExport=!0;var u=[],d=[],p=t.collections.listOrganization({orgId:s.params.orgId},function(e){d=o.decryptCollections(e.Data,s.params.orgId,!0)}).$promise,m=t.ciphers.listOrganizationDetails({organizationId:s.params.orgId},function(e){u=o.decryptCiphers(e.Data)}).$promise;r.all([p,m]).then(function(){if(!u.length)return a.error("Nothing to export.","Error!"),void e.close();for(var t={},n=0;n<d.length;n++)t[d[n].id]=d[n];try{var o=[];for(n=0;n<u.length;n++)if(u[n].type===l.cipherType.login||u[n].type===l.cipherType.secureNote){var r,s={collections:[],type:null,name:u[n].name,notes:u[n].notes,fields:null,login_uri:null,login_username:null,login_password:null,login_totp:null};if(u[n].collectionIds)for(r=0;r<u[n].collectionIds.length;r++)t.hasOwnProperty(u[n].collectionIds[r])&&s.collections.push(t[u[n].collectionIds[r]].name);if(u[n].fields)for(r=0;r<u[n].fields.length;r++)s.fields?s.fields+="\n":s.fields="",s.fields+=(u[n].fields[r].name||"")+": "+u[n].fields[r].value;switch(u[n].type){case l.cipherType.login:s.type="login",s.login_uri=u[n].login.uri,s.login_username=u[n].login.username,s.login_password=u[n].login.password,s.login_totp=u[n].login.totp;break;case l.cipherType.secureNote:s.type="note";break;default:continue}o.push(s)}var p=Papa.unparse(o),m=new Blob([p]);if(window.navigator.msSaveOrOpenBlob)window.navigator.msSaveBlob(m,c());else{var g=window.document.createElement("a");g.href=window.URL.createObjectURL(m,{type:"text/plain"}),g.download=c(),document.body.appendChild(g),g.click(),document.body.removeChild(g)}i.eventTrack("Exported Organization Data"),a.success("Your data has been exported. Check your browser's downloads folder.","Success!"),e.close()}catch(t){a.error("Something went wrong. Please try again.","Error!"),e.close()}},function(){a.error("Something went wrong. Please try again.","Error!"),e.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationSettingsImportController",["$scope","$state","apiService","$uibModalInstance","cipherService","toastr","importService","$analytics","$sce","validationService","cryptoService",function(e,t,n,o,r,a,i,s,l,c,u){function d(i,l,c){if(i.length||l.length){if(l.length){var d=Math.floor(l.length/2),g=l.length-1;if(p(l[0])&&p(l[d])&&p(l[g]))return void m("Data is not formatted correctly. Please check your import file and try again.")}n.ciphers.importOrg({orgId:t.params.orgId},{collections:r.encryptCollections(i,t.params.orgId),ciphers:r.encryptCiphers(l,u.getOrgKey(t.params.orgId)),collectionRelationships:c},function(){o.dismiss("cancel"),t.go("backend.org.vault",{orgId:t.params.orgId}).then(function(){s.eventTrack("Imported Org Data",{label:e.model.source}),a.success("Data has been successfully imported into your vault.","Import Success")})},m)}else m("Nothing was imported.")}function p(e){return(null===e.name||"--"===e.name)&&e.login&&(null===e.login.password||""===e.login.password)}function m(t){if(s.eventTrack("Import Org Data Failed",{label:e.model.source}),o.dismiss("cancel"),t){var n=t.data;if(!n||!n.ValidationErrors)return n&&n.Message?void a.error(n.Message):void a.error(t);var r="";for(var i in n.ValidationErrors)if(n.ValidationErrors.hasOwnProperty(i))for(var l=0;l<n.ValidationErrors[i].length;l++)r+=i+": "+n.ValidationErrors[i][l]+" ";if(""!==r)return void a.error(r)}a.error("Something went wrong. Try again.","Oh No!")}s.eventTrack("organizationSettingsImportController",{category:"Modal"}),e.model={source:""},e.source={},e.splitFeatured=!1,e.options=[{id:"bitwardencsv",name:"bitwarden (csv)",featured:!0,sort:1,instructions:l.trustAsHtml('Export using the web vault (vault.bitwarden.com). Log into the web vault and navigate to your organization\'s admin area. Then to go "Settings" > "Tools" > "Export".')},{id:"lastpass",name:"LastPass (csv)",featured:!0,sort:2,instructions:l.trustAsHtml('See detailed instructions on our help site at <a target="_blank" href="https://help.bitwarden.com/article/import-from-lastpass/">https://help.bitwarden.com/article/import-from-lastpass/</a>')}],e.setSource=function(){for(var t=0;t<e.options.length;t++)if(e.options[t].id===e.model.source){e.source=e.options[t];break}},e.setSource(),e.import=function(t,n){if(t.source&&""!==t.source){var o=document.getElementById("file").files[0];o||t.fileContents&&""!==t.fileContents?(e.processing=!0,i.importOrg(t.source,o||t.fileContents,d,m)):c.addError(n,"file","Select the import file or copy/paste the import file contents.",!0)}else c.addError(n,"source","Select the format of the import file.",!0)},e.close=function(){o.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationVaultAddCipherController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","passwordService","$analytics","authService","orgId","$uibModal","constants",function(e,t,n,o,r,a,i,s,l,c,u){function d(e){var t=$(e.trigger).parent().prev();"text"===t.attr("type")&&t.select()}i.eventTrack("organizationVaultAddCipherController",{category:"Modal"}),e.constants=u,e.selectedType=u.cipherType.login.toString(),e.cipher={type:u.cipherType.login,login:{},identity:{},card:{},secureNote:{type:"0"}},e.hideFolders=e.hideFavorite=e.fromOrg=!0,s.getUserProfile().then(function(t){var n=t.organizations[l];e.useTotp=n.useTotp}),e.typeChanged=function(){e.cipher.type=parseInt(e.selectedType)},e.savePromise=null,e.save=function(){e.cipher.organizationId=l;var o=r.encryptCipher(e.cipher);e.savePromise=t.ciphers.postAdmin(o,function(e){i.eventTrack("Created Organization Cipher");var t=r.decryptCipherPreview(e);n.close(t)}).$promise},e.generatePassword=function(){e.cipher.login.password&&!confirm("Are you sure you want to overwrite the current password?")||(i.eventTrack("Generated Password From Add"),e.cipher.login.password=a.generatePassword({length:14,special:!0}))},e.addField=function(){e.cipher.fields||(e.cipher.fields=[]),e.cipher.fields.push({type:u.fieldType.text.toString(),name:null,value:null})},e.removeField=function(t){var n=e.cipher.fields.indexOf(t);n>-1&&e.cipher.fields.splice(n,1)},e.clipboardSuccess=function(e){e.clearSelection(),d(e)},e.clipboardError=function(e,t){t&&d(e),alert("Your web browser does not support easy clipboard copying. Copy it manually instead.")},e.close=function(){n.dismiss("close")},e.showUpgrade=function(){c.open({animation:!0,templateUrl:"app/views/paidOrgRequired.html",controller:"paidOrgRequiredController",resolve:{orgId:function(){return l}}})}}]),angular.module("bit.organization").controller("organizationVaultAttachmentsController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","cipherId","$analytics","validationService","toastr","$timeout",function(e,t,n,o,r,a,i,s,l,c){i.eventTrack("organizationVaultAttachmentsController",{category:"Modal"}),e.cipher={},e.loading=!0,e.isPremium=!0,e.canUseAttachments=!0;var u=!1;t.ciphers.getAdmin({id:a},function(t){e.cipher=r.decryptCipher(t),e.loading=!1},function(){e.loading=!1}),e.save=function(c){var d=document.getElementById("file").files;if(d&&d.length){var p=o.getOrgKey(e.cipher.organizationId);e.savePromise=r.encryptAttachmentFile(p,d[0]).then(function(e){var n=new FormData,o=new Blob([e.data],{type:"application/octet-stream"});return n.append("data",o,e.fileName),t.ciphers.postAttachment({id:a},n).$promise}).then(function(e){i.eventTrack("Added Attachment"),l.success("The attachment has been added."),u=!0,n.close(!0)},function(e){var t=s.parseErrors(e);l.error(t.length?t[0]:"An error occurred.")})}else s.addError(c,"file","Select a file.",!0)},e.download=function(t){t.loading=!0;var n=o.getOrgKey(e.cipher.organizationId);r.downloadAndDecryptAttachment(n,t,!0).then(function(e){c(function(){t.loading=!1})},function(){c(function(){t.loading=!1})})},e.remove=function(n){confirm("Are you sure you want to delete this attachment ("+n.fileName+")?")&&(n.loading=!0,t.ciphers.delAttachment({id:a,attachmentId:n.id}).$promise.then(function(){n.loading=!1,i.eventTrack("Deleted Organization Attachment");var t=e.cipher.attachments.indexOf(n);t>-1&&e.cipher.attachments.splice(t,1)},function(){l.error("Cannot delete attachment."),n.loading=!1}))},e.close=function(){n.dismiss("cancel")},e.$on("modal.closing",function(t,o,r){u||(t.preventDefault(),u=!0,n.close(!!e.cipher.attachments&&e.cipher.attachments.length>0))})}]),angular.module("bit.organization").controller("organizationVaultCipherCollectionsController",["$scope","apiService","$uibModalInstance","cipherService","cipher","$analytics","collections",function(e,t,n,o,r,a,i){a.eventTrack("organizationVaultCipherCollectionsController",{category:"Modal"}),e.cipher={},e.collections=[],e.selectedCollections={},n.opened.then(function(){for(var t=[],n=0;n<i.length;n++)i[n].id&&t.push(i[n]);e.collections=t,e.cipher=r;var o={};if(e.cipher.collectionIds)for(n=0;n<e.cipher.collectionIds.length;n++)o[e.cipher.collectionIds[n]]=!0;e.selectedCollections=o}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.collections.length;o++)n[e.collections[o].id]=!0;e.selectedCollections=n},e.toggleCollectionSelection=function(t){t in e.selectedCollections?delete e.selectedCollections[t]:e.selectedCollections[t]=!0},e.collectionSelected=function(t){return t.id in e.selectedCollections},e.allSelected=function(){return Object.keys(e.selectedCollections).length===e.collections.length},e.submit=function(){var o={collectionIds:[]};for(var i in e.selectedCollections)e.selectedCollections.hasOwnProperty(i)&&o.collectionIds.push(i);e.submitPromise=t.ciphers.putCollectionsAdmin({id:r.id},o).$promise.then(function(e){a.eventTrack("Edited Cipher Collections"),n.close({action:"collectionsEdit",collectionIds:o.collectionIds})})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationVaultCipherEventsController",["$scope","apiService","$uibModalInstance","cipher","$analytics","eventService",function(e,t,n,o,r,a){r.eventTrack("organizationVaultCipherEventsController",{category:"Modal"}),e.cipher=o,e.events=[],e.loading=!0,e.continuationToken=null;var i=a.getDefaultDateFilters();e.filterStart=i.start,e.filterEnd=i.end,n.opened.then(function(){t.organizationUsers.list({orgId:o.organizationId}).$promise.then(function(t){var n=[];for(s=0;s<t.Data.length;s++){var o={id:t.Data[s].Id,userId:t.Data[s].UserId,name:t.Data[s].Name,email:t.Data[s].Email};n.push(o);var r=o.name||o.email;l[o.userId]=r,c[o.id]=r}return e.orgUsers=n,u(!0)})}),e.refresh=function(){u(!0)},e.next=function(){u(!1)};var s=0,l={},c={};function u(n){var r=a.formatDateFilters(e.filterStart,e.filterEnd);if(!r.error)return n&&(e.continuationToken=null,e.events=[]),e.loading=!0,t.events.listCipher({id:o.id,start:r.start,end:r.end,continuationToken:e.continuationToken}).$promise.then(function(t){e.continuationToken=t.ContinuationToken;var n=[];for(s=0;s<t.Data.length;s++){var o=t.Data[s].ActingUserId||t.Data[s].UserId,r=a.getEventInfo(t.Data[s],{cipherInfo:!1});n.push({message:r.message,appIcon:r.appIcon,appName:r.appName,userId:o,userName:o&&l[o]||"-",date:t.Data[s].Date,ip:t.Data[s].IpAddress})}e.events&&e.events.length>0?e.events=e.events.concat(n):e.events=n,e.loading=!1});alert(r.error)}e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationVaultController",["$scope","apiService","cipherService","$analytics","$q","$state","$localStorage","$uibModal","$filter","authService","$uibModalStack",function(e,t,n,o,r,a,i,s,l,c,u){e.ciphers=[],e.collections=[],e.loading=!0,e.useEvents=!1,e.$on("$viewContentLoaded",function(){c.getUserProfile().then(function(t){if(t.organizations){var n=t.organizations[a.params.orgId];e.useEvents=!!n.useEvents}});var o=t.collections.listOrganization({orgId:a.params.orgId},function(t){for(var o=([{id:null,name:"Unassigned",collapsed:i.collapsedOrgCollections&&"unassigned"in i.collapsedOrgCollections}]),r=0;r<t.Data.length;r++){var a=n.decryptCollection(t.Data[r],null,!0);a.collapsed=i.collapsedOrgCollections&&a.id in i.collapsedOrgCollections,o.push(a)}e.collections=o}).$promise,s=t.ciphers.listOrganizationDetails({organizationId:a.params.orgId},function(t){for(var o=[],r=0;r<t.Data.length;r++){var a=n.decryptCipherPreview(t.Data[r]);o.push(a)}e.ciphers=o}).$promise;r.all([o,s]).then(function(){if(e.loading=!1,$("#search").focus(),a.params.search&&(u.dismissAll(),e.$emit("setSearchVaultText",a.params.search)),a.params.viewEvents){u.dismissAll();var t=l("filter")(e.ciphers,{id:a.params.viewEvents});t&&t.length&&e.viewEvents(t[0])}})}),e.filterByCollection=function(e){return function(t){return t.collectionIds&&t.collectionIds.length?t.collectionIds.indexOf(e.id)>-1:null===e.id}},e.collectionSort=function(e){return e.id?e.name.toLowerCase():""},e.collapseExpand=function(e){i.collapsedOrgCollections||(i.collapsedOrgCollections={});var t=e.id||"unassigned";t in i.collapsedOrgCollections?delete i.collapsedOrgCollections[t]:i.collapsedOrgCollections[t]=!0},e.editCipher=function(t){s.open({animation:!0,templateUrl:"app/vault/views/vaultEditCipher.html",controller:"organizationVaultEditCipherController",resolve:{cipherId:function(){return t.id},orgId:function(){return a.params.orgId}}}).result.then(function(n){var o;"edit"===n.action?(o=e.ciphers.indexOf(t))>-1&&(n.data.collectionIds=e.ciphers[o].collectionIds,e.ciphers[o]=n.data):"delete"===n.action&&(o=e.ciphers.indexOf(t))>-1&&e.ciphers.splice(o,1)})},e.$on("organizationVaultAddCipher",function(t,n){e.addCipher()}),e.addCipher=function(){s.open({animation:!0,templateUrl:"app/vault/views/vaultAddCipher.html",controller:"organizationVaultAddCipherController",resolve:{orgId:function(){return a.params.orgId}}}).result.then(function(t){e.ciphers.push(t)})},e.editCollections=function(t){s.open({animation:!0,templateUrl:"app/organization/views/organizationVaultCipherCollections.html",controller:"organizationVaultCipherCollectionsController",resolve:{cipher:function(){return t},collections:function(){return e.collections}}}).result.then(function(e){e.collectionIds&&(t.collectionIds=e.collectionIds)})},e.viewEvents=function(e){s.open({animation:!0,templateUrl:"app/organization/views/organizationVaultCipherEvents.html",controller:"organizationVaultCipherEventsController",resolve:{cipher:function(){return e}}})},e.attachments=function(e){c.getUserProfile().then(function(t){return!!t.organizations[e.organizationId].maxStorageGb}).then(function(t){t?s.open({animation:!0,templateUrl:"app/vault/views/vaultAttachments.html",controller:"organizationVaultAttachmentsController",resolve:{cipherId:function(){return e.id}}}).result.then(function(t){e.hasAttachments=t}):s.open({animation:!0,templateUrl:"app/views/paidOrgRequired.html",controller:"paidOrgRequiredController",resolve:{orgId:function(){return e.organizationId}}})})},e.removeCipher=function(e,n){if(confirm("Are you sure you want to remove this item ("+e.name+") from the collection ("+n.name+") ?")){for(var r={collectionIds:[]},a=0;a<e.collectionIds.length;a++)e.collectionIds[a]!==n.id&&r.collectionIds.push(e.collectionIds[a]);t.ciphers.putCollections({id:e.id},r).$promise.then(function(t){o.eventTrack("Removed Cipher From Collection"),e.collectionIds=r.collectionIds})}},e.deleteCipher=function(n){confirm("Are you sure you want to delete this item ("+n.name+")?")&&t.ciphers.delAdmin({id:n.id},function(){o.eventTrack("Deleted Cipher");var t=e.ciphers.indexOf(n);t>-1&&e.ciphers.splice(t,1)})}}]),angular.module("bit.organization").controller("organizationVaultEditCipherController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","passwordService","cipherId","$analytics","orgId","$uibModal","constants",function(e,t,n,o,r,a,i,s,l,c,u){function d(e){var t=$(e.trigger).parent().prev();"text"===t.attr("type")&&t.select()}s.eventTrack("organizationVaultEditCipherController",{category:"Modal"}),e.cipher={},e.hideFolders=e.hideFavorite=e.fromOrg=!0,e.constants=u,t.ciphers.getAdmin({id:i},function(t){e.cipher=r.decryptCipher(t),e.useTotp=e.cipher.organizationUseTotp}),e.save=function(o){var a=r.encryptCipher(o,e.cipher.type);e.savePromise=t.ciphers.putAdmin({id:i},a,function(e){s.eventTrack("Edited Organization Cipher");var t=r.decryptCipherPreview(e);n.close({action:"edit",data:t})}).$promise},e.generatePassword=function(){e.cipher.login.password&&!confirm("Are you sure you want to overwrite the current password?")||(s.eventTrack("Generated Password From Edit"),e.cipher.login.password=a.generatePassword({length:14,special:!0}))},e.addField=function(){e.cipher.login.fields||(e.cipher.login.fields=[]),e.cipher.fields.push({type:u.fieldType.text.toString(),name:null,value:null})},e.removeField=function(t){var n=e.cipher.fields.indexOf(t);n>-1&&e.cipher.fields.splice(n,1)},e.clipboardSuccess=function(e){e.clearSelection(),d(e)},e.clipboardError=function(e,t){t&&d(e),alert("Your web browser does not support easy clipboard copying. Copy it manually instead.")},e.delete=function(){confirm("Are you sure you want to delete this item ("+e.cipher.name+")?")&&t.ciphers.delAdmin({id:e.cipher.id},function(){s.eventTrack("Deleted Organization Cipher From Edit"),n.close({action:"delete",data:e.cipher.id})})},e.close=function(){n.dismiss("cancel")},e.showUpgrade=function(){c.open({animation:!0,templateUrl:"app/views/paidOrgRequired.html",controller:"paidOrgRequiredController",resolve:{orgId:function(){return l}}})}}]),angular.module("bit.tools").controller("reportsBreachController",["$scope","apiService","toastr","authService",function(e,t,n,o){e.loading=!0,e.error=!1,e.breachAccounts=[],e.email=null,e.$on("$viewContentLoaded",function(){o.getUserProfile().then(function(n){return e.email=n.email,t.hibp.get({email:e.email}).$promise}).then(function(t){for(var n=[],o=0;o<t.length;o++){var r={id:t[o].Name,title:t[o].Title,domain:t[o].Domain,date:new Date(t[o].BreachDate),reportedDate:new Date(t[o].AddedDate),modifiedDate:new Date(t[o].ModifiedDate),count:t[o].PwnCount,description:t[o].Description,classes:t[o].DataClasses,image:"https://haveibeenpwned.com/Content/Images/PwnedLogos/"+t[o].Name+"."+t[o].LogoType};n.push(r)}e.breachAccounts=n,e.loading=!1},function(t){e.error=404!==t.status,e.loading=!1})})}]),angular.module("bit.services").factory("apiService",["$resource","tokenService","appSettings","$httpParamSerializer","utilsService",function(e,t,n,o,r){var a={},i=n.apiUri,s=n.identityUri;return a.folders=e(i+"/folders/:id",{},{get:{method:"GET",params:{id:"@id"}},list:{method:"GET",params:{}},post:{method:"POST",params:{}},put:{method:"POST",params:{id:"@id"}},del:{url:i+"/folders/:id/delete",method:"POST",params:{id:"@id"}}}),a.ciphers=e(i+"/ciphers/:id",{},{get:{method:"GET",params:{id:"@id"}},getAdmin:{url:i+"/ciphers/:id/admin",method:"GET",params:{id:"@id"}},getDetails:{url:i+"/ciphers/:id/details",method:"GET",params:{id:"@id"}},list:{method:"GET",params:{}},listDetails:{url:i+"/ciphers/details",method:"GET",params:{}},listOrganizationDetails:{url:i+"/ciphers/organization-details",method:"GET",params:{}},post:{method:"POST",params:{}},postAdmin:{url:i+"/ciphers/admin",method:"POST",params:{}},put:{method:"POST",params:{id:"@id"}},putAdmin:{url:i+"/ciphers/:id/admin",method:"POST",params:{id:"@id"}},import:{url:i+"/ciphers/import",method:"POST",params:{}},importOrg:{url:i+"/ciphers/import-organization?organizationId=:orgId",method:"POST",params:{orgId:"@orgId"}},putPartial:{url:i+"/ciphers/:id/partial",method:"POST",params:{id:"@id"}},putShare:{url:i+"/ciphers/:id/share",method:"POST",params:{id:"@id"}},putCollections:{url:i+"/ciphers/:id/collections",method:"POST",params:{id:"@id"}},putCollectionsAdmin:{url:i+"/ciphers/:id/collections-admin",method:"POST",params:{id:"@id"}},del:{url:i+"/ciphers/:id/delete",method:"POST",params:{id:"@id"}},delAdmin:{url:i+"/ciphers/:id/delete-admin",method:"POST",params:{id:"@id"}},delMany:{url:i+"/ciphers/delete",method:"POST"},moveMany:{url:i+"/ciphers/move",method:"POST"},purge:{url:i+"/ciphers/purge",method:"POST"},postAttachment:{url:i+"/ciphers/:id/attachment",method:"POST",headers:{"Content-Type":void 0},params:{id:"@id"}},postShareAttachment:{url:i+"/ciphers/:id/attachment/:attachmentId/share?organizationId=:orgId",method:"POST",headers:{"Content-Type":void 0},params:{id:"@id",attachmentId:"@attachmentId",orgId:"@orgId"}},delAttachment:{url:i+"/ciphers/:id/attachment/:attachmentId/delete",method:"POST",params:{id:"@id",attachmentId:"@attachmentId"}}}),a.organizations=e(i+"/organizations/:id",{},{get:{method:"GET",params:{id:"@id"}},getBilling:{url:i+"/organizations/:id/billing",method:"GET",params:{id:"@id"}},getLicense:{url:i+"/organizations/:id/license",method:"GET",params:{id:"@id"}},list:{method:"GET",params:{}},post:{method:"POST",params:{}},put:{method:"POST",params:{id:"@id"}},putPayment:{url:i+"/organizations/:id/payment",method:"POST",params:{id:"@id"}},putSeat:{url:i+"/organizations/:id/seat",method:"POST",params:{id:"@id"}},putStorage:{url:i+"/organizations/:id/storage",method:"POST",params:{id:"@id"}},putUpgrade:{url:i+"/organizations/:id/upgrade",method:"POST",params:{id:"@id"}},putCancel:{url:i+"/organizations/:id/cancel",method:"POST",params:{id:"@id"}},putReinstate:{url:i+"/organizations/:id/reinstate",method:"POST",params:{id:"@id"}},postLeave:{url:i+"/organizations/:id/leave",method:"POST",params:{id:"@id"}},postVerifyBank:{url:i+"/organizations/:id/verify-bank",method:"POST",params:{id:"@id"}},del:{url:i+"/organizations/:id/delete",method:"POST",params:{id:"@id"}},postLicense:{url:i+"/organizations/license",method:"POST",headers:{"Content-Type":void 0}},putLicense:{url:i+"/organizations/:id/license",method:"POST",headers:{"Content-Type":void 0}}}),a.organizationUsers=e(i+"/organizations/:orgId/users/:id",{},{get:{method:"GET",params:{id:"@id",orgId:"@orgId"}},list:{method:"GET",params:{orgId:"@orgId"}},listGroups:{url:i+"/organizations/:orgId/users/:id/groups",method:"GET",params:{id:"@id",orgId:"@orgId"},isArray:!0},invite:{url:i+"/organizations/:orgId/users/invite",method:"POST",params:{orgId:"@orgId"}},reinvite:{url:i+"/organizations/:orgId/users/:id/reinvite",method:"POST",params:{id:"@id",orgId:"@orgId"}},accept:{url:i+"/organizations/:orgId/users/:id/accept",method:"POST",params:{id:"@id",orgId:"@orgId"}},confirm:{url:i+"/organizations/:orgId/users/:id/confirm",method:"POST",params:{id:"@id",orgId:"@orgId"}},put:{method:"POST",params:{id:"@id",orgId:"@orgId"}},putGroups:{url:i+"/organizations/:orgId/users/:id/groups",method:"POST",params:{id:"@id",orgId:"@orgId"}},del:{url:i+"/organizations/:orgId/users/:id/delete",method:"POST",params:{id:"@id",orgId:"@orgId"}}}),a.collections=e(i+"/organizations/:orgId/collections/:id",{},{get:{method:"GET",params:{id:"@id",orgId:"@orgId"}},getDetails:{url:i+"/organizations/:orgId/collections/:id/details",method:"GET",params:{id:"@id",orgId:"@orgId"}},listMe:{url:i+"/collections?writeOnly=:writeOnly",method:"GET",params:{writeOnly:"@writeOnly"}},listOrganization:{method:"GET",params:{orgId:"@orgId"}},listUsers:{url:i+"/organizations/:orgId/collections/:id/users",method:"GET",params:{id:"@id",orgId:"@orgId"}},post:{method:"POST",params:{orgId:"@orgId"}},put:{method:"POST",params:{id:"@id",orgId:"@orgId"}},del:{url:i+"/organizations/:orgId/collections/:id/delete",method:"POST",params:{id:"@id",orgId:"@orgId"}},delUser:{url:i+"/organizations/:orgId/collections/:id/delete-user/:orgUserId",method:"POST",params:{id:"@id",orgId:"@orgId",orgUserId:"@orgUserId"}}}),a.groups=e(i+"/organizations/:orgId/groups/:id",{},{get:{method:"GET",params:{id:"@id",orgId:"@orgId"}},getDetails:{url:i+"/organizations/:orgId/groups/:id/details",method:"GET",params:{id:"@id",orgId:"@orgId"}},listOrganization:{method:"GET",params:{orgId:"@orgId"}},listUsers:{url:i+"/organizations/:orgId/groups/:id/users",method:"GET",params:{id:"@id",orgId:"@orgId"}},post:{method:"POST",params:{orgId:"@orgId"}},put:{method:"POST",params:{id:"@id",orgId:"@orgId"}},del:{url:i+"/organizations/:orgId/groups/:id/delete",method:"POST",params:{id:"@id",orgId:"@orgId"}},delUser:{url:i+"/organizations/:orgId/groups/:id/delete-user/:orgUserId",method:"POST",params:{id:"@id",orgId:"@orgId",orgUserId:"@orgUserId"}}}),a.accounts=e(i+"/accounts",{},{register:{url:i+"/accounts/register",method:"POST",params:{}},emailToken:{url:i+"/accounts/email-token",method:"POST",params:{}},email:{url:i+"/accounts/email",method:"POST",params:{}},verifyEmailToken:{url:i+"/accounts/verify-email-token",method:"POST",params:{}},verifyEmail:{url:i+"/accounts/verify-email",method:"POST",params:{}},postDeleteRecoverToken:{url:i+"/accounts/delete-recover-token",method:"POST",params:{}},postDeleteRecover:{url:i+"/accounts/delete-recover",method:"POST",params:{}},putPassword:{url:i+"/accounts/password",method:"POST",params:{}},getProfile:{url:i+"/accounts/profile",method:"GET",params:{}},putProfile:{url:i+"/accounts/profile",method:"POST",params:{}},getDomains:{url:i+"/accounts/domains",method:"GET",params:{}},putDomains:{url:i+"/accounts/domains",method:"POST",params:{}},postPasswordHint:{url:i+"/accounts/password-hint",method:"POST",params:{}},putSecurityStamp:{url:i+"/accounts/security-stamp",method:"POST",params:{}},putKeys:{url:i+"/accounts/keys",method:"POST",params:{}},putKey:{url:i+"/accounts/key",method:"POST",params:{}},import:{url:i+"/accounts/import",method:"POST",params:{}},postDelete:{url:i+"/accounts/delete",method:"POST",params:{}},putStorage:{url:i+"/accounts/storage",method:"POST",params:{}},putPayment:{url:i+"/accounts/payment",method:"POST",params:{}},putCancelPremium:{url:i+"/accounts/cancel-premium",method:"POST",params:{}},putReinstatePremium:{url:i+"/accounts/reinstate-premium",method:"POST",params:{}},getBilling:{url:i+"/accounts/billing",method:"GET",params:{}},postPremium:{url:i+"/accounts/premium",method:"POST",headers:{"Content-Type":void 0}},putLicense:{url:i+"/accounts/license",method:"POST",headers:{"Content-Type":void 0}}}),a.twoFactor=e(i+"/two-factor",{},{list:{method:"GET",params:{}},getEmail:{url:i+"/two-factor/get-email",method:"POST",params:{}},getU2f:{url:i+"/two-factor/get-u2f",method:"POST",params:{}},getDuo:{url:i+"/two-factor/get-duo",method:"POST",params:{}},getAuthenticator:{url:i+"/two-factor/get-authenticator",method:"POST",params:{}},getYubi:{url:i+"/two-factor/get-yubikey",method:"POST",params:{}},sendEmail:{url:i+"/two-factor/send-email",method:"POST",params:{}},sendEmailLogin:{url:i+"/two-factor/send-email-login",method:"POST",params:{}},putEmail:{url:i+"/two-factor/email",method:"POST",params:{}},putU2f:{url:i+"/two-factor/u2f",method:"POST",params:{}},putAuthenticator:{url:i+"/two-factor/authenticator",method:"POST",params:{}},putDuo:{url:i+"/two-factor/duo",method:"POST",params:{}},putYubi:{url:i+"/two-factor/yubikey",method:"POST",params:{}},disable:{url:i+"/two-factor/disable",method:"POST",params:{}},recover:{url:i+"/two-factor/recover",method:"POST",params:{}},getRecover:{url:i+"/two-factor/get-recover",method:"POST",params:{}}}),a.settings=e(i+"/settings",{},{getDomains:{url:i+"/settings/domains",method:"GET",params:{}},putDomains:{url:i+"/settings/domains",method:"POST",params:{}}}),a.users=e(i+"/users/:id",{},{getPublicKey:{url:i+"/users/:id/public-key",method:"GET",params:{id:"@id"}}}),a.events=e(i+"/events",{},{list:{method:"GET",params:{}},listOrganization:{url:i+"/organizations/:orgId/events",method:"GET",params:{id:"@orgId"}},listCipher:{url:i+"/ciphers/:id/events",method:"GET",params:{id:"@id"}},listOrganizationUser:{url:i+"/organizations/:orgId/users/:id/events",method:"GET",params:{orgId:"@orgId",id:"@id"}}}),a.identity=e(s+"/connect",{},{token:{url:s+"/connect/token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded; charset=utf-8","Device-Type":r.getDeviceType()},transformRequest:function(e){return o(e)},skipAuthorization:!0,params:{}}}),a.hibp=e("https://haveibeenpwned.com/api/v2/breachedaccount/:email",{},{get:{method:"GET",params:{email:"@email"},isArray:!0}}),a}]),angular.module("bit.services").factory("authService",["cryptoService","apiService","tokenService","$q","jwtHelper","$rootScope","constants",function(e,t,n,o,r,a,i){var s={},l=null;s.logIn=function(r,a,l,c,u){r=r.toLowerCase();var d,p=o.defer();return e.makeKeyAndHash(r,a).then(function(e){d=e;var o={username:r,password:e.hash,grant_type:"password",scope:"api offline_access",client_id:"web"};return l&&null!=c?(u=u||!1!==u,o.twoFactorToken=l,o.twoFactorProvider=c,o.twoFactorRemember=u?"1":"0"):n.getTwoFactorToken(r)&&(o.twoFactorToken=n.getTwoFactorToken(r),o.twoFactorProvider=i.twoFactorProvider.remember,o.twoFactorRemember="0"),t.identity.token(o).$promise}).then(function(t){if(t&&t.access_token)return n.setToken(t.access_token),n.setRefreshToken(t.refresh_token),e.setKey(d.key),t.TwoFactorToken&&n.setTwoFactorToken(t.TwoFactorToken,r),t.Key&&e.setEncKey(t.Key,d.key),t.PrivateKey?(e.setPrivateKey(t.PrivateKey),!0):e.makeKeyPair()}).then(function(n){if(!0!==n)return e.setPrivateKey(n.privateKeyEnc),t.accounts.putKeys({publicKey:n.publicKey,encryptedPrivateKey:n.privateKeyEnc}).$promise}).then(function(){return s.setUserProfile()}).then(function(){p.resolve()},function(e){s.logOut(),400===e.status&&e.data.TwoFactorProviders2&&Object.keys(e.data.TwoFactorProviders2).length?(n.clearTwoFactorToken(r),p.resolve(e.data.TwoFactorProviders2)):p.reject(e)}),p.promise},s.logOut=function(){n.clearTokens(),e.clearKeys(),a.vaultGroupings=a.vaultCiphers=null,l=null},s.getUserProfile=function(){if(!l)return s.setUserProfile();var e=o.defer();return e.resolve(l),e.promise};var c=null;return s.setUserProfile=function(){return c&&0===c.promise.$$state.status?c.promise:(c=o.defer(),n.getToken()?(t.accounts.getProfile({},function(t){if(l={id:t.Id,email:t.Email,emailVerified:t.EmailVerified,premium:t.Premium,extended:{name:t.Name,twoFactorEnabled:t.TwoFactorEnabled,culture:t.Culture}},t.Organizations){for(var n={},o=0;o<t.Organizations.length;o++)n[t.Organizations[o].Id]={id:t.Organizations[o].Id,name:t.Organizations[o].Name,key:t.Organizations[o].Key,status:t.Organizations[o].Status,type:t.Organizations[o].Type,enabled:t.Organizations[o].Enabled,maxCollections:t.Organizations[o].MaxCollections,maxStorageGb:t.Organizations[o].MaxStorageGb,seats:t.Organizations[o].Seats,useGroups:t.Organizations[o].UseGroups,useDirectory:t.Organizations[o].UseDirectory,useEvents:t.Organizations[o].UseEvents,useTotp:t.Organizations[o].UseTotp};l.organizations=n,e.setOrgKeys(n),c.resolve(l)}},function(e){c.reject(e)}),c.promise):(c.reject(),c.promise))},s.addProfileOrganizationOwner=function(t,n){return s.getUserProfile().then(function(o){if(o){o.organizations||(o.organizations={});var r={id:t.Id,name:t.Name,key:n,status:2,type:0,enabled:!0,maxCollections:t.MaxCollections,maxStorageGb:t.MaxStorageGb,seats:t.Seats,useGroups:t.UseGroups,useDirectory:t.UseDirectory,useEvents:t.UseEvents,useTotp:t.UseTotp};o.organizations[r.id]=r,l=o,e.addOrgKey(r.id,r.key)}})},s.removeProfileOrganization=function(t){return s.getUserProfile().then(function(n){n&&(n.organizations&&n.organizations.hasOwnProperty(t)&&(delete n.organizations[t],l=n),e.clearOrgKey(t))})},s.updateProfileOrganization=function(e){return s.getUserProfile().then(function(t){t&&t.organizations&&e.Id in t.organizations&&(t.organizations[e.Id].name=e.Name,l=t)})},s.updateProfilePremium=function(e){return s.getUserProfile().then(function(t){t&&(t.premium=e,l=t)})},s.isAuthenticated=function(){return null!==n.getToken()},s.refreshAccessToken=function(){var e=n.getRefreshToken();return e?t.identity.token({grant_type:"refresh_token",client_id:"web",refresh_token:e}).$promise.then(function(e){return n.setToken(e.access_token),n.setRefreshToken(e.refresh_token),e.access_token},function(e){}):o(function(e,t){e(null)})},s}]),angular.module("bit.services").factory("cipherService",["cryptoService","apiService","$q","$window","constants","appSettings","$localStorage",function(e,t,n,o,r,a,i){var s={disableWebsiteIcons:i.disableWebsiteIcons};function l(t,n){return t&&""!==t?e.encrypt(t,n):null}return s.decryptCiphers=function(e){if(!e)throw"encryptedCiphers is undefined or null";for(var t=[],n=0;n<e.length;n++)t.push(s.decryptCipher(e[n]));return t},s.decryptCipher=function(t){if(!t)throw"encryptedCipher is undefined or null";var n=null;t.OrganizationId&&(n=e.getOrgKey(t.OrganizationId));var o={id:t.Id,organizationId:t.OrganizationId,collectionIds:t.CollectionIds||[],type:t.Type,folderId:t.FolderId,favorite:t.Favorite,edit:t.Edit,organizationUseTotp:t.OrganizationUseTotp,attachments:null,icon:null},a=t.Data;if(a){o.name=e.decrypt(a.Name,n),o.notes=s.decryptProperty(a.Notes,n,!0,!1),o.fields=s.decryptFields(n,a.Fields);var i={};switch(o.type){case r.cipherType.login:i.uri=s.decryptProperty(a.Uri,n,!0,!1),i.username=s.decryptProperty(a.Username,n,!0,!1),i.password=s.decryptProperty(a.Password,n,!0,!1),i.totp=s.decryptProperty(a.Totp,n,!0,!1),o.login=i,o.icon="fa-globe";break;case r.cipherType.secureNote:i.type=a.Type,o.secureNote=i,o.icon="fa-sticky-note-o";break;case r.cipherType.card:i.cardholderName=s.decryptProperty(a.CardholderName,n,!0,!1),i.number=s.decryptProperty(a.Number,n,!0,!1),i.brand=s.decryptProperty(a.Brand,n,!0,!1),i.expMonth=s.decryptProperty(a.ExpMonth,n,!0,!1),i.expYear=s.decryptProperty(a.ExpYear,n,!0,!1),i.code=s.decryptProperty(a.Code,n,!0,!1),o.card=i,o.icon="fa-credit-card";break;case r.cipherType.identity:i.title=s.decryptProperty(a.Title,n,!0,!1),i.firstName=s.decryptProperty(a.FirstName,n,!0,!1),i.middleName=s.decryptProperty(a.MiddleName,n,!0,!1),i.lastName=s.decryptProperty(a.LastName,n,!0,!1),i.address1=s.decryptProperty(a.Address1,n,!0,!1),i.address2=s.decryptProperty(a.Address2,n,!0,!1),i.address3=s.decryptProperty(a.Address3,n,!0,!1),i.city=s.decryptProperty(a.City,n,!0,!1),i.state=s.decryptProperty(a.State,n,!0,!1),i.postalCode=s.decryptProperty(a.PostalCode,n,!0,!1),i.country=s.decryptProperty(a.Country,n,!0,!1),i.company=s.decryptProperty(a.Company,n,!0,!1),i.email=s.decryptProperty(a.Email,n,!0,!1),i.phone=s.decryptProperty(a.Phone,n,!0,!1),i.ssn=s.decryptProperty(a.SSN,n,!0,!1),i.username=s.decryptProperty(a.Username,n,!0,!1),i.passportNumber=s.decryptProperty(a.PassportNumber,n,!0,!1),i.licenseNumber=s.decryptProperty(a.LicenseNumber,n,!0,!1),o.identity=i,o.icon="fa-id-card-o"}}if(!t.Attachments)return o;o.attachments=[];for(var l=0;l<t.Attachments.length;l++)o.attachments.push(s.decryptAttachment(n,t.Attachments[l]));return o},s.decryptCipherPreview=function(t){if(!t)throw"encryptedCipher is undefined or null";var n=null;t.OrganizationId&&(n=e.getOrgKey(t.OrganizationId));var o={id:t.Id,organizationId:t.OrganizationId,collectionIds:t.CollectionIds||[],type:t.Type,folderId:t.FolderId,favorite:t.Favorite,edit:t.Edit,organizationUseTotp:t.OrganizationUseTotp,hasAttachments:!!t.Attachments&&t.Attachments.length>0,meta:{},icon:null},i=t.Data;if(i){switch(o.name=s.decryptProperty(i.Name,n,!1,!0),o.type){case r.cipherType.login:o.subTitle=s.decryptProperty(i.Username,n,!0,!0),o.meta.password=s.decryptProperty(i.Password,n,!0,!0),o.meta.uri=s.decryptProperty(i.Uri,n,!0,!0),function(e,t,n){if(!s.disableWebsiteIcons&&t){var o=t,r=!1;if(0===o.indexOf("androidapp://")?e.icon="fa-android":0===o.indexOf("iosapp://")?e.icon="fa-apple":-1===o.indexOf("://")&&o.indexOf(".")>-1?(o="http://"+o,r=!0):r=0===o.indexOf("http")&&o.indexOf(".")>-1,n&&r)try{var i=new URL(o);e.meta.image=a.iconsUri+"/"+i.hostname+"/icon.png"}catch(e){}}e.icon||(e.icon="fa-globe")}(o,o.meta.uri,!0);break;case r.cipherType.secureNote:o.subTitle=null,o.icon="fa-sticky-note-o";break;case r.cipherType.card:o.subTitle="",o.meta.number=s.decryptProperty(i.Number,n,!0,!0);var l=s.decryptProperty(i.Brand,n,!0,!0);l&&(o.subTitle=l),o.meta.number&&o.meta.number.length>=4&&(""!==o.subTitle&&(o.subTitle+=", "),o.subTitle+="*"+o.meta.number.substr(o.meta.number.length-4)),o.icon="fa-credit-card";break;case r.cipherType.identity:var c=s.decryptProperty(i.FirstName,n,!0,!0),u=s.decryptProperty(i.LastName,n,!0,!0);o.subTitle="",c&&(o.subTitle=c),u&&(""!==o.subTitle&&(o.subTitle+=" "),o.subTitle+=u),o.icon="fa-id-card-o"}""===o.subTitle&&(o.subTitle=null)}return o},s.decryptAttachment=function(t,n){if(!n)throw"encryptedAttachment is undefined or null";return{id:n.Id,url:n.Url,fileName:e.decrypt(n.FileName,t),size:n.SizeName}},s.downloadAndDecryptAttachment=function(t,r,a){var i=n.defer(),s=new XMLHttpRequest;return s.open("GET",r.url,!0),s.responseType="arraybuffer",s.onload=function(n){s.response?e.decryptFromBytes(s.response,t).then(function(e){if(a){var t=new Blob([e]);if(o.navigator.msSaveOrOpenBlob)o.navigator.msSaveBlob(t,r.fileName);else{var n=o.document.createElement("a");n.href=o.URL.createObjectURL(t),n.download=r.fileName,o.document.body.appendChild(n),n.click(),o.document.body.removeChild(n)}}i.resolve(new Uint8Array(e))}):i.reject("No response")},s.send(null),i.promise},s.decryptFields=function(e,t){var n=[];if(t)for(var o=0;o<t.length;o++)n.push(s.decryptField(e,t[o]));return n},s.decryptField=function(t,n){if(!n)throw"encryptedField is undefined or null";return{type:n.Type.toString(),name:n.Name&&""!==n.Name?e.decrypt(n.Name,t):null,value:n.Value&&""!==n.Value?e.decrypt(n.Value,t):null}},s.decryptFolders=function(e){if(!e)throw"encryptedFolders is undefined or null";for(var t=[],n=0;n<e.length;n++)t.push(s.decryptFolder(e[n]));return t},s.decryptFolder=function(t){if(!t)throw"encryptedFolder is undefined or null";return{id:t.Id,name:e.decrypt(t.Name)}},s.decryptFolderPreview=function(e){if(!e)throw"encryptedFolder is undefined or null";return{id:e.Id,name:s.decryptProperty(e.Name,null,!1,!0)}},s.decryptCollections=function(e,t,n){if(!e)throw"encryptedCollections is undefined or null";for(var o=[],r=0;r<e.length;r++)o.push(s.decryptCollection(e[r],t,n));return o},s.decryptCollection=function(t,n,o){if(!t)throw"encryptedCollection is undefined or null";o=!0===o,n=n||t.OrganizationId;var r=e.getOrgKey(n);return{id:t.Id,name:o?s.decryptProperty(t.Name,r,!1,!0):e.decrypt(t.Name,r)}},s.decryptProperty=function(t,n,o,r){if(o&&(!t||""===t))return null;try{t=e.decrypt(t,n)}catch(e){t=null}return t||(r?"[error: cannot decrypt]":null)},s.encryptCiphers=function(e,t){if(!e)throw"unencryptedCiphers is undefined or null";for(var n=[],o=0;o<e.length;o++)n.push(s.encryptCipher(e[o],null,t));return n},s.encryptCipher=function(t,n,o,a){if(!t)throw"unencryptedCipher is undefined or null";t.organizationId&&(o=o||e.getOrgKey(t.organizationId));var i={id:t.id,type:n||t.type,organizationId:t.organizationId||null,folderId:""===t.folderId?null:t.folderId,favorite:null!==t.favorite&&t.favorite,name:e.encrypt(t.name,o),notes:l(t.notes,o),fields:s.encryptFields(t.fields,o)};switch(i.type){case r.cipherType.login:var c=t.login;i.login={uri:l(c.uri,o),username:l(c.username,o),password:l(c.password,o),totp:l(c.totp,o)};break;case r.cipherType.secureNote:i.secureNote={type:t.secureNote.type};break;case r.cipherType.card:var u=t.card;i.card={cardholderName:l(u.cardholderName,o),brand:l(u.brand,o),number:l(u.number,o),expMonth:l(u.expMonth,o),expYear:l(u.expYear,o),code:l(u.code,o)};break;case r.cipherType.identity:var d=t.identity;i.identity={title:l(d.title,o),firstName:l(d.firstName,o),middleName:l(d.middleName,o),lastName:l(d.lastName,o),address1:l(d.address1,o),address2:l(d.address2,o),address3:l(d.address3,o),city:l(d.city,o),state:l(d.state,o),postalCode:l(d.postalCode,o),country:l(d.country,o),company:l(d.company,o),email:l(d.email,o),phone:l(d.phone,o),ssn:l(d.ssn,o),username:l(d.username,o),passportNumber:l(d.passportNumber,o),licenseNumber:l(d.licenseNumber,o)}}if(t.attachments&&a){i.attachments={};for(var p=0;p<t.attachments.length;p++)i.attachments[t.attachments[p].id]=e.encrypt(t.attachments[p].fileName,o)}return i},s.encryptAttachmentFile=function(t,o){var r=n.defer();if(!(o.size>104857600)){var a=new FileReader;return a.readAsArrayBuffer(o),a.onload=function(n){e.encryptToBytes(n.target.result,t).then(function(n){r.resolve({fileName:e.encrypt(o.name,t),data:new Uint8Array(n),size:o.size})})},a.onerror=function(e){r.reject("Error reading file.")},r.promise}r.reject("Maximum file size is 100 MB.")},s.encryptFields=function(e,t){if(!e||!e.length)return null;for(var n=[],o=0;o<e.length;o++)e[o]&&n.push(s.encryptField(e[o],t));return n},s.encryptField=function(t,n){if(!t)throw"unencryptedField is undefined or null";return{type:parseInt(t.type),name:t.name?e.encrypt(t.name,n):null,value:t.value?e.encrypt(t.value.toString(),n):null}},s.encryptFolders=function(e,t){if(!e)throw"unencryptedFolders is undefined or null";for(var n=[],o=0;o<e.length;o++)n.push(s.encryptFolder(e[o],t));return n},s.encryptFolder=function(t,n){if(!t)throw"unencryptedFolder is undefined or null";return{id:t.id,name:e.encrypt(t.name,n)}},s.encryptCollections=function(e,t){if(!e)throw"unencryptedCollections is undefined or null";for(var n=[],o=0;o<e.length;o++)n.push(s.encryptCollection(e[o],t));return n},s.encryptCollection=function(t,n){if(!t)throw"unencryptedCollection is undefined or null";return{id:t.id,name:e.encrypt(t.name,e.getOrgKey(n))}},s}]),angular.module("bit.services").factory("cryptoService",["$sessionStorage","constants","$q","$window",function(e,t,n,o){var r,a,i,s,l,c,u={},d=void 0!==o.crypto?o.crypto:null,p=d&&void 0!==o.crypto.subtle?o.crypto.subtle:null;function m(e,t,n,o){return e="string"==typeof e?b(e):e,t="string"==typeof t?b(t):t,p.importKey("raw",e.buffer,{name:"PBKDF2"},!1,["deriveKey","deriveBits"]).then(function(e){return p.deriveKey({name:"PBKDF2",salt:t.buffer,iterations:n,hash:{name:"SHA-256"}},e,{name:"AES-CBC",length:o},!0,["encrypt","decrypt"])}).then(function(e){return p.exportKey("raw",e)})}function g(e,t,n){var o=forge.hmac.create();o.start("sha256",t),o.update(e);var r=o.digest();return n?forge.util.encode64(r.getBytes()):r.getBytes()}function f(e,t){return p.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]).then(function(t){return p.sign({name:"HMAC",hash:{name:"SHA-256"}},t,e)})}function h(e,t){var n=forge.hmac.create();return n.start("sha256",function(e){var t=new Uint32Array(e/4);d.getRandomValues(t);for(var n=forge.util.createBuffer(),o=0;o<t.length;o++)n.putInt32(t[o]);return n.getBytes()}(32)),n.update(e),e=n.digest().getBytes(),n.start(null,null),n.update(t),e===(t=n.digest().getBytes())}function v(e,n,o){if(n&&(e=forge.util.decode64(e)),!e)throw"Must provide keyBytes";var r=forge.util.createBuffer(e);if(!r||0===r.length())throw"Couldn't make buffer";var a=r.length();if(null==o)if(32===a)o=t.encType.AesCbc256_B64;else{if(64!==a)throw"Unable to determine encType.";o=t.encType.AesCbc256_HmacSha256_B64}if(this.key=e,this.keyB64=forge.util.encode64(e),this.encType=o,o===t.encType.AesCbc256_B64&&32===a)this.encKey=e,this.macKey=null;else if(o===t.encType.AesCbc128_HmacSha256_B64&&32===a)this.encKey=r.getBytes(16),this.macKey=r.getBytes(16);else{if(o!==t.encType.AesCbc256_HmacSha256_B64||64!==a)throw"Unsupported encType/key length.";this.encKey=r.getBytes(32),this.macKey=r.getBytes(32)}}function y(e){for(var t="",n=new Uint8Array(e),r=0;r<n.byteLength;r++)t+=String.fromCharCode(n[r]);return o.btoa(t)}function b(e){for(var t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n}function w(e,t,n){if(e.slice)return e.slice(t,n);if(e=e.buffer,void 0===t&&(t=0),void 0===n&&(n=e.byteLength),t=Math.floor(t),n=Math.floor(n),t<0&&(t+=e.byteLength),n<0&&(n+=e.byteLength),t=Math.min(Math.max(0,t),e.byteLength),(n=Math.min(Math.max(0,n),e.byteLength))-t<=0)return new ArrayBuffer(0);var o=new ArrayBuffer(n-t),r=new Uint8Array(o),a=new Uint8Array(e,t,n-t);return r.set(a),new Uint8Array(o)}return u.setKey=function(t){r=t,e.key=r.keyB64},u.setEncKey=function(t,n,o){if(o)return a=t,void(e.encKey=a.keyB64);try{var r=u.decrypt(t,n,"raw");e.encKey=forge.util.encode64(r),a=new v(r)}catch(e){console.log("Cannot set enc key. Decryption failed.")}},u.setPrivateKey=function(t,n){try{var o=u.decrypt(t,n,"raw");e.privateKey=forge.util.encode64(o),l=forge.pki.privateKeyFromAsn1(forge.asn1.fromDer(o))}catch(e){console.log("Cannot set private key. Decryption failed.")}},u.setOrgKeys=function(t,n){if(t&&0!==Object.keys(t).length){u.clearOrgKeys();var o={},r={},a=!1;for(var i in t)if(t.hasOwnProperty(i))try{var s=new v(u.rsaDecrypt(t[i].key,n));r[i]=s,o[i]=s.keyB64,a=!0}catch(e){console.log("Cannot set org key for "+i+". Decryption failed.")}a?e.orgKeys=o:r=null}},u.addOrgKey=function(t,n,o){(s=u.getOrgKeys())||(s={});var r=e.orgKeys;r||(r={});try{var a=new v(u.rsaDecrypt(n,o));s[t]=a,r[t]=a.keyB64}catch(e){s=null,console.log("Cannot set org key. Decryption failed.")}e.orgKeys=r},u.getKey=function(){if(!r&&e.key&&(r=new v(e.key,!0)),!r)throw"key unavailable";return r},u.getEncKey=function(){return!a&&e.encKey&&(a=new v(e.encKey,!0)),a},u.getPrivateKey=function(t){if(t=t||"native",l){if("raw"===t){var n=forge.pki.privateKeyToAsn1(l),o=forge.pki.wrapRsaPrivateKey(n);return forge.asn1.toDer(o).getBytes()}return l}if(e.privateKey){var r=forge.util.decode64(e.privateKey);if(l=forge.pki.privateKeyFromAsn1(forge.asn1.fromDer(r)),"raw"===t)return r}return l},u.getPublicKey=function(){if(c)return c;var e=u.getPrivateKey();return e?c=forge.pki.setRsaPublicKey(e.n,e.e):null},u.getOrgKeys=function(){if(s)return s;if(e.orgKeys){var t={},n=!1;for(var o in e.orgKeys)e.orgKeys.hasOwnProperty(o)&&(t[o]=new v(e.orgKeys[o],!0),n=!0);n&&(s=t)}return s},u.getOrgKey=function(e){var t=u.getOrgKeys();return t&&e in t?t[e]:null},u.clearKey=function(){r=null,i=null,delete e.key},u.clearEncKey=function(){a=null,delete e.encKey},u.clearKeyPair=function(){l=null,c=null,delete e.privateKey},u.clearOrgKeys=function(){s=null,delete e.orgKeys},u.clearOrgKey=function(t){s.hasOwnProperty(t)&&delete s[t],e.orgKeys.hasOwnProperty(t)&&delete e.orgKeys[t]},u.clearKeys=function(){u.clearKey(),u.clearEncKey(),u.clearKeyPair(),u.clearOrgKeys()},u.makeKey=function(e,t){if(o.cryptoShimmed||-1!==o.navigator.userAgent.indexOf("Edge")){var r=n.defer(),a=forge.pbkdf2(forge.util.encodeUtf8(e),forge.util.encodeUtf8(t),5e3,32,"sha256");return r.resolve(new v(a)),r.promise}return m(e,t,5e3,256).then(function(e){return new v(y(e),!0)})},u.makeEncKey=function(e){var t=forge.random.getBytesSync(64),n=u.encrypt(t,e,"raw");return{encKey:new v(t),encKeyEnc:n}},u.makeKeyPair=function(e){var t=n.defer();return forge.pki.rsa.generateKeyPair({bits:2048,workers:2,workerScript:"/lib/forge/prime.worker.min.js"},function(n,o){if(n)t.reject(n);else{var r=forge.pki.privateKeyToAsn1(o.privateKey),a=forge.pki.wrapRsaPrivateKey(r),i=forge.asn1.toDer(a).getBytes(),s=u.encrypt(i,e,"raw"),l=forge.pki.publicKeyToAsn1(o.publicKey),c=forge.asn1.toDer(l).getBytes();t.resolve({publicKey:forge.util.encode64(c),privateKeyEnc:s})}}),t.promise},u.makeShareKey=function(){var e=forge.random.getBytesSync(64);return{key:new v(e),ct:u.rsaEncryptMe(e)}},u.hashPassword=function(e,t){if(t||(t=u.getKey()),!e||!t)throw"Invalid parameters.";if(o.cryptoShimmed||-1!==o.navigator.userAgent.indexOf("Edge")){var r=n.defer(),a=forge.pbkdf2(t.key,forge.util.encodeUtf8(e),1,32,"sha256");return r.resolve(forge.util.encode64(a)),r.promise}var i=t.getBuffers();return m(new Uint8Array(i.key),e,1,256).then(function(e){return y(e)})},u.makeKeyAndHash=function(e,t){var n;return e=e.toLowerCase(),u.makeKey(t,e).then(function(e){return n=e,u.hashPassword(t,e)}).then(function(e){return{key:n,hash:e}})},u.encrypt=function(e,t,n){var o=function(e,t,n){if(!(t=t||u.getEncKey()||u.getKey()))throw"Encryption key unavailable.";n=n||"utf8";var o=forge.util.createBuffer(e,n),r=forge.random.getBytesSync(16),a=forge.cipher.createCipher("AES-CBC",t.encKey);a.start({iv:r}),a.update(o),a.finish();var i=a.output.getBytes(),s=null;t.macKey&&(s=g(r+i,t.macKey,!1));return{iv:r,ct:i,mac:s,key:t,plainValueEncoding:n}}(e,t,n),r=forge.util.encode64(o.iv)+"|"+forge.util.encode64(o.ct);o.mac&&(r=r+"|"+forge.util.encode64(o.mac));return o.key.encType+"."+r},u.encryptToBytes=function(e,t){return function(e,t){if(!(t=t||u.getEncKey()||u.getKey()))throw"Encryption key unavailable.";var n={iv:new Uint8Array(16),ct:null,mac:null,key:t},o=t.getBuffers();return d.getRandomValues(n.iv),p.importKey("raw",o.encKey,{name:"AES-CBC"},!1,["encrypt"]).then(function(t){return p.encrypt({name:"AES-CBC",iv:n.iv},t,e)}).then(function(e){if(n.ct=new Uint8Array(e),!o.macKey)return null;var t=new Uint8Array(n.iv.length+n.ct.length);return t.set(n.iv,0),t.set(n.ct,n.iv.length),f(t.buffer,o.macKey)}).then(function(e){return e&&(n.mac=new Uint8Array(e)),n})}(e,t).then(function(e){var t=0;e.mac&&(t=e.mac.length);var n=new Uint8Array(1+e.iv.length+t+e.ct.length);return n.set([e.key.encType]),n.set(e.iv,1),e.mac&&n.set(e.mac,1+e.iv.length),n.set(e.ct,1+e.iv.length+t),n.buffer})},u.rsaEncrypt=function(e,n,o){if(!(n=n||u.getPublicKey()))throw"Public key unavailable.";if("string"==typeof n){var r=forge.util.decode64(n);n=forge.pki.publicKeyFromAsn1(forge.asn1.fromDer(r))}var a=n.encrypt(e,"RSA-OAEP",{md:forge.md.sha1.create()}),i=forge.util.encode64(a);if(o&&o.macKey){var s=g(a,o.macKey,!0);return t.encType.Rsa2048_OaepSha1_HmacSha256_B64+"."+i+"|"+s}return t.encType.Rsa2048_OaepSha1_B64+"."+i},u.rsaEncryptMe=function(e){return u.rsaEncrypt(e,u.getPublicKey(),u.getEncKey())},u.decrypt=function(e,n,o){try{n=n||u.getEncKey()||u.getKey();var r,a,s=e.split(".");if(2===s.length)try{r=parseInt(s[0]),a=s[1].split("|")}catch(e){return console.error("Cannot parse headerPieces."),null}else r=3===(a=e.split("|")).length?t.encType.AesCbc128_HmacSha256_B64:t.encType.AesCbc256_B64;if(r===t.encType.AesCbc128_HmacSha256_B64&&n.encType===t.encType.AesCbc256_B64&&(n=i=i||new v(n.key,!1,t.encType.AesCbc128_HmacSha256_B64)),r!==n.encType)throw"encType unavailable.";switch(r){case t.encType.AesCbc128_HmacSha256_B64:case t.encType.AesCbc256_HmacSha256_B64:if(3!==a.length)return console.error("Enc type ("+r+") not valid."),null;break;case t.encType.AesCbc256_B64:if(2!==a.length)return console.error("Enc type ("+r+") not valid."),null;break;default:return console.error("Enc type ("+r+") not supported."),null}var l=forge.util.decode64(a[0]),c=forge.util.decode64(a[1]);if(n.macKey&&a.length>2)if(!h(forge.util.decode64(a[2]),g(l+c,n.macKey,!1)))return console.error("MAC failed."),null;var d=forge.util.createBuffer(c),p=forge.cipher.createDecipher("AES-CBC",n.encKey);return p.start({iv:l}),p.update(d),p.finish(),"utf8"===(o=o||"utf8")?p.output.toString("utf8"):p.output.getBytes()}catch(e){throw console.error("Caught unhandled error in decrypt: "+e),e}},u.decryptFromBytes=function(e,n){try{if(!e)throw"no encBuf.";var o=new Uint8Array(e),r=o[0],a=null,i=null,s=null;switch(r){case t.encType.AesCbc128_HmacSha256_B64:case t.encType.AesCbc256_HmacSha256_B64:if(o.length<=49)return console.error("Enc type ("+r+") not valid."),null;i=w(o,1,17),s=w(o,17,49),a=w(o,49);break;case t.encType.AesCbc256_B64:if(o.length<=17)return console.error("Enc type ("+r+") not valid."),null;i=w(o,1,17),a=w(o,17);break;default:return console.error("Enc type ("+r+") not supported."),null}return function(e,t,n,o,r){if(!(r=r||u.getEncKey()||u.getKey()))throw"Encryption key unavailable.";if(r.macKey&&!o)throw"macBuf required for this type of key.";if(e!==r.encType)throw"encType unavailable.";var a=r.getBuffers(),i=null;return p.importKey("raw",a.encKey,{name:"AES-CBC"},!1,["decrypt"]).then(function(e){if(i=e,!r.macKey||!o)return null;var s=new Uint8Array(n.byteLength+t.byteLength);return s.set(new Uint8Array(n),0),s.set(new Uint8Array(t),n.byteLength),f(s.buffer,a.macKey)}).then(function(e){return null===e?null:(t=o,n=e,i=new Uint8Array(32),d.getRandomValues(i),window.crypto.subtle.importKey("raw",i.buffer,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]).then(function(e){return a=e,window.crypto.subtle.sign({name:"HMAC",hash:{name:"SHA-256"}},a,t)}).then(function(e){return r=e,window.crypto.subtle.sign({name:"HMAC",hash:{name:"SHA-256"}},a,n)}).then(function(e){if(r.byteLength!==e.byteLength)return!1;for(var t=new Uint8Array(r),n=new Uint8Array(e),o=0;o<n.length;o++)if(t[o]!==n[o])return!1;return!0}));var t,n,r,a,i}).then(function(e){return!1===e?(console.error("MAC failed."),null):p.decrypt({name:"AES-CBC",iv:n},i,t)})}(r,a.buffer,i.buffer,s?s.buffer:null,n)}catch(e){throw console.error("Caught unhandled error in decryptFromBytes: "+e),e}},u.rsaDecrypt=function(e,n,o){if(n=n||u.getPrivateKey(),o=o||u.getEncKey(),!n)throw"Private key unavailable.";var r,a,i=e.split(".");if(1===i.length)r=t.encType.Rsa2048_OaepSha256_B64,a=[i[0]];else if(2===i.length)try{r=parseInt(i[0]),a=i[1].split("|")}catch(e){return null}switch(r){case t.encType.Rsa2048_OaepSha256_B64:case t.encType.Rsa2048_OaepSha1_B64:if(1!==a.length)return null;break;case t.encType.Rsa2048_OaepSha256_HmacSha256_B64:case t.encType.Rsa2048_OaepSha1_HmacSha256_B64:if(2!==a.length)return null;break;default:return null}var s,l=forge.util.decode64(a[0]);if(o&&o.macKey&&a.length>1&&!h(forge.util.decode64(a[1]),g(l,o.macKey,!1)))return console.error("MAC failed."),null;if(r===t.encType.Rsa2048_OaepSha256_B64||r===t.encType.Rsa2048_OaepSha256_HmacSha256_B64)s=forge.md.sha256.create();else{if(r!==t.encType.Rsa2048_OaepSha1_B64&&r!==t.encType.Rsa2048_OaepSha1_HmacSha256_B64)throw"encType unavailable.";s=forge.md.sha1.create()}return n.decrypt(l,"RSA-OAEP",{md:s})},v.prototype.getBuffers=function(){if(this.keyBuf)return this.keyBuf;var e=function(e){for(var t=o.atob(e),n=new Uint8Array(t.length),r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}(this.keyB64),t={key:e.buffer};return this.macKey?(t.encKey=w(e,0,e.length/2).buffer,t.macKey=w(e,e.length/2).buffer):(t.encKey=e.buffer,t.macKey=null),this.keyBuf=t,this.keyBuf},u}]),angular.module("bit.services").factory("eventService",["constants","$filter",function(e,t){var n={};function o(e){var t=e.CipherId.substring(0,8);return e.OrganizationId?'<a title="View item '+e.CipherId+'" ui-sref="backend.org.vault({orgId:\''+e.OrganizationId+"',search:'"+t+"',viewEvents:'"+e.CipherId+"'})\"><code>"+t+"</code></a>":"<code>"+t+"</code>"}function r(e){var t=e.GroupId.substring(0,8);return'<a title="View group '+e.GroupId+'" ui-sref="backend.org.groups({orgId:\''+e.OrganizationId+"',search:'"+t+"'})\"><code>"+t+"</code></a>"}function a(e){var t=e.CollectionId.substring(0,8);return'<a title="View collection '+e.CollectionId+'" ui-sref="backend.org.collections({orgId:\''+e.OrganizationId+"',search:'"+t+"'})\"><code>"+t+"</code></a>"}function i(e){var t=e.OrganizationUserId.substring(0,8);return'<a title="View user '+e.OrganizationUserId+'" ui-sref="backend.org.people({orgId:\''+e.OrganizationId+"',search:'"+t+"'})\"><code>"+t+"</code></a>"}return n.getDefaultDateFilters=function(){var e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate(),23,59);return e.setDate(e.getDate()-30),{start:new Date(e.getFullYear(),e.getMonth(),e.getDate(),0,0),end:t}},n.formatDateFilters=function(e,n){var o={start:null,end:null,error:null};try{var r="yyyy-MM-ddTHH:mm";o.start=t("date")(e,r+"Z","UTC"),o.end=t("date")(n,r+":59.999Z","UTC")}catch(e){}return(!o.start||!o.end||o.end<o.start)&&(o.error="Invalid date range."),o},n.getEventInfo=function(t,n){n=n||{cipherInfo:!0};var s=function(t){var n={icon:"fa-globe",name:"Unknown"};switch(t.DeviceType){case e.deviceType.android:n.icon="fa-android",n.name="Mobile App - Android";break;case e.deviceType.ios:n.icon="fa-apple",n.name="Mobile App - iOS";break;case e.deviceType.uwp:n.icon="fa-windows",n.name="Mobile App - Windows";break;case e.deviceType.chromeExt:n.icon="fa-chrome",n.name="Extension - Chrome";break;case e.deviceType.firefoxExt:n.icon="fa-firefox",n.name="Extension - Firefox";break;case e.deviceType.operaExt:n.icon="fa-opera",n.name="Extension - Opera";break;case e.deviceType.edgeExt:n.icon="fa-edge",n.name="Extension - Edge";break;case e.deviceType.vivaldiExt:n.icon="fa-puzzle-piece",n.name="Extension - Vivaldi";break;case e.deviceType.windowsDesktop:n.icon="fa-windows",n.name="Desktop - Windows";break;case e.deviceType.macOsDesktop:n.icon="fa-apple",n.name="Desktop - macOS";break;case e.deviceType.linuxDesktop:n.icon="fa-linux",n.name="Desktop - Linux";break;case e.deviceType.chrome:n.icon="fa-globe",n.name="Web Vault - Chrome";break;case e.deviceType.firefox:n.icon="fa-globe",n.name="Web Vault - Firefox";break;case e.deviceType.opera:n.icon="fa-globe",n.name="Web Vault - Opera";break;case e.deviceType.safari:n.icon="fa-globe",n.name="Web Vault - Safari";break;case e.deviceType.vivaldi:n.icon="fa-globe",n.name="Web Vault - Vivaldi";break;case e.deviceType.edge:n.icon="fa-globe",n.name="Web Vault - Edge";break;case e.deviceType.ie:n.icon="fa-globe",n.name="Web Vault - IE";break;case e.deviceType.unknown:n.icon="fa-globe",n.name="Web Vault - Unknown"}return n}(t);return{message:function(t,n){var s="";switch(t.Type){case e.eventType.User_LoggedIn:s="Logged in.";break;case e.eventType.User_ChangedPassword:s="Changed account password.";break;case e.eventType.User_Enabled2fa:s="Enabled two-step login.";break;case e.eventType.User_Disabled2fa:s="Disabled two-step login.";break;case e.eventType.User_Recovered2fa:s="Recovered account from two-step login.";break;case e.eventType.User_FailedLogIn:s="Login attempt failed with incorrect password.";break;case e.eventType.User_FailedLogIn2fa:s="Login attempt failed with incorrect two-step login.";break;case e.eventType.Cipher_Created:s=n.cipherInfo?"Created item "+o(t)+".":"Created.";break;case e.eventType.Cipher_Updated:s=n.cipherInfo?"Edited item "+o(t)+".":"Edited.";break;case e.eventType.Cipher_Deleted:s=n.cipherInfo?"Deleted item "+o(t)+".":"Deleted";break;case e.eventType.Cipher_AttachmentCreated:s=n.cipherInfo?"Created attachment for item "+o(t)+".":"Created attachment.";break;case e.eventType.Cipher_AttachmentDeleted:s=n.cipherInfo?"Deleted attachment for item "+o(t)+".":"Deleted attachment.";break;case e.eventType.Cipher_Shared:s=n.cipherInfo?"Shared item "+o(t)+".":"Shared.";break;case e.eventType.Cipher_UpdatedCollections:s=n.cipherInfo?"Update collections for item "+o(t)+".":"Updated collections.";break;case e.eventType.Collection_Created:s="Created collection "+a(t)+".";break;case e.eventType.Collection_Updated:s="Edited collection "+a(t)+".";break;case e.eventType.Collection_Deleted:s="Deleted collection "+a(t)+".";break;case e.eventType.Group_Created:s="Created group "+r(t)+".";break;case e.eventType.Group_Updated:s="Edited group "+r(t)+".";break;case e.eventType.Group_Deleted:s="Deleted group "+r(t)+".";break;case e.eventType.OrganizationUser_Invited:s="Invited user "+i(t)+".";break;case e.eventType.OrganizationUser_Confirmed:s="Confirmed user "+i(t)+".";break;case e.eventType.OrganizationUser_Updated:s="Edited user "+i(t)+".";break;case e.eventType.OrganizationUser_Removed:s="Removed user "+i(t)+".";break;case e.eventType.OrganizationUser_UpdatedGroups:s="Edited groups for user "+i(t)+".";break;case e.eventType.Organization_Updated:s="Edited organization settings."}return""===s?null:s}(t,n),appIcon:s.icon,appName:s.name}},n}]),angular.module("bit.services").factory("importService",["constants",function(e){var t={};t.import=function(t,p,m,g){var f,h,v,y,b,w,C,S,k,T,P,I,E,z,O,A,U,x,D,F,M,G,N,B,K,_,L,R,H,V,j,q,Y;if(p)switch(t){case"bitwardencsv":q=p,Y=m,Papa.parse(q,{header:!0,encoding:"UTF-8",complete:function(t){l(t);var n=[],o=[],r=[],a=0;angular.forEach(t.data,function(t,i){var l=n.length,c=o.length,u=t.folder&&""!==t.folder,d=u;if(u)for(a=0;a<n.length;a++)if(n[a].name===t.folder){d=!1,l=a;break}var p={favorite:!(!t.favorite||""===t.favorite||"0"===t.favorite),notes:t.notes&&""!==t.notes?t.notes:null,name:t.name&&""!==t.name?t.name:"--",type:e.cipherType.login};if(t.fields&&""!==t.fields){var m=t.fields.split(/(?:\r\n|\r|\n)/);for(a=0;a<m.length;a++)if(m[a]&&""!==m[a]){var g=m[a].lastIndexOf(": ");if(-1!==g){p.fields||(p.fields=[]);var f={name:m[a].substr(0,g),value:null,type:e.fieldType.text};m[a].length>g+2&&(f.value=m[a].substr(g+2)),p.fields.push(f)}}}var h=t.type?t.type.toLowerCase():null;switch(h){case"login":case null:case void 0:p.type=e.cipherType.login;var v=t.login_totp||t.totp,y=t.login_uri||t.uri,b=t.login_username||t.username,w=t.login_password||t.password;p.login={totp:v&&""!==v?v:null,uri:y&&""!==y?s(y):null,username:b&&""!==b?b:null,password:w&&""!==w?w:null};break;case"note":p.type=e.cipherType.secureNote,p.secureNote={type:0}}if(o.push(p),d&&n.push({name:t.folder}),u){var C={key:c,value:l};r.push(C)}}),Y(n,o,r)}});break;case"lastpass":d(p,m,g,!1);break;case"safeincloudxml":!function(t,n,o){var r=[],a=[],i=[],l=[],c=0,d=0;u(t,function(t){var u=$(t).find("database");if(u.length){var p=u.find("> label");if(p.length)for(c=0;c<p.length;c++){var m=$(p[c]);l[m.attr("id")]=r.length,r.push({name:m.attr("name")})}var g=u.find("> card");if(g.length)for(c=0;c<g.length;c++){var f=$(g[c]);if("true"!==f.attr("template")){var h={favorite:!1,notes:"",name:f.attr("title"),fields:null};if(h.name&&""!==h.name||(h.name="--"),"note"===f.attr("type"))h.type=e.cipherType.secureNote,h.secureNote={type:0};else{h.type=e.cipherType.login,h.login={};var v=f.find("> field");for(d=0;d<v.length;d++){var y=$(v[d]),b=y.text(),w=y.attr("type"),C=y.attr("name");b&&""!==b&&("login"===w?h.login.username=b:"password"===w?h.login.password=b:"notes"===w?h.notes+=b+"\n":"weblogin"===w||"website"===w?h.login.uri=s(b):b.length>200?h.notes+=C+": "+b+"\n":(h.fields||(h.fields=[]),h.fields.push({name:C,value:b,type:e.fieldType.text})))}}var S=f.find("> notes");for(d=0;d<S.length;d++)h.notes+=$(S[d]).text()+"\n";if(""===h.notes&&(h.notes=null),a.push(h),(p=f.find("> label_id")).length){var k=$(p[0]).text(),T=l[k];null!==k&&""!==k&&null!==T&&i.push({key:a.length-1,value:T})}}}n(r,a,i)}else o()},o)}(p,m,g);break;case"keepass2xml":!function(t,n,o){var r=[],a=[],s=[];u(t,function(t){var l=$(t).find("Root");if(l.length){var c=l.find("> Group");c.length&&(!function t(n,o,l){var c=r.length;var u=l;o||(""!==u&&(u+=" > "),u+=n.find("> Name").text(),r.push({name:u}));var d=n.find("> Entry");if(d.length)for(var p=0;p<d.length;p++){for(var m=$(d[p]),g=a.length,f={favorite:!1,notes:null,name:null,type:e.cipherType.login,login:{uri:null,username:null,password:null},fields:null},h=m.find("> String"),v=0;v<h.length;v++){var y=$(h[v]),b=y.find("> Key").text(),w=y.find("> Value").text();if(""!==w)switch(b){case"URL":f.login.uri=i(w);break;case"UserName":f.login.username=w;break;case"Password":f.login.password=w;break;case"Title":f.name=w;break;case"Notes":f.notes=null===f.notes?w+"\n":f.notes+w+"\n";break;default:w.length>200||w.indexOf("\n")>-1?(f.notes||(f.notes=""),f.notes+=b+": "+w+"\n"):(f.fields||(f.fields=[]),f.fields.push({name:b,value:w,type:e.fieldType.text}))}}null===f.name&&(f.name="--"),a.push(f),o||s.push({key:g,value:c})}var C=n.find("> Group");if(C.length)for(var S=0;S<C.length;S++)t($(C[S]),!1,u)}($(c[0]),!0,""),n(r,a,s))}else o()},o)}(p,m,g);break;case"keepassxcsv":V=p,j=m,Papa.parse(V,{header:!0,encoding:"UTF-8",complete:function(t){l(t);var n=[],o=[],r=[];angular.forEach(t.data,function(t,a){t.Group=t.Group.startsWith("Root/")?t.Group.replace("Root/",""):t.Group;var s=t.Group&&""!==t.Group?t.Group.split("/").join(" > "):null,l=n.length,c=o.length,u=null!==s,d=u,p=0;if(u)for(p=0;p<n.length;p++)if(n[p].name===s){d=!1,l=p;break}var m={type:e.cipherType.login,favorite:!1,notes:t.Notes&&""!==t.Notes?t.Notes:null,name:t.Title&&""!==t.Title?t.Title:"--",login:{uri:t.URL&&""!==t.URL?i(t.URL):null,username:t.Username&&""!==t.Username?t.Username:null,password:t.Password&&""!==t.Password?t.Password:null}};if(t.Title&&o.push(m),d&&n.push({name:s}),u){var g={key:c,value:l};r.push(g)}}),j(n,o,r)}});break;case"padlockcsv":R=p,H=m,Papa.parse(R,{encoding:"UTF-8",complete:function(t){l(t);var n=[],o=[],r=[],a=[],i=0,c=0;for(i=0;i<t.data.length;i++){var u=t.data[i];if(0!==i){var d=n.length,p=o.length,m=u[1]&&""!==u[1],g=m;if(m)for(c=0;c<n.length;c++)if(n[c].name===u[1]){g=!1,d=c;break}var f={favorite:!1,type:e.cipherType.login,notes:null,name:u[0]&&""!==u[0]?u[0]:"--",login:{uri:null,username:u[2]&&""!==u[2]?u[2]:null,password:u[3]&&""!==u[3]?u[3]:null},fields:null};if(a.length)for(c=4;c<u.length;c++){var h=u[c];if(h&&""!==h){var v=a[c-4];"url"===v.toLowerCase()||"uri"===v.toLowerCase()?f.login.uri=s(h):(f.fields||(f.fields=[]),f.fields.push({name:v,value:h,type:e.fieldType.text}))}}o.push(f),g&&n.push({name:u[1]}),m&&r.push({key:p,value:d})}else for(c=4;c<u.length;c++)a.push(u[c])}H(n,o,r)}});break;case"1password1pif":!function(t,n,o){var r=[],a=[],s=0;function l(t,n,o,r,a){for(var i=0;i<t.length;i++){var s=t[i];if(s[r]&&""!==s[r]){var l=s[r].toString();if(n.type==e.cipherType.login&&!n.login.username&&s[o]&&"username"===s[o])n.login.username=l;else if(n.type==e.cipherType.login&&!n.login.password&&s[o]&&"password"===s[o])n.login.password=l;else if(n.type==e.cipherType.login&&!n.login.totp&&s[o]&&s[o].startsWith("TOTP_"))n.login.totp=l;else if(l){var c=s[a]||"no_name";l.indexOf("\\n")>-1||l.length>200?(null===n.notes?n.notes="":n.notes+="\n",n.notes+=c+": "+l.split("\\r\\n").join("\n").split("\\n").join("\n")):(n.fields||(n.fields=[]),n.fields.push({name:c,value:l,type:e.fieldType.text}))}}}}c(t,function(t){var o=t.split(/(?:\r\n|\r|\n)/);for(s=0;s<o.length;s++){var c=o[s];if(c.length&&"{"===c[0]){var u=JSON.parse(c),d={type:e.cipherType.login,favorite:!(!u.openContents||!u.openContents.faveIndex),notes:null,name:u.title&&""!==u.title?u.title:"--",fields:null};if("securenotes.SecureNote"===u.typeName?(d.type=e.cipherType.secureNote,d.secureNote={type:0}):(d.type=e.cipherType.login,d.login={uri:u.location&&""!==u.location?i(u.location):null,username:null,password:null,totp:null}),u.secureContents&&(u.secureContents.notesPlain&&""!==u.secureContents.notesPlain&&(d.notes=u.secureContents.notesPlain.split("\\r\\n").join("\n").split("\\n").join("\n")),u.secureContents.fields&&l(u.secureContents.fields,d,"designation","value","name"),u.secureContents.sections))for(var p=0;p<u.secureContents.sections.length;p++)u.secureContents.sections[p].fields&&l(u.secureContents.sections[p].fields,d,"n","v","t");a.push(d)}}n(r,a,[])},o)}(p,m,g);break;case"1password6wincsv":B=p,K=m,_=[],L=[],Papa.parse(B,{encoding:"UTF-8",header:!0,complete:function(t){l(t);for(var n=0;n<t.data.length;n++){var o=t.data[n];if(o.title){var r={type:e.cipherType.login,favorite:!1,notes:o.notesPlain&&""!==o.notesPlain?o.notesPlain:"",name:o.title&&""!==o.title?o.title:"--",login:{uri:null,username:null,password:null}};for(var a in o)if(o.hasOwnProperty(a)){if(null===o[a]||""===o[a])continue;if(r.login.password||"password"!==a)if(r.login.username||"username"!==a)if(r.login.uri||"urls"!==a)"ainfo"===a||"autosubmit"===a||"notesPlain"===a||"ps"===a||"scope"===a||"tags"===a||"title"===a||"uuid"===a||a.startsWith("section:")||(""!==r.notes&&(r.notes+="\n"),r.notes+=a+": "+o[a]);else{var s=o[a].split(/(?:\r\n|\r|\n)/);r.login.uri=i(s[0]);for(var c=1;c<s.length;c++)""!==r.notes&&(r.notes+="\n"),r.notes+="url "+(c+1)+": "+s[c]}else r.login.username=o[a];else r.login.password=o[a]}""===r.notes&&(r.notes=null),L.push(r)}}K(_,L,[])}});break;case"chromecsv":case"vivaldicsv":case"operacsv":G=p,N=m,Papa.parse(G,{header:!0,encoding:"UTF-8",complete:function(t){l(t);var n=[];angular.forEach(t.data,function(t,o){n.push({type:e.cipherType.login,favorite:!1,notes:null,name:t.name&&""!==t.name?t.name:"--",login:{uri:t.url&&""!==t.url?s(t.url):null,username:t.username&&""!==t.username?t.username:null,password:t.password&&""!==t.password?t.password:null}})}),N([],n,[])}});break;case"firefoxpasswordexportercsvxml":!function(t,n,o){var r=[],a=[];function i(e){var t="--";try{if(e&&""!==e){var n=document.createElement("a");n.href=e,n.hostname&&(t=n.hostname)}}catch(e){}return t}{if(!t.type||"text/xml"!==t.type)return void o("Only .xml exports are supported.");u(t,function(t){for(var o=$(t).find("entry"),l=0;l<o.length;l++){var c=$(o[l]);if(c){var u=c.attr("host"),d=c.attr("user"),p=c.attr("password");a.push({type:e.cipherType.login,favorite:!1,notes:null,name:i(u),login:{uri:u&&""!==u?s(u):null,username:d&&""!==d?d:null,password:p&&""!==p?p:null}})}}n(r,a,[])},o)}}(p,m,g);break;case"upmcsv":F=p,M=m,Papa.parse(F,{encoding:"UTF-8",complete:function(t){l(t);var n=[];angular.forEach(t.data,function(t,o){5===t.length&&n.push({type:e.cipherType.login,favorite:!1,notes:t[4]&&""!==t[4]?t[4]:null,name:t[0]&&""!==t[0]?t[0]:"--",login:{uri:t[3]&&""!==t[3]?s(t[3]):null,username:t[1]&&""!==t[1]?t[1]:null,password:t[2]&&""!==t[2]?t[2]:null}})}),M([],n,[])}});break;case"keepercsv":x=p,D=m,Papa.parse(x,{encoding:"UTF-8",complete:function(t){l(t);var n=[],o=[],r=[];angular.forEach(t.data,function(t,a){if(t.length>=6){var i=n.length,l=o.length,c=t[0]&&""!==t[0],u=c,d=0;if(c)for(d=0;d<n.length;d++)if(n[d].name===t[0]){u=!1,i=d;break}var p={type:e.cipherType.login,favorite:!1,notes:t[5]&&""!==t[5]?t[5]:null,name:t[1]&&""!==t[1]?t[1]:"--",login:{uri:t[4]&&""!==t[4]?s(t[4]):null,username:t[2]&&""!==t[2]?t[2]:null,password:t[3]&&""!==t[3]?t[3]:null},fields:null};if(t.length>6)for(d=6;d<t.length;d+=2)t[d+1]&&t[d+1].length>200?(p.notes||(p.notes=""),p.notes+=t[d]+": "+t[d+1]+"\n"):(p.fields||(p.fields=[]),p.fields.push({name:t[d],value:t[d+1],type:e.fieldType.text}));if(o.push(p),u&&n.push({name:t[0]}),c){var m={key:l,value:i};r.push(m)}}}),D(n,o,r)}});break;case"passworddragonxml":!function(t,n,o){var r=[],a=[],i=[],l=0;u(t,function(t){var c=$(t).find("PasswordManager");if(c.length){var u=c.find("> record");if(u.length)for(var d=0;d<u.length;d++){var p=$(u[d]),m=p.find("> Account-Name"),g=m.length?$(m):null,f=p.find("> User-Id"),h=f.length?$(f):null,v=p.find("> Password"),y=v.length?$(v):null,b=p.find("> URL"),w=b.length?$(b):null,C=p.find("> Notes"),S=C.length?$(C):null,k=p.find("> Category"),T=k.length?$(k):null,P=T?T.text():null,I=r.length,E=a.length,z=P&&""!==P&&"Unfiled"!==P,O=z;if(z)for(l=0;l<r.length;l++)if(r[l].name===P){O=!1,I=l;break}var A={type:e.cipherType.login,favorite:!1,notes:S&&""!==S.text()?S.text():null,name:g&&""!==g.text()?g.text():"--",login:{uri:w&&""!==w.text()?s(w.text()):null,username:h&&""!==h.text()?h.text():null,password:y&&""!==y.text()?y.text():null},fields:null},U="";for(l=1;l<=10;l++)U+="> Attribute-"+l,l<10&&(U+=", ");var x=p.find(U);if(x.length)for(l=0;l<x.length;l++){var D=$(x[l]),F=D.prop("tagName"),M=D.text();M&&""!==M&&"null"!==M&&(M.length>200?(A.notes||(A.notes=""),A.notes+=F+": "+M+"\n"):(A.fields||(A.fields=[]),A.fields.push({name:F,value:M,type:e.fieldType.text})))}if(a.push(A),O&&r.push({name:P}),z){var G={key:E,value:I};i.push(G)}}n(r,a,i)}else o()},o)}(p,m,g);break;case"enpasscsv":A=p,U=m,Papa.parse(A,{encoding:"UTF-8",complete:function(t){l(t);for(var n=[],o=0;o<t.data.length;o++){var r=t.data[o];if(!(r.length<2||0===o&&"Title"===r[0])){var a=r[r.length-1],i={type:e.cipherType.login,name:r[0],favorite:!1,notes:a&&""!==a?a:null,fields:null,login:{uri:null,password:null,username:null,totp:null}};if(r.length>2&&r.length%2==0)for(var c=0;c<r.length-2;c+=2){var u=r[c+2];if(u&&""!==u){var d=r[c+1],p=d.toLowerCase();"url"!==p||i.login.uri?"username"!==p&&"email"!==p||i.login.username?"password"!==p||i.login.password?"totp"!==p||i.login.totp?u.length>200?(i.notes||(i.notes=""),i.notes+=d+": "+u+"\n"):(i.fields||(i.fields=[]),i.fields.push({name:d,value:u,type:e.fieldType.text})):i.login.totp=u:i.login.password=u:i.login.username=u:i.login.uri=s(u)}}n.push(i)}}U([],n,[])}});break;case"pwsafexml":!function(t,n,o){var r=[],a=[],i=[],l=0;u(t,function(t){var c=$(t).find("passwordsafe");if(c.length){var u=c.attr("delimiter"),d=c.find("> entry");if(d.length)for(var p=0;p<d.length;p++){var m=$(d[p]),g=m.find("> title"),f=g.length?$(g):null,h=m.find("> username"),v=h.length?$(h):null,y=m.find("> email"),b=y.length?$(y):null,w=b?b.text():null,C=m.find("> password"),S=C.length?$(C):null,k=m.find("> url"),T=k.length?$(k):null,P=m.find("> notes"),I=P.length?$(P):null,E=I?I.text().split(u).join("\n"):null,z=m.find("> group"),O=z.length?$(z):null,A=O?O.text().split(".").join(" > "):null,U=r.length,x=a.length,D=A&&""!==A,F=D;if(D)for(l=0;l<r.length;l++)if(r[l].name===A){F=!1,U=l;break}var M={type:e.cipherType.login,favorite:!1,notes:I&&""!==E?E:null,name:f&&""!==f.text()?f.text():"--",login:{uri:T&&""!==T.text()?s(T.text()):null,username:v&&""!==v.text()?v.text():null,password:S&&""!==S.text()?S.text():null}};if(!M.login.username&&w&&""!==w?M.login.username=w:w&&""!==w&&(M.notes=null===M.notes?"Email: "+w:M.notes+"\nEmail: "+w),a.push(M),F&&r.push({name:A}),D){var G={key:x,value:U};i.push(G)}}n(r,a,i)}else o()},o)}(p,m,g);break;case"dashlanecsv":z=p,O=m,Papa.parse(z,{encoding:"UTF-8",complete:function(t){l(t);for(var n=[],o=0;o<t.data.length;o++){var r=!1,a=t.data[o];if(a.length&&1!==a.length){var s={type:e.cipherType.login,name:a[0]&&""!==a[0]?a[0]:"--",favorite:!1,notes:null,login:{uri:null,password:null,username:null}};if(2===a.length)s.login.uri=i(a[1]);else if(3===a.length)s.login.uri=i(a[1]),s.login.username=a[2];else if(4===a.length)""===a[2]&&""===a[3]?(s.login.username=a[1],s.notes=a[2]+"\n"+a[3]):(s.login.username=a[2],s.notes=a[1]+"\n"+a[3]);else if(5===a.length)s.login.uri=i(a[1]),s.login.username=a[2],s.login.password=a[3],s.notes=a[4];else if(6===a.length)""===a[2]?(s.login.username=a[3],s.login.password=a[4],s.notes=a[5]):(s.login.username=a[2],s.login.password=a[3],s.notes=a[4]+"\n"+a[5]),s.login.uri=i(a[1]);else if(7===a.length)""===a[2]?(s.login.username=a[3],s.notes=a[4]+"\n"+a[6]):(s.login.username=a[2],s.notes=a[3]+"\n"+a[4]+"\n"+a[6]),s.login.uri=i(a[1]),s.login.password=a[5];else{s.notes="";for(var c=1;c<a.length;c++)if(s.notes=s.notes+a[c]+"\n","NO_TYPE"===a[c]){r=!0;break}}r||(""===s.login.username&&(s.login.username=null),""===s.login.password&&(s.login.password=null),""===s.notes&&(s.notes=null),""===s.login.uri&&(s.login.uri=null),n.push(s))}}O([],n,[])}});break;case"stickypasswordxml":!function(t,n,o){var r=[],a=[],i=[],l=0;function c(e,t,n){var o=e.find('> Groups > Group[ID="'+t+'"]');if(o.length){n&&""!==n&&(n=" > "+n),n=o.attr("Name")+n;var r=o.attr("ParentID");return c(e,r,n)}return n}u(t,function(t){var u=$(t).find("root > Database");if(u.length){var d=u.find("> Logins > Login");if(d.length)for(var p=0;p<d.length;p++){var m=$(d[p]),g=m.attr("Name"),f=m.attr("Password"),h=m.attr("ID"),v=null,y=null,b=null,w=null,C=null;if(h&&""!==h){var S=u.find('> Accounts > Account > LoginLinks > Login[SourceLoginID="'+h+'"]');if(S.length){var k=S.parent().parent();k.length&&(v=k.attr("Name"),y=k.attr("Link"),w=k.attr("ParentID"),(b=k.attr("Comments"))&&(b=b.split("/n").join("\n")))}}w&&""!==w&&(C=c(u,w,""));var T=r.length,P=a.length,I=C&&""!==C,E=I;if(I)for(l=0;l<r.length;l++)if(r[l].name===C){E=!1,T=l;break}var z={type:e.cipherType.login,favorite:!1,notes:b&&""!==b?b:null,name:v&&""!==v?v:"--",login:{uri:y&&""!==y?s(y):null,username:g&&""!==g?g:null,password:f&&""!==f?f:null}};if(a.push(z),E&&r.push({name:C}),I){var O={key:P,value:T};i.push(O)}}n(r,a,i)}else o()},o)}(p,m,g);break;case"msecurecsv":I=p,E=m,Papa.parse(I,{encoding:"UTF-8",complete:function(t){l(t);var n=[],o=[],r=[];angular.forEach(t.data,function(t,a){if(t.length>=3){var i=n.length,l=o.length,c=t[0]&&""!==t[0]&&"Unassigned"!==t[0],u=c,d=0;if(c)for(d=0;d<n.length;d++)if(n[d].name===t[0]){u=!1,i=d;break}var p={type:e.cipherType.login,favorite:!1,notes:"",name:t[2]&&""!==t[2]?t[2]:null,login:{uri:null,username:null,password:null}};if("Web Logins"===t[1])p.login.uri=t[4]&&""!==t[4]?s(t[4]):null,p.login.username=t[5]&&""!==t[5]?t[5]:null,p.login.password=t[6]&&""!==t[6]?t[6]:null,p.notes=t[3]&&""!==t[3]?t[3].split("\\n").join("\n"):null;else if(t.length>3)for(var m=3;m<t.length;m++)t[m]&&""!==t[m]&&(""!==p.notes&&(p.notes=p.notes+"\n"),p.notes=p.notes+t[m]);if(t[1]&&""!==t[1]&&"Web Logins"!==t[1]&&(p.name=t[1]+": "+p.name),""===p.notes&&(p.notes=null),o.push(p),u&&n.push({name:t[0]}),c){var g={key:l,value:i};r.push(g)}}}),E(n,o,r)}});break;case"truekeycsv":C=p,S=m,k=[],T=[],P=["kind","autologin","favorite","hexcolor","protectedwithpassword","subdomainonly","type","tk_export_version","note","title","document_content"],Papa.parse(C,{header:!0,encoding:"UTF-8",complete:function(t){l(t),angular.forEach(t.data,function(t,n){var o={type:e.cipherType.login,favorite:!(!t.favorite||"true"!==t.favorite.toLowerCase()),notes:t.memo&&""!==t.memo?t.memo:null,name:t.name&&""!==t.name?t.name:"--",login:{uri:t.url&&""!==t.url?s(t.url):null,username:t.login&&""!==t.login?t.login:null,password:t.password&&""!==t.password?t.password:null},fields:null};if("login"!==t.kind)for(var r in o.name=t.title&&""!==t.title?t.title:"--",o.notes=t.note&&""!==t.note?t.note:null,o.notes||(o.notes=t.document_content&&""!==t.document_content?t.document_content:null),t)t.hasOwnProperty(r)&&P.indexOf(r.toLowerCase())<0&&t[r]&&""!==t[r]&&(t[r].length>200?(o.notes||(o.notes=""),o.notes+=r+": "+t[r]+"\n"):(o.fields||(o.fields=[]),o.fields.push({name:r,value:t[r],type:e.fieldType.text})));T.push(o)}),S(k,T,[])}});break;case"clipperzhtml":!function(t,r,i){var l=[],u=[];c(t,function(t){var i=$(t).find("textarea"),c=i&&i.length?i.val():null,d=c?JSON.parse(c):null;if(d&&d.length)for(var p=0;p<d.length;p++){var m=d[p],g={type:e.cipherType.login,favorite:!1,notes:"",name:m.label&&""!==m.label?m.label.split(" ")[0]:"--",login:{uri:null,username:null,password:null},fields:null};if(m.data&&m.data.notes&&""!==m.data.notes&&(g.notes=m.data.notes.split("\\n").join("\n")),m.currentVersion&&m.currentVersion.fields)for(var f in m.currentVersion.fields)if(m.currentVersion.fields.hasOwnProperty(f)){var h=m.currentVersion.fields[f],v=h.actionType.toLowerCase();switch(v){case"password":g.login.password=h.value;break;case"email":case"username":case"user":case"name":g.login.username=h.value;break;case"url":g.login.uri=s(h.value);break;default:!g.login.username&&a(h.label,o)?g.login.username=h.value:!g.login.password&&a(h.label,n)?g.login.password=h.value:h.value.length>200?(g.notes||(g.notes=""),g.notes+=h.label+": "+h.value+"\n"):(g.fields||(g.fields=[]),g.fields.push({name:h.label,value:h.value,type:e.fieldType.text}))}}""===g.notes&&(g.notes=null),u.push(g)}r(l,u,[])},i)}(p,m,g);break;case"avirajson":!function(t,n,o){var r=[],a=[],s=0;c(t,function(t){var o=JSON.parse(t);if(o&&o.accounts)for(s=0;s<o.accounts.length;s++){var l=o.accounts[s],c={type:e.cipherType.login,favorite:l.is_favorite&&!0===l.is_favorite,notes:null,name:l.label&&""!==l.label?l.label:l.domain,login:{uri:l.domain&&""!==l.domain?i(l.domain):null,username:l.username&&""!==l.username?l.username:null,password:l.password&&""!==l.password?l.password:null}};l.email&&""!==l.email&&(c.login.username&&""!==c.login.username?c.notes=l.email:c.login.username=l.email),c.name&&""!==c.name||(c.name="--"),a.push(c)}n(r,a,[])},o)}(p,m,g);break;case"roboformhtml":!function(t,r,s){var l=[],u=[];c(t,function(t){var s=$(t.split("&shy;").join("").split("<WBR>").join("")).find("table.nobr");if(s.length)for(var c=0;c<s.length;c++){var d=$(s[c]),p={type:e.cipherType.login,favorite:!1,notes:"",name:d.find("span.caption").text(),login:{uri:null,username:null,password:null},fields:null},m=d.find(".subcaption").text();m&&""!==m&&(p.login.uri=i(m));var g=[];if($.each(d.find("table td:not(.subcaption)"),function(e,t){$(t).find("br").replaceWith("\n");var n=$(t).text();""!==n&&g.push(n.split("\\n").join("\n"))}),g.length&&g.length%2==0)for(var f=0;f<g.length;f+=2){var h=g[f],v=g[f+1];!p.login.password&&a(h.replace(":",""),n)?p.login.password=v:!p.login.username&&a(h.replace(":",""),o)?p.login.username=v:v.length>200?(p.notes||(p.notes=""),p.notes+=h+": "+v+"\n"):(p.fields||(p.fields=[]),p.fields.push({name:h,value:v,type:e.fieldType.text}))}p.notes&&""!==p.notes||(p.notes=null),p.name&&""!==p.name||(p.name="--"),u.push(p)}r(l,u,[])},s)}(p,m,g);break;case"saferpasscsv":!function(t,n,o){var r=[],a=[];Papa.parse(t,{header:!0,encoding:"UTF-8",complete:function(t){l(t),angular.forEach(t.data,function(t,n){var o,r;a.push({type:e.cipherType.login,favorite:!1,notes:t.notes&&""!==t.notes?t.notes:null,name:t.url&&""!==t.url?(o=t.url,r=document.createElement("a"),r.href=o,r.hostname.startsWith("www.")?r.hostname.replace("www.",""):r.hostname):"--",login:{uri:t.url&&""!==t.url?s(t.url):null,username:t.username&&""!==t.username?t.username:null,password:t.password&&""!==t.password?t.password:null}})}),n(r,a,[])}})}(p,m);break;case"ascendocsv":b=p,w=m,Papa.parse(b,{encoding:"UTF-8",complete:function(t){l(t);for(var s=[],c=0;c<t.data.length;c++){var u=t.data[c];if(!(u.length<2)){var d=u[u.length-1],p={type:e.cipherType.login,name:u[0],favorite:!1,notes:d&&""!==d?d:null,login:{uri:null,password:null,username:null},fields:null};if(u.length>2&&u.length%2==0)for(var m=0;m<u.length-2;m+=2){var g=u[m+2],f=u[m+1];f&&""!==f&&g&&""!==g&&(f.toLowerCase(),!p.login.uri&&a(f,r)?p.login.uri=i(g):!p.login.username&&a(f,o)?p.login.username=g:!p.login.password&&a(f,n)?p.login.password=g:g.length>200?(p.notes||(p.notes=""),p.notes+=f+": "+g+"\n"):(p.fields||(p.fields=[]),p.fields.push({name:f,value:g,type:e.fieldType.text})))}s.push(p)}}w([],s,[])}});break;case"passwordbossjson":!function(t,n,o){var r=[],a=[],s=0;c(t,function(t){var o=JSON.parse(t);if(o&&o.length)for(s=0;s<o.length;s++){var l=o[s],c={type:e.cipherType.login,favorite:!1,notes:"",name:l.name&&""!==l.name?l.name:"--",login:{uri:l.login_url&&""!==l.login_url?i(l.login_url):null,username:null,password:null},fields:null};if(l.identifiers){for(var u in l.identifiers.notes&&""!==l.identifiers.notes&&(c.notes=l.identifiers.notes.split("\\r\\n").join("\n").split("\\n").join("\n")),l.identifiers)if(l.identifiers.hasOwnProperty(u)){var d=l.identifiers[u];if("notes"===u||""===d||null===d)continue;"username"===u?c.login.username=d:"password"===u?c.login.password=d:d.length>200?(c.notes||(c.notes=""),c.notes+=u+": "+d+"\n"):(c.fields||(c.fields=[]),c.fields.push({name:u,value:d,type:e.fieldType.text}))}""===c.notes&&(c.notes=null),a.push(c)}}n(r,a,[])},o)}(p,m,g);break;case"zohovaultcsv":!function(t,n,o){function r(t,n){if(t&&""!==t)for(var o=t.split(/(?:\r\n|\r|\n)/),r=0;r<o.length;r++){var a=o[r],i=a.indexOf(":");if(!(i<0)){var s=a.substring(0,i),l=a.length>i?a.substring(i+1):null;if(s&&""!==s&&l&&""!==l&&"SecretType"!==s){var c=s.toLowerCase();"user name"===c?n.login.username=l:"password"===c?n.login.password=l:l.length>200?(n.notes||(n.notes=""),n.notes+=s+": "+l+"\n"):(n.fields||(n.fields=[]),n.fields.push({name:s,value:l,type:e.fieldType.text}))}}}}Papa.parse(t,{header:!0,encoding:"UTF-8",complete:function(t){l(t);var o=[],a=[],s=[];angular.forEach(t.data,function(t,n){var l=t.ChamberName,c=o.length,u=a.length,d=l&&""!==l,p=d,m=0;if(d)for(m=0;m<o.length;m++)if(o[m].name===l){p=!1,c=m;break}var g={type:e.cipherType.login,favorite:!(!t.Favorite||"1"!==t.Favorite),notes:t.Notes&&""!==t.Notes?t.Notes:"",name:t["Secret Name"]&&""!==t["Secret Name"]?t["Secret Name"]:"--",login:{uri:t["Secret URL"]&&""!==t["Secret URL"]?i(t["Secret URL"]):null,username:null,password:null},fields:null};if(r(t.SecretData,g),r(t.CustomData,g),""===g.notes&&(g.notes=null),t["Secret Name"]&&a.push(g),p&&o.push({name:l}),d){var f={key:u,value:c};s.push(f)}}),n(o,a,s)}})}(p,m);break;case"splashidcsv":v=p,y=m,Papa.parse(v,{encoding:"UTF-8",complete:function(t){l(t);var n=[],o=[],r=[];function a(e,t,n){for(var o=e;o<t.length-3;o++)t[o]&&""!==t[o]&&(n.notes?""!==n.notes&&(n.notes+="\n"):n.notes="",n.notes+=t[o])}for(var s=1;s<t.data.length;s++)if(!(t.data[s].length<3)){var c=t.data[s],u=c[t.data.length-1],d=c[t.data.length-2],p=c[0],m=n.length,g=o.length,f=u&&""!==u&&"Unfiled"!==u,h=f,v=0;if(f)for(v=0;v<n.length;v++)if(n[v].name===u){h=!1,m=v;break}var b={type:e.cipherType.login,favorite:!1,notes:d,name:c[1]&&""!==c[1]?c[1]:"--",fields:null,login:{uri:null,username:null,password:null}};if("Web Logins"===p||"Servers"===p||"Email Accounts"===p?(b.login.uri=c[4]&&""!==c[4]?i(c[4]):null,b.login.username=c[2]&&""!==c[2]?c[2]:null,b.login.password=c[3]&&""!==c[3]?c[3]:null,a(5,c,b)):c.length>2&&a(2,c,b),b.name&&"--"!==b.name&&"Web Logins"!==p&&"Servers"!==p&&"Email Accounts"!==p&&(b.name=p+": "+b.name),""===b.notes&&(b.notes=null),o.push(b),h&&n.push({name:u}),f){var w={key:g,value:m};r.push(w)}}y(n,o,r)}});break;case"meldiumcsv":f=p,h=m,Papa.parse(f,{header:!0,encoding:"UTF-8",complete:function(t){l(t);for(var n=[],o=0;o<t.data.length;o++){var r=t.data[o],a={type:e.cipherType.login,name:r.DisplayName&&""!==r.DisplayName?r.DisplayName:"--",favorite:!1,notes:r.Notes&&""!==r.Notes?r.Notes:null,login:{uri:r.Url&&""!==r.Url?i(r.Url):null,password:r.Password&&""!==r.Password?r.Password:null,username:r.UserName&&""!==r.UserName?r.UserName:null}};n.push(a)}h([],n,[])}});break;case"passkeepcsv":!function(t,n,o){function r(e,t){var n=t[e]||t[" "+e];return n&&""!==n?n:null}Papa.parse(t,{header:!0,encoding:"UTF-8",complete:function(t){l(t);var o=[],a=[],s=[];angular.forEach(t.data,function(t,n){var l=o.length,c=a.length,u=!!r("category",t),d=u,p=0;if(u)for(p=0;p<o.length;p++)if(o[p].name===r("category",t)){d=!1,l=p;break}var m={type:e.cipherType.login,favorite:!1,notes:r("description",t)?r("description",t):null,name:r("title",t)?r("title",t):"--",login:{uri:r("site",t)?i(r("site",t)):null,username:r("username",t)?r("username",t):null,password:r("password",t)?r("password",t):null}};if(r("password2",t)&&(m.notes?m.notes+="\n":m.notes="",m.notes+="Password 2: "+r("password2",t)),a.push(m),d&&o.push({name:r("category",t)}),u){var g={key:c,value:l};s.push(g)}}),n(o,a,s)}})}(p,m);break;case"gnomejson":!function(t,n,o){var r=[],a=[],s=[],l=0;c(t,function(t){var o=JSON.parse(t),c=0,u=0;if(o&&Object.keys(o).length)for(var d in o)if(o.hasOwnProperty(d)&&o[d].length)for(c=r.length,r.push({name:d}),l=0;l<o[d].length;l++){var p=o[d][l];if(p.display_name&&0===p.display_name.indexOf("http")){u=a.length;var m={type:e.cipherType.login,favorite:!1,notes:"",name:p.display_name.replace("http://","").replace("https://",""),login:{uri:i(p.display_name),username:p.attributes.username_value&&""!==p.attributes.username_value?p.attributes.username_value:null,password:p.secret&&""!==p.secret?p.secret:null}};for(var g in m.name>30&&(m.name=m.name.substring(0,30)),p.attributes)p.attributes.hasOwnProperty(g)&&"username_value"!==g&&"xdg:schema"!==g&&(""!==m.notes&&(m.notes+="\n"),m.notes+=g+": "+p.attributes[g]);""===m.notes&&(m.notes=null),a.push(m),s.push({key:u,value:c})}}n(r,a,s)},o)}(p,m,g);break;default:g()}else g()},t.importOrg=function(t,n,o,r){var a,i;if(n)switch(t){case"bitwardencsv":a=n,i=o,Papa.parse(a,{header:!0,encoding:"UTF-8",complete:function(t){l(t);var n,o=[],r=[],a=[];angular.forEach(t.data,function(t,i){var l=r.length;if(t.collections&&""!==t.collections){var c=t.collections.split(",");for(n=0;n<c.length;n++){for(var u=!0,d=o.length,p=0;p<o.length;p++)if(o[p].name===c[n]){u=!1,d=p;break}u&&o.push({name:c[n]}),a.push({key:l,value:d})}}var m={favorite:!1,notes:t.notes&&""!==t.notes?t.notes:null,name:t.name&&""!==t.name?t.name:"--",type:e.cipherType.login};if(t.fields&&""!==t.fields){var g=t.fields.split(/(?:\r\n|\r|\n)/);for(n=0;n<g.length;n++)if(g[n]&&""!==g[n]){var f=g[n].lastIndexOf(": ");if(-1!==f){m.fields||(m.fields=[]);var h={name:g[n].substr(0,f),value:null,type:e.fieldType.text};g[n].length>f+2&&(h.value=g[n].substr(f+2)),m.fields.push(h)}}}var v=t.type?t.type.toLowerCase():null;switch(v){case"login":case null:case void 0:m.type=e.cipherType.login;var y=t.login_totp||t.totp,b=t.login_uri||t.uri,w=t.login_username||t.username,C=t.login_password||t.password;m.login={totp:y&&""!==y?y:null,uri:b&&""!==b?s(b):null,username:w&&""!==w?w:null,password:C&&""!==C?C:null};break;case"note":m.type=e.cipherType.secureNote,m.secureNote={type:0}}r.push(m)}),i(o,r,a)}});break;case"lastpass":d(n,o,r,!0);break;default:r()}else r()};var n=["password","pass word","passphrase","pass phrase","pass","code","code word","codeword","secret","secret word","personpwd","key","keyword","key word","keyphrase","key phrase","form_pw","wppassword","pin","pwd","pw","pword","passwd","p","serial","serial#","license key","reg #","passwort"],o=["user","name","user name","username","login name","email","e-mail","id","userid","user id","login","form_loginname","wpname","mail","loginid","login id","log","personlogin","first name","last name","card#","account #","member","member #","nom","benutzername"],r=["url","hyper link","hyperlink","link","host","hostname","host name","server","address","hyper ref","href","web","website","web site","site","web-site","uri","ort","adresse"];function a(e,t){if(!e||""===e)return!1;e=e.trim().toLowerCase();for(var n=0;n<t.length;n++)if(e===t[n])return!0;return!1}function i(e){return!(e=e.toLowerCase().trim()).startsWith("http")&&e.indexOf(".")>=0&&(e="http://"+e),s(e)}function s(e){return e.length>1e3?e.substring(0,1e3):e}function l(e){if(e.errors&&e.errors.length)for(var t=0;t<e.errors.length;t++)console.warn("Error parsing row "+e.errors[t].row+": "+e.errors[t].message)}function c(e,t,n){if("string"==typeof e)t(e);else{var o=new FileReader;o.readAsText(e,"utf-8"),o.onload=function(e){t(e.target.result)},o.onerror=function(e){n()}}}function u(e,t,n){c(e,function(e){t($.parseXML(e))},n)}function d(t,n,o,r){if("string"!=typeof t&&t.type&&"text/html"===t.type){var a=new FileReader;a.readAsText(t,"utf-8"),a.onload=function(e){var t,n=$(e.target.result),r=n.find("pre");if(1===r.length)t=r.text().trim(),u(Papa.parse(t,{header:!0,encoding:"UTF-8"}).data);else{for(var a=!1,i=0;i<n.length;i++)if("pre"===n[i].tagName.toLowerCase()){a=!0,t=n[i].outerText.trim(),u(Papa.parse(t,{header:!0,encoding:"UTF-8"}).data);break}a||o()}},a.onerror=function(e){o()}}else Papa.parse(t,{header:!0,encoding:"UTF-8",complete:function(e){l(e),u(e.data)},beforeFirstChunk:function(e){return e.replace(/^\s+/,"")}});function i(e,t,n){for(var o={dataObj:{},notes:null},r=0;r<e.length;r++){var a=e[r].split(":");a.length<1||"NoteType"===a[0]||n.indexOf(a[0])>-1||!a[1]||""===a[1]||("Notes"===a[0]?o.notes?o.notes+="\n"+a[1]:o.notes=a[1]:t.hasOwnProperty(a[0])?o.dataObj[t[a[0]]]=a[1]:(o.notes?o.notes+="\n":o.notes="",o.notes+=a[0]+": "+a[1]))}return o}function c(e){var t={cardholderName:e.ccname&&""!==e.ccname?e.ccname:null,number:e.ccnum&&""!==e.ccnum?e.ccnum:null,brand:e.ccnum&&""!==e.ccnum?function(e){if(!e)return null;var t=new RegExp("^4");return null!=e.match(t)?"Visa":/^(5[1-5][0-9]{14}|2(22[1-9][0-9]{12}|2[3-9][0-9]{13}|[3-6][0-9]{14}|7[0-1][0-9]{13}|720[0-9]{12}))$/.test(e)?"Mastercard":(t=new RegExp("^3[47]"),null!=e.match(t)?"Amex":(t=new RegExp("^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)"),null!=e.match(t)?"Discover":(t=new RegExp("^36"),null!=e.match(t)?"Diners Club":(t=new RegExp("^30[0-5]"),null!=e.match(t)?"Diners Club":(t=new RegExp("^35(2[89]|[3-8][0-9])"),null!=e.match(t)?"JCB":(t=new RegExp("^(4026|417500|4508|4844|491(3|7))"),null!=e.match(t)?"Visa":null))))))}(e.ccnum):null,code:e.cccsc&&""!==e.cccsc?e.cccsc:null};if(e.ccexp&&""!==e.ccexp&&e.ccexp.indexOf("-")>-1){var n=e.ccexp.split("-");n.length>1&&(t.expYear=n[0],t.expMonth=n[1],2===t.expMonth.length&&"0"===t.expMonth[0]&&(t.expMonth=t.expMonth[1]))}return t}function u(t){var o=[],a=[],l=[],u=0;angular.forEach(t,function(t,n){var d,p=o.length,m=a.length,g=t.grouping&&""!==t.grouping&&"(none)"!==t.grouping,f=g;if(g)for(u=0;u<o.length;u++)if(o[u].name===t.grouping){f=!1,p=u;break}if(t.hasOwnProperty("profilename")&&t.hasOwnProperty("profilelanguage")?(d={favorite:!1,name:t.profilename&&""!==t.profilename?t.profilename:"--",type:e.cipherType.card},""===t.title&&""===t.firstname&&""===t.lastname&&""===t.address1&&""===t.phone&&""===t.username&&""===t.email||(d.type=e.cipherType.identity)):d={favorite:!r&&"1"===t.fav,name:t.name&&""!==t.name?t.name:"--",type:"http://sn"===t.url?e.cipherType.secureNote:e.cipherType.login},d.type===e.cipherType.login)d.login={uri:t.url&&""!==t.url?s(t.url):null,username:t.username&&""!==t.username?t.username:null,password:t.password&&""!==t.password?t.password:null},d.notes=t.extra&&""!==t.extra?t.extra:null;else if(d.type===e.cipherType.secureNote){var h=t.extra.split(/(?:\r\n|\r|\n)/),v=!1;if(h.length){var y=h[0].split(":");if(y.length>1&&"NoteType"===y[0]&&("Credit Card"===y[1]||"Address"===y[1])){var b=null;"Credit Card"===y[1]?(b=i(h,{Number:"number","Name on Card":"cardholderName","Security Code":"code"},[]),d.type=e.cipherType.card,d.card=b.dataObj):"Address"===y[1]&&(b=i(h,{Title:"title","First Name":"firstName","Last Name":"lastName","Middle Name":"middleName",Company:"company","Address 1":"address1","Address 2":"address2","Address 3":"address3","City / Town":"city",State:"state","Zip / Postal Code":"postalCode",Country:"country","Email Address":"email",Username:"username"},[]),d.type=e.cipherType.identity,d.identity=b.dataObj),v=!0,d.notes=b.notes}}v||(d.secureNote={type:0},d.notes=t.extra&&""!==t.extra?t.extra:null)}else if(d.type===e.cipherType.card)d.card=c(t),d.notes=t.notes&&""!==t.notes?t.notes:null;else if(d.type===e.cipherType.identity&&(d.identity={title:t.title&&""!==t.title?t.title:null,firstName:t.firstname&&""!==t.firstname?t.firstname:null,middleName:t.middlename&&""!==t.middlename?t.middlename:null,lastName:t.lastname&&""!==t.lastname?t.lastname:null,username:t.username&&""!==t.username?t.username:null,company:t.company&&""!==t.company?t.company:null,ssn:t.ssn&&""!==t.ssn?t.ssn:null,address1:t.address1&&""!==t.address1?t.address1:null,address2:t.address2&&""!==t.address2?t.address2:null,address3:t.address3&&""!==t.address3?t.address3:null,city:t.city&&""!==t.city?t.city:null,state:t.state&&""!==t.state?t.state:null,postalCode:t.zip&&""!==t.zip?t.zip:null,country:t.country&&""!==t.country?t.country:null,email:t.email&&""!==t.email?t.email:null,phone:t.phone&&""!==t.phone?t.phone:null},d.notes=t.notes&&""!==t.notes?t.notes:null,d.identity.title&&(d.identity.title=d.identity.title.charAt(0).toUpperCase()+d.identity.title.slice(1)),t.ccnum&&""!==t.ccnum)){var w=JSON.parse(JSON.stringify(d));w.identity=null,w.type=e.cipherType.card,w.card=c(t),a.push(w)}if(a.push(d),f&&o.push({name:t.grouping}),g){var C={key:m,value:p};l.push(C)}}),n(o,a,l)}}return t}]),angular.module("bit.services").factory("passwordService",function(){var e={};function t(e,n){var o=0,r=n-e,a=Math.ceil(Math.log2(r));if(a>53)throw new Exception("We cannot generate numbers larger than 53 bits.");var i=Math.ceil(a/8),s=Math.pow(2,a)-1,l=new Uint8Array(i);window.crypto.getRandomValues(l);for(var c=8*(i-1),u=0;u<i;u++)o+=l[u]*Math.pow(2,c),c-=8;return(o&=s)>=r?t(e,n):e+o}return e.generatePassword=function(e){var n=angular.extend({},{length:10,ambiguous:!1,number:!0,minNumber:1,uppercase:!0,minUppercase:1,lowercase:!0,minLowercase:1,special:!1,minSpecial:1},e);n.uppercase&&n.minUppercase<0&&(n.minUppercase=1),n.lowercase&&n.minLowercase<0&&(n.minLowercase=1),n.number&&n.minNumber<0&&(n.minNumber=1),n.special&&n.minSpecial<0&&(n.minSpecial=1),(!n.length||n.length<1)&&(n.length=10);var o=n.minUppercase+n.minLowercase+n.minNumber+n.minSpecial;n.length<o&&(n.length=o);var r=[];if(n.lowercase&&n.minLowercase>0)for(var a=0;a<n.minLowercase;a++)r.push("l");if(n.uppercase&&n.minUppercase>0)for(var i=0;i<n.minUppercase;i++)r.push("u");if(n.number&&n.minNumber>0)for(var s=0;s<n.minNumber;s++)r.push("n");if(n.special&&n.minSpecial>0)for(var l=0;l<n.minSpecial;l++)r.push("s");for(;r.length<n.length;)r.push("a");r.sort(function(){return 2*t(0,1)-1});var c="",u="abcdefghijkmnopqrstuvwxyz";n.ambiguous&&(u+="l"),n.lowercase&&(c+=u);var d="ABCDEFGHIJKLMNPQRSTUVWXYZ";n.ambiguous&&(d+="O"),n.uppercase&&(c+=d);var p="23456789";n.ambiguous&&(p+="01"),n.number&&(c+=p);var m="!@#$%^&*";n.special&&(c+=m);for(var g="",f=0;f<n.length;f++){var h;switch(r[f]){case"l":h=u;break;case"u":h=d;break;case"n":h=p;break;case"s":h=m;break;case"a":h=c}var v=t(0,h.length-1);g+=h.charAt(v)}return g},e}),angular.module("bit.services").factory("tokenService",["$sessionStorage","$localStorage","jwtHelper",function(e,t,n){var o={},r=null,a=null;return o.setToken=function(t){e.accessToken=t,r=t},o.getToken=function(){return r||(r=e.accessToken),r||null},o.clearToken=function(){r=null,delete e.accessToken},o.setRefreshToken=function(t){e.refreshToken=t,a=t},o.getRefreshToken=function(){return a||(a=e.refreshToken),a||null},o.clearRefreshToken=function(){a=null,delete e.refreshToken},o.setTwoFactorToken=function(e,n){t.twoFactor||(t.twoFactor={}),t.twoFactor[n]=e},o.getTwoFactorToken=function(e){return t.twoFactor?t.twoFactor[e]:null},o.clearTwoFactorToken=function(e){e?t.twoFactor&&t.twoFactor[e]&&delete t.twoFactor[e]:delete t.twoFactor},o.clearTokens=function(){o.clearToken(),o.clearRefreshToken()},o.tokenSecondsRemaining=function(e,t){var o=n.getTokenExpirationDate(e);if(t=t||0,null===o)return 0;var r=o.valueOf()-((new Date).valueOf()+1e3*t);return Math.round(r/1e3)},o.tokenNeedsRefresh=function(e,t){return t=t||5,o.tokenSecondsRemaining(e)<60*t},o}]),angular.module("bit.services").factory("utilsService",["constants",function(e){var t,n={};return n.getDeviceType=function(n){return t||(t=navigator.userAgent.indexOf(" Vivaldi/")>=0?e.deviceType.vivaldi:window.chrome&&window.chrome.webstore?e.deviceType.chrome:"undefined"!=typeof InstallTrigger?e.deviceType.firefox:window.opr&&opr.addons||window.opera||navigator.userAgent.indexOf(" OPR/")>=0?e.deviceType.firefox:/constructor/i.test(window.HTMLElement)||"[object SafariRemoteNotification]"===(!window.safari||"undefined"!=typeof safari&&safari.pushNotification).toString()?e.deviceType.opera:document.documentMode?e.deviceType.ie:window.StyleMedia?e.deviceType.edge:e.deviceType.unknown)},n}]),angular.module("bit.services").factory("validationService",function(){var e={addErrors:function(t,n){var o=n.data,r="An unexpected error has occurred.";if(t.$errors=[],o&&angular.isObject(o))if(o&&o.ErrorModel&&(o=o.ErrorModel),o.ValidationErrors){for(var a in o.ValidationErrors)if(o.ValidationErrors.hasOwnProperty(a))for(var i=0;i<o.ValidationErrors[a].length;i++)e.addError(t,a,o.ValidationErrors[a][i])}else o.Message?t.$errors.push(o.Message):t.$errors.push(r);else t.$errors.push(r)},addError:function(e,t,n,o){!o&&e.$errors||(e.$errors=[]);for(var r=!0,a=0;a<e.$errors.length;a++)if(e.$errors[a]===n){r=!1;break}r&&e.$errors.push(n),t&&""!==t&&e[t]&&e[t].$registerApiError&&e[t].$registerApiError()},parseErrors:function(e){var t=e.data,n="An unexpected error has occurred.",o=[];if(!t||!angular.isObject(t))return o.push(n),o;for(var r in t&&t.ErrorModel&&(t=t.ErrorModel),t.ValidationErrors||(t.Message?o.push(t.Message):o.push(n)),t.ValidationErrors)if(t.ValidationErrors.hasOwnProperty(r))for(var a=0;a<t.ValidationErrors[r].length;a++)o.push(t.ValidationErrors[r][a]);return o}};return e}),angular.module("bit.vault").controller("settingsAddEditEquivalentDomainController",["$scope","$uibModalInstance","$analytics","domainIndex","domains",function(e,t,n,o,r){n.eventTrack("settingsAddEditEquivalentDomainController",{category:"Modal"}),e.domains=r,e.index=o,e.submit=function(r){n.eventTrack((o?"Edited":"Added")+" Equivalent Domain"),t.close({domains:e.domains,index:o})},e.close=function(){t.dismiss("close")}}]),angular.module("bit.settings").controller("settingsBillingAdjustStorageController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","add",function(e,t,n,o,r,a,i){r.eventTrack("settingsBillingAdjustStorageController",{category:"Modal"}),e.add=i,e.storageAdjustment=0,e.submit=function(){var t={storageGbAdjustment:e.storageAdjustment};i||(t.storageGbAdjustment*=-1),e.submitPromise=o.accounts.putStorage(null,t).$promise.then(function(t){i?(r.eventTrack("Added Storage"),a.success("You have added "+e.storageAdjustment+" GB.")):(r.eventTrack("Removed Storage"),a.success("You have removed "+e.storageAdjustment+" GB.")),n.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("settingsBillingChangePaymentController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","existingPaymentMethod","appSettings","$timeout",function(e,t,n,o,r,a,i,s,l){r.eventTrack("settingsBillingChangePaymentController",{category:"Modal"}),e.existingPaymentMethod=i,e.paymentMethod="card",e.dropinLoaded=!1,e.showPaymentOptions=!1,e.hideBank=!0,e.card={};var c=null;e.changePaymentMethod=function(t){e.paymentMethod=t,"paypal"===e.paymentMethod&&braintree.dropin.create({authorization:s.braintreeKey,container:"#bt-dropin-container",paymentOptionPriority:["paypal"],paypal:{flow:"vault",buttonStyle:{label:"pay",size:"medium",shape:"pill",color:"blue"}}},function(t,n){t?console.error(t):(c=n,l(function(){e.dropinLoaded=!0}))})},e.submit=function(){var t;e.submitPromise=(t=e.card,"paypal"===e.paymentMethod?c.requestPaymentMethod().then(function(e){return e.nonce}).catch(function(e){throw e.message}):stripe.card.createToken(t).then(function(e){return e.id}).catch(function(e){throw e.message})).then(function(e){if(!e)throw"No payment token.";var t={paymentToken:e};return o.accounts.putPayment(null,t).$promise},function(e){throw e}).then(function(t){e.card=null,i?(r.eventTrack("Changed Payment Method"),a.success("You have changed your payment method.")):(r.eventTrack("Added Payment Method"),a.success("You have added a payment method.")),n.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsBillingController",["$scope","apiService","authService","$state","$uibModal","toastr","$analytics","appSettings",function(e,t,n,o,r,a,i,s){e.selfHosted=s.selfHosted,e.charges=[],e.paymentSource=null,e.subscription=null,e.loading=!0;var l=null;function c(){n.getUserProfile().then(function(n){return e.premium=n.premium,n.premium?t.accounts.getBilling({}).$promise:null}).then(function(t){if(!t)return o.go("backend.user.settingsPremium");var n=0;if(e.expiration=t.Expiration,l=t.License,e.storage=null,t&&t.MaxStorageGb&&(e.storage={currentGb:t.StorageGb||0,maxGb:t.MaxStorageGb,currentName:t.StorageName||"0 GB"},e.storage.percentage=+(e.storage.currentGb/e.storage.maxGb*100).toFixed(2)),e.subscription=null,t&&t.Subscription&&(e.subscription={trialEndDate:t.Subscription.TrialEndDate,cancelledDate:t.Subscription.CancelledDate,status:t.Subscription.Status,cancelled:t.Subscription.Cancelled,markedForCancel:!t.Subscription.Cancelled&&t.Subscription.CancelAtEndDate}),e.nextInvoice=null,t&&t.UpcomingInvoice&&(e.nextInvoice={date:t.UpcomingInvoice.Date,amount:t.UpcomingInvoice.Amount}),t&&t.Subscription&&t.Subscription.Items)for(e.subscription.items=[],n=0;n<t.Subscription.Items.length;n++)e.subscription.items.push({amount:t.Subscription.Items[n].Amount,name:t.Subscription.Items[n].Name,interval:t.Subscription.Items[n].Interval,qty:t.Subscription.Items[n].Quantity});e.paymentSource=null,t&&t.PaymentSource&&(e.paymentSource={type:t.PaymentSource.Type,description:t.PaymentSource.Description,cardBrand:t.PaymentSource.CardBrand});var r=[];if(t&&t.Charges)for(n=0;n<t.Charges.length;n++)r.push({date:t.Charges[n].CreatedDate,paymentSource:t.Charges[n].PaymentSource?t.Charges[n].PaymentSource.Description:"-",amount:t.Charges[n].Amount,status:t.Charges[n].Status,failureMessage:t.Charges[n].FailureMessage,refunded:t.Charges[n].Refunded,partiallyRefunded:t.Charges[n].PartiallyRefunded,refundedAmount:t.Charges[n].RefundedAmount,invoiceId:t.Charges[n].InvoiceId});e.charges=r,e.loading=!1})}e.expiration=null,e.$on("$viewContentLoaded",function(){c()}),e.changePayment=function(){e.selfHosted||r.open({animation:!0,templateUrl:"app/settings/views/settingsBillingChangePayment.html",controller:"settingsBillingChangePaymentController",resolve:{existingPaymentMethod:function(){return e.paymentSource?e.paymentSource.description:null}}}).result.then(function(){c()})},e.adjustStorage=function(t){e.selfHosted||r.open({animation:!0,templateUrl:"app/settings/views/settingsBillingAdjustStorage.html",controller:"settingsBillingAdjustStorageController",resolve:{add:function(){return t}}}).result.then(function(){c()})},e.cancel=function(){e.selfHosted||confirm("Are you sure you want to cancel? You will lose access to all premium features at the end of this billing cycle.")&&t.accounts.putCancelPremium({},{}).$promise.then(function(e){i.eventTrack("Canceled Premium"),a.success("Premium subscription has been canceled."),c()})},e.reinstate=function(){e.selfHosted||confirm("Are you sure you want to remove the cancellation request and reinstate your premium membership?")&&t.accounts.putReinstatePremium({},{}).$promise.then(function(e){i.eventTrack("Reinstated Premium"),a.success("Premium cancellation request has been removed."),c()})},e.updateLicense=function(){e.selfHosted&&r.open({animation:!0,templateUrl:"app/settings/views/settingsBillingUpdateLicense.html",controller:"settingsBillingUpdateLicenseController"}).result.then(function(){c()})},e.license=function(){if(!e.selfHosted){var t=JSON.stringify(l,null,2),n=new Blob([t]);if(window.navigator.msSaveOrOpenBlob)window.navigator.msSaveBlob(n,"bitwarden_premium_license.json");else{var o=window.document.createElement("a");o.href=window.URL.createObjectURL(n,{type:"text/plain"}),o.download="bitwarden_premium_license.json",document.body.appendChild(o),o.click(),document.body.removeChild(o)}}}}]),angular.module("bit.settings").controller("settingsBillingUpdateLicenseController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","validationService",function(e,t,n,o,r,a,i){r.eventTrack("settingsBillingUpdateLicenseController",{category:"Modal"}),e.submit=function(t){var s=document.getElementById("file").files;if(s&&s.length){var l=new FormData;l.append("license",s[0]),e.submitPromise=o.accounts.putLicense(l).$promise.then(function(e){r.eventTrack("Updated License"),a.success("You have updated your license."),n.close()})}else i.addError(t,"file","Select a license file.",!0)},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsChangeEmailController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics","validationService",function(e,t,n,o,r,a,i,s,l){var c,u,d;s.eventTrack("settingsChangeEmailController",{category:"Modal"}),e.token=function(t,o){r.getEncKey()?(u=t.masterPassword,d=t.newEmail.toLowerCase(),e.tokenPromise=r.hashPassword(u).then(function(t){var o={newEmail:d,masterPasswordHash:c=t};return n.accounts.emailToken(o,function(){e.tokenSent=!0}).$promise})):l.addError(o,null,"You cannot change your email until you update your encryption key.",!0)},e.confirm=function(l){e.confirmPromise=r.makeKeyAndHash(d,u).then(function(e){var t=r.getEncKey(),o=r.encrypt(t.key,e.key,"raw"),a={token:l.token,newEmail:d,masterPasswordHash:c,newMasterPasswordHash:e.hash,key:o};return n.accounts.email(a).$promise}).then(function(){return o.dismiss("cancel"),a.logOut(),s.eventTrack("Changed Email"),t.go("frontend.login.info")}).then(function(){i.success("Please log back in.","Email Changed")})},e.close=function(){o.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsChangePasswordController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","validationService","toastr","$analytics",function(e,t,n,o,r,a,i,s,l){l.eventTrack("settingsChangePasswordController",{category:"Modal"}),e.save=function(c,u){var d,p=!1;(r.getEncKey()||(i.addError(u,null,"You cannot change your master password until you update your encryption key.",!0),p=!0),e.model.newMasterPassword.length<8&&(i.addError(u,"NewMasterPasswordHash","Master password must be at least 8 characters long.",!0),p=!0),e.model.newMasterPassword!==e.model.confirmNewMasterPassword&&(i.addError(u,"ConfirmNewMasterPasswordHash","New master password confirmation does not match.",!0),p=!0),p)||(e.savePromise=a.getUserProfile().then(function(e){return r.makeKeyAndHash(e.email,c.newMasterPassword)}).then(function(e){return d=e,r.hashPassword(c.masterPassword)}).then(function(e){var t=r.getEncKey(),o=r.encrypt(t.key,d.key,"raw"),a={masterPasswordHash:e,newMasterPasswordHash:d.hash,key:o};return n.accounts.putPassword(a).$promise}).then(function(){return o.dismiss("cancel"),a.logOut(),l.eventTrack("Changed Password"),t.go("frontend.login.info")}).then(function(){s.success("Please log back in.","Master Password Changed")}))},e.close=function(){o.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsController",["$scope","$state","$uibModal","apiService","toastr","authService","$localStorage","$rootScope","cipherService",function(e,t,n,o,r,a,i,s,l){function c(){$("html, body").animate({scrollTop:0},200)}e.model={profile:{},email:null,disableWebsiteIcons:!1},e.$on("$viewContentLoaded",function(){o.accounts.getProfile({},function(t){if(e.model={profile:{name:t.Name,masterPasswordHint:t.MasterPasswordHint,culture:t.Culture},email:t.Email,disableWebsiteIcons:i.disableWebsiteIcons},t.Organizations){for(var n=[],o=0;o<t.Organizations.length;o++)2===t.Organizations[o].Status&&n.push({id:t.Organizations[o].Id,name:t.Organizations[o].Name,status:t.Organizations[o].Status,type:t.Organizations[o].Type,enabled:t.Organizations[o].Enabled});e.model.organizations=n}})}),e.generalSave=function(){e.generalPromise=o.accounts.putProfile({},e.model.profile,function(e){a.setUserProfile(e).then(function(e){r.success("Account has been updated.","Success!")})}).$promise},e.passwordHintSave=function(){e.passwordHintPromise=o.accounts.putProfile({},e.model.profile,function(e){a.setUserProfile(e).then(function(e){r.success("Account has been updated.","Success!")})}).$promise},e.optionsSave=function(){i.disableWebsiteIcons=l.disableWebsiteIcons=e.model.disableWebsiteIcons,s.vaultCiphers=null,r.success("Options have been updated.","Success!")},e.changePassword=function(){n.open({animation:!0,templateUrl:"app/settings/views/settingsChangePassword.html",controller:"settingsChangePasswordController"})},e.changeEmail=function(){n.open({animation:!0,templateUrl:"app/settings/views/settingsChangeEmail.html",controller:"settingsChangeEmailController"})},e.viewOrganization=function(e){if(2===e.type)return c(),void r.error("You cannot manage this organization.");t.go("backend.org.dashboard",{orgId:e.id})},e.leaveOrganization=function(t){confirm("Are you sure you want to leave this organization ("+t.name+")?")&&o.organizations.postLeave({id:t.id},{},function(n){a.refreshAccessToken().then(function(){var n=e.model.organizations.indexOf(t);n>-1&&e.model.organizations.splice(n,1),r.success("You have left the organization."),c()})},function(e){r.error("Unable to leave this organization."),c()})},e.sessions=function(){n.open({animation:!0,templateUrl:"app/settings/views/settingsSessions.html",controller:"settingsSessionsController"})},e.delete=function(){n.open({animation:!0,templateUrl:"app/settings/views/settingsDelete.html",controller:"settingsDeleteController"})},e.purge=function(){n.open({animation:!0,templateUrl:"app/settings/views/settingsPurge.html",controller:"settingsPurgeController"})}}]),angular.module("bit.settings").controller("settingsCreateOrganizationController",["$scope","$state","apiService","cryptoService","toastr","$analytics","authService","constants","appSettings","validationService",function(e,t,n,o,r,a,i,s,l,c){e.plans=s.plans,e.storageGb=s.storageGb,e.paymentMethod="card",e.selfHosted=l.selfHosted,e.model={plan:"free",additionalSeats:0,interval:"year",ownedBusiness:!1,additionalStorageGb:null},e.totalPrice=function(){return"month"===e.model.interval?(e.model.additionalSeats||0)*(e.plans[e.model.plan].monthlySeatPrice||0)+(e.model.additionalStorageGb||0)*e.storageGb.monthlyPrice+(e.plans[e.model.plan].monthlyBasePrice||0):(e.model.additionalSeats||0)*(e.plans[e.model.plan].annualSeatPrice||0)+(e.model.additionalStorageGb||0)*e.storageGb.yearlyPrice+(e.plans[e.model.plan].annualBasePrice||0)},e.changePaymentMethod=function(t){e.paymentMethod=t},e.changedPlan=function(){e.plans[e.model.plan].hasOwnProperty("monthPlanType")&&(e.model.interval="year"),e.plans[e.model.plan].noAdditionalSeats?e.model.additionalSeats=0:e.model.additionalSeats||e.plans[e.model.plan].baseSeats||e.plans[e.model.plan].noAdditionalSeats||(e.model.additionalSeats=1)},e.changedBusiness=function(){e.model.ownedBusiness&&(e.model.plan="teams")},e.submit=function(s,l){var u=o.makeShareKey(),d=o.encrypt("Default Collection",u.key);if(e.selfHosted){var p=document.getElementById("file").files;if(!p||!p.length)return void c.addError(l,"file","Select a license file.",!0);var m=new FormData;m.append("license",p[0]),m.append("key",u.ct),m.append("collectionName",d),e.submitPromise=n.organizations.postLicense(m).$promise.then(h)}else if("free"===s.plan){var g={name:s.name,planType:s.plan,key:u.ct,billingEmail:s.billingEmail,collectionName:d};e.submitPromise=n.organizations.post(g).$promise.then(h)}else{var f=null;if("card"===e.paymentMethod)f=stripe.card.createToken(s.card);else{if("bank"!==e.paymentMethod)return;s.bank.currency="USD",s.bank.country="US",f=stripe.bankAccount.createToken(s.bank)}e.submitPromise=f.then(function(t){var o={name:s.name,planType:"month"===s.interval?e.plans[s.plan].monthPlanType:e.plans[s.plan].annualPlanType,key:u.ct,paymentToken:t.id,additionalSeats:s.additionalSeats,additionalStorageGb:s.additionalStorageGb,billingEmail:s.billingEmail,businessName:s.ownedBusiness?s.businessName:null,country:"card"===e.paymentMethod?s.card.address_country:null,collectionName:d};return n.organizations.post(o).$promise},function(e){throw e.message}).then(h)}function h(e){a.eventTrack("Created Organization"),i.addProfileOrganizationOwner(e,u.ct),i.refreshAccessToken().then(function(){v(e.Id)},function(){v(e.Id)})}function v(e){t.go("backend.org.dashboard",{orgId:e}).then(function(){r.success("Your new organization is ready to go!","Organization Created")})}}}]),angular.module("bit.settings").controller("settingsDeleteController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics","tokenService",function(e,t,n,o,r,a,i,s,l){s.eventTrack("settingsDeleteController",{category:"Modal"}),e.submit=function(c){var u;e.submitPromise=a.getUserProfile().then(function(e){return u=e,r.hashPassword(c.masterPassword)}).then(function(e){return n.accounts.postDelete({masterPasswordHash:e}).$promise}).then(function(){return o.dismiss("cancel"),a.logOut(),l.clearTwoFactorToken(u.email),s.eventTrack("Deleted Account"),t.go("frontend.login.info")}).then(function(){i.success("Your account has been closed and all associated data has been deleted.","Account Deleted")})},e.close=function(){o.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsDomainsController",["$scope","$state","apiService","toastr","$analytics","$uibModal",function(e,t,n,o,r,a){e.globalEquivalentDomains=[],e.equivalentDomains=[],n.settings.getDomains({},function(t){var n;if(t.EquivalentDomains)for(n=0;n<t.EquivalentDomains.length;n++)e.equivalentDomains.push(t.EquivalentDomains[n].join(", "));if(t.GlobalEquivalentDomains)for(n=0;n<t.GlobalEquivalentDomains.length;n++)e.globalEquivalentDomains.push({domains:t.GlobalEquivalentDomains[n].Domains.join(", "),excluded:t.GlobalEquivalentDomains[n].Excluded,key:t.GlobalEquivalentDomains[n].Type})}),e.toggleExclude=function(e){e.excluded=!e.excluded},e.customize=function(t){t.excluded=!0,e.equivalentDomains.push(t.domains)},e.delete=function(t){e.equivalentDomains.splice(t,1),e.$emit("removeAppendedDropdownMenu")},e.addEdit=function(t){a.open({animation:!0,templateUrl:"app/settings/views/settingsAddEditEquivalentDomain.html",controller:"settingsAddEditEquivalentDomainController",resolve:{domainIndex:function(){return t},domains:function(){return null!==t?e.equivalentDomains[t]:null}}}).result.then(function(t){t.domains&&(t.domains=t.domains.split(" ").join("").split(",").join(", ")),null!==t.index?e.equivalentDomains[t.index]=t.domains:e.equivalentDomains.push(t.domains)})},e.saveGlobal=function(){e.globalPromise=i()},e.saveCustom=function(){e.customPromise=i()};var i=function(){for(var t={ExcludedGlobalEquivalentDomains:[],EquivalentDomains:[]},a=0;a<e.globalEquivalentDomains.length;a++)e.globalEquivalentDomains[a].excluded&&t.ExcludedGlobalEquivalentDomains.push(e.globalEquivalentDomains[a].key);for(a=0;a<e.equivalentDomains.length;a++)t.EquivalentDomains.push(e.equivalentDomains[a].split(" ").join("").split(","));return t.EquivalentDomains.length||(t.EquivalentDomains=null),t.ExcludedGlobalEquivalentDomains.length||(t.ExcludedGlobalEquivalentDomains=null),n.settings.putDomains(t,function(e){r.eventTrack("Saved Equivalent Domains"),o.success("Domains have been updated.","Success!")}).$promise}}]),angular.module("bit.settings").controller("settingsPremiumController",["$scope","$state","apiService","toastr","$analytics","authService","constants","$timeout","appSettings","validationService",function(e,t,n,o,r,a,i,s,l,c){var u=null;a.getUserProfile().then(function(e){if((u=e)&&u.premium)return t.go("backend.user.settingsBilling")}),e.selfHosted=l.selfHosted;var d=null;function p(){return a.updateProfilePremium(!0).then(function(){return r.eventTrack("Signed Up Premium"),a.refreshAccessToken()}).then(function(){return t.go("backend.user.settingsBilling")}).then(function(){o.success("Premium upgrade complete.","Success")})}e.storageGbPrice=i.storageGb.yearlyPrice,e.premiumPrice=i.premium.price,e.paymentMethod="card",e.dropinLoaded=!1,e.model={additionalStorageGb:null},e.changePaymentMethod=function(t){e.paymentMethod=t,"paypal"===e.paymentMethod&&braintree.dropin.create({authorization:l.braintreeKey,container:"#bt-dropin-container",paymentOptionPriority:["paypal"],paypal:{flow:"vault",buttonStyle:{label:"pay",size:"medium",shape:"pill",color:"blue"}}},function(t,n){t?console.error(t):(d=n,s(function(){e.dropinLoaded=!0}))})},e.totalPrice=function(){return e.premiumPrice+(e.model.additionalStorageGb||0)*e.storageGbPrice},e.submit=function(t,o){if(e.selfHosted){if(u&&!u.emailVerified)return void c.addError(o,null,"Your account's email address first must be verified.",!0);var r=document.getElementById("file").files;if(!r||!r.length)return void c.addError(o,"file","Select a license file.",!0);var a=new FormData;a.append("license",r[0]),e.submitPromise=n.accounts.postPremium(a).$promise.then(function(e){return p()})}else e.submitPromise=(i=t,"paypal"===e.paymentMethod?d.requestPaymentMethod().then(function(e){return e.nonce}).catch(function(e){throw e.message}):stripe.card.createToken(i.card).then(function(e){return e.id}).catch(function(e){throw e.message})).then(function(e){if(!e)throw"No payment token.";var o=new FormData;return o.append("paymentToken",e),o.append("additionalStorageGb",t.additionalStorageGb||0),n.accounts.postPremium(o).$promise},function(e){throw e}).then(function(e){return p()});var i}}]),angular.module("bit.settings").controller("settingsPurgeController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics","tokenService",function(e,t,n,o,r,a,i,s,l){s.eventTrack("settingsPurgeController",{category:"Modal"}),e.submit=function(a){e.submitPromise=r.hashPassword(a.masterPassword).then(function(e){return n.ciphers.purge({masterPasswordHash:e}).$promise}).then(function(){return o.dismiss("cancel"),s.eventTrack("Purged Vault"),t.go("backend.user.vault",{refreshFromServer:!0})}).then(function(){i.success("All items in your vault have been deleted.","Vault Purged")})},e.close=function(){o.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsSessionsController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","tokenService","toastr","$analytics",function(e,t,n,o,r,a,i,s,l){l.eventTrack("settingsSessionsController",{category:"Modal"}),e.submit=function(c){var u,d;e.submitPromise=r.hashPassword(c.masterPassword).then(function(e){return u=e,a.getUserProfile()}).then(function(e){return d=e,n.accounts.putSecurityStamp({masterPasswordHash:u}).$promise}).then(function(){return o.dismiss("cancel"),a.logOut(),i.clearTwoFactorToken(d.email),l.eventTrack("Deauthorized Sessions"),t.go("frontend.login.info")}).then(function(){s.success("Please log back in.","All Sessions Deauthorized")})},e.close=function(){o.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsTwoStepAuthenticatorController",["$scope","apiService","$uibModalInstance","cryptoService","authService","$q","toastr","$analytics","constants","$timeout",function(e,t,n,o,r,a,i,s,l,c){s.eventTrack("settingsTwoStepAuthenticatorController",{category:"Modal"});var u,d="bitwarden",p=null,m=null;function g(t){var n;e.enabled=t.Enabled,m=t.Key,e.model={key:(n=m,n?n.replace(/(.{4})/g,"$1 ").trim().toUpperCase():null),qr:"https://chart.googleapis.com/chart?chs=160x160&chld=L|0&cht=qr&chl=otpauth://totp/"+d+":"+encodeURIComponent(p.email)+"%3Fsecret="+encodeURIComponent(m)+"%26issuer="+d},e.updateModel={token:null}}c(function(){$("#masterPassword").focus()}),e.auth=function(n){var a=null;e.authPromise=o.hashPassword(n.masterPassword).then(function(e){return u=e,t.twoFactor.getAuthenticator({},{masterPasswordHash:u}).$promise}).then(function(e){return a=e,r.getUserProfile()}).then(function(t){p=t,e.account=p.email,g(a)})},e.submit=function(n){var o;n&&n.token?(o=n,e.submitPromise=t.twoFactor.putAuthenticator({},{token:o.token.replace(" ",""),key:m,masterPasswordHash:u},function(e){s.eventTrack("Enabled Two-step Authenticator"),g(e),o.token=null}).$promise):function(){if(!confirm("Are you sure you want to disable the authenticator app provider?"))return;e.submitPromise=t.twoFactor.disable({},{masterPasswordHash:u,type:l.twoFactorProvider.authenticator},function(t){s.eventTrack("Disabled Two-step Authenticator"),i.success("Authenticator app has been disabled."),e.enabled=t.Enabled,e.close()}).$promise}()};var f=!1;e.close=function(){f=!0,n.close(e.enabled)},e.$on("modal.closing",function(t,n,o){f||(t.preventDefault(),e.close())})}]),angular.module("bit.settings").controller("settingsTwoStepController",["$scope","apiService","toastr","$analytics","constants","$filter","$uibModal","authService",function(e,t,n,o,r,a,i,s){e.providers=r.twoFactorProviderInfo,e.premium=!0,s.getUserProfile().then(function(n){return e.premium=n.premium,t.twoFactor.list({}).$promise}).then(function(t){if(t.Data)for(var n=0;n<t.Data.length;n++)if(t.Data[n].Enabled){var o=a("filter")(e.providers,{type:t.Data[n].Type});o.length&&(o[0].enabled=!0)}}),e.edit=function(t){if(e.premium||t.free){if(t.type===r.twoFactorProvider.authenticator)typeName="Authenticator";else if(t.type===r.twoFactorProvider.email)typeName="Email";else if(t.type===r.twoFactorProvider.yubikey)typeName="Yubi";else if(t.type===r.twoFactorProvider.duo)typeName="Duo";else{if(t.type!==r.twoFactorProvider.u2f)return;typeName="U2f"}i.open({animation:!0,templateUrl:"app/settings/views/settingsTwoStep"+typeName+".html",controller:"settingsTwoStep"+typeName+"Controller",resolve:{enabled:function(){return t.enabled}}}).result.then(function(e){(e||!1===e)&&(t.enabled=e)})}else i.open({animation:!0,templateUrl:"app/views/premiumRequired.html",controller:"premiumRequiredController"})},e.viewRecover=function(){i.open({animation:!0,templateUrl:"app/settings/views/settingsTwoStepRecover.html",controller:"settingsTwoStepRecoverController"})}}]),angular.module("bit.settings").controller("settingsTwoStepDuoController",["$scope","apiService","$uibModalInstance","cryptoService","toastr","$analytics","constants","$timeout",function(e,t,n,o,r,a,i,s){var l;function c(t){e.enabled=t.Enabled,e.updateModel={ikey:t.IntegrationKey,skey:t.SecretKey,host:t.Host}}a.eventTrack("settingsTwoStepDuoController",{category:"Modal"}),e.updateModel={token:null,host:null,ikey:null,skey:null},s(function(){$("#masterPassword").focus()}),e.auth=function(n){e.authPromise=o.hashPassword(n.masterPassword).then(function(e){return l=e,t.twoFactor.getDuo({},{masterPasswordHash:l}).$promise}).then(function(t){c(t),e.authed=!0})},e.submit=function(n){var o;e.enabled?function(){if(!confirm("Are you sure you want to disable the Duo provider?"))return;e.submitPromise=t.twoFactor.disable({},{masterPasswordHash:l,type:i.twoFactorProvider.duo},function(t){a.eventTrack("Disabled Two-step Duo"),r.success("Duo has been disabled."),e.enabled=t.Enabled,e.close()}).$promise}():(o=n,e.submitPromise=t.twoFactor.putDuo({},{integrationKey:o.ikey,secretKey:o.skey,host:o.host,masterPasswordHash:l},function(e){a.eventTrack("Enabled Two-step Duo"),c(e)}).$promise)};var u=!1;e.close=function(){u=!0,n.close(e.enabled)},e.$on("modal.closing",function(t,n,o){u||(t.preventDefault(),e.close())})}]),angular.module("bit.settings").controller("settingsTwoStepEmailController",["$scope","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics","constants","$timeout",function(e,t,n,o,r,a,i,s,l){i.eventTrack("settingsTwoStepEmailController",{category:"Modal"});var c,u=null;e.updateModel={token:null,email:null},l(function(){$("#masterPassword").focus()}),e.auth=function(n){var a=null;e.authPromise=o.hashPassword(n.masterPassword).then(function(e){return c=e,t.twoFactor.getEmail({},{masterPasswordHash:c}).$promise}).then(function(e){return a=e,r.getUserProfile()}).then(function(t){u=t,e.enabled=a.Enabled,e.updateModel.email=e.enabled?a.Email:u.email,e.authed=!0})},e.sendEmail=function(n){if(e.emailError=!1,e.emailSuccess=!1,!n||!n.email||n.email.indexOf("@")<0)return e.emailError=!0,void(e.emailSuccess=!1);e.emailLoading=!0,t.twoFactor.sendEmail({},{masterPasswordHash:c,email:n.email},function(t){e.emailError=!1,e.emailSuccess=!0,e.emailLoading=!1},function(t){e.emailError=!0,e.emailSuccess=!1,e.emailLoading=!1})},e.submit=function(n){var o;n&&n.token?(o=n,e.submitPromise=t.twoFactor.putEmail({},{email:o.email.toLowerCase().trim(),token:o.token.replace(" ",""),masterPasswordHash:c},function(t){i.eventTrack("Enabled Two-step Email"),e.enabled=t.Enabled,o.email=t.Email,o.token=null}).$promise):function(){if(!confirm("Are you sure you want to disable the email provider?"))return;e.submitPromise=t.twoFactor.disable({},{masterPasswordHash:c,type:s.twoFactorProvider.email},function(t){i.eventTrack("Disabled Two-step Email"),a.success("Email has been disabled."),e.enabled=t.Enabled,e.close()}).$promise}()};var d=!1;e.close=function(){d=!0,n.close(e.enabled)},e.$on("modal.closing",function(t,n,o){d||(t.preventDefault(),e.close())})}]),angular.module("bit.settings").controller("settingsTwoStepRecoverController",["$scope","apiService","$uibModalInstance","cryptoService","$analytics","$timeout",function(e,t,n,o,r,a){r.eventTrack("settingsTwoStepRecoverController",{category:"Modal"}),e.code=null,e.auth=function(n){e.authPromise=o.hashPassword(n.masterPassword).then(function(e){return t.twoFactor.getRecover({},{masterPasswordHash:e}).$promise}).then(function(t){e.code=function(e){if(!e)return null;return e.replace(/(.{4})/g,"$1 ").trim().toUpperCase()}(t.Code),e.authed=!0})},a(function(){$("#masterPassword").focus()}),e.print=function(){if(e.code){r.eventTrack("Print Recovery Code");var t=window.open();t.document.write('<div style="font-size: 18px; text-align: center;"><p>bitwarden two-step login recovery code:</p><code style="font-family: Menlo, Monaco, Consolas, \'Courier New\', monospace;">'+e.code+'</code></div><p style="text-align: center;">'+new Date+"</p>"),t.print(),t.close()}},e.close=function(){n.close()}}]),angular.module("bit.settings").controller("settingsTwoStepU2fController",["$scope","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics","constants","$timeout","$window",function(e,t,n,o,r,a,i,s,l,c){var u;i.eventTrack("settingsTwoStepU2fController",{category:"Modal"});var d=!1;e.deviceResponse=null,e.deviceListening=!1,e.deviceError=!1,l(function(){$("#masterPassword").focus()}),e.auth=function(n){e.authPromise=o.hashPassword(n.masterPassword).then(function(e){return u=e,t.twoFactor.getU2f({},{masterPasswordHash:u}).$promise}).then(function(t){return e.enabled=t.Enabled,e.challenge=t.Challenge,e.authed=!0,e.readDevice()})},e.readDevice=function(){d||e.enabled||(console.log("listening for key..."),e.deviceResponse=null,e.deviceError=!1,e.deviceListening=!0,c.u2f.register(e.challenge.AppId,[{version:e.challenge.Version,challenge:e.challenge.Challenge}],[],function(t){if(e.deviceListening=!1,5!==t.errorCode)return t.errorCode?(l(function(){e.deviceError=!0}),void console.log("error: "+t.errorCode)):void l(function(){e.deviceResponse=JSON.stringify(t)});e.readDevice()},10))},e.submit=function(){e.enabled?function(){if(!confirm("Are you sure you want to disable the U2F provider?"))return;e.submitPromise=t.twoFactor.disable({},{masterPasswordHash:u,type:s.twoFactorProvider.u2f},function(t){i.eventTrack("Disabled Two-step U2F"),a.success("U2F has been disabled."),e.enabled=t.Enabled,e.close()}).$promise}():e.submitPromise=t.twoFactor.putU2f({},{deviceResponse:e.deviceResponse,masterPasswordHash:u},function(t){i.eventTrack("Enabled Two-step U2F"),e.enabled=t.Enabled,e.challenge=null,e.deviceResponse=null,e.deviceError=!1}).$promise},e.close=function(){d=!0,n.close(e.enabled)},e.$on("modal.closing",function(t,n,o){d||(t.preventDefault(),e.close())})}]),angular.module("bit.settings").controller("settingsTwoStepYubiController",["$scope","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics","constants","$timeout",function(e,t,n,o,r,a,i,s,l){i.eventTrack("settingsTwoStepYubiController",{category:"Modal"});var c;function u(t){e.enabled=t.Enabled,e.updateModel={key1:{key:t.Key1,existingKey:d(t.Key1,"*",44)},key2:{key:t.Key2,existingKey:d(t.Key2,"*",44)},key3:{key:t.Key3,existingKey:d(t.Key3,"*",44)},nfc:!0===t.Nfc||!t.Enabled}}function d(e,t,n){if(!e||!t||e.length>=n)return e;for(var o=(n-e.length)/t.length,r=0;r<o;r++)e+=t;return e}l(function(){$("#masterPassword").focus()}),e.auth=function(n){var a=null;e.authPromise=o.hashPassword(n.masterPassword).then(function(e){return c=e,t.twoFactor.getYubi({},{masterPasswordHash:c}).$promise}).then(function(e){return a=e,r.getUserProfile()}).then(function(t){t,u(a),e.authed=!0})},e.remove=function(e){e.key=null,e.existingKey=null},e.submit=function(n){e.submitPromise=t.twoFactor.putYubi({},{key1:n.key1.key,key2:n.key2.key,key3:n.key3.key,nfc:n.nfc,masterPasswordHash:c},function(e){i.eventTrack("Saved Two-step YubiKey"),a.success("YubiKey saved."),u(e)}).$promise},e.disable=function(){confirm("Are you sure you want to disable the YubiKey provider?")&&(e.disableLoading=!0,e.submitPromise=t.twoFactor.disable({},{masterPasswordHash:c,type:s.twoFactorProvider.yubikey},function(t){e.disableLoading=!1,i.eventTrack("Disabled Two-step YubiKey"),a.success("YubiKey has been disabled."),e.enabled=t.Enabled,e.close()},function(t){a.error("Failed to disable."),e.disableLoading=!1}).$promise)};var p=!1;e.close=function(){p=!0,n.close(e.enabled)},e.$on("modal.closing",function(t,n,o){p||(t.preventDefault(),e.close())})}]),angular.module("bit.settings").controller("settingsUpdateKeyController",["$scope","$state","apiService","$uibModalInstance","cipherService","cryptoService","authService","validationService","toastr","$analytics","$q",function(e,t,n,o,r,a,i,s,l,c,u){c.eventTrack("settingsUpdateKeyController",{category:"Modal"}),e.save=function(d){a.getEncKey()?s.addError(d,"MasterPasswordHash","You do not need to update. You are already using the new encryption key.",!0):e.savePromise=a.hashPassword(e.masterPassword).then(function(e){return function(e){var t=a.makeEncKey(null),o=[],i=n.ciphers.list({},function(e){for(var n=[],a=0;a<e.Data.length;a++)e.Data[a].OrganizationId||n.push(e.Data[a]);var i=r.decryptCiphers(n);o=r.encryptCiphers(i,t.encKey)}).$promise,s=[],l=n.folders.list({},function(e){var n=r.decryptFolders(e.Data);s=r.encryptFolders(n,t.encKey)}).$promise,c=a.getPrivateKey("raw"),d=null;c&&(d=a.encrypt(c,t.encKey,"raw"));return u.all([i,l]).then(function(){var r={masterPasswordHash:e,ciphers:o,folders:s,privateKey:d,key:t.encKeyEnc};return n.accounts.putKey(r).$promise},function(){throw"Error while encrypting data."}).then(function(){a.setEncKey(t.encKey,null,!0)})}(e)}).then(function(){return o.dismiss("cancel"),i.logOut(),c.eventTrack("Key Updated"),t.go("frontend.login.info")},function(e){throw e||"Error occurred."}).then(function(){l.success("Please log back in. If you are using other bitwarden applications, log out and back in to those as well.","Key Updated",{timeOut:1e4})})},e.close=function(){o.dismiss("cancel")}}]),angular.module("bit.tools").controller("toolsController",["$scope","$uibModal","apiService","toastr","authService",function(e,t,n,o,r){e.import=function(){t.open({animation:!0,templateUrl:"app/tools/views/toolsImport.html",controller:"toolsImportController"})},e.export=function(){t.open({animation:!0,templateUrl:"app/tools/views/toolsExport.html",controller:"toolsExportController"})}}]),angular.module("bit.tools").controller("toolsExportController",["$scope","apiService","$uibModalInstance","cipherService","$q","toastr","$analytics","constants",function(e,t,n,o,r,a,i,s){function l(){var e=new Date;return"bitwarden_export_"+(e.getFullYear()+""+c(e.getMonth()+1,2)+c(e.getDate(),2)+c(e.getHours(),2)+c(e.getMinutes(),2)+c(e.getSeconds(),2))+".csv"}function c(e,t,n){return n=n||"0",(e+="").length>=t?e:new Array(t-e.length+1).join(n)+e}i.eventTrack("toolsExportController",{category:"Modal"}),e.export=function(n){e.startedExport=!0;var c=[],u=[],d=t.folders.list({},function(e){u=o.decryptFolders(e.Data)}).$promise,p=t.ciphers.list({},function(e){c=o.decryptCiphers(e.Data)}).$promise;r.all([d,p]).then(function(){if(!c.length)return a.error("Nothing to export.","Error!"),void e.close();for(var t={},n=0;n<u.length;n++)t[u[n].id]=u[n];try{var o=[];for(n=0;n<c.length;n++)if(c[n].type===s.cipherType.login||c[n].type===s.cipherType.secureNote){var r={folder:c[n].folderId&&c[n].folderId in t?t[c[n].folderId].name:null,favorite:c[n].favorite?1:null,type:null,name:c[n].name,notes:c[n].notes,fields:null,login_uri:null,login_username:null,login_password:null,login_totp:null};if(c[n].fields)for(var d=0;d<c[n].fields.length;d++)r.fields?r.fields+="\n":r.fields="",r.fields+=(c[n].fields[d].name||"")+": "+c[n].fields[d].value;switch(c[n].type){case s.cipherType.login:r.type="login",r.login_uri=c[n].login.uri,r.login_username=c[n].login.username,r.login_password=c[n].login.password,r.login_totp=c[n].login.totp;break;case s.cipherType.secureNote:r.type="note";break;default:continue}o.push(r)}var p=Papa.unparse(o),m=new Blob([p]);if(window.navigator.msSaveOrOpenBlob)window.navigator.msSaveBlob(m,l());else{var g=window.document.createElement("a");g.href=window.URL.createObjectURL(m,{type:"text/plain"}),g.download=l(),document.body.appendChild(g),g.click(),document.body.removeChild(g)}i.eventTrack("Exported Data"),a.success("Your data has been exported. Check your browser's downloads folder.","Success!"),e.close()}catch(t){a.error("Something went wrong. Please try again.","Error!"),e.close()}},function(){a.error("Something went wrong. Please try again.","Error!"),e.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.tools").controller("toolsImportController",["$scope","$state","apiService","$uibModalInstance","cryptoService","cipherService","toastr","importService","$analytics","$sce","validationService",function(e,t,n,o,r,a,i,s,l,c,u){function d(r,s,c){if(r.length||s.length){if(s.length){var u=Math.floor(s.length/2),d=s.length-1;if(p(s[0])&&p(s[u])&&p(s[d]))return void m("Data is not formatted correctly. Please check your import file and try again.")}n.ciphers.import({folders:a.encryptFolders(r),ciphers:a.encryptCiphers(s),folderRelationships:c},function(){o.dismiss("cancel"),t.go("backend.user.vault",{refreshFromServer:!0}).then(function(){l.eventTrack("Imported Data",{label:e.model.source}),i.success("Data has been successfully imported into your vault.","Import Success")})},m)}else m("Nothing was imported.")}function p(e){return(null===e.name||"--"===e.name)&&e.login&&(null===e.login.password||""===e.login.password)}function m(t){if(l.eventTrack("Import Data Failed",{label:e.model.source}),o.dismiss("cancel"),t){var n=t.data;if(!n||!n.ValidationErrors)return n&&n.Message?void i.error(n.Message):void i.error(t);var r="";for(var a in n.ValidationErrors)if(n.ValidationErrors.hasOwnProperty(a))for(var s=0;s<n.ValidationErrors[a].length;s++)r+=a+": "+n.ValidationErrors[a][s]+" ";if(""!==r)return void i.error(r)}i.error("Something went wrong. Try again.","Oh No!")}l.eventTrack("toolsImportController",{category:"Modal"}),e.model={source:""},e.source={},e.splitFeatured=!0,e.options=[{id:"bitwardencsv",name:"bitwarden (csv)",featured:!0,sort:1,instructions:c.trustAsHtml('Export using the web vault (vault.bitwarden.com). Log into the web vault and navigate to "Tools" > "Export".')},{id:"lastpass",name:"LastPass (csv)",featured:!0,sort:2,instructions:c.trustAsHtml('See detailed instructions on our help site at <a target="_blank" href="https://help.bitwarden.com/article/import-from-lastpass/">https://help.bitwarden.com/article/import-from-lastpass/</a>')},{id:"chromecsv",name:"Chrome (csv)",featured:!0,sort:3,instructions:c.trustAsHtml('See detailed instructions on our help site at <a target="_blank" href="https://help.bitwarden.com/article/import-from-chrome/">https://help.bitwarden.com/article/import-from-chrome/</a>')},{id:"firefoxpasswordexportercsvxml",name:"Firefox Password Exporter (xml)",featured:!0,sort:4,instructions:c.trustAsHtml('Use the <a target="_blank" href="https://addons.mozilla.org/en-US/firefox/addon/password-exporter/">Password Exporter</a> addon for FireFox to export your passwords to a XML file. After installing the addon, type <code>about:addons</code> in your FireFox navigation bar. Locate the Password Exporter addon and click the "Options" button. In the dialog that pops up, click the "Export Passwords" button to save the XML file.')},{id:"keepass2xml",name:"KeePass 2 (xml)",featured:!0,sort:5,instructions:c.trustAsHtml('Using the KeePass 2 desktop application, navigate to "File" > "Export" and select the KeePass XML (2.x) option.')},{id:"keepassxcsv",name:"KeePassX (csv)",instructions:c.trustAsHtml('Using the KeePassX desktop application, navigate to "Database" > "Export to CSV file" and save the CSV file.')},{id:"dashlanecsv",name:"Dashlane (csv)",featured:!0,sort:7,instructions:c.trustAsHtml('Using the Dashlane desktop application, navigate to "File" > "Export" > "Unsecured archive (readable) in CSV format" and save the CSV file.')},{id:"1password1pif",name:"1Password (1pif)",featured:!0,sort:6,instructions:c.trustAsHtml('See detailed instructions on our help site at <a target="_blank" href="https://help.bitwarden.com/article/import-from-1password/">https://help.bitwarden.com/article/import-from-1password/</a>')},{id:"1password6wincsv",name:"1Password 6 Windows (csv)",instructions:c.trustAsHtml('See detailed instructions on our help site at <a target="_blank" href="https://help.bitwarden.com/article/import-from-1password/">https://help.bitwarden.com/article/import-from-1password/</a>')},{id:"roboformhtml",name:"RoboForm (html)",instructions:c.trustAsHtml('Using the RoboForm Editor desktop application, navigate to "RoboForm" (top left) > "Print List" > "Logins". When the following print dialog pops up click on the "Save" button and save the HTML file.')},{id:"keepercsv",name:"Keeper (csv)",instructions:c.trustAsHtml('Log into the Keeper web vault (keepersecurity.com/vault). Navigate to "Backup" (top right) and find the "Export to Text File" option. Click "Export Now" to save the TXT/CSV file.')},{id:"enpasscsv",name:"Enpass (csv)",instructions:c.trustAsHtml('Using the Enpass desktop application, navigate to "File" > "Export" > "As CSV". Select "Yes" to the warning alert and save the CSV file. Note that the importer only fully supports files exported while Enpass is set to the English language, so adjust your settings accordingly.')},{id:"safeincloudxml",name:"SafeInCloud (xml)",instructions:c.trustAsHtml('Using the SaveInCloud desktop application, navigate to "File" > "Export" > "As XML" and save the XML file.')},{id:"pwsafexml",name:"Password Safe (xml)",instructions:c.trustAsHtml('Using the Password Safe desktop application, navigate to "File" > "Export To" > "XML format..." and save the XML file.')},{id:"stickypasswordxml",name:"Sticky Password (xml)",instructions:c.trustAsHtml('Using the Sticky Password desktop application, navigate to "Menu" (top right) > "Export" > "Export all". Select the unencrypted format XML option and then the "Save to file" button. Save the XML file.')},{id:"msecurecsv",name:"mSecure (csv)",instructions:c.trustAsHtml('Using the mSecure desktop application, navigate to "File" > "Export" > "CSV File..." and save the CSV file.')},{id:"truekeycsv",name:"True Key (csv)",instructions:c.trustAsHtml('Using the True Key desktop application, click the gear icon (top right) and then navigate to "App Settings". Click the "Export" button, enter your password and save the CSV file.')},{id:"passwordbossjson",name:"Password Boss (json)",instructions:c.trustAsHtml('Using the Password Boss desktop application, navigate to "File" > "Export data" > "Password Boss JSON - not encrypted" and save the JSON file.')},{id:"zohovaultcsv",name:"Zoho Vault (csv)",instructions:c.trustAsHtml('Log into the Zoho web vault (vault.zoho.com). Navigate to "Tools" > "Export Secrets". Select "All Secrets" and click the "Zoho Vault Format CSV" button. Highlight and copy the data from the textarea. Open a text editor like Notepad and paste the data. Save the data from the text editor as <code>zoho_export.csv</code>.')},{id:"splashidcsv",name:"SplashID (csv)",instructions:c.trustAsHtml('Using the SplashID Safe desktop application, click on the SplashID blue lock logo in the top right corner. Navigate to "Export" > "Export as CSV" and save the CSV file.')},{id:"passworddragonxml",name:"Password Dragon (xml)",instructions:c.trustAsHtml('Using the Password Dragon desktop application, navigate to "File" > "Export" > "To XML". In the dialog that pops up select "All Rows" and check all fields. Click the "Export" button and save the XML file.')},{id:"padlockcsv",name:"Padlock (csv)",instructions:c.trustAsHtml('Using the Padlock desktop application, click the hamburger icon in the top left corner and navigate to "Settings". Click the "Export Data" option. Ensure that the "CSV" option is selected from the dropdown. Highlight and copy the data from the textarea. Open a text editor like Notepad and paste the data. Save the data from the text editor as <code>padlock_export.csv</code>.')},{id:"clipperzhtml",name:"Clipperz (html)",instructions:c.trustAsHtml('Log into the Clipperz web application (clipperz.is/app). Click the hamburger menu icon in the top right to expand the navigation bar. Navigate to "Data" > "Export". Click the "download HTML+JSON" button to save the HTML file.')},{id:"avirajson",name:"Avira (json)",instructions:c.trustAsHtml('Using the Avira browser extension, click your username in the top right corner and navigate to "Settings". Locate the "Export Data" section and click "Export". In the dialog that pops up, click the "Export Password Manager Data" button to save the TXT/JSON file.')},{id:"saferpasscsv",name:"SaferPass (csv)",instructions:c.trustAsHtml('Using the SaferPass browser extension, click the hamburger icon in the top left corner and navigate to "Settings". Click the "Export accounts" button to save the CSV file.')},{id:"upmcsv",name:"Universal Password Manager (csv)",instructions:c.trustAsHtml('Using the Universal Password Manager desktop application, navigate to "Database" > "Export" and save the CSV file.')},{id:"ascendocsv",name:"Ascendo DataVault (csv)",instructions:c.trustAsHtml('Using the Ascendo DataVault desktop application, navigate to "Tools" > "Export". In the dialog that pops up, select the "All Items (DVX, CSV)" option. Click the "Ok" button to save the CSV file.')},{id:"meldiumcsv",name:"Meldium (csv)",instructions:c.trustAsHtml('Using the Meldium web vault, navigate to "Settings". Locate the "Export data" function and click "Show me my data" to save the CSV file.')},{id:"passkeepcsv",name:"PassKeep (csv)",instructions:c.trustAsHtml('Using the PassKeep mobile app, navigate to "Backup/Restore". Locate the "CSV Backup/Restore" section and click "Backup to CSV" to save the CSV file.')},{id:"operacsv",name:"Opera (csv)",instructions:c.trustAsHtml('The process for importing from Opera is exactly the same as importing from Google Chrome. See detailed instructions on our help site at <a target="_blank" href="https://help.bitwarden.com/article/import-from-chrome/">https://help.bitwarden.com/article/import-from-chrome/</a>')},{id:"vivaldicsv",name:"Vivaldi (csv)",instructions:c.trustAsHtml('The process for importing from Vivaldi is exactly the same as importing from Google Chrome. See detailed instructions on our help site at <a target="_blank" href="https://help.bitwarden.com/article/import-from-chrome/">https://help.bitwarden.com/article/import-from-chrome/</a>')},{id:"gnomejson",name:"GNOME Passwords and Keys/Seahorse (json)",instructions:c.trustAsHtml('Make sure you have python-keyring and python-gnomekeyring installed. Save the <a target="_blank" href="http://bit.ly/2sMldAI">GNOME Keyring Import/Export</a> python script by Luke Plant to your desktop as <code>pw_helper.py</code>. Open terminal and run <code>chmod +rx Desktop/pw_helper.py</code> and then <code>python Desktop/pw_helper.py export Desktop/my_passwords.json</code>. Then upload the resulting <code>my_passwords.json</code> file here to bitwarden.')}],e.setSource=function(){for(var t=0;t<e.options.length;t++)if(e.options[t].id===e.model.source){e.source=e.options[t];break}},e.setSource(),e.import=function(t,n){if(t.source&&""!==t.source){var o=document.getElementById("file").files[0];o||t.fileContents&&""!==t.fileContents?(e.processing=!0,s.import(t.source,o||t.fileContents,d,m)):u.addError(n,"file","Select the import file or copy/paste the import file contents.",!0)}else u.addError(n,"source","Select the format of the import file.",!0)},e.close=function(){o.dismiss("cancel")}}]),angular.module("bit.vault").controller("vaultAddCipherController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","passwordService","selectedFolder","$analytics","checkedFavorite","$rootScope","authService","$uibModal","constants","$filter",function(e,t,n,o,r,a,i,s,l,c,u,d,p,m){function g(e){var t=$(e.trigger).parent().prev();"text"===t.attr("type")&&t.select()}s.eventTrack("vaultAddCipherController",{category:"Modal"}),e.folders=m("filter")(c.vaultGroupings,{folder:!0}),e.constants=p,e.selectedType=p.cipherType.login.toString(),e.cipher={folderId:i?i.id:null,favorite:!0===l,type:p.cipherType.login,login:{},identity:{},card:{},secureNote:{type:0}},u.getUserProfile().then(function(t){e.useTotp=t.premium}),e.typeChanged=function(){e.cipher.type=parseInt(e.selectedType)},e.savePromise=null,e.save=function(){var o=r.encryptCipher(e.cipher);e.savePromise=t.ciphers.post(o,function(e){s.eventTrack("Created Cipher");var t=r.decryptCipherPreview(e);n.close(t)}).$promise},e.generatePassword=function(){e.cipher.login.password&&!confirm("Are you sure you want to overwrite the current password?")||(s.eventTrack("Generated Password From Add"),e.cipher.login.password=a.generatePassword({length:14,special:!0}))},e.addField=function(){e.cipher.fields||(e.cipher.fields=[]),e.cipher.fields.push({type:p.fieldType.text.toString(),name:null,value:null})},e.removeField=function(t){var n=e.cipher.fields.indexOf(t);n>-1&&e.cipher.fields.splice(n,1)},e.toggleFavorite=function(){e.cipher.favorite=!e.cipher.favorite},e.clipboardSuccess=function(e){e.clearSelection(),g(e)},e.clipboardError=function(e,t){t&&g(e),alert("Your web browser does not support easy clipboard copying. Copy it manually instead.")},e.folderSort=function(e){return e.id?e.name.toLowerCase():""},e.close=function(){n.dismiss("close")},e.showUpgrade=function(){d.open({animation:!0,templateUrl:"app/views/premiumRequired.html",controller:"premiumRequiredController"})}}]),angular.module("bit.vault").controller("vaultAddFolderController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","$analytics",function(e,t,n,o,r,a){a.eventTrack("vaultAddFolderController",{category:"Modal"}),e.savePromise=null,e.save=function(o){var i=r.encryptFolder(o);e.savePromise=t.folders.post(i,function(e){a.eventTrack("Created Folder");var t=r.decryptFolder(e);n.close(t)}).$promise},e.close=function(){n.dismiss("close")}}]),angular.module("bit.vault").controller("vaultAttachmentsController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","cipherId","$analytics","validationService","toastr","$timeout","authService","$uibModal",function(e,t,n,o,r,a,i,s,l,c,u,d){i.eventTrack("vaultAttachmentsController",{category:"Modal"}),e.cipher={},e.readOnly=!0,e.loading=!0,e.isPremium=!0,e.canUseAttachments=!0;var p=!1;function m(){return e.cipher.organizationId?o.getOrgKey(e.cipher.organizationId):null}u.getUserProfile().then(function(n){return e.isPremium=n.premium,t.ciphers.get({id:a}).$promise}).then(function(t){e.cipher=r.decryptCipher(t),e.readOnly=!e.cipher.edit,e.canUseAttachments=e.isPremium||e.cipher.organizationId,e.loading=!1},function(){e.loading=!1}),e.save=function(n){var o=document.getElementById("file"),c=o.files;c&&c.length?e.savePromise=r.encryptAttachmentFile(m(),c[0]).then(function(e){var n=new FormData,o=new Blob([e.data],{type:"application/octet-stream"});return n.append("data",o,e.fileName),t.ciphers.postAttachment({id:a},n).$promise}).then(function(t){i.eventTrack("Added Attachment"),e.cipher=r.decryptCipher(t),o.type="",o.type="file",o.value=""},function(e){var t=s.parseErrors(e);l.error(t.length?t[0]:"An error occurred.")}):s.addError(n,"file","Select a file.",!0)},e.download=function(t){if(t.loading=!0,!e.canUseAttachments)return t.loading=!1,void alert("Premium membership is required to use this feature.");r.downloadAndDecryptAttachment(m(),t,!0).then(function(e){c(function(){t.loading=!1})},function(){c(function(){t.loading=!1})})},e.remove=function(n){confirm("Are you sure you want to delete this attachment ("+n.fileName+")?")&&(n.loading=!0,t.ciphers.delAttachment({id:a,attachmentId:n.id}).$promise.then(function(){n.loading=!1,i.eventTrack("Deleted Attachment");var t=e.cipher.attachments.indexOf(n);t>-1&&e.cipher.attachments.splice(t,1)},function(){l.error("Cannot delete attachment."),n.loading=!1}))},e.close=function(){n.dismiss("cancel")},e.$on("modal.closing",function(t,o,r){p||(t.preventDefault(),p=!0,n.close(!!e.cipher.attachments&&e.cipher.attachments.length>0))}),e.showUpgrade=function(){d.open({animation:!0,templateUrl:"app/views/premiumRequired.html",controller:"premiumRequiredController"})}}]),angular.module("bit.vault").controller("vaultCipherCollectionsController",["$scope","apiService","$uibModalInstance","cipherService","cipherId","$analytics",function(e,t,n,o,r,a){a.eventTrack("vaultCipherCollectionsController",{category:"Modal"}),e.cipher={},e.readOnly=!1,e.loadingCipher=!0,e.loadingCollections=!0,e.selectedCollections={},e.collections=[];var i=null;n.opened.then(function(){t.ciphers.getDetails({id:r}).$promise.then(function(t){if(e.loadingCipher=!1,e.readOnly=!t.Edit,t.Edit&&t.OrganizationId){1===t.Type&&(e.cipher=o.decryptCipherPreview(t));var n={};if(t.CollectionIds)for(var r=0;r<t.CollectionIds.length;r++)n[t.CollectionIds[r]]=null;return{cipher:t,cipherCollections:n}}return null}).then(function(n){return n?(i=n,t.collections.listMe({writeOnly:!0}).$promise):(e.loadingCollections=!1,!1)}).then(function(t){if(!1!==t){for(var n=[],r={},a=t.Data,s=0;s<a.length;s++)if(a[s].OrganizationId===i.cipher.OrganizationId){a[s].Id in i.cipherCollections&&(r[a[s].Id]=!0);var l=o.decryptCollection(a[s]);n.push(l)}e.loadingCollections=!1,e.collections=n,e.selectedCollections=r}})}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.collections.length;o++)n[e.collections[o].id]=!0;e.selectedCollections=n},e.toggleCollectionSelection=function(t){t in e.selectedCollections?delete e.selectedCollections[t]:e.selectedCollections[t]=!0},e.collectionSelected=function(t){return t.id in e.selectedCollections},e.allSelected=function(){return Object.keys(e.selectedCollections).length===e.collections.length},e.submit=function(){var o={collectionIds:[]};for(var i in e.selectedCollections)e.selectedCollections.hasOwnProperty(i)&&o.collectionIds.push(i);e.submitPromise=t.ciphers.putCollections({id:r},o).$promise.then(function(e){a.eventTrack("Edited Cipher Collections"),n.close({action:"collectionsEdit",collectionIds:o.collectionIds})})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.vault").controller("vaultController",["$scope","$uibModal","apiService","$filter","cryptoService","authService","toastr","cipherService","$q","$localStorage","$timeout","$rootScope","$state","$analytics","constants","validationService",function(e,t,n,o,r,a,i,s,l,c,u,d,p,m,g,f){function h(t){d.vaultGroupings=o("orderBy")(t,["folder",b]);var n=o("filter")(d.vaultGroupings,{collection:!0});e.collectionCount=n.length,e.folderCount=t.length-n.length-1,n&&n.length&&(e.firstCollectionId=n[0].id)}function v(t){angular.forEach(d.vaultGroupings,function(e,n){e.collapsed=c.collapsedFolders&&(e.id||"none")in c.collapsedFolders,angular.forEach(t,function(t){t.favorite?t.sort=-1:e.folder&&t.folderId==e.id?t.sort=n:e.collection&&t.collectionIds.indexOf(e.id)>-1&&(t.sort=n)})}),d.vaultCiphers=e.ciphers=o("orderBy")(t,["sort","name","subTitle"]);var n=function(e,t){var n=[],o=0,r=e.length;for(;o<r;)n.push(e.slice(o,o+=t));return n}(d.vaultCiphers,400);if(n.length>0){e.ciphers=n[0];var r=200;angular.forEach(n,function(t,n){n>0&&u(function(){Array.prototype.push.apply(e.ciphers,t)},r+=200)})}}function y(){d.vaultCiphers=e.ciphers=o("orderBy")(d.vaultCiphers,["name","subTitle"])}function b(e){return e.id?e.name.toLowerCase():""}function w(e,t,n){return n.indexOf(e)===t}function C(){return $('input[name="cipherSelection"]:checked').map(function(){return $(this).val()}).get().filter(w)}function S(e){$('input[name="cipherSelection"]').prop("checked",e)}function k(t){var n=d.vaultCiphers.indexOf(t);n>-1&&d.vaultCiphers.splice(n,1),(n=e.ciphers.indexOf(t))>-1&&e.ciphers.splice(n,1)}e.loading=!0,e.ciphers=[],e.folderCount=0,e.collectionCount=0,e.firstCollectionId=null,e.constants=g,e.favoriteCollapsed=c.collapsedFolders&&"favorite"in c.collapsedFolders,e.groupingIdFilter=void 0,e.typeFilter=void 0,p.params.refreshFromServer&&(d.vaultGroupings=d.vaultCiphers=null),e.$on("$viewContentLoaded",function(){if($("#search").focus(),d.vaultGroupings&&d.vaultCiphers)return e.loading=!1,h(d.vaultGroupings),void v(d.vaultCiphers);var t,o,r,a,i;t=[{id:null,name:"No Folder",folder:!0}],o=n.collections.listMe({writeOnly:!1},function(e){for(var n=0;n<e.Data.length;n++){var o=s.decryptCollection(e.Data[n],null,!0);o.collection=!0,t.push(o)}}).$promise,r=n.folders.list({},function(e){for(var n=0;n<e.Data.length;n++){var o=s.decryptFolderPreview(e.Data[n]);o.folder=!0,t.push(o)}}).$promise,a=l.all([o,r]).then(function(){h(t)}),i=n.ciphers.list({},function(e){for(var t=[],n=0;n<e.Data.length;n++){var o=s.decryptCipherPreview(e.Data[n]);t.push(o)}a.then(function(){v(t)})}).$promise,l.all([i,a]).then(function(){e.loading=!1})}),e.clipboardError=function(e){alert("Your web browser does not support easy clipboard copying. Edit the item and copy it manually instead.")},e.collapseExpand=function(e,t){c.collapsedFolders||(c.collapsedFolders={});var n=t?"favorite":e.id||"none";n in c.collapsedFolders?delete c.collapsedFolders[n]:c.collapsedFolders[n]=!0},e.collapseAll=function(){if(c.collapsedFolders||(c.collapsedFolders={}),c.collapsedFolders.none=!0,c.collapsedFolders.favorite=!0,d.vaultGroupings)for(var e=0;e<d.vaultGroupings.length;e++)c.collapsedFolders[d.vaultGroupings[e].id]=!0;$(".box").addClass("collapsed-box"),$(".box .box-header button i.fa-minus").removeClass("fa-minus").addClass("fa-plus")},e.expandAll=function(){c.collapsedFolders&&delete c.collapsedFolders,$(".box").removeClass("collapsed-box"),$(".box-body").show(),$(".box .box-header button i.fa-plus").removeClass("fa-plus").addClass("fa-minus")},e.editCipher=function(n){t.open({animation:!0,templateUrl:"app/vault/views/vaultEditCipher.html",controller:"vaultEditCipherController",resolve:{cipherId:function(){return n.id}}}).result.then(function(t){if("edit"===t.action){var o=e.ciphers.indexOf(n);o>-1&&(d.vaultCiphers[o]=t.data),y()}else"partialEdit"===t.action?(n.folderId=t.data.folderId,n.favorite=t.data.favorite):"delete"===t.action&&k(n)})},e.$on("vaultAddCipher",function(t,n){e.addCipher()}),e.addCipher=function(e,n){t.open({animation:!0,templateUrl:"app/vault/views/vaultAddCipher.html",controller:"vaultAddCipherController",resolve:{selectedFolder:function(){return e&&e.folder?e:null},checkedFavorite:function(){return n}}}).result.then(function(e){d.vaultCiphers.push(e),y()})},e.deleteCipher=function(e){confirm("Are you sure you want to delete this item ("+e.name+")?")&&n.ciphers.del({id:e.id},function(){m.eventTrack("Deleted Item"),k(e)})},e.attachments=function(e){a.getUserProfile().then(function(t){return{isPremium:t.premium,orgUseStorage:e.organizationId&&!!t.organizations[e.organizationId].maxStorageGb}}).then(function(n){if(!e.hasAttachments){if(e.organizationId&&!n.orgUseStorage)return void t.open({animation:!0,templateUrl:"app/views/paidOrgRequired.html",controller:"paidOrgRequiredController",resolve:{orgId:function(){return e.organizationId}}});if(!e.organizationId&&!n.isPremium)return void t.open({animation:!0,templateUrl:"app/views/premiumRequired.html",controller:"premiumRequiredController"})}e.organizationId||r.getEncKey()?t.open({animation:!0,templateUrl:"app/vault/views/vaultAttachments.html",controller:"vaultAttachmentsController",resolve:{cipherId:function(){return e.id}}}).result.then(function(t){e.hasAttachments=t}):i.error("You cannot use this feature until you update your encryption key.","Feature Unavailable")})},e.editFolder=function(e){t.open({animation:!0,templateUrl:"app/vault/views/vaultEditFolder.html",controller:"vaultEditFolderController",size:"sm",resolve:{folderId:function(){return e.id}}}).result.then(function(t){e.name=t.name})},e.$on("vaultAddFolder",function(t,n){e.addFolder()}),e.addFolder=function(){t.open({animation:!0,templateUrl:"app/vault/views/vaultAddFolder.html",controller:"vaultAddFolderController",size:"sm"}).result.then(function(e){e.folder=!0,d.vaultGroupings.push(e),h(d.vaultGroupings)})},e.deleteFolder=function(t){confirm("Are you sure you want to delete this folder ("+t.name+")?")&&n.folders.del({id:t.id},function(){m.eventTrack("Deleted Folder");var n=d.vaultGroupings.indexOf(t);n>-1&&(d.vaultGroupings.splice(n,1),e.folderCount--)})},e.canDeleteFolder=function(e){if(!e||!e.id||!d.vaultCiphers)return!1;var t=o("filter")(d.vaultCiphers,{folderId:e.id});return t&&0===t.length},e.share=function(e){t.open({animation:!0,templateUrl:"app/vault/views/vaultShareCipher.html",controller:"vaultShareCipherController",resolve:{cipherId:function(){return e.id}}}).result.then(function(t){e.organizationId=t})},e.editCollections=function(e){t.open({animation:!0,templateUrl:"app/vault/views/vaultCipherCollections.html",controller:"vaultCipherCollectionsController",resolve:{cipherId:function(){return e.id}}}).result.then(function(t){t.collectionIds&&!t.collectionIds.length?k(e):t.collectionIds&&(e.collectionIds=t.collectionIds)})},e.filterGrouping=function(t){e.groupingIdFilter=t.id,$.AdminLTE&&$.AdminLTE.layout&&u(function(){$.AdminLTE.layout.fix()},0)},e.filterType=function(t){e.typeFilter=t,$.AdminLTE&&$.AdminLTE.layout&&u(function(){$.AdminLTE.layout.fix()},0)},e.clearFilters=function(){e.groupingIdFilter=void 0,e.typeFilter=void 0,$.AdminLTE&&$.AdminLTE.layout&&u(function(){$.AdminLTE.layout.fix()},0)},e.groupingFilter=function(t){return void 0===e.groupingIdFilter||t.id===e.groupingIdFilter},e.cipherFilter=function(t){return function(n){var o=null===t;return!o&&t.folder&&n.folderId===t.id?o=!0:!o&&t.collection&&n.collectionIds.indexOf(t.id)>-1&&(o=!0),o&&(void 0===e.typeFilter||n.type===e.typeFilter)}},e.unselectAll=function(){S(!1)},e.selectFolder=function(e,t){$(t.currentTarget).closest(".box").find('input[name="cipherSelection"]').prop("checked",!0)},e.select=function(e){var t=$(e.currentTarget).closest("tr").find('input[name="cipherSelection"]');t.prop("checked",!t.prop("checked"))},e.bulkMove=function(){var e=C();0!==e.length?t.open({animation:!0,templateUrl:"app/vault/views/vaultMoveCiphers.html",controller:"vaultMoveCiphersController",size:"sm",resolve:{ids:function(){return e}}}).result.then(function(t){for(var n=0;n<e.length;n++){var r=o("filter")(d.vaultCiphers,{id:e[n]});r.length&&(r[0].folderId=t)}S(!1),y(),i.success("Items have been moved!")}):alert("You have not selected anything.")},e.bulkDelete=function(){var t=C();0!==t.length?confirm("Are you sure you want to delete the selected items (total: "+t.length+")?")&&(e.actionLoading=!0,n.ciphers.delMany({ids:t},function(){m.eventTrack("Bulk Deleted Items");for(var n=0;n<t.length;n++){var r=o("filter")(d.vaultCiphers,{id:t[n]});r.length&&r[0].edit&&k(r[0])}S(!1),e.actionLoading=!1,i.success("Items have been deleted!")},function(t){var n=f.parseErrors(t);i.error(n.length?n[0]:"An error occurred."),e.actionLoading=!1})):alert("You have not selected anything.")}}]),angular.module("bit.vault").controller("vaultEditCipherController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","passwordService","cipherId","$analytics","$rootScope","authService","$uibModal","constants","$filter",function(e,t,n,o,r,a,i,s,l,c,u,d,p){function m(e){var t=$(e.trigger).parent().prev();"text"===t.attr("type")&&t.select()}s.eventTrack("vaultEditCipherController",{category:"Modal"}),e.folders=p("filter")(l.vaultGroupings,{folder:!0}),e.cipher={},e.readOnly=!1,e.constants=d,c.getUserProfile().then(function(n){return e.useTotp=n.premium,t.ciphers.get({id:i}).$promise}).then(function(t){e.cipher=r.decryptCipher(t),e.readOnly=!e.cipher.edit,e.useTotp=e.useTotp||e.cipher.organizationUseTotp}),e.save=function(o){if(e.readOnly)e.savePromise=t.ciphers.putPartial({id:i},{folderId:o.folderId,favorite:o.favorite},function(e){s.eventTrack("Partially Edited Cipher"),n.close({action:"partialEdit",data:{id:i,favorite:o.favorite,folderId:o.folderId&&""!==o.folderId?o.folderId:null}})}).$promise;else{var a=r.encryptCipher(o,e.cipher.type);e.savePromise=t.ciphers.put({id:i},a,function(e){s.eventTrack("Edited Cipher");var t=r.decryptCipherPreview(e);n.close({action:"edit",data:t})}).$promise}},e.generatePassword=function(){e.cipher.login.password&&!confirm("Are you sure you want to overwrite the current password?")||(s.eventTrack("Generated Password From Edit"),e.cipher.login.password=a.generatePassword({length:14,special:!0}))},e.addField=function(){e.cipher.fields||(e.cipher.fields=[]),e.cipher.fields.push({type:d.fieldType.text.toString(),name:null,value:null})},e.removeField=function(t){var n=e.cipher.fields.indexOf(t);n>-1&&e.cipher.fields.splice(n,1)},e.toggleFavorite=function(){e.cipher.favorite=!e.cipher.favorite},e.clipboardSuccess=function(e){e.clearSelection(),m(e)},e.clipboardError=function(e,t){t&&m(e),alert("Your web browser does not support easy clipboard copying. Copy it manually instead.")},e.folderSort=function(e){return e.id?e.name.toLowerCase():""},e.delete=function(){confirm("Are you sure you want to delete this item ("+e.cipher.name+")?")&&t.ciphers.del({id:e.cipher.id},function(){s.eventTrack("Deleted Cipher From Edit"),n.close({action:"delete",data:e.cipher.id})})},e.close=function(){n.dismiss("cancel")},e.showUpgrade=function(){u.open({animation:!0,templateUrl:"app/views/premiumRequired.html",controller:"premiumRequiredController"})}}]),angular.module("bit.vault").controller("vaultEditFolderController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","folderId","$analytics",function(e,t,n,o,r,a,i){i.eventTrack("vaultEditFolderController",{category:"Modal"}),e.folder={},t.folders.get({id:a},function(t){e.folder=r.decryptFolder(t)}),e.savePromise=null,e.save=function(o){var s=r.encryptFolder(o);e.savePromise=t.folders.put({id:a},s,function(e){i.eventTrack("Edited Folder");var t=r.decryptFolder(e);n.close(t)}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.vault").controller("vaultMoveCiphersController",["$scope","apiService","$uibModalInstance","ids","$analytics","$rootScope","$filter",function(e,t,n,o,r,a,i){r.eventTrack("vaultMoveCiphersController",{category:"Modal"}),e.folders=i("filter")(a.vaultGroupings,{folder:!0}),e.count=o.length,e.save=function(){e.savePromise=t.ciphers.moveMany({ids:o,folderId:e.folderId},function(){r.eventTrack("Bulk Moved Ciphers"),n.close(e.folderId||null)}).$promise},e.folderSort=function(e){return e.id?e.name.toLowerCase():"!"},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.vault").controller("vaultShareCipherController",["$scope","apiService","$uibModalInstance","authService","cipherService","cipherId","$analytics","$state","cryptoService","$q","toastr",function(e,t,n,o,r,a,i,s,l,c,u){i.eventTrack("vaultShareCipherController",{category:"Modal"}),e.model={},e.cipher={},e.collections=[],e.selectedCollections={},e.organizations=[];var d={};e.loadingCollections=!0,e.loading=!0,e.readOnly=!1,t.ciphers.get({id:a}).$promise.then(function(t){return e.readOnly=!t.Edit,t.Edit&&(e.cipher=r.decryptCipher(t)),t.Edit}).then(function(t){if(e.loading=!1,t)return o.getUserProfile()}).then(function(n){if(n&&n.organizations){var o=[],a=!1;for(var i in n.organizations)n.organizations.hasOwnProperty(i)&&n.organizations[i].enabled&&(o.push({id:n.organizations[i].id,name:n.organizations[i].name}),d[n.organizations[i].id]=0,a||(a=!0,e.model.organizationId=n.organizations[i].id));e.organizations=o,t.collections.listMe({writeOnly:!0},function(t){for(var n=[],o=0;o<t.Data.length;o++){var a=r.decryptCollection(t.Data[o]);a.organizationId=t.Data[o].OrganizationId,n.push(a),d[a.organizationId]++}e.collections=n,e.loadingCollections=!1})}}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.collections.length;o++)e.model.organizationId&&e.collections[o].organizationId===e.model.organizationId&&(n[e.collections[o].id]=!0);e.selectedCollections=n},e.toggleCollectionSelection=function(t){t in e.selectedCollections?delete e.selectedCollections[t]:e.selectedCollections[t]=!0},e.collectionSelected=function(t){return t.id in e.selectedCollections},e.allSelected=function(){return!!e.model.organizationId&&Object.keys(e.selectedCollections).length===d[e.model.organizationId]},e.orgChanged=function(){e.selectedCollections={}},e.submitPromise=null,e.submit=function(o){var s=l.getOrgKey(o.organizationId),d=!1,p=[];if(e.cipher.attachments)for(var m=0;m<e.cipher.attachments.length;m++)!function(e){var n=r.downloadAndDecryptAttachment(null,e,!1).then(function(e){return l.encryptToBytes(e.buffer,s)}).then(function(n){if(!d){var r=new FormData,i=new Blob([n],{type:"application/octet-stream"}),c=l.encrypt(e.fileName,s);return r.append("data",i,c),t.ciphers.postShareAttachment({id:a,attachmentId:e.id,orgId:o.organizationId},r).$promise}},function(e){d=!0});p.push(n)}(e.cipher.attachments[m]);e.submitPromise=c.all(p).then(function(){if(!d){e.cipher.organizationId=o.organizationId;var n={collectionIds:[],cipher:r.encryptCipher(e.cipher,e.cipher.type,null,!0)};for(var i in e.selectedCollections)e.selectedCollections.hasOwnProperty(i)&&n.collectionIds.push(i);return t.ciphers.putShare({id:a},n).$promise}}).then(function(e){i.eventTrack("Shared Cipher"),u.success("Item has been shared."),n.close(o.organizationId)})},e.close=function(){n.dismiss("cancel")},e.createOrg=function(){s.go("backend.user.settingsCreateOrg").then(function(){n.dismiss("cancel")})}}]);