@authress/login 2.2.251 → 2.3.255

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,9 @@
1
1
  # Change log
2
2
  This is the changelog for [Authress Login](readme.md).
3
3
 
4
+ ## 2.3 ##
5
+ * Add MFA device methods.
6
+
4
7
  ## 2.2 ##
5
8
  * Automatically retry on network connection issues.
6
9
  * Handle expired requests on code exchanges.
@@ -1,2 +1,2 @@
1
- /*! Authress Login SDK 2.2.251 | Author - Authress Developers | License information can be found at https://github.com/Authress/login-sdk.js */
2
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.authress=t():e.authress=t()}(this,(()=>(()=>{var e,t,n={219:e=>{function t(e){return String.fromCharCode(parseInt(e.slice(1),16))}function n(e){return`%${`00${e.charCodeAt(0).toString(16)}`.slice(-2)}`}e.exports.decode=function(e){return function(e){return decodeURIComponent(Array.from(atob(e),n).join(""))}(e.replace(/-/g,"+").replace(/_/g,"/"))},e.exports.encode=function(e){return e&&"object"==typeof e?btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,""):function(e){return btoa(encodeURIComponent(e).replace(/%[0-9A-F]{2}/g,t))}(e).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}},99:(e,t,n)=>{const o=n(219),r=n(215),i="ExtensionRequestNonce";let a=null;e.exports=class{constructor(e,t){if(this.extensionId=t,!e)throw Error('Missing required property "authressCustomDomain" in ExtensionClient constructor. The Custom Authress Domain Host is required.');if(!t)throw Error('Missing required property "extensionId" in ExtensionClient constructor. The extension is required for selecting the correct login method.');this.authressCustomDomain=`https://${e.replace(/^(https?:\/+)/,"")}`,this.accessToken=null,window.onload=async()=>{await this.requestToken({silent:!0})}}async getUserIdentity(){const e=await this.accessToken&&r.decode(this.accessToken);return e?1e3*e.exp<Date.now()?(this.accessToken=null,null):e:null}async getTokenResponse(){return await this.getUserIdentity()?{accessToken:this.accessToken}:null}requestToken(e={code:null,silent:!1}){if(a)return a=a.catch((()=>{})).then((()=>this.requestTokenContinuation(e)));const t=this.requestTokenContinuation(e);return t.catch((()=>{})),a=t}async requestTokenContinuation(e={code:null,silent:!1}){const t=e&&e.code||new URLSearchParams(window.location.search).get("code");if(!t){if(!e||!e.silent){const e=Error("OAuth Authorization code is required");throw e.code="InvalidAuthorizationCode",e}return this.getTokenResponse()}const n=new URL(this.authressCustomDomain);n.pathname="/api/authentication/oauth/tokens";const{codeVerifier:o,redirectUrl:r}=JSON.parse(localStorage.getItem(i)||"{}"),a=await fetch(n.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code_verifier:o,code:t,grant_type:"authorization_code",client_id:this.extensionId,redirect_uri:r})}),s=await a.json();this.accessToken=s.access_token;const c=new URL(window.location);return c.searchParams.delete("code"),c.searchParams.delete("iss"),c.searchParams.delete("nonce"),c.searchParams.delete("expires_in"),c.searchParams.delete("access_token"),c.searchParams.delete("id_token"),history.replaceState({},void 0,c.toString()),this.getTokenResponse()}async login(e){const t=await this.getTokenResponse();if(t)return t;const n=await this.requestToken({silent:!0});if(n)return n;const r=new URL(this.authressCustomDomain),a=o.encode((window.crypto||window.msCrypto).getRandomValues(new Uint32Array(16)).toString()),s=await(window.crypto||window.msCrypto).subtle.digest("SHA-256",(new TextEncoder).encode(a)),c=o.encode(s),d=e||window.location.href;return localStorage.setItem(i,JSON.stringify({codeVerifier:a,redirectUrl:d})),r.searchParams.set("client_id",this.extensionId),r.searchParams.set("code_challenge",c),r.searchParams.set("code_challenge_method","S256"),r.searchParams.set("redirect_uri",d),window.location.assign(r.toString()),await new Promise((e=>setTimeout(e,5e3))),null}}},965:e=>{const t={"Content-Type":"application/json"},n=new Set(["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed"]);function o(e){return e&&e.message&&n.has(e.message)}async function r(e){let t=null;for(let n=0;n<5;n++)try{return await e()}catch(e){if(e.retryCount=n,t=e,o(e)||"Network Error"===e.message||"ERR_NETWORK"===e.code||!e.status||e.status>=500){t.isNetworkError=!0,await new Promise((e=>setTimeout(e,10*2**n)));continue}throw e}throw t}e.exports=class{constructor(e,t){if(!e)throw Error("Custom Authress Domain Host is required");const n=t||{debug(){},warn(){},critical(){}};this.logger=n;const o=new URL(`https://${e.replace(/^(https?:\/+)/,"")}`);this.loginUrl=`${o.origin}/api`}get(e,t,n){return r((()=>this.fetchWrapper("GET",e,null,n,t)))}delete(e,t,n){return r((()=>this.fetchWrapper("DELETE",e,null,n,t)))}post(e,t,n,o){return r((()=>this.fetchWrapper("POST",e,n,o,t)))}put(e,t,n,o){return r((()=>this.fetchWrapper("PUT",e,n,o,t)))}patch(e,t,n,o){return r((()=>this.fetchWrapper("PATCH",e,n,o,t)))}async fetchWrapper(e,n,o,r,i){const a=`${this.loginUrl}${n.toString()}`,s=e.toUpperCase(),c=Object.assign({},t,r);try{this.logger.debug({title:"HttpClient Request",method:s,url:a});const e={method:s,headers:c};o&&(e.body=JSON.stringify(o)),"localhost"!==window.location.hostname&&i&&(e.credentials="include");const t=await fetch(a,e);if(!t.ok)throw t;return{url:a,headers:t.headers,status:t.status,data:await t.json()}}catch(e){const t="function"==typeof e.json?await e.json().catch((e=>e)):e,n=t.stack&&t.stack.match(/chrome-extension:[/][/](\w+)[/]/);if(n){this.logger.debug({title:`Fetch failed due to a browser extension - ${s} - ${a}`,method:s,url:a,data:o,headers:c,error:e,resolvedError:t,extensionErrorId:n});const r=new Error(`Extension Error ID: ${n}`);throw r.code="BROWSER_EXTENSION_ERROR",r}let r="HttpClient Response Error";throw e?e.response&&401===e.response.status&&(r="HttpClient Response Error due to invalid token"):r="HttpClient Response Error - Unknown error occurred",this.logger.warn({title:r,online:navigator.onLine,method:s,url:a,data:o,headers:c,error:e,resolvedError:t}),e}}}},125:(e,t,n)=>{const o=n(489),r=n(802),i=n(965),a=n(215),s=n(429);let c,d=new Promise((e=>c=e)),l=null;const u="AuthenticationRequestNonce";const h=n(99);e.exports={LoginClient:class{constructor(e,t){this.settings=Object.assign({applicationId:"app_default"},e),this.logger=t||console;const n=this.settings.authressLoginHostUrl||this.settings.authenticationServiceUrl||"";if(!n)throw Error('Missing required property "authressLoginHostUrl" in LoginClient constructor. Custom Authress Domain Host is required.');this.hostUrl=`https://${n.replace(/^(https?:\/+)/,"")}`,this.httpClient=new i(this.hostUrl,this.logger),this.lastSessionCheck=0,this.enableCredentials=this.getMatchingDomainInfo(this.hostUrl,"undefined"!=typeof window?window:void 0),e.skipBackgroundCredentialsCheck||(window.onload=async()=>{await this.userSessionExists(!0)})}isLocalHost(){return"undefined"!=typeof window&&window.location&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname)}getMatchingDomainInfo(e,t){const n=new URL(e);if(this.isLocalHost())return!1;if(void 0===t)return!1;if("https:"!==t.location.protocol)return!1;const o=n.host.toLowerCase().split(".").reverse(),i=t.location.host.toLowerCase().split(".").reverse();let a=[];for(let e of o){const t=r(i,a.length+1).join(".");if(a.concat(e).join(".")!==t)break;a.push(e)}return a.length===o.length&&a.length===i.length||a.length>1}getUserIdentity(){const e=s.getUserCookie(),t=a.decodeOrParse(e);if(t){const n=t.exp?new Date(1e3*t.exp):new Date(Date.now()+864e5);return s.set(e,n),t.userId=t.sub,t}const n=s.get(),o=a.decodeOrParse(n);return o?(o.userId=o.sub,o):null}async getConnectionCredentials(){await this.waitForUserSession();try{const e=await this.ensureToken();return(await this.httpClient.get("/session/credentials",this.enableCredentials,{Authorization:e&&`Bearer ${e}`})).data}catch(e){return null}}async waitForUserSession(){try{return await d,!0}catch(e){return!1}}userSessionExists(e){return l?Date.now()-this.lastSessionCheck<50?l:(this.lastSessionCheck=Date.now(),l=l.catch((()=>{})).then((()=>this.userSessionContinuation(e)))):(this.lastSessionCheck=Date.now(),l=this.userSessionContinuation(e))}async userSessionContinuation(e){const t=new URLSearchParams(window.location.search),n=new URL(window.location);let r={};try{r=JSON.parse(localStorage.getItem(u)||"{}"),localStorage.removeItem(u),Object.hasOwnProperty.call(r,"enableCredentials")&&(this.enableCredentials=r.enableCredentials)}catch(e){this.logger&&this.logger.debug&&this.logger.debug({title:"LocalStorage failed in Browser",error:e})}if(t.get("state")&&"oauthLogin"===t.get("flow"))return!1;if(r.nonce&&t.get("code")&&(n.searchParams.delete("nonce"),n.searchParams.delete("iss"),n.searchParams.delete("code"),history.replaceState({},void 0,n.toString()),r.nonce===t.get("nonce"))){const e="cookie"===t.get("code")?o.parse(document.cookie)["auth-code"]:t.get("code"),n={grant_type:"authorization_code",redirect_uri:r.redirectUrl,client_id:this.settings.applicationId,code:e,code_verifier:r.codeVerifier};try{const e=await this.httpClient.post(`/authentication/${r.nonce}/tokens`,this.enableCredentials,n),t=a.decode(e.data.id_token),i=t.exp&&new Date(1e3*t.exp)||e.data.expires_in&&new Date(Date.now()+1e3*e.data.expires_in);return document.cookie=o.serialize("authorization",e.data.access_token||"",{expires:i,path:"/",sameSite:"strict"}),s.set(e.data.id_token,i),c(),!0}catch(e){if(e.data&&"invalid_request"===e.data.error)return this.logger&&this.logger.log({title:"Failed exchange authentication response for a token.",error:e}),!1;throw e.data||e}}if(this.isLocalHost()&&t.get("nonce")&&t.get("access_token")&&(n.searchParams.delete("iss"),n.searchParams.delete("nonce"),n.searchParams.delete("expires_in"),n.searchParams.delete("access_token"),n.searchParams.delete("id_token"),history.replaceState({},void 0,n.toString()),!r.nonce||r.nonce===t.get("nonce"))){const e=a.decode(t.get("id_token")),n=e.exp&&new Date(1e3*e.exp)||Number(t.get("expires_in"))&&new Date(Date.now()+1e3*Number(t.get("expires_in")));return document.cookie=o.serialize("authorization",t.get("access_token")||"",{expires:n,path:"/",sameSite:"strict"}),s.set(t.get("id_token"),n),c(),!0}if(this.getUserIdentity())return c(),!0;if(!this.isLocalHost()&&!e){try{const e=await this.httpClient.patch("/session",this.enableCredentials,{});if(e.data.access_token){const t=a.decode(e.data.id_token),n=t.exp&&new Date(1e3*t.exp)||e.data.expires_in&&new Date(Date.now()+1e3*e.data.expires_in);document.cookie=o.serialize("authorization",e.data.access_token||"",{expires:n,path:"/",sameSite:"strict"}),s.set(e.data.id_token,n)}}catch(e){400!==e.status&&404!==e.status&&409!==e.status&&this.logger&&this.logger.log({title:"Failed attempting to check if the user has an existing authentication session",error:e})}if(this.getUserIdentity())return c(),!0}return!1}async updateExtensionAuthenticationRequest({state:e,connectionId:t,tenantLookupIdentifier:n,connectionProperties:o}){if(!t&&!n){const e=Error("connectionId or tenantLookupIdentifier must be specified");throw e.code="InvalidConnection",e}const r=new URLSearchParams(window.location.search),i=e||r.get("state");if(!i){const e=Error("The `state` parameters must be specified to update this authentication request");throw e.code="InvalidAuthenticationRequest",e}try{const e=await this.httpClient.patch(`/authentication/${i}`,!0,{connectionId:t,tenantLookupIdentifier:n,connectionProperties:o});window.location.assign(e.data.authenticationUrl)}catch(e){if(e.status>=400&&e.status<500){const t=Error(e.data.title||e.data.errorCode);throw t.code=e.data.errorCode,t}throw e.data||e}await new Promise((e=>setTimeout(e,5e3)))}async unlinkIdentity(e){if(!e){const e=Error("connectionId must be specified");throw e.code="InvalidConnection",e}if(!this.getUserIdentity()){const e=Error("User must be logged into to unlink an account.");throw e.code="NotLoggedIn",e}let t;try{t=await this.ensureToken({timeoutInMillis:100})}catch(e){if("TokenTimeout"===e.code){const e=Error("User must be logged into an existing account before linking a second account.");throw e.code="NotLoggedIn",e}}const n=this.enableCredentials&&!this.isLocalHost()?{}:{Authorization:`Bearer ${t}`};try{await this.httpClient.delete(`/identities/${encodeURIComponent(e)}`,this.enableCredentials,n)}catch(e){if(e.status>=400&&e.status<500){const t=Error(e.data.title||e.data.errorCode);throw t.code=e.data.errorCode,t}throw e.data||e}}async linkIdentity({connectionId:e,tenantLookupIdentifier:t,redirectUrl:n,connectionProperties:o}){if(!e&&!t){const e=Error("connectionId or tenantLookupIdentifier must be specified");throw e.code="InvalidConnection",e}if(!this.getUserIdentity()){const e=Error("User must be logged into an existing account before linking a second account.");throw e.code="NotLoggedIn",e}let r;try{r=await this.ensureToken({timeoutInMillis:100})}catch(e){if("TokenTimeout"===e.code){const e=Error("User must be logged into an existing account before linking a second account.");throw e.code="NotLoggedIn",e}}const{codeChallenge:i}=await a.getAuthCodes();try{const a=n&&new URL(n).toString()||window.location.href,s=this.enableCredentials&&!this.isLocalHost()?{}:{Authorization:`Bearer ${r}`},c=await this.httpClient.post("/authentication",this.enableCredentials,{linkIdentity:!0,redirectUrl:a,codeChallengeMethod:"S256",codeChallenge:i,connectionId:e,tenantLookupIdentifier:t,connectionProperties:o,applicationId:this.settings.applicationId},s);window.location.assign(c.data.authenticationUrl)}catch(e){if(e.status>=400&&e.status<500){const t=Error(e.data.title||e.data.errorCode);throw t.code=e.data.errorCode,t}throw e}await new Promise((e=>setTimeout(e,5e3)))}async authenticate(e={}){const{connectionId:t,tenantLookupIdentifier:n,inviteId:o,redirectUrl:r,force:i,responseLocation:c,flowType:d,connectionProperties:l,openType:h,multiAccount:p,clearUserDataBeforeLogin:f}=e||{};if(c&&"cookie"!==c&&"query"!==c&&"none"!==c){const e=Error("Authentication response location is not valid");throw e.code="InvalidResponseLocation",e}if(!i&&!p&&await this.userSessionExists())return!0;const{codeVerifier:g,codeChallenge:w}=await a.getAuthCodes();try{const e=r&&new URL(r).toString()||window.location.href;!1!==f&&s.clear();const i=await this.httpClient.post("/authentication",!1,{redirectUrl:e,codeChallengeMethod:"S256",codeChallenge:w,connectionId:t,tenantLookupIdentifier:n,inviteId:o,connectionProperties:l,applicationId:this.settings.applicationId,responseLocation:c,flowType:d,multiAccount:p});if(localStorage.setItem(u,JSON.stringify({nonce:i.data.authenticationRequestId,codeVerifier:g,lastConnectionId:t,tenantLookupIdentifier:n,redirectUrl:e,enableCredentials:i.data.enableCredentials,multiAccount:p})),"tab"===h){const e=window.open(i.data.authenticationUrl,"_blank");e&&!e.closed&&void 0!==e.closed||window.location.assign(i.data.authenticationUrl)}else window.location.assign(i.data.authenticationUrl)}catch(e){if(e.status>=400&&e.status<500){const t=Error(e.data.title||e.data.errorCode);throw t.code=e.data.errorCode,t}throw e.data||e}return await new Promise((e=>setTimeout(e,5e3))),!1}async ensureToken(e){await this.userSessionExists();const t=Object.assign({timeoutInMillis:5e3},e||{}),n=this.waitForUserSession(),r=new Promise(((e,n)=>setTimeout(n,t.timeoutInMillis||0)));try{await Promise.race([n,r])}catch(e){const t=Error("No token retrieved after timeout");throw t.code="TokenTimeout",t}const i=o.parse(document.cookie);return"undefined"!==i.authorization&&i.authorization}async logout(e){if(s.clear(),d=new Promise((e=>c=e)),this.enableCredentials)try{return await this.httpClient.delete("/session",this.enableCredentials),void(e&&e!==window.location.href&&window.location.assign(e))}catch(e){}const t=new URL("/logout",this.hostUrl);t.searchParams.set("redirect_uri",e||window.location.href),t.searchParams.set("client_id",this.settings.applicationId),window.location.assign(t.toString())}},ExtensionClient:h}},215:(e,t,n)=>{const o=n(219);e.exports=new class{decode(e){if(!e)return null;try{const t=JSON.parse(o.decode(e.split(".")[1]));return t.exp&&(t.exp=t.exp-10),t}catch(e){return null}}decodeOrParse(e){if(!e)return null;if("object"==typeof e)return e;try{return JSON.parse(e)}catch(t){return this.decode(e)}}decodeFull(e){if(!e)return null;try{const t=JSON.parse(o.decode(e.split(".")[0])),n=JSON.parse(o.decode(e.split(".")[1]));return n.exp&&(n.exp=n.exp-10),{header:t,payload:n}}catch(e){return null}}async getAuthCodes(){const e=o.encode((window.crypto||window.msCrypto).getRandomValues(new Uint32Array(16)).toString()),t=await(window.crypto||window.msCrypto).subtle.digest("SHA-256",(new TextEncoder).encode(e));return{codeVerifier:e,codeChallenge:o.encode(t)}}}},429:(e,t,n)=>{const o=n(489),r="AuthenticationCredentialsStorage";e.exports=new class{getUserCookie(){return document.cookie.split(";").filter((e=>"user"===e.split("=")[0].trim())).map((e=>e.replace(/^user=/,""))).find((e=>e&&e.trim()))||null}set(e,t){try{const n=o.parse(document.cookie);localStorage.setItem(r,JSON.stringify({idToken:e,expiry:t&&t.getTime(),jsCookies:!!n.authorization})),this.clearCookies("user")}catch(e){console.debug("LocalStorage failed in Browser",e)}}get(){let e={};try{e=o.parse(document.cookie)}catch(e){console.debug("CookieManagement failed in Browser",e)}try{const{idToken:t,expiry:n,jsCookies:o}=JSON.parse(localStorage.getItem(r)||"{}");return t?n<Date.now()||o&&!e.authorization?null:t:this.getUserCookie()}catch(e){return console.debug("LocalStorage failed in Browser",e),this.getUserCookie()}}delete(){try{localStorage.removeItem(r)}catch(e){console.debug("LocalStorage failed in Browser",e)}try{this.clearCookies("user")}catch(e){console.debug("CookieManagement failed in Browser",e)}}clear(){this.clearCookies(),this.delete()}clearCookies(e){if("undefined"==typeof window)return;const t=document.cookie.split("; ");for(const n of t){if(!["user","authorization","auth-code"].includes(n.split("=")[0])||e&&n.split("=")[0]!==e)continue;const t=window.location.hostname.split("."),o=[...Array(t.length-1)].map(((e,n)=>t.reverse().slice(0,n+2).reverse().join("."))).map((e=>[e,`.${e}`])).flat(1).concat(null);"localhost"===window.location.hostname&&o.push("localhost");for(const e of o){const t=e?`domain=${e};`:"",o=`${encodeURIComponent(n.split(";")[0].split("=")[0])}=; expires=Thu, 01-Jan-1970 00:00:01 GMT; ${t} SameSite=Strict; path=`;document.cookie=`${o}/`;const r=location.pathname.split("/");for(;r.length>0;)document.cookie=o+r.join("/"),r.pop()}}}}},489:(e,t)=>{"use strict";t.parse=function(e,t){if("string"!=typeof e)throw new TypeError("argument str must be a string");var n={},o=(t||{}).decode||r,i=0;for(;i<e.length;){var s=e.indexOf("=",i);if(-1===s)break;var c=e.indexOf(";",i);if(-1===c)c=e.length;else if(c<s){i=e.lastIndexOf(";",s-1)+1;continue}var d=e.slice(i,s).trim();if(void 0===n[d]){var l=e.slice(s+1,c).trim();34===l.charCodeAt(0)&&(l=l.slice(1,-1)),n[d]=a(l,o)}i=c+1}return n},t.serialize=function(e,t,r){var a=r||{},s=a.encode||i;if("function"!=typeof s)throw new TypeError("option encode is invalid");if(!o.test(e))throw new TypeError("argument name is invalid");var c=s(t);if(c&&!o.test(c))throw new TypeError("argument val is invalid");var d=e+"="+c;if(null!=a.maxAge){var l=a.maxAge-0;if(isNaN(l)||!isFinite(l))throw new TypeError("option maxAge is invalid");d+="; Max-Age="+Math.floor(l)}if(a.domain){if(!o.test(a.domain))throw new TypeError("option domain is invalid");d+="; Domain="+a.domain}if(a.path){if(!o.test(a.path))throw new TypeError("option path is invalid");d+="; Path="+a.path}if(a.expires){var u=a.expires;if(!function(e){return"[object Date]"===n.call(e)||e instanceof Date}(u)||isNaN(u.valueOf()))throw new TypeError("option expires is invalid");d+="; Expires="+u.toUTCString()}a.httpOnly&&(d+="; HttpOnly");a.secure&&(d+="; Secure");if(a.priority){switch("string"==typeof a.priority?a.priority.toLowerCase():a.priority){case"low":d+="; Priority=Low";break;case"medium":d+="; Priority=Medium";break;case"high":d+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(a.sameSite){switch("string"==typeof a.sameSite?a.sameSite.toLowerCase():a.sameSite){case!0:d+="; SameSite=Strict";break;case"lax":d+="; SameSite=Lax";break;case"strict":d+="; SameSite=Strict";break;case"none":d+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return d};var n=Object.prototype.toString,o=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function r(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function i(e){return encodeURIComponent(e)}function a(e,t){try{return t(e)}catch(t){return e}}},802:e=>{var t=1/0,n=17976931348623157e292,o=NaN,r="[object Symbol]",i=/^\s+|\s+$/g,a=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,c=/^0o[0-7]+$/i,d=parseInt,l=Object.prototype.toString;function u(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=function(e,h,p){return e&&e.length?function(e,t,n){var o=-1,r=e.length;t<0&&(t=-t>r?0:r+t),(n=n>r?r:n)<0&&(n+=r),r=t>n?0:n-t>>>0,t>>>=0;for(var i=Array(r);++o<r;)i[o]=e[o+t];return i}(e,0,(h=p||void 0===h?1:(f=function(e){return e?(e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&l.call(e)==r}(e))return o;if(u(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=u(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(i,"");var n=s.test(e);return n||c.test(e)?d(e.slice(2),n?2:8):a.test(e)?o:+e}(e))===t||e===-t?(e<0?-1:1)*n:e==e?e:0:0===e?e:0}(h),g=f%1,f==f?g?f-g:f:0))<0?0:h):[];var f,g}}},o={};function r(e){var t=o[e];if(void 0!==t){if(void 0!==t.error)throw t.error;return t.exports}var i=o[e]={exports:{}};try{var a={id:e,module:i,factory:n[e],require:r};r.i.forEach((function(e){e(a)})),i=a.module,a.factory.call(i.exports,i,i.exports,a.require)}catch(e){throw i.error=e,e}return i.exports}return r.m=n,r.c=o,r.i=[],r.hu=e=>e+"."+r.h()+".hot-update.js",r.hmrF=()=>"main."+r.h()+".hot-update.json",r.h=()=>"fbd63b733ea504d5473f",r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),e={},t="authress:",r.l=(n,o,i,a)=>{if(e[n])e[n].push(o);else{var s,c;if(void 0!==i)for(var d=document.getElementsByTagName("script"),l=0;l<d.length;l++){var u=d[l];if(u.getAttribute("src")==n||u.getAttribute("data-webpack")==t+i){s=u;break}}s||(c=!0,(s=document.createElement("script")).charset="utf-8",s.timeout=120,r.nc&&s.setAttribute("nonce",r.nc),s.setAttribute("data-webpack",t+i),s.src=n),e[n]=[o];var h=(t,o)=>{s.onerror=s.onload=null,clearTimeout(p);var r=e[n];if(delete e[n],s.parentNode&&s.parentNode.removeChild(s),r&&r.forEach((e=>e(o))),t)return t(o)},p=setTimeout(h.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=h.bind(null,s.onerror),s.onload=h.bind(null,s.onload),c&&document.head.appendChild(s)}},(()=>{var e,t,n,o={},i=r.c,a=[],s=[],c="idle",d=0,l=[];function u(e){c=e;for(var t=[],n=0;n<s.length;n++)t[n]=s[n].call(null,e);return Promise.all(t)}function h(){0==--d&&u("ready").then((function(){if(0===d){var e=l;l=[];for(var t=0;t<e.length;t++)e[t]()}}))}function p(e){if("idle"!==c)throw new Error("check() is only allowed in idle status");return u("check").then(r.hmrM).then((function(n){return n?u("prepare").then((function(){var o=[];return t=[],Promise.all(Object.keys(r.hmrC).reduce((function(e,i){return r.hmrC[i](n.c,n.r,n.m,e,t,o),e}),[])).then((function(){return t=function(){return e?g(e):u("ready").then((function(){return o}))},0===d?t():new Promise((function(e){l.push((function(){e(t())}))}));var t}))})):u(w()?"ready":"idle").then((function(){return null}))}))}function f(e){return"ready"!==c?Promise.resolve().then((function(){throw new Error("apply() is only allowed in ready status (state: "+c+")")})):g(e)}function g(e){e=e||{},w();var o=t.map((function(t){return t(e)}));t=void 0;var r=o.map((function(e){return e.error})).filter(Boolean);if(r.length>0)return u("abort").then((function(){throw r[0]}));var i=u("dispose");o.forEach((function(e){e.dispose&&e.dispose()}));var a,s=u("apply"),c=function(e){a||(a=e)},d=[];return o.forEach((function(e){if(e.apply){var t=e.apply(c);if(t)for(var n=0;n<t.length;n++)d.push(t[n])}})),Promise.all([i,s]).then((function(){return a?u("fail").then((function(){throw a})):n?g(e).then((function(e){return d.forEach((function(t){e.indexOf(t)<0&&e.push(t)})),e})):u("idle").then((function(){return d}))}))}function w(){if(n)return t||(t=[]),Object.keys(r.hmrI).forEach((function(e){n.forEach((function(n){r.hmrI[e](n,t)}))})),n=void 0,!0}r.hmrD=o,r.i.push((function(l){var g,w,m,y,v=l.module,k=function(t,n){var o=i[n];if(!o)return t;var r=function(r){if(o.hot.active){if(i[r]){var s=i[r].parents;-1===s.indexOf(n)&&s.push(n)}else a=[n],e=r;-1===o.children.indexOf(r)&&o.children.push(r)}else console.warn("[HMR] unexpected require("+r+") from disposed module "+n),a=[];return t(r)},s=function(e){return{configurable:!0,enumerable:!0,get:function(){return t[e]},set:function(n){t[e]=n}}};for(var l in t)Object.prototype.hasOwnProperty.call(t,l)&&"e"!==l&&Object.defineProperty(r,l,s(l));return r.e=function(e){return function(e){switch(c){case"ready":u("prepare");case"prepare":return d++,e.then(h,h),e;default:return e}}(t.e(e))},r}(l.require,l.id);v.hot=(g=l.id,w=v,y={_acceptedDependencies:{},_acceptedErrorHandlers:{},_declinedDependencies:{},_selfAccepted:!1,_selfDeclined:!1,_selfInvalidated:!1,_disposeHandlers:[],_main:m=e!==g,_requireSelf:function(){a=w.parents.slice(),e=m?void 0:g,r(g)},active:!0,accept:function(e,t,n){if(void 0===e)y._selfAccepted=!0;else if("function"==typeof e)y._selfAccepted=e;else if("object"==typeof e&&null!==e)for(var o=0;o<e.length;o++)y._acceptedDependencies[e[o]]=t||function(){},y._acceptedErrorHandlers[e[o]]=n;else y._acceptedDependencies[e]=t||function(){},y._acceptedErrorHandlers[e]=n},decline:function(e){if(void 0===e)y._selfDeclined=!0;else if("object"==typeof e&&null!==e)for(var t=0;t<e.length;t++)y._declinedDependencies[e[t]]=!0;else y._declinedDependencies[e]=!0},dispose:function(e){y._disposeHandlers.push(e)},addDisposeHandler:function(e){y._disposeHandlers.push(e)},removeDisposeHandler:function(e){var t=y._disposeHandlers.indexOf(e);t>=0&&y._disposeHandlers.splice(t,1)},invalidate:function(){switch(this._selfInvalidated=!0,c){case"idle":t=[],Object.keys(r.hmrI).forEach((function(e){r.hmrI[e](g,t)})),u("ready");break;case"ready":Object.keys(r.hmrI).forEach((function(e){r.hmrI[e](g,t)}));break;case"prepare":case"check":case"dispose":case"apply":(n=n||[]).push(g)}},check:p,apply:f,status:function(e){if(!e)return c;s.push(e)},addStatusHandler:function(e){s.push(e)},removeStatusHandler:function(e){var t=s.indexOf(e);t>=0&&s.splice(t,1)},data:o[g]},e=void 0,y),v.parents=a,v.children=[],a=[],l.require=k})),r.hmrC={},r.hmrI={}})(),r.p="",(()=>{var e,t,n,o,i,a=r.hmrS_jsonp=r.hmrS_jsonp||{179:0},s={};function c(t,n){return e=n,new Promise(((e,n)=>{s[t]=e;var o=r.p+r.hu(t),i=new Error;r.l(o,(e=>{if(s[t]){s[t]=void 0;var o=e&&("load"===e.type?"missing":e.type),r=e&&e.target&&e.target.src;i.message="Loading hot update chunk "+t+" failed.\n("+o+": "+r+")",i.name="ChunkLoadError",i.type=o,i.request=r,n(i)}}))}))}function d(e){function s(e){for(var t=[e],n={},o=t.map((function(e){return{chain:[e],id:e}}));o.length>0;){var i=o.pop(),a=i.id,s=i.chain,d=r.c[a];if(d&&(!d.hot._selfAccepted||d.hot._selfInvalidated)){if(d.hot._selfDeclined)return{type:"self-declined",chain:s,moduleId:a};if(d.hot._main)return{type:"unaccepted",chain:s,moduleId:a};for(var l=0;l<d.parents.length;l++){var u=d.parents[l],h=r.c[u];if(h){if(h.hot._declinedDependencies[a])return{type:"declined",chain:s.concat([u]),moduleId:a,parentId:u};-1===t.indexOf(u)&&(h.hot._acceptedDependencies[a]?(n[u]||(n[u]=[]),c(n[u],[a])):(delete n[u],t.push(u),o.push({chain:s.concat([u]),id:u})))}}}}return{type:"accepted",moduleId:e,outdatedModules:t,outdatedDependencies:n}}function c(e,t){for(var n=0;n<t.length;n++){var o=t[n];-1===e.indexOf(o)&&e.push(o)}}r.f&&delete r.f.jsonpHmr,t=void 0;var d={},l=[],u={},h=function(e){console.warn("[HMR] unexpected require("+e.id+") to disposed module")};for(var p in n)if(r.o(n,p)){var f,g=n[p],w=!1,m=!1,y=!1,v="";switch((f=g?s(p):{type:"disposed",moduleId:p}).chain&&(v="\nUpdate propagation: "+f.chain.join(" -> ")),f.type){case"self-declined":e.onDeclined&&e.onDeclined(f),e.ignoreDeclined||(w=new Error("Aborted because of self decline: "+f.moduleId+v));break;case"declined":e.onDeclined&&e.onDeclined(f),e.ignoreDeclined||(w=new Error("Aborted because of declined dependency: "+f.moduleId+" in "+f.parentId+v));break;case"unaccepted":e.onUnaccepted&&e.onUnaccepted(f),e.ignoreUnaccepted||(w=new Error("Aborted because "+p+" is not accepted"+v));break;case"accepted":e.onAccepted&&e.onAccepted(f),m=!0;break;case"disposed":e.onDisposed&&e.onDisposed(f),y=!0;break;default:throw new Error("Unexception type "+f.type)}if(w)return{error:w};if(m)for(p in u[p]=g,c(l,f.outdatedModules),f.outdatedDependencies)r.o(f.outdatedDependencies,p)&&(d[p]||(d[p]=[]),c(d[p],f.outdatedDependencies[p]));y&&(c(l,[f.moduleId]),u[p]=h)}n=void 0;for(var k,C=[],b=0;b<l.length;b++){var I=l[b],E=r.c[I];E&&(E.hot._selfAccepted||E.hot._main)&&u[I]!==h&&!E.hot._selfInvalidated&&C.push({module:I,require:E.hot._requireSelf,errorHandler:E.hot._selfAccepted})}return{dispose:function(){var e;o.forEach((function(e){delete a[e]})),o=void 0;for(var t,n=l.slice();n.length>0;){var i=n.pop(),s=r.c[i];if(s){var c={},u=s.hot._disposeHandlers;for(b=0;b<u.length;b++)u[b].call(null,c);for(r.hmrD[i]=c,s.hot.active=!1,delete r.c[i],delete d[i],b=0;b<s.children.length;b++){var h=r.c[s.children[b]];h&&((e=h.parents.indexOf(i))>=0&&h.parents.splice(e,1))}}}for(var p in d)if(r.o(d,p)&&(s=r.c[p]))for(k=d[p],b=0;b<k.length;b++)t=k[b],(e=s.children.indexOf(t))>=0&&s.children.splice(e,1)},apply:function(t){for(var n in u)r.o(u,n)&&(r.m[n]=u[n]);for(var o=0;o<i.length;o++)i[o](r);for(var a in d)if(r.o(d,a)){var s=r.c[a];if(s){k=d[a];for(var c=[],h=[],p=[],f=0;f<k.length;f++){var g=k[f],w=s.hot._acceptedDependencies[g],m=s.hot._acceptedErrorHandlers[g];if(w){if(-1!==c.indexOf(w))continue;c.push(w),h.push(m),p.push(g)}}for(var y=0;y<c.length;y++)try{c[y].call(null,k)}catch(n){if("function"==typeof h[y])try{h[y](n,{moduleId:a,dependencyId:p[y]})}catch(o){e.onErrored&&e.onErrored({type:"accept-error-handler-errored",moduleId:a,dependencyId:p[y],error:o,originalError:n}),e.ignoreErrored||(t(o),t(n))}else e.onErrored&&e.onErrored({type:"accept-errored",moduleId:a,dependencyId:p[y],error:n}),e.ignoreErrored||t(n)}}}for(var v=0;v<C.length;v++){var b=C[v],I=b.module;try{b.require(I)}catch(n){if("function"==typeof b.errorHandler)try{b.errorHandler(n,{moduleId:I,module:r.c[I]})}catch(o){e.onErrored&&e.onErrored({type:"self-accept-error-handler-errored",moduleId:I,error:o,originalError:n}),e.ignoreErrored||(t(o),t(n))}else e.onErrored&&e.onErrored({type:"self-accept-errored",moduleId:I,error:n}),e.ignoreErrored||t(n)}}return l}}}this.webpackHotUpdateauthress=(t,o,a)=>{for(var c in o)r.o(o,c)&&(n[c]=o[c],e&&e.push(c));a&&i.push(a),s[t]&&(s[t](),s[t]=void 0)},r.hmrI.jsonp=function(e,t){n||(n={},i=[],o=[],t.push(d)),r.o(n,e)||(n[e]=r.m[e])},r.hmrC.jsonp=function(e,s,l,u,h,p){h.push(d),t={},o=s,n=l.reduce((function(e,t){return e[t]=!1,e}),{}),i=[],e.forEach((function(e){r.o(a,e)&&void 0!==a[e]?(u.push(c(e,p)),t[e]=!0):t[e]=!1})),r.f&&(r.f.jsonpHmr=function(e,n){t&&r.o(t,e)&&!t[e]&&(n.push(c(e)),t[e]=!0)})},r.hmrM=()=>{if("undefined"==typeof fetch)throw new Error("No browser support: need fetch API");return fetch(r.p+r.hmrF()).then((e=>{if(404!==e.status){if(!e.ok)throw new Error("Failed to fetch update manifest "+e.statusText);return e.json()}}))}})(),r(125)})()));
1
+ /*! Authress Login SDK 2.3.255 | Author - Authress Developers | License information can be found at https://github.com/Authress/login-sdk.js */
2
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.authress=t():e.authress=t()}(this,(()=>(()=>{var e,t,n={219:e=>{function t(e){return String.fromCharCode(parseInt(e.slice(1),16))}function n(e){return`%${`00${e.charCodeAt(0).toString(16)}`.slice(-2)}`}e.exports.decode=function(e){return function(e){return decodeURIComponent(Array.from(atob(e),n).join(""))}(e.replace(/-/g,"+").replace(/_/g,"/"))},e.exports.encode=function(e){return e&&"object"==typeof e?btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,""):function(e){return btoa(encodeURIComponent(e).replace(/%[0-9A-F]{2}/g,t))}(e).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}},99:(e,t,n)=>{const r=n(219),o=n(215),i="ExtensionRequestNonce";let a=null;e.exports=class{constructor(e,t){if(this.extensionId=t,!e)throw Error('Missing required property "authressCustomDomain" in ExtensionClient constructor. The Custom Authress Domain Host is required.');if(!t)throw Error('Missing required property "extensionId" in ExtensionClient constructor. The extension is required for selecting the correct login method.');this.authressCustomDomain=`https://${e.replace(/^(https?:\/+)/,"")}`,this.accessToken=null,window.onload=async()=>{await this.requestToken({silent:!0})}}async getUserIdentity(){const e=await this.accessToken&&o.decode(this.accessToken);return e?1e3*e.exp<Date.now()?(this.accessToken=null,null):e:null}async getTokenResponse(){return await this.getUserIdentity()?{accessToken:this.accessToken}:null}requestToken(e={code:null,silent:!1}){if(a)return a=a.catch((()=>{})).then((()=>this.requestTokenContinuation(e)));const t=this.requestTokenContinuation(e);return t.catch((()=>{})),a=t}async requestTokenContinuation(e={code:null,silent:!1}){const t=e&&e.code||new URLSearchParams(window.location.search).get("code");if(!t){if(!e||!e.silent){const e=Error("OAuth Authorization code is required");throw e.code="InvalidAuthorizationCode",e}return this.getTokenResponse()}const n=new URL(this.authressCustomDomain);n.pathname="/api/authentication/oauth/tokens";const{codeVerifier:r,redirectUrl:o}=JSON.parse(localStorage.getItem(i)||"{}"),a=await fetch(n.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code_verifier:r,code:t,grant_type:"authorization_code",client_id:this.extensionId,redirect_uri:o})}),s=await a.json();this.accessToken=s.access_token;const c=new URL(window.location);return c.searchParams.delete("code"),c.searchParams.delete("iss"),c.searchParams.delete("nonce"),c.searchParams.delete("expires_in"),c.searchParams.delete("access_token"),c.searchParams.delete("id_token"),history.replaceState({},void 0,c.toString()),this.getTokenResponse()}async login(e){const t=await this.getTokenResponse();if(t)return t;const n=await this.requestToken({silent:!0});if(n)return n;const o=new URL(this.authressCustomDomain),a=r.encode((window.crypto||window.msCrypto).getRandomValues(new Uint32Array(16)).toString()),s=await(window.crypto||window.msCrypto).subtle.digest("SHA-256",(new TextEncoder).encode(a)),c=r.encode(s),d=e||window.location.href;return localStorage.setItem(i,JSON.stringify({codeVerifier:a,redirectUrl:d})),o.searchParams.set("client_id",this.extensionId),o.searchParams.set("code_challenge",c),o.searchParams.set("code_challenge_method","S256"),o.searchParams.set("redirect_uri",d),window.location.assign(o.toString()),await new Promise((e=>setTimeout(e,5e3))),null}}},965:e=>{const t={"Content-Type":"application/json"},n=new Set(["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed"]);function r(e){return e&&e.message&&n.has(e.message)}async function o(e){let t=null;for(let n=0;n<5;n++)try{return await e()}catch(e){if(e.retryCount=n,t=e,r(e)||"Network Error"===e.message||"ERR_NETWORK"===e.code||!e.status||e.status>=500){t.isNetworkError=!0,await new Promise((e=>setTimeout(e,10*2**n)));continue}throw e}throw t}e.exports=class{constructor(e,t){if(!e)throw Error("Custom Authress Domain Host is required");const n=t||{debug(){},warn(){},critical(){}};this.logger=n;const r=new URL(`https://${e.replace(/^(https?:\/+)/,"")}`);this.loginUrl=`${r.origin}/api`}get(e,t,n){return o((()=>this.fetchWrapper("GET",e,null,n,t)))}delete(e,t,n){return o((()=>this.fetchWrapper("DELETE",e,null,n,t)))}post(e,t,n,r){return o((()=>this.fetchWrapper("POST",e,n,r,t)))}put(e,t,n,r){return o((()=>this.fetchWrapper("PUT",e,n,r,t)))}patch(e,t,n,r){return o((()=>this.fetchWrapper("PATCH",e,n,r,t)))}async fetchWrapper(e,n,r,o,i){const a=`${this.loginUrl}${n.toString()}`,s=e.toUpperCase(),c=Object.assign({},t,o);try{this.logger.debug({title:"HttpClient Request",method:s,url:a});const e={method:s,headers:c};r&&(e.body=JSON.stringify(r)),"localhost"!==window.location.hostname&&i&&(e.credentials="include");const t=await fetch(a,e);if(!t.ok)throw t;return{url:a,headers:t.headers,status:t.status,data:await t.json()}}catch(e){const t="function"==typeof e.json?await e.json().catch((e=>e)):e,n=t.stack&&t.stack.match(/chrome-extension:[/][/](\w+)[/]/);if(n){this.logger.debug({title:`Fetch failed due to a browser extension - ${s} - ${a}`,method:s,url:a,data:r,headers:c,error:e,resolvedError:t,extensionErrorId:n});const o=new Error(`Extension Error ID: ${n}`);throw o.code="BROWSER_EXTENSION_ERROR",o}let o="HttpClient Response Error";throw e?e.response&&401===e.response.status&&(o="HttpClient Response Error due to invalid token"):o="HttpClient Response Error - Unknown error occurred",this.logger.warn({title:o,online:navigator.onLine,method:s,url:a,data:r,headers:c,error:e,resolvedError:t}),e}}}},125:(e,t,n)=>{const r=n(489),o=n(802),i=n(965),a=n(215),s=n(429);let c,d=new Promise((e=>c=e)),l=null;const u="AuthenticationRequestNonce";const h=n(99);e.exports={LoginClient:class{constructor(e,t){this.settings=Object.assign({applicationId:"app_default"},e),this.logger=t||console;const n=this.settings.authressLoginHostUrl||this.settings.authenticationServiceUrl||"";if(!n)throw Error('Missing required property "authressLoginHostUrl" in LoginClient constructor. Custom Authress Domain Host is required.');this.hostUrl=`https://${n.replace(/^(https?:\/+)/,"")}`,this.httpClient=new i(this.hostUrl,this.logger),this.lastSessionCheck=0,this.enableCredentials=this.getMatchingDomainInfo(this.hostUrl,"undefined"!=typeof window?window:void 0),e.skipBackgroundCredentialsCheck||(window.onload=async()=>{await this.userSessionExists(!0)})}isLocalHost(){return"undefined"!=typeof window&&window.location&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname)}getMatchingDomainInfo(e,t){const n=new URL(e);if(this.isLocalHost())return!1;if(void 0===t)return!1;if("https:"!==t.location.protocol)return!1;const r=n.host.toLowerCase().split(".").reverse(),i=t.location.host.toLowerCase().split(".").reverse();let a=[];for(let e of r){const t=o(i,a.length+1).join(".");if(a.concat(e).join(".")!==t)break;a.push(e)}return a.length===r.length&&a.length===i.length||a.length>1}getUserIdentity(){const e=s.getUserCookie(),t=a.decodeOrParse(e);if(t){const n=t.exp?new Date(1e3*t.exp):new Date(Date.now()+864e5);return s.set(e,n),t.userId=t.sub,t}const n=s.get(),r=a.decodeOrParse(n);return r?(r.userId=r.sub,r):null}async getConnectionCredentials(){await this.waitForUserSession();try{const e=await this.ensureToken();return(await this.httpClient.get("/session/credentials",this.enableCredentials,{Authorization:e&&`Bearer ${e}`})).data}catch(e){return null}}async getDevices(){await this.waitForUserSession();try{const e=await this.ensureToken();return(await this.httpClient.get("/session/devices",this.enableCredentials,{Authorization:e&&`Bearer ${e}`})).data.devices}catch(e){return[]}}async deleteDevice(e){await this.waitForUserSession();try{const t=await this.ensureToken();await this.httpClient.delete(`/session/devices/${encodeURIComponent(e)}`,this.enableCredentials,{Authorization:t&&`Bearer ${t}`})}catch(e){throw this.logger&&this.logger.log({title:"Failed to delete device",error:e}),e}}async openUserConfigurationScreen(e={redirectUrl:null,startPage:"PROFILE"}){const t=new URL("/profile",this.hostUrl);t.searchParams.set("client_id",this.settings.applicationId),t.searchParams.set("redirect_uri",e&&e.redirectUrl||window.location.href),window.location.assign(t.toString()),await Promise.resolve()}async registerDevice(e={name:""}){await this.waitForUserSession();const t=(await this.getUserIdentity()).sub,n={challenge:Uint8Array.from(t,(e=>e.charCodeAt(0))),rp:{name:"WebAuthN Login"},user:{id:Uint8Array.from(t,(e=>e.charCodeAt(0))),name:t,displayName:`Generated User ID: ${t}`},pubKeyCredParams:[{type:"public-key",alg:-36},{type:"public-key",alg:-35},{type:"public-key",alg:-7},{type:"public-key",alg:-259},{type:"public-key",alg:-258},{type:"public-key",alg:-257}],authenticatorSelection:{residentKey:"discouraged",requireResidentKey:!1,userVerification:"discouraged"},timeout:6e4,attestation:"direct"},r=await navigator.credentials.create({publicKey:n}),o={authenticatorAttachment:r.authenticatorAttachment,credentialId:r.id,type:r.type,userId:t,attestation:btoa(String.fromCharCode(...new Uint8Array(r.response.attestationObject))),client:JSON.parse(new TextDecoder("utf-8").decode(r.response.clientDataJSON))},i={name:e&&e.name,code:o,type:"WebAuthN"};try{const e=await this.ensureToken();return(await this.httpClient.post("/session/devices",this.enableCredentials,i,{Authorization:e&&`Bearer ${e}`})).data}catch(e){throw this.logger&&this.logger.log({title:"Failed to register new device",error:e}),e}}async waitForUserSession(){try{return await d,!0}catch(e){return!1}}userSessionExists(e){return l?Date.now()-this.lastSessionCheck<50?l:(this.lastSessionCheck=Date.now(),l=l.catch((()=>{})).then((()=>this.userSessionContinuation(e)))):(this.lastSessionCheck=Date.now(),l=this.userSessionContinuation(e))}async userSessionContinuation(e){const t=new URLSearchParams(window.location.search),n=new URL(window.location);let o={};try{o=JSON.parse(localStorage.getItem(u)||"{}"),localStorage.removeItem(u),Object.hasOwnProperty.call(o,"enableCredentials")&&(this.enableCredentials=o.enableCredentials)}catch(e){this.logger&&this.logger.debug&&this.logger.debug({title:"LocalStorage failed in Browser",error:e})}if(t.get("state")&&"oauthLogin"===t.get("flow"))return!1;if(o.nonce&&t.get("code")&&(n.searchParams.delete("nonce"),n.searchParams.delete("iss"),n.searchParams.delete("code"),history.replaceState({},void 0,n.toString()),o.nonce===t.get("nonce"))){const e="cookie"===t.get("code")?r.parse(document.cookie)["auth-code"]:t.get("code"),n={grant_type:"authorization_code",redirect_uri:o.redirectUrl,client_id:this.settings.applicationId,code:e,code_verifier:o.codeVerifier};try{const e=await this.httpClient.post(`/authentication/${o.nonce}/tokens`,this.enableCredentials,n),t=a.decode(e.data.id_token),i=t.exp&&new Date(1e3*t.exp)||e.data.expires_in&&new Date(Date.now()+1e3*e.data.expires_in);return document.cookie=r.serialize("authorization",e.data.access_token||"",{expires:i,path:"/",sameSite:"strict"}),s.set(e.data.id_token,i),c(),!0}catch(e){if(e.data&&"invalid_request"===e.data.error)return this.logger&&this.logger.log({title:"Failed exchange authentication response for a token.",error:e}),!1;throw e.data||e}}if(this.isLocalHost()&&t.get("nonce")&&t.get("access_token")&&(n.searchParams.delete("iss"),n.searchParams.delete("nonce"),n.searchParams.delete("expires_in"),n.searchParams.delete("access_token"),n.searchParams.delete("id_token"),history.replaceState({},void 0,n.toString()),!o.nonce||o.nonce===t.get("nonce"))){const e=a.decode(t.get("id_token")),n=e.exp&&new Date(1e3*e.exp)||Number(t.get("expires_in"))&&new Date(Date.now()+1e3*Number(t.get("expires_in")));return document.cookie=r.serialize("authorization",t.get("access_token")||"",{expires:n,path:"/",sameSite:"strict"}),s.set(t.get("id_token"),n),c(),!0}if(this.getUserIdentity())return c(),!0;if(!this.isLocalHost()&&!e){try{const e=await this.httpClient.patch("/session",this.enableCredentials,{});if(e.data.access_token){const t=a.decode(e.data.id_token),n=t.exp&&new Date(1e3*t.exp)||e.data.expires_in&&new Date(Date.now()+1e3*e.data.expires_in);document.cookie=r.serialize("authorization",e.data.access_token||"",{expires:n,path:"/",sameSite:"strict"}),s.set(e.data.id_token,n)}}catch(e){400!==e.status&&404!==e.status&&409!==e.status&&this.logger&&this.logger.log({title:"Failed attempting to check if the user has an existing authentication session",error:e})}if(this.getUserIdentity())return c(),!0}return!1}async updateExtensionAuthenticationRequest({state:e,connectionId:t,tenantLookupIdentifier:n,connectionProperties:r}){if(!t&&!n){const e=Error("connectionId or tenantLookupIdentifier must be specified");throw e.code="InvalidConnection",e}const o=new URLSearchParams(window.location.search),i=e||o.get("state");if(!i){const e=Error("The `state` parameters must be specified to update this authentication request");throw e.code="InvalidAuthenticationRequest",e}try{const e=await this.httpClient.patch(`/authentication/${i}`,!0,{connectionId:t,tenantLookupIdentifier:n,connectionProperties:r});window.location.assign(e.data.authenticationUrl)}catch(e){if(e.status>=400&&e.status<500){const t=Error(e.data.title||e.data.errorCode);throw t.code=e.data.errorCode,t}throw e.data||e}await new Promise((e=>setTimeout(e,5e3)))}async unlinkIdentity(e){if(!e){const e=Error("connectionId must be specified");throw e.code="InvalidConnection",e}if(!this.getUserIdentity()){const e=Error("User must be logged into to unlink an account.");throw e.code="NotLoggedIn",e}let t;try{t=await this.ensureToken({timeoutInMillis:100})}catch(e){if("TokenTimeout"===e.code){const e=Error("User must be logged into an existing account before linking a second account.");throw e.code="NotLoggedIn",e}}const n=this.enableCredentials&&!this.isLocalHost()?{}:{Authorization:`Bearer ${t}`};try{await this.httpClient.delete(`/identities/${encodeURIComponent(e)}`,this.enableCredentials,n)}catch(e){if(e.status>=400&&e.status<500){const t=Error(e.data.title||e.data.errorCode);throw t.code=e.data.errorCode,t}throw e.data||e}}async linkIdentity({connectionId:e,tenantLookupIdentifier:t,redirectUrl:n,connectionProperties:r}){if(!e&&!t){const e=Error("connectionId or tenantLookupIdentifier must be specified");throw e.code="InvalidConnection",e}if(!this.getUserIdentity()){const e=Error("User must be logged into an existing account before linking a second account.");throw e.code="NotLoggedIn",e}let o;try{o=await this.ensureToken({timeoutInMillis:100})}catch(e){if("TokenTimeout"===e.code){const e=Error("User must be logged into an existing account before linking a second account.");throw e.code="NotLoggedIn",e}}const{codeChallenge:i}=await a.getAuthCodes();try{const a=n&&new URL(n).toString()||window.location.href,s=this.enableCredentials&&!this.isLocalHost()?{}:{Authorization:`Bearer ${o}`},c=await this.httpClient.post("/authentication",this.enableCredentials,{linkIdentity:!0,redirectUrl:a,codeChallengeMethod:"S256",codeChallenge:i,connectionId:e,tenantLookupIdentifier:t,connectionProperties:r,applicationId:this.settings.applicationId},s);window.location.assign(c.data.authenticationUrl)}catch(e){if(e.status>=400&&e.status<500){const t=Error(e.data.title||e.data.errorCode);throw t.code=e.data.errorCode,t}throw e}await new Promise((e=>setTimeout(e,5e3)))}async authenticate(e={}){const{connectionId:t,tenantLookupIdentifier:n,inviteId:r,redirectUrl:o,force:i,responseLocation:c,flowType:d,connectionProperties:l,openType:h,multiAccount:p,clearUserDataBeforeLogin:f}=e||{};if(c&&"cookie"!==c&&"query"!==c&&"none"!==c){const e=Error("Authentication response location is not valid");throw e.code="InvalidResponseLocation",e}if(!i&&!p&&await this.userSessionExists())return!0;const{codeVerifier:g,codeChallenge:w}=await a.getAuthCodes();try{const e=o&&new URL(o).toString()||window.location.href;!1!==f&&s.clear();const i=await this.httpClient.post("/authentication",!1,{redirectUrl:e,codeChallengeMethod:"S256",codeChallenge:w,connectionId:t,tenantLookupIdentifier:n,inviteId:r,connectionProperties:l,applicationId:this.settings.applicationId,responseLocation:c,flowType:d,multiAccount:p});if(localStorage.setItem(u,JSON.stringify({nonce:i.data.authenticationRequestId,codeVerifier:g,lastConnectionId:t,tenantLookupIdentifier:n,redirectUrl:e,enableCredentials:i.data.enableCredentials,multiAccount:p})),"tab"===h){const e=window.open(i.data.authenticationUrl,"_blank");e&&!e.closed&&void 0!==e.closed||window.location.assign(i.data.authenticationUrl)}else window.location.assign(i.data.authenticationUrl)}catch(e){if(e.status>=400&&e.status<500){const t=Error(e.data.title||e.data.errorCode);throw t.code=e.data.errorCode,t}throw e.data||e}return await new Promise((e=>setTimeout(e,5e3))),!1}async ensureToken(e){await this.userSessionExists();const t=Object.assign({timeoutInMillis:5e3},e||{}),n=this.waitForUserSession(),o=new Promise(((e,n)=>setTimeout(n,t.timeoutInMillis||0)));try{await Promise.race([n,o])}catch(e){const t=Error("No token retrieved after timeout");throw t.code="TokenTimeout",t}const i=r.parse(document.cookie);return"undefined"!==i.authorization&&i.authorization}async logout(e){if(s.clear(),d=new Promise((e=>c=e)),this.enableCredentials)try{return await this.httpClient.delete("/session",this.enableCredentials),void(e&&e!==window.location.href&&window.location.assign(e))}catch(e){}const t=new URL("/logout",this.hostUrl);t.searchParams.set("redirect_uri",e||window.location.href),t.searchParams.set("client_id",this.settings.applicationId),window.location.assign(t.toString())}},ExtensionClient:h}},215:(e,t,n)=>{const r=n(219);e.exports=new class{decode(e){if(!e)return null;try{const t=JSON.parse(r.decode(e.split(".")[1]));return t.exp&&(t.exp=t.exp-10),t}catch(e){return null}}decodeOrParse(e){if(!e)return null;if("object"==typeof e)return e;try{return JSON.parse(e)}catch(t){return this.decode(e)}}decodeFull(e){if(!e)return null;try{const t=JSON.parse(r.decode(e.split(".")[0])),n=JSON.parse(r.decode(e.split(".")[1]));return n.exp&&(n.exp=n.exp-10),{header:t,payload:n}}catch(e){return null}}async getAuthCodes(){const e=r.encode((window.crypto||window.msCrypto).getRandomValues(new Uint32Array(16)).toString()),t=await(window.crypto||window.msCrypto).subtle.digest("SHA-256",(new TextEncoder).encode(e));return{codeVerifier:e,codeChallenge:r.encode(t)}}}},429:(e,t,n)=>{const r=n(489),o="AuthenticationCredentialsStorage";e.exports=new class{getUserCookie(){return document.cookie.split(";").filter((e=>"user"===e.split("=")[0].trim())).map((e=>e.replace(/^user=/,""))).find((e=>e&&e.trim()))||null}set(e,t){try{const n=r.parse(document.cookie);localStorage.setItem(o,JSON.stringify({idToken:e,expiry:t&&t.getTime(),jsCookies:!!n.authorization})),this.clearCookies("user")}catch(e){console.debug("LocalStorage failed in Browser",e)}}get(){let e={};try{e=r.parse(document.cookie)}catch(e){console.debug("CookieManagement failed in Browser",e)}try{const{idToken:t,expiry:n,jsCookies:r}=JSON.parse(localStorage.getItem(o)||"{}");return t?n<Date.now()||r&&!e.authorization?null:t:this.getUserCookie()}catch(e){return console.debug("LocalStorage failed in Browser",e),this.getUserCookie()}}delete(){try{localStorage.removeItem(o)}catch(e){console.debug("LocalStorage failed in Browser",e)}try{this.clearCookies("user")}catch(e){console.debug("CookieManagement failed in Browser",e)}}clear(){this.clearCookies(),this.delete()}clearCookies(e){if("undefined"==typeof window)return;const t=document.cookie.split("; ");for(const n of t){if(!["user","authorization","auth-code"].includes(n.split("=")[0])||e&&n.split("=")[0]!==e)continue;const t=window.location.hostname.split("."),r=[...Array(t.length-1)].map(((e,n)=>t.reverse().slice(0,n+2).reverse().join("."))).map((e=>[e,`.${e}`])).flat(1).concat(null);"localhost"===window.location.hostname&&r.push("localhost");for(const e of r){const t=e?`domain=${e};`:"",r=`${encodeURIComponent(n.split(";")[0].split("=")[0])}=; expires=Thu, 01-Jan-1970 00:00:01 GMT; ${t} SameSite=Strict; path=`;document.cookie=`${r}/`;const o=location.pathname.split("/");for(;o.length>0;)document.cookie=r+o.join("/"),o.pop()}}}}},489:(e,t)=>{"use strict";t.parse=function(e,t){if("string"!=typeof e)throw new TypeError("argument str must be a string");var n={},r=(t||{}).decode||o,i=0;for(;i<e.length;){var s=e.indexOf("=",i);if(-1===s)break;var c=e.indexOf(";",i);if(-1===c)c=e.length;else if(c<s){i=e.lastIndexOf(";",s-1)+1;continue}var d=e.slice(i,s).trim();if(void 0===n[d]){var l=e.slice(s+1,c).trim();34===l.charCodeAt(0)&&(l=l.slice(1,-1)),n[d]=a(l,r)}i=c+1}return n},t.serialize=function(e,t,o){var a=o||{},s=a.encode||i;if("function"!=typeof s)throw new TypeError("option encode is invalid");if(!r.test(e))throw new TypeError("argument name is invalid");var c=s(t);if(c&&!r.test(c))throw new TypeError("argument val is invalid");var d=e+"="+c;if(null!=a.maxAge){var l=a.maxAge-0;if(isNaN(l)||!isFinite(l))throw new TypeError("option maxAge is invalid");d+="; Max-Age="+Math.floor(l)}if(a.domain){if(!r.test(a.domain))throw new TypeError("option domain is invalid");d+="; Domain="+a.domain}if(a.path){if(!r.test(a.path))throw new TypeError("option path is invalid");d+="; Path="+a.path}if(a.expires){var u=a.expires;if(!function(e){return"[object Date]"===n.call(e)||e instanceof Date}(u)||isNaN(u.valueOf()))throw new TypeError("option expires is invalid");d+="; Expires="+u.toUTCString()}a.httpOnly&&(d+="; HttpOnly");a.secure&&(d+="; Secure");if(a.priority){switch("string"==typeof a.priority?a.priority.toLowerCase():a.priority){case"low":d+="; Priority=Low";break;case"medium":d+="; Priority=Medium";break;case"high":d+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(a.sameSite){switch("string"==typeof a.sameSite?a.sameSite.toLowerCase():a.sameSite){case!0:d+="; SameSite=Strict";break;case"lax":d+="; SameSite=Lax";break;case"strict":d+="; SameSite=Strict";break;case"none":d+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return d};var n=Object.prototype.toString,r=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function o(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function i(e){return encodeURIComponent(e)}function a(e,t){try{return t(e)}catch(t){return e}}},802:e=>{var t=1/0,n=17976931348623157e292,r=NaN,o="[object Symbol]",i=/^\s+|\s+$/g,a=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,c=/^0o[0-7]+$/i,d=parseInt,l=Object.prototype.toString;function u(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=function(e,h,p){return e&&e.length?function(e,t,n){var r=-1,o=e.length;t<0&&(t=-t>o?0:o+t),(n=n>o?o:n)<0&&(n+=o),o=t>n?0:n-t>>>0,t>>>=0;for(var i=Array(o);++r<o;)i[r]=e[r+t];return i}(e,0,(h=p||void 0===h?1:(f=function(e){return e?(e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&l.call(e)==o}(e))return r;if(u(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=u(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(i,"");var n=s.test(e);return n||c.test(e)?d(e.slice(2),n?2:8):a.test(e)?r:+e}(e))===t||e===-t?(e<0?-1:1)*n:e==e?e:0:0===e?e:0}(h),g=f%1,f==f?g?f-g:f:0))<0?0:h):[];var f,g}}},r={};function o(e){var t=r[e];if(void 0!==t){if(void 0!==t.error)throw t.error;return t.exports}var i=r[e]={exports:{}};try{var a={id:e,module:i,factory:n[e],require:o};o.i.forEach((function(e){e(a)})),i=a.module,a.factory.call(i.exports,i,i.exports,a.require)}catch(e){throw i.error=e,e}return i.exports}return o.m=n,o.c=r,o.i=[],o.hu=e=>e+"."+o.h()+".hot-update.js",o.hmrF=()=>"main."+o.h()+".hot-update.json",o.h=()=>"06d9f3b6b28aa66110a4",o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),e={},t="authress:",o.l=(n,r,i,a)=>{if(e[n])e[n].push(r);else{var s,c;if(void 0!==i)for(var d=document.getElementsByTagName("script"),l=0;l<d.length;l++){var u=d[l];if(u.getAttribute("src")==n||u.getAttribute("data-webpack")==t+i){s=u;break}}s||(c=!0,(s=document.createElement("script")).charset="utf-8",s.timeout=120,o.nc&&s.setAttribute("nonce",o.nc),s.setAttribute("data-webpack",t+i),s.src=n),e[n]=[r];var h=(t,r)=>{s.onerror=s.onload=null,clearTimeout(p);var o=e[n];if(delete e[n],s.parentNode&&s.parentNode.removeChild(s),o&&o.forEach((e=>e(r))),t)return t(r)},p=setTimeout(h.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=h.bind(null,s.onerror),s.onload=h.bind(null,s.onload),c&&document.head.appendChild(s)}},(()=>{var e,t,n,r={},i=o.c,a=[],s=[],c="idle",d=0,l=[];function u(e){c=e;for(var t=[],n=0;n<s.length;n++)t[n]=s[n].call(null,e);return Promise.all(t)}function h(){0==--d&&u("ready").then((function(){if(0===d){var e=l;l=[];for(var t=0;t<e.length;t++)e[t]()}}))}function p(e){if("idle"!==c)throw new Error("check() is only allowed in idle status");return u("check").then(o.hmrM).then((function(n){return n?u("prepare").then((function(){var r=[];return t=[],Promise.all(Object.keys(o.hmrC).reduce((function(e,i){return o.hmrC[i](n.c,n.r,n.m,e,t,r),e}),[])).then((function(){return t=function(){return e?g(e):u("ready").then((function(){return r}))},0===d?t():new Promise((function(e){l.push((function(){e(t())}))}));var t}))})):u(w()?"ready":"idle").then((function(){return null}))}))}function f(e){return"ready"!==c?Promise.resolve().then((function(){throw new Error("apply() is only allowed in ready status (state: "+c+")")})):g(e)}function g(e){e=e||{},w();var r=t.map((function(t){return t(e)}));t=void 0;var o=r.map((function(e){return e.error})).filter(Boolean);if(o.length>0)return u("abort").then((function(){throw o[0]}));var i=u("dispose");r.forEach((function(e){e.dispose&&e.dispose()}));var a,s=u("apply"),c=function(e){a||(a=e)},d=[];return r.forEach((function(e){if(e.apply){var t=e.apply(c);if(t)for(var n=0;n<t.length;n++)d.push(t[n])}})),Promise.all([i,s]).then((function(){return a?u("fail").then((function(){throw a})):n?g(e).then((function(e){return d.forEach((function(t){e.indexOf(t)<0&&e.push(t)})),e})):u("idle").then((function(){return d}))}))}function w(){if(n)return t||(t=[]),Object.keys(o.hmrI).forEach((function(e){n.forEach((function(n){o.hmrI[e](n,t)}))})),n=void 0,!0}o.hmrD=r,o.i.push((function(l){var g,w,m,y,v=l.module,k=function(t,n){var r=i[n];if(!r)return t;var o=function(o){if(r.hot.active){if(i[o]){var s=i[o].parents;-1===s.indexOf(n)&&s.push(n)}else a=[n],e=o;-1===r.children.indexOf(o)&&r.children.push(o)}else console.warn("[HMR] unexpected require("+o+") from disposed module "+n),a=[];return t(o)},s=function(e){return{configurable:!0,enumerable:!0,get:function(){return t[e]},set:function(n){t[e]=n}}};for(var l in t)Object.prototype.hasOwnProperty.call(t,l)&&"e"!==l&&Object.defineProperty(o,l,s(l));return o.e=function(e){return function(e){switch(c){case"ready":u("prepare");case"prepare":return d++,e.then(h,h),e;default:return e}}(t.e(e))},o}(l.require,l.id);v.hot=(g=l.id,w=v,y={_acceptedDependencies:{},_acceptedErrorHandlers:{},_declinedDependencies:{},_selfAccepted:!1,_selfDeclined:!1,_selfInvalidated:!1,_disposeHandlers:[],_main:m=e!==g,_requireSelf:function(){a=w.parents.slice(),e=m?void 0:g,o(g)},active:!0,accept:function(e,t,n){if(void 0===e)y._selfAccepted=!0;else if("function"==typeof e)y._selfAccepted=e;else if("object"==typeof e&&null!==e)for(var r=0;r<e.length;r++)y._acceptedDependencies[e[r]]=t||function(){},y._acceptedErrorHandlers[e[r]]=n;else y._acceptedDependencies[e]=t||function(){},y._acceptedErrorHandlers[e]=n},decline:function(e){if(void 0===e)y._selfDeclined=!0;else if("object"==typeof e&&null!==e)for(var t=0;t<e.length;t++)y._declinedDependencies[e[t]]=!0;else y._declinedDependencies[e]=!0},dispose:function(e){y._disposeHandlers.push(e)},addDisposeHandler:function(e){y._disposeHandlers.push(e)},removeDisposeHandler:function(e){var t=y._disposeHandlers.indexOf(e);t>=0&&y._disposeHandlers.splice(t,1)},invalidate:function(){switch(this._selfInvalidated=!0,c){case"idle":t=[],Object.keys(o.hmrI).forEach((function(e){o.hmrI[e](g,t)})),u("ready");break;case"ready":Object.keys(o.hmrI).forEach((function(e){o.hmrI[e](g,t)}));break;case"prepare":case"check":case"dispose":case"apply":(n=n||[]).push(g)}},check:p,apply:f,status:function(e){if(!e)return c;s.push(e)},addStatusHandler:function(e){s.push(e)},removeStatusHandler:function(e){var t=s.indexOf(e);t>=0&&s.splice(t,1)},data:r[g]},e=void 0,y),v.parents=a,v.children=[],a=[],l.require=k})),o.hmrC={},o.hmrI={}})(),o.p="",(()=>{var e,t,n,r,i,a=o.hmrS_jsonp=o.hmrS_jsonp||{179:0},s={};function c(t,n){return e=n,new Promise(((e,n)=>{s[t]=e;var r=o.p+o.hu(t),i=new Error;o.l(r,(e=>{if(s[t]){s[t]=void 0;var r=e&&("load"===e.type?"missing":e.type),o=e&&e.target&&e.target.src;i.message="Loading hot update chunk "+t+" failed.\n("+r+": "+o+")",i.name="ChunkLoadError",i.type=r,i.request=o,n(i)}}))}))}function d(e){function s(e){for(var t=[e],n={},r=t.map((function(e){return{chain:[e],id:e}}));r.length>0;){var i=r.pop(),a=i.id,s=i.chain,d=o.c[a];if(d&&(!d.hot._selfAccepted||d.hot._selfInvalidated)){if(d.hot._selfDeclined)return{type:"self-declined",chain:s,moduleId:a};if(d.hot._main)return{type:"unaccepted",chain:s,moduleId:a};for(var l=0;l<d.parents.length;l++){var u=d.parents[l],h=o.c[u];if(h){if(h.hot._declinedDependencies[a])return{type:"declined",chain:s.concat([u]),moduleId:a,parentId:u};-1===t.indexOf(u)&&(h.hot._acceptedDependencies[a]?(n[u]||(n[u]=[]),c(n[u],[a])):(delete n[u],t.push(u),r.push({chain:s.concat([u]),id:u})))}}}}return{type:"accepted",moduleId:e,outdatedModules:t,outdatedDependencies:n}}function c(e,t){for(var n=0;n<t.length;n++){var r=t[n];-1===e.indexOf(r)&&e.push(r)}}o.f&&delete o.f.jsonpHmr,t=void 0;var d={},l=[],u={},h=function(e){console.warn("[HMR] unexpected require("+e.id+") to disposed module")};for(var p in n)if(o.o(n,p)){var f,g=n[p],w=!1,m=!1,y=!1,v="";switch((f=g?s(p):{type:"disposed",moduleId:p}).chain&&(v="\nUpdate propagation: "+f.chain.join(" -> ")),f.type){case"self-declined":e.onDeclined&&e.onDeclined(f),e.ignoreDeclined||(w=new Error("Aborted because of self decline: "+f.moduleId+v));break;case"declined":e.onDeclined&&e.onDeclined(f),e.ignoreDeclined||(w=new Error("Aborted because of declined dependency: "+f.moduleId+" in "+f.parentId+v));break;case"unaccepted":e.onUnaccepted&&e.onUnaccepted(f),e.ignoreUnaccepted||(w=new Error("Aborted because "+p+" is not accepted"+v));break;case"accepted":e.onAccepted&&e.onAccepted(f),m=!0;break;case"disposed":e.onDisposed&&e.onDisposed(f),y=!0;break;default:throw new Error("Unexception type "+f.type)}if(w)return{error:w};if(m)for(p in u[p]=g,c(l,f.outdatedModules),f.outdatedDependencies)o.o(f.outdatedDependencies,p)&&(d[p]||(d[p]=[]),c(d[p],f.outdatedDependencies[p]));y&&(c(l,[f.moduleId]),u[p]=h)}n=void 0;for(var k,C=[],b=0;b<l.length;b++){var I=l[b],S=o.c[I];S&&(S.hot._selfAccepted||S.hot._main)&&u[I]!==h&&!S.hot._selfInvalidated&&C.push({module:I,require:S.hot._requireSelf,errorHandler:S.hot._selfAccepted})}return{dispose:function(){var e;r.forEach((function(e){delete a[e]})),r=void 0;for(var t,n=l.slice();n.length>0;){var i=n.pop(),s=o.c[i];if(s){var c={},u=s.hot._disposeHandlers;for(b=0;b<u.length;b++)u[b].call(null,c);for(o.hmrD[i]=c,s.hot.active=!1,delete o.c[i],delete d[i],b=0;b<s.children.length;b++){var h=o.c[s.children[b]];h&&((e=h.parents.indexOf(i))>=0&&h.parents.splice(e,1))}}}for(var p in d)if(o.o(d,p)&&(s=o.c[p]))for(k=d[p],b=0;b<k.length;b++)t=k[b],(e=s.children.indexOf(t))>=0&&s.children.splice(e,1)},apply:function(t){for(var n in u)o.o(u,n)&&(o.m[n]=u[n]);for(var r=0;r<i.length;r++)i[r](o);for(var a in d)if(o.o(d,a)){var s=o.c[a];if(s){k=d[a];for(var c=[],h=[],p=[],f=0;f<k.length;f++){var g=k[f],w=s.hot._acceptedDependencies[g],m=s.hot._acceptedErrorHandlers[g];if(w){if(-1!==c.indexOf(w))continue;c.push(w),h.push(m),p.push(g)}}for(var y=0;y<c.length;y++)try{c[y].call(null,k)}catch(n){if("function"==typeof h[y])try{h[y](n,{moduleId:a,dependencyId:p[y]})}catch(r){e.onErrored&&e.onErrored({type:"accept-error-handler-errored",moduleId:a,dependencyId:p[y],error:r,originalError:n}),e.ignoreErrored||(t(r),t(n))}else e.onErrored&&e.onErrored({type:"accept-errored",moduleId:a,dependencyId:p[y],error:n}),e.ignoreErrored||t(n)}}}for(var v=0;v<C.length;v++){var b=C[v],I=b.module;try{b.require(I)}catch(n){if("function"==typeof b.errorHandler)try{b.errorHandler(n,{moduleId:I,module:o.c[I]})}catch(r){e.onErrored&&e.onErrored({type:"self-accept-error-handler-errored",moduleId:I,error:r,originalError:n}),e.ignoreErrored||(t(r),t(n))}else e.onErrored&&e.onErrored({type:"self-accept-errored",moduleId:I,error:n}),e.ignoreErrored||t(n)}}return l}}}this.webpackHotUpdateauthress=(t,r,a)=>{for(var c in r)o.o(r,c)&&(n[c]=r[c],e&&e.push(c));a&&i.push(a),s[t]&&(s[t](),s[t]=void 0)},o.hmrI.jsonp=function(e,t){n||(n={},i=[],r=[],t.push(d)),o.o(n,e)||(n[e]=o.m[e])},o.hmrC.jsonp=function(e,s,l,u,h,p){h.push(d),t={},r=s,n=l.reduce((function(e,t){return e[t]=!1,e}),{}),i=[],e.forEach((function(e){o.o(a,e)&&void 0!==a[e]?(u.push(c(e,p)),t[e]=!0):t[e]=!1})),o.f&&(o.f.jsonpHmr=function(e,n){t&&o.o(t,e)&&!t[e]&&(n.push(c(e)),t[e]=!0)})},o.hmrM=()=>{if("undefined"==typeof fetch)throw new Error("No browser support: need fetch API");return fetch(o.p+o.hmrF()).then((e=>{if(404!==e.status){if(!e.ok)throw new Error("Failed to fetch update manifest "+e.statusText);return e.json()}}))}})(),o(125)})()));
@@ -7,7 +7,7 @@
7
7
 
8
8
  /**
9
9
  * @preserve
10
- * Authress Login SDK 2.2.251
10
+ * Authress Login SDK 2.3.255
11
11
  * License: Apache-2.0
12
12
  * Repo : https://github.com/Authress/login-sdk.js
13
13
  * Author : Authress Developers
Binary file
Binary file
package/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- interface Settings {
1
+ export interface Settings {
2
2
  /** Your Authress custom domain - see https://authress.io/app/#/setup?focus=domain */
3
3
  authressLoginHostUrl: string;
4
4
  /** The Authress applicationId for this app - see https://authress.io/app/#/manage?focus=applications */
5
5
  applicationId: string;
6
6
  }
