@passflow/core 0.42.1 → 0.43.0
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/README.md +26 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +66 -7
- package/dist/index.d.ts +66 -7
- package/dist/index.mjs +1250 -1226
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("axios");c=s(c,1);let l=require("@simplewebauthn/browser");var u=`__passflowAntiBot`,d=(e,t)=>{let n=t?{operation:e,identifier:t}:{operation:e};return{[u]:n}},f=e=>{if(typeof e!=`object`||!e)return;let t=e[u];return typeof t==`object`&&t?t:void 0},p=`0.42.1`,m=`X-Passflow-Clientid`,h=`Authorization`,g=`X-Passflow-DeviceId`,_=`X-Passflow-DeviceType`,v=`X-Passflow-Anti-Bot`,y=`X-Passflow-Agent-Tool`,b=`X-Passflow-Device-Proof`,x=`passflow_auth`,S=p,C=[`id`,`offline`,`openid`],w=[`id`,`offline`,`tenant`,`email`,`oidc`,`openid`,`access:tenant:all`],T=`https://auth.passflow.cloud`,E=`default`,D=500,ee=600,te=100,O=6e4,ne=30,re=3,ie=30,ae=200,k=[];for(let e=0;e<256;++e)k.push((e+256).toString(16).slice(1));function A(e,t=0){return(k[e[t+0]]+k[e[t+1]]+k[e[t+2]]+k[e[t+3]]+`-`+k[e[t+4]]+k[e[t+5]]+`-`+k[e[t+6]]+k[e[t+7]]+`-`+k[e[t+8]]+k[e[t+9]]+`-`+k[e[t+10]]+k[e[t+11]]+k[e[t+12]]+k[e[t+13]]+k[e[t+14]]+k[e[t+15]]).toLowerCase()}var oe=new Uint8Array(16);function se(){return crypto.getRandomValues(oe)}function ce(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():j(e,t,n)}function j(e,t,n){e=e||{};let r=e.random??e.rng?.()??se();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n=n||0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return A(r)}var le=e=>{let t=[],n;for(n in e){let r=e[n];if(r===void 0)continue;let i={tenant:{id:r.tenant_id,name:r.tenant_name}};i.groups=r.groups?Object.keys(r.groups).map(e=>{let t=r.groups[e]||[];return{group:{id:e,name:r.group_names?.[e]??`unknown`},roles:t}}):[],i.tenantRoles=i.groups?.find(e=>e.group.id===r.root_group_id),t.push(i)}return{raw:e,tenants:t}};function ue(e){if(typeof window<`u`&&typeof window.atob==`function`)return window.atob(e);if(typeof Buffer<`u`)return Buffer.from(e,`base64`).toString(`utf-8`);throw Error(`No Base64 decoding method available in this environment`)}var M=class{constructor(e){this.storageManager=e}isTokenTypeExpired(e){let t=this.storageManager.getToken(e);if(!t)return!0;let n=P(t);return!n||N(n)}parseTokenType(e){let t=this.storageManager.getToken(e);if(t)return P(t)}};function N(e,t=30){return Math.floor(Date.now()/1e3)+t>e.exp}function P(e){let t=e.split(`.`)[1];if(!t)throw Error(`Invalid token string`);let n=t.replace(/-/g,`+`).replace(/_/g,`/`),r=ue(n+`=`.repeat((4-n.length%4)%4)),i=decodeURIComponent(r.split(``).map(e=>`%`+(`00`+e.charCodeAt(0).toString(16)).slice(-2)).join(``)),a=JSON.parse(i);return a.membership=a.passflow_tm&&a.type!==`invite`?le(a.passflow_tm):void 0,a}var F=function(e){return e.id_token=`id_token`,e.access_token=`access`,e.refresh_token=`refresh`,e.invite_token=`invite`,e.reset_token=`reset`,e.web_cookie=`web-cookie`,e.management=`management`,e.signin=`signin`,e.actor=`actor`,e.two_factor=`2fa`,e}({}),I=function(e){return e.JsonBody=`json_body`,e.Cookie=`cookie`,e.Mobile=`mobile`,e.BFF=`bff`,e}({}),de=function(e){return e.Unknown=`unknown`,e.Valid=`valid`,e.Invalid=`invalid`,e}({}),fe=class{constructor(e){this.storageManager=e,this.mode=`json_body`,this.sessionState=`unknown`,this.isInitializedFlag=!1,this.SESSION_STATE_KEY=`passflow_session_state`,this.loadPersistedMode(),this.loadPersistedSessionState()}sessionStateKey(){return this.storageManager.appKey(this.SESSION_STATE_KEY)}reload(){this.mode=`json_body`,this.isInitializedFlag=!1,this.sessionState=`unknown`,this.loadPersistedMode(),this.loadPersistedSessionState()}setMode(e){this.mode=e,this.isInitializedFlag=!0,this.persistMode()}getMode(){return this.mode}isCookieMode(){return this.mode===`cookie`}isJsonMode(){return this.mode===`json_body`}isMobileMode(){return this.mode===`mobile`}isBFFMode(){return this.mode===`bff`}isInitialized(){return this.isInitializedFlag}setSessionValid(){this.sessionState=`valid`,this.persistSessionState()}setSessionInvalid(){this.sessionState=`invalid`,this.persistSessionState()}setSessionUnknown(){this.sessionState=`unknown`,this.persistSessionState()}isSessionValid(){return this.sessionState===`valid`}isSessionUnknown(){return this.sessionState===`unknown`}isSessionInvalid(){return this.sessionState===`invalid`}getSessionState(){return this.sessionState}reset(){this.mode=`json_body`,this.sessionState=`unknown`,this.isInitializedFlag=!1,this.clearPersistedSessionState(),this.storageManager.clearDeliveryMode()}loadPersistedMode(){let e=this.storageManager.getDeliveryMode();e&&(this.mode=e,this.isInitializedFlag=!0)}loadPersistedSessionState(){try{let e=this.storageManager.storage.getItem(this.sessionStateKey());e&&Object.values(de).includes(e)&&(this.sessionState=e)}catch{}}persistMode(){this.storageManager.setDeliveryMode(this.mode)}persistSessionState(){try{this.storageManager.storage.setItem(this.sessionStateKey(),this.sessionState)}catch{}}clearPersistedSessionState(){try{this.storageManager.storage.removeItem(this.sessionStateKey())}catch{}}},L=`tokens_scopes`,R=`passflowDeviceId`,pe=`passflowInvitationToken`,me=`passflowPreviousRedirectUrl`,he=class{constructor({storage:e,prefix:t,appId:n}={}){this.keyStoragePrefix=``,this.STORAGE_PREFIX=`passflow_`,this.storage=e??localStorage,this.keyStoragePrefix=t?`${t}_`:``,this.scopes=`${this.keyStoragePrefix}${L}`,this.deviceId=`${this.keyStoragePrefix}${R}`,this.invitationToken=`${this.keyStoragePrefix}${pe}`,this.previousRedirectUrl=`${this.keyStoragePrefix}${me}`,this.appId=n||void 0}setAppId(e){this.appId=e||void 0}getAppId(){return this.appId}appKey(e){return this.appId?`${e}:${this.appId}`:e}idTokenKey(){return this.appKey(`${this.STORAGE_PREFIX}id_token`)}csrfTokenKey(){return this.appKey(`${this.STORAGE_PREFIX}csrf_token`)}refreshChallengeKey(){return this.appKey(`${this.STORAGE_PREFIX}refresh_challenge`)}deliveryModeKey(){return this.appKey(`${this.STORAGE_PREFIX}delivery_mode`)}ownToken(e){if(!e)return;if(!this.appId)return e;let t;try{t=P(e).aud}catch{return e}return t===void 0||(Array.isArray(t)?t:[t]).includes(this.appId)?e:void 0}readPrefixed(e,t){let n=this.storage.getItem(e);if(n!==null||e===t)return n??void 0;let r=this.storage.getItem(t);if(r)return this.storage.setItem(e,r),this.storage.removeItem(t),r}removePrefixed(e,t){this.storage.removeItem(e),e!==t&&this.storage.removeItem(t)}readToken(e){return this.ownToken(this.storage.getItem(e))}tokenValueKeys(){return[this.getKeyForTokenType(F.access_token),this.getKeyForTokenType(F.refresh_token),this.getKeyForTokenType(F.id_token),this.idTokenKey()]}holdsOtherAppToken(e){if(!this.appId)return!1;let t=this.storage.getItem(e);return!!t&&this.ownToken(t)===void 0}holdsOnlyOtherAppSession(){if(!this.appId)return!1;let e=this.tokenValueKeys();return e.some(e=>this.holdsOtherAppToken(e))&&!e.some(e=>!!this.readToken(e))}removeOwnToken(e){this.holdsOtherAppToken(e)||this.storage.removeItem(e)}saveTokens(e,t,n){let{id_token:r,access_token:i,refresh_token:a,scopes:o}=e;if(t===I.Cookie||t===I.BFF)r&&this.storage.setItem(this.idTokenKey(),r);else{if(n?.replace&&i){let e=this.holdsOnlyOtherAppSession();r||this.removeOwnToken(this.getKeyForTokenType(F.id_token)),a||this.removeOwnToken(this.getKeyForTokenType(F.refresh_token)),!o&&!e&&this.removePrefixed(this.scopes,L)}r&&this.storage.setItem(this.getKeyForTokenType(F.id_token),r),i&&this.storage.setItem(this.getKeyForTokenType(F.access_token),i),a&&this.storage.setItem(this.getKeyForTokenType(F.refresh_token),a),o&&this.storage.setItem(this.scopes,o.join(`,`))}}getToken(e){return this.readToken(this.getKeyForTokenType(e))}getTokens(){let e=this.getDeliveryMode();if(e===I.Cookie||e===I.BFF){let e=this.readToken(this.idTokenKey());return e?{id_token:e}:void 0}let t=this.readToken(this.getKeyForTokenType(F.access_token));if(t)return{access_token:t,id_token:this.readToken(this.getKeyForTokenType(F.id_token)),refresh_token:this.readToken(this.getKeyForTokenType(F.refresh_token)),scopes:this.getScopes()}}getScopes(){return this.readPrefixed(this.scopes,L)?.split(`,`)}hasJsonModeTokens(){return!!this.readToken(this.getKeyForTokenType(F.access_token))}hasCookieModeIdToken(){return!!this.readToken(this.idTokenKey())}deleteToken(e){let t=this.getKeyForTokenType(e);this.storage.removeItem(t)}deleteTokens(){let e=this.holdsOnlyOtherAppSession();for(let e of this.tokenValueKeys())this.removeOwnToken(e);e||this.removePrefixed(this.scopes,L),this.clearDeliveryMode(),this.clearCsrfToken(),this.clearRefreshChallenge(),this.appId&&this.getHostedSignIn()===void 0&&this.storage.getItem(this.hostedSignInKey())||this.storage.removeItem(this.hostedSignInKey())}setHostedSignIn(e){this.storage.setItem(this.hostedSignInKey(),JSON.stringify({appId:this.appId??``,returnUrl:e}))}getHostedSignIn(){try{let e=JSON.parse(this.storage.getItem(this.hostedSignInKey())??``);return e.appId!==(this.appId??``)||typeof e.returnUrl!=`string`?void 0:e.returnUrl||void 0}catch{return}}hostedSignInKey(){return`${this.keyStoragePrefix}${this.STORAGE_PREFIX}hosted_sign_in`}getDeviceId(){return this.readPrefixed(this.deviceId,R)}setDeviceId(e){this.storage.setItem(this.deviceId,e)}deleteDeviceId(){this.removePrefixed(this.deviceId,R)}setInvitationToken(e){this.storage.setItem(this.invitationToken,e)}getInvitationToken(){return this.readPrefixed(this.invitationToken,pe)}deleteInvitationToken(){this.removePrefixed(this.invitationToken,pe)}setPreviousRedirectUrl(e){this.storage.setItem(this.previousRedirectUrl,e)}getPreviousRedirectUrl(){return this.readPrefixed(this.previousRedirectUrl,me)}deletePreviousRedirectUrl(){this.removePrefixed(this.previousRedirectUrl,me)}setDeliveryMode(e){try{this.storage.setItem(this.deliveryModeKey(),e)}catch{}}getDeliveryMode(){try{let e=this.storage.getItem(this.deliveryModeKey());if(e&&Object.values(I).includes(e))return e}catch{}}clearDeliveryMode(){try{this.storage.removeItem(this.deliveryModeKey())}catch{}}getIdToken(){try{return this.readToken(this.idTokenKey())}catch{return}}setIdToken(e){try{this.storage.setItem(this.idTokenKey(),e)}catch{}}clearIdToken(){try{this.removeOwnToken(this.idTokenKey())}catch{}}getCsrfToken(){try{return this.storage.getItem(this.csrfTokenKey())??void 0}catch{return}}setCsrfToken(e){try{this.storage.setItem(this.csrfTokenKey(),e)}catch{}}clearCsrfToken(){try{this.storage.removeItem(this.csrfTokenKey())}catch{}}getRefreshChallenge(){try{return this.storage.getItem(this.refreshChallengeKey())??void 0}catch{return}}setRefreshChallenge(e){try{this.storage.setItem(this.refreshChallengeKey(),e)}catch{}}clearRefreshChallenge(){try{this.storage.removeItem(this.refreshChallengeKey())}catch{}}tokenKeys(){return[this.getKeyForTokenType(F.id_token),this.getKeyForTokenType(F.access_token),this.getKeyForTokenType(F.refresh_token),this.scopes,this.idTokenKey(),this.csrfTokenKey(),this.deliveryModeKey()]}getKeyForTokenType(e){return`${this.keyStoragePrefix}${e}`}},ge=class{constructor(e){this.storageManager=e??new he}getDeviceId(){return this.storageManager.getDeviceId()||(this.mintedDeviceId??(this.mintedDeviceId=this.generateUniqueDeviceId()),this.storageManager.setDeviceId(this.mintedDeviceId),this.mintedDeviceId)}generateUniqueDeviceId(){return ce()}},_e=class extends Error{constructor(e=`Authentication popup was closed`){super(e),this.name=`PopupClosedError`}},ve=class{constructor(){this.passkeys={startRegistration:e=>(0,l.startRegistration)({optionsJSON:e}),startAuthentication:e=>(0,l.startAuthentication)({optionsJSON:e})}}get storage(){return typeof localStorage>`u`?{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}:localStorage}get storageSharedAcrossTabs(){try{return typeof localStorage<`u`&&localStorage!==null}catch{return!1}}getCurrentUrl(){return typeof window>`u`?null:{href:window.location.href,origin:window.location.origin,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,hostname:window.location.hostname}}replaceUrl(e){typeof window<`u`&&window.history.replaceState({},document.title,e)}navigateTo(e){typeof window<`u`&&(window.location.href=e)}onForeground(e){if(typeof document>`u`)return()=>{};let t=()=>{document.hidden||e()};return document.addEventListener(`visibilitychange`,t),()=>document.removeEventListener(`visibilitychange`,t)}onBackground(e){if(typeof document>`u`)return()=>{};let t=()=>{document.hidden&&e()};return document.addEventListener(`visibilitychange`,t),()=>document.removeEventListener(`visibilitychange`,t)}onBeforeUnload(e){return typeof window>`u`?()=>{}:(window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e))}isInForeground(){return typeof document>`u`||!document.hidden}openAuthUrl(e,t={}){let n=t.mode??`popup`;if(n===`redirect`)return window.location.href=e,new Promise(()=>{});if(n===`deeplink`)return Promise.reject(Error(`openAuthUrl: "deeplink" mode is not supported on web. Use "popup" or "redirect" instead, or provide a native platform adapter.`));let r=t.width??500,i=t.height??600,a=t.expectedReturnOrigin??window.location.origin,o=window.open(e,`_blank`,`width=${r},height=${i}`);return o?this.watchPopup(o,a):(window.location.href=e,new Promise(()=>{}))}async openPendingAuthUrl(e,t={}){if((t.mode??`popup`)!==`popup`)return this.openAuthUrl(await e,t);let n=t.width??500,r=t.height??600,i=t.expectedReturnOrigin??window.location.origin,a=window.open(`about:blank`,`_blank`,`width=${n},height=${r}`),o;try{o=await e}catch(e){throw a?.close(),e}return a?(a.location.href=o,this.watchPopup(a,i)):(window.location.href=o,new Promise(()=>{}))}watchPopup(e,t){return new Promise((n,r)=>{let i=Date.now(),a=setInterval(()=>{if(e.closed)clearInterval(a),r(new _e);else if(Date.now()-i>6e4)clearInterval(a),e.close(),r(Error(`Authentication popup timed out`));else try{if(e.location.href.startsWith(t)){let t=e.location.search,r=e.location.hash;clearInterval(a),e.close(),n({callbackSearch:t,callbackHash:r})}}catch{}},100)})}btoa(e){return btoa(e)}atob(e){if(typeof window<`u`&&typeof window.atob==`function`)return window.atob(e);if(typeof Buffer<`u`)return Buffer.from(e,`base64`).toString(`utf-8`);throw Error(`No Base64 decoding method available in this environment`)}cookiesSupported(){if(typeof document>`u`)return!1;try{document.cookie=`passflow_test=1; SameSite=Lax`;let e=document.cookie.indexOf(`passflow_test=1`)!==-1;return document.cookie=`passflow_test=; expires=Thu, 01 Jan 1970 00:00:00 UTC`,e}catch{return!1}}getDeviceType(){return`web`}},ye=new ve,be=/^[0-9]+$/,xe=Object.freeze({unorderable:!1,zero:!1}),Se=e=>be.test(e)?Number.parseInt(e,10):void 0,Ce=e=>{if(!e)return xe;let t=e.split(/\s+/).filter(e=>e!==``);if(t.length===0)return xe;let n=[];for(let e of t){let t=Se(e);t!==void 0&&n.push(t)}if(n.length===0)return{raw:e,unorderable:!0,zero:!1};let r=Math.min(...n);return r===0?{raw:e,unorderable:!1,zero:!0}:{level:r,raw:e,unorderable:!1,zero:!1}},we=e=>Ce(e).level,Te=`insufficient_user_authentication`,Ee=`upgrade_required`,De=/([A-Za-z0-9!#$%&'*+\-.^_`|~]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]*))/g,Oe=e=>e.replace(/\\(.)/g,`$1`),ke=e=>{let t={};De.lastIndex=0;for(let n of e.matchAll(De)){let e=n[1];if(!e)continue;let r=n[2],i=n[3];t[e.toLowerCase()]=r===void 0?i??``:Oe(r)}return t},Ae=e=>{if(e==null||e===``)return{kind:`absent`};let t=typeof e==`number`?e:Number.parseInt(String(e),10);return Number.isFinite(t)&&t>0?{kind:`valid`,value:t}:{kind:`invalid`,raw:e}},je=e=>{let t=Ae(e);return t.kind===`valid`?t.value:void 0},Me=(e,t)=>{if(!e||!/(^|[\s,])Bearer\b/i.test(e))return;let n=ke(e);if(n.error===`insufficient_user_authentication`)return{acrValues:n.acr_values||void 0,maxAge:je(n.max_age),status:t}},Ne=(e,t)=>{if(!e||typeof e!=`object`)return;let n=e;if(n.error!==`upgrade_required`)return;let r=Array.isArray(n.available_factors)?n.available_factors.filter(e=>typeof e==`string`):void 0;return{acrValues:typeof n.acr_values==`string`&&n.acr_values?n.acr_values:void 0,maxAge:je(n.max_age),status:t,...r?{availableFactors:r}:{},...typeof n.sign_in_required==`boolean`?{signInRequired:n.sign_in_required}:{}}},Pe=(e,t,n)=>({channel:e,acr:Ce(t.acrValues),maxAge:Ae(n),raw:t.acrValues}),Fe=e=>e?ke(e):{},Ie=(e,t)=>{let{status:n}=e;if(n!==401&&n!==403)return{diagnostics:[]};let r=t?.requireChallengeChannel===`header`,i=e.getHeader(`www-authenticate`),a=Me(i,n),o=r?void 0:Ne(e.body,n),s=[],c=(e,t)=>{s.push({status:n,url:``,reason:e,...t?{detail:t}:{}})};if(!a&&!o)return r&&c(`header-required-but-absent`,i?{header:i}:void 0),{diagnostics:s};let l=[];if(a&&l.push(Pe(`header`,a,Fe(i).max_age)),o){let t=e.body;l.push(Pe(`body`,o,t?.max_age))}let u=e=>e;for(let e of l)e.acr.unorderable&&c(`channels-unorderable`,{[u(e.channel)]:e.raw}),e.acr.zero&&c(`zero-constraint-ignored`,{field:`acr_values`,[u(e.channel)]:e.raw}),e.maxAge.kind===`invalid`&&c(`zero-constraint-ignored`,{field:`max_age`,[u(e.channel)]:String(e.maxAge.raw)});let d=l.filter(e=>e.acr.level!==void 0),f,p;for(let e of d){let t=e.acr.level;f===void 0||t>f?(f=t,p=e.raw):t===f&&e.channel===`header`&&(p=e.raw)}let m;for(let e of l)e.maxAge.kind===`valid`&&(m===void 0||e.maxAge.value<m)&&(m=e.maxAge.value);if(l.length===2){let[e,t]=l,n=e.acr.level!==void 0&&t.acr.level!==void 0&&e.acr.level!==t.acr.level,r=e.maxAge.kind===`valid`&&t.maxAge.kind===`valid`&&e.maxAge.value!==t.maxAge.value;(n||r)&&c(`channels-disagree`,{header:e.raw??t.raw,body:t.raw??e.raw})}return{challenge:{acrValues:p,requiredLevel:f,maxAge:m,status:n,channels:l.map(e=>e.channel),...o?.availableFactors?{availableFactors:o.availableFactors}:{},...o?.signInRequired===void 0?{}:{signInRequired:o.signInRequired}},diagnostics:s}},Le=(e,t,n)=>Ie({status:e,getHeader:t,body:n}).challenge,Re=`__passflowUpgradeTransaction`,ze=`__passflowUpgradeReplayed`,Be=(e,t)=>typeof e==`object`&&!!e&&e[t]===!0,Ve=e=>({...e??{},[Re]:!0}),He=e=>Be(e,Re),Ue=e=>({...e,[ze]:!0}),We=e=>Be(e,ze),Ge=function(e){return e.GET=`get`,e.POST=`post`,e.PUT=`put`,e.PATCH=`patch`,e.DELETE=`delete`,e}({}),z=function(e){return e.signin=`/auth/login`,e.signup=`/auth/register`,e.pkceExchange=`/auth/pkce_exchange`,e.redirectCheck=`/auth/redirect/check`,e.signInWithProvider=`/auth/federated/start/`,e.passwordless=`/auth/passwordless/start`,e.passwordlessComplete=`/auth/passwordless/complete`,e.passwordlessStatus=`/auth/passwordless/status`,e.passwordlessApprovalInfo=`/auth/passwordless/approval/info`,e.passwordlessApprovalDecide=`/auth/passwordless/approval/decide`,e.logout=`/user/logout`,e.refresh=`/auth/refresh`,e.validateSession=`/user/me`,e.sendPasswordResetEmail=`/auth/password/reset`,e.resetPassword=`/auth/password/change`,e.appSettings=`/app/settings`,e.passkeyRegisterStart=`/auth/passkey/register/start`,e.passkeyRegisterComplete=`/auth/passkey/register/complete`,e.passkeyAuthenticateStart=`/auth/passkey/authenticate/start`,e.passkeyAuthenticateComplete=`/auth/passkey/authenticate/complete`,e.passkeyValidate=`/auth/validate`,e.settingsAll=`/settings`,e.settingsPasswordPolicy=`/settings/password`,e.settingsPasskey=`/settings/passkey`,e.userPasskey=`/user/passkey`,e.addUserPasskey=`/user/passkey/add/start`,e.completeAddUserPasskey=`/user/passkey/add/complete`,e.userSessions=`/user/sessions`,e.userSessionsRevokeOthers=`/user/sessions/revoke-others`,e.userProfile=`/user/profile`,e.AddressChangeProof=`/v2/user/address-change/proof`,e.joinInvitation=`/user/tenant/join`,e.tenantPath=`/user/tenant`,e.invitationsPath=`/user/tenant/:tenantID/invitations`,e.requestInvitation=`/user/invite`,e.invitationDelete=`/user/invite/:invitationID`,e.invitationResend=`/user/invite/:invitationID/resend`,e.invitationGetLink=`/user/invite/:invitationID/link`,e.twoFactor=`/user/2fa`,e.twoFactorStatus=`/user/2fa/status`,e.twoFactorSetupBegin=`/user/2fa/setup/begin`,e.twoFactorSetupConfirm=`/user/2fa/setup/confirm`,e.twoFactorVerify=`/auth/2fa/verify`,e.twoFactorRecovery=`/auth/2fa/recovery`,e.twoFactorRegenerateCodes=`/user/2fa/recovery-codes/regenerate`,e.twoFactorSetupMagicLink=`/auth/2fa-setup`,e.twoFactorEnrollment=`/auth/2fa/enrollment`,e.twoFactorEnrollmentEmailLink=`/auth/2fa/enrollment/email-link`,e.twoFactorEnrollmentBegin=`/auth/2fa/setup/begin`,e.twoFactorEnrollmentConfirm=`/auth/2fa/setup/confirm`,e.TwoFactorMethodsAvailable=`/v2/user/2fa/methods/available`,e.TwoFactorMethodsRegistered=`/v2/user/2fa/methods`,e.TwoFactorSetupStart=`/v2/user/2fa/setup/start`,e.TwoFactorSetupComplete=`/v2/user/2fa/setup/complete`,e.TwoFactorMethodRemove=`/v2/user/2fa/methods/:id`,e.TwoFactorChallenge=`/v2/auth/2fa/challenge`,e.TwoFactorVerifyV2=`/v2/auth/2fa/verify`,e.TwoFactorAlternative=`/v2/auth/2fa/alternative`,e.TwoFactorTrustedDevices=`/v2/user/2fa/trusted-devices`,e.TwoFactorTrustedDeviceRevoke=`/v2/user/2fa/trusted-devices/:id`,e.TwoFactorPreferredMethod=`/v2/user/2fa/preferred-method`,e.cliAuthStatus=`/cli/auth/status/:sessionId`,e.cliAuthComplete=`/cli/auth/complete`,e.upgradeStart=`/auth/upgrade/start`,e.hostedUpgradeStart=`/auth/session/upgrade/start`,e.hostedUpgrade=`/auth/session/upgrade`,e.antiBotChallenge=`/auth/anti-bot/challenge`,e.deviceAntiBotChallenge=`/oidc/device/anti-bot/challenge`,e.enterpriseResolve=`/auth/enterprise/resolve`,e.enterpriseStart=`/auth/enterprise/start`,e.deviceChallenge=`/auth/device/challenge`,e.userDeviceKey=`/user/device/key`,e}({}),Ke=function(e){return e.passkeyRegisterStart=`/admin/auth/passkey/register/start`,e.passkeyRegisterComplete=`/admin/auth/passkey/register/complete`,e.passkeyAuthenticateStart=`/admin/auth/passkey/authenticate/start`,e.passkeyAuthenticateComplete=`/admin/auth/passkey/authenticate/complete`,e.passkeyValidate=`/admin/auth/validate`,e.logout=`/admin/auth/logout`,e}({}),qe=e=>{if(!e)return null;try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return{origin:t.origin,pathPrefix:n===``?void 0:n}}catch{return null}},Je=e=>typeof e==`object`&&!!e&&e.email_verification_required===!0,Ye=`error.service.unavailable`,Xe=`Passflow is temporarily unavailable. Please try again in a moment.`,B=class extends Error{constructor(e,t){super(),this.name=`PassflowError`,this.id=e?.id??`unknown`,this.message=e?.message??e??`Something went wrong`,this.status=e?.status??500,this.location=e?.location??`unknown`,this.time=e?.time??new Date().toISOString(),t?.cause!==void 0&&(this.cause=t.cause)}},Ze=`error.api.password.change.required`,Qe=`error.api.anti_bot.required`,$e=`error.api.anti_bot.failed`,et=`error.api.anti_bot.unavailable`,tt=`error.anti_bot.provider_missing`,nt=`error.anti_bot.provider_failed`,rt=`error.anti_bot.solve_failed`,it=`error.api.enterprise.email_invalid`,at=`error.api.enterprise.start_input`,ot=`error.api.enterprise.no_connection`,st=`error.api.enterprise.connection_ambiguous`,ct=class extends B{constructor(e,t){super(e,t),this.name=`PassflowPasswordChangeRequiredError`}},lt=`error.2fa.sms.quota.exceeded`,ut=`error.2fa.rate_limit_exceeded`,dt=`error.2fa.recovery_codes.step_up_required`,ft=`error.user.address.change.proof.required`,pt=class extends B{constructor(e,t){super(e,t),this.name=`PassflowSmsQuotaExceededError`,this.challenge=t?.challenge}},mt=class extends B{constructor(e,t,n){super(e,n),this.name=`PassflowSendLimitError`,this.retryAfter=t,this.challenge=n?.challenge}},ht=class extends B{constructor(e,t,n){super(e,n),this.name=`PassflowRecoveryCodesStepUpRequiredError`,this.challenge=t}},gt=class extends B{constructor(e,t){super(e,t),this.name=`PassflowAddressChangeProofRequiredError`}},_t=function(e){return e.google=`google`,e.facebook=`facebook`,e}({}),vt=Object.freeze([`debug_otp_code_for_registration`,`fcm_server_key`,`webpush_vapid_private_key`]),yt=`mask://`,bt=`error.server.update.settings.masked.value.unknown`,xt=e=>typeof e==`string`&&e.startsWith(`mask://`),St=function(e){return e.web=`web`,e.ios=`ios`,e.android=`android`,e}({});function Ct(e){return e}function wt(e,t){let n=e;return Object.entries(t).forEach(([e,t])=>{n=n.replace(`:${e}`,t)}),n}var Tt=function(e){return e.Disabled=`disabled`,e.Optional=`optional`,e.Required=`required`,e}({}),Et=3,Dt=1e3,Ot=e=>t=>{let n=e.headers?.[t]??e.headers?.[t.toLowerCase()];return Array.isArray(n)?n.join(`, `):n},kt=e=>Le(e.status,Ot(e),e.data),At=e=>kt(e)!==void 0,jt=e=>{let t=e.response?.data?.error;return typeof t?.id==`string`?t.id:void 0},Mt=e=>c.default.isAxiosError(e)&&!e.response&&(e.code===c.AxiosError.ERR_NETWORK||!e.code&&e.cause instanceof TypeError),Nt=[502,503,504],Pt=e=>typeof e==`object`&&!!e&&typeof e.error==`object`&&e.error!==null,Ft=(e,t)=>{let n=new c.AxiosError(e.message,e.code);return e.cause instanceof TypeError&&(n.cause=e.cause),new B({id:Ye,message:Xe,status:t,location:e.config?.url??`unknown`,time:new Date().toISOString()},{cause:n})},It=[[/(\/auth\/2fa-setup\/)[^/?#]+/g,`$1:token`],[/(\/cli\/auth\/status\/)[^/?#]+/g,`$1:sessionId`]],Lt=e=>It.reduce((e,[t,n])=>e.replace(t,n),e),Rt=e=>{if(e instanceof B)return e.location=Lt(e.location),e;if(!c.default.isAxiosError(e))return e;if(e.config){let{data:t,headers:n,url:r,...i}=e.config,a={...i,...r===void 0?{}:{url:Lt(r)},headers:new c.AxiosHeaders};e.config=a,e.response&&(e.response.config=a)}return e.request=void 0,e.response&&(e.response.request=void 0),e},zt=e=>e?.includes(z.refresh)??!1,Bt=e=>e?.includes(`/auth/session/`)??!1,Vt=e=>e?.includes(`logout`)??!1,Ht=`__passflowOwnBearer`,Ut=`__passflowRefreshedAfter401`,Wt=e=>typeof e==`object`&&!!e&&e[Ht]===!0,Gt=e=>e?{headers:{[h]:`Bearer ${e}`},[Ht]:!0}:{},Kt=`__passflowSendRefusal`,qt=e=>typeof e==`object`&&!!e&&e[Kt]===!0,Jt=(e={})=>({...e,[Kt]:!0}),Yt=e=>{let t=e?Ot(e)(`Retry-After`)?.trim():void 0;if(!t)return;if(/^\d+$/.test(t))return Number.parseInt(t,10);let n=Date.parse(t);return Number.isNaN(n)?void 0:Math.max(0,Math.ceil((n-Date.now())/1e3))},Xt=e=>{let{challenge_id:t,suggested_method:n,alternative_methods:r}=e;if(typeof t!=`string`||t===``)return;let i={challenge_id:t};return typeof n==`string`&&(i.suggested_method=n),Array.isArray(r)&&(i.alternative_methods=r.filter(e=>typeof e==`string`)),i},Zt=e=>{let t=e.response?.data;if(!Pt(t))return;let{error:n}=t,r=Xt(t);switch(n.id){case lt:return new pt(n,{challenge:r});case ut:return new mt(n,Yt(e.response),{challenge:r});default:return}},Qt={acrValues:`2`,requiredLevel:2,status:403},$t=class{get origin(){return this._platform.getCurrentUrl()?.origin??``}constructor(e,t,n){this.defaultHeaders={Accept:`application/json`,"Content-Type":`application/json`},this.nonAccessTokenEndpoints=[`/auth/`,`/settings`,`/settings/`,`/oidc/device/anti-bot/challenge`],this.protectedEndpoints=[`logout`,`refresh`,`upgrade`];let{url:r,appId:i,keyStoragePrefix:a}=e;this._platform=e.platform??ye,this.url=r||`https://auth.passflow.cloud`,this.upgradeDomain=qe(r),this.storageManager=t??new he({prefix:a??``,appId:i}),this.deviceService=n??new ge(this.storageManager),this.tokenService=new M(this.storageManager),this.tokenDeliveryManager=new fe(this.storageManager),i&&(this.appId=i,this.defaultHeaders={...this.defaultHeaders,[m]:i}),this.defaultHeaders={...this.defaultHeaders,[_]:this._platform.getDeviceType()},this.detectCookieSupport(),this.instance=c.default.create({baseURL:this.url,headers:{...this.defaultHeaders}}),this.instance.interceptors.request.use(async e=>{e.headers[g]=this.deviceService.getDeviceId();let t=f(e);if(t&&this.antiBotHandler){let n=await this.antiBotHandler(t);n&&(e.headers[v]=n.value,t.builtin=n.builtin)}if(this.isNonAuthEndpoint(e.url)||Wt(e)||Bt(e.url))return e;if(this.storageManager.getDeliveryMode()===I.Cookie){e.withCredentials=!0;let t=this.storageManager.getCsrfToken();return t&&(e.headers[`X-CSRF-Token`]=t),e}if(zt(e.url))return e;let n=this.storageManager.getTokens();if(!n?.access_token)return e;let r=n.access_token;if(this.refreshHandler&&n.refresh_token&&!Vt(e.url)){let e=P(n.access_token);if(N(e,30)){let t=!N(e,0);try{r=(await this.refreshHandler({trigger:`pre-request`,allowStale:t}))?.access_token??r}catch(e){if(!t)throw e}}}return e.headers[h]=`Bearer ${r}`,e}),this.instance.interceptors.response.use(e=>e,e=>this.onResponseError(e).catch(e=>Promise.reject(Rt(e))))}async onResponseError(e){if(e.response?.status===401&&!zt(e.config?.url)&&!Bt(e.config?.url)&&!Wt(e.config)&&!this.isUpgradeTransactionError(e)){if(e.config&&await this.refreshedAfterUnauthorized(e.config))return this.instance.request(e.config);this.tokenDeliveryManager.setSessionInvalid()}let t=f(e.config);if(e.config&&e.response?.status===403&&jt(e)===`error.api.anti_bot.failed`&&t?.builtin&&!t.retried)return t.retried=!0,this.instance.request(e.config);if(e.response&&this.upgradeHandler&&!Bt(e.config?.url)){let t=kt(e.response);if(t)try{return await this.upgradeHandler(e,t)}catch(t){if(t!==e)throw t}}if(e.response?.status===429){let t=qt(e.config)?Zt(e):void 0;return t?Promise.reject(t):await this.handleRateLimitError(e)}return this.handleAxiosError(e)}isUpgradeTransactionError(e){return He(e.config)||e.response!==void 0&&At(e.response)}setUpgradeInterceptor(e){this.upgradeHandler=e}setRefreshHandler(e){this.refreshHandler=e}setAntiBotHandler(e){this.antiBotHandler=e}replay(e){return this.instance.request(e)}isProtectedEndpoint(e){return this.protectedEndpoints.some(t=>e?.includes(t))}async refreshedAfterUnauthorized(e){let t=e,n=this.storageManager.getDeliveryMode();if(!this.refreshHandler||t[Ut]||n!==I.Cookie&&n!==I.BFF||this.isNonAuthEndpoint(e.url)||Vt(e.url))return!1;t[Ut]=!0;try{return await this.refreshHandler({trigger:`pre-request`,allowStale:!1})!==void 0}catch{return!1}}isNonAuthEndpoint(e){return this.nonAccessTokenEndpoints.some(t=>e?.includes(t))&&!this.isProtectedEndpoint(e)}detectCookieSupport(){if(!this._platform.cookiesSupported()&&this.tokenDeliveryManager.isCookieMode())throw Error(`Passflow SDK: Cookie delivery mode is configured but cookies are not supported in this environment. Use a platform adapter that supports cookies or configure the server to use JSON token delivery.`)}async handleRateLimitError(e){let t=e.config;if(!t||zt(t.url))return Promise.reject(e);let n=t.method?.toUpperCase();if(![`GET`,`HEAD`,`OPTIONS`].includes(n||``))return Promise.reject(e);let r=t._retryCount||0;if(r>=Et)return Promise.reject(e);let i=Dt*2**r,a=e.response?.headers?.[`retry-after`];if(a){let e=Number.parseInt(a,10);if(!Number.isNaN(e))i=e*1e3;else{let e=new Date(a);Number.isNaN(e.getTime())||(i=Math.max(0,e.getTime()-Date.now()))}}return await new Promise(e=>setTimeout(e,i)),t._retryCount=r+1,this.instance.request(t)}async handleAxiosError(e){if(Mt(e))return Promise.reject(Ft(e,0));if(!e.response)return Promise.reject(e);let t=e.response.status;if(Nt.includes(t)&&!Pt(e.response.data))return Promise.reject(Ft(e,t));let n=e.response.data;if(`error`in n&&typeof n.error==`object`&&n.error!==null){let{error:t}=n;switch(t.id){case Ze:return Promise.reject(new ct(t));case ft:return Promise.reject(new gt(t));case dt:return Promise.reject(new ht(t,kt(e.response)??{...Qt}));default:return Promise.reject(new B(t))}}return Promise.reject(new B({id:`error.http.${t}`,message:e.message||`An error occurred`,status:t,location:e.config?.url||`unknown`,time:new Date().toISOString()}))}async send(e,t,n){return(await this.instance.request({method:e,url:t,...n})).data}get(e,t){return this.send(Ge.GET,e,t)}post(e,t,n){return this.send(Ge.POST,e,{data:t,...n})}put(e,t,n){return this.send(Ge.PUT,e,{data:t,...n})}patch(e,t,n){return this.send(Ge.PATCH,e,{data:t,...n})}delete(e,t){return this.send(Ge.DELETE,e,t)}setAppId(e){this.appId=e,this.tokenDeliveryManager.reload(),this.defaultHeaders={...this.defaultHeaders,[m]:e},this.instance.defaults.headers[m]=e}},en=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getAppSettings(){return this.axiosClient.get(z.appSettings)}},tn={withCredentials:!0},nn=15e3,rn=`X-Passflow-CSRF`,an=`Sign-in failed. Start again.`,on=`Something went wrong. Try again later.`,sn=(e,t,n,r)=>{if(e instanceof B)return e;let i=e?.response?.data?.error;return new B({id:typeof i?.id==`string`?i.id:n,message:typeof i?.message==`string`?i.message:r,status:typeof i?.status==`number`?i.status:0,location:t,time:new Date().toISOString()})},V=(e,t,n,r)=>!t&&!r?.agentTool?e:{...e,...t?d(t,n):{},...r?.agentTool?{headers:{...e?.headers,[y]:`1`}}:{}},cn=(e,t)=>t?{...e,headers:{...e?.headers,[b]:t}}:e,ln=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}setAntiBotHandler(e){this.axiosClient.setAntiBotHandler(e)}async antiBotChallenge(e){try{return await this.axiosClient.post(z.antiBotChallenge,e)}catch(e){throw sn(e,z.antiBotChallenge,`error.anti_bot.challenge`,on)}}async deviceChallenge(){try{return await this.axiosClient.post(z.deviceChallenge)}catch(e){throw sn(e,z.deviceChallenge,`error.device.challenge`,on)}}async deviceAntiBotChallenge(e,t){try{return await this.axiosClient.post(z.deviceAntiBotChallenge,e,{headers:{[rn]:t}})}catch(e){throw sn(e,z.deviceAntiBotChallenge,`error.anti_bot.challenge`,on)}}federatedStart(e,t,n){return this.axiosClient.post(`${z.signInWithProvider}${e}`,t,V(tn,`federated.start`,void 0,n))}enterpriseResolve(e){return this.axiosClient.post(z.enterpriseResolve,{email:e})}enterpriseStart(e,t){return this.axiosClient.post(z.enterpriseStart,e,V(tn,`federated.start`,e.email,t))}refreshToken(e,t,n,r,i){let a={access:n,scopes:t,...r?{upgrade:r}:{}},o=i?{headers:{[h]:`Bearer ${e}`,...i.proof?{[b]:i.proof}:{}},withCredentials:!0}:{headers:{[h]:`Bearer ${e}`}};return this.axiosClient.post(z.refresh,a,r?Ve(o):o)}signIn(e,t,n,r,i){let a={...e,device:t,os:n};return this.axiosClient.post(z.signin,a,cn(V(tn,`sign-in`,e.email??e.phone??e.username,r),i))}signUp(e,t){let{create_tenant:n,anonymous:r}=e,i={...e,create_tenant:n??!1,anonymous:r??!1};return this.axiosClient.post(z.signup,i,V(tn,`sign-up`,e.user.email??e.user.phone_number??e.user.username,t))}async pkceExchange(e,t){try{return await this.axiosClient.post(z.pkceExchange,{authz_code:e,verifier:t},tn)}catch(e){throw sn(e,z.pkceExchange,`error.pkce.exchange`,an)}}async passwordlessSignIn(e,t,n,r){let{create_tenant:i}=e,a={...e,create_tenant:i??!1,device:t,os:n};try{return await this.axiosClient.post(z.passwordless,a,V(void 0,`passwordless.start`,e.email??e.phone,r))}catch(e){throw sn(e,z.passwordless,`error.passwordless.start`,on)}}async passwordlessSignInComplete(e,t){try{return await this.axiosClient.post(z.passwordlessComplete,e,V(tn,void 0,void 0,t))}catch(e){throw sn(e,z.passwordlessComplete,`error.passwordless.complete`,on)}}async passwordlessStatus(e,t){try{return await this.axiosClient.post(z.passwordlessStatus,e,{...tn,timeout:nn,signal:t?.signal})}catch(e){throw sn(e,z.passwordlessStatus,`error.passwordless.status`,an)}}async checkRedirectUrl(e){try{return(await this.axiosClient.post(z.redirectCheck,{redirect_url:e})).redirect_url}catch(e){throw sn(e,z.redirectCheck,`error.redirect.check`,on)}}async passwordlessApprovalInfo(e){try{return await this.axiosClient.post(z.passwordlessApprovalInfo,e)}catch(e){throw sn(e,z.passwordlessApprovalInfo,`error.passwordless.approval`,on)}}async passwordlessApprovalDecide(e){try{return await this.axiosClient.post(z.passwordlessApprovalDecide,e)}catch(e){throw sn(e,z.passwordlessApprovalDecide,`error.passwordless.approval`,on)}}validateEmailCode(e){return this.axiosClient.post(z.passkeyValidate,{challenge_id:e.challenge_id,otp:e.otp},tn)}logOut(e,t,n=!1,r){let i=n?void 0:{refresh_token:t,device:e,...r?{post_logout_redirect_uri:r}:{}},a=n?Ke.logout:z.logout;return this.axiosClient.post(a,i)}validateSession(){return this.axiosClient.get(z.validateSession)}sendPasswordResetEmail(e,t){return this.axiosClient.post(z.sendPasswordResetEmail,e,V(void 0,`password-reset.send`,e.email??e.phone??e.username,t))}resetPassword(e,t,n,r){let i={password:e,scopes:t,...r?{code_challenge:r}:{}};return this.axiosClient.post(z.resetPassword,i,{headers:{[h]:`Bearer ${n}`,[m]:void 0}})}passkeyRegisterStart(e,t,n,r=!1,i){let{create_tenant:a}=e,o={...e,create_tenant:a??!1,device:t,os:n},s=r?Ke.passkeyRegisterStart:z.passkeyRegisterStart;return this.axiosClient.post(s,o,V(void 0,r?void 0:`passkey.register`,e.passkey_username,i))}passkeyRegisterComplete(e,t,n,r=!1,i){let a={challenge_id:n,device:t,passkey_data:e},o=r?Ke.passkeyRegisterComplete:z.passkeyRegisterComplete;return this.axiosClient.post(o,a,V(tn,void 0,void 0,i))}passkeyAuthenticateStart(e,t,n,r=!1,i){let a={...e,user_id:e.user_id??``,device:t,os:n},o=r?Ke.passkeyAuthenticateStart:z.passkeyAuthenticateStart;return this.axiosClient.post(o,a,V(void 0,r?void 0:`passkey.authenticate`,void 0,i))}passkeyAuthenticateComplete(e,t,n,r=!1,i,a){let o={challenge_id:n,device:t,passkey_data:e},s=r?Ke.passkeyAuthenticateComplete:z.passkeyAuthenticateComplete;return this.axiosClient.post(s,o,cn(V(tn,void 0,void 0,i),a))}passkeyValidate(e,t,n,r=!1,i){let a={otp:e,device:t,challenge_id:n},o=z.passkeyValidate;!i&&r&&(o=Ke.passkeyValidate);let s=i?{[m]:i}:{};return this.axiosClient.post(o,a,{headers:s})}},un=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getCLIAuthStatus(e){let t=wt(z.cliAuthStatus,{sessionId:e});return this.axiosClient.get(t)}completeCLIAuth(e){return this.axiosClient.post(z.cliAuthComplete,e)}},dn=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}requestInviteLink(e){return this.axiosClient.post(z.requestInvitation,e)}getInvitations(e){let t={};e.groupID&&(t.group_id=e.groupID.toString()),e.skip!==void 0&&(t.skip=e.skip.toString()),e.limit!==void 0&&(t.limit=e.limit.toString());let n=wt(z.invitationsPath,{tenantID:e.tenantID});return this.axiosClient.get(n,{params:t}).then(e=>({invites:e.invites,nextPageSkip:e.next_page_skip}))}deleteInvitation(e){let t=wt(z.invitationDelete,{invitationID:e});return this.axiosClient.delete(t)}resendInvitation(e){let t=wt(z.invitationResend,{invitationID:e});return this.axiosClient.post(t,{})}getInvitationLink(e){let t=wt(z.invitationGetLink,{invitationID:e});return this.axiosClient.get(t)}},fn=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getSettingsAll(){return this.axiosClient.get(z.settingsAll)}getPasswordPolicySettings(){return this.axiosClient.get(z.settingsPasswordPolicy)}getPasskeySettings(){return this.axiosClient.get(z.settingsPasskey)}},pn=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}joinInvitation(e,t){let n={invite_token:e,scopes:t};return this.axiosClient.post(z.joinInvitation,n)}createTenant(e){let t={name:e};return this.axiosClient.post(z.tenantPath,t)}getTenantDetails(e){let t=`${z.tenantPath}/${e}`;return this.axiosClient.get(t)}updateTenant(e,t){let n=`${z.tenantPath}/${e}`,r={name:t};return this.axiosClient.put(n,r)}deleteTenant(e){let t=`${z.tenantPath}/${e}`;return this.axiosClient.delete(t)}getUserTenantMembership(){return this.axiosClient.get(z.tenantPath)}createGroup(e,t){let n=`${z.tenantPath}/${e}/group`,r={name:t};return this.axiosClient.post(n,r)}getGroupInfo(e,t){let n=`${z.tenantPath}/${e}/group/${t}`;return this.axiosClient.get(n)}updateGroup(e,t,n){let r=`${z.tenantPath}/${e}/group/${t}`,i={name:n};return this.axiosClient.put(r,i)}deleteGroup(e,t){let n=`${z.tenantPath}/${e}/group/${t}`;return this.axiosClient.delete(n)}addUserToGroup(e,t,n,r){let i=`${z.tenantPath}/${e}/group/${t}/add`,a={user_id:n,role:r};return this.axiosClient.post(i,a)}removeUserRolesFromGroup(e,t,n,r){let i=`${z.tenantPath}/${e}/group/${t}/remove_roles`,a={user_id:n,roles:r};return this.axiosClient.post(i,a)}changeUserRoles(e,t,n,r){let i=`${z.tenantPath}/${e}/group/${t}/change`,a={user_id:n,roles:r};return this.axiosClient.post(i,a)}deleteUserFromGroup(e,t,n){let r=`${z.tenantPath}/${e}/group/${t}/${n}`;return this.axiosClient.delete(r)}getRolesForTenant(e){let t=`${z.tenantPath}/${e}/role`;return this.axiosClient.get(t)}createRoleForTenant(e,t){let n=`${z.tenantPath}/${e}/role`,r={name:t};return this.axiosClient.post(n,r)}updateRole(e,t,n){let r=`${z.tenantPath}/${e}/role/${t}`,i={name:n};return this.axiosClient.put(r,i)}deleteRole(e,t){let n=`${z.tenantPath}/${e}/role/${t}`;return this.axiosClient.delete(n)}deleteUserFromTenant(e,t){let n=`${z.tenantPath}/${e}/user/${t}`;return this.axiosClient.delete(n)}getGroupInvitations(e,t,n,r){let i=`${z.tenantPath}/${e}/group/${t}/invitations`;return this.axiosClient.get(i,{params:{limit:n,skip:r}})}getTenantInvitations(e,t,n){let r=`${z.tenantPath}/${e}/invitations`;return this.axiosClient.get(r,{params:{limit:t,skip:n}})}invalidateInviteById(e,t,n){let r=`${z.tenantPath}/${e}/group/${t}/invite/${n}`;return this.axiosClient.delete(r)}invalidateInviteByEmail(e,t,n){let r=`${z.tenantPath}/${e}/group/${t}/invite/email/${n}`;return this.axiosClient.delete(r)}},mn=e=>e?{headers:{Authorization:`Bearer ${e}`}}:{},hn=e=>({withCredentials:!0,...mn(e)}),gn=({qr_code_image:e,qr_code:t,...n})=>({...n,qr_code:(t??e??``).replace(/^data:image\/png;base64,/,``)}),_n={"error.2fa.setup.token.expired":`EXPIRED_TOKEN`,"error.2fa.setup.token.revoked":`REVOKED_TOKEN`,"error.2fa.setup.token.already_used":`ALREADY_USED`,"error.2fa.setup.token.rate.limit.exceeded":`RATE_LIMITED`},vn=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getStatus(e){return this.axiosClient.get(z.twoFactorStatus,Gt(e))}async beginSetup(e){return gn(await this.axiosClient.post(z.twoFactorSetupBegin,{},Gt(e)))}confirmSetup(e,t){return this.axiosClient.post(z.twoFactorSetupConfirm,e,Gt(t))}getEnrollment(e){return this.axiosClient.get(z.twoFactorEnrollment,Gt(e))}sendSetupLink(e){return this.axiosClient.post(z.twoFactorEnrollmentEmailLink,void 0,Gt(e))}async beginEnrollment(e){return gn(await this.axiosClient.post(z.twoFactorEnrollmentBegin,void 0,Gt(e)))}confirmEnrollment(e,t){return this.axiosClient.post(z.twoFactorEnrollmentConfirm,t,Gt(e))}verify(e){let{tfa_token:t,code:n,trust_device:r}=e;return this.axiosClient.post(z.twoFactorVerify,{code:n,...r?{trust_device:!0}:{}},hn(t))}useRecoveryCode(e){let{tfa_token:t,recovery_code:n,trust_device:r}=e;return this.axiosClient.post(z.twoFactorRecovery,{recovery_code:n,...r?{trust_device:!0}:{}},hn(t))}disable(e){return this.axiosClient.delete(z.twoFactor,{data:e})}regenerateRecoveryCodes(e){return this.axiosClient.post(z.twoFactorRegenerateCodes,e)}validateTwoFactorSetupMagicLink(e){let t=`${z.twoFactorSetupMagicLink}/${e}`;return this.axiosClient.get(t,{transformRequest:[(e,t)=>(t&&delete t.Authorization,e)]}).then(e=>{let t=e;return t.valid===!1?{success:!1,error:{code:`INVALID_TOKEN`,message:this.getDefaultErrorMessage(400)}}:{success:!0,sessionToken:t.session_token,userId:t.user_id,expiresIn:t.expires_in,appId:t.app_id,reset:t.reset===!0}}).catch(e=>{if(e instanceof B)return{success:!1,error:{code:_n[e.id]??this.mapStatusToErrorCode(e.status),message:e.message||this.getDefaultErrorMessage(e.status)}};if(e.response){let t=e.response.status,n=e.response.data||{},r=e.response.headers?.[`retry-after`]?parseInt(e.response.headers[`retry-after`],10):void 0;return{success:!1,error:{code:n.error||this.mapStatusToErrorCode(t),message:n.message||this.getDefaultErrorMessage(t),retryAfter:r}}}return{success:!1,error:{code:`SERVER_ERROR`,message:e instanceof Error?e.message:`Unable to connect to the server. Please check your connection.`}}})}mapStatusToErrorCode(e){switch(e){case 400:return`INVALID_TOKEN`;case 404:return`REVOKED_TOKEN`;case 410:return`EXPIRED_TOKEN`;case 429:return`RATE_LIMITED`;default:return`SERVER_ERROR`}}getDefaultErrorMessage(e){switch(e){case 400:return`The provided magic link is invalid or malformed.`;case 404:return`This magic link has been revoked or does not exist.`;case 410:return`This magic link has expired. Please request a new one from your administrator.`;case 429:return`Too many validation attempts. Please try again later.`;default:return`An error occurred while validating the magic link.`}}async getAvailableMethods(){return(await this.axiosClient.get(z.TwoFactorMethodsAvailable))?.available_methods??[]}async getRegisteredMethods(e){let t=Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!==void 0));return(await this.axiosClient.get(z.TwoFactorMethodsRegistered,Object.keys(t).length>0?{params:t}:void 0))?.registered_methods??[]}startMethodSetup(e,t){return this.axiosClient.post(z.TwoFactorSetupStart,{...t,method:e})}completeMethodSetup(e,t){return this.axiosClient.post(z.TwoFactorSetupComplete,{...t,method:e})}startRecoveryCodesByCode(e){return this.axiosClient.post(z.TwoFactorSetupStart,{method:`recovery_codes`,via:e},Jt())}completeRecoveryCodesByCode(e,t){return this.axiosClient.post(z.TwoFactorSetupComplete,{method:`recovery_codes`,setup_id:e,code:t},Jt())}removeMethod(e){let t=wt(z.TwoFactorMethodRemove,{id:e});return this.axiosClient.delete(t)}requestChallenge(e,t){return this.axiosClient.post(z.TwoFactorChallenge,e,Jt(mn(t)))}verifyV2(e,t){let{trust_device:n,...r}=e;return this.axiosClient.post(z.TwoFactorVerifyV2,{...r,...n?{trust_device:!0}:{}},hn(t))}switchToAlternative(e,t){return this.axiosClient.post(z.TwoFactorAlternative,e,Jt(mn(t)))}async getTrustedDevices(){return(await this.axiosClient.get(z.TwoFactorTrustedDevices,{withCredentials:!0}))?.devices??[]}revokeTrustedDevice(e){let t=wt(z.TwoFactorTrustedDeviceRevoke,{id:e});return this.axiosClient.delete(t)}async getPreferredMethod(){return(await this.axiosClient.get(z.TwoFactorPreferredMethod))?.preferred_method??null}async setPreferredMethod(e){return(await this.axiosClient.put(z.TwoFactorPreferredMethod,{method:e}))?.preferred_method??e}async clearPreferredMethod(){await this.axiosClient.delete(z.TwoFactorPreferredMethod)}},yn=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}startUpgrade(e){return this.axiosClient.post(z.upgradeStart,e,Ve({}))}startHostedUpgrade(e){return this.axiosClient.post(z.hostedUpgradeStart,e,{withCredentials:!0})}async commitHostedUpgrade(e){await this.axiosClient.post(z.hostedUpgrade,e,{withCredentials:!0})}},bn=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}enrolDeviceKey(e){return this.axiosClient.post(z.userDeviceKey,e)}getUserPasskeys(){return this.axiosClient.get(z.userPasskey)}renameUserPasskey(e,t){return this.axiosClient.patch(`${z.userPasskey}/${t}`,{name:e})}deleteUserPasskey(e){return this.axiosClient.delete(`${z.userPasskey}/${e}`)}addUserPasskeyStart({relyingPartyId:e,deviceId:t,os:n,passkeyDisplayName:r,passkeyUsername:i}){let a={passkey_display_name:r,passkey_username:i,relying_party_id:e,deviceId:t,os:n};return this.axiosClient.post(z.addUserPasskey,a)}addUserPasskeyComplete(e,t,n){return this.axiosClient.post(z.completeAddUserPasskey,{challenge_id:n,device:t,passkey_data:e})}getUserSessions(){return this.axiosClient.get(z.userSessions)}revokeUserSession(e){return this.axiosClient.delete(`${z.userSessions}/${encodeURIComponent(e)}`)}revokeOtherUserSessions(){return this.axiosClient.post(z.userSessionsRevokeOthers)}requestAddressChangeProof(e){return this.axiosClient.post(z.AddressChangeProof,{method:e},Jt())}updateProfile(e,t){return this.axiosClient.patch(z.userProfile,{...e,...t?{proof:t}:{}},Jt())}},xn=`pf-device-proof+jwt`,Sn={name:`ECDSA`,hash:`SHA-256`};function Cn(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function wn(e){return Cn(new TextEncoder().encode(JSON.stringify(e)))}async function Tn(e){let{kty:t,crv:n,x:r,y:i}=e.jwk,a=`${wn({alg:`ES256`,typ:xn,jwk:{kty:t,crv:n,x:r,y:i}})}.${wn({jti:e.jti,ctr:e.ctr,did:e.did,use:e.use,iat:e.iat})}`,o=await crypto.subtle.sign(Sn,e.privateKey,new TextEncoder().encode(a));return`${a}.${Cn(new Uint8Array(o))}`}async function En(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return Cn(new Uint8Array(t))}var Dn=1,On=`key`,kn=`current`,An=e=>new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)}),jn=e=>new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error??Error(`The device key transaction was aborted`))});function Mn(e){let t,n=()=>(t??(t=new Promise((t,n)=>{let r=indexedDB.open(e,Dn);r.onupgradeneeded=()=>{r.result.objectStoreNames.contains(On)||r.result.createObjectStore(On)},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error),r.onblocked=()=>n(Error(`The device key database is blocked by another tab`))}).catch(e=>{throw t=void 0,e})),t),r=async e=>{let t=(await n()).transaction(On,`readwrite`),r=jn(t),i=await e(t.objectStore(On));return await r,i},i=e=>An(e.get(kn)),a=async()=>{let e=await n();return await i(e.transaction(On,`readonly`).objectStore(On))};return{read:a,async ensure(e){let t=await a();if(t)return t;let n=await e();return await r(async e=>{let t=await i(e);if(t)return t;let r={...n,counter:0,enrolled:!1};return e.put(r,kn),r})},next(){return r(async e=>{let t=await i(e);if(!t)return;let n=t.counter+1,r={...t,counter:n};return e.put(r,kn),{record:r,ctr:n}})},async markEnrolled(){await r(async e=>{let t=await i(e);t&&e.put({...t,enrolled:!0},kn)})},async clear(){await r(e=>An(e.delete(kn)))}}}var Nn=`Device keys need IndexedDB and WebCrypto`,Pn={name:`ECDSA`,namedCurve:`P-256`};function Fn(e){return`${e?`${e}_`:``}passflow_device_key`}function In(){return typeof indexedDB<`u`&&typeof crypto<`u`&&crypto.subtle!==void 0}async function Ln(){let e=await crypto.subtle.generateKey(Pn,!1,[`sign`,`verify`]),{kty:t,crv:n,x:r,y:i}=await crypto.subtle.exportKey(`jwk`,e.publicKey);if(t!==`EC`||n!==`P-256`||!r||!i)throw Error(`The device key could not be exported`);return{keyPair:e,jwk:{kty:t,crv:n,x:r,y:i}}}function Rn(e){let t=e.now??Date.now,n=In(),r=n?Mn(e.dbName):void 0,i=(n,r,i,a)=>Tn({privateKey:n.keyPair.privateKey,jwk:n.jwk,jti:a,ctr:r,did:e.deviceId(),use:i,iat:Math.floor(t()/1e3)});return{supported:n,async isEnrolled(){return r?(await r.read())?.enrolled===!0:!1},async proof(e,t){if(!r)return;let n=await r.next();if(n?.record.enrolled)return await i(n.record,n.ctr,e,t)},async enrolProof(e){if(!r)throw Error(Nn);await r.ensure(Ln);let t=await r.next();if(!t)throw Error(`The device key was deleted while enrolling`);return await i(t.record,t.ctr,`enrol`,e)},async markEnrolled(){await r?.markEnrolled()},async clear(){await r?.clear()}}}var zn={keyReused:`error.device.key.reused`,proofRequired:`error.device.proof.required`,stepUpRequired:`error.device.key.step_up_required`,proofUnavailable:`error.device.proof.unavailable`},Bn=e=>typeof e==`string`&&e.startsWith(`error.device.`),Vn=10,Hn=20,Un=class extends Error{constructor(e){super(`Passflow fetch middleware '${e}' resolved without calling next(). Every registered middleware must delegate exactly once; swallowing a request would drop a caller's fetch inside the Passflow wrapper.`),this.name=`FetchMiddlewareContractError`,this.middlewareName=e}},Wn=[],Gn=0,Kn=!1,qn,Jn,Yn=(e,t)=>e.priority-t.priority||e.seq-t.seq,Xn=()=>typeof globalThis>`u`?void 0:globalThis,Zn=async(e,t,n,r)=>{if(t>=e.length){let e=qn;if(!e)throw Error(`Passflow fetch registry: no captured fetch to delegate to.`);return e(n,r)}let i=e[t];if(!i)return Zn(e,e.length,n,r);let a=!1,o=await i.middleware((n,r)=>(a=!0,Zn(e,t+1,n,r)),n,r);if(!a)throw new Un(i.name);return o},Qn=()=>{let e=Xn();if(!e||typeof e.fetch!=`function`)return!1;let t=e.fetch.bind(e),n=(e,t)=>Zn([...Wn].sort(Yn),0,e,t);return qn=t,Jn=n,e.fetch=n,Kn=!0,!0},$n=()=>{let e=Xn();e&&Jn&&e.fetch===Jn&&(qn&&(e.fetch=qn),Kn=!1,Jn=void 0,qn=void 0)},er=(e,t)=>{if(!Kn&&!Qn())return()=>{};let n={middleware:e,name:t.name,priority:t.priority,seq:Gn++};Wn.push(n);let r=!1;return()=>{r||(r=!0,Wn=Wn.filter(e=>e!==n),Wn.length===0&&$n())}},tr=()=>{let e=Xn();return{installed:Kn,names:[...Wn].sort(Yn).map(e=>e.name),foreignPatch:Kn&&!!e&&!!Jn&&e.fetch!==Jn}},H=class e extends Error{constructor(t){super(t.message),this.name=`M2MError`,this.code=t.code,this.status=t.status??400,this.errorUri=t.errorUri,this.rateLimitInfo=t.rateLimitInfo,this.headers=t.headers,this.cause=t.cause,this.timestamp=new Date().toISOString(),Error.captureStackTrace&&Error.captureStackTrace(this,e)}static fromOAuthError(t,n,r){let i=r?e.parseRateLimitHeaders(r):void 0;return new e({code:t.error,message:t.error_description??e.getDefaultMessage(t.error),status:n,errorUri:t.error_uri,rateLimitInfo:i,headers:r})}static fromError(t,n=`server_error`){return new e({code:n,message:t.message||`An unexpected error occurred`,status:500,cause:t})}static parseRateLimitHeaders(e){let t=e[`x-ratelimit-limit`],n=e[`x-ratelimit-remaining`],r=e[`x-ratelimit-reset`]||e[`retry-after`];if(t&&n&&r)return{limit:parseInt(t,10),remaining:parseInt(n,10),reset:parseInt(r,10)}}static getDefaultMessage(e){return{invalid_request:`The request is missing a required parameter or is otherwise malformed.`,invalid_client:`Client authentication failed. Verify your client credentials.`,invalid_grant:`The provided authorization grant is invalid or expired.`,invalid_scope:`The requested scope is invalid, unknown, or exceeds the allowed scopes.`,unauthorized_client:`The client is not authorized to use this grant type.`,unsupported_grant_type:`The authorization grant type is not supported.`,rate_limit_exceeded:`Too many requests. Please retry after the rate limit window resets.`,server_error:`The authorization server encountered an unexpected error.`,temporarily_unavailable:`The authorization server is temporarily unavailable. Please try again later.`}[e]||`An unknown error occurred.`}isRetryable(){return this.code===`server_error`||this.code===`temporarily_unavailable`||this.code===`rate_limit_exceeded`||this.status>=500}getRetryAfter(){if(this.rateLimitInfo?.reset){let e=Math.floor(Date.now()/1e3),t=this.rateLimitInfo.reset-e;return Math.max(t*1e3,1e3)}return 1e3}toJSON(){return{name:this.name,code:this.code,message:this.message,status:this.status,errorUri:this.errorUri,rateLimitInfo:this.rateLimitInfo,timestamp:this.timestamp}}toString(){let e=`M2MError [${this.code}]: ${this.message}`;return this.status&&(e+=` (HTTP ${this.status})`),e}},nr=class extends H{constructor(e,t){super({code:`temporarily_unavailable`,message:e,status:0,cause:t}),this.name=`M2MNetworkError`}},rr=class extends H{constructor(e,t){super({code:`invalid_request`,message:e,status:400,cause:t}),this.name=`M2MTokenParseError`}},ir=class extends H{constructor(e){super({code:`invalid_request`,message:e,status:400}),this.name=`M2MConfigError`}},ar={InvalidRequest:`invalid_request`,InvalidClient:`invalid_client`,InvalidGrant:`invalid_grant`,InvalidScope:`invalid_scope`,UnauthorizedClient:`unauthorized_client`,UnsupportedGrantType:`unsupported_grant_type`,RateLimitExceeded:`rate_limit_exceeded`,ServerError:`server_error`,TemporarilyUnavailable:`temporarily_unavailable`},or={TOKEN_ENDPOINT:`/oauth2/token`,TIMEOUT:1e4,RETRIES:3,RETRY_DELAY:1e3,REFRESH_THRESHOLD:30,CONTENT_TYPE:`application/x-www-form-urlencoded`},sr=class{constructor(){this.cache=new Map}get(e){let t=this.cache.get(e);return t?Date.now()>=t.expiresAt?(this.cache.delete(e),Promise.resolve(null)):Promise.resolve(t.token):Promise.resolve(null)}set(e,t,n){return this.cache.set(e,{token:t,expiresAt:Date.now()+n*1e3}),Promise.resolve()}delete(e){return this.cache.delete(e),Promise.resolve()}},cr={shouldRetry(e,t){return t>=3?!1:e.code===`server_error`||e.code===`temporarily_unavailable`||e.code===`rate_limit_exceeded`||e.status!==void 0&&e.status>=500},getDelay(e){return 2**(e-1)*1e3}},lr=class{constructor(e){if(!e.url)throw new ir(`M2M client requires a URL`);if(!e.clientId)throw new ir(`M2M client requires a clientId`);if(!e.clientSecret)throw new ir(`M2M client requires a clientSecret`);let t=e.url.replace(/\/$/,``);this.config={url:t,clientId:e.clientId,clientSecret:e.clientSecret,scopes:e.scopes,audience:e.audience,autoRefresh:e.autoRefresh??!1,refreshThreshold:e.refreshThreshold??or.REFRESH_THRESHOLD,timeout:e.timeout??or.TIMEOUT,retries:e.retries??or.RETRIES,retryDelay:e.retryDelay??or.RETRY_DELAY,retryStrategy:e.retryStrategy,cache:e.cache,onTokenRequest:e.onTokenRequest,onTokenResponse:e.onTokenResponse,onError:e.onError},this.cache=e.cache??new sr,this.retryStrategy=e.retryStrategy??cr,this.tokenEndpoint=`${t}${or.TOKEN_ENDPOINT}`}getCacheKey(e,t){let n=e?.sort().join(`,`)||``,r=t?.sort().join(`,`)||``;return`m2m:${this.config.clientId}:${n}:${r}`}async getToken(e){let t=e?.scopes??this.config.scopes,n=e?.audience??this.config.audience,r=this.getCacheKey(t,n);if(!e?.forceRefresh){let e=await this.cache.get(r);if(e&&!this.isTokenExpired(e))return e}return this.requestToken(t,n,r)}async getValidToken(){let e=this.config.scopes,t=this.config.audience,n=this.getCacheKey(e,t),r=await this.cache.get(n);if(r){if(this.config.autoRefresh&&this.isTokenExpired(r,this.config.refreshThreshold))return this.requestToken(e,t,n);if(!this.isTokenExpired(r))return r}return this.requestToken(e,t,n)}async requestToken(e,t,n){let r={grant_type:`client_credentials`,client_id:this.config.clientId,client_secret:this.config.clientSecret};e&&e.length>0&&(r.scope=e.join(` `)),t&&t.length>0&&(r.audience=t.join(` `)),this.config.onTokenRequest&&this.config.onTokenRequest({clientId:this.config.clientId,scopes:e??[],audience:t??[],timestamp:new Date().toISOString()});let i=await this.executeWithRetry(()=>this.doTokenRequest(r));return i.issued_at=Math.floor(Date.now()/1e3),n&&await this.cache.set(n,i,i.expires_in),this.config.onTokenResponse&&this.config.onTokenResponse(i),i}async doTokenRequest(e){let t=new URLSearchParams;t.append(`grant_type`,e.grant_type),t.append(`client_id`,e.client_id),t.append(`client_secret`,e.client_secret),e.scope&&t.append(`scope`,e.scope),e.audience&&t.append(`audience`,e.audience);let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeout);try{let e=await fetch(this.tokenEndpoint,{method:`POST`,headers:{"Content-Type":or.CONTENT_TYPE,Accept:`application/json`},body:t.toString(),signal:n.signal});clearTimeout(r);let i={};e.headers.forEach((e,t)=>{i[t.toLowerCase()]=e});let a=await e.json();if(!e.ok){let t=H.fromOAuthError({error:a.error||`server_error`,error_description:a.error_description||a.message,error_uri:a.error_uri},e.status,i);throw this.config.onError&&this.config.onError({error:t.code,error_description:t.message}),t}return a}catch(e){throw clearTimeout(r),e instanceof Error&&e.name===`AbortError`?new nr(`Request timed out after ${this.config.timeout}ms`):e instanceof TypeError&&e.message.includes(`fetch`)?new nr(`Network error: ${e.message}`,e):e instanceof H?e:H.fromError(e instanceof Error?e:Error(String(e)))}}async executeWithRetry(e){let t;for(let n=1;n<=this.config.retries;n++)try{return await e()}catch(e){if(!(e instanceof H))throw e;if(t=e,n<this.config.retries&&this.retryStrategy.shouldRetry({code:e.code,status:e.status},n)){let e=this.retryStrategy.getDelay(n);await this.sleep(e);continue}throw e}throw t??new H({code:`server_error`,message:`Request failed after retries`})}sleep(e){return new Promise(t=>setTimeout(t,e))}getCachedToken(){let e=this.cache;if(`cache`in e){let t=this.getCacheKey(this.config.scopes,this.config.audience);return e.cache.get(t)?.token??null}return null}isTokenExpired(e,t=0){if(!e)return!0;let n=Math.floor(Date.now()/1e3);return n>=(e.issued_at??n-e.expires_in)+e.expires_in-t}parseToken(e){try{let t=e.split(`.`);if(t.length!==3)throw new rr(`Invalid JWT format: expected 3 parts`);let n=t[1];if(!n)throw new rr(`Invalid JWT format: missing payload`);let r=atob(n.replace(/-/g,`+`).replace(/_/g,`/`)),i=JSON.parse(r);return i.scopes&&typeof i.scopes==`string`?i.scopes=i.scopes.split(` `):i.scopes||(i.scopes=[]),i}catch(e){throw e instanceof rr?e:new rr(`Failed to parse token: ${e instanceof Error?e.message:`Unknown error`}`)}}clearCache(){let e=this.getCacheKey(this.config.scopes,this.config.audience);this.cache.delete(e)}async revokeToken(){let e=this.getCachedToken();if(!e)return;let t=`${this.config.url}/oauth2/revoke`,n=new URLSearchParams;n.append(`token`,e.access_token),n.append(`client_id`,this.config.clientId),n.append(`client_secret`,this.config.clientSecret);try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":or.CONTENT_TYPE},body:n.toString()});if(!e.ok&&e.status!==200){let t=await e.json().catch(()=>({}));throw H.fromOAuthError({error:t.error||`server_error`,error_description:t.error_description||`Token revocation failed`},e.status)}this.clearCache()}catch(e){throw e instanceof H?e:H.fromError(e instanceof Error?e:Error(String(e)))}}get url(){return this.config.url}get clientId(){return this.config.clientId}get scopes(){return this.config.scopes}get audience(){return this.config.audience}},ur=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`,dr=32,fr=e=>{let t=``;for(let n=0;n<e.length;n+=3){let r=e[n],i=e[n+1],a=e[n+2];t+=ur.charAt(r>>2),t+=ur.charAt((r&3)<<4|(i??0)>>4),i!==void 0&&(t+=ur.charAt((i&15)<<2|(a??0)>>6)),a!==void 0&&(t+=ur.charAt(a&63))}return t},pr=()=>{let e=globalThis.crypto;if(!e?.subtle)throw Error(`PKCE needs the Web Crypto API, which is available only in a secure context (https or localhost)`);return e},mr=async e=>{let t=await pr().subtle.digest(`SHA-256`,new TextEncoder().encode(e));return fr(new Uint8Array(t))},hr=(e=dr)=>fr(pr().getRandomValues(new Uint8Array(e))),gr=async()=>{let e=hr(dr);return{verifier:e,challenge:await mr(e)}},_r=()=>!!globalThis.crypto?.subtle,U=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`PassflowOidcError`}},vr=`Sign in again.`,yr=e=>`This app is type ${e} and is a confidential client (it has a secret). For a browser app set its type to SPA; a server-side app redeems the code on its server with the secret.`,br=`This app is a confidential client. For a browser app set its type to SPA (or token_endpoint_auth_method to none); a server-side app must redeem the code on its server with the client secret.`,xr=()=>new U(`TOKENS_IN_URL_NOT_ALLOWED`,`Tokens in the URL are accepted only for apps in Simple mode`),Sr=`passflow_oidc_pkce`,Cr=6e5,wr=e=>{try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/+$/,``)}`}catch{return e}},Tr=e=>!e.includes(`openid`)&&(e.includes(`id`)||e.includes(`oidc`))?[...e,`openid`]:[...e],Er=async e=>{if(!_r())throw new U(`SECURE_CONTEXT_REQUIRED`,`Sign-in needs the Web Crypto API, which is available only in a secure context (https or localhost)`);let t=Tr(e.scopes),n=await gr(),r={verifier:n.verifier,state:hr(),...t.includes(`openid`)?{nonce:hr()}:{},clientId:e.clientId,redirectUri:e.redirectUri,scopes:t,expiresAt:Date.now()+Cr};try{sessionStorage.setItem(Sr,JSON.stringify(r))}catch{throw new U(`STORAGE_UNAVAILABLE`,`Sign-in needs sessionStorage, which cannot be written here`)}let i=new URL(`${e.url.replace(/\/+$/,``)}/oidc/authorize`);return i.search=new URLSearchParams({response_type:`code`,client_id:r.clientId,redirect_uri:r.redirectUri,scope:t.join(` `),state:r.state,code_challenge:n.challenge,code_challenge_method:`S256`,...r.nonce?{nonce:r.nonce}:{}}).toString(),i.toString()},Dr=e=>{let t=e;return typeof t==`object`&&!!t&&typeof t.verifier==`string`&&typeof t.state==`string`&&typeof t.clientId==`string`&&typeof t.redirectUri==`string`&&Array.isArray(t.scopes)&&typeof t.expiresAt==`number`},Or=()=>{let e;try{e=sessionStorage.getItem(Sr)}catch{return{status:`none`}}if(!e)return{status:`none`};try{let t=JSON.parse(e);if(Dr(t)&&Date.now()<t.expiresAt)return{status:`live`,slot:t}}catch{}return{status:`unusable`}},kr=()=>{try{sessionStorage.removeItem(Sr)}catch{}},Ar=async e=>{try{let t=await e.json();return typeof t==`object`&&t?t:void 0}catch{return}},jr=async(e,t,n)=>{let r;try{r=await fetch(`${e.replace(/\/+$/,``)}/oidc/token`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`authorization_code`,code:t,redirect_uri:n.redirectUri,client_id:n.clientId,code_verifier:n.verifier}).toString()})}catch{throw new U(`TOKEN_EXCHANGE_FAILED`,vr)}let i=await Ar(r);if(!r.ok)throw i?.error===`invalid_client`?new U(`invalid_client`,br):i?.error===`invalid_grant`?new U(`invalid_grant`,vr):new U(`TOKEN_EXCHANGE_FAILED`,vr);if(typeof i?.access_token!=`string`)throw new U(`TOKEN_EXCHANGE_FAILED`,vr);let a=typeof i.id_token==`string`?i.id_token:void 0;if(n.scopes.includes(`openid`)){let e;try{e=a?P(a).nonce:void 0}catch{e=void 0}if(!a||e!==n.nonce)throw new U(`ID_TOKEN_INVALID`,`The ID token is missing or not issued for this sign-in. ${vr}`)}return{access_token:i.access_token,...typeof i.refresh_token==`string`?{refresh_token:i.refresh_token}:{},...a?{id_token:a}:{},scopes:n.scopes}},Mr=`error`,Nr=new WeakMap,Pr=(e,t)=>{if(typeof t!=`object`&&typeof t!=`function`||t===null)return!0;let n=Nr.get(e);return n||(n=new WeakSet,Nr.set(e,n)),!n.has(t)&&(n.add(t),!0)},W=(e,t)=>Pr(e,t.originalError)?(e.notify(Mr,t),!0):!1,G=function(e){return e.SignIn=`signin`,e.SignInStart=`signin:start`,e.Register=`register`,e.RegisterStart=`register:start`,e.EmailVerificationRequired=`email-verification:required`,e.SignOut=`signout`,e.SessionRestored=`session:restored`,e.SessionExpired=`session:expired`,e.Error=`error`,e.Refresh=`refresh`,e.RefreshStart=`refresh:start`,e.TokenCacheExpired=`token-cache-expired`,e.TwoFactorRequired=`2fa:required`,e.TwoFactorSetupStarted=`2fa:setup_started`,e.TwoFactorEnabled=`2fa:enabled`,e.TwoFactorDisabled=`2fa:disabled`,e.TwoFactorVerified=`2fa:verified`,e.TwoFactorRecoveryUsed=`2fa:recovery_used`,e.TwoFactorRecoveryCodesLow=`2fa:recovery_low`,e.TwoFactorRecoveryCodesExhausted=`2fa:recovery_exhausted`,e.TwoFactorSetupMagicLinkValidated=`2fa:magic_link_validated`,e.TwoFactorSetupMagicLinkFailed=`2fa:magic_link_failed`,e.TwoFactorChallengeReceived=`two_factor_challenge_received`,e.TwoFactorMethodSwitched=`two_factor_method_switched`,e.TwoFactorDeviceTrusted=`two_factor_device_trusted`,e.RefreshFailing=`refresh:failing`,e.RefreshRecovered=`refresh:recovered`,e.AntiBotSolving=`anti-bot:solving`,e.AntiBotSolved=`anti-bot:solved`,e}({}),Fr=class{constructor(){this.subscribers=new Map}subscribe(e,t){if(t?.length){let n=new Set(t);this.subscribers.set(e,n)}else this.subscribers.set(e,null)}unsubscribe(e,t){if(!t?.length){this.subscribers.delete(e);return}let n=this.subscribers.get(e);n&&(t.forEach(e=>n.delete(e)),n.size===0&&this.subscribers.delete(e))}notify(e,t){e===`error`&&Pr(this,t?.originalError),this.subscribers.forEach((n,r)=>{(!n||n.has(e))&&r.onAuthChange?.(e,t)})}notifyError(e){return W(this,e)}},Ir=256,Lr=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`)),Rr=e=>{let t=new Uint8Array(e),n=``;for(let e of t)n+=Lr[e];return n},zr=class extends Error{};async function Br(e,t,n,r=1/0){let i=globalThis.crypto?.subtle;if(!i)throw Error(`Web Crypto unavailable`);let a=t.toLowerCase(),o=new TextEncoder;for(let t=0;t<=n;t+=Ir){if(Date.now()>r)throw new zr(`Solve timed out`);let s=Math.min(t+Ir-1,n),c=[];for(let n=t;n<=s;n++)c.push(i.digest(`SHA-256`,o.encode(`${e}:${n}`)));let l=await Promise.all(c);for(let e=0;e<l.length;e++)if(Rr(l[e])===a)return t+e}return null}var Vr=`The browser check could not be completed. Try again later.`,Hr=`Verification failed. Try again.`,Ur=6e4,Wr=class extends Error{},Gr=(e,t,n,r)=>new B({id:e,message:t,status:0,location:n,time:new Date().toISOString()},r===void 0?void 0:{cause:r}),Kr=(e,t)=>new Promise((n,r)=>{let i=new Worker(e),a=setTimeout(()=>o(()=>r(new Wr)),Ur),o=e=>{clearTimeout(a),i.terminate(),e()};i.addEventListener(`message`,e=>{let t=e.data;t&&`error`in t?o(()=>r(Error(t.error))):o(()=>n(t?.number??null))}),i.addEventListener(`error`,()=>o(()=>r(Error(`Anti-bot worker failed`)))),i.addEventListener(`messageerror`,()=>o(()=>r(Error(`Anti-bot worker message failed`)))),i.postMessage(t)});async function qr(e,t,n=`anti-bot`){if(e.algorithm!==`SHA-256`)throw Gr(rt,Vr,n);if(!Number.isSafeInteger(e.max)||e.max<0||e.max>5e6)throw Gr(rt,Hr,n);let r={salt:e.salt,challenge:e.challenge,max:e.max},i;try{i=t&&typeof Worker<`u`?await Kr(t,r):await Br(r.salt,r.challenge,r.max,Date.now()+Ur)}catch(e){throw Gr(rt,e instanceof Wr||e instanceof zr?Hr:Vr,n,e)}if(i===null)throw Gr(rt,Vr,n);return i}function Jr(e,t){let n={app:e.app,exp:e.exp,max:e.max,salt:e.salt,challenge:e.challenge,number:t,signature:e.signature};return btoa(JSON.stringify(n))}var Yr=`This app requires a verification token. Call setAntiBotTokenProvider() before signing in.`,Xr=`The verification could not be completed. Try again.`;function Zr(e){let t,n=async(e,t)=>{let n;try{n=await e({action:x,operation:t.operation})}catch(e){throw Gr(nt,Xr,t.operation,e)}if(typeof n!=`string`||n===``)throw Gr(nt,Xr,t.operation);return n},r=async t=>{let n=await e.fetchChallenge({...t.identifier?{identifier:t.identifier}:{},...t.device?{device:t.device}:{}});return Jr(n,await qr(n,e.workerUrl,t.operation))};return{setTokenProvider(e){t=e},async headerFor(i){let a=i.settings??await e.readSettings().catch(()=>void 0);if(a?.bot_mode!==`human_only`)return;let o=a.anti_bot?.provider??`builtin`,s=o===`builtin`;e.store.notify(G.AntiBotSolving,{operation:i.operation,provider:o});let c;if(s)c=await r(i);else{let e=t;if(!e)throw Gr(tt,Yr,i.operation);c=await n(e,i)}return e.store.notify(G.AntiBotSolved,{operation:i.operation,provider:o}),{value:c,builtin:s}}}}var Qr=`passflow-refresh`,$r=`passflow-refresh-takeover`,ei=`passflow-auth`,ti=Object.freeze([1e3,3e3,1e4,3e4,6e4]),ni=.2,ri=6e5,ii=5e3,K=2e4,ai=2e4,oi=1e3,si=2e3,ci=1e3,li=1e4,ui=5e3;function di(e){let t=e?`:${e}`:``;return{lock:`${Qr}${t}`,takeoverLock:`${$r}${t}`,channel:`${ei}${t}`}}function q(e){return typeof e==`string`&&e!==``?e:void 0}function fi(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function pi(e){return typeof e==`object`&&!!e}function mi(e,t){for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function hi(e){if(!pi(e))return null;let t=Array.isArray(e.scopes)?e.scopes.filter(e=>typeof e==`string`):void 0;return mi({},{access_token:q(e.access_token),refresh_token:q(e.refresh_token),id_token:q(e.id_token),scopes:Array.isArray(e.scopes)&&t?.length===e.scopes.length?t:void 0})}function gi(e){if(!pi(e))return null;let{kind:t,attempt:n,nextAt:r,strikes:i}=e;return t!==`transient`&&t!==`auth`||typeof n!=`number`||!Number.isInteger(n)||n<1||fi(r)===void 0||typeof i!=`number`||!Number.isFinite(i)||i<0?null:mi({kind:t,attempt:n,nextAt:r,strikes:i},{from:q(e.from),failingSince:fi(e.failingSince)})}function _i(e){return mi({},{fp:q(e.fp),sub:q(e.sub),sid:q(e.sid),iat:fi(e.iat)})}function vi(e){if(!pi(e))return null;let t=e;if(t.v!==void 0&&t.v!==1)return null;let n=q(t.tabId);if(!n)return null;switch(t.type){case`tokens-refreshed`:{let e=hi(t.tokens),r=q(t.from),i=q(t.to);return!e||!r||!i?null:mi({type:t.type,tabId:n,tokens:e,from:r,to:i},{fromIat:fi(t.fromIat),fromSid:typeof t.fromSid==`string`?t.fromSid:void 0,sentAt:fi(t.sentAt)})}case`session-refreshed`:{let e=fi(t.at);return e===void 0?null:mi({type:t.type,tabId:n,at:e},{sub:q(t.sub)})}case`still-refreshing`:{let e=t.retry===void 0?null:gi(t.retry);return e?{type:t.type,tabId:n,retry:e}:{type:t.type,tabId:n}}case`retry-scheduled`:{let e=gi(t);return e?{type:t.type,tabId:n,message:typeof t.message==`string`?t.message:``,retry:e}:null}case`takeover`:return{type:t.type,tabId:n};case`lock-wanted`:return t.purpose===`commit`||t.purpose===`logout`?{type:t.type,tabId:n,purpose:t.purpose}:null;case`session-ended`:case`signed-out`:return{type:t.type,tabId:n,..._i(t)};case`rate-limited`:{let e=fi(t.until);return e===void 0?null:{type:t.type,tabId:n,until:e}}case`refresh-failed`:{let e=q(t.from);return e?{type:t.type,tabId:n,message:typeof t.message==`string`?t.message:``,from:e}:null}default:return null}}function yi(e,t){let n={v:1,tabId:e};if(t.type===`retry-scheduled`){let{retry:e,...r}=t;return mi(n,{...r,...e})}return mi(n,{...t})}var bi=`[passflow] navigator.locks or BroadcastChannel is unavailable (they need a secure context); each tab refreshes on its own, with the save checks only`,xi={now:()=>Date.now(),random:()=>Math.random(),setTimeout:(e,t)=>{let n=setTimeout(e,t);return n.unref?.(),()=>clearTimeout(n)}};function Si(){let e=globalThis.crypto;return typeof e?.randomUUID==`function`?e.randomUUID():`tab-${Math.random().toString(36).slice(2)}-${Date.now()}`}function Ci(e){return e?{now:()=>e.now(),setTimeout:(t,n)=>e.setTimeout(t,n),random:e.random?()=>e.random?.()??Math.random():xi.random}:xi}function wi(e){return typeof window<`u`&&typeof document<`u`&&e.getDeviceType()===`web`}function Ti(e){try{return e.storageSharedAcrossTabs===!0}catch{return!1}}function Ei(){try{let e=globalThis.navigator?.locks;return e&&typeof e.request==`function`?e:void 0}catch{return}}function Di(e){return t=>{let n=n=>{let r=n.key;(r==null||e().includes(r))&&t()};return window.addEventListener(`storage`,n),()=>window.removeEventListener(`storage`,n)}}function Oi(e){return{transports:null,names:di(e),clock:xi,warnOnFirstCycle:!1}}function ki(e,t,n,r){let i=di(n),a=wi(t),o=a?Di(r.tokenKeys):void 0,s=e=>{let t={transports:null,names:i,clock:xi,warnOnFirstCycle:e};return o&&(t.onStorageChange=o),t};if(typeof e==`object`&&e){let t={transports:{locks:e.locks,channel:e.channel,tabId:e.tabId??Si()},names:i,clock:Ci(e.clock),warnOnFirstCycle:!1};return e.onStorageChange&&(t.onStorageChange=e.onStorageChange),t}if(e===`none`||!a||!Ti(t))return s(!1);let c=Ei();if(!c||typeof BroadcastChannel!=`function`)return s(!0);let l;try{l=new BroadcastChannel(i.channel)}catch{return s(!0)}let u={transports:{locks:c,channel:l,tabId:Si()},names:i,clock:xi,warnOnFirstCycle:!1};return o&&(u.onStorageChange=o),u}var Ai=Object.freeze([`error.token.invalid.error`,`error.api.token.parse.error`,`error.api.user.blocked`,`error.2fa.required_by_app`,`error.validation.token.invalid.subject`,`error.not.found`]);function ji(e){if(typeof e!=`object`||!e)return;let t=e;return typeof t.get==`function`?t.get(`retry-after`):t[`retry-after`]??t[`Retry-After`]}function Mi(e,t){if(typeof e==`number`)return!Number.isFinite(e)||e<0?void 0:Math.min(ri,Math.floor(e)*1e3);if(typeof e!=`string`)return;let n=e.trim();if(n===``)return;if(/^\d+$/.test(n))return Math.min(ri,Number.parseInt(n,10)*1e3);if(!/[a-z]/i.test(n))return;let r=Date.parse(n);if(!Number.isNaN(r))return Math.min(ri,Math.max(0,r-t))}function Ni(e){return typeof e==`number`&&Number.isInteger(e)&&e>=100&&e<=599?e:void 0}function Pi(e){return typeof e==`object`&&e?Fi(e):void 0}function Fi(e){if(typeof e.id==`string`&&e.id!==``)return e.id;let t=e.response?.data;if(typeof t!=`object`||!t)return;let n=t.error;if(typeof n!=`object`||!n)return;let r=n.id;return typeof r==`string`&&r!==``?r:void 0}function Ii(e,t=Date.now()){if(typeof e!=`object`||!e)return{kind:`transient`};let n=e,r=Fi(n),i=Ni(n.response?.status)??Ni(n.status),a={};if(i!==void 0&&(a.status=i),r!==void 0&&(a.id=r),Bn(r))return{kind:`auth`,terminal:!0,...a};if(r===`error.token.blocked`)return{kind:`blocked`,...a};if(r!==void 0&&Ai.includes(r)||i!==void 0&&i>=400&&i<=499&&i!==429)return{kind:`auth`,...a};if(i===void 0)return{kind:`transient`,...a};let o=Mi(n.retryAfter??ji(n.response?.headers),t);return o===void 0?{kind:`transient`,...a}:{kind:`transient`,...a,retryAfterMs:o}}function Li(e,t,n){let r=ti.length,i=ti[(Number.isFinite(e)?Math.min(Math.max(Math.floor(e),1),r):1)-1]??ti[r-1]??6e4,a=Number.isFinite(t)?Math.min(Math.max(t,0),.999):0,o=i+Math.floor(i*ni*a);return Math.max(o,n!==void 0&&Number.isFinite(n)?Math.min(Math.max(n,0),ri):0)}var Ri=class{error(e,...t){console.error(e,...t)}warn(e,...t){console.warn(e,...t)}info(e,...t){console.info(e,...t)}debug(e,...t){console.debug(e,...t)}};function zi(){return new Ri}var Bi={onGranted:()=>!1,onLockLost:()=>void 0,onMessage:()=>void 0};function Vi(e){let{locks:t,channel:n,tabId:r,names:i,clock:a}=e,o=Bi,s=null,c=null,l=null,u=null,d=null,f=null,p=0,m,h=!1,g=!1,_=e=>{g||n.postMessage(yi(r,e))},v=()=>s!==null&&c===null,y=()=>{f?.(),f=null},b=e=>{p=Math.max(p,e),y(),f=a.setTimeout(()=>{f=null,ee()},Math.max(0,p-a.now()))},x=()=>{d?.(),d=null},S=()=>{d=a.setTimeout(()=>{d=null,c&&(h=!1,_(m?{type:`still-refreshing`,retry:m}:{type:`still-refreshing`}),S())},ii)},C=()=>{y(),x(),u?.(),u=null;let e=s;s=null,c=null,e&&(e.dead=!0,e.abort.abort());let t=l;l=null,t?.()},w=()=>{x(),c=null,s=null,l=null,o.onLockLost()},T=(e,t)=>{if(e.dead||s!==e||g){t();return}y(),c=e,l=t,h=!1,S();let n=!1;try{n=o.onGranted()}finally{!n&&c===e&&C()}},E=e=>{if(e.takeover&&(u?.(),u=null),!(e.dead||s!==e))return new Promise(t=>{a.setTimeout(()=>T(e,t),0)})},D=e=>{let n={takeover:e,dead:!1,abort:new AbortController};s=n;let r=e?{steal:!0}:{signal:n.abort.signal};t.request(i.lock,r,()=>E(n)).catch(()=>{n.dead=!0,c===n&&w()})},ee=()=>{if(!v())return;let e=s;t.request(i.takeoverLock,{ifAvailable:!0},t=>{if(s===e&&v()){if(t===null)b(a.now()+K);else return _({type:`takeover`}),new Promise(t=>{u=t,e&&(e.dead=!0,e.abort.abort()),D(!0)})}}).catch(()=>{v()&&b(a.now()+K)})},te=e=>{if(g)return;let t=vi(e.data);if(t&&t.tabId!==r){switch(t.type){case`still-refreshing`:h=!0,v()&&(b(a.now()+K),t.retry&&b(t.retry.nextAt+K));break;case`takeover`:h=!0,v()&&b(a.now()+K);break;case`retry-scheduled`:h=!0,v()&&b(Math.max(a.now(),t.retry.nextAt)+K);break;case`rate-limited`:v()&&b(t.until+K)}o.onMessage(t)}};return n.addEventListener(`message`,te),{coordinated:!0,tabId:r,get waiting(){return v()},get holding(){return c!==null},attach:e=>{o=e},request:e=>{g||s||(p=0,b(Math.max(a.now()+K,e??0)),D(!1))},release:C,post:_,setRetryInfo:e=>{m=e},foreignHolderHeard:()=>h,dispose:()=>{g||(C(),g=!0,n.removeEventListener(`message`,te),n.close())}}}function Hi(e=`local`){let t=Bi,n=!1,r=!1,i=0,a=!1,o=()=>{n=!1,r=!1,i+=1};return{coordinated:!1,tabId:e,get waiting(){return n&&!r},get holding(){return r},attach:e=>{t=e},request:()=>{if(a||n)return;n=!0;let e=++i;Promise.resolve().then(()=>{if(a||i!==e||!n)return;r=!0;let s=!1;try{s=t.onGranted()}finally{!s&&i===e&&o()}})},release:o,post:()=>void 0,setRetryInfo:()=>void 0,foreignHolderHeard:()=>!1,dispose:()=>{o(),a=!0}}}var J={unavailable:`error.refresh.unavailable`,authRetry:`error.refresh.auth_retry`,sessionEnded:`error.refresh.session_ended`,signedOut:`error.refresh.signed_out`,successorTimeout:`error.refresh.successor_timeout`,identityChanged:`error.refresh.identity_changed`,disposed:`error.refresh.disposed`},Ui={"error.refresh.unavailable":503,"error.refresh.auth_retry":401,"error.refresh.session_ended":401,"error.refresh.signed_out":401,"error.refresh.successor_timeout":401,"error.refresh.identity_changed":401,"error.refresh.disposed":499},Wi={"error.refresh.unavailable":`Token refresh is unavailable; a retry is scheduled`,"error.refresh.auth_retry":`Token refresh was refused; a retry is scheduled`,"error.refresh.session_ended":`The session has ended`,"error.refresh.signed_out":`Signed out`,"error.refresh.successor_timeout":`The refresh token was already used and no successor arrived`,"error.refresh.identity_changed":`Storage holds another user's tokens`,"error.refresh.disposed":`The Passflow instance was disposed`},Y=class extends B{constructor(e,t={}){super({id:e,message:t.message??Wi[e],status:Ui[e],location:`/auth/refresh`,time:new Date().toISOString()}),this.name=`PassflowRefreshError`,t.nextRetryAt!==void 0&&(this.nextRetryAt=t.nextRetryAt),t.cause!==void 0&&(this.cause=t.cause)}},Gi=class extends Error{constructor(e,t){super(t??(e===`lock-timeout`?`Step-up commit could not take the refresh lock in time`:`Step-up commit answer arrived after the stored session moved on`)),this.name=`UpgradeCommitInterruptedError`,this.reason=e}};function Ki(e){if(!e)return;let t=3735928559,n=1103547991;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,2654435761),n=Math.imul(n^i,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(t^t>>>13,3266489909),(4294967296*(2097151&n)+(t>>>0)).toString(16)}function qi(e){return typeof e==`string`&&e!==``?e:void 0}function X(e){let t=Ki(e);if(!e||!t)return;let n={};try{let t=P(e);typeof t==`object`&&t&&(n=t)}catch{}let r=typeof n.iat==`number`&&Number.isFinite(n.iat)?n.iat:void 0,i={fp:t},a=qi(n.sub),o=qi(n.sid);return a!==void 0&&(i.sub=a),o!==void 0&&(i.sid=o),r!==void 0&&(i.iat=r),i}var Ji=`[passflow] A refresh token carries no iat claim: it is never taken over an ordered one, and cross-tab adoption falls back to fingerprints`;function Yi(e=e=>zi().warn(e)){let t=new Map,n=new Set,r=!1,i=[],a=!1,o=()=>{a||(a=!0,e(Ji))},s=(e,t)=>e.has(t)?!0:e.size>=32?!1:(e.add(t),!0),c=e=>{if(!e)return;if(e.iat===void 0){s(n,e.fp)||(r=!0);return}let i=e.sid??``,a=t.get(i);if((!a||e.iat>a.floor)&&(a={floor:e.iat,atFloor:new Set,full:!1}),t.delete(i),t.set(i,a),t.size>8){let e=t.keys().next().value;e!==void 0&&t.delete(e)}e.iat<a.floor||s(a.atFloor,e.fp)||(a.full=!0)},l=e=>{if(!e)return!1;if(e.iat===void 0)return r||n.has(e.fp);let i=t.get(e.sid??``);return!i||e.iat>i.floor?!1:e.iat<i.floor||i.full||i.atFloor.has(e.fp)},u=(e,t)=>!e.sub||!t.sub||e.sub===t.sub,d=e=>e?i.some(t=>t.fp===e.fp||t.iat!==void 0&&e.iat!==void 0&&u(t,e)&&t.sid===e.sid&&e.iat<t.iat):!1,f=(e,t)=>e.fp===t.fp?!1:e.iat===void 0?(o(),t.iat===void 0&&!l(e)):t.iat===void 0?!0:e.iat===t.iat?e.sid===t.sid&&l(t)&&!l(e):e.iat>t.iat;return{retire:c,isRetired:l,isAfter:f,isForward:(e,t)=>!e||d(e)||l(e)?!1:t?f(e,t):(e.iat===void 0&&o(),!0),end:e=>{let t=i.findIndex(t=>t.fp===e.fp||t.sid!==void 0&&t.sid===e.sid&&u(t,e));if(t!==-1){let n=i[t];if(n?.iat!==void 0&&(e.iat===void 0||n.iat>e.iat))return;i.splice(t,1)}i.push({...e}),i.length>4&&i.shift()},isEnded:d}}var Xi=class extends Error{constructor(e){super(e===`emptied`?`The shared token storage was emptied`:`The stored refresh token belongs to an ended session`),this.name=`SessionEnded`,this.cause=e}},Zi=class extends Error{constructor(){super(`The shared token storage holds another user's tokens`),this.name=`IdentityChanged`}};function Qi(e){if(e)try{let t=P(e).sub;return typeof t==`string`&&t!==``?t:void 0}catch{return}}function Z(e){return Qi(e?.access_token)??Qi(e?.refresh_token)??Qi(e?.id_token)}function $i(e,t){return!t||e.iat===void 0||t.iat===void 0?!1:e.sid===t.sid&&e.iat<t.iat}function ea(e){return typeof e==`object`&&!!e}function ta(e){let{storage:t,cache:n,schedule:r}=e,i=e.identity??(()=>void 0),a=e.warn??(e=>zi().warn(e)),o=e.lineage??Yi(a),s=e.onSessionLost,c,l=0,u=[],d=[],f=0,p,m=0,h,g,_,v,y=()=>{let e=t.getTokens(),n=e?.refresh_token;if(!n)return p=l,e;p!==void 0&&(f=Math.max(f,p,m),p=void 0);let r=Ki(n)??``;return r!==c?.fp&&(c={fp:r,seq:l}),e},b=()=>X(n.getTokens()?.refresh_token),x=()=>i()??Z(n.getTokens()),S=()=>{let e=b();return!e||e.iat===void 0||!x()?!1:!o.isRetired(e)&&!o.isEnded(e)},C=e=>{let t=b();if(!t||t.fp===e.fp||!S())return!1;let n=x();return!e.sub||n!==e.sub||t.iat===void 0||e.iat===void 0?!1:t.sid!==e.sid||o.isAfter(t,e)},w=e=>!!e?.access_token&&!e.refresh_token&&!n.getTokens()?.refresh_token,T=e=>{let t=x();return d.some(n=>n.seq>e&&(!n.sub||!t||n.sub===t))},E=()=>{let e=x();for(let t=u.length-1;t>=0;t--){let n=u[t];if(!n||n.seq<=f)break;if(!n.sub||!e||n.sub===e)return n}},D=()=>{if(!S())return`end`;let e=c?.seq??0,t=E();return T(t?Math.min(e,t.seq):e)?`end`:t?C(t)?`keep`:`end`:s?`wait`:`end`},ee=()=>{h?.(),h=void 0},te=(e=!1)=>{let t=D();t===`wait`&&e&&(t=`end`),t!==`wait`&&ee(),t===`wait`&&!h&&(h=r(()=>{h=void 0;let e=y();e?.refresh_token||w(e)?oe():te(!0)===`end`&&s?.(`emptied`)},si));let n=t===`keep`?E():void 0;return n&&(m=Math.max(m,n.seq)),n&&g!==n.fp&&(g=n.fp,a(`[passflow] The shared token storage was emptied by the end of the session of ${n.fp}, a refresh token the ${b()?.fp??`(none)`} this tab holds is ahead of: keeping it. Nothing is refreshed until the storage holds a token again.`)),t},O=e=>e.held!==void 0&&b()?.fp===e.held.cachedFp,ne=e=>{let t=b();return!!t&&!o.isRetired(t)&&!o.isEnded(t)&&o.isAfter(t,e)},re=e=>{if(!ne(e))return!1;if(o.isRetired(e))return!0;let t=b();return e.iat!==void 0&&t?.iat!==void 0&&t.sid===e.sid},ie=(e,t)=>o.isForward(e,t)?!0:!!e&&!!t&&e.iat!==void 0&&e.sid!==t.sid&&o.isRetired(t)&&!o.isRetired(e)&&!o.isEnded(e),ae=e=>{let t=b();t&&t.fp!==Ki(e.refresh_token)&&o.retire(t),n.setTokensCache(e)},k=e=>{let t=y(),n=t?.refresh_token;if(n===e.refreshToken)return null;if(!t||!n)return te()===`end`?{kind:`ended`,cause:`emptied`}:{kind:`superseded`,adopted:!1};let r=Qi(t.access_token)??Qi(n);if(e.sub&&r&&e.sub!==r)return{kind:`identity-changed`,saved:!1};let i=X(n);if(o.isEnded(i))return i&&C(i)?{kind:`superseded`,adopted:!1}:{kind:`ended`,cause:`ended`};o.retire(e.order);let a=b();return ie(i,a)||i?.fp===a?.fp&&!o.isRetired(i)?(ae(t),{kind:`superseded`,adopted:!0}):{kind:`superseded`,adopted:!1}},A=e=>C(e)?{kind:`superseded`,adopted:!1}:{kind:`ended`,cause:`ended`},oe=()=>{let t=y();if(!t?.refresh_token&&!w(t)){te()===`end`&&s?.(`emptied`);return}ee();let n=i(),r=Z(t);n&&r&&n!==r?s?.(`identity-changed`):e.onStoredSessionSeen?.()},se=!!s||!!e.onStoredSessionSeen,ce=se&&e.onStorageChange?e.onStorageChange(oe):void 0,j=se&&e.onWake?e.onWake(oe):void 0,le=()=>{let e=y();if(w(e))return`held`;if(!e?.refresh_token){if(te()===`end`)throw new Xi(`emptied`);return`held`}let t=n.getTokens();if(e.refresh_token===t?.refresh_token)return`send`;let r=i()??Z(t),a=Z(e);if(r&&a&&r!==a)throw new Zi;let s=X(e.refresh_token);if(o.isEnded(s)){if(s&&C(s))return`held`;throw new Xi(`ended`)}let c=X(t?.refresh_token);return ie(s,c)?(ae(e),`adopted`):s&&c&&s.sid!==c.sid?`send`:s&&ne(s)?`held`:`send`},ue=e=>{let t=i(),r=Qi(e);if(t&&r&&t!==r)return{kind:`identity-changed`};let a=X(e)??{fp:e};if(o.isEnded(a))return C(a)?{kind:`superseded`}:{kind:`ended`};if(o.isRetired(a)&&ne(a))return{kind:`superseded`};let s={refreshToken:e,order:a},c=t??r??Qi(n.getTokens()?.access_token);return c!==void 0&&(s.sub=c),v&&v.fp===a.fp&&(s.held={cachedFp:v.cachedFp}),{kind:`send`,sent:s}},M=(e,r)=>{if(o.isEnded(e.order))return A(e.order);let i=k(e);if(i)return i;if(!O(e)&&re(e.order))return o.retire(e.order),a(`[passflow] Refused to save a late refresh result: it rotated ${e.order.fp} into ${Ki(r.refresh_token)??`(no refresh token)`}, but this tab already holds ${b()?.fp??`(none)`}, a later successor of ${e.order.fp}. Neither saved nor adopted.`),{kind:`superseded`,adopted:!1};let s=Z(r);if(e.sub&&s&&s!==e.sub)return t.saveTokens(r),{kind:`identity-changed`,saved:!0};let c=X(r.refresh_token);return c&&($i(c,e.order)||$i(c,b()))?(a(`[passflow] Refused to save a refresh result older than the token this tab holds: ${e.order.fp} was answered with ${c.fp}. Neither saved nor adopted.`),{kind:`superseded`,adopted:!1}):(o.retire(e.order),t.saveTokens(r),n.setTokensCache(r),{kind:`saved`})},N=(e,t)=>{if(o.isEnded(e.order))return A(e.order);let n=k(e);if(n)return n.kind===`identity-changed`?{kind:`identity-changed`}:n;if(o.isRetired(e.order)&&ne(e.order))return{kind:`superseded`,adopted:!1};let r=Ii(t),i=r.kind===`blocked`||r.kind===`auth`;return O(e)&&i?(o.retire(e.order),_=e.order,{kind:`own`,failure:r,heldRefused:!0}):(r.kind===`blocked`&&(o.retire(e.order),_=e.order),{kind:`own`,failure:r,heldRefused:!1})},P=e=>{if(!ea(e))return!1;let{from:t,fromIat:r,fromSid:a,to:c,tokens:l}=e;if(typeof t!=`string`||typeof c!=`string`||!ea(l))return!1;let u=l;if(typeof u.access_token!=`string`||u.access_token===``||typeof u.refresh_token!=`string`||u.refresh_token===``||Ki(u.refresh_token)!==c)return!1;let d=y();if(!d?.refresh_token)return!1;let f=n.getTokens(),p=i()??Z(f),m=Z(u);if(p&&m&&p!==m)return s?.(`identity-changed`),!1;let h=X(u.refresh_token),g=X(f?.refresh_token);g&&g.fp===t&&o.retire(g);let _=()=>{if(t!==c&&typeof r==`number`&&Number.isFinite(r)&&typeof a==`string`){let e={fp:t,iat:r};h?.sub!==void 0&&(e.sub=h.sub),a!==``&&(e.sid=a),o.retire(e)}return!0};return g?.fp===c?_():!o.isForward(h,g)||g?.fp!==t&&Ki(d.refresh_token)!==c?!1:(ae({...u}),_())},F=e=>{if(!e||!_)return!1;let t=_;return e.fp===t.fp||o.isEnded(e)||o.isRetired(e)?!1:e.iat!==void 0&&t.iat!==void 0&&e.sid!==t.sid||o.isAfter(e,t)},I=()=>{let e=b();if(!e)return!1;if(F(e))return!0;let t=y(),r=X(t?.refresh_token);if(!t||!r||r.fp===e.fp||!F(r)||!ie(r,e))return!1;let a=i()??Z(n.getTokens()),o=Z(t);return a&&o&&a!==o?(s?.(`identity-changed`),!1):(ae(t),!0)},de=e=>{let t=X(e?.refresh_token),n={},r=i()??Z(e);return t?.fp!==void 0&&(n.fp=t.fp),r!==void 0&&(n.sub=r),t?.sid!==void 0&&(n.sid=t.sid),t?.iat!==void 0&&(n.iat=t.iat),n};return{lineage:o,checkStoredBeforeSend:le,beginSend:ue,commitSave:M,judgeFailure:N,adoptTokens:P,adoptSuccessor:I,beginHeldSend:()=>{let e=X(y()?.refresh_token);if(!e||o.isRetired(e)||o.isEnded(e))return v=void 0,!1;let t=b()?.fp;return v=t===void 0?{fp:e.fp}:{fp:e.fp,cachedFp:t},!0},endHeldSend:()=>{v=void 0},endLineage:e=>o.end(e),endedElsewhere:(e,t)=>{let n=!y()?.refresh_token;l+=1,e===`signed-out`?(d.push(t.sub===void 0?{seq:l}:{sub:t.sub,seq:l}),d.length>4&&d.shift()):t.fp&&(u.push({...t,fp:t.fp,seq:l}),u.length>4&&u.shift()),b()&&n&&te()===`end`&&s?.(`emptied`)},session:()=>de(n.getTokens()),storedSession:()=>de(y()),dropSession:()=>{n.setTokensCache(void 0),n.stopTokenCheck?.()},deleteIfStillDead:e=>{let n=X(y()?.refresh_token);if(!n)return!1;let r=n.sid===e.sid&&(!n.sub||!e.sub||n.sub===e.sub);return n.fp===e.fp||r&&n.iat!==void 0&&e.iat!==void 0&&n.iat<e.iat?(t.deleteTokens(),!0):!1},stop:()=>{ce?.(),j?.(),ee()}}}function na(){let e,t,n=new Promise((n,r)=>{e=n,t=r});return n.catch(()=>void 0),{promise:n,resolve:e,reject:t}}var ra={strikes:J.sessionEnded,"session-ended":J.sessionEnded,"stored-ended":J.sessionEnded,"signed-out":J.signedOut,emptied:J.signedOut,"signed-out-here":J.signedOut,"successor-timeout":J.successorTimeout,"identity-changed":J.identityChanged,disposed:J.disposed};function ia(e){throw Error(`Unexpected refresh state: ${JSON.stringify(e)}`)}function aa(e){if(e===void 0||!Number.isFinite(e))return 3;let t=Math.floor(e);return t>=1?t:3}function oa(e,t){return e instanceof Error&&e.message?e.message:t}function sa(e){if(typeof e!=`object`||!e)return;let t=e.id;return typeof t==`string`||typeof t==`number`?t:void 0}function ca(e){let t={};return e?.access_token&&(t.access_token=e.access_token),e?.refresh_token&&(t.refresh_token=e.refresh_token),e?.id_token&&(t.id_token=e.id_token),e?.scopes&&(t.scopes=[...e.scopes]),t}function la(e,t){let n={};e.access_token&&(n.access_token=e.access_token),e.refresh_token&&(n.refresh_token=e.refresh_token),e.id_token&&(n.id_token=e.id_token);let r=t?.scopes??e.scopes;return r&&(n.scopes=r),n}function ua(e){let{emit:t,storage:n,cache:r,transport:i,coordination:a}=e,o=a.clock,s=e.logger??zi(),c=aa(e.strikes),l=a.transports?Vi({locks:a.transports.locks,channel:a.transports.channel,tabId:a.transports.tabId,names:a.names,clock:o}):Hi(),u={kind:`idle`},d=0,f=!1,p=!a.warnOnFirstCycle,m=0,h=0,g,_,v,y,b,x,S,C,w=!1,T=()=>o.now(),E=()=>i.mode(),D=()=>Ki(r.getTokens()?.refresh_token),ee=()=>({...r.getTokens()??{}}),te=()=>i.opaqueMarker?i.opaqueMarker():n.getTokens()?.id_token,O=()=>(S===void 0&&(S=Z(r.getTokens()??n.getTokens())),S),ne=new Set,re=new Set,ie=e=>()=>{for(let t of Array.from(e))t()},ae=a.onStorageChange?.(ie(ne)),k=e.platform?.onForeground(ie(re)),A=ta({storage:n,cache:r,identity:O,schedule:(e,t)=>o.setTimeout(e,t),onStorageChange:e=>(ne.add(e),()=>ne.delete(e)),onWake:e=>(re.add(e),()=>re.delete(e)),onSessionLost:e=>pe(e),onStoredSessionSeen:()=>{u.kind===`blocked-wait`&&Ae()},warn:e=>s.warn(e)}),oe=e=>({trigger:e,startedAt:T(),plain:na(),fresh:[]}),se=e=>e.kind===`idle`||e.kind===`ended`?void 0:e.pending,ce=(e,t)=>{if(t===void 0)return e.plain.promise;let n={callTime:t,deferred:na()};return e.fresh.push(n),n.deferred.promise},j=(e,t,n=!1)=>{e.plain.resolve(ee());for(let r of e.fresh)n||t!==void 0&&t>=r.callTime?r.deferred.resolve(ee()):ze(`refresh-token`,r.callTime).then(r.deferred.resolve,r.deferred.reject);e.fresh=[]},le=(e,t,n)=>{e.plain.reject(t);for(let r of e.fresh)n!==void 0&&n<r.callTime?ze(`refresh-token`,r.callTime).then(r.deferred.resolve,r.deferred.reject):r.deferred.reject(t);e.fresh=[]},ue=(e,t)=>{if(e){e.plain.reject(t);for(let n of e.fresh)n.deferred.reject(t);e.fresh=[]}},M=(e,n,r,i)=>{let a={message:oa(r,`Token refresh failed`),originalError:r,operation:e,source:n},o=sa(r);o!==void 0&&(a.code=o),i&&(a.refresh=i),t(`error`,a)},N=(e,t)=>{let n={classification:e,willRetry:t!==void 0,strikes:h,maxStrikes:c};return t!==void 0&&(n.nextRetryAt=t),n},P=(e,n)=>{if(u.kind===`refreshing`&&(u.request.outcome=!0),m=0,h=0,g=void 0,v=void 0,l.setRetryInfo(void 0),r.tokenExpiredFlag!==void 0&&(r.tokenExpiredFlag=!1),r.startTokenCheck?.(),t(`refresh`,{tokens:r.getTokens(),source:e}),t(`token-cache-expired`,{isExpired:!1}),_){let{since:e}=_;_=void 0,t(`refresh:recovered`,{since:e,origin:n})}},F=(e,n,r)=>{if(_)return;_={since:e};let i={since:e,origin:r};n!==void 0&&(i.nextRetryAt=n),t(`refresh:failing`,i)},I=(e,t)=>{let n=r.getTokens(),i=Ki(n?.refresh_token);e.fp&&i&&l.post({type:`tokens-refreshed`,tokens:ca(n),from:e.fp,...e.iat===void 0?{}:{fromIat:e.iat},fromSid:e.sid??``,to:i,...t===void 0?{}:{sentAt:t}})},de=()=>{p||(p=!0,s.warn(bi))},fe=e=>{(e.kind===`backoff`||e.kind===`blocked-wait`)&&e.cancel()},L=(e,n)=>{if(u.kind===`ended`)return;let r=se(u);fe(u);let a=A.session(),o=O();switch(d+=1,m=0,h=0,g=void 0,_=void 0,v=void 0,l.setRetryInfo(void 0),w||l.release(),b={...a,cause:e},e!==`disposed`&&A.dropSession(),(e===`strikes`||e===`successor-timeout`)&&E()!==`json`&&i.invalidate(),u={kind:`ended`,cause:e},ue(r,n??new Y(ra[e])),e){case`strikes`:t(`session:expired`,{reason:`refresh_failed`,origin:`this-tab`});break;case`session-ended`:case`stored-ended`:t(`session:expired`,{reason:`refresh_failed`,origin:`other-tab`});break;case`signed-out`:case`emptied`:t(`signout`,o===void 0?{origin:`other-tab`}:{origin:`other-tab`,userId:o});break;case`successor-timeout`:t(`session:expired`,{reason:`successor_timeout`,origin:`this-tab`});break;case`identity-changed`:t(`session:expired`,{reason:`identity_changed`,origin:`this-tab`});break;case`signed-out-here`:case`disposed`:break;default:ia(e)}},R=()=>{if(u.kind!==`ended`||u.cause===`disposed`||f||E()!==`json`)return;let e=n.getTokens(),i=X(e?.refresh_token);if(!e?.refresh_token||!e.access_token||!i||A.lineage.isEnded(i)||A.lineage.isRetired(i))return;let a=b,o=Z(e);if(a&&a.cause!==`successor-timeout`&&(!a.sub||!o||a.sub===o)&&i.sid===a.sid)return;d+=1,m=0,h=0,g=void 0,_=void 0,v=void 0,b=void 0,S=o;let s={...e};r.setTokensCache(s),r.tokenExpiredFlag!==void 0&&(r.tokenExpiredFlag=!1),r.startTokenCheck?.(),u={kind:`idle`},t(`signin`,{tokens:s,origin:`other-tab`})},pe=e=>{u.kind===`ended`||f||E()===`json`&&(L(e===`emptied`?`emptied`:`identity-changed`),e===`identity-changed`&&R())},me=e=>{e instanceof Zi?(L(`identity-changed`),R()):e instanceof Xi?L(e.cause===`emptied`?`emptied`:`stored-ended`):L(`stored-ended`,e)},he=()=>{u={kind:`idle`},w||l.release()},ge=e=>!e.from||E()!==`json`||e.from===D()||e.from===Ki(n.getTokens()?.refresh_token),_e=e=>{let t=g;if(!t)return;if(!l.holding){u={kind:`waiting`,pending:e},l.request(t.nextAt+K);return}l.setRetryInfo(t);let n=d,r=t.nextAt;u={kind:`backoff`,pending:e,dueAt:r,cancel:o.setTimeout(()=>{n===d&&ve()},Math.max(0,r-T()))}},ve=()=>{if(u.kind!==`backoff`||w)return;let{pending:e,dueAt:t}=u;!l.holding||l.foreignHolderHeard()||T()-t>2e4?(l.release(),u={kind:`waiting`,pending:e},l.request((g?.nextAt??T())+K)):(u={kind:`waiting`,pending:e},be()||ye())},ye=()=>{u.kind===`idle`&&l.release()},be=()=>{if(u.kind!==`waiting`)return!1;let e=u.pending;if(E()!==`json`)return xe(e);let t=A.session(),n;try{n=A.checkStoredBeforeSend()}catch(e){return me(e),!1}if(n===`held`){let t=D();return!v||v.fp!==t||T()-v.at<2e4?(v&&v.fp===t||(v={fp:t,at:T()}),u={kind:`idle`},j(e,void 0,!0),!1):(v={fp:t,at:T()},A.beginHeldSend()?Se(e,`held`):(u={kind:`idle`},j(e,void 0,!0),!1))}if(v=void 0,n===`adopted`){if(P(`adopted`,`other-tab`),I(t),e.fresh.length===0)return u={kind:`idle`},j(e,void 0),!1;e.plain.resolve(ee())}return g&&!ge(g)&&(g=void 0),g&&g.nextAt>T()?(m=g.attempt,h=g.strikes,g.failingSince!==void 0&&F(g.failingSince,g.nextAt,`other-tab`),_e(e),!0):(g&&(m=g.attempt,h=g.strikes),Se(e,e.trigger===`held`?`refresh-token`:e.trigger))},xe=e=>y!==void 0&&y>=e.startedAt?(r.setTokensCache(n.getTokens()),P(`adopted`,`other-tab`),u={kind:`idle`},j(e,y),!1):g&&g.nextAt>T()?(m=g.attempt,h=g.strikes,_e(e),!0):Ce(e,e.trigger,void 0,void 0),Se=(e,t)=>{let r=n.getTokens(),i=r?.refresh_token;if(!i)return u={kind:`idle`},j(e,void 0,!0),!1;let a=A.beginSend(i);switch(a.kind){case`superseded`:return A.endHeldSend(),P(`adopted`,`other-tab`),u={kind:`idle`},j(e,void 0),!1;case`ended`:return A.endHeldSend(),L(`stored-ended`),!1;case`identity-changed`:return A.endHeldSend(),L(`identity-changed`),R(),!1;case`send`:return Ce(e,t,a.sent,r);default:return ia(a)}},Ce=(e,n,r,a)=>{let o={generation:d,sentAt:T(),trigger:n,settled:na()};r?o.sent=r:o.marker=te(),a&&(o.stored=a),u={kind:`refreshing`,pending:e,request:o},l.setRetryInfo(g),t(`refresh:start`,{});let c;try{c=i.send(a?{tokens:a}:{})}catch(e){c=Promise.reject(e)}return c.then(e=>{Te(o,e).catch(e=>s.error(`[passflow] Applying a refresh result failed`,e)).finally(()=>o.settled.resolve())},e=>{Ee(o,e),o.settled.resolve()}),!0},we=e=>!f&&e.generation===d&&u.kind===`refreshing`&&u.request===e,Te=async(e,t)=>{if(e.sent?.held&&A.endHeldSend(),!we(e)||u.kind!==`refreshing`)return;let{pending:a}=u;if(!e.sent){let o=Z({...t.id_token?{id_token:t.id_token}:{}}),s=O();if(o!==void 0&&s!==void 0&&o!==s){let t=new Y(J.identityChanged);M(`refresh`,e.trigger,t,N(`auth`)),L(`identity-changed`,t);return}try{await i.applyOpaque(t)}catch(t){Ee(e,t);return}if(!we(e))return;r.setTokensCache({...n.getTokens()??{},...la(t,void 0)}),P(`refresh`,`this-tab`);let c=O();l.post(c===void 0?{type:`session-refreshed`,at:T()}:{type:`session-refreshed`,at:T(),sub:c}),he(),j(a,e.sentAt);return}let o=D(),s=A.commitSave(e.sent,la(t,e.stored));switch(s.kind){case`saved`:P(`refresh`,`this-tab`),I(e.sent.order,e.sentAt),he(),j(a,e.sentAt);return;case`superseded`:e.outcome&&D()===o||P(`adopted`,`other-tab`),s.adopted&&I(e.sent.order),he(),j(a,e.sentAt);return;case`ended`:{let t=new Y(s.cause===`emptied`?J.signedOut:J.sessionEnded);M(`refresh`,e.trigger,t,N(`auth`)),L(s.cause===`emptied`?`emptied`:`stored-ended`,t);return}case`identity-changed`:{let t=new Y(J.identityChanged);M(`refresh`,e.trigger,t,N(`auth`)),L(`identity-changed`,t),R();return}default:ia(s)}},Ee=(e,t)=>{if(e.sent?.held&&A.endHeldSend(),!we(e)||u.kind!==`refreshing`)return;let{pending:n}=u,r,i=!1;if(e.sent){let a=D(),o=A.judgeFailure(e.sent,t);switch(o.kind){case`superseded`:e.outcome&&D()===a||P(`adopted`,`other-tab`),he(),j(n,e.sentAt);return;case`ended`:M(`refresh`,e.trigger,t,N(`auth`)),L(o.cause===`emptied`?`emptied`:`stored-ended`,t);return;case`identity-changed`:M(`refresh`,e.trigger,t,N(`auth`)),L(`identity-changed`,t),R();return;case`own`:r=o.failure,i=o.heldRefused;break;default:ia(o)}}else r=Ii(t,T());if(i)M(`refresh`,e.trigger,t,N(r.kind)),P(`adopted`,`other-tab`),he(),j(n,void 0,!0);else switch(r.kind){case`blocked`:M(`refresh`,e.trigger,t,N(`blocked`)),ke(n,e.sentAt,t,e.marker);return;case`auth`:if(h+=1,m+=1,r.terminal||h>=c){M(`refresh`,e.trigger,t,N(`auth`)),Oe(e,t);return}De(e,n,t,r);return;case`transient`:m+=1,De(e,n,t,r);return;default:ia(r.kind)}},De=(e,t,n,r)=>{let i=T()+Li(m,o.random(),r.retryAfterMs),a=r.kind===`auth`?`auth`:`transient`;M(`refresh`,e.trigger,n,N(a,i)),a===`transient`&&F(T(),i,`this-tab`);let s={kind:a,attempt:m,nextAt:i,strikes:h},c=e.sent?.order.fp;c&&(s.from=c),_&&(s.failingSince=_.since),g=s,l.holding&&l.post({type:`retry-scheduled`,message:oa(n,`Token refresh failed`),retry:s}),_e(oe(`retry`)),le(t,n,e.sentAt)},Oe=(e,t)=>{let n=e.sent?.sub??O(),r=e.sent?.order,i={};r?.fp&&(i.fp=r.fp),n&&(i.sub=n),r?.sid&&(i.sid=r.sid),r?.iat!==void 0&&(i.iat=r.iat),(i.fp||i.sub)&&l.post({type:`session-ended`,...i}),i.fp&&(x=i.fp,A.endLineage({...i,fp:i.fp})),r&&A.deleteIfStillDead(r),L(`strikes`,t)},ke=(e,t,n,r)=>{l.release(),s.warn(`[passflow] The refresh token was already used, most likely by another tab; waiting for its successor: ${oa(n,`blocked`)}`);let i=d,a=T()+ai,c={kind:`blocked-wait`,pending:e,deadline:a,sentAt:t,cancel:()=>void 0,marker:r};if(u=c,Ae())return;let f=E()!==`json`&&!l.coordinated&&!e.cookieRetried,p=()=>{i===d&&u===c&&(Ae()||(f?(e.cookieRetried=!0,u={kind:`waiting`,pending:e},l.request()):T()>=a?(s.warn(`[passflow] No successor of the used refresh token appeared; ending the session in this tab only.`),L(`successor-timeout`)):c.cancel=o.setTimeout(p,oi)))};c.cancel=o.setTimeout(p,f?ci:oi)},Ae=()=>{if(u.kind!==`blocked-wait`)return!1;let e=u;if(E()===`json`){if(!A.adoptSuccessor())return!1}else{let t=y!==void 0&&y>=e.sentAt,i=te(),a=!l.coordinated&&i!==void 0&&i!==e.marker;if(!t&&!a)return!1;r.setTokensCache(n.getTokens())}return u===e&&(e.cancel(),P(`adopted`,`other-tab`),u={kind:`idle`},j(e.pending,void 0,!0),!0)},je=e=>{let t=O(),n=!e.sub||!t||e.sub===t;return E()===`json`?!!e.fp&&e.fp===D()&&n:!e.fp&&n},Me=(e,t)=>{if(e!==`signed-out`||!t.sub)return!1;let n=O();return n!==void 0&&t.sub===n},Ne=(e,t,n)=>{if(u.kind===`ended`||!ge(e))return;let r=g?.nextAt;if(g=e,e.failingSince!==void 0&&F(e.failingSince,e.nextAt,`other-tab`),!t||u.kind!==`waiting`)return;let i=new Y(e.kind===`transient`?J.unavailable:J.authRetry,{nextRetryAt:e.nextAt,cause:n||void 0}),a=u.pending;u.pending=oe(a.trigger),le(a,i,r)},Pe=(e,t)=>{switch(t&&P(`adopted`,`other-tab`),u.kind){case`waiting`:case`backoff`:{let t=u.pending;fe(u),he(),j(t,e);return}case`blocked-wait`:{let e=u.pending;u.cancel(),u={kind:`idle`},j(e,void 0,!0);return}case`idle`:case`refreshing`:case`ended`:return;default:ia(u)}},Fe=e=>{let t={};e.fp&&(t.fp=e.fp),e.sub&&(t.sub=e.sub),e.sid&&(t.sid=e.sid),e.iat!==void 0&&(t.iat=e.iat);let n=u.kind!==`ended`&&(je(t)||Me(e.type,t));t.fp&&A.endLineage({...t,fp:t.fp}),n&&L(e.type===`signed-out`?`signed-out`:`session-ended`),A.endedElsewhere(e.type,t)},Ie=e=>{if(!f)switch(e.type){case`tokens-refreshed`:{if(u.kind===`ended`){R();return}if(E()!==`json`)return;let t=D();if(!A.adoptTokens(e))return;let n=D()!==t;if(!n&&u.kind===`idle`)return;g=void 0,Pe(e.sentAt,n);return}case`session-refreshed`:{if(E()===`json`||u.kind===`ended`)return;let t=O();if(e.sub&&t&&e.sub!==t||(y=Math.max(y??0,e.at),u.kind===`refreshing`))return;if(r.setTokensCache(n.getTokens()),g=void 0,u.kind===`blocked-wait`){Ae();return}Pe(e.at,!0);return}case`still-refreshing`:e.retry&&Ne(e.retry,!1,``),Le();return;case`retry-scheduled`:Ne(e.retry,!0,e.message),Le();return;case`refresh-failed`:if(u.kind===`ended`||E()!==`json`||e.from!==D()&&e.from!==Ki(n.getTokens()?.refresh_token))return;if(F(T(),void 0,`other-tab`),u.kind===`waiting`){let t=u.pending;u.pending=oe(t.trigger),le(t,new Y(J.unavailable,{cause:e.message}),void 0)}return;case`lock-wanted`:if(u.kind===`backoff`&&l.holding&&!w){let e=u.pending;u.cancel(),l.release(),u={kind:`waiting`,pending:e},l.request((g?.nextAt??T())+K)}return;case`session-ended`:case`signed-out`:Fe(e);return;case`takeover`:case`rate-limited`:return;default:ia(e)}},Le=()=>{C&&!l.holding&&l.post({type:`lock-wanted`,purpose:C.purpose})};l.attach({onGranted:()=>{if(f)return!1;if(C){let e=C;return C=void 0,e.granted(),!0}return u.kind===`waiting`&&be()},onLockLost:()=>{if(u.kind===`backoff`){let e=u.pending;u.cancel(),u={kind:`waiting`,pending:e},l.request((g?.nextAt??T())+K)}},onMessage:Ie});let Re=()=>{if(f)return;if(u.kind===`ended`){R();return}if(u.kind===`blocked-wait`&&E()!==`json`){Ae();return}if(u.kind!==`idle`||E()!==`json`||w)return;let e=A.session();try{if(A.checkStoredBeforeSend()!==`adopted`)return}catch{return}P(`adopted`,`other-tab`),l.coordinated&&I(e)};ne.add(Re),re.add(Re);let ze=(e,t)=>{if(f)return Promise.reject(new Y(J.disposed));switch(u.kind){case`ended`:return Promise.reject(new Y(J.sessionEnded));case`idle`:{let n=oe(e);u={kind:`waiting`,pending:n};let r=ce(n,t);return l.holding&&!w?be()||ye():l.request(g?g.nextAt+K:void 0),r}case`waiting`:case`refreshing`:case`backoff`:case`blocked-wait`:return ce(u.pending,t);default:return ia(u)}},Be=e=>{if(f)return Promise.reject(new Y(J.disposed));if(de(),u.kind===`ended`)return Promise.reject(new Y(J.sessionEnded));if(E()===`json`&&!r.getTokens()?.refresh_token){let t=n.getTokens();if(!t?.refresh_token){let n=Error(t?`No refresh token found`:`No tokens found`);return M(`refresh`,e.trigger,n),Promise.reject(n)}}return ze(e.trigger,e.fresh?T():void 0)},Ve=e=>{if(f)return Promise.reject(new Y(J.disposed));if(u.kind===`ended`)return Promise.resolve(r.getTokens());let t=u.kind===`backoff`||u.kind===`blocked-wait`||g!==void 0&&g.nextAt>T();return e.allowStale&&t?Promise.resolve(r.getTokens()):Be({trigger:e.trigger}).then(()=>r.getTokens())},He=(e,t)=>l.holding?Promise.resolve(`granted`):new Promise(n=>{let r=()=>void 0,i={purpose:e,granted:()=>{r(),n(`granted`)}};C=i,l.post({type:`lock-wanted`,purpose:e}),l.request(),r=o.setTimeout(()=>{C===i&&(C=void 0,u.kind!==`waiting`&&l.release(),n(`timeout`))},Math.max(0,t))}),Ue=async e=>{if(u.kind!==`refreshing`)return;let t=u.request.settled.promise;await new Promise(n=>{let r=o.setTimeout(n,Math.max(0,e));t.then(()=>{r(),n()})})},We=()=>{if(w=!1,!f&&l.holding){if(u.kind===`waiting`)be()||ye();else if(u.kind===`backoff`){let e=u.pending;u.cancel(),_e(e)}else u.kind===`idle`&&g&&g.nextAt>T()&&ge(g)?(m=g.attempt,h=g.strikes,_e(oe(`retry`))):u.kind===`idle`&&l.release()}},Ge=async(e,t)=>{if(f)throw new Y(J.disposed);de();let n=T()+li;if(await Ue(n-T()),(!l.holding||u.kind===`refreshing`)&&(u.kind===`refreshing`?`timeout`:await He(`commit`,n-T()))===`timeout`){let e=new Gi(`lock-timeout`);throw M(`upgrade.commit`,`upgrade`,e),e}w=!0;try{return await z(e,t)}finally{We()}},z=async(e,a)=>{let o,s;if(E()===`json`){let e=A.session();try{A.checkStoredBeforeSend()===`adopted`&&(P(`adopted`,`other-tab`),I(e))}catch{}s=n.getTokens();let t=s?.refresh_token;if(!t){let e=Error(s?`No refresh token found`:`No tokens found`);throw M(`upgrade.commit`,`upgrade`,e),e}let r=A.beginSend(t);o=r.kind===`send`?r.sent:{refreshToken:t,order:X(t)??{fp:t}}}let c=T(),u=d;t(`refresh:start`,{});let f;try{f=await i.send(s?{tokens:s,upgrade:e}:{upgrade:e})}catch(e){throw o&&A.judgeFailure(o,e),M(`upgrade.commit`,`upgrade`,e),e}try{i.assertPin(a)}catch(e){throw M(`upgrade.commit`,`upgrade`,e),e}if(!o){if(u!==d){let e=new Gi(`superseded`);throw M(`upgrade.commit`,`upgrade`,e),e}await i.applyOpaque(f),r.setTokensCache({...n.getTokens()??{},...la(f,void 0)}),Ke(c);let e=O();return l.post(e===void 0?{type:`session-refreshed`,at:T()}:{type:`session-refreshed`,at:T(),sub:e}),ee()}let p=A.commitSave(o,la(f,s));if(p.kind===`saved`)return Ke(c),I(o.order,c),ee();let m=new Gi(`superseded`);throw M(`upgrade.commit`,`upgrade`,m),p.kind===`superseded`&&p.adopted&&P(`adopted`,`other-tab`),m},Ke=e=>{if(P(`upgrade`,`this-tab`),u.kind===`waiting`||u.kind===`backoff`||u.kind===`blocked-wait`){let t=u.pending;fe(u),u={kind:`idle`},j(t,e)}},qe=()=>{let e=A.storedSession(),t=e.fp?e:A.session();(E()===`json`?!t.fp:!t.sub)||t.fp&&t.fp===x||(l.post({type:`signed-out`,...t}),t.fp&&A.endLineage({...t,fp:t.fp}))},Je=()=>{let e=se(u);ue(e,new Y(J.signedOut)),(u.kind===`backoff`||u.kind===`blocked-wait`||u.kind===`waiting`)&&(fe(u),u={kind:`idle`})};return{refresh:Be,ensureFresh:Ve,commitUpgrade:Ge,signOut:async e=>{if(f)return e(n.getTokens()?.refresh_token);let t=T()+ui;Je(),await Ue(t-T()),Je(),l.coordinated&&!l.holding&&await He(`logout`,t-T());try{qe(),await e(n.getTokens()?.refresh_token)}finally{u.kind!==`ended`&&L(`signed-out-here`),x=void 0,l.release()}},signOutNow:e=>{if(f)return e(n.getTokens()?.refresh_token);Je();try{qe(),e(n.getTokens()?.refresh_token)}finally{u.kind!==`ended`&&L(`signed-out-here`),x=void 0}},sessionStarted:()=>{if(f)return;let e=se(u);fe(u),d+=1,m=0,h=0,g=void 0,_=void 0,v=void 0,b=void 0,x=void 0,S=void 0,l.setRetryInfo(void 0),u={kind:`idle`},w||l.release(),e&&j(e,void 0,!0)},identity:O,get generation(){return d},get coordinated(){return l.coordinated},get busy(){return u.kind!==`idle`&&u.kind!==`ended`},get ended(){return u.kind===`ended`},dispose:()=>{if(f)return;let e=se(u);fe(u),f=!0,d+=1,u={kind:`ended`,cause:`disposed`},ue(e,new Y(J.disposed)),C=void 0,A.stop(),l.dispose(),ae?.(),k?.()}}}var da={ES256:{kty:`EC`,key:e=>({kty:e.kty,crv:e.crv,x:e.x,y:e.y}),imported:{name:`ECDSA`,namedCurve:`P-256`},signature:{name:`ECDSA`,hash:`SHA-256`}},RS256:{kty:`RSA`,key:e=>({kty:e.kty,n:e.n,e:e.e}),imported:{name:`RSASSA-PKCS1-v1_5`,hash:`SHA-256`},signature:{name:`RSASSA-PKCS1-v1_5`}}},fa=e=>{let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=globalThis.atob(t+`=`.repeat((4-t.length%4)%4));return Uint8Array.from(n,e=>e.charCodeAt(0))},pa=()=>{let e=globalThis.crypto;if(!e?.subtle)throw Error(`Verifying tokens needs the Web Crypto API, available only in a secure context (https or localhost)`);return e};async function ma(e,t,n,r,i){let[a=``,o=``,s=``]=e.split(`.`),c=JSON.parse(new TextDecoder().decode(fa(a))),l=c.alg===`ES256`||c.alg===`RS256`?da[c.alg]:void 0;if(!l)throw Error(`Token signing algorithm ${String(c.alg)} is not accepted`);let u=t.find(e=>e.kid===c.kid&&e.kty===l.kty&&(e.kty!==`EC`||e.crv===`P-256`));if(!u)throw Error(`Token signing key is not published by the server`);let d=pa().subtle,f=await d.importKey(`jwk`,l.key(u),l.imported,!1,[`verify`]),p=new TextEncoder().encode(`${a}.${o}`);if(!await d.verify(l.signature,f,fa(s),p))throw Error(`Token signature is not valid`);let m=P(e),h=Array.isArray(m.aud)?m.aud:[m.aud];if(m.iss!==n)throw Error(`Token issuer does not match the server`);if(!h.includes(r))throw Error(`Token is not issued for this app`);if(typeof m.exp!=`number`||N(m,0))throw Error(`Token has expired`);if(i&&m.type!==i)throw Error(`Token type is not valid`)}async function ha(e,t,n){if(!t)throw Error(`An app id is required to accept tokens from the URL`);if(!n.access_token)throw Error(`No access token received`);pa();let r=e.replace(/\/+$/,``),[i,a]=await Promise.all([c.default.get(`${r}/.well-known/openid-configuration`),c.default.get(`${r}/.well-known/jwks.json`)]),o=i.data?.issuer,s=a.data?.keys??[];if(!o)throw Error(`The server did not publish an issuer`);await ma(n.access_token,s,o,t,F.access_token),n.refresh_token&&await ma(n.refresh_token,s,o,t,F.refresh_token),n.id_token&&await ma(n.id_token,s,o,t)}var Q={twoFactorCodeInvalid:`error.api.request.2fa_code.invalid`,challengeInvalid:`error.upgrade.challenge_invalid`,challengeSessionMismatch:`error.upgrade.challenge_session_mismatch`,challengeTooManyAttempts:`error.upgrade.challenge_too_many_attempts`,unsupportedFactor:`error.upgrade.unsupported_factor`,noSession:`error.upgrade.no_session`,unavailable:`error.upgrade.unavailable`,methodNotRegistered:`error.upgrade.method_not_registered`,prepareNotRequired:`error.upgrade.prepare_not_required`,methodNotSupported:`error.2fa.method_not_supported`,twoFactorNotEnabled:`error.2fa.not_enabled`,notImplemented:`error.not.implemented`,tokenInvalid:`error.api.request.token.invalid`,grantPredatesCredentialReset:`error.grant.predates_credential_reset`,tokenAccessEnded:`error.token.access_ended`,userNotFound:`error.user.not_found`},ga=Object.freeze([Q.twoFactorCodeInvalid,Q.twoFactorNotEnabled,Q.challengeInvalid,Q.challengeSessionMismatch,Q.challengeTooManyAttempts]),_a=Object.freeze([Q.tokenInvalid,Q.grantPredatesCredentialReset,Q.tokenAccessEnded,Q.userNotFound]),va=Object.freeze([`wrong_code`,`challenge_spent`,`not_registered`,`prepare_not_required`]),ya=e=>va.includes(e),ba={wrong_code:`That code was not accepted. Try again.`,challenge_spent:`That verification challenge is no longer valid. Start again.`,exhausted:`Too many attempts. Try again later.`,rate_limited:`Too many requests. Try again later.`,attempts_exhausted:`Too many incorrect attempts. Verification was not completed.`,not_registered:`That verification method is not set up for this account.`,prepare_not_required:`This verification method needs no preparation round.`,fatal:`This verification method cannot be used right now.`,unavailable:`Step-up verification is not available on this deployment.`,protocol:`The server returned an unexpected upgrade response.`,network:`The verification request did not reach the server.`,session_changed:`The session ended during verification.`},$=class extends Error{constructor(e){super(e.message||ba[e.kind]),this.name=`UpgradeTransportError`,this.code=`upgrade_transport`,this.kind=e.kind,this.status=e.status,this.errorId=e.errorId,e.retryAfter!==void 0&&(this.retryAfter=e.retryAfter),this.retryable=ya(e.kind),e.cause!==void 0&&(this.cause=e.cause)}},xa=Object.freeze([`upgrade_transport`,`upgrade_insufficient`,`upgrade_unavailable`,`upgrade_session_changed`,`upgrade_cancelled`,`upgrade_unsatisfiable`,`upgrade_sign_in_required`]),Sa=e=>typeof e==`object`&&!!e&&typeof e.code==`string`&&xa.includes(e.code),Ca=e=>e instanceof $||typeof e==`object`&&!!e&&e.code===`upgrade_transport`,wa=e=>{let t=e?.error,n=typeof t==`string`?t:t?.message;if(typeof n==`string`&&n&&!n.startsWith(`localized error:`))return n},Ta=e=>{if(!e||typeof e!=`object`)return;let t=e[`retry-after`];return typeof t==`string`&&/^\d+$/.test(t.trim())?Number(t.trim()):void 0},Ea=e=>{if(typeof e!=`object`||!e)return{hasResponse:!1,message:typeof e==`string`?e:void 0};let t=e,n=t.response,r=n?.data,i=typeof r?.error?.id==`string`?r.error.id:void 0;return{status:typeof t.status==`number`?t.status:typeof n?.status==`number`?n.status:void 0,errorId:typeof t.id==`string`?t.id:i,message:typeof t.message==`string`?t.message:void 0,hasResponse:n!==void 0||typeof t.status==`number`,serverText:wa(n?.data),retryAfter:Ta(n?.headers)}},Da=(e,t)=>{switch(e){case Q.twoFactorCodeInvalid:return`wrong_code`;case Q.challengeInvalid:case Q.challengeSessionMismatch:return`challenge_spent`;case Q.challengeTooManyAttempts:return`exhausted`;case Q.methodNotRegistered:return`not_registered`;case Q.twoFactorNotEnabled:return t===`refresh`?`session_changed`:`not_registered`;case Q.prepareNotRequired:return`prepare_not_required`;case Q.unavailable:case Q.notImplemented:return`unavailable`;case Q.unsupportedFactor:case Q.noSession:case Q.methodNotSupported:return`fatal`;case Q.tokenInvalid:return t===`refresh`?`session_changed`:`fatal`;case`error.service.unavailable`:return`network`;default:return}},Oa=(e,t)=>e===void 0?`network`:e===501?`unavailable`:e===400?`fatal`:e===429?`rate_limited`:e===401||e===403?t===`start`?`challenge_spent`:`session_changed`:e>=500?`network`:`fatal`,ka=(e,t)=>{if(e instanceof $)return e;let n=Ea(e);if(!n.hasResponse)return new $({kind:`network`,message:n.message,cause:e});let r=Da(n.errorId,t)??Oa(n.status,t);return r===`rate_limited`?new $({kind:r,message:n.serverText,status:n.status,errorId:n.errorId,retryAfter:n.retryAfter,cause:e}):new $({kind:r,message:n.message,status:n.status,errorId:n.errorId,cause:e})},Aa=e=>e.errorId!==void 0&&ga.includes(e.errorId),ja=e=>e.errorId!==void 0&&_a.includes(e.errorId),Ma=class extends Error{constructor(e,t,n){super(n??`The session was elevated, but this action requires a higher assurance level`),this.name=`UpgradeInsufficientError`,this.code=`upgrade_insufficient`,this.obtained=e,this.required=t}},Na=class extends Error{constructor(e=`Step-up verification is not available on this deployment`){super(e),this.name=`UpgradeUnavailableError`,this.code=`upgrade_unavailable`}},Pa=class extends Error{constructor(e=`The session changed during verification`){super(e),this.name=`UpgradeSessionChangedError`,this.code=`upgrade_session_changed`}},Fa=e=>{if(e&&typeof e.sub==`string`&&e.sub!==``)return typeof e.sid==`string`&&e.sid!==``?{sub:e.sub,sid:e.sid}:{sub:e.sub}},Ia=(e,t)=>!t||t.sub!==e.sub?!1:e.sid!==void 0&&t.sid!==void 0?e.sid===t.sid:!0;function La(e){if(!e||typeof e!=`string`)return!1;let t=e.split(`.`);if(t.length!==3)return!1;let n=/^[A-Za-z0-9_-]+$/;return t.every(e=>n.test(e)&&e.length>0)}function Ra(e){return e.replace(/<[^>]*>/g,``).substring(0,200)}function za(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return t.length!==0&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function Ba(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return/^\+[1-9]\d{1,14}$/.test(t)}function Va(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return t.length<3||t.length>30?!1:/^[a-zA-Z0-9_-]+$/.test(t)}function Ha(e,t=6){return!e||typeof e!=`string`?!1:(t===8?/^\d{8}$/:/^\d{6}$/).test(e)}function Ua(e){if(!e||typeof e!=`string`)return null;let t=e.toUpperCase().replace(/\s+/g,``);return t.length>64||!/^[A-Z0-9-]+$/.test(t)||t.replace(/-/g,``)===``?null:t}var Wa=e=>e?[e]:[],Ga=`passflow_2fa_pkce`,Ka=3e5,qa=`passflow_pwless_pending`,Ja=3e3,Ya=`passflow_federated_pkce`,Xa=6e5,Za=`AppId is required for federated auth`;function Qa(e){let t;try{t=new URL(e).protocol}catch{t=void 0}if(t!==`https:`&&t!==`http:`)throw Error(`The federated start returned an address that is not http or https`);return e}function $a(e){if(e)try{let{protocol:t}=new URL(e);return t===`https:`||t===`http:`?e:void 0}catch{return}}function eo(e){return e.provider?.startsWith(`conn_`)?e.login_hint:void 0}function to(e){let t={};return e.connection_id!==void 0&&(t.connection_id=e.connection_id),e.email!==void 0&&(t.email=e.email),t}var no=10,ro=`The sign-in answered with a PKCE code, but its verifier is gone`,io=(e,t)=>new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let i=()=>{clearTimeout(a),r(t?.reason)},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})}),ao=e=>{if(!e)return;let t=new URLSearchParams(e.search).get(`token`);if(t)return t;let n=e.hash.indexOf(`?`);return n<0?void 0:new URLSearchParams(e.hash.slice(n+1)).get(`token`)??void 0},oo=e=>{if(e)try{return P(e).email}catch{return}},so=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d=ye,f,p={coordination:Oi()},m){this.authApi=e,this.deviceService=t,this.storageManager=n,this.subscribeStore=r,this.tokenCacheService=i,this.scopes=a,this.createTenantForNewUser=o,this.url=s,this.sessionCallbacks=c,this.appId=l,this.platform=d,this.readPkceEnabled=f,this.readAppSettings=m,this.emailChallenges=new Map,this.tokenExchangeConfig=u,this.deviceKey=p.deviceKey,this.enrolDeviceKeyRequest=p.enrolDeviceKeyRequest,this.tokenDeliveryManager=new fe(n),this.setBffModeIfConfigured(),this.refresh=ua({emit:this.createRefreshEmit(),storage:n,cache:i,transport:this.createRefreshTransport(),coordination:p.coordination,platform:d,...p.strikes===void 0?{}:{strikes:p.strikes},logger:zi()}),this.initializeSession()}setAppId(e){let t=this.appId;e!==t&&(this.appId=e,this.tokenDeliveryManager.reload(),this.setBffModeIfConfigured(),t&&(this.refresh.sessionStarted(),this.initializeSession()))}setBffModeIfConfigured(){this.tokenExchangeConfig?.enabled&&this.tokenDeliveryManager.setMode(I.BFF)}async isSimpleModeApp(){try{return(await this.readAppSettings?.())?.pkce_enabled===!1}catch{return!1}}async initializeSession(){(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode())&&await this.restoreSession()}async restoreSession(){if(this.storageManager.holdsOnlyOtherAppSession())return!1;let e=this.refresh.generation,t=()=>this.refresh.generation!==e;if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.statusUrl)try{let e=await fetch(this.tokenExchangeConfig.statusUrl,{method:`GET`,credentials:`include`}),n=e.ok?await e.json():void 0;return t()?!1:e.ok&&n.authenticated?(this.tokenDeliveryManager.setSessionValid(),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return t()||this.tokenDeliveryManager.setSessionInvalid(),!1}if(!this.tokenDeliveryManager.isCookieMode())return!1;try{let e=await this.authApi.validateSession();return t()?!1:e?.id?(this.tokenDeliveryManager.setSessionValid(),this.subscribeStore.notify(G.SessionRestored,e),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return t()||this.tokenDeliveryManager.setSessionInvalid(),!1}}async processAuthResponse(e,t){await this.applyAuthResponse(e,t,{replace:!0}),this.refresh.sessionStarted()}async applyAuthResponse(e,t,n){if(e.code&&!e.access_token)throw Error(`A PKCE authorization code was not exchanged, so there are no tokens to apply`);if(this.issuedForAnotherApp(e))throw Error(`The tokens were issued for another app than the current app id, so they are not applied`);this.tokenExchangeConfig?.enabled||`token_delivery`in e&&e.token_delivery&&this.tokenDeliveryManager.setMode(e.token_delivery),this.tokenDeliveryManager.setSessionValid(),this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.callbackUrl&&await this.forwardTokensToBFF(e),e.scopes=t,this.storageManager.saveTokens(e,this.tokenDeliveryManager.getMode(),n),this.tokenCacheService.setTokensCache(e),e.csrf_token&&this.storageManager.setCsrfToken(e.csrf_token),this.deviceKey&&e.refresh_challenge&&this.storageManager.setRefreshChallenge(e.refresh_challenge)}issuedForAnotherApp(e){if(!this.appId)return!1;let t=e.id_token??e.access_token;if(!t)return!1;let n;try{n=P(t).aud}catch{return!1}return n!==void 0&&!(Array.isArray(n)?n:[n]).includes(this.appId)}notifyRegisteredAndSignedIn(e){let t={tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens()};this.subscribeStore.notify(G.Register,t),this.subscribeStore.notify(G.SignIn,t)}handlePendingSecondFactor(e,t,n,r){return e.tfa_token?(n?this.rememberPkceSignIn(n.verifier,r):this.forgetPkceSignIn(),this.subscribeStore.notify(G.TwoFactorRequired,{email:t||``,challengeId:e.challenge_id||``,tfaToken:e.tfa_token||``}),!0):!1}handleEmailVerificationStep(e,t,n,r,i){if(!Je(e))return!1;let a=e.challenge_id||void 0;return a&&r?this.rememberPkceSignIn(r.verifier,i):this.forgetPkceSignIn(),a&&this.rememberEmailChallenge(a,{operation:t,email:n,scopes:i,pkce:r!==void 0}),this.subscribeStore.notify(G.EmailVerificationRequired,{email:n,challengeId:a,operation:t}),!0}rememberEmailChallenge(e,t){this.emailChallenges.delete(e),this.emailChallenges.set(e,t);for(let e of this.emailChallenges.keys()){if(this.emailChallenges.size<=no)break;this.emailChallenges.delete(e)}}rememberPkceSignIn(e,t){if(this.pendingPkce={verifier:e,scopes:t,expiresAt:Date.now()+Ka},typeof sessionStorage<`u`)try{sessionStorage.setItem(Ga,JSON.stringify(this.pendingPkce))}catch{}}readPendingPkce(){if(!this.pendingPkce&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(Ga);this.pendingPkce=e?JSON.parse(e):void 0}catch{this.pendingPkce=void 0}return this.pendingPkce&&Date.now()>=this.pendingPkce.expiresAt&&this.forgetPkceSignIn(),this.pendingPkce}hasPendingPkceSignIn(){return this.readPendingPkce()!==void 0}forgetPkceSignIn(){if(this.pendingPkce=void 0,typeof sessionStorage<`u`)try{sessionStorage.removeItem(Ga)}catch{}}rememberPendingPasswordless(e){if(this.pendingPasswordless=e,typeof sessionStorage<`u`)try{sessionStorage.setItem(qa,JSON.stringify(e))}catch{}}readPendingPasswordless(){if(!this.pendingPasswordless&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(qa);this.pendingPasswordless=e?JSON.parse(e):void 0}catch{this.pendingPasswordless=void 0}return this.pendingPasswordless&&!(Date.now()<this.pendingPasswordless.expiresAt)&&this.forgetPendingPasswordless(),this.pendingPasswordless}forgetPendingPasswordless(){if(this.pendingPasswordless=void 0,typeof sessionStorage<`u`)try{sessionStorage.removeItem(qa)}catch{}}rememberFederatedSlot(e,t){if(this.federatedSlot={verifier:e,scopes:t,expiresAt:Date.now()+Xa},typeof sessionStorage<`u`)try{sessionStorage.setItem(Ya,JSON.stringify(this.federatedSlot))}catch{}}readFederatedSlot(){if(!this.federatedSlot&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(Ya);this.federatedSlot=e?JSON.parse(e):void 0}catch{this.federatedSlot=void 0}return this.federatedSlot&&Date.now()<this.federatedSlot.expiresAt?this.federatedSlot:void 0}forgetFederatedSlot(){if(this.federatedSlot=void 0,typeof sessionStorage<`u`)try{sessionStorage.removeItem(Ya)}catch{}}async startPkce(){let e=!1;try{e=await this.readPkceEnabled?.()??!1}catch(e){zi().warn(`Passflow: could not read the app settings, so this sign-in sends no PKCE challenge`,e);return}return e?gr():void 0}async exchangeCode(e,t){return!e.code||!t?e:await this.authApi.pkceExchange(e.code,t.verifier)}async completePkceSignIn(e){let t=this.readPendingPkce();if(!t)throw Error(ro);let n=await this.authApi.pkceExchange(e,t.verifier);return await this.processAuthResponse(n,t.scopes??this.scopes),n}async applyTokens(e){let t=e;(t.access_token||t.id_token||t.token_delivery)&&await this.processAuthResponse(t,t.scopes??this.readPendingPkce()?.scopes??this.scopes)}async notifySignedIn(e){this.subscribeStore.notify(G.SignIn,{tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()}async forwardTokensToBFF(e){if(!this.tokenExchangeConfig?.callbackUrl)return;let t=await fetch(this.tokenExchangeConfig.callbackUrl,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`},body:JSON.stringify({access_token:e.access_token,refresh_token:e.refresh_token,id_token:e.id_token,expires_in:e.expires_in})});if(!t.ok)throw Error(`BFF token storage failed: ${t.status}`)}async signIn(e,t){if(`email`in e&&e.email&&!za(e.email)){let e=Error(`Invalid email format`),t={operation:`sign-in`,message:`Invalid email format`,originalError:e,code:`VALIDATION_ERROR`};throw W(this.subscribeStore,t),e}if(`username`in e&&e.username&&!Va(e.username)){let e=Error(`Invalid username format. Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens`),t={operation:`sign-in`,message:`Invalid username format. Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens`,originalError:e,code:`VALIDATION_ERROR`};throw W(this.subscribeStore,t),e}if(`phone`in e&&e.phone&&!Ba(e.phone)){let e=Error(`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`),t={operation:`sign-in`,message:`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`,originalError:e,code:`VALIDATION_ERROR`};throw W(this.subscribeStore,t),e}this.subscribeStore.notify(G.SignInStart,{email:e.email});let n=this.deviceService.getDeviceId(),r=Ct(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes;try{let i=await this.startPkce(),a=i?{...e,code_challenge:i.challenge}:e,o=await this.signInProof(),s=o?await this.authApi.signIn(a,n,r,t,o):await this.authApi.signIn(a,n,r,...Wa(t));if(this.handleEmailVerificationStep(s,`sign-in`,e.email,i,e.scopes)||this.handlePendingSecondFactor(s,e.email,i,e.scopes))return s;let c=await this.exchangeCode(s,i);return this.handlePendingSecondFactor(c,e.email)||(await this.processAuthResponse(c,e.scopes),this.subscribeStore.notify(G.SignIn,{tokens:c,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),c}catch(e){let t={operation:`sign-in`,message:e instanceof Error?e.message:`Sign in failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async signUp(e,t){if(e.user.email&&!za(e.user.email)){let e=Error(`Invalid email format`),t={operation:`sign-up`,message:`Invalid email format`,originalError:e,code:`VALIDATION_ERROR`};throw W(this.subscribeStore,t),e}if(e.user.phone_number&&!Ba(e.user.phone_number)){let e=Error(`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`),t={operation:`sign-up`,message:`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`,originalError:e,code:`VALIDATION_ERROR`};throw W(this.subscribeStore,t),e}this.subscribeStore.notify(G.RegisterStart,{email:e.user.email}),e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{let n=await this.startPkce(),r=await this.authApi.signUp(n?{...e,code_challenge:n.challenge}:e,...Wa(t));if(this.handleEmailVerificationStep(r,`sign-up`,e.user.email,n,e.scopes)||this.handlePendingSecondFactor(r,e.user.email,n,e.scopes))return r;let i=await this.exchangeCode(r,n);return this.handlePendingSecondFactor(i,e.user.email)||(await this.processAuthResponse(i,e.scopes),this.notifyRegisteredAndSignedIn(i),await this.submitSessionCheck()),i}catch(e){let t={operation:`sign-up`,message:e instanceof Error?e.message:`Sign up failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async passwordlessSignIn(e,t){if(e.email&&!za(e.email)){let e=Error(`Invalid email format`),t={operation:`passwordless.start`,message:`Invalid email format`,originalError:e,code:`VALIDATION_ERROR`};throw W(this.subscribeStore,t),e}if(e.phone&&!Ba(e.phone)){let e=Error(`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`),t={operation:`passwordless.start`,message:`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`,originalError:e,code:`VALIDATION_ERROR`};throw W(this.subscribeStore,t),e}this.subscribeStore.notify(G.SignInStart,{email:e.email});let n=e.scopes??this.scopes,r=this.deviceService.getDeviceId(),i=Ct(this.platform.getDeviceType());try{let a=await this.startPkce(),o=await this.authApi.passwordlessSignIn({...e,scopes:n,...a?{code_challenge:a.challenge}:{}},r,i,...Wa(t));return a&&o.challenge_id?this.rememberPendingPasswordless({challengeId:o.challenge_id,verifier:a.verifier,codeChallenge:a.challenge,matchCode:o.match_code,email:e.email,scopes:n,expiresAt:new Date(o.expires_at).getTime()}):this.forgetPendingPasswordless(),o}catch(e){let t={operation:`passwordless.start`,message:e instanceof Error?e.message:`Failed to send passwordless sign-in link`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async passwordlessSignInComplete(e,t){this.subscribeStore.notify(G.SignInStart,{}),e.scopes=e.scopes??this.scopes,e.device=this.deviceService.getDeviceId();let n=this.readPendingPasswordless(),r=n?.challengeId===e.challenge_id?n:void 0,i=!1;try{let n=await this.authApi.passwordlessSignInComplete(e,...Wa(t));if(i=!0,this.handlePendingSecondFactor(n,r?.email,r&&{verifier:r.verifier},r?.scopes))return this.forgetPendingPasswordless(),n;let a=n;if(n.code){if(!r)throw Error(ro);if(a=await this.authApi.pkceExchange(n.code,r.verifier),this.handlePendingSecondFactor(a))return this.forgetPendingPasswordless(),{...a,redirect_url:n.redirect_url??``}}let o=n.redirect_url?{...a,redirect_url:n.redirect_url}:a;return await this.processAuthResponse(o,r?.scopes??e.scopes),this.forgetPendingPasswordless(),this.subscribeStore.notify(G.SignIn,{tokens:o,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),{...o,redirect_url:n.redirect_url??``}}catch(e){i&&this.forgetPendingPasswordless();let t={operation:`passwordless.complete`,message:e instanceof Error?e.message:`Passwordless sign in failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async waitForPasswordlessSignIn(e,t){let n=t?.signal;try{let t=this.readPendingPasswordless();if(t?.challengeId!==e)throw Error(ro);for(;;){if(n?.aborted)throw n.reason;if(Date.now()>=t.expiresAt)return this.forgetPendingPasswordless(),{status:`expired`};if(this.readPendingPasswordless()?.challengeId!==e)throw Error(ro);let r;try{r=await this.authApi.passwordlessStatus({challenge_id:e,code_challenge:t.codeChallenge},{signal:n})}catch(e){if(n?.aborted)throw n.reason;if(e instanceof B&&e.status>=400&&e.status<500&&e.status!==429)throw this.forgetPendingPasswordless(),e}if(r?.status===`denied`||r?.status===`expired`||r?.status===`completed`)return this.forgetPendingPasswordless(),{status:r.status};if(r?.status===`approved`&&r.code)return await this.finishApprovedPasswordless(r.code,t);if(r&&r.status===void 0&&r.tfa_token)return this.handlePendingSecondFactor(r,t.email),this.forgetPendingPasswordless(),{status:`second-factor-required`};if(r&&r.status===void 0&&r.redirect_url)return this.forgetPendingPasswordless(),{status:`signed-in`,tokens:{redirect_url:r.redirect_url}};await io(Ja,n)}}catch(e){if(n?.aborted&&e===n.reason)throw e;let t={operation:`passwordless.wait`,message:e instanceof Error?e.message:`Waiting for the passwordless sign-in failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async finishApprovedPasswordless(e,t){try{let n=await this.authApi.pkceExchange(e,t.verifier);return this.handlePendingSecondFactor(n,t.email)?(this.forgetPendingPasswordless(),{status:`second-factor-required`}):(await this.processAuthResponse(n,t.scopes),this.forgetPendingPasswordless(),this.subscribeStore.notify(G.SignIn,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),{status:`signed-in`,tokens:n})}catch(e){throw this.forgetPendingPasswordless(),e}}getPendingPasswordlessSignIn(e){let t=this.readPendingPasswordless();if(t?.challengeId===e&&t.matchCode)return{matchCode:t.matchCode,expiresAt:t.expiresAt}}checkRedirectUrl(e){return this.authApi.checkRedirectUrl(e)}async getPasswordlessApproval(e){try{return await this.authApi.passwordlessApprovalInfo({challenge_id:e})}catch(e){throw this.reportApprovalFailure(e),e}}async decidePasswordlessApproval(e,t,n,r){try{await this.authApi.passwordlessApprovalDecide({challenge_id:e,otp:t,approve:n,match_code:r})}catch(e){throw this.reportApprovalFailure(e),e}}reportApprovalFailure(e){let t={operation:`passwordless.approval`,message:e instanceof Error?e.message:`Passwordless approval failed`,originalError:e,code:e instanceof B?e.id:void 0};W(this.subscribeStore,t)}async verifyEmailCode(e){let t=this.emailChallenges.get(e.challenge_id),n=t?.email;try{let r=t?.pkce===!1?void 0:this.readPendingPkce();if(t?.pkce&&!r)throw Error(ro);let i=await this.authApi.validateEmailCode(e);this.emailChallenges.delete(e.challenge_id);let a=r?.scopes??t?.scopes??this.scopes;if(this.handleEmailVerificationStep(i,t?.operation??`sign-in`,n,r,a)||this.handlePendingSecondFactor(i,n,r,a))return i;let o=i;if(i.code){if(!r)throw Error(ro);if(o=await this.authApi.pkceExchange(i.code,r.verifier),this.handlePendingSecondFactor(o,n))return o}let s=i.redirect_url?{...o,redirect_url:i.redirect_url}:o;return await this.processAuthResponse(s,a),this.forgetPkceSignIn(),t?.operation===`sign-up`?this.notifyRegisteredAndSignedIn(s):this.subscribeStore.notify(G.SignIn,{tokens:s,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),s}catch(e){let t={operation:`email-verification.complete`,message:e instanceof Error?e.message:`Email verification failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async logOut(e){let t=this.refresh.identity(),n,r=e??this.storageManager.getHostedSignIn();return await this.refresh.signOut(async e=>{n=await this.callLogoutApi(e,r),this.forgetPkceSignIn(),this.forgetPendingPasswordless(),this.emailChallenges.clear(),this.clearLocalSession()}),{userId:t,samlLogoutUrl:n}}resetSession(){let e=this.refresh.identity();return this.refresh.signOutNow(()=>{this.emailChallenges.clear(),this.clearLocalSession()}),e}hostedEndSessionUrl(e){let t=this.storageManager.getHostedSignIn();if(!t)return;let n={post_logout_redirect_uri:e??t};this.appId&&(n.client_id=this.appId);let r=this.storageManager.getToken(F.id_token)??this.storageManager.getIdToken();return r&&(n.id_token_hint=r),`${this.url.replace(/\/+$/,``)}/oidc/end_session?${new URLSearchParams(n)}`}async callLogoutApi(e,t){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.logoutUrl){try{await fetch(this.tokenExchangeConfig.logoutUrl,{method:`POST`,credentials:`include`})}catch{}return}let n=e??this.storageManager.getToken(F.refresh_token),r=this.storageManager.getDeviceId();try{let e=await this.authApi.logOut(r,n,!this.appId,t);if(e.status!==`ok`)throw Error(`Logout failed`);return $a(e.saml_logout_url)}catch{return}}clearLocalSession(){this.storageManager.deleteTokens(),this.tokenDeliveryManager.reset(),this.tokenCacheService.setTokensCache(void 0),this.tokenCacheService.stopTokenCheck?.()}readSessionPin(){try{let e=this.storageManager.getToken(F.access_token);return e?Fa(P(e)):void 0}catch{return}}assertSessionPin(e){if(e&&!Ia(e,this.readSessionPin()))throw console.warn(`[passflow] the session or user changed while a step-up upgrade was in flight; the elevated tokens were discarded and the live session was left untouched.`),new Pa(`The session changed during verification, so the elevated tokens were discarded`)}refreshMode(){return this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.refreshUrl?`bff`:this.tokenDeliveryManager.isCookieMode()?`cookie`:`json`}createRefreshEmit(){return(e,t)=>{let n=this.subscribeStore;switch(e){case`refresh`:{let{tokens:e,source:r}=t;n.notify(G.Refresh,{tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens(),source:r});return}case`signin`:{let{tokens:e,origin:r}=t;n.notify(G.SignIn,{tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens(),origin:r});return}case`error`:W(n,t);return;case`refresh:start`:n.notify(G.RefreshStart,{});return;case`token-cache-expired`:n.notify(G.TokenCacheExpired,t);return;case`refresh:failing`:n.notify(G.RefreshFailing,t);return;case`refresh:recovered`:n.notify(G.RefreshRecovered,t);return;case`session:expired`:n.notify(G.SessionExpired,t);return;case`signout`:n.notify(G.SignOut,t);return;default:zi().warn(`[passflow] Unknown refresh event: ${String(e)}`)}}}createRefreshTransport(){return{mode:()=>this.refreshMode(),send:async({tokens:e,upgrade:t})=>{let n=this.refreshMode();if(n===`bff`)return await this.sendBffRefresh();if(this.deviceKey)return await this.sendDeviceKeyRefresh(this.deviceKey,n,e,t);if(n===`cookie`)return t?await this.authApi.refreshToken(``,this.scopes,void 0,t):await this.authApi.refreshToken(``,this.scopes);let r=e?.refresh_token??``,i=e?.scopes??this.scopes,a=e?.access_token;return t?await this.authApi.refreshToken(r,i,a,t):await this.authApi.refreshToken(r,i,a)},applyOpaque:async e=>{this.tokenDeliveryManager.setSessionValid(),this.tokenDeliveryManager.isBFFMode()?(e.id_token&&this.storageManager.setIdToken(e.id_token),e.csrf_token&&this.storageManager.setCsrfToken(e.csrf_token)):await this.applyAuthResponse(e,this.scopes)},invalidate:()=>{this.tokenDeliveryManager.setSessionInvalid(),this.storageManager.clearIdToken(),this.storageManager.clearCsrfToken()},assertPin:e=>this.assertSessionPin(e),opaqueMarker:()=>{let e=this.storageManager.getIdToken(),t=this.storageManager.getCsrfToken();return e===void 0&&t===void 0?void 0:`${e??``}\n${t??``}`}}}async sendDeviceKeyRefresh(e,t,n,r){let i=t===`json`?n?.refresh_token??``:``,a=t===`json`?n?.scopes??this.scopes:this.scopes,o=t===`json`?n?.access_token:void 0,s={};if(e.supported)try{let n=t===`json`?i&&await En(i):this.storageManager.getRefreshChallenge(),r=n?await e.proof(`refresh`,n):void 0;r&&(s={proof:r})}catch(t){throw await e.clear().catch(()=>void 0),new B({id:zn.proofUnavailable,message:`The device key could not sign the refresh. Sign in again.`,status:0,location:z.refresh,time:new Date().toISOString()},{cause:t})}try{return await this.authApi.refreshToken(i,a,o,r,s)}catch(t){throw Bn(Pi(t))&&await e.clear().catch(()=>void 0),t}}async signInProof(){let e=this.deviceKey;if(e&&this.appId)try{if(!await e.isEnrolled())return;let{challenge:t}=await this.authApi.deviceChallenge();return await e.proof(`sign_in`,t)}catch{return}}async enrolDeviceKey(){try{let e=this.deviceKey,t=this.enrolDeviceKeyRequest;if(!e||!t)throw Error(`Device keys are off: set deviceKey: true in the Passflow config`);if(!e.supported)throw Error(Nn);let{challenge:n}=await this.authApi.deviceChallenge();await t({proof:await e.enrolProof(n),key_storage:`software`}),await e.markEnrolled()}catch(e){let t=Pi(e);if(t===zn.keyReused){await this.deviceKey?.clear().catch(()=>void 0);let e=this.resetSession();this.subscribeStore.notify(G.SignOut,e===void 0?{origin:`this-tab`}:{origin:`this-tab`,userId:e})}throw W(this.subscribeStore,{operation:`device-key.enrol`,message:e instanceof Error?e.message:`Device key enrolment failed`,originalError:e,code:t}),e}}async secondFactorCompleted(){this.deviceKey&&await this.enrolDeviceKey().catch(()=>void 0)}async sendBffRefresh(){let e=this.tokenExchangeConfig?.refreshUrl??``,t=await fetch(e,{method:`POST`,credentials:`include`});if(!t.ok){let n,r;try{let e=await t.json();typeof e?.error?.id==`string`&&(n=e.error.id),typeof e?.error?.message==`string`&&(r=e.error.message)}catch{}throw new B({id:n??`error.http.${t.status}`,message:r??`BFF token refresh failed`,status:t.status,location:e,time:new Date().toISOString()})}return await t.json()}async refreshToken(e,t){if(e&&this.tokenDeliveryManager.isBFFMode())throw new $({kind:`unavailable`,message:`Step-up verification cannot be committed through a BFF refresh endpoint`});if(e)return await this.refresh.commitUpgrade(e,t);if(this.refreshMode()===`json`&&!this.refresh.ended){let e=this.storageManager.getTokens();if(!e?.refresh_token){let t=Error(e?`No refresh token found`:`No tokens found`);throw W(this.subscribeStore,{operation:`refresh`,source:`refresh-token`,message:t.message,originalError:t}),t}}return await this.refresh.refresh({trigger:`refresh-token`,fresh:!0})}async sendPasswordResetEmail(e,t){try{return await this.authApi.sendPasswordResetEmail(e,...Wa(t))}catch(e){let t={operation:`password-reset.send`,message:e instanceof Error?e.message:`Failed to send password reset email`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async resetPassword(e,t,n){this.subscribeStore.notify(G.SignInStart,{});let r=n??ao(this.platform.getCurrentUrl()),i=t??this.scopes;try{let t=await this.startPkce(),n=t?await this.authApi.resetPassword(e,i,r,t.challenge):await this.authApi.resetPassword(e,i,r);if(this.handleEmailVerificationStep(n,`reset-password`,oo(r),t,i)||this.handlePendingSecondFactor(n,void 0,t,i))return n;let a=await this.exchangeCode(n,t);if(this.handlePendingSecondFactor(a))return a;let o=n.redirect_url?{...a,redirect_url:n.redirect_url}:a;return await this.processAuthResponse(o,i),this.subscribeStore.notify(G.SignIn,{tokens:o,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),o}catch(e){let t={operation:`password-reset.complete`,message:e instanceof Error?e.message:`Password reset failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async passkeyRegister(e,t){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);this.subscribeStore.notify(G.RegisterStart,{});let n=this.deviceService.getDeviceId(),r=Ct(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{let i=await this.startPkce(),{challenge_id:a,publicKey:o}=await this.authApi.passkeyRegisterStart(i?{...e,code_challenge:i.challenge}:e,n,r,!this.appId,...Wa(t));o.user.id=this.platform.btoa(o.user.id);let s=await this.platform.passkeys.startRegistration(o);if(!s)throw Error(`Passkey registration was not completed`);let c=await this.authApi.passkeyRegisterComplete(s,n,a,!this.appId,...Wa(t));if(this.handlePendingSecondFactor(c,void 0,i,e.scopes))return c;let l=await this.exchangeCode(c,i);return this.handlePendingSecondFactor(l)||(await this.processAuthResponse(l,e.scopes),this.notifyRegisteredAndSignedIn(l),await this.submitSessionCheck()),l}catch(e){let t={operation:`passkey.register`,message:e instanceof Error?e.message:`Passkey registration failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async passkeyAuthenticate(e,t){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);this.subscribeStore.notify(G.SignInStart,{});let n=this.deviceService.getDeviceId(),r=Ct(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes;try{let i=await this.startPkce(),{challenge_id:a,publicKey:o}=await this.authApi.passkeyAuthenticateStart(i?{...e,code_challenge:i.challenge}:e,n,r,!this.appId,...Wa(t)),s=await this.platform.passkeys.startAuthentication(o);if(!s)throw Error(`Passkey authentication was not completed`);let c=await this.signInProof(),l=c?await this.authApi.passkeyAuthenticateComplete(s,n,a,!this.appId,t,c):await this.authApi.passkeyAuthenticateComplete(s,n,a,!this.appId,...Wa(t));if(this.handlePendingSecondFactor(l,void 0,i,e.scopes))return l;let u=await this.exchangeCode(l,i);return this.handlePendingSecondFactor(u)||`access_token`in u&&(await this.processAuthResponse(u,e.scopes),this.subscribeStore.notify(G.SignIn,{tokens:u,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),u}catch(e){let t={operation:`passkey.authenticate`,message:e instanceof Error?e.message:`Passkey authentication failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async usesFederatedPost(e){if(e?.agentTool===!0)return!0;try{return(await this.readAppSettings?.())?.bot_mode===`human_only`}catch{return!1}}federatedStartBody(e,t){let n=eo(e);return{redirect_url:e.redirect_url??this.platform.getCurrentUrl()?.origin??``,scopes:t,...e.device?{device:e.device}:{},...e.create_tenant?{create_tenant:e.create_tenant}:{},...e.invite_token?{invite_token:e.invite_token}:{},...e.parent_challenge_id?{parent_challenge_id:e.parent_challenge_id}:{},...e.code_challenge?{code_challenge:e.code_challenge}:{},...e.code_challenge_method?{code_challenge_method:e.code_challenge_method}:{},...e.state?{state:e.state}:{},...n?{login_hint:n}:{}}}createFederatedAuthUrl(e){if(!this.appId)throw Error(Za);let t=new URL(`/auth/federated/start/${e.provider}`,this.url);return t.search=new URLSearchParams(this.federatedStartQuery(e,e.scopes??this.scopes,this.appId)).toString(),t.toString()}federatedStartQuery(e,t,n){let r=eo(e);return{scopes:t.join(` `),redirect_url:e.redirect_url??this.platform.getCurrentUrl()?.origin??``,appId:n,...e.invite_token?{invite_token:e.invite_token}:{},...e.create_tenant?{create_tenant:e.create_tenant.toString()}:{},...e.device?{device:e.device}:{},...e.code_challenge?{code_challenge:e.code_challenge}:{},...e.code_challenge_method?{code_challenge_method:e.code_challenge_method}:{},...e.state?{state:e.state}:{},...e.parent_challenge_id?{parent_challenge_id:e.parent_challenge_id}:{},...r?{login_hint:r}:{}}}createEnterpriseAuthUrl(e){if(!this.appId)throw Error(Za);let t=e.scopes??this.scopes,n=this.deviceService.getDeviceId(),r=new URL(z.enterpriseStart,this.url);return r.search=new URLSearchParams({...to(e),...this.federatedStartQuery({...e,device:n},t,this.appId)}).toString(),r.toString()}async enterpriseStart(e,t){let n=e.scopes??this.scopes,r=this.deviceService.getDeviceId();return{auth_url:Qa((await this.authApi.enterpriseStart({...to(e),...this.federatedStartBody({...e,device:r},n)},t)).auth_url)}}async federatedAuthWithPopup(e,t){if(this.subscribeStore.notify(G.SignInStart,{provider:e.provider}),!this.appId)throw Error(Za);let n=e.scopes??this.scopes,r=this.deviceService.getDeviceId();try{this.forgetFederatedSlot();let i={mode:`popup`,expectedReturnOrigin:this.platform.getCurrentUrl()?.origin??``},a=(async()=>{let i=await this.startPkce(),a={...e,scopes:n,device:r,...i?{code_challenge:i.challenge,code_challenge_method:`S256`}:{}};return{url:await this.usesFederatedPost(t)?Qa((await this.authApi.federatedStart(e.provider,this.federatedStartBody(a,n),t)).auth_url):this.createFederatedAuthUrl(a),pkce:i}})(),o,s=e=>{o=e,e&&this.rememberFederatedSlot(e.verifier,n)},c;if(this.platform.openPendingAuthUrl)c=this.platform.openPendingAuthUrl(a.then(e=>(s(e.pkce),e.url)),i);else{let e=await a;c=this.platform.openAuthUrl(e.url,i),s(e.pkce)}let l=await c;this.forgetFederatedSlot();let u=new URLSearchParams(l.callbackHash.replace(/^#/,``));if(this.handlePendingSecondFactor({tfa_token:u.get(`tfa_token`)??void 0}))return;let d=new URLSearchParams(l.callbackSearch),f=d.get(`code`),p=d.get(`access_token`)?d:u,m=p.get(`access_token`)||``,h=p.get(`refresh_token`)||``,g=p.get(`id_token`)||``,_={access_token:m,refresh_token:h||void 0,id_token:g||void 0,scopes:n};if(o){if(!f)throw xr();if(_=await this.authApi.pkceExchange(f,o.verifier),this.handlePendingSecondFactor(_))return}else{if(!await this.isSimpleModeApp())throw xr();await ha(this.url,this.appId,_)}await this.processAuthResponse(_,n),this.subscribeStore.notify(G.SignIn,{tokens:_,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.platform.navigateTo(this.platform.getCurrentUrl()?.origin??``)}catch(e){if(this.forgetFederatedSlot(),e instanceof U&&e.code===`TOKENS_IN_URL_NOT_ALLOWED`){W(this.subscribeStore,{operation:`tokens.from-url`,message:e.message,code:e.code,originalError:e});return}let t={operation:`federated.popup`,message:e instanceof Error?e.message:`Authentication failed`,code:e instanceof _e?`POPUP_CLOSED`:`AUTH_FAILED`,originalError:e};W(this.subscribeStore,t)}}federatedAuthWithRedirect(e,t){if(this.subscribeStore.notify(G.SignInStart,{provider:e.provider}),!this.appId)throw Error(Za);let n=e.scopes??this.scopes,r=this.deviceService.getDeviceId();this.startPkce().then(async i=>{let a={...e,scopes:n,device:r,...i?{code_challenge:i.challenge,code_challenge_method:`S256`}:{}},o=await this.usesFederatedPost(t)?Qa((await this.authApi.federatedStart(e.provider,this.federatedStartBody(a,n),t)).auth_url):this.createFederatedAuthUrl(a);i?this.rememberFederatedSlot(i.verifier,n):this.forgetFederatedSlot(),this.platform.navigateTo(o)}).catch(e=>this.reportFederatedRedirectFailure(e))}handleFederatedCode(e){if(!this.appId)return!1;let t=this.readFederatedSlot();return t?(this.forgetFederatedSlot(),this.finishFederatedLanding(e,t),!0):!1}async finishFederatedLanding(e,t){try{let n=await this.authApi.pkceExchange(e,t.verifier);if(this.handlePendingSecondFactor(n))return;await this.processAuthResponse(n,t.scopes),this.subscribeStore.notify(G.SignIn,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens(),source:`federated-landing`}),await this.submitSessionCheck()}catch(e){this.reportFederatedRedirectFailure(e)}}reportFederatedRedirectFailure(e){let t={operation:`federated.redirect`,message:e instanceof Error?e.message:`Federated sign-in failed`,originalError:e,code:e instanceof B?e.id:void 0};W(this.subscribeStore,t)}authRedirectUrl(e={}){try{let{url:t,redirectUrl:n,scopes:r,appId:i}=e??{},a=new URL(t??this.url);a.pathname=(a.pathname.endsWith(`/`)?a.pathname:a.pathname+`/`)+`web`;let o=r??this.scopes,s={appId:i??this.appId??``,redirectto:n??this.platform.getCurrentUrl()?.href??``,scopes:o.join(`,`)};return a.search=new URLSearchParams(s).toString(),a.toString()}catch(e){let t={operation:`auth-redirect.url`,message:e instanceof Error?e.message:`Failed to create auth redirect URL`,originalError:e};throw W(this.subscribeStore,t),e}}async authRedirect(e={}){try{let{url:t,appId:n,redirectUrl:r,scopes:i,state:a}=e;if(t!==void 0&&wr(t)!==wr(this.url)||n!==void 0&&n!==(this.appId??``))throw new U(`OVERRIDE_NOT_SUPPORTED`,`authRedirect() signs in to this instance's url and appId; create a Passflow instance for another server or app`);let o=await this.readAppSettings?.();if(o?.pkce_enabled!==!0){let e=this.authRedirectUrl({redirectUrl:r,scopes:i});this.platform.navigateTo(a?`${e}&${new URLSearchParams({state:a})}`:e);return}if(o.public_client===!1)throw new U(`CONFIDENTIAL_CLIENT`,yr(o.type));let s=this.platform.getCurrentUrl(),c=await Er({url:this.url,clientId:this.appId??``,redirectUri:r??(s?s.origin+s.pathname:``),scopes:i??this.scopes});this.platform.navigateTo(c)}catch(e){let t={operation:`auth-redirect`,message:e instanceof Error?e.message:`Failed to redirect to auth page`,originalError:e,code:e instanceof U?e.code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}handleOidcLanding(e){if(!this.appId)return!1;let t=new URLSearchParams(e.search),n=t.get(`code`),r=t.get(`state`),i=t.get(`error`),a=t.get(`error_description`);if(t.get(`user_state`)||r===null||!n&&!i)return!1;let o=Or();if(o.status===`none`)return!1;kr();for(let e of[`code`,`state`,`iss`,`error`,`error_description`])t.delete(e);let s=t.toString();return this.platform.replaceUrl(e.pathname+(s?`?${s}`:``)+e.hash),this.finishOidcLanding(async()=>{if(o.status===`unusable`)throw new U(`VERIFIER_MISSING`,`This sign-in has expired or its proof key is gone. Sign in again.`);if(o.slot.state!==r)throw new U(`STATE_MISMATCH`,`The sign-in answer does not belong to this sign-in. Sign in again.`);if(i||!n)throw new U(i??`TOKEN_EXCHANGE_FAILED`,Ra(a||i||`Sign in again.`));return{tokens:await jr(this.url,n,o.slot),scopes:o.slot.scopes,returnUrl:o.slot.redirectUri}}),!0}async finishOidcLanding(e){try{await Promise.resolve();let{tokens:t,scopes:n,returnUrl:r}=await e();await this.processAuthResponse(t,n),this.storageManager.setHostedSignIn(r),this.subscribeStore.notify(G.SignIn,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens(),source:`oidc-landing`}),await this.submitSessionCheck()}catch(e){W(this.subscribeStore,{operation:`oidc.redirect`,message:e instanceof Error?e.message:`Sign-in failed`,code:e instanceof U?e.code:void 0,originalError:e})}}isAuthenticated(e){try{if(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode()){let t=!!e?.id_token||!!this.storageManager.getIdToken(),n=this.tokenDeliveryManager.isSessionValid(),r=this.tokenDeliveryManager.isSessionUnknown();return t&&(n||r)}return!e||!e.access_token?!1:!N(e.access_token)||e.refresh_token!==void 0&&!N(e.refresh_token)}catch(e){let t={operation:`auth.is-authenticated`,message:e instanceof Error?e.message:`Failed to check authentication status`,originalError:e};return W(this.subscribeStore,t),!1}}async submitSessionCheck(e=!1){let t,n;try{t=await this.getTokens(e),n=this.tokenCacheService.getParsedTokens()}catch(e){let n={operation:`session.check`,message:e instanceof Error||e instanceof B?e.message:`Session check failed`,originalError:e};W(this.subscribeStore,n),t=void 0}return t&&this.sessionCallbacks.createSession&&await this.sessionCallbacks.createSession({tokens:t,parsedTokens:n}),!t&&this.sessionCallbacks.expiredSession&&await this.sessionCallbacks.expiredSession(),t}async refreshForSession(){try{await this.refresh.refresh({trigger:`session`})}catch{}return this.tokenCacheService.getTokens()}async getTokens(e){try{if(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode()){let t=this.storageManager.getTokens();return t?.id_token?this.tokenDeliveryManager.isSessionInvalid()&&e?await this.refreshForSession():t:void 0}let t=this.storageManager.getTokens();if(!t||!t.access_token)return;if(N(P(t.access_token))){if(e){let e=await this.refreshForSession();return e?.refresh_token||this.storageManager.getTokens()?.refresh_token||!this.tokenCacheService.isExpired()?e:void 0}return}return t}catch(e){let t={operation:`tokens.get`,message:e instanceof Error?e.message:`Failed to get tokens`,originalError:e};W(this.subscribeStore,t);return}}},co=class{constructor(e){this.invitationApi=e}requestInviteLink(e){return this.invitationApi.requestInviteLink(e)}getInvitations(e){return this.invitationApi.getInvitations(e)}deleteInvitation(e){return this.invitationApi.deleteInvitation(e)}resendInvitation(e){return this.invitationApi.resendInvitation(e)}getInvitationLink(e){return this.invitationApi.getInvitationLink(e)}},lo=class{constructor(e){this.data=this.normalize(e)}normalize(e){let t=new Map,n=new Map,r=new Map,i=[];return e.groups?.forEach(e=>{n.set(e.id,{id:e.id,name:e.name,default:e.default??!1,updated_at:e.updated_at,created_at:e.created_at})}),e.roles?.forEach(e=>{r.set(e.id,{id:e.id,tenant_id:e.tenant_id,name:e.name})}),e.users_in_groups?.forEach(e=>{let r=e.user;r&&!t.has(r.id)&&t.set(r.id,{id:r.id,name:r.name??null,email:r.email??null,phone:r.phone??null}),r&&e.group_id&&n.has(e.group_id)&&i.push({userId:r.id,groupId:e.group_id,roleIds:e.roles?.map(e=>e.id)??[]})}),{tenant_id:e.tenant_id,tenant_name:e.tenant_name,users:Array.from(t.values()),groups:Array.from(n.values()),roles:Array.from(r.values()),memberships:i,usersById:t,groupsById:n,rolesById:r}}getUsersInGroup(e){return this.data.memberships.filter(t=>t.groupId===e).map(e=>this.data.usersById.get(e.userId)).filter(e=>e!==void 0)}getGroupsForUser(e){return this.data.memberships.filter(t=>t.userId===e).map(e=>this.data.groupsById.get(e.groupId)).filter(e=>e!==void 0)}getUserRolesInGroup(e,t){let n=this.data.memberships.find(n=>n.userId===e&&n.groupId===t);return n?n.roleIds.map(e=>this.data.rolesById.get(e)).filter(e=>e!==void 0):[]}getData(){return this.data}},uo=class{constructor(e,t,n){this.tenantApi=e,this.scopes=t,this.logger=n||zi()}handlePassflowError(e,t){if(c.default.isAxiosError(e)&&e.response?.data){let n=e.response.data;if(typeof n==`object`&&n&&`error`in n&&typeof n.error==`object`&&n.error!==null){let e=n.error;throw this.logger.error(`${t}: ${e.id} - ${e.message} (Status: ${e.status})`),Error(`Passflow API Error: ${e.id} - ${e.message} (Status: ${e.status})`)}}throw this.logger.error(`${t}:`,e),e instanceof Error?e:Error(String(e))}async joinInvitation(e,t){try{let n=t??this.scopes;return await this.tenantApi.joinInvitation(e,n)}catch(e){this.handlePassflowError(e,`Join invitation failed`)}}async createTenant(e){try{return await this.tenantApi.createTenant(e)}catch(e){this.handlePassflowError(e,`Tenant creation failed`)}}async getTenantDetails(e){try{return await this.tenantApi.getTenantDetails(e)}catch(t){this.handlePassflowError(t,`Get tenant details failed for tenant ID ${e}`)}}async getTenantUserMembership(e){try{return new lo(await this.tenantApi.getTenantDetails(e))}catch(t){this.handlePassflowError(t,`Get tenant user membership failed for tenant ID ${e}`)}}async updateTenant(e,t){try{return await this.tenantApi.updateTenant(e,t)}catch(t){this.handlePassflowError(t,`Update tenant failed for tenant ID ${e}`)}}async deleteTenant(e){try{return await this.tenantApi.deleteTenant(e)}catch(t){this.handlePassflowError(t,`Delete tenant failed for tenant ID ${e}`)}}async getUserTenantMembership(){try{return await this.tenantApi.getUserTenantMembership()}catch(e){this.handlePassflowError(e,`Get user tenant memberships failed`)}}async createGroup(e,t){try{return await this.tenantApi.createGroup(e,t)}catch(t){this.handlePassflowError(t,`Group creation failed for tenant ID ${e}`)}}async getGroupInfo(e,t){try{return await this.tenantApi.getGroupInfo(e,t)}catch(n){this.handlePassflowError(n,`Get group info failed for tenant ID ${e}, group ID ${t}`)}}async updateGroup(e,t,n){try{return await this.tenantApi.updateGroup(e,t,n)}catch(n){this.handlePassflowError(n,`Update group failed for tenant ID ${e}, group ID ${t}`)}}async deleteGroup(e,t){try{return await this.tenantApi.deleteGroup(e,t)}catch(n){this.handlePassflowError(n,`Delete group failed for tenant ID ${e}, group ID ${t}`)}}async addUserToGroup(e,t,n,r){try{return await this.tenantApi.addUserToGroup(e,t,n,r)}catch(r){this.handlePassflowError(r,`Add user to group failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async removeUserRolesFromGroup(e,t,n,r){try{return await this.tenantApi.removeUserRolesFromGroup(e,t,n,r)}catch(r){this.handlePassflowError(r,`Remove user roles from group failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async changeUserRoles(e,t,n,r){try{return await this.tenantApi.changeUserRoles(e,t,n,r)}catch(r){this.handlePassflowError(r,`Change user roles failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async deleteUserFromGroup(e,t,n){try{return await this.tenantApi.deleteUserFromGroup(e,t,n)}catch(r){this.handlePassflowError(r,`Delete user from group failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async getRolesForTenant(e){try{return await this.tenantApi.getRolesForTenant(e)}catch(t){this.handlePassflowError(t,`Get roles for tenant failed for tenant ID ${e}`)}}async createRoleForTenant(e,t){try{return await this.tenantApi.createRoleForTenant(e,t)}catch(t){this.handlePassflowError(t,`Create role for tenant failed for tenant ID ${e}`)}}async updateRole(e,t,n){try{return await this.tenantApi.updateRole(e,t,n)}catch(n){this.handlePassflowError(n,`Update role failed for tenant ID ${e}, role ID ${t}`)}}async deleteRole(e,t){try{return await this.tenantApi.deleteRole(e,t)}catch(n){this.handlePassflowError(n,`Delete role failed for tenant ID ${e}, role ID ${t}`)}}async deleteUserFromTenant(e,t){try{return await this.tenantApi.deleteUserFromTenant(e,t)}catch(n){this.handlePassflowError(n,`Delete user from tenant failed for tenant ID ${e}, user ID ${t}`)}}async getGroupInvitations(e,t,n,r){try{return await this.tenantApi.getGroupInvitations(e,t,n,r)}catch(n){this.handlePassflowError(n,`Get group invitations failed for tenant ID ${e}, group ID ${t}`)}}async getTenantInvitations(e,t,n){try{return await this.tenantApi.getTenantInvitations(e,t,n)}catch(t){this.handlePassflowError(t,`Get tenant invitations failed for tenant ID ${e}`)}}async invalidateInviteById(e,t,n){try{return await this.tenantApi.invalidateInviteById(e,t,n)}catch(r){this.handlePassflowError(r,`Invalidate invite by ID failed for tenant ID ${e}, group ID ${t}, invite ID ${n}`)}}async invalidateInviteByEmail(e,t,n){try{return await this.tenantApi.invalidateInviteByEmail(e,t,n)}catch(r){this.handlePassflowError(r,`Invalidate invite by email failed for tenant ID ${e}, group ID ${t}, email ${n}`)}}},fo=class{constructor(e,t,n,r=ye){this.storageManager=e,this.subscribeStore=n,this.platform=r,this.checkInterval=null,this.CHECK_INTERVAL=6e4,this.unsubscribeForeground=null,this.unsubscribeUnload=null,this.tokenExpiredFlag=!1,this.storageManager=e,this.setupLifecycleListeners()}get isRefreshing(){return this.refreshController?.busy??!1}attachRefreshController(e){this.refreshController=e}initialize(){try{let e=this.tokensCache,t=e??this.storageManager.getTokens();if(!t)return;if(!t.access_token){e||this.setTokensCache(t),this.startTokenCheck();return}N(P(t.access_token))?(this.stopTokenCheck(),this.tokenExpiredFlag||(this.tokenExpiredFlag=!0,this.subscribeStore.notify(G.TokenCacheExpired,{isExpired:!0}))):(e||this.setTokensCache(t),this.startTokenCheck())}catch(e){let t={operation:`tokens.load`,message:e instanceof Error?e.message:`Failed to get tokens`,originalError:e};W(this.subscribeStore,t),this.setTokensCache(void 0)}}startTokenCheck(){this.checkInterval&&clearInterval(this.checkInterval),this.tokenExpiredFlag||(this.setupLifecycleListeners(),this.checkInterval=setInterval(()=>{this.platform.isInForeground()&&(this.isRefreshing||this.tokenExpiredFlag||this.isExpired()&&!this.tokenExpiredFlag&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(G.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck()))},this.CHECK_INTERVAL))}setupLifecycleListeners(){this.unsubscribeForeground&&(this.unsubscribeForeground(),this.unsubscribeForeground=null),this.unsubscribeForeground=this.platform.onForeground(()=>{this.checkInterval&&!this.isRefreshing&&!this.tokenExpiredFlag&&this.isExpired()&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(G.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck())}),this.unsubscribeUnload||(this.unsubscribeUnload=this.platform.onBeforeUnload(()=>{this.destroy()}))}stopTokenCheck(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null),this.unsubscribeForeground&&(this.unsubscribeForeground(),this.unsubscribeForeground=null)}destroy(){this.stopTokenCheck(),this.unsubscribeUnload&&(this.unsubscribeUnload(),this.unsubscribeUnload=null)}setTokensCache(e){this.tokensCache=e,this.parsedTokensCache=e?{access_token:e.access_token?P(e.access_token):void 0,id_token:e.id_token?P(e.id_token):void 0,refresh_token:e.refresh_token?P(e.refresh_token):void 0,scopes:e.scopes}:void 0}getTokens(){return this.tokensCache}async getTokensWithRefresh(){try{if(!this.tokensCache||!this.tokensCache.access_token)return this.tokensCache;if(N(P(this.tokensCache.access_token))&&this.refreshController)try{await this.refreshController.refresh({trigger:`token-check`})}catch{}return this.tokensCache}catch(e){let t={operation:`tokens.get`,message:e instanceof Error?e.message:`Failed to get tokens`,originalError:e};W(this.subscribeStore,t);return}}getParsedTokens(){return this.parsedTokensCache}isExpired(){return this.tokensCache?this.tokensCache.access_token?N(P(this.tokensCache.access_token)):!1:!0}},po=class{constructor(e,t,n){this.twoFactorApi=e,this.subscribeStore=t,this.signInCompleter=n,this.PARTIAL_AUTH_TIMEOUT_MS=3e5,this.SESSION_STORAGE_KEY=`passflow_2fa_challenge`,this.subscribeStore.subscribe({onAuthChange:(e,t)=>{if(e===G.TwoFactorRequired){let e=t;this.setPartialAuthState(e.email,e.challengeId,e.tfaToken)}(e===G.SignIn||e===G.Register)&&(this.clearPartialAuthState(),this.clearMagicLinkSession())}},[G.TwoFactorRequired,G.SignIn,G.Register])}emitErrorAndThrow(e,t,n){let r=e,i={operation:t,message:e instanceof Error?e.message:`${n} failed`,originalError:e,code:r?.id||void 0};throw W(this.subscribeStore,i),e}async getStatus(){try{let e=await this.twoFactorApi.getStatus(this.getMagicLinkSessionToken()??void 0);return this.storeTotpDigits(e.totp_digits),e}catch(e){this.emitErrorAndThrow(e,`2fa.status`,`Get 2FA status`)}}async beginSetup(){try{return this.setupStarted(await this.twoFactorApi.beginSetup(this.getMagicLinkSessionToken()??void 0))}catch(e){this.emitErrorAndThrow(e,`2fa.setup.begin`,`Begin 2FA setup`)}}async confirmSetup(e){this.assertTotpCode(e);try{let t=await this.twoFactorApi.confirmSetup({code:e},this.getMagicLinkSessionToken()??void 0);return this.clearMagicLinkSession(),this.setupConfirmed(t)}catch(e){this.emitErrorAndThrow(e,`2fa.setup.confirm`,`Confirm 2FA setup`)}}async getEnrollment(){try{let e=await this.twoFactorApi.getEnrollment(this.requirePendingTfaToken());return this.storeTotpDigits(e.totp_digits),e}catch(e){this.emitErrorAndThrow(e,`2fa.enrollment.read`,`Read 2FA enrollment`)}}async sendSetupLink(){try{return await this.twoFactorApi.sendSetupLink(this.requirePendingTfaToken())}catch(e){this.emitErrorAndThrow(e,`2fa.enrollment.setup-link`,`Send 2FA setup link`)}}async beginEnrollment(){try{return this.setupStarted(await this.twoFactorApi.beginEnrollment(this.requirePendingTfaToken()))}catch(e){this.emitErrorAndThrow(e,`2fa.setup.begin`,`Begin 2FA enrollment`)}}async confirmEnrollment(e){this.assertTotpCode(e);try{return this.setupConfirmed(await this.twoFactorApi.confirmEnrollment(this.requirePendingTfaToken(),{code:e}))}catch(e){this.emitErrorAndThrow(e,`2fa.setup.confirm`,`Confirm 2FA enrollment`)}}assertTotpCode(e){let t=this.totpDigits;if(t){if(!Ha(e,t))throw Error(`Invalid TOTP code format. Code must be exactly ${t} digits.`)}else if(!Ha(e,6)&&!Ha(e,8))throw Error(`Invalid TOTP code format. Code must be 6 or 8 digits.`)}requirePendingTfaToken(){let e=this.pendingTfaToken();if(!e)throw Error(`2FA verification expired or not required. User must sign in first.`);return e}storeTotpDigits(e){e&&(this.totpDigits=e)}setupStarted(e){return this.storeTotpDigits(e.totp_digits),this.subscribeStore.notify(G.TwoFactorSetupStarted,{secret:e.secret}),e}setupConfirmed(e){let t=e.recovery_codes??[];return this.subscribeStore.notify(G.TwoFactorEnabled,{recoveryCodes:t,clearRecoveryCodes:()=>{t.length=0}}),e}async verify(e,t){if(this.assertTotpCode(e),this.recoverPartialAuthState(),!this.isVerificationRequired())throw Error(`2FA verification expired or not required. User must sign in first.`);if(!this.partialAuthState?.tfaToken)throw Error(`No TFA token found. User must sign in first.`);try{let n=await this.twoFactorApi.verify({code:e,tfa_token:this.partialAuthState.tfaToken,...t?.trustDevice?{trust_device:!0}:{}}),r=await this.finishSignIn(n);return this.subscribeStore.notify(G.TwoFactorVerified,{tokens:r}),r}catch(e){this.emitErrorAndThrow(e,`2fa.verify`,`Verify 2FA code`)}}async useRecoveryCode(e,t){try{let n=Ua(e);if(!n)throw Error(`Invalid recovery code format. Expected letters, digits and dashes, such as XXXX-XXXX-XXXX.`);if(this.recoverPartialAuthState(),!this.isVerificationRequired())throw Error(`2FA verification expired or not required. User must sign in first.`);if(!this.partialAuthState?.tfaToken)throw Error(`No TFA token found. User must sign in first.`);let r=await this.finishSignIn(await this.twoFactorApi.useRecoveryCode({recovery_code:n,tfa_token:this.partialAuthState.tfaToken,...t?.trustDevice?{trust_device:!0}:{}})),i=r.remaining_recovery_codes;return i===0?this.subscribeStore.notify(G.TwoFactorRecoveryCodesExhausted,{tokens:r}):typeof i==`number`&&i<=2&&this.subscribeStore.notify(G.TwoFactorRecoveryCodesLow,{tokens:r,remainingCodes:i}),this.subscribeStore.notify(G.TwoFactorRecoveryUsed,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(G.TwoFactorVerified,{tokens:r}),r}catch(e){this.emitErrorAndThrow(e,`2fa.recovery.use`,`Use recovery code`)}}async disable(e){this.assertTotpCode(e);try{let t=await this.twoFactorApi.disable({code:e});return this.subscribeStore.notify(G.TwoFactorDisabled,{}),t}catch(e){this.emitErrorAndThrow(e,`2fa.disable`,`Disable 2FA`)}}async regenerateRecoveryCodes(e){this.assertTotpCode(e);try{let t=await this.twoFactorApi.regenerateRecoveryCodes({code:e}),n=[...t.recovery_codes];return t.recovery_codes=[],t.recovery_codes=n,t}catch(e){this.emitErrorAndThrow(e,`2fa.recovery.regenerate`,`Regenerate recovery codes`)}}isVerificationRequired(){return this.recoverPartialAuthState(),this.partialAuthState?Date.now()>this.partialAuthState.expiresAt?(this.clearPartialAuthState(),!1):!0:!1}setPartialAuthState(e,t,n){if(this.totpDigits=void 0,this.partialAuthState={email:e,challengeId:t,tfaToken:n,timestamp:Date.now(),expiresAt:Date.now()+this.PARTIAL_AUTH_TIMEOUT_MS},typeof sessionStorage<`u`)try{sessionStorage.setItem(this.SESSION_STORAGE_KEY,JSON.stringify(this.partialAuthState))}catch{}}clearPartialAuthState(){if(this.partialAuthState=void 0,this.totpDigits=void 0,this.signInCompleter?.forgetPkceSignIn(),typeof sessionStorage<`u`)try{sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{}}async finishSignIn(e){let{code:t,...n}=e;if(t&&!this.signInCompleter?.hasPendingPkceSignIn()){this.clearPartialAuthState();let e=Error(`The sign-in answered with a PKCE code, but its verifier is gone`);throw e.id=`PKCE_VERIFIER_MISSING`,e}let r=e;if(t&&this.signInCompleter){let e=await this.signInCompleter.completePkceSignIn(t);r={...n,...e}}else await this.signInCompleter?.applyTokens(r);return await this.signInCompleter?.secondFactorCompleted?.(),this.clearPartialAuthState(),r}pendingTfaToken(){return this.isVerificationRequired()&&this.partialAuthState?.tfaToken||void 0}recoverPartialAuthState(){if(!this.partialAuthState&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(this.SESSION_STORAGE_KEY);if(!e)return;let t=JSON.parse(e);Date.now()<t.expiresAt?this.partialAuthState=t:sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{try{sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{}}}async validateTwoFactorSetupMagicLink(e){let t=await this.twoFactorApi.validateTwoFactorSetupMagicLink(e);return t.success&&t.sessionToken&&t.userId?(this.magicLinkSession={sessionToken:t.sessionToken,userId:t.userId,appId:t.appId,scope:`2fa_setup`,reset:t.reset===!0,timestamp:Date.now(),expiresAt:Date.now()+(t.expiresIn||3600)*1e3},this.subscribeStore.notify(G.TwoFactorSetupMagicLinkValidated,{userId:t.userId,appId:t.appId,expiresIn:t.expiresIn||3600,sessionToken:t.sessionToken,reset:t.reset===!0})):t.error&&this.subscribeStore.notify(G.TwoFactorSetupMagicLinkFailed,{error:t.error}),t}getMagicLinkSession(){return this.magicLinkSession?Date.now()>this.magicLinkSession.expiresAt?(this.clearMagicLinkSession(),null):this.magicLinkSession:null}clearMagicLinkSession(){this.magicLinkSession=void 0}hasMagicLinkSession(){return this.getMagicLinkSession()!==null}getMagicLinkSessionToken(){return this.getMagicLinkSession()?.sessionToken||null}getTotpDigits(){return this.totpDigits??6}async getAvailableMethods(){try{return await this.twoFactorApi.getAvailableMethods()}catch(e){this.emitErrorAndThrow(e,`2fa.methods.available`,`Get available 2FA methods`)}}async getRegisteredMethods(e){try{return await this.twoFactorApi.getRegisteredMethods(e)}catch(e){this.emitErrorAndThrow(e,`2fa.methods.registered`,`Get registered 2FA methods`)}}async startRecoveryCodesByCode(e){try{return await this.twoFactorApi.startRecoveryCodesByCode(e)}catch(e){this.emitErrorAndThrow(e,`2fa.recovery-codes.start`,`Start recovery codes by code`)}}async completeRecoveryCodesByCode(e,t){try{return await this.twoFactorApi.completeRecoveryCodesByCode(e,t)}catch(e){this.emitErrorAndThrow(e,`2fa.recovery-codes.complete`,`Complete recovery codes by code`)}}async startMethodSetup(e,t){try{let n=await this.twoFactorApi.startMethodSetup(e,t);return this.subscribeStore.notify(G.TwoFactorSetupStarted,{secret:``,method:e}),n}catch(e){this.emitErrorAndThrow(e,`2fa.method.setup.start`,`Start 2FA method setup`)}}async completeMethodSetup(e,t){try{let n=await this.twoFactorApi.completeMethodSetup(e,t);return this.subscribeStore.notify(G.TwoFactorEnabled,{recoveryCodes:[],clearRecoveryCodes:()=>{}}),n}catch(e){this.emitErrorAndThrow(e,`2fa.method.setup.complete`,`Complete 2FA method setup`)}}async removeMethod(e){try{await this.twoFactorApi.removeMethod(e)}catch(e){this.emitErrorAndThrow(e,`2fa.method.remove`,`Remove 2FA method`)}}async requestChallenge(e){try{let t=await this.twoFactorApi.requestChallenge(e,this.pendingTfaToken());return this.storeTotpDigits(t.totp_digits),this.subscribeStore.notify(G.TwoFactorChallengeReceived,{challengeId:t.challenge_id,method:t.method,alternativeMethods:t.alternative_methods??[]}),t}catch(e){this.emitErrorAndThrow(e,`2fa.challenge.request`,`Request 2FA challenge`)}}async verifyV2(e){try{let t=await this.twoFactorApi.verifyV2(e,this.pendingTfaToken()),n=await this.finishSignIn(t);return this.subscribeStore.notify(G.TwoFactorVerified,{tokens:{access_token:n.access_token,refresh_token:n.refresh_token}}),await this.signInCompleter?.notifySignedIn(n),n}catch(e){this.emitErrorAndThrow(e,`2fa.challenge.verify`,`Verify 2FA challenge`)}}async switchToAlternative(e){try{let t=await this.twoFactorApi.switchToAlternative(e,this.pendingTfaToken());return this.storeTotpDigits(t.totp_digits),this.subscribeStore.notify(G.TwoFactorMethodSwitched,{challengeId:t.challenge_id,method:t.method,alternativeMethods:t.alternative_methods??[]}),t}catch(e){this.emitErrorAndThrow(e,`2fa.method.switch`,`Switch to alternative 2FA method`)}}async getTrustedDevices(){try{return await this.twoFactorApi.getTrustedDevices()}catch(e){this.emitErrorAndThrow(e,`2fa.trusted-devices.list`,`Get trusted devices`)}}async revokeTrustedDevice(e){try{await this.twoFactorApi.revokeTrustedDevice(e)}catch(e){this.emitErrorAndThrow(e,`2fa.trusted-devices.revoke`,`Revoke trusted device`)}}async getPreferredMethod(){try{return await this.twoFactorApi.getPreferredMethod()}catch(e){this.emitErrorAndThrow(e,`2fa.preferred-method.read`,`Get preferred 2FA method`)}}async setPreferredMethod(e){try{return await this.twoFactorApi.setPreferredMethod(e)}catch(e){this.emitErrorAndThrow(e,`2fa.preferred-method.set`,`Set preferred 2FA method`)}}async clearPreferredMethod(){try{await this.twoFactorApi.clearPreferredMethod()}catch(e){this.emitErrorAndThrow(e,`2fa.preferred-method.clear`,`Clear preferred 2FA method`)}}},mo=class{constructor(e,t,n=ye){this.userAPI=e,this.deviceService=t,this.platform=n}getUserPasskeys(){return this.userAPI.getUserPasskeys()}renameUserPasskey(e,t){return this.userAPI.renameUserPasskey(e,t)}deleteUserPasskey(e){return this.userAPI.deleteUserPasskey(e)}async addUserPasskey({relyingPartyId:e,passkeyUsername:t,passkeyDisplayName:n}={}){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);let r=this.deviceService.getDeviceId(),i=Ct(this.platform.getDeviceType()),{challenge_id:a,publicKey:o}=await this.userAPI.addUserPasskeyStart({relyingPartyId:(e||this.platform.getCurrentUrl()?.hostname)??``,deviceId:r,os:i,passkeyDisplayName:n,passkeyUsername:t});o.user.id=this.platform.btoa(o.user.id);let s=await this.platform.passkeys.startRegistration(o);if(!s)throw Error(`Passkey registration was not completed`);return await this.userAPI.addUserPasskeyComplete(s,r,a)}async listSessions(){return(await this.userAPI.getUserSessions()).sessions}revokeSession(e){return this.userAPI.revokeUserSession(e)}signOutOtherSessions(){return this.userAPI.revokeOtherUserSessions()}requestAddressChangeProof(e){return this.userAPI.requestAddressChangeProof(e)}updateProfile(e,t){return this.userAPI.updateProfile(e,t)}},ho=class extends Error{constructor(e,t,n=!1){super(t),this.name=`UpgradeFactorError`,this.factor=e,this.cancelled=n}},go=(e,t)=>{let n=t?.trim();if(!n)throw new ho(e,`A verification code is required`);return n},_o={type:`totp`,requiresPrepare:!1,input:`code`,assert:async({code:e})=>({code:go(`totp`,e)})},vo={type:`recovery_codes`,requiresPrepare:!1,input:`code`,assert:async({code:e})=>({code:go(`recovery_codes`,e)})},yo={type:`passkey`,requiresPrepare:!0,input:`none`,assert:async({prepared:e,platform:t})=>{if(!e?.webauthn)throw new ho(`passkey`,`The upgrade challenge carried no WebAuthn options`);let n=t.passkeys;if(!n)throw new ho(`passkey`,`This platform does not support passkeys`);let r;try{r=await n.startAuthentication(e.webauthn)}catch(e){throw new ho(`passkey`,e?.message||`Passkey verification was cancelled`,!0)}if(!r)throw new ho(`passkey`,`Passkey verification was cancelled`,!0);return{challenge_id:e.challengeId,credential:r}}},bo=Object.freeze([_o,yo,vo]),xo=(e=bo)=>new Map(e.map(e=>[e.type,e])),So=3,Co={totp:0,passkey:1,email_otp:2,sms_otp:3,recovery_codes:9},wo=e=>e.requiredLevel??we(e.acrValues),To=(e,t)=>{let n=Co[e.type]??5,r=t!==void 0&&t>=So,i=e.type===`passkey`;return(r&&!i?100:0)+n},Eo=(e,t)=>{if(t.availableFactors)return t.availableFactors.flatMap(t=>e.find(e=>e.type===t)??[]);let n=wo(t);return[...e].sort((e,t)=>To(e,n)-To(t,n))},Do=class extends Error{constructor(e){super(`Upgrade authentication was cancelled`),this.code=`upgrade_cancelled`,this.name=`UpgradeCancelledError`,e!==void 0&&(this.cause=e)}},Oo=class extends Error{constructor(e=`Only a fresh sign-in can meet this challenge`){super(e),this.code=`upgrade_sign_in_required`,this.name=`UpgradeSignInRequiredError`}},ko=e=>e?.signInRequired===!0||e?.signInRequired===void 0&&e?.availableFactors?.length===0,Ao=e=>e?.signInRequired===!1&&e.availableFactors?.length===0,jo=`This account has no factor that reaches the required level (it may need a device-bound passkey)`,Mo=e=>{if(ko(e))return new Oo;if(Ao(e))return new No(jo)},No=class extends Error{constructor(e=`No available authentication factor can satisfy this challenge`){super(e),this.code=`upgrade_unsatisfiable`,this.name=`UpgradeUnsatisfiableError`}},Po=4,Fo=3e4,Io=()=>{let e=()=>void 0,t=()=>void 0;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},Lo=e=>({acrValues:e.acrValues,level:e.requiredLevel,maxAge:e.maxAge}),Ro=(e,t)=>t.level===void 0||e.level!==void 0&&e.level>=t.level,zo=(e,t)=>{let n=e.requiredLevel===void 0?t.requiredLevel:t.requiredLevel===void 0?e.requiredLevel:Math.max(e.requiredLevel,t.requiredLevel),r=n===void 0?e.acrValues??t.acrValues:n===e.requiredLevel?e.acrValues:t.acrValues,i=e.maxAge===void 0?t.maxAge:t.maxAge===void 0?e.maxAge:Math.min(e.maxAge,t.maxAge),a=Array.from(new Set([...e.channels??[],...t.channels??[]])),{availableFactors:o,signInRequired:s}=Bo(t,e)&&!Bo(e,t)||!t.availableFactors?e:t;return{acrValues:r,requiredLevel:n,maxAge:i,status:e.status,...a.length>0?{channels:a}:{},...o?{availableFactors:o}:{},...s===void 0?{}:{signInRequired:s}}},Bo=(e,t)=>{let n=t.requiredLevel!==void 0&&(e.requiredLevel===void 0||t.requiredLevel>e.requiredLevel),r=t.maxAge!==void 0&&(e.maxAge===void 0||t.maxAge<e.maxAge);return n||r},Vo=class{constructor(e){this.state=`idle`,this.inFlight=null,this.requirement=null,this.selected=null,this.rankedRequirement=null,this.registrations=[],this.proof=null,this.pruned=new Set,this.openPrompt=null,this.transport=e.transport,this.prompt=e.prompt,this.platform=e.platform,this.available=e.factors??bo,this.registry=xo(this.available),this.maxAttempts=e.maxAttempts??Po,this.readObtainedBar=e.readObtainedBar,this.onFlightSettled=e.onFlightSettled,this.settleTimeoutMs=e.replaySettleTimeoutMs??Fo}get currentState(){return this.state}get active(){return this.inFlight!==null}elevate(e,t={kind:`imperative`}){let n=this.register(e,t);if(this.state===`idle`)this.state=`collecting`,this.requirement=e,this.inFlight=this.runFlight();else{this.join(e);let t=this.proof;t?.status===`proven`?this.release(n,t.obtained):t?.status===`failed`&&(this.receiveReport(n,{outcome:`failed`}),n.settlement.reject(t.reason))}return n.settlement.promise}register(e,t){let n=t.kind===`imperative`&&t.requested!==void 0,r={demanded:t.kind===`imperative`&&t.requested?t.requested:Lo(e),statedBar:n,settlement:Io(),reported:!1,entry:{...t,outcome:`pending`,report:e=>this.receiveReport(r,e)}};return this.registrations.push(r),r}join(e){let t=this.requirement;if(!t){this.requirement=e;return}let n=Bo(t,e);this.requirement=zo(t,e),Mo(this.requirement)?this.state===`collecting`&&this.selected===null&&(this.openPrompt?.onClosed?.(),this.closeOpenPrompt?.()):n&&this.state===`collecting`&&this.selected===null&&this.openPrompt?.onRequirementRaised?.({challenge:this.requirement,factors:this.offeredFactors()})}offeredFactors(){let e=this.available.filter(e=>!this.pruned.has(e.type)),t=this.requirement;return t?Eo(e,t):e}receiveReport(e,t){e.reported||(e.reported=!0,e.entry.outcome=t.outcome,t.obtained&&(e.entry.obtained=t.obtained),t.required&&(e.entry.required=t.required),this.notifyReportsSettled())}notifyReportsSettled(){if(!this.reportsSettled||this.registrations.some(e=>!e.reported))return;let e=this.reportsSettled;this.reportsSettled=void 0,e()}async runFlight(){let e;try{e=await this.prove()}catch(t){e={status:`failed`,reason:t instanceof Error?t:Error(String(t))}}if(this.proof=e,e.status===`failed`)for(let t of this.registrations)this.receiveReport(t,{outcome:`failed`}),t.settlement.reject(e.reason);else{this.state=`replaying`;for(let t of this.registrations)this.release(t,e.obtained);await this.awaitReports()}this.state=`settling`;let t=this.summarise(e);try{this.onFlightSettled?.(t)}catch{}this.state=`done`,this.inFlight=null,this.requirement=null,this.selected=null,this.rankedRequirement=null,this.registrations=[],this.proof=null,this.pruned=new Set,this.openPrompt=null,this.reportsSettled=void 0,this.state=`idle`}release(e,t){if(e.entry.kind===`imperative`){if(e.statedBar&&!Ro(t,e.demanded)){this.receiveReport(e,{outcome:`insufficient`,obtained:t,required:e.demanded}),e.settlement.reject(new Ma(t,e.demanded));return}this.receiveReport(e,{outcome:`replayed`,obtained:t}),e.settlement.resolve({waiter:e.entry,obtained:t})}else e.settlement.resolve({waiter:e.entry,obtained:t})}awaitReports(){return this.registrations.some(e=>!e.reported)?new Promise(e=>{let t=setTimeout(()=>{this.reportsSettled=void 0;for(let e of this.registrations)e.reported||(e.reported=!0,e.entry.outcome=`failed`);e()},this.settleTimeoutMs);this.reportsSettled=()=>{clearTimeout(t),e()}}):Promise.resolve()}summarise(e){let t=this.registrations.map(e=>({...e.entry.kind===`request`?{url:e.entry.url,method:e.entry.method}:{},outcome:e.entry.outcome,...e.entry.obtained?{obtained:e.entry.obtained}:{},...e.entry.required?{required:e.entry.required}:{}}));if(e.status===`failed`)return{proof:e,waiters:t,terminal:`failed`,error:e.reason};let n;for(let e of t){if(e.outcome!==`insufficient`)continue;let t=e.required?.level??0;(!n||t>(n.required?.level??0))&&(n=e)}return n?{proof:e,waiters:t,terminal:`insufficient`,insufficient:{obtained:n.obtained??e.obtained,required:n.required??{}}}:t.some(e=>e.outcome===`failed`||e.outcome===`pending`)?{proof:e,waiters:t,terminal:`failed`}:{proof:e,waiters:t,terminal:`success`}}async prove(){let e;for(let t=0;t<this.maxAttempts;t++){let t=Mo(this.requirement);if(t)return{status:`failed`,reason:t};let n=this.offeredFactors();if(n.length===0)return{status:`failed`,reason:new No};let r=this.requirement,i;try{i=await this.collect(r,n,e)}catch(e){return{status:`failed`,reason:new Do(e)}}let a=Mo(this.requirement);if(a)return{status:`failed`,reason:a};if(i.type===`cancel`)return{status:`failed`,reason:new Do};let o=this.registry.get(i.factor);if(!o)e=new No(`Unknown authentication factor: ${i.factor}`),this.state=`collecting`,this.selected=null;else try{return await this.proveAndCommit(o,i.code),{status:`proven`,obtained:this.readObtainedBar?.()??Lo(this.rankedRequirement??r)}}catch(t){if(t instanceof ho&&t.cancelled)return{status:`failed`,reason:new Do};let n=this.classifyProofFailure(t);if(n)return{status:`failed`,reason:n};t instanceof $&&t.kind===`not_registered`&&this.pruned.add(o.type),e=t,this.state=`collecting`,this.selected=null}}return{status:`failed`,reason:new $({kind:`attempts_exhausted`,...e?{cause:e}:{}})}}collect(e,t,n){let r={challenge:e,factors:t,...n?{previousError:n}:{},onFactorSelected:e=>{this.state===`collecting`&&(this.state=`proving`),this.selected=e,this.rankedRequirement=this.requirement}};this.openPrompt=r;let i=new Promise(e=>{this.closeOpenPrompt=()=>e({type:`cancel`})});return Promise.race([this.prompt(r),i]).finally(()=>{this.closeOpenPrompt=void 0})}classifyProofFailure(e){if(e instanceof Ma||e instanceof Na||e instanceof Pa)return e;if(e instanceof $)switch(e.kind){case`unavailable`:return new Na(e.message);case`exhausted`:case`attempts_exhausted`:case`rate_limited`:case`fatal`:case`protocol`:case`network`:return e;case`session_changed`:return new Pa(e.message);default:return}}async proveAndCommit(e,t){let n=e.requiresPrepare?await this.transport.prepare(e.type):void 0,r=await e.assert({code:t,prepared:n,platform:this.platform});await this.transport.commit(e.type,r)}},Ho=e=>typeof e==`function`?e():e,Uo=e=>{try{return new URL(e)}catch{return}},Wo=(e,t)=>{if(!t||t===`/`)return!0;let n=t.replace(/\/+$/,``);return e===n||e.startsWith(`${n}/`)},Go=(e,t)=>!t||e.origin===void 0?!1:e.origin===t.origin&&Wo(e.pathname,t.pathPrefix),Ko=(e,t)=>{for(let n of t){if(n===``)continue;if(n.startsWith(`/`)){if(e.relativeToBase&&Wo(e.pathname,n))return!0;continue}let t=Uo(n)??Uo(`https://${n}`);if(t&&e.origin!==void 0&&e.origin===t.origin&&Wo(e.pathname,t.pathname))return!0}return!1},qo=(e,t,n)=>Go(e,t.passflow)||Ko(e,t.backend)?!n||n(e.href)!==!1:!1,Jo=e=>{let t=e.detail,n=t?.message??`[passflow] upgrade challenge not actioned: ${e.reason}`;console.warn(n,{status:e.status,url:e.url,reason:e.reason,detail:t})},Yo=(e,t)=>{let n=t.onUpgradeDiagnostic??Jo;return(t,r)=>{n({status:e.status,url:e.request.href,reason:t,detail:{method:e.request.method,...r??{}}})}},Xo=(e,t,n)=>{let r=n.onUpgradeDiagnostic??Jo;for(let n of e)r({...n,url:t.request.href,detail:{method:t.request.method,...n.detail??{}}})},Zo=/\bjson\b/i,Qo=async(e,t)=>{let n=t.requireChallengeChannel===`header`,r=e.getHeader(`content-type`)??``,i=!n&&Zo.test(r),a;if(i)try{a=await e.readBody()}catch{a=void 0}return Ie(i?{status:e.status,getHeader:t=>e.getHeader(t)??void 0,body:a}:{status:e.status,getHeader:t=>e.getHeader(t)??void 0},{requireChallengeChannel:t.requireChallengeChannel})},$o=e=>Ie({status:e.status,getHeader:t=>e.getHeader(t)??void 0},{requireChallengeChannel:`header`}).challenge,es=(e,t)=>t.passflow===null?`[passflow] a 401/403 from ${e} carried an upgrade challenge, but no Passflow endpoint is configured — set \`url\` on the Passflow config.`:`[passflow] a 401/403 from ${e} carried an upgrade challenge, but that URL is not covered by the provider's \`backend\` prop — add it there to enable step-up for this API.`,ts=(e,t)=>e instanceof Do?{kind:`cancelled`}:e instanceof Oo?{kind:`sign-in-required`}:e instanceof No?{kind:`unsatisfiable`,error:e}:e instanceof Na?{kind:`unavailable`}:e instanceof Pa?{kind:`session-changed`}:e instanceof Ma?{kind:`insufficient`,obtained:e.obtained,required:e.required}:e instanceof $?e.kind===`exhausted`||e.kind===`attempts_exhausted`||e.kind===`rate_limited`?{kind:`exhausted`,error:e}:e.kind===`unavailable`?{kind:`unavailable`}:e.kind===`session_changed`?{kind:`session-changed`}:{kind:`transport-failure`,status:e.status,retryable:e.retryable,error:e}:{kind:`transport-failure`,retryable:!1,error:e instanceof Error?e:Error(String(e))},ns=async(e,t,n,r)=>{if(e.status!==401&&e.status!==403)return{kind:`replayed`,response:e};let{challenge:i,diagnostics:a}=await Qo(e,t);if(Xo(a,e,t),!i)return{kind:`replayed`,response:e};if(ko(i))return{kind:`sign-in-required`,response:e};if(Ao(i))return{kind:`unsatisfiable`,error:Mo(i),response:e};let o=Lo(i);return r(`elevated-insufficient`,{obtained:n,required:o}),{kind:`insufficient`,obtained:n,required:o,response:e}},rs=async(e,t)=>{if(!t)return{aborted:!1,value:await e};if(t.aborted)return{aborted:!0,reason:t.reason};if(typeof t.addEventListener!=`function`)return{aborted:!1,value:await e};let n,r=new Promise(e=>{n=()=>e({aborted:!0,reason:t.reason}),t.addEventListener?.(`abort`,n)});try{return await Promise.race([e.then(e=>({aborted:!1,value:e})),r])}finally{n&&t.removeEventListener?.(`abort`,n)}},is=async(e,t)=>{if(e.status!==401&&e.status!==403||e.markers.upgradeTransaction)return{kind:`not-a-challenge`};let n=Yo(e,t);if(e.markers.replayed){if(!qo(e.request,t.scope,t.shouldIntercept))return{kind:`not-a-challenge`};let{challenge:r,diagnostics:i}=await Qo(e,t);if(Xo(i,e,t),!r)return{kind:`not-a-challenge`};let a=t.readObtainedBar?.()??{},o=Lo(r);return n(`elevated-insufficient`,{obtained:a,required:o}),{kind:`insufficient`,obtained:a,required:o,response:e}}if(!qo(e.request,t.scope,t.shouldIntercept))return $o(e)?(n(`challenge-out-of-scope`,{header:e.getHeader(`www-authenticate`)??void 0,message:es(e.request.href,t.scope)}),{kind:`out-of-scope`}):{kind:`not-a-challenge`};let{challenge:r,diagnostics:i}=await Qo(e,t);if(Xo(i,e,t),!r){let r=e.getHeader(`www-authenticate`);return t.requireChallengeChannel!==`header`&&n(`no-channel`,{...r?{header:r}:{},message:e.responseType===`cors`&&!r?`[passflow] a cross-origin ${e.status} from ${e.request.href} carried no readable challenge: \`WWW-Authenticate\` is not CORS-safelisted, so add \`Access-Control-Expose-Headers: WWW-Authenticate\` on that server, or have it emit the \`upgrade_required\` JSON body.`:`[passflow] a ${e.status} from ${e.request.href} carried no upgrade challenge on either channel; treated as an ordinary ${e.status}.`}),{kind:`not-a-challenge`}}if(e.replayable===!1)return n(`replay-unsupported`,{message:`[passflow] a ${e.status} from ${e.request.href} carried an upgrade challenge, but the request cannot be replayed (${e.replayUnsupportedReason??`unsupported body`}), so no prompt was opened.`}),{kind:`replay-unsupported`};let a=t.authorizationSwap?.(),o={kind:`request`,url:e.request.href,method:e.request.method},s,c;try{s=Promise.resolve(t.elevate(r,o)),c=await rs(s,e.signal)}catch(e){return ts(e,void 0)}if(c.aborted)return s?.then(e=>e?.waiter.report({outcome:`failed`}),()=>{}),{kind:`aborted`,reason:c.reason};let l=c.value;if(e.signal?.aborted)return l?.waiter.report({outcome:`failed`}),{kind:`aborted`,reason:e.signal.reason};let u=l?.obtained??t.readObtainedBar?.()??Lo(r),d=t.authorizationSwap?.(),f=d?{from:a?.from??d.from,to:d.to}:void 0;e.markers.replayed=!0;let p;try{p=await e.replay(f?{authorizationSwap:f}:void 0)}catch(t){if(t instanceof Ma)return l?.waiter.report({outcome:`insufficient`,obtained:t.obtained,required:t.required}),e.signal?.aborted?{kind:`aborted`,reason:e.signal.reason}:{kind:`insufficient`,obtained:t.obtained,required:t.required};if(l?.waiter.report({outcome:`failed`}),e.signal?.aborted)return{kind:`aborted`,reason:e.signal.reason};throw t}let m=await ns(p,t,u,n);return m.kind===`insufficient`?l?.waiter.report({outcome:`insufficient`,obtained:m.obtained,required:m.required}):l?.waiter.report({outcome:`replayed`,obtained:u}),m},as=e=>{switch(e.kind){case`cancelled`:return new Do;case`unsatisfiable`:return e.error??new No;case`sign-in-required`:return new Oo;case`unavailable`:return new Na;case`session-changed`:return new Pa;case`insufficient`:return new Ma(e.obtained,e.required);case`exhausted`:return e.error;case`transport-failure`:return e.error;default:return}},os=(e,t,n)=>{switch(e.kind){case`replayed`:return{settle:`resolve`,value:e.response.raw};case`not-a-challenge`:case`out-of-scope`:case`replay-unsupported`:return{settle:`resolve`,value:t};case`aborted`:return{settle:`reject`,error:e.reason};case`cancelled`:return n.onCancel===`reject`?{settle:`reject`,error:new Do}:{settle:`resolve`,value:gs(t,e)};case`unsatisfiable`:case`sign-in-required`:return{settle:`resolve`,value:gs(e.response?.raw??t,e)};case`insufficient`:return{settle:`resolve`,value:gs(e.response?.raw??t,e)};default:return{settle:`resolve`,value:gs(t,e)}}},ss=(e,t)=>{switch(e.kind){case`replayed`:return e.response.rejected?{settle:`reject`,error:e.response.raw??t}:{settle:`resolve`,value:e.response.raw};case`aborted`:return{settle:`reject`,error:e.reason};default:return{settle:`reject`,error:as(e)??t}}},cs=new WeakSet,ls=new WeakSet,us=new WeakSet,ds=new WeakSet,fs=new WeakSet,ps=new WeakSet,ms=new WeakSet,hs=new WeakSet,gs=(e,t)=>{switch(t.kind){case`cancelled`:cs.add(e);break;case`exhausted`:ls.add(e);break;case`insufficient`:us.add(e);break;case`unsatisfiable`:ds.add(e);break;case`sign-in-required`:fs.add(e);break;case`unavailable`:ps.add(e);break;case`session-changed`:ms.add(e);break;case`transport-failure`:hs.add(e)}return e},_s=e=>cs.has(e),vs=e=>ls.has(e),ys=e=>us.has(e),bs=e=>ds.has(e),xs=e=>fs.has(e),Ss=e=>ps.has(e),Cs=e=>ms.has(e),ws=e=>hs.has(e),Ts=`https://passflow-relative.invalid`,Es=()=>{let e=globalThis,t=e.document?.baseURI;if(typeof t==`string`&&t!==``)return t;let n=e.location?.href;return typeof n==`string`&&n!==``&&n!==`about:blank`?n:Ts},Ds=(e,t=Es())=>{let n=t===Ts,r;try{r=new URL(t).origin}catch{r=void 0}let i;try{i=new URL(e,t)}catch{i=void 0}return i?{href:i.href,origin:i.origin,pathname:i.pathname,resolved:!0,relativeToBase:r!==void 0&&i.origin===r,sentinelBase:n}:{href:e,pathname:e.split(/[?#]/)[0]??e,resolved:!1,relativeToBase:!1,sentinelBase:n}},Os=(e,t)=>typeof t==`string`?[e.toLowerCase(),t]:void 0,ks=e=>{let t=[];if(e==null)return Object.freeze(t);let n=e;if(typeof n.forEach==`function`&&typeof n.entries==`function`)return e.forEach((e,n)=>{let r=Os(n,e);r&&t.push(r)}),Object.freeze(t);if(Array.isArray(e)){for(let n of e)if(Array.isArray(n)&&n.length>=2){let e=Os(String(n[0]),n[1]);e&&t.push(e)}return Object.freeze(t)}if(typeof e==`object`)for(let[n,r]of Object.entries(e)){let e=Os(n,Array.isArray(r)?r.join(`, `):r);e&&t.push(e)}return Object.freeze(t)},As=e=>{let t=e.base===void 0?Ds(e.url):Ds(e.url,e.base),n={raw:e.url,href:t.href,dispatchUrl:t.sentinelBase||!t.resolved?e.url:t.href,...t.origin===void 0?{}:{origin:t.origin},pathname:t.pathname,resolved:t.resolved,relativeToBase:t.relativeToBase,method:(e.method??`GET`).toUpperCase(),headers:ks(e.headers),bodyKind:e.bodyKind,...`body`in e?{body:e.body}:{}};return Object.freeze(n)},js=(e,t)=>{if(!t||t.from===t.to)return e;let n=!1,r=e.map(([e,r])=>e===`authorization`&&r===t.from?(n=!0,[e,t.to]):[e,r]);return n?Object.freeze(r):e},Ms=e=>{let t={};for(let[n,r]of e)t[n]=r;return t},Ns=new Set([`GET`,`HEAD`,`OPTIONS`]),Ps=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.clone==`function`&&`method`in e,Fs=e=>typeof e==`string`?e:Ps(e)?e.url:String(e),Is=(e,t)=>(t?.method??(Ps(e)?e.method:void 0)??`GET`).toUpperCase(),Ls=e=>e==null?`none`:typeof e==`string`?`reusable`:typeof e.getReader==`function`?`one-shot`:`reusable`,Rs=e=>{if(typeof e==`string`)return e.length;let t=e;if(typeof t?.size==`number`)return t.size;if(typeof t?.byteLength==`number`)return t.byteLength},zs=(e,t,n)=>e===void 0||e===`always`?!0:e===`idempotent-only`?Ns.has(t.method):typeof e==`function`?e(t):!(e.maxBodyBytes!==void 0&&n!==void 0&&n>e.maxBodyBytes),Bs=(e,t,n,r,i)=>({replayable:!1,bodyKind:e,reason:t,forwardInput:n,forwardInit:i,snapshot:r,replay:()=>Promise.reject(Error(`This request cannot be replayed: ${t}`))}),Vs=(e,t)=>Ms(js(e.headers,t?.authorizationSwap)),Hs=e=>{if(!e||!(`headers`in e))return e;let{headers:t,...n}=e;return n},Us=(e,t)=>t&&`headers`in t&&t.headers!==void 0?t.headers:Ps(e)?e.headers:void 0,Ws=e=>{if(e===null||typeof e==`string`)return e;if(typeof FormData<`u`&&e instanceof FormData){let t=new FormData;for(let[n,r]of e)t.append(n,r);return t}return typeof URLSearchParams<`u`&&e instanceof URLSearchParams?new URLSearchParams(e):e instanceof ArrayBuffer?e.slice(0):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice():e},Gs=(e,t,n)=>new Request(e,{headers:Vs(t,n)}),Ks=(e,t,n)=>{let r=Fs(e),i=Is(e,t),a=Us(e,t),o=(e,t)=>As({url:r,method:i,headers:a,bodyKind:e,...t===void 0?{}:{body:t}});if(Ps(e)){if(e.body===null||e.body===void 0){let a=o(`none`);return zs(n,{url:r,method:i,bodyKind:`none`})?{replayable:!0,bodyKind:`none`,forwardInput:e,forwardInit:t,snapshot:a,replay:(n,r)=>n(Gs(e,a,r),Hs(t))}:Bs(`none`,`the replay policy refused this request`,e,a,t)}let a=o(`request-clone`);if(!zs(n,{url:r,method:i,bodyKind:`request-clone`}))return Bs(`request-clone`,`the replay policy refused this request`,e,a,t);let s;try{s=e.clone()}catch{return Bs(`one-shot`,`the Request body was already consumed and cannot be cloned`,e,a,t)}return{replayable:!0,bodyKind:`request-clone`,forwardInput:e,forwardInit:t,snapshot:a,replay:(e,n)=>e(Gs(s,a,n),Hs(t))}}let s=Ls(t?.body);if(s===`one-shot`)return Bs(`one-shot`,`a streaming request body is consumed by the first send`,e,o(`one-shot`),t);if(!zs(n,{url:r,method:i,bodyKind:s},Rs(t?.body)))return Bs(s,`the replay policy refused this request`,e,o(s),t);let c=t&&`body`in t?Ws(t.body??null):void 0,l=o(s,c);return{replayable:!0,bodyKind:s,forwardInput:e,forwardInit:t,snapshot:l,replay:(e,n)=>e(l.dispatchUrl,{...Hs(t),...c===void 0?{}:{body:c},headers:Vs(l,n),method:l.method})}},qs=e=>typeof e==`object`&&!!e,Js=e=>t=>{if(!qs(e))return;let n=e[t]??e[t.toLowerCase()]??(typeof e.get==`function`?e.get(t):void 0);return Array.isArray(n)?n.join(`, `):typeof n==`string`?n:void 0},Ys=e=>{let t=e?.url??``,n=e?.baseURL;return!n||/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:`${n.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`},Xs=e=>(e?.method??`GET`).toUpperCase(),Zs=e=>e==null?`none`:qs(e)&&(typeof e.pipe==`function`||typeof e.getReader==`function`)?`one-shot`:`reusable`,Qs=(e,t,n)=>{let r=Ms(js(t.headers,n?.authorizationSwap)),i=t.dispatchUrl===t.href&&t.resolved;return{...e,...i?{baseURL:void 0}:{},url:t.dispatchUrl,method:t.method,headers:r,...`body`in t?{data:t.body}:{}}},$s=(e,t,n,r,i,a)=>{let o=t??e?.config,s=Zs(o?.data),c=a??As({url:Ys(o),method:Xs(o),headers:o?.headers,bodyKind:s,body:o?.data}),l={url:c.href,method:c.method,bodyKind:s},u=s!==`one-shot`&&zs(i.replay,l);return{status:e?.status??0,getHeader:Js(e?.headers),readBody:async()=>e?.data,request:c,replay:async e=>{let t=Ue(Qs(o??{},c,e));try{let e=await r(t);return $s(e,e?.config??t,e,r,i,c)}catch(e){let n=qs(e)?e:{};if(!n.response||typeof n.response.status!=`number`||Sa(e))throw e;return{...$s(n.response,n.config??t,e,r,i,c),rejected:!0}}},markers:{...He(o)?{upgradeTransaction:!0}:{},...We(o)?{replayed:!0}:{}},raw:n,replayable:u,replayUnsupportedReason:s===`one-shot`?`a streaming request body is consumed by the first send`:`the replay policy refused this request`,signal:o?.signal}},ec=(e,t)=>async n=>{let r=Ho(e),i=qs(n)?n:{},a=ss(await is($s(i.response,i.config,i.response,t,r),r),n);if(a.settle===`reject`)throw a.error;return a.value},tc=(e,t,n)=>{let r=e.request,i=n??(typeof r==`function`?t=>r.call(e,t):()=>Promise.reject(Error(`Passflow: this client exposes no request() to replay through.`))),a=e.interceptors.response.use(void 0,ec(t,i)),o=!1;return()=>{o||(o=!0,e.interceptors.response.eject(a))}},nc=(e,t)=>{let n=c.default.create(e);return t(n),n},rc=()=>{let e=typeof location>`u`?void 0:location.origin;return e&&e!==`null`?e:void 0},ic=e=>{let t=new URL(e).origin;if(t===`null`)throw Error(`Passflow: "${e}" has no origin a request can be matched against; list http(s) origins only.`);return t},ac=(e,t)=>{let n=(t?.origins??[]).map(ic);return(t,r)=>{if(r)return Promise.resolve(void 0);let i=rc(),a;try{a=new URL(t,i).origin}catch{return Promise.resolve(void 0)}return a!==i&&!n.includes(a)?Promise.resolve(void 0):e()}},oc=e=>typeof Request<`u`&&e instanceof Request,sc=(e,t)=>new Headers(t?.headers===void 0?oc(e)?e.headers:void 0:t.headers),cc=(e,t,n)=>{let r=ac(t,n);return async(t,n)=>{let i=oc(t)?t.url:t instanceof URL?t.href:String(t),a=sc(t,n),o=await r(i,a.has(`authorization`));return o?(a.set(`authorization`,`Bearer ${o}`),e(t,{...n,headers:a})):e(t,n)}},lc=e=>{let t=e.url??``,n=/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return!e.baseURL||n&&e.allowAbsoluteUrls!==!1?t:t?`${e.baseURL.replace(/\/?\/$/,``)}/${t.replace(/^\/+/,``)}`:e.baseURL},uc=e=>e?typeof e.has==`function`?e.has(`Authorization`):Object.keys(e).some(t=>t.toLowerCase()===`authorization`&&e[t]!=null):!1,dc=(e,t)=>{let n=ac(e,t);return async e=>{let t=e.headers,r=await n(lc(e),uc(t));if(!r)return e;let i=`Bearer ${r}`;return t&&typeof t.set==`function`?t.set(`Authorization`,i):e.headers={...t??{},Authorization:i},e}},fc=0,pc=(e,t)=>{let n=t?.signal??(typeof e==`object`&&e?e.signal:void 0)??void 0;if(n)return{get aborted(){return n.aborted},get reason(){return n.reason},...typeof n.addEventListener==`function`?{addEventListener:(e,t)=>n.addEventListener(e,t),removeEventListener:(e,t)=>n.removeEventListener(e,t)}:{}}},mc=e=>t=>e.headers?.get(t),hc=(e,t,n,r,i)=>({status:e.status,getHeader:mc(e),readBody:()=>e.clone().json(),request:t.snapshot,replay:async e=>hc(await t.replay(n,e),t,n,r,i),markers:r,raw:e,replayable:t.replayable,replayUnsupportedReason:t.reason,signal:i,responseType:e.type}),gc=(e,t)=>{let n=(t,n)=>{fc+=1;try{return e(t,n)}finally{--fc}};return async(e,r)=>{if(fc>0)return n(e,r);let i=Ho(t),a=Ks(e,r,i.replay),o=await n(a.forwardInput,a.forwardInit),s=os(await is(hc(o,a,n,{},pc(e,r)),i),o,i);if(s.settle===`reject`)throw s.error;return s.value}},_c=new Set(bo.filter(e=>!e.requiresPrepare).map(e=>e.type)),vc=e=>{if(!e||typeof e!=`object`||!e.challenge_id||!e.expires_at)throw new $({kind:`protocol`,message:`The upgrade start response is missing challenge_id or expires_at`});return{challengeId:e.challenge_id,method:e.method,expiresAt:e.expires_at,webauthn:e.webauthn,codeSentTo:e.code_sent_to}},yc=e=>Sa(e)&&!Ca(e),bc=e=>({async prepare(t){if(!_c.has(t))try{let n=e.relyingPartyId?.();return vc(await e.startUpgrade(n?{method:t,relying_party_id:n}:{method:t}))}catch(e){if(yc(e))throw e;let t=ka(e,`start`);if(t.kind===`prepare_not_required`)return;throw t}},async commit(t,n){let r=e.canCommit();if(!r.ok)throw new $({kind:`unavailable`,message:r.reason});try{await e.commitRefresh({type:t,assertion:n})}catch(t){if(yc(t))throw t;let n=ka(t,`refresh`);throw n.status===401&&ja(n)&&e.markSessionInvalid?.(),n}}}),xc=e=>e===void 0?[]:(Array.isArray(e)?e:[e]).filter(e=>e!==``),Sc=e=>{let t,n=e=>e!==void 0&&t===e,r=r=>{let i=()=>{if(!n(r()))throw new $({kind:`session_changed`})};return bc({...e,relyingPartyId:()=>t?.options.relyingPartyId??e.relyingPartyId?.(),startUpgrade:t=>(i(),e.startUpgrade(t)),commitRefresh:t=>(i(),a=Date.now(),e.commitRefresh(t,r()?.pin)),...e.markSessionInvalid?{markSessionInvalid:()=>{n(r())&&e.markSessionInvalid?.()}}:{}})},i=(t,n)=>{let i={},a={controller:new Vo({transport:r(()=>i.current),prompt:t.prompt,platform:e.platform,factors:t.factors??e.factors,...t.maxAttempts===void 0?{}:{maxAttempts:t.maxAttempts},...e.readObtainedBar?{readObtainedBar:e.readObtainedBar}:{},...t.onFlightSettled?{onFlightSettled:t.onFlightSettled}:{}}),options:t,scope:{passflow:e.passflowDomain,backend:xc(t.backend)},generation:n};return i.current=a,a},a,o=1e4,s;e.stopRepeatedElevation?.subscribe(()=>{s=void 0});let c=e=>{if(!s||Bo(s.challenge,e))return;let t=Math.min(o,e.maxAge===void 0?o:e.maxAge*1e3);if(!(Date.now()-s.at>t))return s.challenge},l=async(r,i)=>{let o=t;if(!o)throw new Na(`Step-up verification is not enabled on this Passflow instance`);let l=e.stopRepeatedElevation?c(r):void 0;if(l)throw new Ma(Lo(l),Lo(r),`This requirement was already proved and the server still refused it: sign the user in again`);o.controller.active||(o.pin=e.readSessionPin?.());let u=await o.controller.elevate(r,i);if(!n(o))throw new Pa;return e.stopRepeatedElevation&&(s={challenge:r,at:a??Date.now()}),u},u=()=>{let n=t,r=n?.scope??{passflow:e.passflowDomain,backend:[]},i=n?.options;return{elevate:l,scope:r,...i?.requireChallengeChannel?{requireChallengeChannel:i.requireChallengeChannel}:{},...i?.shouldIntercept?{shouldIntercept:i.shouldIntercept}:{},...i?.replay===void 0?{}:{replay:i.replay},...i?.onCancel?{onCancel:i.onCancel}:{},...e.authorizationSwap?{authorizationSwap:e.authorizationSwap}:{},...i?.onUpgradeDiagnostic?{onUpgradeDiagnostic:i.onUpgradeDiagnostic}:{},...e.readObtainedBar?{readObtainedBar:e.readObtainedBar}:{}}},d;return Object.defineProperties(async e=>{let t=e?.acrValues===void 0?void 0:Ce(e.acrValues).level,n={status:401,...e?.acrValues===void 0?{}:{acrValues:e.acrValues},...t===void 0?{}:{requiredLevel:t},...e?.maxAge===void 0?{}:{maxAge:e.maxAge}},r=e?.acrValues!==void 0||e?.maxAge!==void 0,i={...e?.acrValues===void 0?{}:{acrValues:e.acrValues},...t===void 0?{}:{level:t},...e?.maxAge===void 0?{}:{maxAge:e.maxAge}},a=(await l(n,{kind:`imperative`,...r?{requested:i}:{}})).obtained.acrValues;return{status:`elevated`,...a===void 0?{}:{acr:a}}},{enable:{value:n=>{d?.(),t=i(n,0);let r=[];if(e.attachInternalSeam){let t=e.attachInternalSeam;t(e=>ec(u,e)),r.push(()=>t(void 0))}n.interceptFetch&&r.push(er((e,t,n)=>gc(e,u)(t,n),{priority:20,name:`passflow-upgrade`})),e.onSessionChange&&r.push(e.onSessionChange(()=>{let e=t;e&&(t=i(e.options,e.generation+1))}));let a=!1;return d=()=>{if(!a){a=!0;for(let e of r)e();t=void 0,d=void 0}},d},enumerable:!0},enabled:{enumerable:!0,get(){return t!==void 0&&e.canCommit().ok}},elevate:{enumerable:!0,value:(e,t)=>l(e,t??{kind:`imperative`})},withAuth:{enumerable:!0,value:(t,n)=>{let r=t=>{let r=gc(t,u);return e.readAccessToken?cc(r,e.readAccessToken,n):r};if(t)return r(t);let i=typeof globalThis>`u`?void 0:globalThis;if(!i||typeof i.fetch!=`function`)throw Error(`Passflow: withAuth() needs a fetch to wrap — this runtime has none.`);return r(i.fetch.bind(i))}},attachAuth:{enumerable:!0,value:(t,n)=>{let r=e.readAccessToken?t.interceptors.request:void 0,i=r?.use(dc(e.readAccessToken,n)),a=tc(t,u);return()=>{a(),r&&i!==void 0&&r.eject(i)}}}})},Cc,wc=class{get origin(){return this.platform.getCurrentUrl()?.origin??``}constructor(e){this.doRefreshTokens=!1,this.session=async({createSession:e,expiredSession:t,doRefresh:n=!1})=>{this.createSessionCallback=e,this.expiredSessionCallback=t,this.doRefreshTokens=n,await this.submitSessionCheck()};let{url:t,appId:n,scopes:r}=e;this.url=t||`https://auth.passflow.cloud`,this.appId=n,this.platform=e.platform??ye,this.deferFederatedLanding=e.deferFederatedLanding??!1,this.storageManager=new he({prefix:e.keyStoragePrefix??``,storage:this.platform.storage,appId:n}),this.deviceService=new ge(this.storageManager),this.authApi=new ln(e,this.storageManager,this.deviceService),this.appApi=new en(e,this.storageManager,this.deviceService),this.userApi=new bn(e,this.storageManager,this.deviceService),this.settingApi=new fn(e,this.storageManager,this.deviceService),this.tenantApi=new pn(e,this.storageManager,this.deviceService),this.invitationApi=new dn(e,this.storageManager,this.deviceService),this.twoFactorApi=new vn(e,this.storageManager,this.deviceService),this.upgradeApi=new yn(e,this.storageManager,this.deviceService),this.upgradeDomain=qe(e.url),this.subscribeStore=new Fr,this.tokenCacheService=new fo(this.storageManager,this.authApi,this.subscribeStore,this.platform),this.scopes=r??w,this.createTenantForNewUser=e.createTenantForNewUser??!1;let i=ki(e.refreshCoordination,this.platform,e.keyStoragePrefix,{tokenKeys:()=>this.storageManager.tokenKeys()}),a=e.deviceKey===!0&&!e.tokenExchange?.enabled?Rn({dbName:Fn(e.keyStoragePrefix),deviceId:()=>this.deviceService.getDeviceId()}):void 0;this.authService=new so(this.authApi,this.deviceService,this.storageManager,this.subscribeStore,this.tokenCacheService,this.scopes,this.createTenantForNewUser,this.url,{createSession:async e=>{await this.createSessionCallback?.(e)},expiredSession:async()=>{await this.expiredSessionCallback?.()}},this.appId??``,e.tokenExchange,this.platform,()=>this.readPkceEnabled(),{coordination:i,...e.refreshStrikes===void 0?{}:{strikes:e.refreshStrikes},...a?{deviceKey:a,enrolDeviceKeyRequest:e=>this.userApi.enrolDeviceKey(e)}:{}},()=>this.readAppSettings()),this.antiBot=Zr({readSettings:()=>this.readAppSettings(),fetchChallenge:({identifier:e,device:t})=>t?this.authApi.deviceAntiBotChallenge({user_code:t.userCode,...e?{identifier:e}:{}},t.csrfToken):this.authApi.antiBotChallenge(e?{identifier:e}:{}),store:this.subscribeStore,...e.antiBotWorkerUrl?{workerUrl:e.antiBotWorkerUrl}:{}}),this.authApi.setAntiBotHandler(e=>this.antiBot.headerFor(e)),this.tokenCacheService.attachRefreshController(this.authService.refresh);for(let e of this.axiosClients())e.setRefreshHandler(e=>this.authService.refresh.ensureFresh(e));this.userService=new mo(this.userApi,this.deviceService,this.platform),this.tenantService=new uo(this.tenantApi,this.scopes),this.tenant=this.tenantService,this.invitationService=new co(this.invitationApi),this.twoFactorService=new po(this.twoFactorApi,this.subscribeStore,this.authService),this.twoFactor=this.twoFactorService,this.upgrade=Sc({startUpgrade:e=>this.upgradeApi.startUpgrade(e),commitRefresh:async(e,t)=>{await this.authService.refreshToken(e,t)},readSessionPin:()=>this.authService.readSessionPin(),canCommit:()=>this.authService.tokenDeliveryManager.isBFFMode()?{ok:!1,reason:`Step-up verification cannot be committed through a BFF refresh endpoint`}:{ok:!0},markSessionInvalid:()=>this.authService.tokenDeliveryManager.setSessionInvalid(),platform:this.platform,passflowDomain:this.upgradeDomain,...e.upgrade?.factors?{factors:e.upgrade.factors}:{},...e.upgrade?.relyingPartyId?{relyingPartyId:()=>e.upgrade?.relyingPartyId}:{},readObtainedBar:()=>this.readAssuranceBar(),authorizationSwap:()=>{let e=this.storageManager.getToken(F.access_token);return e?{from:`Bearer ${e}`,to:`Bearer ${e}`}:void 0},attachInternalSeam:e=>this.attachUpgradeSeam(e),onSessionChange:e=>this.subscribeToSessionChange(e),readAccessToken:async()=>{let e=(await this.getTokens(!0))?.access_token;return e&&!N(P(e))?e:void 0}}),this.hostedUpgrade=Sc({startUpgrade:e=>this.upgradeApi.startHostedUpgrade(e),commitRefresh:e=>this.upgradeApi.commitHostedUpgrade(e),canCommit:()=>({ok:!0}),readSessionPin:()=>void 0,readObtainedBar:()=>void 0,stopRepeatedElevation:{subscribe:e=>this.subscribeToSessionChange(e)},markSessionInvalid:()=>{},platform:this.platform,passflowDomain:this.upgradeDomain,...e.upgrade?.factors?{factors:e.upgrade.factors}:{},...e.upgrade?.relyingPartyId?{relyingPartyId:()=>e.upgrade?.relyingPartyId}:{}}),e.parseQueryParams&&this.checkAndSetTokens(),this.setTokensToCacheFromLocalStorage()}readAppSettings(){if(!this.appId)return Promise.resolve(void 0);if(!this.appSettingsRead){let e=this.appApi.getAppSettings();this.appSettingsRead=e,e.catch(()=>{this.appSettingsRead===e&&(this.appSettingsRead=void 0)})}return this.appSettingsRead}readPkceEnabled(){return this.readAppSettings().then(e=>e?.pkce_enabled??!1)}setAppId(e){e!==this.appId&&(this.appId=e,this.storageManager.setAppId(e),this.appSettingsRead=void 0,this.authApi.setAppId(e),this.appApi.setAppId(e),this.userApi.setAppId(e),this.settingApi.setAppId(e),this.tenantApi.setAppId(e),this.invitationApi.setAppId(e),this.twoFactorApi.setAppId(e),this.upgradeApi.setAppId(e),this.authService.setAppId(e),this.tokenCacheService.setTokensCache(void 0),this.setTokensToCacheFromLocalStorage())}withAuth(e,t){return this.upgrade.withAuth(e,t)}attachAuth(e,t){return this.upgrade.attachAuth(e,t)}createClient(e,t){return nc(e,e=>this.upgrade.attachAuth(e,t))}readAssuranceBar(){let e=this.storageManager.getToken(F.access_token);if(e)try{let t=P(e),n=typeof t.acr==`string`?t.acr:void 0;if(!n)return;let r=Ce(n).level;return r===void 0?{acrValues:n}:{acrValues:n,level:r}}catch{return}}axiosClients(){return[this.authApi.axiosClient,this.appApi.axiosClient,this.userApi.axiosClient,this.settingApi.axiosClient,this.tenantApi.axiosClient,this.invitationApi.axiosClient,this.twoFactorApi.axiosClient,this.upgradeApi.axiosClient]}attachUpgradeSeam(e){for(let t of this.axiosClients()){if(!e){t.setUpgradeInterceptor(void 0);continue}let n=e(e=>t.replay(e));t.setUpgradeInterceptor(n)}}subscribeToSessionChange(e){let t={onAuthChange:()=>e()};return this.subscribeStore.subscribe(t,[G.SignIn,G.SignOut]),()=>this.subscribeStore.unsubscribe(t)}async submitSessionCheck(){let e,t;try{e=await this.authService.getTokens(this.doRefreshTokens),t=this.tokenCacheService.getParsedTokens()}catch(t){let n={operation:`session.check`,message:t instanceof Error||t instanceof B?t.message:`Session check failed`,originalError:t};W(this.subscribeStore,n),e=void 0}e&&this.createSessionCallback&&await this.createSessionCallback({tokens:e,parsedTokens:t}),!e&&this.expiredSessionCallback&&await this.expiredSessionCallback()}subscribe(e,t){this.subscribeStore.subscribe(e,t),this.tokenCacheService.initialize()}unsubscribe(e,t){this.subscribeStore.unsubscribe(e,t)}handleTokensRedirect(){this.checkAndSetTokens()}completeFederatedLanding(){return this.takeFederatedLanding()||this.takeOidcLanding()}checkAndSetTokens(){let e=this.platform.getCurrentUrl(),t=new URLSearchParams(e?.search??``);if(!t.get(`access_token`)&&e?.hash){let n=new URLSearchParams(e.hash.substring(1));n.get(`access_token`)&&(t=n)}if(!t.get(`access_token`)&&this.adoptTwoFactorTokenFromUrl(e)){this.error=void 0;return}let n=t.get(`access_token`),r=t.get(`refresh_token`),i=t.get(`id_token`),a=t.get(`state`)??void 0,o=t.get(`scopes`)?.split(`,`)??this.scopes;if(n){if(!La(n)){W(this.subscribeStore,{operation:`tokens.from-url`,message:`Invalid access token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(e);return}if(r&&!La(r)){W(this.subscribeStore,{operation:`tokens.from-url`,message:`Invalid refresh token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(e);return}if(i&&!La(i)){W(this.subscribeStore,{operation:`tokens.from-url`,message:`Invalid ID token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(e);return}let t={access_token:n,refresh_token:r??void 0,id_token:i??void 0,scopes:o};this.cleanupUrlParams(e),this.error=void 0,this.readAppSettings().catch(()=>void 0).then(e=>{if(e?.pkce_enabled!==!1)throw xr();return ha(this.url,this.appId,t)}).then(()=>{this.storageManager.clearDeliveryMode(),this.storageManager.saveTokens(t,void 0,{replace:!0}),e&&this.storageManager.setHostedSignIn(e.origin+e.pathname),this.tokenCacheService.setTokensCache(t),this.authService.refresh.sessionStarted()}).then(()=>(this.subscribeStore.notify(G.SignIn,{tokens:t,parsedTokens:this.getParsedTokens(),source:`tokens-in-url`,...a?{state:a}:{}}),this.submitSessionCheck()),e=>W(this.subscribeStore,{operation:`tokens.from-url`,message:e instanceof Error?e.message:`Tokens in the URL could not be verified`,code:e instanceof U?e.code:`TOKEN_NOT_VERIFIED`,originalError:e}))}else this.cleanupUrlParams(e),!this.deferFederatedLanding&&!this.takeFederatedLanding()&&this.takeOidcLanding(),this.error=this.checkErrorsFromURL()}takeFederatedLanding(){let e=this.platform.getCurrentUrl();if(!e)return!1;let t=new URLSearchParams(e.search),n=t.get(`code`);if(t.get(`access_token`)||new URLSearchParams(e.hash?.substring(1)).get(`access_token`)||!n||!t.get(`user_state`)||!this.authService.handleFederatedCode(n))return!1;t.delete(`code`),t.delete(`user_state`);let r=t.toString();return this.platform.replaceUrl(e.pathname+(r?`?${r}`:``)+e.hash),!0}takeOidcLanding(){let e=this.platform.getCurrentUrl();return e?this.authService.handleOidcLanding(e):!1}adoptTwoFactorTokenFromUrl(e){if(!e?.hash)return!1;let t=new URLSearchParams(e.hash.substring(1)),n=t.get(`tfa_token`);if(!n)return!1;t.delete(`tfa_token`);let r=t.toString(),i=new URLSearchParams(e.search);i.delete(`user_state`);let a=i.toString();return this.platform.replaceUrl(e.pathname+(a?`?${a}`:``)+(r?`#${r}`:``)),La(n)?(this.subscribeStore.notify(G.TwoFactorRequired,{email:``,challengeId:``,tfaToken:n}),!0):(W(this.subscribeStore,{operation:`tokens.from-url`,message:`Invalid 2FA token format received`,code:`INVALID_TOKEN_FORMAT`}),!0)}checkErrorsFromURL(){let e=new URLSearchParams(this.platform.getCurrentUrl()?.search??``).get(`error`);if(e){let t=Ra(e);return Error(t)}}cleanupUrlParams(e){if(!e)return;let t=[`access_token`,`refresh_token`,`id_token`],n=new URLSearchParams(e.search),r=new URLSearchParams(e.hash?.substring(1)),i=t.some(e=>n.get(e)),a=t.some(e=>r.get(e));if(!a&&!i)return;let o=[...t,`client_challenge`,`user_state`];for(let e of[...o,...i?[`state`]:[]])n.delete(e);let s=n.toString(),c=e.hash??``;if(a){for(let e of[...o,`state`])r.delete(e);let e=r.toString();c=e?`#${e}`:``}this.platform.replaceUrl(e.pathname+(s?`?${s}`:``)+c)}setTokensToCacheFromLocalStorage(){let e=this.storageManager.getTokens();if(!e?.access_token&&this.storageManager.getDeliveryMode()){if(e?.id_token&&this.storageManager.hasCookieModeIdToken()){this.tokenCacheService.setTokensCache(e);return}if(this.storageManager.hasJsonModeTokens())this.storageManager.clearDeliveryMode(),e=this.storageManager.getTokens();else{this.storageManager.deleteTokens();return}}e&&this.tokenCacheService.setTokensCache(e)}getCachedTokens(){return this.tokenCacheService.getTokens()}getTokensWithRefresh(){return this.tokenCacheService.getTokensWithRefresh()}getParsedTokens(){return this.tokenCacheService.getParsedTokens()}areTokensExpired(){return this.tokenCacheService.isExpired()}isAuthenticated(){let e=this.getDeliveryMode();if(e===I.Cookie||e===I.BFF)return this.authService.isAuthenticated(this.tokenCacheService.getParsedTokens()??{});let t=this.storageManager.getTokens();if(!t||!t.access_token)return!1;let n=this.tokenCacheService.getParsedTokens();return n?this.authService.isAuthenticated(n):!1}async signIn(e,t){return await this.authService.signIn(e,t)}async signUp(e,t){return await this.authService.signUp(e,t)}passwordlessSignIn(e,t){return this.authService.passwordlessSignIn(e,t)}async passwordlessSignInComplete(e,t){return await this.authService.passwordlessSignInComplete(e,t)}waitForPasswordlessSignIn(e,t){return this.authService.waitForPasswordlessSignIn(e,t)}getPendingPasswordlessSignIn(e){return this.authService.getPendingPasswordlessSignIn(e)}getPasswordlessApproval(e){return this.authService.getPasswordlessApproval(e)}decidePasswordlessApproval(e,t,n,r){return this.authService.decidePasswordlessApproval(e,t,n,r)}async verifyEmailCode(e){return await this.authService.verifyEmailCode(e)}async checkRedirectUrl(e){try{return await this.authService.checkRedirectUrl(e)}catch(e){this.handleError(e,`redirect.check`,`Redirect check`)}}setAntiBotTokenProvider(e){this.antiBot.setTokenProvider(e)}async antiBotToken(e){try{return(await this.antiBot.headerFor(e))?.value}catch(e){this.handleError(e,`anti-bot.token`,`Anti-bot token`)}}handleError(e,t,n){let r={operation:t,message:e instanceof Error?e.message:`${n} failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,r),e}async logOut(e={}){try{let t=this.authService.hostedEndSessionUrl(e.postLogoutRedirectUri),{userId:n,samlLogoutUrl:r}=await this.authService.logOut(e.postLogoutRedirectUri),i=e.followSamlLogout&&r?r:t;try{this.twoFactorService.clearPartialAuthState(),this.notifySignedOut(n),await this.submitSessionCheck()}finally{i&&this.platform.navigateTo(i)}return r?{samlLogoutUrl:r}:{}}catch(e){this.handleError(e,`log-out`,`Log out`)}}federatedAuthWithPopup(e,t){this.authService.federatedAuthWithPopup(e,t)}federatedAuthWithRedirect(e,t){this.authService.federatedAuthWithRedirect(e,t)}async enterpriseResolve(e){try{return await this.authApi.enterpriseResolve(e)}catch(e){this.handleError(e,`enterprise.resolve`,`Enterprise resolve`)}}createEnterpriseAuthUrl(e){return this.authService.createEnterpriseAuthUrl(e)}async enterpriseStart(e,t){try{return await this.authService.enterpriseStart(e,t)}catch(e){this.handleError(e,`enterprise.start`,`Enterprise start`)}}reset(e){if(this.notifySignedOut(this.authService.resetSession()),e){this.error=Error(e);let t={operation:`reset`,message:e,code:`RESET_ERROR`};throw W(this.subscribeStore,t),this.error}}notifySignedOut(e){this.subscribeStore.notify(G.SignOut,e===void 0?{origin:`this-tab`}:{origin:`this-tab`,userId:e})}dispose(){this.authService.refresh.dispose(),this.tokenCacheService.destroy()}async refreshToken(){return await this.authService.refreshToken()}async enrolDeviceKey(){await this.authService.enrolDeviceKey()}sendPasswordResetEmail(e,t){return this.authService.sendPasswordResetEmail(e,t)}async resetPassword(e,t,n){return await this.authService.resetPassword(e,t,n)}async getAppSettings(){try{return await this.readAppSettings()??await this.appApi.getAppSettings()}catch(e){this.handleError(e,`settings.app`,`Get app settings`)}}async getSettingsAll(){try{return await this.settingApi.getSettingsAll()}catch(e){this.handleError(e,`settings.all`,`Get all settings`)}}async getPasswordPolicySettings(){try{return await this.settingApi.getPasswordPolicySettings()}catch(e){this.handleError(e,`settings.password-policy`,`Get password policy settings`)}}async getPasskeySettings(){try{return await this.settingApi.getPasskeySettings()}catch(e){this.handleError(e,`settings.passkey`,`Get passkey settings`)}}async passkeyRegister(e,t){return await this.authService.passkeyRegister(e,t)}async passkeyAuthenticate(e,t){return await this.authService.passkeyAuthenticate(e,t)}setTokens(e){let t=this.getDeliveryMode(),n=t===I.Cookie||t===I.BFF;this.storageManager.saveTokens(e,n?t:void 0,{replace:!0}),this.tokenCacheService.setTokensCache(e),this.authService.refresh.sessionStarted(),this.subscribeStore.notify(G.SignIn,{tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens()})}async getTokens(e=!1){return await this.authService.getTokens(e)}getToken(e){return this.storageManager.getToken(e)}async getUserPasskeys(){try{return await this.userService.getUserPasskeys()}catch(e){this.handleError(e,`passkey.list`,`Get user passkeys`)}}async renameUserPasskey(e,t){try{return await this.userService.renameUserPasskey(e,t)}catch(e){this.handleError(e,`passkey.rename`,`Rename user passkey`)}}async deleteUserPasskey(e){try{return await this.userService.deleteUserPasskey(e)}catch(e){this.handleError(e,`passkey.delete`,`Delete user passkey`)}}async addUserPasskey(e){try{return await this.userService.addUserPasskey(e)}catch(e){this.handleError(e,`passkey.add`,`Add user passkey`)}}async listSessions(){try{return await this.userService.listSessions()}catch(e){this.handleError(e,`session.list`,`List sessions`)}}async revokeSession(e){let t=this.currentSessionId()===e;try{await this.userService.revokeSession(e)}catch(e){this.handleError(e,`session.revoke`,`Revoke session`)}t&&await this.logOut()}async signOutOtherSessions(){try{return await this.userService.signOutOtherSessions()}catch(e){this.handleError(e,`session.revoke-others`,`Sign out other sessions`)}}async requestAddressChangeProof(e){try{return await this.userService.requestAddressChangeProof(e)}catch(e){this.handleError(e,`profile.address-proof`,`Request address change proof`)}}async updateProfile(e,t){try{return await this.userService.updateProfile(e,t)}catch(e){this.handleError(e,`profile.update`,`Update profile`)}}currentSessionId(){let e=[this.storageManager.getToken(F.access_token),this.storageManager.getToken(F.id_token)??this.storageManager.getIdToken()];for(let t of e)if(t)try{let e=P(t).sid;if(e)return e}catch{}}async joinInvitation(e,t){try{let n=await this.tenant.joinInvitation(e,t);return n.scopes=t??this.scopes,await this.authService.applyTokens(n),n}catch(e){this.handleError(e,`invitation.join`,`Join invitation`)}}async createTenant(e,t){try{let n=await this.tenant.createTenant(e);return t&&await this.refreshToken(),n}catch(e){this.handleError(e,`tenant.create`,`Create tenant`)}}async requestInviteLink(e){try{return e.send_to_email===void 0&&(e.send_to_email=!0),await this.invitationService.requestInviteLink(e)}catch(e){this.handleError(e,`invitation.request-link`,`Request invite link`)}}async getInvitations(e){try{return await this.invitationService.getInvitations(e)}catch(e){this.handleError(e,`invitation.list`,`Get invitations`)}}async deleteInvitation(e){try{return await this.invitationService.deleteInvitation(e)}catch(e){this.handleError(e,`invitation.delete`,`Delete invitation`)}}async resendInvitation(e){try{return await this.invitationService.resendInvitation(e)}catch(e){this.handleError(e,`invitation.resend`,`Resend invitation`)}}async getInvitationLink(e){try{return await this.invitationService.getInvitationLink(e)}catch(e){this.handleError(e,`invitation.get-link`,`Get invitation link`)}}authRedirectUrl(e={}){return this.authService.authRedirectUrl(e)}authRedirect(e={}){return this.authService.authRedirect(e)}getDeliveryMode(){return this.authService.tokenDeliveryManager.getMode()}getDeviceId(){return this.deviceService.getDeviceId()}async restoreSession(){return await this.authService.restoreSession()}async getTwoFactorStatus(){try{return await this.twoFactorService.getStatus()}catch(e){this.handleError(e,`2fa.status`,`Get 2FA status`)}}async beginTwoFactorSetup(){try{return await this.twoFactorService.beginSetup()}catch(e){this.handleError(e,`2fa.setup.begin`,`Begin 2FA setup`)}}async confirmTwoFactorSetup(e){try{return await this.twoFactorService.confirmSetup(e)}catch(e){this.handleError(e,`2fa.setup.confirm`,`Confirm 2FA setup`)}}async getTwoFactorEnrollment(){try{return await this.twoFactorService.getEnrollment()}catch(e){this.handleError(e,`2fa.enrollment.read`,`Read 2FA enrollment`)}}async sendTwoFactorSetupLink(){try{return await this.twoFactorService.sendSetupLink()}catch(e){this.handleError(e,`2fa.enrollment.setup-link`,`Send 2FA setup link`)}}async beginTwoFactorEnrollment(){try{return await this.twoFactorService.beginEnrollment()}catch(e){this.handleError(e,`2fa.setup.begin`,`Begin 2FA enrollment`)}}async confirmTwoFactorEnrollment(e){try{return await this.twoFactorService.confirmEnrollment(e)}catch(e){this.handleError(e,`2fa.setup.confirm`,`Confirm 2FA enrollment`)}}async verifyTwoFactor(e,t){try{let n=await this.twoFactorService.verify(e,t);return this.subscribeStore.notify(G.SignIn,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),n}catch(e){this.handleError(e,`2fa.verify`,`Verify 2FA`)}}async useTwoFactorRecoveryCode(e,t){try{let n=await this.twoFactorService.useRecoveryCode(e,t);return this.subscribeStore.notify(G.SignIn,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),n}catch(e){this.handleError(e,`2fa.recovery.use`,`Use 2FA recovery code`)}}async disableTwoFactor(e){try{return await this.twoFactorService.disable(e)}catch(e){this.handleError(e,`2fa.disable`,`Disable 2FA`)}}async regenerateTwoFactorRecoveryCodes(e){try{return await this.twoFactorService.regenerateRecoveryCodes(e)}catch(e){this.handleError(e,`2fa.recovery.regenerate`,`Regenerate 2FA recovery codes`)}}async getTrustedDevices(){try{return await this.twoFactorService.getTrustedDevices()}catch(e){this.handleError(e,`2fa.trusted-devices.list`,`Get trusted devices`)}}async revokeTrustedDevice(e){try{await this.twoFactorService.revokeTrustedDevice(e)}catch(e){this.handleError(e,`2fa.trusted-devices.revoke`,`Revoke trusted device`)}}async getPreferredTwoFactorMethod(){try{return await this.twoFactorService.getPreferredMethod()}catch(e){this.handleError(e,`2fa.preferred-method.read`,`Get preferred 2FA method`)}}async setPreferredTwoFactorMethod(e){try{return await this.twoFactorService.setPreferredMethod(e)}catch(e){this.handleError(e,`2fa.preferred-method.set`,`Set preferred 2FA method`)}}async clearPreferredTwoFactorMethod(){try{await this.twoFactorService.clearPreferredMethod()}catch(e){this.handleError(e,`2fa.preferred-method.clear`,`Clear preferred 2FA method`)}}isTwoFactorVerificationRequired(){return this.twoFactorService.isVerificationRequired()}getTotpDigits(){return this.twoFactorService.getTotpDigits()}async validateTwoFactorSetupMagicLink(e){return await this.twoFactorService.validateTwoFactorSetupMagicLink(e)}getMagicLinkSession(){return this.twoFactorService.getMagicLinkSession()}hasMagicLinkSession(){return this.twoFactorService.hasMagicLinkSession()}clearMagicLinkSession(){this.twoFactorService.clearMagicLinkSession()}};Cc=wc,Cc.version=S,exports.ADDRESS_CHANGE_PROOF_REQUIRED_ERROR_ID=ft,exports.AGENT_TOOL_HEADER_KEY=y,exports.ANTI_BOT_ACTION=x,exports.ANTI_BOT_FAILED_ERROR_ID=$e,exports.ANTI_BOT_HEADER_KEY=v,exports.ANTI_BOT_PROVIDER_FAILED_ERROR_ID=nt,exports.ANTI_BOT_PROVIDER_MISSING_ERROR_ID=tt,exports.ANTI_BOT_REQUIRED_ERROR_ID=Qe,exports.ANTI_BOT_SOLVE_FAILED_ERROR_ID=rt,exports.ANTI_BOT_UNAVAILABLE_ERROR_ID=et,exports.APP_ID_HEADER_KEY=m,exports.APP_SECRET_NAMES=vt,exports.AUTHORIZATION_HEADER_KEY=h,exports.AppAPI=en,exports.AuthAPI=ln,exports.AuthService=so,exports.CLIAuthAPI=un,exports.DEFAULT_GROUP_NAME=E,exports.DEFAULT_SCOPES=w,exports.DEFAULT_UPGRADE_FACTORS=bo,exports.DEVICE_ID_HEADER_KEY=g,exports.DEVICE_PROOF_HEADER_KEY=b,exports.DEVICE_TYPE_HEADER_KEY=_,exports.DeviceKeyErrorId=zn,exports.ENTERPRISE_CONNECTION_AMBIGUOUS_ERROR_ID=st,exports.ENTERPRISE_EMAIL_INVALID_ERROR_ID=it,exports.ENTERPRISE_NO_CONNECTION_ERROR_ID=ot,exports.ENTERPRISE_START_INPUT_ERROR_ID=at,exports.ERROR_MESSAGE_MAX_LENGTH=ae,exports.FETCH_PRIORITY_OIDC=Vn,exports.FETCH_PRIORITY_UPGRADE=Hn,exports.FetchMiddlewareContractError=Un,exports.INSUFFICIENT_USER_AUTHENTICATION=Te,exports.InvitationAPI=dn,exports.InvitationService=co,exports.M2MClient=lr,exports.M2MConfigError=ir,exports.M2MError=H,exports.M2MErrorCodes=ar,exports.M2MNetworkError=nr,exports.M2MTokenParseError=rr,exports.M2M_DEFAULTS=or,exports.MASKED_SECRET_PREFIX=yt,exports.MINIMAL_DEFAULT_SCOPES=C,exports.OS=St,exports.PASSFLOW_CLOUD_URL=T,exports.PASSWORD_CHANGE_REQUIRED_ERROR_ID=Ze,exports.POPUP_HEIGHT=ee,exports.POPUP_POLL_INTERVAL_MS=te,exports.POPUP_TIMEOUT_MS=O,exports.POPUP_WIDTH=D,exports.Passflow=wc,exports.PassflowAddressChangeProofRequiredError=gt,exports.PassflowAdminEndpointPaths=Ke,exports.PassflowEndpointPaths=z,exports.PassflowError=B,exports.PassflowEvent=G,exports.PassflowOidcError=U,exports.PassflowPasswordChangeRequiredError=ct,exports.PassflowRecoveryCodesStepUpRequiredError=ht,exports.PassflowRefreshError=Y,exports.PassflowSendLimitError=mt,exports.PassflowSmsQuotaExceededError=pt,exports.PopupClosedError=_e,exports.Providers=_t,exports.RECOVERABLE_COMMIT_ERROR_IDS=ga,exports.RECOVERY_CODES_STEP_UP_REQUIRED_ERROR_ID=dt,exports.REFRESH_AUTH_FAILURE_IDS=Ai,exports.RefreshErrorId=J,exports.RequestMethod=Ge,exports.SDK_VERSION=S,exports.SERVICE_UNAVAILABLE_ERROR_ID=Ye,exports.SERVICE_UNAVAILABLE_MESSAGE=Xe,exports.SESSION_INVALIDATING_COMMIT_ERROR_IDS=_a,exports.SETTINGS_MASKED_VALUE_UNKNOWN_ERROR_ID=bt,exports.SessionState=de,exports.SettingAPI=fn,exports.TOKEN_EXPIRY_BUFFER_SECONDS=ne,exports.TWO_FACTOR_SEND_LIMIT_ERROR_ID=ut,exports.TWO_FACTOR_SMS_QUOTA_EXCEEDED_ERROR_ID=lt,exports.TenantAPI=pn,exports.TenantService=uo,exports.TenantUserMembership=lo,exports.TokenCacheService=fo,exports.TokenDeliveryMode=I,exports.TokenType=F,exports.TwoFactorApiClient=vn,exports.TwoFactorPolicy=Tt,exports.TwoFactorService=po,exports.UPGRADE_REQUIRED=Ee,exports.USERNAME_MAX_LENGTH=ie,exports.USERNAME_MIN_LENGTH=re,exports.UpgradeAPI=yn,exports.UpgradeCancelledError=Do,exports.UpgradeCommitInterruptedError=Gi,exports.UpgradeController=Vo,exports.UpgradeErrorIds=Q,exports.UpgradeFactorError=ho,exports.UpgradeInsufficientError=Ma,exports.UpgradeSessionChangedError=Pa,exports.UpgradeSignInRequiredError=Oo,exports.UpgradeTransportError=$,exports.UpgradeUnavailableError=Na,exports.UpgradeUnsatisfiableError=No,exports.UserAPI=bn,exports.UserService=mo,exports.WebAdapter=ve,exports.classifyUpgradeError=ka,exports.factorRegistry=xo,exports.fetchRegistryState=tr,exports.getOSFromDeviceType=Ct,exports.invalidatesSessionOnCommit=ja,exports.isEmailVerificationStep=Je,exports.isMaskedSecret=xt,exports.isRecoverableCommitFailure=Aa,exports.isRetryableUpgradeKind=ya,exports.isTokenExpired=N,exports.isUpgradeCancelled=_s,exports.isUpgradeExhausted=vs,exports.isUpgradeInsufficient=ys,exports.isUpgradeSessionChanged=Cs,exports.isUpgradeSignInRequired=xs,exports.isUpgradeTransportError=Ca,exports.isUpgradeTransportFailure=ws,exports.isUpgradeUnavailable=Ss,exports.isUpgradeUnsatisfiable=bs,exports.isValidEmail=za,exports.isValidJWTFormat=La,exports.isValidPhoneNumber=Ba,exports.isValidUsername=Va,exports.parseChallengeBody=Ne,exports.parseChallengeHeader=Me,exports.parseToken=P,exports.parseUpgradeChallenge=Le,exports.passkeyFactor=yo,exports.pathWithParams=wt,exports.recoveryCodesFactor=vo,exports.registerFetchMiddleware=er,exports.requiredAcrLevel=we,exports.resolveUpgradeDomain=qe,exports.sanitizeErrorMessage=Ra,exports.selectFactors=Eo,exports.totpFactor=_o,exports.webAdapter=ye;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("axios");c=s(c,1);let l=require("@simplewebauthn/browser");var u=`__passflowAntiBot`,d=(e,t)=>{let n=t?{operation:e,identifier:t}:{operation:e};return{[u]:n}},f=e=>{if(typeof e!=`object`||!e)return;let t=e[u];return typeof t==`object`&&t?t:void 0},p=`0.43.0`,m=`X-Passflow-Clientid`,h=`Authorization`,g=`X-Passflow-DeviceId`,_=`X-Passflow-DeviceType`,v=`X-Passflow-Anti-Bot`,y=`X-Passflow-Agent-Tool`,b=`X-Passflow-Device-Proof`,x=`passflow_auth`,S=p,C=[`id`,`offline`,`openid`],w=[`id`,`offline`,`tenant`,`email`,`oidc`,`openid`,`access:tenant:all`],T=`https://auth.passflow.cloud`,E=`default`,D=500,ee=600,te=100,O=6e4,ne=30,re=3,ie=30,ae=200,k=[];for(let e=0;e<256;++e)k.push((e+256).toString(16).slice(1));function A(e,t=0){return(k[e[t+0]]+k[e[t+1]]+k[e[t+2]]+k[e[t+3]]+`-`+k[e[t+4]]+k[e[t+5]]+`-`+k[e[t+6]]+k[e[t+7]]+`-`+k[e[t+8]]+k[e[t+9]]+`-`+k[e[t+10]]+k[e[t+11]]+k[e[t+12]]+k[e[t+13]]+k[e[t+14]]+k[e[t+15]]).toLowerCase()}var oe=new Uint8Array(16);function se(){return crypto.getRandomValues(oe)}function ce(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():j(e,t,n)}function j(e,t,n){e=e||{};let r=e.random??e.rng?.()??se();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n=n||0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return A(r)}var le=e=>{let t=[],n;for(n in e){let r=e[n];if(r===void 0)continue;let i={tenant:{id:r.tenant_id,name:r.tenant_name}};i.groups=r.groups?Object.keys(r.groups).map(e=>{let t=r.groups[e]||[];return{group:{id:e,name:r.group_names?.[e]??`unknown`},roles:t}}):[],i.tenantRoles=i.groups?.find(e=>e.group.id===r.root_group_id),t.push(i)}return{raw:e,tenants:t}};function ue(e){if(typeof window<`u`&&typeof window.atob==`function`)return window.atob(e);if(typeof Buffer<`u`)return Buffer.from(e,`base64`).toString(`utf-8`);throw Error(`No Base64 decoding method available in this environment`)}var M=class{constructor(e){this.storageManager=e}isTokenTypeExpired(e){let t=this.storageManager.getToken(e);if(!t)return!0;let n=P(t);return!n||N(n)}parseTokenType(e){let t=this.storageManager.getToken(e);if(t)return P(t)}};function N(e,t=30){return Math.floor(Date.now()/1e3)+t>e.exp}function P(e){let t=e.split(`.`)[1];if(!t)throw Error(`Invalid token string`);let n=t.replace(/-/g,`+`).replace(/_/g,`/`),r=ue(n+`=`.repeat((4-n.length%4)%4)),i=decodeURIComponent(r.split(``).map(e=>`%`+(`00`+e.charCodeAt(0).toString(16)).slice(-2)).join(``)),a=JSON.parse(i);return a.membership=a.passflow_tm&&a.type!==`invite`?le(a.passflow_tm):void 0,a}var F=function(e){return e.id_token=`id_token`,e.access_token=`access`,e.refresh_token=`refresh`,e.invite_token=`invite`,e.reset_token=`reset`,e.web_cookie=`web-cookie`,e.management=`management`,e.signin=`signin`,e.actor=`actor`,e.two_factor=`2fa`,e}({}),I=function(e){return e.JsonBody=`json_body`,e.Cookie=`cookie`,e.Mobile=`mobile`,e.BFF=`bff`,e}({}),de=function(e){return e.Unknown=`unknown`,e.Valid=`valid`,e.Invalid=`invalid`,e}({}),fe=class{constructor(e){this.storageManager=e,this.mode=`json_body`,this.sessionState=`unknown`,this.isInitializedFlag=!1,this.SESSION_STATE_KEY=`passflow_session_state`,this.loadPersistedMode(),this.loadPersistedSessionState()}sessionStateKey(){return this.storageManager.appKey(this.SESSION_STATE_KEY)}reload(){this.mode=`json_body`,this.isInitializedFlag=!1,this.sessionState=`unknown`,this.loadPersistedMode(),this.loadPersistedSessionState()}setMode(e){this.mode=e,this.isInitializedFlag=!0,this.persistMode()}getMode(){return this.mode}isCookieMode(){return this.mode===`cookie`}isJsonMode(){return this.mode===`json_body`}isMobileMode(){return this.mode===`mobile`}isBFFMode(){return this.mode===`bff`}isInitialized(){return this.isInitializedFlag}setSessionValid(){this.sessionState=`valid`,this.persistSessionState()}setSessionInvalid(){this.sessionState=`invalid`,this.persistSessionState()}setSessionUnknown(){this.sessionState=`unknown`,this.persistSessionState()}isSessionValid(){return this.sessionState===`valid`}isSessionUnknown(){return this.sessionState===`unknown`}isSessionInvalid(){return this.sessionState===`invalid`}getSessionState(){return this.sessionState}reset(){this.mode=`json_body`,this.sessionState=`unknown`,this.isInitializedFlag=!1,this.clearPersistedSessionState(),this.storageManager.clearDeliveryMode()}loadPersistedMode(){let e=this.storageManager.getDeliveryMode();e&&(this.mode=e,this.isInitializedFlag=!0)}loadPersistedSessionState(){try{let e=this.storageManager.storage.getItem(this.sessionStateKey());e&&Object.values(de).includes(e)&&(this.sessionState=e)}catch{}}persistMode(){this.storageManager.setDeliveryMode(this.mode)}persistSessionState(){try{this.storageManager.storage.setItem(this.sessionStateKey(),this.sessionState)}catch{}}clearPersistedSessionState(){try{this.storageManager.storage.removeItem(this.sessionStateKey())}catch{}}},L=`tokens_scopes`,R=`passflowDeviceId`,pe=`passflowInvitationToken`,me=`passflowPreviousRedirectUrl`,he=class{constructor({storage:e,prefix:t,appId:n}={}){this.keyStoragePrefix=``,this.STORAGE_PREFIX=`passflow_`,this.storage=e??localStorage,this.keyStoragePrefix=t?`${t}_`:``,this.scopes=`${this.keyStoragePrefix}${L}`,this.deviceId=`${this.keyStoragePrefix}${R}`,this.invitationToken=`${this.keyStoragePrefix}${pe}`,this.previousRedirectUrl=`${this.keyStoragePrefix}${me}`,this.appId=n||void 0}setAppId(e){this.appId=e||void 0}getAppId(){return this.appId}appKey(e){return this.appId?`${e}:${this.appId}`:e}idTokenKey(){return this.appKey(`${this.STORAGE_PREFIX}id_token`)}csrfTokenKey(){return this.appKey(`${this.STORAGE_PREFIX}csrf_token`)}refreshChallengeKey(){return this.appKey(`${this.STORAGE_PREFIX}refresh_challenge`)}deliveryModeKey(){return this.appKey(`${this.STORAGE_PREFIX}delivery_mode`)}ownToken(e){if(!e)return;if(!this.appId)return e;let t;try{t=P(e).aud}catch{return e}return t===void 0||(Array.isArray(t)?t:[t]).includes(this.appId)?e:void 0}readPrefixed(e,t){let n=this.storage.getItem(e);if(n!==null||e===t)return n??void 0;let r=this.storage.getItem(t);if(r)return this.storage.setItem(e,r),this.storage.removeItem(t),r}removePrefixed(e,t){this.storage.removeItem(e),e!==t&&this.storage.removeItem(t)}readToken(e){return this.ownToken(this.storage.getItem(e))}tokenValueKeys(){return[this.getKeyForTokenType(F.access_token),this.getKeyForTokenType(F.refresh_token),this.getKeyForTokenType(F.id_token),this.idTokenKey()]}holdsOtherAppToken(e){if(!this.appId)return!1;let t=this.storage.getItem(e);return!!t&&this.ownToken(t)===void 0}holdsOnlyOtherAppSession(){if(!this.appId)return!1;let e=this.tokenValueKeys();return e.some(e=>this.holdsOtherAppToken(e))&&!e.some(e=>!!this.readToken(e))}removeOwnToken(e){this.holdsOtherAppToken(e)||this.storage.removeItem(e)}saveTokens(e,t,n){let{id_token:r,access_token:i,refresh_token:a,scopes:o}=e;if(t===I.Cookie||t===I.BFF)r&&this.storage.setItem(this.idTokenKey(),r);else{if(n?.replace&&i){let e=this.holdsOnlyOtherAppSession();r||this.removeOwnToken(this.getKeyForTokenType(F.id_token)),a||this.removeOwnToken(this.getKeyForTokenType(F.refresh_token)),!o&&!e&&this.removePrefixed(this.scopes,L)}r&&this.storage.setItem(this.getKeyForTokenType(F.id_token),r),i&&this.storage.setItem(this.getKeyForTokenType(F.access_token),i),a&&this.storage.setItem(this.getKeyForTokenType(F.refresh_token),a),o&&this.storage.setItem(this.scopes,o.join(`,`))}}getToken(e){return this.readToken(this.getKeyForTokenType(e))}getTokens(){let e=this.getDeliveryMode();if(e===I.Cookie||e===I.BFF){let e=this.readToken(this.idTokenKey());return e?{id_token:e}:void 0}let t=this.readToken(this.getKeyForTokenType(F.access_token));if(t)return{access_token:t,id_token:this.readToken(this.getKeyForTokenType(F.id_token)),refresh_token:this.readToken(this.getKeyForTokenType(F.refresh_token)),scopes:this.getScopes()}}getScopes(){return this.readPrefixed(this.scopes,L)?.split(`,`)}hasJsonModeTokens(){return!!this.readToken(this.getKeyForTokenType(F.access_token))}hasCookieModeIdToken(){return!!this.readToken(this.idTokenKey())}deleteToken(e){let t=this.getKeyForTokenType(e);this.storage.removeItem(t)}deleteTokens(){let e=this.holdsOnlyOtherAppSession();for(let e of this.tokenValueKeys())this.removeOwnToken(e);e||this.removePrefixed(this.scopes,L),this.clearDeliveryMode(),this.clearCsrfToken(),this.clearRefreshChallenge(),this.appId&&this.getHostedSignIn()===void 0&&this.storage.getItem(this.hostedSignInKey())||this.storage.removeItem(this.hostedSignInKey())}setHostedSignIn(e){this.storage.setItem(this.hostedSignInKey(),JSON.stringify({appId:this.appId??``,returnUrl:e}))}getHostedSignIn(){try{let e=JSON.parse(this.storage.getItem(this.hostedSignInKey())??``);return e.appId!==(this.appId??``)||typeof e.returnUrl!=`string`?void 0:e.returnUrl||void 0}catch{return}}hostedSignInKey(){return`${this.keyStoragePrefix}${this.STORAGE_PREFIX}hosted_sign_in`}getDeviceId(){return this.readPrefixed(this.deviceId,R)}setDeviceId(e){this.storage.setItem(this.deviceId,e)}deleteDeviceId(){this.removePrefixed(this.deviceId,R)}setInvitationToken(e){this.storage.setItem(this.invitationToken,e)}getInvitationToken(){return this.readPrefixed(this.invitationToken,pe)}deleteInvitationToken(){this.removePrefixed(this.invitationToken,pe)}setPreviousRedirectUrl(e){this.storage.setItem(this.previousRedirectUrl,e)}getPreviousRedirectUrl(){return this.readPrefixed(this.previousRedirectUrl,me)}deletePreviousRedirectUrl(){this.removePrefixed(this.previousRedirectUrl,me)}setDeliveryMode(e){try{this.storage.setItem(this.deliveryModeKey(),e)}catch{}}getDeliveryMode(){try{let e=this.storage.getItem(this.deliveryModeKey());if(e&&Object.values(I).includes(e))return e}catch{}}clearDeliveryMode(){try{this.storage.removeItem(this.deliveryModeKey())}catch{}}getIdToken(){try{return this.readToken(this.idTokenKey())}catch{return}}setIdToken(e){try{this.storage.setItem(this.idTokenKey(),e)}catch{}}clearIdToken(){try{this.removeOwnToken(this.idTokenKey())}catch{}}getCsrfToken(){try{return this.storage.getItem(this.csrfTokenKey())??void 0}catch{return}}setCsrfToken(e){try{this.storage.setItem(this.csrfTokenKey(),e)}catch{}}clearCsrfToken(){try{this.storage.removeItem(this.csrfTokenKey())}catch{}}getRefreshChallenge(){try{return this.storage.getItem(this.refreshChallengeKey())??void 0}catch{return}}setRefreshChallenge(e){try{this.storage.setItem(this.refreshChallengeKey(),e)}catch{}}clearRefreshChallenge(){try{this.storage.removeItem(this.refreshChallengeKey())}catch{}}tokenKeys(){return[this.getKeyForTokenType(F.id_token),this.getKeyForTokenType(F.access_token),this.getKeyForTokenType(F.refresh_token),this.scopes,this.idTokenKey(),this.csrfTokenKey(),this.deliveryModeKey()]}getKeyForTokenType(e){return`${this.keyStoragePrefix}${e}`}},ge=class{constructor(e){this.storageManager=e??new he}getDeviceId(){return this.storageManager.getDeviceId()||(this.mintedDeviceId??(this.mintedDeviceId=this.generateUniqueDeviceId()),this.storageManager.setDeviceId(this.mintedDeviceId),this.mintedDeviceId)}generateUniqueDeviceId(){return ce()}},_e=class extends Error{constructor(e=`Authentication popup was closed`){super(e),this.name=`PopupClosedError`}},ve=class{constructor(){this.passkeys={startRegistration:e=>(0,l.startRegistration)({optionsJSON:e}),startAuthentication:e=>(0,l.startAuthentication)({optionsJSON:e})}}get storage(){return typeof localStorage>`u`?{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}:localStorage}get storageSharedAcrossTabs(){try{return typeof localStorage<`u`&&localStorage!==null}catch{return!1}}getCurrentUrl(){return typeof window>`u`?null:{href:window.location.href,origin:window.location.origin,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,hostname:window.location.hostname}}replaceUrl(e){typeof window<`u`&&window.history.replaceState({},document.title,e)}navigateTo(e){typeof window<`u`&&(window.location.href=e)}onForeground(e){if(typeof document>`u`)return()=>{};let t=()=>{document.hidden||e()};return document.addEventListener(`visibilitychange`,t),()=>document.removeEventListener(`visibilitychange`,t)}onBackground(e){if(typeof document>`u`)return()=>{};let t=()=>{document.hidden&&e()};return document.addEventListener(`visibilitychange`,t),()=>document.removeEventListener(`visibilitychange`,t)}onBeforeUnload(e){return typeof window>`u`?()=>{}:(window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e))}isInForeground(){return typeof document>`u`||!document.hidden}openAuthUrl(e,t={}){let n=t.mode??`popup`;if(n===`redirect`)return window.location.href=e,new Promise(()=>{});if(n===`deeplink`)return Promise.reject(Error(`openAuthUrl: "deeplink" mode is not supported on web. Use "popup" or "redirect" instead, or provide a native platform adapter.`));let r=t.width??500,i=t.height??600,a=t.expectedReturnOrigin??window.location.origin,o=window.open(e,`_blank`,`width=${r},height=${i}`);return o?this.watchPopup(o,a):(window.location.href=e,new Promise(()=>{}))}async openPendingAuthUrl(e,t={}){if((t.mode??`popup`)!==`popup`)return this.openAuthUrl(await e,t);let n=t.width??500,r=t.height??600,i=t.expectedReturnOrigin??window.location.origin,a=window.open(`about:blank`,`_blank`,`width=${n},height=${r}`),o;try{o=await e}catch(e){throw a?.close(),e}return a?(a.location.href=o,this.watchPopup(a,i)):(window.location.href=o,new Promise(()=>{}))}watchPopup(e,t){return new Promise((n,r)=>{let i=Date.now(),a=setInterval(()=>{if(e.closed)clearInterval(a),r(new _e);else if(Date.now()-i>6e4)clearInterval(a),e.close(),r(Error(`Authentication popup timed out`));else try{if(e.location.href.startsWith(t)){let t=e.location.search,r=e.location.hash;clearInterval(a),e.close(),n({callbackSearch:t,callbackHash:r})}}catch{}},100)})}btoa(e){return btoa(e)}atob(e){if(typeof window<`u`&&typeof window.atob==`function`)return window.atob(e);if(typeof Buffer<`u`)return Buffer.from(e,`base64`).toString(`utf-8`);throw Error(`No Base64 decoding method available in this environment`)}cookiesSupported(){if(typeof document>`u`)return!1;try{document.cookie=`passflow_test=1; SameSite=Lax`;let e=document.cookie.indexOf(`passflow_test=1`)!==-1;return document.cookie=`passflow_test=; expires=Thu, 01 Jan 1970 00:00:00 UTC`,e}catch{return!1}}getDeviceType(){return`web`}},ye=new ve,be=/^[0-9]+$/,xe=Object.freeze({unorderable:!1,zero:!1}),Se=e=>be.test(e)?Number.parseInt(e,10):void 0,Ce=e=>{if(!e)return xe;let t=e.split(/\s+/).filter(e=>e!==``);if(t.length===0)return xe;let n=[];for(let e of t){let t=Se(e);t!==void 0&&n.push(t)}if(n.length===0)return{raw:e,unorderable:!0,zero:!1};let r=Math.min(...n);return r===0?{raw:e,unorderable:!1,zero:!0}:{level:r,raw:e,unorderable:!1,zero:!1}},we=e=>Ce(e).level,Te=`insufficient_user_authentication`,Ee=`upgrade_required`,De=/([A-Za-z0-9!#$%&'*+\-.^_`|~]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]*))/g,Oe=e=>e.replace(/\\(.)/g,`$1`),ke=e=>{let t={};De.lastIndex=0;for(let n of e.matchAll(De)){let e=n[1];if(!e)continue;let r=n[2],i=n[3];t[e.toLowerCase()]=r===void 0?i??``:Oe(r)}return t},Ae=e=>{if(e==null||e===``)return{kind:`absent`};let t=typeof e==`number`?e:Number.parseInt(String(e),10);return Number.isFinite(t)&&t>0?{kind:`valid`,value:t}:{kind:`invalid`,raw:e}},je=e=>{let t=Ae(e);return t.kind===`valid`?t.value:void 0},Me=(e,t)=>{if(!e||!/(^|[\s,])Bearer\b/i.test(e))return;let n=ke(e);if(n.error===`insufficient_user_authentication`)return{acrValues:n.acr_values||void 0,maxAge:je(n.max_age),status:t}},Ne=(e,t)=>{if(!e||typeof e!=`object`)return;let n=e;if(n.error!==`upgrade_required`)return;let r=Array.isArray(n.available_factors)?n.available_factors.filter(e=>typeof e==`string`):void 0;return{acrValues:typeof n.acr_values==`string`&&n.acr_values?n.acr_values:void 0,maxAge:je(n.max_age),status:t,...r?{availableFactors:r}:{},...typeof n.sign_in_required==`boolean`?{signInRequired:n.sign_in_required}:{}}},Pe=(e,t,n)=>({channel:e,acr:Ce(t.acrValues),maxAge:Ae(n),raw:t.acrValues}),Fe=e=>e?ke(e):{},Ie=(e,t)=>{let{status:n}=e;if(n!==401&&n!==403)return{diagnostics:[]};let r=t?.requireChallengeChannel===`header`,i=e.getHeader(`www-authenticate`),a=Me(i,n),o=r?void 0:Ne(e.body,n),s=[],c=(e,t)=>{s.push({status:n,url:``,reason:e,...t?{detail:t}:{}})};if(!a&&!o)return r&&c(`header-required-but-absent`,i?{header:i}:void 0),{diagnostics:s};let l=[];if(a&&l.push(Pe(`header`,a,Fe(i).max_age)),o){let t=e.body;l.push(Pe(`body`,o,t?.max_age))}let u=e=>e;for(let e of l)e.acr.unorderable&&c(`channels-unorderable`,{[u(e.channel)]:e.raw}),e.acr.zero&&c(`zero-constraint-ignored`,{field:`acr_values`,[u(e.channel)]:e.raw}),e.maxAge.kind===`invalid`&&c(`zero-constraint-ignored`,{field:`max_age`,[u(e.channel)]:String(e.maxAge.raw)});let d=l.filter(e=>e.acr.level!==void 0),f,p;for(let e of d){let t=e.acr.level;f===void 0||t>f?(f=t,p=e.raw):t===f&&e.channel===`header`&&(p=e.raw)}let m;for(let e of l)e.maxAge.kind===`valid`&&(m===void 0||e.maxAge.value<m)&&(m=e.maxAge.value);if(l.length===2){let[e,t]=l,n=e.acr.level!==void 0&&t.acr.level!==void 0&&e.acr.level!==t.acr.level,r=e.maxAge.kind===`valid`&&t.maxAge.kind===`valid`&&e.maxAge.value!==t.maxAge.value;(n||r)&&c(`channels-disagree`,{header:e.raw??t.raw,body:t.raw??e.raw})}return{challenge:{acrValues:p,requiredLevel:f,maxAge:m,status:n,channels:l.map(e=>e.channel),...o?.availableFactors?{availableFactors:o.availableFactors}:{},...o?.signInRequired===void 0?{}:{signInRequired:o.signInRequired}},diagnostics:s}},Le=(e,t,n)=>Ie({status:e,getHeader:t,body:n}).challenge,Re=`__passflowUpgradeTransaction`,ze=`__passflowUpgradeReplayed`,Be=(e,t)=>typeof e==`object`&&!!e&&e[t]===!0,Ve=e=>({...e??{},[Re]:!0}),He=e=>Be(e,Re),Ue=e=>({...e,[ze]:!0}),We=e=>Be(e,ze),Ge=function(e){return e.GET=`get`,e.POST=`post`,e.PUT=`put`,e.PATCH=`patch`,e.DELETE=`delete`,e}({}),z=function(e){return e.signin=`/auth/login`,e.signup=`/auth/register`,e.pkceExchange=`/auth/pkce_exchange`,e.redirectCheck=`/auth/redirect/check`,e.signInWithProvider=`/auth/federated/start/`,e.passwordless=`/auth/passwordless/start`,e.passwordlessComplete=`/auth/passwordless/complete`,e.passwordlessStatus=`/auth/passwordless/status`,e.passwordlessApprovalInfo=`/auth/passwordless/approval/info`,e.passwordlessApprovalDecide=`/auth/passwordless/approval/decide`,e.logout=`/user/logout`,e.refresh=`/auth/refresh`,e.validateSession=`/user/me`,e.sendPasswordResetEmail=`/auth/password/reset`,e.resetPassword=`/auth/password/change`,e.appSettings=`/app/settings`,e.passkeyRegisterStart=`/auth/passkey/register/start`,e.passkeyRegisterComplete=`/auth/passkey/register/complete`,e.passkeyAuthenticateStart=`/auth/passkey/authenticate/start`,e.passkeyAuthenticateComplete=`/auth/passkey/authenticate/complete`,e.passkeyValidate=`/auth/validate`,e.settingsAll=`/settings`,e.settingsPasswordPolicy=`/settings/password`,e.settingsPasskey=`/settings/passkey`,e.userPasskey=`/user/passkey`,e.addUserPasskey=`/user/passkey/add/start`,e.completeAddUserPasskey=`/user/passkey/add/complete`,e.userSessions=`/user/sessions`,e.userSessionsRevokeOthers=`/user/sessions/revoke-others`,e.userProfile=`/user/profile`,e.AddressChangeProof=`/v2/user/address-change/proof`,e.joinInvitation=`/user/tenant/join`,e.tenantPath=`/user/tenant`,e.invitationsPath=`/user/tenant/:tenantID/invitations`,e.requestInvitation=`/user/invite`,e.invitationDelete=`/user/invite/:invitationID`,e.invitationResend=`/user/invite/:invitationID/resend`,e.invitationGetLink=`/user/invite/:invitationID/link`,e.twoFactor=`/user/2fa`,e.twoFactorStatus=`/user/2fa/status`,e.twoFactorSetupBegin=`/user/2fa/setup/begin`,e.twoFactorSetupConfirm=`/user/2fa/setup/confirm`,e.twoFactorVerify=`/auth/2fa/verify`,e.twoFactorRecovery=`/auth/2fa/recovery`,e.twoFactorRegenerateCodes=`/user/2fa/recovery-codes/regenerate`,e.twoFactorSetupMagicLink=`/auth/2fa-setup`,e.twoFactorEnrollment=`/auth/2fa/enrollment`,e.twoFactorEnrollmentEmailLink=`/auth/2fa/enrollment/email-link`,e.twoFactorEnrollmentBegin=`/auth/2fa/setup/begin`,e.twoFactorEnrollmentConfirm=`/auth/2fa/setup/confirm`,e.TwoFactorMethodsAvailable=`/v2/user/2fa/methods/available`,e.TwoFactorMethodsRegistered=`/v2/user/2fa/methods`,e.TwoFactorSetupStart=`/v2/user/2fa/setup/start`,e.TwoFactorSetupComplete=`/v2/user/2fa/setup/complete`,e.TwoFactorMethodRemove=`/v2/user/2fa/methods/:id`,e.TwoFactorChallenge=`/v2/auth/2fa/challenge`,e.TwoFactorVerifyV2=`/v2/auth/2fa/verify`,e.TwoFactorAlternative=`/v2/auth/2fa/alternative`,e.TwoFactorPushStatus=`/v2/auth/2fa/push/status`,e.TwoFactorTrustedDevices=`/v2/user/2fa/trusted-devices`,e.TwoFactorTrustedDeviceRevoke=`/v2/user/2fa/trusted-devices/:id`,e.TwoFactorPreferredMethod=`/v2/user/2fa/preferred-method`,e.cliAuthStatus=`/cli/auth/status/:sessionId`,e.cliAuthComplete=`/cli/auth/complete`,e.upgradeStart=`/auth/upgrade/start`,e.hostedUpgradeStart=`/auth/session/upgrade/start`,e.hostedUpgrade=`/auth/session/upgrade`,e.antiBotChallenge=`/auth/anti-bot/challenge`,e.deviceAntiBotChallenge=`/oidc/device/anti-bot/challenge`,e.enterpriseResolve=`/auth/enterprise/resolve`,e.enterpriseStart=`/auth/enterprise/start`,e.deviceChallenge=`/auth/device/challenge`,e.userDeviceKey=`/user/device/key`,e}({}),Ke=function(e){return e.passkeyRegisterStart=`/admin/auth/passkey/register/start`,e.passkeyRegisterComplete=`/admin/auth/passkey/register/complete`,e.passkeyAuthenticateStart=`/admin/auth/passkey/authenticate/start`,e.passkeyAuthenticateComplete=`/admin/auth/passkey/authenticate/complete`,e.passkeyValidate=`/admin/auth/validate`,e.logout=`/admin/auth/logout`,e}({}),qe=e=>{if(!e)return null;try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return{origin:t.origin,pathPrefix:n===``?void 0:n}}catch{return null}},Je=e=>typeof e==`object`&&!!e&&e.email_verification_required===!0,Ye=`error.service.unavailable`,Xe=`Passflow is temporarily unavailable. Please try again in a moment.`,B=class extends Error{constructor(e,t){super(),this.name=`PassflowError`,this.id=e?.id??`unknown`,this.message=e?.message??e??`Something went wrong`,this.status=e?.status??500,this.location=e?.location??`unknown`,this.time=e?.time??new Date().toISOString(),t?.cause!==void 0&&(this.cause=t.cause)}},Ze=`error.api.password.change.required`,Qe=`error.api.anti_bot.required`,$e=`error.api.anti_bot.failed`,et=`error.api.anti_bot.unavailable`,tt=`error.anti_bot.provider_missing`,nt=`error.anti_bot.provider_failed`,rt=`error.anti_bot.solve_failed`,it=`error.api.enterprise.email_invalid`,at=`error.api.enterprise.start_input`,ot=`error.api.enterprise.no_connection`,st=`error.api.enterprise.connection_ambiguous`,ct=class extends B{constructor(e,t){super(e,t),this.name=`PassflowPasswordChangeRequiredError`}},lt=`error.2fa.sms.quota.exceeded`,ut=`error.2fa.rate_limit_exceeded`,dt=`error.2fa.recovery_codes.step_up_required`,ft=`error.user.address.change.proof.required`,pt=class extends B{constructor(e,t){super(e,t),this.name=`PassflowSmsQuotaExceededError`,this.challenge=t?.challenge}},mt=class extends B{constructor(e,t,n){super(e,n),this.name=`PassflowSendLimitError`,this.retryAfter=t,this.challenge=n?.challenge}},ht=class extends B{constructor(e,t,n){super(e,n),this.name=`PassflowRecoveryCodesStepUpRequiredError`,this.challenge=t}},gt=class extends B{constructor(e,t){super(e,t),this.name=`PassflowAddressChangeProofRequiredError`}},_t=function(e){return e.google=`google`,e.facebook=`facebook`,e}({}),vt=Object.freeze([`debug_otp_code_for_registration`,`fcm_server_key`,`webpush_vapid_private_key`]),yt=`mask://`,bt=`error.server.update.settings.masked.value.unknown`,xt=e=>typeof e==`string`&&e.startsWith(`mask://`),St=function(e){return e.web=`web`,e.ios=`ios`,e.android=`android`,e}({});function Ct(e){return e}function wt(e,t){let n=e;return Object.entries(t).forEach(([e,t])=>{n=n.replace(`:${e}`,t)}),n}var Tt=function(e){return e.Disabled=`disabled`,e.Optional=`optional`,e.Required=`required`,e}({}),Et=3,Dt=1e3,Ot=e=>t=>{let n=e.headers?.[t]??e.headers?.[t.toLowerCase()];return Array.isArray(n)?n.join(`, `):n},kt=e=>Le(e.status,Ot(e),e.data),At=e=>kt(e)!==void 0,jt=e=>{let t=e.response?.data?.error;return typeof t?.id==`string`?t.id:void 0},Mt=e=>c.default.isAxiosError(e)&&!e.response&&(e.code===c.AxiosError.ERR_NETWORK||!e.code&&e.cause instanceof TypeError),Nt=[502,503,504],Pt=e=>typeof e==`object`&&!!e&&typeof e.error==`object`&&e.error!==null,Ft=(e,t)=>{let n=new c.AxiosError(e.message,e.code);return e.cause instanceof TypeError&&(n.cause=e.cause),new B({id:Ye,message:Xe,status:t,location:e.config?.url??`unknown`,time:new Date().toISOString()},{cause:n})},It=[[/(\/auth\/2fa-setup\/)[^/?#]+/g,`$1:token`],[/(\/cli\/auth\/status\/)[^/?#]+/g,`$1:sessionId`]],Lt=e=>It.reduce((e,[t,n])=>e.replace(t,n),e),Rt=e=>{if(e instanceof B)return e.location=Lt(e.location),e;if(!c.default.isAxiosError(e))return e;if(e.config){let{data:t,headers:n,url:r,...i}=e.config,a={...i,...r===void 0?{}:{url:Lt(r)},headers:new c.AxiosHeaders};e.config=a,e.response&&(e.response.config=a)}return e.request=void 0,e.response&&(e.response.request=void 0),e},zt=e=>e?.includes(z.refresh)??!1,Bt=e=>e?.includes(`/auth/session/`)??!1,Vt=e=>e?.includes(`logout`)??!1,Ht=`__passflowOwnBearer`,Ut=`__passflowRefreshedAfter401`,Wt=e=>typeof e==`object`&&!!e&&e[Ht]===!0,Gt=e=>e?{headers:{[h]:`Bearer ${e}`},[Ht]:!0}:{},Kt=`__passflowSendRefusal`,qt=e=>typeof e==`object`&&!!e&&e[Kt]===!0,Jt=(e={})=>({...e,[Kt]:!0}),Yt=e=>{let t=e?Ot(e)(`Retry-After`)?.trim():void 0;if(!t)return;if(/^\d+$/.test(t))return Number.parseInt(t,10);let n=Date.parse(t);return Number.isNaN(n)?void 0:Math.max(0,Math.ceil((n-Date.now())/1e3))},Xt=e=>{let{challenge_id:t,suggested_method:n,alternative_methods:r}=e;if(typeof t!=`string`||t===``)return;let i={challenge_id:t};return typeof n==`string`&&(i.suggested_method=n),Array.isArray(r)&&(i.alternative_methods=r.filter(e=>typeof e==`string`)),i},Zt=e=>{let t=e.response?.data;if(!Pt(t))return;let{error:n}=t,r=Xt(t);switch(n.id){case lt:return new pt(n,{challenge:r});case ut:return new mt(n,Yt(e.response),{challenge:r});default:return}},Qt={acrValues:`2`,requiredLevel:2,status:403},$t=class{get origin(){return this._platform.getCurrentUrl()?.origin??``}constructor(e,t,n){this.defaultHeaders={Accept:`application/json`,"Content-Type":`application/json`},this.nonAccessTokenEndpoints=[`/auth/`,`/settings`,`/settings/`,`/oidc/device/anti-bot/challenge`],this.protectedEndpoints=[`logout`,`refresh`,`upgrade`];let{url:r,appId:i,keyStoragePrefix:a}=e;this._platform=e.platform??ye,this.url=r||`https://auth.passflow.cloud`,this.upgradeDomain=qe(r),this.storageManager=t??new he({prefix:a??``,appId:i}),this.deviceService=n??new ge(this.storageManager),this.tokenService=new M(this.storageManager),this.tokenDeliveryManager=new fe(this.storageManager),i&&(this.appId=i,this.defaultHeaders={...this.defaultHeaders,[m]:i}),this.defaultHeaders={...this.defaultHeaders,[_]:this._platform.getDeviceType()},this.detectCookieSupport(),this.instance=c.default.create({baseURL:this.url,headers:{...this.defaultHeaders}}),this.instance.interceptors.request.use(async e=>{e.headers[g]=this.deviceService.getDeviceId();let t=f(e);if(t&&this.antiBotHandler){let n=await this.antiBotHandler(t);n&&(e.headers[v]=n.value,t.builtin=n.builtin)}if(this.isNonAuthEndpoint(e.url)||Wt(e)||Bt(e.url))return e;if(this.storageManager.getDeliveryMode()===I.Cookie){e.withCredentials=!0;let t=this.storageManager.getCsrfToken();return t&&(e.headers[`X-CSRF-Token`]=t),e}if(zt(e.url))return e;let n=this.storageManager.getTokens();if(!n?.access_token)return e;let r=n.access_token;if(this.refreshHandler&&n.refresh_token&&!Vt(e.url)){let e=P(n.access_token);if(N(e,30)){let t=!N(e,0);try{r=(await this.refreshHandler({trigger:`pre-request`,allowStale:t}))?.access_token??r}catch(e){if(!t)throw e}}}return e.headers[h]=`Bearer ${r}`,e}),this.instance.interceptors.response.use(e=>e,e=>this.onResponseError(e).catch(e=>Promise.reject(Rt(e))))}async onResponseError(e){if(e.response?.status===401&&!zt(e.config?.url)&&!Bt(e.config?.url)&&!Wt(e.config)&&!this.isUpgradeTransactionError(e)){if(e.config&&await this.refreshedAfterUnauthorized(e.config))return this.instance.request(e.config);this.tokenDeliveryManager.setSessionInvalid()}let t=f(e.config);if(e.config&&e.response?.status===403&&jt(e)===`error.api.anti_bot.failed`&&t?.builtin&&!t.retried)return t.retried=!0,this.instance.request(e.config);if(e.response&&this.upgradeHandler&&!Bt(e.config?.url)){let t=kt(e.response);if(t)try{return await this.upgradeHandler(e,t)}catch(t){if(t!==e)throw t}}if(e.response?.status===429){let t=qt(e.config)?Zt(e):void 0;return t?Promise.reject(t):await this.handleRateLimitError(e)}return this.handleAxiosError(e)}isUpgradeTransactionError(e){return He(e.config)||e.response!==void 0&&At(e.response)}setUpgradeInterceptor(e){this.upgradeHandler=e}setRefreshHandler(e){this.refreshHandler=e}setAntiBotHandler(e){this.antiBotHandler=e}replay(e){return this.instance.request(e)}isProtectedEndpoint(e){return this.protectedEndpoints.some(t=>e?.includes(t))}async refreshedAfterUnauthorized(e){let t=e,n=this.storageManager.getDeliveryMode();if(!this.refreshHandler||t[Ut]||n!==I.Cookie&&n!==I.BFF||this.isNonAuthEndpoint(e.url)||Vt(e.url))return!1;t[Ut]=!0;try{return await this.refreshHandler({trigger:`pre-request`,allowStale:!1})!==void 0}catch{return!1}}isNonAuthEndpoint(e){return this.nonAccessTokenEndpoints.some(t=>e?.includes(t))&&!this.isProtectedEndpoint(e)}detectCookieSupport(){if(!this._platform.cookiesSupported()&&this.tokenDeliveryManager.isCookieMode())throw Error(`Passflow SDK: Cookie delivery mode is configured but cookies are not supported in this environment. Use a platform adapter that supports cookies or configure the server to use JSON token delivery.`)}async handleRateLimitError(e){let t=e.config;if(!t||zt(t.url))return Promise.reject(e);let n=t.method?.toUpperCase();if(![`GET`,`HEAD`,`OPTIONS`].includes(n||``))return Promise.reject(e);let r=t._retryCount||0;if(r>=Et)return Promise.reject(e);let i=Dt*2**r,a=e.response?.headers?.[`retry-after`];if(a){let e=Number.parseInt(a,10);if(!Number.isNaN(e))i=e*1e3;else{let e=new Date(a);Number.isNaN(e.getTime())||(i=Math.max(0,e.getTime()-Date.now()))}}return await new Promise(e=>setTimeout(e,i)),t._retryCount=r+1,this.instance.request(t)}async handleAxiosError(e){if(Mt(e))return Promise.reject(Ft(e,0));if(!e.response)return Promise.reject(e);let t=e.response.status;if(Nt.includes(t)&&!Pt(e.response.data))return Promise.reject(Ft(e,t));let n=e.response.data;if(`error`in n&&typeof n.error==`object`&&n.error!==null){let{error:t}=n;switch(t.id){case Ze:return Promise.reject(new ct(t));case ft:return Promise.reject(new gt(t));case dt:return Promise.reject(new ht(t,kt(e.response)??{...Qt}));default:return Promise.reject(new B(t))}}return Promise.reject(new B({id:`error.http.${t}`,message:e.message||`An error occurred`,status:t,location:e.config?.url||`unknown`,time:new Date().toISOString()}))}async send(e,t,n){return(await this.instance.request({method:e,url:t,...n})).data}get(e,t){return this.send(Ge.GET,e,t)}post(e,t,n){return this.send(Ge.POST,e,{data:t,...n})}put(e,t,n){return this.send(Ge.PUT,e,{data:t,...n})}patch(e,t,n){return this.send(Ge.PATCH,e,{data:t,...n})}delete(e,t){return this.send(Ge.DELETE,e,t)}setAppId(e){this.appId=e,this.tokenDeliveryManager.reload(),this.defaultHeaders={...this.defaultHeaders,[m]:e},this.instance.defaults.headers[m]=e}},en=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getAppSettings(){return this.axiosClient.get(z.appSettings)}},tn={withCredentials:!0},nn=15e3,rn=`X-Passflow-CSRF`,an=`Sign-in failed. Start again.`,on=`Something went wrong. Try again later.`,sn=(e,t,n,r)=>{if(e instanceof B)return e;let i=e?.response?.data?.error;return new B({id:typeof i?.id==`string`?i.id:n,message:typeof i?.message==`string`?i.message:r,status:typeof i?.status==`number`?i.status:0,location:t,time:new Date().toISOString()})},V=(e,t,n,r)=>!t&&!r?.agentTool?e:{...e,...t?d(t,n):{},...r?.agentTool?{headers:{...e?.headers,[y]:`1`}}:{}},cn=(e,t)=>t?{...e,headers:{...e?.headers,[b]:t}}:e,ln=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}setAntiBotHandler(e){this.axiosClient.setAntiBotHandler(e)}async antiBotChallenge(e){try{return await this.axiosClient.post(z.antiBotChallenge,e)}catch(e){throw sn(e,z.antiBotChallenge,`error.anti_bot.challenge`,on)}}async deviceChallenge(){try{return await this.axiosClient.post(z.deviceChallenge)}catch(e){throw sn(e,z.deviceChallenge,`error.device.challenge`,on)}}async deviceAntiBotChallenge(e,t){try{return await this.axiosClient.post(z.deviceAntiBotChallenge,e,{headers:{[rn]:t}})}catch(e){throw sn(e,z.deviceAntiBotChallenge,`error.anti_bot.challenge`,on)}}federatedStart(e,t,n){return this.axiosClient.post(`${z.signInWithProvider}${e}`,t,V(tn,`federated.start`,void 0,n))}enterpriseResolve(e){return this.axiosClient.post(z.enterpriseResolve,{email:e})}enterpriseStart(e,t){return this.axiosClient.post(z.enterpriseStart,e,V(tn,`federated.start`,e.email,t))}refreshToken(e,t,n,r,i){let a={access:n,scopes:t,...r?{upgrade:r}:{}},o=i?{headers:{[h]:`Bearer ${e}`,...i.proof?{[b]:i.proof}:{}},withCredentials:!0}:{headers:{[h]:`Bearer ${e}`}};return this.axiosClient.post(z.refresh,a,r?Ve(o):o)}signIn(e,t,n,r,i){let a={...e,device:t,os:n};return this.axiosClient.post(z.signin,a,cn(V(tn,`sign-in`,e.email??e.phone??e.username,r),i))}signUp(e,t){let{create_tenant:n,anonymous:r}=e,i={...e,create_tenant:n??!1,anonymous:r??!1};return this.axiosClient.post(z.signup,i,V(tn,`sign-up`,e.user.email??e.user.phone_number??e.user.username,t))}async pkceExchange(e,t){try{return await this.axiosClient.post(z.pkceExchange,{authz_code:e,verifier:t},tn)}catch(e){throw sn(e,z.pkceExchange,`error.pkce.exchange`,an)}}async passwordlessSignIn(e,t,n,r){let{create_tenant:i}=e,a={...e,create_tenant:i??!1,device:t,os:n};try{return await this.axiosClient.post(z.passwordless,a,V(void 0,`passwordless.start`,e.email??e.phone,r))}catch(e){throw sn(e,z.passwordless,`error.passwordless.start`,on)}}async passwordlessSignInComplete(e,t){try{return await this.axiosClient.post(z.passwordlessComplete,e,V(tn,void 0,void 0,t))}catch(e){throw sn(e,z.passwordlessComplete,`error.passwordless.complete`,on)}}async passwordlessStatus(e,t){try{return await this.axiosClient.post(z.passwordlessStatus,e,{...tn,timeout:nn,signal:t?.signal})}catch(e){throw sn(e,z.passwordlessStatus,`error.passwordless.status`,an)}}async checkRedirectUrl(e){try{return(await this.axiosClient.post(z.redirectCheck,{redirect_url:e})).redirect_url}catch(e){throw sn(e,z.redirectCheck,`error.redirect.check`,on)}}async passwordlessApprovalInfo(e){try{return await this.axiosClient.post(z.passwordlessApprovalInfo,e)}catch(e){throw sn(e,z.passwordlessApprovalInfo,`error.passwordless.approval`,on)}}async passwordlessApprovalDecide(e){try{return await this.axiosClient.post(z.passwordlessApprovalDecide,e)}catch(e){throw sn(e,z.passwordlessApprovalDecide,`error.passwordless.approval`,on)}}validateEmailCode(e){return this.axiosClient.post(z.passkeyValidate,{challenge_id:e.challenge_id,otp:e.otp},tn)}logOut(e,t,n=!1,r){let i=n?void 0:{refresh_token:t,device:e,...r?{post_logout_redirect_uri:r}:{}},a=n?Ke.logout:z.logout;return this.axiosClient.post(a,i)}validateSession(){return this.axiosClient.get(z.validateSession)}sendPasswordResetEmail(e,t){return this.axiosClient.post(z.sendPasswordResetEmail,e,V(void 0,`password-reset.send`,e.email??e.phone??e.username,t))}resetPassword(e,t,n,r){let i={password:e,scopes:t,...r?{code_challenge:r}:{}};return this.axiosClient.post(z.resetPassword,i,{headers:{[h]:`Bearer ${n}`,[m]:void 0}})}passkeyRegisterStart(e,t,n,r=!1,i){let{create_tenant:a}=e,o={...e,create_tenant:a??!1,device:t,os:n},s=r?Ke.passkeyRegisterStart:z.passkeyRegisterStart;return this.axiosClient.post(s,o,V(void 0,r?void 0:`passkey.register`,e.passkey_username,i))}passkeyRegisterComplete(e,t,n,r=!1,i){let a={challenge_id:n,device:t,passkey_data:e},o=r?Ke.passkeyRegisterComplete:z.passkeyRegisterComplete;return this.axiosClient.post(o,a,V(tn,void 0,void 0,i))}passkeyAuthenticateStart(e,t,n,r=!1,i){let a={...e,user_id:e.user_id??``,device:t,os:n},o=r?Ke.passkeyAuthenticateStart:z.passkeyAuthenticateStart;return this.axiosClient.post(o,a,V(void 0,r?void 0:`passkey.authenticate`,void 0,i))}passkeyAuthenticateComplete(e,t,n,r=!1,i,a){let o={challenge_id:n,device:t,passkey_data:e},s=r?Ke.passkeyAuthenticateComplete:z.passkeyAuthenticateComplete;return this.axiosClient.post(s,o,cn(V(tn,void 0,void 0,i),a))}passkeyValidate(e,t,n,r=!1,i){let a={otp:e,device:t,challenge_id:n},o=z.passkeyValidate;!i&&r&&(o=Ke.passkeyValidate);let s=i?{[m]:i}:{};return this.axiosClient.post(o,a,{headers:s})}},un=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getCLIAuthStatus(e){let t=wt(z.cliAuthStatus,{sessionId:e});return this.axiosClient.get(t)}completeCLIAuth(e){return this.axiosClient.post(z.cliAuthComplete,e)}},dn=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}requestInviteLink(e){return this.axiosClient.post(z.requestInvitation,e)}getInvitations(e){let t={};e.groupID&&(t.group_id=e.groupID.toString()),e.skip!==void 0&&(t.skip=e.skip.toString()),e.limit!==void 0&&(t.limit=e.limit.toString());let n=wt(z.invitationsPath,{tenantID:e.tenantID});return this.axiosClient.get(n,{params:t}).then(e=>({invites:e.invites,nextPageSkip:e.next_page_skip}))}deleteInvitation(e){let t=wt(z.invitationDelete,{invitationID:e});return this.axiosClient.delete(t)}resendInvitation(e){let t=wt(z.invitationResend,{invitationID:e});return this.axiosClient.post(t,{})}getInvitationLink(e){let t=wt(z.invitationGetLink,{invitationID:e});return this.axiosClient.get(t)}},fn=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getSettingsAll(){return this.axiosClient.get(z.settingsAll)}getPasswordPolicySettings(){return this.axiosClient.get(z.settingsPasswordPolicy)}getPasskeySettings(){return this.axiosClient.get(z.settingsPasskey)}},pn=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}joinInvitation(e,t){let n={invite_token:e,scopes:t};return this.axiosClient.post(z.joinInvitation,n)}createTenant(e){let t={name:e};return this.axiosClient.post(z.tenantPath,t)}getTenantDetails(e){let t=`${z.tenantPath}/${e}`;return this.axiosClient.get(t)}updateTenant(e,t){let n=`${z.tenantPath}/${e}`,r={name:t};return this.axiosClient.put(n,r)}deleteTenant(e){let t=`${z.tenantPath}/${e}`;return this.axiosClient.delete(t)}getUserTenantMembership(){return this.axiosClient.get(z.tenantPath)}createGroup(e,t){let n=`${z.tenantPath}/${e}/group`,r={name:t};return this.axiosClient.post(n,r)}getGroupInfo(e,t){let n=`${z.tenantPath}/${e}/group/${t}`;return this.axiosClient.get(n)}updateGroup(e,t,n){let r=`${z.tenantPath}/${e}/group/${t}`,i={name:n};return this.axiosClient.put(r,i)}deleteGroup(e,t){let n=`${z.tenantPath}/${e}/group/${t}`;return this.axiosClient.delete(n)}addUserToGroup(e,t,n,r){let i=`${z.tenantPath}/${e}/group/${t}/add`,a={user_id:n,role:r};return this.axiosClient.post(i,a)}removeUserRolesFromGroup(e,t,n,r){let i=`${z.tenantPath}/${e}/group/${t}/remove_roles`,a={user_id:n,roles:r};return this.axiosClient.post(i,a)}changeUserRoles(e,t,n,r){let i=`${z.tenantPath}/${e}/group/${t}/change`,a={user_id:n,roles:r};return this.axiosClient.post(i,a)}deleteUserFromGroup(e,t,n){let r=`${z.tenantPath}/${e}/group/${t}/${n}`;return this.axiosClient.delete(r)}getRolesForTenant(e){let t=`${z.tenantPath}/${e}/role`;return this.axiosClient.get(t)}createRoleForTenant(e,t){let n=`${z.tenantPath}/${e}/role`,r={name:t};return this.axiosClient.post(n,r)}updateRole(e,t,n){let r=`${z.tenantPath}/${e}/role/${t}`,i={name:n};return this.axiosClient.put(r,i)}deleteRole(e,t){let n=`${z.tenantPath}/${e}/role/${t}`;return this.axiosClient.delete(n)}deleteUserFromTenant(e,t){let n=`${z.tenantPath}/${e}/user/${t}`;return this.axiosClient.delete(n)}getGroupInvitations(e,t,n,r){let i=`${z.tenantPath}/${e}/group/${t}/invitations`;return this.axiosClient.get(i,{params:{limit:n,skip:r}})}getTenantInvitations(e,t,n){let r=`${z.tenantPath}/${e}/invitations`;return this.axiosClient.get(r,{params:{limit:t,skip:n}})}invalidateInviteById(e,t,n){let r=`${z.tenantPath}/${e}/group/${t}/invite/${n}`;return this.axiosClient.delete(r)}invalidateInviteByEmail(e,t,n){let r=`${z.tenantPath}/${e}/group/${t}/invite/email/${n}`;return this.axiosClient.delete(r)}},mn=e=>e?{headers:{Authorization:`Bearer ${e}`}}:{},hn=e=>({withCredentials:!0,...mn(e)}),gn=({qr_code_image:e,qr_code:t,...n})=>({...n,qr_code:(t??e??``).replace(/^data:image\/png;base64,/,``)}),_n={"error.2fa.setup.token.expired":`EXPIRED_TOKEN`,"error.2fa.setup.token.revoked":`REVOKED_TOKEN`,"error.2fa.setup.token.already_used":`ALREADY_USED`,"error.2fa.setup.token.rate.limit.exceeded":`RATE_LIMITED`},vn=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getStatus(e){return this.axiosClient.get(z.twoFactorStatus,Gt(e))}async beginSetup(e){return gn(await this.axiosClient.post(z.twoFactorSetupBegin,{},Gt(e)))}confirmSetup(e,t){return this.axiosClient.post(z.twoFactorSetupConfirm,e,Gt(t))}getEnrollment(e){return this.axiosClient.get(z.twoFactorEnrollment,Gt(e))}sendSetupLink(e){return this.axiosClient.post(z.twoFactorEnrollmentEmailLink,void 0,Gt(e))}async beginEnrollment(e){return gn(await this.axiosClient.post(z.twoFactorEnrollmentBegin,void 0,Gt(e)))}confirmEnrollment(e,t){return this.axiosClient.post(z.twoFactorEnrollmentConfirm,t,Gt(e))}verify(e){let{tfa_token:t,code:n,trust_device:r}=e;return this.axiosClient.post(z.twoFactorVerify,{code:n,...r?{trust_device:!0}:{}},hn(t))}useRecoveryCode(e){let{tfa_token:t,recovery_code:n,trust_device:r}=e;return this.axiosClient.post(z.twoFactorRecovery,{recovery_code:n,...r?{trust_device:!0}:{}},hn(t))}disable(e){return this.axiosClient.delete(z.twoFactor,{data:e})}regenerateRecoveryCodes(e){return this.axiosClient.post(z.twoFactorRegenerateCodes,e)}validateTwoFactorSetupMagicLink(e){let t=`${z.twoFactorSetupMagicLink}/${e}`;return this.axiosClient.get(t,{transformRequest:[(e,t)=>(t&&delete t.Authorization,e)]}).then(e=>{let t=e;return t.valid===!1?{success:!1,error:{code:`INVALID_TOKEN`,message:this.getDefaultErrorMessage(400)}}:{success:!0,sessionToken:t.session_token,userId:t.user_id,expiresIn:t.expires_in,appId:t.app_id,reset:t.reset===!0}}).catch(e=>{if(e instanceof B)return{success:!1,error:{code:_n[e.id]??this.mapStatusToErrorCode(e.status),message:e.message||this.getDefaultErrorMessage(e.status)}};if(e.response){let t=e.response.status,n=e.response.data||{},r=e.response.headers?.[`retry-after`]?parseInt(e.response.headers[`retry-after`],10):void 0;return{success:!1,error:{code:n.error||this.mapStatusToErrorCode(t),message:n.message||this.getDefaultErrorMessage(t),retryAfter:r}}}return{success:!1,error:{code:`SERVER_ERROR`,message:e instanceof Error?e.message:`Unable to connect to the server. Please check your connection.`}}})}mapStatusToErrorCode(e){switch(e){case 400:return`INVALID_TOKEN`;case 404:return`REVOKED_TOKEN`;case 410:return`EXPIRED_TOKEN`;case 429:return`RATE_LIMITED`;default:return`SERVER_ERROR`}}getDefaultErrorMessage(e){switch(e){case 400:return`The provided magic link is invalid or malformed.`;case 404:return`This magic link has been revoked or does not exist.`;case 410:return`This magic link has expired. Please request a new one from your administrator.`;case 429:return`Too many validation attempts. Please try again later.`;default:return`An error occurred while validating the magic link.`}}async getAvailableMethods(){return(await this.axiosClient.get(z.TwoFactorMethodsAvailable))?.available_methods??[]}async getRegisteredMethods(e){let t=Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!==void 0));return(await this.axiosClient.get(z.TwoFactorMethodsRegistered,Object.keys(t).length>0?{params:t}:void 0))?.registered_methods??[]}startMethodSetup(e,t){return this.axiosClient.post(z.TwoFactorSetupStart,{...t,method:e})}completeMethodSetup(e,t){return this.axiosClient.post(z.TwoFactorSetupComplete,{...t,method:e})}startRecoveryCodesByCode(e){return this.axiosClient.post(z.TwoFactorSetupStart,{method:`recovery_codes`,via:e},Jt())}completeRecoveryCodesByCode(e,t){return this.axiosClient.post(z.TwoFactorSetupComplete,{method:`recovery_codes`,setup_id:e,code:t},Jt())}removeMethod(e){let t=wt(z.TwoFactorMethodRemove,{id:e});return this.axiosClient.delete(t)}requestChallenge(e,t){return this.axiosClient.post(z.TwoFactorChallenge,e,Jt(mn(t)))}verifyV2(e,t){let{trust_device:n,response:r,...i}=e;return this.axiosClient.post(z.TwoFactorVerifyV2,{...i,...r===void 0?{}:{response:r},...n?{trust_device:!0}:{}},hn(t))}switchToAlternative(e,t){return this.axiosClient.post(z.TwoFactorAlternative,e,Jt(mn(t)))}async pushStatus(e,t){let n=await this.axiosClient.post(z.TwoFactorPushStatus,{challenge_id:e},Jt(mn(t)));return n.status===`approved`?{status:`approved`}:{status:`pending`,expires_in_seconds:n.expires_in_seconds??0}}async getTrustedDevices(){return(await this.axiosClient.get(z.TwoFactorTrustedDevices,{withCredentials:!0}))?.devices??[]}revokeTrustedDevice(e){let t=wt(z.TwoFactorTrustedDeviceRevoke,{id:e});return this.axiosClient.delete(t)}async getPreferredMethod(){return(await this.axiosClient.get(z.TwoFactorPreferredMethod))?.preferred_method??null}async setPreferredMethod(e){return(await this.axiosClient.put(z.TwoFactorPreferredMethod,{method:e}))?.preferred_method??e}async clearPreferredMethod(){await this.axiosClient.delete(z.TwoFactorPreferredMethod)}},yn=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}startUpgrade(e){return this.axiosClient.post(z.upgradeStart,e,Ve({}))}startHostedUpgrade(e){return this.axiosClient.post(z.hostedUpgradeStart,e,{withCredentials:!0})}async commitHostedUpgrade(e){await this.axiosClient.post(z.hostedUpgrade,e,{withCredentials:!0})}},bn=class{constructor(e,t,n){this.axiosClient=new $t(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}enrolDeviceKey(e){return this.axiosClient.post(z.userDeviceKey,e)}getUserPasskeys(){return this.axiosClient.get(z.userPasskey)}renameUserPasskey(e,t){return this.axiosClient.patch(`${z.userPasskey}/${t}`,{name:e})}deleteUserPasskey(e){return this.axiosClient.delete(`${z.userPasskey}/${e}`)}addUserPasskeyStart({relyingPartyId:e,deviceId:t,os:n,passkeyDisplayName:r,passkeyUsername:i}){let a={passkey_display_name:r,passkey_username:i,relying_party_id:e,deviceId:t,os:n};return this.axiosClient.post(z.addUserPasskey,a)}addUserPasskeyComplete(e,t,n){return this.axiosClient.post(z.completeAddUserPasskey,{challenge_id:n,device:t,passkey_data:e})}getUserSessions(){return this.axiosClient.get(z.userSessions)}revokeUserSession(e){return this.axiosClient.delete(`${z.userSessions}/${encodeURIComponent(e)}`)}revokeOtherUserSessions(){return this.axiosClient.post(z.userSessionsRevokeOthers)}requestAddressChangeProof(e){return this.axiosClient.post(z.AddressChangeProof,{method:e},Jt())}updateProfile(e,t){return this.axiosClient.patch(z.userProfile,{...e,...t?{proof:t}:{}},Jt())}},xn=`pf-device-proof+jwt`,Sn={name:`ECDSA`,hash:`SHA-256`};function Cn(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function wn(e){return Cn(new TextEncoder().encode(JSON.stringify(e)))}async function Tn(e){let{kty:t,crv:n,x:r,y:i}=e.jwk,a=`${wn({alg:`ES256`,typ:xn,jwk:{kty:t,crv:n,x:r,y:i}})}.${wn({jti:e.jti,ctr:e.ctr,did:e.did,use:e.use,iat:e.iat})}`,o=await crypto.subtle.sign(Sn,e.privateKey,new TextEncoder().encode(a));return`${a}.${Cn(new Uint8Array(o))}`}async function En(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return Cn(new Uint8Array(t))}async function Dn(e,t=``){let n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(`${e}\n${t}`));return Cn(new Uint8Array(n))}var On=1,kn=`key`,An=`current`,jn=e=>new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)}),Mn=e=>new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error??Error(`The device key transaction was aborted`))});function Nn(e){let t,n=()=>(t??(t=new Promise((t,n)=>{let r=indexedDB.open(e,On);r.onupgradeneeded=()=>{r.result.objectStoreNames.contains(kn)||r.result.createObjectStore(kn)},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error),r.onblocked=()=>n(Error(`The device key database is blocked by another tab`))}).catch(e=>{throw t=void 0,e})),t),r=async e=>{let t=(await n()).transaction(kn,`readwrite`),r=Mn(t),i=await e(t.objectStore(kn));return await r,i},i=e=>jn(e.get(An)),a=async()=>{let e=await n();return await i(e.transaction(kn,`readonly`).objectStore(kn))};return{read:a,async ensure(e){let t=await a();if(t)return t;let n=await e();return await r(async e=>{let t=await i(e);if(t)return t;let r={...n,counter:0,enrolled:!1};return e.put(r,An),r})},next(){return r(async e=>{let t=await i(e);if(!t)return;let n=t.counter+1,r={...t,counter:n};return e.put(r,An),{record:r,ctr:n}})},async markEnrolled(){await r(async e=>{let t=await i(e);t&&e.put({...t,enrolled:!0},An)})},async clear(){await r(e=>jn(e.delete(An)))}}}var Pn=`Device keys need IndexedDB and WebCrypto`,Fn={name:`ECDSA`,namedCurve:`P-256`};function In(e){return`${e?`${e}_`:``}passflow_device_key`}function Ln(){return typeof indexedDB<`u`&&typeof crypto<`u`&&crypto.subtle!==void 0}async function Rn(){let e=await crypto.subtle.generateKey(Fn,!1,[`sign`,`verify`]),{kty:t,crv:n,x:r,y:i}=await crypto.subtle.exportKey(`jwk`,e.publicKey);if(t!==`EC`||n!==`P-256`||!r||!i)throw Error(`The device key could not be exported`);return{keyPair:e,jwk:{kty:t,crv:n,x:r,y:i}}}function zn(e){let t=e.now??Date.now,n=Ln(),r=n?Nn(e.dbName):void 0,i=(n,r,i,a)=>Tn({privateKey:n.keyPair.privateKey,jwk:n.jwk,jti:a,ctr:r,did:e.deviceId(),use:i,iat:Math.floor(t()/1e3)});return{supported:n,async isEnrolled(){return r?(await r.read())?.enrolled===!0:!1},async proof(e,t){if(!r)return;let n=await r.next();if(n?.record.enrolled)return await i(n.record,n.ctr,e,t)},async enrolProof(e){if(!r)throw Error(Pn);await r.ensure(Rn);let t=await r.next();if(!t)throw Error(`The device key was deleted while enrolling`);return await i(t.record,t.ctr,`enrol`,e)},async markEnrolled(){await r?.markEnrolled()},async clear(){await r?.clear()}}}var Bn={keyReused:`error.device.key.reused`,proofRequired:`error.device.proof.required`,stepUpRequired:`error.device.key.step_up_required`,proofUnavailable:`error.device.proof.unavailable`},Vn=e=>typeof e==`string`&&e.startsWith(`error.device.`),Hn=10,Un=20,Wn=class extends Error{constructor(e){super(`Passflow fetch middleware '${e}' resolved without calling next(). Every registered middleware must delegate exactly once; swallowing a request would drop a caller's fetch inside the Passflow wrapper.`),this.name=`FetchMiddlewareContractError`,this.middlewareName=e}},Gn=[],Kn=0,qn=!1,Jn,Yn,Xn=(e,t)=>e.priority-t.priority||e.seq-t.seq,Zn=()=>typeof globalThis>`u`?void 0:globalThis,Qn=async(e,t,n,r)=>{if(t>=e.length){let e=Jn;if(!e)throw Error(`Passflow fetch registry: no captured fetch to delegate to.`);return e(n,r)}let i=e[t];if(!i)return Qn(e,e.length,n,r);let a=!1,o=await i.middleware((n,r)=>(a=!0,Qn(e,t+1,n,r)),n,r);if(!a)throw new Wn(i.name);return o},$n=()=>{let e=Zn();if(!e||typeof e.fetch!=`function`)return!1;let t=e.fetch.bind(e),n=(e,t)=>Qn([...Gn].sort(Xn),0,e,t);return Jn=t,Yn=n,e.fetch=n,qn=!0,!0},er=()=>{let e=Zn();e&&Yn&&e.fetch===Yn&&(Jn&&(e.fetch=Jn),qn=!1,Yn=void 0,Jn=void 0)},tr=(e,t)=>{if(!qn&&!$n())return()=>{};let n={middleware:e,name:t.name,priority:t.priority,seq:Kn++};Gn.push(n);let r=!1;return()=>{r||(r=!0,Gn=Gn.filter(e=>e!==n),Gn.length===0&&er())}},nr=()=>{let e=Zn();return{installed:qn,names:[...Gn].sort(Xn).map(e=>e.name),foreignPatch:qn&&!!e&&!!Yn&&e.fetch!==Yn}},H=class e extends Error{constructor(t){super(t.message),this.name=`M2MError`,this.code=t.code,this.status=t.status??400,this.errorUri=t.errorUri,this.rateLimitInfo=t.rateLimitInfo,this.headers=t.headers,this.cause=t.cause,this.timestamp=new Date().toISOString(),Error.captureStackTrace&&Error.captureStackTrace(this,e)}static fromOAuthError(t,n,r){let i=r?e.parseRateLimitHeaders(r):void 0;return new e({code:t.error,message:t.error_description??e.getDefaultMessage(t.error),status:n,errorUri:t.error_uri,rateLimitInfo:i,headers:r})}static fromError(t,n=`server_error`){return new e({code:n,message:t.message||`An unexpected error occurred`,status:500,cause:t})}static parseRateLimitHeaders(e){let t=e[`x-ratelimit-limit`],n=e[`x-ratelimit-remaining`],r=e[`x-ratelimit-reset`]||e[`retry-after`];if(t&&n&&r)return{limit:parseInt(t,10),remaining:parseInt(n,10),reset:parseInt(r,10)}}static getDefaultMessage(e){return{invalid_request:`The request is missing a required parameter or is otherwise malformed.`,invalid_client:`Client authentication failed. Verify your client credentials.`,invalid_grant:`The provided authorization grant is invalid or expired.`,invalid_scope:`The requested scope is invalid, unknown, or exceeds the allowed scopes.`,unauthorized_client:`The client is not authorized to use this grant type.`,unsupported_grant_type:`The authorization grant type is not supported.`,rate_limit_exceeded:`Too many requests. Please retry after the rate limit window resets.`,server_error:`The authorization server encountered an unexpected error.`,temporarily_unavailable:`The authorization server is temporarily unavailable. Please try again later.`}[e]||`An unknown error occurred.`}isRetryable(){return this.code===`server_error`||this.code===`temporarily_unavailable`||this.code===`rate_limit_exceeded`||this.status>=500}getRetryAfter(){if(this.rateLimitInfo?.reset){let e=Math.floor(Date.now()/1e3),t=this.rateLimitInfo.reset-e;return Math.max(t*1e3,1e3)}return 1e3}toJSON(){return{name:this.name,code:this.code,message:this.message,status:this.status,errorUri:this.errorUri,rateLimitInfo:this.rateLimitInfo,timestamp:this.timestamp}}toString(){let e=`M2MError [${this.code}]: ${this.message}`;return this.status&&(e+=` (HTTP ${this.status})`),e}},rr=class extends H{constructor(e,t){super({code:`temporarily_unavailable`,message:e,status:0,cause:t}),this.name=`M2MNetworkError`}},ir=class extends H{constructor(e,t){super({code:`invalid_request`,message:e,status:400,cause:t}),this.name=`M2MTokenParseError`}},ar=class extends H{constructor(e){super({code:`invalid_request`,message:e,status:400}),this.name=`M2MConfigError`}},or={InvalidRequest:`invalid_request`,InvalidClient:`invalid_client`,InvalidGrant:`invalid_grant`,InvalidScope:`invalid_scope`,UnauthorizedClient:`unauthorized_client`,UnsupportedGrantType:`unsupported_grant_type`,RateLimitExceeded:`rate_limit_exceeded`,ServerError:`server_error`,TemporarilyUnavailable:`temporarily_unavailable`},sr={TOKEN_ENDPOINT:`/oauth2/token`,TIMEOUT:1e4,RETRIES:3,RETRY_DELAY:1e3,REFRESH_THRESHOLD:30,CONTENT_TYPE:`application/x-www-form-urlencoded`},cr=class{constructor(){this.cache=new Map}get(e){let t=this.cache.get(e);return t?Date.now()>=t.expiresAt?(this.cache.delete(e),Promise.resolve(null)):Promise.resolve(t.token):Promise.resolve(null)}set(e,t,n){return this.cache.set(e,{token:t,expiresAt:Date.now()+n*1e3}),Promise.resolve()}delete(e){return this.cache.delete(e),Promise.resolve()}},lr={shouldRetry(e,t){return t>=3?!1:e.code===`server_error`||e.code===`temporarily_unavailable`||e.code===`rate_limit_exceeded`||e.status!==void 0&&e.status>=500},getDelay(e){return 2**(e-1)*1e3}},ur=class{constructor(e){if(!e.url)throw new ar(`M2M client requires a URL`);if(!e.clientId)throw new ar(`M2M client requires a clientId`);if(!e.clientSecret)throw new ar(`M2M client requires a clientSecret`);let t=e.url.replace(/\/$/,``);this.config={url:t,clientId:e.clientId,clientSecret:e.clientSecret,scopes:e.scopes,audience:e.audience,autoRefresh:e.autoRefresh??!1,refreshThreshold:e.refreshThreshold??sr.REFRESH_THRESHOLD,timeout:e.timeout??sr.TIMEOUT,retries:e.retries??sr.RETRIES,retryDelay:e.retryDelay??sr.RETRY_DELAY,retryStrategy:e.retryStrategy,cache:e.cache,onTokenRequest:e.onTokenRequest,onTokenResponse:e.onTokenResponse,onError:e.onError},this.cache=e.cache??new cr,this.retryStrategy=e.retryStrategy??lr,this.tokenEndpoint=`${t}${sr.TOKEN_ENDPOINT}`}getCacheKey(e,t){let n=e?.sort().join(`,`)||``,r=t?.sort().join(`,`)||``;return`m2m:${this.config.clientId}:${n}:${r}`}async getToken(e){let t=e?.scopes??this.config.scopes,n=e?.audience??this.config.audience,r=this.getCacheKey(t,n);if(!e?.forceRefresh){let e=await this.cache.get(r);if(e&&!this.isTokenExpired(e))return e}return this.requestToken(t,n,r)}async getValidToken(){let e=this.config.scopes,t=this.config.audience,n=this.getCacheKey(e,t),r=await this.cache.get(n);if(r){if(this.config.autoRefresh&&this.isTokenExpired(r,this.config.refreshThreshold))return this.requestToken(e,t,n);if(!this.isTokenExpired(r))return r}return this.requestToken(e,t,n)}async requestToken(e,t,n){let r={grant_type:`client_credentials`,client_id:this.config.clientId,client_secret:this.config.clientSecret};e&&e.length>0&&(r.scope=e.join(` `)),t&&t.length>0&&(r.audience=t.join(` `)),this.config.onTokenRequest&&this.config.onTokenRequest({clientId:this.config.clientId,scopes:e??[],audience:t??[],timestamp:new Date().toISOString()});let i=await this.executeWithRetry(()=>this.doTokenRequest(r));return i.issued_at=Math.floor(Date.now()/1e3),n&&await this.cache.set(n,i,i.expires_in),this.config.onTokenResponse&&this.config.onTokenResponse(i),i}async doTokenRequest(e){let t=new URLSearchParams;t.append(`grant_type`,e.grant_type),t.append(`client_id`,e.client_id),t.append(`client_secret`,e.client_secret),e.scope&&t.append(`scope`,e.scope),e.audience&&t.append(`audience`,e.audience);let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeout);try{let e=await fetch(this.tokenEndpoint,{method:`POST`,headers:{"Content-Type":sr.CONTENT_TYPE,Accept:`application/json`},body:t.toString(),signal:n.signal});clearTimeout(r);let i={};e.headers.forEach((e,t)=>{i[t.toLowerCase()]=e});let a=await e.json();if(!e.ok){let t=H.fromOAuthError({error:a.error||`server_error`,error_description:a.error_description||a.message,error_uri:a.error_uri},e.status,i);throw this.config.onError&&this.config.onError({error:t.code,error_description:t.message}),t}return a}catch(e){throw clearTimeout(r),e instanceof Error&&e.name===`AbortError`?new rr(`Request timed out after ${this.config.timeout}ms`):e instanceof TypeError&&e.message.includes(`fetch`)?new rr(`Network error: ${e.message}`,e):e instanceof H?e:H.fromError(e instanceof Error?e:Error(String(e)))}}async executeWithRetry(e){let t;for(let n=1;n<=this.config.retries;n++)try{return await e()}catch(e){if(!(e instanceof H))throw e;if(t=e,n<this.config.retries&&this.retryStrategy.shouldRetry({code:e.code,status:e.status},n)){let e=this.retryStrategy.getDelay(n);await this.sleep(e);continue}throw e}throw t??new H({code:`server_error`,message:`Request failed after retries`})}sleep(e){return new Promise(t=>setTimeout(t,e))}getCachedToken(){let e=this.cache;if(`cache`in e){let t=this.getCacheKey(this.config.scopes,this.config.audience);return e.cache.get(t)?.token??null}return null}isTokenExpired(e,t=0){if(!e)return!0;let n=Math.floor(Date.now()/1e3);return n>=(e.issued_at??n-e.expires_in)+e.expires_in-t}parseToken(e){try{let t=e.split(`.`);if(t.length!==3)throw new ir(`Invalid JWT format: expected 3 parts`);let n=t[1];if(!n)throw new ir(`Invalid JWT format: missing payload`);let r=atob(n.replace(/-/g,`+`).replace(/_/g,`/`)),i=JSON.parse(r);return i.scopes&&typeof i.scopes==`string`?i.scopes=i.scopes.split(` `):i.scopes||(i.scopes=[]),i}catch(e){throw e instanceof ir?e:new ir(`Failed to parse token: ${e instanceof Error?e.message:`Unknown error`}`)}}clearCache(){let e=this.getCacheKey(this.config.scopes,this.config.audience);this.cache.delete(e)}async revokeToken(){let e=this.getCachedToken();if(!e)return;let t=`${this.config.url}/oauth2/revoke`,n=new URLSearchParams;n.append(`token`,e.access_token),n.append(`client_id`,this.config.clientId),n.append(`client_secret`,this.config.clientSecret);try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":sr.CONTENT_TYPE},body:n.toString()});if(!e.ok&&e.status!==200){let t=await e.json().catch(()=>({}));throw H.fromOAuthError({error:t.error||`server_error`,error_description:t.error_description||`Token revocation failed`},e.status)}this.clearCache()}catch(e){throw e instanceof H?e:H.fromError(e instanceof Error?e:Error(String(e)))}}get url(){return this.config.url}get clientId(){return this.config.clientId}get scopes(){return this.config.scopes}get audience(){return this.config.audience}},dr=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`,fr=32,pr=e=>{let t=``;for(let n=0;n<e.length;n+=3){let r=e[n],i=e[n+1],a=e[n+2];t+=dr.charAt(r>>2),t+=dr.charAt((r&3)<<4|(i??0)>>4),i!==void 0&&(t+=dr.charAt((i&15)<<2|(a??0)>>6)),a!==void 0&&(t+=dr.charAt(a&63))}return t},mr=()=>{let e=globalThis.crypto;if(!e?.subtle)throw Error(`PKCE needs the Web Crypto API, which is available only in a secure context (https or localhost)`);return e},hr=async e=>{let t=await mr().subtle.digest(`SHA-256`,new TextEncoder().encode(e));return pr(new Uint8Array(t))},gr=(e=fr)=>pr(mr().getRandomValues(new Uint8Array(e))),_r=async()=>{let e=gr(fr);return{verifier:e,challenge:await hr(e)}},vr=()=>!!globalThis.crypto?.subtle,U=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`PassflowOidcError`}},yr=`Sign in again.`,br=e=>`This app is type ${e} and is a confidential client (it has a secret). For a browser app set its type to SPA; a server-side app redeems the code on its server with the secret.`,xr=`This app is a confidential client. For a browser app set its type to SPA (or token_endpoint_auth_method to none); a server-side app must redeem the code on its server with the client secret.`,Sr=()=>new U(`TOKENS_IN_URL_NOT_ALLOWED`,`Tokens in the URL are accepted only for apps in Simple mode`),Cr=`passflow_oidc_pkce`,wr=6e5,Tr=e=>{try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/+$/,``)}`}catch{return e}},Er=e=>!e.includes(`openid`)&&(e.includes(`id`)||e.includes(`oidc`))?[...e,`openid`]:[...e],Dr=async e=>{if(!vr())throw new U(`SECURE_CONTEXT_REQUIRED`,`Sign-in needs the Web Crypto API, which is available only in a secure context (https or localhost)`);let t=Er(e.scopes),n=await _r(),r={verifier:n.verifier,state:gr(),...t.includes(`openid`)?{nonce:gr()}:{},clientId:e.clientId,redirectUri:e.redirectUri,scopes:t,expiresAt:Date.now()+wr};try{sessionStorage.setItem(Cr,JSON.stringify(r))}catch{throw new U(`STORAGE_UNAVAILABLE`,`Sign-in needs sessionStorage, which cannot be written here`)}let i=new URL(`${e.url.replace(/\/+$/,``)}/oidc/authorize`);return i.search=new URLSearchParams({response_type:`code`,client_id:r.clientId,redirect_uri:r.redirectUri,scope:t.join(` `),state:r.state,code_challenge:n.challenge,code_challenge_method:`S256`,...r.nonce?{nonce:r.nonce}:{}}).toString(),i.toString()},Or=e=>{let t=e;return typeof t==`object`&&!!t&&typeof t.verifier==`string`&&typeof t.state==`string`&&typeof t.clientId==`string`&&typeof t.redirectUri==`string`&&Array.isArray(t.scopes)&&typeof t.expiresAt==`number`},kr=()=>{let e;try{e=sessionStorage.getItem(Cr)}catch{return{status:`none`}}if(!e)return{status:`none`};try{let t=JSON.parse(e);if(Or(t)&&Date.now()<t.expiresAt)return{status:`live`,slot:t}}catch{}return{status:`unusable`}},Ar=()=>{try{sessionStorage.removeItem(Cr)}catch{}},jr=async e=>{try{let t=await e.json();return typeof t==`object`&&t?t:void 0}catch{return}},Mr=async(e,t,n)=>{let r;try{r=await fetch(`${e.replace(/\/+$/,``)}/oidc/token`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`authorization_code`,code:t,redirect_uri:n.redirectUri,client_id:n.clientId,code_verifier:n.verifier}).toString()})}catch{throw new U(`TOKEN_EXCHANGE_FAILED`,yr)}let i=await jr(r);if(!r.ok)throw i?.error===`invalid_client`?new U(`invalid_client`,xr):i?.error===`invalid_grant`?new U(`invalid_grant`,yr):new U(`TOKEN_EXCHANGE_FAILED`,yr);if(typeof i?.access_token!=`string`)throw new U(`TOKEN_EXCHANGE_FAILED`,yr);let a=typeof i.id_token==`string`?i.id_token:void 0;if(n.scopes.includes(`openid`)){let e;try{e=a?P(a).nonce:void 0}catch{e=void 0}if(!a||e!==n.nonce)throw new U(`ID_TOKEN_INVALID`,`The ID token is missing or not issued for this sign-in. ${yr}`)}return{access_token:i.access_token,...typeof i.refresh_token==`string`?{refresh_token:i.refresh_token}:{},...a?{id_token:a}:{},scopes:n.scopes}},Nr=`error`,Pr=new WeakMap,Fr=(e,t)=>{if(typeof t!=`object`&&typeof t!=`function`||t===null)return!0;let n=Pr.get(e);return n||(n=new WeakSet,Pr.set(e,n)),!n.has(t)&&(n.add(t),!0)},W=(e,t)=>Fr(e,t.originalError)?(e.notify(Nr,t),!0):!1,G=function(e){return e.SignIn=`signin`,e.SignInStart=`signin:start`,e.Register=`register`,e.RegisterStart=`register:start`,e.EmailVerificationRequired=`email-verification:required`,e.SignOut=`signout`,e.SessionRestored=`session:restored`,e.SessionExpired=`session:expired`,e.Error=`error`,e.Refresh=`refresh`,e.RefreshStart=`refresh:start`,e.TokenCacheExpired=`token-cache-expired`,e.TwoFactorRequired=`2fa:required`,e.TwoFactorSetupStarted=`2fa:setup_started`,e.TwoFactorEnabled=`2fa:enabled`,e.TwoFactorDisabled=`2fa:disabled`,e.TwoFactorVerified=`2fa:verified`,e.TwoFactorRecoveryUsed=`2fa:recovery_used`,e.TwoFactorRecoveryCodesLow=`2fa:recovery_low`,e.TwoFactorRecoveryCodesExhausted=`2fa:recovery_exhausted`,e.TwoFactorSetupMagicLinkValidated=`2fa:magic_link_validated`,e.TwoFactorSetupMagicLinkFailed=`2fa:magic_link_failed`,e.TwoFactorChallengeReceived=`two_factor_challenge_received`,e.TwoFactorMethodSwitched=`two_factor_method_switched`,e.TwoFactorDeviceTrusted=`two_factor_device_trusted`,e.RefreshFailing=`refresh:failing`,e.RefreshRecovered=`refresh:recovered`,e.AntiBotSolving=`anti-bot:solving`,e.AntiBotSolved=`anti-bot:solved`,e}({}),Ir=class{constructor(){this.subscribers=new Map}subscribe(e,t){if(t?.length){let n=new Set(t);this.subscribers.set(e,n)}else this.subscribers.set(e,null)}unsubscribe(e,t){if(!t?.length){this.subscribers.delete(e);return}let n=this.subscribers.get(e);n&&(t.forEach(e=>n.delete(e)),n.size===0&&this.subscribers.delete(e))}notify(e,t){e===`error`&&Fr(this,t?.originalError),this.subscribers.forEach((n,r)=>{(!n||n.has(e))&&r.onAuthChange?.(e,t)})}notifyError(e){return W(this,e)}},Lr=256,Rr=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`)),zr=e=>{let t=new Uint8Array(e),n=``;for(let e of t)n+=Rr[e];return n},Br=class extends Error{};async function Vr(e,t,n,r=1/0){let i=globalThis.crypto?.subtle;if(!i)throw Error(`Web Crypto unavailable`);let a=t.toLowerCase(),o=new TextEncoder;for(let t=0;t<=n;t+=Lr){if(Date.now()>r)throw new Br(`Solve timed out`);let s=Math.min(t+Lr-1,n),c=[];for(let n=t;n<=s;n++)c.push(i.digest(`SHA-256`,o.encode(`${e}:${n}`)));let l=await Promise.all(c);for(let e=0;e<l.length;e++)if(zr(l[e])===a)return t+e}return null}var Hr=`The browser check could not be completed. Try again later.`,Ur=`Verification failed. Try again.`,Wr=6e4,Gr=class extends Error{},Kr=(e,t,n,r)=>new B({id:e,message:t,status:0,location:n,time:new Date().toISOString()},r===void 0?void 0:{cause:r}),qr=(e,t)=>new Promise((n,r)=>{let i=new Worker(e),a=setTimeout(()=>o(()=>r(new Gr)),Wr),o=e=>{clearTimeout(a),i.terminate(),e()};i.addEventListener(`message`,e=>{let t=e.data;t&&`error`in t?o(()=>r(Error(t.error))):o(()=>n(t?.number??null))}),i.addEventListener(`error`,()=>o(()=>r(Error(`Anti-bot worker failed`)))),i.addEventListener(`messageerror`,()=>o(()=>r(Error(`Anti-bot worker message failed`)))),i.postMessage(t)});async function Jr(e,t,n=`anti-bot`){if(e.algorithm!==`SHA-256`)throw Kr(rt,Hr,n);if(!Number.isSafeInteger(e.max)||e.max<0||e.max>5e6)throw Kr(rt,Ur,n);let r={salt:e.salt,challenge:e.challenge,max:e.max},i;try{i=t&&typeof Worker<`u`?await qr(t,r):await Vr(r.salt,r.challenge,r.max,Date.now()+Wr)}catch(e){throw Kr(rt,e instanceof Gr||e instanceof Br?Ur:Hr,n,e)}if(i===null)throw Kr(rt,Hr,n);return i}function Yr(e,t){let n={app:e.app,exp:e.exp,max:e.max,salt:e.salt,challenge:e.challenge,number:t,signature:e.signature};return btoa(JSON.stringify(n))}var Xr=`This app requires a verification token. Call setAntiBotTokenProvider() before signing in.`,Zr=`The verification could not be completed. Try again.`;function Qr(e){let t,n=async(e,t)=>{let n;try{n=await e({action:x,operation:t.operation})}catch(e){throw Kr(nt,Zr,t.operation,e)}if(typeof n!=`string`||n===``)throw Kr(nt,Zr,t.operation);return n},r=async t=>{let n=await e.fetchChallenge({...t.identifier?{identifier:t.identifier}:{},...t.device?{device:t.device}:{}});return Yr(n,await Jr(n,e.workerUrl,t.operation))};return{setTokenProvider(e){t=e},async headerFor(i){let a=i.settings??await e.readSettings().catch(()=>void 0);if(a?.bot_mode!==`human_only`)return;let o=a.anti_bot?.provider??`builtin`,s=o===`builtin`;e.store.notify(G.AntiBotSolving,{operation:i.operation,provider:o});let c;if(s)c=await r(i);else{let e=t;if(!e)throw Kr(tt,Xr,i.operation);c=await n(e,i)}return e.store.notify(G.AntiBotSolved,{operation:i.operation,provider:o}),{value:c,builtin:s}}}}var $r=`passflow-refresh`,ei=`passflow-refresh-takeover`,ti=`passflow-auth`,ni=Object.freeze([1e3,3e3,1e4,3e4,6e4]),ri=.2,ii=6e5,ai=5e3,K=2e4,oi=2e4,si=1e3,ci=2e3,li=1e3,ui=1e4,di=5e3;function fi(e){let t=e?`:${e}`:``;return{lock:`${$r}${t}`,takeoverLock:`${ei}${t}`,channel:`${ti}${t}`}}function q(e){return typeof e==`string`&&e!==``?e:void 0}function pi(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function mi(e){return typeof e==`object`&&!!e}function hi(e,t){for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function gi(e){if(!mi(e))return null;let t=Array.isArray(e.scopes)?e.scopes.filter(e=>typeof e==`string`):void 0;return hi({},{access_token:q(e.access_token),refresh_token:q(e.refresh_token),id_token:q(e.id_token),scopes:Array.isArray(e.scopes)&&t?.length===e.scopes.length?t:void 0})}function _i(e){if(!mi(e))return null;let{kind:t,attempt:n,nextAt:r,strikes:i}=e;return t!==`transient`&&t!==`auth`||typeof n!=`number`||!Number.isInteger(n)||n<1||pi(r)===void 0||typeof i!=`number`||!Number.isFinite(i)||i<0?null:hi({kind:t,attempt:n,nextAt:r,strikes:i},{from:q(e.from),failingSince:pi(e.failingSince)})}function vi(e){return hi({},{fp:q(e.fp),sub:q(e.sub),sid:q(e.sid),iat:pi(e.iat)})}function yi(e){if(!mi(e))return null;let t=e;if(t.v!==void 0&&t.v!==1)return null;let n=q(t.tabId);if(!n)return null;switch(t.type){case`tokens-refreshed`:{let e=gi(t.tokens),r=q(t.from),i=q(t.to);return!e||!r||!i?null:hi({type:t.type,tabId:n,tokens:e,from:r,to:i},{fromIat:pi(t.fromIat),fromSid:typeof t.fromSid==`string`?t.fromSid:void 0,sentAt:pi(t.sentAt)})}case`session-refreshed`:{let e=pi(t.at);return e===void 0?null:hi({type:t.type,tabId:n,at:e},{sub:q(t.sub)})}case`still-refreshing`:{let e=t.retry===void 0?null:_i(t.retry);return e?{type:t.type,tabId:n,retry:e}:{type:t.type,tabId:n}}case`retry-scheduled`:{let e=_i(t);return e?{type:t.type,tabId:n,message:typeof t.message==`string`?t.message:``,retry:e}:null}case`takeover`:return{type:t.type,tabId:n};case`lock-wanted`:return t.purpose===`commit`||t.purpose===`logout`?{type:t.type,tabId:n,purpose:t.purpose}:null;case`session-ended`:case`signed-out`:return{type:t.type,tabId:n,...vi(t)};case`rate-limited`:{let e=pi(t.until);return e===void 0?null:{type:t.type,tabId:n,until:e}}case`refresh-failed`:{let e=q(t.from);return e?{type:t.type,tabId:n,message:typeof t.message==`string`?t.message:``,from:e}:null}default:return null}}function bi(e,t){let n={v:1,tabId:e};if(t.type===`retry-scheduled`){let{retry:e,...r}=t;return hi(n,{...r,...e})}return hi(n,{...t})}var xi=`[passflow] navigator.locks or BroadcastChannel is unavailable (they need a secure context); each tab refreshes on its own, with the save checks only`,Si={now:()=>Date.now(),random:()=>Math.random(),setTimeout:(e,t)=>{let n=setTimeout(e,t);return n.unref?.(),()=>clearTimeout(n)}};function Ci(){let e=globalThis.crypto;return typeof e?.randomUUID==`function`?e.randomUUID():`tab-${Math.random().toString(36).slice(2)}-${Date.now()}`}function wi(e){return e?{now:()=>e.now(),setTimeout:(t,n)=>e.setTimeout(t,n),random:e.random?()=>e.random?.()??Math.random():Si.random}:Si}function Ti(e){return typeof window<`u`&&typeof document<`u`&&e.getDeviceType()===`web`}function Ei(e){try{return e.storageSharedAcrossTabs===!0}catch{return!1}}function Di(){try{let e=globalThis.navigator?.locks;return e&&typeof e.request==`function`?e:void 0}catch{return}}function Oi(e){return t=>{let n=n=>{let r=n.key;(r==null||e().includes(r))&&t()};return window.addEventListener(`storage`,n),()=>window.removeEventListener(`storage`,n)}}function ki(e){return{transports:null,names:fi(e),clock:Si,warnOnFirstCycle:!1}}function Ai(e,t,n,r){let i=fi(n),a=Ti(t),o=a?Oi(r.tokenKeys):void 0,s=e=>{let t={transports:null,names:i,clock:Si,warnOnFirstCycle:e};return o&&(t.onStorageChange=o),t};if(typeof e==`object`&&e){let t={transports:{locks:e.locks,channel:e.channel,tabId:e.tabId??Ci()},names:i,clock:wi(e.clock),warnOnFirstCycle:!1};return e.onStorageChange&&(t.onStorageChange=e.onStorageChange),t}if(e===`none`||!a||!Ei(t))return s(!1);let c=Di();if(!c||typeof BroadcastChannel!=`function`)return s(!0);let l;try{l=new BroadcastChannel(i.channel)}catch{return s(!0)}let u={transports:{locks:c,channel:l,tabId:Ci()},names:i,clock:Si,warnOnFirstCycle:!1};return o&&(u.onStorageChange=o),u}var ji=Object.freeze([`error.token.invalid.error`,`error.api.token.parse.error`,`error.api.user.blocked`,`error.2fa.required_by_app`,`error.validation.token.invalid.subject`,`error.not.found`]);function Mi(e){if(typeof e!=`object`||!e)return;let t=e;return typeof t.get==`function`?t.get(`retry-after`):t[`retry-after`]??t[`Retry-After`]}function Ni(e,t){if(typeof e==`number`)return!Number.isFinite(e)||e<0?void 0:Math.min(ii,Math.floor(e)*1e3);if(typeof e!=`string`)return;let n=e.trim();if(n===``)return;if(/^\d+$/.test(n))return Math.min(ii,Number.parseInt(n,10)*1e3);if(!/[a-z]/i.test(n))return;let r=Date.parse(n);if(!Number.isNaN(r))return Math.min(ii,Math.max(0,r-t))}function Pi(e){return typeof e==`number`&&Number.isInteger(e)&&e>=100&&e<=599?e:void 0}function Fi(e){return typeof e==`object`&&e?Ii(e):void 0}function Ii(e){if(typeof e.id==`string`&&e.id!==``)return e.id;let t=e.response?.data;if(typeof t!=`object`||!t)return;let n=t.error;if(typeof n!=`object`||!n)return;let r=n.id;return typeof r==`string`&&r!==``?r:void 0}function Li(e,t=Date.now()){if(typeof e!=`object`||!e)return{kind:`transient`};let n=e,r=Ii(n),i=Pi(n.response?.status)??Pi(n.status),a={};if(i!==void 0&&(a.status=i),r!==void 0&&(a.id=r),Vn(r))return{kind:`auth`,terminal:!0,...a};if(r===`error.token.blocked`)return{kind:`blocked`,...a};if(r!==void 0&&ji.includes(r)||i!==void 0&&i>=400&&i<=499&&i!==429)return{kind:`auth`,...a};if(i===void 0)return{kind:`transient`,...a};let o=Ni(n.retryAfter??Mi(n.response?.headers),t);return o===void 0?{kind:`transient`,...a}:{kind:`transient`,...a,retryAfterMs:o}}function Ri(e,t,n){let r=ni.length,i=ni[(Number.isFinite(e)?Math.min(Math.max(Math.floor(e),1),r):1)-1]??ni[r-1]??6e4,a=Number.isFinite(t)?Math.min(Math.max(t,0),.999):0,o=i+Math.floor(i*ri*a);return Math.max(o,n!==void 0&&Number.isFinite(n)?Math.min(Math.max(n,0),ii):0)}var zi=class{error(e,...t){console.error(e,...t)}warn(e,...t){console.warn(e,...t)}info(e,...t){console.info(e,...t)}debug(e,...t){console.debug(e,...t)}};function Bi(){return new zi}var Vi={onGranted:()=>!1,onLockLost:()=>void 0,onMessage:()=>void 0};function Hi(e){let{locks:t,channel:n,tabId:r,names:i,clock:a}=e,o=Vi,s=null,c=null,l=null,u=null,d=null,f=null,p=0,m,h=!1,g=!1,_=e=>{g||n.postMessage(bi(r,e))},v=()=>s!==null&&c===null,y=()=>{f?.(),f=null},b=e=>{p=Math.max(p,e),y(),f=a.setTimeout(()=>{f=null,ee()},Math.max(0,p-a.now()))},x=()=>{d?.(),d=null},S=()=>{d=a.setTimeout(()=>{d=null,c&&(h=!1,_(m?{type:`still-refreshing`,retry:m}:{type:`still-refreshing`}),S())},ai)},C=()=>{y(),x(),u?.(),u=null;let e=s;s=null,c=null,e&&(e.dead=!0,e.abort.abort());let t=l;l=null,t?.()},w=()=>{x(),c=null,s=null,l=null,o.onLockLost()},T=(e,t)=>{if(e.dead||s!==e||g){t();return}y(),c=e,l=t,h=!1,S();let n=!1;try{n=o.onGranted()}finally{!n&&c===e&&C()}},E=e=>{if(e.takeover&&(u?.(),u=null),!(e.dead||s!==e))return new Promise(t=>{a.setTimeout(()=>T(e,t),0)})},D=e=>{let n={takeover:e,dead:!1,abort:new AbortController};s=n;let r=e?{steal:!0}:{signal:n.abort.signal};t.request(i.lock,r,()=>E(n)).catch(()=>{n.dead=!0,c===n&&w()})},ee=()=>{if(!v())return;let e=s;t.request(i.takeoverLock,{ifAvailable:!0},t=>{if(s===e&&v()){if(t===null)b(a.now()+K);else return _({type:`takeover`}),new Promise(t=>{u=t,e&&(e.dead=!0,e.abort.abort()),D(!0)})}}).catch(()=>{v()&&b(a.now()+K)})},te=e=>{if(g)return;let t=yi(e.data);if(t&&t.tabId!==r){switch(t.type){case`still-refreshing`:h=!0,v()&&(b(a.now()+K),t.retry&&b(t.retry.nextAt+K));break;case`takeover`:h=!0,v()&&b(a.now()+K);break;case`retry-scheduled`:h=!0,v()&&b(Math.max(a.now(),t.retry.nextAt)+K);break;case`rate-limited`:v()&&b(t.until+K)}o.onMessage(t)}};return n.addEventListener(`message`,te),{coordinated:!0,tabId:r,get waiting(){return v()},get holding(){return c!==null},attach:e=>{o=e},request:e=>{g||s||(p=0,b(Math.max(a.now()+K,e??0)),D(!1))},release:C,post:_,setRetryInfo:e=>{m=e},foreignHolderHeard:()=>h,dispose:()=>{g||(C(),g=!0,n.removeEventListener(`message`,te),n.close())}}}function Ui(e=`local`){let t=Vi,n=!1,r=!1,i=0,a=!1,o=()=>{n=!1,r=!1,i+=1};return{coordinated:!1,tabId:e,get waiting(){return n&&!r},get holding(){return r},attach:e=>{t=e},request:()=>{if(a||n)return;n=!0;let e=++i;Promise.resolve().then(()=>{if(a||i!==e||!n)return;r=!0;let s=!1;try{s=t.onGranted()}finally{!s&&i===e&&o()}})},release:o,post:()=>void 0,setRetryInfo:()=>void 0,foreignHolderHeard:()=>!1,dispose:()=>{o(),a=!0}}}var J={unavailable:`error.refresh.unavailable`,authRetry:`error.refresh.auth_retry`,sessionEnded:`error.refresh.session_ended`,signedOut:`error.refresh.signed_out`,successorTimeout:`error.refresh.successor_timeout`,identityChanged:`error.refresh.identity_changed`,disposed:`error.refresh.disposed`},Wi={"error.refresh.unavailable":503,"error.refresh.auth_retry":401,"error.refresh.session_ended":401,"error.refresh.signed_out":401,"error.refresh.successor_timeout":401,"error.refresh.identity_changed":401,"error.refresh.disposed":499},Gi={"error.refresh.unavailable":`Token refresh is unavailable; a retry is scheduled`,"error.refresh.auth_retry":`Token refresh was refused; a retry is scheduled`,"error.refresh.session_ended":`The session has ended`,"error.refresh.signed_out":`Signed out`,"error.refresh.successor_timeout":`The refresh token was already used and no successor arrived`,"error.refresh.identity_changed":`Storage holds another user's tokens`,"error.refresh.disposed":`The Passflow instance was disposed`},Y=class extends B{constructor(e,t={}){super({id:e,message:t.message??Gi[e],status:Wi[e],location:`/auth/refresh`,time:new Date().toISOString()}),this.name=`PassflowRefreshError`,t.nextRetryAt!==void 0&&(this.nextRetryAt=t.nextRetryAt),t.cause!==void 0&&(this.cause=t.cause)}},Ki=class extends Error{constructor(e,t){super(t??(e===`lock-timeout`?`Step-up commit could not take the refresh lock in time`:`Step-up commit answer arrived after the stored session moved on`)),this.name=`UpgradeCommitInterruptedError`,this.reason=e}};function qi(e){if(!e)return;let t=3735928559,n=1103547991;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,2654435761),n=Math.imul(n^i,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(t^t>>>13,3266489909),(4294967296*(2097151&n)+(t>>>0)).toString(16)}function Ji(e){return typeof e==`string`&&e!==``?e:void 0}function X(e){let t=qi(e);if(!e||!t)return;let n={};try{let t=P(e);typeof t==`object`&&t&&(n=t)}catch{}let r=typeof n.iat==`number`&&Number.isFinite(n.iat)?n.iat:void 0,i={fp:t},a=Ji(n.sub),o=Ji(n.sid);return a!==void 0&&(i.sub=a),o!==void 0&&(i.sid=o),r!==void 0&&(i.iat=r),i}var Yi=`[passflow] A refresh token carries no iat claim: it is never taken over an ordered one, and cross-tab adoption falls back to fingerprints`;function Xi(e=e=>Bi().warn(e)){let t=new Map,n=new Set,r=!1,i=[],a=!1,o=()=>{a||(a=!0,e(Yi))},s=(e,t)=>e.has(t)?!0:e.size>=32?!1:(e.add(t),!0),c=e=>{if(!e)return;if(e.iat===void 0){s(n,e.fp)||(r=!0);return}let i=e.sid??``,a=t.get(i);if((!a||e.iat>a.floor)&&(a={floor:e.iat,atFloor:new Set,full:!1}),t.delete(i),t.set(i,a),t.size>8){let e=t.keys().next().value;e!==void 0&&t.delete(e)}e.iat<a.floor||s(a.atFloor,e.fp)||(a.full=!0)},l=e=>{if(!e)return!1;if(e.iat===void 0)return r||n.has(e.fp);let i=t.get(e.sid??``);return!i||e.iat>i.floor?!1:e.iat<i.floor||i.full||i.atFloor.has(e.fp)},u=(e,t)=>!e.sub||!t.sub||e.sub===t.sub,d=e=>e?i.some(t=>t.fp===e.fp||t.iat!==void 0&&e.iat!==void 0&&u(t,e)&&t.sid===e.sid&&e.iat<t.iat):!1,f=(e,t)=>e.fp===t.fp?!1:e.iat===void 0?(o(),t.iat===void 0&&!l(e)):t.iat===void 0?!0:e.iat===t.iat?e.sid===t.sid&&l(t)&&!l(e):e.iat>t.iat;return{retire:c,isRetired:l,isAfter:f,isForward:(e,t)=>!e||d(e)||l(e)?!1:t?f(e,t):(e.iat===void 0&&o(),!0),end:e=>{let t=i.findIndex(t=>t.fp===e.fp||t.sid!==void 0&&t.sid===e.sid&&u(t,e));if(t!==-1){let n=i[t];if(n?.iat!==void 0&&(e.iat===void 0||n.iat>e.iat))return;i.splice(t,1)}i.push({...e}),i.length>4&&i.shift()},isEnded:d}}var Zi=class extends Error{constructor(e){super(e===`emptied`?`The shared token storage was emptied`:`The stored refresh token belongs to an ended session`),this.name=`SessionEnded`,this.cause=e}},Qi=class extends Error{constructor(){super(`The shared token storage holds another user's tokens`),this.name=`IdentityChanged`}};function $i(e){if(e)try{let t=P(e).sub;return typeof t==`string`&&t!==``?t:void 0}catch{return}}function Z(e){return $i(e?.access_token)??$i(e?.refresh_token)??$i(e?.id_token)}function ea(e,t){return!t||e.iat===void 0||t.iat===void 0?!1:e.sid===t.sid&&e.iat<t.iat}function ta(e){return typeof e==`object`&&!!e}function na(e){let{storage:t,cache:n,schedule:r}=e,i=e.identity??(()=>void 0),a=e.warn??(e=>Bi().warn(e)),o=e.lineage??Xi(a),s=e.onSessionLost,c,l=0,u=[],d=[],f=0,p,m=0,h,g,_,v,y=()=>{let e=t.getTokens(),n=e?.refresh_token;if(!n)return p=l,e;p!==void 0&&(f=Math.max(f,p,m),p=void 0);let r=qi(n)??``;return r!==c?.fp&&(c={fp:r,seq:l}),e},b=()=>X(n.getTokens()?.refresh_token),x=()=>i()??Z(n.getTokens()),S=()=>{let e=b();return!e||e.iat===void 0||!x()?!1:!o.isRetired(e)&&!o.isEnded(e)},C=e=>{let t=b();if(!t||t.fp===e.fp||!S())return!1;let n=x();return!e.sub||n!==e.sub||t.iat===void 0||e.iat===void 0?!1:t.sid!==e.sid||o.isAfter(t,e)},w=e=>!!e?.access_token&&!e.refresh_token&&!n.getTokens()?.refresh_token,T=e=>{let t=x();return d.some(n=>n.seq>e&&(!n.sub||!t||n.sub===t))},E=()=>{let e=x();for(let t=u.length-1;t>=0;t--){let n=u[t];if(!n||n.seq<=f)break;if(!n.sub||!e||n.sub===e)return n}},D=()=>{if(!S())return`end`;let e=c?.seq??0,t=E();return T(t?Math.min(e,t.seq):e)?`end`:t?C(t)?`keep`:`end`:s?`wait`:`end`},ee=()=>{h?.(),h=void 0},te=(e=!1)=>{let t=D();t===`wait`&&e&&(t=`end`),t!==`wait`&&ee(),t===`wait`&&!h&&(h=r(()=>{h=void 0;let e=y();e?.refresh_token||w(e)?oe():te(!0)===`end`&&s?.(`emptied`)},ci));let n=t===`keep`?E():void 0;return n&&(m=Math.max(m,n.seq)),n&&g!==n.fp&&(g=n.fp,a(`[passflow] The shared token storage was emptied by the end of the session of ${n.fp}, a refresh token the ${b()?.fp??`(none)`} this tab holds is ahead of: keeping it. Nothing is refreshed until the storage holds a token again.`)),t},O=e=>e.held!==void 0&&b()?.fp===e.held.cachedFp,ne=e=>{let t=b();return!!t&&!o.isRetired(t)&&!o.isEnded(t)&&o.isAfter(t,e)},re=e=>{if(!ne(e))return!1;if(o.isRetired(e))return!0;let t=b();return e.iat!==void 0&&t?.iat!==void 0&&t.sid===e.sid},ie=(e,t)=>o.isForward(e,t)?!0:!!e&&!!t&&e.iat!==void 0&&e.sid!==t.sid&&o.isRetired(t)&&!o.isRetired(e)&&!o.isEnded(e),ae=e=>{let t=b();t&&t.fp!==qi(e.refresh_token)&&o.retire(t),n.setTokensCache(e)},k=e=>{let t=y(),n=t?.refresh_token;if(n===e.refreshToken)return null;if(!t||!n)return te()===`end`?{kind:`ended`,cause:`emptied`}:{kind:`superseded`,adopted:!1};let r=$i(t.access_token)??$i(n);if(e.sub&&r&&e.sub!==r)return{kind:`identity-changed`,saved:!1};let i=X(n);if(o.isEnded(i))return i&&C(i)?{kind:`superseded`,adopted:!1}:{kind:`ended`,cause:`ended`};o.retire(e.order);let a=b();return ie(i,a)||i?.fp===a?.fp&&!o.isRetired(i)?(ae(t),{kind:`superseded`,adopted:!0}):{kind:`superseded`,adopted:!1}},A=e=>C(e)?{kind:`superseded`,adopted:!1}:{kind:`ended`,cause:`ended`},oe=()=>{let t=y();if(!t?.refresh_token&&!w(t)){te()===`end`&&s?.(`emptied`);return}ee();let n=i(),r=Z(t);n&&r&&n!==r?s?.(`identity-changed`):e.onStoredSessionSeen?.()},se=!!s||!!e.onStoredSessionSeen,ce=se&&e.onStorageChange?e.onStorageChange(oe):void 0,j=se&&e.onWake?e.onWake(oe):void 0,le=()=>{let e=y();if(w(e))return`held`;if(!e?.refresh_token){if(te()===`end`)throw new Zi(`emptied`);return`held`}let t=n.getTokens();if(e.refresh_token===t?.refresh_token)return`send`;let r=i()??Z(t),a=Z(e);if(r&&a&&r!==a)throw new Qi;let s=X(e.refresh_token);if(o.isEnded(s)){if(s&&C(s))return`held`;throw new Zi(`ended`)}let c=X(t?.refresh_token);return ie(s,c)?(ae(e),`adopted`):s&&c&&s.sid!==c.sid?`send`:s&&ne(s)?`held`:`send`},ue=e=>{let t=i(),r=$i(e);if(t&&r&&t!==r)return{kind:`identity-changed`};let a=X(e)??{fp:e};if(o.isEnded(a))return C(a)?{kind:`superseded`}:{kind:`ended`};if(o.isRetired(a)&&ne(a))return{kind:`superseded`};let s={refreshToken:e,order:a},c=t??r??$i(n.getTokens()?.access_token);return c!==void 0&&(s.sub=c),v&&v.fp===a.fp&&(s.held={cachedFp:v.cachedFp}),{kind:`send`,sent:s}},M=(e,r)=>{if(o.isEnded(e.order))return A(e.order);let i=k(e);if(i)return i;if(!O(e)&&re(e.order))return o.retire(e.order),a(`[passflow] Refused to save a late refresh result: it rotated ${e.order.fp} into ${qi(r.refresh_token)??`(no refresh token)`}, but this tab already holds ${b()?.fp??`(none)`}, a later successor of ${e.order.fp}. Neither saved nor adopted.`),{kind:`superseded`,adopted:!1};let s=Z(r);if(e.sub&&s&&s!==e.sub)return t.saveTokens(r),{kind:`identity-changed`,saved:!0};let c=X(r.refresh_token);return c&&(ea(c,e.order)||ea(c,b()))?(a(`[passflow] Refused to save a refresh result older than the token this tab holds: ${e.order.fp} was answered with ${c.fp}. Neither saved nor adopted.`),{kind:`superseded`,adopted:!1}):(o.retire(e.order),t.saveTokens(r),n.setTokensCache(r),{kind:`saved`})},N=(e,t)=>{if(o.isEnded(e.order))return A(e.order);let n=k(e);if(n)return n.kind===`identity-changed`?{kind:`identity-changed`}:n;if(o.isRetired(e.order)&&ne(e.order))return{kind:`superseded`,adopted:!1};let r=Li(t),i=r.kind===`blocked`||r.kind===`auth`;return O(e)&&i?(o.retire(e.order),_=e.order,{kind:`own`,failure:r,heldRefused:!0}):(r.kind===`blocked`&&(o.retire(e.order),_=e.order),{kind:`own`,failure:r,heldRefused:!1})},P=e=>{if(!ta(e))return!1;let{from:t,fromIat:r,fromSid:a,to:c,tokens:l}=e;if(typeof t!=`string`||typeof c!=`string`||!ta(l))return!1;let u=l;if(typeof u.access_token!=`string`||u.access_token===``||typeof u.refresh_token!=`string`||u.refresh_token===``||qi(u.refresh_token)!==c)return!1;let d=y();if(!d?.refresh_token)return!1;let f=n.getTokens(),p=i()??Z(f),m=Z(u);if(p&&m&&p!==m)return s?.(`identity-changed`),!1;let h=X(u.refresh_token),g=X(f?.refresh_token);g&&g.fp===t&&o.retire(g);let _=()=>{if(t!==c&&typeof r==`number`&&Number.isFinite(r)&&typeof a==`string`){let e={fp:t,iat:r};h?.sub!==void 0&&(e.sub=h.sub),a!==``&&(e.sid=a),o.retire(e)}return!0};return g?.fp===c?_():!o.isForward(h,g)||g?.fp!==t&&qi(d.refresh_token)!==c?!1:(ae({...u}),_())},F=e=>{if(!e||!_)return!1;let t=_;return e.fp===t.fp||o.isEnded(e)||o.isRetired(e)?!1:e.iat!==void 0&&t.iat!==void 0&&e.sid!==t.sid||o.isAfter(e,t)},I=()=>{let e=b();if(!e)return!1;if(F(e))return!0;let t=y(),r=X(t?.refresh_token);if(!t||!r||r.fp===e.fp||!F(r)||!ie(r,e))return!1;let a=i()??Z(n.getTokens()),o=Z(t);return a&&o&&a!==o?(s?.(`identity-changed`),!1):(ae(t),!0)},de=e=>{let t=X(e?.refresh_token),n={},r=i()??Z(e);return t?.fp!==void 0&&(n.fp=t.fp),r!==void 0&&(n.sub=r),t?.sid!==void 0&&(n.sid=t.sid),t?.iat!==void 0&&(n.iat=t.iat),n};return{lineage:o,checkStoredBeforeSend:le,beginSend:ue,commitSave:M,judgeFailure:N,adoptTokens:P,adoptSuccessor:I,beginHeldSend:()=>{let e=X(y()?.refresh_token);if(!e||o.isRetired(e)||o.isEnded(e))return v=void 0,!1;let t=b()?.fp;return v=t===void 0?{fp:e.fp}:{fp:e.fp,cachedFp:t},!0},endHeldSend:()=>{v=void 0},endLineage:e=>o.end(e),endedElsewhere:(e,t)=>{let n=!y()?.refresh_token;l+=1,e===`signed-out`?(d.push(t.sub===void 0?{seq:l}:{sub:t.sub,seq:l}),d.length>4&&d.shift()):t.fp&&(u.push({...t,fp:t.fp,seq:l}),u.length>4&&u.shift()),b()&&n&&te()===`end`&&s?.(`emptied`)},session:()=>de(n.getTokens()),storedSession:()=>de(y()),dropSession:()=>{n.setTokensCache(void 0),n.stopTokenCheck?.()},deleteIfStillDead:e=>{let n=X(y()?.refresh_token);if(!n)return!1;let r=n.sid===e.sid&&(!n.sub||!e.sub||n.sub===e.sub);return n.fp===e.fp||r&&n.iat!==void 0&&e.iat!==void 0&&n.iat<e.iat?(t.deleteTokens(),!0):!1},stop:()=>{ce?.(),j?.(),ee()}}}function ra(){let e,t,n=new Promise((n,r)=>{e=n,t=r});return n.catch(()=>void 0),{promise:n,resolve:e,reject:t}}var ia={strikes:J.sessionEnded,"session-ended":J.sessionEnded,"stored-ended":J.sessionEnded,"signed-out":J.signedOut,emptied:J.signedOut,"signed-out-here":J.signedOut,"successor-timeout":J.successorTimeout,"identity-changed":J.identityChanged,disposed:J.disposed};function aa(e){throw Error(`Unexpected refresh state: ${JSON.stringify(e)}`)}function oa(e){if(e===void 0||!Number.isFinite(e))return 3;let t=Math.floor(e);return t>=1?t:3}function sa(e,t){return e instanceof Error&&e.message?e.message:t}function ca(e){if(typeof e!=`object`||!e)return;let t=e.id;return typeof t==`string`||typeof t==`number`?t:void 0}function la(e){let t={};return e?.access_token&&(t.access_token=e.access_token),e?.refresh_token&&(t.refresh_token=e.refresh_token),e?.id_token&&(t.id_token=e.id_token),e?.scopes&&(t.scopes=[...e.scopes]),t}function ua(e,t){let n={};e.access_token&&(n.access_token=e.access_token),e.refresh_token&&(n.refresh_token=e.refresh_token),e.id_token&&(n.id_token=e.id_token);let r=t?.scopes??e.scopes;return r&&(n.scopes=r),n}function da(e){let{emit:t,storage:n,cache:r,transport:i,coordination:a}=e,o=a.clock,s=e.logger??Bi(),c=oa(e.strikes),l=a.transports?Hi({locks:a.transports.locks,channel:a.transports.channel,tabId:a.transports.tabId,names:a.names,clock:o}):Ui(),u={kind:`idle`},d=0,f=!1,p=!a.warnOnFirstCycle,m=0,h=0,g,_,v,y,b,x,S,C,w=!1,T=()=>o.now(),E=()=>i.mode(),D=()=>qi(r.getTokens()?.refresh_token),ee=()=>({...r.getTokens()??{}}),te=()=>i.opaqueMarker?i.opaqueMarker():n.getTokens()?.id_token,O=()=>(S===void 0&&(S=Z(r.getTokens()??n.getTokens())),S),ne=new Set,re=new Set,ie=e=>()=>{for(let t of Array.from(e))t()},ae=a.onStorageChange?.(ie(ne)),k=e.platform?.onForeground(ie(re)),A=na({storage:n,cache:r,identity:O,schedule:(e,t)=>o.setTimeout(e,t),onStorageChange:e=>(ne.add(e),()=>ne.delete(e)),onWake:e=>(re.add(e),()=>re.delete(e)),onSessionLost:e=>pe(e),onStoredSessionSeen:()=>{u.kind===`blocked-wait`&&Ae()},warn:e=>s.warn(e)}),oe=e=>({trigger:e,startedAt:T(),plain:ra(),fresh:[]}),se=e=>e.kind===`idle`||e.kind===`ended`?void 0:e.pending,ce=(e,t)=>{if(t===void 0)return e.plain.promise;let n={callTime:t,deferred:ra()};return e.fresh.push(n),n.deferred.promise},j=(e,t,n=!1)=>{e.plain.resolve(ee());for(let r of e.fresh)n||t!==void 0&&t>=r.callTime?r.deferred.resolve(ee()):ze(`refresh-token`,r.callTime).then(r.deferred.resolve,r.deferred.reject);e.fresh=[]},le=(e,t,n)=>{e.plain.reject(t);for(let r of e.fresh)n!==void 0&&n<r.callTime?ze(`refresh-token`,r.callTime).then(r.deferred.resolve,r.deferred.reject):r.deferred.reject(t);e.fresh=[]},ue=(e,t)=>{if(e){e.plain.reject(t);for(let n of e.fresh)n.deferred.reject(t);e.fresh=[]}},M=(e,n,r,i)=>{let a={message:sa(r,`Token refresh failed`),originalError:r,operation:e,source:n},o=ca(r);o!==void 0&&(a.code=o),i&&(a.refresh=i),t(`error`,a)},N=(e,t)=>{let n={classification:e,willRetry:t!==void 0,strikes:h,maxStrikes:c};return t!==void 0&&(n.nextRetryAt=t),n},P=(e,n)=>{if(u.kind===`refreshing`&&(u.request.outcome=!0),m=0,h=0,g=void 0,v=void 0,l.setRetryInfo(void 0),r.tokenExpiredFlag!==void 0&&(r.tokenExpiredFlag=!1),r.startTokenCheck?.(),t(`refresh`,{tokens:r.getTokens(),source:e}),t(`token-cache-expired`,{isExpired:!1}),_){let{since:e}=_;_=void 0,t(`refresh:recovered`,{since:e,origin:n})}},F=(e,n,r)=>{if(_)return;_={since:e};let i={since:e,origin:r};n!==void 0&&(i.nextRetryAt=n),t(`refresh:failing`,i)},I=(e,t)=>{let n=r.getTokens(),i=qi(n?.refresh_token);e.fp&&i&&l.post({type:`tokens-refreshed`,tokens:la(n),from:e.fp,...e.iat===void 0?{}:{fromIat:e.iat},fromSid:e.sid??``,to:i,...t===void 0?{}:{sentAt:t}})},de=()=>{p||(p=!0,s.warn(xi))},fe=e=>{(e.kind===`backoff`||e.kind===`blocked-wait`)&&e.cancel()},L=(e,n)=>{if(u.kind===`ended`)return;let r=se(u);fe(u);let a=A.session(),o=O();switch(d+=1,m=0,h=0,g=void 0,_=void 0,v=void 0,l.setRetryInfo(void 0),w||l.release(),b={...a,cause:e},e!==`disposed`&&A.dropSession(),(e===`strikes`||e===`successor-timeout`)&&E()!==`json`&&i.invalidate(),u={kind:`ended`,cause:e},ue(r,n??new Y(ia[e])),e){case`strikes`:t(`session:expired`,{reason:`refresh_failed`,origin:`this-tab`});break;case`session-ended`:case`stored-ended`:t(`session:expired`,{reason:`refresh_failed`,origin:`other-tab`});break;case`signed-out`:case`emptied`:t(`signout`,o===void 0?{origin:`other-tab`}:{origin:`other-tab`,userId:o});break;case`successor-timeout`:t(`session:expired`,{reason:`successor_timeout`,origin:`this-tab`});break;case`identity-changed`:t(`session:expired`,{reason:`identity_changed`,origin:`this-tab`});break;case`signed-out-here`:case`disposed`:break;default:aa(e)}},R=()=>{if(u.kind!==`ended`||u.cause===`disposed`||f||E()!==`json`)return;let e=n.getTokens(),i=X(e?.refresh_token);if(!e?.refresh_token||!e.access_token||!i||A.lineage.isEnded(i)||A.lineage.isRetired(i))return;let a=b,o=Z(e);if(a&&a.cause!==`successor-timeout`&&(!a.sub||!o||a.sub===o)&&i.sid===a.sid)return;d+=1,m=0,h=0,g=void 0,_=void 0,v=void 0,b=void 0,S=o;let s={...e};r.setTokensCache(s),r.tokenExpiredFlag!==void 0&&(r.tokenExpiredFlag=!1),r.startTokenCheck?.(),u={kind:`idle`},t(`signin`,{tokens:s,origin:`other-tab`})},pe=e=>{u.kind===`ended`||f||E()===`json`&&(L(e===`emptied`?`emptied`:`identity-changed`),e===`identity-changed`&&R())},me=e=>{e instanceof Qi?(L(`identity-changed`),R()):e instanceof Zi?L(e.cause===`emptied`?`emptied`:`stored-ended`):L(`stored-ended`,e)},he=()=>{u={kind:`idle`},w||l.release()},ge=e=>!e.from||E()!==`json`||e.from===D()||e.from===qi(n.getTokens()?.refresh_token),_e=e=>{let t=g;if(!t)return;if(!l.holding){u={kind:`waiting`,pending:e},l.request(t.nextAt+K);return}l.setRetryInfo(t);let n=d,r=t.nextAt;u={kind:`backoff`,pending:e,dueAt:r,cancel:o.setTimeout(()=>{n===d&&ve()},Math.max(0,r-T()))}},ve=()=>{if(u.kind!==`backoff`||w)return;let{pending:e,dueAt:t}=u;!l.holding||l.foreignHolderHeard()||T()-t>2e4?(l.release(),u={kind:`waiting`,pending:e},l.request((g?.nextAt??T())+K)):(u={kind:`waiting`,pending:e},be()||ye())},ye=()=>{u.kind===`idle`&&l.release()},be=()=>{if(u.kind!==`waiting`)return!1;let e=u.pending;if(E()!==`json`)return xe(e);let t=A.session(),n;try{n=A.checkStoredBeforeSend()}catch(e){return me(e),!1}if(n===`held`){let t=D();return!v||v.fp!==t||T()-v.at<2e4?(v&&v.fp===t||(v={fp:t,at:T()}),u={kind:`idle`},j(e,void 0,!0),!1):(v={fp:t,at:T()},A.beginHeldSend()?Se(e,`held`):(u={kind:`idle`},j(e,void 0,!0),!1))}if(v=void 0,n===`adopted`){if(P(`adopted`,`other-tab`),I(t),e.fresh.length===0)return u={kind:`idle`},j(e,void 0),!1;e.plain.resolve(ee())}return g&&!ge(g)&&(g=void 0),g&&g.nextAt>T()?(m=g.attempt,h=g.strikes,g.failingSince!==void 0&&F(g.failingSince,g.nextAt,`other-tab`),_e(e),!0):(g&&(m=g.attempt,h=g.strikes),Se(e,e.trigger===`held`?`refresh-token`:e.trigger))},xe=e=>y!==void 0&&y>=e.startedAt?(r.setTokensCache(n.getTokens()),P(`adopted`,`other-tab`),u={kind:`idle`},j(e,y),!1):g&&g.nextAt>T()?(m=g.attempt,h=g.strikes,_e(e),!0):Ce(e,e.trigger,void 0,void 0),Se=(e,t)=>{let r=n.getTokens(),i=r?.refresh_token;if(!i)return u={kind:`idle`},j(e,void 0,!0),!1;let a=A.beginSend(i);switch(a.kind){case`superseded`:return A.endHeldSend(),P(`adopted`,`other-tab`),u={kind:`idle`},j(e,void 0),!1;case`ended`:return A.endHeldSend(),L(`stored-ended`),!1;case`identity-changed`:return A.endHeldSend(),L(`identity-changed`),R(),!1;case`send`:return Ce(e,t,a.sent,r);default:return aa(a)}},Ce=(e,n,r,a)=>{let o={generation:d,sentAt:T(),trigger:n,settled:ra()};r?o.sent=r:o.marker=te(),a&&(o.stored=a),u={kind:`refreshing`,pending:e,request:o},l.setRetryInfo(g),t(`refresh:start`,{});let c;try{c=i.send(a?{tokens:a}:{})}catch(e){c=Promise.reject(e)}return c.then(e=>{Te(o,e).catch(e=>s.error(`[passflow] Applying a refresh result failed`,e)).finally(()=>o.settled.resolve())},e=>{Ee(o,e),o.settled.resolve()}),!0},we=e=>!f&&e.generation===d&&u.kind===`refreshing`&&u.request===e,Te=async(e,t)=>{if(e.sent?.held&&A.endHeldSend(),!we(e)||u.kind!==`refreshing`)return;let{pending:a}=u;if(!e.sent){let o=Z({...t.id_token?{id_token:t.id_token}:{}}),s=O();if(o!==void 0&&s!==void 0&&o!==s){let t=new Y(J.identityChanged);M(`refresh`,e.trigger,t,N(`auth`)),L(`identity-changed`,t);return}try{await i.applyOpaque(t)}catch(t){Ee(e,t);return}if(!we(e))return;r.setTokensCache({...n.getTokens()??{},...ua(t,void 0)}),P(`refresh`,`this-tab`);let c=O();l.post(c===void 0?{type:`session-refreshed`,at:T()}:{type:`session-refreshed`,at:T(),sub:c}),he(),j(a,e.sentAt);return}let o=D(),s=A.commitSave(e.sent,ua(t,e.stored));switch(s.kind){case`saved`:P(`refresh`,`this-tab`),I(e.sent.order,e.sentAt),he(),j(a,e.sentAt);return;case`superseded`:e.outcome&&D()===o||P(`adopted`,`other-tab`),s.adopted&&I(e.sent.order),he(),j(a,e.sentAt);return;case`ended`:{let t=new Y(s.cause===`emptied`?J.signedOut:J.sessionEnded);M(`refresh`,e.trigger,t,N(`auth`)),L(s.cause===`emptied`?`emptied`:`stored-ended`,t);return}case`identity-changed`:{let t=new Y(J.identityChanged);M(`refresh`,e.trigger,t,N(`auth`)),L(`identity-changed`,t),R();return}default:aa(s)}},Ee=(e,t)=>{if(e.sent?.held&&A.endHeldSend(),!we(e)||u.kind!==`refreshing`)return;let{pending:n}=u,r,i=!1;if(e.sent){let a=D(),o=A.judgeFailure(e.sent,t);switch(o.kind){case`superseded`:e.outcome&&D()===a||P(`adopted`,`other-tab`),he(),j(n,e.sentAt);return;case`ended`:M(`refresh`,e.trigger,t,N(`auth`)),L(o.cause===`emptied`?`emptied`:`stored-ended`,t);return;case`identity-changed`:M(`refresh`,e.trigger,t,N(`auth`)),L(`identity-changed`,t),R();return;case`own`:r=o.failure,i=o.heldRefused;break;default:aa(o)}}else r=Li(t,T());if(i)M(`refresh`,e.trigger,t,N(r.kind)),P(`adopted`,`other-tab`),he(),j(n,void 0,!0);else switch(r.kind){case`blocked`:M(`refresh`,e.trigger,t,N(`blocked`)),ke(n,e.sentAt,t,e.marker);return;case`auth`:if(h+=1,m+=1,r.terminal||h>=c){M(`refresh`,e.trigger,t,N(`auth`)),Oe(e,t);return}De(e,n,t,r);return;case`transient`:m+=1,De(e,n,t,r);return;default:aa(r.kind)}},De=(e,t,n,r)=>{let i=T()+Ri(m,o.random(),r.retryAfterMs),a=r.kind===`auth`?`auth`:`transient`;M(`refresh`,e.trigger,n,N(a,i)),a===`transient`&&F(T(),i,`this-tab`);let s={kind:a,attempt:m,nextAt:i,strikes:h},c=e.sent?.order.fp;c&&(s.from=c),_&&(s.failingSince=_.since),g=s,l.holding&&l.post({type:`retry-scheduled`,message:sa(n,`Token refresh failed`),retry:s}),_e(oe(`retry`)),le(t,n,e.sentAt)},Oe=(e,t)=>{let n=e.sent?.sub??O(),r=e.sent?.order,i={};r?.fp&&(i.fp=r.fp),n&&(i.sub=n),r?.sid&&(i.sid=r.sid),r?.iat!==void 0&&(i.iat=r.iat),(i.fp||i.sub)&&l.post({type:`session-ended`,...i}),i.fp&&(x=i.fp,A.endLineage({...i,fp:i.fp})),r&&A.deleteIfStillDead(r),L(`strikes`,t)},ke=(e,t,n,r)=>{l.release(),s.warn(`[passflow] The refresh token was already used, most likely by another tab; waiting for its successor: ${sa(n,`blocked`)}`);let i=d,a=T()+oi,c={kind:`blocked-wait`,pending:e,deadline:a,sentAt:t,cancel:()=>void 0,marker:r};if(u=c,Ae())return;let f=E()!==`json`&&!l.coordinated&&!e.cookieRetried,p=()=>{i===d&&u===c&&(Ae()||(f?(e.cookieRetried=!0,u={kind:`waiting`,pending:e},l.request()):T()>=a?(s.warn(`[passflow] No successor of the used refresh token appeared; ending the session in this tab only.`),L(`successor-timeout`)):c.cancel=o.setTimeout(p,si)))};c.cancel=o.setTimeout(p,f?li:si)},Ae=()=>{if(u.kind!==`blocked-wait`)return!1;let e=u;if(E()===`json`){if(!A.adoptSuccessor())return!1}else{let t=y!==void 0&&y>=e.sentAt,i=te(),a=!l.coordinated&&i!==void 0&&i!==e.marker;if(!t&&!a)return!1;r.setTokensCache(n.getTokens())}return u===e&&(e.cancel(),P(`adopted`,`other-tab`),u={kind:`idle`},j(e.pending,void 0,!0),!0)},je=e=>{let t=O(),n=!e.sub||!t||e.sub===t;return E()===`json`?!!e.fp&&e.fp===D()&&n:!e.fp&&n},Me=(e,t)=>{if(e!==`signed-out`||!t.sub)return!1;let n=O();return n!==void 0&&t.sub===n},Ne=(e,t,n)=>{if(u.kind===`ended`||!ge(e))return;let r=g?.nextAt;if(g=e,e.failingSince!==void 0&&F(e.failingSince,e.nextAt,`other-tab`),!t||u.kind!==`waiting`)return;let i=new Y(e.kind===`transient`?J.unavailable:J.authRetry,{nextRetryAt:e.nextAt,cause:n||void 0}),a=u.pending;u.pending=oe(a.trigger),le(a,i,r)},Pe=(e,t)=>{switch(t&&P(`adopted`,`other-tab`),u.kind){case`waiting`:case`backoff`:{let t=u.pending;fe(u),he(),j(t,e);return}case`blocked-wait`:{let e=u.pending;u.cancel(),u={kind:`idle`},j(e,void 0,!0);return}case`idle`:case`refreshing`:case`ended`:return;default:aa(u)}},Fe=e=>{let t={};e.fp&&(t.fp=e.fp),e.sub&&(t.sub=e.sub),e.sid&&(t.sid=e.sid),e.iat!==void 0&&(t.iat=e.iat);let n=u.kind!==`ended`&&(je(t)||Me(e.type,t));t.fp&&A.endLineage({...t,fp:t.fp}),n&&L(e.type===`signed-out`?`signed-out`:`session-ended`),A.endedElsewhere(e.type,t)},Ie=e=>{if(!f)switch(e.type){case`tokens-refreshed`:{if(u.kind===`ended`){R();return}if(E()!==`json`)return;let t=D();if(!A.adoptTokens(e))return;let n=D()!==t;if(!n&&u.kind===`idle`)return;g=void 0,Pe(e.sentAt,n);return}case`session-refreshed`:{if(E()===`json`||u.kind===`ended`)return;let t=O();if(e.sub&&t&&e.sub!==t||(y=Math.max(y??0,e.at),u.kind===`refreshing`))return;if(r.setTokensCache(n.getTokens()),g=void 0,u.kind===`blocked-wait`){Ae();return}Pe(e.at,!0);return}case`still-refreshing`:e.retry&&Ne(e.retry,!1,``),Le();return;case`retry-scheduled`:Ne(e.retry,!0,e.message),Le();return;case`refresh-failed`:if(u.kind===`ended`||E()!==`json`||e.from!==D()&&e.from!==qi(n.getTokens()?.refresh_token))return;if(F(T(),void 0,`other-tab`),u.kind===`waiting`){let t=u.pending;u.pending=oe(t.trigger),le(t,new Y(J.unavailable,{cause:e.message}),void 0)}return;case`lock-wanted`:if(u.kind===`backoff`&&l.holding&&!w){let e=u.pending;u.cancel(),l.release(),u={kind:`waiting`,pending:e},l.request((g?.nextAt??T())+K)}return;case`session-ended`:case`signed-out`:Fe(e);return;case`takeover`:case`rate-limited`:return;default:aa(e)}},Le=()=>{C&&!l.holding&&l.post({type:`lock-wanted`,purpose:C.purpose})};l.attach({onGranted:()=>{if(f)return!1;if(C){let e=C;return C=void 0,e.granted(),!0}return u.kind===`waiting`&&be()},onLockLost:()=>{if(u.kind===`backoff`){let e=u.pending;u.cancel(),u={kind:`waiting`,pending:e},l.request((g?.nextAt??T())+K)}},onMessage:Ie});let Re=()=>{if(f)return;if(u.kind===`ended`){R();return}if(u.kind===`blocked-wait`&&E()!==`json`){Ae();return}if(u.kind!==`idle`||E()!==`json`||w)return;let e=A.session();try{if(A.checkStoredBeforeSend()!==`adopted`)return}catch{return}P(`adopted`,`other-tab`),l.coordinated&&I(e)};ne.add(Re),re.add(Re);let ze=(e,t)=>{if(f)return Promise.reject(new Y(J.disposed));switch(u.kind){case`ended`:return Promise.reject(new Y(J.sessionEnded));case`idle`:{let n=oe(e);u={kind:`waiting`,pending:n};let r=ce(n,t);return l.holding&&!w?be()||ye():l.request(g?g.nextAt+K:void 0),r}case`waiting`:case`refreshing`:case`backoff`:case`blocked-wait`:return ce(u.pending,t);default:return aa(u)}},Be=e=>{if(f)return Promise.reject(new Y(J.disposed));if(de(),u.kind===`ended`)return Promise.reject(new Y(J.sessionEnded));if(E()===`json`&&!r.getTokens()?.refresh_token){let t=n.getTokens();if(!t?.refresh_token){let n=Error(t?`No refresh token found`:`No tokens found`);return M(`refresh`,e.trigger,n),Promise.reject(n)}}return ze(e.trigger,e.fresh?T():void 0)},Ve=e=>{if(f)return Promise.reject(new Y(J.disposed));if(u.kind===`ended`)return Promise.resolve(r.getTokens());let t=u.kind===`backoff`||u.kind===`blocked-wait`||g!==void 0&&g.nextAt>T();return e.allowStale&&t?Promise.resolve(r.getTokens()):Be({trigger:e.trigger}).then(()=>r.getTokens())},He=(e,t)=>l.holding?Promise.resolve(`granted`):new Promise(n=>{let r=()=>void 0,i={purpose:e,granted:()=>{r(),n(`granted`)}};C=i,l.post({type:`lock-wanted`,purpose:e}),l.request(),r=o.setTimeout(()=>{C===i&&(C=void 0,u.kind!==`waiting`&&l.release(),n(`timeout`))},Math.max(0,t))}),Ue=async e=>{if(u.kind!==`refreshing`)return;let t=u.request.settled.promise;await new Promise(n=>{let r=o.setTimeout(n,Math.max(0,e));t.then(()=>{r(),n()})})},We=()=>{if(w=!1,!f&&l.holding){if(u.kind===`waiting`)be()||ye();else if(u.kind===`backoff`){let e=u.pending;u.cancel(),_e(e)}else u.kind===`idle`&&g&&g.nextAt>T()&&ge(g)?(m=g.attempt,h=g.strikes,_e(oe(`retry`))):u.kind===`idle`&&l.release()}},Ge=async(e,t)=>{if(f)throw new Y(J.disposed);de();let n=T()+ui;if(await Ue(n-T()),(!l.holding||u.kind===`refreshing`)&&(u.kind===`refreshing`?`timeout`:await He(`commit`,n-T()))===`timeout`){let e=new Ki(`lock-timeout`);throw M(`upgrade.commit`,`upgrade`,e),e}w=!0;try{return await z(e,t)}finally{We()}},z=async(e,a)=>{let o,s;if(E()===`json`){let e=A.session();try{A.checkStoredBeforeSend()===`adopted`&&(P(`adopted`,`other-tab`),I(e))}catch{}s=n.getTokens();let t=s?.refresh_token;if(!t){let e=Error(s?`No refresh token found`:`No tokens found`);throw M(`upgrade.commit`,`upgrade`,e),e}let r=A.beginSend(t);o=r.kind===`send`?r.sent:{refreshToken:t,order:X(t)??{fp:t}}}let c=T(),u=d;t(`refresh:start`,{});let f;try{f=await i.send(s?{tokens:s,upgrade:e}:{upgrade:e})}catch(e){throw o&&A.judgeFailure(o,e),M(`upgrade.commit`,`upgrade`,e),e}try{i.assertPin(a)}catch(e){throw M(`upgrade.commit`,`upgrade`,e),e}if(!o){if(u!==d){let e=new Ki(`superseded`);throw M(`upgrade.commit`,`upgrade`,e),e}await i.applyOpaque(f),r.setTokensCache({...n.getTokens()??{},...ua(f,void 0)}),Ke(c);let e=O();return l.post(e===void 0?{type:`session-refreshed`,at:T()}:{type:`session-refreshed`,at:T(),sub:e}),ee()}let p=A.commitSave(o,ua(f,s));if(p.kind===`saved`)return Ke(c),I(o.order,c),ee();let m=new Ki(`superseded`);throw M(`upgrade.commit`,`upgrade`,m),p.kind===`superseded`&&p.adopted&&P(`adopted`,`other-tab`),m},Ke=e=>{if(P(`upgrade`,`this-tab`),u.kind===`waiting`||u.kind===`backoff`||u.kind===`blocked-wait`){let t=u.pending;fe(u),u={kind:`idle`},j(t,e)}},qe=()=>{let e=A.storedSession(),t=e.fp?e:A.session();(E()===`json`?!t.fp:!t.sub)||t.fp&&t.fp===x||(l.post({type:`signed-out`,...t}),t.fp&&A.endLineage({...t,fp:t.fp}))},Je=()=>{let e=se(u);ue(e,new Y(J.signedOut)),(u.kind===`backoff`||u.kind===`blocked-wait`||u.kind===`waiting`)&&(fe(u),u={kind:`idle`})};return{refresh:Be,ensureFresh:Ve,commitUpgrade:Ge,signOut:async e=>{if(f)return e(n.getTokens()?.refresh_token);let t=T()+di;Je(),await Ue(t-T()),Je(),l.coordinated&&!l.holding&&await He(`logout`,t-T());try{qe(),await e(n.getTokens()?.refresh_token)}finally{u.kind!==`ended`&&L(`signed-out-here`),x=void 0,l.release()}},signOutNow:e=>{if(f)return e(n.getTokens()?.refresh_token);Je();try{qe(),e(n.getTokens()?.refresh_token)}finally{u.kind!==`ended`&&L(`signed-out-here`),x=void 0}},sessionStarted:()=>{if(f)return;let e=se(u);fe(u),d+=1,m=0,h=0,g=void 0,_=void 0,v=void 0,b=void 0,x=void 0,S=void 0,l.setRetryInfo(void 0),u={kind:`idle`},w||l.release(),e&&j(e,void 0,!0)},identity:O,get generation(){return d},get coordinated(){return l.coordinated},get busy(){return u.kind!==`idle`&&u.kind!==`ended`},get ended(){return u.kind===`ended`},dispose:()=>{if(f)return;let e=se(u);fe(u),f=!0,d+=1,u={kind:`ended`,cause:`disposed`},ue(e,new Y(J.disposed)),C=void 0,A.stop(),l.dispose(),ae?.(),k?.()}}}var fa={ES256:{kty:`EC`,key:e=>({kty:e.kty,crv:e.crv,x:e.x,y:e.y}),imported:{name:`ECDSA`,namedCurve:`P-256`},signature:{name:`ECDSA`,hash:`SHA-256`}},RS256:{kty:`RSA`,key:e=>({kty:e.kty,n:e.n,e:e.e}),imported:{name:`RSASSA-PKCS1-v1_5`,hash:`SHA-256`},signature:{name:`RSASSA-PKCS1-v1_5`}}},pa=e=>{let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=globalThis.atob(t+`=`.repeat((4-t.length%4)%4));return Uint8Array.from(n,e=>e.charCodeAt(0))},ma=()=>{let e=globalThis.crypto;if(!e?.subtle)throw Error(`Verifying tokens needs the Web Crypto API, available only in a secure context (https or localhost)`);return e};async function ha(e,t,n,r,i){let[a=``,o=``,s=``]=e.split(`.`),c=JSON.parse(new TextDecoder().decode(pa(a))),l=c.alg===`ES256`||c.alg===`RS256`?fa[c.alg]:void 0;if(!l)throw Error(`Token signing algorithm ${String(c.alg)} is not accepted`);let u=t.find(e=>e.kid===c.kid&&e.kty===l.kty&&(e.kty!==`EC`||e.crv===`P-256`));if(!u)throw Error(`Token signing key is not published by the server`);let d=ma().subtle,f=await d.importKey(`jwk`,l.key(u),l.imported,!1,[`verify`]),p=new TextEncoder().encode(`${a}.${o}`);if(!await d.verify(l.signature,f,pa(s),p))throw Error(`Token signature is not valid`);let m=P(e),h=Array.isArray(m.aud)?m.aud:[m.aud];if(m.iss!==n)throw Error(`Token issuer does not match the server`);if(!h.includes(r))throw Error(`Token is not issued for this app`);if(typeof m.exp!=`number`||N(m,0))throw Error(`Token has expired`);if(i&&m.type!==i)throw Error(`Token type is not valid`)}async function ga(e,t,n){if(!t)throw Error(`An app id is required to accept tokens from the URL`);if(!n.access_token)throw Error(`No access token received`);ma();let r=e.replace(/\/+$/,``),[i,a]=await Promise.all([c.default.get(`${r}/.well-known/openid-configuration`),c.default.get(`${r}/.well-known/jwks.json`)]),o=i.data?.issuer,s=a.data?.keys??[];if(!o)throw Error(`The server did not publish an issuer`);await ha(n.access_token,s,o,t,F.access_token),n.refresh_token&&await ha(n.refresh_token,s,o,t,F.refresh_token),n.id_token&&await ha(n.id_token,s,o,t)}var Q={twoFactorCodeInvalid:`error.api.request.2fa_code.invalid`,challengeInvalid:`error.upgrade.challenge_invalid`,challengeSessionMismatch:`error.upgrade.challenge_session_mismatch`,challengeTooManyAttempts:`error.upgrade.challenge_too_many_attempts`,unsupportedFactor:`error.upgrade.unsupported_factor`,noSession:`error.upgrade.no_session`,unavailable:`error.upgrade.unavailable`,methodNotRegistered:`error.upgrade.method_not_registered`,prepareNotRequired:`error.upgrade.prepare_not_required`,methodNotSupported:`error.2fa.method_not_supported`,twoFactorNotEnabled:`error.2fa.not_enabled`,notImplemented:`error.not.implemented`,tokenInvalid:`error.api.request.token.invalid`,grantPredatesCredentialReset:`error.grant.predates_credential_reset`,tokenAccessEnded:`error.token.access_ended`,userNotFound:`error.user.not_found`},_a=Object.freeze([Q.twoFactorCodeInvalid,Q.twoFactorNotEnabled,Q.challengeInvalid,Q.challengeSessionMismatch,Q.challengeTooManyAttempts]),va=Object.freeze([Q.tokenInvalid,Q.grantPredatesCredentialReset,Q.tokenAccessEnded,Q.userNotFound]),ya=Object.freeze([`wrong_code`,`challenge_spent`,`not_registered`,`prepare_not_required`]),ba=e=>ya.includes(e),xa={wrong_code:`That code was not accepted. Try again.`,challenge_spent:`That verification challenge is no longer valid. Start again.`,exhausted:`Too many attempts. Try again later.`,rate_limited:`Too many requests. Try again later.`,attempts_exhausted:`Too many incorrect attempts. Verification was not completed.`,not_registered:`That verification method is not set up for this account.`,prepare_not_required:`This verification method needs no preparation round.`,fatal:`This verification method cannot be used right now.`,unavailable:`Step-up verification is not available on this deployment.`,protocol:`The server returned an unexpected upgrade response.`,network:`The verification request did not reach the server.`,session_changed:`The session ended during verification.`},$=class extends Error{constructor(e){super(e.message||xa[e.kind]),this.name=`UpgradeTransportError`,this.code=`upgrade_transport`,this.kind=e.kind,this.status=e.status,this.errorId=e.errorId,e.retryAfter!==void 0&&(this.retryAfter=e.retryAfter),this.retryable=ba(e.kind),e.cause!==void 0&&(this.cause=e.cause)}},Sa=Object.freeze([`upgrade_transport`,`upgrade_insufficient`,`upgrade_unavailable`,`upgrade_session_changed`,`upgrade_cancelled`,`upgrade_unsatisfiable`,`upgrade_sign_in_required`]),Ca=e=>typeof e==`object`&&!!e&&typeof e.code==`string`&&Sa.includes(e.code),wa=e=>e instanceof $||typeof e==`object`&&!!e&&e.code===`upgrade_transport`,Ta=e=>{let t=e?.error,n=typeof t==`string`?t:t?.message;if(typeof n==`string`&&n&&!n.startsWith(`localized error:`))return n},Ea=e=>{if(!e||typeof e!=`object`)return;let t=e[`retry-after`];return typeof t==`string`&&/^\d+$/.test(t.trim())?Number(t.trim()):void 0},Da=e=>{if(typeof e!=`object`||!e)return{hasResponse:!1,message:typeof e==`string`?e:void 0};let t=e,n=t.response,r=n?.data,i=typeof r?.error?.id==`string`?r.error.id:void 0;return{status:typeof t.status==`number`?t.status:typeof n?.status==`number`?n.status:void 0,errorId:typeof t.id==`string`?t.id:i,message:typeof t.message==`string`?t.message:void 0,hasResponse:n!==void 0||typeof t.status==`number`,serverText:Ta(n?.data),retryAfter:Ea(n?.headers)}},Oa=(e,t)=>{switch(e){case Q.twoFactorCodeInvalid:return`wrong_code`;case Q.challengeInvalid:case Q.challengeSessionMismatch:return`challenge_spent`;case Q.challengeTooManyAttempts:return`exhausted`;case Q.methodNotRegistered:return`not_registered`;case Q.twoFactorNotEnabled:return t===`refresh`?`session_changed`:`not_registered`;case Q.prepareNotRequired:return`prepare_not_required`;case Q.unavailable:case Q.notImplemented:return`unavailable`;case Q.unsupportedFactor:case Q.noSession:case Q.methodNotSupported:return`fatal`;case Q.tokenInvalid:return t===`refresh`?`session_changed`:`fatal`;case`error.service.unavailable`:return`network`;default:return}},ka=(e,t)=>e===void 0?`network`:e===501?`unavailable`:e===400?`fatal`:e===429?`rate_limited`:e===401||e===403?t===`start`?`challenge_spent`:`session_changed`:e>=500?`network`:`fatal`,Aa=(e,t)=>{if(e instanceof $)return e;let n=Da(e);if(!n.hasResponse)return new $({kind:`network`,message:n.message,cause:e});let r=Oa(n.errorId,t)??ka(n.status,t);return r===`rate_limited`?new $({kind:r,message:n.serverText,status:n.status,errorId:n.errorId,retryAfter:n.retryAfter,cause:e}):new $({kind:r,message:n.message,status:n.status,errorId:n.errorId,cause:e})},ja=e=>e.errorId!==void 0&&_a.includes(e.errorId),Ma=e=>e.errorId!==void 0&&va.includes(e.errorId),Na=class extends Error{constructor(e,t,n){super(n??`The session was elevated, but this action requires a higher assurance level`),this.name=`UpgradeInsufficientError`,this.code=`upgrade_insufficient`,this.obtained=e,this.required=t}},Pa=class extends Error{constructor(e=`Step-up verification is not available on this deployment`){super(e),this.name=`UpgradeUnavailableError`,this.code=`upgrade_unavailable`}},Fa=class extends Error{constructor(e=`The session changed during verification`){super(e),this.name=`UpgradeSessionChangedError`,this.code=`upgrade_session_changed`}},Ia=e=>{if(e&&typeof e.sub==`string`&&e.sub!==``)return typeof e.sid==`string`&&e.sid!==``?{sub:e.sub,sid:e.sid}:{sub:e.sub}},La=(e,t)=>!t||t.sub!==e.sub?!1:e.sid!==void 0&&t.sid!==void 0?e.sid===t.sid:!0;function Ra(e){if(!e||typeof e!=`string`)return!1;let t=e.split(`.`);if(t.length!==3)return!1;let n=/^[A-Za-z0-9_-]+$/;return t.every(e=>n.test(e)&&e.length>0)}function za(e){return e.replace(/<[^>]*>/g,``).substring(0,200)}function Ba(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return t.length!==0&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function Va(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return/^\+[1-9]\d{1,14}$/.test(t)}function Ha(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return t.length<3||t.length>30?!1:/^[a-zA-Z0-9_-]+$/.test(t)}function Ua(e,t=6){return!e||typeof e!=`string`?!1:(t===8?/^\d{8}$/:/^\d{6}$/).test(e)}function Wa(e){if(!e||typeof e!=`string`)return null;let t=e.toUpperCase().replace(/\s+/g,``);return t.length>64||!/^[A-Z0-9-]+$/.test(t)||t.replace(/-/g,``)===``?null:t}var Ga=e=>e?[e]:[],Ka=`passflow_2fa_pkce`,qa=3e5,Ja=`passflow_pwless_pending`,Ya=3e3,Xa=`passflow_federated_pkce`,Za=6e5,Qa=`AppId is required for federated auth`;function $a(e){let t;try{t=new URL(e).protocol}catch{t=void 0}if(t!==`https:`&&t!==`http:`)throw Error(`The federated start returned an address that is not http or https`);return e}function eo(e){if(e)try{let{protocol:t}=new URL(e);return t===`https:`||t===`http:`?e:void 0}catch{return}}function to(e){return e.provider?.startsWith(`conn_`)?e.login_hint:void 0}function no(e){let t={};return e.connection_id!==void 0&&(t.connection_id=e.connection_id),e.email!==void 0&&(t.email=e.email),t}var ro=10,io=`The sign-in answered with a PKCE code, but its verifier is gone`,ao=(e,t)=>new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let i=()=>{clearTimeout(a),r(t?.reason)},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})}),oo=e=>{if(!e)return;let t=new URLSearchParams(e.search).get(`token`);if(t)return t;let n=e.hash.indexOf(`?`);return n<0?void 0:new URLSearchParams(e.hash.slice(n+1)).get(`token`)??void 0},so=e=>{if(e)try{return P(e).email}catch{return}},co=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d=ye,f,p={coordination:ki()},m){this.authApi=e,this.deviceService=t,this.storageManager=n,this.subscribeStore=r,this.tokenCacheService=i,this.scopes=a,this.createTenantForNewUser=o,this.url=s,this.sessionCallbacks=c,this.appId=l,this.platform=d,this.readPkceEnabled=f,this.readAppSettings=m,this.emailChallenges=new Map,this.tokenExchangeConfig=u,this.deviceKey=p.deviceKey,this.enrolDeviceKeyRequest=p.enrolDeviceKeyRequest,this.tokenDeliveryManager=new fe(n),this.setBffModeIfConfigured(),this.refresh=da({emit:this.createRefreshEmit(),storage:n,cache:i,transport:this.createRefreshTransport(),coordination:p.coordination,platform:d,...p.strikes===void 0?{}:{strikes:p.strikes},logger:Bi()}),this.initializeSession()}setAppId(e){let t=this.appId;e!==t&&(this.appId=e,this.tokenDeliveryManager.reload(),this.setBffModeIfConfigured(),t&&(this.refresh.sessionStarted(),this.initializeSession()))}setBffModeIfConfigured(){this.tokenExchangeConfig?.enabled&&this.tokenDeliveryManager.setMode(I.BFF)}async isSimpleModeApp(){try{return(await this.readAppSettings?.())?.pkce_enabled===!1}catch{return!1}}async initializeSession(){(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode())&&await this.restoreSession()}async restoreSession(){if(this.storageManager.holdsOnlyOtherAppSession())return!1;let e=this.refresh.generation,t=()=>this.refresh.generation!==e;if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.statusUrl)try{let e=await fetch(this.tokenExchangeConfig.statusUrl,{method:`GET`,credentials:`include`}),n=e.ok?await e.json():void 0;return t()?!1:e.ok&&n.authenticated?(this.tokenDeliveryManager.setSessionValid(),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return t()||this.tokenDeliveryManager.setSessionInvalid(),!1}if(!this.tokenDeliveryManager.isCookieMode())return!1;try{let e=await this.authApi.validateSession();return t()?!1:e?.id?(this.tokenDeliveryManager.setSessionValid(),this.subscribeStore.notify(G.SessionRestored,e),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return t()||this.tokenDeliveryManager.setSessionInvalid(),!1}}async processAuthResponse(e,t){await this.applyAuthResponse(e,t,{replace:!0}),this.refresh.sessionStarted()}async applyAuthResponse(e,t,n){if(e.code&&!e.access_token)throw Error(`A PKCE authorization code was not exchanged, so there are no tokens to apply`);if(this.issuedForAnotherApp(e))throw Error(`The tokens were issued for another app than the current app id, so they are not applied`);this.tokenExchangeConfig?.enabled||`token_delivery`in e&&e.token_delivery&&this.tokenDeliveryManager.setMode(e.token_delivery),this.tokenDeliveryManager.setSessionValid(),this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.callbackUrl&&await this.forwardTokensToBFF(e),e.scopes=t,this.storageManager.saveTokens(e,this.tokenDeliveryManager.getMode(),n),this.tokenCacheService.setTokensCache(e),e.csrf_token&&this.storageManager.setCsrfToken(e.csrf_token),this.deviceKey&&e.refresh_challenge&&this.storageManager.setRefreshChallenge(e.refresh_challenge)}issuedForAnotherApp(e){if(!this.appId)return!1;let t=e.id_token??e.access_token;if(!t)return!1;let n;try{n=P(t).aud}catch{return!1}return n!==void 0&&!(Array.isArray(n)?n:[n]).includes(this.appId)}notifyRegisteredAndSignedIn(e){let t={tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens()};this.subscribeStore.notify(G.Register,t),this.subscribeStore.notify(G.SignIn,t)}handlePendingSecondFactor(e,t,n,r){return e.tfa_token?(n?this.rememberPkceSignIn(n.verifier,r):this.forgetPkceSignIn(),this.subscribeStore.notify(G.TwoFactorRequired,{email:t||``,challengeId:e.challenge_id||``,tfaToken:e.tfa_token||``}),!0):!1}handleEmailVerificationStep(e,t,n,r,i){if(!Je(e))return!1;let a=e.challenge_id||void 0;return a&&r?this.rememberPkceSignIn(r.verifier,i):this.forgetPkceSignIn(),a&&this.rememberEmailChallenge(a,{operation:t,email:n,scopes:i,pkce:r!==void 0}),this.subscribeStore.notify(G.EmailVerificationRequired,{email:n,challengeId:a,operation:t}),!0}rememberEmailChallenge(e,t){this.emailChallenges.delete(e),this.emailChallenges.set(e,t);for(let e of this.emailChallenges.keys()){if(this.emailChallenges.size<=ro)break;this.emailChallenges.delete(e)}}rememberPkceSignIn(e,t){if(this.pendingPkce={verifier:e,scopes:t,expiresAt:Date.now()+qa},typeof sessionStorage<`u`)try{sessionStorage.setItem(Ka,JSON.stringify(this.pendingPkce))}catch{}}readPendingPkce(){if(!this.pendingPkce&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(Ka);this.pendingPkce=e?JSON.parse(e):void 0}catch{this.pendingPkce=void 0}return this.pendingPkce&&Date.now()>=this.pendingPkce.expiresAt&&this.forgetPkceSignIn(),this.pendingPkce}hasPendingPkceSignIn(){return this.readPendingPkce()!==void 0}forgetPkceSignIn(){if(this.pendingPkce=void 0,typeof sessionStorage<`u`)try{sessionStorage.removeItem(Ka)}catch{}}rememberPendingPasswordless(e){if(this.pendingPasswordless=e,typeof sessionStorage<`u`)try{sessionStorage.setItem(Ja,JSON.stringify(e))}catch{}}readPendingPasswordless(){if(!this.pendingPasswordless&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(Ja);this.pendingPasswordless=e?JSON.parse(e):void 0}catch{this.pendingPasswordless=void 0}return this.pendingPasswordless&&!(Date.now()<this.pendingPasswordless.expiresAt)&&this.forgetPendingPasswordless(),this.pendingPasswordless}forgetPendingPasswordless(){if(this.pendingPasswordless=void 0,typeof sessionStorage<`u`)try{sessionStorage.removeItem(Ja)}catch{}}rememberFederatedSlot(e,t){if(this.federatedSlot={verifier:e,scopes:t,expiresAt:Date.now()+Za},typeof sessionStorage<`u`)try{sessionStorage.setItem(Xa,JSON.stringify(this.federatedSlot))}catch{}}readFederatedSlot(){if(!this.federatedSlot&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(Xa);this.federatedSlot=e?JSON.parse(e):void 0}catch{this.federatedSlot=void 0}return this.federatedSlot&&Date.now()<this.federatedSlot.expiresAt?this.federatedSlot:void 0}forgetFederatedSlot(){if(this.federatedSlot=void 0,typeof sessionStorage<`u`)try{sessionStorage.removeItem(Xa)}catch{}}async startPkce(){let e=!1;try{e=await this.readPkceEnabled?.()??!1}catch(e){Bi().warn(`Passflow: could not read the app settings, so this sign-in sends no PKCE challenge`,e);return}return e?_r():void 0}async exchangeCode(e,t){return!e.code||!t?e:await this.authApi.pkceExchange(e.code,t.verifier)}async completePkceSignIn(e){let t=this.readPendingPkce();if(!t)throw Error(io);let n=await this.authApi.pkceExchange(e,t.verifier);return await this.processAuthResponse(n,t.scopes??this.scopes),n}async applyTokens(e){let t=e;(t.access_token||t.id_token||t.token_delivery)&&await this.processAuthResponse(t,t.scopes??this.readPendingPkce()?.scopes??this.scopes)}async notifySignedIn(e){this.subscribeStore.notify(G.SignIn,{tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()}async forwardTokensToBFF(e){if(!this.tokenExchangeConfig?.callbackUrl)return;let t=await fetch(this.tokenExchangeConfig.callbackUrl,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`},body:JSON.stringify({access_token:e.access_token,refresh_token:e.refresh_token,id_token:e.id_token,expires_in:e.expires_in})});if(!t.ok)throw Error(`BFF token storage failed: ${t.status}`)}async signIn(e,t){if(`email`in e&&e.email&&!Ba(e.email)){let e=Error(`Invalid email format`),t={operation:`sign-in`,message:`Invalid email format`,originalError:e,code:`VALIDATION_ERROR`};throw W(this.subscribeStore,t),e}if(`username`in e&&e.username&&!Ha(e.username)){let e=Error(`Invalid username format. Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens`),t={operation:`sign-in`,message:`Invalid username format. Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens`,originalError:e,code:`VALIDATION_ERROR`};throw W(this.subscribeStore,t),e}if(`phone`in e&&e.phone&&!Va(e.phone)){let e=Error(`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`),t={operation:`sign-in`,message:`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`,originalError:e,code:`VALIDATION_ERROR`};throw W(this.subscribeStore,t),e}this.subscribeStore.notify(G.SignInStart,{email:e.email});let n=this.deviceService.getDeviceId(),r=Ct(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes;try{let i=await this.startPkce(),a=i?{...e,code_challenge:i.challenge}:e,o=await this.signInProof(),s=o?await this.authApi.signIn(a,n,r,t,o):await this.authApi.signIn(a,n,r,...Ga(t));if(this.handleEmailVerificationStep(s,`sign-in`,e.email,i,e.scopes)||this.handlePendingSecondFactor(s,e.email,i,e.scopes))return s;let c=await this.exchangeCode(s,i);return this.handlePendingSecondFactor(c,e.email)||(await this.processAuthResponse(c,e.scopes),this.subscribeStore.notify(G.SignIn,{tokens:c,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),c}catch(e){let t={operation:`sign-in`,message:e instanceof Error?e.message:`Sign in failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async signUp(e,t){if(e.user.email&&!Ba(e.user.email)){let e=Error(`Invalid email format`),t={operation:`sign-up`,message:`Invalid email format`,originalError:e,code:`VALIDATION_ERROR`};throw W(this.subscribeStore,t),e}if(e.user.phone_number&&!Va(e.user.phone_number)){let e=Error(`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`),t={operation:`sign-up`,message:`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`,originalError:e,code:`VALIDATION_ERROR`};throw W(this.subscribeStore,t),e}this.subscribeStore.notify(G.RegisterStart,{email:e.user.email}),e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{let n=await this.startPkce(),r=await this.authApi.signUp(n?{...e,code_challenge:n.challenge}:e,...Ga(t));if(this.handleEmailVerificationStep(r,`sign-up`,e.user.email,n,e.scopes)||this.handlePendingSecondFactor(r,e.user.email,n,e.scopes))return r;let i=await this.exchangeCode(r,n);return this.handlePendingSecondFactor(i,e.user.email)||(await this.processAuthResponse(i,e.scopes),this.notifyRegisteredAndSignedIn(i),await this.submitSessionCheck()),i}catch(e){let t={operation:`sign-up`,message:e instanceof Error?e.message:`Sign up failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async passwordlessSignIn(e,t){if(e.email&&!Ba(e.email)){let e=Error(`Invalid email format`),t={operation:`passwordless.start`,message:`Invalid email format`,originalError:e,code:`VALIDATION_ERROR`};throw W(this.subscribeStore,t),e}if(e.phone&&!Va(e.phone)){let e=Error(`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`),t={operation:`passwordless.start`,message:`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`,originalError:e,code:`VALIDATION_ERROR`};throw W(this.subscribeStore,t),e}this.subscribeStore.notify(G.SignInStart,{email:e.email});let n=e.scopes??this.scopes,r=this.deviceService.getDeviceId(),i=Ct(this.platform.getDeviceType());try{let a=await this.startPkce(),o=await this.authApi.passwordlessSignIn({...e,scopes:n,...a?{code_challenge:a.challenge}:{}},r,i,...Ga(t));return a&&o.challenge_id?this.rememberPendingPasswordless({challengeId:o.challenge_id,verifier:a.verifier,codeChallenge:a.challenge,matchCode:o.match_code,email:e.email,scopes:n,expiresAt:new Date(o.expires_at).getTime()}):this.forgetPendingPasswordless(),o}catch(e){let t={operation:`passwordless.start`,message:e instanceof Error?e.message:`Failed to send passwordless sign-in link`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async passwordlessSignInComplete(e,t){this.subscribeStore.notify(G.SignInStart,{}),e.scopes=e.scopes??this.scopes,e.device=this.deviceService.getDeviceId();let n=this.readPendingPasswordless(),r=n?.challengeId===e.challenge_id?n:void 0,i=!1;try{let n=await this.authApi.passwordlessSignInComplete(e,...Ga(t));if(i=!0,this.handlePendingSecondFactor(n,r?.email,r&&{verifier:r.verifier},r?.scopes))return this.forgetPendingPasswordless(),n;let a=n;if(n.code){if(!r)throw Error(io);if(a=await this.authApi.pkceExchange(n.code,r.verifier),this.handlePendingSecondFactor(a))return this.forgetPendingPasswordless(),{...a,redirect_url:n.redirect_url??``}}let o=n.redirect_url?{...a,redirect_url:n.redirect_url}:a;return await this.processAuthResponse(o,r?.scopes??e.scopes),this.forgetPendingPasswordless(),this.subscribeStore.notify(G.SignIn,{tokens:o,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),{...o,redirect_url:n.redirect_url??``}}catch(e){i&&this.forgetPendingPasswordless();let t={operation:`passwordless.complete`,message:e instanceof Error?e.message:`Passwordless sign in failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async waitForPasswordlessSignIn(e,t){let n=t?.signal;try{let t=this.readPendingPasswordless();if(t?.challengeId!==e)throw Error(io);for(;;){if(n?.aborted)throw n.reason;if(Date.now()>=t.expiresAt)return this.forgetPendingPasswordless(),{status:`expired`};if(this.readPendingPasswordless()?.challengeId!==e)throw Error(io);let r;try{r=await this.authApi.passwordlessStatus({challenge_id:e,code_challenge:t.codeChallenge},{signal:n})}catch(e){if(n?.aborted)throw n.reason;if(e instanceof B&&e.status>=400&&e.status<500&&e.status!==429)throw this.forgetPendingPasswordless(),e}if(r?.status===`denied`||r?.status===`expired`||r?.status===`completed`)return this.forgetPendingPasswordless(),{status:r.status};if(r?.status===`approved`&&r.code)return await this.finishApprovedPasswordless(r.code,t);if(r&&r.status===void 0&&r.tfa_token)return this.handlePendingSecondFactor(r,t.email),this.forgetPendingPasswordless(),{status:`second-factor-required`};if(r&&r.status===void 0&&r.redirect_url)return this.forgetPendingPasswordless(),{status:`signed-in`,tokens:{redirect_url:r.redirect_url}};await ao(Ya,n)}}catch(e){if(n?.aborted&&e===n.reason)throw e;let t={operation:`passwordless.wait`,message:e instanceof Error?e.message:`Waiting for the passwordless sign-in failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async finishApprovedPasswordless(e,t){try{let n=await this.authApi.pkceExchange(e,t.verifier);return this.handlePendingSecondFactor(n,t.email)?(this.forgetPendingPasswordless(),{status:`second-factor-required`}):(await this.processAuthResponse(n,t.scopes),this.forgetPendingPasswordless(),this.subscribeStore.notify(G.SignIn,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),{status:`signed-in`,tokens:n})}catch(e){throw this.forgetPendingPasswordless(),e}}getPendingPasswordlessSignIn(e){let t=this.readPendingPasswordless();if(t?.challengeId===e&&t.matchCode)return{matchCode:t.matchCode,expiresAt:t.expiresAt}}checkRedirectUrl(e){return this.authApi.checkRedirectUrl(e)}async getPasswordlessApproval(e){try{return await this.authApi.passwordlessApprovalInfo({challenge_id:e})}catch(e){throw this.reportApprovalFailure(e),e}}async decidePasswordlessApproval(e,t,n,r){try{await this.authApi.passwordlessApprovalDecide({challenge_id:e,otp:t,approve:n,match_code:r})}catch(e){throw this.reportApprovalFailure(e),e}}reportApprovalFailure(e){let t={operation:`passwordless.approval`,message:e instanceof Error?e.message:`Passwordless approval failed`,originalError:e,code:e instanceof B?e.id:void 0};W(this.subscribeStore,t)}async verifyEmailCode(e){let t=this.emailChallenges.get(e.challenge_id),n=t?.email;try{let r=t?.pkce===!1?void 0:this.readPendingPkce();if(t?.pkce&&!r)throw Error(io);let i=await this.authApi.validateEmailCode(e);this.emailChallenges.delete(e.challenge_id);let a=r?.scopes??t?.scopes??this.scopes;if(this.handleEmailVerificationStep(i,t?.operation??`sign-in`,n,r,a)||this.handlePendingSecondFactor(i,n,r,a))return i;let o=i;if(i.code){if(!r)throw Error(io);if(o=await this.authApi.pkceExchange(i.code,r.verifier),this.handlePendingSecondFactor(o,n))return o}let s=i.redirect_url?{...o,redirect_url:i.redirect_url}:o;return await this.processAuthResponse(s,a),this.forgetPkceSignIn(),t?.operation===`sign-up`?this.notifyRegisteredAndSignedIn(s):this.subscribeStore.notify(G.SignIn,{tokens:s,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),s}catch(e){let t={operation:`email-verification.complete`,message:e instanceof Error?e.message:`Email verification failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async logOut(e){let t=this.refresh.identity(),n,r=e??this.storageManager.getHostedSignIn();return await this.refresh.signOut(async e=>{n=await this.callLogoutApi(e,r),this.forgetPkceSignIn(),this.forgetPendingPasswordless(),this.emailChallenges.clear(),this.clearLocalSession()}),{userId:t,samlLogoutUrl:n}}resetSession(){let e=this.refresh.identity();return this.refresh.signOutNow(()=>{this.emailChallenges.clear(),this.clearLocalSession()}),e}hostedEndSessionUrl(e){let t=this.storageManager.getHostedSignIn();if(!t)return;let n={post_logout_redirect_uri:e??t};this.appId&&(n.client_id=this.appId);let r=this.storageManager.getToken(F.id_token)??this.storageManager.getIdToken();return r&&(n.id_token_hint=r),`${this.url.replace(/\/+$/,``)}/oidc/end_session?${new URLSearchParams(n)}`}async callLogoutApi(e,t){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.logoutUrl){try{await fetch(this.tokenExchangeConfig.logoutUrl,{method:`POST`,credentials:`include`})}catch{}return}let n=e??this.storageManager.getToken(F.refresh_token),r=this.storageManager.getDeviceId();try{let e=await this.authApi.logOut(r,n,!this.appId,t);if(e.status!==`ok`)throw Error(`Logout failed`);return eo(e.saml_logout_url)}catch{return}}clearLocalSession(){this.storageManager.deleteTokens(),this.tokenDeliveryManager.reset(),this.tokenCacheService.setTokensCache(void 0),this.tokenCacheService.stopTokenCheck?.()}readSessionPin(){try{let e=this.storageManager.getToken(F.access_token);return e?Ia(P(e)):void 0}catch{return}}assertSessionPin(e){if(e&&!La(e,this.readSessionPin()))throw console.warn(`[passflow] the session or user changed while a step-up upgrade was in flight; the elevated tokens were discarded and the live session was left untouched.`),new Fa(`The session changed during verification, so the elevated tokens were discarded`)}refreshMode(){return this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.refreshUrl?`bff`:this.tokenDeliveryManager.isCookieMode()?`cookie`:`json`}createRefreshEmit(){return(e,t)=>{let n=this.subscribeStore;switch(e){case`refresh`:{let{tokens:e,source:r}=t;n.notify(G.Refresh,{tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens(),source:r});return}case`signin`:{let{tokens:e,origin:r}=t;n.notify(G.SignIn,{tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens(),origin:r});return}case`error`:W(n,t);return;case`refresh:start`:n.notify(G.RefreshStart,{});return;case`token-cache-expired`:n.notify(G.TokenCacheExpired,t);return;case`refresh:failing`:n.notify(G.RefreshFailing,t);return;case`refresh:recovered`:n.notify(G.RefreshRecovered,t);return;case`session:expired`:n.notify(G.SessionExpired,t);return;case`signout`:n.notify(G.SignOut,t);return;default:Bi().warn(`[passflow] Unknown refresh event: ${String(e)}`)}}}createRefreshTransport(){return{mode:()=>this.refreshMode(),send:async({tokens:e,upgrade:t})=>{let n=this.refreshMode();if(n===`bff`)return await this.sendBffRefresh();if(this.deviceKey)return await this.sendDeviceKeyRefresh(this.deviceKey,n,e,t);if(n===`cookie`)return t?await this.authApi.refreshToken(``,this.scopes,void 0,t):await this.authApi.refreshToken(``,this.scopes);let r=e?.refresh_token??``,i=e?.scopes??this.scopes,a=e?.access_token;return t?await this.authApi.refreshToken(r,i,a,t):await this.authApi.refreshToken(r,i,a)},applyOpaque:async e=>{this.tokenDeliveryManager.setSessionValid(),this.tokenDeliveryManager.isBFFMode()?(e.id_token&&this.storageManager.setIdToken(e.id_token),e.csrf_token&&this.storageManager.setCsrfToken(e.csrf_token)):await this.applyAuthResponse(e,this.scopes)},invalidate:()=>{this.tokenDeliveryManager.setSessionInvalid(),this.storageManager.clearIdToken(),this.storageManager.clearCsrfToken()},assertPin:e=>this.assertSessionPin(e),opaqueMarker:()=>{let e=this.storageManager.getIdToken(),t=this.storageManager.getCsrfToken();return e===void 0&&t===void 0?void 0:`${e??``}\n${t??``}`}}}async sendDeviceKeyRefresh(e,t,n,r){let i=t===`json`?n?.refresh_token??``:``,a=t===`json`?n?.scopes??this.scopes:this.scopes,o=t===`json`?n?.access_token:void 0,s={};if(e.supported)try{let n=t===`json`?i&&await En(i):this.storageManager.getRefreshChallenge(),r=n?await e.proof(`refresh`,n):void 0;r&&(s={proof:r})}catch(t){throw await e.clear().catch(()=>void 0),new B({id:Bn.proofUnavailable,message:`The device key could not sign the refresh. Sign in again.`,status:0,location:z.refresh,time:new Date().toISOString()},{cause:t})}try{return await this.authApi.refreshToken(i,a,o,r,s)}catch(t){throw Vn(Fi(t))&&await e.clear().catch(()=>void 0),t}}async signInProof(){let e=this.deviceKey;if(e&&this.appId)try{if(!await e.isEnrolled())return;let{challenge:t}=await this.authApi.deviceChallenge();return await e.proof(`sign_in`,t)}catch{return}}async enrolDeviceKey(){try{let e=this.deviceKey,t=this.enrolDeviceKeyRequest;if(!e||!t)throw Error(`Device keys are off: set deviceKey: true in the Passflow config`);if(!e.supported)throw Error(Pn);let{challenge:n}=await this.authApi.deviceChallenge();await t({proof:await e.enrolProof(n),key_storage:`software`}),await e.markEnrolled()}catch(e){let t=Fi(e);if(t===Bn.keyReused){await this.deviceKey?.clear().catch(()=>void 0);let e=this.resetSession();this.subscribeStore.notify(G.SignOut,e===void 0?{origin:`this-tab`}:{origin:`this-tab`,userId:e})}throw W(this.subscribeStore,{operation:`device-key.enrol`,message:e instanceof Error?e.message:`Device key enrolment failed`,originalError:e,code:t}),e}}async secondFactorCompleted(){this.deviceKey&&await this.enrolDeviceKey().catch(()=>void 0)}async sendBffRefresh(){let e=this.tokenExchangeConfig?.refreshUrl??``,t=await fetch(e,{method:`POST`,credentials:`include`});if(!t.ok){let n,r;try{let e=await t.json();typeof e?.error?.id==`string`&&(n=e.error.id),typeof e?.error?.message==`string`&&(r=e.error.message)}catch{}throw new B({id:n??`error.http.${t.status}`,message:r??`BFF token refresh failed`,status:t.status,location:e,time:new Date().toISOString()})}return await t.json()}async refreshToken(e,t){if(e&&this.tokenDeliveryManager.isBFFMode())throw new $({kind:`unavailable`,message:`Step-up verification cannot be committed through a BFF refresh endpoint`});if(e)return await this.refresh.commitUpgrade(e,t);if(this.refreshMode()===`json`&&!this.refresh.ended){let e=this.storageManager.getTokens();if(!e?.refresh_token){let t=Error(e?`No refresh token found`:`No tokens found`);throw W(this.subscribeStore,{operation:`refresh`,source:`refresh-token`,message:t.message,originalError:t}),t}}return await this.refresh.refresh({trigger:`refresh-token`,fresh:!0})}async sendPasswordResetEmail(e,t){try{return await this.authApi.sendPasswordResetEmail(e,...Ga(t))}catch(e){let t={operation:`password-reset.send`,message:e instanceof Error?e.message:`Failed to send password reset email`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async resetPassword(e,t,n){this.subscribeStore.notify(G.SignInStart,{});let r=n??oo(this.platform.getCurrentUrl()),i=t??this.scopes;try{let t=await this.startPkce(),n=t?await this.authApi.resetPassword(e,i,r,t.challenge):await this.authApi.resetPassword(e,i,r);if(this.handleEmailVerificationStep(n,`reset-password`,so(r),t,i)||this.handlePendingSecondFactor(n,void 0,t,i))return n;let a=await this.exchangeCode(n,t);if(this.handlePendingSecondFactor(a))return a;let o=n.redirect_url?{...a,redirect_url:n.redirect_url}:a;return await this.processAuthResponse(o,i),this.subscribeStore.notify(G.SignIn,{tokens:o,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),o}catch(e){let t={operation:`password-reset.complete`,message:e instanceof Error?e.message:`Password reset failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async passkeyRegister(e,t){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);this.subscribeStore.notify(G.RegisterStart,{});let n=this.deviceService.getDeviceId(),r=Ct(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{let i=await this.startPkce(),{challenge_id:a,publicKey:o}=await this.authApi.passkeyRegisterStart(i?{...e,code_challenge:i.challenge}:e,n,r,!this.appId,...Ga(t));o.user.id=this.platform.btoa(o.user.id);let s=await this.platform.passkeys.startRegistration(o);if(!s)throw Error(`Passkey registration was not completed`);let c=await this.authApi.passkeyRegisterComplete(s,n,a,!this.appId,...Ga(t));if(this.handlePendingSecondFactor(c,void 0,i,e.scopes))return c;let l=await this.exchangeCode(c,i);return this.handlePendingSecondFactor(l)||(await this.processAuthResponse(l,e.scopes),this.notifyRegisteredAndSignedIn(l),await this.submitSessionCheck()),l}catch(e){let t={operation:`passkey.register`,message:e instanceof Error?e.message:`Passkey registration failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async passkeyAuthenticate(e,t){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);this.subscribeStore.notify(G.SignInStart,{});let n=this.deviceService.getDeviceId(),r=Ct(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes;try{let i=await this.startPkce(),{challenge_id:a,publicKey:o}=await this.authApi.passkeyAuthenticateStart(i?{...e,code_challenge:i.challenge}:e,n,r,!this.appId,...Ga(t)),s=await this.platform.passkeys.startAuthentication(o);if(!s)throw Error(`Passkey authentication was not completed`);let c=await this.signInProof(),l=c?await this.authApi.passkeyAuthenticateComplete(s,n,a,!this.appId,t,c):await this.authApi.passkeyAuthenticateComplete(s,n,a,!this.appId,...Ga(t));if(this.handlePendingSecondFactor(l,void 0,i,e.scopes))return l;let u=await this.exchangeCode(l,i);return this.handlePendingSecondFactor(u)||`access_token`in u&&(await this.processAuthResponse(u,e.scopes),this.subscribeStore.notify(G.SignIn,{tokens:u,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),u}catch(e){let t={operation:`passkey.authenticate`,message:e instanceof Error?e.message:`Passkey authentication failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}async usesFederatedPost(e){if(e?.agentTool===!0)return!0;try{return(await this.readAppSettings?.())?.bot_mode===`human_only`}catch{return!1}}federatedStartBody(e,t){let n=to(e);return{redirect_url:e.redirect_url??this.platform.getCurrentUrl()?.origin??``,scopes:t,...e.device?{device:e.device}:{},...e.create_tenant?{create_tenant:e.create_tenant}:{},...e.invite_token?{invite_token:e.invite_token}:{},...e.parent_challenge_id?{parent_challenge_id:e.parent_challenge_id}:{},...e.code_challenge?{code_challenge:e.code_challenge}:{},...e.code_challenge_method?{code_challenge_method:e.code_challenge_method}:{},...e.state?{state:e.state}:{},...n?{login_hint:n}:{}}}createFederatedAuthUrl(e){if(!this.appId)throw Error(Qa);let t=new URL(`/auth/federated/start/${e.provider}`,this.url);return t.search=new URLSearchParams(this.federatedStartQuery(e,e.scopes??this.scopes,this.appId)).toString(),t.toString()}federatedStartQuery(e,t,n){let r=to(e);return{scopes:t.join(` `),redirect_url:e.redirect_url??this.platform.getCurrentUrl()?.origin??``,appId:n,...e.invite_token?{invite_token:e.invite_token}:{},...e.create_tenant?{create_tenant:e.create_tenant.toString()}:{},...e.device?{device:e.device}:{},...e.code_challenge?{code_challenge:e.code_challenge}:{},...e.code_challenge_method?{code_challenge_method:e.code_challenge_method}:{},...e.state?{state:e.state}:{},...e.parent_challenge_id?{parent_challenge_id:e.parent_challenge_id}:{},...r?{login_hint:r}:{}}}createEnterpriseAuthUrl(e){if(!this.appId)throw Error(Qa);let t=e.scopes??this.scopes,n=this.deviceService.getDeviceId(),r=new URL(z.enterpriseStart,this.url);return r.search=new URLSearchParams({...no(e),...this.federatedStartQuery({...e,device:n},t,this.appId)}).toString(),r.toString()}async enterpriseStart(e,t){let n=e.scopes??this.scopes,r=this.deviceService.getDeviceId();return{auth_url:$a((await this.authApi.enterpriseStart({...no(e),...this.federatedStartBody({...e,device:r},n)},t)).auth_url)}}async federatedAuthWithPopup(e,t){if(this.subscribeStore.notify(G.SignInStart,{provider:e.provider}),!this.appId)throw Error(Qa);let n=e.scopes??this.scopes,r=this.deviceService.getDeviceId();try{this.forgetFederatedSlot();let i={mode:`popup`,expectedReturnOrigin:this.platform.getCurrentUrl()?.origin??``},a=(async()=>{let i=await this.startPkce(),a={...e,scopes:n,device:r,...i?{code_challenge:i.challenge,code_challenge_method:`S256`}:{}};return{url:await this.usesFederatedPost(t)?$a((await this.authApi.federatedStart(e.provider,this.federatedStartBody(a,n),t)).auth_url):this.createFederatedAuthUrl(a),pkce:i}})(),o,s=e=>{o=e,e&&this.rememberFederatedSlot(e.verifier,n)},c;if(this.platform.openPendingAuthUrl)c=this.platform.openPendingAuthUrl(a.then(e=>(s(e.pkce),e.url)),i);else{let e=await a;c=this.platform.openAuthUrl(e.url,i),s(e.pkce)}let l=await c;this.forgetFederatedSlot();let u=new URLSearchParams(l.callbackHash.replace(/^#/,``));if(this.handlePendingSecondFactor({tfa_token:u.get(`tfa_token`)??void 0}))return;let d=new URLSearchParams(l.callbackSearch),f=d.get(`code`),p=d.get(`access_token`)?d:u,m=p.get(`access_token`)||``,h=p.get(`refresh_token`)||``,g=p.get(`id_token`)||``,_={access_token:m,refresh_token:h||void 0,id_token:g||void 0,scopes:n};if(o){if(!f)throw Sr();if(_=await this.authApi.pkceExchange(f,o.verifier),this.handlePendingSecondFactor(_))return}else{if(!await this.isSimpleModeApp())throw Sr();await ga(this.url,this.appId,_)}await this.processAuthResponse(_,n),this.subscribeStore.notify(G.SignIn,{tokens:_,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.platform.navigateTo(this.platform.getCurrentUrl()?.origin??``)}catch(e){if(this.forgetFederatedSlot(),e instanceof U&&e.code===`TOKENS_IN_URL_NOT_ALLOWED`){W(this.subscribeStore,{operation:`tokens.from-url`,message:e.message,code:e.code,originalError:e});return}let t={operation:`federated.popup`,message:e instanceof Error?e.message:`Authentication failed`,code:e instanceof _e?`POPUP_CLOSED`:`AUTH_FAILED`,originalError:e};W(this.subscribeStore,t)}}federatedAuthWithRedirect(e,t){if(this.subscribeStore.notify(G.SignInStart,{provider:e.provider}),!this.appId)throw Error(Qa);let n=e.scopes??this.scopes,r=this.deviceService.getDeviceId();this.startPkce().then(async i=>{let a={...e,scopes:n,device:r,...i?{code_challenge:i.challenge,code_challenge_method:`S256`}:{}},o=await this.usesFederatedPost(t)?$a((await this.authApi.federatedStart(e.provider,this.federatedStartBody(a,n),t)).auth_url):this.createFederatedAuthUrl(a);i?this.rememberFederatedSlot(i.verifier,n):this.forgetFederatedSlot(),this.platform.navigateTo(o)}).catch(e=>this.reportFederatedRedirectFailure(e))}handleFederatedCode(e){if(!this.appId)return!1;let t=this.readFederatedSlot();return t?(this.forgetFederatedSlot(),this.finishFederatedLanding(e,t),!0):!1}async finishFederatedLanding(e,t){try{let n=await this.authApi.pkceExchange(e,t.verifier);if(this.handlePendingSecondFactor(n))return;await this.processAuthResponse(n,t.scopes),this.subscribeStore.notify(G.SignIn,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens(),source:`federated-landing`}),await this.submitSessionCheck()}catch(e){this.reportFederatedRedirectFailure(e)}}reportFederatedRedirectFailure(e){let t={operation:`federated.redirect`,message:e instanceof Error?e.message:`Federated sign-in failed`,originalError:e,code:e instanceof B?e.id:void 0};W(this.subscribeStore,t)}authRedirectUrl(e={}){try{let{url:t,redirectUrl:n,scopes:r,appId:i}=e??{},a=new URL(t??this.url);a.pathname=(a.pathname.endsWith(`/`)?a.pathname:a.pathname+`/`)+`web`;let o=r??this.scopes,s={appId:i??this.appId??``,redirectto:n??this.platform.getCurrentUrl()?.href??``,scopes:o.join(`,`)};return a.search=new URLSearchParams(s).toString(),a.toString()}catch(e){let t={operation:`auth-redirect.url`,message:e instanceof Error?e.message:`Failed to create auth redirect URL`,originalError:e};throw W(this.subscribeStore,t),e}}async authRedirect(e={}){try{let{url:t,appId:n,redirectUrl:r,scopes:i,state:a}=e;if(t!==void 0&&Tr(t)!==Tr(this.url)||n!==void 0&&n!==(this.appId??``))throw new U(`OVERRIDE_NOT_SUPPORTED`,`authRedirect() signs in to this instance's url and appId; create a Passflow instance for another server or app`);let o=await this.readAppSettings?.();if(o?.pkce_enabled!==!0){let e=this.authRedirectUrl({redirectUrl:r,scopes:i});this.platform.navigateTo(a?`${e}&${new URLSearchParams({state:a})}`:e);return}if(o.public_client===!1)throw new U(`CONFIDENTIAL_CLIENT`,br(o.type));let s=this.platform.getCurrentUrl(),c=await Dr({url:this.url,clientId:this.appId??``,redirectUri:r??(s?s.origin+s.pathname:``),scopes:i??this.scopes});this.platform.navigateTo(c)}catch(e){let t={operation:`auth-redirect`,message:e instanceof Error?e.message:`Failed to redirect to auth page`,originalError:e,code:e instanceof U?e.code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,t),e}}handleOidcLanding(e){if(!this.appId)return!1;let t=new URLSearchParams(e.search),n=t.get(`code`),r=t.get(`state`),i=t.get(`error`),a=t.get(`error_description`);if(t.get(`user_state`)||r===null||!n&&!i)return!1;let o=kr();if(o.status===`none`)return!1;Ar();for(let e of[`code`,`state`,`iss`,`error`,`error_description`])t.delete(e);let s=t.toString();return this.platform.replaceUrl(e.pathname+(s?`?${s}`:``)+e.hash),this.finishOidcLanding(async()=>{if(o.status===`unusable`)throw new U(`VERIFIER_MISSING`,`This sign-in has expired or its proof key is gone. Sign in again.`);if(o.slot.state!==r)throw new U(`STATE_MISMATCH`,`The sign-in answer does not belong to this sign-in. Sign in again.`);if(i||!n)throw new U(i??`TOKEN_EXCHANGE_FAILED`,za(a||i||`Sign in again.`));return{tokens:await Mr(this.url,n,o.slot),scopes:o.slot.scopes,returnUrl:o.slot.redirectUri}}),!0}async finishOidcLanding(e){try{await Promise.resolve();let{tokens:t,scopes:n,returnUrl:r}=await e();await this.processAuthResponse(t,n),this.storageManager.setHostedSignIn(r),this.subscribeStore.notify(G.SignIn,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens(),source:`oidc-landing`}),await this.submitSessionCheck()}catch(e){W(this.subscribeStore,{operation:`oidc.redirect`,message:e instanceof Error?e.message:`Sign-in failed`,code:e instanceof U?e.code:void 0,originalError:e})}}isAuthenticated(e){try{if(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode()){let t=!!e?.id_token||!!this.storageManager.getIdToken(),n=this.tokenDeliveryManager.isSessionValid(),r=this.tokenDeliveryManager.isSessionUnknown();return t&&(n||r)}return!e||!e.access_token?!1:!N(e.access_token)||e.refresh_token!==void 0&&!N(e.refresh_token)}catch(e){let t={operation:`auth.is-authenticated`,message:e instanceof Error?e.message:`Failed to check authentication status`,originalError:e};return W(this.subscribeStore,t),!1}}async submitSessionCheck(e=!1){let t,n;try{t=await this.getTokens(e),n=this.tokenCacheService.getParsedTokens()}catch(e){let n={operation:`session.check`,message:e instanceof Error||e instanceof B?e.message:`Session check failed`,originalError:e};W(this.subscribeStore,n),t=void 0}return t&&this.sessionCallbacks.createSession&&await this.sessionCallbacks.createSession({tokens:t,parsedTokens:n}),!t&&this.sessionCallbacks.expiredSession&&await this.sessionCallbacks.expiredSession(),t}async refreshForSession(){try{await this.refresh.refresh({trigger:`session`})}catch{}return this.tokenCacheService.getTokens()}async getTokens(e){try{if(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode()){let t=this.storageManager.getTokens();return t?.id_token?this.tokenDeliveryManager.isSessionInvalid()&&e?await this.refreshForSession():t:void 0}let t=this.storageManager.getTokens();if(!t||!t.access_token)return;if(N(P(t.access_token))){if(e){let e=await this.refreshForSession();return e?.refresh_token||this.storageManager.getTokens()?.refresh_token||!this.tokenCacheService.isExpired()?e:void 0}return}return t}catch(e){let t={operation:`tokens.get`,message:e instanceof Error?e.message:`Failed to get tokens`,originalError:e};W(this.subscribeStore,t);return}}},lo=class{constructor(e){this.invitationApi=e}requestInviteLink(e){return this.invitationApi.requestInviteLink(e)}getInvitations(e){return this.invitationApi.getInvitations(e)}deleteInvitation(e){return this.invitationApi.deleteInvitation(e)}resendInvitation(e){return this.invitationApi.resendInvitation(e)}getInvitationLink(e){return this.invitationApi.getInvitationLink(e)}},uo=class{constructor(e){this.data=this.normalize(e)}normalize(e){let t=new Map,n=new Map,r=new Map,i=[];return e.groups?.forEach(e=>{n.set(e.id,{id:e.id,name:e.name,default:e.default??!1,updated_at:e.updated_at,created_at:e.created_at})}),e.roles?.forEach(e=>{r.set(e.id,{id:e.id,tenant_id:e.tenant_id,name:e.name})}),e.users_in_groups?.forEach(e=>{let r=e.user;r&&!t.has(r.id)&&t.set(r.id,{id:r.id,name:r.name??null,email:r.email??null,phone:r.phone??null}),r&&e.group_id&&n.has(e.group_id)&&i.push({userId:r.id,groupId:e.group_id,roleIds:e.roles?.map(e=>e.id)??[]})}),{tenant_id:e.tenant_id,tenant_name:e.tenant_name,users:Array.from(t.values()),groups:Array.from(n.values()),roles:Array.from(r.values()),memberships:i,usersById:t,groupsById:n,rolesById:r}}getUsersInGroup(e){return this.data.memberships.filter(t=>t.groupId===e).map(e=>this.data.usersById.get(e.userId)).filter(e=>e!==void 0)}getGroupsForUser(e){return this.data.memberships.filter(t=>t.userId===e).map(e=>this.data.groupsById.get(e.groupId)).filter(e=>e!==void 0)}getUserRolesInGroup(e,t){let n=this.data.memberships.find(n=>n.userId===e&&n.groupId===t);return n?n.roleIds.map(e=>this.data.rolesById.get(e)).filter(e=>e!==void 0):[]}getData(){return this.data}},fo=class{constructor(e,t,n){this.tenantApi=e,this.scopes=t,this.logger=n||Bi()}handlePassflowError(e,t){if(c.default.isAxiosError(e)&&e.response?.data){let n=e.response.data;if(typeof n==`object`&&n&&`error`in n&&typeof n.error==`object`&&n.error!==null){let e=n.error;throw this.logger.error(`${t}: ${e.id} - ${e.message} (Status: ${e.status})`),Error(`Passflow API Error: ${e.id} - ${e.message} (Status: ${e.status})`)}}throw this.logger.error(`${t}:`,e),e instanceof Error?e:Error(String(e))}async joinInvitation(e,t){try{let n=t??this.scopes;return await this.tenantApi.joinInvitation(e,n)}catch(e){this.handlePassflowError(e,`Join invitation failed`)}}async createTenant(e){try{return await this.tenantApi.createTenant(e)}catch(e){this.handlePassflowError(e,`Tenant creation failed`)}}async getTenantDetails(e){try{return await this.tenantApi.getTenantDetails(e)}catch(t){this.handlePassflowError(t,`Get tenant details failed for tenant ID ${e}`)}}async getTenantUserMembership(e){try{return new uo(await this.tenantApi.getTenantDetails(e))}catch(t){this.handlePassflowError(t,`Get tenant user membership failed for tenant ID ${e}`)}}async updateTenant(e,t){try{return await this.tenantApi.updateTenant(e,t)}catch(t){this.handlePassflowError(t,`Update tenant failed for tenant ID ${e}`)}}async deleteTenant(e){try{return await this.tenantApi.deleteTenant(e)}catch(t){this.handlePassflowError(t,`Delete tenant failed for tenant ID ${e}`)}}async getUserTenantMembership(){try{return await this.tenantApi.getUserTenantMembership()}catch(e){this.handlePassflowError(e,`Get user tenant memberships failed`)}}async createGroup(e,t){try{return await this.tenantApi.createGroup(e,t)}catch(t){this.handlePassflowError(t,`Group creation failed for tenant ID ${e}`)}}async getGroupInfo(e,t){try{return await this.tenantApi.getGroupInfo(e,t)}catch(n){this.handlePassflowError(n,`Get group info failed for tenant ID ${e}, group ID ${t}`)}}async updateGroup(e,t,n){try{return await this.tenantApi.updateGroup(e,t,n)}catch(n){this.handlePassflowError(n,`Update group failed for tenant ID ${e}, group ID ${t}`)}}async deleteGroup(e,t){try{return await this.tenantApi.deleteGroup(e,t)}catch(n){this.handlePassflowError(n,`Delete group failed for tenant ID ${e}, group ID ${t}`)}}async addUserToGroup(e,t,n,r){try{return await this.tenantApi.addUserToGroup(e,t,n,r)}catch(r){this.handlePassflowError(r,`Add user to group failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async removeUserRolesFromGroup(e,t,n,r){try{return await this.tenantApi.removeUserRolesFromGroup(e,t,n,r)}catch(r){this.handlePassflowError(r,`Remove user roles from group failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async changeUserRoles(e,t,n,r){try{return await this.tenantApi.changeUserRoles(e,t,n,r)}catch(r){this.handlePassflowError(r,`Change user roles failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async deleteUserFromGroup(e,t,n){try{return await this.tenantApi.deleteUserFromGroup(e,t,n)}catch(r){this.handlePassflowError(r,`Delete user from group failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async getRolesForTenant(e){try{return await this.tenantApi.getRolesForTenant(e)}catch(t){this.handlePassflowError(t,`Get roles for tenant failed for tenant ID ${e}`)}}async createRoleForTenant(e,t){try{return await this.tenantApi.createRoleForTenant(e,t)}catch(t){this.handlePassflowError(t,`Create role for tenant failed for tenant ID ${e}`)}}async updateRole(e,t,n){try{return await this.tenantApi.updateRole(e,t,n)}catch(n){this.handlePassflowError(n,`Update role failed for tenant ID ${e}, role ID ${t}`)}}async deleteRole(e,t){try{return await this.tenantApi.deleteRole(e,t)}catch(n){this.handlePassflowError(n,`Delete role failed for tenant ID ${e}, role ID ${t}`)}}async deleteUserFromTenant(e,t){try{return await this.tenantApi.deleteUserFromTenant(e,t)}catch(n){this.handlePassflowError(n,`Delete user from tenant failed for tenant ID ${e}, user ID ${t}`)}}async getGroupInvitations(e,t,n,r){try{return await this.tenantApi.getGroupInvitations(e,t,n,r)}catch(n){this.handlePassflowError(n,`Get group invitations failed for tenant ID ${e}, group ID ${t}`)}}async getTenantInvitations(e,t,n){try{return await this.tenantApi.getTenantInvitations(e,t,n)}catch(t){this.handlePassflowError(t,`Get tenant invitations failed for tenant ID ${e}`)}}async invalidateInviteById(e,t,n){try{return await this.tenantApi.invalidateInviteById(e,t,n)}catch(r){this.handlePassflowError(r,`Invalidate invite by ID failed for tenant ID ${e}, group ID ${t}, invite ID ${n}`)}}async invalidateInviteByEmail(e,t,n){try{return await this.tenantApi.invalidateInviteByEmail(e,t,n)}catch(r){this.handlePassflowError(r,`Invalidate invite by email failed for tenant ID ${e}, group ID ${t}, email ${n}`)}}},po=class{constructor(e,t,n,r=ye){this.storageManager=e,this.subscribeStore=n,this.platform=r,this.checkInterval=null,this.CHECK_INTERVAL=6e4,this.unsubscribeForeground=null,this.unsubscribeUnload=null,this.tokenExpiredFlag=!1,this.storageManager=e,this.setupLifecycleListeners()}get isRefreshing(){return this.refreshController?.busy??!1}attachRefreshController(e){this.refreshController=e}initialize(){try{let e=this.tokensCache,t=e??this.storageManager.getTokens();if(!t)return;if(!t.access_token){e||this.setTokensCache(t),this.startTokenCheck();return}N(P(t.access_token))?(this.stopTokenCheck(),this.tokenExpiredFlag||(this.tokenExpiredFlag=!0,this.subscribeStore.notify(G.TokenCacheExpired,{isExpired:!0}))):(e||this.setTokensCache(t),this.startTokenCheck())}catch(e){let t={operation:`tokens.load`,message:e instanceof Error?e.message:`Failed to get tokens`,originalError:e};W(this.subscribeStore,t),this.setTokensCache(void 0)}}startTokenCheck(){this.checkInterval&&clearInterval(this.checkInterval),this.tokenExpiredFlag||(this.setupLifecycleListeners(),this.checkInterval=setInterval(()=>{this.platform.isInForeground()&&(this.isRefreshing||this.tokenExpiredFlag||this.isExpired()&&!this.tokenExpiredFlag&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(G.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck()))},this.CHECK_INTERVAL))}setupLifecycleListeners(){this.unsubscribeForeground&&(this.unsubscribeForeground(),this.unsubscribeForeground=null),this.unsubscribeForeground=this.platform.onForeground(()=>{this.checkInterval&&!this.isRefreshing&&!this.tokenExpiredFlag&&this.isExpired()&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(G.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck())}),this.unsubscribeUnload||(this.unsubscribeUnload=this.platform.onBeforeUnload(()=>{this.destroy()}))}stopTokenCheck(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null),this.unsubscribeForeground&&(this.unsubscribeForeground(),this.unsubscribeForeground=null)}destroy(){this.stopTokenCheck(),this.unsubscribeUnload&&(this.unsubscribeUnload(),this.unsubscribeUnload=null)}setTokensCache(e){this.tokensCache=e,this.parsedTokensCache=e?{access_token:e.access_token?P(e.access_token):void 0,id_token:e.id_token?P(e.id_token):void 0,refresh_token:e.refresh_token?P(e.refresh_token):void 0,scopes:e.scopes}:void 0}getTokens(){return this.tokensCache}async getTokensWithRefresh(){try{if(!this.tokensCache||!this.tokensCache.access_token)return this.tokensCache;if(N(P(this.tokensCache.access_token))&&this.refreshController)try{await this.refreshController.refresh({trigger:`token-check`})}catch{}return this.tokensCache}catch(e){let t={operation:`tokens.get`,message:e instanceof Error?e.message:`Failed to get tokens`,originalError:e};W(this.subscribeStore,t);return}}getParsedTokens(){return this.parsedTokensCache}isExpired(){return this.tokensCache?this.tokensCache.access_token?N(P(this.tokensCache.access_token)):!1:!0}},mo=class{constructor(e,t,n){this.twoFactorApi=e,this.subscribeStore=t,this.signInCompleter=n,this.PARTIAL_AUTH_TIMEOUT_MS=3e5,this.SESSION_STORAGE_KEY=`passflow_2fa_challenge`,this.subscribeStore.subscribe({onAuthChange:(e,t)=>{if(e===G.TwoFactorRequired){let e=t;this.setPartialAuthState(e.email,e.challengeId,e.tfaToken)}(e===G.SignIn||e===G.Register)&&(this.clearPartialAuthState(),this.clearMagicLinkSession())}},[G.TwoFactorRequired,G.SignIn,G.Register])}emitErrorAndThrow(e,t,n){let r=e,i={operation:t,message:e instanceof Error?e.message:`${n} failed`,originalError:e,code:r?.id||void 0};throw W(this.subscribeStore,i),e}async getStatus(){try{let e=await this.twoFactorApi.getStatus(this.getMagicLinkSessionToken()??void 0);return this.storeTotpDigits(e.totp_digits),e}catch(e){this.emitErrorAndThrow(e,`2fa.status`,`Get 2FA status`)}}async beginSetup(){try{return this.setupStarted(await this.twoFactorApi.beginSetup(this.getMagicLinkSessionToken()??void 0))}catch(e){this.emitErrorAndThrow(e,`2fa.setup.begin`,`Begin 2FA setup`)}}async confirmSetup(e){this.assertTotpCode(e);try{let t=await this.twoFactorApi.confirmSetup({code:e},this.getMagicLinkSessionToken()??void 0);return this.clearMagicLinkSession(),this.setupConfirmed(t)}catch(e){this.emitErrorAndThrow(e,`2fa.setup.confirm`,`Confirm 2FA setup`)}}async getEnrollment(){try{let e=await this.twoFactorApi.getEnrollment(this.requirePendingTfaToken());return this.storeTotpDigits(e.totp_digits),e}catch(e){this.emitErrorAndThrow(e,`2fa.enrollment.read`,`Read 2FA enrollment`)}}async sendSetupLink(){try{return await this.twoFactorApi.sendSetupLink(this.requirePendingTfaToken())}catch(e){this.emitErrorAndThrow(e,`2fa.enrollment.setup-link`,`Send 2FA setup link`)}}async beginEnrollment(){try{return this.setupStarted(await this.twoFactorApi.beginEnrollment(this.requirePendingTfaToken()))}catch(e){this.emitErrorAndThrow(e,`2fa.setup.begin`,`Begin 2FA enrollment`)}}async confirmEnrollment(e){this.assertTotpCode(e);try{return this.setupConfirmed(await this.twoFactorApi.confirmEnrollment(this.requirePendingTfaToken(),{code:e}))}catch(e){this.emitErrorAndThrow(e,`2fa.setup.confirm`,`Confirm 2FA enrollment`)}}assertTotpCode(e){let t=this.totpDigits;if(t){if(!Ua(e,t))throw Error(`Invalid TOTP code format. Code must be exactly ${t} digits.`)}else if(!Ua(e,6)&&!Ua(e,8))throw Error(`Invalid TOTP code format. Code must be 6 or 8 digits.`)}requirePendingTfaToken(){let e=this.pendingTfaToken();if(!e)throw Error(`2FA verification expired or not required. User must sign in first.`);return e}storeTotpDigits(e){e&&(this.totpDigits=e)}setupStarted(e){return this.storeTotpDigits(e.totp_digits),this.subscribeStore.notify(G.TwoFactorSetupStarted,{secret:e.secret}),e}setupConfirmed(e){let t=e.recovery_codes??[];return this.subscribeStore.notify(G.TwoFactorEnabled,{recoveryCodes:t,clearRecoveryCodes:()=>{t.length=0}}),e}async verify(e,t){if(this.assertTotpCode(e),this.recoverPartialAuthState(),!this.isVerificationRequired())throw Error(`2FA verification expired or not required. User must sign in first.`);if(!this.partialAuthState?.tfaToken)throw Error(`No TFA token found. User must sign in first.`);try{let n=await this.twoFactorApi.verify({code:e,tfa_token:this.partialAuthState.tfaToken,...t?.trustDevice?{trust_device:!0}:{}}),r=await this.finishSignIn(n);return this.subscribeStore.notify(G.TwoFactorVerified,{tokens:r}),r}catch(e){this.emitErrorAndThrow(e,`2fa.verify`,`Verify 2FA code`)}}async useRecoveryCode(e,t){try{let n=Wa(e);if(!n)throw Error(`Invalid recovery code format. Expected letters, digits and dashes, such as XXXX-XXXX-XXXX.`);if(this.recoverPartialAuthState(),!this.isVerificationRequired())throw Error(`2FA verification expired or not required. User must sign in first.`);if(!this.partialAuthState?.tfaToken)throw Error(`No TFA token found. User must sign in first.`);let r=await this.finishSignIn(await this.twoFactorApi.useRecoveryCode({recovery_code:n,tfa_token:this.partialAuthState.tfaToken,...t?.trustDevice?{trust_device:!0}:{}})),i=r.remaining_recovery_codes;return i===0?this.subscribeStore.notify(G.TwoFactorRecoveryCodesExhausted,{tokens:r}):typeof i==`number`&&i<=2&&this.subscribeStore.notify(G.TwoFactorRecoveryCodesLow,{tokens:r,remainingCodes:i}),this.subscribeStore.notify(G.TwoFactorRecoveryUsed,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(G.TwoFactorVerified,{tokens:r}),r}catch(e){this.emitErrorAndThrow(e,`2fa.recovery.use`,`Use recovery code`)}}async disable(e){this.assertTotpCode(e);try{let t=await this.twoFactorApi.disable({code:e});return this.subscribeStore.notify(G.TwoFactorDisabled,{}),t}catch(e){this.emitErrorAndThrow(e,`2fa.disable`,`Disable 2FA`)}}async regenerateRecoveryCodes(e){this.assertTotpCode(e);try{let t=await this.twoFactorApi.regenerateRecoveryCodes({code:e}),n=[...t.recovery_codes];return t.recovery_codes=[],t.recovery_codes=n,t}catch(e){this.emitErrorAndThrow(e,`2fa.recovery.regenerate`,`Regenerate recovery codes`)}}isVerificationRequired(){return this.recoverPartialAuthState(),this.partialAuthState?Date.now()>this.partialAuthState.expiresAt?(this.clearPartialAuthState(),!1):!0:!1}setPartialAuthState(e,t,n){if(this.totpDigits=void 0,this.partialAuthState={email:e,challengeId:t,tfaToken:n,timestamp:Date.now(),expiresAt:Date.now()+this.PARTIAL_AUTH_TIMEOUT_MS},typeof sessionStorage<`u`)try{sessionStorage.setItem(this.SESSION_STORAGE_KEY,JSON.stringify(this.partialAuthState))}catch{}}clearPartialAuthState(){if(this.partialAuthState=void 0,this.totpDigits=void 0,this.signInCompleter?.forgetPkceSignIn(),typeof sessionStorage<`u`)try{sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{}}async finishSignIn(e){let{code:t,...n}=e;if(t&&!this.signInCompleter?.hasPendingPkceSignIn()){this.clearPartialAuthState();let e=Error(`The sign-in answered with a PKCE code, but its verifier is gone`);throw e.id=`PKCE_VERIFIER_MISSING`,e}let r=e;if(t&&this.signInCompleter){let e=await this.signInCompleter.completePkceSignIn(t);r={...n,...e}}else await this.signInCompleter?.applyTokens(r);return await this.signInCompleter?.secondFactorCompleted?.(),this.clearPartialAuthState(),r}pendingTfaToken(){return this.isVerificationRequired()&&this.partialAuthState?.tfaToken||void 0}recoverPartialAuthState(){if(!this.partialAuthState&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(this.SESSION_STORAGE_KEY);if(!e)return;let t=JSON.parse(e);Date.now()<t.expiresAt?this.partialAuthState=t:sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{try{sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{}}}async validateTwoFactorSetupMagicLink(e){let t=await this.twoFactorApi.validateTwoFactorSetupMagicLink(e);return t.success&&t.sessionToken&&t.userId?(this.magicLinkSession={sessionToken:t.sessionToken,userId:t.userId,appId:t.appId,scope:`2fa_setup`,reset:t.reset===!0,timestamp:Date.now(),expiresAt:Date.now()+(t.expiresIn||3600)*1e3},this.subscribeStore.notify(G.TwoFactorSetupMagicLinkValidated,{userId:t.userId,appId:t.appId,expiresIn:t.expiresIn||3600,sessionToken:t.sessionToken,reset:t.reset===!0})):t.error&&this.subscribeStore.notify(G.TwoFactorSetupMagicLinkFailed,{error:t.error}),t}getMagicLinkSession(){return this.magicLinkSession?Date.now()>this.magicLinkSession.expiresAt?(this.clearMagicLinkSession(),null):this.magicLinkSession:null}clearMagicLinkSession(){this.magicLinkSession=void 0}hasMagicLinkSession(){return this.getMagicLinkSession()!==null}getMagicLinkSessionToken(){return this.getMagicLinkSession()?.sessionToken||null}getTotpDigits(){return this.totpDigits??6}async getAvailableMethods(){try{return await this.twoFactorApi.getAvailableMethods()}catch(e){this.emitErrorAndThrow(e,`2fa.methods.available`,`Get available 2FA methods`)}}async getRegisteredMethods(e){try{return await this.twoFactorApi.getRegisteredMethods(e)}catch(e){this.emitErrorAndThrow(e,`2fa.methods.registered`,`Get registered 2FA methods`)}}async startRecoveryCodesByCode(e){try{return await this.twoFactorApi.startRecoveryCodesByCode(e)}catch(e){this.emitErrorAndThrow(e,`2fa.recovery-codes.start`,`Start recovery codes by code`)}}async completeRecoveryCodesByCode(e,t){try{return await this.twoFactorApi.completeRecoveryCodesByCode(e,t)}catch(e){this.emitErrorAndThrow(e,`2fa.recovery-codes.complete`,`Complete recovery codes by code`)}}async startMethodSetup(e,t){try{let n=await this.twoFactorApi.startMethodSetup(e,t);return this.subscribeStore.notify(G.TwoFactorSetupStarted,{secret:``,method:e}),n}catch(e){this.emitErrorAndThrow(e,`2fa.method.setup.start`,`Start 2FA method setup`)}}async completeMethodSetup(e,t){try{let n=await this.twoFactorApi.completeMethodSetup(e,t);return this.subscribeStore.notify(G.TwoFactorEnabled,{recoveryCodes:[],clearRecoveryCodes:()=>{}}),n}catch(e){this.emitErrorAndThrow(e,`2fa.method.setup.complete`,`Complete 2FA method setup`)}}async removeMethod(e){try{await this.twoFactorApi.removeMethod(e)}catch(e){this.emitErrorAndThrow(e,`2fa.method.remove`,`Remove 2FA method`)}}async requestChallenge(e){try{let t=await this.twoFactorApi.requestChallenge(e,this.pendingTfaToken());return this.storeTotpDigits(t.totp_digits),this.subscribeStore.notify(G.TwoFactorChallengeReceived,{challengeId:t.challenge_id,method:t.method,alternativeMethods:t.alternative_methods??[]}),t}catch(e){this.emitErrorAndThrow(e,`2fa.challenge.request`,`Request 2FA challenge`)}}async verifyV2(e){try{let t=await this.twoFactorApi.verifyV2(e,this.pendingTfaToken()),n=await this.finishSignIn(t);return this.subscribeStore.notify(G.TwoFactorVerified,{tokens:{access_token:n.access_token,refresh_token:n.refresh_token}}),await this.signInCompleter?.notifySignedIn(n),n}catch(e){this.emitErrorAndThrow(e,`2fa.challenge.verify`,`Verify 2FA challenge`)}}async switchToAlternative(e){try{let t=await this.twoFactorApi.switchToAlternative(e,this.pendingTfaToken());return this.storeTotpDigits(t.totp_digits),this.subscribeStore.notify(G.TwoFactorMethodSwitched,{challengeId:t.challenge_id,method:t.method,alternativeMethods:t.alternative_methods??[]}),t}catch(e){this.emitErrorAndThrow(e,`2fa.method.switch`,`Switch to alternative 2FA method`)}}async pushStatus(e){try{return await this.twoFactorApi.pushStatus(e,this.pendingTfaToken())}catch(e){this.emitErrorAndThrow(e,`2fa.push.status`,`Read 2FA push status`)}}async getTrustedDevices(){try{return await this.twoFactorApi.getTrustedDevices()}catch(e){this.emitErrorAndThrow(e,`2fa.trusted-devices.list`,`Get trusted devices`)}}async revokeTrustedDevice(e){try{await this.twoFactorApi.revokeTrustedDevice(e)}catch(e){this.emitErrorAndThrow(e,`2fa.trusted-devices.revoke`,`Revoke trusted device`)}}async getPreferredMethod(){try{return await this.twoFactorApi.getPreferredMethod()}catch(e){this.emitErrorAndThrow(e,`2fa.preferred-method.read`,`Get preferred 2FA method`)}}async setPreferredMethod(e){try{return await this.twoFactorApi.setPreferredMethod(e)}catch(e){this.emitErrorAndThrow(e,`2fa.preferred-method.set`,`Set preferred 2FA method`)}}async clearPreferredMethod(){try{await this.twoFactorApi.clearPreferredMethod()}catch(e){this.emitErrorAndThrow(e,`2fa.preferred-method.clear`,`Clear preferred 2FA method`)}}},ho=class{constructor(e,t,n=ye){this.userAPI=e,this.deviceService=t,this.platform=n}getUserPasskeys(){return this.userAPI.getUserPasskeys()}renameUserPasskey(e,t){return this.userAPI.renameUserPasskey(e,t)}deleteUserPasskey(e){return this.userAPI.deleteUserPasskey(e)}async addUserPasskey({relyingPartyId:e,passkeyUsername:t,passkeyDisplayName:n}={}){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);let r=this.deviceService.getDeviceId(),i=Ct(this.platform.getDeviceType()),{challenge_id:a,publicKey:o}=await this.userAPI.addUserPasskeyStart({relyingPartyId:(e||this.platform.getCurrentUrl()?.hostname)??``,deviceId:r,os:i,passkeyDisplayName:n,passkeyUsername:t});o.user.id=this.platform.btoa(o.user.id);let s=await this.platform.passkeys.startRegistration(o);if(!s)throw Error(`Passkey registration was not completed`);return await this.userAPI.addUserPasskeyComplete(s,r,a)}async listSessions(){return(await this.userAPI.getUserSessions()).sessions}revokeSession(e){return this.userAPI.revokeUserSession(e)}signOutOtherSessions(){return this.userAPI.revokeOtherUserSessions()}requestAddressChangeProof(e){return this.userAPI.requestAddressChangeProof(e)}updateProfile(e,t){return this.userAPI.updateProfile(e,t)}},go=class extends Error{constructor(e,t,n=!1){super(t),this.name=`UpgradeFactorError`,this.factor=e,this.cancelled=n}},_o=(e,t)=>{let n=t?.trim();if(!n)throw new go(e,`A verification code is required`);return n},vo={type:`totp`,requiresPrepare:!1,input:`code`,assert:async({code:e})=>({code:_o(`totp`,e)})},yo={type:`recovery_codes`,requiresPrepare:!1,input:`code`,assert:async({code:e})=>({code:_o(`recovery_codes`,e)})},bo={type:`passkey`,requiresPrepare:!0,input:`none`,assert:async({prepared:e,platform:t})=>{if(!e?.webauthn)throw new go(`passkey`,`The upgrade challenge carried no WebAuthn options`);let n=t.passkeys;if(!n)throw new go(`passkey`,`This platform does not support passkeys`);let r;try{r=await n.startAuthentication(e.webauthn)}catch(e){throw new go(`passkey`,e?.message||`Passkey verification was cancelled`,!0)}if(!r)throw new go(`passkey`,`Passkey verification was cancelled`,!0);return{challenge_id:e.challengeId,credential:r}}},xo=Object.freeze([vo,bo,yo]),So=(e=xo)=>new Map(e.map(e=>[e.type,e])),Co=3,wo={totp:0,passkey:1,email_otp:2,sms_otp:3,recovery_codes:9},To=e=>e.requiredLevel??we(e.acrValues),Eo=(e,t)=>{let n=wo[e.type]??5,r=t!==void 0&&t>=Co,i=e.type===`passkey`;return(r&&!i?100:0)+n},Do=(e,t)=>{if(t.availableFactors)return t.availableFactors.flatMap(t=>e.find(e=>e.type===t)??[]);let n=To(t);return[...e].sort((e,t)=>Eo(e,n)-Eo(t,n))},Oo=class extends Error{constructor(e){super(`Upgrade authentication was cancelled`),this.code=`upgrade_cancelled`,this.name=`UpgradeCancelledError`,e!==void 0&&(this.cause=e)}},ko=class extends Error{constructor(e=`Only a fresh sign-in can meet this challenge`){super(e),this.code=`upgrade_sign_in_required`,this.name=`UpgradeSignInRequiredError`}},Ao=e=>e?.signInRequired===!0||e?.signInRequired===void 0&&e?.availableFactors?.length===0,jo=e=>e?.signInRequired===!1&&e.availableFactors?.length===0,Mo=`This account has no factor that reaches the required level (it may need a device-bound passkey)`,No=e=>{if(Ao(e))return new ko;if(jo(e))return new Po(Mo)},Po=class extends Error{constructor(e=`No available authentication factor can satisfy this challenge`){super(e),this.code=`upgrade_unsatisfiable`,this.name=`UpgradeUnsatisfiableError`}},Fo=4,Io=3e4,Lo=()=>{let e=()=>void 0,t=()=>void 0;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},Ro=e=>({acrValues:e.acrValues,level:e.requiredLevel,maxAge:e.maxAge}),zo=(e,t)=>t.level===void 0||e.level!==void 0&&e.level>=t.level,Bo=(e,t)=>{let n=e.requiredLevel===void 0?t.requiredLevel:t.requiredLevel===void 0?e.requiredLevel:Math.max(e.requiredLevel,t.requiredLevel),r=n===void 0?e.acrValues??t.acrValues:n===e.requiredLevel?e.acrValues:t.acrValues,i=e.maxAge===void 0?t.maxAge:t.maxAge===void 0?e.maxAge:Math.min(e.maxAge,t.maxAge),a=Array.from(new Set([...e.channels??[],...t.channels??[]])),{availableFactors:o,signInRequired:s}=Vo(t,e)&&!Vo(e,t)||!t.availableFactors?e:t;return{acrValues:r,requiredLevel:n,maxAge:i,status:e.status,...a.length>0?{channels:a}:{},...o?{availableFactors:o}:{},...s===void 0?{}:{signInRequired:s}}},Vo=(e,t)=>{let n=t.requiredLevel!==void 0&&(e.requiredLevel===void 0||t.requiredLevel>e.requiredLevel),r=t.maxAge!==void 0&&(e.maxAge===void 0||t.maxAge<e.maxAge);return n||r},Ho=class{constructor(e){this.state=`idle`,this.inFlight=null,this.requirement=null,this.selected=null,this.rankedRequirement=null,this.registrations=[],this.proof=null,this.pruned=new Set,this.openPrompt=null,this.transport=e.transport,this.prompt=e.prompt,this.platform=e.platform,this.available=e.factors??xo,this.registry=So(this.available),this.maxAttempts=e.maxAttempts??Fo,this.readObtainedBar=e.readObtainedBar,this.onFlightSettled=e.onFlightSettled,this.settleTimeoutMs=e.replaySettleTimeoutMs??Io}get currentState(){return this.state}get active(){return this.inFlight!==null}elevate(e,t={kind:`imperative`}){let n=this.register(e,t);if(this.state===`idle`)this.state=`collecting`,this.requirement=e,this.inFlight=this.runFlight();else{this.join(e);let t=this.proof;t?.status===`proven`?this.release(n,t.obtained):t?.status===`failed`&&(this.receiveReport(n,{outcome:`failed`}),n.settlement.reject(t.reason))}return n.settlement.promise}register(e,t){let n=t.kind===`imperative`&&t.requested!==void 0,r={demanded:t.kind===`imperative`&&t.requested?t.requested:Ro(e),statedBar:n,settlement:Lo(),reported:!1,entry:{...t,outcome:`pending`,report:e=>this.receiveReport(r,e)}};return this.registrations.push(r),r}join(e){let t=this.requirement;if(!t){this.requirement=e;return}let n=Vo(t,e);this.requirement=Bo(t,e),No(this.requirement)?this.state===`collecting`&&this.selected===null&&(this.openPrompt?.onClosed?.(),this.closeOpenPrompt?.()):n&&this.state===`collecting`&&this.selected===null&&this.openPrompt?.onRequirementRaised?.({challenge:this.requirement,factors:this.offeredFactors()})}offeredFactors(){let e=this.available.filter(e=>!this.pruned.has(e.type)),t=this.requirement;return t?Do(e,t):e}receiveReport(e,t){e.reported||(e.reported=!0,e.entry.outcome=t.outcome,t.obtained&&(e.entry.obtained=t.obtained),t.required&&(e.entry.required=t.required),this.notifyReportsSettled())}notifyReportsSettled(){if(!this.reportsSettled||this.registrations.some(e=>!e.reported))return;let e=this.reportsSettled;this.reportsSettled=void 0,e()}async runFlight(){let e;try{e=await this.prove()}catch(t){e={status:`failed`,reason:t instanceof Error?t:Error(String(t))}}if(this.proof=e,e.status===`failed`)for(let t of this.registrations)this.receiveReport(t,{outcome:`failed`}),t.settlement.reject(e.reason);else{this.state=`replaying`;for(let t of this.registrations)this.release(t,e.obtained);await this.awaitReports()}this.state=`settling`;let t=this.summarise(e);try{this.onFlightSettled?.(t)}catch{}this.state=`done`,this.inFlight=null,this.requirement=null,this.selected=null,this.rankedRequirement=null,this.registrations=[],this.proof=null,this.pruned=new Set,this.openPrompt=null,this.reportsSettled=void 0,this.state=`idle`}release(e,t){if(e.entry.kind===`imperative`){if(e.statedBar&&!zo(t,e.demanded)){this.receiveReport(e,{outcome:`insufficient`,obtained:t,required:e.demanded}),e.settlement.reject(new Na(t,e.demanded));return}this.receiveReport(e,{outcome:`replayed`,obtained:t}),e.settlement.resolve({waiter:e.entry,obtained:t})}else e.settlement.resolve({waiter:e.entry,obtained:t})}awaitReports(){return this.registrations.some(e=>!e.reported)?new Promise(e=>{let t=setTimeout(()=>{this.reportsSettled=void 0;for(let e of this.registrations)e.reported||(e.reported=!0,e.entry.outcome=`failed`);e()},this.settleTimeoutMs);this.reportsSettled=()=>{clearTimeout(t),e()}}):Promise.resolve()}summarise(e){let t=this.registrations.map(e=>({...e.entry.kind===`request`?{url:e.entry.url,method:e.entry.method}:{},outcome:e.entry.outcome,...e.entry.obtained?{obtained:e.entry.obtained}:{},...e.entry.required?{required:e.entry.required}:{}}));if(e.status===`failed`)return{proof:e,waiters:t,terminal:`failed`,error:e.reason};let n;for(let e of t){if(e.outcome!==`insufficient`)continue;let t=e.required?.level??0;(!n||t>(n.required?.level??0))&&(n=e)}return n?{proof:e,waiters:t,terminal:`insufficient`,insufficient:{obtained:n.obtained??e.obtained,required:n.required??{}}}:t.some(e=>e.outcome===`failed`||e.outcome===`pending`)?{proof:e,waiters:t,terminal:`failed`}:{proof:e,waiters:t,terminal:`success`}}async prove(){let e;for(let t=0;t<this.maxAttempts;t++){let t=No(this.requirement);if(t)return{status:`failed`,reason:t};let n=this.offeredFactors();if(n.length===0)return{status:`failed`,reason:new Po};let r=this.requirement,i;try{i=await this.collect(r,n,e)}catch(e){return{status:`failed`,reason:new Oo(e)}}let a=No(this.requirement);if(a)return{status:`failed`,reason:a};if(i.type===`cancel`)return{status:`failed`,reason:new Oo};let o=this.registry.get(i.factor);if(!o)e=new Po(`Unknown authentication factor: ${i.factor}`),this.state=`collecting`,this.selected=null;else try{return await this.proveAndCommit(o,i.code),{status:`proven`,obtained:this.readObtainedBar?.()??Ro(this.rankedRequirement??r)}}catch(t){if(t instanceof go&&t.cancelled)return{status:`failed`,reason:new Oo};let n=this.classifyProofFailure(t);if(n)return{status:`failed`,reason:n};t instanceof $&&t.kind===`not_registered`&&this.pruned.add(o.type),e=t,this.state=`collecting`,this.selected=null}}return{status:`failed`,reason:new $({kind:`attempts_exhausted`,...e?{cause:e}:{}})}}collect(e,t,n){let r={challenge:e,factors:t,...n?{previousError:n}:{},onFactorSelected:e=>{this.state===`collecting`&&(this.state=`proving`),this.selected=e,this.rankedRequirement=this.requirement}};this.openPrompt=r;let i=new Promise(e=>{this.closeOpenPrompt=()=>e({type:`cancel`})});return Promise.race([this.prompt(r),i]).finally(()=>{this.closeOpenPrompt=void 0})}classifyProofFailure(e){if(e instanceof Na||e instanceof Pa||e instanceof Fa)return e;if(e instanceof $)switch(e.kind){case`unavailable`:return new Pa(e.message);case`exhausted`:case`attempts_exhausted`:case`rate_limited`:case`fatal`:case`protocol`:case`network`:return e;case`session_changed`:return new Fa(e.message);default:return}}async proveAndCommit(e,t){let n=e.requiresPrepare?await this.transport.prepare(e.type):void 0,r=await e.assert({code:t,prepared:n,platform:this.platform});await this.transport.commit(e.type,r)}},Uo=e=>typeof e==`function`?e():e,Wo=e=>{try{return new URL(e)}catch{return}},Go=(e,t)=>{if(!t||t===`/`)return!0;let n=t.replace(/\/+$/,``);return e===n||e.startsWith(`${n}/`)},Ko=(e,t)=>!t||e.origin===void 0?!1:e.origin===t.origin&&Go(e.pathname,t.pathPrefix),qo=(e,t)=>{for(let n of t){if(n===``)continue;if(n.startsWith(`/`)){if(e.relativeToBase&&Go(e.pathname,n))return!0;continue}let t=Wo(n)??Wo(`https://${n}`);if(t&&e.origin!==void 0&&e.origin===t.origin&&Go(e.pathname,t.pathname))return!0}return!1},Jo=(e,t,n)=>Ko(e,t.passflow)||qo(e,t.backend)?!n||n(e.href)!==!1:!1,Yo=e=>{let t=e.detail,n=t?.message??`[passflow] upgrade challenge not actioned: ${e.reason}`;console.warn(n,{status:e.status,url:e.url,reason:e.reason,detail:t})},Xo=(e,t)=>{let n=t.onUpgradeDiagnostic??Yo;return(t,r)=>{n({status:e.status,url:e.request.href,reason:t,detail:{method:e.request.method,...r??{}}})}},Zo=(e,t,n)=>{let r=n.onUpgradeDiagnostic??Yo;for(let n of e)r({...n,url:t.request.href,detail:{method:t.request.method,...n.detail??{}}})},Qo=/\bjson\b/i,$o=async(e,t)=>{let n=t.requireChallengeChannel===`header`,r=e.getHeader(`content-type`)??``,i=!n&&Qo.test(r),a;if(i)try{a=await e.readBody()}catch{a=void 0}return Ie(i?{status:e.status,getHeader:t=>e.getHeader(t)??void 0,body:a}:{status:e.status,getHeader:t=>e.getHeader(t)??void 0},{requireChallengeChannel:t.requireChallengeChannel})},es=e=>Ie({status:e.status,getHeader:t=>e.getHeader(t)??void 0},{requireChallengeChannel:`header`}).challenge,ts=(e,t)=>t.passflow===null?`[passflow] a 401/403 from ${e} carried an upgrade challenge, but no Passflow endpoint is configured — set \`url\` on the Passflow config.`:`[passflow] a 401/403 from ${e} carried an upgrade challenge, but that URL is not covered by the provider's \`backend\` prop — add it there to enable step-up for this API.`,ns=(e,t)=>e instanceof Oo?{kind:`cancelled`}:e instanceof ko?{kind:`sign-in-required`}:e instanceof Po?{kind:`unsatisfiable`,error:e}:e instanceof Pa?{kind:`unavailable`}:e instanceof Fa?{kind:`session-changed`}:e instanceof Na?{kind:`insufficient`,obtained:e.obtained,required:e.required}:e instanceof $?e.kind===`exhausted`||e.kind===`attempts_exhausted`||e.kind===`rate_limited`?{kind:`exhausted`,error:e}:e.kind===`unavailable`?{kind:`unavailable`}:e.kind===`session_changed`?{kind:`session-changed`}:{kind:`transport-failure`,status:e.status,retryable:e.retryable,error:e}:{kind:`transport-failure`,retryable:!1,error:e instanceof Error?e:Error(String(e))},rs=async(e,t,n,r)=>{if(e.status!==401&&e.status!==403)return{kind:`replayed`,response:e};let{challenge:i,diagnostics:a}=await $o(e,t);if(Zo(a,e,t),!i)return{kind:`replayed`,response:e};if(Ao(i))return{kind:`sign-in-required`,response:e};if(jo(i))return{kind:`unsatisfiable`,error:No(i),response:e};let o=Ro(i);return r(`elevated-insufficient`,{obtained:n,required:o}),{kind:`insufficient`,obtained:n,required:o,response:e}},is=async(e,t)=>{if(!t)return{aborted:!1,value:await e};if(t.aborted)return{aborted:!0,reason:t.reason};if(typeof t.addEventListener!=`function`)return{aborted:!1,value:await e};let n,r=new Promise(e=>{n=()=>e({aborted:!0,reason:t.reason}),t.addEventListener?.(`abort`,n)});try{return await Promise.race([e.then(e=>({aborted:!1,value:e})),r])}finally{n&&t.removeEventListener?.(`abort`,n)}},as=async(e,t)=>{if(e.status!==401&&e.status!==403||e.markers.upgradeTransaction)return{kind:`not-a-challenge`};let n=Xo(e,t);if(e.markers.replayed){if(!Jo(e.request,t.scope,t.shouldIntercept))return{kind:`not-a-challenge`};let{challenge:r,diagnostics:i}=await $o(e,t);if(Zo(i,e,t),!r)return{kind:`not-a-challenge`};let a=t.readObtainedBar?.()??{},o=Ro(r);return n(`elevated-insufficient`,{obtained:a,required:o}),{kind:`insufficient`,obtained:a,required:o,response:e}}if(!Jo(e.request,t.scope,t.shouldIntercept))return es(e)?(n(`challenge-out-of-scope`,{header:e.getHeader(`www-authenticate`)??void 0,message:ts(e.request.href,t.scope)}),{kind:`out-of-scope`}):{kind:`not-a-challenge`};let{challenge:r,diagnostics:i}=await $o(e,t);if(Zo(i,e,t),!r){let r=e.getHeader(`www-authenticate`);return t.requireChallengeChannel!==`header`&&n(`no-channel`,{...r?{header:r}:{},message:e.responseType===`cors`&&!r?`[passflow] a cross-origin ${e.status} from ${e.request.href} carried no readable challenge: \`WWW-Authenticate\` is not CORS-safelisted, so add \`Access-Control-Expose-Headers: WWW-Authenticate\` on that server, or have it emit the \`upgrade_required\` JSON body.`:`[passflow] a ${e.status} from ${e.request.href} carried no upgrade challenge on either channel; treated as an ordinary ${e.status}.`}),{kind:`not-a-challenge`}}if(e.replayable===!1)return n(`replay-unsupported`,{message:`[passflow] a ${e.status} from ${e.request.href} carried an upgrade challenge, but the request cannot be replayed (${e.replayUnsupportedReason??`unsupported body`}), so no prompt was opened.`}),{kind:`replay-unsupported`};let a=t.authorizationSwap?.(),o={kind:`request`,url:e.request.href,method:e.request.method},s,c;try{s=Promise.resolve(t.elevate(r,o)),c=await is(s,e.signal)}catch(e){return ns(e,void 0)}if(c.aborted)return s?.then(e=>e?.waiter.report({outcome:`failed`}),()=>{}),{kind:`aborted`,reason:c.reason};let l=c.value;if(e.signal?.aborted)return l?.waiter.report({outcome:`failed`}),{kind:`aborted`,reason:e.signal.reason};let u=l?.obtained??t.readObtainedBar?.()??Ro(r),d=t.authorizationSwap?.(),f=d?{from:a?.from??d.from,to:d.to}:void 0;e.markers.replayed=!0;let p;try{p=await e.replay(f?{authorizationSwap:f}:void 0)}catch(t){if(t instanceof Na)return l?.waiter.report({outcome:`insufficient`,obtained:t.obtained,required:t.required}),e.signal?.aborted?{kind:`aborted`,reason:e.signal.reason}:{kind:`insufficient`,obtained:t.obtained,required:t.required};if(l?.waiter.report({outcome:`failed`}),e.signal?.aborted)return{kind:`aborted`,reason:e.signal.reason};throw t}let m=await rs(p,t,u,n);return m.kind===`insufficient`?l?.waiter.report({outcome:`insufficient`,obtained:m.obtained,required:m.required}):l?.waiter.report({outcome:`replayed`,obtained:u}),m},os=e=>{switch(e.kind){case`cancelled`:return new Oo;case`unsatisfiable`:return e.error??new Po;case`sign-in-required`:return new ko;case`unavailable`:return new Pa;case`session-changed`:return new Fa;case`insufficient`:return new Na(e.obtained,e.required);case`exhausted`:return e.error;case`transport-failure`:return e.error;default:return}},ss=(e,t,n)=>{switch(e.kind){case`replayed`:return{settle:`resolve`,value:e.response.raw};case`not-a-challenge`:case`out-of-scope`:case`replay-unsupported`:return{settle:`resolve`,value:t};case`aborted`:return{settle:`reject`,error:e.reason};case`cancelled`:return n.onCancel===`reject`?{settle:`reject`,error:new Oo}:{settle:`resolve`,value:_s(t,e)};case`unsatisfiable`:case`sign-in-required`:return{settle:`resolve`,value:_s(e.response?.raw??t,e)};case`insufficient`:return{settle:`resolve`,value:_s(e.response?.raw??t,e)};default:return{settle:`resolve`,value:_s(t,e)}}},cs=(e,t)=>{switch(e.kind){case`replayed`:return e.response.rejected?{settle:`reject`,error:e.response.raw??t}:{settle:`resolve`,value:e.response.raw};case`aborted`:return{settle:`reject`,error:e.reason};default:return{settle:`reject`,error:os(e)??t}}},ls=new WeakSet,us=new WeakSet,ds=new WeakSet,fs=new WeakSet,ps=new WeakSet,ms=new WeakSet,hs=new WeakSet,gs=new WeakSet,_s=(e,t)=>{switch(t.kind){case`cancelled`:ls.add(e);break;case`exhausted`:us.add(e);break;case`insufficient`:ds.add(e);break;case`unsatisfiable`:fs.add(e);break;case`sign-in-required`:ps.add(e);break;case`unavailable`:ms.add(e);break;case`session-changed`:hs.add(e);break;case`transport-failure`:gs.add(e)}return e},vs=e=>ls.has(e),ys=e=>us.has(e),bs=e=>ds.has(e),xs=e=>fs.has(e),Ss=e=>ps.has(e),Cs=e=>ms.has(e),ws=e=>hs.has(e),Ts=e=>gs.has(e),Es=`https://passflow-relative.invalid`,Ds=()=>{let e=globalThis,t=e.document?.baseURI;if(typeof t==`string`&&t!==``)return t;let n=e.location?.href;return typeof n==`string`&&n!==``&&n!==`about:blank`?n:Es},Os=(e,t=Ds())=>{let n=t===Es,r;try{r=new URL(t).origin}catch{r=void 0}let i;try{i=new URL(e,t)}catch{i=void 0}return i?{href:i.href,origin:i.origin,pathname:i.pathname,resolved:!0,relativeToBase:r!==void 0&&i.origin===r,sentinelBase:n}:{href:e,pathname:e.split(/[?#]/)[0]??e,resolved:!1,relativeToBase:!1,sentinelBase:n}},ks=(e,t)=>typeof t==`string`?[e.toLowerCase(),t]:void 0,As=e=>{let t=[];if(e==null)return Object.freeze(t);let n=e;if(typeof n.forEach==`function`&&typeof n.entries==`function`)return e.forEach((e,n)=>{let r=ks(n,e);r&&t.push(r)}),Object.freeze(t);if(Array.isArray(e)){for(let n of e)if(Array.isArray(n)&&n.length>=2){let e=ks(String(n[0]),n[1]);e&&t.push(e)}return Object.freeze(t)}if(typeof e==`object`)for(let[n,r]of Object.entries(e)){let e=ks(n,Array.isArray(r)?r.join(`, `):r);e&&t.push(e)}return Object.freeze(t)},js=e=>{let t=e.base===void 0?Os(e.url):Os(e.url,e.base),n={raw:e.url,href:t.href,dispatchUrl:t.sentinelBase||!t.resolved?e.url:t.href,...t.origin===void 0?{}:{origin:t.origin},pathname:t.pathname,resolved:t.resolved,relativeToBase:t.relativeToBase,method:(e.method??`GET`).toUpperCase(),headers:As(e.headers),bodyKind:e.bodyKind,...`body`in e?{body:e.body}:{}};return Object.freeze(n)},Ms=(e,t)=>{if(!t||t.from===t.to)return e;let n=!1,r=e.map(([e,r])=>e===`authorization`&&r===t.from?(n=!0,[e,t.to]):[e,r]);return n?Object.freeze(r):e},Ns=e=>{let t={};for(let[n,r]of e)t[n]=r;return t},Ps=new Set([`GET`,`HEAD`,`OPTIONS`]),Fs=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.clone==`function`&&`method`in e,Is=e=>typeof e==`string`?e:Fs(e)?e.url:String(e),Ls=(e,t)=>(t?.method??(Fs(e)?e.method:void 0)??`GET`).toUpperCase(),Rs=e=>e==null?`none`:typeof e==`string`?`reusable`:typeof e.getReader==`function`?`one-shot`:`reusable`,zs=e=>{if(typeof e==`string`)return e.length;let t=e;if(typeof t?.size==`number`)return t.size;if(typeof t?.byteLength==`number`)return t.byteLength},Bs=(e,t,n)=>e===void 0||e===`always`?!0:e===`idempotent-only`?Ps.has(t.method):typeof e==`function`?e(t):!(e.maxBodyBytes!==void 0&&n!==void 0&&n>e.maxBodyBytes),Vs=(e,t,n,r,i)=>({replayable:!1,bodyKind:e,reason:t,forwardInput:n,forwardInit:i,snapshot:r,replay:()=>Promise.reject(Error(`This request cannot be replayed: ${t}`))}),Hs=(e,t)=>Ns(Ms(e.headers,t?.authorizationSwap)),Us=e=>{if(!e||!(`headers`in e))return e;let{headers:t,...n}=e;return n},Ws=(e,t)=>t&&`headers`in t&&t.headers!==void 0?t.headers:Fs(e)?e.headers:void 0,Gs=e=>{if(e===null||typeof e==`string`)return e;if(typeof FormData<`u`&&e instanceof FormData){let t=new FormData;for(let[n,r]of e)t.append(n,r);return t}return typeof URLSearchParams<`u`&&e instanceof URLSearchParams?new URLSearchParams(e):e instanceof ArrayBuffer?e.slice(0):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice():e},Ks=(e,t,n)=>new Request(e,{headers:Hs(t,n)}),qs=(e,t,n)=>{let r=Is(e),i=Ls(e,t),a=Ws(e,t),o=(e,t)=>js({url:r,method:i,headers:a,bodyKind:e,...t===void 0?{}:{body:t}});if(Fs(e)){if(e.body===null||e.body===void 0){let a=o(`none`);return Bs(n,{url:r,method:i,bodyKind:`none`})?{replayable:!0,bodyKind:`none`,forwardInput:e,forwardInit:t,snapshot:a,replay:(n,r)=>n(Ks(e,a,r),Us(t))}:Vs(`none`,`the replay policy refused this request`,e,a,t)}let a=o(`request-clone`);if(!Bs(n,{url:r,method:i,bodyKind:`request-clone`}))return Vs(`request-clone`,`the replay policy refused this request`,e,a,t);let s;try{s=e.clone()}catch{return Vs(`one-shot`,`the Request body was already consumed and cannot be cloned`,e,a,t)}return{replayable:!0,bodyKind:`request-clone`,forwardInput:e,forwardInit:t,snapshot:a,replay:(e,n)=>e(Ks(s,a,n),Us(t))}}let s=Rs(t?.body);if(s===`one-shot`)return Vs(`one-shot`,`a streaming request body is consumed by the first send`,e,o(`one-shot`),t);if(!Bs(n,{url:r,method:i,bodyKind:s},zs(t?.body)))return Vs(s,`the replay policy refused this request`,e,o(s),t);let c=t&&`body`in t?Gs(t.body??null):void 0,l=o(s,c);return{replayable:!0,bodyKind:s,forwardInput:e,forwardInit:t,snapshot:l,replay:(e,n)=>e(l.dispatchUrl,{...Us(t),...c===void 0?{}:{body:c},headers:Hs(l,n),method:l.method})}},Js=e=>typeof e==`object`&&!!e,Ys=e=>t=>{if(!Js(e))return;let n=e[t]??e[t.toLowerCase()]??(typeof e.get==`function`?e.get(t):void 0);return Array.isArray(n)?n.join(`, `):typeof n==`string`?n:void 0},Xs=e=>{let t=e?.url??``,n=e?.baseURL;return!n||/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:`${n.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`},Zs=e=>(e?.method??`GET`).toUpperCase(),Qs=e=>e==null?`none`:Js(e)&&(typeof e.pipe==`function`||typeof e.getReader==`function`)?`one-shot`:`reusable`,$s=(e,t,n)=>{let r=Ns(Ms(t.headers,n?.authorizationSwap)),i=t.dispatchUrl===t.href&&t.resolved;return{...e,...i?{baseURL:void 0}:{},url:t.dispatchUrl,method:t.method,headers:r,...`body`in t?{data:t.body}:{}}},ec=(e,t,n,r,i,a)=>{let o=t??e?.config,s=Qs(o?.data),c=a??js({url:Xs(o),method:Zs(o),headers:o?.headers,bodyKind:s,body:o?.data}),l={url:c.href,method:c.method,bodyKind:s},u=s!==`one-shot`&&Bs(i.replay,l);return{status:e?.status??0,getHeader:Ys(e?.headers),readBody:async()=>e?.data,request:c,replay:async e=>{let t=Ue($s(o??{},c,e));try{let e=await r(t);return ec(e,e?.config??t,e,r,i,c)}catch(e){let n=Js(e)?e:{};if(!n.response||typeof n.response.status!=`number`||Ca(e))throw e;return{...ec(n.response,n.config??t,e,r,i,c),rejected:!0}}},markers:{...He(o)?{upgradeTransaction:!0}:{},...We(o)?{replayed:!0}:{}},raw:n,replayable:u,replayUnsupportedReason:s===`one-shot`?`a streaming request body is consumed by the first send`:`the replay policy refused this request`,signal:o?.signal}},tc=(e,t)=>async n=>{let r=Uo(e),i=Js(n)?n:{},a=cs(await as(ec(i.response,i.config,i.response,t,r),r),n);if(a.settle===`reject`)throw a.error;return a.value},nc=(e,t,n)=>{let r=e.request,i=n??(typeof r==`function`?t=>r.call(e,t):()=>Promise.reject(Error(`Passflow: this client exposes no request() to replay through.`))),a=e.interceptors.response.use(void 0,tc(t,i)),o=!1;return()=>{o||(o=!0,e.interceptors.response.eject(a))}},rc=(e,t)=>{let n=c.default.create(e);return t(n),n},ic=()=>{let e=typeof location>`u`?void 0:location.origin;return e&&e!==`null`?e:void 0},ac=e=>{let t=new URL(e).origin;if(t===`null`)throw Error(`Passflow: "${e}" has no origin a request can be matched against; list http(s) origins only.`);return t},oc=(e,t)=>{let n=(t?.origins??[]).map(ac);return(t,r)=>{if(r)return Promise.resolve(void 0);let i=ic(),a;try{a=new URL(t,i).origin}catch{return Promise.resolve(void 0)}return a!==i&&!n.includes(a)?Promise.resolve(void 0):e()}},sc=e=>typeof Request<`u`&&e instanceof Request,cc=(e,t)=>new Headers(t?.headers===void 0?sc(e)?e.headers:void 0:t.headers),lc=(e,t,n)=>{let r=oc(t,n);return async(t,n)=>{let i=sc(t)?t.url:t instanceof URL?t.href:String(t),a=cc(t,n),o=await r(i,a.has(`authorization`));return o?(a.set(`authorization`,`Bearer ${o}`),e(t,{...n,headers:a})):e(t,n)}},uc=e=>{let t=e.url??``,n=/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return!e.baseURL||n&&e.allowAbsoluteUrls!==!1?t:t?`${e.baseURL.replace(/\/?\/$/,``)}/${t.replace(/^\/+/,``)}`:e.baseURL},dc=e=>e?typeof e.has==`function`?e.has(`Authorization`):Object.keys(e).some(t=>t.toLowerCase()===`authorization`&&e[t]!=null):!1,fc=(e,t)=>{let n=oc(e,t);return async e=>{let t=e.headers,r=await n(uc(e),dc(t));if(!r)return e;let i=`Bearer ${r}`;return t&&typeof t.set==`function`?t.set(`Authorization`,i):e.headers={...t??{},Authorization:i},e}},pc=0,mc=(e,t)=>{let n=t?.signal??(typeof e==`object`&&e?e.signal:void 0)??void 0;if(n)return{get aborted(){return n.aborted},get reason(){return n.reason},...typeof n.addEventListener==`function`?{addEventListener:(e,t)=>n.addEventListener(e,t),removeEventListener:(e,t)=>n.removeEventListener(e,t)}:{}}},hc=e=>t=>e.headers?.get(t),gc=(e,t,n,r,i)=>({status:e.status,getHeader:hc(e),readBody:()=>e.clone().json(),request:t.snapshot,replay:async e=>gc(await t.replay(n,e),t,n,r,i),markers:r,raw:e,replayable:t.replayable,replayUnsupportedReason:t.reason,signal:i,responseType:e.type}),_c=(e,t)=>{let n=(t,n)=>{pc+=1;try{return e(t,n)}finally{--pc}};return async(e,r)=>{if(pc>0)return n(e,r);let i=Uo(t),a=qs(e,r,i.replay),o=await n(a.forwardInput,a.forwardInit),s=ss(await as(gc(o,a,n,{},mc(e,r)),i),o,i);if(s.settle===`reject`)throw s.error;return s.value}},vc=new Set(xo.filter(e=>!e.requiresPrepare).map(e=>e.type)),yc=e=>{if(!e||typeof e!=`object`||!e.challenge_id||!e.expires_at)throw new $({kind:`protocol`,message:`The upgrade start response is missing challenge_id or expires_at`});return{challengeId:e.challenge_id,method:e.method,expiresAt:e.expires_at,webauthn:e.webauthn,codeSentTo:e.code_sent_to}},bc=e=>Ca(e)&&!wa(e),xc=e=>({async prepare(t){if(!vc.has(t))try{let n=e.relyingPartyId?.();return yc(await e.startUpgrade(n?{method:t,relying_party_id:n}:{method:t}))}catch(e){if(bc(e))throw e;let t=Aa(e,`start`);if(t.kind===`prepare_not_required`)return;throw t}},async commit(t,n){let r=e.canCommit();if(!r.ok)throw new $({kind:`unavailable`,message:r.reason});try{await e.commitRefresh({type:t,assertion:n})}catch(t){if(bc(t))throw t;let n=Aa(t,`refresh`);throw n.status===401&&Ma(n)&&e.markSessionInvalid?.(),n}}}),Sc=e=>e===void 0?[]:(Array.isArray(e)?e:[e]).filter(e=>e!==``),Cc=e=>{let t,n=e=>e!==void 0&&t===e,r=r=>{let i=()=>{if(!n(r()))throw new $({kind:`session_changed`})};return xc({...e,relyingPartyId:()=>t?.options.relyingPartyId??e.relyingPartyId?.(),startUpgrade:t=>(i(),e.startUpgrade(t)),commitRefresh:t=>(i(),a=Date.now(),e.commitRefresh(t,r()?.pin)),...e.markSessionInvalid?{markSessionInvalid:()=>{n(r())&&e.markSessionInvalid?.()}}:{}})},i=(t,n)=>{let i={},a={controller:new Ho({transport:r(()=>i.current),prompt:t.prompt,platform:e.platform,factors:t.factors??e.factors,...t.maxAttempts===void 0?{}:{maxAttempts:t.maxAttempts},...e.readObtainedBar?{readObtainedBar:e.readObtainedBar}:{},...t.onFlightSettled?{onFlightSettled:t.onFlightSettled}:{}}),options:t,scope:{passflow:e.passflowDomain,backend:Sc(t.backend)},generation:n};return i.current=a,a},a,o=1e4,s;e.stopRepeatedElevation?.subscribe(()=>{s=void 0});let c=e=>{if(!s||Vo(s.challenge,e))return;let t=Math.min(o,e.maxAge===void 0?o:e.maxAge*1e3);if(!(Date.now()-s.at>t))return s.challenge},l=async(r,i)=>{let o=t;if(!o)throw new Pa(`Step-up verification is not enabled on this Passflow instance`);let l=e.stopRepeatedElevation?c(r):void 0;if(l)throw new Na(Ro(l),Ro(r),`This requirement was already proved and the server still refused it: sign the user in again`);o.controller.active||(o.pin=e.readSessionPin?.());let u=await o.controller.elevate(r,i);if(!n(o))throw new Fa;return e.stopRepeatedElevation&&(s={challenge:r,at:a??Date.now()}),u},u=()=>{let n=t,r=n?.scope??{passflow:e.passflowDomain,backend:[]},i=n?.options;return{elevate:l,scope:r,...i?.requireChallengeChannel?{requireChallengeChannel:i.requireChallengeChannel}:{},...i?.shouldIntercept?{shouldIntercept:i.shouldIntercept}:{},...i?.replay===void 0?{}:{replay:i.replay},...i?.onCancel?{onCancel:i.onCancel}:{},...e.authorizationSwap?{authorizationSwap:e.authorizationSwap}:{},...i?.onUpgradeDiagnostic?{onUpgradeDiagnostic:i.onUpgradeDiagnostic}:{},...e.readObtainedBar?{readObtainedBar:e.readObtainedBar}:{}}},d;return Object.defineProperties(async e=>{let t=e?.acrValues===void 0?void 0:Ce(e.acrValues).level,n={status:401,...e?.acrValues===void 0?{}:{acrValues:e.acrValues},...t===void 0?{}:{requiredLevel:t},...e?.maxAge===void 0?{}:{maxAge:e.maxAge}},r=e?.acrValues!==void 0||e?.maxAge!==void 0,i={...e?.acrValues===void 0?{}:{acrValues:e.acrValues},...t===void 0?{}:{level:t},...e?.maxAge===void 0?{}:{maxAge:e.maxAge}},a=(await l(n,{kind:`imperative`,...r?{requested:i}:{}})).obtained.acrValues;return{status:`elevated`,...a===void 0?{}:{acr:a}}},{enable:{value:n=>{d?.(),t=i(n,0);let r=[];if(e.attachInternalSeam){let t=e.attachInternalSeam;t(e=>tc(u,e)),r.push(()=>t(void 0))}n.interceptFetch&&r.push(tr((e,t,n)=>_c(e,u)(t,n),{priority:20,name:`passflow-upgrade`})),e.onSessionChange&&r.push(e.onSessionChange(()=>{let e=t;e&&(t=i(e.options,e.generation+1))}));let a=!1;return d=()=>{if(!a){a=!0;for(let e of r)e();t=void 0,d=void 0}},d},enumerable:!0},enabled:{enumerable:!0,get(){return t!==void 0&&e.canCommit().ok}},elevate:{enumerable:!0,value:(e,t)=>l(e,t??{kind:`imperative`})},withAuth:{enumerable:!0,value:(t,n)=>{let r=t=>{let r=_c(t,u);return e.readAccessToken?lc(r,e.readAccessToken,n):r};if(t)return r(t);let i=typeof globalThis>`u`?void 0:globalThis;if(!i||typeof i.fetch!=`function`)throw Error(`Passflow: withAuth() needs a fetch to wrap — this runtime has none.`);return r(i.fetch.bind(i))}},attachAuth:{enumerable:!0,value:(t,n)=>{let r=e.readAccessToken?t.interceptors.request:void 0,i=r?.use(fc(e.readAccessToken,n)),a=nc(t,u);return()=>{a(),r&&i!==void 0&&r.eject(i)}}}})},wc,Tc=class{get origin(){return this.platform.getCurrentUrl()?.origin??``}constructor(e){this.doRefreshTokens=!1,this.session=async({createSession:e,expiredSession:t,doRefresh:n=!1})=>{this.createSessionCallback=e,this.expiredSessionCallback=t,this.doRefreshTokens=n,await this.submitSessionCheck()};let{url:t,appId:n,scopes:r}=e;this.url=t||`https://auth.passflow.cloud`,this.appId=n,this.platform=e.platform??ye,this.deferFederatedLanding=e.deferFederatedLanding??!1,this.storageManager=new he({prefix:e.keyStoragePrefix??``,storage:this.platform.storage,appId:n}),this.deviceService=new ge(this.storageManager),this.authApi=new ln(e,this.storageManager,this.deviceService),this.appApi=new en(e,this.storageManager,this.deviceService),this.userApi=new bn(e,this.storageManager,this.deviceService),this.settingApi=new fn(e,this.storageManager,this.deviceService),this.tenantApi=new pn(e,this.storageManager,this.deviceService),this.invitationApi=new dn(e,this.storageManager,this.deviceService),this.twoFactorApi=new vn(e,this.storageManager,this.deviceService),this.upgradeApi=new yn(e,this.storageManager,this.deviceService),this.upgradeDomain=qe(e.url),this.subscribeStore=new Ir,this.tokenCacheService=new po(this.storageManager,this.authApi,this.subscribeStore,this.platform),this.scopes=r??w,this.createTenantForNewUser=e.createTenantForNewUser??!1;let i=Ai(e.refreshCoordination,this.platform,e.keyStoragePrefix,{tokenKeys:()=>this.storageManager.tokenKeys()});this.deviceKeyService=e.deviceKey===!0&&!e.tokenExchange?.enabled?zn({dbName:In(e.keyStoragePrefix),deviceId:()=>this.deviceService.getDeviceId()}):void 0;let a=this.deviceKeyService;this.authService=new co(this.authApi,this.deviceService,this.storageManager,this.subscribeStore,this.tokenCacheService,this.scopes,this.createTenantForNewUser,this.url,{createSession:async e=>{await this.createSessionCallback?.(e)},expiredSession:async()=>{await this.expiredSessionCallback?.()}},this.appId??``,e.tokenExchange,this.platform,()=>this.readPkceEnabled(),{coordination:i,...e.refreshStrikes===void 0?{}:{strikes:e.refreshStrikes},...a?{deviceKey:a,enrolDeviceKeyRequest:e=>this.userApi.enrolDeviceKey(e)}:{}},()=>this.readAppSettings()),this.antiBot=Qr({readSettings:()=>this.readAppSettings(),fetchChallenge:({identifier:e,device:t})=>t?this.authApi.deviceAntiBotChallenge({user_code:t.userCode,...e?{identifier:e}:{}},t.csrfToken):this.authApi.antiBotChallenge(e?{identifier:e}:{}),store:this.subscribeStore,...e.antiBotWorkerUrl?{workerUrl:e.antiBotWorkerUrl}:{}}),this.authApi.setAntiBotHandler(e=>this.antiBot.headerFor(e)),this.tokenCacheService.attachRefreshController(this.authService.refresh);for(let e of this.axiosClients())e.setRefreshHandler(e=>this.authService.refresh.ensureFresh(e));this.userService=new ho(this.userApi,this.deviceService,this.platform),this.tenantService=new fo(this.tenantApi,this.scopes),this.tenant=this.tenantService,this.invitationService=new lo(this.invitationApi),this.twoFactorService=new mo(this.twoFactorApi,this.subscribeStore,this.authService),this.twoFactor=this.twoFactorService,this.upgrade=Cc({startUpgrade:e=>this.upgradeApi.startUpgrade(e),commitRefresh:async(e,t)=>{await this.authService.refreshToken(e,t)},readSessionPin:()=>this.authService.readSessionPin(),canCommit:()=>this.authService.tokenDeliveryManager.isBFFMode()?{ok:!1,reason:`Step-up verification cannot be committed through a BFF refresh endpoint`}:{ok:!0},markSessionInvalid:()=>this.authService.tokenDeliveryManager.setSessionInvalid(),platform:this.platform,passflowDomain:this.upgradeDomain,...e.upgrade?.factors?{factors:e.upgrade.factors}:{},...e.upgrade?.relyingPartyId?{relyingPartyId:()=>e.upgrade?.relyingPartyId}:{},readObtainedBar:()=>this.readAssuranceBar(),authorizationSwap:()=>{let e=this.storageManager.getToken(F.access_token);return e?{from:`Bearer ${e}`,to:`Bearer ${e}`}:void 0},attachInternalSeam:e=>this.attachUpgradeSeam(e),onSessionChange:e=>this.subscribeToSessionChange(e),readAccessToken:async()=>{let e=(await this.getTokens(!0))?.access_token;return e&&!N(P(e))?e:void 0}}),this.hostedUpgrade=Cc({startUpgrade:e=>this.upgradeApi.startHostedUpgrade(e),commitRefresh:e=>this.upgradeApi.commitHostedUpgrade(e),canCommit:()=>({ok:!0}),readSessionPin:()=>void 0,readObtainedBar:()=>void 0,stopRepeatedElevation:{subscribe:e=>this.subscribeToSessionChange(e)},markSessionInvalid:()=>{},platform:this.platform,passflowDomain:this.upgradeDomain,...e.upgrade?.factors?{factors:e.upgrade.factors}:{},...e.upgrade?.relyingPartyId?{relyingPartyId:()=>e.upgrade?.relyingPartyId}:{}}),e.parseQueryParams&&this.checkAndSetTokens(),this.setTokensToCacheFromLocalStorage()}readAppSettings(){if(!this.appId)return Promise.resolve(void 0);if(!this.appSettingsRead){let e=this.appApi.getAppSettings();this.appSettingsRead=e,e.catch(()=>{this.appSettingsRead===e&&(this.appSettingsRead=void 0)})}return this.appSettingsRead}readPkceEnabled(){return this.readAppSettings().then(e=>e?.pkce_enabled??!1)}setAppId(e){e!==this.appId&&(this.appId=e,this.storageManager.setAppId(e),this.appSettingsRead=void 0,this.authApi.setAppId(e),this.appApi.setAppId(e),this.userApi.setAppId(e),this.settingApi.setAppId(e),this.tenantApi.setAppId(e),this.invitationApi.setAppId(e),this.twoFactorApi.setAppId(e),this.upgradeApi.setAppId(e),this.authService.setAppId(e),this.tokenCacheService.setTokensCache(void 0),this.setTokensToCacheFromLocalStorage())}withAuth(e,t){return this.upgrade.withAuth(e,t)}attachAuth(e,t){return this.upgrade.attachAuth(e,t)}createClient(e,t){return rc(e,e=>this.upgrade.attachAuth(e,t))}readAssuranceBar(){let e=this.storageManager.getToken(F.access_token);if(e)try{let t=P(e),n=typeof t.acr==`string`?t.acr:void 0;if(!n)return;let r=Ce(n).level;return r===void 0?{acrValues:n}:{acrValues:n,level:r}}catch{return}}axiosClients(){return[this.authApi.axiosClient,this.appApi.axiosClient,this.userApi.axiosClient,this.settingApi.axiosClient,this.tenantApi.axiosClient,this.invitationApi.axiosClient,this.twoFactorApi.axiosClient,this.upgradeApi.axiosClient]}attachUpgradeSeam(e){for(let t of this.axiosClients()){if(!e){t.setUpgradeInterceptor(void 0);continue}let n=e(e=>t.replay(e));t.setUpgradeInterceptor(n)}}subscribeToSessionChange(e){let t={onAuthChange:()=>e()};return this.subscribeStore.subscribe(t,[G.SignIn,G.SignOut]),()=>this.subscribeStore.unsubscribe(t)}async submitSessionCheck(){let e,t;try{e=await this.authService.getTokens(this.doRefreshTokens),t=this.tokenCacheService.getParsedTokens()}catch(t){let n={operation:`session.check`,message:t instanceof Error||t instanceof B?t.message:`Session check failed`,originalError:t};W(this.subscribeStore,n),e=void 0}e&&this.createSessionCallback&&await this.createSessionCallback({tokens:e,parsedTokens:t}),!e&&this.expiredSessionCallback&&await this.expiredSessionCallback()}subscribe(e,t){this.subscribeStore.subscribe(e,t),this.tokenCacheService.initialize()}unsubscribe(e,t){this.subscribeStore.unsubscribe(e,t)}handleTokensRedirect(){this.checkAndSetTokens()}completeFederatedLanding(){return this.takeFederatedLanding()||this.takeOidcLanding()}checkAndSetTokens(){let e=this.platform.getCurrentUrl(),t=new URLSearchParams(e?.search??``);if(!t.get(`access_token`)&&e?.hash){let n=new URLSearchParams(e.hash.substring(1));n.get(`access_token`)&&(t=n)}if(!t.get(`access_token`)&&this.adoptTwoFactorTokenFromUrl(e)){this.error=void 0;return}let n=t.get(`access_token`),r=t.get(`refresh_token`),i=t.get(`id_token`),a=t.get(`state`)??void 0,o=t.get(`scopes`)?.split(`,`)??this.scopes;if(n){if(!Ra(n)){W(this.subscribeStore,{operation:`tokens.from-url`,message:`Invalid access token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(e);return}if(r&&!Ra(r)){W(this.subscribeStore,{operation:`tokens.from-url`,message:`Invalid refresh token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(e);return}if(i&&!Ra(i)){W(this.subscribeStore,{operation:`tokens.from-url`,message:`Invalid ID token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(e);return}let t={access_token:n,refresh_token:r??void 0,id_token:i??void 0,scopes:o};this.cleanupUrlParams(e),this.error=void 0,this.readAppSettings().catch(()=>void 0).then(e=>{if(e?.pkce_enabled!==!1)throw Sr();return ga(this.url,this.appId,t)}).then(()=>{this.storageManager.clearDeliveryMode(),this.storageManager.saveTokens(t,void 0,{replace:!0}),e&&this.storageManager.setHostedSignIn(e.origin+e.pathname),this.tokenCacheService.setTokensCache(t),this.authService.refresh.sessionStarted()}).then(()=>(this.subscribeStore.notify(G.SignIn,{tokens:t,parsedTokens:this.getParsedTokens(),source:`tokens-in-url`,...a?{state:a}:{}}),this.submitSessionCheck()),e=>W(this.subscribeStore,{operation:`tokens.from-url`,message:e instanceof Error?e.message:`Tokens in the URL could not be verified`,code:e instanceof U?e.code:`TOKEN_NOT_VERIFIED`,originalError:e}))}else this.cleanupUrlParams(e),!this.deferFederatedLanding&&!this.takeFederatedLanding()&&this.takeOidcLanding(),this.error=this.checkErrorsFromURL()}takeFederatedLanding(){let e=this.platform.getCurrentUrl();if(!e)return!1;let t=new URLSearchParams(e.search),n=t.get(`code`);if(t.get(`access_token`)||new URLSearchParams(e.hash?.substring(1)).get(`access_token`)||!n||!t.get(`user_state`)||!this.authService.handleFederatedCode(n))return!1;t.delete(`code`),t.delete(`user_state`);let r=t.toString();return this.platform.replaceUrl(e.pathname+(r?`?${r}`:``)+e.hash),!0}takeOidcLanding(){let e=this.platform.getCurrentUrl();return e?this.authService.handleOidcLanding(e):!1}adoptTwoFactorTokenFromUrl(e){if(!e?.hash)return!1;let t=new URLSearchParams(e.hash.substring(1)),n=t.get(`tfa_token`);if(!n)return!1;t.delete(`tfa_token`);let r=t.toString(),i=new URLSearchParams(e.search);i.delete(`user_state`);let a=i.toString();return this.platform.replaceUrl(e.pathname+(a?`?${a}`:``)+(r?`#${r}`:``)),Ra(n)?(this.subscribeStore.notify(G.TwoFactorRequired,{email:``,challengeId:``,tfaToken:n}),!0):(W(this.subscribeStore,{operation:`tokens.from-url`,message:`Invalid 2FA token format received`,code:`INVALID_TOKEN_FORMAT`}),!0)}checkErrorsFromURL(){let e=new URLSearchParams(this.platform.getCurrentUrl()?.search??``).get(`error`);if(e){let t=za(e);return Error(t)}}cleanupUrlParams(e){if(!e)return;let t=[`access_token`,`refresh_token`,`id_token`],n=new URLSearchParams(e.search),r=new URLSearchParams(e.hash?.substring(1)),i=t.some(e=>n.get(e)),a=t.some(e=>r.get(e));if(!a&&!i)return;let o=[...t,`client_challenge`,`user_state`];for(let e of[...o,...i?[`state`]:[]])n.delete(e);let s=n.toString(),c=e.hash??``;if(a){for(let e of[...o,`state`])r.delete(e);let e=r.toString();c=e?`#${e}`:``}this.platform.replaceUrl(e.pathname+(s?`?${s}`:``)+c)}setTokensToCacheFromLocalStorage(){let e=this.storageManager.getTokens();if(!e?.access_token&&this.storageManager.getDeliveryMode()){if(e?.id_token&&this.storageManager.hasCookieModeIdToken()){this.tokenCacheService.setTokensCache(e);return}if(this.storageManager.hasJsonModeTokens())this.storageManager.clearDeliveryMode(),e=this.storageManager.getTokens();else{this.storageManager.deleteTokens();return}}e&&this.tokenCacheService.setTokensCache(e)}getCachedTokens(){return this.tokenCacheService.getTokens()}getTokensWithRefresh(){return this.tokenCacheService.getTokensWithRefresh()}getParsedTokens(){return this.tokenCacheService.getParsedTokens()}areTokensExpired(){return this.tokenCacheService.isExpired()}isAuthenticated(){let e=this.getDeliveryMode();if(e===I.Cookie||e===I.BFF)return this.authService.isAuthenticated(this.tokenCacheService.getParsedTokens()??{});let t=this.storageManager.getTokens();if(!t||!t.access_token)return!1;let n=this.tokenCacheService.getParsedTokens();return n?this.authService.isAuthenticated(n):!1}async signIn(e,t){return await this.authService.signIn(e,t)}async signUp(e,t){return await this.authService.signUp(e,t)}passwordlessSignIn(e,t){return this.authService.passwordlessSignIn(e,t)}async passwordlessSignInComplete(e,t){return await this.authService.passwordlessSignInComplete(e,t)}waitForPasswordlessSignIn(e,t){return this.authService.waitForPasswordlessSignIn(e,t)}getPendingPasswordlessSignIn(e){return this.authService.getPendingPasswordlessSignIn(e)}getPasswordlessApproval(e){return this.authService.getPasswordlessApproval(e)}decidePasswordlessApproval(e,t,n,r){return this.authService.decidePasswordlessApproval(e,t,n,r)}async verifyEmailCode(e){return await this.authService.verifyEmailCode(e)}async checkRedirectUrl(e){try{return await this.authService.checkRedirectUrl(e)}catch(e){this.handleError(e,`redirect.check`,`Redirect check`)}}setAntiBotTokenProvider(e){this.antiBot.setTokenProvider(e)}async antiBotToken(e){try{return(await this.antiBot.headerFor(e))?.value}catch(e){this.handleError(e,`anti-bot.token`,`Anti-bot token`)}}handleError(e,t,n){let r={operation:t,message:e instanceof Error?e.message:`${n} failed`,originalError:e,code:e instanceof B?e.id:void 0};throw W(this.subscribeStore,r),e}async logOut(e={}){try{let t=this.authService.hostedEndSessionUrl(e.postLogoutRedirectUri),{userId:n,samlLogoutUrl:r}=await this.authService.logOut(e.postLogoutRedirectUri),i=e.followSamlLogout&&r?r:t;try{this.twoFactorService.clearPartialAuthState(),this.notifySignedOut(n),await this.submitSessionCheck()}finally{i&&this.platform.navigateTo(i)}return r?{samlLogoutUrl:r}:{}}catch(e){this.handleError(e,`log-out`,`Log out`)}}federatedAuthWithPopup(e,t){this.authService.federatedAuthWithPopup(e,t)}federatedAuthWithRedirect(e,t){this.authService.federatedAuthWithRedirect(e,t)}async enterpriseResolve(e){try{return await this.authApi.enterpriseResolve(e)}catch(e){this.handleError(e,`enterprise.resolve`,`Enterprise resolve`)}}createEnterpriseAuthUrl(e){return this.authService.createEnterpriseAuthUrl(e)}async enterpriseStart(e,t){try{return await this.authService.enterpriseStart(e,t)}catch(e){this.handleError(e,`enterprise.start`,`Enterprise start`)}}reset(e){if(this.notifySignedOut(this.authService.resetSession()),e){this.error=Error(e);let t={operation:`reset`,message:e,code:`RESET_ERROR`};throw W(this.subscribeStore,t),this.error}}notifySignedOut(e){this.subscribeStore.notify(G.SignOut,e===void 0?{origin:`this-tab`}:{origin:`this-tab`,userId:e})}dispose(){this.authService.refresh.dispose(),this.tokenCacheService.destroy()}async refreshToken(){return await this.authService.refreshToken()}async enrolDeviceKey(){await this.authService.enrolDeviceKey()}async devicePushProof(e,t){return await this.deviceKeyService?.proof(e,t)}sendPasswordResetEmail(e,t){return this.authService.sendPasswordResetEmail(e,t)}async resetPassword(e,t,n){return await this.authService.resetPassword(e,t,n)}async getAppSettings(){try{return await this.readAppSettings()??await this.appApi.getAppSettings()}catch(e){this.handleError(e,`settings.app`,`Get app settings`)}}async getSettingsAll(){try{return await this.settingApi.getSettingsAll()}catch(e){this.handleError(e,`settings.all`,`Get all settings`)}}async getPasswordPolicySettings(){try{return await this.settingApi.getPasswordPolicySettings()}catch(e){this.handleError(e,`settings.password-policy`,`Get password policy settings`)}}async getPasskeySettings(){try{return await this.settingApi.getPasskeySettings()}catch(e){this.handleError(e,`settings.passkey`,`Get passkey settings`)}}async passkeyRegister(e,t){return await this.authService.passkeyRegister(e,t)}async passkeyAuthenticate(e,t){return await this.authService.passkeyAuthenticate(e,t)}setTokens(e){let t=this.getDeliveryMode(),n=t===I.Cookie||t===I.BFF;this.storageManager.saveTokens(e,n?t:void 0,{replace:!0}),this.tokenCacheService.setTokensCache(e),this.authService.refresh.sessionStarted(),this.subscribeStore.notify(G.SignIn,{tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens()})}async getTokens(e=!1){return await this.authService.getTokens(e)}getToken(e){return this.storageManager.getToken(e)}async getUserPasskeys(){try{return await this.userService.getUserPasskeys()}catch(e){this.handleError(e,`passkey.list`,`Get user passkeys`)}}async renameUserPasskey(e,t){try{return await this.userService.renameUserPasskey(e,t)}catch(e){this.handleError(e,`passkey.rename`,`Rename user passkey`)}}async deleteUserPasskey(e){try{return await this.userService.deleteUserPasskey(e)}catch(e){this.handleError(e,`passkey.delete`,`Delete user passkey`)}}async addUserPasskey(e){try{return await this.userService.addUserPasskey(e)}catch(e){this.handleError(e,`passkey.add`,`Add user passkey`)}}async listSessions(){try{return await this.userService.listSessions()}catch(e){this.handleError(e,`session.list`,`List sessions`)}}async revokeSession(e){let t=this.currentSessionId()===e;try{await this.userService.revokeSession(e)}catch(e){this.handleError(e,`session.revoke`,`Revoke session`)}t&&await this.logOut()}async signOutOtherSessions(){try{return await this.userService.signOutOtherSessions()}catch(e){this.handleError(e,`session.revoke-others`,`Sign out other sessions`)}}async requestAddressChangeProof(e){try{return await this.userService.requestAddressChangeProof(e)}catch(e){this.handleError(e,`profile.address-proof`,`Request address change proof`)}}async updateProfile(e,t){try{return await this.userService.updateProfile(e,t)}catch(e){this.handleError(e,`profile.update`,`Update profile`)}}currentSessionId(){let e=[this.storageManager.getToken(F.access_token),this.storageManager.getToken(F.id_token)??this.storageManager.getIdToken()];for(let t of e)if(t)try{let e=P(t).sid;if(e)return e}catch{}}async joinInvitation(e,t){try{let n=await this.tenant.joinInvitation(e,t);return n.scopes=t??this.scopes,await this.authService.applyTokens(n),n}catch(e){this.handleError(e,`invitation.join`,`Join invitation`)}}async createTenant(e,t){try{let n=await this.tenant.createTenant(e);return t&&await this.refreshToken(),n}catch(e){this.handleError(e,`tenant.create`,`Create tenant`)}}async requestInviteLink(e){try{return e.send_to_email===void 0&&(e.send_to_email=!0),await this.invitationService.requestInviteLink(e)}catch(e){this.handleError(e,`invitation.request-link`,`Request invite link`)}}async getInvitations(e){try{return await this.invitationService.getInvitations(e)}catch(e){this.handleError(e,`invitation.list`,`Get invitations`)}}async deleteInvitation(e){try{return await this.invitationService.deleteInvitation(e)}catch(e){this.handleError(e,`invitation.delete`,`Delete invitation`)}}async resendInvitation(e){try{return await this.invitationService.resendInvitation(e)}catch(e){this.handleError(e,`invitation.resend`,`Resend invitation`)}}async getInvitationLink(e){try{return await this.invitationService.getInvitationLink(e)}catch(e){this.handleError(e,`invitation.get-link`,`Get invitation link`)}}authRedirectUrl(e={}){return this.authService.authRedirectUrl(e)}authRedirect(e={}){return this.authService.authRedirect(e)}getDeliveryMode(){return this.authService.tokenDeliveryManager.getMode()}getDeviceId(){return this.deviceService.getDeviceId()}async restoreSession(){return await this.authService.restoreSession()}async getTwoFactorStatus(){try{return await this.twoFactorService.getStatus()}catch(e){this.handleError(e,`2fa.status`,`Get 2FA status`)}}async beginTwoFactorSetup(){try{return await this.twoFactorService.beginSetup()}catch(e){this.handleError(e,`2fa.setup.begin`,`Begin 2FA setup`)}}async confirmTwoFactorSetup(e){try{return await this.twoFactorService.confirmSetup(e)}catch(e){this.handleError(e,`2fa.setup.confirm`,`Confirm 2FA setup`)}}async getTwoFactorEnrollment(){try{return await this.twoFactorService.getEnrollment()}catch(e){this.handleError(e,`2fa.enrollment.read`,`Read 2FA enrollment`)}}async sendTwoFactorSetupLink(){try{return await this.twoFactorService.sendSetupLink()}catch(e){this.handleError(e,`2fa.enrollment.setup-link`,`Send 2FA setup link`)}}async beginTwoFactorEnrollment(){try{return await this.twoFactorService.beginEnrollment()}catch(e){this.handleError(e,`2fa.setup.begin`,`Begin 2FA enrollment`)}}async confirmTwoFactorEnrollment(e){try{return await this.twoFactorService.confirmEnrollment(e)}catch(e){this.handleError(e,`2fa.setup.confirm`,`Confirm 2FA enrollment`)}}async verifyTwoFactor(e,t){try{let n=await this.twoFactorService.verify(e,t);return this.subscribeStore.notify(G.SignIn,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),n}catch(e){this.handleError(e,`2fa.verify`,`Verify 2FA`)}}async useTwoFactorRecoveryCode(e,t){try{let n=await this.twoFactorService.useRecoveryCode(e,t);return this.subscribeStore.notify(G.SignIn,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),n}catch(e){this.handleError(e,`2fa.recovery.use`,`Use 2FA recovery code`)}}async disableTwoFactor(e){try{return await this.twoFactorService.disable(e)}catch(e){this.handleError(e,`2fa.disable`,`Disable 2FA`)}}async regenerateTwoFactorRecoveryCodes(e){try{return await this.twoFactorService.regenerateRecoveryCodes(e)}catch(e){this.handleError(e,`2fa.recovery.regenerate`,`Regenerate 2FA recovery codes`)}}async getTrustedDevices(){try{return await this.twoFactorService.getTrustedDevices()}catch(e){this.handleError(e,`2fa.trusted-devices.list`,`Get trusted devices`)}}async revokeTrustedDevice(e){try{await this.twoFactorService.revokeTrustedDevice(e)}catch(e){this.handleError(e,`2fa.trusted-devices.revoke`,`Revoke trusted device`)}}async getPreferredTwoFactorMethod(){try{return await this.twoFactorService.getPreferredMethod()}catch(e){this.handleError(e,`2fa.preferred-method.read`,`Get preferred 2FA method`)}}async setPreferredTwoFactorMethod(e){try{return await this.twoFactorService.setPreferredMethod(e)}catch(e){this.handleError(e,`2fa.preferred-method.set`,`Set preferred 2FA method`)}}async clearPreferredTwoFactorMethod(){try{await this.twoFactorService.clearPreferredMethod()}catch(e){this.handleError(e,`2fa.preferred-method.clear`,`Clear preferred 2FA method`)}}isTwoFactorVerificationRequired(){return this.twoFactorService.isVerificationRequired()}getTotpDigits(){return this.twoFactorService.getTotpDigits()}async validateTwoFactorSetupMagicLink(e){return await this.twoFactorService.validateTwoFactorSetupMagicLink(e)}getMagicLinkSession(){return this.twoFactorService.getMagicLinkSession()}hasMagicLinkSession(){return this.twoFactorService.hasMagicLinkSession()}clearMagicLinkSession(){this.twoFactorService.clearMagicLinkSession()}};wc=Tc,wc.version=S,exports.ADDRESS_CHANGE_PROOF_REQUIRED_ERROR_ID=ft,exports.AGENT_TOOL_HEADER_KEY=y,exports.ANTI_BOT_ACTION=x,exports.ANTI_BOT_FAILED_ERROR_ID=$e,exports.ANTI_BOT_HEADER_KEY=v,exports.ANTI_BOT_PROVIDER_FAILED_ERROR_ID=nt,exports.ANTI_BOT_PROVIDER_MISSING_ERROR_ID=tt,exports.ANTI_BOT_REQUIRED_ERROR_ID=Qe,exports.ANTI_BOT_SOLVE_FAILED_ERROR_ID=rt,exports.ANTI_BOT_UNAVAILABLE_ERROR_ID=et,exports.APP_ID_HEADER_KEY=m,exports.APP_SECRET_NAMES=vt,exports.AUTHORIZATION_HEADER_KEY=h,exports.AppAPI=en,exports.AuthAPI=ln,exports.AuthService=co,exports.CLIAuthAPI=un,exports.DEFAULT_GROUP_NAME=E,exports.DEFAULT_SCOPES=w,exports.DEFAULT_UPGRADE_FACTORS=xo,exports.DEVICE_ID_HEADER_KEY=g,exports.DEVICE_PROOF_HEADER_KEY=b,exports.DEVICE_TYPE_HEADER_KEY=_,exports.DeviceKeyErrorId=Bn,exports.ENTERPRISE_CONNECTION_AMBIGUOUS_ERROR_ID=st,exports.ENTERPRISE_EMAIL_INVALID_ERROR_ID=it,exports.ENTERPRISE_NO_CONNECTION_ERROR_ID=ot,exports.ENTERPRISE_START_INPUT_ERROR_ID=at,exports.ERROR_MESSAGE_MAX_LENGTH=ae,exports.FETCH_PRIORITY_OIDC=Hn,exports.FETCH_PRIORITY_UPGRADE=Un,exports.FetchMiddlewareContractError=Wn,exports.INSUFFICIENT_USER_AUTHENTICATION=Te,exports.InvitationAPI=dn,exports.InvitationService=lo,exports.M2MClient=ur,exports.M2MConfigError=ar,exports.M2MError=H,exports.M2MErrorCodes=or,exports.M2MNetworkError=rr,exports.M2MTokenParseError=ir,exports.M2M_DEFAULTS=sr,exports.MASKED_SECRET_PREFIX=yt,exports.MINIMAL_DEFAULT_SCOPES=C,exports.OS=St,exports.PASSFLOW_CLOUD_URL=T,exports.PASSWORD_CHANGE_REQUIRED_ERROR_ID=Ze,exports.POPUP_HEIGHT=ee,exports.POPUP_POLL_INTERVAL_MS=te,exports.POPUP_TIMEOUT_MS=O,exports.POPUP_WIDTH=D,exports.Passflow=Tc,exports.PassflowAddressChangeProofRequiredError=gt,exports.PassflowAdminEndpointPaths=Ke,exports.PassflowEndpointPaths=z,exports.PassflowError=B,exports.PassflowEvent=G,exports.PassflowOidcError=U,exports.PassflowPasswordChangeRequiredError=ct,exports.PassflowRecoveryCodesStepUpRequiredError=ht,exports.PassflowRefreshError=Y,exports.PassflowSendLimitError=mt,exports.PassflowSmsQuotaExceededError=pt,exports.PopupClosedError=_e,exports.Providers=_t,exports.RECOVERABLE_COMMIT_ERROR_IDS=_a,exports.RECOVERY_CODES_STEP_UP_REQUIRED_ERROR_ID=dt,exports.REFRESH_AUTH_FAILURE_IDS=ji,exports.RefreshErrorId=J,exports.RequestMethod=Ge,exports.SDK_VERSION=S,exports.SERVICE_UNAVAILABLE_ERROR_ID=Ye,exports.SERVICE_UNAVAILABLE_MESSAGE=Xe,exports.SESSION_INVALIDATING_COMMIT_ERROR_IDS=va,exports.SETTINGS_MASKED_VALUE_UNKNOWN_ERROR_ID=bt,exports.SessionState=de,exports.SettingAPI=fn,exports.TOKEN_EXPIRY_BUFFER_SECONDS=ne,exports.TWO_FACTOR_SEND_LIMIT_ERROR_ID=ut,exports.TWO_FACTOR_SMS_QUOTA_EXCEEDED_ERROR_ID=lt,exports.TenantAPI=pn,exports.TenantService=fo,exports.TenantUserMembership=uo,exports.TokenCacheService=po,exports.TokenDeliveryMode=I,exports.TokenType=F,exports.TwoFactorApiClient=vn,exports.TwoFactorPolicy=Tt,exports.TwoFactorService=mo,exports.UPGRADE_REQUIRED=Ee,exports.USERNAME_MAX_LENGTH=ie,exports.USERNAME_MIN_LENGTH=re,exports.UpgradeAPI=yn,exports.UpgradeCancelledError=Oo,exports.UpgradeCommitInterruptedError=Ki,exports.UpgradeController=Ho,exports.UpgradeErrorIds=Q,exports.UpgradeFactorError=go,exports.UpgradeInsufficientError=Na,exports.UpgradeSessionChangedError=Fa,exports.UpgradeSignInRequiredError=ko,exports.UpgradeTransportError=$,exports.UpgradeUnavailableError=Pa,exports.UpgradeUnsatisfiableError=Po,exports.UserAPI=bn,exports.UserService=ho,exports.WebAdapter=ve,exports.classifyUpgradeError=Aa,exports.factorRegistry=So,exports.fetchRegistryState=nr,exports.getOSFromDeviceType=Ct,exports.invalidatesSessionOnCommit=Ma,exports.isEmailVerificationStep=Je,exports.isMaskedSecret=xt,exports.isRecoverableCommitFailure=ja,exports.isRetryableUpgradeKind=ba,exports.isTokenExpired=N,exports.isUpgradeCancelled=vs,exports.isUpgradeExhausted=ys,exports.isUpgradeInsufficient=bs,exports.isUpgradeSessionChanged=ws,exports.isUpgradeSignInRequired=Ss,exports.isUpgradeTransportError=wa,exports.isUpgradeTransportFailure=Ts,exports.isUpgradeUnavailable=Cs,exports.isUpgradeUnsatisfiable=xs,exports.isValidEmail=Ba,exports.isValidJWTFormat=Ra,exports.isValidPhoneNumber=Va,exports.isValidUsername=Ha,exports.parseChallengeBody=Ne,exports.parseChallengeHeader=Me,exports.parseToken=P,exports.parseUpgradeChallenge=Le,exports.passkeyFactor=bo,exports.pathWithParams=wt,exports.pushChallengeOf=Dn,exports.recoveryCodesFactor=yo,exports.registerFetchMiddleware=tr,exports.requiredAcrLevel=we,exports.resolveUpgradeDomain=qe,exports.sanitizeErrorMessage=za,exports.selectFactors=Do,exports.totpFactor=vo,exports.webAdapter=ye;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|