@authress/login 2.5.378 → 2.5.380
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/dist/authress.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! Authress Login SDK 2.5.
|
|
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={75:(e,t,n)=>{const{sanitizeUrl:o}=n(332),r=n(629),i={"Content-Type":"application/json","X-Powered-By":`Authress Login SDK; Javascript; ${n(330).version}`},a=new Set(["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","Load failed","<HTML DOCUMENT></HTML>"]);function s(e){return"Network Error"===e.message||"ERR_NETWORK"===e.code||!e.status||e.status>=500||"string"==typeof e.message&&a.has(e.message)||"string"==typeof e.data&&a.has(e.data)}async function c(e){let t=null;for(let n=0;n<5;n++)try{return await e()}catch(e){if(e.retryCount=n,!s(e))throw e;t=e,t.isNetworkError=!0,await new Promise((e=>setTimeout(e,10*2**n)));continue}const n=new Error("[Authress Login SDK] Http Request failed due to a Network Error even after multiple retries",{cause:t});throw n.code="AuthressSdkNetworkError",n}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(o(e));this.loginUrl=`${r.origin}/api`}get(e,t,n,o){return c((()=>this.fetchWrapper("GET",e,null,n,t,o)))}delete(e,t,n,o){return c((()=>this.fetchWrapper("DELETE",e,null,n,t,o)))}post(e,t,n,o,r){return c((()=>this.fetchWrapper("POST",e,n,o,t,r)))}put(e,t,n,o,r){return c((()=>this.fetchWrapper("PUT",e,n,o,t,r)))}patch(e,t,n,o,r){return c((()=>this.fetchWrapper("PATCH",e,n,o,t,r)))}async fetchWrapper(e,t,n,o,a,s){const c=`${this.loginUrl}${t.toString()}`,l=e.toUpperCase(),d=Object.assign({},i,o);try{this.logger&&this.logger.debug&&this.logger.debug({title:"[Authress Login SDK] HttpClient Request",method:l,url:c});const e={method:l,headers:d};n&&(e.body=JSON.stringify(n)),!r.isLocalHost()&&a&&(e.credentials="include");const t=await fetch(c,e);if(!t.ok)throw t;let o={};try{o=await t.text(),o=JSON.parse(o)}catch(e){}return{url:c,method:l,headers:t.headers,status:t.status,data:o}}catch(e){let t=e;try{t=await e.text(),t=JSON.parse(t)}catch(e){}const o=t.stack&&t.stack.match(/chrome-extension:[/][/](\w+)[/]/);if(o){this.logger&&this.logger.debug&&this.logger.debug({title:`[Authress Login SDK] Fetch failed due to a browser extension - ${l} - ${c}`,method:l,url:c,data:n,headers:d,error:e,resolvedError:t,extensionErrorId:o});const r=new Error(`Extension Error ID: ${o}`);throw r.code="BROWSER_EXTENSION_ERROR",r}const r=e.status;let i="warn",a="[Authress Login SDK] HttpClient Response Error";e?401===r?(a="[Authress Login SDK] HttpClient Response Error due to invalid token",i="debug"):404===r?(a="[Authress Login SDK] HttpClient Response: Not Found",i="debug"):r<500&&s&&(i="debug"):a="[Authress Login SDK] HttpClient Response Error - Unknown error occurred",this.logger&&this.logger[i]&&this.logger[i]({title:a,online:"undefined"==typeof navigator||navigator.onLine,method:l,url:c,status:r,data:n,headers:d,error:e,resolvedError:t});throw{url:c,method:l,status:r,data:t,headers:e.headers}}}}},160:(e,t,n)=>{const o=n(427),r=n(629),i="AuthenticationCredentialsStorage",a={user:"user",authorization:"authorization",authCode:"auth-code",authUserId:"AuthUserId"};e.exports=new class{constructor(){this.retainUserCookie=!1}getUserCookie(){const e=r.getDocument();if(!e)return null;return e.cookie.split(";").filter((e=>e.split("=")[0].trim()===a.user)).map((e=>e.trim().replace(/^user=/,""))).find((e=>e&&e.trim()))||null}getAuthorizationTokens(){if("undefined"==typeof window||"undefined"==typeof document)return[];return document.cookie.split(";").filter((e=>e.split("=")[0].trim()===a.authorization)).map((e=>e.trim().replace(/^authorization=/,""))).filter((e=>e&&e.trim()))}set(e,t){if("undefined"!=typeof window&&"undefined"!=typeof document)try{const n=o.parse(document.cookie);localStorage.setItem(i,JSON.stringify({idToken:e,expiry:t&&t.getTime(),jsCookies:!!n.authorization})),this.retainUserCookie||this.clearCookies(a.user)}catch(e){console.debug("LocalStorage failed in Browser",e)}}get(){if("undefined"==typeof window||"undefined"==typeof document)return null;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(i)||"{}");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(i)}catch(e){console.debug("LocalStorage failed in Browser",e)}try{this.clearCookies(a.user)}catch(e){console.debug("CookieManagement failed in Browser",e)}}clear(){this.clearCookies(),this.delete()}clearCookies(e){if("undefined"==typeof window||"undefined"==typeof document)return;const t=document.cookie.split("; ");for(const n of t){if(!Object.values(a).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()}}}}},321: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,l=parseInt,d=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:(g=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)&&d.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)?l(e.slice(2),n?2:8):a.test(e)?o:+e}(e))===t||e===-1/0?(e<0?-1:1)*n:e==e?e:0:0===e?e:0}(h),f=g%1,g==g?f?g-f:g:0))<0?0:h):[];var g,f}},330:e=>{"use strict";e.exports=JSON.parse('{"name":"@authress/login","version":"2.5.378","description":"Universal login sdk for Authress authentication as a service. Provides managed authentication for user identity, authentication, and token verification.","main":"./src/index.js","types":"./index.d.ts","files":["index.d.ts","src","dist"],"scripts":{"build":"node make.js build && NODE_ENV=production webpack --mode=production","lint":"eslint --ext .js,.ts src tests make.js index.d.ts","test":"check-dts index.d.ts && mocha tests/*.test.js tests/**/*.test.js -R spec"},"dependencies":{"cookie":"<1","lodash.take":"^4.1.1"},"devDependencies":{"@babel/core":"^7.17.5","@babel/preset-env":"^7.16.11","@types/node":"^14.14.35","@typescript-eslint/eslint-plugin":"^3.1.0","@typescript-eslint/parser":"^3.1.0","babel-loader":"^8.2.3","chai":"^4.2.0","check-dts":"^0.4.4","ci-build-tools":"^1.0.13","commander":"^4.0.1","compression-webpack-plugin":"^9.2.0","eslint":"^7.12.1","eslint-config-cimpress-atsquad":"^1.0.67","eslint-loader":"^4.0.2","eslint-plugin-mocha":"^7.0.1","eslint-plugin-node":"^11.1.0","eslint-plugin-promise":"^6.1.1","fs-extra":"^8.1.0","glob":"^7.1.6","mocha":"^11.1.0","path-browserify":"^1.0.1","sinon":"^7.5.0","sinon-chai":"^3.3.0","terser-webpack-plugin":"^5.3.1","typescript":"^3.9.5","webpack":"^5.69.1","webpack-cli":"^4.9.2"},"repository":{"type":"git","url":"git+https://github.com/Authress/authress-login.js"},"keywords":["authentication","authentication as a service","Login","Login Client","universal login","auth","federated login","secure login","application security","IDaaS","authentication","user authentication","user identity","Oauth2","Oauth2.1","Oauth3","platform","platform login","extension","Authress","Authress client","user security","DBSC","Device Bound Session Credentials"],"author":"Authress Developers <developers@authress.io> (https://authress.io)","license":"Apache-2.0","bugs":{"url":"https://github.com/Authress/authress-login.js/issues"},"homepage":"https://authress.io","engines":{"node":">=18"}}')},332:e=>{e.exports.sanitizeUrl=function(e){let t=e;t.startsWith("http")||(t=`https://${t}`);const n=new URL(t),o=n.host.match(/^([a-z0-9-]+)[.][a-z0-9-]+[.]authress[.]io$/);return o&&(n.host=`${o[1]}.login.authress.io`,t=n.toString()),t.replace(/[/]+$/,"")}},354:(e,t,n)=>{const o=n(427),r=n(321),i=n(629),a=n(75),s=n(836),{sanitizeUrl:c}=n(332),l=n(160);let d,u=new Promise((e=>d=e)),h=Promise.resolve(),p=!1;const g="AuthenticationRequestNonce";const f=n(568);e.exports={LoginClient:class{constructor(e,t){const n=Object.assign({applicationId:"app_default"},e);this.logger=t||console;const o=n.authressApiUrl||n.authressLoginHostUrl||n.authenticationServiceUrl||"";if(!o)throw Error('Missing required property "authressApiUrl" in LoginClient constructor. Custom Authress Domain Host is required.');if(this.applicationId=n.applicationId,!this.applicationId||this.applicationId.match(/^(sc_|ext_)/)){const e=Error("You have incorrectly specified an Authress Service Client or Extension as the applicationId instead of a valid application. The applicationId is your application that your users will log into, usually hosted on your domain https://example.yourdomain.com. Users cannot log *into* a Service Client, but they can log in *with* one. Users can use a Service Client to log in, by setting the connection ID in the *authenticate({ connectionId })* method to be the Authress Service Client.\n(1) If you are building an Custom Login Portal, then the application ID should correspond to this login portal.\n(2) If you are replacing or extending an Authress connection, then specify the Service Client as the connectionId and the end user application as the applicationId.\n(3) If you are building a platform or plugin marketplace, where users will log into third party extensions or apps, then distribute in your SDK a wrapper for the Authress Extension Client using: import { extensionClient } from '@authress/login' found within this SDK.\n(4) If you aren't sure what to do here to fix the problem, the fastest and usually correct solution is go to https://authress.io/app/#/settings?focus=applications create a new application, specify your site in the application url property and then update the value here.");throw e.code="InvalidApplication",e}this.hostUrl=c(o),this.httpClient=new a(this.hostUrl,t),this.lastSessionCheck=0,this.enableCredentials=this.getMatchingDomainInfo(this.hostUrl),l.retainUserCookie=e.retainUserCookie,n.skipBackgroundCredentialsCheck||i.onLoad((async()=>{await this.userSessionExists({backgroundTrigger:!0})}))}getMatchingDomainInfo(e){const t=new URL(e);if(i.isLocalHost())return!1;const n=i.getCurrentLocation();if("https:"!==n.protocol)return!1;const o=t.host.toLowerCase().split(".").reverse(),a=n.host.toLowerCase().split(".").reverse();let s=[];for(let e of o){const t=r(a,s.length+1).join(".");if(s.concat(e).join(".")!==t)break;s.push(e)}return s.length===o.length&&s.length===a.length||s.length>1}getUserIdentity(){const e=l.getUserCookie(),t=s.decodeOrParse(e);if(t){const n=t.exp?new Date(1e3*t.exp):new Date(Date.now()+864e5);return l.set(e,n),t.userId=t.sub,t}const n=l.get(),o=s.decodeOrParse(n);if(!o)return null;const r=new URL(o.iss).hostname,i=new URL(this.hostUrl).hostname;return r.endsWith(i)||i.endsWith(r)?(o.userId=o.sub,o):(l.clear(),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(){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){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:"[Authress Login SDK] Failed to delete device",error:e}),e}}async openUserConfigurationScreen(e={redirectUrl:null,startPage:"Profile"}){if(!await this.userSessionExists()){const e=Error("User must be logged to configure user profile data.");throw e.code="NotLoggedIn",e}const t=new URL("/settings",this.hostUrl);t.searchParams.set("client_id",this.applicationId),t.searchParams.set("start_page",e&&e.startPage||"Profile"),t.searchParams.set("redirect_uri",e&&e.redirectUrl||i.getCurrentLocation().href),i.assign(t.toString()),await Promise.resolve()}async registerDevice(e={name:"",type:"",totp:{}}){const t=await this.getUserIdentity();if(!t){const e=Error("User must be logged to configure user profile data.");throw e.code="NotLoggedIn",e}if(!e){const e=Error("Register Device missing required parameter: 'Options'");throw e.code="InvalidInput",e}let n;if(e.type&&"WebAuthN"!==e.type)"TOTP"===e.type&&(n={name:e.name,code:e.totp.verificationCode,totpData:e.totp,type:"TOTP"});else{const o=t.sub,r={challenge:Uint8Array.from(o,(e=>e.charCodeAt(0))),rp:{id:this.hostUrl.split(".").slice(1).join("."),name:"WebAuthN Login"},user:{id:Uint8Array.from(o,(e=>e.charCodeAt(0))),name:o,displayName:`Generated User ID: ${o}`},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{residentKey:"discouraged",requireResidentKey:!1,userVerification:"discouraged"},timeout:6e4,attestation:"direct"},i=await navigator.credentials.create({publicKey:r}),a={authenticatorAttachment:i.authenticatorAttachment,credentialId:i.id,type:i.type,userId:o,attestation:btoa(String.fromCharCode(...new Uint8Array(i.response.attestationObject))),client:btoa(String.fromCharCode(...new Uint8Array(i.response.clientDataJSON)))};n={name:e&&e.name,code:a,type:"WebAuthN"}}try{const e=await this.ensureToken();return(await this.httpClient.post("/session/devices",this.enableCredentials,n,{Authorization:e&&`Bearer ${e}`})).data}catch(e){throw this.logger&&this.logger.log({title:"[Authress Login SDK] Failed to register new device",error:e,request:n}),e}}async waitForUserSession(){try{return await u,!0}catch(e){return!1}}userSessionExists(e={backgroundTrigger:!1}){return Date.now()-this.lastSessionCheck<50||p?h:(this.lastSessionCheck=Date.now(),p=!0,h=h.catch((()=>{})).then((async()=>{try{const t=await this.userSessionContinuation(null==e?void 0:e.backgroundTrigger);return p=!1,t}catch(e){throw p=!1,e}})))}async userSessionContinuation(e){const t=new URLSearchParams(i.getCurrentLocation().search);let n={};if("undefined"!=typeof localStorage)try{n=JSON.parse(localStorage.getItem(g)||"{}"),localStorage.removeItem(g),Object.hasOwnProperty.call(n,"enableCredentials")&&(this.enableCredentials=n.enableCredentials)}catch(e){this.logger&&this.logger.debug&&this.logger.debug({title:"[Authress Login SDK] LocalStorage failed in Browser",error:e})}if(t.get("state")&&"oauthLogin"===t.get("flow"))return!1;if((n.nonce||t.get("iss")&&t.get("iss").includes(this.hostUrl))&&this.sanitizeQueryParameters(),n.nonce&&t.get("code")&&n.nonce===t.get("nonce")){const e="cookie"===t.get("code")?o.parse(document.cookie)["auth-code"]:t.get("code"),r=await s.calculateAntiAbuseHash({client_id:this.applicationId,authenticationRequestId:n.nonce,code:e}),i={grant_type:"authorization_code",redirect_uri:n.redirectUrl,client_id:this.applicationId,code:e,code_verifier:n.codeVerifier,antiAbuseHash:r};try{const e=await this.httpClient.post(`/authentication/${n.nonce}/tokens`,this.enableCredentials,i),t=s.decode(e.data.id_token),r=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:r,path:"/",sameSite:"strict"}),l.set(e.data.id_token,r),d(),!0}catch(e){if(this.logger&&this.logger.log({title:"[Authress Login SDK] Failed exchange authentication response for a token.",error:e}),e.data&&"invalid_request"===e.data.error)return!1;throw e.data||e}}if(i.isLocalHost()&&t.get("nonce")&&t.get("access_token")&&(!n.nonce||n.nonce===t.get("nonce"))){const e=s.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"}),l.set(t.get("id_token"),n),d(),!0}if(this.getUserIdentity())return d(),!0;if(!i.isLocalHost()&&!e){try{const e=await this.httpClient.patch("/session",this.enableCredentials,{},null,!0);if(e.data.access_token){const t=s.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"}),l.set(e.data.id_token,n)}}catch(e){400===e.status||404===e.status||409===e.status?this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] User does not have an existing authentication session",error:e}):this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Failed attempting to check if the user has an existing authentication session",error:e})}if(this.getUserIdentity())return d(),!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(i.getCurrentLocation().search),a=e||r.get("state");if(!a){const e=Error("The `state` parameters must be specified to update this authentication request");throw e.code="InvalidAuthenticationRequest",e}try{const e=await s.calculateAntiAbuseHash({connectionId:t,tenantLookupIdentifier:n,authenticationRequestId:a}),r=await this.httpClient.patch(`/authentication/${a}`,!0,{antiAbuseHash:e,connectionId:t,tenantLookupIdentifier:n,connectionProperties:o});if(new URL(r.data.authenticationUrl).hostname===i.getCurrentLocation().hostname)return{authenticationUrl:r.data.authenticationUrl};i.assign(r.data.authenticationUrl)}catch(e){if(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Failed to update extension authentication request",error:e}),e.status&&e.status>=400&&e.status<500){const t=Error(e.data&&(e.data.title||e.data.errorCode)||e.data||"Unknown Error");throw t.code=e.data&&e.data.errorCode,t}throw e.data||e}return await new Promise((e=>setTimeout(e,5e3))),null}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 in 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&&!i.isLocalHost()?{}:{Authorization:`Bearer ${t}`};try{await this.httpClient.delete(`/identities/${encodeURIComponent(e)}`,this.enableCredentials,n)}catch(e){if(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Failed to unlink user identity",error:e}),e.status&&e.status>=400&&e.status<500){const t=Error(e.data&&(e.data.title||e.data.errorCode)||e.data||"Unknown Error");throw t.code=e.data&&e.data.errorCode,t}throw e.data||e}}async linkIdentityWithOneTimeCode({connectionId:e,redirectUrl:t}){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 an existing account before linking a second account.");throw e.code="NotLoggedIn",e}let n;try{n=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:o}=await s.getAuthCodes(),r=await s.calculateAntiAbuseHash({connectionId:e,applicationId:this.applicationId});try{const a=t&&new URL(t).toString()||i.getCurrentLocation().href,s=this.enableCredentials&&!i.isLocalHost()?{}:{Authorization:`Bearer ${n}`},c=await this.httpClient.post("/authentication",this.enableCredentials,{antiAbuseHash:r,linkIdentity:!0,redirectUrl:a,codeChallengeMethod:"S256",codeChallenge:o,connectionId:e,applicationId:this.applicationId},s);return{authenticationUrl:c.data.authenticationUrl,authenticationRequestId:c.data.authenticationRequestId}}catch(e){if(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Failed to start user identity link",error:e}),e.status&&e.status>=400&&e.status<500){const t=Error(e.data&&(e.data.title||e.data.errorCode)||e.data||"Unknown Error");throw t.code=e.data&&e.data.errorCode,t}throw 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:a}=await s.getAuthCodes(),c=await s.calculateAntiAbuseHash({connectionId:e,tenantLookupIdentifier:t,applicationId:this.applicationId});try{const s=n&&new URL(n).toString()||i.getCurrentLocation().href,l=this.enableCredentials&&!i.isLocalHost()?{}:{Authorization:`Bearer ${r}`},d=await this.httpClient.post("/authentication",this.enableCredentials,{antiAbuseHash:c,linkIdentity:!0,redirectUrl:s,codeChallengeMethod:"S256",codeChallenge:a,connectionId:e,tenantLookupIdentifier:t,connectionProperties:o,applicationId:this.applicationId},l);i.assign(d.data.authenticationUrl)}catch(e){if(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Failed to start user identity link",error:e}),e.status&&e.status>=400&&e.status<500){const t=Error(e.data&&(e.data.title||e.data.errorCode)||e.data||"Unknown Error");throw t.code=e.data&&e.data.errorCode,t}throw e}await new Promise((e=>setTimeout(e,5e3)))}async authenticateWithOneTimeCode(e={}){const{serviceClientId:t,inviteId:n,redirectUrl:o,force:r,responseLocation:a,flowType:c,clearUserDataBeforeLogin:d}=e||{};if(a&&"cookie"!==a&&"query"!==a&&"none"!==a){const e=Error("Authentication response location is not valid");throw e.code="InvalidResponseLocation",e}if(!t){const e=Error("The Passwordless Service Client ID is required");throw e.code="InvalidInput",e}if(!n&&!r&&await this.userSessionExists()){const n=await this.ensureToken(),o=s.decode(n);if(o&&o.azp&&t!==o.azp){this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Authentication blocked because the user is already logged in, and the requested authentication parameters do not match the original session.",requestedAuthenticationOptions:e,currentAuthenticationSessionData:o});const t=Error('Authentication requested for user that is already logged in, but the connectionId specified does not match their existing session.\n Recommended Options:\n (1) If the goal is to force them to log in with this new connection and ignore their existing session, use the "force" flag.\n (2) If the goal is link their current identity with a new from the new connection, use the linkIdentity() method.\n (3) If the goal is skip log in if they are already logged in or force log in with the connectionId, first check if userSessionExists() and then only if "false", call authenticate().');throw t.code="AuthenticationConstraintContention",t}return null}const{codeVerifier:u,codeChallenge:h}=await s.getAuthCodes(),p=await s.calculateAntiAbuseHash({serviceClientId:t,inviteId:n,applicationId:this.applicationId});try{const e=o&&new URL(o).toString()||i.getCurrentLocation().href;!1!==d&&l.clear();const r=await this.httpClient.post("/authentication",this.enableCredentials,{antiAbuseHash:p,redirectUrl:e,codeChallengeMethod:"S256",codeChallenge:h,connectionId:t,inviteId:n,applicationId:this.applicationId,responseLocation:a,flowType:c});return localStorage.setItem(g,JSON.stringify({nonce:r.data.authenticationRequestId,codeVerifier:u,lastConnectionId:t,redirectUrl:e,enableCredentials:r.data.enableCredentials})),{authenticationUrl:r.data.authenticationUrl,authenticationRequestId:r.data.authenticationRequestId}}catch(e){if(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Failed to start authentication for user",error:e}),e.status&&e.status>=400&&e.status<500){const t=Error(e.data&&(e.data.title||e.data.errorCode)||e.data||"Unknown Error");throw t.code=e.data&&e.data.errorCode,t}throw e.data||e}}async authenticate(e={}){const{connectionId:t,tenantLookupIdentifier:n,inviteId:o,redirectUrl:r,force:a,responseLocation:c,flowType:d,connectionProperties:u,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(!o&&!a&&!p&&await this.userSessionExists()){const n=await this.ensureToken(),o=s.decode(n);if(t&&o&&o.azp&&t!==o.azp){this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Authentication blocked because the user is already logged in, and the requested authentication parameters do not match the original session.",requestedAuthenticationOptions:e,currentAuthenticationSessionData:o});const t=Error('Authentication requested for user that is already logged in, but the connectionId specified does not match their existing session.\n Recommended Options:\n (1) If the goal is to force them to log in with this new connection and ignore their existing session, use the "force" flag.\n (2) If the goal is link their current identity with a new from the new connection, use the linkIdentity() method.\n (3) If the goal is skip log in if they are already logged in or force log in with the connectionId, first check if userSessionExists() and then only if "false", call authenticate().');throw t.code="AuthenticationConstraintContention",t}return null}const{codeVerifier:m,codeChallenge:w}=await s.getAuthCodes(),y=await s.calculateAntiAbuseHash({connectionId:t,tenantLookupIdentifier:n,inviteId:o,applicationId:this.applicationId});try{const e=r&&new URL(r).toString()||i.getCurrentLocation().href;!1!==f&&l.clear();const a=await this.httpClient.post("/authentication",!1,{antiAbuseHash:y,redirectUrl:e,codeChallengeMethod:"S256",codeChallenge:w,connectionId:t,tenantLookupIdentifier:n,inviteId:o,connectionProperties:u,applicationId:this.applicationId,responseLocation:c,flowType:d,multiAccount:p});if(localStorage.setItem(g,JSON.stringify({nonce:a.data.authenticationRequestId,codeVerifier:m,lastConnectionId:t,tenantLookupIdentifier:n,redirectUrl:e,enableCredentials:a.data.enableCredentials,multiAccount:p})),!a.data.authenticationUrl||new URL(a.data.authenticationUrl).hostname===i.getCurrentLocation().hostname)return{authenticationUrl:a.data.authenticationUrl,authenticationRequestId:a.data.authenticationRequestId};if("tab"===h){const e=i.open(a.data.authenticationUrl,"_blank");e&&!e.closed&&void 0!==e.closed||i.assign(a.data.authenticationUrl)}else i.assign(a.data.authenticationUrl)}catch(e){if(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Failed to start authentication for user",error:e}),e.status&&e.status>=400&&e.status<500){const t=Error(e.data&&(e.data.title||e.data.errorCode)||e.data||"Unknown Error");throw t.code=e.data&&e.data.errorCode,t}throw e.data||e}return await new Promise((e=>setTimeout(e,5e3))),null}async ensureToken(e){if(e&&0===e.timeoutInMillis){if(!this.getUserIdentity()){const e=Error("No token retrieved after timeout");throw e.code="TokenTimeout",e}const t=l.getAuthorizationTokens(),n=t.find((t=>{try{const n=s.decode(t);return(null==n?void 0:n.iss)===this.hostUrl||(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Skipping stored authorization cookie because the issuer does not match the library configured value.",requestedAuthenticationOptions:e,currentAuthenticationSessionData:n}),!1)}catch(n){return this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Skipping stored authorization cookie because it is no longer a valid token.",requestedAuthenticationOptions:e,currentAuthenticationSessionDataToken:t,error:n}),!1}}));return n||(t.length?(this.logger&&this.logger.error&&this.logger.log({title:"[Authress Login SDK] No matching issuer token found, returning the first valid token instead."}),t[0]):(this.logger&&this.logger.error&&this.logger.error({title:"[Authress Login SDK] HttpOnly access token configuration has blocked the returning of a valid token. The application specified in the Authress LoginClient constructor has been configured to block returning access tokens via the enableAccessToToken property. To use the loginClient.ensureToken() method in production, please set the enableAccessToToken to true. Note: This setting does not affect localhost."}),null))}await this.userSessionExists();const t=Object.assign({timeoutInMillis:5e3},e||{}),n=this.waitForUserSession(),o=-1===t.timeoutInMillis||t.timeoutInMillis>2**31-1?2**31-1:t.timeoutInMillis,r=new Promise(((e,t)=>setTimeout(t,o||0)));try{await Promise.race([n,r])}catch(e){const t=Error("No token retrieved after timeout");throw t.code="TokenTimeout",t}const i=l.getAuthorizationTokens(),a=i.find((t=>{try{const n=s.decode(t);return(null==n?void 0:n.iss)===this.hostUrl||(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Skipping stored authorization cookie because the issuer does not match the library configured value.",requestedAuthenticationOptions:e,currentAuthenticationSessionData:n}),!1)}catch(n){return this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Skipping stored authorization cookie because it is no longer a valid token.",requestedAuthenticationOptions:e,currentAuthenticationSessionDataToken:t,error:n}),!1}}));return a||(i.length?(this.logger&&this.logger.error&&this.logger.log({title:"[Authress Login SDK] No matching issuer token found, returning the first valid token instead."}),i[0]):(this.logger&&this.logger.error&&this.logger.error({title:"[Authress Login SDK] HttpOnly access token configuration has blocked the returning of a valid token. The application specified in the Authress LoginClient constructor has been configured to block returning access tokens via the enableAccessToToken property. To use the loginClient.ensureToken() method in production, please set the enableAccessToToken to true. Note: This setting does not affect localhost."}),null))}async logout(e){let t;if(e)try{new URL(e),t=e}catch(n){try{t=new URL(e,i.getCurrentLocation().href).toString()}catch(t){const n=Error(`The logout redirect url is not valid URL: ${e}`);throw n.code="InvalidRedirectUrl",n}}if(l.clear(),this.sanitizeQueryParameters(),u=new Promise((e=>d=e)),this.enableCredentials)try{return await this.httpClient.delete("/session",this.enableCredentials),this.lastSessionCheck=0,void(e&&e!==i.getCurrentLocation().href&&i.assign(e))}catch(e){}const n=new URL("/logout",this.hostUrl);n.searchParams.set("redirect_uri",t||i.getCurrentLocation().href),n.searchParams.set("client_id",this.applicationId),i.assign(n.toString()),this.lastSessionCheck=0,await new Promise((e=>setTimeout(e,500)))}sanitizeQueryParameters(){const e=new URL(i.getCurrentLocation());e.searchParams.delete("iss"),e.searchParams.delete("nonce"),e.searchParams.delete("code"),e.searchParams.delete("expires_in"),e.searchParams.delete("access_token"),e.searchParams.delete("id_token"),history.replaceState({},void 0,e.toString())}},ExtensionClient:f,UserConfigurationScreen:{Profile:"Profile",MFA:"MFA"}}},427:(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=e.length;if(r<2)return n;var i=t&&t.decode||d,a=0,s=0,h=0;do{if(-1===(s=e.indexOf("=",a)))break;if(-1===(h=e.indexOf(";",a)))h=r;else if(s>h){a=e.lastIndexOf(";",s-1)+1;continue}var p=c(e,a,s),g=l(e,s,p),f=e.slice(p,g);if(!o.call(n,f)){var m=c(e,s+1,h),w=l(e,h,m);34===e.charCodeAt(m)&&34===e.charCodeAt(w-1)&&(m++,w--);var y=e.slice(m,w);n[f]=u(y,i)}a=h+1}while(a<r);return n},t.serialize=function(e,t,o){var c=o&&o.encode||encodeURIComponent;if("function"!=typeof c)throw new TypeError("option encode is invalid");if(!r.test(e))throw new TypeError("argument name is invalid");var l=c(t);if(!i.test(l))throw new TypeError("argument val is invalid");var d=e+"="+l;if(!o)return d;if(null!=o.maxAge){var u=Math.floor(o.maxAge);if(!isFinite(u))throw new TypeError("option maxAge is invalid");d+="; Max-Age="+u}if(o.domain){if(!a.test(o.domain))throw new TypeError("option domain is invalid");d+="; Domain="+o.domain}if(o.path){if(!s.test(o.path))throw new TypeError("option path is invalid");d+="; Path="+o.path}if(o.expires){var h=o.expires;if(!function(e){return"[object Date]"===n.call(e)}(h)||isNaN(h.valueOf()))throw new TypeError("option expires is invalid");d+="; Expires="+h.toUTCString()}o.httpOnly&&(d+="; HttpOnly");o.secure&&(d+="; Secure");o.partitioned&&(d+="; Partitioned");if(o.priority){switch("string"==typeof o.priority?o.priority.toLowerCase():o.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(o.sameSite){switch("string"==typeof o.sameSite?o.sameSite.toLowerCase():o.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=Object.prototype.hasOwnProperty,r=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,i=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,a=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,s=/^[\u0020-\u003A\u003D-\u007E]*$/;function c(e,t,n){do{var o=e.charCodeAt(t);if(32!==o&&9!==o)return t}while(++t<n);return n}function l(e,t,n){for(;t>n;){var o=e.charCodeAt(--t);if(32!==o&&9!==o)return t+1}return n}function d(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function u(e,t){try{return t(e)}catch(t){return e}}},568:(e,t,n)=>{const o=n(836),{sanitizeUrl:r}=n(332),i=n(629),a="ExtensionRequestNonce";let s=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=r(e),this.accessToken=null,i.onLoad((async()=>{await this.requestToken({silent:!0})}))}async getUserIdentity(){const e=this.accessToken&&await 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(s)return s=s.catch((()=>{})).then((()=>this.requestTokenContinuation(e)));const t=this.requestTokenContinuation(e);return t.catch((()=>{})),s=t}async requestTokenContinuation(e={code:null,silent:!1}){const t=e&&e.code||new URLSearchParams(i.getCurrentLocation().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(a)||"{}"),s=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})}),c=await s.json();this.accessToken=c.access_token;const l=new URL(i.getCurrentLocation());return l.searchParams.delete("code"),l.searchParams.delete("iss"),l.searchParams.delete("nonce"),l.searchParams.delete("expires_in"),l.searchParams.delete("access_token"),l.searchParams.delete("id_token"),history.replaceState({},void 0,l.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),{codeVerifier:s,codeChallenge:c}=o.getAuthCodes(),l=e||i.getCurrentLocation().href;return localStorage.setItem(a,JSON.stringify({codeVerifier:s,redirectUrl:l})),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",l),i.assign(r.toString()),await new Promise((e=>setTimeout(e,5e3))),null}}},629:e=>{e.exports=new class{onLoad(e){"undefined"!=typeof window&&(window.onload=e)}isLocalHost(){return"undefined"!=typeof window&&window.location&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname)}getCurrentLocation(){return"undefined"!=typeof window&&new URL(window.location)||new URL("http://localhost:8080")}getDocument(){return"undefined"==typeof window||"undefined"==typeof document?null:document}assign(e){return"undefined"==typeof window?null:window.location.assign(e.toString())}open(e){return"undefined"==typeof window?null:window.open(e.toString())}}},836:(e,t,n)=>{const o=n(878);e.exports=new class{decode(e){var t;return e?null===(t=this.decodeFull(e))||void 0===t?void 0:t.payload: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;let t=null;try{t=JSON.parse(o.decode(e.split(".")[0]))}catch(e){}try{const 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)}}async calculateAntiAbuseHash(e){const t=Date.now(),n=Object.values(e).filter((e=>e)).join("|");let r=0,i=null;for(;++r&&(i=o.encode(await(window.crypto||window.msCrypto).subtle.digest("SHA-256",(new TextEncoder).encode(`${t};${r};${n}`))),!i.match(/^00/)););return`v2;${t};${r};${i}`}}},878: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(/=+$/,"")}}},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=()=>"74856c1a81f7adedda2e",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 l=document.getElementsByTagName("script"),d=0;d<l.length;d++){var u=l[d];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",l=0,d=[];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).then((function(){}))}function h(){0==--l&&u("ready").then((function(){if(0===l){var e=d;d=[];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?f(e):u("ready").then((function(){return o}))},0===l?t():new Promise((function(e){d.push((function(){e(t())}))}));var t}))})):u(m()?"ready":"idle").then((function(){return null}))}))}function g(e){return"ready"!==c?Promise.resolve().then((function(){throw new Error("apply() is only allowed in ready status (state: "+c+")")})):f(e)}function f(e){e=e||{},m();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)},l=[];return o.forEach((function(e){if(e.apply){var t=e.apply(c);if(t)for(var n=0;n<t.length;n++)l.push(t[n])}})),Promise.all([i,s]).then((function(){return a?u("fail").then((function(){throw a})):n?f(e).then((function(e){return l.forEach((function(t){e.indexOf(t)<0&&e.push(t)})),e})):u("idle").then((function(){return l}))}))}function m(){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(d){var f,m,w,y,k=d.module,v=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 d in t)Object.prototype.hasOwnProperty.call(t,d)&&"e"!==d&&Object.defineProperty(r,d,s(d));return r.e=function(e,n){return function(e){switch(c){case"ready":u("prepare");case"prepare":return l++,e.then(h,h),e;default:return e}}(t.e(e,n))},r}(d.require,d.id);k.hot=(f=d.id,m=k,y={_acceptedDependencies:{},_acceptedErrorHandlers:{},_declinedDependencies:{},_selfAccepted:!1,_selfDeclined:!1,_selfInvalidated:!1,_disposeHandlers:[],_main:w=e!==f,_requireSelf:function(){a=m.parents.slice(),e=w?void 0:f,r(f)},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](f,t)})),u("ready");break;case"ready":Object.keys(r.hmrI).forEach((function(e){r.hmrI[e](f,t)}));break;case"prepare":case"check":case"dispose":case"apply":(n=n||[]).push(f)}},check:p,apply:g,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[f]},e=void 0,y),k.parents=a,k.children=[],a=[],d.require=v})),r.hmrC={},r.hmrI={}})(),r.p="",(()=>{var e,t,n,o,i,a=r.hmrS_jsonp=r.hmrS_jsonp||{792: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 l(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,l=r.c[a];if(l&&(!l.hot._selfAccepted||l.hot._selfInvalidated)){if(l.hot._selfDeclined)return{type:"self-declined",chain:s,moduleId:a};if(l.hot._main)return{type:"unaccepted",chain:s,moduleId:a};for(var d=0;d<l.parents.length;d++){var u=l.parents[d],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 l={},d=[],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 g=n[p],f=g?s(p):{type:"disposed",moduleId:p},m=!1,w=!1,y=!1,k="";switch(f.chain&&(k="\nUpdate propagation: "+f.chain.join(" -> ")),f.type){case"self-declined":e.onDeclined&&e.onDeclined(f),e.ignoreDeclined||(m=new Error("Aborted because of self decline: "+f.moduleId+k));break;case"declined":e.onDeclined&&e.onDeclined(f),e.ignoreDeclined||(m=new Error("Aborted because of declined dependency: "+f.moduleId+" in "+f.parentId+k));break;case"unaccepted":e.onUnaccepted&&e.onUnaccepted(f),e.ignoreUnaccepted||(m=new Error("Aborted because "+p+" is not accepted"+k));break;case"accepted":e.onAccepted&&e.onAccepted(f),w=!0;break;case"disposed":e.onDisposed&&e.onDisposed(f),y=!0;break;default:throw new Error("Unexception type "+f.type)}if(m)return{error:m};if(w)for(p in u[p]=g,c(d,f.outdatedModules),f.outdatedDependencies)r.o(f.outdatedDependencies,p)&&(l[p]||(l[p]=[]),c(l[p],f.outdatedDependencies[p]));y&&(c(d,[f.moduleId]),u[p]=h)}n=void 0;for(var v,b=[],C=0;C<d.length;C++){var I=d[C],S=r.c[I];S&&(S.hot._selfAccepted||S.hot._main)&&u[I]!==h&&!S.hot._selfInvalidated&&b.push({module:I,require:S.hot._requireSelf,errorHandler:S.hot._selfAccepted})}return{dispose:function(){var e;o.forEach((function(e){delete a[e]})),o=void 0;for(var t,n=d.slice();n.length>0;){var i=n.pop(),s=r.c[i];if(s){var c={},u=s.hot._disposeHandlers;for(C=0;C<u.length;C++)u[C].call(null,c);for(r.hmrD[i]=c,s.hot.active=!1,delete r.c[i],delete l[i],C=0;C<s.children.length;C++){var h=r.c[s.children[C]];h&&((e=h.parents.indexOf(i))>=0&&h.parents.splice(e,1))}}}for(var p in l)if(r.o(l,p)&&(s=r.c[p]))for(v=l[p],C=0;C<v.length;C++)t=v[C],(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 l)if(r.o(l,a)){var s=r.c[a];if(s){v=l[a];for(var c=[],h=[],p=[],g=0;g<v.length;g++){var f=v[g],m=s.hot._acceptedDependencies[f],w=s.hot._acceptedErrorHandlers[f];if(m){if(-1!==c.indexOf(m))continue;c.push(m),h.push(w),p.push(f)}}for(var y=0;y<c.length;y++)try{c[y].call(null,v)}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 k=0;k<b.length;k++){var C=b[k],I=C.module;try{C.require(I)}catch(n){if("function"==typeof C.errorHandler)try{C.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 d}}}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(l)),r.o(n,e)||(n[e]=r.m[e])},r.hmrC.jsonp=function(e,s,d,u,h,p){h.push(l),t={},o=s,n=d.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(354)})()));
|
|
1
|
+
/*! Authress Login SDK 2.5.380 | 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={75:(e,t,n)=>{const{sanitizeUrl:o}=n(332),r=n(629),i={"Content-Type":"application/json","X-Powered-By":`Authress Login SDK; Javascript; ${n(330).version}`},a=new Set(["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","Load failed","<HTML DOCUMENT></HTML>"]);function s(e){return"Network Error"===e.message||"ERR_NETWORK"===e.code||!e.status||e.status>=500||"string"==typeof e.message&&a.has(e.message)||"string"==typeof e.data&&a.has(e.data)}async function c(e){let t=null;for(let n=0;n<5;n++)try{return await e()}catch(e){if(e.retryCount=n,!s(e))throw e;t=e,t.isNetworkError=!0,await new Promise((e=>setTimeout(e,10*2**n)));continue}const n=new Error("[Authress Login SDK] Http Request failed due to a Network Error even after multiple retries",{cause:t});throw n.code="AuthressSdkNetworkError",n}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(o(e));this.loginUrl=`${r.origin}/api`}get(e,t,n,o){return c((()=>this.fetchWrapper("GET",e,null,n,t,o)))}delete(e,t,n,o){return c((()=>this.fetchWrapper("DELETE",e,null,n,t,o)))}post(e,t,n,o,r){return c((()=>this.fetchWrapper("POST",e,n,o,t,r)))}put(e,t,n,o,r){return c((()=>this.fetchWrapper("PUT",e,n,o,t,r)))}patch(e,t,n,o,r){return c((()=>this.fetchWrapper("PATCH",e,n,o,t,r)))}async fetchWrapper(e,t,n,o,a,s){const c=`${this.loginUrl}${t.toString()}`,l=e.toUpperCase(),d=Object.assign({},i,o);try{this.logger&&this.logger.debug&&this.logger.debug({title:"[Authress Login SDK] HttpClient Request",method:l,url:c});const e={method:l,headers:d};n&&(e.body=JSON.stringify(n)),!r.isLocalHost()&&a&&(e.credentials="include");const t=await fetch(c,e);if(!t.ok)throw t;let o={};try{o=await t.text(),o=JSON.parse(o)}catch(e){}return{url:c,method:l,headers:t.headers,status:t.status,data:o}}catch(e){let t=e;try{t=await e.text(),t=JSON.parse(t)}catch(e){}const o=t.stack&&t.stack.match(/chrome-extension:[/][/](\w+)[/]/);if(o){this.logger&&this.logger.debug&&this.logger.debug({title:`[Authress Login SDK] Fetch failed due to a browser extension - ${l} - ${c}`,method:l,url:c,data:n,headers:d,error:e,resolvedError:t,extensionErrorId:o});const r=new Error(`Extension Error ID: ${o}`);throw r.code="BROWSER_EXTENSION_ERROR",r}const r=e.status;let i="warn",a="[Authress Login SDK] HttpClient Response Error";e?401===r?(a="[Authress Login SDK] HttpClient Response Error due to invalid token",i="debug"):404===r?(a="[Authress Login SDK] HttpClient Response: Not Found",i="debug"):r<500&&s&&(i="debug"):a="[Authress Login SDK] HttpClient Response Error - Unknown error occurred",this.logger&&this.logger[i]&&this.logger[i]({title:a,online:"undefined"==typeof navigator||navigator.onLine,method:l,url:c,status:r,data:n,headers:d,error:e,resolvedError:t});throw{url:c,method:l,status:r,data:t,headers:e.headers}}}}},160:(e,t,n)=>{const o=n(427),r=n(629),i="AuthenticationCredentialsStorage",a={user:"user",authorization:"authorization",authCode:"auth-code",authUserId:"AuthUserId"};e.exports=new class{constructor(){this.retainUserCookie=!1}getUserCookie(){const e=r.getDocument();if(!e)return null;return e.cookie.split(";").filter((e=>e.split("=")[0].trim()===a.user)).map((e=>e.trim().replace(/^user=/,""))).find((e=>e&&e.trim()))||null}getAuthorizationTokens(){if("undefined"==typeof window||"undefined"==typeof document)return[];return document.cookie.split(";").filter((e=>e.split("=")[0].trim()===a.authorization)).map((e=>e.trim().replace(/^authorization=/,""))).filter((e=>e&&e.trim()))}set(e,t){if("undefined"!=typeof window&&"undefined"!=typeof document)try{const n=o.parse(document.cookie);localStorage.setItem(i,JSON.stringify({idToken:e,expiry:t&&t.getTime(),jsCookies:!!n.authorization})),this.retainUserCookie||this.clearCookies(a.user)}catch(e){console.debug("LocalStorage failed in Browser",e)}}get(){if("undefined"==typeof window||"undefined"==typeof document)return null;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(i)||"{}");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(i)}catch(e){console.debug("LocalStorage failed in Browser",e)}try{this.clearCookies(a.user)}catch(e){console.debug("CookieManagement failed in Browser",e)}}clear(){this.clearCookies(),this.delete()}clearCookies(e){if("undefined"==typeof window||"undefined"==typeof document)return;const t=document.cookie.split("; ");for(const n of t){if(!Object.values(a).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()}}}}},321: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,l=parseInt,d=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:(g=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)&&d.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)?l(e.slice(2),n?2:8):a.test(e)?o:+e}(e))===t||e===-1/0?(e<0?-1:1)*n:e==e?e:0:0===e?e:0}(h),f=g%1,g==g?f?g-f:g:0))<0?0:h):[];var g,f}},330:e=>{"use strict";e.exports=JSON.parse('{"name":"@authress/login","version":"2.5.380","description":"Universal login sdk for Authress authentication as a service. Provides managed authentication for user identity, authentication, and token verification.","main":"./src/index.js","types":"./index.d.ts","files":["index.d.ts","src","dist"],"scripts":{"build":"node make.js build && NODE_ENV=production webpack --mode=production","lint":"eslint --ext .js,.ts src tests make.js index.d.ts","test":"check-dts index.d.ts && mocha tests/*.test.js tests/**/*.test.js -R spec"},"dependencies":{"cookie":"<1","lodash.take":"^4.1.1"},"devDependencies":{"@babel/core":"^7.17.5","@babel/preset-env":"^7.16.11","@types/node":"^14.14.35","@typescript-eslint/eslint-plugin":"^3.1.0","@typescript-eslint/parser":"^3.1.0","babel-loader":"^8.2.3","chai":"^4.2.0","check-dts":"^0.4.4","ci-build-tools":"^1.0.13","commander":"^4.0.1","compression-webpack-plugin":"^9.2.0","eslint":"^7.12.1","eslint-config-cimpress-atsquad":"^1.0.67","eslint-loader":"^4.0.2","eslint-plugin-mocha":"^7.0.1","eslint-plugin-node":"^11.1.0","eslint-plugin-promise":"^6.1.1","fs-extra":"^8.1.0","glob":"^7.1.6","mocha":"^11.1.0","path-browserify":"^1.0.1","sinon":"^7.5.0","sinon-chai":"^3.3.0","terser-webpack-plugin":"^5.3.1","typescript":"^3.9.5","webpack":"^5.69.1","webpack-cli":"^4.9.2"},"repository":{"type":"git","url":"git+https://github.com/Authress/authress-login.js"},"keywords":["authentication","authentication as a service","Login","Login Client","universal login","auth","federated login","secure login","application security","IDaaS","authentication","user authentication","user identity","Oauth2","Oauth2.1","Oauth3","platform","platform login","extension","Authress","Authress client","user security","DBSC","Device Bound Session Credentials"],"author":"Authress Developers <developers@authress.io> (https://authress.io)","license":"Apache-2.0","bugs":{"url":"https://github.com/Authress/authress-login.js/issues"},"homepage":"https://authress.io","engines":{"node":">=18"}}')},332:e=>{e.exports.sanitizeUrl=function(e){let t=e;t.startsWith("http")||(t=`https://${t}`);const n=new URL(t),o=n.host.match(/^([a-z0-9-]+)[.][a-z0-9-]+[.]authress[.]io$/);return o&&(n.host=`${o[1]}.login.authress.io`,t=n.toString()),t.replace(/[/]+$/,"")}},354:(e,t,n)=>{const o=n(427),r=n(321),i=n(629),a=n(75),s=n(836),{sanitizeUrl:c}=n(332),l=n(160);let d,u=new Promise((e=>d=e)),h=Promise.resolve(),p=!1;const g="AuthenticationRequestNonce";const f=n(568);e.exports={LoginClient:class{constructor(e,t){const n=Object.assign({applicationId:"app_default"},e);this.logger=t||console;const o=n.authressApiUrl||n.authressLoginHostUrl||n.authenticationServiceUrl||"";if(!o)throw Error('Missing required property "authressApiUrl" in LoginClient constructor. Custom Authress Domain Host is required.');if(this.applicationId=n.applicationId,!this.applicationId||this.applicationId.match(/^(sc_|ext_)/)){const e=Error("You have incorrectly specified an Authress Service Client or Extension as the applicationId instead of a valid application. The applicationId is your application that your users will log into, usually hosted on your domain https://example.yourdomain.com. Users cannot log *into* a Service Client, but they can log in *with* one. Users can use a Service Client to log in, by setting the connection ID in the *authenticate({ connectionId })* method to be the Authress Service Client.\n(1) If you are building an Custom Login Portal, then the application ID should correspond to this login portal.\n(2) If you are replacing or extending an Authress connection, then specify the Service Client as the connectionId and the end user application as the applicationId.\n(3) If you are building a platform or plugin marketplace, where users will log into third party extensions or apps, then distribute in your SDK a wrapper for the Authress Extension Client using: import { extensionClient } from '@authress/login' found within this SDK.\n(4) If you aren't sure what to do here to fix the problem, the fastest and usually correct solution is go to https://authress.io/app/#/settings?focus=applications create a new application, specify your site in the application url property and then update the value here.");throw e.code="InvalidApplication",e}this.hostUrl=c(o),this.httpClient=new a(this.hostUrl,t),this.lastSessionCheck=0,this.enableCredentials=this.getMatchingDomainInfo(this.hostUrl),l.retainUserCookie=e.retainUserCookie,n.skipBackgroundCredentialsCheck||i.onLoad((async()=>{await this.userSessionExists({backgroundTrigger:!0})}))}getMatchingDomainInfo(e){const t=new URL(e);if(i.isLocalHost())return!1;const n=i.getCurrentLocation();if("https:"!==n.protocol)return!1;const o=t.host.toLowerCase().split(".").reverse(),a=n.host.toLowerCase().split(".").reverse();let s=[];for(let e of o){const t=r(a,s.length+1).join(".");if(s.concat(e).join(".")!==t)break;s.push(e)}return s.length===o.length&&s.length===a.length||s.length>1}getUserIdentity(){const e=l.getUserCookie(),t=s.decodeOrParse(e);if(t){const n=t.exp?new Date(1e3*t.exp):new Date(Date.now()+864e5);return l.set(e,n),t.userId=t.sub,t}const n=l.get(),o=s.decodeOrParse(n);if(!o)return null;const r=new URL(o.iss).hostname,i=new URL(this.hostUrl).hostname;return r.endsWith(i)||i.endsWith(r)?(o.userId=o.sub,o):(l.clear(),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(){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){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:"[Authress Login SDK] Failed to delete device",error:e}),e}}async openUserConfigurationScreen(e={redirectUrl:null,startPage:"Profile"}){if(!await this.userSessionExists()){const e=Error("User must be logged to configure user profile data.");throw e.code="NotLoggedIn",e}const t=new URL("/settings",this.hostUrl);t.searchParams.set("client_id",this.applicationId),t.searchParams.set("start_page",e&&e.startPage||"Profile"),t.searchParams.set("redirect_uri",e&&e.redirectUrl||i.getCurrentLocation().href),i.assign(t.toString()),await Promise.resolve()}async registerDevice(e={name:"",type:"",totp:{}}){const t=await this.getUserIdentity();if(!t){const e=Error("User must be logged to configure user profile data.");throw e.code="NotLoggedIn",e}if(!e){const e=Error("Register Device missing required parameter: 'Options'");throw e.code="InvalidInput",e}let n;if(e.type&&"WebAuthN"!==e.type)"TOTP"===e.type&&(n={name:e.name,code:e.totp.verificationCode,totpData:e.totp,type:"TOTP"});else{const o=t.sub,r={challenge:Uint8Array.from(o,(e=>e.charCodeAt(0))),rp:{id:this.hostUrl.split(".").slice(1).join("."),name:"WebAuthN Login"},user:{id:Uint8Array.from(o,(e=>e.charCodeAt(0))),name:o,displayName:`Generated User ID: ${o}`},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{residentKey:"discouraged",requireResidentKey:!1,userVerification:"discouraged"},timeout:6e4,attestation:"direct"},i=await navigator.credentials.create({publicKey:r}),a={authenticatorAttachment:i.authenticatorAttachment,credentialId:i.id,type:i.type,userId:o,attestation:btoa(String.fromCharCode(...new Uint8Array(i.response.attestationObject))),client:btoa(String.fromCharCode(...new Uint8Array(i.response.clientDataJSON)))};n={name:e&&e.name,code:a,type:"WebAuthN"}}try{const e=await this.ensureToken();return(await this.httpClient.post("/session/devices",this.enableCredentials,n,{Authorization:e&&`Bearer ${e}`})).data}catch(e){throw this.logger&&this.logger.log({title:"[Authress Login SDK] Failed to register new device",error:e,request:n}),e}}async waitForUserSession(){try{return await u,!0}catch(e){return!1}}userSessionExists(e={backgroundTrigger:!1}){return Date.now()-this.lastSessionCheck<50||p?h:(this.lastSessionCheck=Date.now(),p=!0,h=h.catch((()=>{})).then((async()=>{try{const t=await this.userSessionContinuation(null==e?void 0:e.backgroundTrigger);return p=!1,t}catch(e){throw p=!1,e}})))}async userSessionContinuation(e){const t=new URLSearchParams(i.getCurrentLocation().search);let n={};if("undefined"!=typeof localStorage)try{n=JSON.parse(localStorage.getItem(g)||"{}"),localStorage.removeItem(g),Object.hasOwnProperty.call(n,"enableCredentials")&&(this.enableCredentials=n.enableCredentials)}catch(e){this.logger&&this.logger.debug&&this.logger.debug({title:"[Authress Login SDK] LocalStorage failed in Browser",error:e})}if(t.get("state")&&"oauthLogin"===t.get("flow"))return!1;if((n.nonce||t.get("iss")&&t.get("iss").includes(this.hostUrl))&&this.sanitizeQueryParameters(),n.nonce&&t.get("code")&&n.nonce===t.get("nonce")){const e="cookie"===t.get("code")?o.parse(document.cookie)["auth-code"]:t.get("code"),r=await s.calculateAntiAbuseHash({client_id:this.applicationId,authenticationRequestId:n.nonce,code:e}),i={grant_type:"authorization_code",redirect_uri:n.redirectUrl,client_id:this.applicationId,code:e,code_verifier:n.codeVerifier,antiAbuseHash:r};try{const e=await this.httpClient.post(`/authentication/${n.nonce}/tokens`,this.enableCredentials,i),t=s.decode(e.data.id_token),r=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:r,path:"/",sameSite:"strict"}),l.set(e.data.id_token,r),d(),!0}catch(e){if(this.logger&&this.logger.log({title:"[Authress Login SDK] Failed exchange authentication response for a token.",error:e}),e.data&&"invalid_request"===e.data.error)return!1;throw e.data||e}}if(i.isLocalHost()&&t.get("nonce")&&t.get("access_token")&&(!n.nonce||n.nonce===t.get("nonce"))){const e=s.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"}),l.set(t.get("id_token"),n),d(),!0}if(this.getUserIdentity())return d(),!0;if(!i.isLocalHost()&&!e){try{const e=await this.httpClient.patch("/session",this.enableCredentials,{},null,!0);if(e.data.access_token){const t=s.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"}),l.set(e.data.id_token,n)}}catch(e){400===e.status||404===e.status||409===e.status?this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] User does not have an existing authentication session",error:e}):this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Failed attempting to check if the user has an existing authentication session",error:e})}if(this.getUserIdentity())return d(),!0}return!1}async updateExtensionAuthenticationRequest({state:e,connectionId:t,tenantLookupIdentifier:n,connectionProperties:o,hint:r}){if(!t&&!n&&!r){const e=Error("connectionId or tenantLookupIdentifier must be specified");throw e.code="InvalidConnection",e}const a=new URLSearchParams(i.getCurrentLocation().search),c=e||a.get("state");if(!c){const e=Error("The `state` parameters must be specified to update this authentication request");throw e.code="InvalidAuthenticationRequest",e}try{const e=r||n,a=await s.calculateAntiAbuseHash({connectionId:t,tenantLookupIdentifier:e,authenticationRequestId:c}),l=await this.httpClient.patch(`/authentication/${c}`,!0,{antiAbuseHash:a,connectionId:t,tenantLookupIdentifier:e,connectionProperties:o});if(new URL(l.data.authenticationUrl).hostname===i.getCurrentLocation().hostname)return{authenticationUrl:l.data.authenticationUrl};i.assign(l.data.authenticationUrl)}catch(e){if(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Failed to update extension authentication request",error:e}),e.status&&e.status>=400&&e.status<500){const t=Error(e.data&&(e.data.title||e.data.errorCode)||e.data||"Unknown Error");throw t.code=e.data&&e.data.errorCode,t}throw e.data||e}return await new Promise((e=>setTimeout(e,5e3))),null}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 in 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&&!i.isLocalHost()?{}:{Authorization:`Bearer ${t}`};try{await this.httpClient.delete(`/identities/${encodeURIComponent(e)}`,this.enableCredentials,n)}catch(e){if(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Failed to unlink user identity",error:e}),e.status&&e.status>=400&&e.status<500){const t=Error(e.data&&(e.data.title||e.data.errorCode)||e.data||"Unknown Error");throw t.code=e.data&&e.data.errorCode,t}throw e.data||e}}async linkIdentityWithOneTimeCode({connectionId:e,redirectUrl:t}){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 an existing account before linking a second account.");throw e.code="NotLoggedIn",e}let n;try{n=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:o}=await s.getAuthCodes(),r=await s.calculateAntiAbuseHash({connectionId:e,applicationId:this.applicationId});try{const a=t&&new URL(t).toString()||i.getCurrentLocation().href,s=this.enableCredentials&&!i.isLocalHost()?{}:{Authorization:`Bearer ${n}`},c=await this.httpClient.post("/authentication",this.enableCredentials,{antiAbuseHash:r,linkIdentity:!0,redirectUrl:a,codeChallengeMethod:"S256",codeChallenge:o,connectionId:e,applicationId:this.applicationId},s);return{authenticationUrl:c.data.authenticationUrl,authenticationRequestId:c.data.authenticationRequestId}}catch(e){if(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Failed to start user identity link",error:e}),e.status&&e.status>=400&&e.status<500){const t=Error(e.data&&(e.data.title||e.data.errorCode)||e.data||"Unknown Error");throw t.code=e.data&&e.data.errorCode,t}throw 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:a}=await s.getAuthCodes(),c=await s.calculateAntiAbuseHash({connectionId:e,tenantLookupIdentifier:t,applicationId:this.applicationId});try{const s=n&&new URL(n).toString()||i.getCurrentLocation().href,l=this.enableCredentials&&!i.isLocalHost()?{}:{Authorization:`Bearer ${r}`},d=await this.httpClient.post("/authentication",this.enableCredentials,{antiAbuseHash:c,linkIdentity:!0,redirectUrl:s,codeChallengeMethod:"S256",codeChallenge:a,connectionId:e,tenantLookupIdentifier:t,connectionProperties:o,applicationId:this.applicationId},l);i.assign(d.data.authenticationUrl)}catch(e){if(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Failed to start user identity link",error:e}),e.status&&e.status>=400&&e.status<500){const t=Error(e.data&&(e.data.title||e.data.errorCode)||e.data||"Unknown Error");throw t.code=e.data&&e.data.errorCode,t}throw e}await new Promise((e=>setTimeout(e,5e3)))}async authenticateWithOneTimeCode(e={}){const{serviceClientId:t,inviteId:n,redirectUrl:o,force:r,responseLocation:a,flowType:c,clearUserDataBeforeLogin:d}=e||{};if(a&&"cookie"!==a&&"query"!==a&&"none"!==a){const e=Error("Authentication response location is not valid");throw e.code="InvalidResponseLocation",e}if(!t){const e=Error("The Passwordless Service Client ID is required");throw e.code="InvalidInput",e}if(!n&&!r&&await this.userSessionExists()){const n=await this.ensureToken(),o=s.decode(n);if(o&&o.azp&&t!==o.azp){this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Authentication blocked because the user is already logged in, and the requested authentication parameters do not match the original session.",requestedAuthenticationOptions:e,currentAuthenticationSessionData:o});const t=Error('Authentication requested for user that is already logged in, but the connectionId specified does not match their existing session.\n Recommended Options:\n (1) If the goal is to force them to log in with this new connection and ignore their existing session, use the "force" flag.\n (2) If the goal is link their current identity with a new from the new connection, use the linkIdentity() method.\n (3) If the goal is skip log in if they are already logged in or force log in with the connectionId, first check if userSessionExists() and then only if "false", call authenticate().');throw t.code="AuthenticationConstraintContention",t}return null}const{codeVerifier:u,codeChallenge:h}=await s.getAuthCodes(),p=await s.calculateAntiAbuseHash({serviceClientId:t,inviteId:n,applicationId:this.applicationId});try{const e=o&&new URL(o).toString()||i.getCurrentLocation().href;!1!==d&&l.clear();const r=await this.httpClient.post("/authentication",this.enableCredentials,{antiAbuseHash:p,redirectUrl:e,codeChallengeMethod:"S256",codeChallenge:h,connectionId:t,inviteId:n,applicationId:this.applicationId,responseLocation:a,flowType:c});return localStorage.setItem(g,JSON.stringify({nonce:r.data.authenticationRequestId,codeVerifier:u,lastConnectionId:t,redirectUrl:e,enableCredentials:r.data.enableCredentials})),{authenticationUrl:r.data.authenticationUrl,authenticationRequestId:r.data.authenticationRequestId}}catch(e){if(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Failed to start authentication for user",error:e}),e.status&&e.status>=400&&e.status<500){const t=Error(e.data&&(e.data.title||e.data.errorCode)||e.data||"Unknown Error");throw t.code=e.data&&e.data.errorCode,t}throw e.data||e}}async authenticate(e={}){const{connectionId:t,tenantLookupIdentifier:n,inviteId:o,redirectUrl:r,force:a,responseLocation:c,flowType:d,connectionProperties:u,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(!o&&!a&&!p&&await this.userSessionExists()){const n=await this.ensureToken(),o=s.decode(n);if(t&&o&&o.azp&&t!==o.azp){this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Authentication blocked because the user is already logged in, and the requested authentication parameters do not match the original session.",requestedAuthenticationOptions:e,currentAuthenticationSessionData:o});const t=Error('Authentication requested for user that is already logged in, but the connectionId specified does not match their existing session.\n Recommended Options:\n (1) If the goal is to force them to log in with this new connection and ignore their existing session, use the "force" flag.\n (2) If the goal is link their current identity with a new from the new connection, use the linkIdentity() method.\n (3) If the goal is skip log in if they are already logged in or force log in with the connectionId, first check if userSessionExists() and then only if "false", call authenticate().');throw t.code="AuthenticationConstraintContention",t}return null}const{codeVerifier:m,codeChallenge:w}=await s.getAuthCodes(),y=await s.calculateAntiAbuseHash({connectionId:t,tenantLookupIdentifier:n,inviteId:o,applicationId:this.applicationId});try{const e=r&&new URL(r).toString()||i.getCurrentLocation().href;!1!==f&&l.clear();const a=await this.httpClient.post("/authentication",!1,{antiAbuseHash:y,redirectUrl:e,codeChallengeMethod:"S256",codeChallenge:w,connectionId:t,tenantLookupIdentifier:n,inviteId:o,connectionProperties:u,applicationId:this.applicationId,responseLocation:c,flowType:d,multiAccount:p});if(localStorage.setItem(g,JSON.stringify({nonce:a.data.authenticationRequestId,codeVerifier:m,lastConnectionId:t,tenantLookupIdentifier:n,redirectUrl:e,enableCredentials:a.data.enableCredentials,multiAccount:p})),!a.data.authenticationUrl||new URL(a.data.authenticationUrl).hostname===i.getCurrentLocation().hostname)return{authenticationUrl:a.data.authenticationUrl,authenticationRequestId:a.data.authenticationRequestId};if("tab"===h){const e=i.open(a.data.authenticationUrl,"_blank");e&&!e.closed&&void 0!==e.closed||i.assign(a.data.authenticationUrl)}else i.assign(a.data.authenticationUrl)}catch(e){if(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Failed to start authentication for user",error:e}),e.status&&e.status>=400&&e.status<500){const t=Error(e.data&&(e.data.title||e.data.errorCode)||e.data||"Unknown Error");throw t.code=e.data&&e.data.errorCode,t}throw e.data||e}return await new Promise((e=>setTimeout(e,5e3))),null}async ensureToken(e){if(e&&0===e.timeoutInMillis){if(!this.getUserIdentity()){const e=Error("No token retrieved after timeout");throw e.code="TokenTimeout",e}const t=l.getAuthorizationTokens(),n=t.find((t=>{try{const n=s.decode(t);return(null==n?void 0:n.iss)===this.hostUrl||(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Skipping stored authorization cookie because the issuer does not match the library configured value.",requestedAuthenticationOptions:e,currentAuthenticationSessionData:n}),!1)}catch(n){return this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Skipping stored authorization cookie because it is no longer a valid token.",requestedAuthenticationOptions:e,currentAuthenticationSessionDataToken:t,error:n}),!1}}));return n||(t.length?(this.logger&&this.logger.error&&this.logger.log({title:"[Authress Login SDK] No matching issuer token found, returning the first valid token instead."}),t[0]):(this.logger&&this.logger.error&&this.logger.error({title:"[Authress Login SDK] HttpOnly access token configuration has blocked the returning of a valid token. The application specified in the Authress LoginClient constructor has been configured to block returning access tokens via the enableAccessToToken property. To use the loginClient.ensureToken() method in production, please set the enableAccessToToken to true. Note: This setting does not affect localhost."}),null))}await this.userSessionExists();const t=Object.assign({timeoutInMillis:5e3},e||{}),n=this.waitForUserSession(),o=-1===t.timeoutInMillis||t.timeoutInMillis>2**31-1?2**31-1:t.timeoutInMillis,r=new Promise(((e,t)=>setTimeout(t,o||0)));try{await Promise.race([n,r])}catch(e){const t=Error("No token retrieved after timeout");throw t.code="TokenTimeout",t}const i=l.getAuthorizationTokens(),a=i.find((t=>{try{const n=s.decode(t);return(null==n?void 0:n.iss)===this.hostUrl||(this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Skipping stored authorization cookie because the issuer does not match the library configured value.",requestedAuthenticationOptions:e,currentAuthenticationSessionData:n}),!1)}catch(n){return this.logger&&this.logger.log&&this.logger.log({title:"[Authress Login SDK] Skipping stored authorization cookie because it is no longer a valid token.",requestedAuthenticationOptions:e,currentAuthenticationSessionDataToken:t,error:n}),!1}}));return a||(i.length?(this.logger&&this.logger.error&&this.logger.log({title:"[Authress Login SDK] No matching issuer token found, returning the first valid token instead."}),i[0]):(this.logger&&this.logger.error&&this.logger.error({title:"[Authress Login SDK] HttpOnly access token configuration has blocked the returning of a valid token. The application specified in the Authress LoginClient constructor has been configured to block returning access tokens via the enableAccessToToken property. To use the loginClient.ensureToken() method in production, please set the enableAccessToToken to true. Note: This setting does not affect localhost."}),null))}async logout(e){let t;if(e)try{new URL(e),t=e}catch(n){try{t=new URL(e,i.getCurrentLocation().href).toString()}catch(t){const n=Error(`The logout redirect url is not valid URL: ${e}`);throw n.code="InvalidRedirectUrl",n}}if(l.clear(),this.sanitizeQueryParameters(),u=new Promise((e=>d=e)),this.enableCredentials)try{return await this.httpClient.delete("/session",this.enableCredentials),this.lastSessionCheck=0,void(e&&e!==i.getCurrentLocation().href&&i.assign(e))}catch(e){}const n=new URL("/logout",this.hostUrl);n.searchParams.set("redirect_uri",t||i.getCurrentLocation().href),n.searchParams.set("client_id",this.applicationId),i.assign(n.toString()),this.lastSessionCheck=0,await new Promise((e=>setTimeout(e,500)))}sanitizeQueryParameters(){const e=new URL(i.getCurrentLocation());e.searchParams.delete("iss"),e.searchParams.delete("nonce"),e.searchParams.delete("code"),e.searchParams.delete("expires_in"),e.searchParams.delete("access_token"),e.searchParams.delete("id_token"),history.replaceState({},void 0,e.toString())}},ExtensionClient:f,UserConfigurationScreen:{Profile:"Profile",MFA:"MFA"}}},427:(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=e.length;if(r<2)return n;var i=t&&t.decode||d,a=0,s=0,h=0;do{if(-1===(s=e.indexOf("=",a)))break;if(-1===(h=e.indexOf(";",a)))h=r;else if(s>h){a=e.lastIndexOf(";",s-1)+1;continue}var p=c(e,a,s),g=l(e,s,p),f=e.slice(p,g);if(!o.call(n,f)){var m=c(e,s+1,h),w=l(e,h,m);34===e.charCodeAt(m)&&34===e.charCodeAt(w-1)&&(m++,w--);var y=e.slice(m,w);n[f]=u(y,i)}a=h+1}while(a<r);return n},t.serialize=function(e,t,o){var c=o&&o.encode||encodeURIComponent;if("function"!=typeof c)throw new TypeError("option encode is invalid");if(!r.test(e))throw new TypeError("argument name is invalid");var l=c(t);if(!i.test(l))throw new TypeError("argument val is invalid");var d=e+"="+l;if(!o)return d;if(null!=o.maxAge){var u=Math.floor(o.maxAge);if(!isFinite(u))throw new TypeError("option maxAge is invalid");d+="; Max-Age="+u}if(o.domain){if(!a.test(o.domain))throw new TypeError("option domain is invalid");d+="; Domain="+o.domain}if(o.path){if(!s.test(o.path))throw new TypeError("option path is invalid");d+="; Path="+o.path}if(o.expires){var h=o.expires;if(!function(e){return"[object Date]"===n.call(e)}(h)||isNaN(h.valueOf()))throw new TypeError("option expires is invalid");d+="; Expires="+h.toUTCString()}o.httpOnly&&(d+="; HttpOnly");o.secure&&(d+="; Secure");o.partitioned&&(d+="; Partitioned");if(o.priority){switch("string"==typeof o.priority?o.priority.toLowerCase():o.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(o.sameSite){switch("string"==typeof o.sameSite?o.sameSite.toLowerCase():o.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=Object.prototype.hasOwnProperty,r=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,i=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,a=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,s=/^[\u0020-\u003A\u003D-\u007E]*$/;function c(e,t,n){do{var o=e.charCodeAt(t);if(32!==o&&9!==o)return t}while(++t<n);return n}function l(e,t,n){for(;t>n;){var o=e.charCodeAt(--t);if(32!==o&&9!==o)return t+1}return n}function d(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function u(e,t){try{return t(e)}catch(t){return e}}},568:(e,t,n)=>{const o=n(836),{sanitizeUrl:r}=n(332),i=n(629),a="ExtensionRequestNonce";let s=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=r(e),this.accessToken=null,i.onLoad((async()=>{await this.requestToken({silent:!0})}))}async getUserIdentity(){const e=this.accessToken&&await 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(s)return s=s.catch((()=>{})).then((()=>this.requestTokenContinuation(e)));const t=this.requestTokenContinuation(e);return t.catch((()=>{})),s=t}async requestTokenContinuation(e={code:null,silent:!1}){const t=e&&e.code||new URLSearchParams(i.getCurrentLocation().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(a)||"{}"),s=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})}),c=await s.json();this.accessToken=c.access_token;const l=new URL(i.getCurrentLocation());return l.searchParams.delete("code"),l.searchParams.delete("iss"),l.searchParams.delete("nonce"),l.searchParams.delete("expires_in"),l.searchParams.delete("access_token"),l.searchParams.delete("id_token"),history.replaceState({},void 0,l.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),{codeVerifier:s,codeChallenge:c}=o.getAuthCodes(),l=e||i.getCurrentLocation().href;return localStorage.setItem(a,JSON.stringify({codeVerifier:s,redirectUrl:l})),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",l),i.assign(r.toString()),await new Promise((e=>setTimeout(e,5e3))),null}}},629:e=>{e.exports=new class{onLoad(e){"undefined"!=typeof window&&(window.onload=e)}isLocalHost(){return"undefined"!=typeof window&&window.location&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname)}getCurrentLocation(){return"undefined"!=typeof window&&new URL(window.location)||new URL("http://localhost:8080")}getDocument(){return"undefined"==typeof window||"undefined"==typeof document?null:document}assign(e){return"undefined"==typeof window?null:window.location.assign(e.toString())}open(e){return"undefined"==typeof window?null:window.open(e.toString())}}},836:(e,t,n)=>{const o=n(878);e.exports=new class{decode(e){var t;return e?null===(t=this.decodeFull(e))||void 0===t?void 0:t.payload: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;let t=null;try{t=JSON.parse(o.decode(e.split(".")[0]))}catch(e){}try{const 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)}}async calculateAntiAbuseHash(e){const t=Date.now(),n=Object.values(e).filter((e=>e)).join("|");let r=0,i=null;for(;++r&&(i=o.encode(await(window.crypto||window.msCrypto).subtle.digest("SHA-256",(new TextEncoder).encode(`${t};${r};${n}`))),!i.match(/^00/)););return`v2;${t};${r};${i}`}}},878: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(/=+$/,"")}}},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=()=>"67a935fe7773122d5cfd",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 l=document.getElementsByTagName("script"),d=0;d<l.length;d++){var u=l[d];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",l=0,d=[];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).then((function(){}))}function h(){0==--l&&u("ready").then((function(){if(0===l){var e=d;d=[];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?f(e):u("ready").then((function(){return o}))},0===l?t():new Promise((function(e){d.push((function(){e(t())}))}));var t}))})):u(m()?"ready":"idle").then((function(){return null}))}))}function g(e){return"ready"!==c?Promise.resolve().then((function(){throw new Error("apply() is only allowed in ready status (state: "+c+")")})):f(e)}function f(e){e=e||{},m();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)},l=[];return o.forEach((function(e){if(e.apply){var t=e.apply(c);if(t)for(var n=0;n<t.length;n++)l.push(t[n])}})),Promise.all([i,s]).then((function(){return a?u("fail").then((function(){throw a})):n?f(e).then((function(e){return l.forEach((function(t){e.indexOf(t)<0&&e.push(t)})),e})):u("idle").then((function(){return l}))}))}function m(){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(d){var f,m,w,y,k=d.module,v=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 d in t)Object.prototype.hasOwnProperty.call(t,d)&&"e"!==d&&Object.defineProperty(r,d,s(d));return r.e=function(e,n){return function(e){switch(c){case"ready":u("prepare");case"prepare":return l++,e.then(h,h),e;default:return e}}(t.e(e,n))},r}(d.require,d.id);k.hot=(f=d.id,m=k,y={_acceptedDependencies:{},_acceptedErrorHandlers:{},_declinedDependencies:{},_selfAccepted:!1,_selfDeclined:!1,_selfInvalidated:!1,_disposeHandlers:[],_main:w=e!==f,_requireSelf:function(){a=m.parents.slice(),e=w?void 0:f,r(f)},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](f,t)})),u("ready");break;case"ready":Object.keys(r.hmrI).forEach((function(e){r.hmrI[e](f,t)}));break;case"prepare":case"check":case"dispose":case"apply":(n=n||[]).push(f)}},check:p,apply:g,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[f]},e=void 0,y),k.parents=a,k.children=[],a=[],d.require=v})),r.hmrC={},r.hmrI={}})(),r.p="",(()=>{var e,t,n,o,i,a=r.hmrS_jsonp=r.hmrS_jsonp||{792: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 l(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,l=r.c[a];if(l&&(!l.hot._selfAccepted||l.hot._selfInvalidated)){if(l.hot._selfDeclined)return{type:"self-declined",chain:s,moduleId:a};if(l.hot._main)return{type:"unaccepted",chain:s,moduleId:a};for(var d=0;d<l.parents.length;d++){var u=l.parents[d],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 l={},d=[],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 g=n[p],f=g?s(p):{type:"disposed",moduleId:p},m=!1,w=!1,y=!1,k="";switch(f.chain&&(k="\nUpdate propagation: "+f.chain.join(" -> ")),f.type){case"self-declined":e.onDeclined&&e.onDeclined(f),e.ignoreDeclined||(m=new Error("Aborted because of self decline: "+f.moduleId+k));break;case"declined":e.onDeclined&&e.onDeclined(f),e.ignoreDeclined||(m=new Error("Aborted because of declined dependency: "+f.moduleId+" in "+f.parentId+k));break;case"unaccepted":e.onUnaccepted&&e.onUnaccepted(f),e.ignoreUnaccepted||(m=new Error("Aborted because "+p+" is not accepted"+k));break;case"accepted":e.onAccepted&&e.onAccepted(f),w=!0;break;case"disposed":e.onDisposed&&e.onDisposed(f),y=!0;break;default:throw new Error("Unexception type "+f.type)}if(m)return{error:m};if(w)for(p in u[p]=g,c(d,f.outdatedModules),f.outdatedDependencies)r.o(f.outdatedDependencies,p)&&(l[p]||(l[p]=[]),c(l[p],f.outdatedDependencies[p]));y&&(c(d,[f.moduleId]),u[p]=h)}n=void 0;for(var v,b=[],C=0;C<d.length;C++){var I=d[C],S=r.c[I];S&&(S.hot._selfAccepted||S.hot._main)&&u[I]!==h&&!S.hot._selfInvalidated&&b.push({module:I,require:S.hot._requireSelf,errorHandler:S.hot._selfAccepted})}return{dispose:function(){var e;o.forEach((function(e){delete a[e]})),o=void 0;for(var t,n=d.slice();n.length>0;){var i=n.pop(),s=r.c[i];if(s){var c={},u=s.hot._disposeHandlers;for(C=0;C<u.length;C++)u[C].call(null,c);for(r.hmrD[i]=c,s.hot.active=!1,delete r.c[i],delete l[i],C=0;C<s.children.length;C++){var h=r.c[s.children[C]];h&&((e=h.parents.indexOf(i))>=0&&h.parents.splice(e,1))}}}for(var p in l)if(r.o(l,p)&&(s=r.c[p]))for(v=l[p],C=0;C<v.length;C++)t=v[C],(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 l)if(r.o(l,a)){var s=r.c[a];if(s){v=l[a];for(var c=[],h=[],p=[],g=0;g<v.length;g++){var f=v[g],m=s.hot._acceptedDependencies[f],w=s.hot._acceptedErrorHandlers[f];if(m){if(-1!==c.indexOf(m))continue;c.push(m),h.push(w),p.push(f)}}for(var y=0;y<c.length;y++)try{c[y].call(null,v)}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 k=0;k<b.length;k++){var C=b[k],I=C.module;try{C.require(I)}catch(n){if("function"==typeof C.errorHandler)try{C.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 d}}}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(l)),r.o(n,e)||(n[e]=r.m[e])},r.hmrC.jsonp=function(e,s,d,u,h,p){h.push(l),t={},o=s,n=d.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(354)})()));
|
|
Binary file
|
package/dist/authress.min.js.gz
CHANGED
|
Binary file
|
package/index.d.ts
CHANGED
|
@@ -78,6 +78,8 @@ export interface ExtensionAuthenticationParameters {
|
|
|
78
78
|
connectionId?: string;
|
|
79
79
|
/** Instead of connectionId, specify the tenant lookup identifier to log the user with the mapped tenant - see https://authress.io/app/#/manage?focus=tenants */
|
|
80
80
|
tenantLookupIdentifier?: string;
|
|
81
|
+
/** Instead of connectionId or tenant lookup identifier, specify the user's domain or the full email for the user to dynamically identify and log the user with the mapped tenant. */
|
|
82
|
+
hint?: string;
|
|
81
83
|
/** Invite to use to login, only one of the connectionId, tenantLookupIdentifier, or the inviteId is required. */
|
|
82
84
|
inviteId?: string;
|
|
83
85
|
/** Overrides the connection specific properties from the Authress Identity Connection to pass to the identity provider */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@authress/login",
|
|
3
|
-
"version": "2.5.
|
|
3
|
+
"version": "2.5.380",
|
|
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
|
@@ -433,11 +433,12 @@ class LoginClient {
|
|
|
433
433
|
* @param {String} [state] The redirect to your login screen will contain two query parameters `state` and `flow`. Pass the state into this method.
|
|
434
434
|
* @param {String} [connectionId] Specify which provider connection that user would like to use to log in - see https://authress.io/app/#/manage?focus=connections
|
|
435
435
|
* @param {String} [tenantLookupIdentifier] Instead of connectionId, specify the tenant lookup identifier to log the user with the mapped tenant - see https://authress.io/app/#/manage?focus=tenants
|
|
436
|
+
* @param {String} [hint] Instead of connectionId or tenant lookup identifier, specify the user's domain or the full email for the user to dynamically identify and log the user with the mapped tenant.
|
|
436
437
|
* @param {Object} [connectionProperties] Connection specific properties to pass to the identity provider. Can be used to override default scopes for example.
|
|
437
438
|
* @return {Promise<AuthenticateResponse | null>} The authentication response.
|
|
438
439
|
*/
|
|
439
|
-
async updateExtensionAuthenticationRequest({ state, connectionId, tenantLookupIdentifier, connectionProperties }) {
|
|
440
|
-
if (!connectionId && !tenantLookupIdentifier) {
|
|
440
|
+
async updateExtensionAuthenticationRequest({ state, connectionId, tenantLookupIdentifier, connectionProperties, hint }) {
|
|
441
|
+
if (!connectionId && !tenantLookupIdentifier && !hint) {
|
|
441
442
|
const e = Error('connectionId or tenantLookupIdentifier must be specified');
|
|
442
443
|
e.code = 'InvalidConnection';
|
|
443
444
|
throw e;
|
|
@@ -452,10 +453,13 @@ class LoginClient {
|
|
|
452
453
|
}
|
|
453
454
|
|
|
454
455
|
try {
|
|
455
|
-
const
|
|
456
|
+
const resolvedTenantLookupIdentifier = hint || tenantLookupIdentifier;
|
|
457
|
+
const antiAbuseHash = await jwtManager.calculateAntiAbuseHash({ connectionId, tenantLookupIdentifier: resolvedTenantLookupIdentifier, authenticationRequestId });
|
|
456
458
|
const requestOptions = await this.httpClient.patch(`/authentication/${authenticationRequestId}`, true, {
|
|
457
459
|
antiAbuseHash,
|
|
458
|
-
connectionId,
|
|
460
|
+
connectionId,
|
|
461
|
+
tenantLookupIdentifier: resolvedTenantLookupIdentifier,
|
|
462
|
+
connectionProperties
|
|
459
463
|
});
|
|
460
464
|
|
|
461
465
|
// If authenticate is called from inside the custom login screen then instead return the redirect url and let the caller deal with it. That is, if the federated login provider is the same as the current UI, there is no need to do anything special.
|