7
7
 
8
- interface AuthenticationParameters {
8
+ export interface AuthenticationParameters {
9
9
  /** Specify which provider connection that user would like to use to log in - see https://authress.io/app/#/manage?focus=connections */
10
10
  connectionId?: string;
11
11
  /** Instead of connectionId, specify the tenant lookup identifier to log the user with the mapped tenant - see https://authress.io/app/#/manage?focus=tenants */
@@ -26,7 +26,7 @@ interface AuthenticationParameters {
26
26
  clearUserDataBeforeLogin?: boolean;
27
27
  }
28
28
 
29
- interface LinkIdentityParameters {
29
+ export interface LinkIdentityParameters {
30
30
  /** Specify which provider connection that user would like to use to log in - see https://authress.io/app/#/manage?focus=connections */
31
31
  connectionId?: string;
32
32
  /** Instead of connectionId, specify the tenant lookup identifier to log the user with the mapped tenant - see https://authress.io/app/#/manage?focus=tenants */
@@ -37,7 +37,7 @@ interface LinkIdentityParameters {
37
37
  connectionProperties?: Record<string, string>;
38
38
  }
39
39
 
40
- interface ExtensionAuthenticationParameters {
40
+ export interface ExtensionAuthenticationParameters {
41
41
  /** The redirect to your login screen will contain two query parameters `state`. Pass the state into this method. (Default: **window.location.query.state**) */
42
42
  state?: string;
43
43
  /** Specify which provider connection that user would like to use to log in - see https://authress.io/app/#/manage?focus=connections */
@@ -51,16 +51,42 @@ interface ExtensionAuthenticationParameters {
51
51
  }
52
52
 
53
53
  /** Options for getting a token including timeout configuration. */
54
- interface TokenParameters {
54
+ export interface TokenParameters {
55
55
  /** Timeout waiting for user token to populate. After this time an error will be thrown. (Default: **5000**) */
56
56
  timeoutInMillis?: number;
57
57
  }
58
58
 
59
- interface UserCredentials {
59
+ /** User credentials from the Authress Credentials Vault. */
60
+ export interface UserCredentials {
60
61
  /** User access token generated credentials for the connected provider used to log in */
61
62
  accessToken: string;
62
63
  }
63
64
 
65
+ /** MFA device */
66
+ export interface Device {
67
+ /** Unique Device ID for the this user specified MFA device. */
68
+ deviceId: string;
69
+ /** User specified name for this device. */
70
+ name: string;
71
+ }
72
+
73
+ export interface DeviceRegistrationParameters {
74
+ /** The user selected new device name. */
75
+ name: string;
76
+ }
77
+
78
+ export enum UserConfigurationScreen {
79
+ Profile = 'Profile',
80
+ MFA = 'MFA'
81
+ }
82
+
83
+ export interface UserConfigurationScreenParameters {
84
+ /** The return url, where Authress should redirect the user to after they have completed their profile updates. (Default: window.location.href) */
85
+ redirectUrl?: string;
86
+ /** The configuration page to directly navigate the user to. There are multiple Authress profile pages, this selects which one to navigate to. (Default: Profile) */
87
+ startPage: UserConfigurationScreen;
88
+ }
89
+
64
90
  export class LoginClient {
65
91
  /**
66
92
  * @constructor constructs the LoginClient with a given configuration
@@ -82,6 +108,29 @@ export class LoginClient {
82
108
  */
83
109
  getConnectionCredentials(): Promise<UserCredentials | null>;
84
110
 
111
+ /**
112
+ * @description Fetch the list of the user's MFA devices.
113
+ */
114
+ getDevices(): Promise<Device>;
115
+
116
+ /**
117
+ * @description Remove a MFA device from the user's profile
118
+ * @param {string} deviceId The deviceId to delete from the user's profile.
119
+ */
120
+ deleteDevice(deviceId: string): Promise<void>;
121
+
122
+ /**
123
+ * @description Redirects the user to the Authress profile screen to configure MFA and other security properties
124
+ * @param {UserConfigurationScreenParameters} settings Configuration parameters to specify which screen to start on.
125
+ */
126
+ openUserConfigurationScreen(settings: UserConfigurationScreenParameters): Promise<void>;
127
+
128
+ /**
129
+ * @description Starts the MFA device registration flow, requesting the user to insert or attach their MFA device.
130
+ * @param {DeviceRegistrationParameters} settings Configuration settings for the device registration
131
+ */
132
+ registerDevice(settings: DeviceRegistrationParameters): Promise<void>;
133
+
85
134
  /**
86
135
  * @description Async wait for a user session to exist. Will block until {@link userSessionExists} or {@link authenticate} is called.
87
136
  * @return {Promise<void>}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@authress/login",
3
- "version": "2.2.251",
3
+ "version": "2.3.255",
4
4
  "description": "Universal login sdk for Authress authentication as a service. Provides managed authentication for user identity, authentication, and token verification.",
5
5
  "main": "./src/index.js",
6
6
  "types": "./index.d.ts",
package/src/index.js CHANGED
@@ -131,6 +131,104 @@ class LoginClient {
131
131
  }
132
132
  }
133
133
 
134
+ async getDevices() {
135
+ await this.waitForUserSession();
136
+
137
+ try {
138
+ const token = await this.ensureToken();
139
+ const deviceResult = await this.httpClient.get('/session/devices', this.enableCredentials, { Authorization: token && `Bearer ${token}` });
140
+ return deviceResult.data.devices;
141
+ } catch (error) {
142
+ return [];
143
+ }
144
+ }
145
+
146
+ async deleteDevice(deviceId) {
147
+ await this.waitForUserSession();
148
+
149
+ try {
150
+ const token = await this.ensureToken();
151
+ await this.httpClient.delete(`/session/devices/${encodeURIComponent(deviceId)}`, this.enableCredentials, { Authorization: token && `Bearer ${token}` });
152
+ } catch (error) {
153
+ this.logger && this.logger.log({ title: 'Failed to delete device', error });
154
+ throw error;
155
+ }
156
+ }
157
+
158
+ async openUserConfigurationScreen(options = { redirectUrl: null, startPage: 'PROFILE' }) {
159
+ const userConfigurationScreenUrl = new URL('/profile', this.hostUrl);
160
+ userConfigurationScreenUrl.searchParams.set('client_id', this.settings.applicationId);
161
+ userConfigurationScreenUrl.searchParams.set('redirect_uri', options && options.redirectUrl || window.location.href);
162
+ window.location.assign(userConfigurationScreenUrl.toString());
163
+ await Promise.resolve();
164
+ }
165
+
166
+ async registerDevice(options = { name: '' }) {
167
+ await this.waitForUserSession();
168
+
169
+ const userIdentity = await this.getUserIdentity();
170
+ const userId = userIdentity.sub;
171
+
172
+ // https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create
173
+ const publicKeyCredentialCreationOptions = {
174
+ challenge: Uint8Array.from(userId, c => c.charCodeAt(0)),
175
+ rp: {
176
+ name: 'WebAuthN Login'
177
+ },
178
+ user: {
179
+ id: Uint8Array.from(userId, c => c.charCodeAt(0)),
180
+ name: userId,
181
+ displayName: `Generated User ID: ${userId}`
182
+ },
183
+ // https://www.iana.org/assignments/cose/cose.xhtml#algorithms (Order Matters)
184
+ pubKeyCredParams: [
185
+ // Disabled in the library and not currently supported
186
+ // IMPORTANT: NEVER ADD TO THE FRONT OF THIS LIST - because we have no idea which algo public key we have saved in the DB, if we guess wrong there is going to be a mismatch.
187
+ // => So until we have a code to enable a retry and realistically, we can deterministically know which public key to type use, we must never prepend this list, only append unless the user data contains a preference order
188
+ // { type: 'public-key', alg: -8 }, /* EdDSA */
189
+ { type: 'public-key', alg: -36 }, /* ES512 */ { type: 'public-key', alg: -35 }, /* ES384 */ { type: 'public-key', alg: -7 }, /* ES256 */
190
+ // { type: 'public-key', alg: -39 }, /* PS512 */ { type: 'public-key', alg: -38 }, /* PS384 */ { type: 'public-key', alg: -37 }, /* PS256 */
191
+ { type: 'public-key', alg: -259 }, /* RS512 */ { type: 'public-key', alg: -258 }, /* RS384 */ { type: 'public-key', alg: -257 } /* RS256 */
192
+ ],
193
+ authenticatorSelection: {
194
+ residentKey: 'discouraged',
195
+ requireResidentKey: false,
196
+ userVerification: 'discouraged'
197
+ // authenticatorAttachment: 'cross-platform'
198
+ },
199
+ timeout: 60000,
200
+ attestation: 'direct'
201
+ };
202
+
203
+ const credential = await navigator.credentials.create({
204
+ publicKey: publicKeyCredentialCreationOptions
205
+ });
206
+
207
+ const webAuthNTokenRequest = {
208
+ authenticatorAttachment: credential.authenticatorAttachment,
209
+ credentialId: credential.id,
210
+ type: credential.type,
211
+ userId: userId,
212
+ attestation: btoa(String.fromCharCode(...new Uint8Array(credential.response.attestationObject))),
213
+ client: JSON.parse(new TextDecoder('utf-8').decode(credential.response.clientDataJSON))
214
+ };
215
+
216
+ const request = {
217
+ name: options && options.name,
218
+ code: webAuthNTokenRequest,
219
+ type: 'WebAuthN'
220
+ };
221
+
222
+ try {
223
+ const token = await this.ensureToken();
224
+ const deviceCreationResult = await this.httpClient.post('/session/devices', this.enableCredentials, request, { Authorization: token && `Bearer ${token}` });
225
+ return deviceCreationResult.data;
226
+ } catch (error) {
227
+ this.logger && this.logger.log({ title: 'Failed to register new device', error });
228
+ throw error;
229
+ }
230
+ }
231
+
134
232
  /**
135
233
  * @description Async wait for a user session to exist. Will block until {@link userSessionExists} or {@link authenticate} is called.
136
234
  * @return {Promise<void>}