(()=>{var e,t,i,n={61263:(e,t,i)=>{"use strict";var n,r=i(99042);!function(e){e[e.Password=0]="Password",e[e.Sso=1]="Sso",e[e.UserApiKey=2]="UserApiKey",e[e.AuthRequest=3]="AuthRequest",e[e.WebAuthn=4]="WebAuthn"}(n||(n={}));class s{constructor(e=null,t=null,i=!1){this.provider=e,this.token=t,this.remember=i}}var o=i(14375),a=i(7312),l=i(92716),c=i(30359),d=i(84026),u=i(71624);const h="undefined"==typeof window?i(69573):null;class p{static init(){p.inited||(p.inited=!0,p.isNode=void 0!==u&&null!=u.release&&"node"===u.release.name,p.isBrowser="undefined"!=typeof window,p.isMobileBrowser=p.isBrowser&&this.isMobile(window),p.isAppleMobileBrowser=p.isBrowser&&this.isAppleMobile(window),p.isNode?p.global=i.g:p.isBrowser?p.global=window:p.global=self)}static fromB64ToArray(e){if(null==e)return null;if(p.isNode)return new Uint8Array(Buffer.from(e,"base64"));{const t=p.global.atob(e),i=new Uint8Array(t.length);for(let e=0;e("00"+e.toString(16)).slice(-2))).join("")}}static hexStringToArrayBuffer(e){if(e.length%2!=0)throw"HexString has to be an even length";const t=new ArrayBuffer(e.length/2),i=new Uint8Array(t);for(let t=0;t{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}static isGuid(e){return RegExp(p.guidRegex,"i").test(e)}static getHostname(e){if(p.isNullOrWhitespace(e))return null;if((e=e.trim()).startsWith("data:"))return null;if(e.startsWith("about:"))return null;if(e.startsWith("file:"))return null;if(e.indexOf("!")>0)return null;try{const t=(0,d.Fo)(e,{validHosts:this.validHosts});if(null!=t)return t}catch(e){return null}return null}static getHost(e){const t=p.getUrl(e);try{return null!=t&&""!==t.host?t.host:null}catch(e){return null}}static getDomain(e){if(p.isNullOrWhitespace(e))return null;if((e=e.trim()).startsWith("data:"))return null;if(e.startsWith("about:"))return null;try{const t=(0,d.Qc)(e,{validHosts:this.validHosts,allowPrivateDomains:!0});if(null!=t&&null!=t.hostname)return"localhost"===t.hostname||t.isIp?t.hostname:null!=t.domain?t.domain:null}catch(e){return null}return null}static getQueryParams(e){const t=p.getUrl(e);if(null==t||null==t.search||""===t.search)return null;const i=new Map;return("?"===t.search[0]?t.search.substr(1):t.search).split("&").forEach((e=>{const t=e.split("=");t.length<1||i.set(decodeURIComponent(t[0]).toLowerCase(),null==t[1]?"":decodeURIComponent(t[1]))})),i}static getSortFunction(e,t){return(i,n)=>null==i[t]&&null!=n[t]?-1:null!=i[t]&&null==n[t]?1:null==i[t]&&null==n[t]?0:e.collator?e.collator.compare(i[t],n[t]):i[t].localeCompare(n[t])}static isNullOrWhitespace(e){return null==e||"string"!=typeof e||""===e.trim()}static isNullOrEmpty(e){return null==e||"string"!=typeof e||""==e}static isPromise(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch}static nameOf(e){return e}static assign(e,t){return Object.assign(e,t)}static iterateEnum(e){return Object.keys(e).filter((e=>Number.isNaN(+e))).map((t=>e[t]))}static getUrl(e){return this.isNullOrWhitespace(e)?null:(e=e.trim(),p.getUrlObject(e))}static camelToPascalCase(e){return e.charAt(0).toUpperCase()+e.slice(1)}static pickTextColorBasedOnBgColor(e,t=186,i=!1){const n="#"===e.charAt(0)?e.substring(1,7):e;return.299*parseInt(n.substring(0,2),16)+.587*parseInt(n.substring(2,4),16)+.114*parseInt(n.substring(4,6),16)>t?i?"black":"black !important":i?"white":"white !important"}static stringToColor(e){let t=0;for(let i=0;i>8*e&255).toString(16)).substr(-2)}return i}static getContainerService(){if(null==this.global.bitwardenContainerService)throw new Error("global bitwardenContainerService not initialized.");return this.global.bitwardenContainerService}static validateHexColor(e){return/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(e)}static mapToRecord(e){return null==e?null:e instanceof Map?Object.fromEntries(e):e}static recordToMap(e){if(null==e)return null;if(e instanceof Map)return e;const t=Object.entries(e);return 0===t.length?new Map:isNaN(Number(t[0][0]))?new Map(t):new Map(t.map((e=>[Number(e[0]),e[1]])))}static merge(e,t){return Object.assign(e,t)}static encodeRFC3986URIComponent(e){return encodeURIComponent(e).replace(/[!'()*]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))}static normalizePath(e){return o.normalize(decodeURIComponent(e)).replace(/^(\.\.(\/|\\|$))+/,"")}static isMobile(e){let t=!1;var i;return i=e.navigator.userAgent||e.navigator.vendor||e.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(i)||/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(i.substr(0,4)))&&(t=!0),t||null!=e.navigator.userAgent.match(/iPad/i)}static delay(e){return new Promise((t=>setTimeout(t,e)))}static asyncToObservable(e){return(0,l.of)(void 0).pipe((0,c.w)((()=>e())))}static daysRemaining(e){const t=e.getTime()-Date.now();return Math.max(0,Math.floor(t/864e5))}static isAppleMobile(e){return null!=e.navigator.userAgent.match(/iPhone/i)||null!=e.navigator.userAgent.match(/iPad/i)}static getUrlObject(e){const t=e.indexOf("://")>-1;if(!t&&e.indexOf(".")>-1)e="http://"+e;else if(!t)return null;try{return null!=h?new h.URL(e):new URL(e)}catch(e){}return null}}p.inited=!1,p.isNode=!1,p.isBrowser=!0,p.isMobileBrowser=!1,p.isAppleMobileBrowser=!1,p.global=null,p.regexpEmojiPresentation=/(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])/g,p.validHosts=["localhost"],p.originalMinimumPasswordLength=8,p.minimumPasswordLength=12,p.DomainMatchBlacklist=new Map([["google.com",new Set(["script.google.com"])]]),p.guidRegex=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,p.init();class y{constructor(e){this.id=e.id,this.rawId=p.fromBufferToUrlB64(e.rawId),this.type=e.type,this.extensions={}}}class v extends y{constructor(e){if(super(e),!(e.response instanceof AuthenticatorAssertionResponse))throw new Error("Invalid authenticator response");this.response={authenticatorData:p.fromBufferToUrlB64(e.response.authenticatorData),signature:p.fromBufferToUrlB64(e.response.signature),clientDataJSON:p.fromBufferToUrlB64(e.response.clientDataJSON),userHandle:p.fromBufferToUrlB64(e.response.userHandle)}}static fromJSON(e){return Object.assign(Object.create(v.prototype),e)}}var f;!function(e){e[e.AesCbc256_B64=0]="AesCbc256_B64",e[e.AesCbc128_HmacSha256_B64=1]="AesCbc128_HmacSha256_B64",e[e.AesCbc256_HmacSha256_B64=2]="AesCbc256_HmacSha256_B64",e[e.Rsa2048_OaepSha256_B64=3]="Rsa2048_OaepSha256_B64",e[e.Rsa2048_OaepSha1_B64=4]="Rsa2048_OaepSha1_B64",e[e.Rsa2048_OaepSha256_HmacSha256_B64=5]="Rsa2048_OaepSha256_HmacSha256_B64",e[e.Rsa2048_OaepSha1_HmacSha256_B64=6]="Rsa2048_OaepSha1_HmacSha256_B64"}(f||(f={}));const g={[f.AesCbc256_B64]:2,[f.AesCbc128_HmacSha256_B64]:3,[f.AesCbc256_HmacSha256_B64]:3,[f.Rsa2048_OaepSha256_B64]:1,[f.Rsa2048_OaepSha1_B64]:1,[f.Rsa2048_OaepSha256_HmacSha256_B64]:2,[f.Rsa2048_OaepSha1_HmacSha256_B64]:2};var m,w,S,b;!function(e){e[e.Direct=0]="Direct",e[e.Azure=1]="Azure"}(m||(m={})),function(e){e[e.ServerAuthorization=1]="ServerAuthorization",e[e.LocalAuthorization=2]="LocalAuthorization"}(w||(w={})),function(e){e.Local="local",e.Memory="memory",e.Session="session"}(S||(S={}));class P{constructor(e,t,i){this.iterations=e,this.memory=t,this.parallelism=i}}class k{constructor(e,t,i){if(this.min=e,this.max=t,this.defaultValue=i,e>t)throw new Error(`${e} is greater than ${t}.`);if(!1===this.inRange(i))throw new Error("Default value is not in range.")}inRange(e){return e>=this.min&&e<=this.max}}!function(e){e[e.PBKDF2_SHA256=0]="PBKDF2_SHA256",e[e.Argon2id=1]="Argon2id"}(b||(b={}));const O=new k(16,1024,64),C=new k(1,16,4),A=new k(2,10,3),D=(b.PBKDF2_SHA256,new k(6e5,2e6,6e5));new P(D.defaultValue);var x,I,U,T;!function(e){e.Auto="auto",e.Biometric="biometric",e.Pin="pin"}(x||(x={})),function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warning=2]="Warning",e[e.Error=3]="Error"}(I||(I={})),function(e){e.Both="both",e.Disk="disk",e.Memory="memory"}(U||(U={})),function(e){e.System="system",e.Light="light",e.Dark="dark",e.Nord="nord",e.SolarizedDark="solarizedDark"}(T||(T={}));class N{constructor(e,t){if(null==e)throw new Error("Must provide key");if(null==t)if(32===e.byteLength)t=f.AesCbc256_B64;else{if(64!==e.byteLength)throw new Error("Unable to determine encType.");t=f.AesCbc256_HmacSha256_B64}if(this.key=e,this.encType=t,t===f.AesCbc256_B64&&32===e.byteLength)this.encKey=e,this.macKey=null;else if(t===f.AesCbc128_HmacSha256_B64&&32===e.byteLength)this.encKey=e.slice(0,16),this.macKey=e.slice(16,32);else{if(t!==f.AesCbc256_HmacSha256_B64||64!==e.byteLength)throw new Error("Unsupported encType/key length.");this.encKey=e.slice(0,32),this.macKey=e.slice(32,64)}null!=this.key&&(this.keyB64=p.fromBufferToB64(this.key)),null!=this.encKey&&(this.encKeyB64=p.fromBufferToB64(this.encKey)),null!=this.macKey&&(this.macKeyB64=p.fromBufferToB64(this.macKey))}toJSON(){return{keyB64:this.keyB64}}static fromString(e){if(null==e)return null;const t=p.fromB64ToArray(e);return new N(t)}static fromJSON(e){return N.fromString(null==e?void 0:e.keyB64)}}class R{constructor(e,t,i,r,s,o,a){this.email=e,this.accessCode=t,this.authRequestId=i,this.decryptedUserKey=r,this.decryptedMasterKey=s,this.decryptedMasterKeyHash=o,this.twoFactor=a,this.type=n.AuthRequest}static fromJSON(e){return Object.assign(new R(e.email,e.accessCode,e.authRequestId,null,null,e.decryptedMasterKeyHash,e.twoFactor?new s(e.twoFactor.provider,e.twoFactor.token,e.twoFactor.remember):e.twoFactor),{decryptedUserKey:N.fromJSON(e.decryptedUserKey),decryptedMasterKey:N.fromJSON(e.decryptedMasterKey)})}}class E{constructor(e,t,i){this.token=e,this.deviceResponse=t,this.prfKey=i,this.type=n.WebAuthn}static fromJSON(e){return new E(e.token,Object.assign(Object.create(v.prototype),e.deviceResponse),N.fromJSON(e.prfKey))}}class F{static fromResponse(e){var t;if(null==e)return;const i=new F;return i.keyConnectorUrl=null!==(t=null==e?void 0:e.keyConnectorUrl)&&void 0!==t?t:null,i}static fromJSON(e){if(null!=e)return Object.assign(new F,e)}}class M{static fromResponse(e){var t,i,n;if(null==e)return;const r=new M;return r.hasAdminApproval=null!==(t=null==e?void 0:e.hasAdminApproval)&&void 0!==t&&t,r.hasLoginApprovingDevice=null!==(i=null==e?void 0:e.hasLoginApprovingDevice)&&void 0!==i&&i,r.hasManageResetPasswordPermission=null!==(n=null==e?void 0:e.hasManageResetPasswordPermission)&&void 0!==n&&n,r}static fromJSON(e){if(null!=e)return Object.assign(new M,e)}}class K{static fromResponse(e){if(null==e)throw new Error("User Decryption Options are required for client initialization.");const t=new K;if(e.userDecryptionOptions){const i=e.userDecryptionOptions;t.hasMasterPassword=i.hasMasterPassword,t.trustedDeviceOption=M.fromResponse(i.trustedDeviceOption),t.keyConnectorOption=F.fromResponse(i.keyConnectorOption)}else{const i=null!=e.keyConnectorUrl;t.hasMasterPassword=!i,i&&(t.keyConnectorOption=new F,t.keyConnectorOption.keyConnectorUrl=e.keyConnectorUrl)}return t}static fromJSON(e){const t=Object.assign(new K,e);return t.trustedDeviceOption=M.fromJSON(null==e?void 0:e.trustedDeviceOption),t.keyConnectorOption=F.fromJSON(null==e?void 0:e.keyConnectorOption),t}}var L=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class z{constructor(e,t,i,n){null!=t?this.initFromData(e,t,i,n):this.initFromEncryptedString(e)}get ivBytes(){return null==this.iv?null:p.fromB64ToArray(this.iv)}get macBytes(){return null==this.mac?null:p.fromB64ToArray(this.mac)}get dataBytes(){return null==this.data?null:p.fromB64ToArray(this.data)}toJSON(){return this.encryptedString}static fromJSON(e){return null==e?null:new z(e)}initFromData(e,t,i,n){this.encryptedString=null!=i?e+"."+i+"|"+t:e+"."+t,null!=n&&(this.encryptedString=this.encryptedString+"|"+n),this.encryptionType=e,this.data=t,this.iv=i,this.mac=n}initFromEncryptedString(e){if(this.encryptedString=e,!this.encryptedString)return;const{encType:t,encPieces:i}=z.parseEncryptedString(this.encryptedString);if(this.encryptionType=t,i.length===g[t])switch(t){case f.AesCbc128_HmacSha256_B64:case f.AesCbc256_HmacSha256_B64:this.iv=i[0],this.data=i[1],this.mac=i[2];break;case f.AesCbc256_B64:this.iv=i[0],this.data=i[1];break;case f.Rsa2048_OaepSha256_B64:case f.Rsa2048_OaepSha1_B64:this.data=i[0];break;default:return}}static parseEncryptedString(e){const t=e.split(".");let i,n=null;if(2===t.length)try{i=parseInt(t[0],null),n=t[1].split("|")}catch(e){return}else n=e.split("|"),i=3===n.length?f.AesCbc128_HmacSha256_B64:f.AesCbc256_B64;return{encType:i,encPieces:n}}static isSerializedEncString(e){const{encType:t,encPieces:i}=this.parseEncryptedString(e);return g[t]===i.length}decrypt(e,t=null){return L(this,void 0,void 0,(function*(){if(null!=this.decryptedValue)return this.decryptedValue;try{if(null==t&&(t=yield this.getKeyForDecryption(e)),null==t)throw new Error("No key to decrypt EncString with orgId "+e);const i=p.getContainerService().getEncryptService();this.decryptedValue=yield i.decryptToUtf8(this,t)}catch(e){this.decryptedValue="[error: cannot decrypt]"}return this.decryptedValue}))}getKeyForDecryption(e){return L(this,void 0,void 0,(function*(){const t=p.getContainerService().getCryptoService();return null!=e?yield t.getOrgKey(e):yield t.getUserKeyWithLegacySupport()}))}}var V=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class B{constructor(e,t,i,n){this.stateService=e,this.cryptoService=t,this.vaultTimeoutSettingsService=i,this.logService=n}decryptUserKeyWithPin(e){return V(this,void 0,void 0,(function*(){try{const t=yield this.vaultTimeoutSettingsService.isPinLockSet(),{pinKeyEncryptedUserKey:i,oldPinKeyEncryptedMasterKey:n}=yield this.getPinKeyEncryptedKeys(t),r=yield this.stateService.getKdfType(),s=yield this.stateService.getKdfConfig();let o;const a=yield this.stateService.getEmail();return o=n?yield this.cryptoService.decryptAndMigrateOldPinKey("TRANSIENT"===t,e,a,r,s,n):yield this.cryptoService.decryptUserKeyWithPin(e,a,r,s,i),o?(yield this.validatePin(o,e))?o:(this.logService.warning("Pin key decryption successful but pin validation failed."),null):(this.logService.warning("User key null after pin key decryption."),null)}catch(e){return this.logService.error(`Error decrypting user key with pin: ${e}`),null}}))}getPinKeyEncryptedKeys(e){return V(this,void 0,void 0,(function*(){switch(e){case"PERSISTANT":{const e=yield this.stateService.getPinKeyEncryptedUserKey(),t=yield this.stateService.getEncryptedPinProtected();return{pinKeyEncryptedUserKey:e,oldPinKeyEncryptedMasterKey:t?new z(t):void 0}}case"TRANSIENT":return{pinKeyEncryptedUserKey:yield this.stateService.getPinKeyEncryptedUserKeyEphemeral(),oldPinKeyEncryptedMasterKey:yield this.stateService.getDecryptedPinProtected()};case"DISABLED":throw new Error("Pin is disabled");default:return e}}))}validatePin(e,t){return V(this,void 0,void 0,(function*(){const i=yield this.stateService.getProtectedPin();return(yield this.cryptoService.decryptToUtf8(new z(i),e))===t}))}}var _=i(67775),j=i(72591),$=i(37260),W=i(84598),q=i(92786);class H{constructor(e,t,i,n){this.key=e,this.masterPasswordHash=t,this.deviceIdentifier=i,this.requestApproved=n}}class G{constructor(e){this.email=e}}class J{constructor(e){this.response=e}getResponseProperty(e,t=null,i=!1){if(null==e||""===e)throw new Error("propertyName must not be null/empty.");if(null==t&&null!=this.response&&(t=this.response),null==t)return null;if(!i&&void 0===t[e]){let i=null;i=e.charAt(0)===e.charAt(0).toUpperCase()?e.charAt(0).toLowerCase():e.charAt(0).toUpperCase(),e.length>1&&(i+=e.slice(1)),void 0===t[e=i]&&(e=e.toLowerCase()),void 0===t[e]&&(e=e.toUpperCase())}return t[e]}}class Y extends J{constructor(e,t,i){var n,r;super(e);let s=null;if(null!=e){const t=this.getResponseProperty("ErrorModel");s=t&&i?t:e}429===t?this.message="Rate limit exceeded. Try again later.":s&&(this.message=this.getResponseProperty("Message",s),this.validationErrors=this.getResponseProperty("ValidationErrors",s),this.captchaSiteKey=null===(r=null===(n=this.validationErrors)||void 0===n?void 0:n.HCaptcha_SiteKey)||void 0===r?void 0:r[0],this.captchaRequired=!p.isNullOrWhitespace(this.captchaSiteKey)),this.statusCode=t}getSingleMessage(){if(null==this.validationErrors)return this.message;for(const e in this.validationErrors)if(this.validationErrors.hasOwnProperty(e)&&this.validationErrors[e].length)return this.validationErrors[e][0];return this.message}getAllMessages(){const e=[];if(null==this.validationErrors)return e;for(const t in this.validationErrors)this.validationErrors.hasOwnProperty(t)&&this.validationErrors[t].forEach((i=>{let n="";if(t.indexOf("[")>-1&&t.indexOf("]")>-1){const e=t.lastIndexOf(".");n=t.substr(0,e>-1?e:t.length)+": "}e.push(n+i)}));return e}}var Q,X,Z,ee,te=i(59554);class ie{constructor(e,t){this.type=t.getDevice(),this.name=t.getDeviceString(),this.identifier=e,this.pushToken=null}static fromJSON(e){return Object.assign(Object.create(ie.prototype),e)}}class ne{constructor(e,t){this.twoFactor=e,this.device=null!=t?t:null}alterIdentityTokenHeaders(e){}setTwoFactor(e){this.twoFactor=e}setAuthRequestAccessCode(e){this.authRequest=e}toIdentityToken(e){const t={scope:"api offline_access",client_id:e};return this.device&&(t.deviceType=this.device.type,t.deviceIdentifier=this.device.identifier,t.deviceName=this.device.name),this.authRequest&&(t.authRequest=this.authRequest),this.twoFactor&&this.twoFactor.token&&null!=this.twoFactor.provider&&(t.twoFactorToken=this.twoFactor.token,t.twoFactorProvider=this.twoFactor.provider,t.twoFactorRemember=this.twoFactor.remember?"1":"0"),t}}class re extends ne{constructor(e,t,i,n,r){super(n,r),this.email=e,this.masterPasswordHash=t,this.captchaResponse=i,this.twoFactor=n}toIdentityToken(e){const t=super.toIdentityToken(e);return t.grant_type="password",t.username=this.email,t.password=this.masterPasswordHash,null!=this.captchaResponse&&(t.captchaResponse=this.captchaResponse),t}alterIdentityTokenHeaders(e){e.set("Auth-Email",p.fromUtf8ToUrlB64(this.email))}static fromJSON(e){return Object.assign(Object.create(re.prototype),e,{device:e.device?ie.fromJSON(e.device):void 0,twoFactor:e.twoFactor?Object.assign(new s,e.twoFactor):void 0})}}!function(e){e[e.Authenticator=0]="Authenticator",e[e.Email=1]="Email",e[e.Duo=2]="Duo",e[e.Yubikey=3]="Yubikey",e[e.U2f=4]="U2f",e[e.Remember=5]="Remember",e[e.OrganizationDuo=6]="OrganizationDuo",e[e.WebAuthn=7]="WebAuthn"}(Q||(Q={})),function(e){e[e.None=0]="None",e[e.AdminForcePasswordReset=1]="AdminForcePasswordReset",e[e.WeakMasterPassword=2]="WeakMasterPassword",e[e.TdeUserWithoutPasswordHasPasswordResetPermission=3]="TdeUserWithoutPasswordHasPasswordResetPermission"}(X||(X={}));class se{constructor(){this.captchaSiteKey="",this.resetMasterPassword=!1,this.forcePasswordReset=X.None,this.twoFactorProviders=null}get requiresCaptcha(){return!p.isNullOrWhitespace(this.captchaSiteKey)}get requiresTwoFactor(){return null!=this.twoFactorProviders}}class oe extends J{constructor(e){super(e),this.siteKey=this.getResponseProperty("HCaptcha_SiteKey")}}class ae extends J{constructor(e){super(e),this.minComplexity=this.getResponseProperty("MinComplexity"),this.minLength=this.getResponseProperty("MinLength"),this.requireUpper=this.getResponseProperty("RequireUpper"),this.requireLower=this.getResponseProperty("RequireLower"),this.requireNumbers=this.getResponseProperty("RequireNumbers"),this.requireSpecial=this.getResponseProperty("RequireSpecial"),this.enforceOnLogin=this.getResponseProperty("EnforceOnLogin")}}class le extends J{constructor(e){super(e),this.keyConnectorUrl=this.getResponseProperty("KeyConnectorUrl")}}class ce extends J{constructor(e){super(e),this.hasAdminApproval=this.getResponseProperty("HasAdminApproval"),this.hasLoginApprovingDevice=this.getResponseProperty("HasLoginApprovingDevice"),this.hasManageResetPasswordPermission=this.getResponseProperty("HasManageResetPasswordPermission"),e.EncryptedPrivateKey&&(this.encryptedPrivateKey=new z(this.getResponseProperty("EncryptedPrivateKey"))),e.EncryptedUserKey&&(this.encryptedUserKey=new z(this.getResponseProperty("EncryptedUserKey")))}}class de extends J{constructor(e){super(e),e.EncryptedPrivateKey&&(this.encryptedPrivateKey=new z(this.getResponseProperty("EncryptedPrivateKey"))),e.EncryptedUserKey&&(this.encryptedUserKey=new z(this.getResponseProperty("EncryptedUserKey")))}}class ue extends J{constructor(e){super(e),this.hasMasterPassword=this.getResponseProperty("HasMasterPassword"),e.TrustedDeviceOption&&(this.trustedDeviceOption=new ce(this.getResponseProperty("TrustedDeviceOption"))),e.KeyConnectorOption&&(this.keyConnectorOption=new le(this.getResponseProperty("KeyConnectorOption"))),e.WebAuthnPrfOption&&(this.webAuthnPrfOption=new de(this.getResponseProperty("WebAuthnPrfOption")))}}class he extends J{constructor(e){super(e),this.accessToken=e.access_token,this.expiresIn=e.expires_in,this.refreshToken=e.refresh_token,this.tokenType=e.token_type,this.resetMasterPassword=this.getResponseProperty("ResetMasterPassword"),this.privateKey=this.getResponseProperty("PrivateKey"),this.key=this.getResponseProperty("Key"),this.twoFactorToken=this.getResponseProperty("TwoFactorToken"),this.kdf=this.getResponseProperty("Kdf"),this.kdfIterations=this.getResponseProperty("KdfIterations"),this.kdfMemory=this.getResponseProperty("KdfMemory"),this.kdfParallelism=this.getResponseProperty("KdfParallelism"),this.forcePasswordReset=this.getResponseProperty("ForcePasswordReset"),this.apiUseKeyConnector=this.getResponseProperty("ApiUseKeyConnector"),this.keyConnectorUrl=this.getResponseProperty("KeyConnectorUrl"),this.masterPasswordPolicy=new ae(this.getResponseProperty("MasterPasswordPolicy")),e.UserDecryptionOptions&&(this.userDecryptionOptions=new ue(this.getResponseProperty("UserDecryptionOptions")))}}class pe extends J{constructor(e){super(e),this.twoFactorProviders2=new Map,this.captchaToken=this.getResponseProperty("CaptchaBypassToken"),this.twoFactorProviders=this.getResponseProperty("TwoFactorProviders");const t=this.getResponseProperty("TwoFactorProviders2");if(null!=t)for(const e in t)t.hasOwnProperty(e)&&this.twoFactorProviders2.set(parseInt(e,null),t[e]);this.masterPasswordPolicy=new ae(this.getResponseProperty("MasterPasswordPolicy")),this.ssoEmail2faSessionToken=this.getResponseProperty("SsoEmail2faSessionToken"),this.email=this.getResponseProperty("Email")}}!function(e){e.Web="web",e.Browser="browser",e.Desktop="desktop",e.Cli="cli"}(Z||(Z={})),function(e){e[e.Android=0]="Android",e[e.iOS=1]="iOS",e[e.ChromeExtension=2]="ChromeExtension",e[e.FirefoxExtension=3]="FirefoxExtension",e[e.OperaExtension=4]="OperaExtension",e[e.EdgeExtension=5]="EdgeExtension",e[e.WindowsDesktop=6]="WindowsDesktop",e[e.MacOsDesktop=7]="MacOsDesktop",e[e.LinuxDesktop=8]="LinuxDesktop",e[e.ChromeBrowser=9]="ChromeBrowser",e[e.FirefoxBrowser=10]="FirefoxBrowser",e[e.OperaBrowser=11]="OperaBrowser",e[e.EdgeBrowser=12]="EdgeBrowser",e[e.IEBrowser=13]="IEBrowser",e[e.UnknownBrowser=14]="UnknownBrowser",e[e.AndroidAmazon=15]="AndroidAmazon",e[e.UWP=16]="UWP",e[e.SafariBrowser=17]="SafariBrowser",e[e.VivaldiBrowser=18]="VivaldiBrowser",e[e.VivaldiExtension=19]="VivaldiExtension",e[e.SafariExtension=20]="SafariExtension",e[e.SDK=21]="SDK",e[e.Server=22]="Server",e[e.WindowsCLI=23]="WindowsCLI",e[e.MacOsCLI=24]="MacOsCLI",e[e.LinuxCLI=25]="LinuxCLI"}(ee||(ee={}));new Set([ee.Android,ee.iOS,ee.AndroidAmazon]),new Set([ee.WindowsDesktop,ee.MacOsDesktop,ee.LinuxDesktop,ee.UWP,ee.WindowsCLI,ee.MacOsCLI,ee.LinuxCLI]);var ye,ve,fe,ge,me,we,Se,be,Pe,ke,Oe,Ce,Ae,De;!function(e){e[e.SCIM=1]="SCIM",e[e.DomainVerification=2]="DomainVerification"}(ye||(ye={})),function(e){e[e.User_LoggedIn=1e3]="User_LoggedIn",e[e.User_ChangedPassword=1001]="User_ChangedPassword",e[e.User_Updated2fa=1002]="User_Updated2fa",e[e.User_Disabled2fa=1003]="User_Disabled2fa",e[e.User_Recovered2fa=1004]="User_Recovered2fa",e[e.User_FailedLogIn=1005]="User_FailedLogIn",e[e.User_FailedLogIn2fa=1006]="User_FailedLogIn2fa",e[e.User_ClientExportedVault=1007]="User_ClientExportedVault",e[e.User_UpdatedTempPassword=1008]="User_UpdatedTempPassword",e[e.User_MigratedKeyToKeyConnector=1009]="User_MigratedKeyToKeyConnector",e[e.User_RequestedDeviceApproval=1010]="User_RequestedDeviceApproval",e[e.Cipher_Created=1100]="Cipher_Created",e[e.Cipher_Updated=1101]="Cipher_Updated",e[e.Cipher_Deleted=1102]="Cipher_Deleted",e[e.Cipher_AttachmentCreated=1103]="Cipher_AttachmentCreated",e[e.Cipher_AttachmentDeleted=1104]="Cipher_AttachmentDeleted",e[e.Cipher_Shared=1105]="Cipher_Shared",e[e.Cipher_UpdatedCollections=1106]="Cipher_UpdatedCollections",e[e.Cipher_ClientViewed=1107]="Cipher_ClientViewed",e[e.Cipher_ClientToggledPasswordVisible=1108]="Cipher_ClientToggledPasswordVisible",e[e.Cipher_ClientToggledHiddenFieldVisible=1109]="Cipher_ClientToggledHiddenFieldVisible",e[e.Cipher_ClientToggledCardCodeVisible=1110]="Cipher_ClientToggledCardCodeVisible",e[e.Cipher_ClientCopiedPassword=1111]="Cipher_ClientCopiedPassword",e[e.Cipher_ClientCopiedHiddenField=1112]="Cipher_ClientCopiedHiddenField",e[e.Cipher_ClientCopiedCardCode=1113]="Cipher_ClientCopiedCardCode",e[e.Cipher_ClientAutofilled=1114]="Cipher_ClientAutofilled",e[e.Cipher_SoftDeleted=1115]="Cipher_SoftDeleted",e[e.Cipher_Restored=1116]="Cipher_Restored",e[e.Cipher_ClientToggledCardNumberVisible=1117]="Cipher_ClientToggledCardNumberVisible",e[e.Cipher_ClientToggledTOTPSeedVisible=1118]="Cipher_ClientToggledTOTPSeedVisible",e[e.Collection_Created=1300]="Collection_Created",e[e.Collection_Updated=1301]="Collection_Updated",e[e.Collection_Deleted=1302]="Collection_Deleted",e[e.Group_Created=1400]="Group_Created",e[e.Group_Updated=1401]="Group_Updated",e[e.Group_Deleted=1402]="Group_Deleted",e[e.OrganizationUser_Invited=1500]="OrganizationUser_Invited",e[e.OrganizationUser_Confirmed=1501]="OrganizationUser_Confirmed",e[e.OrganizationUser_Updated=1502]="OrganizationUser_Updated",e[e.OrganizationUser_Removed=1503]="OrganizationUser_Removed",e[e.OrganizationUser_UpdatedGroups=1504]="OrganizationUser_UpdatedGroups",e[e.OrganizationUser_UnlinkedSso=1505]="OrganizationUser_UnlinkedSso",e[e.OrganizationUser_ResetPassword_Enroll=1506]="OrganizationUser_ResetPassword_Enroll",e[e.OrganizationUser_ResetPassword_Withdraw=1507]="OrganizationUser_ResetPassword_Withdraw",e[e.OrganizationUser_AdminResetPassword=1508]="OrganizationUser_AdminResetPassword",e[e.OrganizationUser_ResetSsoLink=1509]="OrganizationUser_ResetSsoLink",e[e.OrganizationUser_FirstSsoLogin=1510]="OrganizationUser_FirstSsoLogin",e[e.OrganizationUser_Revoked=1511]="OrganizationUser_Revoked",e[e.OrganizationUser_Restored=1512]="OrganizationUser_Restored",e[e.OrganizationUser_ApprovedAuthRequest=1513]="OrganizationUser_ApprovedAuthRequest",e[e.OrganizationUser_RejectedAuthRequest=1514]="OrganizationUser_RejectedAuthRequest",e[e.Organization_Updated=1600]="Organization_Updated",e[e.Organization_PurgedVault=1601]="Organization_PurgedVault",e[e.Organization_ClientExportedVault=1602]="Organization_ClientExportedVault",e[e.Organization_VaultAccessed=1603]="Organization_VaultAccessed",e[e.Organization_EnabledSso=1604]="Organization_EnabledSso",e[e.Organization_DisabledSso=1605]="Organization_DisabledSso",e[e.Organization_EnabledKeyConnector=1606]="Organization_EnabledKeyConnector",e[e.Organization_DisabledKeyConnector=1607]="Organization_DisabledKeyConnector",e[e.Organization_SponsorshipsSynced=1608]="Organization_SponsorshipsSynced",e[e.Organization_CollectionManagementUpdated=1609]="Organization_CollectionManagementUpdated",e[e.Policy_Updated=1700]="Policy_Updated",e[e.ProviderUser_Invited=1800]="ProviderUser_Invited",e[e.ProviderUser_Confirmed=1801]="ProviderUser_Confirmed",e[e.ProviderUser_Updated=1802]="ProviderUser_Updated",e[e.ProviderUser_Removed=1803]="ProviderUser_Removed",e[e.ProviderOrganization_Created=1900]="ProviderOrganization_Created",e[e.ProviderOrganization_Added=1901]="ProviderOrganization_Added",e[e.ProviderOrganization_Removed=1902]="ProviderOrganization_Removed",e[e.ProviderOrganization_VaultAccessed=1903]="ProviderOrganization_VaultAccessed",e[e.OrganizationDomain_Added=2e3]="OrganizationDomain_Added",e[e.OrganizationDomain_Removed=2001]="OrganizationDomain_Removed",e[e.OrganizationDomain_Verified=2002]="OrganizationDomain_Verified",e[e.OrganizationDomain_NotVerified=2003]="OrganizationDomain_NotVerified",e[e.Secret_Retrieved=2100]="Secret_Retrieved"}(ve||(ve={})),function(e){e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.Ok=200]="Ok",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultiStatus=207]="MultiStatus",e[e.AlreadyReported=208]="AlreadyReported",e[e.ImUsed=226]="ImUsed",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.UseProxy=305]="UseProxy",e[e.SwitchProxy=306]="SwitchProxy",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.LengthRequired=411]="LengthRequired",e[e.PreconditionFailed=412]="PreconditionFailed",e[e.PayloadTooLarge=413]="PayloadTooLarge",e[e.UriTooLong=414]="UriTooLong",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.RangeNotSatisfiable=416]="RangeNotSatisfiable",e[e.ExpectationFailed=417]="ExpectationFailed",e[e.IAmATeapot=418]="IAmATeapot",e[e.MisdirectedRequest=421]="MisdirectedRequest",e[e.UnprocessableEntity=422]="UnprocessableEntity",e[e.Locked=423]="Locked",e[e.FailedDependency=424]="FailedDependency",e[e.UpgradeRequired=426]="UpgradeRequired",e[e.PreconditionRequired=428]="PreconditionRequired",e[e.TooManyRequests=429]="TooManyRequests",e[e.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",e[e.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout",e[e.HttpVersionNotSupported=505]="HttpVersionNotSupported",e[e.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",e[e.InsufficientStorage=507]="InsufficientStorage",e[e.LoopDetected=508]="LoopDetected",e[e.NotExtended=510]="NotExtended",e[e.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired"}(fe||(fe={})),function(e){e[e.One=1]="One",e[e.Latest=1]="Latest"}(ge||(ge={})),function(e){e[e.SyncCipherUpdate=0]="SyncCipherUpdate",e[e.SyncCipherCreate=1]="SyncCipherCreate",e[e.SyncLoginDelete=2]="SyncLoginDelete",e[e.SyncFolderDelete=3]="SyncFolderDelete",e[e.SyncCiphers=4]="SyncCiphers",e[e.SyncVault=5]="SyncVault",e[e.SyncOrgKeys=6]="SyncOrgKeys",e[e.SyncFolderCreate=7]="SyncFolderCreate",e[e.SyncFolderUpdate=8]="SyncFolderUpdate",e[e.SyncCipherDelete=9]="SyncCipherDelete",e[e.SyncSettings=10]="SyncSettings",e[e.LogOut=11]="LogOut",e[e.SyncSendCreate=12]="SyncSendCreate",e[e.SyncSendUpdate=13]="SyncSendUpdate",e[e.SyncSendDelete=14]="SyncSendDelete",e[e.AuthRequest=15]="AuthRequest",e[e.AuthRequestResponse=16]="AuthRequestResponse",e[e.SyncOrganizations=17]="SyncOrganizations"}(me||(me={})),function(e){e[e.Free=0]="Free",e[e.Families=1]="Families",e[e.Teams=2]="Teams",e[e.Enterprise=3]="Enterprise",e[e.TeamsStarter=4]="TeamsStarter"}(we||(we={}));class xe{constructor(e,t){this.publicKey=e,this.encryptedPrivateKey=t}}class Ie{constructor(e){e&&Object.assign(this,e)}toJSON(){return{id:this.id,privateKey:p.fromBufferToByteString(this.privateKey)}}static fromJSON(e){if(null==e)return null;let t=null;return e.privateKey&&(t=p.fromByteStringToArray(e.privateKey)),new Ie({id:e.id,privateKey:t})}}!function(e){e[e.Cipher=0]="Cipher",e[e.CipherView=1]="CipherView"}(Se||(Se={})),function(e){e[e.None=0]="None",e[e.Password=1]="Password"}(be||(be={})),function(e){e[e.Login=1]="Login",e[e.SecureNote=2]="SecureNote",e[e.Card=3]="Card",e[e.Identity=4]="Identity"}(Pe||(Pe={}));class Ue{constructor(e){this.id=null,this.url=null,this.size=null,this.sizeName=null,this.fileName=null,this.key=null,e&&(this.id=e.id,this.url=e.url,this.size=e.size,this.sizeName=e.sizeName)}get fileSize(){try{if(null!=this.size)return parseInt(this.size,null)}catch(e){}return 0}static fromJSON(e){const t=null==e.key?null:N.fromJSON(e.key);return Object.assign(new Ue,e,{key:t})}}!function(e){e[e.Text=0]="Text",e[e.Hidden=1]="Hidden",e[e.Boolean=2]="Boolean",e[e.Linked=3]="Linked"}(ke||(ke={})),function(e){e[e.Username=100]="Username",e[e.Password=101]="Password"}(Oe||(Oe={})),function(e){e[e.CardholderName=300]="CardholderName",e[e.ExpMonth=301]="ExpMonth",e[e.ExpYear=302]="ExpYear",e[e.Code=303]="Code",e[e.Brand=304]="Brand",e[e.Number=305]="Number"}(Ce||(Ce={})),function(e){e[e.Title=400]="Title",e[e.MiddleName=401]="MiddleName",e[e.Address1=402]="Address1",e[e.Address2=403]="Address2",e[e.Address3=404]="Address3",e[e.City=405]="City",e[e.State=406]="State",e[e.PostalCode=407]="PostalCode",e[e.Country=408]="Country",e[e.Company=409]="Company",e[e.Email=410]="Email",e[e.Phone=411]="Phone",e[e.Ssn=412]="Ssn",e[e.Username=413]="Username",e[e.PassportNumber=414]="PassportNumber",e[e.LicenseNumber=415]="LicenseNumber",e[e.FirstName=416]="FirstName",e[e.LastName=417]="LastName",e[e.FullName=418]="FullName"}(Ae||(Ae={})),function(e){e[e.Generic=0]="Generic"}(De||(De={}));class Te{constructor(e,t){this.propertyKey=e,this._i18nKey=t}get i18nKey(){var e;return null!==(e=this._i18nKey)&&void 0!==e?e:this.propertyKey}}function Ne(e,t){return(i,n)=>{null==i.linkedFieldOptions&&(i.linkedFieldOptions=new Map),i.linkedFieldOptions.set(e,new Te(n,t))}}class Re{}var Ee=function(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},Fe=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class Me extends Re{constructor(){super(...arguments),this.cardholderName=null,this.expMonth=null,this.expYear=null,this.code=null,this._brand=null,this._number=null,this._subTitle=null}get maskedCode(){return null!=this.code?"•".repeat(this.code.length):null}get maskedNumber(){return null!=this.number?"•".repeat(this.number.length):null}get brand(){return this._brand}set brand(e){this._brand=e,this._subTitle=null}get number(){return this._number}set number(e){this._number=e,this._subTitle=null}get subTitle(){if(null==this._subTitle&&(this._subTitle=this.brand,null!=this.number&&this.number.length>=4)){null!=this._subTitle&&""!==this._subTitle?this._subTitle+=", ":this._subTitle="";const e=this.number.length>=5&&null!=this.number.match(new RegExp("^3[47]"))?5:4;this._subTitle+="*"+this.number.substr(this.number.length-e)}return this._subTitle}get expiration(){if(!this.expMonth&&!this.expYear)return null;let e=null!=this.expMonth?("0"+this.expMonth).slice(-2):"__";return e+=" / "+(null!=this.expYear?this.formatYear(this.expYear):"____"),e}formatYear(e){return 2===e.length?"20"+e:e}static fromJSON(e){return Object.assign(new Me,e)}static getCardBrandByPatterns(e){if(null==e||"string"!=typeof e||""===e.trim())return null;let 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))))))}}Ee([Ne(Ce.CardholderName),Fe("design:type",String)],Me.prototype,"cardholderName",void 0),Ee([Ne(Ce.ExpMonth,"expirationMonth"),Fe("design:type",String)],Me.prototype,"expMonth",void 0),Ee([Ne(Ce.ExpYear,"expirationYear"),Fe("design:type",String)],Me.prototype,"expYear",void 0),Ee([Ne(Ce.Code,"securityCode"),Fe("design:type",String)],Me.prototype,"code",void 0),Ee([Ne(Ce.Brand),Fe("design:type",String),Fe("design:paramtypes",[String])],Me.prototype,"brand",null),Ee([Ne(Ce.Number),Fe("design:type",String),Fe("design:paramtypes",[String])],Me.prototype,"number",null);class Ke{constructor(e){this.name=null,this.value=null,this.type=null,this.newField=!1,this.showValue=!1,this.showCount=!1,this.linkedId=null,e&&(this.type=e.type,this.linkedId=e.linkedId)}get maskedValue(){return null!=this.value?"••••••••":null}static fromJSON(e){return Object.assign(new Ke,e)}}var Le=function(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},ze=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class Ve extends Re{constructor(){super(),this.title=null,this.middleName=null,this.address1=null,this.address2=null,this.address3=null,this.city=null,this.state=null,this.postalCode=null,this.country=null,this.company=null,this.email=null,this.phone=null,this.ssn=null,this.username=null,this.passportNumber=null,this.licenseNumber=null,this._firstName=null,this._lastName=null,this._subTitle=null}get firstName(){return this._firstName}set firstName(e){this._firstName=e,this._subTitle=null}get lastName(){return this._lastName}set lastName(e){this._lastName=e,this._subTitle=null}get subTitle(){return null!=this._subTitle||null==this.firstName&&null==this.lastName||(this._subTitle="",null!=this.firstName&&(this._subTitle=this.firstName),null!=this.lastName&&(""!==this._subTitle&&(this._subTitle+=" "),this._subTitle+=this.lastName)),this._subTitle}get fullName(){if(null!=this.title||null!=this.firstName||null!=this.middleName||null!=this.lastName){let e="";return null!=this.title&&(e+=this.title+" "),null!=this.firstName&&(e+=this.firstName+" "),null!=this.middleName&&(e+=this.middleName+" "),null!=this.lastName&&(e+=this.lastName),e.trim()}return null}get fullAddress(){let e=this.address1;return p.isNullOrWhitespace(this.address2)||(p.isNullOrWhitespace(e)||(e+=", "),e+=this.address2),p.isNullOrWhitespace(this.address3)||(p.isNullOrWhitespace(e)||(e+=", "),e+=this.address3),e}get fullAddressPart2(){if(null==this.city&&null==this.state&&null==this.postalCode)return null;const e=this.city||"-",t=this.state,i=this.postalCode||"-";let n=e;return p.isNullOrWhitespace(t)||(n+=", "+t),n+=", "+i,n}static fromJSON(e){return Object.assign(new Ve,e)}}Le([Ne(Ae.Title),ze("design:type",String)],Ve.prototype,"title",void 0),Le([Ne(Ae.MiddleName),ze("design:type",String)],Ve.prototype,"middleName",void 0),Le([Ne(Ae.Address1),ze("design:type",String)],Ve.prototype,"address1",void 0),Le([Ne(Ae.Address2),ze("design:type",String)],Ve.prototype,"address2",void 0),Le([Ne(Ae.Address3),ze("design:type",String)],Ve.prototype,"address3",void 0),Le([Ne(Ae.City,"cityTown"),ze("design:type",String)],Ve.prototype,"city",void 0),Le([Ne(Ae.State,"stateProvince"),ze("design:type",String)],Ve.prototype,"state",void 0),Le([Ne(Ae.PostalCode,"zipPostalCode"),ze("design:type",String)],Ve.prototype,"postalCode",void 0),Le([Ne(Ae.Country),ze("design:type",String)],Ve.prototype,"country",void 0),Le([Ne(Ae.Company),ze("design:type",String)],Ve.prototype,"company",void 0),Le([Ne(Ae.Email),ze("design:type",String)],Ve.prototype,"email",void 0),Le([Ne(Ae.Phone),ze("design:type",String)],Ve.prototype,"phone",void 0),Le([Ne(Ae.Ssn),ze("design:type",String)],Ve.prototype,"ssn",void 0),Le([Ne(Ae.Username),ze("design:type",String)],Ve.prototype,"username",void 0),Le([Ne(Ae.PassportNumber),ze("design:type",String)],Ve.prototype,"passportNumber",void 0),Le([Ne(Ae.LicenseNumber),ze("design:type",String)],Ve.prototype,"licenseNumber",void 0),Le([Ne(Ae.FirstName),ze("design:type",String),ze("design:paramtypes",[String])],Ve.prototype,"firstName",null),Le([Ne(Ae.LastName),ze("design:type",String),ze("design:paramtypes",[String])],Ve.prototype,"lastName",null),Le([Ne(Ae.FullName),ze("design:type",String),ze("design:paramtypes",[])],Ve.prototype,"fullName",null);class Be extends Re{constructor(){super(...arguments),this.creationDate=null}get subTitle(){return this.userDisplayName}static fromJSON(e){const t=null!=e.creationDate?new Date(e.creationDate):null;return Object.assign(new Be,e,{creationDate:t})}}const _e=0,je=1,$e=2,We=3,qe=4,He=5,Ge=["https://","http://","ssh://","ftp://","sftp://","irc://","vnc://","rdp://","ms-rd:","chrome://","iosapp://","androidapp://"];class Je{static canLaunch(e){if(p.isNullOrWhitespace(e))return!1;for(let t=0;t=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},Xe=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class Ze extends Re{constructor(e){super(),this.username=null,this.password=null,this.passwordRevisionDate=null,this.totp=null,this.uris=[],this.autofillOnPageLoad=null,this.fido2Credentials=null,e&&(this.passwordRevisionDate=e.passwordRevisionDate,this.autofillOnPageLoad=e.autofillOnPageLoad)}get uri(){return this.hasUris?this.uris[0].uri:null}get maskedPassword(){return null!=this.password?"••••••••":null}get subTitle(){return this.username}get canLaunch(){return this.hasUris&&this.uris.some((e=>e.canLaunch))}get hasTotp(){return!p.isNullOrWhitespace(this.totp)}get launchUri(){if(this.hasUris){const e=this.uris.find((e=>e.canLaunch));if(null!=e)return e.launchUri}return null}get hasUris(){return null!=this.uris&&this.uris.length>0}get hasFido2Credentials(){return null!=this.fido2Credentials&&this.fido2Credentials.length>0}matchesUri(e,t,i=null){return null!=this.uris&&this.uris.some((n=>n.matchesUri(e,t,i)))}static fromJSON(e){var t;const i=null==e.passwordRevisionDate?null:new Date(e.passwordRevisionDate),n=e.uris.map((e=>Ye.fromJSON(e))),r=null===(t=e.fido2Credentials)||void 0===t?void 0:t.map((e=>Be.fromJSON(e)));return Object.assign(new Ze,e,{passwordRevisionDate:i,uris:n,fido2Credentials:r})}}Qe([Ne(Oe.Username),Xe("design:type",String)],Ze.prototype,"username",void 0),Qe([Ne(Oe.Password),Xe("design:type",String)],Ze.prototype,"password",void 0);class et{constructor(e){this.password=null,this.lastUsedDate=null,e&&(this.lastUsedDate=e.lastUsedDate)}static fromJSON(e){const t=null==e.lastUsedDate?null:new Date(e.lastUsedDate);return Object.assign(new et,e,{lastUsedDate:t})}}class tt extends Re{constructor(e){super(),this.type=null,e&&(this.type=e.type)}get subTitle(){return null}static fromJSON(e){return Object.assign(new tt,e)}}class it{constructor(e){var t;this.initializerKey=Se.CipherView,this.id=null,this.organizationId=null,this.folderId=null,this.name=null,this.notes=null,this.type=null,this.favorite=!1,this.organizationUseTotp=!1,this.edit=!1,this.viewPassword=!0,this.login=new Ze,this.identity=new Ve,this.card=new Me,this.secureNote=new tt,this.attachments=null,this.fields=null,this.passwordHistory=null,this.collectionIds=null,this.revisionDate=null,this.creationDate=null,this.deletedDate=null,this.reprompt=be.None,e&&(this.id=e.id,this.organizationId=e.organizationId,this.folderId=e.folderId,this.favorite=e.favorite,this.organizationUseTotp=e.organizationUseTotp,this.edit=e.edit,this.viewPassword=e.viewPassword,this.type=e.type,this.localData=e.localData,this.collectionIds=e.collectionIds,this.revisionDate=e.revisionDate,this.creationDate=e.creationDate,this.deletedDate=e.deletedDate,this.reprompt=null!==(t=e.reprompt)&&void 0!==t?t:be.None)}get item(){switch(this.type){case Pe.Login:return this.login;case Pe.SecureNote:return this.secureNote;case Pe.Card:return this.card;case Pe.Identity:return this.identity}return null}get subTitle(){var e;return null===(e=this.item)||void 0===e?void 0:e.subTitle}get hasPasswordHistory(){return this.passwordHistory&&this.passwordHistory.length>0}get hasAttachments(){return this.attachments&&this.attachments.length>0}get hasOldAttachments(){if(this.hasAttachments)for(let e=0;e0}get passwordRevisionDisplayDate(){return this.type!==Pe.Login||null==this.login||null==this.login.password||""===this.login.password?null:this.login.passwordRevisionDate}get isDeleted(){return null!=this.deletedDate}get linkedFieldOptions(){var e;return null===(e=this.item)||void 0===e?void 0:e.linkedFieldOptions}linkedFieldValue(e){var t;const i=null===(t=this.linkedFieldOptions)||void 0===t?void 0:t.get(e);if(null==i)return null;this.item;return this.item[i.propertyKey]}linkedFieldI18nKey(e){var t;return null===(t=this.linkedFieldOptions.get(e))||void 0===t?void 0:t.i18nKey}toJSON(){return this}static fromJSON(e){var t,i,n;if(null==e)return null;const r=new it,s=null==e.revisionDate?null:new Date(e.revisionDate),o=null==e.deletedDate?null:new Date(e.deletedDate),a=null===(t=e.attachments)||void 0===t?void 0:t.map((e=>Ue.fromJSON(e))),l=null===(i=e.fields)||void 0===i?void 0:i.map((e=>Ke.fromJSON(e))),c=null===(n=e.passwordHistory)||void 0===n?void 0:n.map((e=>et.fromJSON(e)));switch(Object.assign(r,e,{revisionDate:s,deletedDate:o,attachments:a,fields:l,passwordHistory:c}),e.type){case Pe.Card:r.card=Me.fromJSON(e.card);break;case Pe.Identity:r.identity=Ve.fromJSON(e.identity);break;case Pe.Login:r.login=Ze.fromJSON(e.login);break;case Pe.SecureNote:r.secureNote=tt.fromJSON(e.secureNote)}return r}}class nt{constructor(e){this.featureStates={},this.version=null==e?void 0:e.version,this.gitHash=null==e?void 0:e.gitHash,this.server=(null==e?void 0:e.server)?new rt(e.server):null,this.utcDate=(new Date).toISOString(),this.environment=(null==e?void 0:e.environment)?new st(e.environment):null,this.featureStates=null==e?void 0:e.featureStates}static fromJSON(e){return Object.assign(new nt({}),e,{server:(null==e?void 0:e.server)?rt.fromJSON(e.server):null,environment:(null==e?void 0:e.environment)?st.fromJSON(e.environment):null})}}class rt{constructor(e){this.name=e.name,this.url=e.url}static fromJSON(e){return Object.assign(new rt({}),e)}}class st{constructor(e){this.cloudRegion=e.cloudRegion,this.vault=e.vault,this.api=e.api,this.identity=e.identity,this.notifications=e.notifications,this.sso=e.sso}static fromJSON(e){return Object.assign(new st({}),e)}}class ot{toJSON(){return{encrypted:this.encrypted,decrypted:this.decrypted instanceof ArrayBuffer?p.fromBufferToByteString(this.decrypted):this.decrypted}}static fromJSON(e,t,i){if(null==e)return null;const n=new ot;return null!=(null==e?void 0:e.encrypted)&&(n.encrypted=i?i(e.encrypted):e.encrypted),null!=(null==e?void 0:e.decrypted)&&(n.decrypted=t?t(e.decrypted):e.decrypted),n}}class at{}class lt{constructor(){this.ciphers=new at,this.sends=new at,this.passwordGenerationHistory=new ot}static fromJSON(e){var t,i;return null==e?null:Object.assign(new lt,e,{addEditCipherInfo:{cipher:it.fromJSON(null===(t=null==e?void 0:e.addEditCipherInfo)||void 0===t?void 0:t.cipher),collectionIds:null===(i=null==e?void 0:e.addEditCipherInfo)||void 0===i?void 0:i.collectionIds}})}}class ct{constructor(){this.cryptoSymmetricKey=new ot}toJSON(){return p.merge(this,{publicKey:this.publicKey?p.fromBufferToByteString(this.publicKey):void 0})}static fromJSON(e){return null==e?null:Object.assign(new ct,e,{masterKey:N.fromJSON(null==e?void 0:e.masterKey),deviceKey:null==e?void 0:e.deviceKey,cryptoMasterKey:N.fromJSON(null==e?void 0:e.cryptoMasterKey),cryptoSymmetricKey:ot.fromJSON(null==e?void 0:e.cryptoSymmetricKey,N.fromJSON),publicKey:p.fromByteStringToArray(null==e?void 0:e.publicKey)})}static initRecordEncryptionPairsFromJSON(e){return ot.fromJSON(e,(t=>{if(null==e)return null;const i={};for(const e in t)i[e]=N.fromJSON(t[e]);return i}))}}class dt{static fromJSON(e){return null==e?null:Object.assign(new dt,e)}}class ut{constructor(){this.vaultTimeoutAction="lock",this.pinProtected=new ot}static fromJSON(e){return null==e?null:Object.assign(new ut,e,{pinProtected:ot.fromJSON(null==e?void 0:e.pinProtected,z.fromJSON),serverConfig:nt.fromJSON(null==e?void 0:e.serverConfig)})}}class ht{static fromJSON(e){return null==e?null:Object.assign(new ht,e)}}class pt{constructor(e){this.data=new lt,this.keys=new ct,this.profile=new dt,this.settings=new ut,this.tokens=new ht,this.adminAuthRequest=null,Object.assign(this,{data:Object.assign(Object.assign({},new lt),null==e?void 0:e.data),keys:Object.assign(Object.assign({},new ct),null==e?void 0:e.keys),profile:Object.assign(Object.assign({},new dt),null==e?void 0:e.profile),settings:Object.assign(Object.assign({},new ut),null==e?void 0:e.settings),tokens:Object.assign(Object.assign({},new ht),null==e?void 0:e.tokens),adminAuthRequest:null==e?void 0:e.adminAuthRequest})}static fromJSON(e){return null==e?null:Object.assign(new pt({}),e,{keys:ct.fromJSON(null==e?void 0:e.keys),data:lt.fromJSON(null==e?void 0:e.data),profile:dt.fromJSON(null==e?void 0:e.profile),settings:ut.fromJSON(null==e?void 0:e.settings),tokens:ht.fromJSON(null==e?void 0:e.tokens),adminAuthRequest:Ie.fromJSON(null==e?void 0:e.adminAuthRequest)})}}var yt=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class vt{constructor(e,t,i,n,r,s,o,a,l,c,d){this.cryptoService=e,this.apiService=t,this.tokenService=i,this.appIdService=n,this.platformUtilsService=r,this.messagingService=s,this.logService=o,this.stateService=a,this.twoFactorService=l,this.userDecryptionOptionsService=c,this.billingAccountProfileStateService=d}logInTwoFactor(e,t=null){return yt(this,void 0,void 0,(function*(){const t=this.cache.value;t.tokenRequest.setTwoFactor(e),this.cache.next(t);const[i]=yield this.startLogIn();return i}))}startLogIn(){return yt(this,void 0,void 0,(function*(){this.twoFactorService.clearSelectedProvider();const e=this.cache.value.tokenRequest,t=yield this.apiService.postIdentityToken(e);if(t instanceof pe)return[yield this.processTwoFactorResponse(t),t];if(t instanceof oe)return[yield this.processCaptchaResponse(t),t];if(t instanceof he)return[yield this.processTokenResponse(t),t];throw new Error("Invalid response object.")}))}buildDeviceRequest(){return yt(this,void 0,void 0,(function*(){const e=yield this.appIdService.getAppId();return new ie(e,this.platformUtilsService)}))}buildTwoFactor(e,t){return yt(this,void 0,void 0,(function*(){if(null!=e)return e;if(t){const e=yield this.tokenService.getTwoFactorToken(t);if(null!=e)return new s(Q.Remember,e,!1)}return new s}))}saveAccountInformation(e){return yt(this,void 0,void 0,(function*(){const t=yield this.tokenService.decodeAccessToken(e.accessToken),i=t.sub,n=yield this.stateService.getDeviceKey({userId:i}),r=new ct;n&&(r.deviceKey=n);const s=yield this.stateService.getAdminAuthRequest({userId:i}),o=yield this.stateService.getVaultTimeoutAction(),a=yield this.stateService.getVaultTimeout();yield this.tokenService.setTokens(e.accessToken,o,a,e.refreshToken),yield this.stateService.addAccount(new pt({profile:Object.assign(Object.assign({},new dt),{userId:i,name:t.name,email:t.email,kdfIterations:e.kdfIterations,kdfMemory:e.kdfMemory,kdfParallelism:e.kdfParallelism,kdfType:e.kdf}),tokens:Object.assign({},new ht),keys:r,adminAuthRequest:null==s?void 0:s.toJSON()})),yield this.userDecryptionOptionsService.setUserDecryptionOptions(K.fromResponse(e)),yield this.billingAccountProfileStateService.setHasPremium(t.premium,!1)}))}processTokenResponse(e){return yt(this,void 0,void 0,(function*(){const t=new se;if(this.encryptionKeyMigrationRequired(e)&&(t.requiresEncryptionKeyMigration=!0,this.platformUtilsService.getClientType()!==Z.Web))return t;if(t.resetMasterPassword=e.resetMasterPassword,e.forcePasswordReset&&(t.forcePasswordReset=X.AdminForcePasswordReset),yield this.saveAccountInformation(e),null!=e.twoFactorToken){const t=yield this.tokenService.getEmail();yield this.tokenService.setTwoFactorToken(t,e.twoFactorToken)}return yield this.setMasterKey(e),yield this.setUserKey(e),yield this.setPrivateKey(e),this.messagingService.send("loggedIn"),t}))}encryptionKeyMigrationRequired(e){return!1}createKeyPairForOldAccount(){return yt(this,void 0,void 0,(function*(){try{const[e,t]=yield this.cryptoService.makeKeyPair();return yield this.apiService.postAccountKeys(new xe(e,t.encryptedString)),t.encryptedString}catch(e){this.logService.error(e)}}))}processTwoFactorResponse(e){var t;return yt(this,void 0,void 0,(function*(){yield this.clearTwoFactorToken();const i=new se;return i.twoFactorProviders=e.twoFactorProviders2,this.twoFactorService.setProviders(e),this.cache.next(Object.assign(Object.assign({},this.cache.value),{captchaBypassToken:null!==(t=e.captchaToken)&&void 0!==t?t:null})),i.ssoEmail2FaSessionToken=e.ssoEmail2faSessionToken,i.email=e.email,i}))}clearTwoFactorToken(){return yt(this,void 0,void 0,(function*(){const e=this.cache.value.userEnteredEmail;e&&(yield this.tokenService.clearTwoFactorToken(e))}))}processCaptchaResponse(e){return yt(this,void 0,void 0,(function*(){const t=new se;return t.captchaSiteKey=e.siteKey,t}))}}var ft=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class gt{static fromJSON(e){return Object.assign(new gt,e,{tokenRequest:re.fromJSON(e.tokenRequest),authRequestCredentials:R.fromJSON(e.authRequestCredentials)})}}class mt extends vt{constructor(e,t,i,n,r,s,o,a,l,c,d,u,h){super(t,i,n,r,s,o,a,l,c,d,h),this.deviceTrustCryptoService=u,this.cache=new te.X(e),this.email$=this.cache.pipe((0,q.U)((e=>e.tokenRequest.email))),this.accessCode$=this.cache.pipe((0,q.U)((e=>e.authRequestCredentials.accessCode))),this.authRequestId$=this.cache.pipe((0,q.U)((e=>e.authRequestCredentials.authRequestId)))}logIn(e){return ft(this,void 0,void 0,(function*(){const t=new gt;t.tokenRequest=new re(e.email,e.accessCode,null,yield this.buildTwoFactor(e.twoFactor,e.email),yield this.buildDeviceRequest()),t.tokenRequest.setAuthRequestAccessCode(e.authRequestId),t.authRequestCredentials=e,this.cache.next(t);const[i]=yield this.startLogIn();return i}))}logInTwoFactor(e,t){const i=Object.create(null,{logInTwoFactor:{get:()=>super.logInTwoFactor}});return ft(this,void 0,void 0,(function*(){const n=this.cache.value;return n.tokenRequest.captchaResponse=null!=t?t:n.captchaBypassToken,this.cache.next(n),i.logInTwoFactor.call(this,e)}))}setMasterKey(e){return ft(this,void 0,void 0,(function*(){const e=this.cache.value.authRequestCredentials;e.decryptedMasterKey&&e.decryptedMasterKeyHash&&(yield this.cryptoService.setMasterKey(e.decryptedMasterKey),yield this.cryptoService.setMasterKeyHash(e.decryptedMasterKeyHash))}))}setUserKey(e){return ft(this,void 0,void 0,(function*(){const t=this.cache.value.authRequestCredentials;yield this.cryptoService.setMasterKeyEncryptedUserKey(e.key),t.decryptedUserKey?yield this.cryptoService.setUserKey(t.decryptedUserKey):(yield this.trySetUserKeyWithMasterKey(),yield this.deviceTrustCryptoService.trustDeviceIfRequired())}))}trySetUserKeyWithMasterKey(){return ft(this,void 0,void 0,(function*(){const e=yield this.cryptoService.getMasterKey();if(e){const t=yield this.cryptoService.decryptUserKeyWithMasterKey(e);yield this.cryptoService.setUserKey(t)}}))}setPrivateKey(e){var t;return ft(this,void 0,void 0,(function*(){yield this.cryptoService.setPrivateKey(null!==(t=e.privateKey)&&void 0!==t?t:yield this.createKeyPairForOldAccount())}))}exportCache(){return{authRequest:this.cache.value}}}var wt=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class St{buildDomainModel(e,t,i,n=[]){for(const r in i){if(!i.hasOwnProperty(r))continue;const s=t[i[r]||r];n.indexOf(r)>-1?e[r]=s||null:e[r]=s?new z(s):null}}buildDataModel(e,t,i,n=[]){for(const r in i){if(!i.hasOwnProperty(r))continue;const s=e[i[r]||r];n.indexOf(r)>-1?t[r]=null!=s?s:null:t[r]=null!=s?s.encryptedString:null}}decryptObj(e,t,i,n=null){return wt(this,void 0,void 0,(function*(){const r=[],s=this;for(const o in t)t.hasOwnProperty(o)&&function(o){const a=Promise.resolve().then((()=>{const e=t[o]||o;return s[e]?s[e].decrypt(i,n):null})).then((t=>{e[o]=t}));r.push(a)}(o);return yield Promise.all(r),e}))}}class bt extends St{constructor(){super(...arguments),this.minComplexity=0,this.minLength=0,this.requireUpper=!1,this.requireLower=!1,this.requireNumbers=!1,this.requireSpecial=!1,this.enforceOnLogin=!1}static fromResponse(e){if(null==e)return null;const t=new bt;return t.minComplexity=e.minComplexity,t.minLength=e.minLength,t.requireUpper=e.requireUpper,t.requireLower=e.requireLower,t.requireNumbers=e.requireNumbers,t.requireSpecial=e.requireSpecial,t.enforceOnLogin=e.enforceOnLogin,t}}var Pt=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class kt{constructor(){this.forcePasswordResetReason=X.None}static fromJSON(e){return Object.assign(new kt,e,{tokenRequest:re.fromJSON(e.tokenRequest),masterKey:N.fromJSON(e.masterKey)})}}class Ot extends vt{constructor(e,t,i,n,r,s,o,a,l,c,d,u,h,p,y){super(t,i,n,r,s,o,a,l,c,d,y),this.stateService=l,this.passwordStrengthService=u,this.policyService=h,this.loginStrategyService=p,this.cache=new te.X(e),this.email$=this.cache.pipe((0,q.U)((e=>e.tokenRequest.email))),this.serverMasterKeyHash$=this.cache.pipe((0,q.U)((e=>e.tokenRequest.masterPasswordHash))),this.localMasterKeyHash$=this.cache.pipe((0,q.U)((e=>e.localMasterKeyHash)))}logIn(e){return Pt(this,void 0,void 0,(function*(){const{email:t,masterPassword:i,captchaToken:n,twoFactor:r}=e,s=new kt;s.masterKey=yield this.loginStrategyService.makePreloginKey(i,t),s.userEnteredEmail=t,s.localMasterKeyHash=yield this.cryptoService.hashMasterKey(i,s.masterKey,w.LocalAuthorization);const o=yield this.cryptoService.hashMasterKey(i,s.masterKey);s.tokenRequest=new re(t,o,n,yield this.buildTwoFactor(r,t),yield this.buildDeviceRequest()),this.cache.next(s);const[a,l]=yield this.startLogIn(),c=this.getMasterPasswordPolicyOptionsFromResponse(l);if(null==c?void 0:c.enforceOnLogin){this.evaluateMasterPassword(e,c)||(a.requiresCaptcha||a.requiresTwoFactor?this.cache.next(Object.assign(Object.assign({},this.cache.value),{forcePasswordResetReason:X.WeakMasterPassword})):(yield this.stateService.setForceSetPasswordReason(X.WeakMasterPassword),a.forcePasswordReset=X.WeakMasterPassword))}return a}))}logInTwoFactor(e,t){const i=Object.create(null,{logInTwoFactor:{get:()=>super.logInTwoFactor}});return Pt(this,void 0,void 0,(function*(){const n=this.cache.value;n.tokenRequest.captchaResponse=null!=t?t:n.captchaBypassToken,this.cache.next(n);const r=yield i.logInTwoFactor.call(this,e),s=this.cache.value.forcePasswordResetReason;return r.requiresTwoFactor||r.requiresCaptcha||s==X.None||(yield this.stateService.setForceSetPasswordReason(s),r.forcePasswordReset=s),r}))}setMasterKey(e){return Pt(this,void 0,void 0,(function*(){const{masterKey:e,localMasterKeyHash:t}=this.cache.value;yield this.cryptoService.setMasterKey(e),yield this.cryptoService.setMasterKeyHash(t)}))}setUserKey(e){return Pt(this,void 0,void 0,(function*(){if(this.encryptionKeyMigrationRequired(e))return;yield this.cryptoService.setMasterKeyEncryptedUserKey(e.key);const t=yield this.cryptoService.getMasterKey();if(t){const e=yield this.cryptoService.decryptUserKeyWithMasterKey(t);yield this.cryptoService.setUserKey(e)}}))}setPrivateKey(e){var t;return Pt(this,void 0,void 0,(function*(){yield this.cryptoService.setPrivateKey(null!==(t=e.privateKey)&&void 0!==t?t:yield this.createKeyPairForOldAccount())}))}encryptionKeyMigrationRequired(e){return!e.key}getMasterPasswordPolicyOptionsFromResponse(e){return null==e||e instanceof oe?null:bt.fromResponse(e.masterPasswordPolicy)}evaluateMasterPassword({masterPassword:e,email:t},i){var n;const r=null===(n=this.passwordStrengthService.getPasswordStrength(e,t))||void 0===n?void 0:n.score;return this.policyService.evaluateMasterPassword(r,e,i)}exportCache(){return{password:this.cache.value}}}class Ct extends ne{constructor(e,t,i,n,r){super(n,r),this.code=e,this.codeVerifier=t,this.redirectUri=i,this.twoFactor=n}toIdentityToken(e){const t=super.toIdentityToken(e);return t.grant_type="authorization_code",t.code=this.code,t.code_verifier=this.codeVerifier,t.redirect_uri=this.redirectUri,t}static fromJSON(e){return Object.assign(Object.create(Ct.prototype),e,{device:e.device?ie.fromJSON(e.device):void 0,twoFactor:e.twoFactor?Object.assign(new s,e.twoFactor):void 0})}}var At=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Dt{static fromJSON(e){return Object.assign(new Dt,e,{tokenRequest:Ct.fromJSON(e.tokenRequest)})}}class xt extends vt{constructor(e,t,i,n,r,s,o,a,l,c,d,u,h,p,y,v){super(t,i,n,r,s,o,a,l,c,d,v),this.keyConnectorService=u,this.deviceTrustCryptoService=h,this.authRequestService=p,this.i18nService=y,this.cache=new te.X(e),this.email$=this.cache.pipe((0,q.U)((e=>e.email))),this.orgId$=this.cache.pipe((0,q.U)((e=>e.orgId))),this.ssoEmail2FaSessionToken$=this.cache.pipe((0,q.U)((e=>e.ssoEmail2FaSessionToken)))}logIn(e){return At(this,void 0,void 0,(function*(){const t=new Dt;t.orgId=e.orgId,t.userEnteredEmail=e.email,t.tokenRequest=new Ct(e.code,e.codeVerifier,e.redirectUrl,yield this.buildTwoFactor(e.twoFactor,e.email),yield this.buildDeviceRequest()),this.cache.next(t);const[i]=yield this.startLogIn(),n=i.email,r=i.ssoEmail2FaSessionToken;return i.forcePasswordReset==X.AdminForcePasswordReset&&(yield this.stateService.setForceSetPasswordReason(i.forcePasswordReset)),this.cache.next(Object.assign(Object.assign({},this.cache.value),{email:n,ssoEmail2FaSessionToken:r})),i}))}setMasterKey(e){return At(this,void 0,void 0,(function*(){if(this.shouldSetMasterKeyFromKeyConnector(e)){if(null==e.key)yield this.keyConnectorService.convertNewSsoUserToKeyConnector(e,this.cache.value.orgId);else{const t=this.getKeyConnectorUrl(e);yield this.keyConnectorService.setMasterKeyFromUrl(t)}}}))}shouldSetMasterKeyFromKeyConnector(e){var t;const i=null==e?void 0:e.userDecryptionOptions;if(null!=i){const e=i.hasMasterPassword;return null!=(null===(t=i.keyConnectorOption)||void 0===t?void 0:t.keyConnectorUrl)&&!e}return null!=e.keyConnectorUrl}getKeyConnectorUrl(e){var t,i;const n=null==e?void 0:e.userDecryptionOptions;return null!==(t=e.keyConnectorUrl)&&void 0!==t?t:null===(i=null==n?void 0:n.keyConnectorOption)||void 0===i?void 0:i.keyConnectorUrl}setUserKey(e){return At(this,void 0,void 0,(function*(){const t=e.key;t&&(yield this.cryptoService.setMasterKeyEncryptedUserKey(t));const i=null==e?void 0:e.userDecryptionOptions;if(null==i?void 0:i.trustedDeviceOption){yield this.trySetUserKeyWithApprovedAdminRequestIfExists();(yield this.cryptoService.hasUserKey())||(yield this.trySetUserKeyWithDeviceKey(e))}else null!=t&&null!=this.getKeyConnectorUrl(e)&&(yield this.trySetUserKeyWithMasterKey())}))}trySetUserKeyWithApprovedAdminRequestIfExists(){return At(this,void 0,void 0,(function*(){const e=yield this.stateService.getAdminAuthRequest();if(!e)return;let t;try{t=yield this.apiService.getAuthRequest(e.id)}catch(e){return void(e instanceof Y&&e.statusCode===fe.NotFound&&(yield this.stateService.setAdminAuthRequest(null)))}(null==t?void 0:t.requestApproved)&&(t.masterPasswordHash?yield this.authRequestService.setKeysAfterDecryptingSharedMasterKeyAndHash(t,e.privateKey):yield this.authRequestService.setUserKeyAfterDecryptingSharedUserKey(t,e.privateKey),(yield this.cryptoService.hasUserKey())&&(yield this.deviceTrustCryptoService.trustDeviceIfRequired(),yield this.stateService.setAdminAuthRequest(null),this.platformUtilsService.showToast("success",null,this.i18nService.t("loginApproved"))))}))}trySetUserKeyWithDeviceKey(e){var t;return At(this,void 0,void 0,(function*(){const i=null===(t=e.userDecryptionOptions)||void 0===t?void 0:t.trustedDeviceOption,n=yield this.deviceTrustCryptoService.getDeviceKey(),r=null==i?void 0:i.encryptedPrivateKey,s=null==i?void 0:i.encryptedUserKey;if(!n||!r||!s)return;const o=yield this.deviceTrustCryptoService.decryptUserKeyWithDeviceKey(r,s,n);o&&(yield this.cryptoService.setUserKey(o))}))}trySetUserKeyWithMasterKey(){return At(this,void 0,void 0,(function*(){const e=yield this.cryptoService.getMasterKey();if(!e)return;const t=yield this.cryptoService.decryptUserKeyWithMasterKey(e);yield this.cryptoService.setUserKey(t)}))}setPrivateKey(e){var t;return At(this,void 0,void 0,(function*(){null==e.key||(yield this.cryptoService.setPrivateKey(null!==(t=e.privateKey)&&void 0!==t?t:yield this.createKeyPairForOldAccount()))}))}exportCache(){return{sso:this.cache.value}}}class It extends ne{constructor(e,t,i,n){super(i,n),this.clientId=e,this.clientSecret=t,this.twoFactor=i}toIdentityToken(){const e=super.toIdentityToken(this.clientId);return e.scope=this.clientId.startsWith("organization")?"api.organization":"api",e.grant_type="client_credentials",e.client_secret=this.clientSecret,e}static fromJSON(e){return Object.assign(Object.create(It.prototype),e,{device:e.device?ie.fromJSON(e.device):void 0,twoFactor:e.twoFactor?Object.assign(new s,e.twoFactor):void 0})}}var Ut=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Tt{static fromJSON(e){return Object.assign(new Tt,e,{tokenRequest:It.fromJSON(e.tokenRequest)})}}class Nt extends vt{constructor(e,t,i,n,r,s,o,a,l,c,d,u,h,p){super(t,i,n,r,s,o,a,l,c,d,p),this.environmentService=u,this.keyConnectorService=h,this.cache=new te.X(e)}logIn(e){return Ut(this,void 0,void 0,(function*(){const t=new Tt;t.tokenRequest=new It(e.clientId,e.clientSecret,yield this.buildTwoFactor(),yield this.buildDeviceRequest()),this.cache.next(t);const[i]=yield this.startLogIn();return i}))}setMasterKey(e){return Ut(this,void 0,void 0,(function*(){if(e.apiUseKeyConnector){const e=(yield(0,r.z)(this.environmentService.environment$)).getKeyConnectorUrl();yield this.keyConnectorService.setMasterKeyFromUrl(e)}}))}setUserKey(e){return Ut(this,void 0,void 0,(function*(){if(yield this.cryptoService.setMasterKeyEncryptedUserKey(e.key),e.apiUseKeyConnector){const e=yield this.cryptoService.getMasterKey();if(e){const t=yield this.cryptoService.decryptUserKeyWithMasterKey(e);yield this.cryptoService.setUserKey(t)}}}))}setPrivateKey(e){var t;return Ut(this,void 0,void 0,(function*(){yield this.cryptoService.setPrivateKey(null!==(t=e.privateKey)&&void 0!==t?t:yield this.createKeyPairForOldAccount())}))}saveAccountInformation(e){const t=Object.create(null,{saveAccountInformation:{get:()=>super.saveAccountInformation}});return Ut(this,void 0,void 0,(function*(){yield t.saveAccountInformation.call(this,e);const i=yield this.stateService.getVaultTimeout(),n=yield this.stateService.getVaultTimeoutAction(),r=this.cache.value.tokenRequest;yield this.tokenService.setClientId(r.clientId,n,i),yield this.tokenService.setClientSecret(r.clientSecret,n,i)}))}exportCache(){return{userApiKey:this.cache.value}}}class Rt extends ne{constructor(e,t,i){super(void 0,i),this.token=e,this.deviceResponse=t}toIdentityToken(e){const t=super.toIdentityToken(e);return t.grant_type="webauthn",t.token=this.token,t.deviceResponse=JSON.stringify(this.deviceResponse),t}static fromJSON(e){return Object.assign(Object.create(Rt.prototype),e,{deviceResponse:v.fromJSON(e.deviceResponse),device:e.device?ie.fromJSON(e.device):void 0,twoFactor:e.twoFactor?Object.assign(new s,e.twoFactor):void 0})}}var Et,Ft=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Mt{static fromJSON(e){return Object.assign(new Mt,e,{tokenRequest:Rt.fromJSON(e.tokenRequest),credentials:E.fromJSON(e.credentials)})}}class Kt extends vt{constructor(e,t,i,n,r,s,o,a,l,c,d,u){super(t,i,n,r,s,o,a,l,c,d,u),this.cache=new te.X(e)}logIn(e){return Ft(this,void 0,void 0,(function*(){const t=new Mt;t.credentials=e,t.tokenRequest=new Rt(e.token,e.deviceResponse,yield this.buildDeviceRequest()),this.cache.next(t);const[i]=yield this.startLogIn();return i}))}logInTwoFactor(){return Ft(this,void 0,void 0,(function*(){throw new Error("2FA not supported yet for WebAuthn Login.")}))}setMasterKey(){return Ft(this,void 0,void 0,(function*(){return Promise.resolve()}))}setUserKey(e){var t;return Ft(this,void 0,void 0,(function*(){const i=e.key;i&&(yield this.cryptoService.setMasterKeyEncryptedUserKey(i));const n=null==e?void 0:e.userDecryptionOptions;if(null==n?void 0:n.webAuthnPrfOption){const i=null===(t=e.userDecryptionOptions)||void 0===t?void 0:t.webAuthnPrfOption,n=this.cache.value.credentials;if(!n.prfKey)return;const r=yield this.cryptoService.decryptToBytes(i.encryptedPrivateKey,n.prfKey),s=yield this.cryptoService.rsaDecrypt(i.encryptedUserKey.encryptedString,r);s&&(yield this.cryptoService.setUserKey(new N(s)))}}))}setPrivateKey(e){var t;return Ft(this,void 0,void 0,(function*(){yield this.cryptoService.setPrivateKey(null!==(t=e.privateKey)&&void 0!==t?t:yield this.createKeyPairForOldAccount())}))}exportCache(){return{webAuthn:this.cache.value}}}class Lt{constructor(e,t,i){this.stateDefinition=e,this.uniqueDerivationName=t,this.options=i}static from(e,t){return zt(e)?new Lt(e.stateDefinition,e.key,t):new Lt(e[0].stateDefinition,e[1],t)}static fromWithUserId(e,t){return zt(e)?new Lt(e.stateDefinition,e.key,t):new Lt(e[0].stateDefinition,e[1],t)}get derive(){return this.options.derive}deserialize(e){return this.options.deserializer(e)}get cleanupDelayMs(){var e;return this.options.cleanupDelayMs<0?0:null!==(e=this.options.cleanupDelayMs)&&void 0!==e?e:1e3}get clearOnCleanup(){var e;return null===(e=this.options.clearOnCleanup)||void 0===e||e}buildCacheKey(){return`derived_${this.stateDefinition.name}_${this.uniqueDerivationName}`}get storageKey(){return`derived_${this.stateDefinition.name}_${this.uniqueDerivationName}`}}function zt(e){return Object.prototype.hasOwnProperty.call(e,"key")}class Vt{}function Bt(e){return t=>null==t?null:t.map((t=>e(t)))}function _t(e){return t=>{if(null==t)return null;const i={};for(const n in t)i[n]=e(t[n]);return i}}class jt{constructor(e,t,i){if(this.stateDefinition=e,this.key=t,this.options=i,null==i.deserializer)throw new Error(`'deserializer' is a required property on key ${this.errorKeyName}`);if(i.cleanupDelayMs<=0)throw new Error(`'cleanupDelayMs' must be greater than 0. Value of ${i.cleanupDelayMs} passed to key ${this.errorKeyName} `)}get deserializer(){return this.options.deserializer}get cleanupDelayMs(){var e;return this.options.cleanupDelayMs<0?0:null!==(e=this.options.cleanupDelayMs)&&void 0!==e?e:1e3}static array(e,t,i){return new jt(e,t,Object.assign(Object.assign({},i),{deserializer:Bt((e=>i.deserializer(e)))}))}static record(e,t,i){return new jt(e,t,Object.assign(Object.assign({},i),{deserializer:_t((e=>i.deserializer(e)))}))}get fullName(){return`${this.stateDefinition.name}_${this.key}`}get errorKeyName(){return`${this.stateDefinition.name} > ${this.key}`}}const $t=Symbol("UserKeyDefinition");function Wt(e){return $t in e&&!0===e[$t]}class qt{constructor(e,t,i){if(this.stateDefinition=e,this.key=t,this.options=i,this[Et]=!0,null==i.deserializer)throw new Error(`'deserializer' is a required property on key ${this.errorKeyName}`);if(i.cleanupDelayMs<=0)throw new Error(`'cleanupDelayMs' must be greater than 0. Value of ${i.cleanupDelayMs} passed to key ${this.errorKeyName} `);this.clearOn=Array.from(new Set(i.clearOn))}get deserializer(){return this.options.deserializer}get cleanupDelayMs(){var e;return this.options.cleanupDelayMs<0?0:null!==(e=this.options.cleanupDelayMs)&&void 0!==e?e:1e3}static fromBaseKeyDefinition(e){return new qt(e.stateDefinition,e.key,Object.assign(Object.assign({},e.options),{clearOn:[]}))}static array(e,t,i){return new qt(e,t,Object.assign(Object.assign({},i),{deserializer:Bt((e=>i.deserializer(e)))}))}static record(e,t,i){return new qt(e,t,Object.assign(Object.assign({},i),{deserializer:_t((e=>i.deserializer(e)))}))}get fullName(){return`${this.stateDefinition.name}_${this.key}`}buildKey(e){if(!p.isGuid(e))throw new Error(`You cannot build a user key without a valid UserId, building for key ${this.fullName}`);return`user_${e}_${this.stateDefinition.name}_${this.key}`}get errorKeyName(){return`${this.stateDefinition.name} > ${this.key}`}}Et=$t;class Ht{constructor(e,t,i){this.name=e,this.defaultStorageLocation=t,this.storageLocationOverrides=null!=i?i:{}}}const Gt=new Ht("organizations","disk"),Jt=new Ht("policies","disk"),Yt=new Ht("providers","disk"),Qt=(new Ht("organizationManagementPreferences","disk",{web:"disk-local"}),new Ht("billing","disk")),Xt=new Ht("account","memory"),Zt=new Ht("avatar","disk",{web:"disk-local"}),ei=new Ht("ssoLogin","disk"),ti=new Ht("token","disk"),ii=new Ht("tokenDiskLocal","disk",{web:"disk-local"}),ni=new Ht("token","memory"),ri=new Ht("loginStrategy","memory"),si=new Ht("userDecryptionOptions","disk"),oi=new Ht("badgeSettings","disk"),ai=new Ht("userNotificationSettings","disk"),li=new Ht("domainSettings","disk"),ci=new Ht("autofillSettings","disk"),di=new Ht("autofillSettingsLocal","disk",{web:"disk-local"}),ui=(new Ht("newWebLayoutBanner","disk",{web:"disk-local"}),new Ht("unassignedItemsBanner","disk",{web:"disk-local"}),new Ht("applicationId","disk",{web:"disk-local"})),hi=new Ht("biometricSettings","disk"),pi=new Ht("clearEvent","disk"),yi=new Ht("crypto","disk"),vi=new Ht("crypto","memory"),fi=(new Ht("desktopSettings","disk"),new Ht("environment","disk")),gi=new Ht("environment","memory"),mi=new Ht("theming","disk",{web:"disk-local"}),wi=new Ht("translation","disk"),Si=(new Ht("smOnboarding","disk",{web:"disk-local"}),new Ht("generator","disk")),bi=(new Ht("generator","memory"),new Ht("eventCollection","disk")),Pi=new Ht("collection","disk",{web:"memory"}),ki=new Ht("folder","disk",{web:"memory"}),Oi=new Ht("vaultFilter","disk",{web:"disk-local"}),Ci=(new Ht("vaultOnboarding","disk",{web:"disk-local"}),new Ht("vaultSettings","disk",{web:"disk-local"}));var Ai=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Di=jt.array(pi,"lock",{deserializer:e=>e}),xi=jt.array(pi,"logout",{deserializer:e=>e});class Ii{constructor(e,t){this.storageServiceProvider=t,this.stateEventStateMap={lock:e.get(Di),logout:e.get(xi)}}registerEvents(e){return Ai(this,void 0,void 0,(function*(){for(const t of e.clearOn){const i=this.stateEventStateMap[t],[n]=this.storageServiceProvider.get(e.stateDefinition.defaultStorageLocation,e.stateDefinition.storageLocationOverrides),r={state:e.stateDefinition.name,key:e.key,location:n};yield i.update((e=>(null!=e||(e=[]),e.push(r),e)),{shouldUpdate:e=>null==e||-1===e.findIndex((e=>e.state===r.state&&e.key===r.key&&e.location===r.location))})}}))}}var Ui=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Ti{constructor(e,t){this.storageServiceProvider=t,this.stateEventMap={lock:e.get(Di),logout:e.get(xi)}}handleEvent(e,t){return Ui(this,void 0,void 0,(function*(){let i=yield(0,r.z)(this.stateEventMap[e].state$);null!=i||(i=[]);const n=[];for(const e of i)try{const[,i]=this.storageServiceProvider.get(e.location,{}),n=this.storageKeyFor(t,e);null!=(yield i.get(n))&&(yield i.remove(n))}catch(t){let i="Unknown Error";"object"==typeof t&&"message"in t&&"string"==typeof t.message&&(i=t.message),n.push(`${i} in ${e.state} > ${e.key} located ${e.location}`)}if(n.length>0)throw new Error(`One or more errors occurred while handling event '${e}' for user ${t}.\n${n.join("\n")}`)}))}storageKeyFor(e,t){return new qt(new Ht(t.state,t.location),t.key,{deserializer:e=>e,clearOn:[]}).buildKey(e)}}const Ni=new jt(ri,"currentLoginStrategy",{deserializer:e=>e}),Ri=new jt(ri,"loginStrategyCacheExpiration",{deserializer:e=>e?null:new Date(e)}),Ei=new jt(ri,"authRequestPushNotification",{deserializer:e=>e}),Fi=new jt(ri,"loginStrategyCache",{deserializer:e=>null==e?null:{password:e.password?kt.fromJSON(e.password):void 0,sso:e.sso?Dt.fromJSON(e.sso):void 0,userApiKey:e.userApiKey?Tt.fromJSON(e.userApiKey):void 0,authRequest:e.authRequest?gt.fromJSON(e.authRequest):void 0,webAuthn:e.webAuthn?Mt.fromJSON(e.webAuthn):void 0}});var Mi=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Ki=12e4;class Li{constructor(e,t,i,n,r,s,o,a,l,c,d,u,h,p,y,v,f,g,m,w){this.cryptoService=e,this.apiService=t,this.tokenService=i,this.appIdService=n,this.platformUtilsService=r,this.messagingService=s,this.logService=o,this.keyConnectorService=a,this.environmentService=l,this.stateService=c,this.twoFactorService=d,this.i18nService=u,this.encryptService=h,this.passwordStrengthService=p,this.policyService=y,this.deviceTrustCryptoService=v,this.authRequestService=f,this.userDecryptionOptionsService=g,this.stateProvider=m,this.billingAccountProfileStateService=w,this.currentAuthnTypeState=this.stateProvider.get(Ni),this.loginStrategyCacheState=this.stateProvider.get(Fi),this.loginStrategyCacheExpirationState=this.stateProvider.get(Ri),this.authRequestPushNotificationState=this.stateProvider.get(Ei),this.currentAuthType$=this.currentAuthnTypeState.state$,this.authRequestPushNotification$=this.authRequestPushNotificationState.state$.pipe((0,_.h)((e=>null!=e))),this.loginStrategy$=this.currentAuthnTypeState.state$.pipe((0,j.x)(),(0,$.V)(this.loginStrategyCacheState.state$),this.initializeLoginStrategy.bind(this),(0,W.d)({refCount:!0,bufferSize:1}))}getEmail(){return Mi(this,void 0,void 0,(function*(){const e=yield(0,r.z)(this.loginStrategy$);return"email$"in e?yield(0,r.z)(e.email$):null}))}getMasterPasswordHash(){return Mi(this,void 0,void 0,(function*(){const e=yield(0,r.z)(this.loginStrategy$);return"serverMasterKeyHash$"in e?yield(0,r.z)(e.serverMasterKeyHash$):null}))}getSsoEmail2FaSessionToken(){return Mi(this,void 0,void 0,(function*(){const e=yield(0,r.z)(this.loginStrategy$);return"ssoEmail2FaSessionToken$"in e?yield(0,r.z)(e.ssoEmail2FaSessionToken$):null}))}getAccessCode(){return Mi(this,void 0,void 0,(function*(){const e=yield(0,r.z)(this.loginStrategy$);return"accessCode$"in e?yield(0,r.z)(e.accessCode$):null}))}getAuthRequestId(){return Mi(this,void 0,void 0,(function*(){const e=yield(0,r.z)(this.loginStrategy$);return"authRequestId$"in e?yield(0,r.z)(e.authRequestId$):null}))}logIn(e){return Mi(this,void 0,void 0,(function*(){yield this.clearCache(),yield this.currentAuthnTypeState.update((t=>e.type));const t=yield(0,r.z)(this.loginStrategy$),i=Object.assign({},e),n=yield t.logIn(i);return null==n||n.requiresTwoFactor?(yield this.loginStrategyCacheState.update((e=>t.exportCache())),yield this.startSessionTimeout()):yield this.clearCache(),n}))}logInTwoFactor(e,t){return Mi(this,void 0,void 0,(function*(){if(!(yield this.isSessionValid()))throw new Error(this.i18nService.t("sessionTimeout"));const i=yield(0,r.z)(this.loginStrategy$);if(null==i)throw new Error("No login strategy found.");try{const n=yield i.logInTwoFactor(e,t);return null==n||n.requiresTwoFactor||n.requiresCaptcha||(yield this.clearCache()),n}catch(e){throw e instanceof Y||(yield this.clearCache()),e}}))}makePreloginKey(e,t){return Mi(this,void 0,void 0,(function*(){t=t.trim().toLowerCase();let i=null,n=null;try{const e=yield this.apiService.postPrelogin(new G(t));null!=e&&(i=e.kdf,n=new P(e.kdfIterations,e.kdfMemory,e.kdfParallelism))}catch(e){if(null==e||404!==e.statusCode)throw e}return yield this.cryptoService.makeMasterKey(e,t,i,n)}))}sendAuthRequestPushNotification(e){return Mi(this,void 0,void 0,(function*(){null!=e.id&&(yield this.authRequestPushNotificationState.update((t=>e.id)))}))}passwordlessLogin(e,t,i){return Mi(this,void 0,void 0,(function*(){const n=p.fromB64ToArray(t),r=yield this.cryptoService.getMasterKey();let s,o=null;if(r){s=r.encKey;const e=yield this.stateService.getKeyHash();null!=e&&(o=yield this.cryptoService.rsaEncrypt(p.fromUtf8ToArray(e),n))}else{s=(yield this.cryptoService.getUserKey()).key}const a=yield this.cryptoService.rsaEncrypt(s,n),l=new H(a.encryptedString,null==o?void 0:o.encryptedString,yield this.appIdService.getAppId(),i);return yield this.apiService.putAuthRequest(e,l)}))}clearCache(){return Mi(this,void 0,void 0,(function*(){yield this.currentAuthnTypeState.update((e=>null)),yield this.loginStrategyCacheState.update((e=>null)),yield this.clearSessionTimeout()}))}startSessionTimeout(){return Mi(this,void 0,void 0,(function*(){yield this.clearSessionTimeout(),yield this.loginStrategyCacheExpirationState.update((e=>new Date(Date.now()+Ki))),this.sessionTimeout=setTimeout((()=>this.clearCache()),Ki)}))}clearSessionTimeout(){return Mi(this,void 0,void 0,(function*(){yield this.loginStrategyCacheExpirationState.update((e=>null)),this.sessionTimeout=null}))}isSessionValid(){return Mi(this,void 0,void 0,(function*(){if(null==(yield(0,r.z)(this.loginStrategyCacheState.state$)))return!1;const e=yield(0,r.z)(this.loginStrategyCacheExpirationState.state$);return!(null!=e&&e{if(null==e)return null;switch(e){case n.Password:return new Ot(null==t?void 0:t.password,this.cryptoService,this.apiService,this.tokenService,this.appIdService,this.platformUtilsService,this.messagingService,this.logService,this.stateService,this.twoFactorService,this.userDecryptionOptionsService,this.passwordStrengthService,this.policyService,this,this.billingAccountProfileStateService);case n.Sso:return new xt(null==t?void 0:t.sso,this.cryptoService,this.apiService,this.tokenService,this.appIdService,this.platformUtilsService,this.messagingService,this.logService,this.stateService,this.twoFactorService,this.userDecryptionOptionsService,this.keyConnectorService,this.deviceTrustCryptoService,this.authRequestService,this.i18nService,this.billingAccountProfileStateService);case n.UserApiKey:return new Nt(null==t?void 0:t.userApiKey,this.cryptoService,this.apiService,this.tokenService,this.appIdService,this.platformUtilsService,this.messagingService,this.logService,this.stateService,this.twoFactorService,this.userDecryptionOptionsService,this.environmentService,this.keyConnectorService,this.billingAccountProfileStateService);case n.AuthRequest:return new mt(null==t?void 0:t.authRequest,this.cryptoService,this.apiService,this.tokenService,this.appIdService,this.platformUtilsService,this.messagingService,this.logService,this.stateService,this.twoFactorService,this.userDecryptionOptionsService,this.deviceTrustCryptoService,this.billingAccountProfileStateService);case n.WebAuthn:return new Kt(null==t?void 0:t.webAuthn,this.cryptoService,this.apiService,this.tokenService,this.appIdService,this.platformUtilsService,this.messagingService,this.logService,this.stateService,this.twoFactorService,this.userDecryptionOptionsService,this.billingAccountProfileStateService)}})))}}var zi=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Vi=new qt(si,"decryptionOptions",{deserializer:e=>K.fromJSON(e),clearOn:["logout"]});class Bi{constructor(e){this.stateProvider=e,this.userDecryptionOptionsState=this.stateProvider.getActive(Vi),this.userDecryptionOptions$=this.userDecryptionOptionsState.state$,this.hasMasterPassword$=this.userDecryptionOptions$.pipe((0,q.U)((e=>{var t;return null!==(t=null==e?void 0:e.hasMasterPassword)&&void 0!==t&&t})))}userDecryptionOptionsById$(e){return this.stateProvider.getUser(e,Vi).state$}setUserDecryptionOptions(e){return zi(this,void 0,void 0,(function*(){yield this.userDecryptionOptionsState.update((t=>e))}))}}var _i,ji,$i,Wi,qi,Hi,Gi,Ji,Yi,Qi=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Xi{constructor(e,t,i,n){this.appIdService=e,this.cryptoService=t,this.apiService=i,this.stateService=n}approveOrDenyAuthRequest(e,t){return Qi(this,void 0,void 0,(function*(){if(!t.id)throw new Error("Auth request has no id");if(!t.publicKey)throw new Error("Auth request has no public key");const i=p.fromB64ToArray(t.publicKey),n=yield this.cryptoService.getMasterKey(),r=yield this.stateService.getKeyHash();let s,o;if(n&&r)s=yield this.cryptoService.rsaEncrypt(p.fromUtf8ToArray(r),i),o=n.encKey;else{o=(yield this.cryptoService.getUserKey()).key}const a=yield this.cryptoService.rsaEncrypt(o,i),l=new H(a.encryptedString,null==s?void 0:s.encryptedString,yield this.appIdService.getAppId(),e);return yield this.apiService.putAuthRequest(t.id,l)}))}setUserKeyAfterDecryptingSharedUserKey(e,t){return Qi(this,void 0,void 0,(function*(){const i=yield this.decryptPubKeyEncryptedUserKey(e.key,t);yield this.cryptoService.setUserKey(i)}))}setKeysAfterDecryptingSharedMasterKeyAndHash(e,t){return Qi(this,void 0,void 0,(function*(){const{masterKey:i,masterKeyHash:n}=yield this.decryptPubKeyEncryptedMasterKeyAndHash(e.key,e.masterPasswordHash,t),r=yield this.cryptoService.decryptUserKeyWithMasterKey(i);yield this.cryptoService.setMasterKey(i),yield this.cryptoService.setMasterKeyHash(n),yield this.cryptoService.setUserKey(r)}))}decryptPubKeyEncryptedUserKey(e,t){return Qi(this,void 0,void 0,(function*(){const i=yield this.cryptoService.rsaDecrypt(e,t);return new N(i)}))}decryptPubKeyEncryptedMasterKeyAndHash(e,t,i){return Qi(this,void 0,void 0,(function*(){const n=yield this.cryptoService.rsaDecrypt(e,i),r=yield this.cryptoService.rsaDecrypt(t,i);return{masterKey:new N(n),masterKeyHash:p.fromBufferToUtf8(r)}}))}}class Zi{constructor(e,t){null!=e&&(this.id=e.id,this.name=e.name,this.status=e.status,this.type=e.type,this.enabled=e.enabled,this.usePolicies=e.usePolicies,this.useGroups=e.useGroups,this.useDirectory=e.useDirectory,this.useEvents=e.useEvents,this.useTotp=e.useTotp,this.use2fa=e.use2fa,this.useApi=e.useApi,this.useSso=e.useSso,this.useKeyConnector=e.useKeyConnector,this.useScim=e.useScim,this.useCustomPermissions=e.useCustomPermissions,this.useResetPassword=e.useResetPassword,this.useSecretsManager=e.useSecretsManager,this.usePasswordManager=e.usePasswordManager,this.useActivateAutofillPolicy=e.useActivateAutofillPolicy,this.selfHost=e.selfHost,this.usersGetPremium=e.usersGetPremium,this.seats=e.seats,this.maxCollections=e.maxCollections,this.maxStorageGb=e.maxStorageGb,this.ssoBound=e.ssoBound,this.identifier=e.identifier,this.permissions=e.permissions,this.resetPasswordEnrolled=e.resetPasswordEnrolled,this.userId=e.userId,this.hasPublicAndPrivateKeys=e.hasPublicAndPrivateKeys,this.providerId=e.providerId,this.providerName=e.providerName,this.providerType=e.providerType,this.familySponsorshipFriendlyName=e.familySponsorshipFriendlyName,this.familySponsorshipAvailable=e.familySponsorshipAvailable,this.planProductType=e.planProductType,this.keyConnectorEnabled=e.keyConnectorEnabled,this.keyConnectorUrl=e.keyConnectorUrl,this.familySponsorshipLastSyncDate=e.familySponsorshipLastSyncDate,this.familySponsorshipValidUntil=e.familySponsorshipValidUntil,this.familySponsorshipToDelete=e.familySponsorshipToDelete,this.accessSecretsManager=e.accessSecretsManager,this.limitCollectionCreationDeletion=e.limitCollectionCreationDeletion,this.allowAdminAccessToAllCollectionItems=e.allowAdminAccessToAllCollectionItems,this.flexibleCollections=e.flexibleCollections,this.isMember=t.isMember,this.isProviderUser=t.isProviderUser)}static fromJSON(e){return Object.assign(new Zi,e,{familySponsorshipLastSyncDate:null!=e.familySponsorshipLastSyncDate?new Date(e.familySponsorshipLastSyncDate):e.familySponsorshipLastSyncDate,familySponsorshipValidUntil:null!=e.familySponsorshipValidUntil?new Date(e.familySponsorshipValidUntil):e.familySponsorshipValidUntil})}}!function(e){e[e.Default=0]="Default",e[e.BillingSync=1]="BillingSync",e[e.Scim=2]="Scim"}(_i||(_i={})),function(e){e[e.CloudBillingSync=1]="CloudBillingSync",e[e.Scim=2]="Scim"}(ji||(ji={})),function(e){e[e.Invited=0]="Invited",e[e.Accepted=1]="Accepted",e[e.Confirmed=2]="Confirmed",e[e.Revoked=-1]="Revoked"}($i||($i={})),function(e){e[e.Owner=0]="Owner",e[e.Admin=1]="Admin",e[e.User=2]="User",e[e.Manager=3]="Manager",e[e.Custom=4]="Custom"}(Wi||(Wi={})),function(e){e[e.TwoFactorAuthentication=0]="TwoFactorAuthentication",e[e.MasterPassword=1]="MasterPassword",e[e.PasswordGenerator=2]="PasswordGenerator",e[e.SingleOrg=3]="SingleOrg",e[e.RequireSso=4]="RequireSso",e[e.PersonalOwnership=5]="PersonalOwnership",e[e.DisableSend=6]="DisableSend",e[e.SendOptions=7]="SendOptions",e[e.ResetPassword=8]="ResetPassword",e[e.MaximumVaultTimeout=9]="MaximumVaultTimeout",e[e.DisablePersonalVaultExport=10]="DisablePersonalVaultExport",e[e.ActivateAutofill=11]="ActivateAutofill"}(qi||(qi={})),function(e){e[e.Msp=0]="Msp",e[e.Reseller=1]="Reseller"}(Hi||(Hi={})),function(e){e[e.Invited=0]="Invited",e[e.Accepted=1]="Accepted",e[e.Confirmed=2]="Confirmed",e[e.Revoked=-1]="Revoked"}(Gi||(Gi={})),function(e){e[e.ProviderAdmin=0]="ProviderAdmin",e[e.ServiceUser=1]="ServiceUser"}(Ji||(Ji={})),function(e){e[e.Default=0]="Default",e[e.AzureAd=1]="AzureAd",e[e.Okta=2]="Okta",e[e.OneLogin=3]="OneLogin",e[e.JumpCloud=4]="JumpCloud",e[e.GoogleWorkspace=5]="GoogleWorkspace",e[e.Rippling=6]="Rippling"}(Yi||(Yi={}));class en{constructor(e){null!=e&&(this.id=e.id,this.name=e.name,this.status=e.status,this.type=e.type,this.enabled=e.enabled,this.usePolicies=e.usePolicies,this.useGroups=e.useGroups,this.useDirectory=e.useDirectory,this.useEvents=e.useEvents,this.useTotp=e.useTotp,this.use2fa=e.use2fa,this.useApi=e.useApi,this.useSso=e.useSso,this.useKeyConnector=e.useKeyConnector,this.useScim=e.useScim,this.useCustomPermissions=e.useCustomPermissions,this.useResetPassword=e.useResetPassword,this.useSecretsManager=e.useSecretsManager,this.usePasswordManager=e.usePasswordManager,this.useActivateAutofillPolicy=e.useActivateAutofillPolicy,this.selfHost=e.selfHost,this.usersGetPremium=e.usersGetPremium,this.seats=e.seats,this.maxCollections=e.maxCollections,this.maxStorageGb=e.maxStorageGb,this.ssoBound=e.ssoBound,this.identifier=e.identifier,this.permissions=e.permissions,this.resetPasswordEnrolled=e.resetPasswordEnrolled,this.userId=e.userId,this.hasPublicAndPrivateKeys=e.hasPublicAndPrivateKeys,this.providerId=e.providerId,this.providerName=e.providerName,this.providerType=e.providerType,this.isProviderUser=e.isProviderUser,this.isMember=e.isMember,this.familySponsorshipFriendlyName=e.familySponsorshipFriendlyName,this.familySponsorshipAvailable=e.familySponsorshipAvailable,this.planProductType=e.planProductType,this.keyConnectorEnabled=e.keyConnectorEnabled,this.keyConnectorUrl=e.keyConnectorUrl,this.familySponsorshipLastSyncDate=e.familySponsorshipLastSyncDate,this.familySponsorshipValidUntil=e.familySponsorshipValidUntil,this.familySponsorshipToDelete=e.familySponsorshipToDelete,this.accessSecretsManager=e.accessSecretsManager,this.limitCollectionCreationDeletion=e.limitCollectionCreationDeletion,this.allowAdminAccessToAllCollectionItems=e.allowAdminAccessToAllCollectionItems,this.flexibleCollections=e.flexibleCollections)}get canAccess(){return!!this.isOwner||this.enabled&&this.status===$i.Confirmed}get isManager(){return this.type===Wi.Manager||this.isAdmin}get isAdmin(){return this.type===Wi.Admin||this.isOwner}get isOwner(){return this.type===Wi.Owner||this.isProviderUser}get canAccessEventLogs(){return(this.isAdmin||this.permissions.accessEventLogs)&&this.useEvents}get canAccessImportExport(){return this.isAdmin||this.permissions.accessImportExport}get canAccessReports(){return this.isAdmin||this.permissions.accessReports}get canCreateNewCollections(){return this.flexibleCollections?!this.limitCollectionCreationDeletion||this.isAdmin||this.permissions.createNewCollections:this.isManager||this.permissions.createNewCollections}get canEditAnyCollection(){return this.isAdmin||this.permissions.editAnyCollection}get canUseAdminCollections(){return this.canEditAnyCollection}canEditAllCiphers(e){return e?this.isProviderUser||this.type===Wi.Custom&&this.permissions.editAnyCollection||this.allowAdminAccessToAllCollectionItems&&this.isAdmin:this.canEditAnyCollection}get canDeleteAnyCollection(){return this.isAdmin||this.permissions.deleteAnyCollection}get canViewAllCollections(){return this.canEditAnyCollection||this.canDeleteAnyCollection}get canEditAssignedCollections(){return this.isManager||this.permissions.editAssignedCollections}get canDeleteAssignedCollections(){return this.isManager||this.permissions.deleteAssignedCollections}get canViewAssignedCollections(){return this.canDeleteAssignedCollections||this.canEditAssignedCollections}get canManageGroups(){return(this.isAdmin||this.permissions.manageGroups)&&this.useGroups}get canManageSso(){return(this.isAdmin||this.permissions.manageSso)&&this.useSso}get canManageDomainVerification(){return(this.isAdmin||this.permissions.manageSso)&&this.useSso}get canManageScim(){return(this.isAdmin||this.permissions.manageScim)&&this.useScim}get canManagePolicies(){return(this.isAdmin||this.permissions.managePolicies)&&this.usePolicies}get canManageUsers(){return this.isAdmin||this.permissions.manageUsers}get canManageUsersPassword(){return this.isAdmin||this.permissions.manageResetPassword}get canManageDeviceApprovals(){return(this.isAdmin||this.permissions.manageResetPassword)&&this.useSso}get isExemptFromPolicies(){return this.canManagePolicies}get canViewSubscription(){return!!this.canEditSubscription||(this.hasProvider&&this.providerType===Hi.Msp?this.isProviderUser:this.isOwner)}get canEditSubscription(){return this.hasProvider?this.isProviderUser:this.isOwner}get canEditPaymentMethods(){return this.canEditSubscription}get canViewBillingHistory(){return this.canEditSubscription}get hasProvider(){return null!=this.providerId||null!=this.providerName}get hasReseller(){return this.hasProvider&&this.providerType===Hi.Reseller}get canAccessSecretsManager(){return this.useSecretsManager&&this.accessSecretsManager}get isFreeOrg(){return!this.useTotp}get canManageSponsorships(){return this.familySponsorshipAvailable||null!==this.familySponsorshipFriendlyName}static fromJSON(e){return null==e?null:Object.assign(new en,e,{familySponsorshipLastSyncDate:new Date(e.familySponsorshipLastSyncDate),familySponsorshipValidUntil:new Date(e.familySponsorshipValidUntil)})}}var tn=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const nn=qt.record(Gt,"organizations",{deserializer:e=>Zi.fromJSON(e),clearOn:["logout"]});function rn(){return(0,q.U)((e=>e.length>0))}function sn(e){return(0,q.U)((t=>null==t?void 0:t.find((t=>t.id===e))))}class on{constructor(e){this.stateProvider=e,this.organizations$=this.getOrganizationsFromState$(),this.memberOrganizations$=this.organizations$.pipe((0,q.U)((e=>e.filter((e=>e.isMember)))))}get$(e){return this.organizations$.pipe(sn(e))}getAll(e){return tn(this,void 0,void 0,(function*(){return yield(0,r.z)(this.getOrganizationsFromState$(e))}))}canManageSponsorships(){return tn(this,void 0,void 0,(function*(){return yield(0,r.z)(this.organizations$.pipe((0,q.U)((e=>e.filter((e=>e.canManageSponsorships)))),rn()))}))}hasOrganizations(){return tn(this,void 0,void 0,(function*(){return yield(0,r.z)(this.organizations$.pipe(rn()))}))}upsert(e,t){return tn(this,void 0,void 0,(function*(){yield this.stateFor(t).update((t=>{const i=null!=t?t:{};return i[e.id]=e,i}))}))}get(e){return tn(this,void 0,void 0,(function*(){return yield(0,r.z)(this.organizations$.pipe(sn(e)))}))}getFromState(e){return tn(this,void 0,void 0,(function*(){return yield(0,r.z)(this.organizations$.pipe(sn(e)))}))}replace(e,t){return tn(this,void 0,void 0,(function*(){yield this.stateFor(t).update((()=>e))}))}getOrganizationsFromState$(e){return this.stateFor(e).state$.pipe(this.mapOrganizationRecordToArray())}mapOrganizationRecordToArray(){return(0,q.U)((e=>{var t;return null===(t=Object.values(null!=e?e:{}))||void 0===t?void 0:t.map((e=>new en(e)))}))}stateFor(e){return e?this.stateProvider.getUser(e,nn):this.stateProvider.getActive(nn)}}class an extends J{constructor(e,t){super(e);const i=this.getResponseProperty("Data");this.data=null==i?[]:i.map((e=>new t(e))),this.continuationToken=this.getResponseProperty("ContinuationToken")}}class ln{constructor(e){null!=e&&(this.id=e.id,this.organizationId=e.organizationId,this.type=e.type,this.data=e.data,this.enabled=e.enabled)}}class cn extends St{constructor(e){super(),null!=e&&(this.id=e.id,this.organizationId=e.organizationId,this.type=e.type,this.data=e.data,this.enabled=e.enabled)}static fromResponse(e){return new cn(new ln(e))}static fromListResponse(e){var t,i;return null!==(i=null===(t=e.data)||void 0===t?void 0:t.map((e=>cn.fromResponse(e))))&&void 0!==i?i:void 0}}class dn extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.organizationId=this.getResponseProperty("OrganizationId"),this.type=this.getResponseProperty("Type"),this.data=this.getResponseProperty("Data"),this.enabled=this.getResponseProperty("Enabled")}}var un=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class hn{constructor(e,t){this.policyService=e,this.apiService=t}getPolicy(e,t){return un(this,void 0,void 0,(function*(){const i=yield this.apiService.send("GET","/organizations/"+e+"/policies/"+t,null,!0,!0);return new dn(i)}))}getPolicies(e){return un(this,void 0,void 0,(function*(){const t=yield this.apiService.send("GET","/organizations/"+e+"/policies",null,!0,!0);return new an(t,dn)}))}getPoliciesByToken(e,t,i,n){return un(this,void 0,void 0,(function*(){const r=yield this.apiService.send("GET","/organizations/"+e+"/policies/token?token="+encodeURIComponent(t)+"&email="+p.encodeRFC3986URIComponent(i)+"&organizationUserId="+n,null,!1,!0);return new an(r,dn)}))}getMasterPasswordPolicyResponseForOrgUser(e){return un(this,void 0,void 0,(function*(){const t=yield this.apiService.send("GET","/organizations/"+e+"/policies/master-password",null,!0,!0);return new dn(t)}))}getMasterPasswordPolicyOptsForOrgUser(e){return un(this,void 0,void 0,(function*(){try{const t=yield this.getMasterPasswordPolicyResponseForOrgUser(e),i=cn.fromResponse(t);return i?yield(0,r.z)(this.policyService.masterPasswordPolicyOptions$([i])):null}catch(e){if(e instanceof Y&&e.statusCode===fe.NotFound)return null;throw e}}))}putPolicy(e,t,i){return un(this,void 0,void 0,(function*(){const n=yield this.apiService.send("PUT","/organizations/"+e+"/policies/"+t,i,!0,!0),r=new dn(n),s=new ln(r);yield this.policyService.upsert(s)}))}}var pn=i(33031);class yn extends St{constructor(){super(...arguments),this.autoEnrollEnabled=!1}}var vn=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const fn=e=>Object.values(e||{}).map((e=>new cn(e))),gn=jt.record(Jt,"policies",{deserializer:e=>e});class mn{constructor(e,t){this.stateProvider=e,this.organizationService=t,this.activeUserPolicyState=this.stateProvider.getActive(gn),this.activeUserPolicies$=this.activeUserPolicyState.state$.pipe((0,q.U)((e=>fn(e)))),this.policies$=this.activeUserPolicies$}get$(e){const t=this.activeUserPolicies$.pipe((0,q.U)((t=>t.filter((t=>t.type===e)))));return(0,pn.a)([t,this.organizationService.organizations$]).pipe((0,q.U)((([e,t])=>{var i,n;return null!==(n=null===(i=this.enforcedPolicyFilter(e,t))||void 0===i?void 0:i.at(0))&&void 0!==n?n:null})))}getAll$(e,t){const i=this.stateProvider.getUserState$(gn,t).pipe((0,q.U)((e=>fn(e))),(0,q.U)((t=>t.filter((t=>t.type===e)))));return(0,pn.a)([i,this.organizationService.organizations$]).pipe((0,q.U)((([e,t])=>this.enforcedPolicyFilter(e,t))))}getAll(e){return vn(this,void 0,void 0,(function*(){return yield(0,r.z)(this.policies$.pipe((0,q.U)((t=>t.filter((t=>t.type===e))))))}))}policyAppliesToActiveUser$(e){return this.get$(e).pipe((0,q.U)((e=>null!=e)))}policyAppliesToUser(e){return vn(this,void 0,void 0,(function*(){return yield(0,r.z)(this.policyAppliesToActiveUser$(e))}))}enforcedPolicyFilter(e,t){const i=Object.fromEntries(t.map((e=>[e.id,e])));return e.filter((e=>{const t=i[e.organizationId];return null==t||e.enabled&&t.status>=$i.Accepted&&t.usePolicies&&!this.isExemptFromPolicy(e.type,t)}))}masterPasswordPolicyOptions$(e){return(e?(0,l.of)(e):this.policies$).pipe((0,q.U)((e=>{let t=null;const i=e.filter((e=>e.type===qi.MasterPassword));return null==i||0===i.length||i.forEach((e=>{e.enabled&&null!=e.data&&(null==t&&(t=new bt),null!=e.data.minComplexity&&e.data.minComplexity>t.minComplexity&&(t.minComplexity=e.data.minComplexity),null!=e.data.minLength&&e.data.minLength>t.minLength&&(t.minLength=e.data.minLength),e.data.requireUpper&&(t.requireUpper=!0),e.data.requireLower&&(t.requireLower=!0),e.data.requireNumbers&&(t.requireNumbers=!0),e.data.requireSpecial&&(t.requireSpecial=!0),e.data.enforceOnLogin&&(t.enforceOnLogin=!0))})),t})))}evaluateMasterPassword(e,t,i){return null==i||!(i.minComplexity>0&&i.minComplexity>e)&&(!(i.minLength>0&&i.minLength>t.length)&&((!i.requireUpper||t.toLocaleLowerCase()!==t)&&((!i.requireLower||t.toLocaleUpperCase()!==t)&&(!(i.requireNumbers&&!/[0-9]/.test(t))&&!(i.requireSpecial&&!/[!@#$%\^&*]/g.test(t))))))}getResetPasswordPolicyOptions(e,t){var i,n,r;const s=new yn;if(null==e||null==t)return[s,!1];const o=e.find((e=>e.organizationId===t&&e.type===qi.ResetPassword&&e.enabled));return s.autoEnrollEnabled=null!==(n=null===(i=null==o?void 0:o.data)||void 0===i?void 0:i.autoEnrollEnabled)&&void 0!==n&&n,[s,null!==(r=null==o?void 0:o.enabled)&&void 0!==r&&r]}upsert(e){return vn(this,void 0,void 0,(function*(){yield this.activeUserPolicyState.update((t=>(null!=t||(t={}),t[e.id]=e,t)))}))}replace(e){return vn(this,void 0,void 0,(function*(){yield this.activeUserPolicyState.update((()=>e))}))}clear(e){return vn(this,void 0,void 0,(function*(){yield this.stateProvider.setUserState(gn,null,e)}))}isExemptFromPolicy(e,t){return e===qi.MaximumVaultTimeout?t.isOwner:t.canManagePolicies}}var wn=i(2097);class Sn{constructor(e){null!=e&&(this.id=e.id,this.name=e.name,this.status=e.status,this.type=e.type,this.enabled=e.enabled,this.userId=e.userId,this.useEvents=e.useEvents)}get canAccess(){return!!this.isProviderAdmin||this.enabled&&this.status===Gi.Confirmed}get canCreateOrganizations(){return this.enabled&&this.isProviderAdmin}get canManageUsers(){return this.isProviderAdmin}get canAccessEventLogs(){return this.isProviderAdmin}get isProviderAdmin(){return this.type===Ji.ProviderAdmin}}var bn=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Pn=jt.record(Yt,"providers",{deserializer:e=>e});class kn{constructor(e){this.stateProvider=e}providers$(e){return(null!=e?this.stateProvider.getUser(e,Pn).state$:this.stateProvider.activeUserId$.pipe((0,wn.q)(1),(0,c.w)((e=>null!=e?this.stateProvider.getUser(e,Pn).state$:(0,l.of)(null))))).pipe(this.mapProviderRecordToArray())}mapProviderRecordToArray(){return(0,q.U)((e=>{var t;return null===(t=Object.values(null!=e?e:{}))||void 0===t?void 0:t.map((e=>new Sn(e)))}))}get(e){return bn(this,void 0,void 0,(function*(){return yield(0,r.z)(this.providers$().pipe((t=e,(0,q.U)((e=>null==e?void 0:e.find((e=>e.id===t)))))));var t}))}getAll(){return bn(this,void 0,void 0,(function*(){return yield(0,r.z)(this.providers$())}))}save(e,t){return bn(this,void 0,void 0,(function*(){yield this.stateProvider.setUserState(Pn,e,t)}))}}var On;!function(e){e[e.LoggedOut=0]="LoggedOut",e[e.Locked=1]="Locked",e[e.Unlocked=2]="Unlocked"}(On||(On={}));var Cn=i(54019);function An(e,t){return(null==e?void 0:e.status)===(null==t?void 0:t.status)&&(null==e?void 0:e.email)===(null==t?void 0:t.email)&&(null==e?void 0:e.name)===(null==t?void 0:t.name)}class Dn{}var xn=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const In=jt.record(Xt,"accounts",{deserializer:e=>e}),Un=new jt(Xt,"activeAccountId",{deserializer:e=>e});class Tn{constructor(e,t,i){this.messagingService=e,this.logService=t,this.globalStateProvider=i,this.lock=new Cn.x,this.logout=new Cn.x,this.accountLock$=this.lock.asObservable(),this.accountLogout$=this.logout.asObservable(),this.accountsState=this.globalStateProvider.get(In),this.activeAccountIdState=this.globalStateProvider.get(Un),this.accounts$=this.accountsState.state$.pipe((0,q.U)((e=>null==e?{}:e))),this.activeAccount$=this.activeAccountIdState.state$.pipe((0,$.V)(this.accounts$),(0,q.U)((([e,t])=>e?Object.assign({id:e},t[e]):void 0)),(0,j.x)(((e,t)=>(null==e?void 0:e.id)===(null==t?void 0:t.id)&&An(e,t))),(0,W.d)({bufferSize:1,refCount:!1}))}addAccount(e,t){return xn(this,void 0,void 0,(function*(){yield this.accountsState.update((i=>(i||(i={}),i[e]=t,i)))}))}setAccountName(e,t){return xn(this,void 0,void 0,(function*(){yield this.setAccountInfo(e,{name:t})}))}setAccountEmail(e,t){return xn(this,void 0,void 0,(function*(){yield this.setAccountInfo(e,{email:t})}))}setAccountStatus(e,t){return xn(this,void 0,void 0,(function*(){yield this.setAccountInfo(e,{status:t}),t===On.LoggedOut?this.logout.next(e):t===On.Locked&&this.lock.next(e)}))}setMaxAccountStatus(e,t){return xn(this,void 0,void 0,(function*(){yield this.accountsState.update((i=>(i[e].status=t,i)),{shouldUpdate:i=>{if(null==(null==i?void 0:i[e]))throw new Error("Account does not exist");return i[e].status>t}})}))}switchAccount(e){return xn(this,void 0,void 0,(function*(){yield this.activeAccountIdState.update(((t,i)=>{if(null==e)return null;if(null==(null==i?void 0:i[e]))throw new Error("Account does not exist");return e}),{combineLatestWith:this.accounts$,shouldUpdate:t=>t!==e})}))}delete(){var e;return xn(this,void 0,void 0,(function*(){try{null===(e=this.messagingService)||void 0===e||e.send("logout")}catch(e){throw this.logService.error(e),e}}))}setAccountInfo(e,t){return xn(this,void 0,void 0,(function*(){function i(e){return Object.assign(Object.assign({},e),t)}yield this.accountsState.update((t=>(t[e]=i(t[e]),t)),{shouldUpdate:t=>{if(null==(null==t?void 0:t[e]))throw new Error("Account does not exist");return!An(t[e],i(t[e]))}})}))}}var Nn=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Rn{constructor(e,t,i,n){this.messagingService=e,this.cryptoService=t,this.apiService=i,this.stateService=n}getAuthStatus(e){return Nn(this,void 0,void 0,(function*(){if(!(yield this.stateService.getIsAuthenticated({userId:e})))return On.LoggedOut;if(!(yield this.cryptoService.hasUserKeyInMemory(e))){if((yield this.cryptoService.hasUserKeyStored(x.Auto,e))&&!(yield this.stateService.getEverBeenUnlocked({userId:e}))){const t=yield this.cryptoService.getUserKeyFromStorage(x.Auto,e);yield this.cryptoService.setUserKey(t,e)}}return(yield this.cryptoService.hasUserKeyInMemory(e))?On.Unlocked:On.Locked}))}logOut(e){e(),this.messagingService.send("loggedOut")}}class En{constructor(e){this.avatarColor=e}}var Fn=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Mn=new qt(Zt,"avatarColor",{deserializer:e=>e,clearOn:[]});class Kn{constructor(e,t){this.apiService=e,this.stateProvider=t,this.avatarColor$=this.stateProvider.getActive(Mn).state$}setAvatarColor(e){return Fn(this,void 0,void 0,(function*(){const{avatarColor:t}=yield this.apiService.putAvatar(new En(e));yield this.stateProvider.setUserState(Mn,t)}))}setSyncAvatarColor(e,t){return Fn(this,void 0,void 0,(function*(){yield this.stateProvider.getUser(e,Mn).update((()=>t))}))}getUserAvatarColor$(e){return this.stateProvider.getUser(e,Mn).state$}}class Ln{}class zn extends Ln{}class Vn{}var Bn=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class _n{constructor(e,t,i,n,r,s,o,a,l,c){this.keyGenerationService=e,this.cryptoFunctionService=t,this.cryptoService=i,this.encryptService=n,this.stateService=r,this.appIdService=s,this.devicesApiService=o,this.i18nService=a,this.platformUtilsService=l,this.userDecryptionOptionsService=c,this.supportsDeviceTrust$=this.userDecryptionOptionsService.userDecryptionOptions$.pipe((0,q.U)((e=>{var t;return null!==(t=null!=(null==e?void 0:e.trustedDeviceOption))&&void 0!==t&&t})))}getShouldTrustDevice(){return Bn(this,void 0,void 0,(function*(){return yield this.stateService.getShouldTrustDevice()}))}setShouldTrustDevice(e){return Bn(this,void 0,void 0,(function*(){yield this.stateService.setShouldTrustDevice(e)}))}trustDeviceIfRequired(){return Bn(this,void 0,void 0,(function*(){(yield this.getShouldTrustDevice())&&(yield this.trustDevice(),yield this.setShouldTrustDevice(!1))}))}trustDevice(){return Bn(this,void 0,void 0,(function*(){const e=yield this.cryptoService.getUserKey();if(!e)throw new Error("User symmetric key not found");const t=yield this.makeDeviceKey(),[i,n]=yield this.cryptoFunctionService.rsaGenerateKeyPair(2048),[r,s,o]=yield Promise.all([this.cryptoService.rsaEncrypt(e.key,i),this.encryptService.encrypt(i,e),this.encryptService.encrypt(n,t)]),a=yield this.appIdService.getAppId(),l=yield this.devicesApiService.updateTrustedDeviceKeys(a,r.encryptedString,s.encryptedString,o.encryptedString);return yield this.setDeviceKey(t),this.platformUtilsService.showToast("success",null,this.i18nService.t("deviceTrusted")),l}))}rotateDevicesTrust(e,t){return Bn(this,void 0,void 0,(function*(){if(null==(yield this.getDeviceKey()))return;const i=yield(0,r.z)(this.cryptoService.activeUserKey$),n=yield this.appIdService.getAppId(),s=new Ln;s.masterPasswordHash=t;const o=yield this.devicesApiService.getDeviceKeys(n,s),a=yield this.encryptService.decryptToBytes(o.encryptedPublicKey,i),l=yield this.cryptoService.rsaEncrypt(e.key,a),c=yield this.encryptService.encrypt(a,e),d=new Vn;d.encryptedUserKey=l.encryptedString,d.encryptedPublicKey=c.encryptedString;const u=new zn;u.masterPasswordHash=t,u.currentDevice=d,u.otherDevices=[],yield this.devicesApiService.updateTrust(u,n)}))}getDeviceKey(){return Bn(this,void 0,void 0,(function*(){return yield this.stateService.getDeviceKey()}))}setDeviceKey(e){return Bn(this,void 0,void 0,(function*(){yield this.stateService.setDeviceKey(e)}))}makeDeviceKey(){return Bn(this,void 0,void 0,(function*(){return yield this.keyGenerationService.createKey(512)}))}decryptUserKeyWithDeviceKey(e,t,i){return Bn(this,void 0,void 0,(function*(){if(i||(i=yield this.getDeviceKey()),!i)return null;try{const n=yield this.encryptService.decryptToBytes(e,i),r=yield this.cryptoService.rsaDecrypt(t.encryptedString,n);return new N(r)}catch(e){return yield this.setDeviceKey(null),null}}))}}var jn=i(8241);class $n{constructor(e){Object.assign(this,e)}}class Wn{constructor(e){this.devicesApiService=e}getDevices$(){return(0,jn.P)((()=>this.devicesApiService.getDevices())).pipe((0,q.U)((e=>e.data.map((e=>new $n(e))))))}getDeviceByIdentifier$(e){return(0,jn.P)((()=>this.devicesApiService.getDeviceByIdentifier(e))).pipe((0,q.U)((e=>new $n(e))))}isDeviceKnownForUser$(e,t){return(0,jn.P)((()=>this.devicesApiService.getKnownDevice(e,t)))}updateTrustedDeviceKeys$(e,t,i,n){return(0,jn.P)((()=>this.devicesApiService.updateTrustedDeviceKeys(e,t,i,n))).pipe((0,q.U)((e=>new $n(e))))}}class qn extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.userId=this.getResponseProperty("UserId"),this.name=this.getResponseProperty("Name"),this.identifier=this.getResponseProperty("Identifier"),this.type=this.getResponseProperty("Type"),this.creationDate=this.getResponseProperty("CreationDate"),this.revisionDate=this.getResponseProperty("RevisionDate")}}class Hn extends J{constructor(e){super(e),this.id=this.getResponseProperty("id"),this.name=this.getResponseProperty("name"),this.identifier=this.getResponseProperty("identifier"),this.type=this.getResponseProperty("type"),this.creationDate=new Date(this.getResponseProperty("creationDate")),e.encryptedUserKey&&(this.encryptedUserKey=new z(this.getResponseProperty("encryptedUserKey"))),e.encryptedPublicKey&&(this.encryptedPublicKey=new z(this.getResponseProperty("encryptedPublicKey")))}}class Gn{constructor(e,t,i){this.encryptedUserKey=e,this.encryptedPublicKey=t,this.encryptedPrivateKey=i}}var Jn=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Yn{constructor(e){this.apiService=e}getKnownDevice(e,t){return Jn(this,void 0,void 0,(function*(){return yield this.apiService.send("GET","/devices/knowndevice",null,!1,!0,null,(i=>{i.set("X-Device-Identifier",t),i.set("X-Request-Email",p.fromUtf8ToUrlB64(e))}))}))}getDeviceByIdentifier(e){return Jn(this,void 0,void 0,(function*(){const t=yield this.apiService.send("GET",`/devices/identifier/${e}`,null,!0,!0);return new qn(t)}))}getDevices(){return Jn(this,void 0,void 0,(function*(){const e=yield this.apiService.send("GET","/devices",null,!0,!0,null);return new an(e,qn)}))}updateTrustedDeviceKeys(e,t,i,n){return Jn(this,void 0,void 0,(function*(){const r=new Gn(t,i,n),s=yield this.apiService.send("PUT",`/devices/${e}/keys`,r,!0,!0);return new qn(s)}))}updateTrust(e,t){return Jn(this,void 0,void 0,(function*(){yield this.apiService.send("POST","/devices/update-trust",e,!0,!1,null,(e=>{e.set("Device-Identifier",t)}))}))}getDeviceKeys(e,t){return Jn(this,void 0,void 0,(function*(){const i=yield this.apiService.send("POST",`/devices/${e}/retrieve-keys`,t,!0,!0);return new Hn(i)}))}}class Qn{constructor(e){this.key=e}}class Xn{constructor(e,t,i,n,r){this.key=e,this.kdf=t,this.kdfIterations=i.iterations,this.kdfMemory=i.memory,this.kdfParallelism=i.parallelism,this.orgIdentifier=n,this.keys=r}}var Zn=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class er{constructor(e,t,i,n,r,s,o,a){this.stateService=e,this.cryptoService=t,this.apiService=i,this.tokenService=n,this.logService=r,this.organizationService=s,this.keyGenerationService=o,this.logoutCallback=a}setUsesKeyConnector(e){return this.stateService.setUsesKeyConnector(e)}getUsesKeyConnector(){return Zn(this,void 0,void 0,(function*(){return yield this.stateService.getUsesKeyConnector()}))}userNeedsMigration(){return Zn(this,void 0,void 0,(function*(){const e=yield this.tokenService.getIsExternal(),t=null!=(yield this.getManagingOrganization()),i=!(yield this.getUsesKeyConnector());return e&&t&&i}))}migrateUser(){return Zn(this,void 0,void 0,(function*(){const e=yield this.getManagingOrganization(),t=yield this.cryptoService.getMasterKey(),i=new Qn(t.encKeyB64);try{yield this.apiService.postUserKeyToKeyConnector(e.keyConnectorUrl,i)}catch(e){this.handleKeyConnectorError(e)}yield this.apiService.postConvertToKeyConnector()}))}setMasterKeyFromUrl(e){return Zn(this,void 0,void 0,(function*(){try{const t=yield this.apiService.getMasterKeyFromKeyConnector(e),i=p.fromB64ToArray(t.key),n=new N(i);yield this.cryptoService.setMasterKey(n)}catch(e){this.handleKeyConnectorError(e)}}))}getManagingOrganization(){return Zn(this,void 0,void 0,(function*(){return(yield this.organizationService.getAll()).find((e=>e.keyConnectorEnabled&&e.type!==Wi.Admin&&e.type!==Wi.Owner&&!e.isProviderUser))}))}convertNewSsoUserToKeyConnector(e,t){var i;return Zn(this,void 0,void 0,(function*(){const{kdf:n,kdfIterations:r,kdfMemory:s,kdfParallelism:o,keyConnectorUrl:a,userDecryptionOptions:l}=e,c=yield this.keyGenerationService.createKey(512),d=new P(r,s,o),u=yield this.cryptoService.makeMasterKey(c.keyB64,yield this.tokenService.getEmail(),n,d),h=new Qn(u.encKeyB64);yield this.cryptoService.setMasterKey(u);const p=yield this.cryptoService.makeUserKey(u);yield this.cryptoService.setUserKey(p[0]),yield this.cryptoService.setMasterKeyEncryptedUserKey(p[1].encryptedString);const[y,v]=yield this.cryptoService.makeKeyPair();try{const e=null!=a?a:null===(i=null==l?void 0:l.keyConnectorOption)||void 0===i?void 0:i.keyConnectorUrl;yield this.apiService.postUserKeyToKeyConnector(e,h)}catch(e){this.handleKeyConnectorError(e)}const f=new xe(y,v.encryptedString),g=new Xn(p[1].encryptedString,n,d,t,f);yield this.apiService.postSetKeyConnectorKey(g)}))}setConvertAccountRequired(e){return Zn(this,void 0,void 0,(function*(){yield this.stateService.setConvertAccountToKeyConnector(e)}))}getConvertAccountRequired(){return Zn(this,void 0,void 0,(function*(){return yield this.stateService.getConvertAccountToKeyConnector()}))}removeConvertAccountRequired(){return Zn(this,void 0,void 0,(function*(){yield this.stateService.setConvertAccountToKeyConnector(null)}))}clear(){return Zn(this,void 0,void 0,(function*(){yield this.removeConvertAccountRequired()}))}handleKeyConnectorError(e){throw this.logService.error(e),null!=this.logoutCallback&&this.logoutCallback(!1),new Error("Key Connector error")}}var tr=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const ir=new jt(ei,"ssoCodeVerifier",{deserializer:e=>e}),nr=new jt(ei,"ssoState",{deserializer:e=>e}),rr=new jt(ei,"organizationSsoIdentifier",{deserializer:e=>e}),sr=new jt(ei,"ssoEmail",{deserializer:e=>e});class or{constructor(e){this.stateProvider=e,this.codeVerifierState=this.stateProvider.getGlobal(ir),this.ssoState=this.stateProvider.getGlobal(nr),this.orgSsoIdentifierState=this.stateProvider.getGlobal(rr),this.ssoEmailState=this.stateProvider.getGlobal(sr),this.activeUserOrgSsoIdentifierState=this.stateProvider.getActive(rr)}getCodeVerifier(){return(0,r.z)(this.codeVerifierState.state$)}setCodeVerifier(e){return tr(this,void 0,void 0,(function*(){yield this.codeVerifierState.update((t=>e))}))}getSsoState(){return(0,r.z)(this.ssoState.state$)}setSsoState(e){return tr(this,void 0,void 0,(function*(){yield this.ssoState.update((t=>e))}))}getOrganizationSsoIdentifier(){return(0,r.z)(this.orgSsoIdentifierState.state$)}setOrganizationSsoIdentifier(e){return tr(this,void 0,void 0,(function*(){yield this.orgSsoIdentifierState.update((t=>e))}))}getSsoEmail(){return(0,r.z)(this.ssoEmailState.state$)}setSsoEmail(e){return tr(this,void 0,void 0,(function*(){yield this.ssoEmailState.update((t=>e))}))}getActiveUserOrganizationSsoIdentifier(){return(0,r.z)(this.activeUserOrgSsoIdentifierState.state$)}setActiveUserOrganizationSsoIdentifier(e){return tr(this,void 0,void 0,(function*(){yield this.activeUserOrgSsoIdentifierState.update((t=>e))}))}}var ar;!function(e){e.Lock="lock",e.LogOut="logOut"}(ar||(ar={}));const lr=new jt(ti,"accessToken",{deserializer:e=>e}),cr=new jt(ni,"accessToken",{deserializer:e=>e}),dr=new jt(ti,"refreshToken",{deserializer:e=>e}),ur=new jt(ni,"refreshToken",{deserializer:e=>e}),hr=new jt(ti,"refreshTokenMigratedToSecureStorage",{deserializer:e=>e}),pr=jt.record(ii,"emailTwoFactorTokenRecord",{deserializer:e=>e}),yr=new jt(ti,"apiKeyClientId",{deserializer:e=>e}),vr=new jt(ni,"apiKeyClientId",{deserializer:e=>e}),fr=new jt(ti,"apiKeyClientSecret",{deserializer:e=>e}),gr=new jt(ni,"apiKeyClientSecret",{deserializer:e=>e});var mr,wr=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};!function(e){e.Disk="disk",e.SecureStorage="secureStorage",e.Memory="memory"}(mr||(mr={}));class Sr{constructor(e,t,i,n,r,s,o){this.singleUserStateProvider=e,this.globalStateProvider=t,this.platformSupportsSecureStorage=i,this.secureStorageService=n,this.keyGenerationService=r,this.encryptService=s,this.logService=o,this.accessTokenKeySecureStorageKey="_accessTokenKey",this.refreshTokenSecureStorageKey="_refreshToken",this.initializeState()}initializeState(){this.emailTwoFactorTokenRecordGlobalState=this.globalStateProvider.get(pr),this.activeUserIdGlobalState=this.globalStateProvider.get(Un)}setTokens(e,t,i,n,r){return wr(this,void 0,void 0,(function*(){if(!e)throw new Error("Access token is required.");const s=yield this.getUserIdFromAccessToken(e);if(!s)throw new Error("User id not found. Cannot set tokens.");yield this._setAccessToken(e,t,i,s),n&&(yield this.setRefreshToken(n,t,i,s)),null!=r&&(yield this.setClientId(r[0],t,i,s),yield this.setClientSecret(r[1],t,i,s))}))}getAccessTokenKey(e){return wr(this,void 0,void 0,(function*(){const t=yield this.secureStorageService.get(`${e}${this.accessTokenKeySecureStorageKey}`,this.getSecureStorageOptions(e));if(!t)return null;return N.fromJSON(t)}))}createAndSaveAccessTokenKey(e){return wr(this,void 0,void 0,(function*(){const t=yield this.keyGenerationService.createKey(512);return yield this.secureStorageService.save(`${e}${this.accessTokenKeySecureStorageKey}`,t,this.getSecureStorageOptions(e)),t}))}clearAccessTokenKey(e){return wr(this,void 0,void 0,(function*(){yield this.secureStorageService.remove(`${e}${this.accessTokenKeySecureStorageKey}`,this.getSecureStorageOptions(e))}))}getOrCreateAccessTokenKey(e){return wr(this,void 0,void 0,(function*(){if(!this.platformSupportsSecureStorage)throw new Error("Platform does not support secure storage. Cannot obtain access token key.");if(!e)throw new Error("User id not found. Cannot obtain access token key.");let t=yield this.getAccessTokenKey(e);return t||(t=yield this.createAndSaveAccessTokenKey(e)),t}))}encryptAccessToken(e,t){return wr(this,void 0,void 0,(function*(){const i=yield this.getOrCreateAccessTokenKey(t);return yield this.encryptService.encrypt(e,i)}))}decryptAccessToken(e,t){return wr(this,void 0,void 0,(function*(){const i=yield this.getAccessTokenKey(t);if(!i)return null;return yield this.encryptService.decryptToUtf8(e,i)}))}_setAccessToken(e,t,i,n){return wr(this,void 0,void 0,(function*(){switch(yield this.determineStorageLocation(t,i,!0)){case mr.SecureStorage:{const t=yield this.encryptAccessToken(e,n);return yield this.singleUserStateProvider.get(n,lr).update((e=>t.encryptedString)),void(yield this.singleUserStateProvider.get(n,cr).update((e=>null)))}case mr.Disk:return void(yield this.singleUserStateProvider.get(n,lr).update((t=>e)));case mr.Memory:return void(yield this.singleUserStateProvider.get(n,cr).update((t=>e)))}}))}setAccessToken(e,t,i){return wr(this,void 0,void 0,(function*(){if(!e)throw new Error("Access token is required.");const n=yield this.getUserIdFromAccessToken(e);if(!n)throw new Error("User id not found. Cannot save access token.");yield this._setAccessToken(e,t,i,n)}))}clearAccessToken(e){return wr(this,void 0,void 0,(function*(){if(null!=e||(e=yield(0,r.z)(this.activeUserIdGlobalState.state$)),!e)throw new Error("User id not found. Cannot clear access token.");this.platformSupportsSecureStorage&&(yield this.clearAccessTokenKey(e)),yield this.singleUserStateProvider.get(e,lr).update((e=>null)),yield this.singleUserStateProvider.get(e,cr).update((e=>null))}))}getAccessToken(e){var t;return wr(this,void 0,void 0,(function*(){if(null!=e||(e=yield(0,r.z)(this.activeUserIdGlobalState.state$)),!e)return;const i=yield this.getStateValueByUserIdAndKeyDef(e,cr);if(null!=i)return i;const n=yield this.getStateValueByUserIdAndKeyDef(e,lr);if(!n)return null;if(this.platformSupportsSecureStorage){if(!(yield this.getAccessTokenKey(e)))return n;try{const t=new z(n);return yield this.decryptAccessToken(t,e)}catch(e){return this.logService.error(`Failed to decrypt access token: ${null!==(t=null==e?void 0:e.message)&&void 0!==t?t:"Unknown error."}`),null}}return n}))}setRefreshToken(e,t,i,n){return wr(this,void 0,void 0,(function*(){if(!n)throw new Error("User id not found. Cannot save refresh token.");switch(yield this.determineStorageLocation(t,i,!0)){case mr.SecureStorage:return yield this.saveStringToSecureStorage(n,this.refreshTokenSecureStorageKey,e),yield this.singleUserStateProvider.get(n,dr).update((e=>null)),yield this.singleUserStateProvider.get(n,ur).update((e=>null)),void(yield this.setRefreshTokenMigratedToSecureStorage(n));case mr.Disk:return void(yield this.singleUserStateProvider.get(n,dr).update((t=>e)));case mr.Memory:return void(yield this.singleUserStateProvider.get(n,ur).update((t=>e)))}}))}getRefreshToken(e){return wr(this,void 0,void 0,(function*(){if(null!=e||(e=yield(0,r.z)(this.activeUserIdGlobalState.state$)),!e)return;const t=yield this.getRefreshTokenMigratedToSecureStorage(e);if(this.platformSupportsSecureStorage&&t)return yield this.getStringFromSecureStorage(e,this.refreshTokenSecureStorageKey);const i=yield this.getStateValueByUserIdAndKeyDef(e,ur);if(null!=i)return i;const n=yield this.getStateValueByUserIdAndKeyDef(e,dr);return null!=n?n:null}))}clearRefreshToken(e){return wr(this,void 0,void 0,(function*(){if(!e)throw new Error("User id not found. Cannot clear refresh token.");this.platformSupportsSecureStorage&&(yield this.secureStorageService.remove(`${e}${this.refreshTokenSecureStorageKey}`,this.getSecureStorageOptions(e))),yield this.singleUserStateProvider.get(e,ur).update((e=>null)),yield this.singleUserStateProvider.get(e,dr).update((e=>null))}))}getRefreshTokenMigratedToSecureStorage(e){return wr(this,void 0,void 0,(function*(){return yield(0,r.z)(this.singleUserStateProvider.get(e,hr).state$)}))}setRefreshTokenMigratedToSecureStorage(e){return wr(this,void 0,void 0,(function*(){yield this.singleUserStateProvider.get(e,hr).update((e=>!0))}))}setClientId(e,t,i,n){return wr(this,void 0,void 0,(function*(){if(null!=n||(n=yield(0,r.z)(this.activeUserIdGlobalState.state$)),!n)throw new Error("User id not found. Cannot save client id.");const s=yield this.determineStorageLocation(t,i,!1);s===mr.Disk?yield this.singleUserStateProvider.get(n,yr).update((t=>e)):s===mr.Memory&&(yield this.singleUserStateProvider.get(n,vr).update((t=>e)))}))}getClientId(e){return wr(this,void 0,void 0,(function*(){if(null!=e||(e=yield(0,r.z)(this.activeUserIdGlobalState.state$)),!e)return;const t=yield this.getStateValueByUserIdAndKeyDef(e,vr);return null!=t?t:yield this.getStateValueByUserIdAndKeyDef(e,yr)}))}clearClientId(e){return wr(this,void 0,void 0,(function*(){if(null!=e||(e=yield(0,r.z)(this.activeUserIdGlobalState.state$)),!e)throw new Error("User id not found. Cannot clear client id.");yield this.singleUserStateProvider.get(e,vr).update((e=>null)),yield this.singleUserStateProvider.get(e,yr).update((e=>null))}))}setClientSecret(e,t,i,n){return wr(this,void 0,void 0,(function*(){if(null!=n||(n=yield(0,r.z)(this.activeUserIdGlobalState.state$)),!n)throw new Error("User id not found. Cannot save client secret.");const s=yield this.determineStorageLocation(t,i,!1);s===mr.Disk?yield this.singleUserStateProvider.get(n,fr).update((t=>e)):s===mr.Memory&&(yield this.singleUserStateProvider.get(n,gr).update((t=>e)))}))}getClientSecret(e){return wr(this,void 0,void 0,(function*(){if(null!=e||(e=yield(0,r.z)(this.activeUserIdGlobalState.state$)),!e)return;const t=yield this.getStateValueByUserIdAndKeyDef(e,gr);return null!=t?t:yield this.getStateValueByUserIdAndKeyDef(e,fr)}))}clearClientSecret(e){return wr(this,void 0,void 0,(function*(){if(null!=e||(e=yield(0,r.z)(this.activeUserIdGlobalState.state$)),!e)throw new Error("User id not found. Cannot clear client secret.");yield this.singleUserStateProvider.get(e,gr).update((e=>null)),yield this.singleUserStateProvider.get(e,fr).update((e=>null))}))}setTwoFactorToken(e,t){return wr(this,void 0,void 0,(function*(){yield this.emailTwoFactorTokenRecordGlobalState.update((i=>(null!=i||(i={}),i[e]=t,i)))}))}getTwoFactorToken(e){return wr(this,void 0,void 0,(function*(){const t=yield(0,r.z)(this.emailTwoFactorTokenRecordGlobalState.state$);return t?t[e]:null}))}clearTwoFactorToken(e){return wr(this,void 0,void 0,(function*(){yield this.emailTwoFactorTokenRecordGlobalState.update((t=>(null!=t||(t={}),delete t[e],t)))}))}clearTokens(e){return wr(this,void 0,void 0,(function*(){if(null!=e||(e=yield(0,r.z)(this.activeUserIdGlobalState.state$)),!e)throw new Error("User id not found. Cannot clear tokens.");yield Promise.all([this.clearAccessToken(e),this.clearRefreshToken(e),this.clearClientId(e),this.clearClientSecret(e)])}))}decodeAccessToken(e){return wr(this,void 0,void 0,(function*(){if(null==(e=null!=e?e:yield this.getAccessToken()))throw new Error("Access token not found.");return function(e){if(null==e)throw new Error("JWT token not found");const t=e.split(".");if(3!==t.length)throw new Error("JWT must have 3 parts");const i=t[1];let n;try{n=p.fromUrlB64ToUtf8(i)}catch(e){throw new Error("Cannot decode the token")}try{return JSON.parse(n)}catch(e){throw new Error("Cannot parse the token's payload into JSON")}}(e)}))}getTokenExpirationDate(){return wr(this,void 0,void 0,(function*(){let e;try{e=yield this.decodeAccessToken()}catch(e){throw new Error("Failed to decode access token: "+e.message)}if(!e||"number"!=typeof e.exp)return null;const t=new Date(0);return t.setUTCSeconds(e.exp),t}))}tokenSecondsRemaining(e=0){return wr(this,void 0,void 0,(function*(){const t=yield this.getTokenExpirationDate();if(null==t)return 0;const i=t.valueOf()-((new Date).valueOf()+1e3*e);return Math.round(i/1e3)}))}tokenNeedsRefresh(e=5){return wr(this,void 0,void 0,(function*(){return(yield this.tokenSecondsRemaining())<60*e}))}getUserId(){return wr(this,void 0,void 0,(function*(){let e;try{e=yield this.decodeAccessToken()}catch(e){throw new Error("Failed to decode access token: "+e.message)}if(!e||"string"!=typeof e.sub)throw new Error("No user id found");return e.sub}))}getUserIdFromAccessToken(e){return wr(this,void 0,void 0,(function*(){let t;try{t=yield this.decodeAccessToken(e)}catch(e){throw new Error("Failed to decode access token: "+e.message)}if(!t||"string"!=typeof t.sub)throw new Error("No user id found");return t.sub}))}getEmail(){return wr(this,void 0,void 0,(function*(){let e;try{e=yield this.decodeAccessToken()}catch(e){throw new Error("Failed to decode access token: "+e.message)}if(!e||"string"!=typeof e.email)throw new Error("No email found");return e.email}))}getEmailVerified(){return wr(this,void 0,void 0,(function*(){let e;try{e=yield this.decodeAccessToken()}catch(e){throw new Error("Failed to decode access token: "+e.message)}if(!e||"boolean"!=typeof e.email_verified)throw new Error("No email verification found");return e.email_verified}))}getName(){return wr(this,void 0,void 0,(function*(){let e;try{e=yield this.decodeAccessToken()}catch(e){throw new Error("Failed to decode access token: "+e.message)}return e&&"string"==typeof e.name?e.name:null}))}getIssuer(){return wr(this,void 0,void 0,(function*(){let e;try{e=yield this.decodeAccessToken()}catch(e){throw new Error("Failed to decode access token: "+e.message)}if(!e||"string"!=typeof e.iss)throw new Error("No issuer found");return e.iss}))}getIsExternal(){return wr(this,void 0,void 0,(function*(){let e;try{e=yield this.decodeAccessToken()}catch(e){throw new Error("Failed to decode access token: "+e.message)}return Array.isArray(e.amr)&&e.amr.includes("external")}))}getStateValueByUserIdAndKeyDef(e,t){return wr(this,void 0,void 0,(function*(){return yield(0,r.z)(this.singleUserStateProvider.get(e,t).state$)}))}determineStorageLocation(e,t,i){return wr(this,void 0,void 0,(function*(){return e===ar.LogOut&&null!=t?mr.Memory:i&&this.platformSupportsSecureStorage?mr.SecureStorage:mr.Disk}))}saveStringToSecureStorage(e,t,i){return wr(this,void 0,void 0,(function*(){yield this.secureStorageService.save(`${e}${t}`,i,this.getSecureStorageOptions(e))}))}getStringFromSecureStorage(e,t){return wr(this,void 0,void 0,(function*(){return yield this.secureStorageService.get(`${e}${t}`,this.getSecureStorageOptions(e))}))}getSecureStorageOptions(e){return{storageLocation:U.Disk,useSecureStorage:!0,userId:e}}}const br={[Q.Authenticator]:{type:Q.Authenticator,name:null,description:null,priority:1,sort:1,premium:!1},[Q.Yubikey]:{type:Q.Yubikey,name:null,description:null,priority:3,sort:2,premium:!0},[Q.Duo]:{type:Q.Duo,name:"Duo",description:null,priority:2,sort:3,premium:!0},[Q.OrganizationDuo]:{type:Q.OrganizationDuo,name:"Duo (Organization)",description:null,priority:10,sort:4,premium:!1},[Q.Email]:{type:Q.Email,name:null,description:null,priority:0,sort:6,premium:!1},[Q.WebAuthn]:{type:Q.WebAuthn,name:null,description:null,priority:4,sort:5,premium:!1}};class Pr{constructor(e,t){this.i18nService=e,this.platformUtilsService=t,this.selectedTwoFactorProviderType=null}init(){br[Q.Email].name=this.i18nService.t("emailTitle"),br[Q.Email].description=this.i18nService.t("emailDesc"),br[Q.Authenticator].name=this.i18nService.t("authenticatorAppTitle"),br[Q.Authenticator].description=this.i18nService.t("authenticatorAppDesc"),br[Q.Duo].description=this.i18nService.t("duoDesc"),br[Q.OrganizationDuo].name="Duo ("+this.i18nService.t("organization")+")",br[Q.OrganizationDuo].description=this.i18nService.t("duoOrganizationDesc"),br[Q.WebAuthn].name=this.i18nService.t("webAuthnTitle"),br[Q.WebAuthn].description=this.i18nService.t("webAuthnDesc"),br[Q.Yubikey].name=this.i18nService.t("yubiKeyTitle"),br[Q.Yubikey].description=this.i18nService.t("yubiKeyDesc")}getSupportedProviders(e){const t=[];return null==this.twoFactorProvidersData||(this.twoFactorProvidersData.has(Q.OrganizationDuo)&&this.platformUtilsService.supportsDuo()&&t.push(br[Q.OrganizationDuo]),this.twoFactorProvidersData.has(Q.Authenticator)&&t.push(br[Q.Authenticator]),this.twoFactorProvidersData.has(Q.Yubikey)&&t.push(br[Q.Yubikey]),this.twoFactorProvidersData.has(Q.Duo)&&this.platformUtilsService.supportsDuo()&&t.push(br[Q.Duo]),this.twoFactorProvidersData.has(Q.WebAuthn)&&this.platformUtilsService.supportsWebAuthn(e)&&t.push(br[Q.WebAuthn]),this.twoFactorProvidersData.has(Q.Email)&&t.push(br[Q.Email])),t}getDefaultProvider(e){if(null==this.twoFactorProvidersData)return null;if(null!=this.selectedTwoFactorProviderType&&this.twoFactorProvidersData.has(this.selectedTwoFactorProviderType))return this.selectedTwoFactorProviderType;let t=null,i=-1;return this.twoFactorProvidersData.forEach(((n,r)=>{const s=br[r];if(null!=s&&s.priority>i){if(r===Q.WebAuthn&&!e)return;t=r,i=s.priority}})),t}setSelectedProvider(e){this.selectedTwoFactorProviderType=e}clearSelectedProvider(){this.selectedTwoFactorProviderType=null}setProviders(e){this.twoFactorProvidersData=e.twoFactorProviders2}clearProviders(){this.twoFactorProvidersData=null}getProviders(){return this.twoFactorProvidersData}}var kr,Or=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Cr{constructor(e){this.apiService=e}postAccountVerifyOTP(e){return this.apiService.send("POST","/accounts/verify-otp",e,!0,!1)}postAccountRequestOTP(){return Or(this,void 0,void 0,(function*(){return this.apiService.send("POST","/accounts/request-otp",null,!0,!1)}))}}!function(e){e[e.MasterPassword=0]="MasterPassword",e[e.OTP=1]="OTP",e[e.PIN=2]="PIN",e[e.Biometrics=3]="Biometrics"}(kr||(kr={}));class Ar{constructor(e){this.OTP=e}}var Dr=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class xr{constructor(e,t,i,n,r,s,o,a,l){this.stateService=e,this.cryptoService=t,this.i18nService=i,this.userVerificationApiService=n,this.userDecryptionOptionsService=r,this.pinCryptoService=s,this.logService=o,this.vaultTimeoutSettingsService=a,this.platformUtilsService=l}getAvailableVerificationOptions(e){return Dr(this,void 0,void 0,(function*(){if("client"===e){const[e,t,i,n]=yield Promise.all([this.hasMasterPasswordAndMasterKeyHash(),this.vaultTimeoutSettingsService.isPinLockSet(),this.vaultTimeoutSettingsService.isBiometricLockSet(),this.cryptoService.hasUserKeyStored(x.Biometric)]);return{client:{masterPassword:e,pin:"DISABLED"!==t,biometrics:i&&(n||!this.platformUtilsService.supportsSecureStorage())},server:{masterPassword:!1,otp:!1}}}{const e=yield this.hasMasterPassword();return{client:{masterPassword:!1,pin:!1,biometrics:!1},server:{masterPassword:e,otp:!e}}}}))}buildRequest(e,t,i){return Dr(this,void 0,void 0,(function*(){this.validateSecretInput(e);const n=null!=t?new t:new Ln;if(e.type===kr.OTP)n.otp=e.secret;else{let t=yield this.cryptoService.getMasterKey();t||i||(t=yield this.cryptoService.makeMasterKey(e.secret,yield this.stateService.getEmail(),yield this.stateService.getKdfType(),yield this.stateService.getKdfConfig())),n.masterPasswordHash=i?e.secret:yield this.cryptoService.hashMasterKey(e.secret,t)}return n}))}verifyUser(e){return Dr(this,void 0,void 0,(function*(){switch(function(e){return"secret"in e}(e)&&this.validateSecretInput(e),e.type){case kr.OTP:return this.verifyUserByOTP(e);case kr.MasterPassword:return this.verifyUserByMasterPassword(e);case kr.PIN:return this.verifyUserByPIN(e);case kr.Biometrics:return this.verifyUserByBiometrics();default:return e}}))}verifyUserByOTP(e){return Dr(this,void 0,void 0,(function*(){const t=new Ar(e.secret);try{yield this.userVerificationApiService.postAccountVerifyOTP(t)}catch(e){throw new Error(this.i18nService.t("invalidVerificationCode"))}return!0}))}verifyUserByMasterPassword(e){return Dr(this,void 0,void 0,(function*(){let t=yield this.cryptoService.getMasterKey();t||(t=yield this.cryptoService.makeMasterKey(e.secret,yield this.stateService.getEmail(),yield this.stateService.getKdfType(),yield this.stateService.getKdfConfig()));if(!(yield this.cryptoService.compareAndUpdateKeyHash(e.secret,t)))throw new Error(this.i18nService.t("invalidMasterPassword"));return yield this.cryptoService.setMasterKey(t),!0}))}verifyUserByPIN(e){return Dr(this,void 0,void 0,(function*(){return null!=(yield this.pinCryptoService.decryptUserKeyWithPin(e.secret))}))}verifyUserByBiometrics(){return Dr(this,void 0,void 0,(function*(){let e;try{e=yield this.cryptoService.getUserKeyFromStorage(x.Biometric)}catch(e){return this.logService.error(`Biometrics User Verification failed: ${e.message}`),!1}return null!=e}))}requestOTP(){return Dr(this,void 0,void 0,(function*(){yield this.userVerificationApiService.postAccountRequestOTP()}))}hasMasterPassword(e){return Dr(this,void 0,void 0,(function*(){if(e){const t=yield(0,r.z)(this.userDecryptionOptionsService.userDecryptionOptionsById$(e));if(null!=(null==t?void 0:t.hasMasterPassword))return t.hasMasterPassword}return yield(0,r.z)(this.userDecryptionOptionsService.hasMasterPassword$)}))}hasMasterPasswordAndMasterKeyHash(e){return Dr(this,void 0,void 0,(function*(){return(yield this.hasMasterPassword(e))&&null!=(yield this.cryptoService.getMasterKeyHash())}))}validateSecretInput(e){if(null==(null==e?void 0:e.secret)||""===e.secret)switch(e.type){case kr.OTP:throw new Error(this.i18nService.t("verificationCodeRequired"));case kr.MasterPassword:throw new Error(this.i18nService.t("masterPasswordRequired"));case kr.PIN:throw new Error(this.i18nService.t("pinRequired"))}}}const Ir=null,Ur="autofill-card",Tr="autofill",Nr="autofill-identity",Rr="copy-identifier",Er="copy-password",Fr="copy-username",Mr="copy-totp",Kr="create-card",Lr="create-identity",zr="create-login",Vr="generate-password",Br="noop",_r="root",jr="separator",$r=15e4,Wr=0,qr=2;var Hr=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Gr=new jt(ci,"autofillOnPageLoad",{deserializer:e=>null!=e&&e}),Jr=new jt(ci,"autofillOnPageLoadDefault",{deserializer:e=>null!=e&&e}),Yr=new jt(ci,"autofillOnPageLoadCalloutIsDismissed",{deserializer:e=>null!=e&&e}),Qr=new jt(ci,"autofillOnPageLoadPolicyToastHasDisplayed",{deserializer:e=>null!=e&&e}),Xr=new jt(ci,"autoCopyTotp",{deserializer:e=>null==e||e}),Zr=new jt(di,"inlineMenuVisibility",{deserializer:e=>null!=e?e:Wr}),es=new jt(ci,"enableContextMenu",{deserializer:e=>null==e||e}),ts=new jt(di,"clearClipboardDelay",{deserializer:e=>null!=e?e:Ir});class is{constructor(e,t){this.stateProvider=e,this.policyService=t,this.autofillOnPageLoadState=this.stateProvider.getActive(Gr),this.autofillOnPageLoad$=this.autofillOnPageLoadState.state$.pipe((0,q.U)((e=>null!=e&&e))),this.autofillOnPageLoadDefaultState=this.stateProvider.getActive(Jr),this.autofillOnPageLoadDefault$=this.autofillOnPageLoadDefaultState.state$.pipe((0,q.U)((e=>null==e||e))),this.autofillOnPageLoadCalloutIsDismissedState=this.stateProvider.getActive(Yr),this.autofillOnPageLoadCalloutIsDismissed$=this.autofillOnPageLoadCalloutIsDismissedState.state$.pipe((0,q.U)((e=>null!=e&&e))),this.activateAutofillOnPageLoadFromPolicy$=this.policyService.policyAppliesToActiveUser$(qi.ActivateAutofill),this.autofillOnPageLoadPolicyToastHasDisplayedState=this.stateProvider.getActive(Qr),this.autofillOnPageLoadPolicyToastHasDisplayed$=this.autofillOnPageLoadState.state$.pipe((0,q.U)((e=>null!=e&&e))),this.autoCopyTotpState=this.stateProvider.getActive(Xr),this.autoCopyTotp$=this.autoCopyTotpState.state$.pipe((0,q.U)((e=>null==e||e))),this.inlineMenuVisibilityState=this.stateProvider.getGlobal(Zr),this.inlineMenuVisibility$=this.inlineMenuVisibilityState.state$.pipe((0,q.U)((e=>null!=e?e:Wr))),this.enableContextMenuState=this.stateProvider.getGlobal(es),this.enableContextMenu$=this.enableContextMenuState.state$.pipe((0,q.U)((e=>null==e||e))),this.clearClipboardDelayState=this.stateProvider.getActive(ts),this.clearClipboardDelay$=this.clearClipboardDelayState.state$.pipe((0,q.U)((e=>null!=e?e:Ir)))}setAutofillOnPageLoad(e){return Hr(this,void 0,void 0,(function*(){yield this.autofillOnPageLoadState.update((()=>e))}))}setAutofillOnPageLoadDefault(e){return Hr(this,void 0,void 0,(function*(){yield this.autofillOnPageLoadDefaultState.update((()=>e))}))}setAutofillOnPageLoadCalloutIsDismissed(e){return Hr(this,void 0,void 0,(function*(){yield this.autofillOnPageLoadCalloutIsDismissedState.update((()=>e))}))}setAutofillOnPageLoadPolicyToastHasDisplayed(e){return Hr(this,void 0,void 0,(function*(){yield this.autofillOnPageLoadPolicyToastHasDisplayedState.update((()=>e))}))}setAutoCopyTotp(e){return Hr(this,void 0,void 0,(function*(){yield this.autoCopyTotpState.update((()=>e))}))}setInlineMenuVisibility(e){return Hr(this,void 0,void 0,(function*(){yield this.inlineMenuVisibilityState.update((()=>e))}))}setEnableContextMenu(e){return Hr(this,void 0,void 0,(function*(){yield this.enableContextMenuState.update((()=>e))}))}setClearClipboardDelay(e){return Hr(this,void 0,void 0,(function*(){yield this.clearClipboardDelayState.update((()=>e))}))}}var ns=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const rs=new jt(oi,"enableBadgeCounter",{deserializer:e=>null==e||e});class ss{constructor(e){this.stateProvider=e,this.enableBadgeCounterState=this.stateProvider.getActive(rs),this.enableBadgeCounter$=this.enableBadgeCounterState.state$.pipe((0,q.U)((e=>null==e||e)))}setEnableBadgeCounter(e){return ns(this,void 0,void 0,(function*(){yield this.enableBadgeCounterState.update((()=>e))}))}}var os=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const as=new jt(li,"showFavicons",{deserializer:e=>null==e||e}),ls=new jt(li,"neverDomains",{deserializer:e=>null!=e?e:null}),cs=new qt(li,"equivalentDomains",{deserializer:e=>null!=e?e:null,clearOn:["logout"]}),ds=new jt(li,"defaultUriMatchStrategy",{deserializer:e=>null!=e?e:_e});class us{constructor(e){this.stateProvider=e,this.showFaviconsState=this.stateProvider.getGlobal(as),this.showFavicons$=this.showFaviconsState.state$.pipe((0,q.U)((e=>null==e||e))),this.neverDomainsState=this.stateProvider.getGlobal(ls),this.neverDomains$=this.neverDomainsState.state$.pipe((0,q.U)((e=>null!=e?e:null))),this.equivalentDomainsState=this.stateProvider.getActive(cs),this.equivalentDomains$=this.equivalentDomainsState.state$.pipe((0,q.U)((e=>null!=e?e:null))),this.defaultUriMatchStrategyState=this.stateProvider.getActive(ds),this.defaultUriMatchStrategy$=this.defaultUriMatchStrategyState.state$.pipe((0,q.U)((e=>null!=e?e:_e)))}setShowFavicons(e){return os(this,void 0,void 0,(function*(){yield this.showFaviconsState.update((()=>e))}))}setNeverDomains(e){return os(this,void 0,void 0,(function*(){yield this.neverDomainsState.update((()=>e))}))}setEquivalentDomains(e){return os(this,void 0,void 0,(function*(){yield this.equivalentDomainsState.update((()=>e))}))}setDefaultUriMatchStrategy(e){return os(this,void 0,void 0,(function*(){yield this.defaultUriMatchStrategyState.update((()=>e))}))}getUrlEquivalentDomains(e){return this.equivalentDomains$.pipe((0,q.U)((t=>{const i=p.getDomain(e);if(null==i||null==t)return new Set;const n=t.filter((e=>e.includes(i))).flat();return new Set(n)})))}}var hs=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const ps=new jt(ai,"enableAddedLoginPrompt",{deserializer:e=>null==e||e}),ys=new jt(ai,"enableChangedPasswordPrompt",{deserializer:e=>null==e||e});class vs{constructor(e){this.stateProvider=e,this.enableAddedLoginPromptState=this.stateProvider.getGlobal(ps),this.enableAddedLoginPrompt$=this.enableAddedLoginPromptState.state$.pipe((0,q.U)((e=>null==e||e))),this.enableChangedPasswordPromptState=this.stateProvider.getGlobal(ys),this.enableChangedPasswordPrompt$=this.enableChangedPasswordPromptState.state$.pipe((0,q.U)((e=>null==e||e)))}setEnableAddedLoginPrompt(e){return hs(this,void 0,void 0,(function*(){yield this.enableAddedLoginPromptState.update((()=>e))}))}setEnableChangedPasswordPrompt(e){return hs(this,void 0,void 0,(function*(){yield this.enableChangedPasswordPromptState.update((()=>e))}))}}var fs=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const gs=new jt(Qt,"accountProfile",{deserializer:e=>e});class ms{constructor(e){this.billingAccountProfileState=e.getActive(gs);const t=e.activeUserId$.pipe((0,c.w)((t=>null!=t?e.getUser(t,gs).state$:(0,l.of)(null))));this.hasPremiumFromAnyOrganization$=t.pipe((0,q.U)((e=>!!(null==e?void 0:e.hasPremiumFromAnyOrganization)))),this.hasPremiumPersonally$=t.pipe((0,q.U)((e=>!!(null==e?void 0:e.hasPremiumPersonally)))),this.hasPremiumFromAnySource$=t.pipe((0,q.U)((e=>!0===(null==e?void 0:e.hasPremiumFromAnyOrganization)||!0===(null==e?void 0:e.hasPremiumPersonally))))}setHasPremium(e,t){return fs(this,void 0,void 0,(function*(){yield this.billingAccountProfileState.update((i=>({hasPremiumPersonally:e,hasPremiumFromAnyOrganization:t})))}))}}class ws{}const Ss=new jt(hi,"biometricUnlockEnabled",{deserializer:e=>e}),bs=new jt(hi,"requirePasswordOnStart",{deserializer:e=>e}),Ps=new jt(hi,"clientKeyHalf",{deserializer:e=>e}),ks=new jt(hi,"dismissedBiometricRequirePasswordOnStartCallout",{deserializer:e=>e}),Os=jt.record(hi,"promptCancelled",{deserializer:e=>e}),Cs=new jt(hi,"promptAutomatically",{deserializer:e=>e}),As=new jt(hi,"fingerprintValidated",{deserializer:e=>e});var Ds=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class xs{constructor(e){this.stateProvider=e,this.biometricUnlockEnabledState=this.stateProvider.getActive(Ss),this.biometricUnlockEnabled$=this.biometricUnlockEnabledState.state$.pipe((0,q.U)(Boolean)),this.requirePasswordOnStartState=this.stateProvider.getActive(bs),this.requirePasswordOnStart$=this.requirePasswordOnStartState.state$.pipe((0,q.U)((e=>!!e))),this.encryptedClientKeyHalfState=this.stateProvider.getActive(Ps),this.encryptedClientKeyHalf$=this.encryptedClientKeyHalfState.state$.pipe((0,q.U)(Is)),this.dismissedRequirePasswordOnStartCalloutState=this.stateProvider.getActive(ks),this.dismissedRequirePasswordOnStartCallout$=this.dismissedRequirePasswordOnStartCalloutState.state$.pipe((0,q.U)(Boolean)),this.promptCancelledState=this.stateProvider.getGlobal(Os),this.promptCancelled$=(0,pn.a)([this.stateProvider.activeUserId$,this.promptCancelledState.state$]).pipe((0,q.U)((([e,t])=>{var i;return null!==(i=null==t?void 0:t[e])&&void 0!==i&&i}))),this.promptAutomaticallyState=this.stateProvider.getActive(Cs),this.promptAutomatically$=this.promptAutomaticallyState.state$.pipe((0,q.U)(Boolean)),this.fingerprintValidatedState=this.stateProvider.getGlobal(As),this.fingerprintValidated$=this.fingerprintValidatedState.state$.pipe((0,q.U)(Boolean))}setBiometricUnlockEnabled(e){return Ds(this,void 0,void 0,(function*(){yield this.biometricUnlockEnabledState.update((()=>e))}))}getBiometricUnlockEnabled(e){return Ds(this,void 0,void 0,(function*(){return yield(0,r.z)(this.stateProvider.getUser(e,Ss).state$.pipe((0,q.U)(Boolean)))}))}setRequirePasswordOnStart(e){return Ds(this,void 0,void 0,(function*(){let t;yield this.requirePasswordOnStartState.update(((i,[n])=>(t=n,e)),{combineLatestWith:this.requirePasswordOnStartState.combinedState$}),e||(yield this.removeEncryptedClientKeyHalf(t))}))}setEncryptedClientKeyHalf(e,t){var i;return Ds(this,void 0,void 0,(function*(){const n=null!==(i=null==e?void 0:e.encryptedString)&&void 0!==i?i:null;t?yield this.stateProvider.getUser(t,Ps).update((()=>n)):yield this.encryptedClientKeyHalfState.update((()=>n))}))}removeEncryptedClientKeyHalf(e){return Ds(this,void 0,void 0,(function*(){yield this.stateProvider.getUser(e,Ps).update((()=>null))}))}getRequirePasswordOnStart(e){return Ds(this,void 0,void 0,(function*(){return!!(yield(0,r.z)(this.stateProvider.getUser(e,bs).state$))}))}getEncryptedClientKeyHalf(e){return Ds(this,void 0,void 0,(function*(){return yield(0,r.z)(this.stateProvider.getUser(e,Ps).state$.pipe((0,q.U)(Is)))}))}logout(e){return Ds(this,void 0,void 0,(function*(){yield this.stateProvider.getUser(e,Ps).update((()=>null)),yield this.resetUserPromptCancelled(e)}))}setDismissedRequirePasswordOnStartCallout(){return Ds(this,void 0,void 0,(function*(){yield this.dismissedRequirePasswordOnStartCalloutState.update((()=>!0))}))}resetUserPromptCancelled(e){return Ds(this,void 0,void 0,(function*(){yield this.stateProvider.getGlobal(Os).update(((t,i)=>(delete t[null!=e?e:i],t)),{combineLatestWith:this.stateProvider.activeUserId$,shouldUpdate:(t,i)=>null!=(null==t?void 0:t[null!=e?e:i])})}))}setUserPromptCancelled(){return Ds(this,void 0,void 0,(function*(){yield this.promptCancelledState.update(((e,t)=>(null!=e||(e={}),e[t]=!0,e)),{combineLatestWith:this.stateProvider.activeUserId$,shouldUpdate:(e,t)=>{if(null==t)throw new Error("Cannot update biometric prompt cancelled state without an active user");return!0}})}))}resetAllPromptCancelled(){return Ds(this,void 0,void 0,(function*(){yield this.promptCancelledState.update((()=>null))}))}setPromptAutomatically(e){return Ds(this,void 0,void 0,(function*(){yield this.promptAutomaticallyState.update((()=>e))}))}setFingerprintValidated(e){return Ds(this,void 0,void 0,(function*(){yield this.fingerprintValidatedState.update((()=>e))}))}}function Is(e){return null==e?null:new z(e)}class Us{constructor(e){this.accountConstructor=e}create(e){return new this.accountConstructor(e)}}class Ts{constructor(e){this.globalStateConstructor=e}create(e){return new this.globalStateConstructor(e)}}class Ns{constructor(e,t){this.globalStateFactory=new Ts(e),this.accountFactory=new Us(t)}createGlobal(e){return this.globalStateFactory.create(e)}createAccount(e){return this.accountFactory.create(e)}}class Rs{constructor(){this.theme=T.System}}var Es=i(80060),Fs=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Ms=new jt(ui,"appId",{deserializer:e=>e}),Ks=new jt(ui,"anonymousAppId",{deserializer:e=>e});class Ls{constructor(e){const t=e.get(Ms),i=e.get(Ks);this.appId$=t.state$.pipe((0,Es.b)((e=>Fs(this,void 0,void 0,(function*(){e||(yield t.update((()=>p.newGuid())))})))),(0,_.h)((e=>!!e))),this.anonymousAppId$=i.state$.pipe((0,Es.b)((e=>Fs(this,void 0,void 0,(function*(){e||(yield i.update((()=>p.newGuid())))})))),(0,_.h)((e=>!!e)))}getAppId(){return Fs(this,void 0,void 0,(function*(){return yield(0,r.z)(this.appId$)}))}getAnonymousAppId(){return Fs(this,void 0,void 0,(function*(){return yield(0,r.z)(this.anonymousAppId$)}))}}class zs extends J{constructor(e){super(e),this.featureStates={},null!=e&&(this.version=this.getResponseProperty("Version"),this.gitHash=this.getResponseProperty("GitHash"),this.server=new Bs(this.getResponseProperty("Server")),this.environment=new Vs(this.getResponseProperty("Environment")),this.featureStates=this.getResponseProperty("FeatureStates"))}}class Vs extends J{constructor(e=null){super(e),null!=e&&(this.cloudRegion=this.getResponseProperty("CloudRegion"),this.vault=this.getResponseProperty("Vault"),this.api=this.getResponseProperty("Api"),this.identity=this.getResponseProperty("Identity"),this.notifications=this.getResponseProperty("Notifications"),this.sso=this.getResponseProperty("Sso"))}}class Bs extends J{constructor(e=null){super(e),null!=e&&(this.name=this.getResponseProperty("Name"),this.url=this.getResponseProperty("Url"))}}var _s=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class js{constructor(e,t){this.apiService=e,this.authService=t}get(){return _s(this,void 0,void 0,(function*(){const e=(yield this.authService.getAuthStatus())!==On.LoggedOut,t=yield this.apiService.send("GET","/config",null,e,!0);return new zs(t)}))}}class $s{constructor(e,t=null){this.isDev=e,this.filter=t,this.timersMap=new Map}debug(e){this.isDev&&this.write(I.Debug,e)}info(e){this.write(I.Info,e)}warning(e){this.write(I.Warning,e)}error(e){this.write(I.Error,e)}write(e,t){if(null==this.filter||!this.filter(e))switch(e){case I.Debug:case I.Info:console.log(t);break;case I.Warning:console.warn(t);break;case I.Error:console.error(t)}}}class Ws{constructor(e,t){this.cryptoService=e,this.encryptService=t}attachToGlobal(e){e.bitwardenContainerService||(e.bitwardenContainerService=this)}getCryptoService(){if(null==this.cryptoService)throw new Error("ContainerService.cryptoService not initialized.");return this.cryptoService}getEncryptService(){if(null==this.encryptService)throw new Error("ContainerService.encryptService not initialized.");return this.encryptService}}var qs=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Hs{constructor(e){this.buffer=e,this.encryptionType=null,this.dataBytes=null,this.ivBytes=null,this.macBytes=null;const t=e,i=t[0];switch(i){case f.AesCbc128_HmacSha256_B64:case f.AesCbc256_HmacSha256_B64:{const e=50;t.lengthnew so(e)))),e.fido2Credentials&&(this.fido2Credentials=null===(t=e.fido2Credentials)||void 0===t?void 0:t.map((e=>new ro(e)))))}}class ao{constructor(e){null!=e&&(this.password=e.password,this.lastUsedDate=e.lastUsedDate)}}class lo{constructor(e){null!=e&&(this.type=e.type)}}class co{constructor(e,t){if(null!=e){switch(this.id=e.id,this.organizationId=e.organizationId,this.folderId=e.folderId,this.edit=e.edit,this.viewPassword=e.viewPassword,this.organizationUseTotp=e.organizationUseTotp,this.favorite=e.favorite,this.revisionDate=e.revisionDate,this.type=e.type,this.name=e.name,this.notes=e.notes,this.collectionIds=null!=t?t:e.collectionIds,this.creationDate=e.creationDate,this.deletedDate=e.deletedDate,this.reprompt=e.reprompt,this.key=e.key,this.type){case Pe.Login:this.login=new oo(e.login);break;case Pe.SecureNote:this.secureNote=new lo(e.secureNote);break;case Pe.Card:this.card=new to(e.card);break;case Pe.Identity:this.identity=new no(e.identity)}null!=e.fields&&(this.fields=e.fields.map((e=>new io(e)))),null!=e.attachments&&(this.attachments=e.attachments.map((e=>new eo(e)))),null!=e.passwordHistory&&(this.passwordHistory=e.passwordHistory.map((e=>new ao(e))))}}}var uo=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class ho extends St{constructor(e){super(),null!=e&&(this.size=e.size,this.buildDomainModel(this,e,{id:null,url:null,sizeName:null,fileName:null,key:null},["id","url","sizeName"]))}decrypt(e,t){return uo(this,void 0,void 0,(function*(){const i=yield this.decryptObj(new Ue(this),{fileName:null},e,t);return null!=this.key&&(i.key=yield this.decryptAttachmentKey(e,t)),i}))}decryptAttachmentKey(e,t){return uo(this,void 0,void 0,(function*(){try{null==t&&(t=yield this.getKeyForDecryption(e));const i=p.getContainerService().getEncryptService(),n=yield i.decryptToBytes(this.key,t);return new N(n)}catch(e){}}))}getKeyForDecryption(e){return uo(this,void 0,void 0,(function*(){const t=p.getContainerService().getCryptoService();return null!=e?yield t.getOrgKey(e):yield t.getUserKeyWithLegacySupport()}))}toAttachmentData(){const e=new eo;return e.size=this.size,this.buildDataModel(this,e,{id:null,url:null,sizeName:null,fileName:null,key:null},["id","url","sizeName"]),e}static fromJSON(e){if(null==e)return null;const t=z.fromJSON(e.key),i=z.fromJSON(e.fileName);return Object.assign(new ho,e,{key:t,fileName:i})}}class po extends St{constructor(e){super(),null!=e&&this.buildDomainModel(this,e,{cardholderName:null,brand:null,number:null,expMonth:null,expYear:null,code:null},[])}decrypt(e,t){return this.decryptObj(new Me,{cardholderName:null,brand:null,number:null,expMonth:null,expYear:null,code:null},e,t)}toCardData(){const e=new to;return this.buildDataModel(this,e,{cardholderName:null,brand:null,number:null,expMonth:null,expYear:null,code:null}),e}static fromJSON(e){if(null==e)return null;const t=z.fromJSON(e.cardholderName),i=z.fromJSON(e.brand),n=z.fromJSON(e.number),r=z.fromJSON(e.expMonth),s=z.fromJSON(e.expYear),o=z.fromJSON(e.code);return Object.assign(new po,e,{cardholderName:t,brand:i,number:n,expMonth:r,expYear:s,code:o})}}class yo extends St{constructor(e){super(),null!=e&&(this.type=e.type,this.linkedId=e.linkedId,this.buildDomainModel(this,e,{name:null,value:null},[]))}decrypt(e,t){return this.decryptObj(new Ke(this),{name:null,value:null},e,t)}toFieldData(){const e=new io;return this.buildDataModel(this,e,{name:null,value:null,type:null,linkedId:null},["type","linkedId"]),e}static fromJSON(e){if(null==e)return null;const t=z.fromJSON(e.name),i=z.fromJSON(e.value);return Object.assign(new yo,e,{name:t,value:i})}}class vo extends St{constructor(e){super(),null!=e&&this.buildDomainModel(this,e,{title:null,firstName:null,middleName:null,lastName:null,address1:null,address2:null,address3:null,city:null,state:null,postalCode:null,country:null,company:null,email:null,phone:null,ssn:null,username:null,passportNumber:null,licenseNumber:null},[])}decrypt(e,t){return this.decryptObj(new Ve,{title:null,firstName:null,middleName:null,lastName:null,address1:null,address2:null,address3:null,city:null,state:null,postalCode:null,country:null,company:null,email:null,phone:null,ssn:null,username:null,passportNumber:null,licenseNumber:null},e,t)}toIdentityData(){const e=new no;return this.buildDataModel(this,e,{title:null,firstName:null,middleName:null,lastName:null,address1:null,address2:null,address3:null,city:null,state:null,postalCode:null,country:null,company:null,email:null,phone:null,ssn:null,username:null,passportNumber:null,licenseNumber:null}),e}static fromJSON(e){if(null==e)return null;const t=z.fromJSON(e.title),i=z.fromJSON(e.firstName),n=z.fromJSON(e.middleName),r=z.fromJSON(e.lastName),s=z.fromJSON(e.address1),o=z.fromJSON(e.address2),a=z.fromJSON(e.address3),l=z.fromJSON(e.city),c=z.fromJSON(e.state),d=z.fromJSON(e.postalCode),u=z.fromJSON(e.country),h=z.fromJSON(e.company),p=z.fromJSON(e.email),y=z.fromJSON(e.phone),v=z.fromJSON(e.ssn),f=z.fromJSON(e.username),g=z.fromJSON(e.passportNumber),m=z.fromJSON(e.licenseNumber);return Object.assign(new vo,e,{title:t,firstName:i,middleName:n,lastName:r,address1:s,address2:o,address3:a,city:l,state:c,postalCode:d,country:u,company:h,email:p,phone:y,ssn:v,username:f,passportNumber:g,licenseNumber:m})}}var fo=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class go extends St{constructor(e){super(),this.credentialId=null,null!=e&&(this.buildDomainModel(this,e,{credentialId:null,keyType:null,keyAlgorithm:null,keyCurve:null,keyValue:null,rpId:null,userHandle:null,userName:null,counter:null,rpName:null,userDisplayName:null,discoverable:null},[]),this.creationDate=null!=e.creationDate?new Date(e.creationDate):null)}decrypt(e,t){return fo(this,void 0,void 0,(function*(){const i=yield this.decryptObj(new Be,{credentialId:null,keyType:null,keyAlgorithm:null,keyCurve:null,keyValue:null,rpId:null,userHandle:null,userName:null,rpName:null,userDisplayName:null,discoverable:null},e,t),{counter:n}=yield this.decryptObj({counter:""},{counter:null},e,t);i.counter=parseInt(n);const{discoverable:r}=yield this.decryptObj({discoverable:""},{discoverable:null},e,t);return i.discoverable="true"===r,i.creationDate=this.creationDate,i}))}toFido2CredentialData(){const e=new ro;return e.creationDate=this.creationDate.toISOString(),this.buildDataModel(this,e,{credentialId:null,keyType:null,keyAlgorithm:null,keyCurve:null,keyValue:null,rpId:null,userHandle:null,userName:null,counter:null,rpName:null,userDisplayName:null,discoverable:null}),e}static fromJSON(e){if(null==e)return null;const t=z.fromJSON(e.credentialId),i=z.fromJSON(e.keyType),n=z.fromJSON(e.keyAlgorithm),r=z.fromJSON(e.keyCurve),s=z.fromJSON(e.keyValue),o=z.fromJSON(e.rpId),a=z.fromJSON(e.userHandle),l=z.fromJSON(e.userName),c=z.fromJSON(e.counter),d=z.fromJSON(e.rpName),u=z.fromJSON(e.userDisplayName),h=z.fromJSON(e.discoverable),p=null!=e.creationDate?new Date(e.creationDate):null;return Object.assign(new go,e,{credentialId:t,keyType:i,keyAlgorithm:n,keyCurve:r,keyValue:s,rpId:o,userHandle:a,userName:l,counter:c,rpName:d,userDisplayName:u,discoverable:h,creationDate:p})}}var mo=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class wo extends St{constructor(e){super(),null!=e&&(this.match=e.match,this.buildDomainModel(this,e,{uri:null,uriChecksum:null},[]))}decrypt(e,t){return this.decryptObj(new Ye(this),{uri:null},e,t)}validateChecksum(e,t,i){return mo(this,void 0,void 0,(function*(){if(null==this.uriChecksum)return!1;const n=p.getContainerService().getEncryptService(),r=yield n.hash(e,"sha256");return(yield this.uriChecksum.decrypt(t,i))===r}))}toLoginUriData(){const e=new so;return this.buildDataModel(this,e,{uri:null,uriChecksum:null,match:null},["match"]),e}static fromJSON(e){if(null==e)return null;const t=z.fromJSON(e.uri),i=z.fromJSON(e.uriChecksum);return Object.assign(new wo,e,{uri:t,uriChecksum:i})}}var So=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class bo extends St{constructor(e){super(),null!=e&&(this.passwordRevisionDate=null!=e.passwordRevisionDate?new Date(e.passwordRevisionDate):null,this.autofillOnPageLoad=e.autofillOnPageLoad,this.buildDomainModel(this,e,{username:null,password:null,totp:null},[]),e.uris&&(this.uris=[],e.uris.forEach((e=>{this.uris.push(new wo(e))}))),e.fido2Credentials&&(this.fido2Credentials=e.fido2Credentials.map((e=>new go(e)))))}decrypt(e,t,i){return So(this,void 0,void 0,(function*(){const n=yield this.decryptObj(new Ze(this),{username:null,password:null,totp:null},e,i);if(null!=this.uris){n.uris=[];for(let r=0;rt.decrypt(e,i))))),n}))}toLoginData(){const e=new oo;return e.passwordRevisionDate=null!=this.passwordRevisionDate?this.passwordRevisionDate.toISOString():null,e.autofillOnPageLoad=this.autofillOnPageLoad,this.buildDataModel(this,e,{username:null,password:null,totp:null}),null!=this.uris&&this.uris.length>0&&(e.uris=[],this.uris.forEach((t=>{e.uris.push(t.toLoginUriData())}))),null!=this.fido2Credentials&&this.fido2Credentials.length>0&&(e.fido2Credentials=this.fido2Credentials.map((e=>e.toFido2CredentialData()))),e}static fromJSON(e){var t,i,n;if(null==e)return null;const r=z.fromJSON(e.username),s=z.fromJSON(e.password),o=z.fromJSON(e.totp),a=null==e.passwordRevisionDate?null:new Date(e.passwordRevisionDate),l=null===(t=e.uris)||void 0===t?void 0:t.map((e=>wo.fromJSON(e))),c=null!==(n=null===(i=e.fido2Credentials)||void 0===i?void 0:i.map((e=>go.fromJSON(e))))&&void 0!==n?n:[];return Object.assign(new bo,e,{username:r,password:s,totp:o,passwordRevisionDate:a,uris:l,fido2Credentials:c})}}class Po extends St{constructor(e){super(),null!=e&&(this.buildDomainModel(this,e,{password:null}),this.lastUsedDate=new Date(e.lastUsedDate))}decrypt(e,t){return this.decryptObj(new et(this),{password:null},e,t)}toPasswordHistoryData(){const e=new ao;return e.lastUsedDate=this.lastUsedDate.toISOString(),this.buildDataModel(this,e,{password:null}),e}static fromJSON(e){if(null==e)return null;const t=z.fromJSON(e.password),i=null==e.lastUsedDate?null:new Date(e.lastUsedDate);return Object.assign(new Po,e,{password:t,lastUsedDate:i})}}class ko extends St{constructor(e){super(),null!=e&&(this.type=e.type)}decrypt(e,t){return Promise.resolve(new tt(this))}toSecureNoteData(){const e=new lo;return e.type=this.type,e}static fromJSON(e){return null==e?null:Object.assign(new ko,e)}}var Oo=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Co extends St{constructor(e,t=null){if(super(),this.initializerKey=Se.Cipher,null!=e){switch(this.buildDomainModel(this,e,{id:null,organizationId:null,folderId:null,name:null,notes:null,key:null},["id","organizationId","folderId"]),this.type=e.type,this.favorite=e.favorite,this.organizationUseTotp=e.organizationUseTotp,this.edit=e.edit,null!=e.viewPassword?this.viewPassword=e.viewPassword:this.viewPassword=!0,this.revisionDate=null!=e.revisionDate?new Date(e.revisionDate):null,this.collectionIds=e.collectionIds,this.localData=t,this.creationDate=null!=e.creationDate?new Date(e.creationDate):null,this.deletedDate=null!=e.deletedDate?new Date(e.deletedDate):null,this.reprompt=e.reprompt,this.type){case Pe.Login:this.login=new bo(e.login);break;case Pe.SecureNote:this.secureNote=new ko(e.secureNote);break;case Pe.Card:this.card=new po(e.card);break;case Pe.Identity:this.identity=new vo(e.identity)}null!=e.attachments?this.attachments=e.attachments.map((e=>new ho(e))):this.attachments=null,null!=e.fields?this.fields=e.fields.map((e=>new yo(e))):this.fields=null,null!=e.passwordHistory?this.passwordHistory=e.passwordHistory.map((e=>new Po(e))):this.passwordHistory=null}}decrypt(e){return Oo(this,void 0,void 0,(function*(){const t=new it(this);let i=!0;if(null!=this.key){const t=p.getContainerService().getEncryptService();e=new N(yield t.decryptToBytes(this.key,e)),i=!1}switch(yield this.decryptObj(t,{name:null,notes:null},this.organizationId,e),this.type){case Pe.Login:t.login=yield this.login.decrypt(this.organizationId,i,e);break;case Pe.SecureNote:t.secureNote=yield this.secureNote.decrypt(this.organizationId,e);break;case Pe.Card:t.card=yield this.card.decrypt(this.organizationId,e);break;case Pe.Identity:t.identity=yield this.identity.decrypt(this.organizationId,e)}if(null!=this.attachments&&this.attachments.length>0){const i=[];yield this.attachments.reduce(((t,n)=>t.then((()=>n.decrypt(this.organizationId,e))).then((e=>{i.push(e)}))),Promise.resolve()),t.attachments=i}if(null!=this.fields&&this.fields.length>0){const i=[];yield this.fields.reduce(((t,n)=>t.then((()=>n.decrypt(this.organizationId,e))).then((e=>{i.push(e)}))),Promise.resolve()),t.fields=i}if(null!=this.passwordHistory&&this.passwordHistory.length>0){const i=[];yield this.passwordHistory.reduce(((t,n)=>t.then((()=>n.decrypt(this.organizationId,e))).then((e=>{i.push(e)}))),Promise.resolve()),t.passwordHistory=i}return t}))}toCipherData(){var e;const t=new co;switch(t.id=this.id,t.organizationId=this.organizationId,t.folderId=this.folderId,t.edit=this.edit,t.viewPassword=this.viewPassword,t.organizationUseTotp=this.organizationUseTotp,t.favorite=this.favorite,t.revisionDate=null!=this.revisionDate?this.revisionDate.toISOString():null,t.type=this.type,t.collectionIds=this.collectionIds,t.creationDate=null!=this.creationDate?this.creationDate.toISOString():null,t.deletedDate=null!=this.deletedDate?this.deletedDate.toISOString():null,t.reprompt=this.reprompt,t.key=null===(e=this.key)||void 0===e?void 0:e.encryptedString,this.buildDataModel(this,t,{name:null,notes:null}),t.type){case Pe.Login:t.login=this.login.toLoginData();break;case Pe.SecureNote:t.secureNote=this.secureNote.toSecureNoteData();break;case Pe.Card:t.card=this.card.toCardData();break;case Pe.Identity:t.identity=this.identity.toIdentityData()}return null!=this.fields&&(t.fields=this.fields.map((e=>e.toFieldData()))),null!=this.attachments&&(t.attachments=this.attachments.map((e=>e.toAttachmentData()))),null!=this.passwordHistory&&(t.passwordHistory=this.passwordHistory.map((e=>e.toPasswordHistoryData()))),t}static fromJSON(e){var t,i,n;if(null==e)return null;const r=new Co,s=z.fromJSON(e.name),o=z.fromJSON(e.notes),a=null==e.revisionDate?null:new Date(e.revisionDate),l=null==e.deletedDate?null:new Date(e.deletedDate),c=null===(t=e.attachments)||void 0===t?void 0:t.map((e=>ho.fromJSON(e))),d=null===(i=e.fields)||void 0===i?void 0:i.map((e=>yo.fromJSON(e))),u=null===(n=e.passwordHistory)||void 0===n?void 0:n.map((e=>Po.fromJSON(e))),h=z.fromJSON(e.key);switch(Object.assign(r,e,{name:s,notes:o,revisionDate:a,deletedDate:l,attachments:c,fields:d,passwordHistory:u,key:h}),e.type){case Pe.Card:r.card=po.fromJSON(e.card);break;case Pe.Identity:r.identity=vo.fromJSON(e.identity);break;case Pe.Login:r.login=bo.fromJSON(e.login);break;case Pe.SecureNote:r.secureNote=ko.fromJSON(e.secureNote)}return r}}const Ao={[Se.Cipher]:Co.fromJSON,[Se.CipherView]:it.fromJSON};var Do=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class xo extends Ys{constructor(){super(...arguments),this.clear$=new Cn.x}decryptItems(e,t){var n;return Do(this,void 0,void 0,(function*(){if(null==e||e.length<1)return[];this.logService.info("Starting decryption using multithreading"),null!==(n=this.worker)&&void 0!==n||(this.worker=new Worker(new URL(i.p+i.u(768),i.b))),this.restartTimeout();const s={id:p.newGuid(),items:e,key:t};return this.worker.postMessage(JSON.stringify(s)),yield(0,r.z)((0,Qs.R)(this.worker,"message").pipe((0,_.h)((e=>{var t;return(null===(t=e.data)||void 0===t?void 0:t.id)===s.id})),(0,q.U)((e=>JSON.parse(e.data.items))),(0,q.U)((e=>e.map((e=>{var t;return(t=e.initializerKey,Ao[t])(e)})))),(0,Xs.R)(this.clear$),(0,Zs.d)([])))}))}clear(){var e;this.clear$.next(),null===(e=this.worker)||void 0===e||e.terminate(),this.worker=null,this.clearTimeout()}restartTimeout(){this.clearTimeout(),this.timeout=setTimeout((()=>this.clear()),18e4)}clearTimeout(){null!=this.timeout&&clearTimeout(this.timeout)}}var Io=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Uo{constructor(e){this.logService=e}upload(e,t,i){return Io(this,void 0,void 0,(function*(){return t.buffer.byteLength<=268435456?yield this.azureUploadBlob(e,t):yield this.azureUploadBlocks(e,t,i)}))}azureUploadBlob(e,t){return Io(this,void 0,void 0,(function*(){const i=p.getUrl(e),n=new Headers({"x-ms-date":(new Date).toUTCString(),"x-ms-version":i.searchParams.get("sv"),"Content-Length":t.buffer.byteLength.toString(),"x-ms-blob-type":"BlockBlob"}),r=new Request(e,{body:t.buffer,cache:"no-store",method:"PUT",headers:n}),s=yield fetch(r);if(201!==s.status)throw new Error(`Failed to create Azure blob: ${s.status}`)}))}azureUploadBlocks(e,t,i){return Io(this,void 0,void 0,(function*(){const n=p.getUrl(e),r=this.getMaxBlockSize(n.searchParams.get("sv"));let s=0;const o=Math.ceil(t.buffer.byteLength/r),a=[];if(o>5e4)throw new Error("Cannot upload file, exceeds maximum size of "+5e4*r);try{for(;s{t+=`${e}`})),t+="",t}getMaxBlockSize(e){return To.compare(e,"2019-12-12")>=0?4194304e3:To.compare(e,"2016-05-31")>=0?104857600:4194304}}class To{static compare(e,t){return"string"==typeof e&&(e=new To(e)),"string"==typeof t&&(t=new To(t)),e.year!==t.year?e.year-t.year:e.month!==t.month?e.month-t.month:e.day!==t.day?e.day-t.day:0}constructor(e){this.year=0,this.month=0,this.day=0;try{const t=e.split("-").map((e=>Number.parseInt(e,10)));this.year=t[0],this.month=t[1],this.day=t[2]}catch(e){}}compare(e){return To.compare(this,e)}}var No=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Ro{upload(e,t,i){return No(this,void 0,void 0,(function*(){const n=new FormData;try{const i=new Blob([t.buffer],{type:"application/octet-stream"});n.append("data",i,e)}catch(i){if(!p.isNode||p.isBrowser)throw i;n.append("data",Buffer.from(t.buffer),{filepath:e,contentType:"application/octet-stream"})}yield i(n)}))}}var Eo=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Fo{constructor(e){this.logService=e,this.azureFileUploadService=new Uo(e),this.bitwardenFileUploadService=new Ro}upload(e,t,i,n){return Eo(this,void 0,void 0,(function*(){try{switch(e.fileUploadType){case m.Direct:yield this.bitwardenFileUploadService.upload(t.encryptedString,i,(e=>n.postDirect(e)));break;case m.Azure:yield this.azureFileUploadService.upload(e.url,i,n.renewFileUploadUrl);break;default:throw new Error("Unknown file upload type")}}catch(e){throw yield n.rollback(),e}}))}}var Mo=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Ko{constructor(e){this.cryptoFunctionService=e}createKey(e){return Mo(this,void 0,void 0,(function*(){const t=yield this.cryptoFunctionService.aesGenerateKey(e);return new N(t)}))}createKeyWithPurpose(e,t,i){return Mo(this,void 0,void 0,(function*(){if(null==i){const e=yield this.cryptoFunctionService.randomBytes(32);i=p.fromBufferToUtf8(e)}const n=yield this.cryptoFunctionService.aesGenerateKey(e),r=yield this.cryptoFunctionService.hkdf(n,i,t,64,"sha256");return{salt:i,material:n,derivedKey:new N(r)}}))}deriveKeyFromMaterial(e,t,i){return Mo(this,void 0,void 0,(function*(){const n=yield this.cryptoFunctionService.hkdf(e,t,i,64,"sha256");return new N(n)}))}deriveKeyFromPassword(e,t,i,n){return Mo(this,void 0,void 0,(function*(){let r=null;if(null==i||i===b.PBKDF2_SHA256)null==n.iterations&&(n.iterations=D.defaultValue),r=yield this.cryptoFunctionService.pbkdf2(e,t,"sha256",n.iterations);else{if(i!=b.Argon2id)throw new Error("Unknown Kdf.");{null==n.iterations&&(n.iterations=A.defaultValue),null==n.memory&&(n.memory=O.defaultValue),null==n.parallelism&&(n.parallelism=C.defaultValue);const i=yield this.cryptoFunctionService.hash(t,"sha256");r=yield this.cryptoFunctionService.argon2(e,i,n.iterations,1024*n.memory,n.parallelism)}}return new N(r)}))}}class Lo{}class zo extends Lo{constructor(){super(...arguments),this.type=zo.TYPE}}zo.TYPE="MemoryStorageService";var Vo=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Bo extends zo{constructor(){super(...arguments),this.store=new Map,this.updatesSubject=new Cn.x}get valuesRequireDeserialization(){return!1}get updates$(){return this.updatesSubject.asObservable()}get(e){if(this.store.has(e)){const t=this.store.get(e);return Promise.resolve(t)}return Promise.resolve(null)}has(e){return Vo(this,void 0,void 0,(function*(){return null!=(yield this.get(e))}))}save(e,t){if(null==t)return this.remove(e);const i=structuredClone(t);return this.store.set(e,i),this.updatesSubject.next({key:e,updateType:"save"}),Promise.resolve()}remove(e){return this.store.delete(e),this.updatesSubject.next({key:e,updateType:"remove"}),Promise.resolve()}getBypassCache(e){return this.get(e)}}var _o=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class jo{static create(){return new jo([])}constructor(e){this.migrations=e}with(...e){return this.addMigrator(e,"up")}rollback(...e){return 3===e.length&&(e=[e[0],e[2],e[1]]),this.addMigrator(e,"down")}migrate(e){return this.migrations.reduce(((t,i)=>t.then((()=>_o(this,void 0,void 0,(function*(){yield this.runMigrator(i.migrator,e,i.direction)}))))),Promise.resolve())}addMigrator(e,t="up"){const i=1===e.length?{migrator:new e[0],direction:t}:{migrator:new e[0](e[1],e[2]),direction:t};return new jo([...this.migrations,i])}runMigrator(e,t,i){return _o(this,void 0,void 0,(function*(){const n=yield e.shouldMigrate(t,i);if(t.info(`Migrator ${e.constructor.name} (to version ${e.toVersion}) should migrate: ${n} - ${i}`),n){const n="up"===i?e.migrate:e.rollback;yield n.bind(e)(t),t.info(`Migrator ${e.constructor.name} (to version ${e.toVersion}) migrated - ${i}`),yield e.updateVersion(t,i),t.info(`Migrator ${e.constructor.name} (to version ${e.toVersion}) updated version - ${i}`)}}))}}var $o=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Wo=new Error("Irreversible migration");class qo{constructor(e,t){if(this.fromVersion=e,this.toVersion=t,null==e||null==t)throw new Error("Invalid migration");if(e>t)throw new Error("Invalid migration")}shouldMigrate(e,t){const i="up"===t?this.fromVersion:this.toVersion;return Promise.resolve(e.currentVersion===i)}updateVersion(e,t){return $o(this,void 0,void 0,(function*(){const i="up"===t?this.toVersion:this.fromVersion;e.currentVersion=i,yield e.set("stateVersion",i)}))}}var Ho=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Go={key:"everHadUserKey",stateDefinition:{name:"crypto"}};class Jo extends qo{migrate(e){return Ho(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return Ho(this,void 0,void 0,(function*(){const r=null===(n=null==i?void 0:i.profile)||void 0===n?void 0:n.everHadUserKey;yield e.setToUser(t,Go,null!=r&&r),null!=r&&delete i.profile.everHadUserKey,yield e.set(t,i)}))}(t,i)))])}))}rollback(e){return Ho(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return Ho(this,void 0,void 0,(function*(){const r=yield e.getFromUser(t,Go);i&&(i.profile=Object.assign(null!==(n=i.profile)&&void 0!==n?n:{},{everHadUserKey:r}),yield e.set(t,i)),yield e.setToUser(t,Go,null)}))}(t,i)))])}))}}var Yo=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Qo={key:"organizationKeys",stateDefinition:{name:"crypto"}};class Xo extends qo{migrate(e){return Yo(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n,r;return Yo(this,void 0,void 0,(function*(){const s=null===(r=null===(n=null==i?void 0:i.keys)||void 0===n?void 0:n.organizationKeys)||void 0===r?void 0:r.encrypted;null!=s&&(yield e.setToUser(t,Qo,s),delete i.keys.organizationKeys,yield e.set(t,i))}))}(t,i)))])}))}rollback(e){return Yo(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return Yo(this,void 0,void 0,(function*(){const r=yield e.getFromUser(t,Qo);i&&r&&(i.keys=Object.assign(null!==(n=i.keys)&&void 0!==n?n:{},{organizationKeys:{encrypted:r}}),yield e.set(t,i)),yield e.setToUser(t,Qo,null)}))}(t,i)))])}))}}var Zo=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const ea={name:"environment"},ta={key:"region",stateDefinition:ea},ia={key:"urls",stateDefinition:ea};class na extends qo{migrate(e){return Zo(this,void 0,void 0,(function*(){const t=yield e.get("global");null!=(null==t?void 0:t.region)&&(yield e.setToGlobal(ta,t.region)),null!=(null==t?void 0:t.environmentUrls)&&(yield e.setToGlobal(ia,t.environmentUrls));const i=yield e.getAccounts();yield Promise.all(i.map((({userId:t,account:i})=>Zo(this,void 0,void 0,(function*(){var n,r,s,o;null!=(null===(n=null==i?void 0:i.settings)||void 0===n?void 0:n.region)&&(yield e.setToUser(t,ta,i.settings.region)),null!=(null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.environmentUrls)&&(yield e.setToUser(t,ia,i.settings.environmentUrls)),null===(s=null==i?void 0:i.settings)||void 0===s||delete s.region,null===(o=null==i?void 0:i.settings)||void 0===o||delete o.environmentUrls,yield e.set(t,i)}))))),null==t||delete t.region,null==t||delete t.environmentUrls,yield e.set("global",t)}))}rollback(e){return Zo(this,void 0,void 0,(function*(){let t=yield e.get("global"),i=!1;const n=yield e.getFromGlobal(ta);n&&(t||(t={}),i=!0,t.region=n,yield e.setToGlobal(ta,null));const r=yield e.getFromGlobal(ia);r&&(t||(t={}),i=!0,t.environmentUrls=r,yield e.setToGlobal(ia,null)),i&&(yield e.set("global",t));const s=yield e.getAccounts();yield Promise.all(s.map((({userId:t,account:i})=>function(t,i){return Zo(this,void 0,void 0,(function*(){let n=!1;const r=yield e.getFromUser(t,ta);r&&(i||(i={}),i.settings||(i.settings={}),n=!0,i.settings.region=r,yield e.setToUser(t,ta,null));const s=yield e.getFromUser(t,ia);s&&(i||(i={}),i.settings||(i.settings={}),n=!0,i.settings.environmentUrls=s,yield e.setToUser(t,ia,null)),n&&(yield e.set(t,i))}))}(t,i))))}))}}var ra=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const sa={key:"providerKeys",stateDefinition:{name:"crypto"}};class oa extends qo{migrate(e){return ra(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n,r;return ra(this,void 0,void 0,(function*(){const s=null===(r=null===(n=null==i?void 0:i.keys)||void 0===n?void 0:n.providerKeys)||void 0===r?void 0:r.encrypted;null!=s&&(yield e.setToUser(t,sa,s),delete i.keys.providerKeys,yield e.set(t,i))}))}(t,i)))])}))}rollback(e){return ra(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return ra(this,void 0,void 0,(function*(){const r=yield e.getFromUser(t,sa);i&&r&&(i.keys=Object.assign(null!==(n=i.keys)&&void 0!==n?n:{},{providerKeys:{encrypted:r}}),yield e.set(t,i)),yield e.setToUser(t,sa,null)}))}(t,i)))])}))}}var aa=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const la={key:"clientKeyHalf",stateDefinition:{name:"biometricSettings"}};class ca extends qo{migrate(e){return aa(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>aa(this,void 0,void 0,(function*(){var n,r;null!=(null===(n=null==i?void 0:i.keys)||void 0===n?void 0:n.biometricEncryptionClientKeyHalf)&&(yield e.setToUser(t,la,i.keys.biometricEncryptionClientKeyHalf),null===(r=null==i?void 0:i.keys)||void 0===r||delete r.biometricEncryptionClientKeyHalf,yield e.set(t,i))})))))}))}rollback(e){return aa(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>function(t,i){var n;return aa(this,void 0,void 0,(function*(){let r=!1;const s=yield e.getFromUser(t,la);s&&(null!=i||(i={}),null!==(n=i.keys)&&void 0!==n||(i.keys={}),r=!0,i.keys.biometricEncryptionClientKeyHalf=s,yield e.setToUser(t,la,null)),r&&(yield e.set(t,i))}))}(t,i))))}))}}var da=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const ua={key:"folders",stateDefinition:{name:"folder"}};class ha extends qo{migrate(e){return da(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n,r;return da(this,void 0,void 0,(function*(){const s=null===(r=null===(n=null==i?void 0:i.data)||void 0===n?void 0:n.folders)||void 0===r?void 0:r.encrypted;null!=s&&(yield e.setToUser(t,ua,s),delete i.data.folders,yield e.set(t,i))}))}(t,i)))])}))}rollback(e){return da(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return da(this,void 0,void 0,(function*(){const r=yield e.getFromUser(t,ua);i&&(i.data=Object.assign(null!==(n=i.data)&&void 0!==n?n:{},{folders:{encrypted:r}}),yield e.set(t,i)),yield e.setToUser(t,ua,null)}))}(t,i)))])}))}}var pa=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const ya={key:"lastSync",stateDefinition:{name:"sync"}};class va extends qo{migrate(e){return pa(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return pa(this,void 0,void 0,(function*(){const r=null===(n=null==i?void 0:i.profile)||void 0===n?void 0:n.lastSync;yield e.setToUser(t,ya,null!=r?r:null),null!=r&&(delete i.profile.lastSync,yield e.set(t,i))}))}(t,i)))])}))}rollback(e){return pa(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return pa(this,void 0,void 0,(function*(){const r=yield e.getFromUser(t,ya);i&&(i.profile=Object.assign(null!==(n=i.profile)&&void 0!==n?n:{},{lastSync:r}),yield e.set(t,i)),yield e.setToUser(t,ya,null)}))}(t,i)))])}))}}var fa=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const ga={key:"enablePasskeys",stateDefinition:{name:"vaultSettings"}};class ma extends qo{migrate(e){return fa(this,void 0,void 0,(function*(){const t=yield e.get("global");null!=(null==t?void 0:t.enablePasskeys)&&(yield e.setToGlobal(ga,t.enablePasskeys),null==t||delete t.enablePasskeys,yield e.set("global",t))}))}rollback(e){return fa(this,void 0,void 0,(function*(){let t=yield e.get("global");const i=yield e.getFromGlobal(ga);null!=i&&(t=Object.assign(null!=t?t:{},{enablePasskeys:i}),yield e.set("global",t),yield e.setToGlobal(ga,void 0))}))}}var wa=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Sa={stateDefinition:{name:"autofillSettings"}};class ba extends qo{migrate(e){return wa(this,void 0,void 0,(function*(){const t=yield e.get("global");null!=(null==t?void 0:t.autoFillOverlayVisibility)&&(yield e.setToGlobal({stateDefinition:{name:"autofillSettingsLocal"},key:"inlineMenuVisibility"},t.autoFillOverlayVisibility),delete t.autoFillOverlayVisibility,yield e.set("global",t));const i=yield e.getAccounts();yield Promise.all([...i.map((({userId:t,account:i})=>function(t,i){return wa(this,void 0,void 0,(function*(){let n=!1;const r=null==i?void 0:i.settings;null!=(null==r?void 0:r.autoFillOnPageLoadDefault)&&(yield e.setToUser(t,Object.assign(Object.assign({},Sa),{key:"autofillOnPageLoadDefault"}),r.autoFillOnPageLoadDefault),delete i.settings.autoFillOnPageLoadDefault,n=!0),null!=(null==r?void 0:r.enableAutoFillOnPageLoad)&&(yield e.setToUser(t,Object.assign(Object.assign({},Sa),{key:"autofillOnPageLoad"}),null==r?void 0:r.enableAutoFillOnPageLoad),delete i.settings.enableAutoFillOnPageLoad,n=!0),null!=(null==r?void 0:r.dismissedAutoFillOnPageLoadCallout)&&(yield e.setToUser(t,Object.assign(Object.assign({},Sa),{key:"autofillOnPageLoadCalloutIsDismissed"}),null==r?void 0:r.dismissedAutoFillOnPageLoadCallout),delete i.settings.dismissedAutoFillOnPageLoadCallout,n=!0),null!=(null==r?void 0:r.disableAutoTotpCopy)&&(yield e.setToUser(t,Object.assign(Object.assign({},Sa),{key:"autoCopyTotp"}),!(null==r?void 0:r.disableAutoTotpCopy)),delete i.settings.disableAutoTotpCopy,n=!0),null!=(null==r?void 0:r.activateAutoFillOnPageLoadFromPolicy)&&(yield e.setToUser(t,{stateDefinition:{name:"autofillSettingsLocal"},key:"activateAutofillOnPageLoadFromPolicy"},null==r?void 0:r.activateAutoFillOnPageLoadFromPolicy),delete i.settings.activateAutoFillOnPageLoadFromPolicy,n=!0),n&&(yield e.set(t,i))}))}(t,i)))])}))}rollback(e){return wa(this,void 0,void 0,(function*(){const t=(yield e.get("global"))||{},i=yield e.getFromGlobal({stateDefinition:{name:"autofillSettingsLocal"},key:"inlineMenuVisibility"});i&&(yield e.set("global",Object.assign(Object.assign({},t),{autoFillOverlayVisibility:i})),yield e.setToGlobal({stateDefinition:{name:"autofillSettingsLocal"},key:"inlineMenuVisibility"},null));const n=yield e.getAccounts();yield Promise.all([...n.map((({userId:t,account:i})=>function(t,i){return wa(this,void 0,void 0,(function*(){let n=!1,r=(null==i?void 0:i.settings)||{};const s=yield e.getFromUser(t,Object.assign(Object.assign({},Sa),{key:"autofillOnPageLoadDefault"})),o=yield e.getFromUser(t,Object.assign(Object.assign({},Sa),{key:"autofillOnPageLoad"})),a=yield e.getFromUser(t,Object.assign(Object.assign({},Sa),{key:"autofillOnPageLoadCalloutIsDismissed"})),l=yield e.getFromUser(t,Object.assign(Object.assign({},Sa),{key:"autoCopyTotp"})),c=yield e.getFromUser(t,{stateDefinition:{name:"autofillSettingsLocal"},key:"activateAutofillOnPageLoadFromPolicy"});null!=s&&(r=Object.assign(Object.assign({},r),{autoFillOnPageLoadDefault:s}),yield e.setToUser(t,Object.assign(Object.assign({},Sa),{key:"autofillOnPageLoadDefault"}),null),n=!0),null!=o&&(r=Object.assign(Object.assign({},r),{enableAutoFillOnPageLoad:o}),yield e.setToUser(t,Object.assign(Object.assign({},Sa),{key:"autofillOnPageLoad"}),null),n=!0),null!=a&&(r=Object.assign(Object.assign({},r),{dismissedAutoFillOnPageLoadCallout:a}),yield e.setToUser(t,Object.assign(Object.assign({},Sa),{key:"autofillOnPageLoadCalloutIsDismissed"}),null),n=!0),null!=l&&(r=Object.assign(Object.assign({},r),{disableAutoTotpCopy:!l}),yield e.setToUser(t,Object.assign(Object.assign({},Sa),{key:"autoCopyTotp"}),null),n=!0),null!=c&&(r=Object.assign(Object.assign({},r),{activateAutoFillOnPageLoadFromPolicy:c}),yield e.setToUser(t,{stateDefinition:{name:"autofillSettingsLocal"},key:"activateAutofillOnPageLoadFromPolicy"},null),n=!0),n&&(yield e.set(t,Object.assign(Object.assign({},i),{settings:r})))}))}(t,i)))])}))}}var Pa=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const ka={key:"requirePasswordOnStart",stateDefinition:{name:"biometricSettings"}};class Oa extends qo{migrate(e){return Pa(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>Pa(this,void 0,void 0,(function*(){var n;null!=(null===(n=null==i?void 0:i.settings)||void 0===n?void 0:n.requirePasswordOnStart)&&(yield e.setToUser(t,ka,i.settings.requirePasswordOnStart),delete i.settings.requirePasswordOnStart,yield e.set(t,i))})))))}))}rollback(e){return Pa(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>function(t,i){var n;return Pa(this,void 0,void 0,(function*(){const r=yield e.getFromUser(t,ka);r&&(null!=i||(i={}),null!==(n=i.settings)&&void 0!==n||(i.settings={}),i.settings.requirePasswordOnStart=r,yield e.setToUser(t,ka,null),yield e.set(t,i))}))}(t,i))))}))}}var Ca=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Aa={key:"privateKey",stateDefinition:{name:"crypto"}};class Da extends qo{migrate(e){return Ca(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n,r;return Ca(this,void 0,void 0,(function*(){const s=null===(r=null===(n=null==i?void 0:i.keys)||void 0===n?void 0:n.privateKey)||void 0===r?void 0:r.encrypted;null!=s&&(yield e.setToUser(t,Aa,s),delete i.keys.privateKey,yield e.set(t,i))}))}(t,i)))])}))}rollback(e){return Ca(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return Ca(this,void 0,void 0,(function*(){const r=yield e.getFromUser(t,Aa);i&&r&&(i.keys=Object.assign(null!==(n=i.keys)&&void 0!==n?n:{},{privateKey:{encrypted:r}}),yield e.set(t,i)),yield e.setToUser(t,Aa,null)}))}(t,i)))])}))}}var xa=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Ia={key:"collections",stateDefinition:{name:"collection"}};class Ua extends qo{migrate(e){return xa(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n,r;return xa(this,void 0,void 0,(function*(){const s=null===(r=null===(n=null==i?void 0:i.data)||void 0===n?void 0:n.collections)||void 0===r?void 0:r.encrypted;null!=s&&(yield e.setToUser(t,Ia,s),delete i.data.collections,yield e.set(t,i))}))}(t,i)))])}))}rollback(e){return xa(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return xa(this,void 0,void 0,(function*(){const r=yield e.getFromUser(t,Ia);i&&(i.data=Object.assign(null!==(n=i.data)&&void 0!==n?n:{},{collections:{encrypted:r}}),yield e.set(t,i)),yield e.setToUser(t,Ia,null)}))}(t,i)))])}))}}var Ta=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Na={key:"collapsedGroupings",stateDefinition:{name:"vaultFilter"}};class Ra extends qo{migrate(e){return Ta(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return Ta(this,void 0,void 0,(function*(){const r=null===(n=null==i?void 0:i.settings)||void 0===n?void 0:n.collapsedGroupings;null!=r&&(yield e.setToUser(t,Na,r),delete i.settings.collapsedGroupings,yield e.set(t,i))}))}(t,i)))])}))}rollback(e){return Ta(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return Ta(this,void 0,void 0,(function*(){const r=yield e.getFromUser(t,Na);i&&(i.settings=Object.assign(null!==(n=i.settings)&&void 0!==n?n:{},{collapsedGroupings:r}),yield e.set(t,i)),yield e.setToUser(t,Na,null)}))}(t,i)))])}))}}var Ea=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Fa={key:"dismissedBiometricRequirePasswordOnStartCallout",stateDefinition:{name:"biometricSettings"}},Ma={key:"promptAutomatically",stateDefinition:{name:"biometricSettings"}};class Ka extends qo{migrate(e){return Ea(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>Ea(this,void 0,void 0,(function*(){var n,r,s,o;null!=i&&(null!=(null===(n=null==i?void 0:i.settings)||void 0===n?void 0:n.dismissedBiometricRequirePasswordOnStartCallout)&&(yield e.setToUser(t,Fa,i.settings.dismissedBiometricRequirePasswordOnStartCallout)),null!=(null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.disableAutoBiometricsPrompt)&&(yield e.setToUser(t,Ma,!i.settings.disableAutoBiometricsPrompt)),null===(s=null==i?void 0:i.settings)||void 0===s||delete s.dismissedBiometricRequirePasswordOnStartCallout,null===(o=null==i?void 0:i.settings)||void 0===o||delete o.disableAutoBiometricsPrompt,yield e.set(t,i))})))))}))}rollback(e){return Ea(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>function(t,i){var n,r;return Ea(this,void 0,void 0,(function*(){let s=!1;const o=yield e.getFromUser(t,Fa);o&&(null!=i||(i={}),null!==(n=i.settings)&&void 0!==n||(i.settings={}),s=!0,i.settings.dismissedBiometricRequirePasswordOnStartCallout=o,yield e.setToUser(t,Fa,null));const a=yield e.getFromUser(t,Ma);null!=a&&(null!=i||(i={}),null!==(r=i.settings)&&void 0!==r||(i.settings={}),s=!0,i.settings.disableAutoBiometricsPrompt=!a,yield e.setToUser(t,Ma,null)),s&&(yield e.set(t,i))}))}(t,i))))}))}}var La=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const za={key:"tasks",stateDefinition:{name:"smOnboarding"}};class Va extends qo{migrate(e){return La(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>La(this,void 0,void 0,(function*(){var n;null!=(null===(n=null==i?void 0:i.settings)||void 0===n?void 0:n.smOnboardingTasks)&&(yield e.setToUser(t,za,i.settings.smOnboardingTasks),delete i.settings.smOnboardingTasks,yield e.set(t,i))})))))}))}rollback(e){return La(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>function(t,i){var n;return La(this,void 0,void 0,(function*(){const r=yield e.getFromUser(t,za);r&&(null!=i||(i={}),null!==(n=i.settings)&&void 0!==n||(i.settings={}),i.settings.smOnboardingTasks=r,yield e.setToUser(t,za,null),yield e.set(t,i))}))}(t,i))))}))}}var Ba=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const _a={stateDefinition:{name:"autofillSettingsLocal"}};class ja extends qo{migrate(e){return Ba(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){return Ba(this,void 0,void 0,(function*(){const n=null==i?void 0:i.settings;void 0!==(null==n?void 0:n.clearClipboard)&&(yield e.setToUser(t,Object.assign(Object.assign({},_a),{key:"clearClipboardDelay"}),n.clearClipboard),delete i.settings.clearClipboard,yield e.set(t,i))}))}(t,i)))])}))}rollback(e){return Ba(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){return Ba(this,void 0,void 0,(function*(){let n=(null==i?void 0:i.settings)||{};const r=yield e.getFromUser(t,Object.assign(Object.assign({},_a),{key:"clearClipboardDelay"}));void 0!==r&&(n=Object.assign(Object.assign({},n),{clearClipboard:r}),yield e.setToUser(t,Object.assign(Object.assign({},_a),{key:"clearClipboardDelay"}),null),yield e.set(t,Object.assign(Object.assign({},i),{settings:n})))}))}(t,i)))])}))}}var $a=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Wa={key:"lastSync",stateDefinition:{name:"sync"}};class qa extends qo{rollback(e){return $a(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return $a(this,void 0,void 0,(function*(){const r=null===(n=null==i?void 0:i.profile)||void 0===n?void 0:n.lastSync;yield e.setToUser(t,Wa,null!=r?r:null),null!=r&&(delete i.profile.lastSync,yield e.set(t,i))}))}(t,i)))])}))}migrate(e){return $a(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return $a(this,void 0,void 0,(function*(){const r=yield e.getFromUser(t,Wa);i&&(i.profile=Object.assign(null!==(n=i.profile)&&void 0!==n?n:{},{lastSync:r}),yield e.set(t,i)),yield e.setToUser(t,Wa,null)}))}(t,i)))])}))}}var Ha=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Ga={stateDefinition:{name:"badgeSettings"},key:"enableBadgeCounter"};class Ja extends qo{migrate(e){return Ha(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){return Ha(this,void 0,void 0,(function*(){const n=null==i?void 0:i.settings;null!=(null==n?void 0:n.disableBadgeCounter)&&(yield e.setToUser(t,Ga,!n.disableBadgeCounter),delete i.settings.disableBadgeCounter,yield e.set(t,i))}))}(t,i)))])}))}rollback(e){return Ha(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){return Ha(this,void 0,void 0,(function*(){let n=(null==i?void 0:i.settings)||{};const r=yield e.getFromUser(t,Ga);null!=r&&(n=Object.assign(Object.assign({},n),{disableBadgeCounter:!r}),yield e.setToUser(t,Ga,null),yield e.set(t,Object.assign(Object.assign({},i),{settings:n})))}))}(t,i)))])}))}}var Ya=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Qa={key:"biometricUnlockEnabled",stateDefinition:{name:"biometricSettings"}};class Xa extends qo{migrate(e){return Ya(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>Ya(this,void 0,void 0,(function*(){var n,r;null!=i&&(null!=(null===(n=null==i?void 0:i.settings)||void 0===n?void 0:n.biometricUnlock)&&(yield e.setToUser(t,Qa,i.settings.biometricUnlock)),null===(r=null==i?void 0:i.settings)||void 0===r||delete r.biometricUnlock,yield e.set(t,i))})))))}))}rollback(e){return Ya(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>function(t,i){var n;return Ya(this,void 0,void 0,(function*(){const r=yield e.getFromUser(t,Qa);null!=r&&(null!=i||(i={}),null!==(n=i.settings)&&void 0!==n||(i.settings={}),i.settings.biometricUnlock=r,yield e.setToUser(t,Qa,null),yield e.set(t,i))}))}(t,i))))}))}}var Za=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class el extends qo{migrate(e){return Za(this,void 0,void 0,(function*(){const t=yield e.get("global");null!=(null==t?void 0:t.disableAddLoginNotification)&&(yield e.setToGlobal({stateDefinition:{name:"userNotificationSettings"},key:"enableAddedLoginPrompt"},!t.disableAddLoginNotification),delete t.disableAddLoginNotification,yield e.set("global",t)),null!=(null==t?void 0:t.disableChangedPasswordNotification)&&(yield e.setToGlobal({stateDefinition:{name:"userNotificationSettings"},key:"enableChangedPasswordPrompt"},!t.disableChangedPasswordNotification),delete t.disableChangedPasswordNotification,yield e.set("global",t))}))}rollback(e){return Za(this,void 0,void 0,(function*(){const t=(yield e.get("global"))||{},i=yield e.getFromGlobal({stateDefinition:{name:"userNotificationSettings"},key:"enableAddedLoginPrompt"}),n=yield e.getFromGlobal({stateDefinition:{name:"userNotificationSettings"},key:"enableChangedPasswordPrompt"});i&&(yield e.set("global",Object.assign(Object.assign({},t),{disableAddLoginNotification:!i})),yield e.setToGlobal({stateDefinition:{name:"userNotificationSettings"},key:"enableAddedLoginPrompt"},null)),n&&(yield e.set("global",Object.assign(Object.assign({},t),{disableChangedPasswordNotification:!n})),yield e.setToGlobal({stateDefinition:{name:"userNotificationSettings"},key:"enableChangedPasswordPrompt"},null))}))}}var tl,il=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};!function(e){e[e.TwoFactorAuthentication=0]="TwoFactorAuthentication",e[e.MasterPassword=1]="MasterPassword",e[e.PasswordGenerator=2]="PasswordGenerator",e[e.SingleOrg=3]="SingleOrg",e[e.RequireSso=4]="RequireSso",e[e.PersonalOwnership=5]="PersonalOwnership",e[e.DisableSend=6]="DisableSend",e[e.SendOptions=7]="SendOptions",e[e.ResetPassword=8]="ResetPassword",e[e.MaximumVaultTimeout=9]="MaximumVaultTimeout",e[e.DisablePersonalVaultExport=10]="DisablePersonalVaultExport",e[e.ActivateAutofill=11]="ActivateAutofill"}(tl||(tl={}));const nl={key:"policies",stateDefinition:{name:"policies"}};class rl extends qo{migrate(e){return il(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>function(t,i){var n,r;return il(this,void 0,void 0,(function*(){const s=null===(r=null===(n=null==i?void 0:i.data)||void 0===n?void 0:n.policies)||void 0===r?void 0:r.encrypted;null!=s&&(yield e.setToUser(t,nl,s),delete i.data.policies,yield e.set(t,i))}))}(t,i))))}))}rollback(e){return il(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>function(t,i){var n;return il(this,void 0,void 0,(function*(){const r=yield e.getFromUser(t,nl);i&&(i.data=Object.assign(null!==(n=i.data)&&void 0!==n?n:{},{policies:{encrypted:r}}),yield e.set(t,i)),yield e.setToUser(t,nl,null)}))}(t,i))))}))}}var sl=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const ol={stateDefinition:{name:"autofillSettings"},key:"enableContextMenu"};class al extends qo{migrate(e){return sl(this,void 0,void 0,(function*(){const t=yield e.get("global");null!=(null==t?void 0:t.disableContextMenuItem)&&(yield e.setToGlobal(ol,!t.disableContextMenuItem),delete t.disableContextMenuItem,yield e.set("global",t))}))}rollback(e){return sl(this,void 0,void 0,(function*(){const t=(yield e.get("global"))||{},i=yield e.getFromGlobal(ol);null!=i&&(yield e.set("global",Object.assign(Object.assign({},t),{disableContextMenuItem:!i})),yield e.setToGlobal(ol,null))}))}}var ll=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const cl={key:"locale",stateDefinition:{name:"translation"}};class dl extends qo{migrate(e){return ll(this,void 0,void 0,(function*(){const t=yield e.get("global");(null==t?void 0:t.locale)&&(yield e.setToGlobal(cl,t.locale),delete t.locale,yield e.set("global",t))}))}rollback(e){var t;return ll(this,void 0,void 0,(function*(){const i=yield e.getFromGlobal(cl);if(!i)return;const n=null!==(t=yield e.get("global"))&&void 0!==t?t:{};n.locale=i,yield e.set("global",n),yield e.setToGlobal(cl,null)}))}}var ul=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const hl="appId",pl="anonymousAppId",yl={key:hl,stateDefinition:{name:"applicationId"}},vl={key:pl,stateDefinition:{name:"applicationId"}};class fl extends qo{migrate(e){return ul(this,void 0,void 0,(function*(){const t=yield e.get(hl),i=yield e.get(pl);null!=t&&(yield e.setToGlobal(yl,t),yield e.set(hl,null)),null!=i&&(yield e.setToGlobal(vl,i),yield e.set(pl,null))}))}rollback(e){return ul(this,void 0,void 0,(function*(){const t=yield e.getFromGlobal(yl),i=yield e.getFromGlobal(vl);null!=t&&(yield e.set(hl,t),yield e.setToGlobal(yl,null)),null!=i&&(yield e.set(pl,i),yield e.setToGlobal(vl,null))}))}}var gl=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const ml={stateDefinition:{name:"domainSettings"},key:"defaultUriMatchStrategy"},wl={stateDefinition:{name:"domainSettings"},key:"equivalentDomains"},Sl={stateDefinition:{name:"domainSettings"},key:"neverDomains"};class bl extends qo{migrate(e){return gl(this,void 0,void 0,(function*(){let t=!1;const i=yield e.get("global");null!=(null==i?void 0:i.neverDomains)&&(yield e.setToGlobal(Sl,i.neverDomains),delete i.neverDomains,yield e.set("global",i));const n=yield e.getAccounts();yield Promise.all([...n.map((({userId:i,account:n})=>function(i,n){var r;return gl(this,void 0,void 0,(function*(){const s=null==n?void 0:n.settings;null!=(null==s?void 0:s.defaultUriMatch)&&(yield e.setToUser(i,ml,s.defaultUriMatch),delete n.settings.defaultUriMatch,t=!0),null!=(null===(r=null==s?void 0:s.settings)||void 0===r?void 0:r.equivalentDomains)&&(yield e.setToUser(i,wl,s.settings.equivalentDomains),delete n.settings.settings.equivalentDomains,delete n.settings.settings,t=!0),t&&(yield e.set(i,n))}))}(i,n)))])}))}rollback(e){return gl(this,void 0,void 0,(function*(){let t=!1;const i=(yield e.get("global"))||{},n=yield e.getFromGlobal(Sl);null!=n&&(yield e.set("global",Object.assign(Object.assign({},i),{neverDomains:n})),yield e.setToGlobal(Sl,null));const r=yield e.getAccounts();yield Promise.all([...r.map((({userId:i,account:n})=>function(i,n){return gl(this,void 0,void 0,(function*(){let r=(null==n?void 0:n.settings)||{};const s=yield e.getFromUser(i,ml),o=yield e.getFromUser(i,wl);null!=s&&(r=Object.assign(Object.assign({},r),{defaultUriMatch:s}),yield e.setToUser(i,ml,null),t=!0),null!=o&&(r=Object.assign(Object.assign({},r),{settings:{equivalentDomains:o}}),yield e.setToUser(i,wl,null),t=!0),t&&(yield e.set(i,Object.assign(Object.assign({},n),{settings:r})))}))}(i,n)))])}))}}var Pl=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const kl={key:"selection",stateDefinition:{name:"theming"}};class Ol extends qo{migrate(e){return Pl(this,void 0,void 0,(function*(){const t=yield e.get("global"),i=null==t?void 0:t.theme;null!=i&&(yield e.setToGlobal(kl,i),delete t.theme,yield e.set("global",t))}))}rollback(e){var t;return Pl(this,void 0,void 0,(function*(){const i=yield e.getFromGlobal(kl);if(null!=i){const n=null!==(t=yield e.get("global"))&&void 0!==t?t:{};n.theme=i,yield e.set("global",n),yield e.removeFromGlobal(kl)}}))}}var Cl=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Al={stateDefinition:{name:"vaultSettings"}};class Dl extends qo{migrate(e){return Cl(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){return Cl(this,void 0,void 0,(function*(){let n=!1;const r=null==i?void 0:i.settings;null!=(null==r?void 0:r.dontShowCardsCurrentTab)&&(yield e.setToUser(t,Object.assign(Object.assign({},Al),{key:"showCardsCurrentTab"}),!r.dontShowCardsCurrentTab),delete i.settings.dontShowCardsCurrentTab,n=!0),null!=(null==r?void 0:r.dontShowIdentitiesCurrentTab)&&(yield e.setToUser(t,Object.assign(Object.assign({},Al),{key:"showIdentitiesCurrentTab"}),!r.dontShowIdentitiesCurrentTab),delete i.settings.dontShowIdentitiesCurrentTab,n=!0),n&&(yield e.set(t,i))}))}(t,i)))])}))}rollback(e){return Cl(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return Cl(this,void 0,void 0,(function*(){let r=!1,s=null!==(n=null==i?void 0:i.settings)&&void 0!==n?n:{};const o=yield e.getFromUser(t,Object.assign(Object.assign({},Al),{key:"showCardsCurrentTab"})),a=yield e.getFromUser(t,Object.assign(Object.assign({},Al),{key:"showIdentitiesCurrentTab"}));null!=o&&(s=Object.assign(Object.assign({},s),{dontShowCardsCurrentTab:!o}),yield e.setToUser(t,Object.assign(Object.assign({},Al),{key:"showCardsCurrentTab"}),null),r=!0),null!=a&&(s=Object.assign(Object.assign({},s),{dontShowIdentitiesCurrentTab:!a}),yield e.setToUser(t,Object.assign(Object.assign({},Al),{key:"showIdentitiesCurrentTab"}),null),r=!0),r&&(yield e.set(t,Object.assign(Object.assign({},i),{settings:s})))}))}(t,i)))])}))}}var xl=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Il={key:"avatarColor",stateDefinition:{name:"avatar"}};class Ul extends qo{migrate(e){return xl(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>xl(this,void 0,void 0,(function*(){var n,r;null!=(null===(n=null==i?void 0:i.settings)||void 0===n?void 0:n.avatarColor)&&(yield e.setToUser(t,Il,i.settings.avatarColor),null===(r=null==i?void 0:i.settings)||void 0===r||delete r.avatarColor,yield e.set(t,i))})))))}))}rollback(e){return xl(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>function(t,i){return xl(this,void 0,void 0,(function*(){let n=!1;const r=yield e.getFromUser(t,Il);r&&(i||(i={}),n=!0,i.settings.avatarColor=r,yield e.setToUser(t,Il,null)),n&&(yield e.set(t,i))}))}(t,i))))}))}}var Tl=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Nl={key:"emailTwoFactorTokenRecord",stateDefinition:{name:"tokenDiskLocal"}},Rl={name:"token"},El={key:"accessToken",stateDefinition:Rl},Fl={key:"refreshToken",stateDefinition:Rl},Ml={key:"apiKeyClientId",stateDefinition:Rl},Kl={key:"apiKeyClientSecret",stateDefinition:Rl};class Ll extends qo{migrate(e){return Tl(this,void 0,void 0,(function*(){const t=yield e.get("global"),i={},n=yield e.getAccounts();yield Promise.all([...n.map((({userId:n,account:r})=>function(t,i,n,r){var s,o,a,l,c;return Tl(this,void 0,void 0,(function*(){let d=!1;const u=null===(s=null==i?void 0:i.profile)||void 0===s?void 0:s.email;null!=n&&null!=i&&null!=u&&(r[u]=n);const h=null===(o=null==i?void 0:i.tokens)||void 0===o?void 0:o.accessToken;null!=h&&("web-disk-local"!==e.type&&(yield e.setToUser(t,El,h)),delete i.tokens.accessToken,d=!0);const p=null===(a=null==i?void 0:i.tokens)||void 0===a?void 0:a.refreshToken;null!=p&&("web-disk-local"!==e.type&&(yield e.setToUser(t,Fl,p)),delete i.tokens.refreshToken,d=!0);const y=null===(l=null==i?void 0:i.profile)||void 0===l?void 0:l.apiKeyClientId;null!=y&&("web-disk-local"!==e.type&&(yield e.setToUser(t,Ml,y)),delete i.profile.apiKeyClientId,d=!0);const v=null===(c=null==i?void 0:i.keys)||void 0===c?void 0:c.apiKeyClientSecret;null!=v&&("web-disk-local"!==e.type&&(yield e.setToUser(t,Kl,v)),delete i.keys.apiKeyClientSecret,d=!0),d&&(yield e.set(t,i))}))}(n,r,null==t?void 0:t.twoFactorToken,i)))]),yield e.setToGlobal(Nl,i),null==t||delete t.twoFactorToken,yield e.set("global",t)}))}rollback(e){var t;return Tl(this,void 0,void 0,(function*(){const i=yield e.getAccounts();let n=null;for(const{account:r}of i){const i=null===(t=null==r?void 0:r.profile)||void 0===t?void 0:t.email;if(null==i)continue;if(n=(yield e.getFromGlobal(Nl))[i],null!=n)break}if(null!=n){let t=yield e.get("global");t||(t={}),t.twoFactorToken=n,yield e.set("global",t)}yield e.setToGlobal(Nl,null),yield Promise.all([...i.map((({userId:t,account:i})=>function(t,i){return Tl(this,void 0,void 0,(function*(){let n=!1;const r=yield e.getFromUser(t,El);(null==i?void 0:i.tokens)&&null!=r&&(i.tokens.accessToken=r,n=!0),yield e.setToUser(t,El,null);const s=yield e.getFromUser(t,Fl);(null==i?void 0:i.tokens)&&null!=s&&(i.tokens.refreshToken=s,n=!0),yield e.setToUser(t,Fl,null);const o=yield e.getFromUser(t,Ml);(null==i?void 0:i.profile)&&null!=o&&(i.profile.apiKeyClientId=o,n=!0),yield e.setToUser(t,Ml,null);const a=yield e.getFromUser(t,Kl);(null==i?void 0:i.keys)&&null!=a&&(i.keys.apiKeyClientSecret=a,n=!0),yield e.setToUser(t,Kl,null),n&&(yield e.set(t,i))}))}(t,i)))])}))}}var zl=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Vl={key:"accountProfile",stateDefinition:{name:"billing"}};class Bl extends qo{migrate(e){return zl(this,void 0,void 0,(function*(){const t=yield e.getAccounts(),i=(t,i)=>zl(this,void 0,void 0,(function*(){var n,r,s,o;const a=null===(n=null==i?void 0:i.profile)||void 0===n?void 0:n.hasPremiumPersonally,l=null===(r=null==i?void 0:i.profile)||void 0===r?void 0:r.hasPremiumFromOrganization;null==a&&null==l||(yield e.setToUser(t,Vl,{hasPremiumPersonally:a,hasPremiumFromOrganization:l}),null===(s=null==i?void 0:i.profile)||void 0===s||delete s.hasPremiumPersonally,null===(o=null==i?void 0:i.profile)||void 0===o||delete o.hasPremiumFromOrganization,yield e.set(t,i))}));yield Promise.all([...t.map((({userId:e,account:t})=>i(e,t)))])}))}rollback(e){return zl(this,void 0,void 0,(function*(){const t=yield e.getAccounts(),i=(t,i)=>zl(this,void 0,void 0,(function*(){var n;const r=yield e.getFromUser(t,Vl);i&&r&&(i.profile=Object.assign(null!==(n=i.profile)&&void 0!==n?n:{},{hasPremiumPersonally:null==r?void 0:r.hasPremiumPersonally,hasPremiumFromOrganization:null==r?void 0:r.hasPremiumFromOrganization}),yield e.set(t,i)),yield e.setToUser(t,Vl,null)}));yield Promise.all([...t.map((({userId:e,account:t})=>i(e,t)))])}))}}var _l=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class jl extends qo{migrate(e){return _l(this,void 0,void 0,(function*(){const t=yield e.getAccounts();Promise.all(t.map((({userId:t,account:i})=>function(t,i){var n;return _l(this,void 0,void 0,(function*(){if(null!=(null===(n=null==i?void 0:i.profile)||void 0===n?void 0:n.everBeenUnlocked))return delete i.profile.everBeenUnlocked,e.set(t,i)}))}(t,i))))}))}rollback(e){throw Wo}updateVersion(e,t){return _l(this,void 0,void 0,(function*(){const i="up"===t?this.toVersion:this.fromVersion;e.currentVersion=i;const n=(yield e.get("global"))||{};yield e.set("global",Object.assign(Object.assign({},n),{stateVersion:i}))}))}}var $l,Wl,ql,Hl,Gl=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};!function(e){e[e.Invited=0]="Invited",e[e.Accepted=1]="Accepted",e[e.Confirmed=2]="Confirmed",e[e.Revoked=-1]="Revoked"}($l||($l={})),function(e){e[e.Owner=0]="Owner",e[e.Admin=1]="Admin",e[e.User=2]="User",e[e.Manager=3]="Manager",e[e.Custom=4]="Custom"}(Wl||(Wl={})),function(e){e[e.Msp=0]="Msp",e[e.Reseller=1]="Reseller"}(ql||(ql={})),function(e){e[e.Free=0]="Free",e[e.Families=1]="Families",e[e.Teams=2]="Teams",e[e.Enterprise=3]="Enterprise",e[e.TeamsStarter=4]="TeamsStarter"}(Hl||(Hl={}));const Jl={key:"organizations",stateDefinition:{name:"organizations"}};class Yl extends qo{migrate(e){return Gl(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>function(t,i){var n;return Gl(this,void 0,void 0,(function*(){const r=null===(n=null==i?void 0:i.data)||void 0===n?void 0:n.organizations;null!=r&&(yield e.setToUser(t,Jl,r),delete i.data.organizations,yield e.set(t,i))}))}(t,i))))}))}rollback(e){return Gl(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>function(t,i){var n;return Gl(this,void 0,void 0,(function*(){const r=yield e.getFromUser(t,Jl);i&&(i.data=Object.assign(null!==(n=i.data)&&void 0!==n?n:{},{organizations:r}),yield e.set(t,i)),yield e.setToUser(t,Jl,null)}))}(t,i))))}))}}var Ql=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Xl={stateDefinition:{name:"eventCollection"},key:"eventCollection"};class Zl extends qo{migrate(e){return Ql(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return Ql(this,void 0,void 0,(function*(){const r=null===(n=null==i?void 0:i.data)||void 0===n?void 0:n.eventCollection;null!=r&&(yield e.setToUser(t,Xl,r),delete i.data.eventCollection,yield e.set(t,i))}))}(t,i)))])}))}rollback(e){return Ql(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){var n;return Ql(this,void 0,void 0,(function*(){const r=yield e.getFromUser(t,Xl);i&&(i.data=Object.assign(null!==(n=i.data)&&void 0!==n?n:{},{eventCollection:r}),yield e.set(t,i)),yield e.setToUser(t,Xl,null)}))}(t,i)))])}))}}var ec=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const tc={stateDefinition:{name:"domainSettings"},key:"showFavicons"};class ic extends qo{migrate(e){return ec(this,void 0,void 0,(function*(){const t=yield e.get("global");null!=(null==t?void 0:t.disableFavicon)&&(yield e.setToGlobal(tc,!t.disableFavicon),delete t.disableFavicon,yield e.set("global",t))}))}rollback(e){return ec(this,void 0,void 0,(function*(){const t=(yield e.get("global"))||{},i=yield e.getFromGlobal(tc);null!=i&&(yield e.set("global",Object.assign(Object.assign({},t),{disableFavicon:!i})),yield e.setToGlobal(tc,null))}))}}var nc=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const rc={key:"autoConfirmFingerPrints",stateDefinition:{name:"organizationManagementPreferences"}};class sc extends qo{migrate(e){return nc(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>nc(this,void 0,void 0,(function*(){var n,r;null!=(null===(n=null==i?void 0:i.settings)||void 0===n?void 0:n.autoConfirmFingerPrints)&&(yield e.setToUser(t,rc,i.settings.autoConfirmFingerPrints),null===(r=null==i?void 0:i.settings)||void 0===r||delete r.autoConfirmFingerPrints,yield e.set(t,i))})))))}))}rollback(e){return nc(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>function(t,i){return nc(this,void 0,void 0,(function*(){let n=!1;const r=yield e.getFromUser(t,rc);r&&(i||(i={}),n=!0,i.settings.autoConfirmFingerPrints=r,yield e.setToUser(t,rc,null)),n&&(yield e.set(t,i))}))}(t,i))))}))}}var oc=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const ac={key:"decryptionOptions",stateDefinition:{name:"userDecryptionOptions"}};class lc extends qo{migrate(e){return oc(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){return oc(this,void 0,void 0,(function*(){const n=null==i?void 0:i.decryptionOptions;null!=n&&(yield e.setToUser(t,ac,n),delete i.decryptionOptions,yield e.set(t,i))}))}(t,i)))])}))}rollback(e){return oc(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){return oc(this,void 0,void 0,(function*(){const n=yield e.getFromUser(t,ac);i&&(i.decryptionOptions=Object.assign(i.decryptionOptions,n),yield e.set(t,i)),yield e.setToUser(t,ac,null)}))}(t,i)))])}))}}var cc=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const dc={name:"environment"},uc={key:"region",stateDefinition:dc},hc={key:"urls",stateDefinition:dc},pc={key:"environment",stateDefinition:dc};class yc extends qo{migrate(e){return cc(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){return cc(this,void 0,void 0,(function*(){const i=yield e.getFromUser(t,uc),n=yield e.getFromUser(t,hc);null==i&&null==n||(yield e.setToUser(t,pc,{region:i,urls:n}),yield e.removeFromUser(t,uc),yield e.removeFromUser(t,hc))}))}(t)))]);const i=yield e.getFromGlobal(uc),n=yield e.getFromGlobal(hc);null==i&&null==n||(yield e.setToGlobal(pc,{region:i,urls:n}),yield e.removeFromGlobal(uc),yield e.removeFromGlobal(hc))}))}rollback(e){return cc(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all([...t.map((({userId:t,account:i})=>function(t,i){return cc(this,void 0,void 0,(function*(){const i=yield e.getFromUser(t,pc);yield e.setToUser(t,uc,null==i?void 0:i.region),yield e.setToUser(t,hc,null==i?void 0:i.urls),yield e.removeFromUser(t,pc)}))}(t)))]);const i=yield e.getFromGlobal(pc);yield e.setToGlobal(uc,null==i?void 0:i.region),yield e.setToGlobal(hc,null==i?void 0:i.urls),yield e.removeFromGlobal(pc)}))}}var vc=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const fc={key:"promptCancelled",stateDefinition:{name:"biometricSettings"}};class gc extends qo{migrate(e){return vc(this,void 0,void 0,(function*(){yield Promise.all((yield e.getAccounts()).map((({userId:t})=>vc(this,void 0,void 0,(function*(){null!=e.getFromUser(t,fc)&&(yield e.removeFromUser(t,fc))})))))}))}rollback(e){return vc(this,void 0,void 0,(function*(){throw Wo}))}}var mc=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const wc={name:"desktopSettings"},Sc={key:"window",stateDefinition:wc},bc={key:"closeToTray",stateDefinition:wc},Pc={key:"minimizeToTray",stateDefinition:wc},kc={key:"startToTray",stateDefinition:wc},Oc={key:"trayEnabled",stateDefinition:wc},Cc={key:"openAtLogin",stateDefinition:wc},Ac={key:"alwaysShowDock",stateDefinition:wc},Dc={key:"alwaysOnTop",stateDefinition:wc};class xc extends qo{migrate(e){return mc(this,void 0,void 0,(function*(){const t=yield e.get("global");let i=!1;void 0!==(null==t?void 0:t.window)&&(yield e.setToGlobal(Sc,t.window),i=!0,delete t.window),null!=(null==t?void 0:t.enableCloseToTray)&&(yield e.setToGlobal(bc,t.enableCloseToTray),i=!0,delete t.enableCloseToTray),null!=(null==t?void 0:t.enableMinimizeToTray)&&(yield e.setToGlobal(Pc,t.enableMinimizeToTray),i=!0,delete t.enableMinimizeToTray),null!=(null==t?void 0:t.enableStartToTray)&&(yield e.setToGlobal(kc,t.enableStartToTray),i=!0,delete t.enableStartToTray),null!=(null==t?void 0:t.enableTray)&&(yield e.setToGlobal(Oc,t.enableTray),i=!0,delete t.enableTray),null!=(null==t?void 0:t.openAtLogin)&&(yield e.setToGlobal(Cc,t.openAtLogin),i=!0,delete t.openAtLogin),null!=(null==t?void 0:t.alwaysShowDock)&&(yield e.setToGlobal(Ac,t.alwaysShowDock),i=!0,delete t.alwaysShowDock),null!=(null==t?void 0:t.enableAlwaysOnTop)&&(yield e.setToGlobal(Dc,t.enableAlwaysOnTop),i=!0,delete t.enableAlwaysOnTop),i&&(yield e.set("global",t));const n=yield e.getAccounts();yield Promise.all(n.map((({userId:t,account:i})=>function(t,i){var n;return mc(this,void 0,void 0,(function*(){null!=(null===(n=null==i?void 0:i.settings)||void 0===n?void 0:n.enableAlwaysOnTop)&&(delete i.settings.enableAlwaysOnTop,yield e.set(t,i))}))}(t,i))))}))}rollback(e){throw Wo}}var Ic=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Uc={key:"enableDuckDuckGoBrowserIntegration",stateDefinition:{name:"autofillSettings"}};class Tc extends qo{migrate(e){return Ic(this,void 0,void 0,(function*(){const t=yield e.get("global");null!=(null==t?void 0:t.enableDuckDuckGoBrowserIntegration)&&(yield e.setToGlobal(Uc,t.enableDuckDuckGoBrowserIntegration),delete t.enableDuckDuckGoBrowserIntegration,yield e.set("global",t))}))}rollback(e){var t;return Ic(this,void 0,void 0,(function*(){const i=yield e.getFromGlobal(Uc);if(!i)return;const n=null!==(t=yield e.get("global"))&&void 0!==t?t:{};n.enableDuckDuckGoBrowserIntegration=i,yield e.set("global",n),yield e.removeFromGlobal(Uc)}))}}var Nc=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Rc extends qo{migrate(e){return Nc(this,void 0,void 0,(function*(){const t=yield e.getAccounts();Promise.all(t.map((({userId:t,account:i})=>function(t,i){var n,r;return Nc(this,void 0,void 0,(function*(){const s=null===(r=null===(n=null==i?void 0:i.keys)||void 0===n?void 0:n.organizationKeys)||void 0===r?void 0:r.encrypted;if(null==s)return;const o={};Object.entries(s).forEach((([e,t])=>{o[e]={type:"organization",key:t}})),i.keys.organizationKeys.encrypted=o,yield e.set(t,i)}))}(t,i))))}))}rollback(e){return Nc(this,void 0,void 0,(function*(){const t=yield e.getAccounts();Promise.all(t.map((({userId:t,account:i})=>Nc(this,void 0,void 0,(function*(){return function(t,i){var n,r;return Nc(this,void 0,void 0,(function*(){const s=null===(r=null===(n=null==i?void 0:i.keys)||void 0===n?void 0:n.organizationKeys)||void 0===r?void 0:r.encrypted;if(null==s)return;const o={};Object.entries(s).forEach((([e,t])=>{o[e]=t.key})),i.keys.organizationKeys.encrypted=o,yield e.set(t,i)}))}(t,i)})))))}))}updateVersion(e,t){return Nc(this,void 0,void 0,(function*(){const i="up"===t?this.toVersion:this.fromVersion;e.currentVersion=i;const n=(yield e.get("global"))||{};yield e.set("global",Object.assign(Object.assign({},n),{stateVersion:i}))}))}}var Ec=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Fc extends qo{migrate(e){return Ec(this,void 0,void 0,(function*(){const t=yield e.getAccounts();yield Promise.all(t.map((({userId:t,account:i})=>function(t,i){var n;return Ec(this,void 0,void 0,(function*(){(null===(n=null==i?void 0:i.keys)||void 0===n?void 0:n.legacyEtmKey)&&(delete i.keys.legacyEtmKey,yield e.set(t,i))}))}(t,i))))}))}rollback(e){return Ec(this,void 0,void 0,(function*(){throw Wo}))}updateVersion(e,t){return Ec(this,void 0,void 0,(function*(){const i="up"===t?this.toVersion:this.fromVersion;e.currentVersion=i;const n=(yield e.get("global"))||{};yield e.set("global",Object.assign(Object.assign({},n),{stateVersion:i}))}))}}var Mc=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Kc extends qo{migrate(e){var t;return Mc(this,void 0,void 0,(function*(){const i=yield e.get("global"),n=null!==(t=null==i?void 0:i.noAutoPromptBiometrics)&&void 0!==t&&t,r=yield e.getAccounts();delete i.noAutoPromptBiometrics,yield Promise.all([...r.map((({userId:t,account:i})=>function(t,i){var r;return Mc(this,void 0,void 0,(function*(){null!=i&&n&&(i.settings=Object.assign(null!==(r=null==i?void 0:i.settings)&&void 0!==r?r:{},{disableAutoBiometricsPrompt:!0}),yield e.set(t,i))}))}(t,i))),e.set("global",i)])}))}rollback(e){return Mc(this,void 0,void 0,(function*(){throw Wo}))}updateVersion(e,t){return Mc(this,void 0,void 0,(function*(){const i="up"===t?this.toVersion:this.fromVersion;e.currentVersion=i;const n=(yield e.get("global"))||{};yield e.set("global",Object.assign(Object.assign({},n),{stateVersion:i}))}))}}var Lc=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class zc extends qo{migrate(e){return Lc(this,void 0,void 0,(function*(){const t=yield e.get("global");if(!t.stateVersion)throw new Error("Migration failed, state version not found");yield e.set("stateVersion",t.stateVersion),delete t.stateVersion,yield e.set("global",t)}))}rollback(e){return Lc(this,void 0,void 0,(function*(){const t=yield e.get("stateVersion"),i=yield e.get("global");yield e.set("global",Object.assign(Object.assign({},i),{stateVersion:t})),yield e.set("stateVersion",void 0)}))}updateVersion(e,t){return Lc(this,void 0,void 0,(function*(){const i="up"===t?this.toVersion:this.fromVersion;if(e.currentVersion=i,"up"===t)yield e.set("stateVersion",i);else{const t=(yield e.get("global"))||{};yield e.set("global",Object.assign(Object.assign({},t),{stateVersion:i}))}}))}}var Vc=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Bc extends qo{tryAddSetting(e,t,i){if(e.some((({account:e})=>void 0!==t(e)))){const n=!e.some((({account:e})=>{var i;return!1===(null!==(i=t(e))&&void 0!==i&&i)}));i(n)}}migrate(e){return Vc(this,void 0,void 0,(function*(){const t=yield e.get("global"),i=yield e.getAccounts(),n=i.reduce(((e,{account:t})=>{var i,n;const r=null!==(n=null===(i=t.settings)||void 0===i?void 0:i.neverDomains)&&void 0!==n?n:{};for(const[t,i]of Object.entries(r))null!=e||(e={}),e[t]=i;return e}),void 0),r={};null!=n&&(r.neverDomains=n),this.tryAddSetting(i,(e=>{var t;return null===(t=e.settings)||void 0===t?void 0:t.disableAddLoginNotification}),(e=>r.disableAddLoginNotification=e)),this.tryAddSetting(i,(e=>{var t;return null===(t=e.settings)||void 0===t?void 0:t.disableChangedPasswordNotification}),(e=>r.disableChangedPasswordNotification=e)),this.tryAddSetting(i,(e=>{var t;return null===(t=e.settings)||void 0===t?void 0:t.disableContextMenuItem}),(e=>r.disableContextMenuItem=e)),yield e.set("global",Object.assign(Object.assign({},t),r)),yield Promise.all(i.map((({userId:t,account:i})=>Vc(this,void 0,void 0,(function*(){var n,r,s,o;null===(n=i.settings)||void 0===n||delete n.disableAddLoginNotification,null===(r=i.settings)||void 0===r||delete r.disableChangedPasswordNotification,null===(s=i.settings)||void 0===s||delete s.disableContextMenuItem,null===(o=i.settings)||void 0===o||delete o.neverDomains,yield e.set(t,i)})))))}))}rollback(e){throw new Error("Method not implemented.")}}var _c=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class jc extends qo{constructor(){super(0,Wc)}shouldMigrate(e){return Promise.resolve(e.currentVersionGc(this,void 0,void 0,(function*(){return{userId:e,account:yield this.get(e)}})))))}))}getUserKey(e,t){return this.currentVersion<9?function(){throw Error("No key builder should be used for versions prior to 9.")}():function(e,t){return`user_${e}_${t.stateDefinition.name}_${t.key}`}(e,t)}getGlobalKey(e){return this.currentVersion<9?function(){throw Error("No key builder should be used for versions prior to 9.")}():function(e){return`global_${e.stateDefinition.name}_${e.key}`}(e)}}var Yc=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Qc{constructor(e,t,i){this.diskStorage=e,this.logService=t,this.migrationBuilderService=i}run(){return Yc(this,void 0,void 0,(function*(){const e=new Jc(yield qc(this.diskStorage,this.logService),this.diskStorage,this.logService,"general");if(e.currentVersion<0)return void(yield this.diskStorage.save("stateVersion",48));const t=this.migrationBuilderService.build();yield t.migrate(e)}))}waitForCompletion(){return Yc(this,void 0,void 0,(function*(){yield function(e,t){return $c(this,void 0,void 0,(function*(){const i=()=>$c(this,void 0,void 0,(function*(){return(yield qc(e,t))>=48})),n=e=>$c(this,void 0,void 0,(function*(){const r=2*e;if(!(r>8192))return new Promise((s=>{setTimeout((()=>$c(this,void 0,void 0,(function*(){(yield i())||(t.info(`Waiting for migrations to finish, waiting for ${r}ms`),yield n(r)),s()}))),e)}))}));(yield i())||(yield n(2))}))}(this.diskStorage,this.logService)}))}}class Xc{constructor(e,t){this.diskStorageService=e,this.memoryStorageService=t}get(e,t){switch(e){case"disk":return[e,this.diskStorageService];case"memory":return[e,this.memoryStorageService];default:throw new Error(`Unexpected location: ${e}`)}}}var Zc=i(91246),ed=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class td{constructor(e,t,i=null,n,r,s,o){this.messagingService=e,this.platformUtilsService=t,this.reloadCallback=i,this.stateService=n,this.autofillSettingsService=r,this.vaultTimeoutSettingsService=s,this.biometricStateService=o,this.reloadInterval=null,this.clearClipboardTimeout=null,this.clearClipboardTimeoutFunction=null}startProcessReload(e){return ed(this,void 0,void 0,(function*(){const t=yield(0,r.z)(this.stateService.accounts$);if(null!=t){const i=Object.keys(t);if(i.length>0)for(const t of i)if((yield e.getAuthStatus(t))===On.Unlocked)return}if(null!=this.reloadInterval)return;null==(yield this.stateService.getPinKeyEncryptedUserKeyEphemeral())&&(this.cancelProcessReload(),yield this.executeProcessReload())}))}executeProcessReload(){return ed(this,void 0,void 0,(function*(){if(!(yield(0,r.z)(this.biometricStateService.fingerprintValidated$))){clearInterval(this.reloadInterval),this.reloadInterval=null;if(null!=(yield(0,r.z)(this.stateService.activeAccount$.pipe((0,Zc.V)(500))))){if((yield(0,r.z)(this.vaultTimeoutSettingsService.vaultTimeoutAction$().pipe((0,Zc.V)(500))))===ar.LogOut){const e=yield this.stateService.nextUpActiveUser();yield this.stateService.setActiveUser(e)}}return this.messagingService.send("reloadProcess"),void(null!=this.reloadCallback&&(yield this.reloadCallback()))}null==this.reloadInterval&&(this.reloadInterval=setInterval((()=>ed(this,void 0,void 0,(function*(){return yield this.executeProcessReload()}))),1e3))}))}cancelProcessReload(){null!=this.reloadInterval&&(clearInterval(this.reloadInterval),this.reloadInterval=null)}clearClipboard(e,t=null){return ed(this,void 0,void 0,(function*(){if(null!=this.clearClipboardTimeout&&(clearTimeout(this.clearClipboardTimeout),this.clearClipboardTimeout=null),p.isNullOrWhitespace(e))return;const i=yield(0,r.z)(this.autofillSettingsService.clearClipboardDelay$);null!=i&&(null==t&&(t=1e3*i),this.clearClipboardTimeoutFunction=()=>ed(this,void 0,void 0,(function*(){const t=yield this.platformUtilsService.readFromClipboard();e===t&&this.platformUtilsService.copyToClipboard("",{clearing:!0})})),this.clearClipboardTimeout=setTimeout((()=>ed(this,void 0,void 0,(function*(){yield this.clearPendingClipboard()}))),t))}))}clearPendingClipboard(){return ed(this,void 0,void 0,(function*(){null!=this.clearClipboardTimeoutFunction&&(yield this.clearClipboardTimeoutFunction(),this.clearClipboardTimeoutFunction=null)}))}}var id=i(99405),nd=i(86268);class rd{}var sd=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class od{constructor(e){this.crypto=void 0!==e.crypto?e.crypto:null,this.subtle=this.crypto&&void 0!==this.crypto.subtle?this.crypto.subtle:null,this.wasmSupported=this.checkIfWasmSupported()}pbkdf2(e,t,i,n){return sd(this,void 0,void 0,(function*(){const r="sha256"===i?256:512,s=this.toBuf(e),o={name:"PBKDF2",salt:this.toBuf(t),iterations:n,hash:{name:this.toWebCryptoAlgorithm(i)}},a=yield this.subtle.importKey("raw",s,{name:"PBKDF2"},!1,["deriveBits"]),l=yield this.subtle.deriveBits(o,a,r);return new Uint8Array(l)}))}argon2(e,t,i,n,r){return sd(this,void 0,void 0,(function*(){if(!this.wasmSupported)throw"Webassembly support is required for the Argon2 KDF feature.";const s=new Uint8Array(this.toBuf(e)),o=new Uint8Array(this.toBuf(t)),a=yield id.hash({pass:s,salt:o,time:i,mem:n,parallelism:r,hashLen:32,type:id.ArgonType.Argon2id});return id.unloadRuntime(),a.hash}))}hkdf(e,t,i,n,r){return sd(this,void 0,void 0,(function*(){const s={name:"HKDF",salt:this.toBuf(t),info:this.toBuf(i),hash:{name:this.toWebCryptoAlgorithm(r)}},o=yield this.subtle.importKey("raw",e,{name:"HKDF"},!1,["deriveBits"]),a=yield this.subtle.deriveBits(s,o,8*n);return new Uint8Array(a)}))}hkdfExpand(e,t,i,n){return sd(this,void 0,void 0,(function*(){const r="sha256"===n?32:64;if(i>255*r)throw new Error("outputByteSize is too large.");if(new Uint8Array(e).length=i)break}return d.slice(0,i)}))}hash(e,t){return sd(this,void 0,void 0,(function*(){if("md5"===t){const t=nd.md.md5.create(),i=this.toByteString(e);return t.update(i,"raw"),p.fromByteStringToArray(t.digest().data)}const i=this.toBuf(e),n=yield this.subtle.digest({name:this.toWebCryptoAlgorithm(t)},i);return new Uint8Array(n)}))}hmac(e,t,i){return sd(this,void 0,void 0,(function*(){const n={name:"HMAC",hash:{name:this.toWebCryptoAlgorithm(i)}},r=yield this.subtle.importKey("raw",t,n,!1,["sign"]),s=yield this.subtle.sign(n,r,e);return new Uint8Array(s)}))}compare(e,t){return sd(this,void 0,void 0,(function*(){const i=yield this.randomBytes(32),n={name:"HMAC",hash:{name:"SHA-256"}},r=yield this.subtle.importKey("raw",i,n,!1,["sign"]),s=yield this.subtle.sign(n,r,e),o=yield this.subtle.sign(n,r,t);if(s.byteLength!==o.byteLength)return!1;const a=new Uint8Array(s),l=new Uint8Array(o);for(let e=0;enull!=e?this.singleUserStateProvider.get(e,this.keyDefinition).combinedState$:ad.C))),this.state$=this.combinedState$.pipe((0,q.U)((([e,t])=>t)))}update(e,t={}){return cd(this,void 0,void 0,(function*(){const i=yield(0,r.z)(this.activeUserId$.pipe((0,Zc.V)({first:1e3,with:()=>(0,ld._)((()=>new Error(`Timeout while retrieving active user for key ${this.keyDefinition.fullName}.`)))})));if(null==i)throw new Error(`Error storing ${this.keyDefinition.fullName} for the active user: No active user at this time.`);return[i,yield this.singleUserStateProvider.get(i,this.keyDefinition).update(e,t)]}))}}class ud{constructor(e,t){this.accountService=e,this.singleUserStateProvider=t,this.activeUserId$=this.accountService.activeAccount$.pipe((0,q.U)((e=>null==e?void 0:e.id)),(0,j.x)(((e,t)=>null==e||null==t?e==t:e===t)))}get(e){return Wt(e)||(e=qt.fromBaseKeyDefinition(e)),new dd(e,this.activeUserId$,this.singleUserStateProvider)}}var hd=i(62324),pd=i(12294),yd=i(56110),vd=i(66966);const fd={shouldUpdate:()=>!0,combineLatestWith:null,msTimeout:1e3};var gd=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function md(e,t,i){return gd(this,void 0,void 0,(function*(){if(t.valuesRequireDeserialization){const n=yield t.get(e);return i(n)}{const i=yield t.get(e);return null!=i?i:null}}))}var wd=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Sd{constructor(e,t,i){this.key=e,this.storageService=t,this.keyDefinition=i;const n=t.updates$.pipe((0,_.h)((t=>t.key===e)),(0,c.w)((n=>wd(this,void 0,void 0,(function*(){return"remove"===n.updateType?null:yield md(e,t,i.deserializer)})))));this.state$=(0,hd.T)((0,jn.P)((()=>md(e,t,i.deserializer))),n).pipe((0,pd.B)({connector:()=>new yd.t(1),resetOnRefCountZero:()=>(0,vd.H)(i.cleanupDelayMs)}))}update(e,t={}){return wd(this,void 0,void 0,(function*(){t=function(e){return Object.assign(Object.assign({},fd),e)}(t),null!=this.updatePromise&&(yield this.updatePromise);try{this.updatePromise=this.internalUpdate(e,t);return yield this.updatePromise}finally{this.updatePromise=null}}))}internalUpdate(e,t){return wd(this,void 0,void 0,(function*(){const i=yield this.getStateForUpdate(),n=null!=t.combineLatestWith?yield(0,r.z)(t.combineLatestWith.pipe((0,Zc.V)(t.msTimeout))):null;if(!t.shouldUpdate(i,n))return i;const s=e(i,n);return yield this.doStorageSave(s,i),s}))}doStorageSave(e,t){return wd(this,void 0,void 0,(function*(){yield this.storageService.save(this.key,e)}))}getStateForUpdate(){return wd(this,void 0,void 0,(function*(){return yield md(this.key,this.storageService,this.keyDefinition.deserializer)}))}}class bd extends Sd{constructor(e,t){super(function(e){return`global_${e.stateDefinition.name}_${e.key}`}(e),t,e)}}class Pd{constructor(e){this.storageServiceProvider=e,this.globalStateCache={}}get(e){const[t,i]=this.storageServiceProvider.get(e.stateDefinition.defaultStorageLocation,e.stateDefinition.storageLocationOverrides),n=this.buildCacheKey(t,e),r=this.globalStateCache[n];if(null!=r)return r;const s=new bd(e,i);return this.globalStateCache[n]=s,s}buildCacheKey(e,t){return`${e}_${t.fullName}`}}var kd=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Od extends Sd{constructor(e,t,i,n){super(t.buildKey(e),i,t),this.userId=e,this.stateEventRegistrarService=n,this.combinedState$=(0,pn.a)([(0,l.of)(e),this.state$])}doStorageSave(e,t){const i=Object.create(null,{doStorageSave:{get:()=>super.doStorageSave}});return kd(this,void 0,void 0,(function*(){yield i.doStorageSave.call(this,e,t),null!=e&&null==t&&(yield this.stateEventRegistrarService.registerEvents(this.keyDefinition))}))}}class Cd{constructor(e,t){this.storageServiceProvider=e,this.stateEventRegistrarService=t,this.cache={}}get(e,t){Wt(t)||(t=qt.fromBaseKeyDefinition(t));const[i,n]=this.storageServiceProvider.get(t.stateDefinition.defaultStorageLocation,t.stateDefinition.storageLocationOverrides),r=this.buildCacheKey(i,e,t),s=this.cache[r];if(null!=s)return s;const o=new Od(e,t,n,this.stateEventRegistrarService);return this.cache[r]=o,o}buildCacheKey(e,t,i){return`${e}_${i.fullName}_${t}`}}var Ad=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Dd{constructor(e,t,i,n){this.activeUserStateProvider=e,this.singleUserStateProvider=t,this.globalStateProvider=i,this.derivedStateProvider=n,this.getActive=this.activeUserStateProvider.get.bind(this.activeUserStateProvider),this.getUser=this.singleUserStateProvider.get.bind(this.singleUserStateProvider),this.getGlobal=this.globalStateProvider.get.bind(this.globalStateProvider),this.getDerived=this.derivedStateProvider.get.bind(this.derivedStateProvider),this.activeUserId$=this.activeUserStateProvider.activeUserId$}getUserState$(e,t){return t?this.getUser(t,e).state$:this.activeUserId$.pipe((0,_.h)((e=>null!=e)),(0,wn.q)(1),(0,c.w)((t=>this.getUser(t,e).state$)))}getUserStateOrDefault$(e,t){const{userId:i,defaultValue:n=null}=t;return i?this.getUser(i,e).state$:this.activeUserId$.pipe((0,wn.q)(1),(0,c.w)((t=>null!=t?this.getUser(t,e).state$:(0,l.of)(n))))}setUserState(e,t,i){return Ad(this,void 0,void 0,(function*(){return i?[i,yield this.getUser(i,e).update((()=>t))]:yield this.getActive(e).update((()=>t))}))}}var xd=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Id=new jt(mi,"selection",{deserializer:e=>e});class Ud{constructor(e,t=T.System){this.globalStateProvider=e,this.defaultTheme=t,this.selectedThemeState=this.globalStateProvider.get(Id),this.selectedTheme$=this.selectedThemeState.state$.pipe((0,q.U)((e=>null!=e?e:this.defaultTheme)))}setSelectedTheme(e){return xd(this,void 0,void 0,(function*(){yield this.selectedThemeState.update((()=>e),{shouldUpdate:t=>t!==e})}))}}class Td extends J{constructor(e,t){super(e),this.id=this.getResponseProperty("Id"),this.type=this.getResponseProperty("Type"),this.organizationId=this.getResponseProperty("OrganizationId"),this.enabled=this.getResponseProperty("Enabled");const i=this.getResponseProperty("Config");this.config=null==i?null:new t(i)}}class Nd extends J{constructor(e=null){super(e),null!=e&&(this.cardholderName=this.getResponseProperty("CardholderName"),this.brand=this.getResponseProperty("Brand"),this.number=this.getResponseProperty("Number"),this.expMonth=this.getResponseProperty("ExpMonth"),this.expYear=this.getResponseProperty("ExpYear"),this.code=this.getResponseProperty("Code"))}}class Rd extends J{constructor(e=null){super(e),null!=e&&(this.type=this.getResponseProperty("Type"),this.name=this.getResponseProperty("Name"),this.value=this.getResponseProperty("Value"),this.linkedId=this.getResponseProperty("linkedId"))}}class Ed extends J{constructor(e=null){super(e),null!=e&&(this.title=this.getResponseProperty("Title"),this.firstName=this.getResponseProperty("FirstName"),this.middleName=this.getResponseProperty("MiddleName"),this.lastName=this.getResponseProperty("LastName"),this.address1=this.getResponseProperty("Address1"),this.address2=this.getResponseProperty("Address2"),this.address3=this.getResponseProperty("Address3"),this.city=this.getResponseProperty("City"),this.state=this.getResponseProperty("State"),this.postalCode=this.getResponseProperty("PostalCode"),this.country=this.getResponseProperty("Country"),this.company=this.getResponseProperty("Company"),this.email=this.getResponseProperty("Email"),this.phone=this.getResponseProperty("Phone"),this.ssn=this.getResponseProperty("SSN"),this.username=this.getResponseProperty("Username"),this.passportNumber=this.getResponseProperty("PassportNumber"),this.licenseNumber=this.getResponseProperty("LicenseNumber"))}}class Fd extends J{constructor(e=null){super(e),null!=e&&(this.credentialId=this.getResponseProperty("CredentialId"),this.keyType=this.getResponseProperty("KeyType"),this.keyAlgorithm=this.getResponseProperty("KeyAlgorithm"),this.keyCurve=this.getResponseProperty("KeyCurve"),this.keyValue=this.getResponseProperty("keyValue"),this.rpId=this.getResponseProperty("RpId"),this.userHandle=this.getResponseProperty("UserHandle"),this.userName=this.getResponseProperty("UserName"),this.counter=this.getResponseProperty("Counter"),this.rpName=this.getResponseProperty("RpName"),this.userDisplayName=this.getResponseProperty("UserDisplayName"),this.discoverable=this.getResponseProperty("Discoverable"),this.creationDate=this.getResponseProperty("CreationDate"))}}class Md extends J{constructor(e=null){if(super(e),this.match=null,null==e)return;this.uri=this.getResponseProperty("Uri"),this.uriChecksum=this.getResponseProperty("UriChecksum");const t=this.getResponseProperty("Match");this.match=null!=t?t:null}}class Kd extends J{constructor(e=null){if(super(e),null==e)return;this.username=this.getResponseProperty("Username"),this.password=this.getResponseProperty("Password"),this.passwordRevisionDate=this.getResponseProperty("PasswordRevisionDate"),this.totp=this.getResponseProperty("Totp"),this.autofillOnPageLoad=this.getResponseProperty("AutofillOnPageLoad");const t=this.getResponseProperty("Uris");null!=t&&(this.uris=t.map((e=>new Md(e))));const i=this.getResponseProperty("Fido2Credentials");null!=i&&(this.fido2Credentials=i.map((e=>new Fd(e))))}}class Ld extends J{constructor(e=null){super(e),null!=e&&(this.type=this.getResponseProperty("Type"))}}class zd extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.url=this.getResponseProperty("Url"),this.fileName=this.getResponseProperty("FileName"),this.key=this.getResponseProperty("Key"),this.size=this.getResponseProperty("Size"),this.sizeName=this.getResponseProperty("SizeName")}}class Vd extends J{constructor(e){super(e),this.password=this.getResponseProperty("Password"),this.lastUsedDate=this.getResponseProperty("LastUsedDate")}}class Bd extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.organizationId=this.getResponseProperty("OrganizationId"),this.folderId=this.getResponseProperty("FolderId")||null,this.type=this.getResponseProperty("Type"),this.name=this.getResponseProperty("Name"),this.notes=this.getResponseProperty("Notes"),this.favorite=this.getResponseProperty("Favorite")||!1,this.edit=!!this.getResponseProperty("Edit"),null==this.getResponseProperty("ViewPassword")?this.viewPassword=!0:this.viewPassword=this.getResponseProperty("ViewPassword"),this.organizationUseTotp=this.getResponseProperty("OrganizationUseTotp"),this.revisionDate=this.getResponseProperty("RevisionDate"),this.collectionIds=this.getResponseProperty("CollectionIds"),this.creationDate=this.getResponseProperty("CreationDate"),this.deletedDate=this.getResponseProperty("DeletedDate");const t=this.getResponseProperty("Login");null!=t&&(this.login=new Kd(t));const i=this.getResponseProperty("Card");null!=i&&(this.card=new Nd(i));const n=this.getResponseProperty("Identity");null!=n&&(this.identity=new Ed(n));const r=this.getResponseProperty("SecureNote");null!=r&&(this.secureNote=new Ld(r));const s=this.getResponseProperty("Fields");null!=s&&(this.fields=s.map((e=>new Rd(e))));const o=this.getResponseProperty("Attachments");null!=o&&(this.attachments=o.map((e=>new zd(e))));const a=this.getResponseProperty("PasswordHistory");null!=a&&(this.passwordHistory=a.map((e=>new Vd(e)))),this.reprompt=this.getResponseProperty("Reprompt")||be.None,this.key=this.getResponseProperty("Key")||null}}class _d extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.readOnly=this.getResponseProperty("ReadOnly"),this.hidePasswords=this.getResponseProperty("HidePasswords"),this.manage=this.getResponseProperty("Manage")}}class jd extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.organizationId=this.getResponseProperty("OrganizationId"),this.name=this.getResponseProperty("Name"),this.externalId=this.getResponseProperty("ExternalId")}}class $d extends jd{constructor(e){super(e),this.readOnly=this.getResponseProperty("ReadOnly")||!1,this.manage=this.getResponseProperty("Manage")||!1,this.hidePasswords=this.getResponseProperty("HidePasswords")||!1,this.assigned="collectionDetails"==this.getResponseProperty("object")}}class Wd extends jd{constructor(e){super(e),this.groups=[],this.users=[],this.assigned=this.getResponseProperty("Assigned")||!1;const t=this.getResponseProperty("Groups");null!=t&&(this.groups=t.map((e=>new _d(e))));const i=this.getResponseProperty("Users");null!=i&&(this.users=i.map((e=>new _d(e))))}}class qd extends J{constructor(e){super(e);const t=this.getResponseProperty("Collections");null!=t&&(this.collections=t.map((e=>new jd(e))));const i=this.getResponseProperty("Ciphers");null!=i&&(this.ciphers=i.map((e=>new Bd(e))))}}class Hd extends J{constructor(e){super(e);const t=this.getResponseProperty("LastSyncDate");t&&(this.lastSyncDate=new Date(t))}}class Gd extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.providerId=this.getResponseProperty("ProviderId"),this.organizationId=this.getResponseProperty("OrganizationId"),this.key=this.getResponseProperty("Key"),this.settings=this.getResponseProperty("Settings"),this.creationDate=this.getResponseProperty("CreationDate"),this.revisionDate=this.getResponseProperty("RevisionDate"),this.userCount=this.getResponseProperty("UserCount"),this.seats=this.getResponseProperty("Seats"),this.plan=this.getResponseProperty("Plan")}}class Jd extends Gd{constructor(e){super(e),this.organizationName=this.getResponseProperty("OrganizationName")}}class Yd extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.userId=this.getResponseProperty("UserId"),this.key=this.getResponseProperty("Key")}}class Qd extends Yd{}class Xd extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.error=this.getResponseProperty("Error")}}class Zd extends J{constructor(e=null){if(super(e),null==e)return this;this.accessEventLogs=this.getResponseProperty("AccessEventLogs"),this.accessImportExport=this.getResponseProperty("AccessImportExport"),this.accessReports=this.getResponseProperty("AccessReports"),this.createNewCollections=this.getResponseProperty("CreateNewCollections"),this.editAnyCollection=this.getResponseProperty("EditAnyCollection"),this.deleteAnyCollection=this.getResponseProperty("DeleteAnyCollection"),this.editAssignedCollections=this.getResponseProperty("EditAssignedCollections"),this.deleteAssignedCollections=this.getResponseProperty("DeleteAssignedCollections"),this.manageCiphers=this.getResponseProperty("ManageCiphers"),this.manageGroups=this.getResponseProperty("ManageGroups"),this.manageSso=this.getResponseProperty("ManageSso"),this.managePolicies=this.getResponseProperty("ManagePolicies"),this.manageUsers=this.getResponseProperty("ManageUsers"),this.manageResetPassword=this.getResponseProperty("ManageResetPassword"),this.manageScim=this.getResponseProperty("ManageScim")}}class eu extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.userId=this.getResponseProperty("UserId"),this.type=this.getResponseProperty("Type"),this.status=this.getResponseProperty("Status"),this.permissions=new Zd(this.getResponseProperty("Permissions"))}}class tu extends eu{constructor(e){super(e),this.name=this.getResponseProperty("Name"),this.email=this.getResponseProperty("Email")}}class iu extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.name=this.getResponseProperty("Name"),this.businessName=this.getResponseProperty("BusinessName"),this.billingEmail=this.getResponseProperty("BillingEmail"),this.creationDate=this.getResponseProperty("CreationDate")}}class nu extends J{constructor(e){super(e),this.apiKey=this.getResponseProperty("ApiKey"),this.revisionDate=new Date(this.getResponseProperty("RevisionDate"))}}class ru extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.publicKey=this.getResponseProperty("PublicKey"),this.requestDeviceType=this.getResponseProperty("RequestDeviceType"),this.requestIpAddress=this.getResponseProperty("RequestIpAddress"),this.key=this.getResponseProperty("Key"),this.masterPasswordHash=this.getResponseProperty("MasterPasswordHash"),this.creationDate=this.getResponseProperty("CreationDate"),this.requestApproved=this.getResponseProperty("RequestApproved"),this.responseDate=this.getResponseProperty("ResponseDate");const t=new Date(this.creationDate),i=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds()),n=new Date(Date.now()),r=Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds());this.isExpired=r-i>=9e5,this.isAnswered=null!=this.requestApproved&&null!=this.responseDate}}class su extends J{constructor(e){super(e),this.isDeviceVerificationSectionEnabled=this.getResponseProperty("IsDeviceVerificationSectionEnabled"),this.unknownDeviceVerificationEnabled=this.getResponseProperty("UnknownDeviceVerificationEnabled")}}class ou extends J{constructor(e){super(e),this.key=this.getResponseProperty("Key")}}class au extends J{constructor(e){super(e),this.kdf=this.getResponseProperty("Kdf"),this.kdfIterations=this.getResponseProperty("KdfIterations"),this.kdfMemory=this.getResponseProperty("KdfMemory"),this.kdfParallelism=this.getResponseProperty("KdfParallelism")}}class lu extends J{constructor(e){super(e),this.captchaBypassToken=this.getResponseProperty("CaptchaBypassToken")}}class cu extends J{constructor(e){super(e),this.token=this.getResponseProperty("Token")}}class du extends J{constructor(e){super(e),this.enabled=this.getResponseProperty("Enabled"),this.key=this.getResponseProperty("Key")}}class uu extends J{constructor(e){super(e),this.enabled=this.getResponseProperty("Enabled"),this.host=this.getResponseProperty("Host"),this.secretKey=this.getResponseProperty("SecretKey"),this.integrationKey=this.getResponseProperty("IntegrationKey")}}class hu extends J{constructor(e){super(e),this.enabled=this.getResponseProperty("Enabled"),this.email=this.getResponseProperty("Email")}}class pu extends J{constructor(e){super(e),this.enabled=this.getResponseProperty("Enabled"),this.type=this.getResponseProperty("Type")}}class yu extends J{constructor(e){super(e),this.code=this.getResponseProperty("Code")}}class vu extends J{constructor(e){super(e),this.enabled=this.getResponseProperty("Enabled");const t=this.getResponseProperty("Keys");this.keys=null==t?null:t.map((e=>new fu(e)))}}class fu extends J{constructor(e){super(e),this.name=this.getResponseProperty("Name"),this.id=this.getResponseProperty("Id"),this.migrated=this.getResponseProperty("Migrated")}}class gu extends J{constructor(e){super(e),this.attestation=this.getResponseProperty("attestation"),this.authenticatorSelection=this.getResponseProperty("authenticatorSelection"),this.challenge=p.fromUrlB64ToArray(this.getResponseProperty("challenge")),this.excludeCredentials=this.getResponseProperty("excludeCredentials").map((e=>(e.id=p.fromUrlB64ToArray(e.id).buffer,e))),this.extensions=this.getResponseProperty("extensions"),this.pubKeyCredParams=this.getResponseProperty("pubKeyCredParams"),this.rp=this.getResponseProperty("rp"),this.timeout=this.getResponseProperty("timeout");const t=this.getResponseProperty("user");t.id=p.fromUrlB64ToArray(t.id),this.user=t}}class mu extends J{constructor(e){super(e),this.enabled=this.getResponseProperty("Enabled"),this.key1=this.getResponseProperty("Key1"),this.key2=this.getResponseProperty("Key2"),this.key3=this.getResponseProperty("Key3"),this.key4=this.getResponseProperty("Key4"),this.key5=this.getResponseProperty("Key5"),this.nfc=this.getResponseProperty("Nfc")}}class wu extends J{constructor(e){super(e),this.type=this.getResponseProperty("Type"),this.cardBrand=this.getResponseProperty("CardBrand"),this.description=this.getResponseProperty("Description"),this.needsVerification=this.getResponseProperty("NeedsVerification")}}class Su extends J{constructor(e){super(e),this.url=this.getResponseProperty("Url"),this.pdfUrl=this.getResponseProperty("PdfUrl"),this.number=this.getResponseProperty("Number"),this.paid=this.getResponseProperty("Paid"),this.date=this.getResponseProperty("Date"),this.amount=this.getResponseProperty("Amount")}}class bu extends J{constructor(e){super(e),this.createdDate=this.getResponseProperty("CreatedDate"),this.amount=this.getResponseProperty("Amount"),this.refunded=this.getResponseProperty("Refunded"),this.partiallyRefunded=this.getResponseProperty("PartiallyRefunded"),this.refundedAmount=this.getResponseProperty("RefundedAmount"),this.type=this.getResponseProperty("Type"),this.paymentMethodType=this.getResponseProperty("PaymentMethodType"),this.details=this.getResponseProperty("Details")}}class Pu extends J{constructor(e){super(e),this.invoices=[],this.transactions=[];const t=this.getResponseProperty("Transactions"),i=this.getResponseProperty("Invoices");null!=t&&(this.transactions=t.map((e=>new bu(e)))),null!=i&&(this.invoices=i.map((e=>new Su(e))))}get hasNoHistory(){return 0==this.invoices.length&&0==this.transactions.length}}class ku extends J{constructor(e){super(e),this.balance=this.getResponseProperty("Balance");const t=this.getResponseProperty("PaymentSource");this.paymentSource=null==t?null:new wu(t)}}class Ou extends J{constructor(e){var t,i,n,r;super(e),this.id=this.getResponseProperty("Id"),this.name=this.getResponseProperty("Name"),this.usePolicies=this.getResponseProperty("UsePolicies"),this.useGroups=this.getResponseProperty("UseGroups"),this.useDirectory=this.getResponseProperty("UseDirectory"),this.useEvents=this.getResponseProperty("UseEvents"),this.useTotp=this.getResponseProperty("UseTotp"),this.use2fa=this.getResponseProperty("Use2fa"),this.useApi=this.getResponseProperty("UseApi"),this.useSso=this.getResponseProperty("UseSso"),this.useKeyConnector=null!==(t=this.getResponseProperty("UseKeyConnector"))&&void 0!==t&&t,this.useScim=null!==(i=this.getResponseProperty("UseScim"))&&void 0!==i&&i,this.useCustomPermissions=null!==(n=this.getResponseProperty("UseCustomPermissions"))&&void 0!==n&&n,this.useResetPassword=this.getResponseProperty("UseResetPassword"),this.useSecretsManager=this.getResponseProperty("UseSecretsManager"),this.usePasswordManager=this.getResponseProperty("UsePasswordManager"),this.useActivateAutofillPolicy=this.getResponseProperty("UseActivateAutofillPolicy"),this.selfHost=this.getResponseProperty("SelfHost"),this.usersGetPremium=this.getResponseProperty("UsersGetPremium"),this.seats=this.getResponseProperty("Seats"),this.maxCollections=this.getResponseProperty("MaxCollections"),this.maxStorageGb=this.getResponseProperty("MaxStorageGb"),this.key=this.getResponseProperty("Key"),this.hasPublicAndPrivateKeys=this.getResponseProperty("HasPublicAndPrivateKeys"),this.status=this.getResponseProperty("Status"),this.type=this.getResponseProperty("Type"),this.enabled=this.getResponseProperty("Enabled"),this.ssoBound=this.getResponseProperty("SsoBound"),this.identifier=this.getResponseProperty("Identifier"),this.permissions=new Zd(this.getResponseProperty("permissions")),this.resetPasswordEnrolled=this.getResponseProperty("ResetPasswordEnrolled"),this.userId=this.getResponseProperty("UserId"),this.providerId=this.getResponseProperty("ProviderId"),this.providerName=this.getResponseProperty("ProviderName"),this.providerType=this.getResponseProperty("ProviderType"),this.familySponsorshipFriendlyName=this.getResponseProperty("FamilySponsorshipFriendlyName"),this.familySponsorshipAvailable=this.getResponseProperty("FamilySponsorshipAvailable"),this.planProductType=this.getResponseProperty("PlanProductType"),this.keyConnectorEnabled=null!==(r=this.getResponseProperty("KeyConnectorEnabled"))&&void 0!==r&&r,this.keyConnectorUrl=this.getResponseProperty("KeyConnectorUrl");const s=this.getResponseProperty("FamilySponsorshipLastSyncDate");s&&(this.familySponsorshipLastSyncDate=new Date(s));const o=this.getResponseProperty("FamilySponsorshipValidUntil");o&&(this.familySponsorshipValidUntil=new Date(o)),this.familySponsorshipToDelete=this.getResponseProperty("FamilySponsorshipToDelete"),this.accessSecretsManager=this.getResponseProperty("AccessSecretsManager"),this.limitCollectionCreationDeletion=this.getResponseProperty("LimitCollectionCreationDeletion"),this.allowAdminAccessToAllCollectionItems=this.getResponseProperty("AllowAdminAccessToAllCollectionItems"),this.flexibleCollections=this.getResponseProperty("FlexibleCollections")}}class Cu extends Ou{constructor(e){super(e),this.keyConnectorEnabled=!1}}class Au extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.name=this.getResponseProperty("Name"),this.key=this.getResponseProperty("Key"),this.status=this.getResponseProperty("Status"),this.type=this.getResponseProperty("Type"),this.enabled=this.getResponseProperty("Enabled"),this.permissions=new Zd(this.getResponseProperty("permissions")),this.userId=this.getResponseProperty("UserId"),this.useEvents=this.getResponseProperty("UseEvents")}}class Du extends J{constructor(e){var t,i;super(e),this.organizations=[],this.providers=[],this.providerOrganizations=[],this.id=this.getResponseProperty("Id"),this.name=this.getResponseProperty("Name"),this.email=this.getResponseProperty("Email"),this.emailVerified=this.getResponseProperty("EmailVerified"),this.masterPasswordHint=this.getResponseProperty("MasterPasswordHint"),this.premiumPersonally=this.getResponseProperty("Premium"),this.premiumFromOrganization=this.getResponseProperty("PremiumFromOrganization"),this.culture=this.getResponseProperty("Culture"),this.twoFactorEnabled=this.getResponseProperty("TwoFactorEnabled"),this.key=this.getResponseProperty("Key"),this.avatarColor=this.getResponseProperty("AvatarColor"),this.creationDate=this.getResponseProperty("CreationDate"),this.privateKey=this.getResponseProperty("PrivateKey"),this.securityStamp=this.getResponseProperty("SecurityStamp"),this.forcePasswordReset=null!==(t=this.getResponseProperty("ForcePasswordReset"))&&void 0!==t&&t,this.usesKeyConnector=null!==(i=this.getResponseProperty("UsesKeyConnector"))&&void 0!==i&&i;const n=this.getResponseProperty("Organizations");null!=n&&(this.organizations=n.map((e=>new Ou(e))));const r=this.getResponseProperty("Providers");null!=r&&(this.providers=r.map((e=>new Au(e))));const s=this.getResponseProperty("ProviderOrganizations");null!=s&&(this.providerOrganizations=s.map((e=>new Cu(e))))}}class xu extends J{constructor(e){super(e);const t=this.getResponseProperty("UserProfile");null!=t&&(this.userProfile=new Du(t)),this.paymentIntentClientSecret=this.getResponseProperty("PaymentIntentClientSecret"),this.success=this.getResponseProperty("Success")}}class Iu extends J{constructor(e){super(e),this.type=this.getResponseProperty("Type"),this.product=this.getResponseProperty("Product"),this.name=this.getResponseProperty("Name"),this.isAnnual=this.getResponseProperty("IsAnnual"),this.nameLocalizationKey=this.getResponseProperty("NameLocalizationKey"),this.descriptionLocalizationKey=this.getResponseProperty("DescriptionLocalizationKey"),this.canBeUsedByBusiness=this.getResponseProperty("CanBeUsedByBusiness"),this.trialPeriodDays=this.getResponseProperty("TrialPeriodDays"),this.hasSelfHost=this.getResponseProperty("HasSelfHost"),this.hasPolicies=this.getResponseProperty("HasPolicies"),this.hasGroups=this.getResponseProperty("HasGroups"),this.hasDirectory=this.getResponseProperty("HasDirectory"),this.hasEvents=this.getResponseProperty("HasEvents"),this.hasTotp=this.getResponseProperty("HasTotp"),this.has2fa=this.getResponseProperty("Has2fa"),this.hasApi=this.getResponseProperty("HasApi"),this.hasSso=this.getResponseProperty("HasSso"),this.hasResetPassword=this.getResponseProperty("HasResetPassword"),this.usersGetPremium=this.getResponseProperty("UsersGetPremium"),this.upgradeSortOrder=this.getResponseProperty("UpgradeSortOrder"),this.displaySortOrder=this.getResponseProperty("DisplaySortOrder"),this.legacyYear=this.getResponseProperty("LegacyYear"),this.disabled=this.getResponseProperty("Disabled");const t=this.getResponseProperty("PasswordManager"),i=this.getResponseProperty("SecretsManager");this.PasswordManager=null==t?null:new Tu(t),this.SecretsManager=null==i?null:new Uu(i)}}class Uu extends J{constructor(e){super(e),this.stripeSeatPlanId=this.getResponseProperty("StripeSeatPlanId"),this.baseSeats=this.getResponseProperty("BaseSeats"),this.basePrice=this.getResponseProperty("BasePrice"),this.seatPrice=this.getResponseProperty("SeatPrice"),this.hasAdditionalSeatsOption=this.getResponseProperty("HasAdditionalSeatsOption"),this.maxAdditionalSeats=this.getResponseProperty("MaxAdditionalSeats"),this.maxSeats=this.getResponseProperty("MaxSeats"),this.stripeServiceAccountPlanId=this.getResponseProperty("StripeServiceAccountPlanId"),this.additionalPricePerServiceAccount=this.getResponseProperty("AdditionalPricePerServiceAccount"),this.baseServiceAccount=this.getResponseProperty("BaseServiceAccount"),this.maxServiceAccount=this.getResponseProperty("MaxServiceAccount"),this.hasAdditionalServiceAccountOption=this.getResponseProperty("HasAdditionalServiceAccountOption"),this.maxAdditionalServiceAccounts=this.getResponseProperty("MaxAdditionalServiceAccounts"),this.maxProjects=this.getResponseProperty("MaxProjects")}}class Tu extends J{constructor(e){super(e),this.stripePlanId=this.getResponseProperty("StripePlanId"),this.stripeSeatPlanId=this.getResponseProperty("StripeSeatPlanId"),this.stripeStoragePlanId=this.getResponseProperty("StripeStoragePlanId"),this.stripePremiumAccessPlanId=this.getResponseProperty("StripePremiumAccessPlanId"),this.basePrice=this.getResponseProperty("BasePrice"),this.seatPrice=this.getResponseProperty("SeatPrice"),this.baseSeats=this.getResponseProperty("BaseSeats"),this.maxAdditionalSeats=this.getResponseProperty("MaxAdditionalSeats"),this.premiumAccessOptionPrice=this.getResponseProperty("PremiumAccessOptionPrice"),this.maxSeats=this.getResponseProperty("MaxSeats"),this.additionalStoragePricePerGb=this.getResponseProperty("AdditionalStoragePricePerGb"),this.hasAdditionalSeatsOption=this.getResponseProperty("HasAdditionalSeatsOption"),this.baseStorageGb=this.getResponseProperty("BaseStorageGb"),this.maxCollections=this.getResponseProperty("MaxCollections"),this.hasAdditionalStorageOption=this.getResponseProperty("HasAdditionalStorageOption"),this.maxAdditionalStorage=this.getResponseProperty("MaxAdditionalStorage"),this.hasPremiumAccessOption=this.getResponseProperty("HasPremiumAccessOption")}}class Nu extends J{constructor(e){super(e),this.storageName=this.getResponseProperty("StorageName"),this.storageGb=this.getResponseProperty("StorageGb"),this.maxStorageGb=this.getResponseProperty("MaxStorageGb"),this.license=this.getResponseProperty("License"),this.expiration=this.getResponseProperty("Expiration");const t=this.getResponseProperty("Subscription"),i=this.getResponseProperty("UpcomingInvoice");this.subscription=null==t?null:new Ru(t),this.upcomingInvoice=null==i?null:new Fu(i)}}class Ru extends J{constructor(e){super(e),this.items=[],this.trialStartDate=this.getResponseProperty("TrialStartDate"),this.trialEndDate=this.getResponseProperty("TrialEndDate"),this.periodStartDate=this.getResponseProperty("PeriodStartDate"),this.periodEndDate=this.getResponseProperty("PeriodEndDate"),this.cancelledDate=this.getResponseProperty("CancelledDate"),this.cancelAtEndDate=this.getResponseProperty("CancelAtEndDate"),this.status=this.getResponseProperty("Status"),this.cancelled=this.getResponseProperty("Cancelled");const t=this.getResponseProperty("Items");null!=t&&(this.items=t.map((e=>new Eu(e))))}}class Eu extends J{constructor(e){super(e),this.productId=this.getResponseProperty("ProductId"),this.name=this.getResponseProperty("Name"),this.amount=this.getResponseProperty("Amount"),this.quantity=this.getResponseProperty("Quantity"),this.interval=this.getResponseProperty("Interval"),this.sponsoredSubscriptionItem=this.getResponseProperty("SponsoredSubscriptionItem"),this.addonSubscriptionItem=this.getResponseProperty("AddonSubscriptionItem")}}class Fu extends J{constructor(e){super(e),this.date=this.getResponseProperty("Date"),this.amount=this.getResponseProperty("Amount")}}class Mu extends J{constructor(e){super(e),this.taxId=this.getResponseProperty("TaxIdNumber"),this.taxIdType=this.getResponseProperty("TaxIdType"),this.line1=this.getResponseProperty("Line1"),this.line2=this.getResponseProperty("Line2"),this.city=this.getResponseProperty("City"),this.state=this.getResponseProperty("State"),this.postalCode=this.getResponseProperty("PostalCode"),this.country=this.getResponseProperty("Country")}}class Ku extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.country=this.getResponseProperty("Country"),this.state=this.getResponseProperty("State"),this.postalCode=this.getResponseProperty("PostalCode"),this.rate=this.getResponseProperty("Rate")}}class Lu{constructor(e){this.ids=null==e?[]:e}}class zu extends J{constructor(e){super(e),this.addedDate=this.getResponseProperty("AddedDate"),this.breachDate=this.getResponseProperty("BreachDate"),this.dataClasses=this.getResponseProperty("DataClasses"),this.description=this.getResponseProperty("Description"),this.domain=this.getResponseProperty("Domain"),this.isActive=this.getResponseProperty("IsActive"),this.isVerified=this.getResponseProperty("IsVerified"),this.logoPath=this.getResponseProperty("LogoPath"),this.modifiedDate=this.getResponseProperty("ModifiedDate"),this.name=this.getResponseProperty("Name"),this.pwnCount=this.getResponseProperty("PwnCount"),this.title=this.getResponseProperty("Title")}}class Vu extends J{constructor(e){super(e),this.type=this.getResponseProperty("Type"),this.domains=this.getResponseProperty("Domains"),this.excluded=this.getResponseProperty("Excluded")}}class Bu extends J{constructor(e){super(e),this.globalEquivalentDomains=[],this.equivalentDomains=this.getResponseProperty("EquivalentDomains");const t=this.getResponseProperty("GlobalEquivalentDomains");this.globalEquivalentDomains=null!=t?t.map((e=>new Vu(e))):[]}}class _u extends J{constructor(e){super(e),this.type=this.getResponseProperty("Type"),this.userId=this.getResponseProperty("UserId"),this.organizationId=this.getResponseProperty("OrganizationId"),this.providerId=this.getResponseProperty("ProviderId"),this.cipherId=this.getResponseProperty("CipherId"),this.collectionId=this.getResponseProperty("CollectionId"),this.groupId=this.getResponseProperty("GroupId"),this.policyId=this.getResponseProperty("PolicyId"),this.organizationUserId=this.getResponseProperty("OrganizationUserId"),this.providerUserId=this.getResponseProperty("ProviderUserId"),this.providerOrganizationId=this.getResponseProperty("ProviderOrganizationId"),this.actingUserId=this.getResponseProperty("ActingUserId"),this.date=this.getResponseProperty("Date"),this.deviceType=this.getResponseProperty("DeviceType"),this.ipAddress=this.getResponseProperty("IpAddress"),this.installationId=this.getResponseProperty("InstallationId"),this.systemUser=this.getResponseProperty("SystemUser"),this.domainName=this.getResponseProperty("DomainName"),this.secretId=this.getResponseProperty("SecretId"),this.serviceAccountId=this.getResponseProperty("ServiceAccountId")}}class ju extends J{constructor(e){super(e),this.userId=this.getResponseProperty("UserId"),this.publicKey=this.getResponseProperty("PublicKey")}}class $u extends J{constructor(e){super(e),this.url=null,this.attachmentId=this.getResponseProperty("AttachmentId"),this.fileUploadType=this.getResponseProperty("FileUploadType");const t=this.getResponseProperty("CipherResponse"),i=this.getResponseProperty("CipherMiniResponse");this.cipherResponse=null==t?null:new Bd(t),this.cipherMiniResponse=null==i?null:new Bd(i),this.url=this.getResponseProperty("Url")}}class Wu extends J{constructor(e=null){super(e),null!=e&&(this.id=this.getResponseProperty("Id"),this.fileName=this.getResponseProperty("FileName"),this.size=this.getResponseProperty("Size"),this.sizeName=this.getResponseProperty("SizeName"))}}class qu extends J{constructor(e=null){super(e),null!=e&&(this.text=this.getResponseProperty("Text"),this.hidden=this.getResponseProperty("Hidden")||!1)}}class Hu extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.accessId=this.getResponseProperty("AccessId"),this.type=this.getResponseProperty("Type"),this.name=this.getResponseProperty("Name"),this.notes=this.getResponseProperty("Notes"),this.key=this.getResponseProperty("Key"),this.maxAccessCount=this.getResponseProperty("MaxAccessCount"),this.accessCount=this.getResponseProperty("AccessCount"),this.revisionDate=this.getResponseProperty("RevisionDate"),this.expirationDate=this.getResponseProperty("ExpirationDate"),this.deletionDate=this.getResponseProperty("DeletionDate"),this.password=this.getResponseProperty("Password"),this.disable=this.getResponseProperty("Disabled")||!1,this.hideEmail=this.getResponseProperty("HideEmail")||!1;const t=this.getResponseProperty("Text");null!=t&&(this.text=new qu(t));const i=this.getResponseProperty("File");null!=i&&(this.file=new Wu(i))}}class Gu extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.name=this.getResponseProperty("Name"),this.revisionDate=this.getResponseProperty("RevisionDate")}}class Ju extends J{constructor(e){super(e),this.folders=[],this.collections=[],this.ciphers=[],this.policies=[],this.sends=[];const t=this.getResponseProperty("Profile");null!=t&&(this.profile=new Du(t));const i=this.getResponseProperty("Folders");null!=i&&(this.folders=i.map((e=>new Gu(e))));const n=this.getResponseProperty("Collections");null!=n&&(this.collections=n.map((e=>new $d(e))));const r=this.getResponseProperty("Ciphers");null!=r&&(this.ciphers=r.map((e=>new Bd(e))));const s=this.getResponseProperty("Domains");null!=s&&(this.domains=new Bu(s));const o=this.getResponseProperty("Policies");null!=o&&(this.policies=o.map((e=>new dn(e))));const a=this.getResponseProperty("Sends");null!=a&&(this.sends=a.map((e=>new Hu(e))))}}var Yu=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Qu{constructor(e,t,i,n,r,s,o=null){this.tokenService=e,this.platformUtilsService=t,this.environmentService=i,this.appIdService=n,this.stateService=r,this.logoutCallback=s,this.customUserAgent=o,this.isWebClient=!1,this.isDesktopClient=!1,this.device=t.getDevice(),this.deviceType=this.device.toString(),this.isWebClient=this.device===ee.IEBrowser||this.device===ee.ChromeBrowser||this.device===ee.EdgeBrowser||this.device===ee.FirefoxBrowser||this.device===ee.OperaBrowser||this.device===ee.SafariBrowser||this.device===ee.UnknownBrowser||this.device===ee.VivaldiBrowser,this.isDesktopClient=this.device===ee.WindowsDesktop||this.device===ee.MacOsDesktop||this.device===ee.LinuxDesktop||this.device===ee.WindowsCLI||this.device===ee.MacOsCLI||this.device===ee.LinuxCLI}postIdentityToken(e){return Yu(this,void 0,void 0,(function*(){const t=new Headers({"Content-Type":"application/x-www-form-urlencoded; charset=utf-8",Accept:"application/json","Device-Type":this.deviceType});null!=this.customUserAgent&&t.set("User-Agent",this.customUserAgent),e.alterIdentityTokenHeaders(t);const i=e instanceof It?e.toIdentityToken():e.toIdentityToken(this.platformUtilsService.getClientType()),n=yield(0,r.z)(this.environmentService.environment$),s=yield this.fetch(new Request(n.getIdentityUrl()+"/connect/token",{body:this.qsStringify(i),credentials:yield this.getCredentials(),cache:"no-store",headers:t,method:"POST"}));let o=null;if(this.isJsonResponse(s)&&(o=yield s.json()),null!=o){if(200===s.status)return new he(o);if(400===s.status&&o.TwoFactorProviders2&&Object.keys(o.TwoFactorProviders2).length)return new pe(o);if(400===s.status&&o.HCaptcha_SiteKey&&Object.keys(o.HCaptcha_SiteKey).length)return new oe(o)}return Promise.reject(new Y(o,s.status,!0))}))}refreshIdentityToken(){return Yu(this,void 0,void 0,(function*(){try{yield this.doAuthRefresh()}catch(e){return Promise.reject(null)}}))}postAuthRequest(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("POST","/auth-requests/",e,!1,!0);return new ru(t)}))}postAdminAuthRequest(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("POST","/auth-requests/admin-request",e,!0,!0);return new ru(t)}))}getAuthResponse(e,t){return Yu(this,void 0,void 0,(function*(){const i=`/auth-requests/${e}/response?code=${t}`,n=yield this.send("GET",i,null,!1,!0);return new ru(n)}))}getAuthRequest(e){return Yu(this,void 0,void 0,(function*(){const t=`/auth-requests/${e}`,i=yield this.send("GET",t,null,!0,!0);return new ru(i)}))}putAuthRequest(e,t){return Yu(this,void 0,void 0,(function*(){const i=`/auth-requests/${e}`,n=yield this.send("PUT",i,t,!0,!0);return new ru(n)}))}getAuthRequests(){return Yu(this,void 0,void 0,(function*(){const e=yield this.send("GET","/auth-requests/",null,!0,!0);return new an(e,ru)}))}getLastAuthRequest(){return Yu(this,void 0,void 0,(function*(){const e=(yield this.getAuthRequests()).data.filter((e=>!e.isAnswered&&!e.isExpired));return e.sort(((e,t)=>e.creationDate.localeCompare(t.creationDate)))[e.length-1]}))}getProfile(){return Yu(this,void 0,void 0,(function*(){const e=yield this.send("GET","/accounts/profile",null,!0,!0);return new Du(e)}))}getUserSubscription(){return Yu(this,void 0,void 0,(function*(){const e=yield this.send("GET","/accounts/subscription",null,!0,!0);return new Nu(e)}))}getTaxInfo(){return Yu(this,void 0,void 0,(function*(){const e=yield this.send("GET","/accounts/tax",null,!0,!0);return new Mu(e)}))}putProfile(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("PUT","/accounts/profile",e,!0,!0);return new Du(t)}))}putAvatar(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("PUT","/accounts/avatar",e,!0,!0);return new Du(t)}))}putTaxInfo(e){return this.send("PUT","/accounts/tax",e,!0,!1)}postPrelogin(e){return Yu(this,void 0,void 0,(function*(){const t=yield(0,r.z)(this.environmentService.environment$),i=yield this.send("POST","/accounts/prelogin",e,!1,!0,t.getIdentityUrl());return new au(i)}))}postEmailToken(e){return this.send("POST","/accounts/email-token",e,!0,!1)}postEmail(e){return this.send("POST","/accounts/email",e,!0,!1)}postPassword(e){return this.send("POST","/accounts/password",e,!0,!1)}setPassword(e){return this.send("POST","/accounts/set-password",e,!0,!1)}postSetKeyConnectorKey(e){return this.send("POST","/accounts/set-key-connector-key",e,!0,!1)}postSecurityStamp(e){return this.send("POST","/accounts/security-stamp",e,!0,!1)}getAccountRevisionDate(){return Yu(this,void 0,void 0,(function*(){return yield this.send("GET","/accounts/revision-date",null,!0,!0)}))}postPasswordHint(e){return this.send("POST","/accounts/password-hint",e,!1,!1)}postRegister(e){return Yu(this,void 0,void 0,(function*(){const t=yield(0,r.z)(this.environmentService.environment$),i=yield this.send("POST","/accounts/register",e,!1,!0,t.getIdentityUrl());return new lu(i)}))}postPremium(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("POST","/accounts/premium",e,!0,!0);return new xu(t)}))}postReinstatePremium(){return this.send("POST","/accounts/reinstate-premium",null,!0,!1)}postAccountStorage(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("POST","/accounts/storage",e,!0,!0);return new xu(t)}))}postAccountPayment(e){return this.send("POST","/accounts/payment",e,!0,!1)}postAccountLicense(e){return this.send("POST","/accounts/license",e,!0,!1)}postAccountKeys(e){return this.send("POST","/accounts/keys",e,!0,!1)}postAccountVerifyEmail(){return this.send("POST","/accounts/verify-email",null,!0,!1)}postAccountVerifyEmailToken(e){return this.send("POST","/accounts/verify-email-token",e,!1,!1)}postAccountVerifyPassword(e){return this.send("POST","/accounts/verify-password",e,!0,!0)}postAccountRecoverDelete(e){return this.send("POST","/accounts/delete-recover",e,!1,!1)}postAccountRecoverDeleteToken(e){return this.send("POST","/accounts/delete-recover-token",e,!1,!1)}postAccountKdf(e){return this.send("POST","/accounts/kdf",e,!0,!1)}deleteSsoUser(e){return Yu(this,void 0,void 0,(function*(){return this.send("DELETE","/accounts/sso/"+e,null,!0,!1)}))}getSsoUserIdentifier(){return Yu(this,void 0,void 0,(function*(){return this.send("GET","/accounts/sso/user-identifier",null,!0,!0)}))}postUserApiKey(e,t){return Yu(this,void 0,void 0,(function*(){const e=yield this.send("POST","/accounts/api-key",t,!0,!0);return new nu(e)}))}postUserRotateApiKey(e,t){return Yu(this,void 0,void 0,(function*(){const e=yield this.send("POST","/accounts/rotate-api-key",t,!0,!0);return new nu(e)}))}putUpdateTempPassword(e){return this.send("PUT","/accounts/update-temp-password",e,!0,!1)}postConvertToKeyConnector(){return this.send("POST","/accounts/convert-to-key-connector",null,!0,!1)}getUserBillingHistory(){return Yu(this,void 0,void 0,(function*(){const e=yield this.send("GET","/accounts/billing/history",null,!0,!0);return new Pu(e)}))}getUserBillingPayment(){return Yu(this,void 0,void 0,(function*(){const e=yield this.send("GET","/accounts/billing/payment-method",null,!0,!0);return new ku(e)}))}getCipher(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("GET","/ciphers/"+e,null,!0,!0);return new Bd(t)}))}getFullCipherDetails(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("GET","/ciphers/"+e+"/details",null,!0,!0);return new Bd(t)}))}getCipherAdmin(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("GET","/ciphers/"+e+"/admin",null,!0,!0);return new Bd(t)}))}getCiphersOrganization(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("GET","/ciphers/organization-details?organizationId="+e,null,!0,!0);return new an(t,Bd)}))}postCipher(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("POST","/ciphers",e,!0,!0);return new Bd(t)}))}postCipherCreate(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("POST","/ciphers/create",e,!0,!0);return new Bd(t)}))}postCipherAdmin(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("POST","/ciphers/admin",e,!0,!0);return new Bd(t)}))}putCipher(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("PUT","/ciphers/"+e,t,!0,!0);return new Bd(i)}))}putPartialCipher(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("PUT","/ciphers/"+e+"/partial",t,!0,!0);return new Bd(i)}))}putCipherAdmin(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("PUT","/ciphers/"+e+"/admin",t,!0,!0);return new Bd(i)}))}deleteCipher(e){return this.send("DELETE","/ciphers/"+e,null,!0,!1)}deleteCipherAdmin(e){return this.send("DELETE","/ciphers/"+e+"/admin",null,!0,!1)}deleteManyCiphers(e){return this.send("DELETE","/ciphers",e,!0,!1)}deleteManyCiphersAdmin(e){return this.send("DELETE","/ciphers/admin",e,!0,!1)}putMoveCiphers(e){return this.send("PUT","/ciphers/move",e,!0,!1)}putShareCipher(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("PUT","/ciphers/"+e+"/share",t,!0,!0);return new Bd(i)}))}putShareCiphers(e){return this.send("PUT","/ciphers/share",e,!0,!1)}putCipherCollections(e,t){return this.send("PUT","/ciphers/"+e+"/collections",t,!0,!1)}putCipherCollectionsAdmin(e,t){return this.send("PUT","/ciphers/"+e+"/collections-admin",t,!0,!1)}postPurgeCiphers(e,t=null){let i="/ciphers/purge";return null!=t&&(i+="?organizationId="+t),this.send("POST",i,e,!0,!1)}putDeleteCipher(e){return this.send("PUT","/ciphers/"+e+"/delete",null,!0,!1)}putDeleteCipherAdmin(e){return this.send("PUT","/ciphers/"+e+"/delete-admin",null,!0,!1)}putDeleteManyCiphers(e){return this.send("PUT","/ciphers/delete",e,!0,!1)}putDeleteManyCiphersAdmin(e){return this.send("PUT","/ciphers/delete-admin",e,!0,!1)}putRestoreCipher(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("PUT","/ciphers/"+e+"/restore",null,!0,!0);return new Bd(t)}))}putRestoreCipherAdmin(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("PUT","/ciphers/"+e+"/restore-admin",null,!0,!0);return new Bd(t)}))}putRestoreManyCiphers(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("PUT","/ciphers/restore",e,!0,!0);return new an(t,Bd)}))}putRestoreManyCiphersAdmin(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("PUT","/ciphers/restore-admin",e,!0,!0);return new an(t,Bd)}))}getAttachmentData(e,t,i){return Yu(this,void 0,void 0,(function*(){const n=(null!=i?"/emergency-access/"+i+"/":"/ciphers/")+e+"/attachment/"+t,r=yield this.send("GET",n,null,!0,!0);return new zd(r)}))}postCipherAttachment(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("POST","/ciphers/"+e+"/attachment/v2",t,!0,!0);return new $u(i)}))}postCipherAttachmentLegacy(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("POST","/ciphers/"+e+"/attachment",t,!0,!0);return new Bd(i)}))}postCipherAttachmentAdminLegacy(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("POST","/ciphers/"+e+"/attachment-admin",t,!0,!0);return new Bd(i)}))}deleteCipherAttachment(e,t){return this.send("DELETE","/ciphers/"+e+"/attachment/"+t,null,!0,!1)}deleteCipherAttachmentAdmin(e,t){return this.send("DELETE","/ciphers/"+e+"/attachment/"+t+"/admin",null,!0,!1)}postShareCipherAttachment(e,t,i,n){return this.send("POST","/ciphers/"+e+"/attachment/"+t+"/share?organizationId="+n,i,!0,!1)}renewAttachmentUploadUrl(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("GET","/ciphers/"+e+"/attachment/"+t+"/renew",null,!0,!0);return new $u(i)}))}postAttachmentFile(e,t,i){return this.send("POST","/ciphers/"+e+"/attachment/"+t,i,!0,!1)}getCollectionAccessDetails(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("GET","/organizations/"+e+"/collections/"+t+"/details",null,!0,!0);return new Wd(i)}))}getUserCollections(){return Yu(this,void 0,void 0,(function*(){const e=yield this.send("GET","/collections",null,!0,!0);return new an(e,jd)}))}getCollections(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("GET","/organizations/"+e+"/collections",null,!0,!0);return new an(t,jd)}))}getManyCollectionsWithAccessDetails(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("GET","/organizations/"+e+"/collections/details",null,!0,!0);return new an(t,Wd)}))}getCollectionUsers(e,t){return Yu(this,void 0,void 0,(function*(){return(yield this.send("GET","/organizations/"+e+"/collections/"+t+"/users",null,!0,!0)).map((e=>new _d(e)))}))}postCollection(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("POST","/organizations/"+e+"/collections",t,!0,!0);return new $d(i)}))}putCollection(e,t,i){return Yu(this,void 0,void 0,(function*(){const n=yield this.send("PUT","/organizations/"+e+"/collections/"+t,i,!0,!0);return new $d(n)}))}putCollectionUsers(e,t,i){return Yu(this,void 0,void 0,(function*(){yield this.send("PUT","/organizations/"+e+"/collections/"+t+"/users",i,!0,!1)}))}deleteCollection(e,t){return this.send("DELETE","/organizations/"+e+"/collections/"+t,null,!0,!1)}deleteManyCollections(e,t){return this.send("DELETE","/organizations/"+e+"/collections",new Lu(t),!0,!1)}deleteCollectionUser(e,t,i){return this.send("DELETE","/organizations/"+e+"/collections/"+t+"/user/"+i,null,!0,!1)}getGroupUsers(e,t){return Yu(this,void 0,void 0,(function*(){return yield this.send("GET","/organizations/"+e+"/groups/"+t+"/users",null,!0,!0)}))}putGroupUsers(e,t,i){return Yu(this,void 0,void 0,(function*(){yield this.send("PUT","/organizations/"+e+"/groups/"+t+"/users",i,!0,!1)}))}deleteGroupUser(e,t,i){return this.send("DELETE","/organizations/"+e+"/groups/"+t+"/user/"+i,null,!0,!1)}getPlans(){return Yu(this,void 0,void 0,(function*(){const e=yield this.send("GET","/plans",null,!1,!0);return new an(e,Iu)}))}postPublicImportDirectory(e){return Yu(this,void 0,void 0,(function*(){return this.send("POST","/public/organization/import",e,!0,!1)}))}getTaxRates(){return Yu(this,void 0,void 0,(function*(){const e=yield this.send("GET","/plans/sales-tax-rates/",null,!0,!0);return new an(e,Ku)}))}getSettingsDomains(){return Yu(this,void 0,void 0,(function*(){const e=yield this.send("GET","/settings/domains",null,!0,!0);return new Bu(e)}))}putSettingsDomains(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("PUT","/settings/domains",e,!0,!0);return new Bu(t)}))}getSync(){return Yu(this,void 0,void 0,(function*(){const e=this.isDesktopClient||this.isWebClient?"/sync?excludeDomains=true":"/sync",t=yield this.send("GET",e,null,!0,!0);return new Ju(t)}))}getTwoFactorProviders(){return Yu(this,void 0,void 0,(function*(){const e=yield this.send("GET","/two-factor",null,!0,!0);return new an(e,pu)}))}getTwoFactorOrganizationProviders(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("GET","/organizations/"+e+"/two-factor",null,!0,!0);return new an(t,pu)}))}getTwoFactorAuthenticator(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("POST","/two-factor/get-authenticator",e,!0,!0);return new du(t)}))}getTwoFactorEmail(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("POST","/two-factor/get-email",e,!0,!0);return new hu(t)}))}getTwoFactorDuo(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("POST","/two-factor/get-duo",e,!0,!0);return new uu(t)}))}getTwoFactorOrganizationDuo(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("POST","/organizations/"+e+"/two-factor/get-duo",t,!0,!0);return new uu(i)}))}getTwoFactorYubiKey(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("POST","/two-factor/get-yubikey",e,!0,!0);return new mu(t)}))}getTwoFactorWebAuthn(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("POST","/two-factor/get-webauthn",e,!0,!0);return new vu(t)}))}getTwoFactorWebAuthnChallenge(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("POST","/two-factor/get-webauthn-challenge",e,!0,!0);return new gu(t)}))}getTwoFactorRecover(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("POST","/two-factor/get-recover",e,!0,!0);return new yu(t)}))}putTwoFactorAuthenticator(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("PUT","/two-factor/authenticator",e,!0,!0);return new du(t)}))}putTwoFactorEmail(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("PUT","/two-factor/email",e,!0,!0);return new hu(t)}))}putTwoFactorDuo(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("PUT","/two-factor/duo",e,!0,!0);return new uu(t)}))}putTwoFactorOrganizationDuo(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("PUT","/organizations/"+e+"/two-factor/duo",t,!0,!0);return new uu(i)}))}putTwoFactorYubiKey(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("PUT","/two-factor/yubikey",e,!0,!0);return new mu(t)}))}putTwoFactorWebAuthn(e){return Yu(this,void 0,void 0,(function*(){const t=e.deviceResponse.response,i=Object.assign({},e);i.deviceResponse={id:e.deviceResponse.id,rawId:btoa(e.deviceResponse.id),type:e.deviceResponse.type,extensions:e.deviceResponse.getClientExtensionResults(),response:{AttestationObject:p.fromBufferToB64(t.attestationObject),clientDataJson:p.fromBufferToB64(t.clientDataJSON)}};const n=yield this.send("PUT","/two-factor/webauthn",i,!0,!0);return new vu(n)}))}deleteTwoFactorWebAuthn(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("DELETE","/two-factor/webauthn",e,!0,!0);return new vu(t)}))}putTwoFactorDisable(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("PUT","/two-factor/disable",e,!0,!0);return new pu(t)}))}putTwoFactorOrganizationDisable(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("PUT","/organizations/"+e+"/two-factor/disable",t,!0,!0);return new pu(i)}))}postTwoFactorRecover(e){return this.send("POST","/two-factor/recover",e,!1,!1)}postTwoFactorEmailSetup(e){return this.send("POST","/two-factor/send-email",e,!0,!1)}postTwoFactorEmail(e){return this.send("POST","/two-factor/send-email-login",e,!1,!1)}getDeviceVerificationSettings(){return Yu(this,void 0,void 0,(function*(){const e=yield this.send("GET","/two-factor/get-device-verification-settings",null,!0,!0);return new su(e)}))}putDeviceVerificationSettings(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("PUT","/two-factor/device-verification-settings",e,!0,!0);return new su(t)}))}getCloudCommunicationsEnabled(){return Yu(this,void 0,void 0,(function*(){return yield this.send("GET","/organizations/connections/enabled",null,!0,!0)}))}getOrganizationConnection(e,t,i){return Yu(this,void 0,void 0,(function*(){const n=yield this.send("GET",`/organizations/connections/${e}/${t}`,null,!0,!0);return new Td(n,i)}))}createOrganizationConnection(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("POST","/organizations/connections/",e,!0,!0);return new Td(i,t)}))}updateOrganizationConnection(e,t,i){return Yu(this,void 0,void 0,(function*(){const n=yield this.send("PUT","/organizations/connections/"+i,e,!0,!0);return new Td(n,t)}))}deleteOrganizationConnection(e){return Yu(this,void 0,void 0,(function*(){return this.send("DELETE","/organizations/connections/"+e,null,!0,!1)}))}postProviderSetup(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("POST","/providers/"+e+"/setup",t,!0,!0);return new iu(i)}))}getProvider(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("GET","/providers/"+e,null,!0,!0);return new iu(t)}))}putProvider(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("PUT","/providers/"+e,t,!0,!0);return new iu(i)}))}getProviderUsers(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("GET","/providers/"+e+"/users",null,!0,!0);return new an(t,tu)}))}getProviderUser(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("GET","/providers/"+e+"/users/"+t,null,!0,!0);return new eu(i)}))}postProviderUserInvite(e,t){return this.send("POST","/providers/"+e+"/users/invite",t,!0,!1)}postProviderUserReinvite(e,t){return this.send("POST","/providers/"+e+"/users/"+t+"/reinvite",null,!0,!1)}postManyProviderUserReinvite(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("POST","/providers/"+e+"/users/reinvite",t,!0,!0);return new an(i,Xd)}))}postProviderUserBulkConfirm(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("POST","/providers/"+e+"/users/confirm",t,!0,!0);return new an(i,Xd)}))}deleteManyProviderUsers(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("DELETE","/providers/"+e+"/users",t,!0,!0);return new an(i,Xd)}))}postProviderUserAccept(e,t,i){return this.send("POST","/providers/"+e+"/users/"+t+"/accept",i,!0,!1)}postProviderUserConfirm(e,t,i){return this.send("POST","/providers/"+e+"/users/"+t+"/confirm",i,!0,!1)}postProviderUsersPublicKey(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("POST","/providers/"+e+"/users/public-keys",t,!0,!0);return new an(i,Qd)}))}putProviderUser(e,t,i){return this.send("PUT","/providers/"+e+"/users/"+t,i,!0,!1)}deleteProviderUser(e,t){return this.send("DELETE","/providers/"+e+"/users/"+t,null,!0,!1)}getProviderClients(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("GET","/providers/"+e+"/organizations",null,!0,!0);return new an(t,Jd)}))}postProviderAddOrganization(e,t){return this.send("POST","/providers/"+e+"/organizations/add",t,!0,!1)}postProviderCreateOrganization(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.send("POST","/providers/"+e+"/organizations",t,!0,!0);return new Gd(i)}))}deleteProviderOrganization(e,t){return this.send("DELETE","/providers/"+e+"/organizations/"+t,null,!0,!1)}getEvents(e,t,i){return Yu(this,void 0,void 0,(function*(){const n=yield this.send("GET",this.addEventParameters("/events",e,t,i),null,!0,!0);return new an(n,_u)}))}getEventsCipher(e,t,i,n){return Yu(this,void 0,void 0,(function*(){const r=yield this.send("GET",this.addEventParameters("/ciphers/"+e+"/events",t,i,n),null,!0,!0);return new an(r,_u)}))}getEventsOrganization(e,t,i,n){return Yu(this,void 0,void 0,(function*(){const r=yield this.send("GET",this.addEventParameters("/organizations/"+e+"/events",t,i,n),null,!0,!0);return new an(r,_u)}))}getEventsOrganizationUser(e,t,i,n,r){return Yu(this,void 0,void 0,(function*(){const s=yield this.send("GET",this.addEventParameters("/organizations/"+e+"/users/"+t+"/events",i,n,r),null,!0,!0);return new an(s,_u)}))}getEventsProvider(e,t,i,n){return Yu(this,void 0,void 0,(function*(){const r=yield this.send("GET",this.addEventParameters("/providers/"+e+"/events",t,i,n),null,!0,!0);return new an(r,_u)}))}getEventsProviderUser(e,t,i,n,r){return Yu(this,void 0,void 0,(function*(){const s=yield this.send("GET",this.addEventParameters("/providers/"+e+"/users/"+t+"/events",i,n,r),null,!0,!0);return new an(s,_u)}))}postEventsCollect(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.getActiveBearerToken(),i=new Headers({"Device-Type":this.deviceType,Authorization:"Bearer "+t,"Content-Type":"application/json; charset=utf-8"});null!=this.customUserAgent&&i.set("User-Agent",this.customUserAgent);const n=yield(0,r.z)(this.environmentService.environment$);if(200!==(yield this.fetch(new Request(n.getEventsUrl()+"/collect",{cache:"no-store",credentials:yield this.getCredentials(),method:"POST",body:JSON.stringify(e),headers:i}))).status)return Promise.reject("Event post failed.")}))}getUserPublicKey(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("GET","/users/"+e+"/public-key",null,!0,!0);return new ju(t)}))}getHibpBreach(e){return Yu(this,void 0,void 0,(function*(){return(yield this.send("GET","/hibp/breach?username="+e,null,!0,!0)).map((e=>new zu(e)))}))}postBitPayInvoice(e){return Yu(this,void 0,void 0,(function*(){return yield this.send("POST","/bitpay-invoice",e,!0,!0)}))}postSetupPayment(){return Yu(this,void 0,void 0,(function*(){return yield this.send("POST","/setup-payment",null,!0,!0)}))}getMasterKeyFromKeyConnector(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.getActiveBearerToken(),i=yield this.fetch(new Request(e+"/user-keys",{cache:"no-store",method:"GET",headers:new Headers({Accept:"application/json",Authorization:"Bearer "+t})}));if(200!==i.status){const e=yield this.handleError(i,!1,!0);return Promise.reject(e)}return new ou(yield i.json())}))}postUserKeyToKeyConnector(e,t){return Yu(this,void 0,void 0,(function*(){const i=yield this.getActiveBearerToken(),n=yield this.fetch(new Request(e+"/user-keys",{cache:"no-store",method:"POST",headers:new Headers({Accept:"application/json",Authorization:"Bearer "+i,"Content-Type":"application/json; charset=utf-8"}),body:JSON.stringify(t)}));if(200!==n.status){const e=yield this.handleError(n,!1,!0);return Promise.reject(e)}}))}getKeyConnectorAlive(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.fetch(new Request(e+"/alive",{cache:"no-store",method:"GET",headers:new Headers({Accept:"application/json","Content-Type":"application/json; charset=utf-8"})}));if(200!==t.status){const e=yield this.handleError(t,!1,!0);return Promise.reject(e)}}))}getOrganizationExport(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("GET","/organizations/"+e+"/export",null,!0,!0);return new qd(t)}))}getActiveBearerToken(){return Yu(this,void 0,void 0,(function*(){let e=yield this.tokenService.getAccessToken();return(yield this.tokenService.tokenNeedsRefresh())&&(yield this.doAuthRefresh(),e=yield this.tokenService.getAccessToken()),e}))}fetch(e){return Yu(this,void 0,void 0,(function*(){return"GET"===e.method&&(e.headers.set("Cache-Control","no-store"),e.headers.set("Pragma","no-cache")),e.headers.set("Bitwarden-Client-Name",this.platformUtilsService.getClientType()),e.headers.set("Bitwarden-Client-Version",yield this.platformUtilsService.getApplicationVersionNumber()),this.nativeFetch(e)}))}nativeFetch(e){return fetch(e)}preValidateSso(e){return Yu(this,void 0,void 0,(function*(){if(null==e||""===e)throw new Error("Organization Identifier was not provided.");const t=new Headers({Accept:"application/json","Device-Type":this.deviceType});null!=this.customUserAgent&&t.set("User-Agent",this.customUserAgent);const i=yield(0,r.z)(this.environmentService.environment$),n=`/sso/prevalidate?domainHint=${encodeURIComponent(e)}`,s=yield this.fetch(new Request(i.getIdentityUrl()+n,{cache:"no-store",credentials:yield this.getCredentials(),headers:t,method:"GET"}));if(200===s.status){const e=yield s.json();return new cu(e)}{const e=yield this.handleError(s,!1,!0);return Promise.reject(e)}}))}postCreateSponsorship(e,t){return Yu(this,void 0,void 0,(function*(){return yield this.send("POST","/organization/sponsorship/"+(this.platformUtilsService.isSelfHost()?"self-hosted/":"")+e+"/families-for-enterprise",t,!0,!1)}))}getSponsorshipSyncStatus(e){return Yu(this,void 0,void 0,(function*(){const t=yield this.send("GET","/organization/sponsorship/"+e+"/sync-status",null,!0,!0);return new Hd(t)}))}deleteRevokeSponsorship(e){return Yu(this,void 0,void 0,(function*(){return yield this.send("DELETE","/organization/sponsorship/"+(this.platformUtilsService.isSelfHost()?"self-hosted/":"")+e,null,!0,!1)}))}deleteRemoveSponsorship(e){return Yu(this,void 0,void 0,(function*(){return yield this.send("DELETE","/organization/sponsorship/sponsored/"+e,null,!0,!1)}))}postPreValidateSponsorshipToken(e){return Yu(this,void 0,void 0,(function*(){return yield this.send("POST","/organization/sponsorship/validate-token?sponsorshipToken="+encodeURIComponent(e),null,!0,!0)}))}postRedeemSponsorship(e,t){return Yu(this,void 0,void 0,(function*(){return yield this.send("POST","/organization/sponsorship/redeem?sponsorshipToken="+encodeURIComponent(e),t,!0,!1)}))}postResendSponsorshipOffer(e){return Yu(this,void 0,void 0,(function*(){return yield this.send("POST","/organization/sponsorship/"+e+"/families-for-enterprise/resend",null,!0,!1)}))}doAuthRefresh(){return Yu(this,void 0,void 0,(function*(){const e=yield this.tokenService.getRefreshToken();if(null!=e&&""!==e)return this.doRefreshToken();const t=yield this.tokenService.getClientId(),i=yield this.tokenService.getClientSecret();if(!p.isNullOrWhitespace(t)&&!p.isNullOrWhitespace(i))return this.doApiTokenRefresh();throw new Error("Cannot refresh token, no refresh token or api keys are stored")}))}doRefreshToken(){return Yu(this,void 0,void 0,(function*(){const e=yield this.tokenService.getRefreshToken();if(null==e||""===e)throw new Error;const t=new Headers({"Content-Type":"application/x-www-form-urlencoded; charset=utf-8",Accept:"application/json","Device-Type":this.deviceType});null!=this.customUserAgent&&t.set("User-Agent",this.customUserAgent);const i=yield(0,r.z)(this.environmentService.environment$),n=yield this.tokenService.decodeAccessToken(),s=yield this.fetch(new Request(i.getIdentityUrl()+"/connect/token",{body:this.qsStringify({grant_type:"refresh_token",client_id:n.client_id,refresh_token:e}),cache:"no-store",credentials:yield this.getCredentials(),headers:t,method:"POST"}));if(200!==s.status){const e=yield this.handleError(s,!0,!0);return Promise.reject(e)}{const e=yield s.json(),t=new he(e),i=yield this.stateService.getVaultTimeoutAction(),n=yield this.stateService.getVaultTimeout();yield this.tokenService.setTokens(t.accessToken,i,n,t.refreshToken)}}))}doApiTokenRefresh(){return Yu(this,void 0,void 0,(function*(){const e=yield this.tokenService.getClientId(),t=yield this.tokenService.getClientSecret(),i=yield this.appIdService.getAppId(),n=new ie(i,this.platformUtilsService),r=new It(e,t,new s,n),o=yield this.postIdentityToken(r);if(!(o instanceof he))throw new Error("Invalid response received when refreshing api token");const a=yield this.stateService.getVaultTimeoutAction(),l=yield this.stateService.getVaultTimeout();yield this.tokenService.setAccessToken(o.accessToken,a,l)}))}send(e,t,i,n,s,o,a){return Yu(this,void 0,void 0,(function*(){const l=yield(0,r.z)(this.environmentService.environment$);o=p.isNullOrWhitespace(o)?l.getApiUrl():o;const c=t.split("?"),d=o+p.normalizePath(c[0])+(c.length>1?`?${c[1]}`:""),u=new Headers({"Device-Type":this.deviceType});null!=this.customUserAgent&&u.set("User-Agent",this.customUserAgent);const h={cache:"no-store",credentials:yield this.getCredentials(),method:e};if(n){const e=yield this.getActiveBearerToken();u.set("Authorization","Bearer "+e)}null!=i&&("string"==typeof i?(h.body=i,u.set("Content-Type","application/x-www-form-urlencoded; charset=utf-8")):"object"==typeof i&&(i instanceof FormData?h.body=i:(u.set("Content-Type","application/json; charset=utf-8"),h.body=JSON.stringify(i)))),s&&u.set("Accept","application/json"),null!=a&&a(u),h.headers=u;const y=yield this.fetch(new Request(d,h)),v=y.headers.get("content-type"),f=null!=v&&-1!==v.indexOf("application/json");if(s&&200===y.status&&f){return yield y.json()}if(200!==y.status){const e=yield this.handleError(y,!1,n);return Promise.reject(e)}}))}handleError(e,t,i){return Yu(this,void 0,void 0,(function*(){let n=null;return this.isJsonResponse(e)?n=yield e.json():this.isTextResponse(e)&&(n={Message:yield e.text()}),i&&(401===e.status||403===e.status||t&&400===e.status&&null!=n&&"invalid_grant"===n.error)?(yield this.logoutCallback(!0),null):new Y(n,e.status,t)}))}qsStringify(e){return Object.keys(e).map((t=>encodeURIComponent(t)+"="+encodeURIComponent(e[t]))).join("&")}getCredentials(){return Yu(this,void 0,void 0,(function*(){const e=yield(0,r.z)(this.environmentService.environment$);if(!this.isWebClient||e.hasBaseUrl())return"include"}))}addEventParameters(e,t,i,n){return null!=t&&(e+="?start="+t),null!=i&&(e+=e.indexOf("?")>-1?"&":"?",e+="end="+i),null!=n&&(e+=e.indexOf("?")>-1?"&":"?",e+="continuationToken="+n),e}isJsonResponse(e){const t=e.headers.get("content-type");return null!=t&&t.indexOf("application/json")>-1}isTextResponse(e){const t=e.headers.get("content-type");return null!=t&&t.indexOf("text")>-1}}var Xu=function(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},Zu=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},eh=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class th{constructor(e,t){this.cryptoFunctionService=e,this.apiService=t}passwordLeaked(e){return eh(this,void 0,void 0,(function*(){const t=yield this.cryptoFunctionService.hash(e,"sha1"),i=p.fromBufferToHex(t).toUpperCase(),n=i.substr(0,5),r=i.substr(5),s=yield this.apiService.nativeFetch(new Request("https://api.pwnedpasswords.com/range/"+n)),o=(yield s.text()).split(/\r?\n/).find((e=>e.split(":")[0]===r));return null!=o?parseInt(o.split(":")[1],10):0}))}breachedAccounts(e){return eh(this,void 0,void 0,(function*(){try{return yield this.apiService.getHibpBreach(e)}catch(e){if(404===e.statusCode)return[];throw new Error}}))}}var ih,nh;Xu([(ih=100,nh=()=>"passwordLeaked",(e,t,i)=>{const n=i.value,r=new Map;return{value:function(...e){const t=(e=>{let t=r.get(e);return null!=t||(t=new Map,r.set(e,t)),t})(this),i=nh(e);let s=t.get(i);return null==s&&(s=[],t.set(i,s)),new Promise(((o,a)=>{const l=()=>{const c=()=>{s.splice(s.indexOf(l),1),s.length>=ih?s[ih-1]():0===s.length&&(t.delete(i),0===t.size&&r.delete(this))};n.apply(this,e).then((e=>(c(),e))).catch((e=>{throw c(),e})).then(o,a)};s.push(l),s.length<=ih&&l()}))}}}),Zu("design:type",Function),Zu("design:paramtypes",[String]),Zu("design:returntype",Promise)],th.prototype,"passwordLeaked",null);var rh=i(29720),sh=i(99566);class oh{static fromJSON(e){return Object.assign(new oh,e)}}const ah=jt.array(bi,"events",{deserializer:e=>oh.fromJSON(e)});var lh=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class ch{constructor(e,t,i,n,r){this.cipherService=e,this.stateProvider=t,this.organizationService=i,this.eventUploadService=n,this.accountService=r}collect(e,t=null,i=!1,n=null){return lh(this,void 0,void 0,(function*(){const s=yield(0,r.z)(this.stateProvider.activeUserId$),o=this.stateProvider.getUser(s,ah);if(!(yield this.shouldUpdate(t,n)))return;const a=new oh;a.type=e,a.cipherId=t,a.date=(new Date).toISOString(),a.organizationId=n,yield o.update((e=>((e=null!=e?e:[]).push(a),e))),i&&(yield this.eventUploadService.uploadEvents())}))}shouldUpdate(e=null,t=null){return lh(this,void 0,void 0,(function*(){const i=this.organizationService.organizations$.pipe((0,q.U)((e=>{var t,i;return null!==(i=null===(t=null==e?void 0:e.filter((e=>e.useEvents)))||void 0===t?void 0:t.map((e=>e.id)))&&void 0!==i?i:[]}))),n=(0,rh.D)(this.cipherService.get(e)),[s,o,a]=yield(0,r.z)((0,sh.$)(this.accountService.activeAccount$,i,n));return s.status==On.Unlocked&&(null!=o&&0!=o.length&&((null!=a||null!=t)&&(!(null!=a&&!o.includes(null==a?void 0:a.organizationId))&&!(null!=t&&!o.includes(t)))))}))}}class dh{}var uh=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class hh{constructor(e,t,i,n){this.apiService=e,this.stateProvider=t,this.logService=i,this.accountService=n,this.inited=!1}init(e){this.inited||(this.inited=!0,e&&(this.uploadEvents(),setInterval((()=>this.uploadEvents()),6e4)))}uploadEvents(e){return uh(this,void 0,void 0,(function*(){e||(e=yield(0,r.z)(this.stateProvider.activeUserId$));const t=this.accountService.accounts$.pipe((0,q.U)((t=>{var i;return(null===(i=t[e])||void 0===i?void 0:i.status)===On.Unlocked})));if(!(yield(0,r.z)(t)))return;const i=yield this.takeEvents(e);if(null==i||0===i.length)return;const n=i.map((e=>{const t=new dh;return t.type=e.type,t.cipherId=e.cipherId,t.date=e.date,t.organizationId=e.organizationId,t}));try{yield this.apiService.postEventsCollect(n)}catch(t){this.logService.error(t),yield this.stateProvider.setUserState(ah,i,e)}}))}takeEvents(e){return uh(this,void 0,void 0,(function*(){let t=null;return yield this.stateProvider.getUser(e,ah).update((e=>(t=null!=e?e:[],[]))),t}))}}var ph=i(84002),yh=i(63195),vh=i(30325);class fh extends J{constructor(e){super(e),this.contextId=this.getResponseProperty("ContextId"),this.type=this.getResponseProperty("Type");const t=this.getResponseProperty("Payload");switch(this.type){case me.SyncCipherCreate:case me.SyncCipherDelete:case me.SyncCipherUpdate:case me.SyncLoginDelete:this.payload=new gh(t);break;case me.SyncFolderCreate:case me.SyncFolderDelete:case me.SyncFolderUpdate:this.payload=new mh(t);break;case me.SyncVault:case me.SyncCiphers:case me.SyncOrganizations:case me.SyncOrgKeys:case me.SyncSettings:case me.LogOut:this.payload=new wh(t);break;case me.SyncSendCreate:case me.SyncSendUpdate:case me.SyncSendDelete:this.payload=new Sh(t);break;case me.AuthRequest:case me.AuthRequestResponse:this.payload=new bh(t)}}}class gh extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.userId=this.getResponseProperty("UserId"),this.organizationId=this.getResponseProperty("OrganizationId"),this.collectionIds=this.getResponseProperty("CollectionIds"),this.revisionDate=new Date(this.getResponseProperty("RevisionDate"))}}class mh extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.userId=this.getResponseProperty("UserId"),this.revisionDate=new Date(this.getResponseProperty("RevisionDate"))}}class wh extends J{constructor(e){super(e),this.userId=this.getResponseProperty("UserId"),this.date=new Date(this.getResponseProperty("Date"))}}class Sh extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.userId=this.getResponseProperty("UserId"),this.revisionDate=new Date(this.getResponseProperty("RevisionDate"))}}class bh extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.userId=this.getResponseProperty("UserId")}}var Ph=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class kh{constructor(e,t,i,n,r,s,o,a,l){this.logService=e,this.syncService=t,this.appIdService=i,this.apiService=n,this.environmentService=r,this.logoutCallback=s,this.stateService=o,this.authService=a,this.messagingService=l,this.connected=!1,this.inited=!1,this.inactive=!1,this.reconnectTimer=null,this.environmentService.environment$.subscribe((()=>{this.inited&&this.init()}))}init(){return Ph(this,void 0,void 0,(function*(){this.inited=!1,this.url=(yield(0,r.z)(this.environmentService.environment$)).getNotificationsUrl(),"https://-"!==this.url&&(null!=this.signalrConnection&&(this.signalrConnection.off("ReceiveMessage"),this.signalrConnection.off("Heartbeat"),yield this.signalrConnection.stop(),this.connected=!1,this.signalrConnection=null),this.signalrConnection=(new ph.s).withUrl(this.url+"/hub",{accessTokenFactory:()=>this.apiService.getActiveBearerToken(),skipNegotiation:!0,transport:yh.n.WebSockets}).withHubProtocol(new vh.e).build(),this.signalrConnection.on("ReceiveMessage",(e=>this.processNotification(new fh(e)))),this.signalrConnection.on("Heartbeat",(e=>{})),this.signalrConnection.onclose((()=>{this.connected=!1,this.reconnect(!0)})),this.inited=!0,(yield this.isAuthedAndUnlocked())&&(yield this.reconnect(!1)))}))}updateConnection(e=!1){return Ph(this,void 0,void 0,(function*(){if(this.inited)try{(yield this.isAuthedAndUnlocked())?yield this.reconnect(e):yield this.signalrConnection.stop()}catch(e){this.logService.error(e.toString())}}))}reconnectFromActivity(){return Ph(this,void 0,void 0,(function*(){this.inactive=!1,this.inited&&!this.connected&&(yield this.reconnect(!0))}))}disconnectFromInactivity(){return Ph(this,void 0,void 0,(function*(){this.inactive=!0,this.inited&&this.connected&&(yield this.signalrConnection.stop())}))}processNotification(e){return Ph(this,void 0,void 0,(function*(){const t=yield this.appIdService.getAppId();if(null==e||e.contextId===t)return;const i=yield this.stateService.getIsAuthenticated(),n=e.payload.userId||e.payload.UserId,r=yield this.stateService.getUserId();if(!i||null==n||n===r)switch(e.type){case me.SyncCipherCreate:case me.SyncCipherUpdate:yield this.syncService.syncUpsertCipher(e.payload,e.type===me.SyncCipherUpdate);break;case me.SyncCipherDelete:case me.SyncLoginDelete:yield this.syncService.syncDeleteCipher(e.payload);break;case me.SyncFolderCreate:case me.SyncFolderUpdate:yield this.syncService.syncUpsertFolder(e.payload,e.type===me.SyncFolderUpdate);break;case me.SyncFolderDelete:yield this.syncService.syncDeleteFolder(e.payload);break;case me.SyncVault:case me.SyncCiphers:case me.SyncSettings:i&&(yield this.syncService.fullSync(!1));break;case me.SyncOrganizations:i&&(yield this.syncService.fullSync(!0));break;case me.SyncOrgKeys:i&&(yield this.syncService.fullSync(!0),yield this.signalrConnection.stop());break;case me.LogOut:i&&this.logoutCallback(!0);break;case me.SyncSendCreate:case me.SyncSendUpdate:yield this.syncService.syncUpsertSend(e.payload,e.type===me.SyncSendUpdate);break;case me.SyncSendDelete:yield this.syncService.syncDeleteSend(e.payload);break;case me.AuthRequest:(yield this.stateService.getApproveLoginRequests())&&this.messagingService.send("openLoginApproval",{notificationId:e.payload.id})}}))}reconnect(e){return Ph(this,void 0,void 0,(function*(){if(null!=this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.connected||!this.inited||this.inactive)return;if(yield this.isAuthedAndUnlocked()){try{yield this.signalrConnection.start(),this.connected=!0,e&&(yield this.syncService.fullSync(!1))}catch(e){this.logService.error(e)}this.connected||(this.reconnectTimer=setTimeout((()=>this.reconnect(e)),this.random(12e4,3e5)))}}))}isAuthedAndUnlocked(){return Ph(this,void 0,void 0,(function*(){return(yield this.authService.getAuthStatus())>=On.Unlocked}))}random(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e}}var Oh=i(56118),Ch=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Ah{constructor(e,t){this.logService=e,this.i18nService=t,this.indexedEntityId=null,this.indexing=!1,this.index=null,this.immediateSearchLocales=["zh-CN","zh-TW","ja","ko","vi"],this.defaultSearchableMinLength=2,this.searchableMinLength=this.defaultSearchableMinLength,this.i18nService.locale$.subscribe((e=>{-1!==this.immediateSearchLocales.indexOf(e)?this.searchableMinLength=1:this.searchableMinLength=this.defaultSearchableMinLength})),Ah.registeredPipeline||(Ah.registeredPipeline=!0,Oh.Pipeline.registerFunction(this.normalizeAccentsPipelineFunction,"normalizeAccents"))}clearIndex(){this.indexedEntityId=null,this.index=null}isSearchable(e){return!(null==(e=Ah.normalizeSearchQuery(e))||null==this.index&&e.length"))}indexCiphers(e,t){if(this.indexing)return;this.indexing=!0,this.indexedEntityId=t,this.index=null;const i=new Oh.Builder;i.pipeline.add(this.normalizeAccentsPipelineFunction),i.ref("id"),i.field("shortid",{boost:100,extractor:e=>e.id.substr(0,8)}),i.field("name",{boost:10}),i.field("subtitle",{boost:5,extractor:e=>null!=e.subTitle&&e.type===Pe.Card?e.subTitle.replace(/\*/g,""):e.subTitle}),i.field("notes"),i.field("login.username",{extractor:e=>e.type===Pe.Login&&null!=e.login?e.login.username:null}),i.field("login.uris",{boost:2,extractor:e=>this.uriExtractor(e)}),i.field("fields",{extractor:e=>this.fieldExtractor(e,!1)}),i.field("fields_joined",{extractor:e=>this.fieldExtractor(e,!0)}),i.field("attachments",{extractor:e=>this.attachmentExtractor(e,!1)}),i.field("attachments_joined",{extractor:e=>this.attachmentExtractor(e,!0)}),i.field("organizationid",{extractor:e=>e.organizationId}),(e=e||[]).forEach((e=>i.add(e))),this.index=i.build(),this.indexing=!1,this.logService.info("Finished search indexing")}searchCiphers(e,t=null,i){return Ch(this,void 0,void 0,(function*(){const n=[];if(null!=e&&(e=Ah.normalizeSearchQuery(e.trim().toLowerCase())),""===e&&(e=null),null==i&&(i=[]),null!=t&&Array.isArray(t)&&t.length>0?i=i.filter((e=>t.every((t=>null==t||t(e))))):null!=t&&(i=i.filter(t)),!this.isSearchable(e))return i;this.indexing&&(yield new Promise((e=>setTimeout(e,250))),this.indexing&&(yield new Promise((e=>setTimeout(e,500)))));const r=this.getIndexForSearch();if(null==r)return this.searchCiphersBasic(i,e);const s=new Map;i.forEach((e=>s.set(e.id,e)));let o=null;if(null!=e&&e.length>1&&0===e.indexOf(">"))try{o=r.search(e.substr(1).trim())}catch(e){this.logService.error(e)}else{const t=Oh.Query.wildcard.LEADING|Oh.Query.wildcard.TRAILING;o=r.query((i=>{Oh.tokenizer(e).forEach((e=>{const n=e.toString();i.term(n,{fields:["name"],wildcard:t}),i.term(n,{fields:["subtitle"],wildcard:t}),i.term(n,{fields:["login.uris"],wildcard:t}),i.term(n,{})}))}))}return null!=o&&o.forEach((e=>{s.has(e.ref)&&n.push(s.get(e.ref))})),n}))}searchCiphersBasic(e,t,i=!1){return t=Ah.normalizeSearchQuery(t.trim().toLowerCase()),e.filter((e=>i===e.isDeleted&&(null!=e.name&&e.name.toLowerCase().indexOf(t)>-1||(!!(t.length>=8&&e.id.startsWith(t))||(null!=e.subTitle&&e.subTitle.toLowerCase().indexOf(t)>-1||!!(e.login&&e.login.hasUris&&e.login.uris.some((e=>{var i;return(null===(i=null==e?void 0:e.uri)||void 0===i?void 0:i.toLowerCase().indexOf(t))>-1}))))))))}searchSends(e,t){if(null===(t=Ah.normalizeSearchQuery(t.trim().toLocaleLowerCase())))return e;const i=[],n=[];return e.forEach((e=>{var r,s,o;null!=e.name&&e.name.toLowerCase().indexOf(t)>-1?i.push(e):(t.length>=8&&(e.id.startsWith(t)||e.accessId.toLocaleLowerCase().startsWith(t)||null!=(null===(r=e.file)||void 0===r?void 0:r.id)&&e.file.id.startsWith(t))||null!=e.notes&&e.notes.toLowerCase().indexOf(t)>-1||null!=(null===(s=e.text)||void 0===s?void 0:s.text)&&e.text.text.toLowerCase().indexOf(t)>-1||null!=(null===(o=e.file)||void 0===o?void 0:o.fileName)&&e.file.fileName.toLowerCase().indexOf(t)>-1)&&n.push(e)})),i.concat(n)}getIndexForSearch(){return this.index}fieldExtractor(e,t){if(!e.hasFields)return null;let i=[];return e.fields.forEach((e=>{null!=e.name&&i.push(e.name),e.type===ke.Text&&null!=e.value&&i.push(e.value)})),i=i.filter((e=>""!==e.trim())),0===i.length?null:t?i.join(" "):i}attachmentExtractor(e,t){if(!e.hasAttachments)return null;let i=[];return e.attachments.forEach((e=>{null!=e&&null!=e.fileName&&(t&&e.fileName.indexOf(".")>-1?i.push(e.fileName.substr(0,e.fileName.lastIndexOf("."))):i.push(e.fileName))})),i=i.filter((e=>""!==e.trim())),0===i.length?null:t?i.join(" "):i}uriExtractor(e){if(e.type!==Pe.Login||null==e.login||!e.login.hasUris)return null;const t=[];return e.login.uris.forEach((e=>{if(null==e.uri||""===e.uri)return;if(null!=e.hostname)return void t.push(e.hostname);let i=e.uri;if(e.match!==qe){const e=i.indexOf("://");e>-1&&(i=i.substr(e+3));const t=i.search(/\?|&|#/);t>-1&&(i=i.substring(0,t))}t.push(i)})),t.length>0?t:null}normalizeAccentsPipelineFunction(e){const t=["name","login.username","subtitle","notes"];return e.metadata.fields.every((e=>t.includes(e)))?Ah.normalizeSearchQuery(e.toString()):e}static normalizeSearchQuery(e){return null==e?void 0:e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}}Ah.registeredPipeline=!1;var Dh=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class xh{constructor(e,t,i,n,r,s){this.userDecryptionOptionsService=e,this.cryptoService=t,this.tokenService=i,this.policyService=n,this.stateService=r,this.biometricStateService=s}setVaultTimeoutOptions(e,t){return Dh(this,void 0,void 0,(function*(){const i=yield this.tokenService.getAccessToken(),n=yield this.tokenService.getRefreshToken(),r=yield this.tokenService.getClientId(),s=yield this.tokenService.getClientSecret();yield this.stateService.setVaultTimeout(e);const o=yield this.stateService.getVaultTimeoutAction();null==e&&0!==e||t!==ar.LogOut||t===o||(yield this.tokenService.clearTokens()),yield this.stateService.setVaultTimeoutAction(t),yield this.tokenService.setTokens(i,t,e,n,[r,s]),yield this.cryptoService.refreshAdditionalKeys()}))}availableVaultTimeoutActions$(e){return(0,jn.P)((()=>this.getAvailableVaultTimeoutActions(e)))}isPinLockSet(e){return Dh(this,void 0,void 0,(function*(){const t=!!(yield this.stateService.getProtectedPin({userId:e})),i=!!(yield this.stateService.getPinKeyEncryptedUserKey({userId:e})),n=!!(yield this.stateService.getEncryptedPinProtected({userId:e}));return i||n?"PERSISTANT":!t||i||n?"DISABLED":"TRANSIENT"}))}isBiometricLockSet(e){return Dh(this,void 0,void 0,(function*(){const t=null==e?(0,r.z)(this.biometricStateService.biometricUnlockEnabled$):this.biometricStateService.getBiometricUnlockEnabled(e);return yield t}))}getVaultTimeout(e){return Dh(this,void 0,void 0,(function*(){const t=yield this.stateService.getVaultTimeout({userId:e}),i=yield(0,r.z)(this.policyService.getAll$(qi.MaximumVaultTimeout,e));if(null==i?void 0:i.length){let n=Math.min(t,i[0].data.minutes);return(null==t||n<0)&&(n=i[0].data.minutes),t!==n&&(yield this.stateService.setVaultTimeout(n,{userId:e})),n}return t}))}vaultTimeoutAction$(e){return(0,jn.P)((()=>this.getVaultTimeoutAction(e)))}getVaultTimeoutAction(e){return Dh(this,void 0,void 0,(function*(){const t=yield this.getAvailableVaultTimeoutActions();if(1===t.length)return t[0];const i=yield this.stateService.getVaultTimeoutAction({userId:e}),n=yield(0,r.z)(this.policyService.getAll$(qi.MaximumVaultTimeout,e));if(null==n?void 0:n.length){const r=n[0].data.action;if(r&&i!==r&&(yield this.stateService.setVaultTimeoutAction(r,{userId:e})),r&&t.includes(r))return r}if(null==i){const t=(yield this.userHasMasterPassword(e))?ar.Lock:ar.LogOut;return yield this.stateService.setVaultTimeoutAction(t,{userId:e}),t}return i===ar.LogOut?ar.LogOut:ar.Lock}))}getAvailableVaultTimeoutActions(e){return Dh(this,void 0,void 0,(function*(){const t=[ar.LogOut];return((yield this.userHasMasterPassword(e))||"DISABLED"!==(yield this.isPinLockSet(e))||(yield this.isBiometricLockSet(e)))&&t.push(ar.Lock),t}))}clear(e){return Dh(this,void 0,void 0,(function*(){yield this.stateService.setEverBeenUnlocked(!1,{userId:e}),yield this.cryptoService.clearPinKeys(e)}))}userHasMasterPassword(e){return Dh(this,void 0,void 0,(function*(){if(e){const t=yield(0,r.z)(this.userDecryptionOptionsService.userDecryptionOptionsById$(e));if(null!=(null==t?void 0:t.hasMasterPassword))return t.hasMasterPassword}return yield(0,r.z)(this.userDecryptionOptionsService.hasMasterPassword$)}))}}const Ih=function(){const e=Object.freeze({min:5,max:128}),t=Object.freeze({min:0,max:9}),i=Object.freeze({min:0,max:9});return Object.freeze({length:e,minDigits:t,minSpecialCharacters:i})}();class Uh{constructor(e){function t(e,t){return{min:Math.max(t.min,e),max:Math.max(t.max,e)}}this.policy=structuredClone(e),this.minDigits=t(e.numberCount,Ih.minDigits),this.minSpecialCharacters=t(e.specialCount,Ih.minSpecialCharacters);const i=this.minDigits.min+this.minSpecialCharacters.min,n=e.minLength>0?e.minLength:Ih.length.min,r=Math.max(n,i,Ih.length.min);this.length={min:r,max:Math.max(Ih.length.max,r)}}get policyInEffect(){return[this.policy.useUppercase,this.policy.useLowercase,this.policy.useNumbers,this.policy.useSpecial,this.policy.minLength>Ih.length.min,this.policy.numberCount>Ih.minDigits.min,this.policy.specialCount>Ih.minSpecialCharacters.min].includes(!0)}applyPolicy(e){function t(e,t){const{min:i,max:n}=t,r=Math.min(e||0,n);return Math.max(r,i)}const i=this.policy.useUppercase||e.uppercase||!1,n=this.policy.useLowercase||e.lowercase||!1,r=this.policy.useNumbers||e.number||e.minNumber>0,s=this.policy.useSpecial||e.special||e.minSpecial>0,o=t(e.length,this.length),a=t(e.minNumber,this.minDigits),l=t(e.minSpecial,this.minSpecialCharacters);return Object.assign(Object.assign({},e),{length:o,uppercase:i,lowercase:n,number:r,minNumber:a,special:s,minSpecial:l})}sanitize(e){var t;function i(e,t){const i=null!=e?e:t>0;return[i,i?t||1:0]}const[n,r]=i(e.lowercase,e.minLowercase),[s,o]=i(e.uppercase,e.minUppercase),[a,l]=i(e.number,e.minNumber),[c,d]=i(e.special,e.minSpecial),u=r+o+l+d,h=Math.max(u,this.length.min),p=Math.max(null!==(t=e.length)&&void 0!==t?t:h,h);return Object.assign(Object.assign({},e),{length:p,minLength:h,lowercase:n,minLowercase:r,uppercase:s,minUppercase:o,number:a,minNumber:l,special:c,minSpecial:d})}}Object.freeze({length:14,minLength:Ih.length.min,ambiguous:!0,uppercase:!0,lowercase:!0,number:!0,minNumber:1,special:!1,minSpecial:0}),new jt(Si,"passwordGeneratorSettings",{deserializer:e=>e}),new jt(Si,"passphraseGeneratorSettings",{deserializer:e=>e}),new jt(Si,"effUsernameGeneratorSettings",{deserializer:e=>e}),new jt(Si,"catchallGeneratorSettings",{deserializer:e=>e}),new jt(Si,"subaddressGeneratorSettings",{deserializer:e=>e}),new jt(Si,"addyIoForwarder",{deserializer:e=>e}),new jt(Si,"duckDuckGoForwarder",{deserializer:e=>e}),new jt(Si,"fastmailForwarder",{deserializer:e=>e}),new jt(Si,"firefoxRelayForwarder",{deserializer:e=>e}),new jt(Si,"forwardEmailForwarder",{deserializer:e=>e}),new jt(Si,"simpleLoginForwarder",{deserializer:e=>e}),new jt(Si,"passwordGeneratorHistory",{deserializer:e=>e}),Object.freeze({minLength:0,useUppercase:!1,useLowercase:!1,useNumbers:!1,numberCount:0,useSpecial:!1,specialCount:0});class Th extends St{constructor(){super(...arguments),this.defaultType="",this.minLength=0,this.useUppercase=!1,this.useLowercase=!1,this.useNumbers=!1,this.numberCount=0,this.useSpecial=!1,this.specialCount=0,this.minNumberWords=0,this.capitalize=!1,this.includeNumber=!1}inEffect(){return""!==this.defaultType||this.minLength>0||this.numberCount>0||this.specialCount>0||this.useUppercase||this.useLowercase||this.useNumbers||this.useSpecial||this.minNumberWords>0||this.capitalize||this.includeNumber}clone(){const e=new Th;return Object.assign(e,this),e}}const Nh=["abacus","abdomen","abdominal","abide","abiding","ability","ablaze","able","abnormal","abrasion","abrasive","abreast","abridge","abroad","abruptly","absence","absentee","absently","absinthe","absolute","absolve","abstain","abstract","absurd","accent","acclaim","acclimate","accompany","account","accuracy","accurate","accustom","acetone","achiness","aching","acid","acorn","acquaint","acquire","acre","acrobat","acronym","acting","action","activate","activator","active","activism","activist","activity","actress","acts","acutely","acuteness","aeration","aerobics","aerosol","aerospace","afar","affair","affected","affecting","affection","affidavit","affiliate","affirm","affix","afflicted","affluent","afford","affront","aflame","afloat","aflutter","afoot","afraid","afterglow","afterlife","aftermath","aftermost","afternoon","aged","ageless","agency","agenda","agent","aggregate","aghast","agile","agility","aging","agnostic","agonize","agonizing","agony","agreeable","agreeably","agreed","agreeing","agreement","aground","ahead","ahoy","aide","aids","aim","ajar","alabaster","alarm","albatross","album","alfalfa","algebra","algorithm","alias","alibi","alienable","alienate","aliens","alike","alive","alkaline","alkalize","almanac","almighty","almost","aloe","aloft","aloha","alone","alongside","aloof","alphabet","alright","although","altitude","alto","aluminum","alumni","always","amaretto","amaze","amazingly","amber","ambiance","ambiguity","ambiguous","ambition","ambitious","ambulance","ambush","amendable","amendment","amends","amenity","amiable","amicably","amid","amigo","amino","amiss","ammonia","ammonium","amnesty","amniotic","among","amount","amperage","ample","amplifier","amplify","amply","amuck","amulet","amusable","amused","amusement","amuser","amusing","anaconda","anaerobic","anagram","anatomist","anatomy","anchor","anchovy","ancient","android","anemia","anemic","aneurism","anew","angelfish","angelic","anger","angled","angler","angles","angling","angrily","angriness","anguished","angular","animal","animate","animating","animation","animator","anime","animosity","ankle","annex","annotate","announcer","annoying","annually","annuity","anointer","another","answering","antacid","antarctic","anteater","antelope","antennae","anthem","anthill","anthology","antibody","antics","antidote","antihero","antiquely","antiques","antiquity","antirust","antitoxic","antitrust","antiviral","antivirus","antler","antonym","antsy","anvil","anybody","anyhow","anymore","anyone","anyplace","anything","anytime","anyway","anywhere","aorta","apache","apostle","appealing","appear","appease","appeasing","appendage","appendix","appetite","appetizer","applaud","applause","apple","appliance","applicant","applied","apply","appointee","appraisal","appraiser","apprehend","approach","approval","approve","apricot","april","apron","aptitude","aptly","aqua","aqueduct","arbitrary","arbitrate","ardently","area","arena","arguable","arguably","argue","arise","armadillo","armband","armchair","armed","armful","armhole","arming","armless","armoire","armored","armory","armrest","army","aroma","arose","around","arousal","arrange","array","arrest","arrival","arrive","arrogance","arrogant","arson","art","ascend","ascension","ascent","ascertain","ashamed","ashen","ashes","ashy","aside","askew","asleep","asparagus","aspect","aspirate","aspire","aspirin","astonish","astound","astride","astrology","astronaut","astronomy","astute","atlantic","atlas","atom","atonable","atop","atrium","atrocious","atrophy","attach","attain","attempt","attendant","attendee","attention","attentive","attest","attic","attire","attitude","attractor","attribute","atypical","auction","audacious","audacity","audible","audibly","audience","audio","audition","augmented","august","authentic","author","autism","autistic","autograph","automaker","automated","automatic","autopilot","available","avalanche","avatar","avenge","avenging","avenue","average","aversion","avert","aviation","aviator","avid","avoid","await","awaken","award","aware","awhile","awkward","awning","awoke","awry","axis","babble","babbling","babied","baboon","backache","backboard","backboned","backdrop","backed","backer","backfield","backfire","backhand","backing","backlands","backlash","backless","backlight","backlit","backlog","backpack","backpedal","backrest","backroom","backshift","backside","backslid","backspace","backspin","backstab","backstage","backtalk","backtrack","backup","backward","backwash","backwater","backyard","bacon","bacteria","bacterium","badass","badge","badland","badly","badness","baffle","baffling","bagel","bagful","baggage","bagged","baggie","bagginess","bagging","baggy","bagpipe","baguette","baked","bakery","bakeshop","baking","balance","balancing","balcony","balmy","balsamic","bamboo","banana","banish","banister","banjo","bankable","bankbook","banked","banker","banking","banknote","bankroll","banner","bannister","banshee","banter","barbecue","barbed","barbell","barber","barcode","barge","bargraph","barista","baritone","barley","barmaid","barman","barn","barometer","barrack","barracuda","barrel","barrette","barricade","barrier","barstool","bartender","barterer","bash","basically","basics","basil","basin","basis","basket","batboy","batch","bath","baton","bats","battalion","battered","battering","battery","batting","battle","bauble","bazooka","blabber","bladder","blade","blah","blame","blaming","blanching","blandness","blank","blaspheme","blasphemy","blast","blatancy","blatantly","blazer","blazing","bleach","bleak","bleep","blemish","blend","bless","blighted","blimp","bling","blinked","blinker","blinking","blinks","blip","blissful","blitz","blizzard","bloated","bloating","blob","blog","bloomers","blooming","blooper","blot","blouse","blubber","bluff","bluish","blunderer","blunt","blurb","blurred","blurry","blurt","blush","blustery","boaster","boastful","boasting","boat","bobbed","bobbing","bobble","bobcat","bobsled","bobtail","bodacious","body","bogged","boggle","bogus","boil","bok","bolster","bolt","bonanza","bonded","bonding","bondless","boned","bonehead","boneless","bonelike","boney","bonfire","bonnet","bonsai","bonus","bony","boogeyman","boogieman","book","boondocks","booted","booth","bootie","booting","bootlace","bootleg","boots","boozy","borax","boring","borough","borrower","borrowing","boss","botanical","botanist","botany","botch","both","bottle","bottling","bottom","bounce","bouncing","bouncy","bounding","boundless","bountiful","bovine","boxcar","boxer","boxing","boxlike","boxy","breach","breath","breeches","breeching","breeder","breeding","breeze","breezy","brethren","brewery","brewing","briar","bribe","brick","bride","bridged","brigade","bright","brilliant","brim","bring","brink","brisket","briskly","briskness","bristle","brittle","broadband","broadcast","broaden","broadly","broadness","broadside","broadways","broiler","broiling","broken","broker","bronchial","bronco","bronze","bronzing","brook","broom","brought","browbeat","brownnose","browse","browsing","bruising","brunch","brunette","brunt","brush","brussels","brute","brutishly","bubble","bubbling","bubbly","buccaneer","bucked","bucket","buckle","buckshot","buckskin","bucktooth","buckwheat","buddhism","buddhist","budding","buddy","budget","buffalo","buffed","buffer","buffing","buffoon","buggy","bulb","bulge","bulginess","bulgur","bulk","bulldog","bulldozer","bullfight","bullfrog","bullhorn","bullion","bullish","bullpen","bullring","bullseye","bullwhip","bully","bunch","bundle","bungee","bunion","bunkbed","bunkhouse","bunkmate","bunny","bunt","busboy","bush","busily","busload","bust","busybody","buzz","cabana","cabbage","cabbie","cabdriver","cable","caboose","cache","cackle","cacti","cactus","caddie","caddy","cadet","cadillac","cadmium","cage","cahoots","cake","calamari","calamity","calcium","calculate","calculus","caliber","calibrate","calm","caloric","calorie","calzone","camcorder","cameo","camera","camisole","camper","campfire","camping","campsite","campus","canal","canary","cancel","candied","candle","candy","cane","canine","canister","cannabis","canned","canning","cannon","cannot","canola","canon","canopener","canopy","canteen","canyon","capable","capably","capacity","cape","capillary","capital","capitol","capped","capricorn","capsize","capsule","caption","captivate","captive","captivity","capture","caramel","carat","caravan","carbon","cardboard","carded","cardiac","cardigan","cardinal","cardstock","carefully","caregiver","careless","caress","caretaker","cargo","caring","carless","carload","carmaker","carnage","carnation","carnival","carnivore","carol","carpenter","carpentry","carpool","carport","carried","carrot","carrousel","carry","cartel","cartload","carton","cartoon","cartridge","cartwheel","carve","carving","carwash","cascade","case","cash","casing","casino","casket","cassette","casually","casualty","catacomb","catalog","catalyst","catalyze","catapult","cataract","catatonic","catcall","catchable","catcher","catching","catchy","caterer","catering","catfight","catfish","cathedral","cathouse","catlike","catnap","catnip","catsup","cattail","cattishly","cattle","catty","catwalk","caucasian","caucus","causal","causation","cause","causing","cauterize","caution","cautious","cavalier","cavalry","caviar","cavity","cedar","celery","celestial","celibacy","celibate","celtic","cement","census","ceramics","ceremony","certainly","certainty","certified","certify","cesarean","cesspool","chafe","chaffing","chain","chair","chalice","challenge","chamber","chamomile","champion","chance","change","channel","chant","chaos","chaperone","chaplain","chapped","chaps","chapter","character","charbroil","charcoal","charger","charging","chariot","charity","charm","charred","charter","charting","chase","chasing","chaste","chastise","chastity","chatroom","chatter","chatting","chatty","cheating","cheddar","cheek","cheer","cheese","cheesy","chef","chemicals","chemist","chemo","cherisher","cherub","chess","chest","chevron","chevy","chewable","chewer","chewing","chewy","chief","chihuahua","childcare","childhood","childish","childless","childlike","chili","chill","chimp","chip","chirping","chirpy","chitchat","chivalry","chive","chloride","chlorine","choice","chokehold","choking","chomp","chooser","choosing","choosy","chop","chosen","chowder","chowtime","chrome","chubby","chuck","chug","chummy","chump","chunk","churn","chute","cider","cilantro","cinch","cinema","cinnamon","circle","circling","circular","circulate","circus","citable","citadel","citation","citizen","citric","citrus","city","civic","civil","clad","claim","clambake","clammy","clamor","clamp","clamshell","clang","clanking","clapped","clapper","clapping","clarify","clarinet","clarity","clash","clasp","class","clatter","clause","clavicle","claw","clay","clean","clear","cleat","cleaver","cleft","clench","clergyman","clerical","clerk","clever","clicker","client","climate","climatic","cling","clinic","clinking","clip","clique","cloak","clobber","clock","clone","cloning","closable","closure","clothes","clothing","cloud","clover","clubbed","clubbing","clubhouse","clump","clumsily","clumsy","clunky","clustered","clutch","clutter","coach","coagulant","coastal","coaster","coasting","coastland","coastline","coat","coauthor","cobalt","cobbler","cobweb","cocoa","coconut","cod","coeditor","coerce","coexist","coffee","cofounder","cognition","cognitive","cogwheel","coherence","coherent","cohesive","coil","coke","cola","cold","coleslaw","coliseum","collage","collapse","collar","collected","collector","collide","collie","collision","colonial","colonist","colonize","colony","colossal","colt","coma","come","comfort","comfy","comic","coming","comma","commence","commend","comment","commerce","commode","commodity","commodore","common","commotion","commute","commuting","compacted","compacter","compactly","compactor","companion","company","compare","compel","compile","comply","component","composed","composer","composite","compost","composure","compound","compress","comprised","computer","computing","comrade","concave","conceal","conceded","concept","concerned","concert","conch","concierge","concise","conclude","concrete","concur","condense","condiment","condition","condone","conducive","conductor","conduit","cone","confess","confetti","confidant","confident","confider","confiding","configure","confined","confining","confirm","conflict","conform","confound","confront","confused","confusing","confusion","congenial","congested","congrats","congress","conical","conjoined","conjure","conjuror","connected","connector","consensus","consent","console","consoling","consonant","constable","constant","constrain","constrict","construct","consult","consumer","consuming","contact","container","contempt","contend","contented","contently","contents","contest","context","contort","contour","contrite","control","contusion","convene","convent","copartner","cope","copied","copier","copilot","coping","copious","copper","copy","coral","cork","cornball","cornbread","corncob","cornea","corned","corner","cornfield","cornflake","cornhusk","cornmeal","cornstalk","corny","coronary","coroner","corporal","corporate","corral","correct","corridor","corrode","corroding","corrosive","corsage","corset","cortex","cosigner","cosmetics","cosmic","cosmos","cosponsor","cost","cottage","cotton","couch","cough","could","countable","countdown","counting","countless","country","county","courier","covenant","cover","coveted","coveting","coyness","cozily","coziness","cozy","crabbing","crabgrass","crablike","crabmeat","cradle","cradling","crafter","craftily","craftsman","craftwork","crafty","cramp","cranberry","crane","cranial","cranium","crank","crate","crave","craving","crawfish","crawlers","crawling","crayfish","crayon","crazed","crazily","craziness","crazy","creamed","creamer","creamlike","crease","creasing","creatable","create","creation","creative","creature","credible","credibly","credit","creed","creme","creole","crepe","crept","crescent","crested","cresting","crestless","crevice","crewless","crewman","crewmate","crib","cricket","cried","crier","crimp","crimson","cringe","cringing","crinkle","crinkly","crisped","crisping","crisply","crispness","crispy","criteria","critter","croak","crock","crook","croon","crop","cross","crouch","crouton","crowbar","crowd","crown","crucial","crudely","crudeness","cruelly","cruelness","cruelty","crumb","crummiest","crummy","crumpet","crumpled","cruncher","crunching","crunchy","crusader","crushable","crushed","crusher","crushing","crust","crux","crying","cryptic","crystal","cubbyhole","cube","cubical","cubicle","cucumber","cuddle","cuddly","cufflink","culinary","culminate","culpable","culprit","cultivate","cultural","culture","cupbearer","cupcake","cupid","cupped","cupping","curable","curator","curdle","cure","curfew","curing","curled","curler","curliness","curling","curly","curry","curse","cursive","cursor","curtain","curtly","curtsy","curvature","curve","curvy","cushy","cusp","cussed","custard","custodian","custody","customary","customer","customize","customs","cut","cycle","cyclic","cycling","cyclist","cylinder","cymbal","cytoplasm","cytoplast","dab","dad","daffodil","dagger","daily","daintily","dainty","dairy","daisy","dallying","dance","dancing","dandelion","dander","dandruff","dandy","danger","dangle","dangling","daredevil","dares","daringly","darkened","darkening","darkish","darkness","darkroom","darling","darn","dart","darwinism","dash","dastardly","data","datebook","dating","daughter","daunting","dawdler","dawn","daybed","daybreak","daycare","daydream","daylight","daylong","dayroom","daytime","dazzler","dazzling","deacon","deafening","deafness","dealer","dealing","dealmaker","dealt","dean","debatable","debate","debating","debit","debrief","debtless","debtor","debug","debunk","decade","decaf","decal","decathlon","decay","deceased","deceit","deceiver","deceiving","december","decency","decent","deception","deceptive","decibel","decidable","decimal","decimeter","decipher","deck","declared","decline","decode","decompose","decorated","decorator","decoy","decrease","decree","dedicate","dedicator","deduce","deduct","deed","deem","deepen","deeply","deepness","deface","defacing","defame","default","defeat","defection","defective","defendant","defender","defense","defensive","deferral","deferred","defiance","defiant","defile","defiling","define","definite","deflate","deflation","deflator","deflected","deflector","defog","deforest","defraud","defrost","deftly","defuse","defy","degraded","degrading","degrease","degree","dehydrate","deity","dejected","delay","delegate","delegator","delete","deletion","delicacy","delicate","delicious","delighted","delirious","delirium","deliverer","delivery","delouse","delta","deluge","delusion","deluxe","demanding","demeaning","demeanor","demise","democracy","democrat","demote","demotion","demystify","denatured","deniable","denial","denim","denote","dense","density","dental","dentist","denture","deny","deodorant","deodorize","departed","departure","depict","deplete","depletion","deplored","deploy","deport","depose","depraved","depravity","deprecate","depress","deprive","depth","deputize","deputy","derail","deranged","derby","derived","desecrate","deserve","deserving","designate","designed","designer","designing","deskbound","desktop","deskwork","desolate","despair","despise","despite","destiny","destitute","destruct","detached","detail","detection","detective","detector","detention","detergent","detest","detonate","detonator","detoxify","detract","deuce","devalue","deviancy","deviant","deviate","deviation","deviator","device","devious","devotedly","devotee","devotion","devourer","devouring","devoutly","dexterity","dexterous","diabetes","diabetic","diabolic","diagnoses","diagnosis","diagram","dial","diameter","diaper","diaphragm","diary","dice","dicing","dictate","dictation","dictator","difficult","diffused","diffuser","diffusion","diffusive","dig","dilation","diligence","diligent","dill","dilute","dime","diminish","dimly","dimmed","dimmer","dimness","dimple","diner","dingbat","dinghy","dinginess","dingo","dingy","dining","dinner","diocese","dioxide","diploma","dipped","dipper","dipping","directed","direction","directive","directly","directory","direness","dirtiness","disabled","disagree","disallow","disarm","disarray","disaster","disband","disbelief","disburse","discard","discern","discharge","disclose","discolor","discount","discourse","discover","discuss","disdain","disengage","disfigure","disgrace","dish","disinfect","disjoin","disk","dislike","disliking","dislocate","dislodge","disloyal","dismantle","dismay","dismiss","dismount","disobey","disorder","disown","disparate","disparity","dispatch","dispense","dispersal","dispersed","disperser","displace","display","displease","disposal","dispose","disprove","dispute","disregard","disrupt","dissuade","distance","distant","distaste","distill","distinct","distort","distract","distress","district","distrust","ditch","ditto","ditzy","dividable","divided","dividend","dividers","dividing","divinely","diving","divinity","divisible","divisibly","division","divisive","divorcee","dizziness","dizzy","doable","docile","dock","doctrine","document","dodge","dodgy","doily","doing","dole","dollar","dollhouse","dollop","dolly","dolphin","domain","domelike","domestic","dominion","dominoes","donated","donation","donator","donor","donut","doodle","doorbell","doorframe","doorknob","doorman","doormat","doornail","doorpost","doorstep","doorstop","doorway","doozy","dork","dormitory","dorsal","dosage","dose","dotted","doubling","douche","dove","down","dowry","doze","drab","dragging","dragonfly","dragonish","dragster","drainable","drainage","drained","drainer","drainpipe","dramatic","dramatize","drank","drapery","drastic","draw","dreaded","dreadful","dreadlock","dreamboat","dreamily","dreamland","dreamless","dreamlike","dreamt","dreamy","drearily","dreary","drench","dress","drew","dribble","dried","drier","drift","driller","drilling","drinkable","drinking","dripping","drippy","drivable","driven","driver","driveway","driving","drizzle","drizzly","drone","drool","droop","drop-down","dropbox","dropkick","droplet","dropout","dropper","drove","drown","drowsily","drudge","drum","dry","dubbed","dubiously","duchess","duckbill","ducking","duckling","ducktail","ducky","duct","dude","duffel","dugout","duh","duke","duller","dullness","duly","dumping","dumpling","dumpster","duo","dupe","duplex","duplicate","duplicity","durable","durably","duration","duress","during","dusk","dust","dutiful","duty","duvet","dwarf","dweeb","dwelled","dweller","dwelling","dwindle","dwindling","dynamic","dynamite","dynasty","dyslexia","dyslexic","each","eagle","earache","eardrum","earflap","earful","earlobe","early","earmark","earmuff","earphone","earpiece","earplugs","earring","earshot","earthen","earthlike","earthling","earthly","earthworm","earthy","earwig","easeful","easel","easiest","easily","easiness","easing","eastbound","eastcoast","easter","eastward","eatable","eaten","eatery","eating","eats","ebay","ebony","ebook","ecard","eccentric","echo","eclair","eclipse","ecologist","ecology","economic","economist","economy","ecosphere","ecosystem","edge","edginess","edging","edgy","edition","editor","educated","education","educator","eel","effective","effects","efficient","effort","eggbeater","egging","eggnog","eggplant","eggshell","egomaniac","egotism","egotistic","either","eject","elaborate","elastic","elated","elbow","eldercare","elderly","eldest","electable","election","elective","elephant","elevate","elevating","elevation","elevator","eleven","elf","eligible","eligibly","eliminate","elite","elitism","elixir","elk","ellipse","elliptic","elm","elongated","elope","eloquence","eloquent","elsewhere","elude","elusive","elves","email","embargo","embark","embassy","embattled","embellish","ember","embezzle","emblaze","emblem","embody","embolism","emboss","embroider","emcee","emerald","emergency","emission","emit","emote","emoticon","emotion","empathic","empathy","emperor","emphases","emphasis","emphasize","emphatic","empirical","employed","employee","employer","emporium","empower","emptier","emptiness","empty","emu","enable","enactment","enamel","enchanted","enchilada","encircle","enclose","enclosure","encode","encore","encounter","encourage","encroach","encrust","encrypt","endanger","endeared","endearing","ended","ending","endless","endnote","endocrine","endorphin","endorse","endowment","endpoint","endurable","endurance","enduring","energetic","energize","energy","enforced","enforcer","engaged","engaging","engine","engorge","engraved","engraver","engraving","engross","engulf","enhance","enigmatic","enjoyable","enjoyably","enjoyer","enjoying","enjoyment","enlarged","enlarging","enlighten","enlisted","enquirer","enrage","enrich","enroll","enslave","ensnare","ensure","entail","entangled","entering","entertain","enticing","entire","entitle","entity","entomb","entourage","entrap","entree","entrench","entrust","entryway","entwine","enunciate","envelope","enviable","enviably","envious","envision","envoy","envy","enzyme","epic","epidemic","epidermal","epidermis","epidural","epilepsy","epileptic","epilogue","epiphany","episode","equal","equate","equation","equator","equinox","equipment","equity","equivocal","eradicate","erasable","erased","eraser","erasure","ergonomic","errand","errant","erratic","error","erupt","escalate","escalator","escapable","escapade","escapist","escargot","eskimo","esophagus","espionage","espresso","esquire","essay","essence","essential","establish","estate","esteemed","estimate","estimator","estranged","estrogen","etching","eternal","eternity","ethanol","ether","ethically","ethics","euphemism","evacuate","evacuee","evade","evaluate","evaluator","evaporate","evasion","evasive","even","everglade","evergreen","everybody","everyday","everyone","evict","evidence","evident","evil","evoke","evolution","evolve","exact","exalted","example","excavate","excavator","exceeding","exception","excess","exchange","excitable","exciting","exclaim","exclude","excluding","exclusion","exclusive","excretion","excretory","excursion","excusable","excusably","excuse","exemplary","exemplify","exemption","exerciser","exert","exes","exfoliate","exhale","exhaust","exhume","exile","existing","exit","exodus","exonerate","exorcism","exorcist","expand","expanse","expansion","expansive","expectant","expedited","expediter","expel","expend","expenses","expensive","expert","expire","expiring","explain","expletive","explicit","explode","exploit","explore","exploring","exponent","exporter","exposable","expose","exposure","express","expulsion","exquisite","extended","extending","extent","extenuate","exterior","external","extinct","extortion","extradite","extras","extrovert","extrude","extruding","exuberant","fable","fabric","fabulous","facebook","facecloth","facedown","faceless","facelift","faceplate","faceted","facial","facility","facing","facsimile","faction","factoid","factor","factsheet","factual","faculty","fade","fading","failing","falcon","fall","false","falsify","fame","familiar","family","famine","famished","fanatic","fancied","fanciness","fancy","fanfare","fang","fanning","fantasize","fantastic","fantasy","fascism","fastball","faster","fasting","fastness","faucet","favorable","favorably","favored","favoring","favorite","fax","feast","federal","fedora","feeble","feed","feel","feisty","feline","felt-tip","feminine","feminism","feminist","feminize","femur","fence","fencing","fender","ferment","fernlike","ferocious","ferocity","ferret","ferris","ferry","fervor","fester","festival","festive","festivity","fetal","fetch","fever","fiber","fiction","fiddle","fiddling","fidelity","fidgeting","fidgety","fifteen","fifth","fiftieth","fifty","figment","figure","figurine","filing","filled","filler","filling","film","filter","filth","filtrate","finale","finalist","finalize","finally","finance","financial","finch","fineness","finer","finicky","finished","finisher","finishing","finite","finless","finlike","fiscally","fit","five","flaccid","flagman","flagpole","flagship","flagstick","flagstone","flail","flakily","flaky","flame","flammable","flanked","flanking","flannels","flap","flaring","flashback","flashbulb","flashcard","flashily","flashing","flashy","flask","flatbed","flatfoot","flatly","flatness","flatten","flattered","flatterer","flattery","flattop","flatware","flatworm","flavored","flavorful","flavoring","flaxseed","fled","fleshed","fleshy","flick","flier","flight","flinch","fling","flint","flip","flirt","float","flock","flogging","flop","floral","florist","floss","flounder","flyable","flyaway","flyer","flying","flyover","flypaper","foam","foe","fog","foil","folic","folk","follicle","follow","fondling","fondly","fondness","fondue","font","food","fool","footage","football","footbath","footboard","footer","footgear","foothill","foothold","footing","footless","footman","footnote","footpad","footpath","footprint","footrest","footsie","footsore","footwear","footwork","fossil","foster","founder","founding","fountain","fox","foyer","fraction","fracture","fragile","fragility","fragment","fragrance","fragrant","frail","frame","framing","frantic","fraternal","frayed","fraying","frays","freckled","freckles","freebase","freebee","freebie","freedom","freefall","freehand","freeing","freeload","freely","freemason","freeness","freestyle","freeware","freeway","freewill","freezable","freezing","freight","french","frenzied","frenzy","frequency","frequent","fresh","fretful","fretted","friction","friday","fridge","fried","friend","frighten","frightful","frigidity","frigidly","frill","fringe","frisbee","frisk","fritter","frivolous","frolic","from","front","frostbite","frosted","frostily","frosting","frostlike","frosty","froth","frown","frozen","fructose","frugality","frugally","fruit","frustrate","frying","gab","gaffe","gag","gainfully","gaining","gains","gala","gallantly","galleria","gallery","galley","gallon","gallows","gallstone","galore","galvanize","gambling","game","gaming","gamma","gander","gangly","gangrene","gangway","gap","garage","garbage","garden","gargle","garland","garlic","garment","garnet","garnish","garter","gas","gatherer","gathering","gating","gauging","gauntlet","gauze","gave","gawk","gazing","gear","gecko","geek","geiger","gem","gender","generic","generous","genetics","genre","gentile","gentleman","gently","gents","geography","geologic","geologist","geology","geometric","geometry","geranium","gerbil","geriatric","germicide","germinate","germless","germproof","gestate","gestation","gesture","getaway","getting","getup","giant","gibberish","giblet","giddily","giddiness","giddy","gift","gigabyte","gigahertz","gigantic","giggle","giggling","giggly","gigolo","gilled","gills","gimmick","girdle","giveaway","given","giver","giving","gizmo","gizzard","glacial","glacier","glade","gladiator","gladly","glamorous","glamour","glance","glancing","glandular","glare","glaring","glass","glaucoma","glazing","gleaming","gleeful","glider","gliding","glimmer","glimpse","glisten","glitch","glitter","glitzy","gloater","gloating","gloomily","gloomy","glorified","glorifier","glorify","glorious","glory","gloss","glove","glowing","glowworm","glucose","glue","gluten","glutinous","glutton","gnarly","gnat","goal","goatskin","goes","goggles","going","goldfish","goldmine","goldsmith","golf","goliath","gonad","gondola","gone","gong","good","gooey","goofball","goofiness","goofy","google","goon","gopher","gore","gorged","gorgeous","gory","gosling","gossip","gothic","gotten","gout","gown","grab","graceful","graceless","gracious","gradation","graded","grader","gradient","grading","gradually","graduate","graffiti","grafted","grafting","grain","granddad","grandkid","grandly","grandma","grandpa","grandson","granite","granny","granola","grant","granular","grape","graph","grapple","grappling","grasp","grass","gratified","gratify","grating","gratitude","gratuity","gravel","graveness","graves","graveyard","gravitate","gravity","gravy","gray","grazing","greasily","greedily","greedless","greedy","green","greeter","greeting","grew","greyhound","grid","grief","grievance","grieving","grievous","grill","grimace","grimacing","grime","griminess","grimy","grinch","grinning","grip","gristle","grit","groggily","groggy","groin","groom","groove","grooving","groovy","grope","ground","grouped","grout","grove","grower","growing","growl","grub","grudge","grudging","grueling","gruffly","grumble","grumbling","grumbly","grumpily","grunge","grunt","guacamole","guidable","guidance","guide","guiding","guileless","guise","gulf","gullible","gully","gulp","gumball","gumdrop","gumminess","gumming","gummy","gurgle","gurgling","guru","gush","gusto","gusty","gutless","guts","gutter","guy","guzzler","gyration","habitable","habitant","habitat","habitual","hacked","hacker","hacking","hacksaw","had","haggler","haiku","half","halogen","halt","halved","halves","hamburger","hamlet","hammock","hamper","hamster","hamstring","handbag","handball","handbook","handbrake","handcart","handclap","handclasp","handcraft","handcuff","handed","handful","handgrip","handgun","handheld","handiness","handiwork","handlebar","handled","handler","handling","handmade","handoff","handpick","handprint","handrail","handsaw","handset","handsfree","handshake","handstand","handwash","handwork","handwoven","handwrite","handyman","hangnail","hangout","hangover","hangup","hankering","hankie","hanky","haphazard","happening","happier","happiest","happily","happiness","happy","harbor","hardcopy","hardcore","hardcover","harddisk","hardened","hardener","hardening","hardhat","hardhead","hardiness","hardly","hardness","hardship","hardware","hardwired","hardwood","hardy","harmful","harmless","harmonica","harmonics","harmonize","harmony","harness","harpist","harsh","harvest","hash","hassle","haste","hastily","hastiness","hasty","hatbox","hatchback","hatchery","hatchet","hatching","hatchling","hate","hatless","hatred","haunt","haven","hazard","hazelnut","hazily","haziness","hazing","hazy","headache","headband","headboard","headcount","headdress","headed","header","headfirst","headgear","heading","headlamp","headless","headlock","headphone","headpiece","headrest","headroom","headscarf","headset","headsman","headstand","headstone","headway","headwear","heap","heat","heave","heavily","heaviness","heaving","hedge","hedging","heftiness","hefty","helium","helmet","helper","helpful","helping","helpless","helpline","hemlock","hemstitch","hence","henchman","henna","herald","herbal","herbicide","herbs","heritage","hermit","heroics","heroism","herring","herself","hertz","hesitancy","hesitant","hesitate","hexagon","hexagram","hubcap","huddle","huddling","huff","hug","hula","hulk","hull","human","humble","humbling","humbly","humid","humiliate","humility","humming","hummus","humongous","humorist","humorless","humorous","humpback","humped","humvee","hunchback","hundredth","hunger","hungrily","hungry","hunk","hunter","hunting","huntress","huntsman","hurdle","hurled","hurler","hurling","hurray","hurricane","hurried","hurry","hurt","husband","hush","husked","huskiness","hut","hybrid","hydrant","hydrated","hydration","hydrogen","hydroxide","hyperlink","hypertext","hyphen","hypnoses","hypnosis","hypnotic","hypnotism","hypnotist","hypnotize","hypocrisy","hypocrite","ibuprofen","ice","iciness","icing","icky","icon","icy","idealism","idealist","idealize","ideally","idealness","identical","identify","identity","ideology","idiocy","idiom","idly","igloo","ignition","ignore","iguana","illicitly","illusion","illusive","image","imaginary","imagines","imaging","imbecile","imitate","imitation","immature","immerse","immersion","imminent","immobile","immodest","immorally","immortal","immovable","immovably","immunity","immunize","impaired","impale","impart","impatient","impeach","impeding","impending","imperfect","imperial","impish","implant","implement","implicate","implicit","implode","implosion","implosive","imply","impolite","important","importer","impose","imposing","impotence","impotency","impotent","impound","imprecise","imprint","imprison","impromptu","improper","improve","improving","improvise","imprudent","impulse","impulsive","impure","impurity","iodine","iodize","ion","ipad","iphone","ipod","irate","irk","iron","irregular","irrigate","irritable","irritably","irritant","irritate","islamic","islamist","isolated","isolating","isolation","isotope","issue","issuing","italicize","italics","item","itinerary","itunes","ivory","ivy","jab","jackal","jacket","jackknife","jackpot","jailbird","jailbreak","jailer","jailhouse","jalapeno","jam","janitor","january","jargon","jarring","jasmine","jaundice","jaunt","java","jawed","jawless","jawline","jaws","jaybird","jaywalker","jazz","jeep","jeeringly","jellied","jelly","jersey","jester","jet","jiffy","jigsaw","jimmy","jingle","jingling","jinx","jitters","jittery","job","jockey","jockstrap","jogger","jogging","john","joining","jokester","jokingly","jolliness","jolly","jolt","jot","jovial","joyfully","joylessly","joyous","joyride","joystick","jubilance","jubilant","judge","judgingly","judicial","judiciary","judo","juggle","juggling","jugular","juice","juiciness","juicy","jujitsu","jukebox","july","jumble","jumbo","jump","junction","juncture","june","junior","juniper","junkie","junkman","junkyard","jurist","juror","jury","justice","justifier","justify","justly","justness","juvenile","kabob","kangaroo","karaoke","karate","karma","kebab","keenly","keenness","keep","keg","kelp","kennel","kept","kerchief","kerosene","kettle","kick","kiln","kilobyte","kilogram","kilometer","kilowatt","kilt","kimono","kindle","kindling","kindly","kindness","kindred","kinetic","kinfolk","king","kinship","kinsman","kinswoman","kissable","kisser","kissing","kitchen","kite","kitten","kitty","kiwi","kleenex","knapsack","knee","knelt","knickers","knoll","koala","kooky","kosher","krypton","kudos","kung","labored","laborer","laboring","laborious","labrador","ladder","ladies","ladle","ladybug","ladylike","lagged","lagging","lagoon","lair","lake","lance","landed","landfall","landfill","landing","landlady","landless","landline","landlord","landmark","landmass","landmine","landowner","landscape","landside","landslide","language","lankiness","lanky","lantern","lapdog","lapel","lapped","lapping","laptop","lard","large","lark","lash","lasso","last","latch","late","lather","latitude","latrine","latter","latticed","launch","launder","laundry","laurel","lavender","lavish","laxative","lazily","laziness","lazy","lecturer","left","legacy","legal","legend","legged","leggings","legible","legibly","legislate","lego","legroom","legume","legwarmer","legwork","lemon","lend","length","lens","lent","leotard","lesser","letdown","lethargic","lethargy","letter","lettuce","level","leverage","levers","levitate","levitator","liability","liable","liberty","librarian","library","licking","licorice","lid","life","lifter","lifting","liftoff","ligament","likely","likeness","likewise","liking","lilac","lilly","lily","limb","limeade","limelight","limes","limit","limping","limpness","line","lingo","linguini","linguist","lining","linked","linoleum","linseed","lint","lion","lip","liquefy","liqueur","liquid","lisp","list","litigate","litigator","litmus","litter","little","livable","lived","lively","liver","livestock","lividly","living","lizard","lubricant","lubricate","lucid","luckily","luckiness","luckless","lucrative","ludicrous","lugged","lukewarm","lullaby","lumber","luminance","luminous","lumpiness","lumping","lumpish","lunacy","lunar","lunchbox","luncheon","lunchroom","lunchtime","lung","lurch","lure","luridness","lurk","lushly","lushness","luster","lustfully","lustily","lustiness","lustrous","lusty","luxurious","luxury","lying","lyrically","lyricism","lyricist","lyrics","macarena","macaroni","macaw","mace","machine","machinist","magazine","magenta","maggot","magical","magician","magma","magnesium","magnetic","magnetism","magnetize","magnifier","magnify","magnitude","magnolia","mahogany","maimed","majestic","majesty","majorette","majority","makeover","maker","makeshift","making","malformed","malt","mama","mammal","mammary","mammogram","manager","managing","manatee","mandarin","mandate","mandatory","mandolin","manger","mangle","mango","mangy","manhandle","manhole","manhood","manhunt","manicotti","manicure","manifesto","manila","mankind","manlike","manliness","manly","manmade","manned","mannish","manor","manpower","mantis","mantra","manual","many","map","marathon","marauding","marbled","marbles","marbling","march","mardi","margarine","margarita","margin","marigold","marina","marine","marital","maritime","marlin","marmalade","maroon","married","marrow","marry","marshland","marshy","marsupial","marvelous","marxism","mascot","masculine","mashed","mashing","massager","masses","massive","mastiff","matador","matchbook","matchbox","matcher","matching","matchless","material","maternal","maternity","math","mating","matriarch","matrimony","matrix","matron","matted","matter","maturely","maturing","maturity","mauve","maverick","maximize","maximum","maybe","mayday","mayflower","moaner","moaning","mobile","mobility","mobilize","mobster","mocha","mocker","mockup","modified","modify","modular","modulator","module","moisten","moistness","moisture","molar","molasses","mold","molecular","molecule","molehill","mollusk","mom","monastery","monday","monetary","monetize","moneybags","moneyless","moneywise","mongoose","mongrel","monitor","monkhood","monogamy","monogram","monologue","monopoly","monorail","monotone","monotype","monoxide","monsieur","monsoon","monstrous","monthly","monument","moocher","moodiness","moody","mooing","moonbeam","mooned","moonlight","moonlike","moonlit","moonrise","moonscape","moonshine","moonstone","moonwalk","mop","morale","morality","morally","morbidity","morbidly","morphine","morphing","morse","mortality","mortally","mortician","mortified","mortify","mortuary","mosaic","mossy","most","mothball","mothproof","motion","motivate","motivator","motive","motocross","motor","motto","mountable","mountain","mounted","mounting","mourner","mournful","mouse","mousiness","moustache","mousy","mouth","movable","move","movie","moving","mower","mowing","much","muck","mud","mug","mulberry","mulch","mule","mulled","mullets","multiple","multiply","multitask","multitude","mumble","mumbling","mumbo","mummified","mummify","mummy","mumps","munchkin","mundane","municipal","muppet","mural","murkiness","murky","murmuring","muscular","museum","mushily","mushiness","mushroom","mushy","music","musket","muskiness","musky","mustang","mustard","muster","mustiness","musty","mutable","mutate","mutation","mute","mutilated","mutilator","mutiny","mutt","mutual","muzzle","myself","myspace","mystified","mystify","myth","nacho","nag","nail","name","naming","nanny","nanometer","nape","napkin","napped","napping","nappy","narrow","nastily","nastiness","national","native","nativity","natural","nature","naturist","nautical","navigate","navigator","navy","nearby","nearest","nearly","nearness","neatly","neatness","nebula","nebulizer","nectar","negate","negation","negative","neglector","negligee","negligent","negotiate","nemeses","nemesis","neon","nephew","nerd","nervous","nervy","nest","net","neurology","neuron","neurosis","neurotic","neuter","neutron","never","next","nibble","nickname","nicotine","niece","nifty","nimble","nimbly","nineteen","ninetieth","ninja","nintendo","ninth","nuclear","nuclei","nucleus","nugget","nullify","number","numbing","numbly","numbness","numeral","numerate","numerator","numeric","numerous","nuptials","nursery","nursing","nurture","nutcase","nutlike","nutmeg","nutrient","nutshell","nuttiness","nutty","nuzzle","nylon","oaf","oak","oasis","oat","obedience","obedient","obituary","object","obligate","obliged","oblivion","oblivious","oblong","obnoxious","oboe","obscure","obscurity","observant","observer","observing","obsessed","obsession","obsessive","obsolete","obstacle","obstinate","obstruct","obtain","obtrusive","obtuse","obvious","occultist","occupancy","occupant","occupier","occupy","ocean","ocelot","octagon","octane","october","octopus","ogle","oil","oink","ointment","okay","old","olive","olympics","omega","omen","ominous","omission","omit","omnivore","onboard","oncoming","ongoing","onion","online","onlooker","only","onscreen","onset","onshore","onslaught","onstage","onto","onward","onyx","oops","ooze","oozy","opacity","opal","open","operable","operate","operating","operation","operative","operator","opium","opossum","opponent","oppose","opposing","opposite","oppressed","oppressor","opt","opulently","osmosis","other","otter","ouch","ought","ounce","outage","outback","outbid","outboard","outbound","outbreak","outburst","outcast","outclass","outcome","outdated","outdoors","outer","outfield","outfit","outflank","outgoing","outgrow","outhouse","outing","outlast","outlet","outline","outlook","outlying","outmatch","outmost","outnumber","outplayed","outpost","outpour","output","outrage","outrank","outreach","outright","outscore","outsell","outshine","outshoot","outsider","outskirts","outsmart","outsource","outspoken","outtakes","outthink","outward","outweigh","outwit","oval","ovary","oven","overact","overall","overarch","overbid","overbill","overbite","overblown","overboard","overbook","overbuilt","overcast","overcoat","overcome","overcook","overcrowd","overdraft","overdrawn","overdress","overdrive","overdue","overeager","overeater","overexert","overfed","overfeed","overfill","overflow","overfull","overgrown","overhand","overhang","overhaul","overhead","overhear","overheat","overhung","overjoyed","overkill","overlabor","overlaid","overlap","overlay","overload","overlook","overlord","overlying","overnight","overpass","overpay","overplant","overplay","overpower","overprice","overrate","overreach","overreact","override","overripe","overrule","overrun","overshoot","overshot","oversight","oversized","oversleep","oversold","overspend","overstate","overstay","overstep","overstock","overstuff","oversweet","overtake","overthrow","overtime","overtly","overtone","overture","overturn","overuse","overvalue","overview","overwrite","owl","oxford","oxidant","oxidation","oxidize","oxidizing","oxygen","oxymoron","oyster","ozone","paced","pacemaker","pacific","pacifier","pacifism","pacifist","pacify","padded","padding","paddle","paddling","padlock","pagan","pager","paging","pajamas","palace","palatable","palm","palpable","palpitate","paltry","pampered","pamperer","pampers","pamphlet","panama","pancake","pancreas","panda","pandemic","pang","panhandle","panic","panning","panorama","panoramic","panther","pantomime","pantry","pants","pantyhose","paparazzi","papaya","paper","paprika","papyrus","parabola","parachute","parade","paradox","paragraph","parakeet","paralegal","paralyses","paralysis","paralyze","paramedic","parameter","paramount","parasail","parasite","parasitic","parcel","parched","parchment","pardon","parish","parka","parking","parkway","parlor","parmesan","parole","parrot","parsley","parsnip","partake","parted","parting","partition","partly","partner","partridge","party","passable","passably","passage","passcode","passenger","passerby","passing","passion","passive","passivism","passover","passport","password","pasta","pasted","pastel","pastime","pastor","pastrami","pasture","pasty","patchwork","patchy","paternal","paternity","path","patience","patient","patio","patriarch","patriot","patrol","patronage","patronize","pauper","pavement","paver","pavestone","pavilion","paving","pawing","payable","payback","paycheck","payday","payee","payer","paying","payment","payphone","payroll","pebble","pebbly","pecan","pectin","peculiar","peddling","pediatric","pedicure","pedigree","pedometer","pegboard","pelican","pellet","pelt","pelvis","penalize","penalty","pencil","pendant","pending","penholder","penknife","pennant","penniless","penny","penpal","pension","pentagon","pentagram","pep","perceive","percent","perch","percolate","perennial","perfected","perfectly","perfume","periscope","perish","perjurer","perjury","perkiness","perky","perm","peroxide","perpetual","perplexed","persecute","persevere","persuaded","persuader","pesky","peso","pessimism","pessimist","pester","pesticide","petal","petite","petition","petri","petroleum","petted","petticoat","pettiness","petty","petunia","phantom","phobia","phoenix","phonebook","phoney","phonics","phoniness","phony","phosphate","photo","phrase","phrasing","placard","placate","placidly","plank","planner","plant","plasma","plaster","plastic","plated","platform","plating","platinum","platonic","platter","platypus","plausible","plausibly","playable","playback","player","playful","playgroup","playhouse","playing","playlist","playmaker","playmate","playoff","playpen","playroom","playset","plaything","playtime","plaza","pleading","pleat","pledge","plentiful","plenty","plethora","plexiglas","pliable","plod","plop","plot","plow","ploy","pluck","plug","plunder","plunging","plural","plus","plutonium","plywood","poach","pod","poem","poet","pogo","pointed","pointer","pointing","pointless","pointy","poise","poison","poker","poking","polar","police","policy","polio","polish","politely","polka","polo","polyester","polygon","polygraph","polymer","poncho","pond","pony","popcorn","pope","poplar","popper","poppy","popsicle","populace","popular","populate","porcupine","pork","porous","porridge","portable","portal","portfolio","porthole","portion","portly","portside","poser","posh","posing","possible","possibly","possum","postage","postal","postbox","postcard","posted","poster","posting","postnasal","posture","postwar","pouch","pounce","pouncing","pound","pouring","pout","powdered","powdering","powdery","power","powwow","pox","praising","prance","prancing","pranker","prankish","prankster","prayer","praying","preacher","preaching","preachy","preamble","precinct","precise","precision","precook","precut","predator","predefine","predict","preface","prefix","preflight","preformed","pregame","pregnancy","pregnant","preheated","prelaunch","prelaw","prelude","premiere","premises","premium","prenatal","preoccupy","preorder","prepaid","prepay","preplan","preppy","preschool","prescribe","preseason","preset","preshow","president","presoak","press","presume","presuming","preteen","pretended","pretender","pretense","pretext","pretty","pretzel","prevail","prevalent","prevent","preview","previous","prewar","prewashed","prideful","pried","primal","primarily","primary","primate","primer","primp","princess","print","prior","prism","prison","prissy","pristine","privacy","private","privatize","prize","proactive","probable","probably","probation","probe","probing","probiotic","problem","procedure","process","proclaim","procreate","procurer","prodigal","prodigy","produce","product","profane","profanity","professed","professor","profile","profound","profusely","progeny","prognosis","program","progress","projector","prologue","prolonged","promenade","prominent","promoter","promotion","prompter","promptly","prone","prong","pronounce","pronto","proofing","proofread","proofs","propeller","properly","property","proponent","proposal","propose","props","prorate","protector","protegee","proton","prototype","protozoan","protract","protrude","proud","provable","proved","proven","provided","provider","providing","province","proving","provoke","provoking","provolone","prowess","prowler","prowling","proximity","proxy","prozac","prude","prudishly","prune","pruning","pry","psychic","public","publisher","pucker","pueblo","pug","pull","pulmonary","pulp","pulsate","pulse","pulverize","puma","pumice","pummel","punch","punctual","punctuate","punctured","pungent","punisher","punk","pupil","puppet","puppy","purchase","pureblood","purebred","purely","pureness","purgatory","purge","purging","purifier","purify","purist","puritan","purity","purple","purplish","purposely","purr","purse","pursuable","pursuant","pursuit","purveyor","pushcart","pushchair","pusher","pushiness","pushing","pushover","pushpin","pushup","pushy","putdown","putt","puzzle","puzzling","pyramid","pyromania","python","quack","quadrant","quail","quaintly","quake","quaking","qualified","qualifier","qualify","quality","qualm","quantum","quarrel","quarry","quartered","quarterly","quarters","quartet","quench","query","quicken","quickly","quickness","quicksand","quickstep","quiet","quill","quilt","quintet","quintuple","quirk","quit","quiver","quizzical","quotable","quotation","quote","rabid","race","racing","racism","rack","racoon","radar","radial","radiance","radiantly","radiated","radiation","radiator","radio","radish","raffle","raft","rage","ragged","raging","ragweed","raider","railcar","railing","railroad","railway","raisin","rake","raking","rally","ramble","rambling","ramp","ramrod","ranch","rancidity","random","ranged","ranger","ranging","ranked","ranking","ransack","ranting","rants","rare","rarity","rascal","rash","rasping","ravage","raven","ravine","raving","ravioli","ravishing","reabsorb","reach","reacquire","reaction","reactive","reactor","reaffirm","ream","reanalyze","reappear","reapply","reappoint","reapprove","rearrange","rearview","reason","reassign","reassure","reattach","reawake","rebalance","rebate","rebel","rebirth","reboot","reborn","rebound","rebuff","rebuild","rebuilt","reburial","rebuttal","recall","recant","recapture","recast","recede","recent","recess","recharger","recipient","recital","recite","reckless","reclaim","recliner","reclining","recluse","reclusive","recognize","recoil","recollect","recolor","reconcile","reconfirm","reconvene","recopy","record","recount","recoup","recovery","recreate","rectal","rectangle","rectified","rectify","recycled","recycler","recycling","reemerge","reenact","reenter","reentry","reexamine","referable","referee","reference","refill","refinance","refined","refinery","refining","refinish","reflected","reflector","reflex","reflux","refocus","refold","reforest","reformat","reformed","reformer","reformist","refract","refrain","refreeze","refresh","refried","refueling","refund","refurbish","refurnish","refusal","refuse","refusing","refutable","refute","regain","regalia","regally","reggae","regime","region","register","registrar","registry","regress","regretful","regroup","regular","regulate","regulator","rehab","reheat","rehire","rehydrate","reimburse","reissue","reiterate","rejoice","rejoicing","rejoin","rekindle","relapse","relapsing","relatable","related","relation","relative","relax","relay","relearn","release","relenting","reliable","reliably","reliance","reliant","relic","relieve","relieving","relight","relish","relive","reload","relocate","relock","reluctant","rely","remake","remark","remarry","rematch","remedial","remedy","remember","reminder","remindful","remission","remix","remnant","remodeler","remold","remorse","remote","removable","removal","removed","remover","removing","rename","renderer","rendering","rendition","renegade","renewable","renewably","renewal","renewed","renounce","renovate","renovator","rentable","rental","rented","renter","reoccupy","reoccur","reopen","reorder","repackage","repacking","repaint","repair","repave","repaying","repayment","repeal","repeated","repeater","repent","rephrase","replace","replay","replica","reply","reporter","repose","repossess","repost","repressed","reprimand","reprint","reprise","reproach","reprocess","reproduce","reprogram","reps","reptile","reptilian","repugnant","repulsion","repulsive","repurpose","reputable","reputably","request","require","requisite","reroute","rerun","resale","resample","rescuer","reseal","research","reselect","reseller","resemble","resend","resent","reset","reshape","reshoot","reshuffle","residence","residency","resident","residual","residue","resigned","resilient","resistant","resisting","resize","resolute","resolved","resonant","resonate","resort","resource","respect","resubmit","result","resume","resupply","resurface","resurrect","retail","retainer","retaining","retake","retaliate","retention","rethink","retinal","retired","retiree","retiring","retold","retool","retorted","retouch","retrace","retract","retrain","retread","retreat","retrial","retrieval","retriever","retry","return","retying","retype","reunion","reunite","reusable","reuse","reveal","reveler","revenge","revenue","reverb","revered","reverence","reverend","reversal","reverse","reversing","reversion","revert","revisable","revise","revision","revisit","revivable","revival","reviver","reviving","revocable","revoke","revolt","revolver","revolving","reward","rewash","rewind","rewire","reword","rework","rewrap","rewrite","rhyme","ribbon","ribcage","rice","riches","richly","richness","rickety","ricotta","riddance","ridden","ride","riding","rifling","rift","rigging","rigid","rigor","rimless","rimmed","rind","rink","rinse","rinsing","riot","ripcord","ripeness","ripening","ripping","ripple","rippling","riptide","rise","rising","risk","risotto","ritalin","ritzy","rival","riverbank","riverbed","riverboat","riverside","riveter","riveting","roamer","roaming","roast","robbing","robe","robin","robotics","robust","rockband","rocker","rocket","rockfish","rockiness","rocking","rocklike","rockslide","rockstar","rocky","rogue","roman","romp","rope","roping","roster","rosy","rotten","rotting","rotunda","roulette","rounding","roundish","roundness","roundup","roundworm","routine","routing","rover","roving","royal","rubbed","rubber","rubbing","rubble","rubdown","ruby","ruckus","rudder","rug","ruined","rule","rumble","rumbling","rummage","rumor","runaround","rundown","runner","running","runny","runt","runway","rupture","rural","ruse","rush","rust","rut","sabbath","sabotage","sacrament","sacred","sacrifice","sadden","saddlebag","saddled","saddling","sadly","sadness","safari","safeguard","safehouse","safely","safeness","saffron","saga","sage","sagging","saggy","said","saint","sake","salad","salami","salaried","salary","saline","salon","saloon","salsa","salt","salutary","salute","salvage","salvaging","salvation","same","sample","sampling","sanction","sanctity","sanctuary","sandal","sandbag","sandbank","sandbar","sandblast","sandbox","sanded","sandfish","sanding","sandlot","sandpaper","sandpit","sandstone","sandstorm","sandworm","sandy","sanitary","sanitizer","sank","santa","sapling","sappiness","sappy","sarcasm","sarcastic","sardine","sash","sasquatch","sassy","satchel","satiable","satin","satirical","satisfied","satisfy","saturate","saturday","sauciness","saucy","sauna","savage","savanna","saved","savings","savior","savor","saxophone","say","scabbed","scabby","scalded","scalding","scale","scaling","scallion","scallop","scalping","scam","scandal","scanner","scanning","scant","scapegoat","scarce","scarcity","scarecrow","scared","scarf","scarily","scariness","scarring","scary","scavenger","scenic","schedule","schematic","scheme","scheming","schilling","schnapps","scholar","science","scientist","scion","scoff","scolding","scone","scoop","scooter","scope","scorch","scorebook","scorecard","scored","scoreless","scorer","scoring","scorn","scorpion","scotch","scoundrel","scoured","scouring","scouting","scouts","scowling","scrabble","scraggly","scrambled","scrambler","scrap","scratch","scrawny","screen","scribble","scribe","scribing","scrimmage","script","scroll","scrooge","scrounger","scrubbed","scrubber","scruffy","scrunch","scrutiny","scuba","scuff","sculptor","sculpture","scurvy","scuttle","secluded","secluding","seclusion","second","secrecy","secret","sectional","sector","secular","securely","security","sedan","sedate","sedation","sedative","sediment","seduce","seducing","segment","seismic","seizing","seldom","selected","selection","selective","selector","self","seltzer","semantic","semester","semicolon","semifinal","seminar","semisoft","semisweet","senate","senator","send","senior","senorita","sensation","sensitive","sensitize","sensually","sensuous","sepia","september","septic","septum","sequel","sequence","sequester","series","sermon","serotonin","serpent","serrated","serve","service","serving","sesame","sessions","setback","setting","settle","settling","setup","sevenfold","seventeen","seventh","seventy","severity","shabby","shack","shaded","shadily","shadiness","shading","shadow","shady","shaft","shakable","shakily","shakiness","shaking","shaky","shale","shallot","shallow","shame","shampoo","shamrock","shank","shanty","shape","shaping","share","sharpener","sharper","sharpie","sharply","sharpness","shawl","sheath","shed","sheep","sheet","shelf","shell","shelter","shelve","shelving","sherry","shield","shifter","shifting","shiftless","shifty","shimmer","shimmy","shindig","shine","shingle","shininess","shining","shiny","ship","shirt","shivering","shock","shone","shoplift","shopper","shopping","shoptalk","shore","shortage","shortcake","shortcut","shorten","shorter","shorthand","shortlist","shortly","shortness","shorts","shortwave","shorty","shout","shove","showbiz","showcase","showdown","shower","showgirl","showing","showman","shown","showoff","showpiece","showplace","showroom","showy","shrank","shrapnel","shredder","shredding","shrewdly","shriek","shrill","shrimp","shrine","shrink","shrivel","shrouded","shrubbery","shrubs","shrug","shrunk","shucking","shudder","shuffle","shuffling","shun","shush","shut","shy","siamese","siberian","sibling","siding","sierra","siesta","sift","sighing","silenced","silencer","silent","silica","silicon","silk","silliness","silly","silo","silt","silver","similarly","simile","simmering","simple","simplify","simply","sincere","sincerity","singer","singing","single","singular","sinister","sinless","sinner","sinuous","sip","siren","sister","sitcom","sitter","sitting","situated","situation","sixfold","sixteen","sixth","sixties","sixtieth","sixtyfold","sizable","sizably","size","sizing","sizzle","sizzling","skater","skating","skedaddle","skeletal","skeleton","skeptic","sketch","skewed","skewer","skid","skied","skier","skies","skiing","skilled","skillet","skillful","skimmed","skimmer","skimming","skimpily","skincare","skinhead","skinless","skinning","skinny","skintight","skipper","skipping","skirmish","skirt","skittle","skydiver","skylight","skyline","skype","skyrocket","skyward","slab","slacked","slacker","slacking","slackness","slacks","slain","slam","slander","slang","slapping","slapstick","slashed","slashing","slate","slather","slaw","sled","sleek","sleep","sleet","sleeve","slept","sliceable","sliced","slicer","slicing","slick","slider","slideshow","sliding","slighted","slighting","slightly","slimness","slimy","slinging","slingshot","slinky","slip","slit","sliver","slobbery","slogan","sloped","sloping","sloppily","sloppy","slot","slouching","slouchy","sludge","slug","slum","slurp","slush","sly","small","smartly","smartness","smasher","smashing","smashup","smell","smelting","smile","smilingly","smirk","smite","smith","smitten","smock","smog","smoked","smokeless","smokiness","smoking","smoky","smolder","smooth","smother","smudge","smudgy","smuggler","smuggling","smugly","smugness","snack","snagged","snaking","snap","snare","snarl","snazzy","sneak","sneer","sneeze","sneezing","snide","sniff","snippet","snipping","snitch","snooper","snooze","snore","snoring","snorkel","snort","snout","snowbird","snowboard","snowbound","snowcap","snowdrift","snowdrop","snowfall","snowfield","snowflake","snowiness","snowless","snowman","snowplow","snowshoe","snowstorm","snowsuit","snowy","snub","snuff","snuggle","snugly","snugness","speak","spearfish","spearhead","spearman","spearmint","species","specimen","specked","speckled","specks","spectacle","spectator","spectrum","speculate","speech","speed","spellbind","speller","spelling","spendable","spender","spending","spent","spew","sphere","spherical","sphinx","spider","spied","spiffy","spill","spilt","spinach","spinal","spindle","spinner","spinning","spinout","spinster","spiny","spiral","spirited","spiritism","spirits","spiritual","splashed","splashing","splashy","splatter","spleen","splendid","splendor","splice","splicing","splinter","splotchy","splurge","spoilage","spoiled","spoiler","spoiling","spoils","spoken","spokesman","sponge","spongy","sponsor","spoof","spookily","spooky","spool","spoon","spore","sporting","sports","sporty","spotless","spotlight","spotted","spotter","spotting","spotty","spousal","spouse","spout","sprain","sprang","sprawl","spray","spree","sprig","spring","sprinkled","sprinkler","sprint","sprite","sprout","spruce","sprung","spry","spud","spur","sputter","spyglass","squabble","squad","squall","squander","squash","squatted","squatter","squatting","squeak","squealer","squealing","squeamish","squeegee","squeeze","squeezing","squid","squiggle","squiggly","squint","squire","squirt","squishier","squishy","stability","stabilize","stable","stack","stadium","staff","stage","staging","stagnant","stagnate","stainable","stained","staining","stainless","stalemate","staleness","stalling","stallion","stamina","stammer","stamp","stand","stank","staple","stapling","starboard","starch","stardom","stardust","starfish","stargazer","staring","stark","starless","starlet","starlight","starlit","starring","starry","starship","starter","starting","startle","startling","startup","starved","starving","stash","state","static","statistic","statue","stature","status","statute","statutory","staunch","stays","steadfast","steadier","steadily","steadying","steam","steed","steep","steerable","steering","steersman","stegosaur","stellar","stem","stench","stencil","step","stereo","sterile","sterility","sterilize","sterling","sternness","sternum","stew","stick","stiffen","stiffly","stiffness","stifle","stifling","stillness","stilt","stimulant","stimulate","stimuli","stimulus","stinger","stingily","stinging","stingray","stingy","stinking","stinky","stipend","stipulate","stir","stitch","stock","stoic","stoke","stole","stomp","stonewall","stoneware","stonework","stoning","stony","stood","stooge","stool","stoop","stoplight","stoppable","stoppage","stopped","stopper","stopping","stopwatch","storable","storage","storeroom","storewide","storm","stout","stove","stowaway","stowing","straddle","straggler","strained","strainer","straining","strangely","stranger","strangle","strategic","strategy","stratus","straw","stray","streak","stream","street","strength","strenuous","strep","stress","stretch","strewn","stricken","strict","stride","strife","strike","striking","strive","striving","strobe","strode","stroller","strongbox","strongly","strongman","struck","structure","strudel","struggle","strum","strung","strut","stubbed","stubble","stubbly","stubborn","stucco","stuck","student","studied","studio","study","stuffed","stuffing","stuffy","stumble","stumbling","stump","stung","stunned","stunner","stunning","stunt","stupor","sturdily","sturdy","styling","stylishly","stylist","stylized","stylus","suave","subarctic","subatomic","subdivide","subdued","subduing","subfloor","subgroup","subheader","subject","sublease","sublet","sublevel","sublime","submarine","submerge","submersed","submitter","subpanel","subpar","subplot","subprime","subscribe","subscript","subsector","subside","subsiding","subsidize","subsidy","subsoil","subsonic","substance","subsystem","subtext","subtitle","subtly","subtotal","subtract","subtype","suburb","subway","subwoofer","subzero","succulent","such","suction","sudden","sudoku","suds","sufferer","suffering","suffice","suffix","suffocate","suffrage","sugar","suggest","suing","suitable","suitably","suitcase","suitor","sulfate","sulfide","sulfite","sulfur","sulk","sullen","sulphate","sulphuric","sultry","superbowl","superglue","superhero","superior","superjet","superman","supermom","supernova","supervise","supper","supplier","supply","support","supremacy","supreme","surcharge","surely","sureness","surface","surfacing","surfboard","surfer","surgery","surgical","surging","surname","surpass","surplus","surprise","surreal","surrender","surrogate","surround","survey","survival","survive","surviving","survivor","sushi","suspect","suspend","suspense","sustained","sustainer","swab","swaddling","swagger","swampland","swan","swapping","swarm","sway","swear","sweat","sweep","swell","swept","swerve","swifter","swiftly","swiftness","swimmable","swimmer","swimming","swimsuit","swimwear","swinger","swinging","swipe","swirl","switch","swivel","swizzle","swooned","swoop","swoosh","swore","sworn","swung","sycamore","sympathy","symphonic","symphony","symptom","synapse","syndrome","synergy","synopses","synopsis","synthesis","synthetic","syrup","system","t-shirt","tabasco","tabby","tableful","tables","tablet","tableware","tabloid","tackiness","tacking","tackle","tackling","tacky","taco","tactful","tactical","tactics","tactile","tactless","tadpole","taekwondo","tag","tainted","take","taking","talcum","talisman","tall","talon","tamale","tameness","tamer","tamper","tank","tanned","tannery","tanning","tantrum","tapeless","tapered","tapering","tapestry","tapioca","tapping","taps","tarantula","target","tarmac","tarnish","tarot","tartar","tartly","tartness","task","tassel","taste","tastiness","tasting","tasty","tattered","tattle","tattling","tattoo","taunt","tavern","thank","that","thaw","theater","theatrics","thee","theft","theme","theology","theorize","thermal","thermos","thesaurus","these","thesis","thespian","thicken","thicket","thickness","thieving","thievish","thigh","thimble","thing","think","thinly","thinner","thinness","thinning","thirstily","thirsting","thirsty","thirteen","thirty","thong","thorn","those","thousand","thrash","thread","threaten","threefold","thrift","thrill","thrive","thriving","throat","throbbing","throng","throttle","throwaway","throwback","thrower","throwing","thud","thumb","thumping","thursday","thus","thwarting","thyself","tiara","tibia","tidal","tidbit","tidiness","tidings","tidy","tiger","tighten","tightly","tightness","tightrope","tightwad","tigress","tile","tiling","till","tilt","timid","timing","timothy","tinderbox","tinfoil","tingle","tingling","tingly","tinker","tinkling","tinsel","tinsmith","tint","tinwork","tiny","tipoff","tipped","tipper","tipping","tiptoeing","tiptop","tiring","tissue","trace","tracing","track","traction","tractor","trade","trading","tradition","traffic","tragedy","trailing","trailside","train","traitor","trance","tranquil","transfer","transform","translate","transpire","transport","transpose","trapdoor","trapeze","trapezoid","trapped","trapper","trapping","traps","trash","travel","traverse","travesty","tray","treachery","treading","treadmill","treason","treat","treble","tree","trekker","tremble","trembling","tremor","trench","trend","trespass","triage","trial","triangle","tribesman","tribunal","tribune","tributary","tribute","triceps","trickery","trickily","tricking","trickle","trickster","tricky","tricolor","tricycle","trident","tried","trifle","trifocals","trillion","trilogy","trimester","trimmer","trimming","trimness","trinity","trio","tripod","tripping","triumph","trivial","trodden","trolling","trombone","trophy","tropical","tropics","trouble","troubling","trough","trousers","trout","trowel","truce","truck","truffle","trump","trunks","trustable","trustee","trustful","trusting","trustless","truth","try","tubby","tubeless","tubular","tucking","tuesday","tug","tuition","tulip","tumble","tumbling","tummy","turban","turbine","turbofan","turbojet","turbulent","turf","turkey","turmoil","turret","turtle","tusk","tutor","tutu","tux","tweak","tweed","tweet","tweezers","twelve","twentieth","twenty","twerp","twice","twiddle","twiddling","twig","twilight","twine","twins","twirl","twistable","twisted","twister","twisting","twisty","twitch","twitter","tycoon","tying","tyke","udder","ultimate","ultimatum","ultra","umbilical","umbrella","umpire","unabashed","unable","unadorned","unadvised","unafraid","unaired","unaligned","unaltered","unarmored","unashamed","unaudited","unawake","unaware","unbaked","unbalance","unbeaten","unbend","unbent","unbiased","unbitten","unblended","unblessed","unblock","unbolted","unbounded","unboxed","unbraided","unbridle","unbroken","unbuckled","unbundle","unburned","unbutton","uncanny","uncapped","uncaring","uncertain","unchain","unchanged","uncharted","uncheck","uncivil","unclad","unclaimed","unclamped","unclasp","uncle","unclip","uncloak","unclog","unclothed","uncoated","uncoiled","uncolored","uncombed","uncommon","uncooked","uncork","uncorrupt","uncounted","uncouple","uncouth","uncover","uncross","uncrown","uncrushed","uncured","uncurious","uncurled","uncut","undamaged","undated","undaunted","undead","undecided","undefined","underage","underarm","undercoat","undercook","undercut","underdog","underdone","underfed","underfeed","underfoot","undergo","undergrad","underhand","underline","underling","undermine","undermost","underpaid","underpass","underpay","underrate","undertake","undertone","undertook","undertow","underuse","underwear","underwent","underwire","undesired","undiluted","undivided","undocked","undoing","undone","undrafted","undress","undrilled","undusted","undying","unearned","unearth","unease","uneasily","uneasy","uneatable","uneaten","unedited","unelected","unending","unengaged","unenvied","unequal","unethical","uneven","unexpired","unexposed","unfailing","unfair","unfasten","unfazed","unfeeling","unfiled","unfilled","unfitted","unfitting","unfixable","unfixed","unflawed","unfocused","unfold","unfounded","unframed","unfreeze","unfrosted","unfrozen","unfunded","unglazed","ungloved","unglue","ungodly","ungraded","ungreased","unguarded","unguided","unhappily","unhappy","unharmed","unhealthy","unheard","unhearing","unheated","unhelpful","unhidden","unhinge","unhitched","unholy","unhook","unicorn","unicycle","unified","unifier","uniformed","uniformly","unify","unimpeded","uninjured","uninstall","uninsured","uninvited","union","uniquely","unisexual","unison","unissued","unit","universal","universe","unjustly","unkempt","unkind","unknotted","unknowing","unknown","unlaced","unlatch","unlawful","unleaded","unlearned","unleash","unless","unleveled","unlighted","unlikable","unlimited","unlined","unlinked","unlisted","unlit","unlivable","unloaded","unloader","unlocked","unlocking","unlovable","unloved","unlovely","unloving","unluckily","unlucky","unmade","unmanaged","unmanned","unmapped","unmarked","unmasked","unmasking","unmatched","unmindful","unmixable","unmixed","unmolded","unmoral","unmovable","unmoved","unmoving","unnamable","unnamed","unnatural","unneeded","unnerve","unnerving","unnoticed","unopened","unopposed","unpack","unpadded","unpaid","unpainted","unpaired","unpaved","unpeeled","unpicked","unpiloted","unpinned","unplanned","unplanted","unpleased","unpledged","unplowed","unplug","unpopular","unproven","unquote","unranked","unrated","unraveled","unreached","unread","unreal","unreeling","unrefined","unrelated","unrented","unrest","unretired","unrevised","unrigged","unripe","unrivaled","unroasted","unrobed","unroll","unruffled","unruly","unrushed","unsaddle","unsafe","unsaid","unsalted","unsaved","unsavory","unscathed","unscented","unscrew","unsealed","unseated","unsecured","unseeing","unseemly","unseen","unselect","unselfish","unsent","unsettled","unshackle","unshaken","unshaved","unshaven","unsheathe","unshipped","unsightly","unsigned","unskilled","unsliced","unsmooth","unsnap","unsocial","unsoiled","unsold","unsolved","unsorted","unspoiled","unspoken","unstable","unstaffed","unstamped","unsteady","unsterile","unstirred","unstitch","unstopped","unstuck","unstuffed","unstylish","unsubtle","unsubtly","unsuited","unsure","unsworn","untagged","untainted","untaken","untamed","untangled","untapped","untaxed","unthawed","unthread","untidy","untie","until","untimed","untimely","untitled","untoasted","untold","untouched","untracked","untrained","untreated","untried","untrimmed","untrue","untruth","unturned","untwist","untying","unusable","unused","unusual","unvalued","unvaried","unvarying","unveiled","unveiling","unvented","unviable","unvisited","unvocal","unwanted","unwarlike","unwary","unwashed","unwatched","unweave","unwed","unwelcome","unwell","unwieldy","unwilling","unwind","unwired","unwitting","unwomanly","unworldly","unworn","unworried","unworthy","unwound","unwoven","unwrapped","unwritten","unzip","upbeat","upchuck","upcoming","upcountry","update","upfront","upgrade","upheaval","upheld","uphill","uphold","uplifted","uplifting","upload","upon","upper","upright","uprising","upriver","uproar","uproot","upscale","upside","upstage","upstairs","upstart","upstate","upstream","upstroke","upswing","uptake","uptight","uptown","upturned","upward","upwind","uranium","urban","urchin","urethane","urgency","urgent","urging","urologist","urology","usable","usage","useable","used","uselessly","user","usher","usual","utensil","utility","utilize","utmost","utopia","utter","vacancy","vacant","vacate","vacation","vagabond","vagrancy","vagrantly","vaguely","vagueness","valiant","valid","valium","valley","valuables","value","vanilla","vanish","vanity","vanquish","vantage","vaporizer","variable","variably","varied","variety","various","varmint","varnish","varsity","varying","vascular","vaseline","vastly","vastness","veal","vegan","veggie","vehicular","velcro","velocity","velvet","vendetta","vending","vendor","veneering","vengeful","venomous","ventricle","venture","venue","venus","verbalize","verbally","verbose","verdict","verify","verse","version","versus","vertebrae","vertical","vertigo","very","vessel","vest","veteran","veto","vexingly","viability","viable","vibes","vice","vicinity","victory","video","viewable","viewer","viewing","viewless","viewpoint","vigorous","village","villain","vindicate","vineyard","vintage","violate","violation","violator","violet","violin","viper","viral","virtual","virtuous","virus","visa","viscosity","viscous","viselike","visible","visibly","vision","visiting","visitor","visor","vista","vitality","vitalize","vitally","vitamins","vivacious","vividly","vividness","vixen","vocalist","vocalize","vocally","vocation","voice","voicing","void","volatile","volley","voltage","volumes","voter","voting","voucher","vowed","vowel","voyage","wackiness","wad","wafer","waffle","waged","wager","wages","waggle","wagon","wake","waking","walk","walmart","walnut","walrus","waltz","wand","wannabe","wanted","wanting","wasabi","washable","washbasin","washboard","washbowl","washcloth","washday","washed","washer","washhouse","washing","washout","washroom","washstand","washtub","wasp","wasting","watch","water","waviness","waving","wavy","whacking","whacky","wham","wharf","wheat","whenever","whiff","whimsical","whinny","whiny","whisking","whoever","whole","whomever","whoopee","whooping","whoops","why","wick","widely","widen","widget","widow","width","wieldable","wielder","wife","wifi","wikipedia","wildcard","wildcat","wilder","wildfire","wildfowl","wildland","wildlife","wildly","wildness","willed","willfully","willing","willow","willpower","wilt","wimp","wince","wincing","wind","wing","winking","winner","winnings","winter","wipe","wired","wireless","wiring","wiry","wisdom","wise","wish","wisplike","wispy","wistful","wizard","wobble","wobbling","wobbly","wok","wolf","wolverine","womanhood","womankind","womanless","womanlike","womanly","womb","woof","wooing","wool","woozy","word","work","worried","worrier","worrisome","worry","worsening","worshiper","worst","wound","woven","wow","wrangle","wrath","wreath","wreckage","wrecker","wrecking","wrench","wriggle","wriggly","wrinkle","wrinkly","wrist","writing","written","wrongdoer","wronged","wrongful","wrongly","wrongness","wrought","xbox","xerox","yahoo","yam","yanking","yapping","yard","yarn","yeah","yearbook","yearling","yearly","yearning","yeast","yelling","yelp","yen","yesterday","yiddish","yield","yin","yippee","yo-yo","yodel","yoga","yogurt","yonder","yoyo","yummy","zap","zealous","zebra","zen","zeppelin","zero","zestfully","zesty","zigzagged","zipfile","zipping","zippy","zips","zit","zodiac","zombie","zone","zoning","zookeeper","zoologist","zoology","zoom"],Rh=Object.freeze({numWords:3,wordSeparator:"-",capitalize:!1,includeNumber:!1});const Eh=function(){const e=Object.freeze({min:3,max:20});return Object.freeze({numWords:e})}();class Fh{constructor(e){var t,i;this.policy=structuredClone(e),this.numWords=(t=e.minNumberWords,i=Eh.numWords,{min:Math.max(i.min,t),max:Math.max(i.max,t)})}get policyInEffect(){return[this.policy.capitalize,this.policy.includeNumber,this.policy.minNumberWords>Eh.numWords.min].includes(!0)}applyPolicy(e){const t=this.policy.capitalize||e.capitalize||!1,i=this.policy.includeNumber||e.includeNumber||!1,n=function(e,t){const{min:i,max:n}=t,r=Math.min(null!=e?e:t.min,n);return Math.max(r,i)}(e.numWords,this.numWords);return Object.assign(Object.assign({},e),{numWords:n,capitalize:t,includeNumber:i})}sanitize(e){var t,i;const n=""===e.wordSeparator?"":null!==(i=null===(t=e.wordSeparator)||void 0===t?void 0:t[0])&&void 0!==i?i:Rh.wordSeparator;return Object.assign(Object.assign({},e),{wordSeparator:n})}}class Mh{constructor(e,t){this.password=e,this.date=t}}var Kh=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Lh={length:14,minLength:5,ambiguous:!1,number:!0,minNumber:1,uppercase:!0,minUppercase:0,lowercase:!0,minLowercase:0,special:!1,minSpecial:0,type:"password",numWords:3,wordSeparator:"-",capitalize:!1,includeNumber:!1},zh=new Th;class Vh{constructor(e,t,i){this.cryptoService=e,this.policyService=t,this.stateService=i}generatePassword(e){var t;return Kh(this,void 0,void 0,(function*(){if("passphrase"===(null!==(t=e.type)&&void 0!==t?t:Lh.type))return this.generatePassphrase(Object.assign(Object.assign({},Lh),e));const i=new Uh(zh).sanitize(Object.assign(Object.assign({},Lh),e)),n=[];if(i.lowercase&&i.minLowercase>0)for(let e=0;e0)for(let e=0;e0)for(let e=0;e0)for(let e=0;e{e.enabled&&null!=e.data&&(null==i&&(i=new Th),null!=e.data.defaultType&&"password"!==i.defaultType&&(i.defaultType=e.data.defaultType),null!=e.data.minLength&&e.data.minLength>i.minLength&&(i.minLength=e.data.minLength),e.data.useUpper&&(i.useUppercase=!0),e.data.useLower&&(i.useLowercase=!0),e.data.useNumbers&&(i.useNumbers=!0),null!=e.data.minNumbers&&e.data.minNumbers>i.numberCount&&(i.numberCount=e.data.minNumbers),e.data.useSpecial&&(i.useSpecial=!0),null!=e.data.minSpecial&&e.data.minSpecial>i.specialCount&&(i.specialCount=e.data.minSpecial),null!=e.data.minNumberWords&&e.data.minNumberWords>i.minNumberWords&&(i.minNumberWords=e.data.minNumberWords),e.data.capitalize&&(i.capitalize=!0),e.data.includeNumber&&(i.includeNumber=!0))})),i}))}saveOptions(e){return Kh(this,void 0,void 0,(function*(){yield this.stateService.setPasswordGenerationOptions(e)}))}getHistory(){return Kh(this,void 0,void 0,(function*(){if(!(yield this.cryptoService.hasUserKey()))return new Array;if(null==(yield this.stateService.getDecryptedPasswordGenerationHistory())){const e=yield this.stateService.getEncryptedPasswordGenerationHistory(),t=yield this.decryptHistory(e);yield this.stateService.setDecryptedPasswordGenerationHistory(t)}const e=yield this.stateService.getDecryptedPasswordGenerationHistory();return null!=e?e:new Array}))}addHistory(e){return Kh(this,void 0,void 0,(function*(){if(!(yield this.cryptoService.hasUserKey()))return;const t=yield this.getHistory();if(this.matchesPrevious(e,t))return;t.unshift(new Mh(e,Date.now())),t.length>100&&t.pop();const i=yield this.encryptHistory(t);return yield this.stateService.setDecryptedPasswordGenerationHistory(t),yield this.stateService.setEncryptedPasswordGenerationHistory(i)}))}clear(e){return Kh(this,void 0,void 0,(function*(){yield this.stateService.setEncryptedPasswordGenerationHistory(null,{userId:e}),yield this.stateService.setDecryptedPasswordGenerationHistory(null,{userId:e})}))}normalizeOptions(e,t){const i="password"==e.type?new Uh(t):new Fh(t),n=i.applyPolicy(e),r=i.sanitize(n);return Object.assign(e,r),e}capitalize(e){return e.charAt(0).toUpperCase()+e.slice(1)}appendRandomNumberToRandomWord(e){return Kh(this,void 0,void 0,(function*(){if(null==e||e.length<=0)return;const t=yield this.cryptoService.randomNumber(0,e.length-1),i=yield this.cryptoService.randomNumber(0,9);e[t]=e[t]+i}))}encryptHistory(e){return Kh(this,void 0,void 0,(function*(){if(null==e||0===e.length)return Promise.resolve([]);const t=e.map((e=>Kh(this,void 0,void 0,(function*(){const t=yield this.cryptoService.encrypt(e.password);return new Mh(t.encryptedString,e.date)}))));return yield Promise.all(t)}))}decryptHistory(e){return Kh(this,void 0,void 0,(function*(){if(null==e||0===e.length)return Promise.resolve([]);const t=e.map((e=>Kh(this,void 0,void 0,(function*(){const t=yield this.cryptoService.decryptToUtf8(new z(e.password));return new Mh(t,e.date)}))));return yield Promise.all(t)}))}matchesPrevious(e,t){return null!=t&&0!==t.length&&t[t.length-1].password===e}shuffleArray(e){return Kh(this,void 0,void 0,(function*(){for(let t=e.length-1;t>0;t--){const i=yield this.cryptoService.randomNumber(0,t);[e[t],e[i]]=[e[i],e[t]]}}))}}var Bh=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class _h{generate(e,t){var i,n,r;return Bh(this,void 0,void 0,(function*(){if(null==t.apiKey||""===t.apiKey)throw"Invalid addy.io API token.";if(null==(null===(i=t.anonaddy)||void 0===i?void 0:i.domain)||""===t.anonaddy.domain)throw"Invalid addy.io domain.";if(null==(null===(n=t.anonaddy)||void 0===n?void 0:n.baseUrl)||""===t.anonaddy.baseUrl)throw"Invalid addy.io url.";const s={redirect:"manual",cache:"no-store",method:"POST",headers:new Headers({Authorization:"Bearer "+t.apiKey,"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"})},o=t.anonaddy.baseUrl+"/api/v1/aliases";s.body=JSON.stringify({domain:t.anonaddy.domain,description:(null!=t.website?"Website: "+t.website+". ":"")+"Generated by Bitwarden."});const a=new Request(o,s),l=yield e.nativeFetch(a);if(200===l.status||201===l.status){const e=yield l.json();return null===(r=null==e?void 0:e.data)||void 0===r?void 0:r.email}if(401===l.status)throw"Invalid addy.io API token.";if(null!=(null==l?void 0:l.statusText))throw"addy.io error:\n"+l.statusText;throw"Unknown addy.io error occurred."}))}}var jh=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class $h{generate(e,t){return jh(this,void 0,void 0,(function*(){if(null==t.apiKey||""===t.apiKey)throw"Invalid DuckDuckGo API token.";const i={redirect:"manual",cache:"no-store",method:"POST",headers:new Headers({Authorization:"Bearer "+t.apiKey,"Content-Type":"application/json"})},n=new Request("https://quack.duckduckgo.com/api/email/addresses",i),r=yield e.nativeFetch(n);if(200===r.status||201===r.status){const e=yield r.json();if(e.address)return`${e.address}@duck.com`}else if(401===r.status)throw"Invalid DuckDuckGo API token.";throw"Unknown DuckDuckGo error occurred."}))}}var Wh=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class qh{generate(e,t){var i,n,r,s,o,a,l,c,d,u,h;return Wh(this,void 0,void 0,(function*(){if(null==t.apiKey||""===t.apiKey)throw"Invalid Fastmail API token.";const p=yield this.getAccountId(e,t);if(null==p||""===p)throw"Unable to obtain Fastmail masked email account ID.";const y={redirect:"manual",cache:"no-store",method:"POST",headers:new Headers({Authorization:"Bearer "+t.apiKey,"Content-Type":"application/json"})};y.body=JSON.stringify({using:["https://www.fastmail.com/dev/maskedemail","urn:ietf:params:jmap:core"],methodCalls:[["MaskedEmail/set",{accountId:p,create:{"new-masked-email":{state:"enabled",description:"",forDomain:t.website,emailPrefix:t.fastmail.prefix}}},"0"]]});const v=new Request("https://api.fastmail.com/jmap/api/",y),f=yield e.nativeFetch(v);if(200===f.status){const e=yield f.json();if(null!=e.methodResponses&&e.methodResponses.length>0&&e.methodResponses[0].length>0)if("MaskedEmail/set"===e.methodResponses[0][0]){if(null!=(null===(n=null===(i=e.methodResponses[0][1])||void 0===i?void 0:i.created)||void 0===n?void 0:n["new-masked-email"]))return null===(o=null===(s=null===(r=e.methodResponses[0][1])||void 0===r?void 0:r.created)||void 0===s?void 0:s["new-masked-email"])||void 0===o?void 0:o.email;if(null!=(null===(l=null===(a=e.methodResponses[0][1])||void 0===a?void 0:a.notCreated)||void 0===l?void 0:l["new-masked-email"]))throw"Fastmail error: "+(null===(u=null===(d=null===(c=e.methodResponses[0][1])||void 0===c?void 0:c.notCreated)||void 0===d?void 0:d["new-masked-email"])||void 0===u?void 0:u.description)}else if("error"===e.methodResponses[0][0])throw"Fastmail error: "+(null===(h=e.methodResponses[0][1])||void 0===h?void 0:h.description)}if(401===f.status||403===f.status)throw"Invalid Fastmail API token.";throw"Unknown Fastmail error occurred."}))}getAccountId(e,t){return Wh(this,void 0,void 0,(function*(){const i={cache:"no-store",method:"GET",headers:new Headers({Authorization:"Bearer "+t.apiKey})},n=new Request("https://api.fastmail.com/.well-known/jmap",i),r=yield e.nativeFetch(n);if(200===r.status){const e=yield r.json();if(null!=e.primaryAccounts)return e.primaryAccounts["https://www.fastmail.com/dev/maskedemail"]}return null}))}}var Hh=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Gh{generate(e,t){return Hh(this,void 0,void 0,(function*(){if(null==t.apiKey||""===t.apiKey)throw"Invalid Firefox Relay API token.";const i={redirect:"manual",cache:"no-store",method:"POST",headers:new Headers({Authorization:"Token "+t.apiKey,"Content-Type":"application/json"})};i.body=JSON.stringify({enabled:!0,generated_for:t.website,description:(null!=t.website?t.website+" - ":"")+"Generated by Bitwarden."});const n=new Request("https://relay.firefox.com/api/v1/relayaddresses/",i),r=yield e.nativeFetch(n);if(200===r.status||201===r.status){const e=yield r.json();return null==e?void 0:e.full_address}if(401===r.status)throw"Invalid Firefox Relay API token.";throw"Unknown Firefox Relay error occurred."}))}}class Jh{constructor(){this.fastmail=new Yh,this.anonaddy=new Qh,this.forwardemail=new Xh,this.simplelogin=new Zh}}class Yh{}class Qh{}class Xh{}class Zh{}var ep=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class tp{generate(e,t){return ep(this,void 0,void 0,(function*(){if(null==t.apiKey||""===t.apiKey)throw"Invalid SimpleLogin API key.";const i={redirect:"manual",cache:"no-store",method:"POST",headers:new Headers({Authentication:t.apiKey,"Content-Type":"application/json"})};let n=t.simplelogin.baseUrl+"/api/alias/random/new";null!=t.website&&(n+="?hostname="+t.website),i.body=JSON.stringify({note:(null!=t.website?"Website: "+t.website+". ":"")+"Generated by Bitwarden."});const r=new Request(n,i),s=yield e.nativeFetch(r);if(200===s.status||201===s.status){return(yield s.json()).alias}if(401===s.status)throw"Invalid SimpleLogin API key.";const o=yield s.json();if(null!=(null==o?void 0:o.error))throw"SimpleLogin error:"+o.error;throw"Unknown SimpleLogin error occurred."}))}}var ip=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class np{generate(e,t){var i,n;return ip(this,void 0,void 0,(function*(){if(null==t.apiKey||""===t.apiKey)throw"Invalid Forward Email API key.";if(null==(null===(i=t.forwardemail)||void 0===i?void 0:i.domain)||""===t.forwardemail.domain)throw"Invalid Forward Email domain.";const r={redirect:"manual",cache:"no-store",method:"POST",headers:new Headers({Authorization:"Basic "+p.fromUtf8ToB64(t.apiKey+":"),"Content-Type":"application/json"})},s=`https://api.forwardemail.net/v1/domains/${t.forwardemail.domain}/aliases`;r.body=JSON.stringify({labels:t.website,description:(null!=t.website?"Website: "+t.website+". ":"")+"Generated by Bitwarden."});const o=new Request(s,r),a=yield e.nativeFetch(o);if(200===a.status||201===a.status){const e=yield a.json();return(null==e?void 0:e.name)+"@"+((null===(n=null==e?void 0:e.domain)||void 0===n?void 0:n.name)||t.forwardemail.domain)}if(401===a.status)throw"Invalid Forward Email API key.";const l=yield a.json();if(null!=(null==l?void 0:l.message))throw"Forward Email error:\n"+l.message;if(null!=(null==l?void 0:l.error))throw"Forward Email error:\n"+l.error;throw"Unknown Forward Email error occurred."}))}}var rp=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const sp={type:"word",wordCapitalize:!0,wordIncludeNumber:!0,subaddressType:"random",catchallType:"random",forwardedService:"",forwardedAnonAddyDomain:"anonaddy.me",forwardedAnonAddyBaseUrl:"https://app.addy.io",forwardedForwardEmailDomain:"hideaddress.net",forwardedSimpleLoginBaseUrl:"https://app.simplelogin.io"};class op{constructor(e,t,i){this.cryptoService=e,this.stateService=t,this.apiService=i}generateUsername(e){return"catchall"===e.type?this.generateCatchall(e):"subaddress"===e.type?this.generateSubaddress(e):"forwarded"===e.type?this.generateForwarded(e):this.generateWord(e)}generateWord(e){return rp(this,void 0,void 0,(function*(){const t=Object.assign({},sp,e);null==t.wordCapitalize&&(t.wordCapitalize=!0),null==t.wordIncludeNumber&&(t.wordIncludeNumber=!0);const i=yield this.cryptoService.randomNumber(0,Nh.length-1);let n=Nh[i];if(t.wordCapitalize&&(n=n.charAt(0).toUpperCase()+n.slice(1)),t.wordIncludeNumber){const e=yield this.cryptoService.randomNumber(1,9999);n+=this.zeroPad(e.toString(),4)}return n}))}generateSubaddress(e){return rp(this,void 0,void 0,(function*(){const t=Object.assign({},sp,e),i=t.subaddressEmail;if(null==i||i.length<3)return t.subaddressEmail;const n=i.indexOf("@");if(n<1||n>=i.length-1)return i;null==t.subaddressType&&(t.subaddressType="random");const r=i.substr(0,n),s=i.substr(n+1,i.length);let o="";return"random"===t.subaddressType?o=yield this.randomString(8):"website-name"===t.subaddressType&&(o=t.website),r+"+"+o+"@"+s}))}generateCatchall(e){return rp(this,void 0,void 0,(function*(){const t=Object.assign({},sp,e);if(null==t.catchallDomain||""===t.catchallDomain)return null;null==t.catchallType&&(t.catchallType="random");let i="";return"random"===t.catchallType?i=yield this.randomString(8):"website-name"===t.catchallType&&(i=t.website),i+"@"+t.catchallDomain}))}generateForwarded(e){return rp(this,void 0,void 0,(function*(){const t=Object.assign({},sp,e);if(null==t.forwardedService)return null;let i=null;const n=new Jh;return n.website=t.website,"simplelogin"===t.forwardedService?(i=new tp,n.apiKey=t.forwardedSimpleLoginApiKey,n.simplelogin.baseUrl=t.forwardedSimpleLoginBaseUrl):"anonaddy"===t.forwardedService?(i=new _h,n.apiKey=t.forwardedAnonAddyApiToken,n.anonaddy.domain=t.forwardedAnonAddyDomain,n.anonaddy.baseUrl=t.forwardedAnonAddyBaseUrl):"firefoxrelay"===t.forwardedService?(i=new Gh,n.apiKey=t.forwardedFirefoxApiToken):"fastmail"===t.forwardedService?(i=new qh,n.apiKey=t.forwardedFastmailApiToken):"duckduckgo"===t.forwardedService?(i=new $h,n.apiKey=t.forwardedDuckDuckGoToken):"forwardemail"===t.forwardedService&&(i=new np,n.apiKey=t.forwardedForwardEmailApiToken,n.forwardemail.domain=t.forwardedForwardEmailDomain),null==i?null:i.generate(this.apiService,n)}))}getOptions(){return rp(this,void 0,void 0,(function*(){let e=yield this.stateService.getUsernameGenerationOptions();return e=null==e?Object.assign({},sp):Object.assign({},sp,e),yield this.stateService.setUsernameGenerationOptions(e),e}))}saveOptions(e){return rp(this,void 0,void 0,(function*(){yield this.stateService.setUsernameGenerationOptions(e)}))}randomString(e){return rp(this,void 0,void 0,(function*(){let t="";const i="abcdefghijklmnopqrstuvwxyz1234567890";for(let n=0;n=t?e:new Array(t-e.length+1).join("0")+e}}var ap,lp=i(3653);class cp{getPasswordStrength(e,t=null,i=null){if(null==e||0===e.length)return null;const n=["bitwarden","bit","warden",...null!=i?i:[],...this.emailToUserInputs(t)],r=Array.from(new Set(n));return lp(e,r)}emailToUserInputs(e){if(null==e||0===e.length)return[];const t=e.indexOf("@");return t<0?[]:e.substring(0,t).trim().toLowerCase().split(/[^A-Za-z0-9]/)}}!function(e){e[e.Text=0]="Text",e[e.File=1]="File"}(ap||(ap={}));class dp{constructor(e){null!=e&&(this.id=e.id,this.fileName=e.fileName,this.size=e.size,this.sizeName=e.sizeName)}}class up{constructor(e){null!=e&&(this.text=e.text,this.hidden=e.hidden)}}class hp{constructor(e){if(null!=e)switch(this.id=e.id,this.accessId=e.accessId,this.type=e.type,this.name=e.name,this.notes=e.notes,this.key=e.key,this.maxAccessCount=e.maxAccessCount,this.accessCount=e.accessCount,this.revisionDate=e.revisionDate,this.expirationDate=e.expirationDate,this.deletionDate=e.deletionDate,this.password=e.password,this.disabled=e.disable,this.hideEmail=e.hideEmail,this.type){case ap.Text:this.text=new up(e.text);break;case ap.File:this.file=new dp(e.file)}}}class pp{constructor(e,t){switch(this.type=e.type,this.fileLength=t,this.name=e.name?e.name.encryptedString:null,this.notes=e.notes?e.notes.encryptedString:null,this.maxAccessCount=e.maxAccessCount,this.expirationDate=null!=e.expirationDate?e.expirationDate.toISOString():null,this.deletionDate=null!=e.deletionDate?e.deletionDate.toISOString():null,this.key=null!=e.key?e.key.encryptedString:null,this.password=e.password,this.disabled=e.disabled,this.hideEmail=e.hideEmail,this.type){case ap.Text:this.text=new qu,this.text.text=null!=e.text.text?e.text.text.encryptedString:null,this.text.hidden=e.text.hidden;break;case ap.File:this.file=new Wu,this.file.fileName=null!=e.file.fileName?e.file.fileName.encryptedString:null}}}class yp extends J{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.type=this.getResponseProperty("Type"),this.name=this.getResponseProperty("Name");const t=this.getResponseProperty("Text");null!=t&&(this.text=new qu(t));const i=this.getResponseProperty("File");null!=i&&(this.file=new Wu(i)),this.expirationDate=this.getResponseProperty("ExpirationDate"),this.creatorIdentifier=this.getResponseProperty("CreatorIdentifier")}}class vp extends J{constructor(e){super(e),this.id=null,this.url=null,this.id=this.getResponseProperty("Id"),this.url=this.getResponseProperty("Url")}}class fp extends J{constructor(e){super(e),this.url=null,this.fileUploadType=this.getResponseProperty("FileUploadType");const t=this.getResponseProperty("SendResponse");this.sendResponse=null==t?null:new Hu(t),this.url=this.getResponseProperty("Url")}}var gp=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class mp{constructor(e,t,i){this.apiService=e,this.fileUploadService=t,this.sendService=i}getSend(e){return gp(this,void 0,void 0,(function*(){const t=yield this.apiService.send("GET","/sends/"+e,null,!0,!0);return new Hu(t)}))}postSendAccess(e,t,i){return gp(this,void 0,void 0,(function*(){const n=yield this.apiService.send("POST","/sends/access/"+e,t,!1,!0,i,(t=>{t.set("Send-Id",e)}));return new yp(n)}))}getSendFileDownloadData(e,t,i){return gp(this,void 0,void 0,(function*(){const n=yield this.apiService.send("POST","/sends/"+e.id+"/access/file/"+e.file.id,t,!1,!0,i,(t=>{t.set("Send-Id",e.id)}));return new vp(n)}))}getSends(){return gp(this,void 0,void 0,(function*(){const e=yield this.apiService.send("GET","/sends",null,!0,!0);return new an(e,Hu)}))}postSend(e){return gp(this,void 0,void 0,(function*(){const t=yield this.apiService.send("POST","/sends",e,!0,!0);return new Hu(t)}))}postFileTypeSend(e){return gp(this,void 0,void 0,(function*(){const t=yield this.apiService.send("POST","/sends/file/v2",e,!0,!0);return new fp(t)}))}renewSendFileUploadUrl(e,t){return gp(this,void 0,void 0,(function*(){const i=yield this.apiService.send("GET","/sends/"+e+"/file/"+t,null,!0,!0);return new fp(i)}))}postSendFile(e,t,i){return this.apiService.send("POST","/sends/"+e+"/file/"+t,i,!0,!1)}postSendFileLegacy(e){return gp(this,void 0,void 0,(function*(){const t=yield this.apiService.send("POST","/sends/file",e,!0,!0);return new Hu(t)}))}putSend(e,t){return gp(this,void 0,void 0,(function*(){const i=yield this.apiService.send("PUT","/sends/"+e,t,!0,!0);return new Hu(i)}))}putSendRemovePassword(e){return gp(this,void 0,void 0,(function*(){const t=yield this.apiService.send("PUT","/sends/"+e+"/remove-password",null,!0,!0);return new Hu(t)}))}deleteSend(e){return this.apiService.send("DELETE","/sends/"+e,null,!0,!1)}save(e){return gp(this,void 0,void 0,(function*(){const t=yield this.upload(e),i=new hp(t);yield this.sendService.upsert(i)}))}delete(e){return gp(this,void 0,void 0,(function*(){yield this.deleteSend(e),yield this.sendService.delete(e)}))}removePassword(e){return gp(this,void 0,void 0,(function*(){const t=yield this.putSendRemovePassword(e),i=new hp(t);yield this.sendService.upsert(i)}))}upload(e){var t;return gp(this,void 0,void 0,(function*(){const i=new pp(e[0],null===(t=e[1])||void 0===t?void 0:t.buffer.byteLength);let n;if(null==e[0].id){if(e[0].type===ap.Text)n=yield this.postSend(i);else try{const t=yield this.postFileTypeSend(i);n=t.sendResponse,yield this.fileUploadService.upload(t,e[0].file.fileName,e[1],this.generateMethods(t,n))}catch(t){if(!(t instanceof Y&&404===t.statusCode))throw t instanceof Y?new Error(t.getSingleMessage()):t;n=yield this.legacyServerSendFileUpload(e,i)}e[0].id=n.id,e[0].accessId=n.accessId}else n=yield this.putSend(e[0].id,i);return n}))}generateMethods(e,t){return{postDirect:this.generatePostDirectCallback(t),renewFileUploadUrl:this.generateRenewFileUploadUrlCallback(t.id,t.file.id),rollback:this.generateRollbackCallback(t.id)}}generatePostDirectCallback(e){return t=>this.postSendFile(e.id,e.file.id,t)}generateRenewFileUploadUrlCallback(e,t){return()=>gp(this,void 0,void 0,(function*(){const i=yield this.renewSendFileUploadUrl(e,t);return null==i?void 0:i.url}))}generateRollbackCallback(e){return()=>this.deleteSend(e)}legacyServerSendFileUpload(e,t){return gp(this,void 0,void 0,(function*(){const i=new FormData;try{const n=new Blob([e[1].buffer],{type:"application/octet-stream"});i.append("model",JSON.stringify(t)),i.append("data",n,e[0].file.fileName.encryptedString)}catch(n){if(!p.isNode||p.isBrowser)throw n;i.append("model",JSON.stringify(t)),i.append("data",Buffer.from(e[1].buffer),{filepath:e[0].file.fileName.encryptedString,contentType:"application/octet-stream"})}return yield this.postSendFileLegacy(i)}))}}var wp=i(82783);function Sp(e){return"string"==typeof e?JSON.parse(e):e}function bp(e){const t=Sp({showPasswordless:!0,enableCipherKeyEncryption:!1,accountSwitching:!0});return null==t[e]||!!t[e]}function Pp(e){return(t,i,n)=>{const r=n.value,s=new Map;return{value:function(...t){const i=(e=>{let t=s.get(e);return null!=t||(t=new Map,s.set(e,t)),t})(this),n=e(t);let o=i.get(n);if(null!=o)return o;const a=()=>{i.delete(n),0===i.size&&s.delete(this)};return o=r.apply(this,t).then((e=>(a(),e))).catch((e=>{throw a(),e})),i.set(n,o),o}}}}class kp{constructor(e){this.comparator=e,this.sortedCiphersByUrl=new Map,this.timeouts=new Map}isCached(e){return this.sortedCiphersByUrl.has(e)}addCiphers(e,t){t.sort(this.comparator),this.sortedCiphersByUrl.set(e,new Op(t)),this.resetTimer(e)}getLastUsed(e){return this.resetTimer(e),this.isCached(e)?this.sortedCiphersByUrl.get(e).getLastUsed():null}getLastLaunched(e){return this.isCached(e)?this.sortedCiphersByUrl.get(e).getLastLaunched():null}getNext(e){return this.resetTimer(e),this.isCached(e)?this.sortedCiphersByUrl.get(e).getNext():null}updateLastUsedIndex(e){this.isCached(e)&&this.sortedCiphersByUrl.get(e).updateLastUsedIndex()}clear(){this.sortedCiphersByUrl.clear(),this.timeouts.clear()}resetTimer(e){clearTimeout(this.timeouts.get(e)),this.timeouts.set(e,setTimeout((()=>{this.sortedCiphersByUrl.delete(e),this.timeouts.delete(e)}),3e3))}}class Op{constructor(e){this.ciphers=e,this.lastUsedIndex=-1}getLastUsed(){return this.lastUsedIndex=Math.max(this.lastUsedIndex,0),this.ciphers[this.lastUsedIndex]}getLastLaunched(){const e=this.ciphers.filter((e=>{var t;return null===(t=e.localData)||void 0===t?void 0:t.lastLaunched}));return e.sort(((e,t)=>t.localData.lastLaunched.valueOf()-e.localData.lastLaunched.valueOf()))[0]}getNextIndex(){return(this.lastUsedIndex+1)%this.ciphers.length}getNext(){return this.ciphers[this.getNextIndex()]}updateLastUsedIndex(){this.lastUsedIndex=this.getNextIndex()}}class Cp{constructor(e,t){this.ids=null==e?[]:e,this.organizationId=t}}class Ap{constructor(e,t){this.ids=null==e?[]:e,this.folderId=t}}class Dp{constructor(e,t){this.ids=null==e?[]:e,this.organizationId=t}}class xp{}class Ip{constructor(e){var t,i,n;switch(this.type=e.type,this.folderId=e.folderId,this.organizationId=e.organizationId,this.name=e.name?e.name.encryptedString:null,this.notes=e.notes?e.notes.encryptedString:null,this.favorite=e.favorite,this.lastKnownRevisionDate=e.revisionDate,this.reprompt=e.reprompt,this.key=null===(t=e.key)||void 0===t?void 0:t.encryptedString,this.type){case Pe.Login:this.login=new Kd,this.login.uris=null!==(n=null===(i=e.login.uris)||void 0===i?void 0:i.map((e=>{const t=new Md;return t.uri=null!=e.uri?e.uri.encryptedString:null,t.match=null!=e.match?e.match:null,t.uriChecksum=null!=e.uriChecksum?e.uriChecksum.encryptedString:null,t})))&&void 0!==n?n:[],this.login.username=e.login.username?e.login.username.encryptedString:null,this.login.password=e.login.password?e.login.password.encryptedString:null,this.login.passwordRevisionDate=null!=e.login.passwordRevisionDate?e.login.passwordRevisionDate.toISOString():null,this.login.totp=e.login.totp?e.login.totp.encryptedString:null,this.login.autofillOnPageLoad=e.login.autofillOnPageLoad,null!=e.login.fido2Credentials&&(this.login.fido2Credentials=e.login.fido2Credentials.map((e=>{const t=new Fd;return t.credentialId=null!=e.credentialId?e.credentialId.encryptedString:null,t.keyType=null!=e.keyType?e.keyType.encryptedString:null,t.keyAlgorithm=null!=e.keyAlgorithm?e.keyAlgorithm.encryptedString:null,t.keyCurve=null!=e.keyCurve?e.keyCurve.encryptedString:null,t.keyValue=null!=e.keyValue?e.keyValue.encryptedString:null,t.rpId=null!=e.rpId?e.rpId.encryptedString:null,t.rpName=null!=e.rpName?e.rpName.encryptedString:null,t.counter=null!=e.counter?e.counter.encryptedString:null,t.userHandle=null!=e.userHandle?e.userHandle.encryptedString:null,t.userName=null!=e.userName?e.userName.encryptedString:null,t.userDisplayName=null!=e.userDisplayName?e.userDisplayName.encryptedString:null,t.discoverable=null!=e.discoverable?e.discoverable.encryptedString:null,t.creationDate=null!=e.creationDate?e.creationDate.toISOString():null,t})));break;case Pe.SecureNote:this.secureNote=new Ld,this.secureNote.type=e.secureNote.type;break;case Pe.Card:this.card=new Nd,this.card.cardholderName=null!=e.card.cardholderName?e.card.cardholderName.encryptedString:null,this.card.brand=null!=e.card.brand?e.card.brand.encryptedString:null,this.card.number=null!=e.card.number?e.card.number.encryptedString:null,this.card.expMonth=null!=e.card.expMonth?e.card.expMonth.encryptedString:null,this.card.expYear=null!=e.card.expYear?e.card.expYear.encryptedString:null,this.card.code=null!=e.card.code?e.card.code.encryptedString:null;break;case Pe.Identity:this.identity=new Ed,this.identity.title=null!=e.identity.title?e.identity.title.encryptedString:null,this.identity.firstName=null!=e.identity.firstName?e.identity.firstName.encryptedString:null,this.identity.middleName=null!=e.identity.middleName?e.identity.middleName.encryptedString:null,this.identity.lastName=null!=e.identity.lastName?e.identity.lastName.encryptedString:null,this.identity.address1=null!=e.identity.address1?e.identity.address1.encryptedString:null,this.identity.address2=null!=e.identity.address2?e.identity.address2.encryptedString:null,this.identity.address3=null!=e.identity.address3?e.identity.address3.encryptedString:null,this.identity.city=null!=e.identity.city?e.identity.city.encryptedString:null,this.identity.state=null!=e.identity.state?e.identity.state.encryptedString:null,this.identity.postalCode=null!=e.identity.postalCode?e.identity.postalCode.encryptedString:null,this.identity.country=null!=e.identity.country?e.identity.country.encryptedString:null,this.identity.company=null!=e.identity.company?e.identity.company.encryptedString:null,this.identity.email=null!=e.identity.email?e.identity.email.encryptedString:null,this.identity.phone=null!=e.identity.phone?e.identity.phone.encryptedString:null,this.identity.ssn=null!=e.identity.ssn?e.identity.ssn.encryptedString:null,this.identity.username=null!=e.identity.username?e.identity.username.encryptedString:null,this.identity.passportNumber=null!=e.identity.passportNumber?e.identity.passportNumber.encryptedString:null,this.identity.licenseNumber=null!=e.identity.licenseNumber?e.identity.licenseNumber.encryptedString:null}null!=e.fields&&(this.fields=e.fields.map((e=>{const t=new Rd;return t.type=e.type,t.name=e.name?e.name.encryptedString:null,t.value=e.value?e.value.encryptedString:null,t.linkedId=e.linkedId,t}))),null!=e.passwordHistory&&(this.passwordHistory=[],e.passwordHistory.forEach((e=>{this.passwordHistory.push({lastUsedDate:e.lastUsedDate,password:e.password?e.password.encryptedString:null})}))),null!=e.attachments&&(this.attachments={},this.attachments2={},e.attachments.forEach((e=>{const t=e.fileName?e.fileName.encryptedString:null;this.attachments[e.id]=t;const i=new xp;i.fileName=t,null!=e.key&&(i.key=e.key.encryptedString),this.attachments2[e.id]=i})))}}class Up extends Ip{constructor(e){super(e),this.id=e.id}}class Tp{constructor(e,t){null!=e&&(this.ciphers=[],e.forEach((e=>{this.ciphers.push(new Up(e))}))),this.collectionIds=t}}class Np{constructor(e,t,i,n=!1){this.organizationId=e,this.cipherIds=t,this.collectionIds=i,this.removeCollections=n}}class Rp{constructor(e){this.collectionIds=null==e?[]:e}}class Ep{constructor(e){this.cipher=new Ip(e),this.collectionIds=e.collectionIds}}class Fp{constructor(e){this.folderId=e.folderId,this.favorite=e.favorite}}class Mp{constructor(e){this.cipher=new Ip(e),this.collectionIds=e.collectionIds}}var Kp=function(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},Lp=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},zp=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Vp=new wp.SemVer("2024.2.0");class Bp{constructor(e,t,i,n,r,s,o,a,l,c){this.cryptoService=e,this.domainSettingsService=t,this.apiService=i,this.i18nService=n,this.searchService=r,this.stateService=s,this.autofillSettingsService=o,this.encryptService=a,this.cipherFileUploadService=l,this.configService=c,this.sortedCiphersCache=new kp(this.sortCiphersByLastUsed)}getDecryptedCipherCache(){return zp(this,void 0,void 0,(function*(){return yield this.stateService.getDecryptedCiphers()}))}setDecryptedCipherCache(e){return zp(this,void 0,void 0,(function*(){null!=e&&0===e.length||(yield this.stateService.setDecryptedCiphers(e)),null!=this.searchService&&(null==e?this.searchService.clearIndex():this.searchService.indexCiphers(e))}))}clearCache(e){return zp(this,void 0,void 0,(function*(){yield this.clearDecryptedCiphersState(e)}))}encrypt(e,t,i,n=null){var r;return zp(this,void 0,void 0,(function*(){null!=e.id&&(null==n&&(n=yield this.get(e.id)),null!=n&&(yield this.updateModelfromExistingCipher(e,n)),this.adjustPasswordHistoryLength(e));const s=new Co;if(s.id=e.id,s.folderId=e.folderId,s.favorite=e.favorite,s.organizationId=e.organizationId,s.type=e.type,s.collectionIds=e.collectionIds,s.revisionDate=e.revisionDate,s.reprompt=e.reprompt,s.edit=e.edit,yield this.getCipherKeyEncryptionEnabled()){s.key=null!==(r=null==n?void 0:n.key)&&void 0!==r?r:null;const o=yield this.getKeyForCipherKeyDecryption(s);return t||(t=o),i||(i=o),this.encryptCipherWithCipherKey(e,s,t,i)}if(null==t&&null!=s.organizationId&&null==(t=yield this.cryptoService.getOrgKey(s.organizationId)))throw new Error("Cannot encrypt cipher for organization. No key.");return s.key=null,this.encryptCipher(e,s,t)}))}encryptAttachments(e,t){return zp(this,void 0,void 0,(function*(){if(null==e||0===e.length)return null;const i=[],n=[];return e.forEach((e=>zp(this,void 0,void 0,(function*(){const r=new ho;r.id=e.id,r.size=e.size,r.sizeName=e.sizeName,r.url=e.url;const s=this.encryptObjProperty(e,r,{fileName:null},t).then((()=>zp(this,void 0,void 0,(function*(){null!=e.key&&(r.key=yield this.cryptoService.encrypt(e.key.key,t)),n.push(r)}))));i.push(s)})))),yield Promise.all(i),n}))}encryptFields(e,t){return zp(this,void 0,void 0,(function*(){if(!e||!e.length)return null;const i=this,n=[];return yield e.reduce(((e,r)=>zp(this,void 0,void 0,(function*(){yield e;const s=yield i.encryptField(r,t);n.push(s)}))),Promise.resolve()),n}))}encryptField(e,t){return zp(this,void 0,void 0,(function*(){const i=new yo;return i.type=e.type,i.linkedId=e.linkedId,e.type===ke.Boolean&&"true"!==e.value&&(e.value="false"),yield this.encryptObjProperty(e,i,{name:null,value:null},t),i}))}encryptPasswordHistories(e,t){return zp(this,void 0,void 0,(function*(){if(!e||!e.length)return null;const i=this,n=[];return yield e.reduce(((e,r)=>zp(this,void 0,void 0,(function*(){yield e;const s=yield i.encryptPasswordHistory(r,t);n.push(s)}))),Promise.resolve()),n}))}encryptPasswordHistory(e,t){return zp(this,void 0,void 0,(function*(){const i=new Po;return i.lastUsedDate=e.lastUsedDate,yield this.encryptObjProperty(e,i,{password:null},t),i}))}get(e){return zp(this,void 0,void 0,(function*(){const t=yield this.stateService.getEncryptedCiphers();if(null==t||!t.hasOwnProperty(e))return null;const i=yield this.stateService.getLocalData();return new Co(t[e],i?i[e]:null)}))}getAll(){return zp(this,void 0,void 0,(function*(){const e=yield this.stateService.getLocalData(),t=yield this.stateService.getEncryptedCiphers(),i=[];for(const n in t)t.hasOwnProperty(n)&&i.push(new Co(t[n],e?e[n]:null));return i}))}getAllDecrypted(){return zp(this,void 0,void 0,(function*(){if(null!=(yield this.getDecryptedCipherCache()))return yield this.reindexCiphers(),yield this.getDecryptedCipherCache();const e=yield this.getAll(),t=yield this.cryptoService.getOrgKeys(),i=yield this.cryptoService.getUserKeyWithLegacySupport();if(0===Object.keys(t).length&&null==i)return;const n=e.reduce(((e,t)=>{var i,n;return null!==(i=e[n=t.organizationId])&&void 0!==i||(e[n]=[]),e[t.organizationId].push(t),e}),{}),r=(yield Promise.all(Object.entries(n).map((([e,n])=>{var r;return this.encryptService.decryptItems(n,null!==(r=t[e])&&void 0!==r?r:i)})))).flat().sort(this.getLocaleSortingFunction());return yield this.setDecryptedCipherCache(r),r}))}reindexCiphers(){var e;return zp(this,void 0,void 0,(function*(){const t=yield this.stateService.getUserId();null!=this.searchService&&(null!==(e=this.searchService.indexedEntityId)&&void 0!==e?e:t)!==t&&this.searchService.indexCiphers(yield this.getDecryptedCipherCache(),t)}))}getAllDecryptedForGrouping(e,t=!0){return zp(this,void 0,void 0,(function*(){return(yield this.getAllDecrypted()).filter((i=>!i.isDeleted&&(!(!t||i.folderId!==e)||!t&&null!=i.collectionIds&&i.collectionIds.indexOf(e)>-1)))}))}getAllDecryptedForUrl(e,t,i=null){return zp(this,void 0,void 0,(function*(){if(null==e&&null==t)return Promise.resolve([]);const n=yield(0,r.z)(this.domainSettingsService.getUrlEquivalentDomains(e)),s=yield this.getAllDecrypted();return null!=i||(i=yield(0,r.z)(this.domainSettingsService.defaultUriMatchStrategy$)),s.filter((r=>{const s=r.type===Pe.Login&&null!==r.login;return null===r.deletedDate&&(!(!Array.isArray(t)||!t.includes(r.type)||s)||!!s&&r.login.matchesUri(e,n,i))}))}))}getAllFromApiForOrganization(e){return zp(this,void 0,void 0,(function*(){const t=yield this.apiService.getCiphersOrganization(e);return yield this.decryptOrganizationCiphersResponse(t,e)}))}getManyFromApiForOrganization(e){return zp(this,void 0,void 0,(function*(){const t=yield this.apiService.send("GET","/ciphers/organization-details/assigned?organizationId="+e,null,!0,!0);return this.decryptOrganizationCiphersResponse(t,e)}))}decryptOrganizationCiphersResponse(e,t){return zp(this,void 0,void 0,(function*(){if(null==(null==e?void 0:e.data)||e.data.length<1)return[];const i=e.data.map((e=>new Co(new co(e)))),n=yield this.cryptoService.getOrgKey(t),r=yield this.encryptService.decryptItems(i,n);return r.sort(this.getLocaleSortingFunction()),r}))}getLastUsedForUrl(e,t=!1){return zp(this,void 0,void 0,(function*(){return this.getCipherForUrl(e,!0,!1,t)}))}getLastLaunchedForUrl(e,t=!1){return zp(this,void 0,void 0,(function*(){return this.getCipherForUrl(e,!1,!0,t)}))}getNextCipherForUrl(e){return zp(this,void 0,void 0,(function*(){return this.getCipherForUrl(e,!1,!1,!1)}))}updateLastUsedIndexForUrl(e){this.sortedCiphersCache.updateLastUsedIndex(e)}updateLastUsedDate(e){return zp(this,void 0,void 0,(function*(){let t=yield this.stateService.getLocalData();t||(t={}),t[e]?t[e].lastUsedDate=(new Date).getTime():t[e]={lastUsedDate:(new Date).getTime()},yield this.stateService.setLocalData(t);const i=yield this.stateService.getDecryptedCiphers();if(i){for(let n=0;n{null==i.key&&n.push(this.shareAttachmentWithServer(i,e.id,t))})),yield Promise.all(n),e.organizationId=t,e.collectionIds=i;const r=yield this.encryptSharedCipher(e),s=new Mp(r),o=yield this.apiService.putShareCipher(e.id,s),a=new co(o,i);yield this.upsert(a)}))}shareManyWithServer(e,t,i){return zp(this,void 0,void 0,(function*(){const n=[],r=[];for(const s of e)s.organizationId=t,s.collectionIds=i,n.push(this.encryptSharedCipher(s).then((e=>{r.push(e)})));yield Promise.all(n);const s=new Tp(r,i);try{yield this.apiService.putShareCiphers(s)}catch(t){for(const t of e)t.organizationId=null,t.collectionIds=null;throw t}yield this.upsert(r.map((e=>e.toCipherData())))}))}saveAttachmentWithServer(e,t,i=!1){return new Promise(((n,r)=>{const s=new FileReader;s.readAsArrayBuffer(t),s.onload=s=>zp(this,void 0,void 0,(function*(){try{const r=yield this.saveAttachmentRawWithServer(e,t.name,s.target.result,i);n(r)}catch(e){r(e)}})),s.onerror=()=>{r("Error reading file.")}}))}saveAttachmentRawWithServer(e,t,i,n=!1){return zp(this,void 0,void 0,(function*(){const r=yield this.getKeyForCipherKeyDecryption(e),s=yield this.getCipherKeyEncryptionEnabled(),o=s&&null!=e.key?new N(yield this.encryptService.decryptToBytes(e.key,r)):r;if(null!=e.key&&!s){const t=yield e.decrypt(yield this.getKeyForCipherKeyDecryption(e));e=yield this.encrypt(t),yield this.updateWithServer(e)}const a=yield this.encryptService.encrypt(t,o),l=yield this.cryptoService.makeDataEncKey(o),c=yield this.encryptService.encryptToBytes(new Uint8Array(i),l[0]),d=yield this.cipherFileUploadService.upload(e,a,c,n,l),u=new co(d,e.collectionIds);return n||(yield this.upsert(u)),new Co(u)}))}saveCollectionsWithServer(e){return zp(this,void 0,void 0,(function*(){const t=new Rp(e.collectionIds);yield this.apiService.putCipherCollections(e.id,t);const i=e.toCipherData();yield this.upsert(i)}))}bulkUpdateCollectionsWithServer(e,t,i,n=!1){var r,s;return zp(this,void 0,void 0,(function*(){const o=new Np(e,t,i,n);yield this.apiService.send("POST","/ciphers/bulk-collections",o,!0,!1);const a=yield this.stateService.getEncryptedCiphers();for(const e of t){const t=a[e];t&&(t.collectionIds=n?null===(r=t.collectionIds)||void 0===r?void 0:r.filter((e=>!i.includes(e))):[...new Set([...null!==(s=t.collectionIds)&&void 0!==s?s:[],...i])])}yield this.clearCache(),yield this.stateService.setEncryptedCiphers(a)}))}upsert(e){return zp(this,void 0,void 0,(function*(){let t=yield this.stateService.getEncryptedCiphers();if(null==t&&(t={}),e instanceof co){const i=e;t[i.id]=i}else e.forEach((e=>{t[e.id]=e}));yield this.replace(t)}))}replace(e){return zp(this,void 0,void 0,(function*(){yield this.clearDecryptedCiphersState(),yield this.stateService.setEncryptedCiphers(e)}))}clear(e){return zp(this,void 0,void 0,(function*(){yield this.clearEncryptedCiphersState(e),yield this.clearCache(e)}))}moveManyWithServer(e,t){return zp(this,void 0,void 0,(function*(){yield this.apiService.putMoveCiphers(new Ap(e,t));let i=yield this.stateService.getEncryptedCiphers();null==i&&(i={}),e.forEach((e=>{i.hasOwnProperty(e)&&(i[e].folderId=t)})),yield this.clearCache(),yield this.stateService.setEncryptedCiphers(i)}))}delete(e){return zp(this,void 0,void 0,(function*(){const t=yield this.stateService.getEncryptedCiphers();if(null!=t){if("string"==typeof e){if(null==t[e])return;delete t[e]}else e.forEach((e=>{delete t[e]}));yield this.clearCache(),yield this.stateService.setEncryptedCiphers(t)}}))}deleteWithServer(e,t=!1){return zp(this,void 0,void 0,(function*(){t?yield this.apiService.deleteCipherAdmin(e):yield this.apiService.deleteCipher(e),yield this.delete(e)}))}deleteManyWithServer(e,t=!1){return zp(this,void 0,void 0,(function*(){const i=new Cp(e);t?yield this.apiService.deleteManyCiphersAdmin(i):yield this.apiService.deleteManyCiphers(i),yield this.delete(e)}))}deleteAttachment(e,t){return zp(this,void 0,void 0,(function*(){const i=yield this.stateService.getEncryptedCiphers();if(null!=i&&i.hasOwnProperty(e)&&null!=i[e].attachments){for(let n=0;nn?-1:null!=n&&null==i?1:0}sortCiphersByLastUsedThenName(e,t){const i=this.sortCiphersByLastUsed(e,t);return 0!==i?i:this.getLocaleSortingFunction()(e,t)}getLocaleSortingFunction(){return(e,t)=>{let i=e.name,n=t.name;if(null==i&&null!=n)return-1;if(null!=i&&null==n)return 1;if(null==i&&null==n)return 0;const r=this.i18nService.collator?this.i18nService.collator.compare(i,n):i.localeCompare(n);return 0!==r||e.type!==Pe.Login||t.type!==Pe.Login?r:(null!=e.login.username&&(i+=e.login.username),null!=t.login.username&&(n+=t.login.username),this.i18nService.collator?this.i18nService.collator.compare(i,n):i.localeCompare(n))}}softDelete(e){return zp(this,void 0,void 0,(function*(){const t=yield this.stateService.getEncryptedCiphers();if(null==t)return;const i=e=>{null!=t[e]&&(t[e].deletedDate=(new Date).toISOString())};"string"==typeof e?i(e):e.forEach(i),yield this.clearCache(),yield this.stateService.setEncryptedCiphers(t)}))}softDeleteWithServer(e,t=!1){return zp(this,void 0,void 0,(function*(){t?yield this.apiService.putDeleteCipherAdmin(e):yield this.apiService.putDeleteCipher(e),yield this.softDelete(e)}))}softDeleteManyWithServer(e,t=!1){return zp(this,void 0,void 0,(function*(){const i=new Cp(e);t?yield this.apiService.putDeleteManyCiphersAdmin(i):yield this.apiService.putDeleteManyCiphers(i),yield this.softDelete(e)}))}restore(e){return zp(this,void 0,void 0,(function*(){const t=yield this.stateService.getEncryptedCiphers();if(null==t)return;const i=e=>{null!=t[e.id]&&(t[e.id].deletedDate=null,t[e.id].revisionDate=e.revisionDate)};e.constructor.name===Array.name?e.forEach(i):i(e),yield this.clearCache(),yield this.stateService.setEncryptedCiphers(t)}))}restoreWithServer(e,t=!1){return zp(this,void 0,void 0,(function*(){let i;i=t?yield this.apiService.putRestoreCipherAdmin(e):yield this.apiService.putRestoreCipher(e),yield this.restore({id:e,revisionDate:i.revisionDate})}))}restoreManyWithServer(e,t=null,i=!1){return zp(this,void 0,void 0,(function*(){let n;if(i){const i=new Dp(e,t);n=yield this.apiService.putRestoreManyCiphersAdmin(i)}else{const t=new Dp(e);n=yield this.apiService.putRestoreManyCiphers(t)}const r=[];for(const e of n.data)r.push({id:e.id,revisionDate:e.revisionDate});yield this.restore(r)}))}getKeyForCipherKeyDecryption(e){return zp(this,void 0,void 0,(function*(){return(yield this.cryptoService.getOrgKey(e.organizationId))||(yield this.cryptoService.getUserKeyWithLegacySupport())}))}encryptSharedCipher(e){return zp(this,void 0,void 0,(function*(){const t=yield this.cryptoService.getUserKeyWithLegacySupport();return yield this.encrypt(e,null,t)}))}updateModelfromExistingCipher(e,t){return zp(this,void 0,void 0,(function*(){const i=yield t.decrypt(yield this.getKeyForCipherKeyDecryption(t));if(e.passwordHistory=i.passwordHistory||[],e.type===Pe.Login&&i.type===Pe.Login)if(null!=i.login.password&&""!==i.login.password&&i.login.password!==e.login.password){const t=new et;t.password=i.login.password,t.lastUsedDate=e.login.passwordRevisionDate=new Date,e.passwordHistory.splice(0,0,t)}else e.login.passwordRevisionDate=i.login.passwordRevisionDate;if(i.hasFields){const t=i.fields.filter((e=>e.type===ke.Hidden&&null!=e.name&&""!==e.name&&null!=e.value&&""!==e.value)),n=null==e.fields?[]:e.fields.filter((e=>e.type===ke.Hidden&&null!=e.name&&""!==e.name));t.forEach((t=>{const i=n.find((e=>e.name===t.name));if(null==i||i.value!==t.value){const i=new et;i.password=t.name+": "+t.value,i.lastUsedDate=new Date,e.passwordHistory.splice(0,0,i)}}))}}))}adjustPasswordHistoryLength(e){null!=e.passwordHistory&&0===e.passwordHistory.length?e.passwordHistory=null:null!=e.passwordHistory&&e.passwordHistory.length>5&&(e.passwordHistory=e.passwordHistory.slice(0,5))}shareAttachmentWithServer(e,t,i){return zp(this,void 0,void 0,(function*(){const n=yield this.apiService.nativeFetch(new Request(e.url,{cache:"no-store"}));if(200!==n.status)throw Error("Failed to download attachment: "+n.status.toString());const r=yield Hs.fromResponse(n),s=yield this.cryptoService.decryptFromBytes(r,null);let o;o=yield this.cryptoService.getOrgKey(i),o||(o=yield this.cryptoService.getUserKeyWithLegacySupport());const a=yield this.cryptoService.makeDataEncKey(o),l=yield this.encryptService.encrypt(e.fileName,o),c=yield this.encryptService.encryptToBytes(new Uint8Array(s),a[0]),d=new FormData;try{const e=new Blob([c.buffer],{type:"application/octet-stream"});d.append("key",a[1].encryptedString),d.append("data",e,l.encryptedString)}catch(e){if(!p.isNode||p.isBrowser)throw e;d.append("key",a[1].encryptedString),d.append("data",Buffer.from(c.buffer),{filepath:l.encryptedString,contentType:"application/octet-stream"})}try{yield this.apiService.postShareCipherAttachment(t,e.id,d,i)}catch(e){throw new Error(e.getSingleMessage())}}))}encryptObjProperty(e,t,i,n){return zp(this,void 0,void 0,(function*(){const r=[],s=this;for(const o in i)i.hasOwnProperty(o)&&function(t,o){const a=Promise.resolve().then((()=>{const r=e[i[t]||t];return r&&""!==r?s.cryptoService.encrypt(r,n):null})).then((e=>{o[t]=e}));r.push(a)}(o,t);yield Promise.all(r)}))}encryptCipherData(e,t,i){return zp(this,void 0,void 0,(function*(){switch(e.type){case Pe.Login:if(e.login=new bo,e.login.passwordRevisionDate=t.login.passwordRevisionDate,e.login.autofillOnPageLoad=t.login.autofillOnPageLoad,yield this.encryptObjProperty(t.login,e.login,{username:null,password:null,totp:null},i),null!=t.login.uris){e.login.uris=[],t.login.uris=t.login.uris.filter((e=>null!=e.uri));for(let n=0;nzp(this,void 0,void 0,(function*(){const t=new go;return yield this.encryptObjProperty(e,t,{credentialId:null,keyType:null,keyAlgorithm:null,keyCurve:null,keyValue:null,rpId:null,rpName:null,userHandle:null,userName:null,userDisplayName:null,origin:null},i),t.counter=yield this.cryptoService.encrypt(String(e.counter),i),t.discoverable=yield this.cryptoService.encrypt(String(e.discoverable),i),t.creationDate=e.creationDate,t})))))));case Pe.SecureNote:return e.secureNote=new ko,void(e.secureNote.type=t.secureNote.type);case Pe.Card:return e.card=new po,void(yield this.encryptObjProperty(t.card,e.card,{cardholderName:null,brand:null,number:null,expMonth:null,expYear:null,code:null},i));case Pe.Identity:return e.identity=new vo,void(yield this.encryptObjProperty(t.identity,e.identity,{title:null,firstName:null,middleName:null,lastName:null,address1:null,address2:null,address3:null,city:null,state:null,postalCode:null,country:null,company:null,email:null,phone:null,ssn:null,username:null,passportNumber:null,licenseNumber:null},i));default:throw new Error("Unknown cipher type.")}}))}getAutofillOnPageLoadDefault(){return zp(this,void 0,void 0,(function*(){return yield(0,r.z)(this.autofillSettingsService.autofillOnPageLoadDefault$)}))}getCipherForUrl(e,t,i,n){return zp(this,void 0,void 0,(function*(){const r=n?"autofillOnPageLoad-"+e:e;if(!this.sortedCiphersCache.isCached(r)){let t=yield this.getAllDecryptedForUrl(e);if(!t)return null;if(n){const e=yield this.getAutofillOnPageLoadDefault();if(t=t.filter((t=>t.login.autofillOnPageLoad||null==t.login.autofillOnPageLoad&&!1!==e)),0===t.length)return null}this.sortedCiphersCache.addCiphers(r,t)}return i?this.sortedCiphersCache.getLastLaunched(r):t?this.sortedCiphersCache.getLastUsed(r):this.sortedCiphersCache.getNext(r)}))}clearEncryptedCiphersState(e){return zp(this,void 0,void 0,(function*(){yield this.stateService.setEncryptedCiphers(null,{userId:e})}))}clearDecryptedCiphersState(e){return zp(this,void 0,void 0,(function*(){yield this.stateService.setDecryptedCiphers(null,{userId:e}),this.clearSortedCiphers()}))}clearSortedCiphers(){this.sortedCiphersCache.clear()}encryptCipher(e,t,i){return zp(this,void 0,void 0,(function*(){return yield Promise.all([this.encryptObjProperty(e,t,{name:null,notes:null},i),this.encryptCipherData(t,e,i),this.encryptFields(e.fields,i).then((e=>{t.fields=e})),this.encryptPasswordHistories(e.passwordHistory,i).then((e=>{t.passwordHistory=e})),this.encryptAttachments(e.attachments,i).then((e=>{t.attachments=e}))]),t}))}encryptCipherWithCipherKey(e,t,i,n){return zp(this,void 0,void 0,(function*(){let r;return r=null==t.key?yield this.cryptoService.makeCipherKey():new N(yield this.encryptService.decryptToBytes(t.key,n)),t.key=yield this.encryptService.encrypt(r.key,i),this.encryptCipher(e,t,r)}))}getCipherKeyEncryptionEnabled(){return zp(this,void 0,void 0,(function*(){return bp("enableCipherKeyEncryption")&&(yield(0,r.z)(this.configService.checkServerMeetsVersionRequirement$(Vp)))}))}}Kp([Pp((()=>"getAllDecrypted")),Lp("design:type",Function),Lp("design:paramtypes",[]),Lp("design:returntype",Promise)],Bp.prototype,"getAllDecrypted",null);class _p{constructor(e){this.id=e.id,this.organizationId=e.organizationId,this.name=e.name,this.externalId=e.externalId,this.readOnly=e.readOnly,this.manage=e.manage,this.hidePasswords=e.hidePasswords}static fromJSON(e){return Object.assign(new _p(new $d({})),e)}}class jp{constructor(e){this.id=null,this.organizationId=null,this.name=null,this.externalId=null,this.readOnly=null,this.hidePasswords=null,this.manage=null,this.assigned=null,e&&(this.id=e.id,this.organizationId=e.organizationId,this.externalId=e.externalId,e instanceof $p&&(this.readOnly=e.readOnly,this.hidePasswords=e.hidePasswords,this.manage=e.manage,this.assigned=!0),e instanceof Wd&&(this.assigned=e.assigned))}canEditItems(e,t){if(null!=e&&e.id!==this.organizationId)throw new Error("Id of the organization provided does not match the org id of the collection.");return(null==e?void 0:e.flexibleCollections)?(null==e?void 0:e.canEditAllCiphers(t))||this.manage||this.assigned&&!this.readOnly:(null==e?void 0:e.canEditAnyCollection)||(null==e?void 0:e.canEditAssignedCollections)&&this.assigned}canEdit(e){if(null!=e&&e.id!==this.organizationId)throw new Error("Id of the organization provided does not match the org id of the collection.");return(null==e?void 0:e.flexibleCollections)?(null==e?void 0:e.canEditAnyCollection)||this.manage:(null==e?void 0:e.canEditAnyCollection)||(null==e?void 0:e.canEditAssignedCollections)}canDelete(e){if(null!=e&&e.id!==this.organizationId)throw new Error("Id of the organization provided does not match the org id of the collection.");return(null==e?void 0:e.flexibleCollections)?(null==e?void 0:e.canDeleteAnyCollection)||!(null==e?void 0:e.limitCollectionCreationDeletion)&&this.manage:(null==e?void 0:e.canDeleteAnyCollection)||(null==e?void 0:e.canDeleteAssignedCollections)}static fromJSON(e){return Object.assign(new jp(new $p),e)}}class $p extends St{constructor(e){super(),null!=e&&this.buildDomainModel(this,e,{id:null,organizationId:null,name:null,externalId:null,readOnly:null,hidePasswords:null,manage:null},["id","organizationId","externalId","readOnly","hidePasswords","manage"])}decrypt(){return this.decryptObj(new jp(this),{name:null},this.organizationId)}}class Wp{constructor(e,t,i,n){this.children=[],this.parent=t,this.node=e,i&&(this.node.name=i),n&&(this.node.id=n)}}class qp{static nestedTraverse(e,t,i,n,r,s){if(i.length<=t)return;const o=t===i.length-1,a=i[t];for(let l=0;le.node.name===a)).length){if(o)return void e.push(new Wp(n,r,a));const l=a+s+i[t+1];qp.nestedTraverse(e,0,[l,...i.slice(t+2)],n,r,s)}}static getTreeNodeObject(e,t){if(e.node.id===t)return e;for(let i=0;i_p.fromJSON(e)}),Jp=Lt.from(Gp,{deserializer:e=>e.map((e=>jp.fromJSON(e))),derive:(e,{collectionService:t})=>Hp(void 0,void 0,void 0,(function*(){const i=[];for(const t in null!=e?e:{}){const n=t;i.push(new $p(e[n]))}return yield t.decryptMany(i)}))});class Yp{decryptedCollectionViews$(e){return this.decryptedCollections$.pipe((0,q.U)((t=>t.filter((t=>e.includes(t.id))))))}constructor(e,t,i){this.cryptoService=e,this.i18nService=t,this.stateProvider=i,this.encryptedCollectionDataState=this.stateProvider.getActive(Gp),this.encryptedCollections$=this.encryptedCollectionDataState.state$.pipe((0,q.U)((e=>{const t=[];for(const i in null!=e?e:{})t.push(new $p(e[i]));return t}))),this.decryptedCollectionDataState=this.stateProvider.getDerived(this.encryptedCollectionDataState.state$,Jp,{collectionService:this}),this.decryptedCollections$=this.decryptedCollectionDataState.state$}clearActiveUserCache(){return Hp(this,void 0,void 0,(function*(){yield this.decryptedCollectionDataState.forceValue(null)}))}encrypt(e){return Hp(this,void 0,void 0,(function*(){if(null==e.organizationId)throw new Error("Collection has no organization id.");const t=yield this.cryptoService.getOrgKey(e.organizationId);if(null==t)throw new Error("No key for this collection's organization.");const i=new $p;return i.id=e.id,i.organizationId=e.organizationId,i.readOnly=e.readOnly,i.name=yield this.cryptoService.encrypt(e.name,t),i}))}decryptMany(e){return Hp(this,void 0,void 0,(function*(){if(null==e)return[];const t=[],i=[];return e.forEach((e=>{i.push(e.decrypt().then((e=>t.push(e))))})),yield Promise.all(i),t.sort(p.getSortFunction(this.i18nService,"name"))}))}get(e){var t;return Hp(this,void 0,void 0,(function*(){return null!==(t=yield(0,r.z)(this.encryptedCollections$.pipe((0,q.U)((t=>t.find((t=>t.id===e)))))))&&void 0!==t?t:null}))}getAll(){return Hp(this,void 0,void 0,(function*(){return yield(0,r.z)(this.encryptedCollections$)}))}getAllDecrypted(){return Hp(this,void 0,void 0,(function*(){return yield(0,r.z)(this.decryptedCollections$)}))}getAllNested(e=null){return Hp(this,void 0,void 0,(function*(){null==e&&(e=yield this.getAllDecrypted());const t=[];return e.forEach((e=>{const i=new jp;i.id=e.id,i.organizationId=e.organizationId;const n=null!=e.name?e.name.replace(/^\/+|\/+$/g,"").split("/"):[];qp.nestedTraverse(t,0,n,i,null,"/")})),t}))}getNested(e){return Hp(this,void 0,void 0,(function*(){const t=yield this.getAllNested();return qp.getTreeNodeObjectFromList(t,e)}))}upsert(e){return Hp(this,void 0,void 0,(function*(){null!=e&&(yield this.encryptedCollectionDataState.update((t=>(null==t&&(t={}),Array.isArray(e)?e.forEach((e=>{t[e.id]=e})):t[e.id]=e,t))))}))}replace(e){return Hp(this,void 0,void 0,(function*(){yield this.encryptedCollectionDataState.update((()=>e))}))}clear(e){return Hp(this,void 0,void 0,(function*(){null==e?(yield this.encryptedCollectionDataState.update((()=>null)),yield this.decryptedCollectionDataState.forceValue(null)):yield this.stateProvider.getUser(e,Gp).update((()=>null))}))}delete(e){return Hp(this,void 0,void 0,(function*(){yield this.encryptedCollectionDataState.update((t=>(null==t&&(t={}),"string"==typeof e?delete t[e]:e.forEach((e=>{delete t[e]})),t)))}))}}var Qp,Xp;!function(e){e[e.ES256=-7]="ES256",e[e.RS256=-257]="RS256"}(Qp||(Qp={})),function(e){e.Unknown="UnknownError",e.NotSupported="NotSupportedError",e.InvalidState="InvalidStateError",e.NotAllowed="NotAllowedError",e.Constraint="ConstraintError"}(Xp||(Xp={}));class Zp extends Error{constructor(e){super(e),this.errorCode=e}}const ey=4294967296,ty=9007199254740992;class iy{constructor(e,t){this.value=e,this.tag=t}}const ny={decode:function(e,t,i){let n=new DataView(e),r=new Uint8Array(e),s=0,o=function(e,t){return new iy(e,t)},a=function(e){};function l(e,t){return s+=e,t}function c(t){return l(t,new Uint8Array(e,s,t))}function d(){return l(1,r[s])}function u(){return l(2,n.getUint16(s))}function h(){return l(4,n.getUint32(s))}function p(){return 255===r[s]&&(s+=1,!0)}function y(e){if(e<24)return e;if(24===e)return d();if(25===e)return u();if(26===e)return h();if(27===e)return h()*ey+h();if(31===e)return-1;throw new Error("Invalid length encoding")}function v(e){let t=d();if(255===t)return-1;let i=y(31&t);if(i<0||t>>5!==e)throw new Error("Invalid indefinite length element");return i}function f(e,t){for(let i=0;i>10),e.push(56320|1023&i))}}"function"==typeof t&&(o=t),"function"==typeof i&&(a=i);let g=function e(){let t,i,r=d(),h=r>>5,g=31&r;if(7===h)switch(g){case 25:return function(){let e=new ArrayBuffer(4),t=new DataView(e),i=u(),n=32768&i,r=31744&i,s=1023&i;if(31744===r)r=261120;else if(0!==r)r+=114688;else if(0!==s)return(n?-1:1)*s*5.960464477539063e-8;return t.setUint32(0,n<<16|r<<13|s<<13),t.getFloat32(0)}();case 26:return l(4,n.getFloat32(s));case 27:return l(8,n.getFloat64(s))}if(i=y(g),i<0&&(h<2||6=0;)n+=i,e.push(c(i));let r=new Uint8Array(n),s=0;for(t=0;t=0;)f(n,i);else f(n,i);let r="";for(t=0;t>2;for(let i=0;i>6),n.push(128|63&e)):e<55296||e>=57344?(n.push(224|e>>12),n.push(128|e>>6&63),n.push(128|63&e)):(e=(1023&e)<<10,e|=1023&t.charCodeAt(++i),e+=65536,n.push(240|e>>18),n.push(128|e>>12&63),n.push(128|e>>6&63),n.push(128|63&e))}return p(3,n.length),c(n);default:let r,y;if(Array.isArray(t))for(r=t.length,p(4,r),i=0;i(t+256).toString(16).substring(1)));function py(e){if(!vy(e))throw TypeError("GUID parameter is invalid");let t;const i=new Uint8Array(16);return i[0]=(t=parseInt(e.slice(0,8),16))>>>24,i[1]=t>>>16&255,i[2]=t>>>8&255,i[3]=255&t,i[4]=(t=parseInt(e.slice(9,13),16))>>>8,i[5]=255&t,i[6]=(t=parseInt(e.slice(14,18),16))>>>8,i[7]=255&t,i[8]=(t=parseInt(e.slice(19,23),16))>>>8,i[9]=255&t,i[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,i[11]=t/4294967296&255,i[12]=t>>>24&255,i[13]=t>>>16&255,i[14]=t>>>8&255,i[15]=255&t,i}function yy(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer),i=(hy[t[0]]+hy[t[1]]+hy[t[2]]+hy[t[3]]+"-"+hy[t[4]]+hy[t[5]]+"-"+hy[t[6]]+hy[t[7]]+"-"+hy[t[8]]+hy[t[9]]+"-"+hy[t[10]]+hy[t[11]]+hy[t[12]]+hy[t[13]]+hy[t[14]]+hy[t[15]]).toLowerCase();if(!vy(i))throw TypeError("Converted GUID is invalid");return i}function vy(e){return RegExp(/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,"i").test(e)}var fy=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const gy=new Uint8Array([213,72,130,110,121,180,219,64,163,216,17,17,111,126,131,73]),my=["sign"];class wy{constructor(e,t,i,n){this.cipherService=e,this.userInterface=t,this.syncService=i,this.logService=n}makeCredential(e,t,i){var n,r,s,o,a,l,c;return fy(this,void 0,void 0,(function*(){const d=yield this.userInterface.newSession(e.fallbackSupported,t,i);try{if(e.credTypesAndPubKeyAlgs.every((e=>e.alg!==Qp.ES256))){const t=e.credTypesAndPubKeyAlgs.map((e=>e.alg)).join(", ");throw null===(n=this.logService)||void 0===n||n.warning(`[Fido2Authenticator] No compatible algorithms found, RP requested: ${t}`),new Zp(Xp.NotSupported)}if(null!=e.requireResidentKey&&"boolean"!=typeof e.requireResidentKey)throw null===(r=this.logService)||void 0===r||r.error(`[Fido2Authenticator] Invalid 'requireResidentKey' value: ${String(e.requireResidentKey)}`),new Zp(Xp.Unknown);if(null!=e.requireUserVerification&&"boolean"!=typeof e.requireUserVerification)throw null===(s=this.logService)||void 0===s||s.error(`[Fido2Authenticator] Invalid 'requireUserVerification' value: ${String(e.requireUserVerification)}`),new Zp(Xp.Unknown);yield d.ensureUnlockedVault(),yield this.syncService.fullSync(!1);const t=yield this.findExcludedCredentials(e.excludeCredentialDescriptorList);if(t.length>0)throw null===(o=this.logService)||void 0===o||o.info("[Fido2Authenticator] Aborting due to excluded credential found in vault."),yield d.informExcludedCredential(t),new Zp(Xp.NotAllowed);let i,u,h,y,v,f=!1;const g=yield d.confirmNewCredential({credentialName:e.rpEntity.name,userName:e.userEntity.displayName,userVerification:e.requireUserVerification,rpId:e.rpEntity.id}),m=g.cipherId;if(f=g.userVerified,void 0===m)throw null===(a=this.logService)||void 0===a||a.warning("[Fido2Authenticator] Aborting because user confirmation was not recieved."),new Zp(Xp.NotAllowed);try{h=yield function(){return fy(this,void 0,void 0,(function*(){return yield crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,my)}))}(),v=yield crypto.subtle.exportKey("spki",h.publicKey);const t=yield this.cipherService.get(m);if(i=yield t.decrypt(yield this.cipherService.getKeyForCipherKeyDecryption(t)),!f&&(e.requireUserVerification||i.reprompt!==be.None))throw null===(l=this.logService)||void 0===l||l.warning("[Fido2Authenticator] Aborting because user verification was unsuccessful."),new Zp(Xp.NotAllowed);u=yield function(e,t){return fy(this,void 0,void 0,(function*(){if("ECDSA"!==t.algorithm.name&&"P-256"!==t.algorithm.namedCurve)throw new Zp(Xp.Unknown);const i=yield crypto.subtle.exportKey("pkcs8",t),n=new Be;return n.credentialId=p.newGuid(),n.keyType="public-key",n.keyAlgorithm="ECDSA",n.keyCurve="P-256",n.keyValue=uy.bufferToString(i),n.rpId=e.rpEntity.id,n.userHandle=uy.bufferToString(e.userEntity.id),n.userName=e.userEntity.name,n.counter=0,n.rpName=e.rpEntity.name,n.userDisplayName=e.userEntity.displayName,n.discoverable=e.requireResidentKey,n.creationDate=new Date,n}))}(e,h.privateKey),i.login.fido2Credentials=[u];const n=yield this.cipherService.encrypt(i);yield this.cipherService.updateWithServer(n),y=u.credentialId}catch(e){throw null===(c=this.logService)||void 0===c||c.error(`[Fido2Authenticator] Aborting because of unknown error when creating credential: ${e}`),new Zp(Xp.Unknown)}const w=yield by({rpId:e.rpEntity.id,credentialId:py(y),counter:u.counter,userPresence:!0,userVerification:f,keyPair:h}),S=new Uint8Array(ny.encode({fmt:"none",attStmt:{},authData:w}));return{credentialId:py(y),attestationObject:S,authData:w,publicKey:v,publicKeyAlgorithm:-7}}finally{d.close()}}))}getAssertion(e,t,i){var n,r,s,o,a,l;return fy(this,void 0,void 0,(function*(){const c=yield this.userInterface.newSession(e.fallbackSupported,t,i);try{if(null!=e.requireUserVerification&&"boolean"!=typeof e.requireUserVerification)throw null===(n=this.logService)||void 0===n||n.error(`[Fido2Authenticator] Invalid 'requireUserVerification' value: ${String(e.requireUserVerification)}`),new Zp(Xp.Unknown);let t;if(yield c.ensureUnlockedVault(),yield this.syncService.fullSync(!1),t=(null===(r=e.allowCredentialDescriptorList)||void 0===r?void 0:r.length)>0?yield this.findCredentialsById(e.allowCredentialDescriptorList,e.rpId):yield this.findCredentialsByRp(e.rpId),0===t.length)throw null===(s=this.logService)||void 0===s||s.info("[Fido2Authenticator] Aborting because no matching credentials were found in the vault."),yield c.informCredentialNotFound(),new Zp(Xp.NotAllowed);const i=yield c.pickCredential({cipherIds:t.map((e=>e.id)),userVerification:e.requireUserVerification}),d=i.cipherId,u=i.userVerified,h=t.find((e=>e.id===d));if(void 0===h)throw null===(o=this.logService)||void 0===o||o.error("[Fido2Authenticator] Aborting because the selected credential could not be found."),new Zp(Xp.NotAllowed);if(!u&&(e.requireUserVerification||h.reprompt!==be.None))throw null===(a=this.logService)||void 0===a||a.warning("[Fido2Authenticator] Aborting because user verification was unsuccessful."),new Zp(Xp.NotAllowed);try{const t=h.login.fido2Credentials[0],i=t.credentialId;if(t.counter>0&&++t.counter,h.localData=Object.assign(Object.assign({},h.localData),{lastUsedDate:(new Date).getTime()}),t.counter>0){const e=yield this.cipherService.encrypt(h);yield this.cipherService.updateWithServer(e)}const n=yield by({rpId:t.rpId,credentialId:py(i),counter:t.counter,userPresence:!0,userVerification:u}),r=yield function(e){return fy(this,void 0,void 0,(function*(){const t=new Uint8Array([...e.authData,...uy.bufferSourceToUint8Array(e.clientDataHash)]);return dy(new Uint8Array(yield crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e.privateKey,t)))}))}({authData:n,clientDataHash:e.hash,privateKey:yield Sy(t)});return{authenticatorData:n,selectedCredential:{id:py(i),userHandle:uy.stringToBuffer(t.userHandle)},signature:r}}catch(e){throw null===(l=this.logService)||void 0===l||l.error(`[Fido2Authenticator] Aborting because of unknown error when asserting credential: ${e}`),new Zp(Xp.Unknown)}}finally{c.close()}}))}findExcludedCredentials(e){return fy(this,void 0,void 0,(function*(){const t=[];for(const i of e)try{t.push(yy(i.id))}catch(e){}if(0===t.length)return[];return(yield this.cipherService.getAllDecrypted()).filter((e=>!e.isDeleted&&null==e.organizationId&&e.type===Pe.Login&&e.login.hasFido2Credentials&&t.includes(e.login.fido2Credentials[0].credentialId))).map((e=>e.id))}))}findCredentialsById(e,t){return fy(this,void 0,void 0,(function*(){const i=[];for(const t of e)try{i.push(yy(t.id))}catch(e){}if(0===i.length)return[];return(yield this.cipherService.getAllDecrypted()).filter((e=>!e.isDeleted&&e.type===Pe.Login&&e.login.hasFido2Credentials&&e.login.fido2Credentials[0].rpId===t&&i.includes(e.login.fido2Credentials[0].credentialId)))}))}findCredentialsByRp(e){return fy(this,void 0,void 0,(function*(){return(yield this.cipherService.getAllDecrypted()).filter((t=>!t.isDeleted&&t.type===Pe.Login&&t.login.hasFido2Credentials&&t.login.fido2Credentials[0].rpId===e&&t.login.fido2Credentials[0].discoverable))}))}}function Sy(e){return fy(this,void 0,void 0,(function*(){const t=uy.stringToBuffer(e.keyValue);return yield crypto.subtle.importKey("pkcs8",t,{name:e.keyAlgorithm,namedCurve:e.keyCurve},!0,my)}))}function by(e){return fy(this,void 0,void 0,(function*(){const t=[],i=new Uint8Array(yield crypto.subtle.digest({name:"SHA-256"},p.fromByteStringToArray(e.rpId)));t.push(...i);const n=function(e){let t=0;e.extensionData&&(t|=64);e.attestationData&&(t|=64);e.backupEligibility&&(t|=8);e.backupState&&(t|=16);e.userVerification&&(t|=4);e.userPresence&&(t|=1);return t}({extensionData:!1,attestationData:null!=e.keyPair,backupEligibility:!0,backupState:!0,userVerification:e.userVerification,userPresence:e.userPresence});t.push(n);const r=e.counter;if(t.push((4278190080&r)>>24&255,(16711680&r)>>16&255,(65280&r)>>8&255,255&r),e.keyPair){const i=[];i.push(...gy);const n=uy.bufferSourceToUint8Array(e.credentialId),r=[(n.length-(255&n.length))/256,255&n.length];i.push(...r),i.push(...n);const s=yield crypto.subtle.exportKey("jwk",e.keyPair.publicKey),o=p.fromUrlB64ToArray(s.x),a=p.fromUrlB64ToArray(s.y),l=new Uint8Array(77);l.set([165,1,2,3,38,32,1,33,88,32],0),l.set(o,10),l.set([34,88,32],42),l.set(a,45),i.push(...l),t.push(...i)}return new Uint8Array(t)}))}const Py="UserRequestedFallback";class ky extends Error{constructor(){super("FallbackRequested"),this.fallbackRequested=!0}}function Oy(e,t){const i=(0,d.Qc)(t,{allowPrivateDomains:!0}),n=(0,d.Qc)(e,{allowPrivateDomains:!0});return null==i.domain&&i.hostname==n.hostname&&"localhost"==i.hostname||null!=i.domain&&i.domain==n.domain&&i.subdomain.endsWith(n.subdomain)}var Cy=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Ay{constructor(e,t,i,n,r,s){this.authenticator=e,this.configService=t,this.authService=i,this.vaultSettingsService=n,this.domainSettingsService=r,this.logService=s}isFido2FeatureEnabled(e,t){var i;return Cy(this,void 0,void 0,(function*(){const n=yield(0,r.z)(this.vaultSettingsService.enablePasskeys$),s=(yield this.authService.getAuthStatus())!==On.LoggedOut,o=yield(0,r.z)(this.domainSettingsService.neverDomains$),a=null!=o&&e in o,l=yield(0,r.z)(this.configService.serverConfig$),c=t===(null===(i=l.environment)||void 0===i?void 0:i.vault);return n&&s&&!a&&!c}))}createCredential(e,t,i=new AbortController){var n,r,s,o,a,l,c,u,h,y,v,f,g,m,w;return Cy(this,void 0,void 0,(function*(){const S=(0,d.Qc)(e.origin,{allowPrivateDomains:!0});if(!(yield this.isFido2FeatureEnabled(S.hostname,e.origin)))throw null===(n=this.logService)||void 0===n||n.warning("[Fido2Client] Fido2VaultCredential is not enabled"),new ky;if(!e.sameOriginWithAncestors)throw null===(r=this.logService)||void 0===r||r.warning(`[Fido2Client] Invalid 'sameOriginWithAncestors' value: ${e.sameOriginWithAncestors}`),new DOMException("Invalid 'sameOriginWithAncestors' value","NotAllowedError");const b=uy.stringToBuffer(e.user.id);if(b.length<1||b.length>64)throw null===(s=this.logService)||void 0===s||s.warning(`[Fido2Client] Invalid 'user.id' length: ${e.user.id} (${b.length})`),new TypeError("Invalid 'user.id' length");if(e.rp.id=null!==(o=e.rp.id)&&void 0!==o?o:S.hostname,null==S.hostname||!e.origin.startsWith("https://"))throw null===(a=this.logService)||void 0===a||a.warning(`[Fido2Client] Invalid https origin: ${e.origin}`),new DOMException("'origin' is not a valid https origin","SecurityError");if(!Oy(e.rp.id,e.origin))throw null===(l=this.logService)||void 0===l||l.warning(`[Fido2Client] 'rp.id' cannot be used with the current origin: rp.id = ${e.rp.id}; origin = ${e.origin}`),new DOMException("'rp.id' cannot be used with the current origin","SecurityError");let P;if(P=(null===(c=e.pubKeyCredParams)||void 0===c?void 0:c.length)>0?e.pubKeyCredParams.filter((e=>-7===e.alg&&"public-key"===e.type)):[{alg:-7,type:"public-key"},{alg:-257,type:"public-key"}],0===P.length){const e=P.map((e=>e.alg)).join(", ");throw null===(u=this.logService)||void 0===u||u.warning(`[Fido2Client] No compatible algorithms found, RP requested: ${e}`),new DOMException("No supported key algorithms were found","NotSupportedError")}const k={type:"webauthn.create",challenge:e.challenge,origin:e.origin,crossOrigin:!e.sameOriginWithAncestors},O=JSON.stringify(k),C=p.fromByteStringToArray(O),A=yield crypto.subtle.digest({name:"SHA-256"},C),D=function({params:e,credTypesAndPubKeyAlgs:t,clientDataHash:i}){var n,r,s,o,a,l,c,d,u;const h=null!==(r=null===(n=e.excludeCredentials)||void 0===n?void 0:n.map((e=>({id:uy.stringToBuffer(e.id),transports:e.transports,type:e.type}))))&&void 0!==r?r:[],p="required"===(null===(s=e.authenticatorSelection)||void 0===s?void 0:s.residentKey)||"preferred"===(null===(o=e.authenticatorSelection)||void 0===o?void 0:o.residentKey)||void 0===(null===(a=e.authenticatorSelection)||void 0===a?void 0:a.residentKey)&&!0===(null===(l=e.authenticatorSelection)||void 0===l?void 0:l.requireResidentKey),y="required"===(null===(c=e.authenticatorSelection)||void 0===c?void 0:c.userVerification)||"preferred"===(null===(d=e.authenticatorSelection)||void 0===d?void 0:d.userVerification)||void 0===(null===(u=e.authenticatorSelection)||void 0===u?void 0:u.userVerification);return{requireResidentKey:p,requireUserVerification:y,enterpriseAttestationPossible:"enterprise"===e.attestation,excludeCredentialDescriptorList:h,credTypesAndPubKeyAlgs:t,hash:i,rpEntity:{id:e.rp.id,name:e.rp.name},userEntity:{id:uy.stringToBuffer(e.user.id),displayName:e.user.displayName,name:e.user.name},fallbackSupported:e.fallbackSupported}}({params:e,credTypesAndPubKeyAlgs:P,clientDataHash:A});if(i.signal.aborted)throw null===(h=this.logService)||void 0===h||h.info("[Fido2Client] Aborted with AbortController"),new DOMException("The operation either timed out or was not allowed.","AbortError");const x=xy(i,null===(y=e.authenticatorSelection)||void 0===y?void 0:y.userVerification,e.timeout);let I,U;try{I=yield this.authenticator.makeCredential(D,t,i)}catch(e){if(i.signal.aborted&&i.signal.reason===Py)throw null===(v=this.logService)||void 0===v||v.info("[Fido2Client] Aborting because user requested fallback"),new ky;if(e instanceof Zp&&e.errorCode===Xp.InvalidState)throw null===(f=this.logService)||void 0===f||f.warning(`[Fido2Client] Unknown error: ${e}`),new DOMException("Unknown error occured.","InvalidStateError");throw null===(g=this.logService)||void 0===g||g.info(`[Fido2Client] Aborted by user: ${e}`),new DOMException("The operation either timed out or was not allowed.","NotAllowedError")}if(i.signal.aborted)throw null===(m=this.logService)||void 0===m||m.info("[Fido2Client] Aborted with AbortController"),new DOMException("The operation either timed out or was not allowed.","AbortError");return(null===(w=e.extensions)||void 0===w?void 0:w.credProps)&&(U={rk:D.requireResidentKey}),clearTimeout(x),{credentialId:uy.bufferToString(I.credentialId),attestationObject:uy.bufferToString(I.attestationObject),authData:uy.bufferToString(I.authData),clientDataJSON:uy.bufferToString(C),publicKey:uy.bufferToString(I.publicKey),publicKeyAlgorithm:I.publicKeyAlgorithm,transports:"google.com"===e.rp.id?["internal","usb"]:["internal"],extensions:{credProps:U}}}))}assertCredential(e,t,i=new AbortController){var n,r,s,o,a,l,c,u,h;return Cy(this,void 0,void 0,(function*(){const y=(0,d.Qc)(e.origin,{allowPrivateDomains:!0});if(!(yield this.isFido2FeatureEnabled(y.hostname,e.origin)))throw null===(n=this.logService)||void 0===n||n.warning("[Fido2Client] Fido2VaultCredential is not enabled"),new ky;if(e.rpId=null!==(r=e.rpId)&&void 0!==r?r:y.hostname,null==y.hostname||!e.origin.startsWith("https://"))throw null===(s=this.logService)||void 0===s||s.warning(`[Fido2Client] Invalid https origin: ${e.origin}`),new DOMException("'origin' is not a valid https origin","SecurityError");if(!Oy(e.rpId,e.origin))throw null===(o=this.logService)||void 0===o||o.warning(`[Fido2Client] 'rp.id' cannot be used with the current origin: rp.id = ${e.rpId}; origin = ${e.origin}`),new DOMException("'rp.id' cannot be used with the current origin","SecurityError");const v={type:"webauthn.get",challenge:e.challenge,origin:e.origin,crossOrigin:!e.sameOriginWithAncestors},f=JSON.stringify(v),g=p.fromByteStringToArray(f),m=yield crypto.subtle.digest({name:"SHA-256"},g),w=function({params:e,clientDataHash:t}){const i=e.allowedCredentialIds.map((e=>({id:uy.stringToBuffer(e),type:"public-key"}))),n="required"===e.userVerification||"preferred"===e.userVerification||void 0===e.userVerification;return{rpId:e.rpId,requireUserVerification:n,hash:t,allowCredentialDescriptorList:i,extensions:{},fallbackSupported:e.fallbackSupported}}({params:e,clientDataHash:m});if(i.signal.aborted)throw null===(a=this.logService)||void 0===a||a.info("[Fido2Client] Aborted with AbortController"),new DOMException("The operation either timed out or was not allowed.","AbortError");const S=xy(i,e.userVerification,e.timeout);let b;try{b=yield this.authenticator.getAssertion(w,t,i)}catch(e){if(i.signal.aborted&&i.signal.reason===Py)throw null===(l=this.logService)||void 0===l||l.info("[Fido2Client] Aborting because user requested fallback"),new ky;if(e instanceof Zp&&e.errorCode===Xp.InvalidState)throw null===(c=this.logService)||void 0===c||c.warning(`[Fido2Client] Unknown error: ${e}`),new DOMException("Unknown error occured.","InvalidStateError");throw null===(u=this.logService)||void 0===u||u.info(`[Fido2Client] Aborted by user: ${e}`),new DOMException("The operation either timed out or was not allowed.","NotAllowedError")}if(i.signal.aborted)throw null===(h=this.logService)||void 0===h||h.info("[Fido2Client] Aborted with AbortController"),new DOMException("The operation either timed out or was not allowed.","AbortError");return clearTimeout(S),{authenticatorData:uy.bufferToString(b.authenticatorData),clientDataJSON:uy.bufferToString(g),credentialId:uy.bufferToString(b.selectedCredential.id),userHandle:void 0!==b.selectedCredential.userHandle?uy.bufferToString(b.selectedCredential.userHandle):void 0,signature:uy.bufferToString(b.signature)}}))}}const Dy={NO_VERIFICATION:{DEFAULT:12e4,MIN:3e4,MAX:18e4},WITH_VERIFICATION:{DEFAULT:3e5,MIN:3e4,MAX:6e5}};function xy(e,t,i){let n;return"required"===t?(i=null!=i?i:Dy.WITH_VERIFICATION.DEFAULT,n=Math.max(Dy.WITH_VERIFICATION.MIN,Math.min(i,Dy.WITH_VERIFICATION.MAX))):(i=null!=i?i:Dy.NO_VERIFICATION.DEFAULT,n=Math.max(Dy.NO_VERIFICATION.MIN,Math.min(i,Dy.NO_VERIFICATION.MAX))),window.setTimeout((()=>e.abort()),n)}var Iy=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Uy{constructor(e,t){this.apiService=e,this.fileUploadService=t}upload(e,t,i,n,r){return Iy(this,void 0,void 0,(function*(){const s={key:r[1].encryptedString,fileName:t.encryptedString,fileSize:i.buffer.byteLength,adminRequest:n};let o;try{const r=yield this.apiService.postCipherAttachment(e.id,s);o=n?r.cipherMiniResponse:r.cipherResponse,yield this.fileUploadService.upload(r,t,i,this.generateMethods(r,o,s.adminRequest))}catch(n){if(!(n instanceof Y&&404===n.statusCode||405===n.statusCode))throw n instanceof Y?new Error(n.getSingleMessage()):n;o=yield this.legacyServerAttachmentFileUpload(s.adminRequest,e.id,t,i,r[1])}return o}))}generateMethods(e,t,i){return{postDirect:this.generatePostDirectCallback(e,i),renewFileUploadUrl:this.generateRenewFileUploadUrlCallback(e,t,i),rollback:this.generateRollbackCallback(t,e,i)}}generatePostDirectCallback(e,t){return i=>{const n=t?e.cipherMiniResponse:e.cipherResponse;return this.apiService.postAttachmentFile(n.id,e.attachmentId,i)}}generateRenewFileUploadUrlCallback(e,t,i){return()=>Iy(this,void 0,void 0,(function*(){const i=yield this.apiService.renewAttachmentUploadUrl(t.id,e.attachmentId);return null==i?void 0:i.url}))}generateRollbackCallback(e,t,i){return()=>i?this.apiService.deleteCipherAttachmentAdmin(e.id,t.attachmentId):this.apiService.deleteCipherAttachment(e.id,t.attachmentId)}legacyServerAttachmentFileUpload(e,t,i,n,r){return Iy(this,void 0,void 0,(function*(){const s=new FormData;try{const e=new Blob([n.buffer],{type:"application/octet-stream"});s.append("key",r.encryptedString),s.append("data",e,i.encryptedString)}catch(e){if(!p.isNode||p.isBrowser)throw e;s.append("key",r.encryptedString),s.append("data",Buffer.from(n.buffer),{filepath:i.encryptedString,contentType:"application/octet-stream"})}let o;try{o=e?yield this.apiService.postCipherAttachmentAdminLegacy(t,s):yield this.apiService.postCipherAttachmentLegacy(t,s)}catch(e){throw new Error(e.getSingleMessage())}return o}))}}class Ty{constructor(e){this.name=null==e?void 0:e.name,this.id=null==e?void 0:e.id,this.revisionDate=null==e?void 0:e.revisionDate}static fromJSON(e){return Object.assign(new Ty({}),e)}}class Ny{constructor(e){this.name=e.name?e.name.encryptedString:null}}var Ry=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Ey{constructor(e,t){this.folderService=e,this.apiService=t}save(e){return Ry(this,void 0,void 0,(function*(){const t=new Ny(e);let i;null==e.id?(i=yield this.postFolder(t),e.id=i.id):i=yield this.putFolder(e.id,t);const n=new Ty(i);yield this.folderService.upsert(n)}))}delete(e){return Ry(this,void 0,void 0,(function*(){yield this.deleteFolder(e),yield this.folderService.delete(e)}))}get(e){return Ry(this,void 0,void 0,(function*(){const t=yield this.apiService.send("GET","/folders/"+e,null,!0,!0);return new Gu(t)}))}postFolder(e){return Ry(this,void 0,void 0,(function*(){const t=yield this.apiService.send("POST","/folders",e,!0,!0);return new Gu(t)}))}putFolder(e,t){return Ry(this,void 0,void 0,(function*(){const i=yield this.apiService.send("PUT","/folders/"+e,t,!0,!0);return new Gu(i)}))}deleteFolder(e){return this.apiService.send("DELETE","/folders/"+e,null,!0,!1)}}class Fy{constructor(e){this.id=null,this.name=null,this.revisionDate=null,e&&(this.id=e.id,this.revisionDate=e.revisionDate)}static fromJSON(e){const t=null==e.revisionDate?null:new Date(e.revisionDate);return Object.assign(new Fy,e,{revisionDate:t})}}class My extends St{constructor(e){super(),null!=e&&(this.buildDomainModel(this,e,{id:null,name:null},["id"]),this.revisionDate=null!=e.revisionDate?new Date(e.revisionDate):null)}decrypt(){return this.decryptObj(new Fy(this),{name:null},null)}static fromJSON(e){const t=null==e.revisionDate?null:new Date(e.revisionDate);return Object.assign(new My,e,{name:z.fromJSON(e.name),revisionDate:t})}}var Ky=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Ly=jt.record(ki,"folders",{deserializer:e=>Ty.fromJSON(e)}),zy=Lt.from(Ly,{deserializer:e=>e.map((e=>Fy.fromJSON(e))),derive:(e,{folderService:t,cryptoService:i})=>Ky(void 0,void 0,void 0,(function*(){const n=Object.values(e||{}).map((e=>new My(e)));return(yield i.hasUserKey())?yield t.decryptFolders(n):[]}))});var Vy=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class By{constructor(e,t,i,n,r){this.cryptoService=e,this.i18nService=t,this.cipherService=i,this.stateService=n,this.stateProvider=r,this.encryptedFoldersState=this.stateProvider.getActive(Ly),this.decryptedFoldersState=this.stateProvider.getDerived(this.encryptedFoldersState.state$,zy,{folderService:this,cryptoService:this.cryptoService}),this.folders$=this.encryptedFoldersState.state$.pipe((0,q.U)((e=>Object.values(e).map((e=>new My(e)))))),this.folderViews$=this.decryptedFoldersState.state$}clearCache(){return Vy(this,void 0,void 0,(function*(){yield this.decryptedFoldersState.forceValue([])}))}encrypt(e,t){return Vy(this,void 0,void 0,(function*(){const i=new My;return i.id=e.id,i.name=yield this.cryptoService.encrypt(e.name,t),i}))}get(e){return Vy(this,void 0,void 0,(function*(){return(yield(0,r.z)(this.folders$)).find((t=>t.id===e))}))}getAllFromState(){return Vy(this,void 0,void 0,(function*(){return yield(0,r.z)(this.folders$)}))}getFromState(e){return Vy(this,void 0,void 0,(function*(){const t=yield this.get(e);return t||null}))}getAllDecryptedFromState(){return Vy(this,void 0,void 0,(function*(){return yield(0,r.z)(this.folderViews$)}))}upsert(e){return Vy(this,void 0,void 0,(function*(){yield this.encryptedFoldersState.update((t=>{if(null==t&&(t={}),e instanceof Ty){const i=e;t[i.id]=i}else e.forEach((e=>{t[e.id]=e}));return t}))}))}replace(e){return Vy(this,void 0,void 0,(function*(){e&&(yield this.encryptedFoldersState.update((()=>Object.assign({},e))))}))}clear(e){return Vy(this,void 0,void 0,(function*(){null==e?(yield this.encryptedFoldersState.update((()=>({}))),yield this.decryptedFoldersState.forceValue([])):yield this.stateProvider.getUser(e,Ly).update((()=>({})))}))}delete(e){return Vy(this,void 0,void 0,(function*(){yield this.encryptedFoldersState.update((t=>{if(null!=t){if("string"==typeof e){if(null==t[e])return;delete t[e]}else e.forEach((e=>{delete t[e]}));return t}}));const t=yield this.stateService.getEncryptedCiphers();if(null!=t){const i=[];for(const n in t)t[n].folderId===e&&(t[n].folderId=null,i.push(t[n]));i.length>0&&this.cipherService.upsert(i)}}))}decryptFolders(e){return Vy(this,void 0,void 0,(function*(){const t=e.map((e=>e.decrypt())),i=yield Promise.all(t);i.sort(p.getSortFunction(this.i18nService,"name"));const n=new Fy;return n.name=this.i18nService.t("noneFolder"),i.push(n),i}))}}class _y{constructor(){this._sync=new Cn.x,this.sync$=this._sync.asObservable()}next(e){this._sync.next(e)}}class jy{constructor(e){this.id=e.id,this.name=e.name,this.status=e.status,this.type=e.type,this.enabled=e.enabled,this.userId=e.userId,this.useEvents=e.useEvents}}var $y=function(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},Wy=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},qy=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Hy{constructor(e,t,i,n,r,s,o,a,l,c,d,u,h,p,y,v,f,g,m,w){this.apiService=e,this.domainSettingsService=t,this.folderService=i,this.cipherService=n,this.cryptoService=r,this.collectionService=s,this.messagingService=o,this.policyService=a,this.sendService=l,this.logService=c,this.keyConnectorService=d,this.stateService=u,this.providerService=h,this.folderApiService=p,this.organizationService=y,this.sendApiService=v,this.userDecryptionOptionsService=f,this.avatarService=g,this.logoutCallback=m,this.billingAccountProfileStateService=w,this.syncInProgress=!1}getLastSync(){return qy(this,void 0,void 0,(function*(){if(null==(yield this.stateService.getUserId()))return null;const e=yield this.stateService.getLastSync();return e?new Date(e):null}))}setLastSync(e,t){return qy(this,void 0,void 0,(function*(){yield this.stateService.setLastSync(e.toJSON(),{userId:t})}))}fullSync(e,t=!1){return qy(this,void 0,void 0,(function*(){this.syncStarted();if(!(yield this.stateService.getIsAuthenticated()))return this.syncCompleted(!1);const i=new Date;let n=!1;try{n=yield this.needsSyncing(e)}catch(e){if(t)throw e}if(!n)return yield this.setLastSync(i),this.syncCompleted(!1);try{yield this.apiService.refreshIdentityToken();const e=yield this.apiService.getSync();return yield this.syncProfile(e.profile),yield this.syncFolders(e.folders),yield this.syncCollections(e.collections),yield this.syncCiphers(e.ciphers),yield this.syncSends(e.sends),yield this.syncSettings(e.domains),yield this.syncPolicies(e.policies),yield this.setLastSync(i),this.syncCompleted(!0)}catch(e){if(t)throw e;return this.syncCompleted(!1)}}))}syncUpsertFolder(e,t){return qy(this,void 0,void 0,(function*(){if(this.syncStarted(),yield this.stateService.getIsAuthenticated())try{const i=yield this.folderService.get(e.id);if(!t&&null==i||t&&null!=i&&i.revisionDate=e.revisionDate&&(i=!1);let r=!1;if(i&&(t?(i=null!=n,r=!0):null==e.collectionIds||null==e.organizationId?i=null==n:(i=!1,r=!0)),!i&&r&&null!=e.organizationId&&null!=e.collectionIds&&e.collectionIds.length>0){const t=yield this.collectionService.getAll();if(null!=t)for(let n=0;n-1){i=!0;break}}if(i){const t=yield this.apiService.getFullCipherDetails(e.id);if(null!=t)return yield this.cipherService.upsert(new co(t)),this.messagingService.send("syncedUpsertedCipher",{cipherId:e.id}),this.syncCompleted(!0)}}catch(i){if(null!=i&&404===i.statusCode&&t)return yield this.cipherService.delete(e.id),this.messagingService.send("syncedDeletedCipher",{cipherId:e.id}),this.syncCompleted(!0)}return this.syncCompleted(!1)}))}syncDeleteCipher(e){return qy(this,void 0,void 0,(function*(){return this.syncStarted(),(yield this.stateService.getIsAuthenticated())?(yield this.cipherService.delete(e.id),this.messagingService.send("syncedDeletedCipher",{cipherId:e.id}),this.syncCompleted(!0)):this.syncCompleted(!1)}))}syncUpsertSend(e,t){return qy(this,void 0,void 0,(function*(){if(this.syncStarted(),yield this.stateService.getIsAuthenticated())try{const i=this.sendService.get(e.id);if(!t&&null==i||t&&null!=i&&i.revisionDate{i[e.id]=new jy(e)})),yield this.providerService.save(i),yield this.syncProfileOrganizations(e),(yield this.keyConnectorService.userNeedsMigration())?(yield this.keyConnectorService.setConvertAccountRequired(!0),this.messagingService.send("convertAccountToKeyConnector")):this.keyConnectorService.removeConvertAccountRequired()}))}setForceSetPasswordReasonIfNeeded(e){return qy(this,void 0,void 0,(function*(){e.forcePasswordReset&&(yield this.stateService.setForceSetPasswordReason(X.AdminForcePasswordReset));const t=yield(0,r.z)(this.userDecryptionOptionsService.userDecryptionOptions$);null==t&&this.logService.error("Sync: Account decryption options are null or undefined.");let i=!1;for(const t of e.organizations){const e=t.type===Wi.Admin,n=t.type===Wi.Owner;if(e||n||t.permissions&&t.permissions.manageResetPassword){i=!0;break}}void 0!==t.trustedDeviceOption&&!t.hasMasterPassword&&i&&(yield this.stateService.setForceSetPasswordReason(X.TdeUserWithoutPasswordHasPasswordResetPermission))}))}syncProfileOrganizations(e){return qy(this,void 0,void 0,(function*(){const t={};e.organizations.forEach((e=>{t[e.id]=new Zi(e,{isMember:!0,isProviderUser:!1})})),e.providerOrganizations.forEach((e=>{null==t[e.id]?t[e.id]=new Zi(e,{isMember:!1,isProviderUser:!0}):t[e.id].isProviderUser=!0})),yield this.organizationService.replace(t)}))}syncFolders(e){return qy(this,void 0,void 0,(function*(){const t={};return e.forEach((e=>{t[e.id]=new Ty(e)})),yield this.folderService.replace(t)}))}syncCollections(e){return qy(this,void 0,void 0,(function*(){const t={};return e.forEach((e=>{t[e.id]=new _p(e)})),yield this.collectionService.replace(t)}))}syncCiphers(e){return qy(this,void 0,void 0,(function*(){const t={};return e.forEach((e=>{t[e.id]=new co(e)})),yield this.cipherService.replace(t)}))}syncSends(e){return qy(this,void 0,void 0,(function*(){const t={};return e.forEach((e=>{t[e.id]=new hp(e)})),yield this.sendService.replace(t)}))}syncSettings(e){return qy(this,void 0,void 0,(function*(){let t=[];return null!=e&&null!=e.equivalentDomains&&(t=t.concat(e.equivalentDomains)),null!=e&&null!=e.globalEquivalentDomains&&e.globalEquivalentDomains.forEach((e=>{e.domains.length>0&&t.push(e.domains)})),this.domainSettingsService.setEquivalentDomains(t)}))}syncPolicies(e){return qy(this,void 0,void 0,(function*(){const t={};return null!=e&&e.forEach((e=>{t[e.id]=new ln(e)})),yield this.policyService.replace(t)}))}}$y([Pp((()=>"fullSync")),Wy("design:type",Function),Wy("design:paramtypes",[Boolean,Object]),Wy("design:returntype",Promise)],Hy.prototype,"fullSync",null);var Gy=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Jy="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",Yy="23456789BCDFGHJKMNPQRTVWXY";class Qy{constructor(e,t){this.cryptoFunctionService=e,this.logService=t}getCode(e){return Gy(this,void 0,void 0,(function*(){if(null==e)return null;let t=30,i="sha1",n=6,r=e;const s=0===e.toLowerCase().indexOf("otpauth://"),o=!s&&0===e.toLowerCase().indexOf("steam://");if(s){const s=p.getQueryParams(e);if(s.has("digits")&&null!=s.get("digits"))try{const e=parseInt(s.get("digits").trim(),null);e>10?n=10:e>0&&(n=e)}catch(e){this.logService.error("Invalid digits param.")}if(s.has("period")&&null!=s.get("period"))try{const e=parseInt(s.get("period").trim(),null);e>0&&(t=e)}catch(e){this.logService.error("Invalid period param.")}if(s.has("secret")&&null!=s.get("secret")&&(r=s.get("secret")),s.has("algorithm")&&null!=s.get("algorithm")){const e=s.get("algorithm").toLowerCase();"sha1"!==e&&"sha256"!==e&&"sha512"!==e||(i=e)}}else o&&(r=e.substr(8),n=5);const a=Math.round((new Date).getTime()/1e3),l=this.leftPad(this.decToHex(Math.floor(a/t)),16,"0"),c=p.fromHexToArray(l),d=this.b32ToBytes(r);if(!d.length||!c.length)return null;const u=yield this.sign(d,c,i);if(0===u.length)return null;const h=15&u[u.length-1],y=(127&u[h])<<24|(255&u[h+1])<<16|(255&u[h+2])<<8|255&u[h+3];let v="";if(o){let e=2147483647&y;for(let t=0;t=e.length&&(e=Array(t+1-e.length).join(i)+e),e}decToHex(e){return(e<15.5?"0":"")+Math.round(e).toString(16)}b32ToHex(e){e=e.toUpperCase();let t="";for(let i=0;ie}),Zy=new jt(Ci,"showCardsCurrentTab",{deserializer:e=>e}),ev=new jt(Ci,"showIdentitiesCurrentTab",{deserializer:e=>e});var tv=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class iv{constructor(e){this.stateProvider=e,this.enablePasskeysState=this.stateProvider.getGlobal(Xy),this.enablePasskeys$=this.enablePasskeysState.state$.pipe((0,q.U)((e=>null==e||e))),this.showCardsCurrentTabState=this.stateProvider.getActive(Zy),this.showCardsCurrentTab$=this.showCardsCurrentTabState.state$.pipe((0,q.U)((e=>null==e||e))),this.showIdentitiesCurrentTabState=this.stateProvider.getActive(ev),this.showIdentitiesCurrentTab$=this.showIdentitiesCurrentTabState.state$.pipe((0,q.U)((e=>null==e||e)))}setShowCardsCurrentTab(e){return tv(this,void 0,void 0,(function*(){yield this.showCardsCurrentTabState.update((()=>e))}))}setShowIdentitiesCurrentTab(e){return tv(this,void 0,void 0,(function*(){yield this.showIdentitiesCurrentTabState.update((()=>e))}))}setEnablePasskeys(e){return tv(this,void 0,void 0,(function*(){yield this.enablePasskeysState.update((()=>e))}))}}var nv=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class rv{constructor(e){this.apiService=e}postImportCiphers(e){return nv(this,void 0,void 0,(function*(){return yield this.apiService.send("POST","/ciphers/import",e,!0,!1)}))}postImportOrganizationCiphers(e,t){return nv(this,void 0,void 0,(function*(){return yield this.apiService.send("POST","/ciphers/import-organization?organizationId="+e,t,!0,!1)}))}}class sv{constructor(){this.ciphers=[],this.folders=[],this.folderRelationships=[]}}class ov{constructor(){this.ciphers=[],this.collections=[],this.collectionRelationships=[]}}class av{constructor(e,t){this.key=e,this.value=t}}class lv{constructor(e){this.groups=[],this.users=[],null!=e&&(this.name=e.name?e.name.encryptedString:null,this.externalId=e.externalId)}}class cv extends lv{constructor(e){null!=e&&(super(e),this.id=e.id)}}class dv extends Ny{constructor(e){super(e),this.id=e.id}}class uv{constructor(){this.success=!1,this.ciphers=[],this.folders=[],this.folderRelationships=[],this.collections=[],this.collectionRelationships=[]}}var hv=i(59778);class pv{constructor(){this.organizationId=null,this.logService=new $s(!1),this.newLineRegex=/(?:\r\n|\r|\n)/,this.passwordFieldNames=["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"],this.usernameFieldNames=["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"],this.notesFieldNames=["note","notes","comment","comments","memo","description","free form","freeform","free text","freetext","free","kommentar"],this.uriFieldNames=["url","hyper link","hyperlink","link","host","hostname","host name","server","address","hyper ref","href","web","website","web site","site","web-site","uri","ort","adresse"],this.parseCsvOptions={encoding:"UTF-8",skipEmptyLines:!1}}get organization(){return null!=this.organizationId}parseXml(e){if(!this.validateNoExternalEntities(e))return null;const t=(new DOMParser).parseFromString(e,"application/xml");return null!=t&&null==t.querySelector("parsererror")?t:null}parseCsv(e,t,i={}){const n=Object.assign({header:t},this.parseCsvOptions,i);e=this.splitNewLine(e).join("\n").trim();const r=hv.parse(e,n);return null!=r.errors&&r.errors.length>0&&r.errors.forEach((e=>{null!=e.row&&this.logService.warning("Error parsing row "+e.row+": "+e.message)})),r.data&&r.data.length>0?r.data:null}parseSingleRowCsv(e){if(this.isNullOrWhitespace(e))return null;const t=this.parseCsv(e,!1);return null!=t&&t.length>0&&t[0].length>0?t[0]:null}makeUriArray(e){if(null==e)return null;if("string"==typeof e){const t=new Ye;return t.uri=this.fixUri(e),this.isNullOrWhitespace(t.uri)?null:(t.match=null,[t])}if(e.length>0){const t=[];return e.forEach((e=>{const i=new Ye;i.uri=this.fixUri(e),this.isNullOrWhitespace(i.uri)||(i.match=null,t.push(i))})),0===t.length?null:t}return null}fixUri(e){return null==e?null:(-1===(e=e.trim()).indexOf("://")&&e.indexOf(".")>=0&&(e="http://"+e),e.length>1e3?e.substring(0,1e3):e)}nameFromUrl(e){const t=p.getHostname(e);return this.isNullOrWhitespace(t)?null:t.startsWith("www.")?t.replace("www.",""):t}isNullOrWhitespace(e){return p.isNullOrWhitespace(e)}getValueOrDefault(e,t=null){return this.isNullOrWhitespace(e)?t:e}splitNewLine(e){return e.split(this.newLineRegex)}setCardExpiration(e,t){if(this.isNullOrWhitespace(t))return!1;t=t.replace(/\s/g,"");const i=new RegExp("^0?(?[1-9]|1[0-2])/(?(?:[1-2][0-9])?[0-9]{2})$"),n=t.match(i);if(!n)return!1;e.card.expMonth=n.groups.month;const r=n.groups.year;return e.card.expYear=2===r.length?"20"+r:r,!0}moveFoldersToCollections(e){e.folderRelationships.forEach((t=>e.collectionRelationships.push(t))),e.collections=e.folders.map((e=>{const t=new jp;return t.name=e.name,t.id=e.id,t})),e.folderRelationships=[],e.folders=[]}querySelectorDirectChild(e,t){const i=this.querySelectorAllDirectChild(e,t);return 0===i.length?null:i[0]}querySelectorAllDirectChild(e,t){return Array.from(e.querySelectorAll(t)).filter((t=>t.parentNode===e))}initLoginCipher(){const e=new it;return e.favorite=!1,e.notes="",e.fields=[],e.login=new Ze,e.type=Pe.Login,e}cleanupCipher(e){null!=e&&(e.type!==Pe.Login&&(e.login=null),this.isNullOrWhitespace(e.name)&&(e.name="--"),this.isNullOrWhitespace(e.notes)?e.notes=null:e.notes=e.notes.trim(),null!=e.fields&&0===e.fields.length&&(e.fields=null),null!=e.passwordHistory&&0===e.passwordHistory.length&&(e.passwordHistory=null))}processKvp(e,t,i,n=ke.Text){if(!this.isNullOrWhitespace(i))if(this.isNullOrWhitespace(t)&&(t=""),i.length>200||i.trim().search(this.newLineRegex)>-1)null==e.notes&&(e.notes=""),e.notes+=t+": "+this.splitNewLine(i).join("\n")+"\n";else{null==e.fields&&(e.fields=[]);const r=new Ke;r.type=n,r.name=t,r.value=i,e.fields.push(r)}}processFolder(e,t,i=!0){if(this.isNullOrWhitespace(t))return;let n=e.folders.length;t=t.replace("\\","/");let r=!0;for(let i=0;i0&&(e.identity.firstName=this.getValueOrDefault(i[0])),2===i.length?e.identity.lastName=this.getValueOrDefault(i[1]):i.length>=3&&(e.identity.middleName=this.getValueOrDefault(i[1]),e.identity.lastName=i.slice(2,i.length).join(" "))}validateNoExternalEntities(e){return!new RegExp("{if(e.length<2)return;const i=this.initLoginCipher();if(i.notes=this.getValueOrDefault(e[e.length-1]),i.name=this.getValueOrDefault(e[0],"--"),e.length>2&&e.length%2==0)for(let t=0;t-1?i.login.password=this.getValueOrDefault(n):null==i.login.username&&this.usernameFieldNames.indexOf(s)>-1?i.login.username=this.getValueOrDefault(n):(null==i.login.uris||0===i.login.uris.length)&&this.uriFieldNames.indexOf(s)>-1?i.login.uris=this.makeUriArray(n):this.processKvp(i,r,n)}this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class vv extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.name),i.login.uris=this.makeUriArray(e.web),i.login.password=this.getValueOrDefault(e.password),i.login.username=this.getValueOrDefault(e.login),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class fv extends pv{parse(e){const t=new uv,i=JSON.parse(e);return null==i?(t.success=!1,Promise.resolve(t)):(null!=i.logins&&i.logins.forEach((e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.custName),i.notes=this.getValueOrDefault(e.note),i.login.uris=this.makeUriArray(e.url),i.login.password=this.getValueOrDefault(e.pwd),i.login.username=this.getValueOrDefault(e.loginName),this.cleanupCipher(i),t.ciphers.push(i)})),null!=i.notes&&i.notes.forEach((e=>{const i=this.initLoginCipher();i.type=Pe.SecureNote,i.secureNote.type=De.Generic,i.name=this.getValueOrDefault(e.label),i.notes=this.getValueOrDefault(e.text),this.cleanupCipher(i),t.ciphers.push(i)})),null!=i.cards&&i.cards.forEach((e=>{const i=this.initLoginCipher();i.type=Pe.Card,i.name=this.getValueOrDefault(e.custName),i.notes=this.getValueOrDefault(e.note),i.card.cardholderName=this.getValueOrDefault(e.holderName),i.card.number=this.getValueOrDefault(e.cardNumber),i.card.code=this.getValueOrDefault(e.cvv),i.card.brand=Me.getCardBrandByPatterns(i.card.number),null!=e.expirationDate&&(null!=e.expirationDate.month&&(i.card.expMonth=e.expirationDate.month+""),null!=e.expirationDate.year&&(i.card.expYear=e.expirationDate.year+"")),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class gv extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.name,this.getValueOrDefault(this.nameFromUrl(e.website),"--")),i.login.uris=this.makeUriArray(e.website),i.login.password=this.getValueOrDefault(e.password),this.isNullOrWhitespace(e.username)&&!this.isNullOrWhitespace(e.secondary_username)?i.login.username=e.secondary_username:(i.login.username=this.getValueOrDefault(e.username),i.notes=this.getValueOrDefault(e.secondary_username)),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class mv extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{if("list"===e.grouping)return;const i=this.initLoginCipher();i.favorite="1"===e.fav,i.name=this.getValueOrDefault(e.name),i.notes=this.getValueOrDefault(e.extra),"note"!==e.grouping&&(i.login.uris=this.makeUriArray(e.url),i.login.password=this.getValueOrDefault(e.password),i.login.username=this.getValueOrDefault(e.username)),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class wv extends pv{constructor(){super(...arguments),this.androidPatternRegex=new RegExp("^android:\\/\\/.*(?<=@)(.*)(?=\\/)")}parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{const i=this.initLoginCipher();let n=e.name;!n&&this.androidPatternRegex.test(e.url)&&(n=e.url.match(this.androidPatternRegex)[1]),i.name=this.getValueOrDefault(n,"--"),i.login.username=this.getValueOrDefault(e.username),i.login.password=this.getValueOrDefault(e.password),i.login.uris=this.makeUriArray(e.url),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class Sv extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{if(this.organization&&!this.isNullOrWhitespace(e.collections)){e.collections.split(",").forEach((e=>{let i=!0,n=t.collections.length;for(let r=0;rn+2&&(r.value=t[e].substr(n+2)),i.fields.push(r)}}switch(null!=e.type?e.type.toLowerCase():null){case"note":i.type=Pe.SecureNote,i.secureNote=new tt,i.secureNote.type=De.Generic;break;default:{i.type=Pe.Login,i.login=new Ze,i.login.totp=this.getValueOrDefault(e.login_totp||e.totp),i.login.username=this.getValueOrDefault(e.login_username||e.username),i.login.password=this.getValueOrDefault(e.login_password||e.password);const t=this.parseSingleRowCsv(e.login_uri||e.uri);i.login.uris=this.makeUriArray(t);break}}t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class bv{static template(){const e=new bv;return e.cardholderName="John Doe",e.brand="visa",e.number="4242424242424242",e.expMonth="04",e.expYear="2023",e.code="123",e}static toView(e,t=new Me){return t.cardholderName=e.cardholderName,t.brand=e.brand,t.number=e.number,t.expMonth=e.expMonth,t.expYear=e.expYear,t.code=e.code,t}static toDomain(e,t=new po){return t.cardholderName=null!=e.cardholderName?new z(e.cardholderName):null,t.brand=null!=e.brand?new z(e.brand):null,t.number=null!=e.number?new z(e.number):null,t.expMonth=null!=e.expMonth?new z(e.expMonth):null,t.expYear=null!=e.expYear?new z(e.expYear):null,t.code=null!=e.code?new z(e.code):null,t}constructor(e){var t,i,n,r,s,o;null!=e&&(e instanceof Me?(this.cardholderName=e.cardholderName,this.brand=e.brand,this.number=e.number,this.expMonth=e.expMonth,this.expYear=e.expYear,this.code=e.code):(this.cardholderName=null===(t=e.cardholderName)||void 0===t?void 0:t.encryptedString,this.brand=null===(i=e.brand)||void 0===i?void 0:i.encryptedString,this.number=null===(n=e.number)||void 0===n?void 0:n.encryptedString,this.expMonth=null===(r=e.expMonth)||void 0===r?void 0:r.encryptedString,this.expYear=null===(s=e.expYear)||void 0===s?void 0:s.encryptedString,this.code=null===(o=e.code)||void 0===o?void 0:o.encryptedString))}}class Pv{static template(){const e=new Pv;return e.name="Field name",e.value="Some value",e.type=ke.Text,e}static toView(e,t=new Ke){return t.type=e.type,t.value=e.value,t.name=e.name,t.linkedId=e.linkedId,t}static toDomain(e,t=new yo){return t.type=e.type,t.value=null!=e.value?new z(e.value):null,t.name=null!=e.name?new z(e.name):null,t.linkedId=e.linkedId,t}constructor(e){var t,i;null!=e&&(e instanceof Ke?(this.name=e.name,this.value=e.value):(this.name=null===(t=e.name)||void 0===t?void 0:t.encryptedString,this.value=null===(i=e.value)||void 0===i?void 0:i.encryptedString),this.type=e.type,this.linkedId=e.linkedId)}}class kv{static template(){const e=new kv;return e.title="Mr",e.firstName="John",e.middleName="William",e.lastName="Doe",e.address1="123 Any St",e.address2="Apt #123",e.address3=null,e.city="New York",e.state="NY",e.postalCode="10001",e.country="US",e.company="Acme Inc.",e.email="john@company.com",e.phone="5555551234",e.ssn="000-123-4567",e.username="jdoe",e.passportNumber="US-123456789",e.licenseNumber="D123-12-123-12333",e}static toView(e,t=new Ve){return t.title=e.title,t.firstName=e.firstName,t.middleName=e.middleName,t.lastName=e.lastName,t.address1=e.address1,t.address2=e.address2,t.address3=e.address3,t.city=e.city,t.state=e.state,t.postalCode=e.postalCode,t.country=e.country,t.company=e.company,t.email=e.email,t.phone=e.phone,t.ssn=e.ssn,t.username=e.username,t.passportNumber=e.passportNumber,t.licenseNumber=e.licenseNumber,t}static toDomain(e,t=new vo){return t.title=null!=e.title?new z(e.title):null,t.firstName=null!=e.firstName?new z(e.firstName):null,t.middleName=null!=e.middleName?new z(e.middleName):null,t.lastName=null!=e.lastName?new z(e.lastName):null,t.address1=null!=e.address1?new z(e.address1):null,t.address2=null!=e.address2?new z(e.address2):null,t.address3=null!=e.address3?new z(e.address3):null,t.city=null!=e.city?new z(e.city):null,t.state=null!=e.state?new z(e.state):null,t.postalCode=null!=e.postalCode?new z(e.postalCode):null,t.country=null!=e.country?new z(e.country):null,t.company=null!=e.company?new z(e.company):null,t.email=null!=e.email?new z(e.email):null,t.phone=null!=e.phone?new z(e.phone):null,t.ssn=null!=e.ssn?new z(e.ssn):null,t.username=null!=e.username?new z(e.username):null,t.passportNumber=null!=e.passportNumber?new z(e.passportNumber):null,t.licenseNumber=null!=e.licenseNumber?new z(e.licenseNumber):null,t}constructor(e){var t,i,n,r,s,o,a,l,c,d,u,h,p,y,v,f,g,m;null!=e&&(e instanceof Ve?(this.title=e.title,this.firstName=e.firstName,this.middleName=e.middleName,this.lastName=e.lastName,this.address1=e.address1,this.address2=e.address2,this.address3=e.address3,this.city=e.city,this.state=e.state,this.postalCode=e.postalCode,this.country=e.country,this.company=e.company,this.email=e.email,this.phone=e.phone,this.ssn=e.ssn,this.username=e.username,this.passportNumber=e.passportNumber,this.licenseNumber=e.licenseNumber):(this.title=null===(t=e.title)||void 0===t?void 0:t.encryptedString,this.firstName=null===(i=e.firstName)||void 0===i?void 0:i.encryptedString,this.middleName=null===(n=e.middleName)||void 0===n?void 0:n.encryptedString,this.lastName=null===(r=e.lastName)||void 0===r?void 0:r.encryptedString,this.address1=null===(s=e.address1)||void 0===s?void 0:s.encryptedString,this.address2=null===(o=e.address2)||void 0===o?void 0:o.encryptedString,this.address3=null===(a=e.address3)||void 0===a?void 0:a.encryptedString,this.city=null===(l=e.city)||void 0===l?void 0:l.encryptedString,this.state=null===(c=e.state)||void 0===c?void 0:c.encryptedString,this.postalCode=null===(d=e.postalCode)||void 0===d?void 0:d.encryptedString,this.country=null===(u=e.country)||void 0===u?void 0:u.encryptedString,this.company=null===(h=e.company)||void 0===h?void 0:h.encryptedString,this.email=null===(p=e.email)||void 0===p?void 0:p.encryptedString,this.phone=null===(y=e.phone)||void 0===y?void 0:y.encryptedString,this.ssn=null===(v=e.ssn)||void 0===v?void 0:v.encryptedString,this.username=null===(f=e.username)||void 0===f?void 0:f.encryptedString,this.passportNumber=null===(g=e.passportNumber)||void 0===g?void 0:g.encryptedString,this.licenseNumber=null===(m=e.licenseNumber)||void 0===m?void 0:m.encryptedString))}}class Ov{static template(){const e=new Ov;return e.credentialId="keyId",e.keyType="keyType",e.keyAlgorithm="keyAlgorithm",e.keyCurve="keyCurve",e.keyValue="keyValue",e.rpId="rpId",e.userHandle="userHandle",e.userName="userName",e.counter="counter",e.rpName="rpName",e.userDisplayName="userDisplayName",e.discoverable="false",e.creationDate=null,e}static toView(e,t=new Be){return t.credentialId=e.credentialId,t.keyType=e.keyType,t.keyAlgorithm=e.keyAlgorithm,t.keyCurve=e.keyCurve,t.keyValue=e.keyValue,t.rpId=e.rpId,t.userHandle=e.userHandle,t.userName=e.userName,t.counter=parseInt(e.counter),t.rpName=e.rpName,t.userDisplayName=e.userDisplayName,t.discoverable="true"===e.discoverable,t.creationDate=new Date(e.creationDate),t}static toDomain(e,t=new go){return t.credentialId=null!=e.credentialId?new z(e.credentialId):null,t.keyType=null!=e.keyType?new z(e.keyType):null,t.keyAlgorithm=null!=e.keyAlgorithm?new z(e.keyAlgorithm):null,t.keyCurve=null!=e.keyCurve?new z(e.keyCurve):null,t.keyValue=null!=e.keyValue?new z(e.keyValue):null,t.rpId=null!=e.rpId?new z(e.rpId):null,t.userHandle=null!=e.userHandle?new z(e.userHandle):null,t.userName=null!=e.userName?new z(e.userName):null,t.counter=null!=e.counter?new z(e.counter):null,t.rpName=null!=e.rpName?new z(e.rpName):null,t.userDisplayName=null!=e.userDisplayName?new z(e.userDisplayName):null,t.discoverable=null!=e.discoverable?new z(e.discoverable):null,t.creationDate=e.creationDate,t}constructor(e){var t,i,n,r,s,o,a,l,c,d,u,h;null!=e&&(e instanceof Be?(this.credentialId=e.credentialId,this.keyType=e.keyType,this.keyAlgorithm=e.keyAlgorithm,this.keyCurve=e.keyCurve,this.keyValue=e.keyValue,this.rpId=e.rpId,this.userHandle=e.userHandle,this.userName=e.userName,this.counter=String(e.counter),this.rpName=e.rpName,this.userDisplayName=e.userDisplayName,this.discoverable=String(e.discoverable)):(this.credentialId=null===(t=e.credentialId)||void 0===t?void 0:t.encryptedString,this.keyType=null===(i=e.keyType)||void 0===i?void 0:i.encryptedString,this.keyAlgorithm=null===(n=e.keyAlgorithm)||void 0===n?void 0:n.encryptedString,this.keyCurve=null===(r=e.keyCurve)||void 0===r?void 0:r.encryptedString,this.keyValue=null===(s=e.keyValue)||void 0===s?void 0:s.encryptedString,this.rpId=null===(o=e.rpId)||void 0===o?void 0:o.encryptedString,this.userHandle=null===(a=e.userHandle)||void 0===a?void 0:a.encryptedString,this.userName=null===(l=e.userName)||void 0===l?void 0:l.encryptedString,this.counter=null===(c=e.counter)||void 0===c?void 0:c.encryptedString,this.rpName=null===(d=e.rpName)||void 0===d?void 0:d.encryptedString,this.userDisplayName=null===(u=e.userDisplayName)||void 0===u?void 0:u.encryptedString,this.discoverable=null===(h=e.discoverable)||void 0===h?void 0:h.encryptedString),this.creationDate=e.creationDate)}}class Cv{static template(){const e=new Cv;return e.uri="https://google.com",e.match=null,e}static toView(e,t=new Ye){return t.uri=e.uri,t.match=e.match,t}static toDomain(e,t=new wo){return t.uri=null!=e.uri?new z(e.uri):null,t.uriChecksum=null!=e.uriChecksum?new z(e.uriChecksum):null,t.match=e.match,t}constructor(e){var t,i;this.match=null,null!=e&&(e instanceof Ye?this.uri=e.uri:(this.uri=null===(t=e.uri)||void 0===t?void 0:t.encryptedString,this.uriChecksum=null===(i=e.uriChecksum)||void 0===i?void 0:i.encryptedString),this.match=e.match)}}class Av{static template(){const e=new Av;return e.uris=[],e.username="jdoe",e.password="myp@ssword123",e.totp="JBSWY3DPEHPK3PXP",e.fido2Credentials=[Ov.template()],e}static toView(e,t=new Ze){return null!=e.uris&&(t.uris=e.uris.map((e=>Cv.toView(e)))),t.username=e.username,t.password=e.password,t.totp=e.totp,null!=e.fido2Credentials&&(t.fido2Credentials=e.fido2Credentials.map((e=>Ov.toView(e)))),t}static toDomain(e,t=new bo){return null!=e.uris&&(t.uris=e.uris.map((e=>Cv.toDomain(e)))),t.username=null!=e.username?new z(e.username):null,t.password=null!=e.password?new z(e.password):null,t.totp=null!=e.totp?new z(e.totp):null,t}constructor(e){var t,i,n;this.fido2Credentials=[],null!=e&&(null!=e.uris&&(this.uris=e.uris.map((e=>new Cv(e)))),null!=e.fido2Credentials&&(this.fido2Credentials=e.fido2Credentials.map((e=>new Ov(e)))),e instanceof Ze?(this.username=e.username,this.password=e.password,this.totp=e.totp):(this.username=null===(t=e.username)||void 0===t?void 0:t.encryptedString,this.password=null===(i=e.password)||void 0===i?void 0:i.encryptedString,this.totp=null===(n=e.totp)||void 0===n?void 0:n.encryptedString))}}class Dv{static template(){const e=new Dv;return e.password=null,e.lastUsedDate=null,e}static toView(e,t=new et){return t.password=e.password,t.lastUsedDate=e.lastUsedDate,t}static toDomain(e,t=new Po){return t.password=null!=e.password?new z(e.password):null,t.lastUsedDate=e.lastUsedDate,t}constructor(e){var t;this.lastUsedDate=null,null!=e&&(this.password=e instanceof et?e.password:null===(t=e.password)||void 0===t?void 0:t.encryptedString,this.lastUsedDate=e.lastUsedDate)}}class xv{static template(){const e=new xv;return e.type=De.Generic,e}static toView(e,t=new tt){return t.type=e.type,t}static toDomain(e,t=new ko){return t.type=e.type,t}constructor(e){null!=e&&(this.type=e.type)}}class Iv{constructor(){this.passwordHistory=null,this.revisionDate=null,this.creationDate=null,this.deletedDate=null}static template(){const e=new Iv;return e.organizationId=null,e.collectionIds=null,e.folderId=null,e.type=Pe.Login,e.name="Item name",e.notes="Some notes about this item.",e.favorite=!1,e.fields=[],e.login=null,e.secureNote=null,e.card=null,e.identity=null,e.reprompt=be.None,e.passwordHistory=[],e.creationDate=null,e.revisionDate=null,e.deletedDate=null,e}static toView(e,t=new it){var i,n,r;if(t.type=e.type,t.folderId=e.folderId,null==t.organizationId&&(t.organizationId=e.organizationId),t.collectionIds||e.collectionIds){const r=new Set((null!==(i=t.collectionIds)&&void 0!==i?i:[]).concat(null!==(n=e.collectionIds)&&void 0!==n?n:[]));t.collectionIds=Array.from(r.values())}switch(t.name=e.name,t.notes=e.notes,t.favorite=e.favorite,t.reprompt=null!==(r=e.reprompt)&&void 0!==r?r:be.None,null!=e.fields&&(t.fields=e.fields.map((e=>Pv.toView(e)))),e.type){case Pe.Login:t.login=Av.toView(e.login);break;case Pe.SecureNote:t.secureNote=xv.toView(e.secureNote);break;case Pe.Card:t.card=bv.toView(e.card);break;case Pe.Identity:t.identity=kv.toView(e.identity)}return null!=e.passwordHistory&&(t.passwordHistory=e.passwordHistory.map((e=>Dv.toView(e)))),t.creationDate=e.creationDate,t.revisionDate=e.revisionDate,t.deletedDate=e.deletedDate,t}static toDomain(e,t=new Co){var i;switch(t.type=e.type,t.folderId=e.folderId,null==t.organizationId&&(t.organizationId=e.organizationId),t.name=null!=e.name?new z(e.name):null,t.notes=null!=e.notes?new z(e.notes):null,t.favorite=e.favorite,t.reprompt=null!==(i=e.reprompt)&&void 0!==i?i:be.None,t.key=null!=e.key?new z(e.key):null,null!=e.fields&&(t.fields=e.fields.map((e=>Pv.toDomain(e)))),e.type){case Pe.Login:t.login=Av.toDomain(e.login);break;case Pe.SecureNote:t.secureNote=xv.toDomain(e.secureNote);break;case Pe.Card:t.card=bv.toDomain(e.card);break;case Pe.Identity:t.identity=kv.toDomain(e.identity)}return null!=e.passwordHistory&&(t.passwordHistory=e.passwordHistory.map((e=>Dv.toDomain(e)))),t.creationDate=e.creationDate,t.revisionDate=e.revisionDate,t.deletedDate=e.deletedDate,t}build(e){var t,i,n;switch(this.organizationId=e.organizationId,this.folderId=e.folderId,this.type=e.type,this.reprompt=e.reprompt,e instanceof it?(this.name=e.name,this.notes=e.notes):(this.name=null===(t=e.name)||void 0===t?void 0:t.encryptedString,this.notes=null===(i=e.notes)||void 0===i?void 0:i.encryptedString,this.key=null===(n=e.key)||void 0===n?void 0:n.encryptedString),this.favorite=e.favorite,null!=e.fields&&(this.fields=e.fields.map((e=>new Pv(e)))),e.type){case Pe.Login:this.login=new Av(e.login);break;case Pe.SecureNote:this.secureNote=new xv(e.secureNote);break;case Pe.Card:this.card=new bv(e.card);break;case Pe.Identity:this.identity=new kv(e.identity)}null!=e.passwordHistory&&(this.passwordHistory=e.passwordHistory.map((e=>new Dv(e)))),this.creationDate=e.creationDate,this.revisionDate=e.revisionDate,this.deletedDate=e.deletedDate}}class Uv extends Iv{build(e){this.id=e.id,super.build(e),this.collectionIds=e.collectionIds}}class Tv{static template(){const e=new Tv;return e.organizationId="00000000-0000-0000-0000-000000000000",e.name="Collection name",e.externalId=null,e}static toView(e,t=new jp){return t.name=e.name,t.externalId=e.externalId,null==t.organizationId&&(t.organizationId=e.organizationId),t}static toDomain(e,t=new $p){return t.name=null!=e.name?new z(e.name):null,t.externalId=e.externalId,null==t.organizationId&&(t.organizationId=e.organizationId),t}build(e){var t;this.organizationId=e.organizationId,this.name=e instanceof jp?e.name:null===(t=e.name)||void 0===t?void 0:t.encryptedString,this.externalId=e.externalId}}class Nv extends Tv{static toView(e,t=new jp){return t.id=e.id,super.toView(e,t)}static toDomain(e,t=new $p){return t.id=e.id,super.toDomain(e,t)}build(e){this.id=e.id,super.build(e)}}class Rv{static template(){const e=new Rv;return e.name="Folder name",e}static toView(e,t=new Fy){return t.name=e.name,t}static toDomain(e,t=new My){return t.name=null!=e.name?new z(e.name):null,t}build(e){var t;this.name=e instanceof Fy?e.name:null===(t=e.name)||void 0===t?void 0:t.encryptedString}}class Ev extends Rv{static toView(e,t=new Fy){return t.id=e.id,super.toView(e,t)}static toDomain(e,t=new My){return t.id=e.id,super.toDomain(e,t)}build(e){this.id=e.id,super.build(e)}}var Fv=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Mv extends pv{constructor(e,t,i){super(),this.cryptoService=e,this.i18nService=t,this.cipherService=i}parse(e){return Fv(this,void 0,void 0,(function*(){this.result=new uv;const t=JSON.parse(e);return null==t||null==t.items?(this.result.success=!1,this.result):(t.encrypted?yield this.parseEncrypted(t):yield this.parseDecrypted(t),this.result)}))}parseEncrypted(e){return Fv(this,void 0,void 0,(function*(){if(null!=e.encKeyValidation_DO_NOT_EDIT){const t=yield this.cryptoService.getOrgKey(this.organizationId),i=new z(e.encKeyValidation_DO_NOT_EDIT);if(null===(yield this.cryptoService.decryptToUtf8(i,t)))return this.result.success=!1,void(this.result.errorMessage=this.i18nService.t("importEncKeyError"))}const t=this.organization?yield this.parseCollections(e):yield this.parseFolders(e);for(const i of e.items){const e=Uv.toDomain(i);e.id=null,e.organizationId=this.organizationId,e.collectionIds=null,null!=e.passwordHistory&&e.passwordHistory.length>5&&(e.passwordHistory=e.passwordHistory.slice(0,5)),!this.organization&&null!=i.folderId&&t.has(i.folderId)?this.result.folderRelationships.push([this.result.ciphers.length,t.get(i.folderId)]):this.organization&&null!=i.collectionIds&&i.collectionIds.forEach((e=>{t.has(e)&&this.result.collectionRelationships.push([this.result.ciphers.length,t.get(e)])}));const n=yield e.decrypt(yield this.cipherService.getKeyForCipherKeyDecryption(e));this.cleanupCipher(n),this.result.ciphers.push(n)}this.result.success=!0}))}parseDecrypted(e){return Fv(this,void 0,void 0,(function*(){const t=this.organization?yield this.parseCollections(e):yield this.parseFolders(e);e.items.forEach((e=>{const i=Uv.toView(e);i.id=null,i.organizationId=null,i.collectionIds=null,null!=i.passwordHistory&&i.passwordHistory.length>5&&(i.passwordHistory=i.passwordHistory.slice(0,5)),!this.organization&&null!=e.folderId&&t.has(e.folderId)?this.result.folderRelationships.push([this.result.ciphers.length,t.get(e.folderId)]):this.organization&&null!=e.collectionIds&&e.collectionIds.forEach((e=>{t.has(e)&&this.result.collectionRelationships.push([this.result.ciphers.length,t.get(e)])})),this.cleanupCipher(i),this.result.ciphers.push(i)})),this.result.success=!0}))}parseFolders(e){return Fv(this,void 0,void 0,(function*(){if(null==e.folders)return null;const t=new Map;for(const i of e.folders){let n;if(e.encrypted){const e=Ev.toDomain(i);null!=e&&(n=yield e.decrypt())}else n=Ev.toView(i);null!=n&&(t.set(i.id,this.result.folders.length),this.result.folders.push(n))}return t}))}parseCollections(e){return Fv(this,void 0,void 0,(function*(){if(null==e.collections)return null;const t=new Map;for(const i of e.collections){let n;if(e.encrypted){const e=Nv.toDomain(i);e.organizationId=this.organizationId,n=yield e.decrypt()}else n=Nv.toView(i),n.organizationId=null;null!=n&&(t.set(i.id,this.result.collections.length),this.result.collections.push(n))}return t}))}}var Kv=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Lv extends Mv{constructor(e,t,i,n){super(e,t,i),this.promptForPassword_callback=n}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return Kv(this,void 0,void 0,(function*(){const i=new uv,n=JSON.parse(e);if(!n)return i.success=!1,i;if(!(null==n?void 0:n.encrypted))return yield t.parse.call(this,e);if(!(null==n?void 0:n.passwordProtected))return yield t.parse.call(this,e);if(this.cannotParseFile(n))return i.success=!1,i;const r=yield this.promptForPassword_callback();if(!(yield this.checkPassword(n,r)))return i.success=!1,i.errorMessage=this.i18nService.t("invalidFilePassword"),i;const s=new z(n.data),o=yield this.cryptoService.decryptToUtf8(s,this.key);return yield t.parse.call(this,o)}))}checkPassword(e,t){return Kv(this,void 0,void 0,(function*(){if(this.isNullOrWhitespace(t))return!1;this.key=yield this.cryptoService.makePinKey(t,e.salt,e.kdfType,new P(e.kdfIterations,e.kdfMemory,e.kdfParallelism));const i=new z(e.encKeyValidation_DO_NOT_EDIT);return null!==(yield this.cryptoService.decryptToUtf8(i,this.key))}))}cannotParseFile(e){return!(e&&e.encrypted&&e.passwordProtected&&e.salt&&e.kdfIterations&&"number"==typeof e.kdfIterations&&null!=e.kdfType&&null!=b[e.kdfType]&&e.encKeyValidation_DO_NOT_EDIT&&e.data)}}class zv extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{"null"===e.label&&(e.label=null);const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.label,this.getValueOrDefault(this.nameFromUrl(e.domain),"--")),i.login.uris=this.makeUriArray(e.domain),i.login.password=this.getValueOrDefault(e.password),this.isNullOrWhitespace(e.email)&&!this.isNullOrWhitespace(e.username)?i.login.username=e.username:(i.login.username=this.getValueOrDefault(e.email),i.notes=this.getValueOrDefault(e.username)),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}const Vv=["!group_id","!group_name","title","username","password","URL","id"];class Bv extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{this.processFolder(t,this.getValueOrDefault(e["!group_name"]));const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.title,"--"),i.login.username=this.getValueOrDefault(e.username),i.login.password=this.getValueOrDefault(e.password),i.login.uris=this.makeUriArray(e.URL);let n=!1;for(const t in e)e.hasOwnProperty(t)&&(n||-1!==Vv.indexOf(t)||(n=!0),n&&this.processKvp(i,t,e[t]));this.cleanupCipher(i),t.ciphers.push(i)})),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}}class _v extends pv{parse(e){const t=new uv,i=this.parseXml(e);if(null==i)return t.success=!1,Promise.resolve(t);const n=i.querySelector("textarea");if(null==n||this.isNullOrWhitespace(n.textContent))return t.errorMessage="Missing textarea.",t.success=!1,Promise.resolve(t);return JSON.parse(n.textContent).forEach((e=>{const i=this.initLoginCipher();if(this.isNullOrWhitespace(e.label)||(i.name=e.label.split(" ")[0]),null==e.data||this.isNullOrWhitespace(e.data.notes)||(i.notes=e.data.notes.split("\\n").join("\n")),null!=e.currentVersion&&null!=e.currentVersion.fields)for(const t in e.currentVersion.fields){if(!e.currentVersion.fields.hasOwnProperty(t))continue;const n=e.currentVersion.fields[t];switch(null!=n.actionType?n.actionType.toLowerCase():null){case"password":i.login.password=this.getValueOrDefault(n.value);break;case"email":case"username":case"user":case"name":i.login.username=this.getValueOrDefault(n.value);break;case"url":i.login.uris=this.makeUriArray(n.value);break;default:{const e=null!=n.label?n.label.toLowerCase():null;null==i.login.password&&this.passwordFieldNames.indexOf(e)>-1?i.login.password=this.getValueOrDefault(n.value):null==i.login.username&&this.usernameFieldNames.indexOf(e)>-1?i.login.username=this.getValueOrDefault(n.value):(null==i.login.uris||0===i.login.uris.length)&&this.uriFieldNames.indexOf(e)>-1?i.login.uris=this.makeUriArray(n.value):this.processKvp(i,n.label,n.value);break}}}this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t)}}class jv extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{this.processFolder(t,this.getValueOrDefault(e.Category));const i=this.initLoginCipher();i.favorite="True"===this.getValueOrDefault(e.Favorite),i.name=this.getValueOrDefault(e.Entry,"--"),i.notes=this.getValueOrDefault(e.Note),i.login.username=this.getValueOrDefault(e.Username,e.Email),i.login.password=this.getValueOrDefault(e.Password),i.login.totp=this.getValueOrDefault(e.TOTP),i.login.uris=this.makeUriArray(e.Website),this.isNullOrWhitespace(e.Username)||this.processKvp(i,"Email",e.Email),this.processKvp(i,"Phone",e.Phone),this.processKvp(i,"PIN",e.PIN),this.processKvp(i,"Account",e.Account),this.processKvp(i,"Date",e.Date),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)})),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}}const $v=new Set(["title","note","username","password","url","otpSecret","category"]),Wv=new Set(["type","title","first_name","middle_name","last_name","login","email","phone_number","address","country","state","city","zip","item_name"]),qv=new Set(["title","note"]);class Hv extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);if(null==i)return t.success=!1,Promise.resolve(t);if(null!=i[0].type&&null!=i[0].title){if(1===i.filter((e=>"name"===e.type)).length){const e=this.initLoginCipher();return e.type=Pe.Identity,e.identity=new Ve,i.forEach((t=>{this.parsePersonalInformationRecordAsIdentity(e,t)})),this.cleanupCipher(e),t.ciphers.push(e),t.success=!0,Promise.resolve(t)}}return i.forEach((e=>{const i=this.initLoginCipher(),n=Object.keys(e);"username"===n[0]&&(this.processFolder(t,e.category),this.parseCredentialsRecord(i,e)),"type"===n[0]&&"account_name"===n[1]&&this.parsePaymentRecord(i,e),"type"===n[0]&&"number"===n[1]&&this.parseIdRecord(i,e),"type"===n[0]!=null&&"title"===n[1]&&this.parsePersonalInformationRecord(i,e),"title"===n[0]&&"note"===n[1]&&this.parseSecureNoteRecords(i,e),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)})),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}parseCredentialsRecord(e,t){e.type=Pe.Login,e.login=new Ze,e.name=t.title,e.notes=t.note,e.login.username=t.username,e.login.password=t.password,e.login.totp=t.otpSecret,e.login.uris=this.makeUriArray(t.url),this.importUnmappedFields(e,t,$v)}parsePaymentRecord(e,t){e.type=Pe.Card,e.card=new Me,e.name=t.account_name;let i=[];switch(t.type){case"credit_card":e.card.cardholderName=t.account_name,e.card.number=t.cc_number,e.card.brand=Me.getCardBrandByPatterns(e.card.number),e.card.code=t.code,this.setCardExpiration(e,`${t.expiration_month}/${t.expiration_year}`),i=["account_name","account_holder","cc_number","code","expiration_month","expiration_year"];break;case"bank":e.card.cardholderName=t.account_holder,e.card.number=t.account_number,i=["account_name","account_holder","account_number"]}this.importUnmappedFields(e,t,new Set(i))}parseIdRecord(e,t){e.type=Pe.Identity,e.identity=new Ve;const i=["name","number"];switch(t.type){case"card":e.name=`${t.name} ${t.type}`,this.processFullName(e,t.name),e.identity.licenseNumber=t.number;break;case"passport":e.name=`${t.name} ${t.type}`,this.processFullName(e,t.name),e.identity.passportNumber=t.number;break;case"license":e.name=`${t.name} ${t.type}`,this.processFullName(e,t.name),e.identity.licenseNumber=t.number,e.identity.state=t.state,i.push("state");break;case"social_security":e.name=`${t.name} ${t.type}`,this.processFullName(e,t.name),e.identity.ssn=t.number;break;case"tax_number":e.name=t.type,e.identity.licenseNumber=t.number}this.importUnmappedFields(e,t,new Set(i))}parsePersonalInformationRecord(e,t){e.type=Pe.SecureNote,e.secureNote.type=De.Generic,"name"===t.type?e.name=`${t.title} ${t.first_name} ${t.middle_name} ${t.last_name}`.replace(" "," ").trim():e.name=t.item_name;const i=t;Object.keys(t).forEach((t=>{this.processKvp(e,t,i[t])}))}parsePersonalInformationRecordAsIdentity(e,t){switch(t.type){case"name":this.processFullName(e,`${t.first_name} ${t.middle_name} ${t.last_name}`),e.identity.title=t.title,e.name=e.identity.fullName,e.identity.username=t.login;break;case"email":e.identity.email=t.email;break;case"number":e.identity.phone=t.phone_number;break;case"address":e.identity.address1=t.address,e.identity.city=t.city,e.identity.postalCode=t.zip,e.identity.state=t.state,e.identity.country=t.country}this.importUnmappedFields(e,t,Wv)}parseSecureNoteRecords(e,t){e.type=Pe.SecureNote,e.secureNote.type=De.Generic,e.name=t.title,e.notes=t.note,this.importUnmappedFields(e,t,qv)}importUnmappedFields(e,t,i){Object.keys(t).filter((e=>!i.has(e))).forEach((i=>{const n=t;this.processKvp(e,i,n[i])}))}}const Gv=new Set(["ADDRESS","AUTHENTIFIANT","BANKSTATEMENT","IDCARD","IDENTITY","PAYMENTMEANS_CREDITCARD","PAYMENTMEAN_PAYPAL","EMAIL"]);class Jv extends pv{parse(e){this.result=new uv;const t=JSON.parse(e);if(null==t||0===t.length)return this.result.success=!1,Promise.resolve(this.result);null!=t.ADDRESS&&this.processAddress(t.ADDRESS),null!=t.AUTHENTIFIANT&&this.processAuth(t.AUTHENTIFIANT),null!=t.BANKSTATEMENT&&this.processNote(t.BANKSTATEMENT,"BankAccountName"),null!=t.IDCARD&&this.processNote(t.IDCARD,"Fullname"),null!=t.PAYMENTMEANS_CREDITCARD&&this.processCard(t.PAYMENTMEANS_CREDITCARD),null!=t.IDENTITY&&this.processIdentity(t.IDENTITY);for(const e in t)t.hasOwnProperty(e)&&!Gv.has(e)&&this.processNote(t[e],null,"Generic Note");return this.result.success=!0,Promise.resolve(this.result)}processAuth(e){e.forEach((e=>{const t=this.initLoginCipher();t.name=this.getValueOrDefault(e.title),t.login.username=this.getValueOrDefault(e.login,this.getValueOrDefault(e.secondaryLogin)),this.isNullOrWhitespace(t.login.username)?t.login.username=this.getValueOrDefault(e.email):this.isNullOrWhitespace(e.email)||(t.notes="Email: "+e.email+"\n"),t.login.password=this.getValueOrDefault(e.password),t.login.uris=this.makeUriArray(e.domain),t.notes+=this.getValueOrDefault(e.note,""),this.convertToNoteIfNeeded(t),this.cleanupCipher(t),this.result.ciphers.push(t)}))}processIdentity(e){e.forEach((e=>{const t=new it;t.identity=new Ve,t.type=Pe.Identity,t.name=this.getValueOrDefault(e.fullName,"");const i=t.name.split(" ");i.length>0&&(t.identity.firstName=this.getValueOrDefault(i[0])),2===i.length?t.identity.lastName=this.getValueOrDefault(i[1]):3===i.length&&(t.identity.middleName=this.getValueOrDefault(i[1]),t.identity.lastName=this.getValueOrDefault(i[2])),t.identity.username=this.getValueOrDefault(e.pseudo),this.cleanupCipher(t),this.result.ciphers.push(t)}))}processAddress(e){e.forEach((e=>{const t=new it;t.identity=new Ve,t.type=Pe.Identity,t.name=this.getValueOrDefault(e.addressName),t.identity.address1=this.getValueOrDefault(e.addressFull),t.identity.city=this.getValueOrDefault(e.city),t.identity.state=this.getValueOrDefault(e.state),t.identity.postalCode=this.getValueOrDefault(e.zipcode),t.identity.country=this.getValueOrDefault(e.country),null!=t.identity.country&&(t.identity.country=t.identity.country.toUpperCase()),this.cleanupCipher(t),this.result.ciphers.push(t)}))}processCard(e){e.forEach((e=>{const t=new it;t.card=new Me,t.type=Pe.Card,t.name=this.getValueOrDefault(e.bank),t.card.number=this.getValueOrDefault(e.cardNumber),t.card.brand=Me.getCardBrandByPatterns(t.card.number),t.card.cardholderName=this.getValueOrDefault(e.owner),this.isNullOrWhitespace(t.card.brand)||(this.isNullOrWhitespace(t.name)?t.name=t.card.brand:t.name+=" - "+t.card.brand),this.cleanupCipher(t),this.result.ciphers.push(t)}))}processNote(e,t,i=null){e.forEach((e=>{const n=new it;n.secureNote=new tt,n.type=Pe.SecureNote,n.secureNote.type=De.Generic,n.name=null!=i?i:this.getValueOrDefault(e[t]);for(const i in e)e.hasOwnProperty(i)&&i!==t&&this.processKvp(n,i,e[i].toString());this.cleanupCipher(n),this.result.ciphers.push(n)}))}}class Yv extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.Label,"--"),i.notes=this.getValueOrDefault(e.Notes);const n=this.getValueOrDefault(e.Text);this.isNullOrWhitespace(n)||(this.isNullOrWhitespace(i.notes)?i.notes=n:i.notes+="\n\n"+n);const r=e["Entry Type"];if("Password"===r)i.login.username=this.getValueOrDefault(e.Username),i.login.password=this.getValueOrDefault(e.Password),i.login.uris=this.makeUriArray(e["Site URL"]);else if("Credit Card"===r){i.type=Pe.Card,i.card=new Me,i.card.cardholderName=this.getValueOrDefault(e["Name on card"]),i.card.number=this.getValueOrDefault(e["Card Number"]),i.card.brand=Me.getCardBrandByPatterns(i.card.number),i.card.code=this.getValueOrDefault(e.CVV);const t=this.getValueOrDefault(e.Expiry);if(!this.isNullOrWhitespace(t)){const e=t.split("/");e.length>1&&(i.card.expMonth=parseInt(e[0],null).toString(),i.card.expYear=(2e3+parseInt(e[1],null)).toString())}}this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class Qv extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!1);if(null==i)return t.success=!1,Promise.resolve(t);let n=!0;return i.forEach((e=>{if(e.length<2||n&&("Title"===e[0]||"title"===e[0]))return void(n=!1);const i=this.initLoginCipher();if(i.notes=this.getValueOrDefault(e[e.length-1]),i.name=this.getValueOrDefault(e[0],"--"),2!==e.length&&(this.containsField(e,"username")||this.containsField(e,"password")||this.containsField(e,"email")||this.containsField(e,"url"))||(i.type=Pe.SecureNote,i.secureNote=new tt,i.secureNote.type=De.Generic),this.containsField(e,"cardholder")&&this.containsField(e,"number")&&this.containsField(e,"expiry date")&&(i.type=Pe.Card,i.card=new Me),e.length>2&&e.length%2==0)for(let t=0;t!this.isNullOrWhitespace(e)&&e.toLowerCase()===t.toLowerCase())).length>0}}const Xv=new RegExp("androidapp://.*==@","g");class Zv extends pv{parse(e){const t=new uv,i=JSON.parse(e);if(null==i||null==i.items||0===i.items.length)return t.success=!1,Promise.resolve(t);const n=new Map,r=new Map,s=this.buildFolderTree(i.folders);return this.flattenFolderTree(null,s,n),n.forEach(((e,i)=>{r.set(i,t.folders.length);const n=new Fy;n.name=e,t.folders.push(n)})),i.items.forEach((e=>{null!=e.folders&&e.folders.length>0&&r.has(e.folders[0])&&t.folderRelationships.push([t.ciphers.length,r.get(e.folders[0])]);const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.title),i.favorite=e.favorite>0,null!=e.template_type&&null!=e.fields&&e.fields.length>0&&(0===e.template_type.indexOf("login.")||0===e.template_type.indexOf("password.")?this.processLogin(i,e.fields):0===e.template_type.indexOf("creditcard.")?this.processCard(i,e.fields):e.template_type.indexOf("identity.")<0&&e.fields.some((e=>"password"===e.type&&!this.isNullOrWhitespace(e.value)))?this.processLogin(i,e.fields):this.processNote(i,e.fields)),i.notes+="\n"+this.getValueOrDefault(e.note,""),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t)}processLogin(e,t){const i=[];t.forEach((t=>{if(!this.isNullOrWhitespace(t.value)&&"section"!==t.type)if("username"!==t.type&&"email"!==t.type||!this.isNullOrWhitespace(e.login.username))if("password"===t.type&&this.isNullOrWhitespace(e.login.password))e.login.password=t.value;else if("totp"===t.type&&this.isNullOrWhitespace(e.login.totp))e.login.totp=t.value;else if("url"===t.type)i.push(t.value);else if(".Android#"===t.type){let e=t.value.startsWith("androidapp://")?t.value:"androidapp://"+t.value;e=e.replace("android://",""),e=e.replace(Xv,"androidapp://"),i.push(e)}else this.processKvp(e,t.label,t.value,1===t.sensitive?ke.Hidden:ke.Text);else e.login.username=t.value})),e.login.uris=this.makeUriArray(i)}processCard(e,t){e.card=new Me,e.type=Pe.Card,t.forEach((t=>{this.isNullOrWhitespace(t.value)||"section"===t.type||"ccType"===t.type||("ccName"===t.type&&this.isNullOrWhitespace(e.card.cardholderName)?e.card.cardholderName=t.value:"ccNumber"===t.type&&this.isNullOrWhitespace(e.card.number)?(e.card.number=t.value,e.card.brand=Me.getCardBrandByPatterns(e.card.number)):"ccCvc"===t.type&&this.isNullOrWhitespace(e.card.code)?e.card.code=t.value:"ccExpiry"===t.type&&this.isNullOrWhitespace(e.card.expYear)&&this.setCardExpiration(e,t.value)||this.processKvp(e,t.label,t.value,1===t.sensitive?ke.Hidden:ke.Text))}))}processNote(e,t){t.forEach((t=>{this.isNullOrWhitespace(t.value)||"section"===t.type||this.processKvp(e,t.label,t.value,1===t.sensitive?ke.Hidden:ke.Text)}))}buildFolderTree(e){if(null==e)return[];const t=[],i=new Map([]);return e.forEach((e=>{i.set(e.uuid,e),e.children=[]})),e.forEach((e=>{null!=e.parent_uuid&&""!==e.parent_uuid&&i.has(e.parent_uuid)?i.get(e.parent_uuid).children.push(e):t.push(e)})),t}flattenFolderTree(e,t,i){null!=t&&t.forEach((t=>{if(null!=t.title&&""!==t.title.trim()){let n=t.title.trim();null!=e&&""!==e.trim()&&(n=e+"/"+n),i.set(t.uuid,n),null!=t.children&&0!==t.children.length&&this.flattenFolderTree(n,t.children,i)}}))}}class ef extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.filter((e=>"chrome://FirefoxAccounts"!==e.url)).forEach((e=>{const i=this.initLoginCipher(),n=this.getValueOrDefault(e.url,this.getValueOrDefault(e.hostname));i.name=this.getValueOrDefault(this.nameFromUrl(n),"--"),i.login.username=this.getValueOrDefault(e.username),i.login.password=this.getValueOrDefault(e.password),i.login.uris=this.makeUriArray(n),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}var tf;!function(e){e[e.Login=1]="Login",e[e.CreditCard=2]="CreditCard"}(tf||(tf={}));class nf extends pv{parse(e){const t=new uv,i=JSON.parse(e);if(null==i||null==i.data)return t.success=!1,Promise.resolve(t);for(const e in i.data){if(!i.data.hasOwnProperty(e))continue;const n=i.data[e],r=this.parseEntry(n);t.ciphers.push(r)}return t.success=!0,Promise.resolve(t)}parseEntry(e){const t=this.initLoginCipher();switch(t.name=this.getValueOrDefault(e.service),t.notes=this.getValueOrDefault(e.notes),t.favorite=e.favorite>0,e.type){case tf.Login:this.handleLoginEntry(e,t);break;case tf.CreditCard:this.handleCreditCardEntry(e,t);break;default:return}return this.convertToNoteIfNeeded(t),this.cleanupCipher(t),t}handleLoginEntry(e,t){t.login.username=this.getValueOrDefault(e.username),t.login.password=this.getValueOrDefault(e.password),t.login.uris=this.makeUriArray(e.url)}handleCreditCardEntry(e,t){t.type=Pe.Card,t.card=new Me,t.card.cardholderName=this.getValueOrDefault(e.username),t.card.number=this.getValueOrDefault(e.creditNumber),t.card.brand=Me.getCardBrandByPatterns(t.card.number),t.card.code=this.getValueOrDefault(e.creditCvv),this.isNullOrWhitespace(e.creditExpiry)||this.setCardExpiration(t,e.creditExpiry)||this.processKvp(t,"Expiration",e.creditExpiry),this.isNullOrWhitespace(e.password)||this.processKvp(t,"PIN",e.password)}}class rf extends pv{parse(e){const t=new uv,i=JSON.parse(e);if(null==i||0===Object.keys(i).length)return t.success=!1,Promise.resolve(t);for(const e in i)i.hasOwnProperty(e)&&!this.isNullOrWhitespace(e)&&0!==i[e].length&&i[e].forEach((i=>{if(this.isNullOrWhitespace(i.display_name)||0!==i.display_name.indexOf("http"))return;this.processFolder(t,e);const n=this.initLoginCipher();if(n.name=i.display_name.replace("http://","").replace("https://",""),n.name.length>30&&(n.name=n.name.substring(0,30)),n.login.password=this.getValueOrDefault(i.secret),n.login.uris=this.makeUriArray(i.display_name),null!=i.attributes){n.login.username=null!=i.attributes?this.getValueOrDefault(i.attributes.username_value):null;for(const e in i.attributes)i.attributes.hasOwnProperty(e)&&"username_value"!==e&&"xdg:schema"!==e&&this.processKvp(n,e,i.attributes[e])}this.convertToNoteIfNeeded(n),this.cleanupCipher(n),t.ciphers.push(n)}));return this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}}const sf="Notes\n\n",of="Applications\n\n",af="Websites\n\n",lf="\n---\n";class cf extends pv{parse(e){const t=new uv;let i,n,r,s=this.splitNewLine(e).join("\n");if(-1!==s.indexOf(sf)){const e=s.split(sf);e.length>1&&(s=e[0],i=e[1])}if(-1!==s.indexOf(of)){const e=s.split(of);e.length>1&&(s=e[0],n=e[1])}if(0===s.indexOf(af)){const e=s.split(af);e.length>1&&(s=e[0],r=e[1])}const o=this.parseDataCategory(i),a=this.parseDataCategory(n),l=this.parseDataCategory(r);return o.forEach((e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.get("Name")),i.notes=this.getValueOrDefault(e.get("Text")),this.cleanupCipher(i),t.ciphers.push(i)})),l.concat(a).forEach((e=>{const i=this.initLoginCipher(),n=e.has("Website name")?"Website name":"Application";i.name=this.getValueOrDefault(e.get(n),""),this.isNullOrWhitespace(e.get("Login name"))||(this.isNullOrWhitespace(i.name)||(i.name+=": "),i.name+=e.get("Login name")),i.notes=this.getValueOrDefault(e.get("Comment")),e.has("Website URL")&&(i.login.uris=this.makeUriArray(e.get("Website URL"))),i.login.username=this.getValueOrDefault(e.get("Login")),i.login.password=this.getValueOrDefault(e.get("Password")),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t)}parseDataCategory(e){if(this.isNullOrWhitespace(e)||-1===e.indexOf(lf))return[];const t=[];return e.split(lf).forEach((e=>{if(-1===e.indexOf("\n"))return;const i=new Map;let n,r;e.split("\n").forEach((e=>{if(null!=n)return void(n+="\n"+e);const t=e.indexOf(":");let s,o;-1!==t&&(s=e.substring(0,t),e.length>t+1&&(o=e.substring(t+2)),null!=s&&i.set(s,o),"Comment"!==s&&"Text"!==s||(n=o,r=s))})),null!=n&&null!=r&&i.set(r,n),0!==i.size&&t.push(i)})),t}}class df extends pv{constructor(){super(...arguments),this.result=new uv}parse(e){const t=this.parseXml(e);if(null==t)return this.result.success=!1,Promise.resolve(this.result);const i=t.querySelector("KeePassFile");if(null==i)return this.result.errorMessage="Missing `KeePassFile` node.",this.result.success=!1,Promise.resolve(this.result);const n=i.querySelector("Root");if(null==n)return this.result.errorMessage="Missing `KeePassFile > Root` node.",this.result.success=!1,Promise.resolve(this.result);const r=n.querySelector("Group");return null==r?(this.result.errorMessage="Missing `KeePassFile > Root > Group` node.",this.result.success=!1,Promise.resolve(this.result)):(this.traverse(r,!0,""),this.organization&&this.moveFoldersToCollections(this.result),this.result.success=!0,Promise.resolve(this.result))}traverse(e,t,i){const n=this.result.folders.length;let r=i;if(!t){""!==r&&(r+="/");const t=this.querySelectorDirectChild(e,"Name");r+=null==t?"-":t.textContent;const i=new Fy;i.name=r,this.result.folders.push(i)}this.querySelectorAllDirectChild(e,"Entry").forEach((e=>{const i=this.result.ciphers.length,r=this.initLoginCipher();this.querySelectorAllDirectChild(e,"String").forEach((e=>{const t=this.querySelectorDirectChild(e,"Value"),i=null!=t?t.textContent:null;if(this.isNullOrWhitespace(i))return;const n=this.querySelectorDirectChild(e,"Key"),s=null!=n?n.textContent:null;if("URL"===s)r.login.uris=this.makeUriArray(i);else if("UserName"===s)r.login.username=i;else if("Password"===s)r.login.password=i;else if("otp"===s)r.login.totp=i.replace("key=","");else if("Title"===s)r.name=i;else if("Notes"===s)r.notes+=i+"\n";else{let e=ke.Text;const n=t.attributes;n.length>0&&null!=n.ProtectInMemory&&"True"===n.ProtectInMemory.value&&(e=ke.Hidden),this.processKvp(r,s,i,e)}})),this.cleanupCipher(r),this.result.ciphers.push(r),t||this.result.folderRelationships.push([i,n])})),this.querySelectorAllDirectChild(e,"Group").forEach((e=>{this.traverse(e,!1,r)}))}}class uf extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{if(this.isNullOrWhitespace(e.Title))return;e.Group=!this.isNullOrWhitespace(e.Group)&&e.Group.startsWith("Root/")?e.Group.replace("Root/",""):e.Group;const i=this.isNullOrWhitespace(e.Group)?null:e.Group;this.processFolder(t,i);const n=this.initLoginCipher();n.notes=this.getValueOrDefault(e.Notes),n.name=this.getValueOrDefault(e.Title,"--"),n.login.username=this.getValueOrDefault(e.Username),n.login.password=this.getValueOrDefault(e.Password),n.login.uris=this.makeUriArray(e.URL),this.cleanupCipher(n),t.ciphers.push(n)})),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}}class hf extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!1);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{if(e.length<6)return;this.processFolder(t,e[0]);const i=this.initLoginCipher(),n=this.getValueOrDefault(e[5]);if(n&&(i.notes=`${n}\n`),i.name=this.getValueOrDefault(e[1],"--"),i.login.username=this.getValueOrDefault(e[2]),i.login.password=this.getValueOrDefault(e[3]),i.login.uris=this.makeUriArray(e[4]),e.length>7)for(let t=7;t{const i=t.ciphers.length;let n=t.folders.length,r=e.grouping;null!=r&&(r=r.replace(/\\/g,"/").replace(/[\x00-\x1F\x7F-\x9F]/g,""));const s="(none)"!==this.getValueOrDefault(r,"(none)");let o=s;if(s)for(let e=0;e-1){const i=e.ccexp.split("-");i.length>1&&(t.expYear=i[0],t.expMonth=i[1],2===t.expMonth.length&&"0"===t.expMonth[0]&&(t.expMonth=t.expMonth[1]))}return t}parseIdentity(e){const t=new Ve;return t.title=this.getValueOrDefault(e.title),t.firstName=this.getValueOrDefault(e.firstname),t.middleName=this.getValueOrDefault(e.middlename),t.lastName=this.getValueOrDefault(e.lastname),t.username=this.getValueOrDefault(e.username),t.company=this.getValueOrDefault(e.company),t.ssn=this.getValueOrDefault(e.ssn),t.address1=this.getValueOrDefault(e.address1),t.address2=this.getValueOrDefault(e.address2),t.address3=this.getValueOrDefault(e.address3),t.city=this.getValueOrDefault(e.city),t.state=this.getValueOrDefault(e.state),t.postalCode=this.getValueOrDefault(e.zip),t.country=this.getValueOrDefault(e.country),t.email=this.getValueOrDefault(e.email),t.phone=this.getValueOrDefault(e.phone),this.isNullOrWhitespace(t.title)||(t.title=t.title.charAt(0).toUpperCase()+t.title.slice(1)),t}parseSecureNote(e,t){const i=this.splitNewLine(e.extra);let n=!1;if(i.length){const e=i[0].split(":");if(e.length>1&&"NoteType"===e[0]&&("Credit Card"===e[1]||"Address"===e[1])){if("Credit Card"===e[1]){const e=this.parseSecureNoteMapping(t,i,{Number:"number","Name on Card":"cardholderName","Security Code":"code","Expiration Date":"expMonth"});if(this.isNullOrWhitespace(e.expMonth)||","===e.expMonth)e.expMonth=void 0;else{const[t,i]=e.expMonth.split(",");if(this.isNullOrWhitespace(t))e.expMonth=void 0;else{const i=new Date(Date.parse(t.trim()+" 1, 2012")).getMonth()+1;isNaN(i)?e.expMonth=void 0:e.expMonth=i.toString()}this.isNullOrWhitespace(i)||(e.expYear=i)}t.type=Pe.Card,t.card=e}else if("Address"===e[1]){const e=this.parseSecureNoteMapping(t,i,{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"});t.type=Pe.Identity,t.identity=e}n=!0}}n||(t.secureNote=new tt,t.secureNote.type=De.Generic,t.notes=this.getValueOrDefault(e.extra))}parseSecureNoteMapping(e,t,i){const n={};let r=!1;return t.forEach((t=>{let s=null,o=null;if(!r){if(this.isNullOrWhitespace(t))return;const e=t.indexOf(":");if(-1===e?s=t:(s=t.substring(0,e),t.length>e&&(o=t.substring(e+1))),this.isNullOrWhitespace(s)||this.isNullOrWhitespace(o)||"NoteType"===s)return}r?e.notes+="\n"+t:"Notes"===s?(this.isNullOrWhitespace(e.notes)?e.notes=o:e.notes+="\n"+o,r=!0):i.hasOwnProperty(s)?n[i[s]]=o:this.processKvp(e,s,o)})),n}}class yf extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!1);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{if(e.length<4)return;const i=this.initLoginCipher();i.name=this.getValueOrDefault(e[0],"--"),i.login.username=this.getValueOrDefault(e[2]),i.login.password=this.getValueOrDefault(e[3]),i.login.uris=this.makeUriArray(e[1]),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class vf extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.DisplayName,"--"),i.notes=this.getValueOrDefault(e.Notes),i.login.username=this.getValueOrDefault(e.UserName),i.login.password=this.getValueOrDefault(e.Password),i.login.uris=this.makeUriArray(e.Url),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class ff extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!1);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{if(e.length<3)return;const i="Unassigned"!==this.getValueOrDefault(e[0],"Unassigned")?e[0]:null;this.processFolder(t,i);const n=this.initLoginCipher();if(n.name=this.getValueOrDefault(e[2],"--"),"Web Logins"===e[1]||"Login"===e[1])n.login.uris=this.makeUriArray(e[4]),n.login.username=this.getValueOrDefault(e[5]),n.login.password=this.getValueOrDefault(e[6]),n.notes=this.isNullOrWhitespace(e[3])?null:e[3].split("\\n").join("\n");else if(e.length>3){n.type=Pe.SecureNote,n.secureNote=new tt,n.secureNote.type=De.Generic;for(let t=3;t{const i=this.initLoginCipher();if(i.name=this.getValueOrDefault(e.nickname,"--"),i.notes=this.getValueOrDefault(e.additionalInfo),void 0!==e.url)i.login.uris=this.makeUriArray(e.url),i.login.username=this.getValueOrDefault(e.username),i.login.password=this.getValueOrDefault(e.password),i.login.totp=this.getValueOrDefault(e.twofaSecret),this.importUnmappedFields(i,e,mf);else if(void 0!==e.authToken)i.login.totp=this.getValueOrDefault(e.authToken),this.importUnmappedFields(i,e,Pf);else if(void 0!==e.cardNumber)i.card=new Me,i.type=Pe.Card,i.card.cardholderName=this.getValueOrDefault(e.cardName),i.card.number=this.getValueOrDefault(e.cardNumber),i.card.brand=Me.getCardBrandByPatterns(i.card.number),i.card.expMonth=this.getValueOrDefault(e.exp_month),i.card.expYear=this.getValueOrDefault(e.exp_year),i.card.code=this.getValueOrDefault(e.cvv),this.importUnmappedFields(i,e,wf);else if(void 0!==e.firstName)i.identity=new Ve,i.type=Pe.Identity,i.identity.title=this.getValueOrDefault(e.title),i.identity.firstName=this.getValueOrDefault(e.firstName),i.identity.middleName=this.getValueOrDefault(e.middleName),i.identity.lastName=this.getValueOrDefault(e.lastName),i.identity.phone=this.getValueOrDefault(e.number),i.identity.email=this.getValueOrDefault(e.email),i.identity.address1=this.getValueOrDefault(e.firstAddressLine),i.identity.address2=this.getValueOrDefault(e.secondAddressLine),i.identity.city=this.getValueOrDefault(e.city),i.identity.country=this.getValueOrDefault(e.country),i.identity.postalCode=this.getValueOrDefault(e.zipCode),this.importUnmappedFields(i,e,Sf);else if(void 0!==e.idType){switch(i.identity=new Ve,i.type=Pe.Identity,this.processFullName(i,e.idName),i.identity.country=this.getValueOrDefault(e.idCountry),e.idType){case"Passport":i.identity.passportNumber=e.idNumber;break;case"Social Security":i.identity.ssn=e.idNumber;break;default:i.identity.licenseNumber=e.idNumber}this.importUnmappedFields(i,e,bf)}else{if(void 0===e.content)return;i.secureNote=new tt,i.type=Pe.SecureNote,i.secureNote.type=De.Generic,i.notes=this.getValueOrDefault(e.content),this.importUnmappedFields(i,e,kf)}this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}importUnmappedFields(e,t,i){Object.keys(t).filter((e=>!i.has(e))).forEach((i=>{const n=t;this.processKvp(e,i,n[i])}))}}class Cf extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{const i=this.evaluateType(e);if(void 0===i)return;this.organization||this.processFolder(t,e.folder);const n=new it;switch(n.name=this.getValueOrDefault(e.name,"--"),n.notes=this.getValueOrDefault(e.note),i){case Pe.Login:n.type=Pe.Login,n.login=new Ze,n.login.username=this.getValueOrDefault(e.username),n.login.password=this.getValueOrDefault(e.password),n.login.uris=this.makeUriArray(e.url);break;case Pe.Card:n.type=Pe.Card,n.card.cardholderName=this.getValueOrDefault(e.cardholdername),n.card.number=this.getValueOrDefault(e.cardnumber),n.card.code=this.getValueOrDefault(e.cvc),n.card.brand=Me.getCardBrandByPatterns(n.card.number),this.setCardExpiration(n,e.expirydate);break;case Pe.Identity:n.type=Pe.Identity,this.processFullName(n,this.getValueOrDefault(e.full_name)),n.identity.address1=this.getValueOrDefault(e.address1),n.identity.address2=this.getValueOrDefault(e.address2),n.identity.city=this.getValueOrDefault(e.city),n.identity.state=this.getValueOrDefault(e.state),n.identity.postalCode=this.getValueOrDefault(e.zipcode),n.identity.country=this.getValueOrDefault(e.country),null!=n.identity.country&&(n.identity.country=n.identity.country.toUpperCase()),n.identity.email=this.getValueOrDefault(e.email),n.identity.phone=this.getValueOrDefault(e.phone_number);break;case Pe.SecureNote:n.type=Pe.SecureNote,n.secureNote.type=De.Generic}this.cleanupCipher(n),t.ciphers.push(n)})),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}evaluateType(e){return this.isNullOrWhitespace(e.username)?this.isNullOrWhitespace(e.cardnumber)?this.isNullOrWhitespace(e.full_name)?this.isNullOrWhitespace(e.note)?void 0:Pe.SecureNote:Pe.Identity:Pe.Card:Pe.Login}}class Af extends pv{constructor(){super(...arguments),this.result=new uv}parse(e){return e.split(this.newLineRegex).forEach((e=>{if(this.isNullOrWhitespace(e)||"{"!==e[0])return;const t=JSON.parse(e);if(!0===t.trashed)return;const i=this.initLoginCipher();this.isNullOrWhitespace(t.hmac)?this.processStandardItem(t,i):this.processWinOpVaultItem(t,i),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),this.result.ciphers.push(i)})),this.result.success=!0,Promise.resolve(this.result)}processWinOpVaultItem(e,t){if(null!=e.overview&&(t.name=this.getValueOrDefault(e.overview.title),null!=e.overview.URLs)){const i=[];e.overview.URLs.forEach((e=>{this.isNullOrWhitespace(e.u)||i.push(e.u)})),t.login.uris=this.makeUriArray(i)}null!=e.details&&(null!=e.details.passwordHistory&&this.parsePasswordHistory(e.details.passwordHistory,t),this.isNullOrWhitespace(e.details.ccnum)&&this.isNullOrWhitespace(e.details.cvv)?this.isNullOrWhitespace(e.details.firstname)&&this.isNullOrWhitespace(e.details.address1)||(t.type=Pe.Identity,t.identity=new Ve):(t.type=Pe.Card,t.card=new Me),t.type!==Pe.Login||this.isNullOrWhitespace(e.details.password)||(t.login.password=e.details.password),this.isNullOrWhitespace(e.details.notesPlain)||(t.notes=e.details.notesPlain.split(this.newLineRegex).join("\n")+"\n"),null!=e.details.fields&&this.parseFields(e.details.fields,t,"designation","value","name"),null!=e.details.sections&&e.details.sections.forEach((e=>{null!=e.fields&&this.parseFields(e.fields,t,"n","v","t")})))}processStandardItem(e,t){if(t.favorite=!(!e.openContents||!e.openContents.faveIndex),t.name=this.getValueOrDefault(e.title),"securenotes.SecureNote"===e.typeName?(t.type=Pe.SecureNote,t.secureNote=new tt,t.secureNote.type=De.Generic):"wallet.financial.CreditCard"===e.typeName?(t.type=Pe.Card,t.card=new Me):"identities.Identity"===e.typeName?(t.type=Pe.Identity,t.identity=new Ve):t.login.uris=this.makeUriArray(e.location),null!=e.secureContents){if(null!=e.secureContents.passwordHistory&&this.parsePasswordHistory(e.secureContents.passwordHistory,t),this.isNullOrWhitespace(e.secureContents.notesPlain)||(t.notes=e.secureContents.notesPlain.split(this.newLineRegex).join("\n")+"\n"),t.type===Pe.Login&&(this.isNullOrWhitespace(e.secureContents.password)||(t.login.password=e.secureContents.password),null!=e.secureContents.URLs)){const i=[];e.secureContents.URLs.forEach((e=>{this.isNullOrWhitespace(e.url)||i.push(e.url)})),i.length>0&&(t.login.uris=this.makeUriArray(i))}null!=e.secureContents.fields&&this.parseFields(e.secureContents.fields,t,"designation","value","name"),null!=e.secureContents.sections&&e.secureContents.sections.forEach((e=>{null!=e.fields&&this.parseFields(e.fields,t,"n","v","t")}))}}parsePasswordHistory(e,t){const i=e.length>5?5:e.length;t.passwordHistory=e.filter((e=>!this.isNullOrWhitespace(e.value)&&null!=e.time)).sort(((e,t)=>t.time-e.time)).slice(0,i).map((e=>{const t=new et;return t.password=e.value,t.lastUsedDate=new Date((""+e.time).length>=13?e.time:1e3*e.time),t}))}parseFields(e,t,i,n,r){e.forEach((e=>{if(null==e[n]||""===e[n].toString().trim())return;const s="date"===e.k?new Date(1e3*e[n]).toUTCString():e[n].toString(),o=null!=e[i]?e[i].toString():null;if(t.type===Pe.Login){if(this.isNullOrWhitespace(t.login.username)&&"username"===o)return void(t.login.username=s);if(this.isNullOrWhitespace(t.login.password)&&"password"===o)return void(t.login.password=s);if(this.isNullOrWhitespace(t.login.totp)&&null!=o&&o.startsWith("TOTP_"))return void(t.login.totp=s)}else if(t.type===Pe.Card){if(this.isNullOrWhitespace(t.card.number)&&"ccnum"===o)return t.card.number=s,void(t.card.brand=Me.getCardBrandByPatterns(t.card.number));if(this.isNullOrWhitespace(t.card.code)&&"cvv"===o)return void(t.card.code=s);if(this.isNullOrWhitespace(t.card.cardholderName)&&"cardholder"===o)return void(t.card.cardholderName=s);if(this.isNullOrWhitespace(t.card.expiration)&&"expiry"===o&&6===s.length)return t.card.expMonth=s.substr(4,2),"0"===t.card.expMonth[0]&&(t.card.expMonth=t.card.expMonth.substr(1,1)),void(t.card.expYear=s.substr(0,4));if("type"===o)return}else if(t.type===Pe.Identity){const i=t.identity;if(this.isNullOrWhitespace(i.firstName)&&"firstname"===o)return void(i.firstName=s);if(this.isNullOrWhitespace(i.lastName)&&"lastname"===o)return void(i.lastName=s);if(this.isNullOrWhitespace(i.middleName)&&"initial"===o)return void(i.middleName=s);if(this.isNullOrWhitespace(i.phone)&&"defphone"===o)return void(i.phone=s);if(this.isNullOrWhitespace(i.company)&&"company"===o)return void(i.company=s);if(this.isNullOrWhitespace(i.email)&&"email"===o)return void(i.email=s);if(this.isNullOrWhitespace(i.username)&&"username"===o)return void(i.username=s);if("address"===o){const{street:t,city:r,country:s,zip:o}=e[n];return i.address1=this.getValueOrDefault(t),i.city=this.getValueOrDefault(r),this.isNullOrWhitespace(s)||(i.country=s.toUpperCase()),void(i.postalCode=this.getValueOrDefault(o))}}const a=this.isNullOrWhitespace(e[r])?"no_name":e[r];if("password"===a&&null!=t.passwordHistory&&t.passwordHistory.some((e=>e.password===s)))return;const l="concealed"===e.k?ke.Hidden:ke.Text;this.processKvp(t,a,s,l)}))}}var Df,xf;!function(e){e.Login="001",e.CreditCard="002",e.SecureNote="003",e.Identity="004",e.Password="005",e.Document="006",e.SoftwareLicense="100",e.BankAccount="101",e.Database="102",e.DriversLicense="103",e.OutdoorLicense="104",e.Membership="105",e.Passport="106",e.RewardsProgram="107",e.SocialSecurityNumber="108",e.WirelessRouter="109",e.Server="110",e.EmailAccount="111",e.API_Credential="112",e.MedicalRecord="113"}(Df||(Df={})),function(e){e.TextOrHtml="T",e.EmailAddress="E",e.URL="U",e.Number="N",e.Password="P",e.TextArea="A",e.PhoneNumber="TEL",e.CheckBox="C"}(xf||(xf={}));class If extends pv{constructor(){super(...arguments),this.result=new uv}parse(e){return JSON.parse(e).accounts[0].vaults.forEach((e=>{e.items.forEach((e=>{if(!0===e.trashed)return;const t=this.initLoginCipher(),i=e.categoryUuid;switch(i){case Df.Login:case Df.Database:case Df.Password:case Df.WirelessRouter:case Df.Server:case Df.API_Credential:t.type=Pe.Login,t.login=new Ze;break;case Df.CreditCard:case Df.BankAccount:t.type=Pe.Card,t.card=new Me;break;case Df.SecureNote:case Df.SoftwareLicense:case Df.EmailAccount:case Df.MedicalRecord:t.type=Pe.SecureNote,t.secureNote=new tt,t.secureNote.type=De.Generic;break;case Df.Identity:case Df.DriversLicense:case Df.OutdoorLicense:case Df.Membership:case Df.Passport:case Df.RewardsProgram:case Df.SocialSecurityNumber:t.type=Pe.Identity,t.identity=new Ve}t.favorite=1===e.favIndex,this.processOverview(e.overview,t),this.processLoginFields(e,t),this.processDetails(i,e.details,t),this.parsePasswordHistory(e.details.passwordHistory,t),this.processSections(i,e.details.sections,t),this.isNullOrWhitespace(e.details.notesPlain)||(t.notes=e.details.notesPlain.split(this.newLineRegex).join("\n")+"\n"),this.convertToNoteIfNeeded(t),this.cleanupCipher(t),this.result.ciphers.push(t)}))})),this.organization&&this.moveFoldersToCollections(this.result),this.result.success=!0,Promise.resolve(this.result)}processOverview(e,t){if(null!=e){if(t.name=this.getValueOrDefault(e.title),null!=e.urls){const i=[];e.urls.forEach((e=>{this.isNullOrWhitespace(e.url)||i.push(e.url)})),t.login.uris=this.makeUriArray(i)}if(null!=e.tags&&e.tags.length>0){const t=this.capitalize(e.tags[0]);this.processFolder(this.result,t)}}}capitalize(e){return e.trim().replace(/\w\S*/g,(e=>e.replace(/^\w/,(e=>e.toUpperCase()))))}processLoginFields(e,t){null!=e.details&&null!=e.details.loginFields&&0!==e.details.loginFields.length&&e.details.loginFields.forEach((e=>{if("username"===e.designation&&""!==e.value)return t.type=Pe.Login,void(t.login.username=e.value);if("password"===e.designation&&""!==e.value)return t.type=Pe.Login,void(t.login.password=e.value);let i=e.value,n=ke.Text;switch(e.fieldType){case xf.Password:n=ke.Hidden;break;case xf.CheckBox:i=""!==e.value?"true":"false",n=ke.Boolean}this.processKvp(t,e.name,i,n)}))}processDetails(e,t,i){e===Df.Password&&null!=t&&(i.login.password=t.password)}processSections(e,t,i){null!=t&&0!==t.length&&t.forEach((t=>{null!=t.fields&&this.parseSectionFields(e,t.fields,i,t.title)}))}parseSectionFields(e,t,i,n){t.forEach((t=>{const r=Object.keys(t.value)[0],s=t;if(null==s.value||null==s.value[r]||""===s.value[r])return;const o=this.getFieldName(t.title,n),a=this.extractValue(t.value,r);if(i.type===Pe.Login){if(this.fillLogin(t,a,i))return;switch(e){case Df.Login:case Df.Database:case Df.EmailAccount:case Df.WirelessRouter:break;case Df.Server:if(this.isNullOrWhitespace(i.login.uri)&&"url"===t.id)return void(i.login.uris=this.makeUriArray(a));break;case Df.API_Credential:if(this.fillApiCredentials(t,a,i))return}}else if(i.type===Pe.Card){if(this.fillCreditCard(t,a,i))return;if(e===Df.BankAccount&&this.fillBankAccount(t,a,i))return}else if(i.type===Pe.Identity){if(this.fillIdentity(t,a,i,r))return;if("address"===r){const{street:e,city:n,country:r,zip:s,state:o}=t.value.address;return i.identity.address1=this.getValueOrDefault(e),i.identity.city=this.getValueOrDefault(n),this.isNullOrWhitespace(r)||(i.identity.country=r.toUpperCase()),i.identity.postalCode=this.getValueOrDefault(s),void(i.identity.state=this.getValueOrDefault(o))}switch(e){case Df.Identity:break;case Df.DriversLicense:if(this.fillDriversLicense(t,a,i))return;break;case Df.OutdoorLicense:if(this.fillOutdoorLicense(t,a,i))return;break;case Df.Membership:if(this.fillMembership(t,a,i))return;break;case Df.Passport:if(this.fillPassport(t,a,i))return;break;case Df.RewardsProgram:if(this.fillRewardsProgram(t,a,i))return;break;case Df.SocialSecurityNumber:if(this.fillSSN(t,a,i))return}}if("email"===r){const{email_address:e,provider:n}=t.value.email;return this.processKvp(i,o,e,ke.Text),void this.processKvp(i,"provider",n,ke.Text)}if("password"===t.title&&null!=i.passwordHistory&&i.passwordHistory.some((e=>e.password===a)))return;t.guarded&&i.reprompt===be.None&&(i.reprompt=be.Password);const l="concealed"===r?ke.Hidden:ke.Text;this.processKvp(i,o,a,l)}))}getFieldName(e,t){return this.isNullOrWhitespace(e)?this.isNullOrWhitespace(t)?"":t:e}extractValue(e,t){return"date"===t?new Date(1e3*e.date).toUTCString():"monthYear"===t?e.monthYear.toString():e[t]}fillLogin(e,t,i){const n=this.getFieldName(e.title);return this.isNullOrWhitespace(i.login.username)&&"username"===n?(i.login.username=t,!0):this.isNullOrWhitespace(i.login.password)&&"password"===n?(i.login.password=t,!0):!(!this.isNullOrWhitespace(i.login.totp)||null==e.id||!e.id.startsWith("TOTP_"))&&(i.login.totp=t,!0)}fillApiCredentials(e,t,i){const n=this.getFieldName(e.title);return this.isNullOrWhitespace(i.login.password)&&"credential"===n?(i.login.password=t,!0):!(!this.isNullOrWhitespace(i.login.uri)||"hostname"!==n)&&(i.login.uris=this.makeUriArray(t),!0)}fillCreditCard(e,t,i){if(this.isNullOrWhitespace(i.card.number)&&"ccnum"===e.id)return i.card.number=t,i.card.brand=Me.getCardBrandByPatterns(i.card.number),!0;if(this.isNullOrWhitespace(i.card.code)&&"cvv"===e.id)return i.card.code=t,!0;if(this.isNullOrWhitespace(i.card.cardholderName)&&"cardholder"===e.id)return i.card.cardholderName=t,!0;if(this.isNullOrWhitespace(i.card.expiration)&&"expiry"===e.id){const e=t.toString().trim();return i.card.expMonth=e.substring(4,6),"0"===i.card.expMonth[0]&&(i.card.expMonth=i.card.expMonth.substring(1,2)),i.card.expYear=e.substring(0,4),!0}return"type"===e.id}fillBankAccount(e,t,i){return!(!this.isNullOrWhitespace(i.card.cardholderName)||"owner"!==e.id)&&(i.card.cardholderName=t,!0)}fillIdentity(e,t,i,n){if(this.isNullOrWhitespace(i.identity.firstName)&&"firstname"===e.id)return i.identity.firstName=t,!0;if(this.isNullOrWhitespace(i.identity.lastName)&&"lastname"===e.id)return i.identity.lastName=t,!0;if(this.isNullOrWhitespace(i.identity.middleName)&&"initial"===e.id)return i.identity.middleName=t,!0;if(this.isNullOrWhitespace(i.identity.phone)&&"defphone"===e.id)return i.identity.phone=t,!0;if(this.isNullOrWhitespace(i.identity.company)&&"company"===e.id)return i.identity.company=t,!0;if(this.isNullOrWhitespace(i.identity.email)){if("email"===n){const{email_address:t,provider:n}=e.value.email;return i.identity.email=this.getValueOrDefault(t),this.processKvp(i,"provider",n,ke.Text),!0}if("email"===e.id)return i.identity.email=t,!0}return!(!this.isNullOrWhitespace(i.identity.username)||"username"!==e.id)&&(i.identity.username=t,!0)}fillDriversLicense(e,t,i){return this.isNullOrWhitespace(i.identity.firstName)&&"fullname"===e.id?(this.processFullName(i,t),!0):this.isNullOrWhitespace(i.identity.address1)&&"address"===e.id?(i.identity.address1=t,!0):this.isNullOrWhitespace(i.identity.country)&&"country"===e.id?(i.identity.country=t,!0):this.isNullOrWhitespace(i.identity.state)&&"state"===e.id?(i.identity.state=t,!0):!(!this.isNullOrWhitespace(i.identity.licenseNumber)||"number"!==e.id)&&(i.identity.licenseNumber=t,!0)}fillOutdoorLicense(e,t,i){return this.isNullOrWhitespace(i.identity.firstName)&&"name"===e.id?(this.processFullName(i,t),!0):this.isNullOrWhitespace(i.identity.country)&&"country"===e.id?(i.identity.country=t,!0):!(!this.isNullOrWhitespace(i.identity.state)||"state"!==e.id)&&(i.identity.state=t,!0)}fillMembership(e,t,i){return this.isNullOrWhitespace(i.identity.firstName)&&"member_name"===e.id?(this.processFullName(i,t),!0):this.isNullOrWhitespace(i.identity.company)&&"org_name"===e.id?(i.identity.company=t,!0):!(!this.isNullOrWhitespace(i.identity.phone)||"phone"!==e.id)&&(i.identity.phone=t,!0)}fillPassport(e,t,i){return this.isNullOrWhitespace(i.identity.firstName)&&"fullname"===e.id?(this.processFullName(i,t),!0):this.isNullOrWhitespace(i.identity.country)&&"issuing_country"===e.id?(i.identity.country=t,!0):!(!this.isNullOrWhitespace(i.identity.passportNumber)||"number"!==e.id)&&(i.identity.passportNumber=t,!0)}fillRewardsProgram(e,t,i){return this.isNullOrWhitespace(i.identity.firstName)&&"member_name"===e.id?(this.processFullName(i,t),!0):!(!this.isNullOrWhitespace(i.identity.company)||"company_name"!==e.id)&&(i.identity.company=t,!0)}fillSSN(e,t,i){return this.isNullOrWhitespace(i.identity.firstName)&&"name"===e.id?(this.processFullName(i,t),!0):!(!this.isNullOrWhitespace(i.identity.ssn)||"number"!==e.id)&&(i.identity.ssn=t,!0)}parsePasswordHistory(e,t){if(null==e||0===e.length)return;const i=e.length>5?5:e.length;t.passwordHistory=e.filter((e=>!this.isNullOrWhitespace(e.value)&&null!=e.time)).sort(((e,t)=>t.time-e.time)).slice(0,i).map((e=>{const t=new et;return t.password=e.value,t.lastUsedDate=new Date((""+e.time).length>=13?e.time:1e3*e.time),t}))}}class Uf{constructor(e,t,i){this.importRecord=e,this.property=t,this.cipher=i,this.lowerProperty=t.toLowerCase()}}const Tf=["ainfo","autosubmit","notesplain","ps","scope","tags","title","uuid","notes"];class Nf extends pv{constructor(){super(...arguments),this.loginPropertyParsers=[this.setLoginUsername,this.setLoginPassword,this.setLoginUris],this.creditCardPropertyParsers=[this.setCreditCardNumber,this.setCreditCardVerification,this.setCreditCardCardholderName,this.setCreditCardExpiry],this.identityPropertyParsers=[this.setIdentityFirstName,this.setIdentityInitial,this.setIdentityLastName,this.setIdentityUserName,this.setIdentityEmail,this.setIdentityPhone,this.setIdentityCompany]}parse(e){const t=new uv,i=this.parseCsv(e,!0,{quoteChar:'"',escapeChar:"\\"});return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{if(this.isNullOrWhitespace(this.getProp(e,"title")))return;const i=this.initLoginCipher();i.name=this.getValueOrDefault(this.getProp(e,"title"),"--"),this.setNotes(e,i),this.setCipherType(e,i);let n=null;for(const t in e){if(!e.hasOwnProperty(t)||this.isNullOrWhitespace(e[t]))continue;const r=new Uf(e,t,i);i.type===Pe.Login&&this.setKnownLoginValue(r)||(i.type===Pe.Card&&this.setKnownCreditCardValue(r)||i.type===Pe.Identity&&this.setKnownIdentityValue(r)||(n=this.setUnknownValue(r,n)))}i.type===Pe.Login&&!this.isNullOrWhitespace(n)&&this.isNullOrWhitespace(i.login.username)&&-1===n.indexOf("://")&&(i.login.username=n),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}getProp(e,t){return Object.entries(e).reduce(((e,t)=>(e[t[0].toLowerCase()]=t[1],e)),{})[t.toLowerCase()]}getPropByRegexp(e,t){const i=Object.keys(e).reduce(((e,i)=>(i.match(t)&&e.push(i),e)),[]);return 0===i.length?null:e[i[0]]}getPropIncluding(e,t){const i=Object.keys(e).reduce(((e,i)=>(i.toLowerCase().includes(t.toLowerCase())&&e.push(i),e)),[]);return 0===i.length?null:e[i[0]]}setNotes(e,t){t.notes=this.getValueOrDefault(this.getProp(e,"notesPlain"),"")+"\n"+this.getValueOrDefault(this.getProp(e,"notes"),"")+"\n",t.notes.trim()}setKnownLoginValue(e){return this.loginPropertyParsers.reduce(((t,i)=>(t||(t=i.bind(this)(e)),t)),!1)}setKnownCreditCardValue(e){return this.creditCardPropertyParsers.reduce(((t,i)=>(t||(t=i.bind(this)(e)),t)),!1)}setKnownIdentityValue(e){return this.identityPropertyParsers.reduce(((t,i)=>(t||(t=i.bind(this)(e)),t)),!1)}setUnknownValue(e,t){if(-1===Tf.indexOf(e.lowerProperty)&&!e.lowerProperty.startsWith("section:")&&!e.lowerProperty.startsWith("section ")){if(null==t&&"email"===e.lowerProperty)return e.importRecord[e.property];if("created date"===e.lowerProperty||"modified date"===e.lowerProperty){const t=new Date(1e3*parseInt(e.importRecord[e.property],10)).toUTCString();return this.processKvp(e.cipher,"1Password "+e.property,t),null}e.lowerProperty.includes("password")||e.lowerProperty.includes("key")||e.lowerProperty.includes("secret")?this.processKvp(e.cipher,e.property,e.importRecord[e.property],ke.Hidden):this.processKvp(e.cipher,e.property,e.importRecord[e.property])}return null}setIdentityFirstName(e){return!(!this.isNullOrWhitespace(e.cipher.identity.firstName)||!e.lowerProperty.includes("first name"))&&(e.cipher.identity.firstName=e.importRecord[e.property],!0)}setIdentityInitial(e){return!(!this.isNullOrWhitespace(e.cipher.identity.middleName)||!e.lowerProperty.includes("initial"))&&(e.cipher.identity.middleName=e.importRecord[e.property],!0)}setIdentityLastName(e){return!(!this.isNullOrWhitespace(e.cipher.identity.lastName)||!e.lowerProperty.includes("last name"))&&(e.cipher.identity.lastName=e.importRecord[e.property],!0)}setIdentityUserName(e){return!(!this.isNullOrWhitespace(e.cipher.identity.username)||!e.lowerProperty.includes("username"))&&(e.cipher.identity.username=e.importRecord[e.property],!0)}setIdentityCompany(e){return!(!this.isNullOrWhitespace(e.cipher.identity.company)||!e.lowerProperty.includes("company"))&&(e.cipher.identity.company=e.importRecord[e.property],!0)}setIdentityPhone(e){return!(!this.isNullOrWhitespace(e.cipher.identity.phone)||!e.lowerProperty.includes("default phone"))&&(e.cipher.identity.phone=e.importRecord[e.property],!0)}setIdentityEmail(e){return!(!this.isNullOrWhitespace(e.cipher.identity.email)||!e.lowerProperty.includes("email"))&&(e.cipher.identity.email=e.importRecord[e.property],!0)}setCreditCardNumber(e){return!(!this.isNullOrWhitespace(e.cipher.card.number)||!e.lowerProperty.includes("number"))&&(e.cipher.card.number=e.importRecord[e.property],e.cipher.card.brand=Me.getCardBrandByPatterns(e.cipher.card.number),!0)}setCreditCardVerification(e){return!(!this.isNullOrWhitespace(e.cipher.card.code)||!e.lowerProperty.includes("verification number"))&&(e.cipher.card.code=e.importRecord[e.property],!0)}setCreditCardCardholderName(e){return!(!this.isNullOrWhitespace(e.cipher.card.cardholderName)||!e.lowerProperty.includes("cardholder name"))&&(e.cipher.card.cardholderName=e.importRecord[e.property],!0)}setCreditCardExpiry(e){return!(!this.isNullOrWhitespace(e.cipher.card.expiration)||!e.lowerProperty.includes("expiry date")||7!==e.importRecord[e.property].length)&&(e.cipher.card.expMonth=e.importRecord[e.property].substr(0,2),"0"===e.cipher.card.expMonth[0]&&(e.cipher.card.expMonth=e.cipher.card.expMonth.substr(1,1)),e.cipher.card.expYear=e.importRecord[e.property].substr(3,4),!0)}setLoginPassword(e){return!(!this.isNullOrWhitespace(e.cipher.login.password)||"password"!==e.lowerProperty)&&(e.cipher.login.password=e.importRecord[e.property],!0)}setLoginUsername(e){return!(!this.isNullOrWhitespace(e.cipher.login.username)||"username"!==e.lowerProperty)&&(e.cipher.login.username=e.importRecord[e.property],!0)}setLoginUris(e){if((null==e.cipher.login.uris||0===e.cipher.login.uris.length)&&"urls"===e.lowerProperty){const t=e.importRecord[e.property].split(this.newLineRegex);return e.cipher.login.uris=this.makeUriArray(t),!0}return"url"===e.lowerProperty&&(null==e.cipher.login.uris&&(e.cipher.login.uris=[]),e.cipher.login.uris.concat(this.makeUriArray(e.importRecord[e.property])),!0)}}class Rf extends Nf{setCipherType(e,t){switch(this.getValueOrDefault(this.getProp(e,"type"),"Login")){case"Credit Card":t.type=Pe.Card,t.card=new Me,Tf.push("type");break;case"Identity":t.type=Pe.Identity,t.identity=new Ve,Tf.push("type");break;case"Login":case"Secure Note":Tf.push("type")}}}class Ef extends Nf{constructor(){super(),this.identityPropertyParsers.push(this.setIdentityAddress)}setCipherType(e,t){t.type=Pe.Login,t.login=new Ze,this.isNullOrWhitespace(this.getPropByRegexp(e,/\d+: number/i))||this.isNullOrWhitespace(this.getPropByRegexp(e,/\d+: expiry date/i))||(t.type=Pe.Card,t.card=new Me),this.isNullOrWhitespace(this.getPropByRegexp(e,/name \d+: first name/i))&&this.isNullOrWhitespace(this.getPropByRegexp(e,/name \d+: initial/i))&&this.isNullOrWhitespace(this.getPropByRegexp(e,/name \d+: last name/i))&&this.isNullOrWhitespace(this.getPropByRegexp(e,/internet \d+: email/i))||(t.type=Pe.Identity,t.identity=new Ve)}setIdentityAddress(e){return!!e.lowerProperty.match(/address \d+: address/i)&&(this.processKvp(e.cipher,"address",e.importRecord[e.property]),!0)}setCreditCardExpiry(e){if(this.isNullOrWhitespace(e.cipher.card.expiration)&&e.lowerProperty.includes("expiry date")){const t=e.importRecord[e.property].split("/");return e.cipher.card.expMonth=t[0],"0"===e.cipher.card.expMonth[0]&&2===e.cipher.card.expMonth.length&&(e.cipher.card.expMonth=e.cipher.card.expMonth.substr(1,1)),e.cipher.card.expYear=t[2].length>4?t[2].substr(0,4):t[2],!0}return!1}}class Ff extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!1);if(null==i)return t.success=!1,Promise.resolve(t);let n=null;return i.forEach((e=>{if(null==n)return void(n=e.map((e=>e)));if(e.length<2||e.length!==n.length)return;if(!this.isNullOrWhitespace(e[1]))if(this.organization){e[1].split(",").forEach((e=>{e=e.trim();let i=!0,n=t.collections.length;for(let r=0;r0?i[0].trim():null;this.processFolder(t,n)}const i=this.initLoginCipher();i.name=this.getValueOrDefault(e[0],"--");for(let t=2;t-1?i.login.username=e[t]:this.passwordFieldNames.indexOf(r)>-1?i.login.password=e[t]:this.uriFieldNames.indexOf(r)>-1?i.login.uris=this.makeUriArray(e[t]):this.processKvp(i,n[t],e[t]))}this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t)}}class Mf extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{this.processFolder(t,this.getValue("category",e));const i=this.initLoginCipher();i.notes=this.getValue("description",e),i.name=this.getValueOrDefault(this.getValue("title",e),"--"),i.login.username=this.getValue("username",e),i.login.password=this.getValue("password",e),i.login.uris=this.makeUriArray(this.getValue("site",e)),this.processKvp(i,"Password 2",this.getValue("password2",e)),this.cleanupCipher(i),t.ciphers.push(i)})),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}getValue(e,t){return this.getValueOrDefault(t[e],this.getValueOrDefault(t[" "+e]))}}class Kf extends pv{parse(e){const t=new uv,i=JSON.parse(e);return null==i||null==i.passwords||0===i.passwords.length?(t.success=!1,Promise.resolve(t)):1==i.encrypted?(t.success=!1,t.errorMessage="Unable to import an encrypted passky backup.",Promise.resolve(t)):(i.passwords.forEach((e=>{const i=this.initLoginCipher();i.name=e.website,i.login.username=e.username,i.login.password=e.password,i.login.uris=this.makeUriArray(e.website),i.notes=e.message,this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class Lf extends pv{parse(e){const t=new uv,i=JSON.parse(e);return null==i||0===i.length?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{if(null!=e.tags&&e.tags.length>0){const i=e.tags[0].text;this.processFolder(t,i)}const i=this.initLoginCipher();i.name=e.label,i.login.username=this.getValueOrDefault(e.username),this.isNullOrWhitespace(i.login.username)?i.login.username=this.getValueOrDefault(e.email):this.isNullOrWhitespace(e.email)||(i.notes="Email: "+e.email+"\n"),i.login.password=this.getValueOrDefault(e.password),i.login.uris=this.makeUriArray(e.url),i.notes+=this.getValueOrDefault(e.description,""),null!=e.otp&&(i.login.totp=this.getValueOrDefault(e.otp.secret)),null!=e.custom_fields&&e.custom_fields.forEach((e=>{switch(e.field_type){case"text":case"password":this.processKvp(i,e.label,e.value)}})),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)})),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}}class zf extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{const i=this.isNullOrWhitespace(e.Tags)?null:JSON.parse(e.Tags),n=null!=i&&null!=i.tags&&i.tags.length>0?i.tags.map((e=>{try{const t=JSON.parse(e);return this.getValueOrDefault(t.tag)}catch(e){}return null})).filter((e=>!this.isNullOrWhitespace(e))):null;this.organization&&null!=n&&n.length>0?n.forEach((e=>{let i=!0,n=t.collections.length;for(let r=0;r0&&this.processFolder(t,n[0]);const r=this.initLoginCipher();r.notes=this.getValueOrDefault(e.Notes,""),r.notes+="\n\n"+this.getValueOrDefault(e["Shared Notes"],"")+"\n",r.name=this.getValueOrDefault(e["Entry Name"],"--"),r.login.username=this.getValueOrDefault(e["User ID"]),r.login.password=this.getValueOrDefault(e.Password),r.login.uris=this.makeUriArray(e.URL),null!=e.__parsed_extra&&e.__parsed_extra.length>0&&e.__parsed_extra.forEach((e=>{this.isNullOrWhitespace(e)||(r.notes+="\n"+e)}));const s=this.isNullOrWhitespace(e["Extra Fields"])?null:JSON.parse(e["Extra Fields"]),o=null!=s&&null!=s.extraFields&&s.extraFields.length>0?s.extraFields.map((e=>{try{return JSON.parse(e)}catch(e){}return null})):null;null!=o&&o.forEach((e=>{null!=e&&this.processKvp(r,e.name,e.data)})),this.cleanupCipher(r),t.ciphers.push(r)})),t.success=!0,Promise.resolve(t))}}class Vf extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!1);if(null==i)return t.success=!1,Promise.resolve(t);let n=!0;return i.forEach((e=>{if(5!==e.length&&e.length<9)return;const i=10===e.length&&"0"===e[0],r=this.initLoginCipher();if(r.name=this.getValueOrDefault(e[i?1:0],"--"),r.login.username=this.getValueOrDefault(e[i?2:1]),r.login.password=this.getValueOrDefault(e[i?3:2]),5===e.length)n=!1,r.notes=this.getValueOrDefault(e[4]),r.login.uris=this.makeUriArray(e[3]);else{const n=this.getValueOrDefault(e[i?9:8],"(None)");let s="(None)"!==n?n.split("\\").join("/"):null;null!=s&&(s=n.split(" > ").join("/"),s=n.split(">").join("/")),this.processFolder(t,s),r.notes=this.getValueOrDefault(e[i?5:3]),r.login.uris=this.makeUriArray(e[4])}this.convertToNoteIfNeeded(r),this.cleanupCipher(r),t.ciphers.push(r)})),n&&this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}}class Bf extends pv{parse(e){const t=new uv,i=JSON.parse(e);if(null==i||null==i.items)return t.success=!1,Promise.resolve(t);const n=new Map;i.folders.forEach((e=>{n.set(e.id,e.name)}));const r=new Map;return n.forEach(((e,i)=>{r.set(i,t.folders.length);const n=new Fy;n.name=e,t.folders.push(n)})),i.items.forEach((e=>{const i=this.initLoginCipher();if(i.name=this.getValueOrDefault(e.name,"--"),i.login.uris=this.makeUriArray(e.login_url),null!=e.folder&&r.has(e.folder)&&t.folderRelationships.push([t.ciphers.length,r.get(e.folder)]),null!=e.identifiers){this.isNullOrWhitespace(e.identifiers.notes)||(i.notes=e.identifiers.notes.split("\\r\\n").join("\n").split("\\n").join("\n")),"CreditCard"===e.type&&(i.card=new Me,i.type=Pe.Card);for(const t in e.identifiers){if(!e.identifiers.hasOwnProperty(t))continue;const n=e.identifiers[t],r=null!=n?n.toString():null;if(!this.isNullOrWhitespace(r)&&"notes"!==t&&"ignoreItemInSecurityScore"!==t)if("custom_fields"!==t){if(i.type===Pe.Card){if("cardNumber"===t){i.card.number=r,i.card.brand=Me.getCardBrandByPatterns(i.card.number);continue}if("nameOnCard"===t){i.card.cardholderName=r;continue}if("security_code"===t){i.card.code=r;continue}if("expires"===t){try{const e=new Date(r);i.card.expYear=e.getFullYear().toString(),i.card.expMonth=(e.getMonth()+1).toString()}catch(e){}continue}if("cardType"===t)continue}else{if(("username"===t||"email"===t)&&this.isNullOrWhitespace(i.login.username)){i.login.username=r;continue}if("password"===t){i.login.password=r;continue}if("totp"===t){i.login.totp=r;continue}if((null==i.login.uris||0===i.login.uris.length)&&this.uriFieldNames.indexOf(t)>-1){i.login.uris=this.makeUriArray(r);continue}}this.processKvp(i,t,r)}else n.forEach((e=>{this.processKvp(i,e.name,e.value)}))}this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)}})),t.success=!0,Promise.resolve(t)}}class _f extends pv{parse(e){const t=new uv,i=this.parseXml(e);if(null==i)return t.success=!1,Promise.resolve(t);const n=i.querySelectorAll("PasswordManager > record");return Array.from(n).forEach((e=>{const i=this.querySelectorDirectChild(e,"Category"),n=null==i||this.isNullOrWhitespace(i.textContent)||"Unfiled"===i.textContent?null:i.textContent;this.processFolder(t,n);const r=this.querySelectorDirectChild(e,"Account-Name"),s=this.querySelectorDirectChild(e,"User-Id"),o=this.querySelectorDirectChild(e,"Password"),a=this.querySelectorDirectChild(e,"URL"),l=this.querySelectorDirectChild(e,"Notes"),c=this.initLoginCipher();c.name=null!=r?this.getValueOrDefault(r.textContent,"--"):"--",c.notes=null!=l?this.getValueOrDefault(l.textContent):"",c.login.username=null!=s?this.getValueOrDefault(s.textContent):null,c.login.password=null!=o?this.getValueOrDefault(o.textContent):null,c.login.uris=null!=a?this.makeUriArray(a.textContent):null;const d=[];for(let e=1;e<=10;e++)d.push("Attribute-"+e);this.querySelectorAllDirectChild(e,d.join(",")).forEach((e=>{this.isNullOrWhitespace(e.textContent)||"null"===e.textContent||this.processKvp(c,e.tagName,e.textContent)})),this.cleanupCipher(c),t.ciphers.push(c)})),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}}class jf extends pv{parse(e){const t=new uv,i=this.parseXml(e);if(null==i)return t.success=!1,Promise.resolve(t);const n=i.querySelector("passwordsafe");if(null==n)return t.errorMessage="Missing `passwordsafe` node.",t.success=!1,Promise.resolve(t);const r=n.getAttribute("delimiter"),s=i.querySelectorAll("passwordsafe > entry");return Array.from(s).forEach((e=>{const i=this.querySelectorDirectChild(e,"group"),n=null==i||this.isNullOrWhitespace(i.textContent)?null:i.textContent.split(".").join("/");this.processFolder(t,n);const s=this.querySelectorDirectChild(e,"title"),o=this.querySelectorDirectChild(e,"username"),a=this.querySelectorDirectChild(e,"email"),l=this.querySelectorDirectChild(e,"password"),c=this.querySelectorDirectChild(e,"url"),d=this.querySelectorDirectChild(e,"notes"),u=this.initLoginCipher();u.name=null!=s?this.getValueOrDefault(s.textContent,"--"):"--",u.notes=null!=d?this.getValueOrDefault(d.textContent,"").split(r).join("\n"):null,u.login.username=null!=o?this.getValueOrDefault(o.textContent):null,u.login.password=null!=l?this.getValueOrDefault(l.textContent):null,u.login.uris=null!=c?this.makeUriArray(c.textContent):null,this.isNullOrWhitespace(u.login.username)&&null!=a?u.login.username=this.getValueOrDefault(a.textContent):null==a||this.isNullOrWhitespace(a.textContent)||(u.notes=this.isNullOrWhitespace(u.notes)?"Email: "+a.textContent:u.notes+"\nEmail: "+a.textContent),this.cleanupCipher(u),t.ciphers.push(u)})),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}}class $f extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!1);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{if(e.length<1)return;e.length>5&&this.processFolder(t,e[5]);const i=this.initLoginCipher();i.name=this.getValueOrDefault(e[0],"--"),e.length>4&&(i.notes=this.getValueOrDefault(e[4],"").split("¬").join("\n")),e.length>2&&(i.login.username=this.getValueOrDefault(e[2])),e.length>3&&(i.login.password=this.getValueOrDefault(e[3])),e.length>1&&(i.login.uris=this.makeUriArray(e[1])),this.cleanupCipher(i),t.ciphers.push(i)})),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}}var Wf;!function(e){e[e.ACTIVE=1]="ACTIVE",e[e.TRASHED=2]="TRASHED"}(Wf||(Wf={}));class qf extends pv{constructor(e){super(),this.i18nService=e}parse(e){const t=new uv,i=JSON.parse(e);if(null==i||null==i.vaults)return t.success=!1,Promise.resolve(t);if(i.encrypted)return t.success=!1,t.errorMessage=this.i18nService.t("unsupportedEncryptedImport"),Promise.resolve(t);for(const[,e]of Object.entries(i.vaults))for(const i of e.items){if(i.state==Wf.TRASHED)continue;this.processFolder(t,e.name);const n=this.initLoginCipher();switch(n.name=this.getValueOrDefault(i.data.metadata.name,"--"),n.notes=this.getValueOrDefault(i.data.metadata.note),i.data.type){case"login":{const e=i.data.content;n.login.uris=this.makeUriArray(e.urls),n.login.username=this.getValueOrDefault(e.username),n.login.password=this.getValueOrDefault(e.password),n.login.totp=this.getValueOrDefault(e.totpUri);for(const e of i.data.extraFields)this.processKvp(n,e.fieldName,"totp"==e.type?e.data.totpUri:e.data.content,"text"==e.type?ke.Text:ke.Hidden);break}case"note":n.type=Pe.SecureNote,n.secureNote=new tt,n.secureNote.type=De.Generic;break;case"creditCard":{const e=i.data.content;n.type=Pe.Card,n.card=new Me,n.card.cardholderName=this.getValueOrDefault(e.cardholderName),n.card.number=this.getValueOrDefault(e.number),n.card.brand=Me.getCardBrandByPatterns(e.number),n.card.code=this.getValueOrDefault(e.verificationNumber),this.isNullOrWhitespace(e.expirationDate)||(n.card.expMonth=e.expirationDate.substring(0,2),n.card.expMonth=n.card.expMonth.replace(/^0+/,""),n.card.expYear=e.expirationDate.substring(2,6)),this.isNullOrWhitespace(e.pin)||this.processKvp(n,"PIN",e.pin,ke.Hidden);break}}this.cleanupCipher(n),t.ciphers.push(n)}return this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}}class Hf extends pv{constructor(){super(...arguments),this.WEBSITE_mappedValues=new Set(["type","name","website_password_title","website_password_notes","website_password_username","website_password_password","website_password_url","autosubmit","website_password_auto_submit","urlfilter","website_password_url_filter"]),this.APP_PWD_mappedValues=new Set(["type","name","application_password_title","application_password_notes","application_password_username","application_password_password"]),this.BOOKMARK_mappedValues=new Set(["type","name","bookmark_title","bookmark_notes","bookmark_url"]),this.NOTES_mappedValues=new Set(["type","name","note_title","note_notes"]),this.TOTP_mappedValues=new Set(["type","name","totp_title","totp_notes","totp_code"]),this.ENV_VARIABLES_mappedValues=new Set(["type","name","environment_variables_title","environment_variables_notes","environment_variables_variables"]),this.GPG_mappedValues=new Set(["type","name","mail_gpg_own_key_title","mail_gpg_own_key_public","mail_gpg_own_key_name","mail_gpg_own_key_email","mail_gpg_own_key_private"])}parse(e){const t=new uv,i=JSON.parse(e);return null==i?(t.success=!1,Promise.resolve(t)):(this.parseFolders(t,i.folders),this.handleItemParsing(t,i.items),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}parseFolders(e,t,i){null!=t&&0!==t.length&&t.forEach((t=>{const n=null!=t.items&&t.items.length>0,r=null!=t.folders&&t.folders.length>0;(n||r)&&(p.isNullOrWhitespace(i)||(t.name=i+"/"+t.name),r&&this.parseFolders(e,t.folders,t.name),n?this.handleItemParsing(e,t.items,t.name):this.processFolder(e,t.name,n))}))}handleItemParsing(e,t,i){null!=t&&0!==t.length&&t.forEach((t=>{const n=this.parsePsonoItem(t);this.processFolder(e,i,!0),this.cleanupCipher(n),e.ciphers.push(n)}))}parsePsonoItem(e){const t=this.initLoginCipher();switch(e.type){case"website_password":this.parseWebsiteLogins(e,t);break;case"application_password":this.parseApplicationPasswords(e,t);break;case"environment_variables":this.parseEnvironmentVariables(e,t);break;case"totp":this.parseTOTP(e,t);break;case"bookmark":this.parseBookmarks(e,t);break;case"note":this.parseNotes(e,t)}return t}parseWebsiteLogins(e,t){var i;null!=e&&"website_password"==e.type&&(t.name=e.website_password_title,t.notes=e.website_password_notes,t.login.username=e.website_password_username,t.login.password=e.website_password_password,t.login.uris=this.makeUriArray(e.website_password_url),this.processKvp(t,"website_password_auto_submit",null===(i=e.website_password_auto_submit)||void 0===i?void 0:i.toString(),ke.Boolean),this.processKvp(t,"website_password_url_filter",e.website_password_url_filter),this.importUnmappedFields(t,e,this.WEBSITE_mappedValues))}parseApplicationPasswords(e,t){null!=e&&"application_password"==e.type&&(t.name=e.application_password_title,t.notes=e.application_password_notes,t.login.username=e.application_password_username,t.login.password=e.application_password_password,this.importUnmappedFields(t,e,this.APP_PWD_mappedValues))}parseBookmarks(e,t){null!=e&&"bookmark"==e.type&&(t.name=e.bookmark_title,t.notes=e.bookmark_notes,t.login.uris=this.makeUriArray(e.bookmark_url),this.importUnmappedFields(t,e,this.BOOKMARK_mappedValues))}parseNotes(e,t){null!=e&&"note"==e.type&&(t.type=Pe.SecureNote,t.secureNote=new tt,t.secureNote.type=De.Generic,t.name=e.note_title,t.notes=e.note_notes,this.importUnmappedFields(t,e,this.NOTES_mappedValues))}parseTOTP(e,t){null!=e&&"totp"==e.type&&(t.name=e.totp_title,t.notes=e.totp_notes,t.login.totp=e.totp_code,this.importUnmappedFields(t,e,this.TOTP_mappedValues))}parseEnvironmentVariables(e,t){null!=e&&"environment_variables"==e.type&&(t.type=Pe.SecureNote,t.secureNote=new tt,t.secureNote.type=De.Generic,t.name=e.environment_variables_title,t.notes=e.environment_variables_notes,e.environment_variables_variables.forEach((e=>{this.processKvp(t,e.key,e.value)})),this.importUnmappedFields(t,e,this.ENV_VARIABLES_mappedValues))}parseGPG(e,t){null!=e&&"mail_gpg_own_key"==e.type&&(t.type=Pe.SecureNote,t.secureNote=new tt,t.secureNote.type=De.Generic,t.name=e.mail_gpg_own_key_title,t.notes=e.mail_gpg_own_key_public,this.processKvp(t,"mail_gpg_own_key_name",e.mail_gpg_own_key_name),this.processKvp(t,"mail_gpg_own_key_email",e.mail_gpg_own_key_email),this.processKvp(t,"mail_gpg_own_key_private",e.mail_gpg_own_key_private,ke.Hidden),this.importUnmappedFields(t,e,this.GPG_mappedValues))}importUnmappedFields(e,t,i){Object.keys(t).filter((e=>!i.has(e))).forEach((i=>{const n=t;this.processKvp(e,i,n[i].toString())}))}}class Gf extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{if("true"===e.trash)return;const i=this.initLoginCipher();if(i.name=this.getValueOrDefault(e.name),i.notes=this.getValueOrDefault(e.notes),"LoginItem"===e.type)i.login.uris=this.makeUriArray(e.website),i.login.password=this.getValueOrDefault(e.password),i.login.username=this.getValueOrDefault(e.username);else if("CreditCardItem"===e.type){i.type=Pe.Card,i.card=new Me,i.card.cardholderName=this.getValueOrDefault(e.cardholder),i.card.number=this.getValueOrDefault(e.number),i.card.brand=Me.getCardBrandByPatterns(i.card.number),i.card.code=this.getValueOrDefault(e.verification);try{const t=this.getValueOrDefault(e.expiryMonth);if(null!=t){const e=parseInt(t,null);null!=e&&e>=1&&e<=12&&(i.card.expMonth=e.toString())}}catch(e){}try{const t=this.getValueOrDefault(e.expiryYear);if(null!=t){const e=parseInt(t,null);null!=e&&(i.card.expYear=e.toString())}}catch(e){}const t=this.getValueOrDefault(e.pin);null!=t&&this.processKvp(i,"PIN",t);const n=this.getValueOrDefault(e.zipCode);null!=n&&this.processKvp(i,"Zip Code",n)}this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class Jf extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);if(null==i)return t.success=!1,Promise.resolve(t);let n=1;return i.forEach((e=>{const r=!this.isNullOrWhitespace(e.Folder)&&e.Folder.startsWith("/")?e.Folder.replace("/",""):e.Folder,s=this.isNullOrWhitespace(r)?null:r;this.processFolder(t,s);const o=this.initLoginCipher();if(o.notes=this.getValueOrDefault(e.Note),o.name=this.getValueOrDefault(e.Name,"--"),o.login.username=this.getValueOrDefault(e.Login),o.login.password=this.getValueOrDefault(e.Pwd),o.login.uris=this.makeUriArray(e.Url),!this.isNullOrWhitespace(e.Rf_fields)){let t=[e.Rf_fields];null!=e.__parsed_extra&&e.__parsed_extra.length>0&&(t=t.concat(e.__parsed_extra)),t.forEach((e=>{const t=e.split(":");if(t.length<3)return;const i="-no-name-"===t[0]?null:t[0],n=4===t.length&&"rck"===t[2]?t[1]:t[2];this.processKvp(o,i,n)}))}this.convertToNoteIfNeeded(o),this.cleanupCipher(o),n===i.length&&"--"===o.name&&this.isNullOrWhitespace(o.login.password)||(t.ciphers.push(o),n++)})),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}}class Yf extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{var i;const n=this.initLoginCipher();n.name=this.getValueOrDefault(e.Title,"--"),n.login.username=this.getValueOrDefault(e.Username),n.login.password=this.getValueOrDefault(e.Password),n.login.uris=this.makeUriArray(null!==(i=e.Url)&&void 0!==i?i:e.URL),n.login.totp=this.getValueOrDefault(e.OTPAuth),n.notes=this.getValueOrDefault(e.Notes),this.cleanupCipher(n),t.ciphers.push(n)})),t.success=!0,Promise.resolve(t))}}class Qf extends pv{parse(e){const t=new uv,i=this.parseXml(e);if(null==i)return t.success=!1,Promise.resolve(t);if(null==i.querySelector("database"))return t.errorMessage="Missing `database` node.",t.success=!1,Promise.resolve(t);const n=new Map;return Array.from(i.querySelectorAll("database > label")).forEach((e=>{const i=e.getAttribute("name"),r=e.getAttribute("id");if(!this.isNullOrWhitespace(i)&&!this.isNullOrWhitespace(r)){n.set(r,t.folders.length);const e=new Fy;e.name=i,t.folders.push(e)}})),Array.from(i.querySelectorAll("database > card")).forEach((e=>{if("true"===e.getAttribute("template")||"true"===e.getAttribute("deleted"))return;const i=this.querySelectorDirectChild(e,"label_id");if(null!=i){const e=i.textContent;!this.isNullOrWhitespace(e)&&n.has(e)&&t.folderRelationships.push([t.ciphers.length,n.get(e)])}const r=this.initLoginCipher();r.name=this.getValueOrDefault(e.getAttribute("title"),"--"),"true"===e.getAttribute("star")&&(r.favorite=!0);"note"===e.getAttribute("type")?(r.type=Pe.SecureNote,r.secureNote=new tt,r.secureNote.type=De.Generic):Array.from(this.querySelectorAllDirectChild(e,"field")).forEach((e=>{const t=e.textContent;if(this.isNullOrWhitespace(t))return;const i=e.getAttribute("name"),n=this.getValueOrDefault(e.getAttribute("type"),"").toLowerCase();"login"===n?r.login.username=t:"password"===n||"secret"===n?this.processKvp(r,i,t,ke.Hidden):"one_time_password"===n?r.login.totp=t:"notes"===n?r.notes+=t+"\n":"weblogin"===n||"website"===n?r.login.uris.push(...this.makeUriArray(t)):this.processKvp(r,i,t)})),Array.from(this.querySelectorAllDirectChild(e,"notes")).forEach((e=>{r.notes+=e.textContent+"\n"})),this.setPassword(r),this.cleanupCipher(r),t.ciphers.push(r)})),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}setPassword(e){const t=e.fields.filter((e=>e.type===ke.Hidden));if(!t.length)return;let i;for(const n of t)if(this.passwordFieldNames.includes(n.name.toLowerCase())){i=n,e.fields=e.fields.filter((e=>e!==i));break}i||(i=t[0]),e.login.password=i.value}}class Xf extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(this.nameFromUrl(e.url),"--"),i.notes=this.getValueOrDefault(e.notes),i.login.username=this.getValueOrDefault(e.username),i.login.password=this.getValueOrDefault(e.password),i.login.uris=this.makeUriArray(e.url),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class Zf extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);if(null==i)return t.success=!1,Promise.resolve(t);const n=Object.keys(i[0]).find((e=>/url/i.test(e)));return i.forEach((e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.Title),i.notes=this.getValueOrDefault(e.Comment),i.login.uris=this.makeUriArray(e[n]),i.login.password=this.getValueOrDefault(e.Password),i.login.username=this.getValueOrDefault(e.Username),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t)}}class eg extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!1);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{if(e.length<3)return;this.processFolder(t,this.getValueOrDefault(e[e.length-1]));const i=this.initLoginCipher();i.notes=this.getValueOrDefault(e[e.length-2],""),i.name=this.getValueOrDefault(e[1],"--"),"Web Logins"===e[0]||"Servers"===e[0]||"Email Accounts"===e[0]?(i.login.username=this.getValueOrDefault(e[2]),i.login.password=this.getValueOrDefault(e[3]),i.login.uris=this.makeUriArray(e[4]),this.parseFieldsToNotes(i,5,e)):this.parseFieldsToNotes(i,2,e),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)})),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}parseFieldsToNotes(e,t,i){for(let n=t;n Database > Logins > Login");return Array.from(n).forEach((e=>{const n=e.getAttribute("ID");if(this.isNullOrWhitespace(n))return;const r=e.getAttribute("Name"),s=e.getAttribute("Password");let o=null,a=null,l=null,c=null,d=null;const u=i.querySelector('root > Database > Accounts > Account > LoginLinks > Login[SourceLoginID="'+n+'"]');if(null!=u){const e=u.parentElement.parentElement;null!=e&&(o=e.getAttribute("Name"),a=e.getAttribute("Link"),c=e.getAttribute("ParentID"),l=e.getAttribute("Comments"),this.isNullOrWhitespace(l)||(l=l.split("/n").join("\n")))}this.isNullOrWhitespace(c)||(d=this.buildGroupText(i,c,""),this.processFolder(t,d));const h=this.initLoginCipher();h.name=this.getValueOrDefault(o,"--"),h.notes=this.getValueOrDefault(l),h.login.username=this.getValueOrDefault(r),h.login.password=this.getValueOrDefault(s),h.login.uris=this.makeUriArray(a),this.cleanupCipher(h),t.ciphers.push(h)})),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}buildGroupText(e,t,i){const n=e.querySelector('root > Database > Groups > Group[ID="'+t+'"]');return null==n?i:(this.isNullOrWhitespace(i)||(i="/"+i),i=n.getAttribute("Name")+i,this.buildGroupText(e,n.getAttribute("ParentID"),i))}}const ig=["kind","autologin","favorite","hexcolor","protectedwithpassword","subdomainonly","type","tk_export_version","note","title","document_content"];class ng extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{const i=this.initLoginCipher();if(i.favorite="true"===this.getValueOrDefault(e.favorite,"").toLowerCase(),i.name=this.getValueOrDefault(e.name,"--"),i.notes=this.getValueOrDefault(e.memo,""),i.login.username=this.getValueOrDefault(e.login),i.login.password=this.getValueOrDefault(e.password),i.login.uris=this.makeUriArray(e.url),"login"!==e.kind&&(i.name=this.getValueOrDefault(e.title,"--"),i.notes=this.getValueOrDefault(e.note,"")),"cc"===e.kind){if(i.type=Pe.Card,i.card=new Me,i.card.cardholderName=this.getValueOrDefault(e.cardholder),i.card.number=this.getValueOrDefault(e.number),i.card.brand=Me.getCardBrandByPatterns(i.card.number),!this.isNullOrWhitespace(e.expiryDate))try{const t=new Date(e.expiryDate);i.card.expYear=t.getFullYear().toString(),i.card.expMonth=(t.getMonth()+1).toString()}catch(e){}}else if("login"!==e.kind){i.type=Pe.SecureNote,i.secureNote=new tt,i.secureNote.type=De.Generic,this.isNullOrWhitespace(i.notes)||(i.notes=this.getValueOrDefault(e.document_content,""));for(const t in e)e.hasOwnProperty(t)&&ig.indexOf(t.toLowerCase())<0&&!this.isNullOrWhitespace(e[t])&&this.processKvp(i,t,e[t])}this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class rg extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!1);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{if(5!==e.length)return;const i=this.initLoginCipher();i.name=this.getValueOrDefault(e[0],"--"),i.notes=this.getValueOrDefault(e[4]),i.login.username=this.getValueOrDefault(e[1]),i.login.password=this.getValueOrDefault(e[2]),i.login.uris=this.makeUriArray(e[3]),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class sg extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.Name,"--"),i.login.username=this.getValueOrDefault(e["User name"]),i.login.password=this.getValueOrDefault(e.Password),i.login.uris=this.makeUriArray(e.URL),this.cleanupCipher(i),t.ciphers.push(i)})),t.success=!0,Promise.resolve(t))}}class og extends pv{parse(e){const t=new uv,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach((e=>{if(this.isNullOrWhitespace(e["Password Name"])&&this.isNullOrWhitespace(e["Secret Name"]))return;this.processFolder(t,this.getValueOrDefault(e.ChamberName));const i=this.initLoginCipher();i.favorite="1"===this.getValueOrDefault(e.Favorite,"0"),i.notes=this.getValueOrDefault(e.Notes),i.name=this.getValueOrDefault(e["Password Name"],this.getValueOrDefault(e["Secret Name"],"--")),i.login.uris=this.makeUriArray(this.getValueOrDefault(e["Password URL"],this.getValueOrDefault(e["Secret URL"]))),this.parseData(i,e.SecretData),this.parseData(i,e.CustomData),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)})),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}parseData(e,t){if(this.isNullOrWhitespace(t))return;this.splitNewLine(t).forEach((t=>{const i=t.indexOf(":");if(i<0)return;const n=t.substring(0,i),r=t.length>i?t.substring(i+1):null;if(this.isNullOrWhitespace(n)||this.isNullOrWhitespace(r)||"SecretType"===n)return;const s=n.toLowerCase();null==e.login.username&&this.usernameFieldNames.indexOf(s)>-1?e.login.username=r:null==e.login.password&&this.passwordFieldNames.indexOf(s)>-1?e.login.password=r:this.processKvp(e,n,r)}))}}const ag=[{id:"bitwardenjson",name:"Bitwarden (json)"},{id:"bitwardencsv",name:"Bitwarden (csv)"},{id:"chromecsv",name:"Chrome (csv)"},{id:"dashlanecsv",name:"Dashlane (csv)"},{id:"firefoxcsv",name:"Firefox (csv)"},{id:"keepass2xml",name:"KeePass 2 (xml)"},{id:"lastpasscsv",name:"LastPass"},{id:"safaricsv",name:"Safari and macOS (csv)"},{id:"1password1pux",name:"1Password (1pux/json)"}],lg=[{id:"keepassxcsv",name:"KeePassX (csv)"},{id:"1password1pif",name:"1Password (1pif)"},{id:"1passwordwincsv",name:"1Password 6 and 7 Windows (csv)"},{id:"1passwordmaccsv",name:"1Password 6 and 7 Mac (csv)"},{id:"dashlanejson",name:"Dashlane (json)"},{id:"roboformcsv",name:"RoboForm (csv)"},{id:"keepercsv",name:"Keeper (csv)"},{id:"enpasscsv",name:"Enpass (csv)"},{id:"enpassjson",name:"Enpass (json)"},{id:"protonpass",name:"ProtonPass (zip/json)"},{id:"safeincloudxml",name:"SafeInCloud (xml)"},{id:"pwsafexml",name:"Password Safe - pwsafe.org (xml)"},{id:"stickypasswordxml",name:"Sticky Password (xml)"},{id:"msecurecsv",name:"mSecure (csv)"},{id:"truekeycsv",name:"True Key (csv)"},{id:"passwordbossjson",name:"Password Boss (json)"},{id:"zohovaultcsv",name:"Zoho Vault (csv)"},{id:"splashidcsv",name:"SplashID (csv)"},{id:"passworddragonxml",name:"Password Dragon (xml)"},{id:"padlockcsv",name:"Padlock (csv)"},{id:"passboltcsv",name:"Passbolt (csv)"},{id:"clipperzhtml",name:"Clipperz (html)"},{id:"aviracsv",name:"Avira (csv)"},{id:"saferpasscsv",name:"SaferPass (csv)"},{id:"upmcsv",name:"Universal Password Manager (csv)"},{id:"ascendocsv",name:"Ascendo DataVault (csv)"},{id:"meldiumcsv",name:"Meldium (csv)"},{id:"passkeepcsv",name:"PassKeep (csv)"},{id:"operacsv",name:"Opera (csv)"},{id:"vivaldicsv",name:"Vivaldi (csv)"},{id:"gnomejson",name:"GNOME Passwords and Keys/Seahorse (json)"},{id:"blurcsv",name:"Blur (csv)"},{id:"passwordagentcsv",name:"Password Agent (csv)"},{id:"passpackcsv",name:"Passpack (csv)"},{id:"passmanjson",name:"Passman (json)"},{id:"avastcsv",name:"Avast Passwords (csv)"},{id:"avastjson",name:"Avast Passwords (json)"},{id:"fsecurefsk",name:"F-Secure KEY (fsk)"},{id:"kasperskytxt",name:"Kaspersky Password Manager (txt)"},{id:"remembearcsv",name:"RememBear (csv)"},{id:"passwordwallettxt",name:"PasswordWallet (txt)"},{id:"mykicsv",name:"Myki (csv)"},{id:"securesafecsv",name:"SecureSafe (csv)"},{id:"logmeoncecsv",name:"LogMeOnce (csv)"},{id:"blackberrycsv",name:"BlackBerry Password Keeper (csv)"},{id:"buttercupcsv",name:"Buttercup (csv)"},{id:"codebookcsv",name:"Codebook (csv)"},{id:"encryptrcsv",name:"Encryptr (csv)"},{id:"yoticsv",name:"Yoti (csv)"},{id:"nordpasscsv",name:"Nordpass (csv)"},{id:"psonojson",name:"Psono (json)"},{id:"passkyjson",name:"Passky (json)"}];var cg=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class dg{constructor(e,t,i,n,r,s){this.cipherService=e,this.folderService=t,this.importApiService=i,this.i18nService=n,this.collectionService=r,this.cryptoService=s,this.featuredImportOptions=ag,this.regularImportOptions=lg}getImportOptions(){return this.featuredImportOptions.concat(this.regularImportOptions)}import(e,t,i=null,n=null,r){return cg(this,void 0,void 0,(function*(){let s;try{s=yield e.parse(t)}catch(e){if(e instanceof SyntaxError)throw new Error(this.i18nService.t("importFormatError"));throw e}if(!s.success){if(!p.isNullOrWhitespace(s.errorMessage))throw new Error(s.errorMessage);throw new Error(this.i18nService.t("importFormatError"))}if(0===s.folders.length&&0===s.ciphers.length)throw new Error(this.i18nService.t("importNothingError"));if(s.ciphers.length>0){const e=Math.floor(s.ciphers.length/2),t=s.ciphers.length-1;if(this.badData(s.ciphers[0])&&this.badData(s.ciphers[e])&&this.badData(s.ciphers[t]))throw new Error(this.i18nService.t("importFormatError"))}if(i&&!n&&!r){if(s.collectionRelationships.lengtht.folderRelationships.push(new av(e[0],e[1])))),yield this.importApiService.postImportCiphers(t)}))}handleOrganizationalImport(e,t){return cg(this,void 0,void 0,(function*(){const i=new ov;for(let n=0;ni.collectionRelationships.push(new av(e[0],e[1])))),yield this.importApiService.postImportOrganizationCiphers(t,i)}))}badData(e){return(null==e.name||"--"===e.name)&&e.type===Pe.Login&&null!=e.login&&p.isNullOrWhitespace(e.login.password)}handleServerError(e,t){if(null==e.validationErrors)return new Error(e.message);let i="";return Object.entries(e.validationErrors).forEach((([e,n],r)=>{let s,o;const a=Number(e.match(/[0-9]+/)[0]);switch(e.match(/^\w+/)[0]){case"Ciphers":s=t.ciphers[a],o=Pe[s.type];break;case"Folders":s=t.folders[a],o="Folder";break;case"Collections":s=t.collections[a],o="Collection";break;default:return}r>0&&(i+="\n\n"),"Folder"!==o&&"Collection"!==o&&(i+="["+(a+1)+"] "),i+="["+o+'] "'+s.name+'": '+n})),new Error(i)}setImportTarget(e,t,i){return cg(this,void 0,void 0,(function*(){if(!i)return;if(t){if(!(i instanceof jp))throw new Error("Error assigning target collection");const t=[];e.ciphers.forEach(((i,n)=>{Array.isArray(e.collectionRelationships)&&e.collectionRelationships.some((([e])=>e===n))||t.push([n,0])}));const n=[...e.collections];e.collections=[i],n.map((t=>{const n=new jp;n.name=`${i.name}/${t.name}`,e.collections.push(n)}));const r=[...e.collectionRelationships];return e.collectionRelationships=[...t],void r.map((t=>{e.collectionRelationships.push([t[0],t[1]+1])}))}if(!(i instanceof Fy))throw new Error("Error assigning target folder");const n=[];e.ciphers.forEach(((e,t)=>{p.isNullOrEmpty(e.folderId)&&(e.folderId=i.id,n.push([t,0]))}));const r=[...e.folders];e.folders=[i],r.map((t=>{const n=`${i.name}/${t.name}`,r=new Fy;r.name=n,e.folders.push(r)}));const s=[...e.folderRelationships];e.folderRelationships=[...n],s.map((t=>{e.folderRelationships.push([t[0],t[1]+1])}))}))}}class ug{static getFileName(e=null,t="csv"){const i=new Date;return"bitwarden"+(e?"_"+e:"")+"_export_"+(i.getFullYear()+""+this.padNumber(i.getMonth()+1,2)+this.padNumber(i.getDate(),2)+this.padNumber(i.getHours(),2)+this.padNumber(i.getMinutes(),2)+this.padNumber(i.getSeconds(),2))+"."+t}static padNumber(e,t,i="0"){const n=e.toString();return n.length>=t?n:new Array(t-n.length+1).join(i)+n}}var hg=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class pg{constructor(e,t){this.individualVaultExportService=e,this.organizationVaultExportService=t}getExport(e="csv",t){return hg(this,void 0,void 0,(function*(){if(!p.isNullOrWhitespace(t)){if("csv"==e)throw new Error("CSV does not support password protected export");return this.individualVaultExportService.getPasswordProtectedExport(t)}return this.individualVaultExportService.getExport(e)}))}getOrganizationExport(e,t,i,n=!1){return hg(this,void 0,void 0,(function*(){if(!p.isNullOrWhitespace(i)){if("csv"==t)throw new Error("CSV does not support password protected export");return this.organizationVaultExportService.getPasswordProtectedExport(e,i,n)}return this.organizationVaultExportService.getOrganizationExport(e,t,n)}))}getFileName(e=null,t="csv"){return ug.getFileName(e,t)}}var yg=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class vg{constructor(e,t,i){this.cryptoService=e,this.cryptoFunctionService=t,this.stateService=i}buildPasswordExport(e,t){return yg(this,void 0,void 0,(function*(){const i=yield this.stateService.getKdfType(),n=yield this.stateService.getKdfConfig(),r=p.fromBufferToB64(yield this.cryptoFunctionService.randomBytes(16)),s=yield this.cryptoService.makePinKey(t,r,i,n),o=yield this.cryptoService.encrypt(p.newGuid(),s),a=yield this.cryptoService.encrypt(e,s),l={encrypted:!0,passwordProtected:!0,salt:r,kdfType:i,kdfIterations:n.iterations,kdfMemory:n.memory,kdfParallelism:n.parallelism,encKeyValidation_DO_NOT_EDIT:o.encryptedString,data:a.encryptedString};return JSON.stringify(l,null," ")}))}buildCommonCipher(e,t){switch(e.type=null,e.name=t.name,e.notes=t.notes,e.fields=null,e.reprompt=t.reprompt,e.login_uri=null,e.login_username=null,e.login_password=null,e.login_totp=null,t.fields&&t.fields.forEach((t=>{e.fields?e.fields+="\n":e.fields="",e.fields+=(t.name||"")+": "+t.value})),t.type){case Pe.Login:e.type="login",e.login_username=t.login.username,e.login_password=t.login.password,e.login_totp=t.login.totp,t.login.uris&&(e.login_uri=[],t.login.uris.forEach((t=>{e.login_uri.push(t.uri)})));break;case Pe.SecureNote:e.type="note";break;default:return}return e}}var fg=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class gg extends vg{constructor(e,t,i,n,r,s){super(i,n,r),this.cipherService=e,this.apiService=t,this.collectionService=s}getPasswordProtectedExport(e,t,i){return fg(this,void 0,void 0,(function*(){const n=yield this.getOrganizationExport(e,"json",i);return this.buildPasswordExport(n,t)}))}getOrganizationExport(e,t="csv",i){return fg(this,void 0,void 0,(function*(){if(p.isNullOrWhitespace(e))throw new Error("OrganizationId must be set");return"encrypted_json"===t?i?this.getEncryptedManagedExport(e):this.getOrganizationEncryptedExport(e):i?this.getDecryptedManagedExport(e,t):this.getOrganizationDecryptedExport(e,t)}))}getOrganizationDecryptedExport(e,t){return fg(this,void 0,void 0,(function*(){const i=[],n=[],r=[];return r.push(this.apiService.getOrganizationExport(e).then((e=>{const t=[];return null!=e&&(null!=e.collections&&e.collections.length>0&&e.collections.forEach((e=>{const n=new $p(new _p(e));t.push(n.decrypt().then((e=>{i.push(e)})))})),null!=e.ciphers&&e.ciphers.length>0&&e.ciphers.filter((e=>null===e.deletedDate)).forEach((e=>fg(this,void 0,void 0,(function*(){const i=new Co(new co(e));t.push(this.cipherService.getKeyForCipherKeyDecryption(i).then((e=>i.decrypt(e))).then((e=>{n.push(e)})))}))))),Promise.all(t)}))),yield Promise.all(r),"csv"===t?this.buildCsvExport(i,n):this.buildJsonExport(i,n)}))}getOrganizationEncryptedExport(e){return fg(this,void 0,void 0,(function*(){const t=[],i=[],n=[];return n.push(this.apiService.getCollections(e).then((e=>{null!=e&&null!=e.data&&e.data.length>0&&e.data.forEach((e=>{const i=new $p(new _p(e));t.push(i)}))}))),n.push(this.apiService.getCiphersOrganization(e).then((e=>{null!=e&&null!=e.data&&e.data.length>0&&e.data.filter((e=>null===e.deletedDate)).forEach((e=>{const t=new Co(new co(e));i.push(t)}))}))),yield Promise.all(n),this.BuildEncryptedExport(e,t,i)}))}getDecryptedManagedExport(e,t){return fg(this,void 0,void 0,(function*(){let i=[],n=[],r=[];const s=[];return s.push(this.collectionService.getAllDecrypted().then((t=>fg(this,void 0,void 0,(function*(){r=t.filter((t=>t.organizationId==e&&t.manage))}))))),s.push(this.cipherService.getAllDecrypted().then((e=>{n=e}))),yield Promise.all(s),i=n.filter((t=>null==t.deletedDate&&t.organizationId==e&&r.some((e=>t.collectionIds.some((t=>e.id===t)))))),"csv"===t?this.buildCsvExport(r,i):this.buildJsonExport(r,i)}))}getEncryptedManagedExport(e){return fg(this,void 0,void 0,(function*(){let t=[],i=[],n=[];const r=[];return r.push(this.collectionService.getAll().then((t=>{n=t.filter((t=>t.organizationId==e&&t.manage))}))),r.push(this.cipherService.getAll().then((e=>{i=e}))),yield Promise.all(r),t=i.filter((t=>null==t.deletedDate&&t.organizationId==e&&n.some((e=>t.collectionIds.some((t=>e.id===t)))))),this.BuildEncryptedExport(e,n,t)}))}BuildEncryptedExport(e,t,i){return fg(this,void 0,void 0,(function*(){const n=yield this.cryptoService.getOrgKey(e),r={encrypted:!0,encKeyValidation_DO_NOT_EDIT:(yield this.cryptoService.encrypt(p.newGuid(),n)).encryptedString,collections:[],items:[]};return t.forEach((e=>{const t=new Nv;t.build(e),r.collections.push(t)})),i.forEach((e=>{const t=new Uv;t.build(e),r.items.push(t)})),JSON.stringify(r,null," ")}))}buildCsvExport(e,t){const i=new Map;e.forEach((e=>{i.set(e.id,e)}));const n=[];return t.forEach((e=>{if(e.type!==Pe.Login&&e.type!==Pe.SecureNote)return;const t={collections:[]};null!=e.collectionIds&&(t.collections=e.collectionIds.filter((e=>i.has(e))).map((e=>i.get(e).name))),this.buildCommonCipher(t,e),n.push(t)})),hv.unparse(n)}buildJsonExport(e,t){const i={encrypted:!1,collections:[],items:[]};return e.forEach((e=>{const t=new Nv;t.build(e),i.collections.push(t)})),t.forEach((e=>{const t=new Uv;t.build(e),i.items.push(t)})),JSON.stringify(i,null," ")}}var mg=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class wg extends vg{constructor(e,t,i,n,r){super(i,n,r),this.folderService=e,this.cipherService=t}getExport(e="csv"){return mg(this,void 0,void 0,(function*(){return"encrypted_json"===e?this.getEncryptedExport():this.getDecryptedExport(e)}))}getPasswordProtectedExport(e){return mg(this,void 0,void 0,(function*(){const t=yield this.getExport("json");return this.buildPasswordExport(t,e)}))}getDecryptedExport(e){return mg(this,void 0,void 0,(function*(){let t=[],i=[];const n=[];return n.push(this.folderService.getAllDecryptedFromState().then((e=>{t=e}))),n.push(this.cipherService.getAllDecrypted().then((e=>{i=e.filter((e=>null==e.deletedDate))}))),yield Promise.all(n),"csv"===e?this.buildCsvExport(t,i):this.buildJsonExport(t,i)}))}getEncryptedExport(){return mg(this,void 0,void 0,(function*(){let e=[],t=[];const i=[];i.push(this.folderService.getAllFromState().then((t=>{e=t}))),i.push(this.cipherService.getAll().then((e=>{t=e.filter((e=>null==e.deletedDate))}))),yield Promise.all(i);const n={encrypted:!0,encKeyValidation_DO_NOT_EDIT:(yield this.cryptoService.encrypt(p.newGuid())).encryptedString,folders:[],items:[]};return e.forEach((e=>{if(null==e.id)return;const t=new Ev;t.build(e),n.folders.push(t)})),t.forEach((e=>{if(null!=e.organizationId)return;const t=new Uv;t.build(e),t.collectionIds=null,n.items.push(t)})),JSON.stringify(n,null," ")}))}buildCsvExport(e,t){const i=new Map;e.forEach((e=>{null!=e.id&&i.set(e.id,e)}));const n=[];return t.forEach((e=>{if(e.type!==Pe.Login&&e.type!==Pe.SecureNote)return;if(null!=e.organizationId)return;const t={};t.folder=null!=e.folderId&&i.has(e.folderId)?i.get(e.folderId).name:null,t.favorite=e.favorite?1:null,this.buildCommonCipher(t,e),n.push(t)})),hv.unparse(n)}buildJsonExport(e,t){const i={encrypted:!1,folders:[],items:[]};return e.forEach((e=>{if(null==e.id)return;const t=new Ev;t.build(e),i.folders.push(t)})),t.forEach((e=>{if(null!=e.organizationId)return;const t=new Uv;t.build(e),t.collectionIds=null,i.items.push(t)})),JSON.stringify(i,null," ")}}var Sg=i(30054);class bg{static sendMessageToApp(e,t=null,i=!1){return xg.isSafariApi?new Promise((i=>{const n=(new Date).getTime().toString()+"_"+Math.floor(Math.random()*Number.MAX_SAFE_INTEGER);browser.runtime.sendNativeMessage("com.bitwarden.desktop",{id:n,command:e,data:t,responseData:null},(e=>{i(e)}))})):Promise.resolve(null)}}var Pg=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class kg{static copy(e,t){return Pg(this,void 0,void 0,(function*(){if(kg.isClipboardApiSupported(e,"writeText"))try{yield e.navigator.clipboard.writeText(t)}catch(i){kg.consoleLogService.debug(`Error copying to clipboard using the clipboard API, attempting legacy method: ${i}`),this.useLegacyCopyMethod(e,t)}else this.useLegacyCopyMethod(e,t)}))}static read(e){return Pg(this,void 0,void 0,(function*(){if(!kg.isClipboardApiSupported(e,"readText"))return this.useLegacyReadMethod(e);try{return yield e.navigator.clipboard.readText()}catch(t){return kg.consoleLogService.debug(`Error reading from clipboard using the clipboard API, attempting legacy method: ${t}`),this.useLegacyReadMethod(e)}}))}static useLegacyCopyMethod(e,t){if(!kg.isLegacyClipboardMethodSupported(e,"copy"))return void kg.consoleLogService.warning("Legacy copy method not supported");const i=e.document.createElement("textarea");i.textContent=t||" ",i.style.position="fixed",e.document.body.appendChild(i),i.select();try{e.document.execCommand("copy")}catch(e){kg.consoleLogService.warning(`Error writing to clipboard: ${e}`)}finally{e.document.body.removeChild(i)}}static useLegacyReadMethod(e){if(!kg.isLegacyClipboardMethodSupported(e,"paste"))return kg.consoleLogService.warning("Legacy paste method not supported"),"";const t=e.document.createElement("textarea");t.style.position="fixed",e.document.body.appendChild(t),t.focus();try{return e.document.execCommand("paste")?t.value:""}catch(e){kg.consoleLogService.warning(`Error reading from clipboard: ${e}`)}finally{e.document.body.removeChild(t)}return""}static isClipboardApiSupported(e,t){return"clipboard"in e.navigator&&t in e.navigator.clipboard}static isLegacyClipboardMethodSupported(e,t){return"queryCommandSupported"in e.document&&e.document.queryCommandSupported(t)}}kg.consoleLogService=new $s(!1);const Og=kg;var Cg=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Ag{constructor(e,t,i){this.clipboardWriteCallback=e,this.biometricCallback=t,this.globalContext=i}static getDevice(e){return this.deviceCache||(Ag.isFirefox()?this.deviceCache=ee.FirefoxExtension:Ag.isOpera(e)?this.deviceCache=ee.OperaExtension:Ag.isEdge()?this.deviceCache=ee.EdgeExtension:Ag.isVivaldi()?this.deviceCache=ee.VivaldiExtension:Ag.isChrome(e)?this.deviceCache=ee.ChromeExtension:Ag.isSafari(e)&&(this.deviceCache=ee.SafariExtension)),this.deviceCache}getDevice(){return Ag.getDevice(this.globalContext)}getDeviceString(){return ee[this.getDevice()].toLowerCase().replace("extension","")}getClientType(){return Z.Browser}static isFirefox(){return-1!==navigator.userAgent.indexOf(" Firefox/")||-1!==navigator.userAgent.indexOf(" Gecko/")}isFirefox(){return this.getDevice()===ee.FirefoxExtension}static isChrome(e){return e.chrome&&-1!==navigator.userAgent.indexOf(" Chrome/")}isChrome(){return this.getDevice()===ee.ChromeExtension}static isEdge(){return-1!==navigator.userAgent.indexOf(" Edg/")}isEdge(){return this.getDevice()===ee.EdgeExtension}static isOpera(e){var t;return!!(null===(t=e.opr)||void 0===t?void 0:t.addons)||!!e.opera||navigator.userAgent.indexOf(" OPR/")>=0}isOpera(){return this.getDevice()===ee.OperaExtension}static isVivaldi(){return-1!==navigator.userAgent.indexOf(" Vivaldi/")}isVivaldi(){return this.getDevice()===ee.VivaldiExtension}static isSafari(e){return!Ag.isOpera(e)&&-1!==navigator.userAgent.indexOf(" Safari/")}static safariVersion(){var e;return null===(e=navigator.userAgent.match("Version/([0-9.]*)"))||void 0===e?void 0:e[1]}static shouldApplySafariHeightFix(e){var t;if(Ag.getDevice(e)!==ee.SafariExtension)return!1;const i=Ag.safariVersion(),n=null===(t=null==i?void 0:i.split("."))||void 0===t?void 0:t.map((e=>Number(e)));return(null==n?void 0:n[0])<16||16===(null==n?void 0:n[0])&&0===(null==n?void 0:n[1])}isSafari(){return this.getDevice()===ee.SafariExtension}isIE(){return!1}isMacAppStore(){return!1}isViewOpen(){return Cg(this,void 0,void 0,(function*(){return Boolean(yield xg.sendMessageWithResponse("checkVaultPopupHeartbeat"))}))}lockTimeout(){return null}launchUri(e,t){xg.createNewTab(e,t&&!0===t.extensionPage)}getApplicationVersion(){return Promise.resolve(xg.getApplicationVersion())}getApplicationVersionNumber(){return Cg(this,void 0,void 0,(function*(){return(yield this.getApplicationVersion()).split(RegExp("[+|-]"))[0].trim()}))}supportsWebAuthn(e){return"undefined"!=typeof PublicKeyCredential}supportsDuo(){return!0}isDev(){return!1}isSelfHost(){return!1}copyToClipboard(e,t){const i=(null==t?void 0:t.window)||this.globalContext,n=Boolean(null==t?void 0:t.clearing),r=(null==t?void 0:t.clearMs)||null,s=()=>{n||null==this.clipboardWriteCallback||this.clipboardWriteCallback(e,r)};this.isSafari()?bg.sendMessageToApp("copyToClipboard",e).then(s):(this.isChrome()&&""===e&&(e="\0"),this.isChrome()&&xg.isManifestVersion(3)?this.triggerOffscreenCopyToClipboard(e).then(s):Og.copy(i,e).then(s))}readFromClipboard(e){return Cg(this,void 0,void 0,(function*(){const t=(null==e?void 0:e.window)||this.globalContext;return this.isSafari()?yield bg.sendMessageToApp("readFromClipboard"):this.isChrome()&&xg.isManifestVersion(3)?yield this.triggerOffscreenReadFromClipboard():yield Og.read(t)}))}supportsBiometric(){return Cg(this,void 0,void 0,(function*(){const e=yield xg.getPlatformInfo();return"mac"===e.os||"win"===e.os}))}authenticateBiometric(){return this.biometricCallback()}supportsSecureStorage(){return!1}getAutofillKeyboardShortcut(){return Cg(this,void 0,void 0,(function*(){let e;return this.isSafari()?e="Cmd+Shift+L":this.isFirefox()?(e=(yield browser.commands.getAll()).find((e=>"autofill_login"===e.name)).shortcut,"mac"===(yield browser.runtime.getPlatformInfo()).os&&"Ctrl+Shift+L"===e&&(e="Cmd+Shift+L")):yield new Promise((t=>chrome.commands.getAll((i=>t(e=i.find((e=>"autofill_login"===e.name)).shortcut))))),e}))}triggerOffscreenCopyToClipboard(e){return Cg(this,void 0,void 0,(function*(){yield xg.createOffscreenDocument([chrome.offscreen.Reason.CLIPBOARD],"Write text to the clipboard."),yield xg.sendMessageWithResponse("offscreenCopyToClipboard",{text:e}),xg.closeOffscreenDocument()}))}triggerOffscreenReadFromClipboard(){return Cg(this,void 0,void 0,(function*(){yield xg.createOffscreenDocument([chrome.offscreen.Reason.CLIPBOARD],"Read text from the clipboard.");const e=yield xg.sendMessageWithResponse("offscreenReadFromClipboard");return xg.closeOffscreenDocument(),"string"==typeof e?e:""}))}}Ag.deviceCache=null;var Dg=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class xg{static get manifestVersion(){return chrome.runtime.getManifest().manifest_version}static isManifestVersion(e){return xg.manifestVersion===e}static getWindow(e){return Dg(this,void 0,void 0,(function*(){return e?yield xg.getWindowById(e):xg.getCurrentWindow()}))}static getCurrentWindow(){return Dg(this,void 0,void 0,(function*(){return new Promise((e=>chrome.windows.getCurrent({populate:!0},e)))}))}static getWindowById(e){return Dg(this,void 0,void 0,(function*(){return new Promise((t=>chrome.windows.get(e,{populate:!0},t)))}))}static createWindow(e){return Dg(this,void 0,void 0,(function*(){return new Promise((t=>chrome.windows.create(e,(e=>{t(e)}))))}))}static removeWindow(e){return Dg(this,void 0,void 0,(function*(){return new Promise((t=>chrome.windows.remove(e,(()=>t()))))}))}static updateWindowProperties(e,t){return Dg(this,void 0,void 0,(function*(){return new Promise((i=>chrome.windows.update(e,t,(()=>{i()}))))}))}static focusWindow(e){return Dg(this,void 0,void 0,(function*(){yield xg.updateWindowProperties(e,{focused:!0})}))}static getTabFromCurrentWindowId(){return Dg(this,void 0,void 0,(function*(){return yield xg.tabsQueryFirst({active:!0,windowId:chrome.windows.WINDOW_ID_CURRENT})}))}static getTab(e){return Dg(this,void 0,void 0,(function*(){return e?xg.isManifestVersion(3)?yield chrome.tabs.get(e):new Promise((t=>chrome.tabs.get(e,(e=>{t(e)})))):null}))}static getTabFromCurrentWindow(){return Dg(this,void 0,void 0,(function*(){return yield xg.tabsQueryFirst({active:!0,currentWindow:!0})}))}static getActiveTabs(){return Dg(this,void 0,void 0,(function*(){return yield xg.tabsQuery({active:!0})}))}static tabsQuery(e){return Dg(this,void 0,void 0,(function*(){return new Promise((t=>{chrome.tabs.query(e,(e=>{t(e)}))}))}))}static tabsQueryFirst(e){return Dg(this,void 0,void 0,(function*(){const t=yield xg.tabsQuery(e);return t.length>0?t[0]:null}))}static tabSendMessageData(e,t,i=null){const n={command:t};return null!=i&&(n.data=i),xg.tabSendMessage(e,n)}static tabSendMessage(e,t,i=null){return Dg(this,void 0,void 0,(function*(){if(e&&e.id)return new Promise((n=>{chrome.tabs.sendMessage(e.id,t,i,(()=>{chrome.runtime.lastError,n()}))}))}))}static sendTabsMessage(e,t,i,n){chrome.tabs.sendMessage(e,t,i,n)}static getPrivateModeWindows(){return Dg(this,void 0,void 0,(function*(){return(yield browser.windows.getAll()).filter((e=>e.incognito))}))}static onWindowCreated(e){return Dg(this,void 0,void 0,(function*(){return chrome.windows.onCreated.addListener(e)}))}static getBackgroundPage(){return void 0===chrome.extension.getBackgroundPage?null:chrome.extension.getBackgroundPage()}static isBackgroundPage(e){return void 0!==e&&e===xg.getBackgroundPage()}static getApplicationVersion(){return chrome.runtime.getManifest().version}static getExtensionViews(e){return void 0===chrome.extension.getViews?[]:chrome.extension.getViews(e)}static isPopupOpen(){return Dg(this,void 0,void 0,(function*(){return Promise.resolve(xg.getExtensionViews({type:"popup"}).length>0)}))}static createNewTab(e,t=!0){return new Promise((i=>chrome.tabs.create({url:e,active:t},(e=>i(e)))))}static messageListener(e,t){xg.addListener(chrome.runtime.onMessage,t)}static messageListener$(){return new Sg.y((e=>{const t=t=>{e.next(t)};return xg.addListener(chrome.runtime.onMessage,t),()=>xg.removeListener(chrome.runtime.onMessage,t)}))}static storageChangeListener(e){xg.addListener(chrome.storage.onChanged,e)}static addListener(e,t){e.addListener(t),xg.isSafariApi&&!xg.isBackgroundPage(self)&&(xg.trackedChromeEventListeners.push([e,t]),xg.setupUnloadListeners())}static removeListener(e,t){if(e.removeListener(t),xg.isSafariApi&&!xg.isBackgroundPage(self)){const e=xg.trackedChromeEventListeners.findIndex((([e,i])=>i==t));-1!==e&&xg.trackedChromeEventListeners.splice(e,1)}}static setupUnloadListeners(){window.onpagehide=()=>{for(const[e,t]of xg.trackedChromeEventListeners)e.removeListener(t)}}static sendMessage(e,t={}){const i=Object.assign({},{command:e},t);return chrome.runtime.sendMessage(i)}static sendMessageWithResponse(e,t={}){const i=Object.assign({},{command:e},t);return new Promise((e=>chrome.runtime.sendMessage(i,e)))}static focusTab(e){return Dg(this,void 0,void 0,(function*(){chrome.tabs.update(e,{active:!0,highlighted:!0})}))}static closePopup(e){xg.isWebExtensionsApi&&xg.isFirefoxOnAndroid?browser.tabs.update({active:!0}).finally(e.close):e.close()}static gaFilter(){return!1}static getUILanguage(){return chrome.i18n.getUILanguage()}static reloadExtension(e){var t;return"function"==typeof(null===(t=null==e?void 0:e.location)||void 0===t?void 0:t.reload)?e.location.reload(!0):chrome.runtime.reload()}static reloadOpenWindows(e=!1){const t=xg.getExtensionViews();if(!t.length)return;const i=window.location.href;t.filter((e=>null!=e.location.href&&!e.location.href.includes("background.html"))).filter((t=>!e||t.location.href!==i)).forEach((e=>e.location.reload()))}static connectNative(e){return xg.isWebExtensionsApi?browser.runtime.connectNative(e):xg.isChromeApi?chrome.runtime.connectNative(e):void 0}static requestPermission(e){return xg.isWebExtensionsApi?browser.permissions.request(e):new Promise((t=>{chrome.permissions.request(e,t)}))}static permissionsGranted(e){return Dg(this,void 0,void 0,(function*(){return new Promise((t=>chrome.permissions.contains({permissions:e},(e=>t(e)))))}))}static getPlatformInfo(){return xg.isWebExtensionsApi?browser.runtime.getPlatformInfo():new Promise((e=>{chrome.runtime.getPlatformInfo(e)}))}static getBrowserAction(){return xg.isManifestVersion(3)?chrome.action:chrome.browserAction}static getSidebarAction(e){var t;const i=Ag.getDevice(e);return i!==ee.FirefoxExtension&&i!==ee.OperaExtension?null:(null===(t=e.opr)||void 0===t?void 0:t.sidebarAction)||browser.sidebarAction}static captureVisibleTab(){return new Promise((e=>{chrome.tabs.captureVisibleTab(null,{format:"png"},e)}))}static executeScriptInTab(e,t,i){return xg.isManifestVersion(3)?chrome.scripting.executeScript({target:{tabId:e,allFrames:t.allFrames,frameIds:t.frameId?[t.frameId]:null},files:t.file?[t.file]:null,injectImmediately:"document_start"===t.runAt,world:(null==i?void 0:i.world)||"ISOLATED"}):new Promise((i=>{chrome.tabs.executeScript(e,t,(e=>{i(e)}))}))}static browserAutofillSettingsOverridden(){return Dg(this,void 0,void 0,(function*(){const e=e=>"controlled_by_this_extension"===e.levelOfControl&&!e.value,t=yield new Promise((t=>chrome.privacy.services.autofillAddressEnabled.get({},(i=>t(e(i)))))),i=yield new Promise((t=>chrome.privacy.services.autofillCreditCardEnabled.get({},(i=>t(e(i)))))),n=yield new Promise((t=>chrome.privacy.services.passwordSavingEnabled.get({},(i=>t(e(i))))));return t&&i&&n}))}static updateDefaultBrowserAutofillSettings(e){chrome.privacy.services.autofillAddressEnabled.set({value:e}),chrome.privacy.services.autofillCreditCardEnabled.set({value:e}),chrome.privacy.services.passwordSavingEnabled.set({value:e})}static createOffscreenDocument(e,t){return Dg(this,void 0,void 0,(function*(){yield chrome.offscreen.createDocument({url:"offscreen-document/index.html",reasons:e,justification:t})}))}static closeOffscreenDocument(e){chrome.offscreen.closeDocument((()=>{e&&e()}))}}xg.isWebExtensionsApi="undefined"!=typeof browser,xg.isSafariApi=-1!==navigator.userAgent.indexOf(" Safari/")&&-1===navigator.userAgent.indexOf(" Chrome/")&&-1===navigator.userAgent.indexOf(" Chromium/"),xg.isChromeApi=!xg.isSafariApi&&"undefined"!=typeof chrome,xg.isFirefoxOnAndroid=-1!==navigator.userAgent.indexOf("Firefox/")&&-1!==navigator.userAgent.indexOf("Android"),xg.trackedChromeEventListeners=[];class Ig{constructor(e){this.contextMenuClickedHandler=e,this.contextMenus=chrome.contextMenus}init(){this.contextMenus&&(this.contextMenus.onClicked.addListener(((e,t)=>this.contextMenuClickedHandler.run(e,t))),xg.messageListener("contextmenus.background",((e,t)=>{"unlockCompleted"===e.command&&"contextmenus.background"===e.data.target&&this.contextMenuClickedHandler.cipherAction(e.data.commandToRetry.message.contextMenuOnClickData,e.data.commandToRetry.sender.tab).then((()=>{xg.tabSendMessageData(t.tab,"closeNotificationBar")}))})))}}var Ug=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Tg{static inSidebar(e){return Tg.urlContainsSearchParams(e,"uilocation","sidebar")}static inPopout(e){return Tg.urlContainsSearchParams(e,"uilocation","popout")}static inSingleActionPopout(e,t){return Tg.urlContainsSearchParams(e,"singleActionPopout",t)}static inPopup(e){return-1===e.location.href.indexOf("uilocation=")||e.location.href.indexOf("uilocation=popup")>-1}static getContentScrollY(e,t="main"){return e.document.getElementsByTagName(t)[0].scrollTop}static setContentScrollY(e,t,i={delay:0,containerSelector:"main"}){return Ug(this,void 0,void 0,(function*(){const{delay:n,containerSelector:r}=i;return new Promise((i=>e.setTimeout((()=>{const n=e.document.querySelector(r);!isNaN(t)&&n&&(n.scrollTop=t),i()}),n)))}))}static backgroundInitializationRequired(){return!xg.getBackgroundPage()}static inPrivateMode(){return Tg.backgroundInitializationRequired()&&!xg.isManifestVersion(3)}static openPopout(e,t={}){return Ug(this,void 0,void 0,(function*(){const{senderWindowId:i,singleActionKey:n,forceCloseExistingWindows:r,windowOptions:s}=t,o={type:"popup",focused:!0,width:380,height:630},a=o.width,l=yield xg.getWindow(i),c=Object.assign(Object.assign(Object.assign({left:l.left+l.width-a-15,top:l.top+90},o),s),{url:Tg.buildPopoutUrl(e,n)});if(!(yield Tg.isSingleActionPopoutOpen(n,c,r))||r)return yield xg.createWindow(c)}))}static closeSingleActionPopout(e,t=0){return Ug(this,void 0,void 0,(function*(){const i=chrome.runtime.getURL("popup/index.html"),n=yield xg.tabsQuery({url:`${i}*`});for(const i of n)i.url.includes(`singleActionPopout=${e}`)&&setTimeout((()=>xg.removeWindow(i.windowId)),t)}))}static openCurrentPagePopout(e,t=null){return Ug(this,void 0,void 0,(function*(){const i=t||e.location.href,n=new URL(i);let r=n.hash;r.startsWith("#/tabs/current")&&(r="#/tabs/vault"),yield Tg.openPopout(`${n.pathname}${r}`),Tg.inPopup(e)&&xg.closePopup(e)}))}static isSingleActionPopoutOpen(e,t,i=!1){return Ug(this,void 0,void 0,(function*(){if(!e)return!1;const n=chrome.runtime.getURL("popup/index.html"),r=(yield xg.tabsQuery({url:`${n}*`})).filter((t=>t.url.includes(`singleActionPopout=${e}`)));if(0===r.length)return!1;if(!i){const e=r.shift();yield xg.updateWindowProperties(e.windowId,{focused:!0,width:t.width,height:t.height,top:t.top,left:t.left})}return r.forEach((e=>xg.removeWindow(e.windowId))),!0}))}static urlContainsSearchParams(e,t,i){return e.location.href.indexOf(`${t}=${i}`)>-1}static buildPopoutUrl(e,t){const i=new URL(chrome.runtime.getURL(e));return i.searchParams.set("uilocation","popout"),t&&i.searchParams.set("singleActionPopout",t),i.toString()}}const Ng=Tg;var Rg=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Eg="auth_unlockExtension",Fg="auth_ssoAuthResult",Mg="auth_twoFactorAuth",Kg=new Set([chrome.runtime.getURL("popup/index.html#/lock"),chrome.runtime.getURL("popup/index.html#/home")]);function Lg(e,t=!1){return Rg(this,void 0,void 0,(function*(){(yield xg.tabsQuery({windowType:"popup"})).forEach((e=>{Kg.has(e.url)&&xg.removeWindow(e.windowId)})),yield Ng.openPopout("popup/index.html",{singleActionKey:Eg,senderWindowId:e.windowId}),yield xg.tabSendMessageData(e,"bgUnlockPopoutOpened",{skipNotification:t})}))}var zg=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Vg={viewVaultItem:"vault_viewVaultItem",addEditVaultItem:"vault_AddEditVaultItem",fido2Popout:"vault_Fido2Popout"};function Bg(e,t){return zg(this,void 0,void 0,(function*(){const{cipherId:i,action:n,forceCloseExistingWindows:r}=t;let s="popup/index.html#/view-cipher",o="?";const a=(e,t)=>{const i=`${o}${e}=${t}`;return o="&",i};i&&(s+=a("cipherId",i)),e.id&&(s+=a("senderTabId",String(e.id))),n&&(s+=a("action",n)),yield Ng.openPopout(s,{singleActionKey:`${Vg.viewVaultItem}_${i}`,senderWindowId:e.windowId,forceCloseExistingWindows:r})}))}function _g(e,t){return zg(this,void 0,void 0,(function*(){yield Bg(e,Object.assign({forceCloseExistingWindows:!0},t)),yield xg.tabSendMessageData(e,"bgVaultItemRepromptPopoutOpened")}))}function jg(e,t={}){return zg(this,void 0,void 0,(function*(){const{cipherId:i,cipherType:n}=t,{url:r,windowId:s}=e;let o=Vg.addEditVaultItem,a="popup/index.html#/edit-cipher",l="?";const c=(e,t)=>{const i=`${l}${e}=${t}`;return l="&",i};i&&!n&&(o+=`_${i}`,a+=c("cipherId",i)),n&&!i&&(o+=`_${n}`,a+=c("type",String(n))),e.url&&(a+=c("uri",r)),yield Ng.openPopout(a,{singleActionKey:o,senderWindowId:s})}))}const $g="add",Wg="change",qg="unlock",Hg="fileless-import";var Gg=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Jg{constructor(e,t,i,n,r,s,o,a,l,c,d){this.autofillService=e,this.cipherService=t,this.authService=i,this.policyService=n,this.folderService=r,this.stateService=s,this.userNotificationSettingsService=o,this.domainSettingsService=a,this.environmentService=l,this.logService=c,this.themeStateService=d,this.openUnlockPopout=Lg,this.openAddEditVaultItemPopout=jg,this.notificationQueue=[],this.extensionMessageHandlers={unlockCompleted:({message:e,sender:t})=>this.handleUnlockCompleted(e,t),bgGetFolderData:()=>this.getFolderData(),bgCloseNotificationBar:({sender:e})=>this.handleCloseNotificationBarMessage(e),bgAdjustNotificationBar:({message:e,sender:t})=>this.handleAdjustNotificationBarMessage(e,t),bgAddLogin:({message:e,sender:t})=>this.addLogin(e,t),bgChangedPassword:({message:e,sender:t})=>this.changedPassword(e,t),bgRemoveTabFromNotificationQueue:({sender:e})=>this.removeTabFromNotificationQueue(e.tab),bgSaveCipher:({message:e,sender:t})=>this.handleSaveCipherMessage(e,t),bgNeverSave:({sender:e})=>this.saveNever(e.tab),collectPageDetailsResponse:({message:e})=>this.handleCollectPageDetailsResponseMessage(e),bgUnlockPopoutOpened:({message:e,sender:t})=>this.unlockVault(e,t.tab),checkNotificationQueue:({sender:e})=>this.checkNotificationQueue(e.tab),bgReopenUnlockPopout:({sender:e})=>this.openUnlockPopout(e.tab),bgGetEnableChangedPasswordPrompt:()=>this.getEnableChangedPasswordPrompt(),bgGetEnableAddedLoginPrompt:()=>this.getEnableAddedLoginPrompt(),bgGetExcludedDomains:()=>this.getExcludedDomains(),getWebVaultUrlForNotification:()=>this.getWebVaultUrl()},this.handleExtensionMessage=(e,t,i)=>{const n=this.extensionMessageHandlers[null==e?void 0:e.command];if(!n)return;const r=n({message:e,sender:t});return r?(Promise.resolve(r).then((e=>i(e))).catch((e=>this.logService.error(e))),!0):void 0}}init(){return Gg(this,void 0,void 0,(function*(){null!=chrome.runtime&&(this.setupExtensionMessageListener(),this.cleanupNotificationQueue())}))}getEnableChangedPasswordPrompt(){return Gg(this,void 0,void 0,(function*(){return yield(0,r.z)(this.userNotificationSettingsService.enableChangedPasswordPrompt$)}))}getEnableAddedLoginPrompt(){return Gg(this,void 0,void 0,(function*(){return yield(0,r.z)(this.userNotificationSettingsService.enableAddedLoginPrompt$)}))}getExcludedDomains(){return Gg(this,void 0,void 0,(function*(){return yield(0,r.z)(this.domainSettingsService.neverDomains$)}))}checkNotificationQueue(e=null){return Gg(this,void 0,void 0,(function*(){if(0===this.notificationQueue.length)return;if(null!=e)return void(yield this.doNotificationQueueCheck(e));const t=yield xg.getTabFromCurrentWindow();null!=t&&(yield this.doNotificationQueueCheck(t))}))}cleanupNotificationQueue(){for(let e=this.notificationQueue.length-1;e>=0;e--)this.notificationQueue[e].expiresthis.logService.error(e))),this.notificationQueue.splice(e,1));setTimeout((()=>this.cleanupNotificationQueue()),3e4)}doNotificationQueueCheck(e){return Gg(this,void 0,void 0,(function*(){const t=p.getDomain(null==e?void 0:e.url);if(!t)return;const i=this.notificationQueue.find((i=>i.tab.id===e.id&&i.domain===t));i&&(yield this.sendNotificationQueueMessage(e,i))}))}sendNotificationQueueMessage(e,t){return Gg(this,void 0,void 0,(function*(){const i=t.type,n={isVaultLocked:t.wasVaultLocked,theme:yield(0,r.z)(this.themeStateService.selectedTheme$)};switch(i){case $g:n.removeIndividualVault=yield this.removeIndividualVault();break;case Hg:n.importType=t.importType}yield xg.tabSendMessageData(e,"openNotificationBar",{type:i,typeData:n})}))}removeTabFromNotificationQueue(e){for(let t=this.notificationQueue.length-1;t>=0;t--)this.notificationQueue[t].tab.id===e.id&&this.notificationQueue.splice(t,1)}addLogin(e,t){return Gg(this,void 0,void 0,(function*(){const i=yield this.authService.getAuthStatus();if(i===On.LoggedOut)return;const n=e.login,r=n.username?n.username.toLowerCase():"",s=p.getDomain(n.url);if(null==s)return;const o=yield this.getEnableAddedLoginPrompt();if(i===On.Locked)return void(o&&(yield this.pushAddLoginToQueue(s,n,t.tab,!0)));const a=(yield this.cipherService.getAllDecryptedForUrl(n.url)).filter((e=>null!=e.login.username&&e.login.username.toLowerCase()===r));if(o&&0===a.length)return void(yield this.pushAddLoginToQueue(s,n,t.tab));(yield this.getEnableChangedPasswordPrompt())&&1===a.length&&a[0].login.password!==n.password&&(yield this.pushChangePasswordToQueue(a[0].id,s,n.password,t.tab))}))}pushAddLoginToQueue(e,t,i,n=!1){return Gg(this,void 0,void 0,(function*(){this.removeTabFromNotificationQueue(i);const r={type:$g,username:t.username,password:t.password,domain:e,uri:t.url,tab:i,expires:new Date((new Date).getTime()+$r),wasVaultLocked:n};this.notificationQueue.push(r),yield this.checkNotificationQueue(i)}))}changedPassword(e,t){return Gg(this,void 0,void 0,(function*(){const i=e.data,n=p.getDomain(i.url);if(null==n)return;if((yield this.authService.getAuthStatus())e.login.password===i.currentPassword));1===e.length&&(r=e[0].id)}else 1===s.length&&(r=s[0].id);null!=r&&(yield this.pushChangePasswordToQueue(r,n,i.newPassword,t.tab))}))}handleCollectPageDetailsResponseMessage(e){return Gg(this,void 0,void 0,(function*(){if("notificationBar"!==e.sender)return;const t=this.autofillService.getFormsWithPasswordFields(e.details);yield xg.tabSendMessageData(e.tab,"notificationBarPageDetails",{details:e.details,forms:t})}))}unlockVault(e,t){var i;return Gg(this,void 0,void 0,(function*(){if(null===(i=e.data)||void 0===i?void 0:i.skipNotification)return;if((yield this.authService.getAuthStatus())!==On.Locked||this.notificationQueue.length)return;const n=p.getDomain(t.url);n&&(yield this.pushUnlockVaultToQueue(n,t))}))}requestFilelessImport(e,t){return Gg(this,void 0,void 0,(function*(){if((yield this.authService.getAuthStatus())!==On.Unlocked||this.notificationQueue.length)return;const i=p.getDomain(e.url);i&&(yield this.pushRequestFilelessImportToQueue(i,e,t))}))}pushChangePasswordToQueue(e,t,i,n,r=!1){return Gg(this,void 0,void 0,(function*(){this.removeTabFromNotificationQueue(n);const s={type:Wg,cipherId:e,newPassword:i,domain:t,tab:n,expires:new Date((new Date).getTime()+$r),wasVaultLocked:r};this.notificationQueue.push(s),yield this.checkNotificationQueue(n)}))}pushUnlockVaultToQueue(e,t){return Gg(this,void 0,void 0,(function*(){this.removeTabFromNotificationQueue(t);const i={type:qg,domain:e,tab:t,expires:new Date((new Date).getTime()+3e4),wasVaultLocked:!0};yield this.sendNotificationQueueMessage(t,i)}))}pushRequestFilelessImportToQueue(e,t,i){return Gg(this,void 0,void 0,(function*(){this.removeTabFromNotificationQueue(t);const n={type:Hg,domain:e,tab:t,expires:new Date((new Date).getTime()+3e4),wasVaultLocked:!1,importType:i};this.notificationQueue.push(n),yield this.checkNotificationQueue(t),this.removeTabFromNotificationQueue(t)}))}handleSaveCipherMessage(e,t){return Gg(this,void 0,void 0,(function*(){if((yield this.authService.getAuthStatus())=0;n--){const r=this.notificationQueue[n];if(r.tab.id!==e.id||r.type!==$g&&r.type!==Wg)continue;const s=p.getDomain(e.url);if(null!=s&&s!==r.domain)continue;if(this.notificationQueue.splice(n,1),r.type===Wg){const i=yield this.getDecryptedCipherById(r.cipherId);return void(yield this.updatePassword(i,r.newPassword,t,e))}if(r.wasVaultLocked){const i=(yield this.cipherService.getAllDecryptedForUrl(r.uri)).find((e=>null!=e.login.username&&e.login.username.toLowerCase()===r.username));if(null!=i)return void(yield this.updatePassword(i,r.password,t,e))}i=(yield this.folderExists(i))?i:null;const o=this.convertAddLoginQueueMessageToCipherView(r,i);if(t)return yield this.editItem(o,e),void(yield xg.tabSendMessage(e,{command:"closeNotificationBar"}));const a=yield this.cipherService.encrypt(o);try{yield this.cipherService.createWithServer(a),yield xg.tabSendMessage(e,{command:"saveCipherAttemptCompleted"}),yield xg.tabSendMessage(e,{command:"addedCipher"})}catch(t){yield xg.tabSendMessageData(e,"saveCipherAttemptCompleted",{error:String(t.message)})}}}))}updatePassword(e,t,i,n){return Gg(this,void 0,void 0,(function*(){if(e.login.password=t,i)return yield this.editItem(e,n),yield xg.tabSendMessage(n,{command:"closeNotificationBar"}),void(yield xg.tabSendMessage(n,{command:"editedCipher"}));const r=yield this.cipherService.encrypt(e);try{yield this.cipherService.updateWithServer(r),yield xg.tabSendMessage(n,{command:"saveCipherAttemptCompleted"})}catch(e){yield xg.tabSendMessageData(n,"saveCipherAttemptCompleted",{error:String(e.message)})}}))}editItem(e,t){return Gg(this,void 0,void 0,(function*(){yield this.stateService.setAddEditCipherInfo({cipher:e,collectionIds:e.collectionIds}),yield this.openAddEditVaultItemPopout(t,{cipherId:e.id})}))}folderExists(e){return Gg(this,void 0,void 0,(function*(){if(p.isNullOrWhitespace(e)||"null"===e)return!1;return(yield(0,r.z)(this.folderService.folderViews$)).some((t=>t.id===e))}))}getDecryptedCipherById(e){return Gg(this,void 0,void 0,(function*(){const t=yield this.cipherService.get(e);return null!=t&&t.type===Pe.Login?yield t.decrypt(yield this.cipherService.getKeyForCipherKeyDecryption(t)):null}))}saveNever(e){return Gg(this,void 0,void 0,(function*(){for(let t=this.notificationQueue.length-1;t>=0;t--){const i=this.notificationQueue[t];if(i.tab.id!==e.id||i.type!==$g)continue;const n=p.getDomain(e.url);if(null!=n&&n!==i.domain)continue;this.notificationQueue.splice(t,1),yield xg.tabSendMessageData(e,"closeNotificationBar");const r=p.getHostname(e.url);yield this.cipherService.saveNeverDomain(r)}}))}getFolderData(){return Gg(this,void 0,void 0,(function*(){return yield(0,r.z)(this.folderService.folderViews$)}))}getWebVaultUrl(){return Gg(this,void 0,void 0,(function*(){return(yield(0,r.z)(this.environmentService.environment$)).getWebVaultUrl()}))}removeIndividualVault(){return Gg(this,void 0,void 0,(function*(){return yield(0,r.z)(this.policyService.policyAppliesToActiveUser$(qi.PersonalOwnership))}))}handleUnlockCompleted(e,t){return Gg(this,void 0,void 0,(function*(){const i=e.data,n=i.commandToRetry.message.command;if("autofill_login"===n&&(yield xg.tabSendMessageData(t.tab,"closeNotificationBar")),"notification.background"!==i.target)return;const r=this.extensionMessageHandlers[n];r&&r({message:i.commandToRetry.message,sender:i.commandToRetry.sender})}))}handleCloseNotificationBarMessage(e){return Gg(this,void 0,void 0,(function*(){yield xg.tabSendMessageData(e.tab,"closeNotificationBar")}))}handleAdjustNotificationBarMessage(e,t){return Gg(this,void 0,void 0,(function*(){yield xg.tabSendMessageData(t.tab,"adjustNotificationBar",e.data)}))}convertAddLoginQueueMessageToCipherView(e,t){const i=new Ye;i.uri=e.uri;const n=new Ze;n.uris=[i],n.username=e.username,n.password=e.password;const r=new it;return r.name=(p.getHostname(e.uri)||e.domain).replace(/^www\./,""),r.folderId=t,r.type=Pe.Login,r.login=n,r}setupExtensionMessageListener(){xg.messageListener("notification.background",this.handleExtensionMessage)}}function Yg(e,t,i){let n,r,s="";const o={Visa:"card-visa",Mastercard:"card-mastercard",Amex:"card-amex",Discover:"card-discover","Diners Club":"card-diners-club",JCB:"card-jcb",Maestro:"card-maestro",UnionPay:"card-union-pay",RuPay:"card-ru-pay"};switch(t.type){case Pe.Login:if(n="bwi-globe",t.login.uri){let o=t.login.uri,a=!1;if(0===o.indexOf("androidapp://")?(n="bwi-android",r=null):0===o.indexOf("iosapp://")?(n="bwi-apple",r=null):i&&-1===o.indexOf("://")&&o.indexOf(".")>-1?(o=`http://${o}`,a=!0):i&&(a=0===o.indexOf("http")&&o.indexOf(".")>-1),i&&a)try{r=`${e}/${p.getHostname(o)}/icon.png`,s="images/bwi-globe.png"}catch(e){}}else r=null;break;case Pe.SecureNote:n="bwi-sticky-note";break;case Pe.Card:n="bwi-credit-card",i&&t.card.brand in o&&(n=`credit-card-icon ${o[t.card.brand]}`);break;case Pe.Identity:n="bwi-id-card"}return{imageEnabled:i,image:r,fallbackImage:s,icon:n}}const Qg="autofill-overlay-button",Xg="autofill-overlay-list",Zg="autofill-overlay-button-port",em="autofill-overlay-list-port";var tm=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const im=class{constructor(e,t,i,n,s,o,a,l,c,d){this.cipherService=e,this.autofillService=t,this.authService=i,this.environmentService=n,this.domainSettingsService=s,this.stateService=o,this.autofillSettingsService=a,this.i18nService=l,this.platformUtilsService=c,this.themeStateService=d,this.openUnlockPopout=Lg,this.openViewVaultItemPopout=Bg,this.openAddEditVaultItemPopout=jg,this.overlayLoginCiphers=new Map,this.pageDetailsForTab={},this.userAuthStatus=On.LoggedOut,this.extensionMessageHandlers={openAutofillOverlay:()=>this.openOverlay(!1),autofillOverlayElementClosed:({message:e})=>this.overlayElementClosed(e),autofillOverlayAddNewVaultItem:({message:e,sender:t})=>this.addNewVaultItem(e,t),getAutofillOverlayVisibility:()=>this.getOverlayVisibility(),checkAutofillOverlayFocused:()=>this.checkOverlayFocused(),focusAutofillOverlayList:()=>this.focusOverlayList(),updateAutofillOverlayPosition:({message:e})=>this.updateOverlayPosition(e),updateAutofillOverlayHidden:({message:e})=>this.updateOverlayHidden(e),updateFocusedFieldData:({message:e})=>this.setFocusedFieldData(e),collectPageDetailsResponse:({message:e,sender:t})=>this.storePageDetails(e,t),unlockCompleted:({message:e})=>this.unlockCompleted(e),addEditCipherSubmitted:()=>this.updateOverlayCiphers(),deletedCipher:()=>this.updateOverlayCiphers()},this.overlayButtonPortMessageHandlers={overlayButtonClicked:({port:e})=>this.handleOverlayButtonClicked(e),closeAutofillOverlay:({port:e})=>this.closeOverlay(e),forceCloseAutofillOverlay:({port:e})=>this.closeOverlay(e,!0),overlayPageBlurred:()=>this.checkOverlayListFocused(),redirectOverlayFocusOut:({message:e,port:t})=>this.redirectOverlayFocusOut(e,t)},this.overlayListPortMessageHandlers={checkAutofillOverlayButtonFocused:()=>this.checkOverlayButtonFocused(),forceCloseAutofillOverlay:({port:e})=>this.closeOverlay(e,!0),overlayPageBlurred:()=>this.checkOverlayButtonFocused(),unlockVault:({port:e})=>this.unlockVault(e),fillSelectedListItem:({message:e,port:t})=>this.fillSelectedOverlayListItem(e,t),addNewVaultItem:({port:e})=>this.getNewVaultItemDetails(e),viewSelectedCipher:({message:e,port:t})=>this.viewSelectedCipher(e,t),redirectOverlayFocusOut:({message:e,port:t})=>this.redirectOverlayFocusOut(e,t)},this.handleExtensionMessage=(e,t,i)=>{const n=this.extensionMessageHandlers[null==e?void 0:e.command];if(!n)return;const r=n({message:e,sender:t});return r?(Promise.resolve(r).then((e=>i(e))),!0):void 0},this.handlePortOnConnect=e=>tm(this,void 0,void 0,(function*(){const t=e.name===em,i=e.name===Zg;(t||i)&&(t?this.overlayListPort=e:this.overlayButtonPort=e,e.onMessage.addListener(this.handleOverlayElementPortMessage),e.postMessage({command:"initAutofillOverlay"+(t?"List":"Button"),authStatus:yield this.getAuthStatus(),styleSheetUrl:chrome.runtime.getURL(`overlay/${t?"list":"button"}.css`),theme:yield(0,r.z)(this.themeStateService.selectedTheme$),translations:this.getTranslations(),ciphers:t?yield this.getOverlayCipherData():null}),this.updateOverlayPosition({overlayElement:t?Xg:Qg}))})),this.handleOverlayElementPortMessage=(e,t)=>{const i=null==e?void 0:e.command;let n;t.name===Zg&&(n=this.overlayButtonPortMessageHandlers[i]),t.name===em&&(n=this.overlayListPortMessageHandlers[i]),n&&n({message:e,port:t})}}removePageDetails(e){this.pageDetailsForTab[e]&&(this.pageDetailsForTab[e].clear(),delete this.pageDetailsForTab[e])}init(){return tm(this,void 0,void 0,(function*(){this.setupExtensionMessageListeners();const e=yield(0,r.z)(this.environmentService.environment$);this.iconsServerUrl=e.getIconsUrl(),yield this.getOverlayVisibility(),yield this.getAuthStatus()}))}updateOverlayCiphers(){var e;return tm(this,void 0,void 0,(function*(){if(this.userAuthStatus!==On.Unlocked)return;const t=yield xg.getTabFromCurrentWindowId();if(!(null==t?void 0:t.url))return;this.overlayLoginCiphers=new Map;const i=(yield this.cipherService.getAllDecryptedForUrl(t.url)).sort(((e,t)=>this.cipherService.sortCiphersByLastUsedThenName(e,t)));for(let e=0;e=35&&(o=n>=50?.47*n:.42*n);const a=n-o,l=e+o/2;let c=t+i-n+o/2;const d=parseInt(r,10);return d>parseInt(s,10)&&(c=t+i-n-(d-o+2)),{top:`${Math.round(l)}px`,left:`${Math.round(c)}px`,height:`${Math.round(a)}px`,width:`${Math.round(a)}px`}}getOverlayListPosition(){if(!this.focusedFieldData)return;const{top:e,left:t,width:i,height:n}=this.focusedFieldData.focusedFieldRects;return{width:`${Math.round(i)}px`,top:`${Math.round(e+n)}px`,left:`${Math.round(t)}px`}}setFocusedFieldData({focusedFieldData:e}){this.focusedFieldData=e}updateOverlayHidden({display:e}){var t,i;if(!e)return;const n={command:"updateOverlayHidden",styles:{display:e}};null===(t=this.overlayButtonPort)||void 0===t||t.postMessage(n),null===(i=this.overlayListPort)||void 0===i||i.postMessage(n)}openOverlay(e=!1,t=!1){return tm(this,void 0,void 0,(function*(){const i=yield xg.getTabFromCurrentWindowId();yield xg.tabSendMessageData(i,"openAutofillOverlay",{isFocusingFieldElement:e,isOpeningFullOverlay:t,authStatus:yield this.getAuthStatus()})}))}getOverlayVisibility(){return tm(this,void 0,void 0,(function*(){return yield(0,r.z)(this.autofillSettingsService.inlineMenuVisibility$)}))}getAuthStatus(){return tm(this,void 0,void 0,(function*(){const e=this.userAuthStatus;return this.userAuthStatus=yield this.authService.getAuthStatus(),this.userAuthStatus!==e&&this.userAuthStatus===On.Unlocked&&(this.updateOverlayButtonAuthStatus(),yield this.updateOverlayCiphers()),this.userAuthStatus}))}updateOverlayButtonAuthStatus(){var e;null===(e=this.overlayButtonPort)||void 0===e||e.postMessage({command:"updateOverlayButtonAuthStatus",authStatus:this.userAuthStatus})}handleOverlayButtonClicked(e){this.userAuthStatus===On.Unlocked?this.openOverlay(!1,!0):this.unlockVault(e)}unlockVault(e){return tm(this,void 0,void 0,(function*(){const{sender:t}=e;this.closeOverlay(e);const i={commandToRetry:{message:{command:"openAutofillOverlay"},sender:t},target:"overlay.background"};yield xg.tabSendMessageData(t.tab,"addToLockedVaultPendingNotifications",i),yield this.openUnlockPopout(t.tab,!0)}))}viewSelectedCipher({overlayCipherId:e},{sender:t}){return tm(this,void 0,void 0,(function*(){const i=this.overlayLoginCiphers.get(e);i&&(yield this.openViewVaultItemPopout(t.tab,{cipherId:i.id,action:"show-autofill-button"}))}))}focusOverlayList(){var e;null===(e=this.overlayListPort)||void 0===e||e.postMessage({command:"focusOverlayList"})}unlockCompleted(e){var t,i,n;return tm(this,void 0,void 0,(function*(){yield this.getAuthStatus(),"openAutofillOverlay"===(null===(n=null===(i=null===(t=e.data)||void 0===t?void 0:t.commandToRetry)||void 0===i?void 0:i.message)||void 0===n?void 0:n.command)&&(yield this.openOverlay(!0))}))}getTranslations(){return this.overlayPageTranslations||(this.overlayPageTranslations={locale:xg.getUILanguage(),opensInANewWindow:this.i18nService.translate("opensInANewWindow"),buttonPageTitle:this.i18nService.translate("bitwardenOverlayButton"),toggleBitwardenVaultOverlay:this.i18nService.translate("toggleBitwardenVaultOverlay"),listPageTitle:this.i18nService.translate("bitwardenVault"),unlockYourAccount:this.i18nService.translate("unlockYourAccountToViewMatchingLogins"),unlockAccount:this.i18nService.translate("unlockAccount"),fillCredentialsFor:this.i18nService.translate("fillCredentialsFor"),partialUsername:this.i18nService.translate("partialUsername"),view:this.i18nService.translate("view"),noItemsToShow:this.i18nService.translate("noItemsToShow"),newItem:this.i18nService.translate("newItem"),addNewVaultItem:this.i18nService.translate("addNewVaultItem")}),this.overlayPageTranslations}redirectOverlayFocusOut({direction:e},{sender:t}){e&&xg.tabSendMessageData(t.tab,"redirectOverlayFocusOut",{direction:e})}getNewVaultItemDetails({sender:e}){xg.tabSendMessage(e.tab,{command:"addNewVaultItemFromOverlay"})}addNewVaultItem({login:e},t){return tm(this,void 0,void 0,(function*(){if(!e)return;const i=new Ye;i.uri=e.uri;const n=new Ze;n.uris=[i],n.username=e.username||"",n.password=e.password||"";const r=new it;r.name=(p.getHostname(e.uri)||e.hostname).replace(/^www\./,""),r.folderId=null,r.type=Pe.Login,r.login=n,yield this.stateService.setAddEditCipherInfo({cipher:r,collectionIds:r.collectionIds}),yield xg.sendMessage("inlineAutofillMenuRefreshAddEditCipher"),yield this.openAddEditVaultItemPopout(t.tab,{cipherId:r.id})}))}setupExtensionMessageListeners(){xg.messageListener("overlay.background",this.handleExtensionMessage),xg.addListener(chrome.runtime.onConnect,this.handlePortOnConnect)}};var nm=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class rm{constructor(e,t,i){this.main=e,this.notificationBackground=t,this.overlayBackground=i,this.handleWindowOnFocusChanged=e=>nm(this,void 0,void 0,(function*(){null==e||e<0||(this.focusedWindowId=e,yield this.updateCurrentTabData(),this.main.messagingService.send("windowChanged"))})),this.handleTabOnActivated=()=>nm(this,void 0,void 0,(function*(){yield this.updateCurrentTabData(),this.main.messagingService.send("tabChanged")})),this.handleTabOnReplaced=()=>nm(this,void 0,void 0,(function*(){this.main.onReplacedRan||(this.main.onReplacedRan=!0,yield this.notificationBackground.checkNotificationQueue(),yield this.updateCurrentTabData(),this.main.messagingService.send("tabChanged"))})),this.handleTabOnUpdated=(e,t,i)=>nm(this,void 0,void 0,(function*(){new Set(["loading","unloaded"]).has(t.status)&&this.overlayBackground.removePageDetails(e),this.focusedWindowId>0&&i.windowId!==this.focusedWindowId||i.active&&(yield this.overlayBackground.updateOverlayCiphers(),this.main.onUpdatedRan||(this.main.onUpdatedRan=!0,yield this.notificationBackground.checkNotificationQueue(i),yield this.main.refreshBadge(),yield this.main.refreshMenu(),this.main.messagingService.send("tabChanged")))})),this.handleTabOnRemoved=e=>nm(this,void 0,void 0,(function*(){this.overlayBackground.removePageDetails(e)})),this.updateCurrentTabData=()=>nm(this,void 0,void 0,(function*(){yield Promise.all([this.main.refreshBadge(),this.main.refreshMenu(),this.overlayBackground.updateOverlayCiphers()])}))}init(){return nm(this,void 0,void 0,(function*(){chrome.tabs&&chrome.windows&&(this.updateCurrentTabData(),this.setupTabEventListeners())}))}setupTabEventListeners(){chrome.windows.onFocusChanged.addListener(this.handleWindowOnFocusChanged),chrome.tabs.onActivated.addListener(this.handleTabOnActivated),chrome.tabs.onReplaced.addListener(this.handleTabOnReplaced),chrome.tabs.onUpdated.addListener(this.handleTabOnUpdated),chrome.tabs.onRemoved.addListener(this.handleTabOnRemoved)}}var sm=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class om{constructor(e,t,i){this.cipherService=t,this.authService=i,this.pendingAuthRequests=[],xg.isManifestVersion(2)&&(this.webRequest=window.chrome.webRequest),this.isFirefox=e.isFirefox()}init(){return sm(this,void 0,void 0,(function*(){this.webRequest&&this.webRequest.onAuthRequired&&(this.webRequest.onAuthRequired.addListener(((e,t)=>sm(this,void 0,void 0,(function*(){if(e.url&&-1===this.pendingAuthRequests.indexOf(e.requestId)){if(this.pendingAuthRequests.push(e.requestId),this.isFirefox)return new Promise(((t,i)=>sm(this,void 0,void 0,(function*(){yield this.resolveAuthCredentials(e.url,t,i)}))));yield this.resolveAuthCredentials(e.url,t,t)}else t&&t()}))),{urls:["http://*/*","https://*/*"]},[this.isFirefox?"blocking":"asyncBlocking"]),this.webRequest.onCompleted.addListener((e=>this.completeAuthRequest(e)),{urls:["http://*/*"]}),this.webRequest.onErrorOccurred.addListener((e=>this.completeAuthRequest(e)),{urls:["http://*/*"]}))}))}resolveAuthCredentials(e,t,i){return sm(this,void 0,void 0,(function*(){if((yield this.authService.getAuthStatus())-1&&this.pendingAuthRequests.splice(t,1)}}var am=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function lm(e,t,i,n){return am(this,void 0,void 0,(function*(){let r=e[t];if(i.alwaysInitializeNewService||!r){const e=n();r=e instanceof Promise?yield e:e}return i.doNotStoreInitializedService||(e[t]=r),r}))}function cm(e,t){return lm(e,"logService",t,(()=>new $s(t.logServiceOptions.isDev,t.logServiceOptions.filter)))}function dm(e,t){return lm(e,"cryptoFunctionService",t,(()=>new od(t.cryptoFunctionServiceOptions.win)))}var um=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function hm(e,t){return lm(e,"encryptService",t,(()=>um(this,void 0,void 0,(function*(){return new Ys(yield dm(e,t),yield cm(e,t),t.encryptServiceOptions.logMacFailures)}))))}var pm=i(86742);var ym=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class vm{constructor(e){var t;this.chromeStorageApi=e,this.updates$=(t=this.chromeStorageApi.onChanged,new Sg.y((e=>{const i=(...t)=>{chrome.runtime.lastError?e.error(chrome.runtime.lastError):e.next(t)};return xg.addListener(t,i),()=>xg.removeListener(t,i)}))).pipe((0,pm.z)((([e])=>Object.entries(e).map((([e,t])=>({key:e,updateType:"newValue"in t?"save":"remove"}))))))}get valuesRequireDeserialization(){return!0}get(e){return ym(this,void 0,void 0,(function*(){return new Promise((t=>{this.chromeStorageApi.get(e,(i=>{null==i||null==i[e]?t(null):t(i[e])}))}))}))}has(e){return ym(this,void 0,void 0,(function*(){return null!=(yield this.get(e))}))}save(e,t){return ym(this,void 0,void 0,(function*(){if(null==t)return this.remove(e);t instanceof Set&&(t=Array.from(t));const i={[e]:t};return new Promise((e=>{this.chromeStorageApi.set(i,(()=>{e()}))}))}))}remove(e){return ym(this,void 0,void 0,(function*(){return new Promise((t=>{this.chromeStorageApi.remove(e,(()=>{t()}))}))}))}}class fm extends vm{constructor(){super(chrome.storage.local)}}function gm(e){return bp(e)}class mm extends vm{constructor(){super(chrome.storage.session)}}var wm=function(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},Sm=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},bm=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Pm="localEncryptionKey",km="session";class Om extends zo{constructor(e,t){super(),this.encryptService=e,this.keyGenerationService=t,this.cache=new Map,this.localStorage=new fm,this.sessionStorage=new mm,this.updatesSubject=new Cn.x,this.updates$=this.updatesSubject.asObservable()}get valuesRequireDeserialization(){return!0}get(e,t){return bm(this,void 0,void 0,(function*(){return this.cache.has(e)?this.cache.get(e):yield this.getBypassCache(e,t)}))}getBypassCache(e,t){return bm(this,void 0,void 0,(function*(){const i=yield this.getLocalSession(yield this.getSessionEncKey());if(null==i||!Object.keys(i).includes(e))return null;let n=i[e];return null!=(null==t?void 0:t.deserializer)&&(n=t.deserializer(n)),this.cache.set(e,n),this.cache.get(e)}))}has(e){return bm(this,void 0,void 0,(function*(){return null!=(yield this.get(e))}))}save(e,t){var i;return bm(this,void 0,void 0,(function*(){null==t?this.cache.delete(e):this.cache.set(e,t);const n=yield this.getSessionEncKey(),r=null!==(i=yield this.getLocalSession(n))&&void 0!==i?i:{};r[e]=t,yield this.setLocalSession(r,n)}))}remove(e){return bm(this,void 0,void 0,(function*(){yield this.save(e,null)}))}getLocalSession(e){return bm(this,void 0,void 0,(function*(){const t=yield this.localStorage.get(km);if(null==t)return null;const i=yield this.encryptService.decryptToUtf8(new z(t),e);return null==i?(yield this.setSessionEncKey(null),yield this.localStorage.remove(km),null):JSON.parse(i)}))}setLocalSession(e,t){return bm(this,void 0,void 0,(function*(){yield this.setEncryptedLocalSession(e,t)}))}setDecryptedLocalSession(e){return bm(this,void 0,void 0,(function*(){const t=JSON.parse(JSON.stringify(e));null==e?yield this.localStorage.remove(km):yield this.localStorage.save(km,t)}))}setEncryptedLocalSession(e,t){return bm(this,void 0,void 0,(function*(){const i=JSON.stringify(e),n=yield this.encryptService.encrypt(i,t);if(null==n)return yield this.localStorage.remove(km);yield this.localStorage.save(km,n.encryptedString)}))}getSessionEncKey(){return bm(this,void 0,void 0,(function*(){let e=yield this.sessionStorage.get(Pm);if(null==e||0==Object.keys(e).length){return e=(yield this.keyGenerationService.createKeyWithPurpose(128,"ephemeral","bitwarden-ephemeral")).derivedKey,yield this.setSessionEncKey(e),e}return N.fromJSON(e)}))}setSessionEncKey(e){return bm(this,void 0,void 0,(function*(){null==e?yield this.sessionStorage.remove(Pm):yield this.sessionStorage.save(Pm,e)}))}}wm([function(e,t,i){i.value,i.value=function(...e){throw new Error("This method should not be called, it is protected by a disabled dev flag.")}},Sm("design:type",Function),Sm("design:paramtypes",[Object]),Sm("design:returntype",Promise)],Om.prototype,"setDecryptedLocalSession",null);var Cm=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Am extends zo{constructor(){super(...arguments),this.store={},this.updatesSubject=new Cn.x}get valuesRequireDeserialization(){return!0}get updates$(){return this.updatesSubject.asObservable()}get(e){const t=this.store[e];if(t){const e=JSON.parse(t);return Promise.resolve(e)}return Promise.resolve(null)}has(e){return Cm(this,void 0,void 0,(function*(){return null!=(yield this.get(e))}))}save(e,t){return null==t?this.remove(e):(this.store[e]=JSON.stringify(t),this.updatesSubject.next({key:e,updateType:"save"}),Promise.resolve())}remove(e){return delete this.store[e],this.updatesSubject.next({key:e,updateType:"remove"}),Promise.resolve()}getBypassCache(e){return this.get(e)}}var Dm=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class xm extends Am{constructor(){super(),this._ports=[],xg.addListener(chrome.runtime.onConnect,(e=>{if(e.name!==function(e){switch(e){case chrome.storage.local:return"local";case chrome.storage.sync:return"sync";case chrome.storage.session:return"session";default:throw new Error("Unknown storage location")}}(chrome.storage.session))return;this._ports.push(e);const t=this.onMessageFromForeground.bind(this);e.onDisconnect.addListener((()=>{this._ports.splice(this._ports.indexOf(e),1),e.onMessage.removeListener(t)})),e.onMessage.addListener(t),this.sendMessageTo(e,{action:"initialization",data:Array.from(Object.keys(this.store))})})),this.updates$.subscribe((e=>{this.broadcastMessage({action:"subject_update",data:e})}))}onMessageFromForeground(e,t){var i;return Dm(this,void 0,void 0,(function*(){if("background"===e.originator)return;let n=null;switch(e.action){case"get":case"getBypassCache":case"has":n=yield this[e.action](e.key);break;case"save":yield this.save(e.key,JSON.parse(null!==(i=e.data)&&void 0!==i?i:null));break;case"remove":yield this.remove(e.key)}this.sendMessageTo(t,{id:e.id,key:e.key,data:JSON.stringify(n)})}))}broadcastMessage(e){this._ports.forEach((t=>{this.sendMessageTo(t,e)}))}sendMessageTo(e,t){e.postMessage(Object.assign(Object.assign({},t),{originator:"background"}))}}var Im=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Um(e,t){return lm(e,"keyGenerationService",t,(()=>Im(this,void 0,void 0,(function*(){return new Ko(yield dm(e,t))}))))}var Tm=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Nm(e,t){return lm(e,"diskStorageService",t,(()=>new fm))}function Rm(e,t){return lm(e,"secureStorageService",t,(()=>new fm))}function Em(e,t){return lm(e,"memoryStorageService",t,(()=>Tm(this,void 0,void 0,(function*(){return new xm}))))}var Fm=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Mm(e,t){return Fm(this,void 0,void 0,(function*(){return lm(e,"storageServiceProvider",t,(()=>Fm(this,void 0,void 0,(function*(){return new Xc(yield function(e,t){return lm(e,"diskStorageService",t,(()=>new fm))}(e,t),yield Em(e,t))}))))}))}var Km=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Lm(e,t){return Km(this,void 0,void 0,(function*(){return lm(e,"globalStateProvider",t,(()=>Km(this,void 0,void 0,(function*(){return new Pd(yield Mm(e,t))}))))}))}class zm extends Ag{constructor(e,t,i,n){super(t,i,n),this.messagingService=e}showToast(e,t,i,n){this.messagingService.send("showToast",{text:i,title:t,type:e,options:n})}}class Vm{send(e,t={}){return xg.sendMessage(e,t)}}function Bm(e,t){return lm(e,"messagingService",t,(()=>new Vm))}var _m=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function jm(e,t){return lm(e,"platformUtilsService",t,(()=>_m(this,void 0,void 0,(function*(){return new zm(yield Bm(e,t),t.platformUtilsServiceOptions.clipboardWriteCallback,t.platformUtilsServiceOptions.biometricCallback,t.platformUtilsServiceOptions.win)}))))}var $m=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};var Wm=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function qm(e,t){return Wm(this,void 0,void 0,(function*(){return lm(e,"singleUserStateProvider",t,(()=>Wm(this,void 0,void 0,(function*(){return new Cd(yield Mm(e,t),yield function(e,t){return $m(this,void 0,void 0,(function*(){return lm(e,"stateEventRegistrarService",t,(()=>$m(this,void 0,void 0,(function*(){return new Ii(yield Lm(e,t),yield Mm(e,t))}))))}))}(e,t))}))))}))}var Hm=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Gm(e,t){return lm(e,"tokenService",t,(()=>Hm(this,void 0,void 0,(function*(){return new Sr(yield qm(e,t),yield Lm(e,t),(yield jm(e,t)).supportsSecureStorage(),yield Rm(e,t),yield Um(e,t),yield hm(e,t),yield cm(e,t))}))))}var Jm=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};var Ym,Qm=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Xm(e,t){return lm(e,"accountService",t,(()=>Qm(this,void 0,void 0,(function*(){return new Tn(yield Bm(e,t),yield cm(e,t),yield Lm(e,t))}))))}!function(e){e.US="US",e.EU="EU",e.SelfHosted="Self-hosted"}(Ym||(Ym={}));class Zm{}var ew=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class tw{static fromJSON(e){return Object.assign(new tw,e)}}const iw=new jt(fi,"environment",{deserializer:tw.fromJSON}),nw=new jt(gi,"cloudRegion",{deserializer:e=>e}),rw=[{key:Ym.US,domain:"bitwarden.com",urls:{base:null,api:"https://api.bitwarden.com",identity:"https://identity.bitwarden.com",icons:"https://icons.bitwarden.net",webVault:"https://vault.bitwarden.com",notifications:"https://notifications.bitwarden.com",events:"https://events.bitwarden.com",scim:"https://scim.bitwarden.com"}},{key:Ym.EU,domain:"bitwarden.eu",urls:{base:null,api:"https://api.bitwarden.eu",identity:"https://identity.bitwarden.eu",icons:"https://icons.bitwarden.eu",webVault:"https://vault.bitwarden.eu",notifications:"https://notifications.bitwarden.eu",events:"https://events.bitwarden.eu",scim:"https://scim.bitwarden.eu"}}],sw=Ym.US,ow=rw.find((e=>e.key===sw));class aw{constructor(e,t){this.stateProvider=e,this.accountService=t,this.activeAccountId$=this.accountService.activeAccount$.pipe((0,q.U)((e=>null==e?void 0:e.id))),this.globalState=this.stateProvider.getGlobal(iw),this.globalCloudRegionState=this.stateProvider.getGlobal(nw);const i=this.activeAccountId$.pipe((0,j.x)(((e,t)=>e==t)));this.environment$=i.pipe((0,c.w)((e=>e?this.stateProvider.getUser(e,iw).state$:this.stateProvider.getGlobal(iw).state$)),(0,q.U)((e=>this.buildEnvironment(null==e?void 0:e.region,null==e?void 0:e.urls)))),this.cloudWebVaultUrl$=i.pipe((0,c.w)((e=>e?this.stateProvider.getUser(e,nw).state$:this.stateProvider.getGlobal(nw).state$)),(0,q.U)((e=>{if(null!=e){const t=this.getRegionConfig(e);if(null!=t)return t.urls.webVault}return ow.urls.webVault})))}availableRegions(){var e;const t=null!==(e={ENV:"production"}.ADDITIONAL_REGIONS)&&void 0!==e?e:[];return rw.concat(t)}getRegionConfig(e){return this.availableRegions().find((t=>t.key===e))}setEnvironment(e,t){return ew(this,void 0,void 0,(function*(){return null==this.getRegionConfig(e)&&(e=Ym.SelfHosted),e==Ym.SelfHosted&&cw(t)&&(e=sw),e!=Ym.SelfHosted?(yield this.globalState.update((()=>({region:e,urls:null}))),null):(t.base=lw(t.base),t.webVault=lw(t.webVault),t.api=lw(t.api),t.identity=lw(t.identity),t.icons=lw(t.icons),t.notifications=lw(t.notifications),t.events=lw(t.events),t.keyConnector=lw(t.keyConnector),t.scim=null,yield this.globalState.update((()=>({region:e,urls:{base:t.base,api:t.api,identity:t.identity,webVault:t.webVault,icons:t.icons,notifications:t.notifications,events:t.events,keyConnector:t.keyConnector}}))),t)}))}buildEnvironment(e,t){if(null==this.getRegionConfig(e)&&(e=Ym.SelfHosted),e==Ym.SelfHosted&&cw(t)&&(e=sw),e!=Ym.SelfHosted){const t=this.getRegionConfig(e);if(null!=t)return new uw(t)}return new hw(t)}setCloudRegion(e,t){return ew(this,void 0,void 0,(function*(){null==e?yield this.globalCloudRegionState.update((()=>t)):yield this.stateProvider.getUser(e,nw).update((()=>t))}))}getEnvironment(e){return ew(this,void 0,void 0,(function*(){if(null==e)return yield(0,r.z)(this.environment$);const t=yield this.getEnvironmentState(e);return this.buildEnvironment(t.region,t.urls)}))}getEnvironmentState(e){return ew(this,void 0,void 0,(function*(){const t=yield(0,r.z)(this.activeAccountId$);return null==t?yield(0,r.z)(this.globalState.state$):yield(0,r.z)(this.stateProvider.getUser(null!=e?e:t,iw).state$)}))}seedUserEnvironment(e){return ew(this,void 0,void 0,(function*(){const t=yield(0,r.z)(this.globalState.state$);yield this.stateProvider.getUser(e,iw).update((()=>t))}))}}function lw(e){return null==e||""===e?null:((e=e.replace(/\/+$/g,"")).startsWith("http://")||e.startsWith("https://")||(e="https://"+e),e.trim())}function cw(e){return null==e||null==e.base&&null==e.webVault&&null==e.api&&null==e.identity&&null==e.icons&&null==e.notifications&&null==e.events}class dw{constructor(e,t){this.region=e,this.urls=t,e==Ym.SelfHosted&&(this.urls.scim=null)}getRegion(){return this.region}getUrls(){return{base:this.urls.base,webVault:this.urls.webVault,api:this.urls.api,identity:this.urls.identity,icons:this.urls.icons,notifications:this.urls.notifications,events:this.urls.events,keyConnector:this.urls.keyConnector,scim:this.urls.scim}}hasBaseUrl(){return null!=this.urls.base}getWebVaultUrl(){return this.getUrl("webVault","")}getApiUrl(){return this.getUrl("api","/api")}getEventsUrl(){return this.getUrl("events","/events")}getIconsUrl(){return this.getUrl("icons","/icons")}getIdentityUrl(){return this.getUrl("identity","/identity")}getKeyConnectorUrl(){return this.urls.keyConnector}getNotificationsUrl(){return this.getUrl("notifications","/notifications")}getScimUrl(){return null!=this.urls.scim?this.urls.scim+"/v2":"https://vault.bitwarden.com"===this.getWebVaultUrl()?"https://scim.bitwarden.com/v2":this.getWebVaultUrl()+"/scim/v2"}getSendUrl(){return"https://vault.bitwarden.com"===this.getWebVaultUrl()?"https://send.bitwarden.com/#":this.getWebVaultUrl()+"/#/send/"}isCloud(){return this.region!==Ym.SelfHosted}getUrl(e,t){return null!=this.urls[e]?this.urls[e]:this.urls.base?this.urls.base+t:ow.urls[e]}}class uw extends dw{constructor(e){super(e.key,e.urls),this.config=e}getHostname(){return this.config.domain}}class hw extends dw{constructor(e){super(Ym.SelfHosted,e)}getHostname(){return p.getHost(this.getWebVaultUrl())}}var pw=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class yw extends aw{constructor(e,t,i){super(t,i),this.logService=e}hasManagedEnvironment(){return pw(this,void 0,void 0,(function*(){try{return null!=(yield this.getManagedEnvironment())}catch(e){return this.logService.error(e),!1}}))}settingsHaveChanged(){return pw(this,void 0,void 0,(function*(){if(!(yield this.hasManagedEnvironment()))return!1;const e=yield this.getManagedEnvironment(),t=(yield(0,r.z)(this.environment$)).getUrls();return e.base!=t.base||e.webVault!=t.webVault||e.api!=t.api||e.identity!=t.identity||e.icons!=t.icons||e.notifications!=t.notifications||e.events!=t.events}))}getManagedEnvironment(){return new Promise(((e,t)=>{if(null==chrome.storage.managed)return e(null);chrome.storage.managed.get("environment",(i=>{if(chrome.runtime.lastError)return t(chrome.runtime.lastError);e(i.environment)}))}))}setUrlsToManagedEnvironment(){return pw(this,void 0,void 0,(function*(){const e=yield this.getManagedEnvironment();yield this.setEnvironment(Ym.SelfHosted,{base:e.base,webVault:e.webVault,api:e.api,identity:e.identity,icons:e.icons,notifications:e.notifications,events:e.events})}))}}var vw=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};var fw=i(59157),gw=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class mw{constructor(e,t,i,n){this.parentState$=e,this.deriveDefinition=t,this.memoryStorage=i,this.dependencies=n,this.forcedValueSubject=new Cn.x,this.storageKey=t.storageKey;const r=this.parentState$.pipe((0,fw.b)((e=>gw(this,void 0,void 0,(function*(){let t=this.deriveDefinition.derive(e,this.dependencies);t instanceof Promise&&(t=yield t);const i=t;return yield this.storeValue(i),i})))));this.state$=(0,hd.T)(this.forcedValueSubject,r).pipe((0,pd.B)({connector:()=>new yd.t(1),resetOnRefCountZero:()=>(0,vd.H)(this.deriveDefinition.cleanupDelayMs).pipe((0,fw.b)((()=>gw(this,void 0,void 0,(function*(){return this.deriveDefinition.clearOnCleanup&&(yield this.memoryStorage.remove(this.storageKey)),!0})))))}))}forceValue(e){return gw(this,void 0,void 0,(function*(){return yield this.storeValue(e),this.forcedValueSubject.next(e),e}))}storeValue(e){return this.memoryStorage.save(this.storageKey,{derived:!0,value:e})}}class ww{constructor(e){this.memoryStorage=e,this.cache={}}get(e,t,i){const n=t.buildCacheKey(),r=this.cache[n];if(null!=r)return r;const s=this.buildDerivedState(e,t,i);return this.cache[n]=s,s}buildDerivedState(e,t,i){return new mw(e,t,this.memoryStorage,i)}}var Sw=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class bw extends mw{constructor(e,t,i,n){super(e,t,i,n),this.portSubscriptions=new Map;const r=t.buildCacheKey();xg.addListener(chrome.runtime.onConnect,(e=>{if(e.name!==r)return;const t=this.onMessageFromForeground.bind(this);e.onDisconnect.addListener((()=>{var i;null===(i=this.portSubscriptions.get(e))||void 0===i||i.unsubscribe(),this.portSubscriptions.delete(e),e.onMessage.removeListener(t)})),e.onMessage.addListener(t);const i=this.state$.subscribe();this.portSubscriptions.set(e,i)}))}onMessageFromForeground(e,t){return Sw(this,void 0,void 0,(function*(){if("background"!==e.originator)switch(e.action){case"nextState":{const i=JSON.parse(e.data),n=this.deriveDefinition.deserialize(i);yield this.forceValue(n),yield this.sendResponse(e,{action:"resolve"},t);break}}}))}sendResponse(e,t,i){return Sw(this,void 0,void 0,(function*(){this.sendMessage(Object.assign(Object.assign({},t),{id:e.id}),i)}))}sendMessage(e,t){return Sw(this,void 0,void 0,(function*(){t.postMessage(Object.assign(Object.assign({},e),{originator:"background"}))}))}}class Pw extends ww{buildDerivedState(e,t,i){return new bw(e,t,this.memoryStorage,i)}}var kw=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};var Ow=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Cw(e,t){return Ow(this,void 0,void 0,(function*(){return lm(e,"stateProvider",t,(()=>Ow(this,void 0,void 0,(function*(){return new Dd(yield function(e,t){return vw(this,void 0,void 0,(function*(){return lm(e,"activeUserStateProvider",t,(()=>vw(this,void 0,void 0,(function*(){return new ud(yield Xm(e,t),yield qm(e,t))}))))}))}(e,t),yield qm(e,t),yield Lm(e,t),yield function(e,t){return kw(this,void 0,void 0,(function*(){return lm(e,"derivedStateProvider",t,(()=>kw(this,void 0,void 0,(function*(){return new Pw(yield Em(e,t))}))))}))}(e,t))}))))}))}var Aw=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Dw(e,t){return lm(e,"environmentService",t,(()=>Aw(this,void 0,void 0,(function*(){return new yw(yield cm(e,t),yield Cw(e,t),yield Xm(e,t))}))))}class xw{}class Iw{constructor(e){this.id=null,this.size=null,this.sizeName=null,this.fileName=null,e&&(this.id=e.id,this.size=e.size,this.sizeName=e.sizeName)}get fileSize(){try{if(null!=this.size)return parseInt(this.size,null)}catch(e){}return 0}static fromJSON(e){return null==e?null:Object.assign(new Iw,e)}}class Uw{constructor(e){this.text=null,e&&(this.hidden=e.hidden)}get maskedText(){return null!=this.text?"••••••••":null}static fromJSON(e){return null==e?null:Object.assign(new Uw,e)}}class Tw{constructor(e){this.id=null,this.accessId=null,this.name=null,this.notes=null,this.type=null,this.text=new Uw,this.file=new Iw,this.maxAccessCount=null,this.accessCount=0,this.revisionDate=null,this.deletionDate=null,this.expirationDate=null,this.password=null,this.disabled=!1,this.hideEmail=!1,e&&(this.id=e.id,this.accessId=e.accessId,this.type=e.type,this.maxAccessCount=e.maxAccessCount,this.accessCount=e.accessCount,this.revisionDate=e.revisionDate,this.deletionDate=e.deletionDate,this.expirationDate=e.expirationDate,this.disabled=e.disabled,this.password=e.password,this.hideEmail=e.hideEmail)}get urlB64Key(){return p.fromBufferToUrlB64(this.key)}get maxAccessCountReached(){return null!=this.maxAccessCount&&this.accessCount>=this.maxAccessCount}get expired(){return null!=this.expirationDate&&this.expirationDate<=new Date}get pendingDelete(){return this.deletionDate<=new Date}toJSON(){return p.merge(Object.assign({},this),{key:p.fromBufferToB64(this.key)})}static fromJSON(e){return null==e?null:Object.assign(new Tw,e,{key:p.fromB64ToArray(e.key),cryptoKey:N.fromJSON(e.cryptoKey),text:Uw.fromJSON(e.text),file:Iw.fromJSON(e.file),revisionDate:null==e.revisionDate?null:new Date(e.revisionDate),deletionDate:null==e.deletionDate?null:new Date(e.deletionDate),expirationDate:null==e.expirationDate?null:new Date(e.expirationDate)})}}class Nw{constructor(e){this.accounts={},this.authenticatedAccounts=[],this.accountActivity={},this.globals=e}static fromJSON(e,t){return null==e?null:Object.assign(new Nw(null),e,{accounts:Nw.buildAccountMapFromJSON(null==e?void 0:e.accounts,t)})}static buildAccountMapFromJSON(e,t){if(!e)return{};const i={};for(const n in e)i[n]=t(e[n]);return i}}var Rw=function(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},Ew=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},Fw=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Mw="state",Kw="global",Lw="authenticatedAccounts",zw="activeUserId",Vw="tempAccountSettings",Bw="accountActivity",_w="_user_auto",jw="_user_biometric",$w="_masterkey_auto",Ww="_masterkey_biometric",qw="_masterkey",Hw="DuckDuckGoSharedKey";class Gw{constructor(e,t,i,n,r,s,o,a,l,c=!0){this.storageService=e,this.secureStorageService=t,this.memoryStorageService=i,this.logService=n,this.stateFactory=r,this.accountService=s,this.environmentService=o,this.tokenService=a,this.migrationRunner=l,this.useAccountCache=c,this.accountsSubject=new te.X({}),this.accounts$=this.accountsSubject.asObservable(),this.activeAccountSubject=new te.X(null),this.activeAccount$=this.activeAccountSubject.asObservable(),this.hasBeenInited=!1,this.isRecoveredSession=!1,this.accountDiskCache=new te.X({}),this.accountDeserializer=pt.fromJSON,this.activeAccountUnlocked$=this.accountService.activeAccount$.pipe((0,q.U)((e=>(null==e?void 0:e.status)===On.Unlocked)))}init(e={}){return Fw(this,void 0,void 0,(function*(){const{runMigrations:t=!0}=e;this.hasBeenInited||(t?yield this.migrationRunner.run():yield this.migrationRunner.waitForCompletion(),yield this.state().then((e=>Fw(this,void 0,void 0,(function*(){null==e?yield this.setState(new Nw(this.createGlobals())):this.isRecoveredSession=!0})))),yield this.initAccountState(),this.hasBeenInited=!0)}))}initAccountState(){return Fw(this,void 0,void 0,(function*(){this.isRecoveredSession||(yield this.updateState((e=>Fw(this,void 0,void 0,(function*(){var t;e.authenticatedAccounts=null!==(t=yield this.storageService.get(Lw))&&void 0!==t?t:[];for(const t in e.authenticatedAccounts)null!=t&&(e=yield this.syncAccountFromDisk(e.authenticatedAccounts[t]));const i=yield this.storageService.get(zw);if(null!=i&&(e.activeUserId=i),yield this.pushAccounts(),this.activeAccountSubject.next(e.activeUserId),null!=e.activeUserId&&null==this.accountsSubject.value[e.activeUserId]){const t=yield this.getAccountFromDisk({userId:e.activeUserId});yield this.accountService.addAccount(e.activeUserId,{name:t.profile.name,email:t.profile.email,status:On.LoggedOut})}return yield this.accountService.switchAccount(e.activeUserId),e})))))}))}syncAccountFromDisk(e){return Fw(this,void 0,void 0,(function*(){if(null==e)return;const t=yield this.getAccountFromDisk({userId:e}),i=yield this.updateState((i=>Fw(this,void 0,void 0,(function*(){return null==i.accounts&&(i.accounts={}),i.accounts[e]=this.createAccount(),i.accounts[e].profile=t.profile,i})))),n=yield this.tokenService.getAccessToken(e),r=yield this.getUserKeyAutoUnlock({userId:e}),s=null==n?On.LoggedOut:null==r?On.Locked:On.Unlocked;return yield this.accountService.addAccount(e,{status:s,name:t.profile.name,email:t.profile.email}),i}))}addAccount(e){return Fw(this,void 0,void 0,(function*(){yield this.environmentService.seedUserEnvironment(e.profile.userId),yield this.updateState((t=>Fw(this,void 0,void 0,(function*(){return t.authenticatedAccounts.push(e.profile.userId),yield this.storageService.save(Lw,t.authenticatedAccounts),t.accounts[e.profile.userId]=e,t})))),yield this.scaffoldNewAccountStorage(e),yield this.setLastActive((new Date).getTime(),{userId:e.profile.userId}),yield this.accountService.addAccount(e.profile.userId,{status:On.Locked,name:e.profile.name,email:e.profile.email}),yield this.setActiveUser(e.profile.userId)}))}setActiveUser(e){return Fw(this,void 0,void 0,(function*(){yield this.clearDecryptedDataForActiveUser(),yield this.updateState((t=>Fw(this,void 0,void 0,(function*(){return t.activeUserId=e,yield this.storageService.save(zw,e),this.activeAccountSubject.next(t.activeUserId),yield this.accountService.switchAccount(e),t})))),yield this.pushAccounts()}))}clean(e){var t;return Fw(this,void 0,void 0,(function*(){e=this.reconcileOptions(e,yield this.defaultInMemoryOptions()),yield this.deAuthenticateAccount(e.userId);let i=null===(t=yield this.state())||void 0===t?void 0:t.activeUserId;return e.userId===i&&(i=yield this.dynamicallySetActiveUser()),yield this.removeAccountFromDisk(null==e?void 0:e.userId),yield this.removeAccountFromMemory(null==e?void 0:e.userId),yield this.pushAccounts(),i}))}getAddEditCipherInfo(e){var t;return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(e,yield this.defaultInMemoryOptions())),n=null===(t=null==i?void 0:i.data)||void 0===t?void 0:t.addEditCipherInfo;return null==n?null:{cipher:null!=(null==n?void 0:n.cipher.toJSON)?n.cipher:it.fromJSON(null==n?void 0:n.cipher),collectionIds:null==n?void 0:n.collectionIds}}))}setAddEditCipherInfo(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultInMemoryOptions()));i.data.addEditCipherInfo=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultInMemoryOptions()))}))}getBiometricFingerprintValidated(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null!==(i=null===(t=yield this.getGlobals(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.biometricFingerprintValidated)&&void 0!==i&&i}))}setBiometricFingerprintValidated(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getGlobals(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.biometricFingerprintValidated=e,yield this.saveGlobals(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getConvertAccountToKeyConnector(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.profile)||void 0===i?void 0:i.convertAccountToKeyConnector}))}setConvertAccountToKeyConnector(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.profile.convertAccountToKeyConnector=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getCryptoMasterKey(e){var t;return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(e,yield this.defaultInMemoryOptions()));return null===(t=null==i?void 0:i.keys)||void 0===t?void 0:t.cryptoMasterKey}))}getMasterKey(e){var t;return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(e,yield this.defaultInMemoryOptions()));return null===(t=null==i?void 0:i.keys)||void 0===t?void 0:t.masterKey}))}setMasterKey(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultInMemoryOptions()));i.keys.masterKey=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultInMemoryOptions()))}))}getMasterKeyEncryptedUserKey(e){var t;return Fw(this,void 0,void 0,(function*(){return null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.keys.masterKeyEncryptedUserKey}))}setMasterKeyEncryptedUserKey(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.keys.masterKeyEncryptedUserKey=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getUserKeyAutoUnlock(e){return Fw(this,void 0,void 0,(function*(){return null==(null==(e=this.reconcileOptions(this.reconcileOptions(e,{keySuffix:"auto"}),yield this.defaultSecureStorageOptions()))?void 0:e.userId)?null:yield this.secureStorageService.get(`${e.userId}${_w}`,e)}))}setUserKeyAutoUnlock(e,t){return Fw(this,void 0,void 0,(function*(){null!=(null==(t=this.reconcileOptions(this.reconcileOptions(t,{keySuffix:"auto"}),yield this.defaultSecureStorageOptions()))?void 0:t.userId)&&(yield this.saveSecureStorageKey(_w,e,t))}))}getUserKeyBiometric(e){return Fw(this,void 0,void 0,(function*(){return null==(null==(e=this.reconcileOptions(this.reconcileOptions(e,{keySuffix:"biometric"}),yield this.defaultSecureStorageOptions()))?void 0:e.userId)?null:yield this.secureStorageService.get(`${e.userId}${jw}`,e)}))}hasUserKeyBiometric(e){return Fw(this,void 0,void 0,(function*(){return null!=(null==(e=this.reconcileOptions(this.reconcileOptions(e,{keySuffix:"biometric"}),yield this.defaultSecureStorageOptions()))?void 0:e.userId)&&(yield this.secureStorageService.has(`${e.userId}${jw}`,e))}))}setUserKeyBiometric(e,t){return Fw(this,void 0,void 0,(function*(){null!=(null==(t=this.reconcileOptions(this.reconcileOptions(t,{keySuffix:"biometric"}),yield this.defaultSecureStorageOptions()))?void 0:t.userId)&&(yield this.saveSecureStorageKey(jw,e,t))}))}getPinKeyEncryptedUserKey(e){var t,i;return Fw(this,void 0,void 0,(function*(){return z.fromJSON(null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.settings)||void 0===i?void 0:i.pinKeyEncryptedUserKey)}))}setPinKeyEncryptedUserKey(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.settings.pinKeyEncryptedUserKey=null==e?void 0:e.encryptedString,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getPinKeyEncryptedUserKeyEphemeral(e){var t,i;return Fw(this,void 0,void 0,(function*(){return z.fromJSON(null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultInMemoryOptions())))||void 0===t?void 0:t.settings)||void 0===i?void 0:i.pinKeyEncryptedUserKeyEphemeral)}))}setPinKeyEncryptedUserKeyEphemeral(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultInMemoryOptions()));i.settings.pinKeyEncryptedUserKeyEphemeral=null==e?void 0:e.encryptedString,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultInMemoryOptions()))}))}getCryptoMasterKeyAuto(e){return Fw(this,void 0,void 0,(function*(){return null==(null==(e=this.reconcileOptions(this.reconcileOptions(e,{keySuffix:"auto"}),yield this.defaultSecureStorageOptions()))?void 0:e.userId)?null:yield this.secureStorageService.get(`${e.userId}${$w}`,e)}))}setCryptoMasterKeyAuto(e,t){return Fw(this,void 0,void 0,(function*(){null!=(null==(t=this.reconcileOptions(this.reconcileOptions(t,{keySuffix:"auto"}),yield this.defaultSecureStorageOptions()))?void 0:t.userId)&&(yield this.saveSecureStorageKey($w,e,t))}))}getCryptoMasterKeyB64(e){return Fw(this,void 0,void 0,(function*(){return null==(null==(e=this.reconcileOptions(e,yield this.defaultSecureStorageOptions()))?void 0:e.userId)?null:yield this.secureStorageService.get(`${null==e?void 0:e.userId}${qw}`,e)}))}setCryptoMasterKeyB64(e,t){return Fw(this,void 0,void 0,(function*(){null!=(null==(t=this.reconcileOptions(t,yield this.defaultSecureStorageOptions()))?void 0:t.userId)&&(yield this.saveSecureStorageKey(qw,e,t))}))}getCryptoMasterKeyBiometric(e){return Fw(this,void 0,void 0,(function*(){return null==(null==(e=this.reconcileOptions(this.reconcileOptions(e,{keySuffix:"biometric"}),yield this.defaultSecureStorageOptions()))?void 0:e.userId)?null:yield this.secureStorageService.get(`${e.userId}${Ww}`,e)}))}hasCryptoMasterKeyBiometric(e){return Fw(this,void 0,void 0,(function*(){return null!=(null==(e=this.reconcileOptions(this.reconcileOptions(e,{keySuffix:"biometric"}),yield this.defaultSecureStorageOptions()))?void 0:e.userId)&&(yield this.secureStorageService.has(`${e.userId}${Ww}`,e))}))}setCryptoMasterKeyBiometric(e,t){return Fw(this,void 0,void 0,(function*(){null!=(null==(t=this.reconcileOptions(this.reconcileOptions(t,{keySuffix:"biometric"}),yield this.defaultSecureStorageOptions()))?void 0:t.userId)&&(yield this.saveSecureStorageKey(Ww,e,t))}))}getDecryptedCiphers(e){var t,i,n;return Fw(this,void 0,void 0,(function*(){return null===(n=null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultInMemoryOptions())))||void 0===t?void 0:t.data)||void 0===i?void 0:i.ciphers)||void 0===n?void 0:n.decrypted}))}setDecryptedCiphers(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultInMemoryOptions()));i.data.ciphers.decrypted=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultInMemoryOptions()))}))}getDecryptedPasswordGenerationHistory(e){var t,i,n;return Fw(this,void 0,void 0,(function*(){return null===(n=null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultInMemoryOptions())))||void 0===t?void 0:t.data)||void 0===i?void 0:i.passwordGenerationHistory)||void 0===n?void 0:n.decrypted}))}setDecryptedPasswordGenerationHistory(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultInMemoryOptions()));i.data.passwordGenerationHistory.decrypted=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultInMemoryOptions()))}))}getDecryptedPinProtected(e){var t,i,n;return Fw(this,void 0,void 0,(function*(){return null===(n=null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultInMemoryOptions())))||void 0===t?void 0:t.settings)||void 0===i?void 0:i.pinProtected)||void 0===n?void 0:n.decrypted}))}setDecryptedPinProtected(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultInMemoryOptions()));i.settings.pinProtected.decrypted=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultInMemoryOptions()))}))}getDecryptedSends(e){var t,i,n;return Fw(this,void 0,void 0,(function*(){return null===(n=null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultInMemoryOptions())))||void 0===t?void 0:t.data)||void 0===i?void 0:i.sends)||void 0===n?void 0:n.decrypted}))}setDecryptedSends(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultInMemoryOptions()));i.data.sends.decrypted=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultInMemoryOptions()))}))}getDisableGa(e){var t,i,n;return Fw(this,void 0,void 0,(function*(){return null!==(n=null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.settings)||void 0===i?void 0:i.disableGa)&&void 0!==n&&n}))}setDisableGa(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.settings.disableGa=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getDuckDuckGoSharedKey(e){return Fw(this,void 0,void 0,(function*(){return null==(null==(e=this.reconcileOptions(e,yield this.defaultSecureStorageOptions()))?void 0:e.userId)?null:yield this.secureStorageService.get(Hw,e)}))}setDuckDuckGoSharedKey(e,t){return Fw(this,void 0,void 0,(function*(){null!=(null==(t=this.reconcileOptions(t,yield this.defaultSecureStorageOptions()))?void 0:t.userId)&&(null==e?yield this.secureStorageService.remove(Hw,t):yield this.secureStorageService.save(Hw,e,t))}))}getDeviceKey(e){var t;return Fw(this,void 0,void 0,(function*(){if(null==(null==(e=this.reconcileOptions(e,yield this.defaultOnDiskLocalOptions()))?void 0:e.userId))return null;const i=yield this.getAccount(e),n=null===(t=null==i?void 0:i.keys)||void 0===t?void 0:t.deviceKey;return null!=n?N.fromJSON(n):null}))}setDeviceKey(e,t){var i;return Fw(this,void 0,void 0,(function*(){if(null==(null==(t=this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()))?void 0:t.userId))return;const n=yield this.getAccount(t);n.keys.deviceKey=null!==(i=null==e?void 0:e.toJSON())&&void 0!==i?i:null,yield this.saveAccount(n,t)}))}getAdminAuthRequest(e){return Fw(this,void 0,void 0,(function*(){if(null==(null==(e=this.reconcileOptions(e,yield this.defaultOnDiskLocalOptions()))?void 0:e.userId))return null;const t=yield this.getAccount(e);return(null==t?void 0:t.adminAuthRequest)?Ie.fromJSON(t.adminAuthRequest):null}))}setAdminAuthRequest(e,t){return Fw(this,void 0,void 0,(function*(){if(null==(null==(t=this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()))?void 0:t.userId))return;const i=yield this.getAccount(t);i.adminAuthRequest=null==e?void 0:e.toJSON(),yield this.saveAccount(i,t)}))}getShouldTrustDevice(e){var t,i;return Fw(this,void 0,void 0,(function*(){if(null==(null==(e=this.reconcileOptions(e,yield this.defaultOnDiskLocalOptions()))?void 0:e.userId))return null;const n=yield this.getAccount(e);return null!==(i=null===(t=null==n?void 0:n.settings)||void 0===t?void 0:t.trustDeviceChoiceForDecryption)&&void 0!==i?i:null}))}setShouldTrustDevice(e,t){return Fw(this,void 0,void 0,(function*(){if(null==(null==(t=this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()))?void 0:t.userId))return;const i=yield this.getAccount(t);i.settings.trustDeviceChoiceForDecryption=e,yield this.saveAccount(i,t)}))}getEmail(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultInMemoryOptions())))||void 0===t?void 0:t.profile)||void 0===i?void 0:i.email}))}setEmail(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultInMemoryOptions()));i.profile.email=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultInMemoryOptions()))}))}getEmailVerified(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null!==(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.profile.emailVerified)&&void 0!==i&&i}))}setEmailVerified(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.profile.emailVerified=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getEnableBrowserIntegration(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null!==(i=null===(t=yield this.getGlobals(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.enableBrowserIntegration)&&void 0!==i&&i}))}setEnableBrowserIntegration(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getGlobals(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.enableBrowserIntegration=e,yield this.saveGlobals(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getEnableBrowserIntegrationFingerprint(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null!==(i=null===(t=yield this.getGlobals(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.enableBrowserIntegrationFingerprint)&&void 0!==i&&i}))}setEnableBrowserIntegrationFingerprint(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getGlobals(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.enableBrowserIntegrationFingerprint=e,yield this.saveGlobals(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getEncryptedCiphers(e){var t,i,n;return Fw(this,void 0,void 0,(function*(){return null===(n=null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskMemoryOptions())))||void 0===t?void 0:t.data)||void 0===i?void 0:i.ciphers)||void 0===n?void 0:n.encrypted}))}setEncryptedCiphers(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskMemoryOptions()));i.data.ciphers.encrypted=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskMemoryOptions()))}))}getEncryptedCryptoSymmetricKey(e){var t;return Fw(this,void 0,void 0,(function*(){return null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.keys.cryptoSymmetricKey.encrypted}))}getEncryptedPasswordGenerationHistory(e){var t,i,n;return Fw(this,void 0,void 0,(function*(){return null===(n=null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.data)||void 0===i?void 0:i.passwordGenerationHistory)||void 0===n?void 0:n.encrypted}))}setEncryptedPasswordGenerationHistory(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.data.passwordGenerationHistory.encrypted=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getEncryptedPinProtected(e){var t,i,n;return Fw(this,void 0,void 0,(function*(){return null===(n=null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.settings)||void 0===i?void 0:i.pinProtected)||void 0===n?void 0:n.encrypted}))}setEncryptedPinProtected(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.settings.pinProtected.encrypted=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getEncryptedSends(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskMemoryOptions())))||void 0===t?void 0:t.data)||void 0===i?void 0:i.sends.encrypted}))}setEncryptedSends(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskMemoryOptions()));i.data.sends.encrypted=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskMemoryOptions()))}))}getEverBeenUnlocked(e){var t,i,n;return Fw(this,void 0,void 0,(function*(){return null!==(n=null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultInMemoryOptions())))||void 0===t?void 0:t.profile)||void 0===i?void 0:i.everBeenUnlocked)&&void 0!==n&&n}))}setEverBeenUnlocked(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultInMemoryOptions()));i.profile.everBeenUnlocked=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultInMemoryOptions()))}))}getForceSetPasswordReason(e){var t,i,n;return Fw(this,void 0,void 0,(function*(){return null!==(n=null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskMemoryOptions())))||void 0===t?void 0:t.profile)||void 0===i?void 0:i.forceSetPasswordReason)&&void 0!==n?n:X.None}))}setForceSetPasswordReason(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskMemoryOptions()));i.profile.forceSetPasswordReason=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskMemoryOptions()))}))}getInstalledVersion(e){var t;return Fw(this,void 0,void 0,(function*(){return null===(t=yield this.getGlobals(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.installedVersion}))}setInstalledVersion(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getGlobals(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.installedVersion=e,yield this.saveGlobals(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getIsAuthenticated(e){return Fw(this,void 0,void 0,(function*(){return null!=(yield this.tokenService.getAccessToken(null==e?void 0:e.userId))&&null!=(yield this.getUserId(e))}))}getKdfConfig(e){var t,i,n,r,s,o;return Fw(this,void 0,void 0,(function*(){const a=null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.profile)||void 0===i?void 0:i.kdfIterations,l=null===(r=null===(n=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===n?void 0:n.profile)||void 0===r?void 0:r.kdfMemory,c=null===(o=null===(s=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===s?void 0:s.profile)||void 0===o?void 0:o.kdfParallelism;return new P(a,l,c)}))}setKdfConfig(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.profile.kdfIterations=e.iterations,i.profile.kdfMemory=e.memory,i.profile.kdfParallelism=e.parallelism,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getKdfType(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.profile)||void 0===i?void 0:i.kdfType}))}setKdfType(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.profile.kdfType=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getKeyHash(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.profile)||void 0===i?void 0:i.keyHash}))}setKeyHash(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.profile.keyHash=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getLastActive(e){return Fw(this,void 0,void 0,(function*(){e=this.reconcileOptions(e,yield this.defaultOnDiskOptions());const t=yield this.storageService.get(Bw,e);return null==t||Object.keys(t).length<1?null:t[e.userId]}))}setLastActive(e,t){var i;return Fw(this,void 0,void 0,(function*(){if(null==(t=this.reconcileOptions(t,yield this.defaultOnDiskOptions())).userId)return;const n=null!==(i=yield this.storageService.get(Bw,t))&&void 0!==i?i:{};n[t.userId]=e,yield this.storageService.save(Bw,n,t)}))}getLastSync(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskMemoryOptions())))||void 0===t?void 0:t.profile)||void 0===i?void 0:i.lastSync}))}setLastSync(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskMemoryOptions()));i.profile.lastSync=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskMemoryOptions()))}))}getLocalData(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskLocalOptions())))||void 0===t?void 0:t.data)||void 0===i?void 0:i.localData}))}setLocalData(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()));i.data.localData=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()))}))}getMinimizeOnCopyToClipboard(e){var t,i,n;return Fw(this,void 0,void 0,(function*(){return null!==(n=null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.settings)||void 0===i?void 0:i.minimizeOnCopyToClipboard)&&void 0!==n&&n}))}setMinimizeOnCopyToClipboard(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.settings.minimizeOnCopyToClipboard=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getOrganizationInvitation(e){var t;return Fw(this,void 0,void 0,(function*(){return null===(t=yield this.getGlobals(this.reconcileOptions(e,yield this.defaultInMemoryOptions())))||void 0===t?void 0:t.organizationInvitation}))}setOrganizationInvitation(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getGlobals(this.reconcileOptions(t,yield this.defaultInMemoryOptions()));i.organizationInvitation=e,yield this.saveGlobals(i,this.reconcileOptions(t,yield this.defaultInMemoryOptions()))}))}getPasswordGenerationOptions(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskLocalOptions())))||void 0===t?void 0:t.settings)||void 0===i?void 0:i.passwordGenerationOptions}))}setPasswordGenerationOptions(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()));i.settings.passwordGenerationOptions=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()))}))}getUsernameGenerationOptions(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskLocalOptions())))||void 0===t?void 0:t.settings)||void 0===i?void 0:i.usernameGenerationOptions}))}setUsernameGenerationOptions(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()));i.settings.usernameGenerationOptions=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()))}))}getGeneratorOptions(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskLocalOptions())))||void 0===t?void 0:t.settings)||void 0===i?void 0:i.generatorOptions}))}setGeneratorOptions(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()));i.settings.generatorOptions=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()))}))}getProtectedPin(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.settings)||void 0===i?void 0:i.protectedPin}))}setProtectedPin(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.settings.protectedPin=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getRememberedEmail(e){var t;return Fw(this,void 0,void 0,(function*(){return null===(t=yield this.getGlobals(this.reconcileOptions(e,yield this.defaultOnDiskLocalOptions())))||void 0===t?void 0:t.rememberedEmail}))}setRememberedEmail(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getGlobals(this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()));i.rememberedEmail=e,yield this.saveGlobals(i,this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()))}))}getSecurityStamp(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultInMemoryOptions())))||void 0===t?void 0:t.tokens)||void 0===i?void 0:i.securityStamp}))}setSecurityStamp(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultInMemoryOptions()));i.tokens.securityStamp=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultInMemoryOptions()))}))}getUserId(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.profile)||void 0===i?void 0:i.userId}))}getUsesKeyConnector(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.profile)||void 0===i?void 0:i.usesKeyConnector}))}setUsesKeyConnector(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.profile.usesKeyConnector=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getVaultTimeout(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskLocalOptions())))||void 0===t?void 0:t.settings)||void 0===i?void 0:i.vaultTimeout}))}setVaultTimeout(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()));i.settings.vaultTimeout=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()))}))}getVaultTimeoutAction(e){var t,i,n;return Fw(this,void 0,void 0,(function*(){const r=null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskLocalOptions())))||void 0===t?void 0:t.settings)||void 0===i?void 0:i.vaultTimeoutAction;return null!=r?r:null===(n=yield this.getGlobals(this.reconcileOptions(e,yield this.defaultOnDiskLocalOptions())))||void 0===n?void 0:n.vaultTimeoutAction}))}setVaultTimeoutAction(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()));i.settings.vaultTimeoutAction=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()))}))}getApproveLoginRequests(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskLocalOptions())))||void 0===t?void 0:t.settings)||void 0===i?void 0:i.approveLoginRequests}))}setApproveLoginRequests(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()));i.settings.approveLoginRequests=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()))}))}setServerConfig(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()));return i.settings.serverConfig=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultOnDiskLocalOptions()))}))}getServerConfig(e){var t,i;return Fw(this,void 0,void 0,(function*(){return null===(i=null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultOnDiskLocalOptions())))||void 0===t?void 0:t.settings)||void 0===i?void 0:i.serverConfig}))}getDeepLinkRedirectUrl(e){var t;return Fw(this,void 0,void 0,(function*(){return null===(t=yield this.getGlobals(this.reconcileOptions(e,yield this.defaultOnDiskOptions())))||void 0===t?void 0:t.deepLinkRedirectUrl}))}setDeepLinkRedirectUrl(e,t){return Fw(this,void 0,void 0,(function*(){const i=yield this.getGlobals(this.reconcileOptions(t,yield this.defaultOnDiskOptions()));i.deepLinkRedirectUrl=e,yield this.saveGlobals(i,this.reconcileOptions(t,yield this.defaultOnDiskOptions()))}))}getGlobals(e){return Fw(this,void 0,void 0,(function*(){let t;return this.useMemory(e.storageLocation)&&(t=yield this.getGlobalsFromMemory()),this.useDisk&&null==t&&(t=yield this.getGlobalsFromDisk(e)),null==t&&(t=this.createGlobals()),t}))}saveGlobals(e,t){return Fw(this,void 0,void 0,(function*(){return this.useMemory(t.storageLocation)?this.saveGlobalsToMemory(e):yield this.saveGlobalsToDisk(e,t)}))}getGlobalsFromMemory(){return Fw(this,void 0,void 0,(function*(){return(yield this.state()).globals}))}getGlobalsFromDisk(e){return Fw(this,void 0,void 0,(function*(){return yield this.storageService.get(Kw,e)}))}saveGlobalsToMemory(e){return Fw(this,void 0,void 0,(function*(){yield this.updateState((t=>Fw(this,void 0,void 0,(function*(){return t.globals=e,t}))))}))}saveGlobalsToDisk(e,t){return Fw(this,void 0,void 0,(function*(){t.useSecureStorage?yield this.secureStorageService.save(Kw,e,t):yield this.storageService.save(Kw,e,t)}))}getAccount(e){return Fw(this,void 0,void 0,(function*(){try{let t;return this.useMemory(e.storageLocation)&&(t=yield this.getAccountFromMemory(e)),this.useDisk(e.storageLocation)&&null==t&&(t=yield this.getAccountFromDisk(e)),t}catch(e){this.logService.error(e)}}))}getAccountFromMemory(e){return Fw(this,void 0,void 0,(function*(){return yield this.state().then((t=>Fw(this,void 0,void 0,(function*(){return null==t.accounts?null:t.accounts[yield this.getUserIdFromMemory(e)]}))))}))}getUserIdFromMemory(e){return Fw(this,void 0,void 0,(function*(){return yield this.state().then((t=>{var i,n;return null!=(null==e?void 0:e.userId)?null===(n=null===(i=t.accounts[e.userId])||void 0===i?void 0:i.profile)||void 0===n?void 0:n.userId:t.activeUserId}))}))}getAccountFromDisk(e){var t,i;return Fw(this,void 0,void 0,(function*(){if(null==(null==e?void 0:e.userId)&&null==(null===(t=yield this.state())||void 0===t?void 0:t.activeUserId))return null;if(this.useAccountCache){const t=this.accountDiskCache.value[e.userId];if(null!=t)return t}const n=(null==e?void 0:e.useSecureStorage)?null!==(i=yield this.secureStorageService.get(e.userId,e))&&void 0!==i?i:yield this.storageService.get(e.userId,this.reconcileOptions(e,{htmlStorageLocation:S.Local})):yield this.storageService.get(e.userId,e);return this.setDiskCache(e.userId,n),n}))}useMemory(e){return e===U.Memory||e===U.Both}useDisk(e){return e===U.Disk||e===U.Both}saveAccount(e,t={storageLocation:U.Both,useSecureStorage:!1}){return Fw(this,void 0,void 0,(function*(){return this.useMemory(t.storageLocation)?yield this.saveAccountToMemory(e):yield this.saveAccountToDisk(e,t)}))}saveAccountToDisk(e,t){return Fw(this,void 0,void 0,(function*(){const i=t.useSecureStorage?this.secureStorageService:this.storageService;yield i.save(`${t.userId}`,e,t),this.deleteDiskCache(t.userId)}))}saveAccountToMemory(e){return Fw(this,void 0,void 0,(function*(){null!==(yield this.getAccountFromMemory({userId:e.profile.userId}))&&(yield this.updateState((t=>new Promise((i=>{t.accounts[e.profile.userId]=e,i(t)}))))),yield this.pushAccounts()}))}scaffoldNewAccountStorage(e){return Fw(this,void 0,void 0,(function*(){const t=JSON.parse(JSON.stringify(e));yield this.scaffoldNewAccountLocalStorage(t),yield this.scaffoldNewAccountSessionStorage(t),yield this.scaffoldNewAccountMemoryStorage(t)}))}scaffoldNewAccountLocalStorage(e){return Fw(this,void 0,void 0,(function*(){const t=yield this.getAccount(this.reconcileOptions({userId:e.profile.userId},yield this.defaultOnDiskLocalOptions()));null!=(null==t?void 0:t.settings)?e.settings=t.settings:(yield this.storageService.has(Vw))&&(e.settings=yield this.storageService.get(Vw),yield this.storageService.remove(Vw)),yield this.saveAccount(e,this.reconcileOptions({userId:e.profile.userId},yield this.defaultOnDiskLocalOptions()))}))}scaffoldNewAccountMemoryStorage(e){return Fw(this,void 0,void 0,(function*(){const t=yield this.getAccount(this.reconcileOptions({userId:e.profile.userId},yield this.defaultOnDiskMemoryOptions()));null!=(null==t?void 0:t.settings)&&(e.settings=t.settings),yield this.storageService.save(e.profile.userId,e,yield this.defaultOnDiskMemoryOptions()),yield this.saveAccount(e,this.reconcileOptions({userId:e.profile.userId},yield this.defaultOnDiskMemoryOptions()))}))}scaffoldNewAccountSessionStorage(e){return Fw(this,void 0,void 0,(function*(){const t=yield this.getAccount(this.reconcileOptions({userId:e.profile.userId},yield this.defaultOnDiskOptions()));null!=(null==t?void 0:t.settings)&&(e.settings=t.settings),yield this.storageService.save(e.profile.userId,e,yield this.defaultOnDiskMemoryOptions()),yield this.saveAccount(e,this.reconcileOptions({userId:e.profile.userId},yield this.defaultOnDiskOptions()))}))}pushAccounts(){return Fw(this,void 0,void 0,(function*(){yield this.state().then((e=>{null==e.accounts||Object.keys(e.accounts).length<1?this.accountsSubject.next({}):this.accountsSubject.next(e.accounts)}))}))}reconcileOptions(e,t){var i,n,r,s,o;return null==e?t:(e.userId=null!==(i=null==e?void 0:e.userId)&&void 0!==i?i:t.userId,e.storageLocation=null!==(n=null==e?void 0:e.storageLocation)&&void 0!==n?n:t.storageLocation,e.useSecureStorage=null!==(r=null==e?void 0:e.useSecureStorage)&&void 0!==r?r:t.useSecureStorage,e.htmlStorageLocation=null!==(s=null==e?void 0:e.htmlStorageLocation)&&void 0!==s?s:t.htmlStorageLocation,e.keySuffix=null!==(o=null==e?void 0:e.keySuffix)&&void 0!==o?o:t.keySuffix,e)}defaultInMemoryOptions(){return Fw(this,void 0,void 0,(function*(){return{storageLocation:U.Memory,userId:(yield this.state()).activeUserId}}))}defaultOnDiskOptions(){var e,t;return Fw(this,void 0,void 0,(function*(){return{storageLocation:U.Disk,htmlStorageLocation:S.Session,userId:null!==(t=null===(e=yield this.state())||void 0===e?void 0:e.activeUserId)&&void 0!==t?t:yield this.getActiveUserIdFromStorage(),useSecureStorage:!1}}))}defaultOnDiskLocalOptions(){var e,t;return Fw(this,void 0,void 0,(function*(){return{storageLocation:U.Disk,htmlStorageLocation:S.Local,userId:null!==(t=null===(e=yield this.state())||void 0===e?void 0:e.activeUserId)&&void 0!==t?t:yield this.getActiveUserIdFromStorage(),useSecureStorage:!1}}))}defaultOnDiskMemoryOptions(){var e,t;return Fw(this,void 0,void 0,(function*(){return{storageLocation:U.Disk,htmlStorageLocation:S.Memory,userId:null!==(t=null===(e=yield this.state())||void 0===e?void 0:e.activeUserId)&&void 0!==t?t:yield this.getUserId(),useSecureStorage:!1}}))}defaultSecureStorageOptions(){var e,t;return Fw(this,void 0,void 0,(function*(){return{storageLocation:U.Disk,useSecureStorage:!0,userId:null!==(t=null===(e=yield this.state())||void 0===e?void 0:e.activeUserId)&&void 0!==t?t:yield this.getActiveUserIdFromStorage()}}))}getActiveUserIdFromStorage(){return Fw(this,void 0,void 0,(function*(){return yield this.storageService.get(zw)}))}removeAccountFromLocalStorage(e=null){var t;return Fw(this,void 0,void 0,(function*(){e=null!=e?e:null===(t=yield this.state())||void 0===t?void 0:t.activeUserId;const i=yield this.getAccount(this.reconcileOptions({userId:e},yield this.defaultOnDiskLocalOptions()));yield this.saveAccount(this.resetAccount(i),this.reconcileOptions({userId:e},yield this.defaultOnDiskLocalOptions()))}))}removeAccountFromSessionStorage(e=null){var t;return Fw(this,void 0,void 0,(function*(){e=null!=e?e:null===(t=yield this.state())||void 0===t?void 0:t.activeUserId;const i=yield this.getAccount(this.reconcileOptions({userId:e},yield this.defaultOnDiskOptions()));yield this.saveAccount(this.resetAccount(i),this.reconcileOptions({userId:e},yield this.defaultOnDiskOptions()))}))}removeAccountFromSecureStorage(e=null){var t;return Fw(this,void 0,void 0,(function*(){e=null!=e?e:null===(t=yield this.state())||void 0===t?void 0:t.activeUserId,yield this.setUserKeyAutoUnlock(null,{userId:e}),yield this.setUserKeyBiometric(null,{userId:e}),yield this.setCryptoMasterKeyAuto(null,{userId:e}),yield this.setCryptoMasterKeyBiometric(null,{userId:e}),yield this.setCryptoMasterKeyB64(null,{userId:e})}))}removeAccountFromMemory(e=null){return Fw(this,void 0,void 0,(function*(){yield this.updateState((t=>Fw(this,void 0,void 0,(function*(){return e=null!=e?e:t.activeUserId,delete t.accounts[e],this.deleteDiskCache(e),t})))),yield this.accountService.setAccountStatus(e,On.LoggedOut)}))}resetAccount(e){const t={settings:e.settings,keys:{deviceKey:e.keys.deviceKey},adminAuthRequest:e.adminAuthRequest};return Object.assign(this.createAccount(),t)}clearDecryptedDataForActiveUser(){return Fw(this,void 0,void 0,(function*(){yield this.updateState((e=>Fw(this,void 0,void 0,(function*(){var t;const i=null==e?void 0:e.activeUserId;return null!=i&&null!=(null===(t=null==e?void 0:e.accounts[i])||void 0===t?void 0:t.data)&&(e.accounts[i].data=new lt),e}))))}))}createAccount(e=null){return this.stateFactory.createAccount(e)}createGlobals(e=null){return this.stateFactory.createGlobal(e)}deAuthenticateAccount(e){return Fw(this,void 0,void 0,(function*(){yield this.tokenService.clearTokens(e),yield this.setLastActive(null,{userId:e}),yield this.updateState((t=>Fw(this,void 0,void 0,(function*(){return t.authenticatedAccounts=t.authenticatedAccounts.filter((t=>t!==e)),yield this.storageService.save(Lw,t.authenticatedAccounts),t}))))}))}removeAccountFromDisk(e){return Fw(this,void 0,void 0,(function*(){yield this.removeAccountFromSessionStorage(e),yield this.removeAccountFromLocalStorage(e),yield this.removeAccountFromSecureStorage(e)}))}nextUpActiveUser(){var e;return Fw(this,void 0,void 0,(function*(){const t=null===(e=yield this.state())||void 0===e?void 0:e.accounts;if(null==t||Object.keys(t).length<1)return null;let i;for(const e in t)if(null!=e){if(yield this.getIsAuthenticated({userId:e})){i=e;break}i=null}return i}))}dynamicallySetActiveUser(){return Fw(this,void 0,void 0,(function*(){const e=yield this.nextUpActiveUser();return yield this.setActiveUser(e),e}))}saveSecureStorageKey(e,t,i){return Fw(this,void 0,void 0,(function*(){return null==t?yield this.secureStorageService.remove(`${i.userId}${e}`,i):yield this.secureStorageService.save(`${i.userId}${e}`,t,i)}))}state(){return Fw(this,void 0,void 0,(function*(){return yield this.memoryStorageService.get(Mw,{deserializer:e=>Nw.fromJSON(e,this.accountDeserializer)})}))}setState(e){return Fw(this,void 0,void 0,(function*(){return yield this.memoryStorageService.save(Mw,e),e}))}updateState(e){return Fw(this,void 0,void 0,(function*(){return yield this.state().then((t=>Fw(this,void 0,void 0,(function*(){const i=yield e(t);if(null==i)throw new Error("Attempted to update state to null value");return yield this.setState(i)}))))}))}setDiskCache(e,t,i){this.useAccountCache&&(this.accountDiskCache.value[e]=t,this.accountDiskCache.next(this.accountDiskCache.value))}deleteDiskCache(e){this.useAccountCache&&(delete this.accountDiskCache.value[e],this.accountDiskCache.next(this.accountDiskCache.value))}}function Jw(e,t=(e=>e)){return(i,n,r)=>{const s=r.value;return{value:function(...i){const r=s.apply(this,i);if(!p.isPromise(r))throw new Error(`Error applying prototype to stored value -- result is not a promise for method ${String(n)}`);return r.then((i=>{if(null==i)return null;if(i instanceof Array)return i.map((i=>null==i||i.constructor.name===e.prototype.constructor.name?i:t(Object.create(e.prototype,Object.getOwnPropertyDescriptors(i)))));throw new Error(`Attempted to retrieve non array type from state as an array for method ${String(n)}`)}))}}}}function Yw(e,t=(e=>e)){return(i,n,r)=>{const s=r.value;return{value:function(...i){const r=s.apply(this,i);if(!p.isPromise(r))throw new Error(`Error applying prototype to stored value -- result is not a promise for method ${String(n)}`);return r.then((i=>{if(null==i)return null;for(const[n,r]of Object.entries(i))i[n]=null==r||r.constructor.name===e.prototype.constructor.name?t(r):t(Object.create(e.prototype,Object.getOwnPropertyDescriptors(r)));return i}))}}}}Rw([Jw(it,it.fromJSON),Ew("design:type",Function),Ew("design:paramtypes",[Object]),Ew("design:returntype",Promise)],Gw.prototype,"getDecryptedCiphers",null),Rw([Jw(Mh),Ew("design:type",Function),Ew("design:paramtypes",[Object]),Ew("design:returntype",Promise)],Gw.prototype,"getDecryptedPasswordGenerationHistory",null),Rw([Jw(Tw),Ew("design:type",Function),Ew("design:paramtypes",[Object]),Ew("design:returntype",Promise)],Gw.prototype,"getDecryptedSends",null),Rw([Yw(co),Ew("design:type",Function),Ew("design:paramtypes",[Object]),Ew("design:returntype",Promise)],Gw.prototype,"getEncryptedCiphers",null),Rw([Jw(Mh),Ew("design:type",Function),Ew("design:paramtypes",[Object]),Ew("design:returntype",Promise)],Gw.prototype,"getEncryptedPasswordGenerationHistory",null),Rw([Yw(hp),Ew("design:type",Function),Ew("design:paramtypes",[Object]),Ew("design:returntype",Promise)],Gw.prototype,"getEncryptedSends",null);class Qw{static fromJSON(e){return null==e?null:Object.assign(new Qw,e)}}class Xw extends Qw{toJSON(){return p.merge(this,{collectionCounts:p.mapToRecord(this.collectionCounts),folderCounts:p.mapToRecord(this.folderCounts),typeCounts:p.mapToRecord(this.typeCounts)})}static fromJSON(e){var t,i,n,r;return null==e?null:Object.assign(new Xw,e,{favoriteCiphers:null===(t=e.favoriteCiphers)||void 0===t?void 0:t.map((e=>it.fromJSON(e))),noFolderCiphers:null===(i=e.noFolderCiphers)||void 0===i?void 0:i.map((e=>it.fromJSON(e))),ciphers:null===(n=e.ciphers)||void 0===n?void 0:n.map((e=>it.fromJSON(e))),collectionCounts:p.recordToMap(e.collectionCounts),folderCounts:p.recordToMap(e.folderCounts),typeCounts:p.recordToMap(e.typeCounts),folders:null===(r=e.folders)||void 0===r?void 0:r.map((e=>Fy.fromJSON(e)))})}}class Zw extends Qw{toJSON(){return p.merge(this,{typeCounts:p.mapToRecord(this.typeCounts)})}static fromJSON(e){var t;return null==e?null:Object.assign(new Zw,e,{sends:null===(t=e.sends)||void 0===t?void 0:t.map((e=>Tw.fromJSON(e))),typeCounts:p.recordToMap(e.typeCounts)})}}class eS extends ut{constructor(){super(...arguments),this.vaultTimeout=-1}static fromJSON(e){return null==e?null:Object.assign(new eS,e,super.fromJSON(e))}}class tS extends pt{constructor(e){var t,i,n,r;super(e),this.settings=new eS,Object.assign(this.settings,Object.assign(Object.assign({},new eS),this.settings)),this.groupings=null!==(t=null==e?void 0:e.groupings)&&void 0!==t?t:new Xw,this.send=null!==(i=null==e?void 0:e.send)&&void 0!==i?i:new Zw,this.ciphers=null!==(n=null==e?void 0:e.ciphers)&&void 0!==n?n:new Qw,this.sendType=null!==(r=null==e?void 0:e.sendType)&&void 0!==r?r:new Qw}static fromJSON(e){return null==e?null:Object.assign(new tS({}),e,super.fromJSON(e),{settings:eS.fromJSON(e.settings),groupings:Xw.fromJSON(e.groupings),send:Zw.fromJSON(e.send),ciphers:Qw.fromJSON(e.ciphers),sendType:Qw.fromJSON(e.sendType)})}}var iS=i(49129);class nS{static builder(e){const t=e.initializer;return"array"===e.initializeAs?e=>e.map((e=>t(e))):"record"===e.initializeAs?e=>{const i={};for(const n in e)i[n]=t(e[n]);return i}:e=>t(e)}}var rS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class sS{constructor(e,t,i){if(this.subject=e,this.memoryStorageService=t,this.metaData=i,this.id=p.newGuid(),this.ignoreNUpdates=0,!(e instanceof Cn.x))throw new Error("subject must inherit from Subject");if(null==i.initializer)throw new Error("initializer must be provided")}init(){return rS(this,void 0,void 0,(function*(){switch(this.subject.constructor){case yd.t:this.ignoreNUpdates=this.subject._buffer.length;break;case te.X:this.ignoreNUpdates=1}yield this.observe();(yield this.memoryStorageService.has(this.metaData.sessionKey))&&(yield this.updateFromMemory()),this.listenForUpdates()}))}observe(){return rS(this,void 0,void 0,(function*(){const e=this.subject.pipe((0,iS.T)(this.ignoreNUpdates));this.ignoreNUpdates=0,this.subscription=e.pipe((0,fw.b)((e=>rS(this,void 0,void 0,(function*(){this.ignoreNUpdates>0?this.ignoreNUpdates-=1:yield this.updateSession(e)}))))).subscribe()}))}listenForUpdates(){xg.messageListener(this.updateMessageCommand,(e=>{this.updateFromMessage(e)}))}updateFromMessage(e){return rS(this,void 0,void 0,(function*(){e.command==this.updateMessageCommand&&e.id!==this.id&&(yield this.update(e.serializedValue))}))}updateFromMemory(){return rS(this,void 0,void 0,(function*(){const e=yield this.memoryStorageService.getBypassCache(this.metaData.sessionKey);yield this.update(e)}))}update(e){return rS(this,void 0,void 0,(function*(){const t=JSON.parse(e);!xg.isManifestVersion(3)&&xg.isBackgroundPage(self)&&(yield this.memoryStorageService.save(this.metaData.sessionKey,e));const i=nS.builder(this.metaData)(t);this.ignoreNUpdates=1,this.subject.next(i)}))}updateSession(e){return rS(this,void 0,void 0,(function*(){const t=JSON.stringify(e);(xg.isManifestVersion(3)||xg.isBackgroundPage(self))&&(yield this.memoryStorageService.save(this.metaData.sessionKey,t)),yield xg.sendMessage(this.updateMessageCommand,{id:this.id,serializedValue:t})}))}get updateMessageCommand(){return`${this.metaData.sessionKey}_update`}}function oS(e){return class extends e{constructor(...e){super(...e);const t=this.findStorageService([this].concat(e));null!=this.__syncedItemMetadata&&this.__syncedItemMetadata instanceof Array&&(this.__sessionSyncers=this.__syncedItemMetadata.map((e=>this.buildSyncer(e,t))))}buildSyncer(e,t){const i=new sS(this[e.propertyKey],t,e);return i.init(),i}findStorageService(t){const i=t.find(this.isMemoryStorageService);if(i)return i;const n=t.find((e=>null!=(null==e?void 0:e.memoryStorageService)&&this.isMemoryStorageService(e.memoryStorageService)));if(n)return n.memoryStorageService;throw new Error(`Cannot decorate ${e.name} with browserSession, Browser's AbstractMemoryStorageService must be accessible through the observed classes parameters`)}isMemoryStorageService(e){return null!=e.type&&e.type===zo.TYPE}}}let aS=0;function lS(e){return(t,i)=>{var n;const r=t;null==r.__syncedItemMetadata&&(r.__syncedItemMetadata=[]),r.__syncedItemMetadata.push({propertyKey:i,sessionKey:`${i}_${aS++}`,initializer:e.initializer,initializeAs:null!==(n=e.initializeAs)&&void 0!==n?n:"object"})}}var cS=function(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},dS=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},uS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};let hS=class extends Gw{constructor(e,t,i,n,r,s,o,a,l,c=!0){super(e,t,i,n,r,s,o,a,l,c),this.accountDeserializer=tS.fromJSON,c&&(xg.storageChangeListener(((e,t)=>{if("local"===t)for(const t of Object.keys(e))"accountActivity"!==t&&this.accountDiskCache.value[t]&&this.deleteDiskCache(t)})),xg.addListener(chrome.runtime.onMessage,((e,t,i)=>{"initializeDiskCache"===e.command&&i(JSON.stringify(this.accountDiskCache.value))})))}initAccountState(){const e=Object.create(null,{initAccountState:{get:()=>super.initAccountState}});return uS(this,void 0,void 0,(function*(){if(this.isRecoveredSession&&this.useAccountCache){const e=yield xg.sendMessageWithResponse("initializeDiskCache");this.accountDiskCache.next(JSON.parse(e))}else yield e.initAccountState.call(this)}))}addAccount(e){const t=Object.create(null,{addAccount:{get:()=>super.addAccount}});return uS(this,void 0,void 0,(function*(){e=new tS(e),yield t.addAccount.call(this,e)}))}getIsAuthenticated(e){const t=Object.create(null,{getIsAuthenticated:{get:()=>super.getIsAuthenticated}});return uS(this,void 0,void 0,(function*(){return(yield t.getIsAuthenticated.call(this,e))&&null!=(yield this.getAccount(yield this.defaultInMemoryOptions()))}))}getBrowserGroupingComponentState(e){var t;return uS(this,void 0,void 0,(function*(){return null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultInMemoryOptions())))||void 0===t?void 0:t.groupings}))}setBrowserGroupingComponentState(e,t){return uS(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultInMemoryOptions()));i.groupings=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultInMemoryOptions()))}))}getBrowserVaultItemsComponentState(e){var t;return uS(this,void 0,void 0,(function*(){return null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultInMemoryOptions())))||void 0===t?void 0:t.ciphers}))}setBrowserVaultItemsComponentState(e,t){return uS(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultInMemoryOptions()));i.ciphers=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultInMemoryOptions()))}))}getBrowserSendComponentState(e){var t;return uS(this,void 0,void 0,(function*(){return null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultInMemoryOptions())))||void 0===t?void 0:t.send}))}setBrowserSendComponentState(e,t){return uS(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultInMemoryOptions()));i.send=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultInMemoryOptions()))}))}getBrowserSendTypeComponentState(e){var t;return uS(this,void 0,void 0,(function*(){return null===(t=yield this.getAccount(this.reconcileOptions(e,yield this.defaultInMemoryOptions())))||void 0===t?void 0:t.sendType}))}setBrowserSendTypeComponentState(e,t){return uS(this,void 0,void 0,(function*(){const i=yield this.getAccount(this.reconcileOptions(t,yield this.defaultInMemoryOptions()));i.sendType=e,yield this.saveAccount(i,this.reconcileOptions(t,yield this.defaultInMemoryOptions()))}))}saveAccountToDisk(e,t){return uS(this,void 0,void 0,(function*(){const i=t.useSecureStorage?this.secureStorageService:this.storageService;yield i.save(`${t.userId}`,e,t)}))}};cS([lS({initializer:tS.fromJSON,initializeAs:"record"}),dS("design:type",te.X)],hS.prototype,"accountsSubject",void 0),cS([lS({initializer:e=>e}),dS("design:type",te.X)],hS.prototype,"activeAccountSubject",void 0),hS=cS([oS,dS("design:paramtypes",[Lo,Lo,zo,xw,Ns,Dn,Zm,class{},Qc,Object])],hS);var pS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};var yS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function vS(e,t){return yS(this,void 0,void 0,(function*(){const i=yield lm(e,"stateService",t,(()=>yS(this,void 0,void 0,(function*(){return new hS(yield Nm(e,t),yield Rm(e,t),yield function(e,t){return lm(e,"memoryStorageService",t,(()=>Tm(this,void 0,void 0,(function*(){return xg.isManifestVersion(3)?new Om(yield hm(e,t),yield Um(e,t)):new Bo}))))}(e,t),yield cm(e,t),t.stateServiceOptions.stateFactory,yield Xm(e,t),yield Dw(e,t),yield Gm(e,t),yield function(e,t){return pS(this,void 0,void 0,(function*(){return lm(e,"migrationRunner",t,(()=>pS(this,void 0,void 0,(function*(){return new Qc(yield Nm(e,t),yield cm(e,t),new Hc)}))))}))}(e,t),t.stateServiceOptions.useAccountCache)}))));return yield i.init(),i}))}var fS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function gS(e,t){return lm(e,"apiService",t,(()=>fS(this,void 0,void 0,(function*(){return new Qu(yield Gm(e,t),yield jm(e,t),yield Dw(e,t),yield function(e,t){return lm(e,"appIdService",t,(()=>Jm(this,void 0,void 0,(function*(){return new Ls(yield Lm(e,t))}))))}(e,t),yield vS(e,t),t.apiServiceOptions.logoutCallback,t.apiServiceOptions.customUserAgent)}))))}var mS=i(19583),wS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class SS{static fromData(e){switch(e.type){case"organization":return new bS(e.key);case"provider":return new PS(e.key,e.providerId);default:return null}}}class bS{constructor(e){this.key=e}decrypt(e){return wS(this,void 0,void 0,(function*(){const t=yield e.rsaDecrypt(this.key);return new N(t)}))}toData(){return{type:"organization",key:this.key}}}class PS{constructor(e,t){this.key=e,this.providerId=t}decrypt(e){return wS(this,void 0,void 0,(function*(){const t=yield e.getProviderKey(this.providerId),i=yield e.decryptToBytes(new z(this.key),t);return new N(i)}))}toData(){return{type:"provider",key:this.key,providerId:this.providerId}}}var kS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const OS=jt.record(yi,"organizationKeys",{deserializer:e=>e}),CS=Lt.from(OS,{deserializer:e=>{const t={};for(const i of Object.keys(null!=e?e:{}))t[i]=N.fromJSON(e[i]);return t},derive:(e,{cryptoService:t})=>kS(void 0,void 0,void 0,(function*(){const i={};for(const n of Object.keys(null!=e?e:{})){if(null!=i[n])continue;const r=SS.fromData(e[n]),s=yield r.decrypt(t);i[n]=s}return i}))});var AS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const DS=jt.record(yi,"providerKeys",{deserializer:e=>e}),xS=Lt.from(DS,{deserializer:e=>{const t={};for(const i of Object.keys(null!=e?e:{}))t[i]=N.fromJSON(e[i]);return t},derive:(e,{encryptService:t,cryptoService:i})=>AS(void 0,void 0,void 0,(function*(){const n={};for(const r of Object.keys(null!=e?e:{})){if(null!=n[r])continue;const s=new z(e[r]),o=yield i.getPrivateKey(),a=yield t.rsaDecrypt(s,o),l=new N(a);n[r]=l}return n}))});var IS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const US=new jt(yi,"everHadUserKey",{deserializer:e=>e}),TS=new jt(yi,"privateKey",{deserializer:e=>e}),NS=Lt.fromWithUserId(TS,{deserializer:e=>new Uint8Array(Object.values(e)),derive:([e,t],{encryptService:i,cryptoService:n})=>IS(void 0,void 0,void 0,(function*(){if(null==t)return null;const r=yield n.getUserKey(e);if(null==r)return null;const s=new z(t);return yield i.decryptToBytes(s,r)}))}),RS=Lt.from([NS,"publicKey"],{deserializer:e=>new Uint8Array(Object.values(e)),derive:(e,{cryptoFunctionService:t})=>IS(void 0,void 0,void 0,(function*(){return null==e?null:yield t.rsaExtractPublicKey(e)}))}),ES=new jt(vi,"userKey",{deserializer:e=>N.fromJSON(e)});var FS=function(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},MS=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},KS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class LS{constructor(e,t,i,n,r,s,o,a){this.keyGenerationService=e,this.cryptoFunctionService=t,this.encryptService=i,this.platformUtilService=n,this.logService=r,this.stateService=s,this.accountService=o,this.stateProvider=a,this.activeUserKeyState=a.getActive(ES),this.activeUserKey$=this.activeUserKeyState.state$,this.activeUserEverHadUserKey=a.getActive(US),this.everHadUserKey$=this.activeUserEverHadUserKey.state$.pipe((0,q.U)((e=>null!=e&&e))),this.activeUserEncryptedPrivateKeyState=a.getActive(TS),this.activeUserPrivateKeyState=a.getDerived(this.activeUserEncryptedPrivateKeyState.combinedState$.pipe((0,_.h)((([e,t])=>null!=t))),NS,{encryptService:this.encryptService,cryptoService:this}),this.activeUserPrivateKey$=this.activeUserPrivateKeyState.state$,this.activeUserPublicKeyState=a.getDerived(this.activeUserPrivateKey$.pipe((0,_.h)((e=>null!=e))),RS,{cryptoFunctionService:this.cryptoFunctionService}),this.activeUserPublicKey$=this.activeUserPublicKeyState.state$,this.activeUserEncryptedOrgKeysState=a.getActive(OS),this.activeUserOrgKeysState=a.getDerived(this.activeUserEncryptedOrgKeysState.state$.pipe((0,_.h)((e=>null!=e))),CS,{cryptoService:this}),this.activeUserOrgKeys$=this.activeUserOrgKeysState.state$,this.activeUserEncryptedProviderKeysState=a.getActive(DS),this.activeUserProviderKeysState=a.getDerived(this.activeUserEncryptedProviderKeysState.state$.pipe((0,_.h)((e=>null!=e))),xS,{encryptService:this.encryptService,cryptoService:this}),this.activeUserProviderKeys$=this.activeUserProviderKeysState.state$}setUserKey(e,t){return KS(this,void 0,void 0,(function*(){if(null==e)throw new Error("No key provided. Use ClearUserKey to clear the key");[t,e]=yield this.stateProvider.setUserState(ES,e,t),yield this.stateProvider.setUserState(US,!0,t),yield this.accountService.setAccountStatus(t,On.Unlocked),yield this.storeAdditionalKeys(e,t)}))}refreshAdditionalKeys(){return KS(this,void 0,void 0,(function*(){const e=yield this.getUserKey();yield this.setUserKey(e)}))}getUserKey(e){return KS(this,void 0,void 0,(function*(){let t=yield(0,r.z)(this.stateProvider.getUserState$(ES,e));return t||((yield this.hasUserKeyStored(x.Auto,e))&&(t=yield this.getKeyFromStorage(x.Auto,e),t)?(yield this.setUserKey(t,e),t):void 0)}))}isLegacyUser(e,t){return KS(this,void 0,void 0,(function*(){return yield this.validateUserKey(null!=e?e:yield this.getMasterKey(t))}))}getUserKeyWithLegacySupport(e){return KS(this,void 0,void 0,(function*(){const t=yield this.getUserKey(e);return t||(yield this.getMasterKey(e))}))}getUserKeyFromStorage(e,t){return KS(this,void 0,void 0,(function*(){const i=yield this.getKeyFromStorage(e,t);if(i)return(yield this.validateUserKey(i))||(this.logService.warning("Invalid key, throwing away stored keys"),yield this.clearAllStoredUserKeys(t)),i}))}hasUserKey(e){return KS(this,void 0,void 0,(function*(){return null!=e||(e=yield(0,r.z)(this.stateProvider.activeUserId$)),null!=e&&((yield this.hasUserKeyInMemory(e))||(yield this.hasUserKeyStored(x.Auto,e)))}))}hasUserKeyInMemory(e){return KS(this,void 0,void 0,(function*(){return null!=e||(e=yield(0,r.z)(this.stateProvider.activeUserId$)),null!=e&&null!=(yield(0,r.z)(this.stateProvider.getUserState$(ES,e)))}))}hasUserKeyStored(e,t){return KS(this,void 0,void 0,(function*(){return null!=(yield this.getKeyFromStorage(e,t))}))}makeUserKey(e){return KS(this,void 0,void 0,(function*(){if(e||(e=yield this.getMasterKey()),null==e)throw new Error("No Master Key found.");const t=yield this.keyGenerationService.createKey(512);return this.buildProtectedSymmetricKey(e,t.key)}))}clearUserKey(e=!0,t){return KS(this,void 0,void 0,(function*(){[t]=yield this.stateProvider.setUserState(ES,null,t),yield this.accountService.setMaxAccountStatus(t,On.Locked),e&&(yield this.clearAllStoredUserKeys(t))}))}clearStoredUserKey(e,t){return KS(this,void 0,void 0,(function*(){e===x.Auto&&(this.stateService.setUserKeyAutoUnlock(null,{userId:t}),this.clearDeprecatedKeys(x.Auto,t)),e===x.Pin&&(this.stateService.setPinKeyEncryptedUserKeyEphemeral(null,{userId:t}),this.clearDeprecatedKeys(x.Pin,t))}))}setMasterKeyEncryptedUserKey(e,t){return KS(this,void 0,void 0,(function*(){yield this.stateService.setMasterKeyEncryptedUserKey(e,{userId:t})}))}setMasterKey(e,t){return KS(this,void 0,void 0,(function*(){yield this.stateService.setMasterKey(e,{userId:t})}))}getMasterKey(e){return KS(this,void 0,void 0,(function*(){let t=yield this.stateService.getMasterKey({userId:e});return t||(t=yield this.stateService.getCryptoMasterKey({userId:e}),t&&(yield this.setMasterKey(t,e))),t}))}getOrDeriveMasterKey(e,t){return KS(this,void 0,void 0,(function*(){let i=yield this.getMasterKey(t);return i||(yield this.makeMasterKey(e,yield this.stateService.getEmail({userId:t}),yield this.stateService.getKdfType({userId:t}),yield this.stateService.getKdfConfig({userId:t})))}))}makeMasterKey(e,t,i,n){return KS(this,void 0,void 0,(function*(){return yield this.keyGenerationService.deriveKeyFromPassword(e,t,i,n)}))}clearMasterKey(e){return KS(this,void 0,void 0,(function*(){yield this.stateService.setMasterKey(null,{userId:e})}))}encryptUserKeyWithMasterKey(e,t){return KS(this,void 0,void 0,(function*(){return t||(t=yield this.getUserKey()),yield this.buildProtectedSymmetricKey(e,t.key)}))}decryptUserKeyWithMasterKey(e,t,i){return KS(this,void 0,void 0,(function*(){if(e||(e=yield this.getMasterKey(i)),null==e)throw new Error("No master key found.");if(!t){let e=yield this.stateService.getMasterKeyEncryptedUserKey({userId:i});if(null==e&&(e=yield this.stateService.getEncryptedCryptoSymmetricKey({userId:i})),null==e)throw new Error("No encrypted user key found.");t=new z(e)}let n;if(t.encryptionType===f.AesCbc256_B64)n=yield this.encryptService.decryptToBytes(t,e);else{if(t.encryptionType!==f.AesCbc256_HmacSha256_B64)throw new Error("Unsupported encryption type.");{const i=yield this.stretchKey(e);n=yield this.encryptService.decryptToBytes(t,i)}}return null==n?null:new N(n)}))}hashMasterKey(e,t,i){return KS(this,void 0,void 0,(function*(){if(t||(t=yield this.getMasterKey()),null==e||null==t)throw new Error("Invalid parameters.");const n=i===w.LocalAuthorization?2:1,r=yield this.cryptoFunctionService.pbkdf2(t.key,e,"sha256",n);return p.fromBufferToB64(r)}))}setMasterKeyHash(e){return KS(this,void 0,void 0,(function*(){yield this.stateService.setKeyHash(e)}))}getMasterKeyHash(){return KS(this,void 0,void 0,(function*(){return yield this.stateService.getKeyHash()}))}clearMasterKeyHash(e){return KS(this,void 0,void 0,(function*(){return yield this.stateService.setKeyHash(null,{userId:e})}))}compareAndUpdateKeyHash(e,t){return KS(this,void 0,void 0,(function*(){const i=yield this.getMasterKeyHash();if(null!=e&&null!=i){const n=yield this.hashMasterKey(e,t,w.LocalAuthorization);if(null!=n&&i===n)return!0;const r=yield this.hashMasterKey(e,t,w.ServerAuthorization);if(null!=r&&i===r)return yield this.setMasterKeyHash(n),!0}return!1}))}setOrgKeys(e=[],t=[]){return KS(this,void 0,void 0,(function*(){this.activeUserEncryptedOrgKeysState.update((i=>{const n={};return e.forEach((e=>{n[e.id]={type:"organization",key:e.key}})),t.forEach((e=>{n[e.id]={type:"provider",providerId:e.providerId,key:e.key}})),n}))}))}getOrgKey(e){return KS(this,void 0,void 0,(function*(){return(yield(0,r.z)(this.activeUserOrgKeys$))[e]}))}getOrgKeys(){return KS(this,void 0,void 0,(function*(){return yield(0,r.z)(this.activeUserOrgKeys$)}))}makeDataEncKey(e){return KS(this,void 0,void 0,(function*(){if(null==e)throw new Error("No key provided");const t=yield this.keyGenerationService.createKey(512);return this.buildProtectedSymmetricKey(e,t.key)}))}clearOrgKeys(e,t){var i;return KS(this,void 0,void 0,(function*(){const n=null===(i=yield(0,r.z)(this.accountService.activeAccount$))||void 0===i?void 0:i.id;if(e)(null==t||t===n)&&(yield this.activeUserOrgKeysState.forceValue({}));else{if(null==t&&null==n)return;yield this.stateProvider.getUser(null!=t?t:n,OS).update((()=>null))}}))}setProviderKeys(e){return KS(this,void 0,void 0,(function*(){yield this.activeUserEncryptedProviderKeysState.update((t=>{const i={};return e.forEach((e=>{i[e.id]=e.key})),i}))}))}getProviderKey(e){var t;return KS(this,void 0,void 0,(function*(){return null==e?null:null!==(t=(yield(0,r.z)(this.activeUserProviderKeys$))[e])&&void 0!==t?t:null}))}getProviderKeys(){return KS(this,void 0,void 0,(function*(){return yield(0,r.z)(this.activeUserProviderKeys$)}))}clearProviderKeys(e,t){var i;return KS(this,void 0,void 0,(function*(){const n=null===(i=yield(0,r.z)(this.accountService.activeAccount$))||void 0===i?void 0:i.id;if(e)(null==t||t===n)&&(yield this.activeUserProviderKeysState.forceValue({}));else{if(null==t&&null==n)return;yield this.stateProvider.getUser(null!=t?t:n,DS).update((()=>null))}}))}getPublicKey(){return KS(this,void 0,void 0,(function*(){return yield(0,r.z)(this.activeUserPublicKey$)}))}makeOrgKey(){return KS(this,void 0,void 0,(function*(){const e=yield this.keyGenerationService.createKey(512),t=yield this.getPublicKey();return[yield this.rsaEncrypt(e.key,t),e]}))}setPrivateKey(e){return KS(this,void 0,void 0,(function*(){null!=e&&(yield this.activeUserEncryptedPrivateKeyState.update((()=>e)))}))}getPrivateKey(){return KS(this,void 0,void 0,(function*(){return yield(0,r.z)(this.activeUserPrivateKey$)}))}getFingerprint(e,t){return KS(this,void 0,void 0,(function*(){if(null==t&&(t=yield this.getPublicKey()),null===t)throw new Error("No public key available.");const i=yield this.cryptoFunctionService.hash(t,"sha256"),n=yield this.cryptoFunctionService.hkdfExpand(i,e,32,"sha256");return this.hashPhrase(n)}))}makeKeyPair(e){return KS(this,void 0,void 0,(function*(){e||(e=yield this.getUserKeyWithLegacySupport());const t=yield this.cryptoFunctionService.rsaGenerateKeyPair(2048);return[p.fromBufferToB64(t[0]),yield this.encryptService.encrypt(t[1],e)]}))}clearKeyPair(e,t){var i;return KS(this,void 0,void 0,(function*(){const n=null===(i=yield(0,r.z)(this.accountService.activeAccount$))||void 0===i?void 0:i.id;if(e)(null==t||t===n)&&(yield this.activeUserPrivateKeyState.forceValue(null),yield this.activeUserPublicKeyState.forceValue(null));else{if(null==t&&null==n)return;yield this.stateProvider.getUser(null!=t?t:n,TS).update((()=>null))}}))}makePinKey(e,t,i,n){return KS(this,void 0,void 0,(function*(){const r=yield this.keyGenerationService.deriveKeyFromPassword(e,t,i,n);return yield this.stretchKey(r)}))}clearPinKeys(e){return KS(this,void 0,void 0,(function*(){yield this.stateService.setPinKeyEncryptedUserKey(null,{userId:e}),yield this.stateService.setPinKeyEncryptedUserKeyEphemeral(null,{userId:e}),yield this.stateService.setProtectedPin(null,{userId:e}),yield this.clearDeprecatedKeys(x.Pin,e)}))}decryptUserKeyWithPin(e,t,i,n,r){return KS(this,void 0,void 0,(function*(){if(r||(r=yield this.stateService.getPinKeyEncryptedUserKey()),r||(r=yield this.stateService.getPinKeyEncryptedUserKeyEphemeral()),!r)throw new Error("No PIN protected key found.");const s=yield this.makePinKey(e,t,i,n),o=yield this.encryptService.decryptToBytes(r,s);return new N(o)}))}decryptMasterKeyWithPin(e,t,i,n,r){return KS(this,void 0,void 0,(function*(){if(!r){const e=yield this.stateService.getEncryptedPinProtected();if(null==e)throw new Error("No PIN protected key found.");r=new z(e)}const s=yield this.makePinKey(e,t,i,n),o=yield this.encryptService.decryptToBytes(r,s);return new N(o)}))}makeSendKey(e){return KS(this,void 0,void 0,(function*(){return yield this.keyGenerationService.deriveKeyFromMaterial(e,"bitwarden-send","send")}))}makeCipherKey(){return KS(this,void 0,void 0,(function*(){return yield this.keyGenerationService.createKey(512)}))}clearKeys(e){return KS(this,void 0,void 0,(function*(){yield this.clearUserKey(!0,e),yield this.clearMasterKeyHash(e),yield this.clearOrgKeys(!1,e),yield this.clearProviderKeys(!1,e),yield this.clearKeyPair(!1,e),yield this.clearPinKeys(e),yield this.stateProvider.setUserState(US,null,e)}))}rsaEncrypt(e,t){return KS(this,void 0,void 0,(function*(){if(null==t&&(t=yield this.getPublicKey()),null==t)throw new Error("Public key unavailable.");const i=yield this.cryptoFunctionService.rsaEncrypt(e,t,"sha1");return new z(f.Rsa2048_OaepSha1_B64,p.fromBufferToB64(i))}))}rsaDecrypt(e,t){return KS(this,void 0,void 0,(function*(){const i=e.split(".");let n,r=null;if(1===i.length)r=f.Rsa2048_OaepSha256_B64,n=[i[0]];else if(2===i.length)try{r=parseInt(i[0],null),n=i[1].split("|")}catch(e){this.logService.error(e)}switch(r){case f.Rsa2048_OaepSha256_B64:case f.Rsa2048_OaepSha1_B64:case f.Rsa2048_OaepSha256_HmacSha256_B64:case f.Rsa2048_OaepSha1_HmacSha256_B64:break;default:throw new Error("encType unavailable.")}if(null==n||n.length<=0)throw new Error("encPieces unavailable.");const s=p.fromB64ToArray(n[0]),o=null!=t?t:yield this.getPrivateKey();if(null==o)throw new Error("No private key.");let a="sha1";switch(r){case f.Rsa2048_OaepSha256_B64:case f.Rsa2048_OaepSha256_HmacSha256_B64:a="sha256";break;case f.Rsa2048_OaepSha1_B64:case f.Rsa2048_OaepSha1_HmacSha256_B64:break;default:throw new Error("encType unavailable.")}return this.cryptoFunctionService.rsaDecrypt(s,o,a)}))}randomNumber(e,t){return KS(this,void 0,void 0,(function*(){let i=0;const n=t-e+1,r=Math.ceil(Math.log2(n));if(r>53)throw new Error("We cannot generate numbers larger than 53 bits.");const s=Math.ceil(r/8),o=Math.pow(2,r)-1,a=new Uint8Array(yield this.cryptoFunctionService.randomBytes(s));let l=8*(s-1);for(let e=0;e=n?this.randomNumber(e,t):e+i}))}validateUserKey(e){return KS(this,void 0,void 0,(function*(){if(!e)return!1;try{const[e,t]=yield(0,r.z)(this.activeUserEncryptedPrivateKeyState.combinedState$);if(null==t)return!1;const i=yield NS.derive([e,t],{encryptService:this.encryptService,cryptoService:this});yield RS.derive(i,{cryptoFunctionService:this.cryptoFunctionService})}catch(e){return!1}return!0}))}initAccount(){return KS(this,void 0,void 0,(function*(){const e=yield this.keyGenerationService.createKey(512),[t,i]=yield this.makeKeyPair(e);return yield this.setUserKey(e),yield this.activeUserEncryptedPrivateKeyState.update((()=>i.encryptedString)),{userKey:e,publicKey:t,privateKey:i}}))}storeAdditionalKeys(e,t){return KS(this,void 0,void 0,(function*(){(yield this.shouldStoreKey(x.Auto,t))?yield this.stateService.setUserKeyAutoUnlock(e.keyB64,{userId:t}):yield this.stateService.setUserKeyAutoUnlock(null,{userId:t}),yield this.clearDeprecatedKeys(x.Auto,t);(yield this.shouldStoreKey(x.Pin,t))?(yield this.storePinKey(e,t),yield this.clearDeprecatedKeys(x.Pin,t)):(yield this.stateService.setPinKeyEncryptedUserKey(null,{userId:t}),yield this.stateService.setPinKeyEncryptedUserKeyEphemeral(null,{userId:t}))}))}storePinKey(e,t){return KS(this,void 0,void 0,(function*(){const i=yield this.encryptService.decryptToUtf8(new z(yield this.stateService.getProtectedPin({userId:t})),e),n=yield this.makePinKey(i,yield this.stateService.getEmail({userId:t}),yield this.stateService.getKdfType({userId:t}),yield this.stateService.getKdfConfig({userId:t})),r=yield this.encryptService.encrypt(e.key,n);null!=(yield this.stateService.getPinKeyEncryptedUserKey({userId:t}))?yield this.stateService.setPinKeyEncryptedUserKey(r,{userId:t}):yield this.stateService.setPinKeyEncryptedUserKeyEphemeral(r,{userId:t})}))}shouldStoreKey(e,t){return KS(this,void 0,void 0,(function*(){let i=!1;switch(e){case x.Auto:i=null==(yield this.stateService.getVaultTimeout({userId:t}));break;case x.Pin:i=!!(yield this.stateService.getProtectedPin({userId:t}));break}return i}))}getKeyFromStorage(e,t){return KS(this,void 0,void 0,(function*(){if(e===x.Auto){const e=yield this.stateService.getUserKeyAutoUnlock({userId:t});if(e)return new N(p.fromB64ToArray(e))}return null}))}validateKdfConfig(e,t){switch(e){case b.PBKDF2_SHA256:if(!D.inRange(t.iterations))throw new Error(`PBKDF2 iterations must be between ${D.min} and ${D.max}`);break;case b.Argon2id:if(!A.inRange(t.iterations))throw new Error(`Argon2 iterations must be between ${A.min} and ${A.max}`);if(!O.inRange(t.memory))throw new Error(`Argon2 memory must be between ${O.min}mb and ${O.max}mb`);if(!C.inRange(t.parallelism))throw new Error(`Argon2 parallelism must be between ${C.min} and ${C.max}.`)}}clearAllStoredUserKeys(e){return KS(this,void 0,void 0,(function*(){yield this.stateService.setUserKeyAutoUnlock(null,{userId:e}),yield this.stateService.setPinKeyEncryptedUserKeyEphemeral(null,{userId:e})}))}stretchKey(e){return KS(this,void 0,void 0,(function*(){const t=new Uint8Array(64),i=yield this.cryptoFunctionService.hkdfExpand(e.key,"enc",32,"sha256"),n=yield this.cryptoFunctionService.hkdfExpand(e.key,"mac",32,"sha256");return t.set(new Uint8Array(i)),t.set(new Uint8Array(n),32),new N(t)}))}hashPhrase(e,t=64){return KS(this,void 0,void 0,(function*(){const i=Math.log(Nh.length)/Math.log(2);let n=Math.ceil(t/i);const r=Array.from(new Uint8Array(e));if(n*i>4*r.length)throw new Error("Output entropy of hash function is too small");const s=[];let o=mS.fromArray(r,256);for(;n--;){const e=o.mod(Nh.length);o=o.divide(Nh.length),s.push(Nh[e])}return s}))}buildProtectedSymmetricKey(e,t){return KS(this,void 0,void 0,(function*(){let i=null;if(32===e.key.byteLength){const n=yield this.stretchKey(e);i=yield this.encryptService.encrypt(t,n)}else{if(64!==e.key.byteLength)throw new Error("Invalid key size.");i=yield this.encryptService.encrypt(t,e)}return[new N(t),i]}))}clearDeprecatedKeys(e,t){return KS(this,void 0,void 0,(function*(){e===x.Auto?yield this.stateService.setCryptoMasterKeyAuto(null,{userId:t}):e===x.Pin&&(yield this.stateService.setEncryptedPinProtected(null,{userId:t}),yield this.stateService.setDecryptedPinProtected(null,{userId:t}))}))}migrateAutoKeyIfNeeded(e){return KS(this,void 0,void 0,(function*(){const t=yield this.stateService.getCryptoMasterKeyAuto({userId:e});if(!t)return;const i=new N(p.fromB64ToArray(t));if(yield this.isLegacyUser(i,e))return void(yield this.setMasterKey(i,e));const n=yield this.stateService.getEncryptedCryptoSymmetricKey({userId:e}),r=yield this.decryptUserKeyWithMasterKey(i,new z(n),e);yield this.stateService.setUserKeyAutoUnlock(r.keyB64,{userId:e}),yield this.stateService.setCryptoMasterKeyAuto(null,{userId:e}),yield this.setMasterKeyEncryptedUserKey(n)}))}decryptAndMigrateOldPinKey(e,t,i,n,r,s){return KS(this,void 0,void 0,(function*(){const o=yield this.decryptMasterKeyWithPin(t,i,n,r,s),a=yield this.stateService.getEncryptedCryptoSymmetricKey(),l=yield this.decryptUserKeyWithMasterKey(o,new z(a)),c=yield this.makePinKey(t,i,n,r),d=yield this.encryptService.encrypt(l.key,c);if(e)yield this.stateService.setDecryptedPinProtected(null),yield this.stateService.setPinKeyEncryptedUserKeyEphemeral(d);else{yield this.stateService.setEncryptedPinProtected(null),yield this.stateService.setPinKeyEncryptedUserKey(d);const e=yield this.encryptService.encrypt(t,l);yield this.stateService.setProtectedPin(e.encryptedString)}return yield this.stateService.setCryptoMasterKeyBiometric(null),l}))}encrypt(e,t){return KS(this,void 0,void 0,(function*(){return t||(t=yield this.getUserKeyWithLegacySupport()),yield this.encryptService.encrypt(e,t)}))}encryptToBytes(e,t){return KS(this,void 0,void 0,(function*(){return t||(t=yield this.getUserKeyWithLegacySupport()),this.encryptService.encryptToBytes(e,t)}))}decryptToBytes(e,t){return KS(this,void 0,void 0,(function*(){return t||(t=yield this.getUserKeyWithLegacySupport()),this.encryptService.decryptToBytes(e,t)}))}decryptToUtf8(e,t){return KS(this,void 0,void 0,(function*(){return t||(t=yield this.getUserKeyWithLegacySupport()),yield this.encryptService.decryptToUtf8(e,t)}))}decryptFromBytes(e,t){return KS(this,void 0,void 0,(function*(){if(null==e)throw new Error("No buffer provided for decryption.");return t||(t=yield this.getUserKeyWithLegacySupport()),this.encryptService.decryptToBytes(e,t)}))}}FS([Pp((()=>"getOrgKeys")),MS("design:type",Function),MS("design:paramtypes",[]),MS("design:returntype",Promise)],LS.prototype,"getOrgKeys",null),FS([Pp((()=>"getProviderKeys")),MS("design:type",Function),MS("design:paramtypes",[]),MS("design:returntype",Promise)],LS.prototype,"getProviderKeys",null);var zS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class VS extends LS{constructor(e,t,i,n,r,s,o,a,l){super(e,t,i,n,r,s,o,a),this.biometricStateService=l}hasUserKeyStored(e,t){const i=Object.create(null,{hasUserKeyStored:{get:()=>super.hasUserKeyStored}});return zS(this,void 0,void 0,(function*(){if(e===x.Biometric){const e=null==t?(0,r.z)(this.biometricStateService.biometricUnlockEnabled$):this.biometricStateService.getBiometricUnlockEnabled(t);return yield e}return i.hasUserKeyStored.call(this,e,t)}))}getKeyFromStorage(e,t){const i=Object.create(null,{getKeyFromStorage:{get:()=>super.getKeyFromStorage}});return zS(this,void 0,void 0,(function*(){if(e===x.Biometric){if(!(yield this.platformUtilService.authenticateBiometric()))return null;const e=yield(0,r.z)(this.stateProvider.getUserState$(ES,t));if(e)return e}return yield i.getKeyFromStorage.call(this,e,t)}))}}var BS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function _S(e,t){return lm(e,"biometricStateService",t,(()=>BS(this,void 0,void 0,(function*(){return new xs(yield Cw(e,t))}))))}var jS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function $S(e,t){return lm(e,"cryptoService",t,(()=>jS(this,void 0,void 0,(function*(){return new VS(yield Um(e,t),yield dm(e,t),yield hm(e,t),yield jm(e,t),yield cm(e,t),yield vS(e,t),yield Xm(e,t),yield Cw(e,t),yield _S(e,t))}))))}var WS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function qS(e,t){return lm(e,"authService",t,(()=>WS(this,void 0,void 0,(function*(){return new Rn(yield Bm(e,t),yield $S(e,t),yield gS(e,t),yield vS(e,t))}))))}var HS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function GS(e,t){return lm(e,"organizationService",t,(()=>HS(this,void 0,void 0,(function*(){return new on(yield Cw(e,t))}))))}var JS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function YS(e,t){return lm(e,"policyService",t,(()=>JS(this,void 0,void 0,(function*(){return new mn(yield Cw(e,t),yield GS(e,t))}))))}var QS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function XS(e,t){return lm(e,"autofillSettingsService",t,(()=>QS(this,void 0,void 0,(function*(){return new is(yield Cw(e,t),yield YS(e,t))}))))}var ZS=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function eb(e,t){return lm(e,"domainSettingsService",t,(()=>ZS(this,void 0,void 0,(function*(){return new us(yield Cw(e,t))}))))}var tb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};var ib=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function nb(e,t){return lm(e,"cipherFileUploadService",t,(()=>ib(this,void 0,void 0,(function*(){return new Uy(yield gS(e,t),yield function(e,t){return lm(e,"fileUploadService",t,(()=>tb(this,void 0,void 0,(function*(){return new Fo(yield cm(e,t))}))))}(e,t))}))))}var rb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class sb{constructor(e,t,i){this.systemLanguage=e,this.localesDirectory=t,this.getLocalesJson=i,this.supportedTranslationLocales=["en"],this.defaultLocale="en",this.localeNames=new Map([["af","Afrikaans"],["ar","العربية الفصحى"],["az","Azərbaycanca"],["be","Беларуская"],["bg","български"],["bn","বাংলা"],["bs","bosanski jezik"],["ca","català"],["cs","čeština"],["cy","Cymraeg, y Gymraeg"],["da","dansk"],["de","Deutsch"],["el","Ελληνικά"],["en","English"],["en-GB","English (British)"],["en-IN","English (India)"],["eo","Esperanto"],["es","español"],["et","eesti"],["eu","euskara"],["fa","فارسی"],["fi","suomi"],["fil","Wikang Filipino"],["fr","français"],["gl","galego"],["he","עברית"],["hi","हिन्दी"],["hr","hrvatski"],["hu","magyar"],["id","Bahasa Indonesia"],["it","italiano"],["ja","日本語"],["ka","ქართული"],["km","ខ្មែរ, ខេមរភាសា, ភាសាខ្មែរ"],["kn","ಕನ್ನಡ"],["ko","한국어"],["lt","lietuvių kalba"],["lv","Latvietis"],["me","црногорски"],["ml","മലയാളം"],["mr","मराठी"],["my","ဗမာစကား"],["nb","norsk (bokmål)"],["ne","नेपाली"],["nl","Nederlands"],["nn","Norsk Nynorsk"],["or","ଓଡ଼ିଆ"],["pl","polski"],["pt-BR","português do Brasil"],["pt-PT","português"],["ro","română"],["ru","русский"],["si","සිංහල"],["sk","slovenčina"],["sl","Slovenski jezik, Slovenščina"],["sr","Српски"],["sv","svenska"],["te","తెలుగు"],["th","ไทย"],["tr","Türkçe"],["uk","українська"],["vi","Tiếng Việt"],["zh-CN","中文(中国大陆)"],["zh-TW","中文(台灣)"]]),this.defaultMessages={},this.localeMessages={},this.systemLanguage=e.replace("_","-")}init(e){return rb(this,void 0,void 0,(function*(){if(this.inited)throw new Error("i18n already initialized.");if(null==this.supportedTranslationLocales||0===this.supportedTranslationLocales.length)throw new Error("supportedTranslationLocales not set.");this.inited=!0,this.translationLocale=null!=e?e:this.systemLanguage;try{this.collator=new Intl.Collator(this.translationLocale,{numeric:!0,sensitivity:"base"})}catch(e){this.collator=null}-1===this.supportedTranslationLocales.indexOf(this.translationLocale)&&(this.translationLocale=this.translationLocale.slice(0,2),-1===this.supportedTranslationLocales.indexOf(this.translationLocale)&&(this.translationLocale=this.defaultLocale)),null!=this.localesDirectory&&(yield this.loadMessages(this.translationLocale,this.localeMessages),this.translationLocale!==this.defaultLocale&&(yield this.loadMessages(this.defaultLocale,this.defaultMessages)))}))}t(e,t,i,n){return this.translate(e,t,i,n)}translate(e,t,i,n){let r;return r=this.localeMessages.hasOwnProperty(e)&&this.localeMessages[e]?this.localeMessages[e]:this.defaultMessages.hasOwnProperty(e)&&this.defaultMessages[e]?this.defaultMessages[e]:"",""!==r&&(null!=t&&(r=r.split("__$1__").join(t.toString())),null!=i&&(r=r.split("__$2__").join(i.toString())),null!=n&&(r=r.split("__$3__").join(n.toString()))),r}loadMessages(e,t){return rb(this,void 0,void 0,(function*(){const i=e.replace("-","_"),n=yield this.getLocalesJson(i);for(const e in n)if(n.hasOwnProperty(e)&&(t[e]=n[e].message,n[e].placeholders))for(const i in n[e].placeholders){if(!n[e].placeholders.hasOwnProperty(i)||!n[e].placeholders[i].content)continue;const r="\\$"+i.toUpperCase()+"\\$";let s=n[e].placeholders[i].content;"$1"!==s&&"$2"!==s&&"$3"!==s||(s="__$"+s+"__"),t[e]=t[e].replace(new RegExp(r,"g"),s)}}))}}var ob=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const ab=new jt(wi,"locale",{deserializer:e=>e});class lb extends sb{constructor(e,t,i,n){super(e,t,i),this.systemLanguage=e,this.localesDirectory=t,this.getLocalesJson=i,this.translationLocaleState=n.get(ab),this.userSetLocale$=this.translationLocaleState.state$,this.locale$=this.userSetLocale$.pipe((0,q.U)((e=>null!=e?e:this.translationLocale)))}setLocale(e){return ob(this,void 0,void 0,(function*(){yield this.translationLocaleState.update((()=>e))}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});return ob(this,void 0,void 0,(function*(){const t=yield(0,r.z)(this.translationLocaleState.state$);yield e.init.call(this,t)}))}}var cb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class db extends lb{constructor(e,t){super(e,null,(e=>cb(this,void 0,void 0,(function*(){const t=yield fetch(this.localesDirectory+e+"/messages.json");return yield t.json()}))),t),this.supportedTranslationLocales=["en","ar","az","be","bg","bn","bs","ca","cs","cy","da","de","el","en-GB","en-IN","es","et","eu","fa","fi","fil","fr","gl","he","hi","hr","hu","id","it","ja","ka","km","kn","ko","lt","lv","ml","mr","my","nb","ne","nl","nn","or","pl","pt-BR","pt-PT","ro","ru","si","sk","sl","sr","sv","te","th","tr","uk","vi","zh-CN","zh-TW"]}t(e,t,i,n){return this.translate(e,t,i,n)}translate(e,t,i,n){if(null==this.localesDirectory){const r=[];return null!=t&&r.push(t),null!=i&&r.push(i),null!=n&&r.push(n),r.length?chrome.i18n.getMessage(e,r):chrome.i18n.getMessage(e)}return super.translate(e,t,i,n)}}var ub=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function hb(e,t){return ub(this,void 0,void 0,(function*(){const i=yield lm(e,"i18nService",t,(()=>ub(this,void 0,void 0,(function*(){return new db(t.i18nServiceOptions.systemLanguage,yield Lm(e,t))}))));return i.inited||(yield i.init()),i}))}var pb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};var yb=i(22726),vb=i(79596);class fb{constructor(e){var t,i;this.featureStates={},this.version=e.version,this.gitHash=e.gitHash,this.server=e.server,this.utcDate=new Date(e.utcDate),this.environment=e.environment,this.featureStates=e.featureStates,null==(null===(t=this.server)||void 0===t?void 0:t.name)&&null==(null===(i=this.server)||void 0===i?void 0:i.url)&&(this.server=null)}getAgeInMilliseconds(){var e;return(new Date).getTime()-(null===(e=this.utcDate)||void 0===e?void 0:e.getTime())}isValid(){return this.getAgeInMilliseconds()<=864e5}expiresSoon(){return this.getAgeInMilliseconds()>=648e5}static fromJSON(e){return null==e?null:new fb(e)}}var gb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const mb=36e5;class wb{constructor(e,t,i,n,r,s,o=!0){this.stateService=e,this.configApiService=t,this.authService=i,this.environmentService=n,this.logService=r,this.stateProvider=s,this.subscribe=o,this.inited=!1,this._serverConfig=new yd.t(1),this.serverConfig$=this._serverConfig.asObservable(),this._forceFetchConfig=new Cn.x,this.refreshTimer$=(0,vd.H)(mb,mb),this.cloudRegion$=this.serverConfig$.pipe((0,q.U)((e=>{var t,i;return null!==(i=null===(t=null==e?void 0:e.environment)||void 0===t?void 0:t.cloudRegion)&&void 0!==i?i:Ym.US})))}init(){if(!this.subscribe||this.inited)return;const e=(0,jn.P)((()=>this.configApiService.get())).pipe((0,q.U)((e=>new nt(e))),(0,yb.j)((e=>this.saveConfig(e))),(0,vb.K)((e=>(this.logService.error("Unable to fetch ServerConfig: "+(null==e?void 0:e.message)),this.stateService.getServerConfig()))));(0,hd.T)(this.refreshTimer$,this.environmentService.environment$,this._forceFetchConfig).pipe((0,fw.b)((()=>e)),(0,q.U)((e=>null==e?null:new fb(e)))).subscribe((e=>this._serverConfig.next(e))),this.inited=!0}getFeatureFlag$(e,t){return this.serverConfig$.pipe((0,q.U)((i=>null==(null==i?void 0:i.featureStates)||null==i.featureStates[e]?t:i.featureStates[e])))}getFeatureFlag(e,t){return gb(this,void 0,void 0,(function*(){return yield(0,r.z)(this.getFeatureFlag$(e,t))}))}triggerServerConfigFetch(){this._forceFetchConfig.next()}saveConfig(e){var t;return gb(this,void 0,void 0,(function*(){if((yield this.authService.getAuthStatus())===On.LoggedOut)return;const i=yield(0,r.z)(this.stateProvider.activeUserId$);yield this.stateService.setServerConfig(e),yield this.environmentService.setCloudRegion(i,null===(t=e.environment)||void 0===t?void 0:t.cloudRegion)}))}checkServerMeetsVersionRequirement$(e){return this.serverConfig$.pipe((0,q.U)((t=>{if(null==t)return!1;return new wp.SemVer(t.version).compare(e)>=0})))}}var Sb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};var bb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Pb(e,t){return lm(e,"configService",t,(()=>bb(this,void 0,void 0,(function*(){var i,n;return new wb(yield vS(e,t),yield function(e,t){return lm(e,"configApiService",t,(()=>Sb(this,void 0,void 0,(function*(){return new js(yield gS(e,t),yield qS(e,t))}))))}(e,t),yield qS(e,t),yield Dw(e,t),yield cm(e,t),yield Cw(e,t),null===(n=null===(i=t.configServiceOptions)||void 0===i?void 0:i.subscribe)||void 0===n||n)}))))}var kb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Ob(e,t){return lm(e,"cipherService",t,(()=>kb(this,void 0,void 0,(function*(){return new Bp(yield $S(e,t),yield eb(e,t),yield gS(e,t),yield hb(e,t),yield function(e,t){return lm(e,"searchService",t,(()=>pb(this,void 0,void 0,(function*(){return new Ah(yield cm(e,t),yield hb(e,t))}))))}(e,t),yield vS(e,t),yield XS(e,t),yield hm(e,t),yield nb(e,t),yield Pb(e,t))}))))}var Cb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Ab(e,t){return lm(e,"billingAccountProfileStateService",t,(()=>Cb(this,void 0,void 0,(function*(){return new ms(yield Cw(e,t))}))))}var Db=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class xb{constructor(e,t,i,n,r){this.stateService=e,this.autofillSettingsService=t,this.i18nService=i,this.logService=n,this.billingAccountProfileStateService=r,this.initRunning=!1,this.initContextMenuItems=[{id:_r,title:"Bitwarden"},{id:Tr,parentId:_r,title:this.i18nService.t("autoFillLogin")},{id:Fr,parentId:_r,title:this.i18nService.t("copyUsername")},{id:Er,parentId:_r,title:this.i18nService.t("copyPassword")},{id:Mr,parentId:_r,title:this.i18nService.t("copyVerificationCode"),checkPremiumAccess:!0},{id:jr+1,type:"separator",parentId:_r},{id:Nr,parentId:_r,title:this.i18nService.t("autoFillIdentity")},{id:Ur,parentId:_r,title:this.i18nService.t("autoFillCard")},{id:jr+2,type:"separator",parentId:_r},{id:Vr,parentId:_r,title:this.i18nService.t("generatePasswordCopied")},{id:Rr,parentId:_r,title:this.i18nService.t("copyElementIdentifier")}],this.noCardsContextMenuItems=[{id:`${Ur}_NOTICE`,enabled:!1,parentId:Ur,title:this.i18nService.t("noCards"),type:"normal"},{id:`${Ur}_${jr}`,parentId:Ur,type:"separator"},{id:`${Ur}_${Kr}`,parentId:Ur,title:this.i18nService.t("addCardMenu"),type:"normal"}],this.noIdentitiesContextMenuItems=[{id:`${Nr}_NOTICE`,enabled:!1,parentId:Nr,title:this.i18nService.t("noIdentities"),type:"normal"},{id:`${Nr}_${jr}`,parentId:Nr,type:"separator"},{id:`${Nr}_${Lr}`,parentId:Nr,title:this.i18nService.t("addIdentityMenu"),type:"normal"}],this.noLoginsContextMenuItems=[{id:`${Tr}_NOTICE`,enabled:!1,parentId:Tr,title:this.i18nService.t("noMatchingLogins"),type:"normal"},{id:`${Tr}_${jr}1`,parentId:Tr,type:"separator"}]}static mv3Create(e){return Db(this,void 0,void 0,(function*(){const t=new Ns(Rs,tS),i={cryptoFunctionServiceOptions:{win:self},encryptServiceOptions:{logMacFailures:!1},i18nServiceOptions:{systemLanguage:chrome.i18n.getUILanguage()},logServiceOptions:{isDev:!1},stateServiceOptions:{stateFactory:t},platformUtilsServiceOptions:{clipboardWriteCallback:()=>Promise.resolve(),biometricCallback:()=>Promise.resolve(!1),win:self}};return new xb(yield vS(e,i),yield XS(e,i),yield hb(e,i),yield cm(e,i),yield Ab(e,i))}))}init(){return Db(this,void 0,void 0,(function*(){if(!(yield(0,r.z)(this.autofillSettingsService.enableContextMenu$)))return yield xb.removeAll(),!1;if(this.initRunning)return!0;this.initRunning=!0;try{for(const e of this.initContextMenuItems)e.checkPremiumAccess&&!(yield(0,r.z)(this.billingAccountProfileStateService.hasPremiumFromAnySource$))||(delete e.checkPremiumAccess,yield xb.create(Object.assign(Object.assign({},e),{contexts:["all"]})))}catch(e){this.logService.warning(e.message)}finally{this.initRunning=!1}return!0}))}static removeAll(){return Db(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{chrome.contextMenus.removeAll((()=>{chrome.runtime.lastError?t(chrome.runtime.lastError):e()}))}))}))}static remove(e){return new Promise(((t,i)=>{chrome.contextMenus.remove(e,(()=>{chrome.runtime.lastError?i(chrome.runtime.lastError):t()}))}))}loadOptions(e,t,i){var n,s,o,a;return Db(this,void 0,void 0,(function*(){try{const l=xb.sanitizeContextMenuTitle(e),c=e=>Db(this,void 0,void 0,(function*(){const i=`${e}_${t}`;return yield xb.create({type:"normal",id:i,parentId:e,title:l,contexts:["all"]})}));i&&(i.type!==Pe.Login||p.isNullOrEmpty(null===(n=i.login)||void 0===n?void 0:n.password))||(yield c(Tr),(null===(s=null==i?void 0:i.viewPassword)||void 0===s||s)&&(yield c(Er))),i&&(i.type!==Pe.Login||p.isNullOrEmpty(null===(o=i.login)||void 0===o?void 0:o.username))||(yield c(Fr));!(yield(0,r.z)(this.billingAccountProfileStateService.hasPremiumFromAnySource$))||i&&p.isNullOrEmpty(null===(a=i.login)||void 0===a?void 0:a.totp)||(yield c(Mr)),i&&i.type!==Pe.Card||t===zr||(yield c(Ur)),i&&i.type!==Pe.Identity||t===zr||(yield c(Nr))}catch(e){this.logService.warning(e.message)}}))}static sanitizeContextMenuTitle(e){return e.replace(/&/g,"&&")}noAccess(){return Db(this,void 0,void 0,(function*(){if(yield this.init()){const e=yield this.stateService.getIsAuthenticated();this.loadOptions(this.i18nService.t(e?"unlockVaultMenu":"loginToVaultMenu"),Br).catch((e=>this.logService.warning(e.message)))}}))}noCards(){return Db(this,void 0,void 0,(function*(){try{for(const e of this.noCardsContextMenuItems)yield xb.create(e)}catch(e){this.logService.warning(e.message)}}))}noIdentities(){return Db(this,void 0,void 0,(function*(){try{for(const e of this.noIdentitiesContextMenuItems)yield xb.create(e)}catch(e){this.logService.warning(e.message)}}))}noLogins(){return Db(this,void 0,void 0,(function*(){try{for(const e of this.noLoginsContextMenuItems)yield xb.create(e);yield this.loadOptions(this.i18nService.t("addLoginMenu"),zr)}catch(e){this.logService.warning(e.message)}}))}}xb.create=e=>Db(void 0,void 0,void 0,(function*(){if(chrome.contextMenus)return new Promise(((t,i)=>{chrome.contextMenus.create(e,(()=>{if(chrome.runtime.lastError)return i(chrome.runtime.lastError);t()}))}))}));var Ib=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Ub=(...e)=>Promise.resolve(),Tb=["loggedIn","unlocked","syncCompleted","bgUpdateContextMenu","editedCipher","addedCipher","deletedCipher"];class Nb{constructor(e,t,i){this.mainContextMenuHandler=e,this.authService=t,this.cipherService=i}static create(e){return Ib(this,void 0,void 0,(function*(){const t=new Ns(Rs,tS),i={apiServiceOptions:{logoutCallback:Ub},cryptoFunctionServiceOptions:{win:self},encryptServiceOptions:{logMacFailures:!1},i18nServiceOptions:{systemLanguage:chrome.i18n.getUILanguage()},keyConnectorServiceOptions:{logoutCallback:Ub},logServiceOptions:{isDev:!1},platformUtilsServiceOptions:{biometricCallback:()=>Promise.resolve(!1),clipboardWriteCallback:Ub,win:self},stateServiceOptions:{stateFactory:t}};return new Nb(yield xb.mv3Create(e),yield qS(e,i),yield Ob(e,i))}))}static windowsOnFocusChangedListener(e,t){return Ib(this,void 0,void 0,(function*(){const e=yield Nb.create(t),i=yield xg.getTabFromCurrentWindow();yield e.update(null==i?void 0:i.url)}))}static tabsOnActivatedListener(e,t){return Ib(this,void 0,void 0,(function*(){const i=yield Nb.create(t),n=yield xg.getTab(e.tabId);yield i.update(n.url)}))}static tabsOnReplacedListener(e,t,i){return Ib(this,void 0,void 0,(function*(){const t=yield Nb.create(i),n=yield xg.getTab(e);yield t.update(n.url)}))}static tabsOnUpdatedListener(e,t,i,n){return Ib(this,void 0,void 0,(function*(){if("complete"!==t.status)return;const e=yield Nb.create(n);yield e.update(i.url)}))}static messageListener(e,t,i){return Ib(this,void 0,void 0,(function*(){if(!Nb.shouldListen(e))return;const t=yield Nb.create(i);yield t.messageListener(e)}))}static shouldListen(e){return Tb.includes(e.command)}messageListener(e,t){return Ib(this,void 0,void 0,(function*(){if(!Nb.shouldListen(e))return;const t=yield xg.getActiveTabs();t&&0!==t.length&&(yield this.update(t[0].url))}))}update(e){return Ib(this,void 0,void 0,(function*(){if(this.mainContextMenuHandler.initRunning)return;const t=yield this.authService.getAuthStatus();if(yield xb.removeAll(),t!==On.Unlocked)return void(yield this.mainContextMenuHandler.noAccess());if(!(yield this.mainContextMenuHandler.init()))return;const i=yield this.cipherService.getAllDecryptedForUrl(e,[Pe.Card,Pe.Identity]);i.sort(((e,t)=>this.cipherService.sortCiphersByLastUsedThenName(e,t)));const n=i.reduce(((e,t)=>{if(!(null==t?void 0:t.type))return e;const i=e[t.type]||[];return Object.assign(Object.assign({},e),{[t.type]:[...i,t]})}),{[Pe.Login]:[],[Pe.Card]:[],[Pe.Identity]:[]});0===n[Pe.Login].length&&(yield this.mainContextMenuHandler.noLogins()),0===n[Pe.Identity].length&&(yield this.mainContextMenuHandler.noIdentities()),0===n[Pe.Card].length&&(yield this.mainContextMenuHandler.noCards());for(const e of i)yield this.updateForCipher(e)}))}updateForCipher(e){var t,i;return Ib(this,void 0,void 0,(function*(){if(null==e||!new Set([Pe.Login,Pe.Card,Pe.Identity]).has(e.type))return;let n=e.name;e.type===Pe.Login&&!p.isNullOrEmpty(n)&&(null===(t=e.login)||void 0===t?void 0:t.username)&&(n+=` (${e.login.username})`),e.type===Pe.Card&&(null===(i=e.card)||void 0===i?void 0:i.subTitle)&&(n+=` ${e.card.subTitle}`),yield this.mainContextMenuHandler.loadOptions(n,e.id,e)}))}}var Rb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Eb(e,t){return lm(e,"userDecryptionOptionsService",t,(()=>Rb(this,void 0,void 0,(function*(){return new Bi(yield Cw(e,t))}))))}var Fb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Mb(e,t){return lm(e,"vaultTimeoutSettingsService",t,(()=>Fb(this,void 0,void 0,(function*(){return new xh(yield Eb(e,t),yield $S(e,t),yield Gm(e,t),yield YS(e,t),yield vS(e,t),yield _S(e,t))}))))}var Kb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};var Lb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};var zb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Vb(e,t){return lm(e,"userVerificationService",t,(()=>zb(this,void 0,void 0,(function*(){return new xr(yield vS(e,t),yield $S(e,t),yield hb(e,t),yield function(e,t){return lm(e,"userVerificationApiService",t,(()=>Lb(this,void 0,void 0,(function*(){return new Cr(yield gS(e,t))}))))}(e,t),yield Eb(e,t),yield function(e,t){return lm(e,"pinCryptoService",t,(()=>Kb(this,void 0,void 0,(function*(){return new B(yield vS(e,t),yield $S(e,t),yield Mb(e,t),yield cm(e,t))}))))}(e,t),yield cm(e,t),yield Mb(e,t),yield jm(e,t))}))))}var Bb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};var _b=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function jb(e,t){return lm(e,"eventCollectionService",t,(()=>_b(this,void 0,void 0,(function*(){return new ch(yield Ob(e,t),yield Cw(e,t),yield GS(e,t),yield function(e,t){return lm(e,"eventUploadService",t,(()=>Bb(this,void 0,void 0,(function*(){return new hh(yield gS(e,t),yield Cw(e,t),yield cm(e,t),yield Xm(e,t))}))))}(e,t),yield Xm(e,t))}))))}var $b=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Wb(e,t){return lm(e,"passwordGenerationService",t,(()=>$b(this,void 0,void 0,(function*(){return new Vh(yield $S(e,t),yield YS(e,t),yield vS(e,t))}))))}var qb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};function Hb(e,t){return lm(e,"totpService",t,(()=>qb(this,void 0,void 0,(function*(){return new Qy(yield dm(e,t),yield cm(e,t))}))))}const Gb="autofill-injected-script-port";class Jb{constructor(){this.script=[],this.properties={},this.metadata={},this.autosubmit=null}}class Yb{}Yb.UsernameFieldNames=["username","user name","email","email address","e-mail","e-mail address","userid","user id","customer id","login id","login","benutzername","benutzer name","email adresse","e-mail adresse","benutzerid","benutzer id"],Yb.TotpFieldNames=["totp","2fa","mfa","totpcode","2facode","approvals_code","code","mfacode","otc","otc-code","otp-code","otpcode","pin","security_code","twofactor","twofa","twofactorcode","verificationCode"],Yb.SearchFieldNames=["search","query","find","go"],Yb.FieldIgnoreList=["captcha","findanything","forgot"],Yb.PasswordFieldExcludeList=[...Yb.FieldIgnoreList,"onetimepassword"],Yb.ExcludedAutofillLoginTypes=["hidden","file","button","image","reset","search"],Yb.ExcludedAutofillTypes=["radio","checkbox",...Yb.ExcludedAutofillLoginTypes],Yb.ExcludedOverlayTypes=["textarea",...Yb.ExcludedAutofillTypes];class Qb{}Qb.CardAttributes=["autoCompleteType","data-stripe","htmlName","htmlID","label-tag","placeholder","label-left","label-top","data-recurly"],Qb.CardAttributesExtended=[...Qb.CardAttributes,"label-right"],Qb.CardHolderFieldNames=["cc-name","card-name","cardholder-name","cardholder","name","nom"],Qb.CardHolderFieldNameValues=["cc-name","card-name","cardholder-name","cardholder","tbName"],Qb.CardNumberFieldNames=["cc-number","cc-num","card-number","card-num","number","cc","cc-no","card-no","credit-card","numero-carte","carte","carte-credit","num-carte","cb-num","card-pan"],Qb.CardNumberFieldNameValues=["cc-number","cc-num","card-number","card-num","cc-no","card-no","numero-carte","num-carte","cb-num"],Qb.CardExpiryFieldNames=["cc-exp","card-exp","cc-expiration","card-expiration","cc-ex","card-ex","card-expire","card-expiry","validite","expiration","expiry","mm-yy","mm-yyyy","yy-mm","yyyy-mm","expiration-date","payment-card-expiration","payment-cc-date"],Qb.CardExpiryFieldNameValues=["mm-yy","mm-yyyy","yy-mm","yyyy-mm","expiration-date","payment-card-expiration"],Qb.ExpiryMonthFieldNames=["exp-month","cc-exp-month","cc-month","card-month","cc-mo","card-mo","exp-mo","card-exp-mo","cc-exp-mo","card-expiration-month","expiration-month","cc-mm","cc-m","card-mm","card-m","card-exp-mm","cc-exp-mm","exp-mm","exp-m","expire-month","expire-mo","expiry-month","expiry-mo","card-expire-month","card-expire-mo","card-expiry-month","card-expiry-mo","mois-validite","mois-expiration","m-validite","m-expiration","expiry-date-field-month","expiration-date-month","expiration-date-mm","exp-mon","validity-mo","exp-date-mo","cb-date-mois","date-m"],Qb.ExpiryYearFieldNames=["exp-year","cc-exp-year","cc-year","card-year","cc-yr","card-yr","exp-yr","card-exp-yr","cc-exp-yr","card-expiration-year","expiration-year","cc-yy","cc-y","card-yy","card-y","card-exp-yy","cc-exp-yy","exp-yy","exp-y","cc-yyyy","card-yyyy","card-exp-yyyy","cc-exp-yyyy","expire-year","expire-yr","expiry-year","expiry-yr","card-expire-year","card-expire-yr","card-expiry-year","card-expiry-yr","an-validite","an-expiration","annee-validite","annee-expiration","expiry-date-field-year","expiration-date-year","cb-date-ann","expiration-date-yy","expiration-date-yyyy","validity-year","exp-date-year","date-y"],Qb.CVVFieldNames=["cvv","cvc","cvv2","cc-csc","cc-cvv","card-csc","card-cvv","cvd","cid","cvc2","cnv","cvn2","cc-code","card-code","code-securite","security-code","crypto","card-verif","verification-code","csc","ccv"],Qb.CardBrandFieldNames=["cc-type","card-type","card-brand","cc-brand","cb-type"],Qb.MonthAbbr=["mm","mm","mm","mm","мм","mm"],Qb.YearAbbrShort=["yy","åå","jj","aa","гг","rr"],Qb.YearAbbrLong=["yyyy","åååå","jjjj","aa","гггг","rrrr"];class Xb{}Xb.IdentityAttributes=["autoCompleteType","data-stripe","htmlName","htmlID","label-tag","placeholder","label-left","label-top","data-recurly"],Xb.FullNameFieldNames=["name","full-name","your-name"],Xb.FullNameFieldNameValues=["full-name","your-name"],Xb.TitleFieldNames=["honorific-prefix","prefix","title","anrede"],Xb.FirstnameFieldNames=["f-name","first-name","given-name","first-n","vorname"],Xb.MiddlenameFieldNames=["m-name","middle-name","additional-name","middle-initial","middle-n","middle-i"],Xb.LastnameFieldNames=["l-name","last-name","s-name","surname","family-name","family-n","last-n","nachname","familienname"],Xb.EmailFieldNames=["e-mail","email-address"],Xb.AddressFieldNames=["address","street-address","addr","street","mailing-addr","billing-addr","mail-addr","bill-addr","strasse","adresse"],Xb.AddressFieldNameValues=["mailing-addr","billing-addr","mail-addr","bill-addr"],Xb.Address1FieldNames=["address-1","address-line-1","addr-1","street-1"],Xb.Address2FieldNames=["address-2","address-line-2","addr-2","street-2"],Xb.Address3FieldNames=["address-3","address-line-3","addr-3","street-3"],Xb.PostalCodeFieldNames=["postal","zip","zip2","zip-code","postal-code","post-code","address-zip","address-postal","address-code","address-postal-code","address-zip-code","plz","postleitzahl"],Xb.CityFieldNames=["city","town","address-level-2","address-city","address-town","ort","stadt","wohnort"],Xb.StateFieldNames=["state","province","provence","address-level-1","address-state","address-province","bundesland"],Xb.CountryFieldNames=["country","country-code","country-name","address-country","address-country-name","address-country-code","land"],Xb.PhoneFieldNames=["phone","mobile","mobile-phone","tel","telephone","phone-number","telefon","telefonnummer","mobil","handy"],Xb.UserNameFieldNames=["user-name","user-id","screen-name"],Xb.CompanyFieldNames=["company","company-name","organization","organization-name","firma"],Xb.IsoCountries={afghanistan:"AF","aland islands":"AX",albania:"AL",algeria:"DZ","american samoa":"AS",andorra:"AD",angola:"AO",anguilla:"AI",antarctica:"AQ","antigua and barbuda":"AG",argentina:"AR",armenia:"AM",aruba:"AW",australia:"AU",austria:"AT",azerbaijan:"AZ",bahamas:"BS",bahrain:"BH",bangladesh:"BD",barbados:"BB",belarus:"BY",belgium:"BE",belize:"BZ",benin:"BJ",bermuda:"BM",bhutan:"BT",bolivia:"BO","bosnia and herzegovina":"BA",botswana:"BW","bouvet island":"BV",brazil:"BR","british indian ocean territory":"IO","brunei darussalam":"BN",bulgaria:"BG","burkina faso":"BF",burundi:"BI",cambodia:"KH",cameroon:"CM",canada:"CA","cape verde":"CV","cayman islands":"KY","central african republic":"CF",chad:"TD",chile:"CL",china:"CN","christmas island":"CX","cocos (keeling) islands":"CC",colombia:"CO",comoros:"KM",congo:"CG","congo, democratic republic":"CD","cook islands":"CK","costa rica":"CR","cote d'ivoire":"CI",croatia:"HR",cuba:"CU",cyprus:"CY","czech republic":"CZ",denmark:"DK",djibouti:"DJ",dominica:"DM","dominican republic":"DO",ecuador:"EC",egypt:"EG","el salvador":"SV","equatorial guinea":"GQ",eritrea:"ER",estonia:"EE",ethiopia:"ET","falkland islands":"FK","faroe islands":"FO",fiji:"FJ",finland:"FI",france:"FR","french guiana":"GF","french polynesia":"PF","french southern territories":"TF",gabon:"GA",gambia:"GM",georgia:"GE",germany:"DE",ghana:"GH",gibraltar:"GI",greece:"GR",greenland:"GL",grenada:"GD",guadeloupe:"GP",guam:"GU",guatemala:"GT",guernsey:"GG",guinea:"GN","guinea-bissau":"GW",guyana:"GY",haiti:"HT","heard island & mcdonald islands":"HM","holy see (vatican city state)":"VA",honduras:"HN","hong kong":"HK",hungary:"HU",iceland:"IS",india:"IN",indonesia:"ID","iran, islamic republic of":"IR",iraq:"IQ",ireland:"IE","isle of man":"IM",israel:"IL",italy:"IT",jamaica:"JM",japan:"JP",jersey:"JE",jordan:"JO",kazakhstan:"KZ",kenya:"KE",kiribati:"KI","republic of korea":"KR","south korea":"KR","democratic people's republic of korea":"KP","north korea":"KP",kuwait:"KW",kyrgyzstan:"KG","lao people's democratic republic":"LA",latvia:"LV",lebanon:"LB",lesotho:"LS",liberia:"LR","libyan arab jamahiriya":"LY",liechtenstein:"LI",lithuania:"LT",luxembourg:"LU",macao:"MO",macedonia:"MK",madagascar:"MG",malawi:"MW",malaysia:"MY",maldives:"MV",mali:"ML",malta:"MT","marshall islands":"MH",martinique:"MQ",mauritania:"MR",mauritius:"MU",mayotte:"YT",mexico:"MX","micronesia, federated states of":"FM",moldova:"MD",monaco:"MC",mongolia:"MN",montenegro:"ME",montserrat:"MS",morocco:"MA",mozambique:"MZ",myanmar:"MM",namibia:"NA",nauru:"NR",nepal:"NP",netherlands:"NL","netherlands antilles":"AN","new caledonia":"NC","new zealand":"NZ",nicaragua:"NI",niger:"NE",nigeria:"NG",niue:"NU","norfolk island":"NF","northern mariana islands":"MP",norway:"NO",oman:"OM",pakistan:"PK",palau:"PW","palestinian territory, occupied":"PS",panama:"PA","papua new guinea":"PG",paraguay:"PY",peru:"PE",philippines:"PH",pitcairn:"PN",poland:"PL",portugal:"PT","puerto rico":"PR",qatar:"QA",reunion:"RE",romania:"RO","russian federation":"RU",rwanda:"RW","saint barthelemy":"BL","saint helena":"SH","saint kitts and nevis":"KN","saint lucia":"LC","saint martin":"MF","saint pierre and miquelon":"PM","saint vincent and grenadines":"VC",samoa:"WS","san marino":"SM","sao tome and principe":"ST","saudi arabia":"SA",senegal:"SN",serbia:"RS",seychelles:"SC","sierra leone":"SL",singapore:"SG",slovakia:"SK",slovenia:"SI","solomon islands":"SB",somalia:"SO","south africa":"ZA","south georgia and sandwich isl.":"GS",spain:"ES","sri lanka":"LK",sudan:"SD",suriname:"SR","svalbard and jan mayen":"SJ",swaziland:"SZ",sweden:"SE",switzerland:"CH","syrian arab republic":"SY",taiwan:"TW",tajikistan:"TJ",tanzania:"TZ",thailand:"TH","timor-leste":"TL",togo:"TG",tokelau:"TK",tonga:"TO","trinidad and tobago":"TT",tunisia:"TN",turkey:"TR",turkmenistan:"TM","turks and caicos islands":"TC",tuvalu:"TV",uganda:"UG",ukraine:"UA","united arab emirates":"AE","united kingdom":"GB","united states":"US","united states outlying islands":"UM",uruguay:"UY",uzbekistan:"UZ",vanuatu:"VU",venezuela:"VE",vietnam:"VN","virgin islands, british":"VG","virgin islands, u.s.":"VI","wallis and futuna":"WF","western sahara":"EH",yemen:"YE",zambia:"ZM",zimbabwe:"ZW"},Xb.IsoStates={alabama:"AL",alaska:"AK","american samoa":"AS",arizona:"AZ",arkansas:"AR",california:"CA",colorado:"CO",connecticut:"CT",delaware:"DE","district of columbia":"DC","federated states of micronesia":"FM",florida:"FL",georgia:"GA",guam:"GU",hawaii:"HI",idaho:"ID",illinois:"IL",indiana:"IN",iowa:"IA",kansas:"KS",kentucky:"KY",louisiana:"LA",maine:"ME","marshall islands":"MH",maryland:"MD",massachusetts:"MA",michigan:"MI",minnesota:"MN",mississippi:"MS",missouri:"MO",montana:"MT",nebraska:"NE",nevada:"NV","new hampshire":"NH","new jersey":"NJ","new mexico":"NM","new york":"NY","north carolina":"NC","north dakota":"ND","northern mariana islands":"MP",ohio:"OH",oklahoma:"OK",oregon:"OR",palau:"PW",pennsylvania:"PA","puerto rico":"PR","rhode island":"RI","south carolina":"SC","south dakota":"SD",tennessee:"TN",texas:"TX",utah:"UT",vermont:"VT","virgin islands":"VI",virginia:"VA",washington:"WA","west virginia":"WV",wisconsin:"WI",wyoming:"WY"},Xb.IsoProvinces={alberta:"AB","british columbia":"BC",manitoba:"MB","new brunswick":"NB","newfoundland and labrador":"NL","nova scotia":"NS",ontario:"ON","prince edward island":"PE",quebec:"QC",saskatchewan:"SK"};var Zb=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class eP{constructor(e,t,i,n,r,s,o,a,l){this.cipherService=e,this.stateService=t,this.autofillSettingsService=i,this.totpService=n,this.eventCollectionService=r,this.logService=s,this.domainSettingsService=o,this.userVerificationService=a,this.billingAccountProfileStateService=l,this.openVaultItemPasswordRepromptPopout=_g,this.currentlyOpeningPasswordRepromptPopout=!1,this.autofillScriptPortsSet=new Set,this.handleInjectedScriptPortConnection=e=>{e.name===Gb&&(this.autofillScriptPortsSet.add(e),e.onDisconnect.addListener(this.handleInjectScriptPortOnDisconnect))},this.handleInjectScriptPortOnDisconnect=e=>{e.name===Gb&&this.autofillScriptPortsSet.delete(e)}}loadAutofillScriptsOnInstall(){return Zb(this,void 0,void 0,(function*(){xg.addListener(chrome.runtime.onConnect,this.handleInjectedScriptPortConnection),this.injectAutofillScriptsInAllTabs()}))}reloadAutofillScripts(){return Zb(this,void 0,void 0,(function*(){this.autofillScriptPortsSet.forEach((e=>{e.disconnect(),this.autofillScriptPortsSet.delete(e)})),this.injectAutofillScriptsInAllTabs()}))}injectAutofillScripts(e,t=0,i=!0){return Zb(this,void 0,void 0,(function*(){const n=[(yield this.getOverlayVisibility())?"bootstrap-autofill-overlay.js":"bootstrap-autofill.js"],r=yield this.getAutofillOnPageLoad();i&&r?n.push("autofiller.js"):yield xg.executeScriptInTab(e.id,{file:"content/content-message-handler.js",runAt:"document_start"}),n.push("notificationBar.js","contextMenuHandler.js");for(const i of n)yield xg.executeScriptInTab(e.id,{file:`content/${i}`,frameId:t,runAt:"document_start"})}))}getFormsWithPasswordFields(e){const t=[],i=eP.loadPasswordFields(e,!0,!0,!1,!0);if(0===i.length)return t;const n=i.filter((e=>void 0===e.form)),r=Object.keys(e.forms),s=r.length;if(3===i.length&&1==s&&n.length>0){const e=r[0];i.filter((t=>null!==t.form&&t.form===e)).length>0&&n.forEach((t=>{t.form=e}))}for(const n in e.forms){if(!e.forms.hasOwnProperty(n))continue;const r=i.filter((e=>n===e.form));if(r.length>0){let i=this.findUsernameField(e,r[0],!1,!1,!1);null==i&&(i=this.findUsernameField(e,r[0],!0,!0,!1)),t.push({form:e.forms[n],password:r[0],username:i,passwords:r})}}return t}getOverlayVisibility(){return Zb(this,void 0,void 0,(function*(){return yield(0,r.z)(this.autofillSettingsService.inlineMenuVisibility$)}))}getShouldAutoCopyTotp(){return Zb(this,void 0,void 0,(function*(){return yield(0,r.z)(this.autofillSettingsService.autoCopyTotp$)}))}getAutofillOnPageLoad(){return Zb(this,void 0,void 0,(function*(){return yield(0,r.z)(this.autofillSettingsService.autofillOnPageLoad$)}))}getDefaultUriMatchStrategy(){return Zb(this,void 0,void 0,(function*(){return yield(0,r.z)(this.domainSettingsService.defaultUriMatchStrategy$)}))}doAutoFill(e){return Zb(this,void 0,void 0,(function*(){const t=e.tab;if(!(t&&e.cipher&&e.pageDetails&&e.pageDetails.length))throw new Error("Nothing to auto-fill.");let i=null;const n=yield(0,r.z)(this.billingAccountProfileStateService.hasPremiumFromAnySource$),s=yield this.getDefaultUriMatchStrategy();n||(e.cipher.login.totp=null);let o=!1;if(yield Promise.all(e.pageDetails.map((r=>Zb(this,void 0,void 0,(function*(){if(r.tab.id!==t.id||r.tab.url!==t.url)return;const a=yield this.generateFillScript(r.details,{skipUsernameOnlyFill:e.skipUsernameOnlyFill||!1,onlyEmptyFields:e.onlyEmptyFields||!1,onlyVisibleFields:e.onlyVisibleFields||!1,fillNewPassword:e.fillNewPassword||!1,allowTotpAutofill:e.allowTotpAutofill||!1,cipher:e.cipher,tabUrl:t.url,defaultUriMatch:s});if(!a||!a.script||!a.script.length)return;if(a.untrustedIframe&&null!=e.allowUntrustedIframe&&!e.allowUntrustedIframe)return void this.logService.info("Auto-fill on page load was blocked due to an untrusted iframe.");if(a.properties.delay_between_operations=20,o=!0,e.skipLastUsed||this.cipherService.updateLastUsedDate(e.cipher.id),xg.tabSendMessage(t,{command:"fillForm",fillScript:a,url:t.url,pageDetailsUrl:r.details.url},{frameId:r.frameId}),e.cipher.type!==Pe.Login||null!==i||!e.cipher.login.totp||!n&&!e.cipher.organizationUseTotp)return;const l=yield this.getShouldAutoCopyTotp();i=l?yield this.totpService.getCode(e.cipher.login.totp):null}))))),o)return this.eventCollectionService.collect(ve.Cipher_ClientAutofilled,e.cipher.id),null!==i?i:null;throw new Error("Did not auto-fill.")}))}doAutoFillOnTab(e,t,i){var n,r;return Zb(this,void 0,void 0,(function*(){let s;if(i)s=yield this.cipherService.getNextCipherForUrl(t.url);else{const e=yield this.cipherService.getLastLaunchedForUrl(t.url,!0);s=e&&Date.now().valueOf()-(null===(r=null===(n=e.localData)||void 0===n?void 0:n.lastLaunched)||void 0===r?void 0:r.valueOf())<3e4?e:yield this.cipherService.getLastUsedForUrl(t.url,!0)}if(null==s||s.reprompt===be.Password&&!i)return null;if(yield this.isPasswordRepromptRequired(s,t))return i&&this.cipherService.updateLastUsedIndexForUrl(t.url),null;const o=yield this.doAutoFill({tab:t,cipher:s,pageDetails:e,skipLastUsed:!i,skipUsernameOnlyFill:!i,onlyEmptyFields:!i,onlyVisibleFields:!i,fillNewPassword:i,allowUntrustedIframe:i,allowTotpAutofill:i});return i&&this.cipherService.updateLastUsedIndexForUrl(t.url),o}))}isPasswordRepromptRequired(e,t){return Zb(this,void 0,void 0,(function*(){const i=yield this.userVerificationService.hasMasterPasswordAndMasterKeyHash();return!(e.reprompt!==be.Password||!i)&&(this.isDebouncingPasswordRepromptPopout()||(yield this.openVaultItemPasswordRepromptPopout(t,{cipherId:e.id,action:"autofill"})),!0)}))}doAutoFillActiveTab(e,t,i){var n,r,s;return Zb(this,void 0,void 0,(function*(){if(!(null===(s=null===(r=null===(n=e[0])||void 0===n?void 0:n.details)||void 0===r?void 0:r.fields)||void 0===s?void 0:s.length))return null;const o=yield this.getActiveTab();if(!o||!o.url)return null;if(!i||i===Pe.Login)return yield this.doAutoFillOnTab(e,o,t);const a=((yield this.cipherService.getAllDecryptedForUrl(o.url,[i]))||[]).find((({type:e})=>e===i));return a&&a.reprompt===be.None?yield this.doAutoFill({tab:o,cipher:a,pageDetails:e,skipLastUsed:!t,skipUsernameOnlyFill:!t,onlyEmptyFields:!t,onlyVisibleFields:!t,fillNewPassword:!1,allowUntrustedIframe:t,allowTotpAutofill:!1}):null}))}getActiveTab(){return Zb(this,void 0,void 0,(function*(){const e=yield xg.getTabFromCurrentWindow();if(!e)throw new Error("No tab found.");return e}))}generateFillScript(e,t){return Zb(this,void 0,void 0,(function*(){if(!e||!t.cipher)return null;let i=new Jb;const n={},r=t.cipher.fields;if(r&&r.length){const s=[];r.forEach((e=>{eP.hasValue(e.name)&&s.push(e.name.toLowerCase())})),e.fields.forEach((e=>{if(n.hasOwnProperty(e.opid))return;if(!e.viewable&&"span"!==e.tagName)return;if(eP.isSearchField(e))return;const o=this.findMatchingFieldIndex(e,s);if(o>-1){const s=r[o];let a;s.type===ke.Linked?a=t.cipher.linkedFieldValue(s.linkedId):(a=s.value,null==a&&s.type===ke.Boolean&&(a="false")),n[e.opid]=e,eP.fillByOpid(i,e,a)}}))}switch(t.cipher.type){case Pe.Login:i=yield this.generateLoginFillScript(i,e,n,t);break;case Pe.Card:i=this.generateCardFillScript(i,e,n,t);break;case Pe.Identity:i=this.generateIdentityFillScript(i,e,n,t);break;default:return null}return i}))}generateLoginFillScript(e,t,i,n){var r,s;return Zb(this,void 0,void 0,(function*(){if(!n.cipher.login)return null;const o=[],a=[],l=[];let c=null,d=null,u=null;const h=n.cipher.login;e.savedUrls=null!==(s=null===(r=null==h?void 0:h.uris)||void 0===r?void 0:r.filter((e=>e.match!=He)).map((e=>e.uri)))&&void 0!==s?s:[],e.untrustedIframe=yield this.inUntrustedIframe(t.url,n);let p=eP.loadPasswordFields(t,!1,!1,n.onlyEmptyFields,n.fillNewPassword);p.length||n.onlyVisibleFields||(p=eP.loadPasswordFields(t,!0,!0,n.onlyEmptyFields,n.fillNewPassword));for(const e in t.forms)t.forms.hasOwnProperty(e)&&p.forEach((e=>{c=e,o.push(c),h.username&&(d=this.findUsernameField(t,c,!1,!1,!1),d||n.onlyVisibleFields||(d=this.findUsernameField(t,c,!0,!0,!1)),d&&a.push(d)),n.allowTotpAutofill&&h.totp&&(u=this.findTotpField(t,c,!1,!1,!1),u||n.onlyVisibleFields||(u=this.findTotpField(t,c,!0,!0,!1)),u&&l.push(u))}));return p.length&&!o.length&&(c=p[0],o.push(c),h.username&&c.elementNumber>0&&(d=this.findUsernameField(t,c,!1,!1,!0),d||n.onlyVisibleFields||(d=this.findUsernameField(t,c,!0,!0,!0)),d&&a.push(d)),n.allowTotpAutofill&&h.totp&&c.elementNumber>0&&(u=this.findTotpField(t,c,!1,!1,!0),u||n.onlyVisibleFields||(u=this.findTotpField(t,c,!0,!0,!0)),u&&l.push(u))),p.length||t.fields.forEach((e=>{n.skipUsernameOnlyFill||!e.viewable||"text"!==e.type&&"email"!==e.type&&"tel"!==e.type||!eP.fieldIsFuzzyMatch(e,Yb.UsernameFieldNames)||a.push(e),!n.allowTotpAutofill||!e.viewable||"text"!==e.type&&"number"!==e.type||!eP.fieldIsFuzzyMatch(e,Yb.TotpFieldNames)&&"one-time-code"!==e.autoCompleteType||l.push(e)})),a.forEach((t=>{i.hasOwnProperty(t.opid)||(i[t.opid]=t,eP.fillByOpid(e,t,h.username))})),o.forEach((t=>{i.hasOwnProperty(t.opid)||(i[t.opid]=t,eP.fillByOpid(e,t,h.password))})),n.allowTotpAutofill&&(yield Promise.all(l.map((t=>Zb(this,void 0,void 0,(function*(){if(Object.prototype.hasOwnProperty.call(i,t.opid))return;i[t.opid]=t;const n=yield this.totpService.getCode(h.totp);eP.fillByOpid(e,t,n)})))))),e=eP.setFillScriptForFocus(i,e)}))}generateCardFillScript(e,t,i,n){if(!n.cipher.card)return null;const r={};t.fields.forEach((e=>{if(!eP.isExcludedFieldType(e,Yb.ExcludedAutofillTypes))for(let t=0;t1&&(t=n[1])}}else!this.fieldAttrsContain(r.expMonth,"mm")&&2!==r.expMonth.maxLength||1!==t.length||(t="0"+t);i[r.expMonth.opid]=r.expMonth,eP.fillByOpid(e,r.expMonth,t)}if(r.expYear&&eP.hasValue(s.expYear)){let t=s.expYear;if(r.expYear.selectInfo&&r.expYear.selectInfo.options)for(let e=0;e-1&&i[1].length>n+1){const e=i[1].substring(n+2);if(null!=e&&""!==e.trim()&&e===s.expYear){t=i[1];break}}}else this.fieldAttrsContain(r.expYear,"yyyy")||4===r.expYear.maxLength?2===t.length&&(t="20"+t):(this.fieldAttrsContain(r.expYear,"yy")||2===r.expYear.maxLength)&&4===t.length&&(t=t.substr(2));i[r.expYear.opid]=r.expYear,eP.fillByOpid(e,r.expYear,t)}if(r.exp&&eP.hasValue(s.expMonth)&&eP.hasValue(s.expYear)){const t=("0"+s.expMonth).slice(-2);let n=s.expYear,o=null;2===n.length?(o=n,n="20"+n):4===n.length&&(o=n.substr(2,2));let a=null;for(let e=0;e{if(i||!e.hasOwnProperty(n)||!e[n])return;let r=e[n];r=r.replace(/ /g,"").toLowerCase(),i=r.indexOf(t)>-1})),i}generateIdentityFillScript(e,t,i,n){if(!n.cipher.identity)return null;const r={};t.fields.forEach((e=>{if(!eP.isExcludedFieldType(e,Yb.ExcludedAutofillTypes))for(let t=0;t2){const t=s.state.toLowerCase(),n=Xb.IsoStates[t]||Xb.IsoProvinces[t];n&&(o=!0,this.makeScriptActionWithValue(e,n,r.state,i))}o||this.makeScriptAction(e,s,r,i,"state");let a=!1;if(r.country&&s.country&&s.country.length>2){const t=s.country.toLowerCase(),n=Xb.IsoCountries[t];n&&(a=!0,this.makeScriptActionWithValue(e,n,r.country,i))}if(a||this.makeScriptAction(e,s,r,i,"country"),r.name&&(s.firstName||s.lastName)){let t="";eP.hasValue(s.firstName)&&(t=s.firstName),eP.hasValue(s.middleName)&&(""!==t&&(t+=" "),t+=s.middleName),eP.hasValue(s.lastName)&&(""!==t&&(t+=" "),t+=s.lastName),this.makeScriptActionWithValue(e,t,r.name,i)}if(r.address&&eP.hasValue(s.address1)){let t="";eP.hasValue(s.address1)&&(t=s.address1),eP.hasValue(s.address2)&&(""!==t&&(t+=", "),t+=s.address2),eP.hasValue(s.address3)&&(""!==t&&(t+=", "),t+=s.address3),this.makeScriptActionWithValue(e,t,r.address,i)}return e}static isExcludedType(e,t){return t.indexOf(e)>-1}static isSearchField(e){const t=[e.type,e.htmlName,e.htmlID,e.placeholder];for(let e=0;e-1;if(r=r.toLowerCase().replace(/-/g,""),e===r||s&&e.indexOf(r)>-1)return!0}return!1}makeScriptAction(e,t,i,n,r,s){s=s||r,this.makeScriptActionWithValue(e,t[r],i[s],n)}makeScriptActionWithValue(e,t,i,n){let r=!1;if(eP.hasValue(t)&&i)if("select-one"===i.type&&i.selectInfo&&i.selectInfo.options)for(let e=0;e1&&(t=n[1]);break}if(r)break}else r=!0;r&&(n[i.opid]=i,eP.fillByOpid(e,i,t))}static valueIsLikePassword(e){if(null==e)return!1;const t=e.toLowerCase().replace(/[\s_-]/g,"");return!(t.indexOf("password")<0)&&!Yb.PasswordFieldExcludeList.some((e=>t.indexOf(e)>-1))}static fieldHasDisqualifyingAttributeValue(e){const t=[e.htmlID,e.htmlName,e.placeholder];let i=!1;for(let e=0;er.indexOf(e)>-1))),i)break}return i}static loadPasswordFields(e,t,i,n,r){const s=[];return e.fields.forEach((e=>{const o="password"===e.type;if(!o&&eP.isExcludedFieldType(e,Yb.ExcludedAutofillLoginTypes))return;if(eP.fieldHasDisqualifyingAttributeValue(e))return;e.disabled||!i&&e.readonly||!o&&!(()=>{if("text"!==e.type)return!1;const t=[e.htmlID,e.htmlName,e.placeholder];for(let e=0;e=t.elementNumber)break;if(!a.disabled&&(n||!a.readonly)&&(r||a.form===t.form)&&(i||a.viewable)&&("text"===a.type||"email"===a.type||"tel"===a.type)&&(s=a,this.findMatchingFieldIndex(a,Yb.UsernameFieldNames)>-1))break}}return s}findTotpField(e,t,i,n,r){let s=null;for(let o=0;o-1||"one-time-code"===a.autoCompleteType))break}return s}findMatchingFieldIndex(e,t){for(let i=0;i-1){if(this.fieldPropertyIsPrefixMatch(e,"htmlID",t[i],"id"))return i;if(this.fieldPropertyIsPrefixMatch(e,"htmlName",t[i],"name"))return i;if(this.fieldPropertyIsPrefixMatch(e,"label-left",t[i],"label"))return i;if(this.fieldPropertyIsPrefixMatch(e,"label-right",t[i],"label"))return i;if(this.fieldPropertyIsPrefixMatch(e,"label-tag",t[i],"label"))return i;if(this.fieldPropertyIsPrefixMatch(e,"label-aria",t[i],"label"))return i;if(this.fieldPropertyIsPrefixMatch(e,"placeholder",t[i],"placeholder"))return i}if(this.fieldPropertyIsMatch(e,"htmlID",t[i]))return i;if(this.fieldPropertyIsMatch(e,"htmlName",t[i]))return i;if(this.fieldPropertyIsMatch(e,"label-left",t[i]))return i;if(this.fieldPropertyIsMatch(e,"label-right",t[i]))return i;if(this.fieldPropertyIsMatch(e,"label-tag",t[i]))return i;if(this.fieldPropertyIsMatch(e,"label-aria",t[i]))return i;if(this.fieldPropertyIsMatch(e,"placeholder",t[i]))return i}return-1}fieldPropertyIsPrefixMatch(e,t,i,n,r="="){if(0===i.indexOf(n+r)){const n=i.indexOf(r),s=i.substring(n+1);return null!=s&&this.fieldPropertyIsMatch(e,t,s)}return!1}fieldPropertyIsMatch(e,t,i){let n=e[t];if(!eP.hasValue(n))return!1;if(n=n.trim().replace(/(?:\r\n|\r|\n)/g,""),i.startsWith("regex="))try{const e=i.split("=",2);if(2===e.length){return new RegExp(e[1],"i").test(n)}}catch(e){this.logService.error(e)}else if(i.startsWith("csv=")){const e=i.split("=",2);if(2===e.length){const t=e[1].split(",");for(let e=0;e-1)return!0;return!1}static hasValue(e){return Boolean(e&&""!==e)}static setFillScriptForFocus(e,t){let i=null,n=null;for(const t in e)e.hasOwnProperty(t)&&e[t].viewable&&(i=e[t],"password"===e[t].type&&(n=e[t]));return n?t.script.push(["focus_by_opid",n.opid]):i&&t.script.push(["focus_by_opid",i.opid]),t}static fillByOpid(e,t,i){t.maxLength&&i&&i.length>t.maxLength&&(i=i.substr(0,i.length)),"span"!==t.tagName&&(e.script.push(["click_on_opid",t.opid]),e.script.push(["focus_by_opid",t.opid])),e.script.push(["fill_by_opid",t.opid,i])}static forCustomFieldsOnly(e){return"span"===e.tagName}isDebouncingPasswordRepromptPopout(){return!!this.currentlyOpeningPasswordRepromptPopout||(this.currentlyOpeningPasswordRepromptPopout=!0,clearTimeout(this.openPasswordRepromptPopoutDebounce),this.openPasswordRepromptPopoutDebounce=setTimeout((()=>{this.currentlyOpeningPasswordRepromptPopout=!1}),100),!1)}injectAutofillScriptsInAllTabs(){var e;return Zb(this,void 0,void 0,(function*(){const t=yield xg.tabsQuery({});for(let i=0;iiP(this,void 0,void 0,(function*(){return new tP(yield Ob(e,t),yield vS(e,t),yield XS(e,t),yield Hb(e,t),yield jb(e,t),yield cm(e,t),yield eb(e,t),yield Vb(e,t),yield Ab(e,t))}))))}var rP=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const sP="clearClipboard";class oP{static run(){return rP(this,void 0,void 0,(function*(){const e=yield xg.getActiveTabs();e&&0!==e.length&&xg.sendTabsMessage(e[0].id,{command:"clearClipboard"})}))}}var aP=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const lP=(e,t)=>aP(void 0,void 0,void 0,(function*(){if(null==e.id)throw new Error("Cannot copy text to clipboard with a tab that does not have an id.");xg.sendTabsMessage(e.id,{command:"copyText",text:t})}));var cP=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const dP=[sP],uP={clearClipboard:null};function hP(e,t){return cP(this,void 0,void 0,(function*(){xg.isManifestVersion(3)?yield chrome.storage.session.set({[e]:t}):uP[e]=t}))}var pP=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class yP{constructor(e,t){this.passwordGenerationService=e,this.autofillSettingsService=t}getClearClipboard(){return pP(this,void 0,void 0,(function*(){return yield(0,r.z)(this.autofillSettingsService.clearClipboardDelay$)}))}generatePasswordToClipboard(e){return pP(this,void 0,void 0,(function*(){const[t]=yield this.passwordGenerationService.getOptions(),i=yield this.passwordGenerationService.generatePassword(t);lP(e,i);const n=yield this.getClearClipboard();null!=n&&(yield function(e,t){return cP(this,void 0,void 0,(function*(){if(!t||0===t)return void(yield this.clearAlarmTime(e));const i=Date.now()+t;yield hP(e,i)}))}(sP,1e3*n))}))}}var vP=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class fP{constructor(e){this.autofillService=e}doAutofillTabCommand(e){return vP(this,void 0,void 0,(function*(){if(!e.id)throw new Error("Tab does not have an id, cannot complete autofill.");const t=yield this.collectPageDetails(e.id);yield this.autofillService.doAutoFillOnTab([{frameId:0,tab:e,details:t}],e,!0)}))}doAutofillTabWithCipherCommand(e,t){return vP(this,void 0,void 0,(function*(){if(!e.id)throw new Error("Tab does not have an id, cannot complete autofill.");const i=yield this.collectPageDetails(e.id);yield this.autofillService.doAutoFill({tab:e,cipher:t,pageDetails:[{frameId:0,tab:e,details:i}],skipLastUsed:!1,skipUsernameOnlyFill:!1,onlyEmptyFields:!1,onlyVisibleFields:!1,fillNewPassword:!0,allowTotpAutofill:!0})}))}collectPageDetails(e){return vP(this,void 0,void 0,(function*(){return new Promise(((t,i)=>{chrome.tabs.sendMessage(e,{command:"collectPageDetailsImmediately"},(e=>{chrome.runtime.lastError?i(chrome.runtime.lastError):t(e)}))}))}))}}var gP=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const mP=(...e)=>Promise.reject("This action is not implemented inside of a service worker context.");class wP{constructor(e,t,i,n,r,s,o,a,l){this.copyToClipboard=e,this.generatePasswordToClipboard=t,this.autofillAction=i,this.authService=n,this.cipherService=r,this.stateService=s,this.totpService=o,this.eventCollectionService=a,this.userVerificationService=l}static mv3Create(e){return gP(this,void 0,void 0,(function*(){const t=new Ns(Rs,tS),i={apiServiceOptions:{logoutCallback:mP},cryptoFunctionServiceOptions:{win:self},encryptServiceOptions:{logMacFailures:!1},i18nServiceOptions:{systemLanguage:chrome.i18n.getUILanguage()},keyConnectorServiceOptions:{logoutCallback:mP},logServiceOptions:{isDev:!1},platformUtilsServiceOptions:{biometricCallback:mP,clipboardWriteCallback:mP,win:self},stateServiceOptions:{stateFactory:t},autofillSettingsServiceOptions:{stateFactory:XS}},n=new yP(yield Wb(e,i),yield XS(e,i)),r=new fP(yield nP(e,i));return new wP((e=>lP(e.tab,e.text)),(e=>n.generatePasswordToClipboard(e)),((e,t)=>r.doAutofillTabWithCipherCommand(e,t)),yield qS(e,i),yield Ob(e,i),yield vS(e,i),yield Hb(e,i),yield jb(e,i),yield Vb(e,i))}))}static onClickedListener(e,t,i={}){return gP(this,void 0,void 0,(function*(){const n=yield wP.mv3Create(i);yield n.run(e,t)}))}static messageListener(e,t,i){return gP(this,void 0,void 0,(function*(){if("unlockCompleted"!==e.command||"contextmenus.background"!==e.data.target)return;const t=yield wP.mv3Create(i);yield t.run(e.data.commandToRetry.message.contextMenuOnClickData,e.data.commandToRetry.sender.tab)}))}run(e,t){return gP(this,void 0,void 0,(function*(){if(t)switch(e.menuItemId){case Vr:yield this.generatePasswordToClipboard(t);break;case Rr:this.copyToClipboard({text:yield this.getIdentifier(t,e),tab:t});break;default:yield this.cipherAction(e,t)}}))}cipherAction(e,t){return gP(this,void 0,void 0,(function*(){if(!t)return;if((yield this.authService.getAuthStatus())e===i))}if(n||r)switch(this.stateService.setLastActive((new Date).getTime()),e.parentMenuItemId){case Tr:case Nr:case Ur:{const e=this.getCipherCreationType(i);if(e){yield jg(t,{cipherType:e});break}(yield this.isPasswordRepromptRequired(n))?yield _g(t,{cipherId:n.id,action:Tr}):yield this.autofillAction(t,n);break}case Fr:if(i===zr){yield jg(t,{cipherType:Pe.Login});break}this.copyToClipboard({text:n.login.username,tab:t});break;case Er:if(i===zr){yield jg(t,{cipherType:Pe.Login});break}(yield this.isPasswordRepromptRequired(n))?yield _g(t,{cipherId:n.id,action:Er}):(this.copyToClipboard({text:n.login.password,tab:t}),this.eventCollectionService.collect(ve.Cipher_ClientCopiedPassword,n.id));break;case Mr:if(i===zr){yield jg(t,{cipherType:Pe.Login});break}(yield this.isPasswordRepromptRequired(n))?yield _g(t,{cipherId:n.id,action:Mr}):this.copyToClipboard({text:yield this.totpService.getCode(n.login.totp),tab:t})}}))}isPasswordRepromptRequired(e){return gP(this,void 0,void 0,(function*(){return e.reprompt===be.Password&&(yield this.userVerificationService.hasMasterPasswordAndMasterKeyHash())}))}getCipherCreationType(e){return e===Lr?Pe.Identity:e===Kr?Pe.Card:e===zr?Pe.Login:null}getIdentifier(e,t){return gP(this,void 0,void 0,(function*(){return new Promise(((i,n)=>{xg.sendTabsMessage(e.id,{command:"getClickedElement"},{frameId:t.frameId},(e=>{chrome.runtime.lastError?n(chrome.runtime.lastError):i(e)}))}))}))}}var SP=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};var bP=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class PP{static windowsOnFocusChangedListener(e,t){return bP(this,void 0,void 0,(function*(){yield new PP(self).run({windowId:e,existingServices:t})}))}static tabsOnActivatedListener(e,t){return bP(this,void 0,void 0,(function*(){yield new PP(self).run({tabId:e.tabId,existingServices:t,windowId:e.windowId})}))}static tabsOnReplacedListener(e,t,i){return bP(this,void 0,void 0,(function*(){yield new PP(self).run({tabId:e,existingServices:i})}))}static tabsOnUpdatedListener(e,t,i,n){return bP(this,void 0,void 0,(function*(){yield new PP(self).run({tabId:e,existingServices:n,windowId:i.windowId})}))}static messageListener(e,t){return bP(this,void 0,void 0,(function*(){PP.listenedToCommands.includes(e.command)&&(yield new PP(self).run({existingServices:t}))}))}constructor(e){this.inited=!1,this.badgeAction=xg.getBrowserAction(),this.sidebarAction=xg.getSidebarAction(self),this.win=e}run(e){return bP(this,void 0,void 0,(function*(){yield this.initServices(null==e?void 0:e.existingServices);const t=yield this.authService.getAuthStatus();switch(yield this.setBadgeBackgroundColor(),t){case On.LoggedOut:yield this.setLoggedOut();break;case On.Locked:yield this.setLocked();break;case On.Unlocked:{const t=yield this.getTab(null==e?void 0:e.tabId,null==e?void 0:e.windowId);yield this.setUnlocked({tab:t,windowId:null==t?void 0:t.windowId});break}}}))}setLoggedOut(){return bP(this,void 0,void 0,(function*(){yield this.setBadgeIcon("_gray"),yield this.clearBadgeText()}))}setLocked(){return bP(this,void 0,void 0,(function*(){yield this.setBadgeIcon("_locked"),yield this.clearBadgeText()}))}clearBadgeText(){return bP(this,void 0,void 0,(function*(){const e=yield xg.getActiveTabs();null!=e&&e.forEach((e=>bP(this,void 0,void 0,(function*(){null!=e.id&&(yield this.setBadgeText("",e.id))}))))}))}setUnlocked(e){var t,i;return bP(this,void 0,void 0,(function*(){yield this.initServices(),yield this.setBadgeIcon("");if(!(yield(0,r.z)(this.badgeSettingsService.enableBadgeCounter$)))return;const n=yield this.cipherService.getAllDecryptedForUrl(null===(t=null==e?void 0:e.tab)||void 0===t?void 0:t.url);let s=0==n.length?"":n.length.toString();n.length>9&&(s="9+"),yield this.setBadgeText(s,null===(i=null==e?void 0:e.tab)||void 0===i?void 0:i.id)}))}setBadgeBackgroundColor(e="#294e5f"){var t;(null===(t=this.badgeAction)||void 0===t?void 0:t.setBadgeBackgroundColor)&&this.badgeAction.setBadgeBackgroundColor({color:e}),this.isOperaSidebar(this.sidebarAction)&&this.sidebarAction.setBadgeBackgroundColor({color:e})}setBadgeText(e,t){this.setActionText(e,t),this.setSideBarText(e,t)}setBadgeIcon(e,t){return bP(this,void 0,void 0,(function*(){const i={path:{19:"/images/icon19"+e+".png",38:"/images/icon38"+e+".png"}};t&&Ag.isFirefox()&&(i.windowId=t),yield this.setActionIcon(i),yield this.setSidebarActionIcon(i)}))}setActionText(e,t){var i;(null===(i=this.badgeAction)||void 0===i?void 0:i.setBadgeText)&&this.badgeAction.setBadgeText({text:e,tabId:t})}setSideBarText(e,t){if(this.isOperaSidebar(this.sidebarAction))this.sidebarAction.setBadgeText({text:e,tabId:t});else if(this.sidebarAction){const i="Bitwarden"+(p.isNullOrEmpty(e)?"":` [${e}]`);this.sidebarAction.setTitle({title:i,tabId:t})}}setActionIcon(e){var t;return bP(this,void 0,void 0,(function*(){(null===(t=this.badgeAction)||void 0===t?void 0:t.setIcon)&&(this.useSyncApiCalls?this.badgeAction.setIcon(e):yield new Promise((t=>this.badgeAction.setIcon(e,(()=>t())))))}))}setSidebarActionIcon(e){var t;return bP(this,void 0,void 0,(function*(){(null===(t=this.sidebarAction)||void 0===t?void 0:t.setIcon)&&(this.isOperaSidebar(this.sidebarAction)?yield new Promise((t=>this.sidebarAction.setIcon(e,(()=>t())))):yield this.sidebarAction.setIcon(e))}))}getTab(e,t){var i,n,r;return bP(this,void 0,void 0,(function*(){return null!==(r=null!==(n=null!==(i=yield xg.getTab(e))&&void 0!==i?i:t?yield xg.tabsQueryFirst({active:!0,windowId:t}):yield xg.tabsQueryFirst({active:!0,currentWindow:!0}))&&void 0!==n?n:yield xg.tabsQueryFirst({active:!0,lastFocusedWindow:!0}))&&void 0!==r?r:yield xg.tabsQueryFirst({active:!0})}))}get useSyncApiCalls(){return Ag.isFirefox()||Ag.isSafari(this.win)}initServices(e){return bP(this,void 0,void 0,(function*(){if(this.inited)return this;const t=e||{},i={cryptoFunctionServiceOptions:{win:self},encryptServiceOptions:{logMacFailures:!1},logServiceOptions:{isDev:!1},platformUtilsServiceOptions:{clipboardWriteCallback:(e,t)=>Promise.reject("not implemented"),biometricCallback:()=>Promise.reject("not implemented"),win:self},stateServiceOptions:{stateFactory:new Ns(Rs,tS)},apiServiceOptions:{logoutCallback:()=>Promise.reject("not implemented")},keyConnectorServiceOptions:{logoutCallback:()=>Promise.reject("not implemented")},i18nServiceOptions:{systemLanguage:xg.getUILanguage()}};return this.badgeSettingsService=yield function(e,t){return lm(e,"badgeSettingsService",t,(()=>SP(this,void 0,void 0,(function*(){return new ss(yield Cw(e,t))}))))}(t,i),this.authService=yield qS(t,i),this.cipherService=yield Ob(t,i),self.bitwardenContainerService||new Ws(t.cryptoService,t.encryptService).attachToGlobal(self),this.inited=!0,this}))}isOperaSidebar(e){return null!=e&&null!=e.setBadgeText}}PP.listenedToCommands=["updateBadge","loggedIn","unlocked","syncCompleted","bgUpdateContextMenu","editedCipher","addedCipher","deletedCipher"];var kP=function(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},OP=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let CP=class extends wb{constructor(e,t,i,n,r,s,o=!1){super(e,t,i,n,r,s,o)}};kP([lS({initializer:fb.fromJSON}),OP("design:type",yd.t)],CP.prototype,"_serverConfig",void 0),CP=kP([oS,OP("design:paramtypes",[class{},class{},class{},Zm,xw,Vt,Object])],CP);class AP{send(e,t={}){const i=Object.assign({},{command:e},t);window.bitwardenPopupMainMessageListener(i)}}var DP=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class xP extends St{constructor(e){super(),null!=e&&(this.size=e.size,this.buildDomainModel(this,e,{id:null,sizeName:null,fileName:null},["id","sizeName"]))}decrypt(e){return DP(this,void 0,void 0,(function*(){return yield this.decryptObj(new Iw(this),{fileName:null},null,e)}))}static fromJSON(e){return null==e?null:Object.assign(new xP,e,{fileName:z.fromJSON(e.fileName)})}}class IP extends St{constructor(e){super(),null!=e&&(this.hidden=e.hidden,this.buildDomainModel(this,e,{text:null},[]))}decrypt(e){return this.decryptObj(new Uw(this),{text:null},null,e)}static fromJSON(e){return null==e?null:Object.assign(new IP,e,{text:z.fromJSON(e.text)})}}var UP=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class TP extends St{constructor(e){if(super(),null!=e)switch(this.buildDomainModel(this,e,{id:null,accessId:null,name:null,notes:null,key:null},["id","accessId"]),this.type=e.type,this.maxAccessCount=e.maxAccessCount,this.accessCount=e.accessCount,this.password=e.password,this.disabled=e.disabled,this.revisionDate=null!=e.revisionDate?new Date(e.revisionDate):null,this.deletionDate=null!=e.deletionDate?new Date(e.deletionDate):null,this.expirationDate=null!=e.expirationDate?new Date(e.expirationDate):null,this.hideEmail=e.hideEmail,this.type){case ap.Text:this.text=new IP(e.text);break;case ap.File:this.file=new xP(e.file)}}decrypt(){return UP(this,void 0,void 0,(function*(){const e=new Tw(this),t=p.getContainerService().getCryptoService();try{e.key=yield t.decryptToBytes(this.key,null),e.cryptoKey=yield t.makeSendKey(e.key)}catch(e){}switch(yield this.decryptObj(e,{name:null,notes:null},null,e.cryptoKey),this.type){case ap.File:e.file=yield this.file.decrypt(e.cryptoKey);break;case ap.Text:e.text=yield this.text.decrypt(e.cryptoKey)}return e}))}static fromJSON(e){if(null==e)return null;const t=null==e.revisionDate?null:new Date(e.revisionDate),i=null==e.expirationDate?null:new Date(e.expirationDate),n=null==e.deletionDate?null:new Date(e.deletionDate);return Object.assign(new TP,e,{key:z.fromJSON(e.key),name:z.fromJSON(e.name),notes:z.fromJSON(e.notes),text:IP.fromJSON(e.text),file:xP.fromJSON(e.file),revisionDate:t,expirationDate:i,deletionDate:n})}}class NP extends pp{constructor(e){super(e),this.id=e.id}}var RP=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class EP{constructor(e,t,i,n){this.cryptoService=e,this.i18nService=t,this.keyGenerationService=i,this.stateService=n,this.sendKeySalt="bitwarden-send",this.sendKeyPurpose="send",this._sends=new te.X([]),this._sendViews=new te.X([]),this.sends$=this._sends.asObservable(),this.sendViews$=this._sendViews.asObservable(),this.stateService.activeAccountUnlocked$.pipe((0,fw.b)((e=>RP(this,void 0,void 0,(function*(){if(null==p.global.bitwardenContainerService)return;if(!e)return this._sends.next([]),void this._sendViews.next([]);const t=yield this.stateService.getEncryptedSends();yield this.updateObservables(t)}))))).subscribe()}clearCache(){return RP(this,void 0,void 0,(function*(){yield this._sendViews.next([])}))}encrypt(e,t,i,n){return RP(this,void 0,void 0,(function*(){let r=null;const s=new TP;if(s.id=e.id,s.type=e.type,s.disabled=e.disabled,s.hideEmail=e.hideEmail,s.maxAccessCount=e.maxAccessCount,null==e.key){const t=yield this.keyGenerationService.createKeyWithPurpose(128,this.sendKeyPurpose,this.sendKeySalt);e.key=t.material,e.cryptoKey=t.derivedKey}if(null!=i){const t=yield this.keyGenerationService.deriveKeyFromPassword(i,e.key,b.PBKDF2_SHA256,{iterations:1e5});s.password=t.keyB64}if(s.key=yield this.cryptoService.encrypt(e.key,n),s.name=yield this.cryptoService.encrypt(e.name,e.cryptoKey),s.notes=yield this.cryptoService.encrypt(e.notes,e.cryptoKey),s.type===ap.Text)s.text=new IP,s.text.text=yield this.cryptoService.encrypt(e.text.text,e.cryptoKey),s.text.hidden=e.text.hidden;else if(s.type===ap.File&&(s.file=new xP,null!=t))if(t instanceof ArrayBuffer){const[i,n]=yield this.encryptFileData(e.file.fileName,t,e.cryptoKey);s.file.fileName=i,r=n}else r=yield this.parseFile(s,t,e.cryptoKey);return[s,r]}))}get(e){return this._sends.getValue().find((t=>t.id===e))}get$(e){return this.sends$.pipe((0,j.x)(((t,i)=>{const n=t.find((t=>t.id===e)),r=i.find((t=>t.id===e));if(!n||!r)return!1;return Object.keys(r).every((e=>{if(null!=n[e]&&null===r[e]||null===n[e]&&null!=r[e])return!1;switch(e){case"name":case"notes":case"key":return null===n[e]&&null===r[e]||n[e].encryptedString===r[e].encryptedString;case"text":return null==n[e].text&&null==r[e].text||!(null!=n[e].text&&null==r[e].text||null==n[e].text&&null!=r[e].text)&&n[e].text.encryptedString===r[e].text.encryptedString;case"file":return!0;case"revisionDate":case"expirationDate":case"deletionDate":return null===n[e]&&null===r[e]||n[e].getTime()===r[e].getTime();default:return n[e]===r[e]}}))})),(0,q.U)((t=>t.find((t=>t.id===e)))))}getFromState(e){return RP(this,void 0,void 0,(function*(){const t=yield this.stateService.getEncryptedSends();return null!=t&&t.hasOwnProperty(e)?new TP(t[e]):null}))}getAll(){return RP(this,void 0,void 0,(function*(){const e=yield this.stateService.getEncryptedSends(),t=[];for(const i in e)e.hasOwnProperty(i)&&t.push(new TP(e[i]));return t}))}getAllDecryptedFromState(){return RP(this,void 0,void 0,(function*(){let e=yield this.stateService.getDecryptedSends();if(null!=e)return e;e=[];if(!(yield this.cryptoService.hasUserKey()))throw new Error("No user key found.");const t=[];return(yield this.getAll()).forEach((i=>{t.push(i.decrypt().then((t=>e.push(t))))})),yield Promise.all(t),e.sort(p.getSortFunction(this.i18nService,"name")),yield this.stateService.setDecryptedSends(e),e}))}upsert(e){return RP(this,void 0,void 0,(function*(){let t=yield this.stateService.getEncryptedSends();if(null==t&&(t={}),e instanceof hp){const i=e;t[i.id]=i}else e.forEach((e=>{t[e.id]=e}));yield this.replace(t)}))}clear(e){return RP(this,void 0,void 0,(function*(){null!=e&&e!=(yield this.stateService.getUserId())||(this._sends.next([]),this._sendViews.next([])),yield this.stateService.setDecryptedSends(null,{userId:e}),yield this.stateService.setEncryptedSends(null,{userId:e})}))}delete(e){return RP(this,void 0,void 0,(function*(){const t=yield this.stateService.getEncryptedSends();if(null!=t){if("string"==typeof e){if(null==t[e])return;delete t[e]}else e.forEach((e=>{delete t[e]}));yield this.replace(t)}}))}replace(e){return RP(this,void 0,void 0,(function*(){yield this.updateObservables(e),yield this.stateService.setEncryptedSends(e)}))}getRotatedKeys(e){return RP(this,void 0,void 0,(function*(){if(null==e)throw new Error("New user key is required for rotation.");return yield Promise.all(this._sends.value.map((t=>RP(this,void 0,void 0,(function*(){const i=yield this.cryptoService.decryptToBytes(t.key);return t.key=yield this.cryptoService.encrypt(i,e),new NP(t)})))))}))}parseFile(e,t,i){return new Promise(((n,r)=>{const s=new FileReader;s.readAsArrayBuffer(t),s.onload=s=>RP(this,void 0,void 0,(function*(){try{const[r,o]=yield this.encryptFileData(t.name,s.target.result,i);e.file.fileName=r,n(o)}catch(e){r(e)}})),s.onerror=()=>{r("Error reading file.")}}))}encryptFileData(e,t,i){return RP(this,void 0,void 0,(function*(){return[yield this.cryptoService.encrypt(e,i),yield this.cryptoService.encryptToBytes(new Uint8Array(t),i)]}))}updateObservables(e){return RP(this,void 0,void 0,(function*(){const t=Object.values(e||{}).map((e=>new TP(e)));this._sends.next(t),(yield this.cryptoService.hasUserKey())&&this._sendViews.next(yield this.decryptSends(t))}))}decryptSends(e){return RP(this,void 0,void 0,(function*(){const t=e.map((e=>e.decrypt())),i=yield Promise.all(t);return i.sort(p.getSortFunction(this.i18nService,"name")),i}))}}var FP=function(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o},MP=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let KP=class extends EP{};FP([lS({initializer:TP.fromJSON,initializeAs:"array"}),MP("design:type",te.X)],KP.prototype,"_sends",void 0),FP([lS({initializer:Tw.fromJSON,initializeAs:"array"}),MP("design:type",te.X)],KP.prototype,"_sendViews",void 0),KP=FP([oS],KP);var LP=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class zP{constructor(e,t,i,n,r,s,o,a,l,c,d,u=null,h=null){this.cipherService=e,this.folderService=t,this.collectionService=i,this.cryptoService=n,this.platformUtilsService=r,this.messagingService=s,this.searchService=o,this.stateService=a,this.authService=l,this.vaultTimeoutSettingsService=c,this.stateEventRunnerService=d,this.lockedCallback=u,this.loggedOutCallback=h,this.inited=!1}init(e){return LP(this,void 0,void 0,(function*(){this.inited||(yield this.migrateKeyForNeverLockIfNeeded(),this.inited=!0,e&&this.startCheck())}))}startCheck(){this.checkVaultTimeout(),setInterval((()=>this.checkVaultTimeout()),1e4)}checkVaultTimeout(){return LP(this,void 0,void 0,(function*(){const e=yield this.platformUtilsService.isViewOpen(),t=yield(0,r.z)(this.stateService.activeAccount$.pipe((0,Zc.V)(500))),i=yield(0,r.z)(this.stateService.accounts$);for(const n in i)null!=n&&(yield this.shouldLock(n,t,e))&&(yield this.executeTimeoutAction(n))}))}lock(e){return LP(this,void 0,void 0,(function*(){if(!(yield this.stateService.getIsAuthenticated({userId:e})))return;(yield(0,r.z)(this.vaultTimeoutSettingsService.availableVaultTimeoutActions$(e))).includes(ar.Lock)||(yield this.logOut(e));const t=yield this.stateService.getUserId();null!=e&&e!==t||(this.searchService.clearIndex(),yield this.folderService.clearCache(),yield this.collectionService.clearActiveUserCache()),yield this.stateService.setEverBeenUnlocked(!0,{userId:e}),yield this.stateService.setUserKeyAutoUnlock(null,{userId:e}),yield this.stateService.setCryptoMasterKeyAuto(null,{userId:e}),yield this.cryptoService.clearUserKey(!1,e),yield this.cryptoService.clearMasterKey(e),yield this.cryptoService.clearOrgKeys(!0,e),yield this.cryptoService.clearKeyPair(!0,e),yield this.cipherService.clearCache(e),yield this.stateEventRunnerService.handleEvent("lock",null!=e?e:t),this.messagingService.send("locked",{userId:e}),null!=this.lockedCallback&&(yield this.lockedCallback(e))}))}logOut(e){return LP(this,void 0,void 0,(function*(){null!=this.loggedOutCallback&&(yield this.loggedOutCallback(!1,e))}))}shouldLock(e,t,i){return LP(this,void 0,void 0,(function*(){if(i&&e===t)return!1;const n=yield this.authService.getAuthStatus(e);if(n===On.Locked||n===On.LoggedOut)return!1;const r=yield this.vaultTimeoutSettingsService.getVaultTimeout(e);if(null==r||r<0)return!1;const s=yield this.stateService.getLastActive({userId:e});if(null==s)return!1;const o=60*r;return((new Date).getTime()-s)/1e3>=o}))}executeTimeoutAction(e){return LP(this,void 0,void 0,(function*(){(yield(0,r.z)(this.vaultTimeoutSettingsService.vaultTimeoutAction$(e)))===ar.LogOut?yield this.logOut(e):yield this.lock(e)}))}migrateKeyForNeverLockIfNeeded(){return LP(this,void 0,void 0,(function*(){if(this.platformUtilsService.getClientType()==Z.Web)return;const e=yield(0,r.z)(this.stateService.accounts$);for(const t in e)null!=t&&(yield this.cryptoService.migrateAutoKeyIfNeeded(t),(yield this.cryptoService.isLegacyUser(null,t))&&(yield this.logOut(t)))}))}}var VP,BP=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class _P extends zP{startCheck(){this.checkVaultTimeout(),this.platformUtilsService.isSafari()?this.checkSafari():setInterval((()=>this.checkVaultTimeout()),1e4)}checkSafari(){return BP(this,void 0,void 0,(function*(){for(;;)try{yield bg.sendMessageToApp("sleep"),this.checkVaultTimeout()}catch(e){console.log("Exception Safari VaultTimeout",e)}}))}}!function(e){e.BrowserFilelessImport="browser-fileless-import",e.ItemShare="item-share",e.FlexibleCollectionsV1="flexible-collections-v-1",e.BulkCollectionAccess="bulk-collection-access",e.VaultOnboarding="vault-onboarding",e.GeneratorToolsModernization="generator-tools-modernization",e.KeyRotationImprovements="key-rotation-improvements",e.FlexibleCollectionsMigration="flexible-collections-migration",e.ShowPaymentMethodWarningBanners="show-payment-method-warning-banners",e.UnassignedItemsBanner="unassigned-items-banner"}(VP||(VP={}));const jP={LpSuppressImportDownload:{mv2:{file:"content/lp-suppress-import-download-script-append-mv2.js"},mv3:{file:"content/lp-suppress-import-download.js",scriptingApiDetails:{world:"MAIN"}}}},$P="LP",WP="fileless-importer-notification-bar",qP="lp-fileless-importer";var HP=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class GP{constructor(e,t,i,n,r,s){this.configService=e,this.authService=t,this.policyService=i,this.notificationBackground=n,this.importService=r,this.syncService=s,this.importNotificationsPortMessageHandlers={startFilelessImport:({message:e})=>this.startFilelessImport(e.importType),cancelFilelessImport:({message:e,port:t})=>this.cancelFilelessImport(e.importType,t.sender)},this.lpImporterPortMessageHandlers={displayLpImportNotification:({port:e})=>this.displayFilelessImportNotification(e.sender.tab,$P),startLpImport:({message:e})=>this.triggerLpImport(e.data)},this.handlePortOnConnect=e=>HP(this,void 0,void 0,(function*(){if(!GP.filelessImporterPortNames.has(e.name))return;const t=yield this.configService.getFeatureFlag(VP.BrowserFilelessImport),i=yield this.authService.getAuthStatus(),n=yield this.removeIndividualVault(),r=t&&i===On.Unlocked&&!n;if(e.postMessage({command:"verifyFeatureFlag",filelessImportEnabled:r}),r)switch(e.onMessage.addListener(this.handleImporterPortMessage),e.onDisconnect.addListener(this.handleImporterPortDisconnect),e.name){case qP:this.lpImporterPort=e,yield this.injectScriptConfig(e.sender,3===xg.manifestVersion?jP.LpSuppressImportDownload.mv3:jP.LpSuppressImportDownload.mv2);break;case WP:this.importNotificationsPort=e}})),this.handleImporterPortMessage=(e,t)=>{let i;switch(t.name){case qP:i=this.lpImporterPortMessageHandlers[e.command];break;case WP:i=this.importNotificationsPortMessageHandlers[e.command]}i&&i({message:e,port:t})},this.handleImporterPortDisconnect=e=>{switch(e.name){case qP:this.lpImporterPort=null;break;case WP:this.importNotificationsPort=null}}}init(){this.setupPortMessageListeners()}startFilelessImport(e){var t;e===$P&&(null===(t=this.lpImporterPort)||void 0===t||t.postMessage({command:"startLpFilelessImport"}))}cancelFilelessImport(e,t){return HP(this,void 0,void 0,(function*(){e===$P&&this.triggerLpImporterCsvDownload(),yield xg.tabSendMessage(t.tab,{command:"closeNotificationBar"})}))}displayFilelessImportNotification(e,t){return HP(this,void 0,void 0,(function*(){yield this.notificationBackground.requestFilelessImport(e,t)}))}injectScriptConfig(e,t){return HP(this,void 0,void 0,(function*(){yield xg.executeScriptInTab(e.tab.id,{file:t.file,runAt:"document_start"},t.scriptingApiDetails)}))}triggerLpImporterCsvDownload(){var e,t;null===(e=this.lpImporterPort)||void 0===e||e.postMessage({command:"triggerCsvDownload"}),null===(t=this.lpImporterPort)||void 0===t||t.disconnect()}triggerLpImport(e){var t,i;return HP(this,void 0,void 0,(function*(){if(!e)return;const n=this.importService.getImporter("lastpasscsv",(()=>HP(this,void 0,void 0,(function*(){return""}))),null);try{(yield this.importService.import(n,e,null,null,!1)).success&&(null===(t=this.importNotificationsPort)||void 0===t||t.postMessage({command:"filelessImportCompleted"}),yield this.syncService.fullSync(!0))}catch(e){null===(i=this.importNotificationsPort)||void 0===i||i.postMessage({command:"filelessImportFailed",importErrorMessage:Object.values(e).length?e:chrome.i18n.getMessage("importNetworkError")})}}))}removeIndividualVault(){return HP(this,void 0,void 0,(function*(){return yield(0,r.z)(this.policyService.policyAppliesToActiveUser$(qi.PersonalOwnership))}))}setupPortMessageListeners(){chrome.runtime.onConnect.addListener(this.handlePortOnConnect)}}GP.filelessImporterPortNames=new Set([qP,WP]);const JP=GP;var YP=i(19863),QP=i(74094),XP=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class ZP extends Error{constructor(){super("Fido2UserInterfaceSession was closed")}}class ek{constructor(e){this.authService=e}newSession(e,t,i){return XP(this,void 0,void 0,(function*(){return yield tk.create(this.authService,e,t,i)}))}}class tk{static create(e,t,i,n){return XP(this,void 0,void 0,(function*(){return new tk(e,t,i,n)}))}static sendMessage(e){xg.sendMessage("BrowserFido2UserInterfaceServiceMessage",e)}static abortPopout(e,t=!1){this.sendMessage({sessionId:e,type:"AbortResponse",fallbackRequested:t})}static confirmNewCredentialResponse(e,t,i){this.sendMessage({sessionId:e,type:"ConfirmNewCredentialResponse",cipherId:t,userVerified:i})}constructor(e,t,i,n=new AbortController,r=p.newGuid()){this.authService=e,this.fallbackSupported=t,this.tab=i,this.abortController=n,this.sessionId=r,this.closed=!1,this.messages$=xg.messageListener$().pipe((0,_.h)((e=>e.sessionId===this.sessionId))),this.connected$=new te.X(!1),this.destroy$=new Cn.x,this.messages$.pipe((0,_.h)((e=>"ConnectResponse"===e.type)),(0,wn.q)(1),(0,Xs.R)(this.destroy$)).subscribe((()=>{this.connected$.next(!0)})),(0,Qs.R)(n.signal,"abort").pipe((0,Xs.R)(this.destroy$)).subscribe((()=>{this.close(),tk.sendMessage({type:"AbortRequest",sessionId:this.sessionId})})),this.messages$.pipe((0,_.h)((e=>"AbortResponse"===e.type)),(0,wn.q)(1),(0,Xs.R)(this.destroy$)).subscribe((e=>{"AbortResponse"===e.type&&(this.close(),this.abort(e.fallbackRequested))})),this.windowClosed$=(0,YP.R)((e=>chrome.windows.onRemoved.addListener(e)),(e=>chrome.windows.onRemoved.removeListener(e))),tk.sendMessage({type:"NewSessionCreatedRequest",sessionId:r})}pickCredential({cipherIds:e,userVerification:t}){return XP(this,void 0,void 0,(function*(){const i={type:"PickCredentialRequest",cipherIds:e,sessionId:this.sessionId,userVerification:t,fallbackSupported:this.fallbackSupported};yield this.send(i);const n=yield this.receive("PickCredentialResponse");return{cipherId:n.cipherId,userVerified:n.userVerified}}))}confirmNewCredential({credentialName:e,userName:t,userVerification:i,rpId:n}){return XP(this,void 0,void 0,(function*(){const r={type:"ConfirmNewCredentialRequest",sessionId:this.sessionId,credentialName:e,userName:t,userVerification:i,fallbackSupported:this.fallbackSupported,rpId:n};yield this.send(r);const s=yield this.receive("ConfirmNewCredentialResponse");return{cipherId:s.cipherId,userVerified:s.userVerified}}))}informExcludedCredential(e){return XP(this,void 0,void 0,(function*(){const t={type:"InformExcludedCredentialRequest",sessionId:this.sessionId,existingCipherIds:e,fallbackSupported:this.fallbackSupported};yield this.send(t),yield this.receive("AbortResponse")}))}ensureUnlockedVault(){return XP(this,void 0,void 0,(function*(){(yield this.authService.getAuthStatus())!==On.Unlocked&&(yield this.connect())}))}informCredentialNotFound(){return XP(this,void 0,void 0,(function*(){const e={type:"InformCredentialNotFoundRequest",sessionId:this.sessionId,fallbackSupported:this.fallbackSupported};yield this.send(e),yield this.receive("AbortResponse")}))}close(){return XP(this,void 0,void 0,(function*(){yield function(e){return zg(this,void 0,void 0,(function*(){yield Ng.closeSingleActionPopout(`${Vg.fido2Popout}_${e}`)}))}(this.sessionId),this.closed=!0,this.destroy$.next(),this.destroy$.complete()}))}abort(e=!1){return XP(this,void 0,void 0,(function*(){this.abortController.abort(e?Py:void 0)}))}send(e){return XP(this,void 0,void 0,(function*(){this.connected$.value||(yield this.connect()),tk.sendMessage(e)}))}receive(e){return XP(this,void 0,void 0,(function*(){try{return yield(0,r.z)(this.messages$.pipe((0,_.h)((t=>t.sessionId===this.sessionId&&t.type===e)),(0,Xs.R)(this.destroy$)))}catch(e){if(e instanceof QP.K)throw new ZP;throw e}}))}connect(){return XP(this,void 0,void 0,(function*(){if(this.closed)throw new Error("Cannot re-open closed session");const e=(0,r.z)((0,hd.T)(this.connected$.pipe((0,_.h)((e=>!0===e))),(0,Qs.R)(this.abortController.signal,"abort").pipe((0,c.w)((()=>(0,ld._)((()=>new ZP))))))),t=yield function(e,t){return zg(this,void 0,void 0,(function*(){const{sessionId:i,fallbackSupported:n}=t,r=`popup/index.html#/fido2?sessionId=${i}&fallbackSupported=${n}&senderTabId=${e.id}&senderUrl=${encodeURIComponent(e.url)}`;return(yield Ng.openPopout(r,{singleActionKey:`${Vg.fido2Popout}_${i}`,senderWindowId:e.windowId,forceCloseExistingWindows:!0,windowOptions:{height:570}})).id}))}(this.tab,{sessionId:this.sessionId,fallbackSupported:this.fallbackSupported});this.windowClosed$.pipe((0,_.h)((e=>t===e)),(0,Xs.R)(this.destroy$)).subscribe((()=>{this.close(),this.abort(!0)})),yield e}))}}var ik=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class nk{init(){return ik(this,void 0,void 0,(function*(){(yield xg.tabsQuery({})).forEach((e=>{var t;(null===(t=e.url)||void 0===t?void 0:t.startsWith("https"))&&this.injectFido2ContentScripts({tab:e})})),xg.addListener(chrome.runtime.onConnect,(e=>{"fido2ContentScriptReady"===e.name&&e.postMessage({command:"fido2ContentScriptInit"})}))}))}injectFido2ContentScripts(e){return ik(this,void 0,void 0,(function*(){yield xg.executeScriptInTab(e.tab.id,{file:"content/fido2/content-script.js",frameId:e.frameId,runAt:"document_start"})}))}}class rk{constructor(e){this.selectedCollection=!1,this.selectedFolder=!1,this.myVaultOnly=!1,this.refreshCollectionsAndFolders=!1,Object.assign(this,e)}resetFilter(){this.cipherType=null,this.status=null,this.selectedCollection=!1,this.selectedCollectionId=null,this.selectedFolder=!1,this.selectedFolderId=null}resetOrganization(){this.myVaultOnly=!1,this.selectedOrganizationId=null,this.resetFilter()}buildFilter(){return e=>{let t=!0;return"favorites"===this.status&&t&&(t=e.favorite),"trash"===this.status&&t&&(t=e.isDeleted),null!=this.cipherType&&t&&(t=e.type===this.cipherType),this.selectedFolder&&null==this.selectedFolderId&&t&&(t=null==e.folderId),this.selectedFolder&&null!=this.selectedFolderId&&t&&(t=e.folderId===this.selectedFolderId),this.selectedCollection&&null==this.selectedCollectionId&&t&&(t=null!=e.organizationId&&(null==e.collectionIds||0===e.collectionIds.length)),this.selectedCollection&&null!=this.selectedCollectionId&&t&&(t=null!=e.collectionIds&&e.collectionIds.includes(this.selectedCollectionId)),null!=this.selectedOrganizationId&&t&&(t=e.organizationId===this.selectedOrganizationId),this.myVaultOnly&&t&&(t=null===e.organizationId),t}}}function sk(e){return e.isMember}class ok{}class ak{hasId(e){return null!=this.fullList&&this.fullList.filter((t=>t.id===e)).length>0}constructor(e){Object.assign(this,e)}}const lk=jt.array(Oi,"collapsedGroupings",{deserializer:e=>e});var ck=i(85762);class dk{}class uk{}class hk{}class pk{}var yk=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class vk{constructor(e,t,i,n,r,s){this.organizationService=e,this.folderService=t,this.cipherService=i,this.collectionService=n,this.policyService=r,this.stateProvider=s,this.collapsedGroupingsState=this.stateProvider.getActive(lk),this.collapsedGroupings$=this.collapsedGroupingsState.state$.pipe((0,q.U)((e=>new Set(e))))}storeCollapsedFilterNodes(e){return yk(this,void 0,void 0,(function*(){yield this.collapsedGroupingsState.update((()=>Array.from(e)))}))}buildCollapsedFilterNodes(){return yk(this,void 0,void 0,(function*(){return yield(0,r.z)(this.collapsedGroupings$)}))}buildOrganizations(){return yk(this,void 0,void 0,(function*(){let e=yield this.organizationService.getAll();return null!=e&&(e=e.filter(sk).sort(((e,t)=>e.name.localeCompare(t.name)))),e}))}buildNestedFolders(e){const t=t=>yk(this,void 0,void 0,(function*(){let i;if(null==e||"MyVault"==e)i=t;else{const n=(yield this.cipherService.getAllDecrypted()).filter((t=>t.organizationId==e));i=t.filter((e=>n.some((t=>t.folderId==e.id))||null==e.id))}const n=yield this.getAllFoldersNested(i);return new ak({fullList:i,nestedList:n})}));return this.folderService.folderViews$.pipe((0,pm.z)((e=>(0,rh.D)(t(e)))))}buildCollections(e){return yk(this,void 0,void 0,(function*(){const t=yield this.collectionService.getAllDecrypted();let i;i=null!=e?t.filter((t=>t.organizationId===e)):t;const n=yield this.collectionService.getAllNested(i);return new ak({fullList:i,nestedList:n})}))}checkForSingleOrganizationPolicy(){return yk(this,void 0,void 0,(function*(){return yield(0,r.z)(this.policyService.policyAppliesToActiveUser$(qi.SingleOrg))}))}checkForPersonalOwnershipPolicy(){return yk(this,void 0,void 0,(function*(){return yield(0,r.z)(this.policyService.policyAppliesToActiveUser$(qi.PersonalOwnership))}))}getAllFoldersNested(e){return yk(this,void 0,void 0,(function*(){const t=[];return e.forEach((e=>{const i=new Fy;i.id=e.id,i.revisionDate=e.revisionDate;const n=null!=e.name?e.name.replace(/^\/+|\/+$/g,"").split("/"):[];qp.nestedTraverse(t,0,n,i,null,"/")})),t}))}getFolderNested(e){return yk(this,void 0,void 0,(function*(){const t=yield this.getAllFoldersNested(yield(0,r.z)(this.folderService.folderViews$));return qp.getTreeNodeObjectFromList(t,e)}))}}vk.ɵfac=function(e){return new(e||vk)(ck.LFG(ok),ck.LFG(dk),ck.LFG(uk),ck.LFG(hk),ck.LFG(pk),ck.LFG(Vt))},vk.ɵprov=ck.Yz7({token:vk,factory:vk.ɵfac});class fk extends vk{constructor(e,t,i,n,r,s,o){super(e,t,i,n,r,s),this.accountService=o,this.vaultFilter=new rk,this.allVaults="allVaults",this.myVault="myVault",this.vaultFilter.myVaultOnly=!1,this.vaultFilter.selectedOrganizationId=null,this.accountService.activeAccount$.subscribe((e=>{this.setVaultFilter(this.allVaults)}))}getVaultFilter(){return this.vaultFilter}setVaultFilter(e){e===this.allVaults?(this.vaultFilter.myVaultOnly=!1,this.vaultFilter.selectedOrganizationId=null):e===this.myVault?(this.vaultFilter.myVaultOnly=!0,this.vaultFilter.selectedOrganizationId=null):(this.vaultFilter.myVaultOnly=!1,this.vaultFilter.selectedOrganizationId=e)}clear(){this.setVaultFilter(this.allVaults)}filterCipherForSelectedVault(e){if(!this.vaultFilter.selectedOrganizationId&&!this.vaultFilter.myVaultOnly)return!1;if(this.vaultFilter.selectedOrganizationId){if(e.organizationId===this.vaultFilter.selectedOrganizationId)return!1}else if(this.vaultFilter.myVaultOnly&&!e.organizationId)return!1;return!0}}var gk=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class mk{constructor(e,t,i,n,r){this.main=e,this.passwordGenerationService=t,this.platformUtilsService=i,this.vaultTimeoutService=n,this.authService=r,this.isSafari=this.platformUtilsService.isSafari(),this.isVivaldi=this.platformUtilsService.isVivaldi()}init(){return gk(this,void 0,void 0,(function*(){xg.messageListener("commands.background",(e=>{"unlockCompleted"===e.command&&"commands.background"===e.data.target&&this.processCommand(e.data.commandToRetry.message.command,e.data.commandToRetry.sender).catch((e=>this.main.logService.error(e)))})),chrome&&chrome.commands&&chrome.commands.onCommand.addListener((e=>gk(this,void 0,void 0,(function*(){yield this.processCommand(e)}))))}))}processCommand(e,t){return gk(this,void 0,void 0,(function*(){switch(e){case"generate_password":yield this.generatePasswordToClipboard();break;case"autofill_login":yield this.autoFillLogin(t?t.tab:null);break;case"open_popup":yield this.openPopup();break;case"lock_vault":yield this.vaultTimeoutService.lock()}}))}generatePasswordToClipboard(){var e,t;return gk(this,void 0,void 0,(function*(){const i=null!==(t=null===(e=yield this.passwordGenerationService.getOptions())||void 0===e?void 0:e[0])&&void 0!==t?t:{},n=yield this.passwordGenerationService.generatePassword(i);this.platformUtilsService.copyToClipboard(n),yield this.passwordGenerationService.addHistory(n)}))}autoFillLogin(e){return gk(this,void 0,void 0,(function*(){if(e||(e=yield xg.getTabFromCurrentWindowId()),null!=e){if((yield this.authService.getAuthStatus()){"active"===e?this.notificationsService.reconnectFromActivity():this.notificationsService.disconnectFromInactivity()};this.idle.onStateChanged&&this.idle.setDetectionInterval?(this.idle.setDetectionInterval(300),this.idle.onStateChanged.addListener(e)):this.pollIdle(e),this.idle.onStateChanged&&this.idle.onStateChanged.addListener((e=>wk(this,void 0,void 0,(function*(){if("locked"===e){const e=yield(0,r.z)(this.accountService.accounts$);for(const t in e){if(-2===(yield this.stateService.getVaultTimeout({userId:t}))){(yield this.stateService.getVaultTimeoutAction({userId:t}))===ar.LogOut?yield this.vaultTimeoutService.logOut(t):yield this.vaultTimeoutService.lock(t)}}}}))))}))}pollIdle(e){null!=this.idleTimer&&(window.clearTimeout(this.idleTimer),this.idleTimer=null),this.idle.queryState(300,(t=>{t!==this.idleState&&(this.idleState=t,e(t)),this.idleTimer=window.setTimeout((()=>this.pollIdle(e)),5e3)}))}}var bk=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Pk{constructor(e,t,i,n,r,s,o,a,l,c){var d;this.cryptoService=e,this.cryptoFunctionService=t,this.runtimeBackground=i,this.messagingService=n,this.appIdService=r,this.platformUtilsService=s,this.stateService=o,this.logService=a,this.authService=l,this.biometricStateService=c,this.connected=!1,this.resolver=null,this.privateKey=null,this.publicKey=null,this.secureSetupResolve=null,(null===(d=null===chrome||void 0===chrome?void 0:chrome.permissions)||void 0===d?void 0:d.onAdded)&&chrome.permissions.onAdded.addListener((e=>{var t;(null===(t=e.permissions)||void 0===t?void 0:t.includes("nativeMessaging"))&&xg.reloadExtension(null)}))}connect(){return bk(this,void 0,void 0,(function*(){return this.appId=yield this.appIdService.getAppId(),yield this.biometricStateService.setFingerprintValidated(!1),new Promise(((e,t)=>{this.port=xg.connectNative("com.8bit.bitwarden"),this.connecting=!0;const i=()=>{this.connected=!0,this.connecting=!1,e()};this.platformUtilsService.isSafari()&&i(),this.port.onMessage.addListener((e=>bk(this,void 0,void 0,(function*(){switch(e.command){case"connected":i();break;case"disconnected":this.connecting&&t(new Error("startDesktop")),this.connected=!1,this.port.disconnect();break;case"setupEncryption":{if(e.appId!==this.appId)return;const t=p.fromB64ToArray(e.sharedSecret),i=yield this.cryptoFunctionService.rsaDecrypt(t,this.privateKey,"sha1");this.validatingFingerprint&&(this.validatingFingerprint=!1,yield this.biometricStateService.setFingerprintValidated(!0)),this.sharedSecret=new N(i),this.secureSetupResolve();break}case"invalidateEncryption":if(e.appId!==this.appId)return;this.sharedSecret=null,this.privateKey=null,this.connected=!1,this.messagingService.send("showDialog",{title:{key:"nativeMessagingInvalidEncryptionTitle"},content:{key:"nativeMessagingInvalidEncryptionDesc"},acceptButtonText:{key:"ok"},cancelButtonText:null,type:"danger"});break;case"verifyFingerprint":null==this.sharedSecret&&(this.validatingFingerprint=!0,this.showFingerprintDialog());break;case"wrongUserId":this.showWrongUserDialog();break;default:if(!this.platformUtilsService.isSafari()&&e.appId!==this.appId)return;this.onMessage(e.message)}})))),this.port.onDisconnect.addListener((e=>{let i;i=xg.isWebExtensionsApi?e.error.message:chrome.runtime.lastError.message,this.sharedSecret=null,this.privateKey=null,this.connected=!1;t(new Error(null!=i?"desktopIntegrationDisabled":null))}))}))}))}showWrongUserDialog(){this.messagingService.send("showDialog",{title:{key:"nativeMessagingWrongUserTitle"},content:{key:"nativeMessagingWrongUserDesc"},acceptButtonText:{key:"ok"},cancelButtonText:null,type:"danger"})}send(e){return bk(this,void 0,void 0,(function*(){this.connected||(yield this.connect()),e.userId=yield this.stateService.getUserId(),e.timestamp=Date.now(),this.platformUtilsService.isSafari()?this.postMessage(e):this.postMessage({appId:this.appId,message:yield this.encryptMessage(e)})}))}encryptMessage(e){return bk(this,void 0,void 0,(function*(){return null==this.sharedSecret&&(yield this.secureCommunication()),yield this.cryptoService.encrypt(JSON.stringify(e),this.sharedSecret)}))}getResponse(){return new Promise(((e,t)=>{this.resolver=e}))}postMessage(e){try{const t=e;e.message instanceof z&&(t.message={encryptedString:e.message.encryptedString,encryptionType:e.message.encryptionType,data:e.message.data,iv:e.message.iv,mac:e.message.mac}),this.port.postMessage(t)}catch(e){this.logService.error("NativeMessaging port disconnected, disconnecting."),this.sharedSecret=null,this.privateKey=null,this.connected=!1,this.messagingService.send("showDialog",{title:{key:"nativeMessagingInvalidEncryptionTitle"},content:{key:"nativeMessagingInvalidEncryptionDesc"},acceptButtonText:{key:"ok"},cancelButtonText:null,type:"danger"})}}onMessage(e){return bk(this,void 0,void 0,(function*(){let t=e;if(this.platformUtilsService.isSafari()||(t=JSON.parse(yield this.cryptoService.decryptToUtf8(e,this.sharedSecret))),Math.abs(t.timestamp-Date.now())>1e4)this.logService.error("NativeMessage is to old, ignoring.");else{switch(t.command){case"biometricUnlock":{if("not enabled"===t.response){this.messagingService.send("showDialog",{title:{key:"biometricsNotEnabledTitle"},content:{key:"biometricsNotEnabledDesc"},acceptButtonText:{key:"ok"},cancelButtonText:null,type:"danger"});break}if("not supported"===t.response){this.messagingService.send("showDialog",{title:{key:"biometricsNotSupportedTitle"},content:{key:"biometricsNotSupportedDesc"},acceptButtonText:{key:"ok"},cancelButtonText:null,type:"danger"});break}if("canceled"===t.response)break;const e=yield(0,r.z)(this.biometricStateService.biometricUnlockEnabled$);if(null===e||!1===e){"unlocked"===t.response&&(yield this.biometricStateService.setBiometricUnlockEnabled(!0));break}if((yield this.authService.getAuthStatus())===On.Unlocked)break;if("unlocked"===t.response){try{if(t.userKeyB64){const e=new N(p.fromB64ToArray(t.userKeyB64));yield this.cryptoService.setUserKey(e)}else{if(!t.keyB64)throw new Error("No key received");{let e=yield this.stateService.getEncryptedCryptoSymmetricKey();if(e||(e=yield this.stateService.getMasterKeyEncryptedUserKey()),!e)throw new Error("No encrypted user key found");const i=new N(p.fromB64ToArray(t.keyB64)),n=yield this.cryptoService.decryptUserKeyWithMasterKey(i,new z(e));yield this.cryptoService.setMasterKey(i),yield this.cryptoService.setUserKey(n)}}}catch(e){return this.logService.error("Unable to set key: "+e),this.messagingService.send("showDialog",{title:{key:"biometricsFailedTitle"},content:{key:"biometricsFailedDesc"},acceptButtonText:{key:"ok"},cancelButtonText:null,type:"danger"}),void(this.resolver&&this.resolver(t))}try{yield this.cryptoService.getFingerprint(yield this.stateService.getUserId())}catch(e){return this.logService.error("Unable to verify key: "+e),yield this.cryptoService.clearKeys(),this.showWrongUserDialog(),void(this.resolver&&this.resolver(t))}this.runtimeBackground.processMessage({command:"unlocked"},null)}break}default:this.logService.error("NativeMessage, got unknown command: "+t.command)}this.resolver&&this.resolver(t)}}))}secureCommunication(){return bk(this,void 0,void 0,(function*(){const[e,t]=yield this.cryptoFunctionService.rsaGenerateKeyPair(2048);return this.publicKey=e,this.privateKey=t,this.sendUnencrypted({command:"setupEncryption",publicKey:p.fromBufferToB64(e),userId:yield this.stateService.getUserId()}),new Promise(((e,t)=>this.secureSetupResolve=e))}))}sendUnencrypted(e){return bk(this,void 0,void 0,(function*(){this.connected||(yield this.connect()),e.timestamp=Date.now(),this.postMessage({appId:this.appId,message:e})}))}showFingerprintDialog(){return bk(this,void 0,void 0,(function*(){const e=yield this.cryptoService.getFingerprint(yield this.stateService.getUserId(),this.publicKey);this.messagingService.send("showNativeMessagingFinterprintDialog",{fingerprint:e})}))}}class kk{constructor(){this.abortControllers=new Map}runWithAbortController(e,t){const i=new AbortController;return this.abortControllers.set(e,i),t(i).finally((()=>{this.abortControllers.delete(e)}))}abort(e){var t;null===(t=this.abortControllers.get(e))||void 0===t||t.abort()}}var Ok=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Ck{constructor(e,t,i,n,r,s,o,a,l,c,d,u,h){this.main=e,this.autofillService=t,this.platformUtilsService=i,this.i18nService=n,this.notificationsService=r,this.stateService=s,this.autofillSettingsService=o,this.systemService=a,this.environmentService=l,this.messagingService=c,this.logService=d,this.configService=u,this.fido2Service=h,this.pageDetailsToAutoFill=[],this.onInstalledReason=null,this.lockedVaultPendingNotifications=[],this.abortManager=new kk,chrome.runtime.onInstalled.addListener((e=>{this.onInstalledReason=e.reason}))}init(){return Ok(this,void 0,void 0,(function*(){if(!chrome.runtime)return;yield this.checkOnInstalled();const e=(e,t,i)=>["checkFido2FeatureEnabled","fido2RegisterCredentialRequest","fido2GetCredentialRequest","biometricUnlock"].includes(e.command)?(this.processMessage(e,t).then((e=>i({result:e})),(e=>i({error:Object.assign(Object.assign({},e),{message:e.message})}))),!0):(this.processMessage(e,t),!1);xg.messageListener("runtime.background",e),this.main.popupOnlyContext&&(window.bitwardenBackgroundMessageListener=e)}))}processMessage(e,t){var i;return Ok(this,void 0,void 0,(function*(){switch(e.command){case"loggedIn":case"unlocked":{let t;"loggedIn"===e.command&&(yield this.sendBwInstalledMessageToVault()),(null===(i=this.lockedVaultPendingNotifications)||void 0===i?void 0:i.length)>0&&(t=this.lockedVaultPendingNotifications.pop(),yield function(){return Rg(this,void 0,void 0,(function*(){yield Ng.closeSingleActionPopout(Eg)}))}()),yield this.notificationsService.updateConnection("loggedIn"===e.command),yield this.main.refreshBadge(),yield this.main.refreshMenu(!1),this.systemService.cancelProcessReload(),t&&(yield xg.focusWindow(t.commandToRetry.sender.tab.windowId),yield xg.focusTab(t.commandToRetry.sender.tab.id),yield xg.tabSendMessageData(t.commandToRetry.sender.tab,"unlockCompleted",t));break}case"addToLockedVaultPendingNotifications":this.lockedVaultPendingNotifications.push(e.data);break;case"logout":yield this.main.logout(e.expired,e.userId);break;case"syncCompleted":e.successfully&&(setTimeout((()=>Ok(this,void 0,void 0,(function*(){yield this.main.refreshBadge(),yield this.main.refreshMenu()}))),2e3),this.configService.triggerServerConfigFetch());break;case"openPopup":yield this.main.openPopup();break;case"triggerAutofillScriptInjection":yield this.autofillService.injectAutofillScripts(t.tab,t.frameId);break;case"bgCollectPageDetails":yield this.main.collectPageDetailsForContentScript(t.tab,e.sender,t.frameId);break;case"bgUpdateContextMenu":case"editedCipher":case"addedCipher":case"deletedCipher":yield this.main.refreshBadge(),yield this.main.refreshMenu();break;case"bgReseedStorage":yield this.main.reseedStorage();break;case"collectPageDetailsResponse":switch(e.sender){case"autofiller":case"autofill_cmd":{this.stateService.setLastActive((new Date).getTime());const i=yield this.autofillService.doAutoFillActiveTab([{frameId:t.frameId,tab:e.tab,details:e.details}],"autofill_cmd"===e.sender);null!=i&&this.platformUtilsService.copyToClipboard(i);break}case"autofill_card":yield this.autofillService.doAutoFillActiveTab([{frameId:t.frameId,tab:e.tab,details:e.details}],!1,Pe.Card);break;case"autofill_identity":yield this.autofillService.doAutoFillActiveTab([{frameId:t.frameId,tab:e.tab,details:e.details}],!1,Pe.Identity);break;case"contextMenu":clearTimeout(this.autofillTimeout),this.pageDetailsToAutoFill.push({frameId:t.frameId,tab:e.tab,details:e.details}),this.autofillTimeout=setTimeout((()=>Ok(this,void 0,void 0,(function*(){return yield this.autofillPage(e.tab)}))),300)}break;case"authResult":{const t=(yield(0,r.z)(this.environmentService.environment$)).getWebVaultUrl();if(null==e.referrer||p.getHostname(t)!==e.referrer)return;if(e.lastpass)this.messagingService.send("importCallbackLastPass",{code:e.code,state:e.state});else try{yield function(e){return Rg(this,void 0,void 0,(function*(){const{code:t,state:i}=e,n=`popup/index.html#/sso?code=${encodeURIComponent(t)}&state=${encodeURIComponent(i)}`;yield Ng.openPopout(n,{singleActionKey:Fg})}))}(e)}catch(e){this.logService.error("Unable to open sso popout tab")}break}case"webAuthnResult":{const t=(yield(0,r.z)(this.environmentService.environment$)).getWebVaultUrl();if(null==e.referrer||p.getHostname(t)!==e.referrer)return;yield function(e){return Rg(this,void 0,void 0,(function*(){const{data:t,remember:i}=e,n=`popup/index.html#/2fa;webAuthnResponse=${encodeURIComponent(t)};remember=${encodeURIComponent(i)}`;yield Ng.openPopout(n,{singleActionKey:Mg})}))}(e);break}case"reloadPopup":this.messagingService.send("reloadPopup");break;case"emailVerificationRequired":this.messagingService.send("showDialog",{title:{key:"emailVerificationRequired"},content:{key:"emailVerificationRequiredDesc"},acceptButtonText:{key:"ok"},cancelButtonText:null,type:"info"});break;case"getClickedElementResponse":this.platformUtilsService.copyToClipboard(e.identifier);break;case"triggerFido2ContentScriptInjection":yield this.fido2Service.injectFido2ContentScripts(t);break;case"fido2AbortRequest":this.abortManager.abort(e.abortedRequestId);break;case"checkFido2FeatureEnabled":return yield this.main.fido2ClientService.isFido2FeatureEnabled(e.hostname,e.origin);case"fido2RegisterCredentialRequest":return yield this.abortManager.runWithAbortController(e.requestId,(i=>Ok(this,void 0,void 0,(function*(){try{return yield this.main.fido2ClientService.createCredential(e.data,t.tab,i)}finally{yield xg.focusTab(t.tab.id),yield xg.focusWindow(t.tab.windowId)}}))));case"fido2GetCredentialRequest":return yield this.abortManager.runWithAbortController(e.requestId,(i=>Ok(this,void 0,void 0,(function*(){try{return yield this.main.fido2ClientService.assertCredential(e.data,t.tab,i)}finally{yield xg.focusTab(t.tab.id),yield xg.focusWindow(t.tab.windowId)}}))));case"switchAccount":yield this.main.switchAccount(e.userId);break;case"clearClipboard":yield this.main.clearClipboard(e.clipboardValue,e.timeoutMs);break;case"biometricUnlock":return yield this.main.biometricUnlock()}}))}autofillPage(e){return Ok(this,void 0,void 0,(function*(){const t=yield this.autofillService.doAutoFill({tab:e,cipher:this.main.loginToAutoFill,pageDetails:this.pageDetailsToAutoFill,fillNewPassword:!0,allowTotpAutofill:!0});null!=t&&this.platformUtilsService.copyToClipboard(t),this.main.loginToAutoFill=null,this.pageDetailsToAutoFill=[]}))}checkOnInstalled(){return Ok(this,void 0,void 0,(function*(){setTimeout((()=>Ok(this,void 0,void 0,(function*(){this.autofillService.loadAutofillScriptsOnInstall(),null!=this.onInstalledReason&&("install"===this.onInstalledReason&&(xg.createNewTab("https://bitwarden.com/browser-start/"),yield this.autofillSettingsService.setInlineMenuVisibility(qr),(yield this.environmentService.hasManagedEnvironment())&&(yield this.environmentService.setUrlsToManagedEnvironment())),this.onInstalledReason=null)}))),100)}))}sendBwInstalledMessageToVault(){return Ok(this,void 0,void 0,(function*(){try{const e=(yield(0,r.z)(this.environmentService.environment$)).getWebVaultUrl(),t=new URL(e),i=yield xg.tabsQuery({url:`${t.href}*`});if(!(null==i?void 0:i.length))return;for(const e of i)yield xg.executeScriptInTab(e.id,{file:"content/send-on-installed-message.js",runAt:"document_end"})}catch(e){this.logService.error(`Error sending on installed message to vault: ${e}`)}}))}}var Ak=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};class Dk{constructor(e=!1){this.isPrivateMode=e,this.loginToAutoFill=null,this.popupOnlyContext=e||xg.isManifestVersion(3);const t=(e,t)=>Ak(this,void 0,void 0,(function*(){return yield this.logout(e,t)}));this.messagingService=this.popupOnlyContext?new AP:new Vm,this.logService=new $s(!1),this.cryptoFunctionService=new od(self),this.keyGenerationService=new Ko(this.cryptoFunctionService),this.storageService=new fm,this.secureStorageService=this.storageService,this.memoryStorageService=xg.isManifestVersion(3)?new Om(new Ys(this.cryptoFunctionService,this.logService,!1),this.keyGenerationService):new Bo,this.memoryStorageForStateProviders=xg.isManifestVersion(3)?new Om(new Ys(this.cryptoFunctionService,this.logService,!1),this.keyGenerationService):new xm;const i=new Xc(this.storageService,this.memoryStorageForStateProviders);this.globalStateProvider=new Pd(i);const n=new Ii(this.globalStateProvider,i);this.stateEventRunnerService=new Ti(this.globalStateProvider,i),this.encryptService=gm("multithreadDecryption")?new xo(this.cryptoFunctionService,this.logService,!0):new Ys(this.cryptoFunctionService,this.logService,!0),this.singleUserStateProvider=new Cd(i,n),this.accountService=new Tn(this.messagingService,this.logService,this.globalStateProvider),this.activeUserStateProvider=new ud(this.accountService,this.singleUserStateProvider),this.derivedStateProvider=new Pw(this.memoryStorageForStateProviders),this.stateProvider=new Dd(this.activeUserStateProvider,this.singleUserStateProvider,this.globalStateProvider,this.derivedStateProvider),this.environmentService=new yw(this.logService,this.stateProvider,this.accountService),this.biometricStateService=new xs(this.stateProvider),this.userNotificationSettingsService=new vs(this.stateProvider),this.platformUtilsService=new zm(this.messagingService,((e,t)=>this.clearClipboard(e,t)),(()=>Ak(this,void 0,void 0,(function*(){return this.biometricUnlock()}))),self),this.tokenService=new Sr(this.singleUserStateProvider,this.globalStateProvider,this.platformUtilsService.supportsSecureStorage(),this.secureStorageService,this.keyGenerationService,this.encryptService,this.logService);const r=new Qc(this.storageService,this.logService,new Hc);this.stateService=new hS(this.storageService,this.secureStorageService,this.memoryStorageService,this.logService,new Ns(Rs,tS),this.accountService,this.environmentService,this.tokenService,r);const s=new Ud(this.globalStateProvider);this.i18nService=new db(xg.getUILanguage(),this.globalStateProvider),this.cryptoService=new VS(this.keyGenerationService,this.cryptoFunctionService,this.encryptService,this.platformUtilsService,this.logService,this.stateService,this.accountService,this.stateProvider,this.biometricStateService),this.appIdService=new Ls(this.globalStateProvider),this.apiService=new Qu(this.tokenService,this.platformUtilsService,this.environmentService,this.appIdService,this.stateService,(e=>this.logout(e))),this.domainSettingsService=new us(this.stateProvider),this.fileUploadService=new Fo(this.logService),this.cipherFileUploadService=new Uy(this.apiService,this.fileUploadService),this.searchService=new Ah(this.logService,this.i18nService),this.collectionService=new Yp(this.cryptoService,this.i18nService,this.stateProvider),this.syncNotifierService=new _y,this.organizationService=new on(this.stateProvider),this.policyService=new mn(this.stateProvider,this.organizationService),this.autofillSettingsService=new is(this.stateProvider,this.policyService),this.badgeSettingsService=new ss(this.stateProvider),this.policyApiService=new hn(this.policyService,this.apiService),this.keyConnectorService=new er(this.stateService,this.cryptoService,this.apiService,this.tokenService,this.logService,this.organizationService,this.keyGenerationService,t),this.passwordStrengthService=new cp,this.passwordGenerationService=new Vh(this.cryptoService,this.policyService,this.stateService),this.twoFactorService=new Pr(this.i18nService,this.platformUtilsService);const o=this,a=new class extends ws{constructor(){super(...arguments),this.send=(e,t={})=>{const i=Object.assign({},{command:e},t);o.runtimeBackground.processMessage(i,o)}}};this.userDecryptionOptionsService=new Bi(this.stateProvider),this.devicesApiService=new Yn(this.apiService),this.deviceTrustCryptoService=new _n(this.keyGenerationService,this.cryptoFunctionService,this.cryptoService,this.encryptService,this.stateService,this.appIdService,this.devicesApiService,this.i18nService,this.platformUtilsService,this.userDecryptionOptionsService),this.devicesService=new Wn(this.devicesApiService),this.authRequestService=new Xi(this.appIdService,this.cryptoService,this.apiService,this.stateService),this.authService=new Rn(a,this.cryptoService,this.apiService,this.stateService),this.billingAccountProfileStateService=new ms(this.stateProvider),this.loginStrategyService=new Li(this.cryptoService,this.apiService,this.tokenService,this.appIdService,this.platformUtilsService,a,this.logService,this.keyConnectorService,this.environmentService,this.stateService,this.twoFactorService,this.i18nService,this.encryptService,this.passwordStrengthService,this.policyService,this.deviceTrustCryptoService,this.authRequestService,this.userDecryptionOptionsService,this.globalStateProvider,this.billingAccountProfileStateService),this.ssoLoginService=new or(this.stateProvider),this.userVerificationApiService=new Cr(this.apiService),this.configApiService=new js(this.apiService,this.authService),this.configService=new CP(this.stateService,this.configApiService,this.authService,this.environmentService,this.logService,this.stateProvider,!0),this.cipherService=new Bp(this.cryptoService,this.domainSettingsService,this.apiService,this.i18nService,this.searchService,this.stateService,this.autofillSettingsService,this.encryptService,this.cipherFileUploadService,this.configService),this.folderService=new By(this.cryptoService,this.i18nService,this.cipherService,this.stateService,this.stateProvider),this.folderApiService=new Ey(this.folderService,this.apiService),this.vaultTimeoutSettingsService=new xh(this.userDecryptionOptionsService,this.cryptoService,this.tokenService,this.policyService,this.stateService,this.biometricStateService),this.pinCryptoService=new B(this.stateService,this.cryptoService,this.vaultTimeoutSettingsService,this.logService),this.userVerificationService=new xr(this.stateService,this.cryptoService,this.i18nService,this.userVerificationApiService,this.userDecryptionOptionsService,this.pinCryptoService,this.logService,this.vaultTimeoutSettingsService,this.platformUtilsService),this.vaultFilterService=new fk(this.organizationService,this.folderService,this.cipherService,this.collectionService,this.policyService,this.stateProvider,this.accountService),this.vaultSettingsService=new iv(this.stateProvider),this.vaultTimeoutService=new _P(this.cipherService,this.folderService,this.collectionService,this.cryptoService,this.platformUtilsService,this.messagingService,this.searchService,this.stateService,this.authService,this.vaultTimeoutSettingsService,this.stateEventRunnerService,(e=>Ak(this,void 0,void 0,(function*(){null!=this.notificationsService&&this.notificationsService.updateConnection(!1),yield this.refreshBadge(),yield this.refreshMenu(!0),null!=this.systemService&&(yield this.systemService.clearPendingClipboard(),yield this.systemService.startProcessReload(this.authService))}))),t),this.containerService=new Ws(this.cryptoService,this.encryptService),this.sendService=new KP(this.cryptoService,this.i18nService,this.keyGenerationService,this.stateService),this.sendApiService=new mp(this.apiService,this.fileUploadService,this.sendService),this.avatarService=new Kn(this.apiService,this.stateProvider),this.providerService=new kn(this.stateProvider),this.syncService=new Hy(this.apiService,this.domainSettingsService,this.folderService,this.cipherService,this.cryptoService,this.collectionService,this.messagingService,this.policyService,this.sendService,this.logService,this.keyConnectorService,this.stateService,this.providerService,this.folderApiService,this.organizationService,this.sendApiService,this.userDecryptionOptionsService,this.avatarService,t,this.billingAccountProfileStateService),this.eventUploadService=new hh(this.apiService,this.stateProvider,this.logService,this.accountService),this.eventCollectionService=new ch(this.cipherService,this.stateProvider,this.organizationService,this.eventUploadService,this.accountService),this.totpService=new Qy(this.cryptoFunctionService,this.logService),this.autofillService=new tP(this.cipherService,this.stateService,this.autofillSettingsService,this.totpService,this.eventCollectionService,this.logService,this.domainSettingsService,this.userVerificationService,this.billingAccountProfileStateService),this.auditService=new th(this.cryptoFunctionService,this.apiService),this.importApiService=new rv(this.apiService),this.importService=new dg(this.cipherService,this.folderService,this.importApiService,this.i18nService,this.collectionService,this.cryptoService),this.individualVaultExportService=new wg(this.folderService,this.cipherService,this.cryptoService,this.cryptoFunctionService,this.stateService),this.organizationVaultExportService=new gg(this.cipherService,this.apiService,this.cryptoService,this.cryptoFunctionService,this.stateService,this.collectionService),this.exportService=new pg(this.individualVaultExportService,this.organizationVaultExportService),this.notificationsService=new kh(this.logService,this.syncService,this.appIdService,this.apiService,this.environmentService,t,this.stateService,this.authService,this.messagingService),this.fido2Service=new nk,this.fido2UserInterfaceService=new ek(this.authService),this.fido2AuthenticatorService=new wy(this.cipherService,this.fido2UserInterfaceService,this.syncService,this.logService),this.fido2ClientService=new Ay(this.fido2AuthenticatorService,this.configService,this.authService,this.vaultSettingsService,this.domainSettingsService,this.logService);if(this.systemService=new td(this.messagingService,this.platformUtilsService,(()=>{const e=this.platformUtilsService.isSafari()||this.platformUtilsService.isFirefox()||this.platformUtilsService.isOpera();return xg.reloadExtension(e?self:null),Promise.resolve()}),this.stateService,this.autofillSettingsService,this.vaultTimeoutSettingsService,this.biometricStateService),this.isSafari=this.platformUtilsService.isSafari(),this.runtimeBackground=new Ck(this,this.autofillService,this.platformUtilsService,this.i18nService,this.notificationsService,this.stateService,this.autofillSettingsService,this.systemService,this.environmentService,this.messagingService,this.logService,this.configService,this.fido2Service),this.nativeMessagingBackground=new Pk(this.cryptoService,this.cryptoFunctionService,this.runtimeBackground,this.messagingService,this.appIdService,this.platformUtilsService,this.stateService,this.logService,this.authService,this.biometricStateService),this.commandsBackground=new mk(this,this.passwordGenerationService,this.platformUtilsService,this.vaultTimeoutService,this.authService),this.notificationBackground=new Jg(this.autofillService,this.cipherService,this.authService,this.policyService,this.folderService,this.stateService,this.userNotificationSettingsService,this.domainSettingsService,this.environmentService,this.logService,s),this.overlayBackground=new im(this.cipherService,this.autofillService,this.authService,this.environmentService,this.domainSettingsService,this.stateService,this.autofillSettingsService,this.i18nService,this.platformUtilsService,s),this.filelessImporterBackground=new JP(this.configService,this.authService,this.policyService,this.notificationBackground,this.importService,this.syncService),this.tabsBackground=new rm(this,this.notificationBackground,this.overlayBackground),!this.popupOnlyContext){const e=new wP((e=>this.platformUtilsService.copyToClipboard(e.text)),(e=>Ak(this,void 0,void 0,(function*(){var e,t;const i=null!==(t=null===(e=yield this.passwordGenerationService.getOptions())||void 0===e?void 0:e[0])&&void 0!==t?t:{},n=yield this.passwordGenerationService.generatePassword(i);this.platformUtilsService.copyToClipboard(n),this.passwordGenerationService.addHistory(n)}))),((e,t)=>Ak(this,void 0,void 0,(function*(){this.loginToAutoFill=t,null!=e&&xg.tabSendMessage(e,{command:"collectPageDetails",tab:e,sender:"contextMenu"})}))),this.authService,this.cipherService,this.stateService,this.totpService,this.eventCollectionService,this.userVerificationService);this.contextMenusBackground=new Ig(e)}this.idleBackground=new Sk(this.vaultTimeoutService,this.stateService,this.notificationsService,this.accountService),this.webRequestBackground=new om(this.platformUtilsService,this.cipherService,this.authService),this.usernameGenerationService=new op(this.cryptoService,this.stateService,this.apiService),this.popupOnlyContext||(this.mainContextMenuHandler=new xb(this.stateService,this.autofillSettingsService,this.i18nService,this.logService,this.billingAccountProfileStateService),this.cipherContextMenuHandler=new Nb(this.mainContextMenuHandler,this.authService,this.cipherService))}bootstrap(){var e;return Ak(this,void 0,void 0,(function*(){if(this.containerService.attachToGlobal(window),yield this.stateService.init(),yield this.vaultTimeoutService.init(!0),yield this.i18nService.init(),yield this.eventUploadService.init(!0),yield this.runtimeBackground.init(),yield this.notificationBackground.init(),this.filelessImporterBackground.init(),yield this.commandsBackground.init(),this.configService.init(),this.twoFactorService.init(),yield this.overlayBackground.init(),yield this.tabsBackground.init(),this.popupOnlyContext||null===(e=this.contextMenusBackground)||void 0===e||e.init(),yield this.idleBackground.init(),yield this.webRequestBackground.init(),yield this.fido2Service.init(),this.platformUtilsService.isFirefox()&&!this.isPrivateMode){(yield xg.getPrivateModeWindows()).forEach((e=>Ak(this,void 0,void 0,(function*(){yield new PP(self).setBadgeIcon("",e.id)})))),xg.onWindowCreated((e=>Ak(this,void 0,void 0,(function*(){e.incognito&&(yield new PP(self).setBadgeIcon("",e.id))}))))}return new Promise((e=>{setTimeout((()=>Ak(this,void 0,void 0,(function*(){this.isPrivateMode||(yield this.refreshBadge()),this.fullSync(!0),setTimeout((()=>this.notificationsService.init()),2500),e()}))),500)}))}))}refreshBadge(){return Ak(this,void 0,void 0,(function*(){yield new PP(self).run({existingServices:this})}))}refreshMenu(e=!1){var t,i,n;return Ak(this,void 0,void 0,(function*(){if(!chrome.windows||!chrome.contextMenus)return;if(yield xb.removeAll(),e)return yield null===(t=this.mainContextMenuHandler)||void 0===t?void 0:t.noAccess(),void(this.onUpdatedRan=this.onReplacedRan=!1);yield null===(i=this.mainContextMenuHandler)||void 0===i?void 0:i.init();const r=yield xg.getTabFromCurrentWindow();r&&(yield null===(n=this.cipherContextMenuHandler)||void 0===n?void 0:n.update(r.url),this.onUpdatedRan=this.onReplacedRan=!1)}))}switchAccount(e){return Ak(this,void 0,void 0,(function*(){try{if(yield this.stateService.setActiveUser(e),null==e)return yield this.stateService.setRememberedEmail(null),yield this.refreshBadge(),yield this.refreshMenu(),void(yield this.overlayBackground.updateOverlayCiphers());const t=yield this.authService.getAuthStatus(e),i=(yield this.stateService.getForceSetPasswordReason({userId:e}))!=X.None;yield this.systemService.clearPendingClipboard(),yield this.notificationsService.updateConnection(!1),t===On.Locked?this.messagingService.send("locked",{userId:e}):i?this.messagingService.send("update-temp-password",{userId:e}):(this.messagingService.send("unlocked",{userId:e}),yield this.refreshBadge(),yield this.refreshMenu(),yield this.overlayBackground.updateOverlayCiphers(),yield this.syncService.fullSync(!1))}finally{this.messagingService.send("switchAccountFinish",{userId:e})}}))}logout(e,t){var i;return Ak(this,void 0,void 0,(function*(){null!=t||(t=null===(i=yield(0,r.z)(this.accountService.activeAccount$))||void 0===i?void 0:i.id),yield this.eventUploadService.uploadEvents(t),yield Promise.all([this.syncService.setLastSync(new Date(0),t),this.cryptoService.clearKeys(t),this.cipherService.clear(t),this.folderService.clear(t),this.collectionService.clear(t),this.policyService.clear(t),this.passwordGenerationService.clear(t),this.vaultTimeoutSettingsService.clear(t),this.keyConnectorService.clear(),this.vaultFilterService.clear(),this.biometricStateService.logout(t),this.providerService.save(null,t)]);const n=yield this.needsStorageReseed(),s=yield this.stateService.getUserId(),o=yield this.stateService.clean({userId:t});null!=t&&t!==s||this.searchService.clearIndex(),yield this.stateEventRunnerService.handleEvent("logout",s),null!=o?(yield this.switchAccount(o),this.messagingService.send("switchAccountFinish")):this.messagingService.send("doneLoggingOut",{expired:e,userId:t}),n&&(yield this.reseedStorage()),xg.isManifestVersion(3)&&xg.sendMessage("updateBadge"),yield this.refreshBadge(),yield this.mainContextMenuHandler.noAccess(),this.notificationsService.updateConnection(!1),yield this.systemService.clearPendingClipboard(),yield this.systemService.startProcessReload(this.authService)}))}needsStorageReseed(){return Ak(this,void 0,void 0,(function*(){return null!=(yield this.stateService.getVaultTimeout())}))}collectPageDetailsForContentScript(e,t,i=null){return Ak(this,void 0,void 0,(function*(){if(null==e||!e.id)return;const n={};null!=i&&(n.frameId=i),xg.tabSendMessage(e,{command:"collectPageDetails",tab:e,sender:t},n)}))}openPopup(){return Ak(this,void 0,void 0,(function*(){this.isSafari&&(yield bg.sendMessageToApp("showPopover",null,!0))}))}reseedStorage(){return Ak(this,void 0,void 0,(function*(){if(!this.platformUtilsService.isChrome()&&!this.platformUtilsService.isVivaldi()&&!this.platformUtilsService.isOpera())return;const e=yield new Promise((e=>{chrome.storage.local.get(null,(t=>e(t)))}));yield new Promise((e=>{chrome.storage.local.clear((()=>e()))}));for(const t in e)e.hasOwnProperty(t)&&(yield this.storageService.save(t,e[t]))}))}clearClipboard(e,t){return Ak(this,void 0,void 0,(function*(){null!=this.systemService&&(yield this.systemService.clearClipboard(e,t))}))}biometricUnlock(){return Ak(this,void 0,void 0,(function*(){if(null==this.nativeMessagingBackground)return!1;const e=this.nativeMessagingBackground.getResponse();yield this.nativeMessagingBackground.send({command:"biometricUnlock"});return"unlocked"===(yield e).response}))}fullSync(e=!1){return Ak(this,void 0,void 0,(function*(){const t=216e5,i=yield this.syncService.getLastSync();let n=21600001;null!=i&&(n=(new Date).getTime()-i.getTime()),e||n>=t?(yield this.syncService.fullSync(e),this.scheduleNextSync()):this.scheduleNextSync()}))}scheduleNextSync(){this.syncTimeout&&clearTimeout(this.syncTimeout),this.syncTimeout=setTimeout((()=>Ak(this,void 0,void 0,(function*(){return yield this.fullSync()}))),3e5)}}var xk=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Ik=e=>xk(void 0,void 0,void 0,(function*(){dP.forEach((e=>xk(void 0,void 0,void 0,(function*(){const t=yield function(e){return cP(this,void 0,void 0,(function*(){let t;return t=xg.isManifestVersion(3)?(yield chrome.storage.session.get(e))[e]:uP[e],t}))}(e);if(!t)return;if(!(t>Date.now())&&(yield function(e){return cP(this,void 0,void 0,(function*(){yield hP(e,null)}))}(e),e===sP))oP.run()}))))}));var Uk=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Tk=(e,t={})=>(...i)=>Uk(void 0,void 0,void 0,(function*(){const n=Object.assign({},t);for(const t of e)yield t(...i,n)}));var Nk=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Rk=(e,t)=>Nk(void 0,void 0,void 0,(function*(){switch(e){case"autofill_login":yield Ek(t);break;case"generate_password":yield Fk(t)}})),Ek=e=>Nk(void 0,void 0,void 0,(function*(){const t={},i={cryptoFunctionServiceOptions:{win:self},encryptServiceOptions:{logMacFailures:!0},logServiceOptions:{isDev:!1},platformUtilsServiceOptions:{clipboardWriteCallback:()=>Promise.resolve(),biometricCallback:()=>Promise.resolve(!1),win:self},stateServiceOptions:{stateFactory:new Ns(Rs,tS)},apiServiceOptions:{logoutCallback:()=>Promise.resolve()},keyConnectorServiceOptions:{logoutCallback:()=>Promise.resolve()},i18nServiceOptions:{systemLanguage:xg.getUILanguage()}},n=yield cm(t,i),r=yield qS(t,i),s=yield nP(t,i);if((yield r.getAuthStatus())Nk(void 0,void 0,void 0,(function*(){const t=new Ns(Rs,tS),i={},n={cryptoFunctionServiceOptions:{win:self},encryptServiceOptions:{logMacFailures:!1},logServiceOptions:{isDev:!1},platformUtilsServiceOptions:{biometricCallback:()=>Promise.resolve(!0),clipboardWriteCallback:()=>Promise.resolve(),win:self},stateServiceOptions:{stateFactory:t},autofillSettingsServiceOptions:{stateFactory:XS}};new yP(yield Wb(i,n),yield XS(i,n)).generatePasswordToClipboard(e)}));var Mk=function(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((n=n.apply(e,t||[])).next())}))};const Kk=Tk([PP.windowsOnFocusChangedListener,Nb.windowsOnFocusChangedListener]),Lk=Tk([PP.tabsOnActivatedListener,Nb.tabsOnActivatedListener]),zk=Tk([PP.tabsOnReplacedListener,Nb.tabsOnReplacedListener]),Vk=Tk([PP.tabsOnUpdatedListener,Nb.tabsOnUpdatedListener]),Bk=wP.onClickedListener,_k=Tk([PP.messageListener,Nb.messageListener,wP.messageListener]);if(xg.isManifestVersion(3))chrome.commands.onCommand.addListener(Rk),chrome.runtime.onInstalled.addListener((function(e){return Mk(this,void 0,void 0,(function*(){const t={encryptServiceOptions:{logMacFailures:!1},cryptoFunctionServiceOptions:{win:self},logServiceOptions:{isDev:!1},stateServiceOptions:{stateFactory:new Ns(Rs,tS)}},i=yield Dw({},t);setTimeout((()=>Mk(this,void 0,void 0,(function*(){null!=e.reason&&e.reason===chrome.runtime.OnInstalledReason.INSTALL&&(xg.createNewTab("https://bitwarden.com/browser-start/"),(yield i.hasManagedEnvironment())&&(yield i.setUrlsToManagedEnvironment()))}))),100)}))})),chrome.alarms.onAlarm.addListener(Ik),function(e){const t=6e4/e;let i=Date.now()+t;for(let n=0;n{_k(e,t)}));else{(window.bitwardenMain=new Dk).bootstrap().then((()=>{}))}},62082:()=>{},10731:()=>{},69693:()=>{},83613:()=>{},37275:()=>{},36039:()=>{},12442:()=>{},95942:()=>{},53260:()=>{}},r={};function s(e){var t=r[e];if(void 0!==t)return t.exports;var i=r[e]={id:e,loaded:!1,exports:{}};return n[e].call(i.exports,i,i.exports,s),i.loaded=!0,i.exports}s.m=n,s.c=r,e=[],s.O=(t,i,n,r)=>{if(!i){var o=1/0;for(d=0;d=r)&&Object.keys(s.O).every((e=>s.O[e](i[l])))?i.splice(l--,1):(a=!1,r0&&e[d-1][2]>r;d--)e[d]=e[d-1];e[d]=[i,n,r]},i=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,s.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var r=Object.create(null);s.r(r);var o={};t=t||[null,i({}),i([]),i(i)];for(var a=2&n&&e;"object"==typeof a&&!~t.indexOf(a);a=i(a))Object.getOwnPropertyNames(a).forEach((t=>o[t]=()=>e[t]));return o.default=()=>e,s.d(r,o),r},s.d=(e,t)=>{for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},s.u=e=>"encrypt-worker.js",s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),(()=>{var e;s.g.importScripts&&(e=s.g.location+"");var t=s.g.document;if(!e&&t&&(t.currentScript&&(e=t.currentScript.src),!e)){var i=t.getElementsByTagName("script");if(i.length)for(var n=i.length-1;n>-1&&!e;)e=i[n--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),s.p=e})(),(()=>{s.b=document.baseURI||self.location.href;var e={352:0};s.O.j=t=>0===e[t];var t=(t,i)=>{var n,r,[o,a,l]=i,c=0;if(o.some((t=>0!==e[t]))){for(n in a)s.o(a,n)&&(s.m[n]=a[n]);if(l)var d=l(s)}for(t&&t(i);cs(61263)));o=s.O(o)})(); //# sourceMappingURL=background.js.map