@passflow/core 0.27.0 → 0.28.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 +29 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -1
- package/dist/index.d.ts +9 -1
- package/dist/index.mjs +1096 -1079
- 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=`0.27.0`,d=`X-Passflow-Clientid`,f=`Authorization`,p=`X-Passflow-DeviceId`,m=`X-Passflow-DeviceType`,h=u,g=[`id`,`offline`,`openid`],_=[`id`,`offline`,`tenant`,`email`,`oidc`,`openid`,`access:tenant:all`],v=`https://auth.passflow.cloud`,y=`default`,b=500,x=600,S=100,C=6e4,w=30,T=3,E=30,D=200,O=[];for(let e=0;e<256;++e)O.push((e+256).toString(16).slice(1));function ee(e,t=0){return(O[e[t+0]]+O[e[t+1]]+O[e[t+2]]+O[e[t+3]]+`-`+O[e[t+4]]+O[e[t+5]]+`-`+O[e[t+6]]+O[e[t+7]]+`-`+O[e[t+8]]+O[e[t+9]]+`-`+O[e[t+10]]+O[e[t+11]]+O[e[t+12]]+O[e[t+13]]+O[e[t+14]]+O[e[t+15]]).toLowerCase()}var k=new Uint8Array(16);function te(){return crypto.getRandomValues(k)}function ne(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():re(e,t,n)}function re(e,t,n){e=e||{};let r=e.random??e.rng?.()??te();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 ee(r)}var ie=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 ae(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 A=class{constructor(e){this.storageManager=e}isTokenTypeExpired(e){let t=this.storageManager.getToken(e);if(!t)return!0;let n=M(t);return!n||j(n)}parseTokenType(e){let t=this.storageManager.getToken(e);if(t)return M(t)}};function j(e,t=30){return Math.floor(Date.now()/1e3)+t>e.exp}function M(e){let t=e.split(`.`)[1];if(!t)throw Error(`Invalid token string`);let n=t.replace(/-/g,`+`).replace(/_/g,`/`),r=ae(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`?ie(a.passflow_tm):void 0,a}var N=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}({}),P=function(e){return e.JsonBody=`json_body`,e.Cookie=`cookie`,e.Mobile=`mobile`,e.BFF=`bff`,e}({}),oe=function(e){return e.Unknown=`unknown`,e.Valid=`valid`,e.Invalid=`invalid`,e}({}),se=class{constructor(e){this.storageManager=e,this.mode=`json_body`,this.sessionState=`unknown`,this.isInitializedFlag=!1,this.STORAGE_PREFIX=`passflow_`,this.DELIVERY_MODE_KEY=`${this.STORAGE_PREFIX}delivery_mode`,this.SESSION_STATE_KEY=`${this.STORAGE_PREFIX}session_state`,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.clearPersistedMode(),this.clearPersistedSessionState()}loadPersistedMode(){try{let e=this.storageManager.storage.getItem(this.DELIVERY_MODE_KEY);e&&Object.values(P).includes(e)&&(this.mode=e,this.isInitializedFlag=!0)}catch{}}loadPersistedSessionState(){try{let e=this.storageManager.storage.getItem(this.SESSION_STATE_KEY);e&&Object.values(oe).includes(e)&&(this.sessionState=e)}catch{}}persistMode(){try{this.storageManager.storage.setItem(this.DELIVERY_MODE_KEY,this.mode)}catch{}}persistSessionState(){try{this.storageManager.storage.setItem(this.SESSION_STATE_KEY,this.sessionState)}catch{}}clearPersistedMode(){try{this.storageManager.storage.removeItem(this.DELIVERY_MODE_KEY)}catch{}}clearPersistedSessionState(){try{this.storageManager.storage.removeItem(this.SESSION_STATE_KEY)}catch{}}},F=class{constructor({storage:e,prefix:t}={}){this.keyStoragePrefix=``,this.scopes=`${this.keyStoragePrefix}tokens_scopes`,this.deviceId=`${this.keyStoragePrefix}passflowDeviceId`,this.invitationToken=`${this.keyStoragePrefix}passflowInvitationToken`,this.previousRedirectUrl=`${this.keyStoragePrefix}passflowPreviousRedirectUrl`,this.STORAGE_PREFIX=`passflow_`,this.ID_TOKEN_KEY=`${this.STORAGE_PREFIX}id_token`,this.CSRF_TOKEN_KEY=`${this.STORAGE_PREFIX}csrf_token`,this.DELIVERY_MODE_KEY=`${this.STORAGE_PREFIX}delivery_mode`,this.storage=e??localStorage,this.keyStoragePrefix=t?`${t}_`:``}saveTokens(e,t){let{id_token:n,access_token:r,refresh_token:i,scopes:a}=e;t===P.Cookie||t===P.BFF?n&&this.storage.setItem(this.ID_TOKEN_KEY,n):(n&&this.storage.setItem(this.getKeyForTokenType(N.id_token),n),r&&this.storage.setItem(this.getKeyForTokenType(N.access_token),r),i&&this.storage.setItem(this.getKeyForTokenType(N.refresh_token),i),a&&this.storage.setItem(this.scopes,a.join(`,`)))}getToken(e){let t=this.getKeyForTokenType(e);return this.storage.getItem(t)??void 0}getTokens(){let e=this.getDeliveryMode();if(e===P.Cookie||e===P.BFF){let e=this.storage.getItem(this.ID_TOKEN_KEY);return e?{id_token:e}:void 0}let t=this.storage.getItem(this.getKeyForTokenType(N.access_token));if(t)return{access_token:t,id_token:this.storage.getItem(this.getKeyForTokenType(N.id_token))??void 0,refresh_token:this.storage.getItem(this.getKeyForTokenType(N.refresh_token))??void 0,scopes:this.storage.getItem(this.scopes)?.split(`,`)??void 0}}getScopes(){return this.storage.getItem(this.scopes)?.split(`,`)??void 0}hasJsonModeTokens(){return!!this.storage.getItem(this.getKeyForTokenType(N.access_token))}hasCookieModeIdToken(){return!!this.storage.getItem(this.ID_TOKEN_KEY)}deleteToken(e){let t=this.getKeyForTokenType(e);this.storage.removeItem(t)}deleteTokens(){this.storage.removeItem(this.getKeyForTokenType(N.id_token)),this.storage.removeItem(this.getKeyForTokenType(N.access_token)),this.storage.removeItem(this.getKeyForTokenType(N.refresh_token)),this.storage.removeItem(this.scopes),this.clearIdToken(),this.clearDeliveryMode(),this.clearCsrfToken()}getDeviceId(){return this.storage.getItem(this.deviceId)??void 0}setDeviceId(e){this.storage.setItem(this.deviceId,e)}deleteDeviceId(){this.storage.removeItem(this.deviceId)}setInvitationToken(e){this.storage.setItem(this.invitationToken,e)}getInvitationToken(){return this.storage.getItem(this.invitationToken)??void 0}deleteInvitationToken(){this.storage.removeItem(this.invitationToken)}setPreviousRedirectUrl(e){this.storage.setItem(this.previousRedirectUrl,e)}getPreviousRedirectUrl(){return this.storage.getItem(this.previousRedirectUrl)??void 0}deletePreviousRedirectUrl(){this.storage.removeItem(this.previousRedirectUrl)}setDeliveryMode(e){try{this.storage.setItem(this.DELIVERY_MODE_KEY,e)}catch{}}getDeliveryMode(){try{let e=this.storage.getItem(this.DELIVERY_MODE_KEY);if(e&&Object.values(P).includes(e))return e}catch{}}clearDeliveryMode(){try{this.storage.removeItem(this.DELIVERY_MODE_KEY)}catch{}}getIdToken(){try{return this.storage.getItem(this.ID_TOKEN_KEY)??void 0}catch{return}}setIdToken(e){try{this.storage.setItem(this.ID_TOKEN_KEY,e)}catch{}}clearIdToken(){try{this.storage.removeItem(this.ID_TOKEN_KEY)}catch{}}getCsrfToken(){try{return this.storage.getItem(this.CSRF_TOKEN_KEY)??void 0}catch{return}}setCsrfToken(e){try{this.storage.setItem(this.CSRF_TOKEN_KEY,e)}catch{}}clearCsrfToken(){try{this.storage.removeItem(this.CSRF_TOKEN_KEY)}catch{}}tokenKeys(){return[this.getKeyForTokenType(N.id_token),this.getKeyForTokenType(N.access_token),this.getKeyForTokenType(N.refresh_token),this.scopes,this.ID_TOKEN_KEY,this.CSRF_TOKEN_KEY,this.DELIVERY_MODE_KEY]}getKeyForTokenType(e){return`${this.keyStoragePrefix}${e}`}},I=class{constructor(e){this.storageManager=e??new F}getDeviceId(){let e=this.storageManager.getDeviceId();if(!e){let e=this.generateUniqueDeviceId();return this.storageManager.setDeviceId(e),e}return e}generateUniqueDeviceId(){return ne()}},L=class extends Error{constructor(e=`Authentication popup was closed`){super(e),this.name=`PopupClosedError`}},ce=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?new Promise((e,t)=>{let n=Date.now(),r=setInterval(()=>{if(o.closed)clearInterval(r),t(new L);else if(Date.now()-n>6e4)clearInterval(r),o.close(),t(Error(`Authentication popup timed out`));else try{if(o.location.href.startsWith(a)){let t=o.location.search,n=o.location.hash;clearInterval(r),o.close(),e({callbackSearch:t,callbackHash:n})}}catch{}},100)}):(window.location.href=e,new Promise(()=>{}))}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`}},R=new ce,le=/^[0-9]+$/,ue=Object.freeze({unorderable:!1,zero:!1}),z=e=>le.test(e)?Number.parseInt(e,10):void 0,B=e=>{if(!e)return ue;let t=e.split(/\s+/).filter(e=>e!==``);if(t.length===0)return ue;let n=[];for(let e of t){let t=z(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}},de=e=>B(e).level,fe=`insufficient_user_authentication`,pe=`upgrade_required`,me=/([A-Za-z0-9!#$%&'*+\-.^_`|~]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]*))/g,he=e=>e.replace(/\\(.)/g,`$1`),ge=e=>{let t={};me.lastIndex=0;for(let n of e.matchAll(me)){let e=n[1];if(!e)continue;let r=n[2],i=n[3];t[e.toLowerCase()]=r===void 0?i??``:he(r)}return t},_e=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}},ve=e=>{let t=_e(e);return t.kind===`valid`?t.value:void 0},ye=(e,t)=>{if(!e||!/(^|[\s,])Bearer\b/i.test(e))return;let n=ge(e);if(n.error===`insufficient_user_authentication`)return{acrValues:n.acr_values||void 0,maxAge:ve(n.max_age),status:t}},be=(e,t)=>{if(!e||typeof e!=`object`)return;let n=e;if(n.error===`upgrade_required`)return{acrValues:typeof n.acr_values==`string`&&n.acr_values?n.acr_values:void 0,maxAge:ve(n.max_age),status:t}},xe=(e,t,n)=>({channel:e,acr:B(t.acrValues),maxAge:_e(n),raw:t.acrValues}),Se=e=>e?ge(e):{},Ce=(e,t)=>{let{status:n}=e;if(n!==401&&n!==403)return{diagnostics:[]};let r=t?.requireChallengeChannel===`header`,i=e.getHeader(`www-authenticate`),a=ye(i,n),o=r?void 0:be(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(xe(`header`,a,Se(i).max_age)),o){let t=e.body;l.push(xe(`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)},diagnostics:s}},we=(e,t,n)=>Ce({status:e,getHeader:t,body:n}).challenge,Te=`__passflowUpgradeTransaction`,Ee=`__passflowUpgradeReplayed`,De=(e,t)=>typeof e==`object`&&!!e&&e[t]===!0,Oe=e=>({...e??{},[Te]:!0}),ke=e=>De(e,Te),Ae=e=>({...e,[Ee]:!0}),je=e=>De(e,Ee),Me=function(e){return e.GET=`get`,e.POST=`post`,e.PUT=`put`,e.PATCH=`patch`,e.DELETE=`delete`,e}({}),V=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.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.cliAuthStatus=`/cli/auth/status/:sessionId`,e.cliAuthComplete=`/cli/auth/complete`,e.upgradeStart=`/auth/upgrade/start`,e}({}),Ne=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}({}),Pe=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}},Fe=e=>typeof e==`object`&&!!e&&e.email_verification_required===!0,H=class extends Error{constructor(e){super(),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()}},Ie=function(e){return e.google=`google`,e.facebook=`facebook`,e}({}),Le=Object.freeze([`debug_otp_code_for_registration`,`fcm_server_key`,`webpush_vapid_private_key`]),Re=`mask://`,ze=`error.server.update.settings.masked.value.unknown`,Be=e=>typeof e==`string`&&e.startsWith(`mask://`),Ve=function(e){return e.web=`web`,e.ios=`ios`,e.android=`android`,e}({});function He(e){return e}function Ue(e,t){let n=e;return Object.entries(t).forEach(([e,t])=>{n=n.replace(`:${e}`,t)}),n}var We=function(e){return e.Disabled=`disabled`,e.Optional=`optional`,e.Required=`required`,e}({}),Ge=3,Ke=1e3,qe=e=>t=>{let n=e.headers?.[t]??e.headers?.[t.toLowerCase()];return Array.isArray(n)?n.join(`, `):n},Je=e=>we(e.status,qe(e),e.data),Ye=e=>Je(e)!==void 0,Xe=e=>e?.includes(V.refresh)??!1,Ze=e=>e?.includes(`logout`)??!1,Qe=`__passflowOwnBearer`,$e=e=>typeof e==`object`&&!!e&&e[Qe]===!0,et=e=>e?{headers:{[f]:`Bearer ${e}`},[Qe]:!0}:{},tt=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/`],this.protectedEndpoints=[`logout`,`refresh`,`upgrade`];let{url:r,appId:i,keyStoragePrefix:a}=e;this._platform=e.platform??R,this.url=r||`https://auth.passflow.cloud`,this.upgradeDomain=Pe(r),this.storageManager=t??new F({prefix:a??``}),this.deviceService=n??new I(this.storageManager),this.tokenService=new A(this.storageManager),this.tokenDeliveryManager=new se(this.storageManager),i&&(this.appId=i,this.defaultHeaders={...this.defaultHeaders,[d]:i});let o=this.deviceService.getDeviceId();this.defaultHeaders={...this.defaultHeaders,[p]:o,[m]:this._platform.getDeviceType()},this.detectCookieSupport(),this.instance=c.default.create({baseURL:this.url,headers:{...this.defaultHeaders}}),this.instance.interceptors.request.use(async e=>{if(this.isNonAuthEndpoint(e.url)||$e(e))return e;if(this.tokenDeliveryManager.isCookieMode()){e.withCredentials=!0;let t=this.storageManager.getCsrfToken();return t&&(e.headers[`X-CSRF-Token`]=t),e}if(Xe(e.url))return e;let t=this.storageManager.getTokens();if(!t?.access_token)return e;let n=t.access_token;if(this.refreshHandler&&t.refresh_token&&!Ze(e.url)){let e=M(t.access_token);if(j(e,30)){let t=!j(e,0);try{n=(await this.refreshHandler({trigger:`pre-request`,allowStale:t}))?.access_token??n}catch(e){if(!t)throw e}}}return e.headers[f]=`Bearer ${n}`,e}),this.instance.interceptors.response.use(e=>e,async e=>{if(e.response?.status!==401||Xe(e.config?.url)||$e(e.config)||this.isUpgradeTransactionError(e)||this.tokenDeliveryManager.setSessionInvalid(),e.response&&this.upgradeHandler){let t=Je(e.response);if(t)try{return await this.upgradeHandler(e,t)}catch(t){if(t!==e)throw t}}return e.response?.status===429?await this.handleRateLimitError(e):this.handleAxiosError(e)})}isUpgradeTransactionError(e){return ke(e.config)||e.response!==void 0&&Ye(e.response)}setUpgradeInterceptor(e){this.upgradeHandler=e}setRefreshHandler(e){this.refreshHandler=e}replay(e){return this.instance.request(e)}isProtectedEndpoint(e){return this.protectedEndpoints.some(t=>e?.includes(t))}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||Xe(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>=Ge)return Promise.reject(e);let i=Ke*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(!e.response)return Promise.reject(e);let t=e.response.status,n=e.response.data;if(`error`in n&&typeof n.error==`object`&&n.error!==null){let{error:e}=n;return Promise.reject(new H(e))}return Promise.reject(new H({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(Me.GET,e,t)}post(e,t,n){return this.send(Me.POST,e,{data:t,...n})}put(e,t,n){return this.send(Me.PUT,e,{data:t,...n})}patch(e,t,n){return this.send(Me.PATCH,e,{data:t,...n})}delete(e,t){return this.send(Me.DELETE,e,t)}setAppId(e){this.appId=e,this.defaultHeaders={...this.defaultHeaders,[d]:e},this.instance.defaults.headers.common[d]=e}},nt=class{constructor(e,t,n){this.axiosClient=new tt(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getAppSettings(){return this.axiosClient.get(V.appSettings)}},rt={withCredentials:!0},it=15e3,at=`Sign-in failed. Start again.`,ot=`Something went wrong. Try again later.`,st=(e,t,n,r)=>{if(e instanceof H)return e;let i=e?.response?.data?.error;return new H({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()})},ct=class{constructor(e,t,n){this.axiosClient=new tt(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}refreshToken(e,t,n,r){let i={access:n,scopes:t,...r?{upgrade:r}:{}},a={headers:{[f]:`Bearer ${e}`}};return this.axiosClient.post(V.refresh,i,r?Oe(a):a)}signIn(e,t,n){let r={...e,device:t,os:n};return this.axiosClient.post(V.signin,r,rt)}signUp(e){let{create_tenant:t,anonymous:n}=e,r={...e,create_tenant:t??!1,anonymous:n??!1};return this.axiosClient.post(V.signup,r,rt)}async pkceExchange(e,t){try{return await this.axiosClient.post(V.pkceExchange,{authz_code:e,verifier:t},rt)}catch(e){throw st(e,V.pkceExchange,`error.pkce.exchange`,at)}}async passwordlessSignIn(e,t,n){let{create_tenant:r}=e,i={...e,create_tenant:r??!1,device:t,os:n};try{return await this.axiosClient.post(V.passwordless,i)}catch(e){throw st(e,V.passwordless,`error.passwordless.start`,ot)}}async passwordlessSignInComplete(e){try{return await this.axiosClient.post(V.passwordlessComplete,e,rt)}catch(e){throw st(e,V.passwordlessComplete,`error.passwordless.complete`,ot)}}async passwordlessStatus(e,t){try{return await this.axiosClient.post(V.passwordlessStatus,e,{...rt,timeout:it,signal:t?.signal})}catch(e){throw st(e,V.passwordlessStatus,`error.passwordless.status`,at)}}async checkRedirectUrl(e){try{return(await this.axiosClient.post(V.redirectCheck,{redirect_url:e})).redirect_url}catch(e){throw st(e,V.redirectCheck,`error.redirect.check`,ot)}}async passwordlessApprovalInfo(e){try{return await this.axiosClient.post(V.passwordlessApprovalInfo,e)}catch(e){throw st(e,V.passwordlessApprovalInfo,`error.passwordless.approval`,ot)}}async passwordlessApprovalDecide(e){try{return await this.axiosClient.post(V.passwordlessApprovalDecide,e)}catch(e){throw st(e,V.passwordlessApprovalDecide,`error.passwordless.approval`,ot)}}validateEmailCode(e){return this.axiosClient.post(V.passkeyValidate,{challenge_id:e.challenge_id,otp:e.otp},rt)}logOut(e,t,n=!1){let r=n?void 0:{refresh_token:t,device:e},i=n?Ne.logout:V.logout;return this.axiosClient.post(i,r)}validateSession(){return this.axiosClient.get(V.validateSession)}sendPasswordResetEmail(e){return this.axiosClient.post(V.sendPasswordResetEmail,e)}resetPassword(e,t,n,r){let i={password:e,scopes:t,...r?{code_challenge:r}:{}};return this.axiosClient.post(V.resetPassword,i,{headers:{[f]:`Bearer ${n}`,[d]:void 0}})}passkeyRegisterStart(e,t,n,r=!1){let{create_tenant:i}=e,a={...e,create_tenant:i??!1,device:t,os:n},o=r?Ne.passkeyRegisterStart:V.passkeyRegisterStart;return this.axiosClient.post(o,a)}passkeyRegisterComplete(e,t,n,r=!1){let i={challenge_id:n,device:t,passkey_data:e},a=r?Ne.passkeyRegisterComplete:V.passkeyRegisterComplete;return this.axiosClient.post(a,i,rt)}passkeyAuthenticateStart(e,t,n,r=!1){let i={...e,user_id:e.user_id??``,device:t,os:n},a=r?Ne.passkeyAuthenticateStart:V.passkeyAuthenticateStart;return this.axiosClient.post(a,i)}passkeyAuthenticateComplete(e,t,n,r=!1){let i={challenge_id:n,device:t,passkey_data:e},a=r?Ne.passkeyAuthenticateComplete:V.passkeyAuthenticateComplete;return this.axiosClient.post(a,i,rt)}passkeyValidate(e,t,n,r=!1,i){let a={otp:e,device:t,challenge_id:n},o=V.passkeyValidate;!i&&r&&(o=Ne.passkeyValidate);let s=i?{[d]:i}:{};return this.axiosClient.post(o,a,{headers:s})}},lt=class{constructor(e,t,n){this.axiosClient=new tt(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getCLIAuthStatus(e){let t=Ue(V.cliAuthStatus,{sessionId:e});return this.axiosClient.get(t)}completeCLIAuth(e){return this.axiosClient.post(V.cliAuthComplete,e)}},ut=class{constructor(e,t,n){this.axiosClient=new tt(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}requestInviteLink(e){return this.axiosClient.post(V.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=Ue(V.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=Ue(V.invitationDelete,{invitationID:e});return this.axiosClient.delete(t)}resendInvitation(e){let t=Ue(V.invitationResend,{invitationID:e});return this.axiosClient.post(t,{})}getInvitationLink(e){let t=Ue(V.invitationGetLink,{invitationID:e});return this.axiosClient.get(t)}},dt=class{constructor(e,t,n){this.axiosClient=new tt(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getSettingsAll(){return this.axiosClient.get(V.settingsAll)}getPasswordPolicySettings(){return this.axiosClient.get(V.settingsPasswordPolicy)}getPasskeySettings(){return this.axiosClient.get(V.settingsPasskey)}},ft=class{constructor(e,t,n){this.axiosClient=new tt(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}joinInvitation(e,t){let n={invite_token:e,scopes:t};return this.axiosClient.post(V.joinInvitation,n)}createTenant(e){let t={name:e};return this.axiosClient.post(V.tenantPath,t)}getTenantDetails(e){let t=`${V.tenantPath}/${e}`;return this.axiosClient.get(t)}updateTenant(e,t){let n=`${V.tenantPath}/${e}`,r={name:t};return this.axiosClient.put(n,r)}deleteTenant(e){let t=`${V.tenantPath}/${e}`;return this.axiosClient.delete(t)}getUserTenantMembership(){return this.axiosClient.get(V.tenantPath)}createGroup(e,t){let n=`${V.tenantPath}/${e}/group`,r={name:t};return this.axiosClient.post(n,r)}getGroupInfo(e,t){let n=`${V.tenantPath}/${e}/group/${t}`;return this.axiosClient.get(n)}updateGroup(e,t,n){let r=`${V.tenantPath}/${e}/group/${t}`,i={name:n};return this.axiosClient.put(r,i)}deleteGroup(e,t){let n=`${V.tenantPath}/${e}/group/${t}`;return this.axiosClient.delete(n)}addUserToGroup(e,t,n,r){let i=`${V.tenantPath}/${e}/group/${t}/add`,a={user_id:n,role:r};return this.axiosClient.post(i,a)}removeUserRolesFromGroup(e,t,n,r){let i=`${V.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=`${V.tenantPath}/${e}/group/${t}/change`,a={user_id:n,roles:r};return this.axiosClient.post(i,a)}deleteUserFromGroup(e,t,n){let r=`${V.tenantPath}/${e}/group/${t}/${n}`;return this.axiosClient.delete(r)}getRolesForTenant(e){let t=`${V.tenantPath}/${e}/role`;return this.axiosClient.get(t)}createRoleForTenant(e,t){let n=`${V.tenantPath}/${e}/role`,r={name:t};return this.axiosClient.post(n,r)}updateRole(e,t,n){let r=`${V.tenantPath}/${e}/role/${t}`,i={name:n};return this.axiosClient.put(r,i)}deleteRole(e,t){let n=`${V.tenantPath}/${e}/role/${t}`;return this.axiosClient.delete(n)}deleteUserFromTenant(e,t){let n=`${V.tenantPath}/${e}/user/${t}`;return this.axiosClient.delete(n)}getGroupInvitations(e,t,n,r){let i=`${V.tenantPath}/${e}/group/${t}/invitations`;return this.axiosClient.get(i,{params:{limit:n,skip:r}})}getTenantInvitations(e,t,n){let r=`${V.tenantPath}/${e}/invitations`;return this.axiosClient.get(r,{params:{limit:t,skip:n}})}invalidateInviteById(e,t,n){let r=`${V.tenantPath}/${e}/group/${t}/invite/${n}`;return this.axiosClient.delete(r)}invalidateInviteByEmail(e,t,n){let r=`${V.tenantPath}/${e}/group/${t}/invite/email/${n}`;return this.axiosClient.delete(r)}},pt=e=>e?{headers:{Authorization:`Bearer ${e}`}}:{},mt=e=>({withCredentials:!0,...pt(e)}),ht=({qr_code_image:e,qr_code:t,...n})=>({...n,qr_code:(t??e??``).replace(/^data:image\/png;base64,/,``)}),gt={"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`},_t=class{constructor(e,t,n){this.axiosClient=new tt(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getStatus(e){return this.axiosClient.get(V.twoFactorStatus,et(e))}async beginSetup(e){return ht(await this.axiosClient.post(V.twoFactorSetupBegin,{},et(e)))}confirmSetup(e,t){return this.axiosClient.post(V.twoFactorSetupConfirm,e,et(t))}async getEnrollment(e){return(await this.axiosClient.get(V.twoFactorEnrollment,et(e))).enrollment}sendSetupLink(e){return this.axiosClient.post(V.twoFactorEnrollmentEmailLink,void 0,et(e))}async beginEnrollment(e){return ht(await this.axiosClient.post(V.twoFactorEnrollmentBegin,void 0,et(e)))}confirmEnrollment(e,t){return this.axiosClient.post(V.twoFactorEnrollmentConfirm,t,et(e))}verify(e){let{tfa_token:t,code:n,trust_device:r}=e;return this.axiosClient.post(V.twoFactorVerify,{code:n,...r?{trust_device:!0}:{}},mt(t))}useRecoveryCode(e){let{tfa_token:t,recovery_code:n,trust_device:r}=e;return this.axiosClient.post(V.twoFactorRecovery,{recovery_code:n,...r?{trust_device:!0}:{}},mt(t))}disable(e){return this.axiosClient.delete(V.twoFactor,{data:e})}regenerateRecoveryCodes(e){return this.axiosClient.post(V.twoFactorRegenerateCodes,e)}validateTwoFactorSetupMagicLink(e){let t=`${V.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}}).catch(e=>{if(e instanceof H)return{success:!1,error:{code:gt[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.`}}getAvailableMethods(){return this.axiosClient.get(V.TwoFactorMethodsAvailable)}getRegisteredMethods(){return this.axiosClient.get(V.TwoFactorMethodsRegistered)}startMethodSetup(e,t){return this.axiosClient.post(V.TwoFactorSetupStart,{...t,method:e})}completeMethodSetup(e,t){return this.axiosClient.post(V.TwoFactorSetupComplete,{...t,method:e})}removeMethod(e){let t=Ue(V.TwoFactorMethodRemove,{id:e});return this.axiosClient.delete(t)}requestChallenge(e,t){return this.axiosClient.post(V.TwoFactorChallenge,e,pt(t))}verifyV2(e,t){let{trust_device:n,...r}=e;return this.axiosClient.post(V.TwoFactorVerifyV2,{...r,...n?{trust_device:!0}:{}},mt(t))}switchToAlternative(e,t){return this.axiosClient.post(V.TwoFactorAlternative,e,pt(t))}async getTrustedDevices(){return(await this.axiosClient.get(V.TwoFactorTrustedDevices,{withCredentials:!0}))?.devices??[]}revokeTrustedDevice(e){let t=Ue(V.TwoFactorTrustedDeviceRevoke,{id:e});return this.axiosClient.delete(t)}},vt=class{constructor(e,t,n){this.axiosClient=new tt(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}startUpgrade(e){return this.axiosClient.post(V.upgradeStart,e,Oe({}))}},yt=class{constructor(e,t,n){this.axiosClient=new tt(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getUserPasskeys(){return this.axiosClient.get(V.userPasskey)}renameUserPasskey(e,t){return this.axiosClient.patch(`${V.userPasskey}/${t}`,{name:e})}deleteUserPasskey(e){return this.axiosClient.delete(`${V.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(V.addUserPasskey,a)}addUserPasskeyComplete(e,t,n){return this.axiosClient.post(V.completeAddUserPasskey,{challenge_id:n,device:t,passkey_data:e})}},bt=10,xt=20,St=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}},Ct=[],wt=0,Tt=!1,Et,Dt,Ot=(e,t)=>e.priority-t.priority||e.seq-t.seq,kt=()=>typeof globalThis>`u`?void 0:globalThis,At=async(e,t,n,r)=>{if(t>=e.length){let e=Et;if(!e)throw Error(`Passflow fetch registry: no captured fetch to delegate to.`);return e(n,r)}let i=e[t];if(!i)return At(e,e.length,n,r);let a=!1,o=await i.middleware((n,r)=>(a=!0,At(e,t+1,n,r)),n,r);if(!a)throw new St(i.name);return o},jt=()=>{let e=kt();if(!e||typeof e.fetch!=`function`)return!1;let t=e.fetch.bind(e),n=(e,t)=>At([...Ct].sort(Ot),0,e,t);return Et=t,Dt=n,e.fetch=n,Tt=!0,!0},Mt=()=>{let e=kt();e&&Dt&&e.fetch===Dt&&(Et&&(e.fetch=Et),Tt=!1,Dt=void 0,Et=void 0)},Nt=(e,t)=>{if(!Tt&&!jt())return()=>{};let n={middleware:e,name:t.name,priority:t.priority,seq:wt++};Ct.push(n);let r=!1;return()=>{r||(r=!0,Ct=Ct.filter(e=>e!==n),Ct.length===0&&Mt())}},Pt=()=>{let e=kt();return{installed:Tt,names:[...Ct].sort(Ot).map(e=>e.name),foreignPatch:Tt&&!!e&&!!Dt&&e.fetch!==Dt}},U=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}},Ft=class extends U{constructor(e,t){super({code:`temporarily_unavailable`,message:e,status:0,cause:t}),this.name=`M2MNetworkError`}},It=class extends U{constructor(e,t){super({code:`invalid_request`,message:e,status:400,cause:t}),this.name=`M2MTokenParseError`}},Lt=class extends U{constructor(e){super({code:`invalid_request`,message:e,status:400}),this.name=`M2MConfigError`}},Rt={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`},zt={TOKEN_ENDPOINT:`/oauth2/token`,TIMEOUT:1e4,RETRIES:3,RETRY_DELAY:1e3,REFRESH_THRESHOLD:30,CONTENT_TYPE:`application/x-www-form-urlencoded`},Bt=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()}},Vt={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}},Ht=class{constructor(e){if(!e.url)throw new Lt(`M2M client requires a URL`);if(!e.clientId)throw new Lt(`M2M client requires a clientId`);if(!e.clientSecret)throw new Lt(`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??zt.REFRESH_THRESHOLD,timeout:e.timeout??zt.TIMEOUT,retries:e.retries??zt.RETRIES,retryDelay:e.retryDelay??zt.RETRY_DELAY,retryStrategy:e.retryStrategy,cache:e.cache,onTokenRequest:e.onTokenRequest,onTokenResponse:e.onTokenResponse,onError:e.onError},this.cache=e.cache??new Bt,this.retryStrategy=e.retryStrategy??Vt,this.tokenEndpoint=`${t}${zt.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":zt.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=U.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 Ft(`Request timed out after ${this.config.timeout}ms`):e instanceof TypeError&&e.message.includes(`fetch`)?new Ft(`Network error: ${e.message}`,e):e instanceof U?e:U.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 U))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 U({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 It(`Invalid JWT format: expected 3 parts`);let n=t[1];if(!n)throw new It(`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 It?e:new It(`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":zt.CONTENT_TYPE},body:n.toString()});if(!e.ok&&e.status!==200){let t=await e.json().catch(()=>({}));throw U.fromOAuthError({error:t.error||`server_error`,error_description:t.error_description||`Token revocation failed`},e.status)}this.clearCache()}catch(e){throw e instanceof U?e:U.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}},Ut=`error`,Wt=new WeakMap,Gt=(e,t)=>{if(typeof t!=`object`&&typeof t!=`function`||t===null)return!0;let n=Wt.get(e);return n||(n=new WeakSet,Wt.set(e,n)),!n.has(t)&&(n.add(t),!0)},W=(e,t)=>Gt(e,t.originalError)?(e.notify(Ut,t),!0):!1,Kt=`passflow-refresh`,qt=`passflow-refresh-takeover`,Jt=`passflow-auth`,Yt=Object.freeze([1e3,3e3,1e4,3e4,6e4]),Xt=.2,Zt=6e5,Qt=5e3,G=2e4,$t=2e4,en=1e3,tn=2e3,nn=1e3,rn=1e4,an=5e3;function on(e){let t=e?`:${e}`:``;return{lock:`${Kt}${t}`,takeoverLock:`${qt}${t}`,channel:`${Jt}${t}`}}function K(e){return typeof e==`string`&&e!==``?e:void 0}function sn(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function cn(e){return typeof e==`object`&&!!e}function ln(e,t){for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function un(e){if(!cn(e))return null;let t=Array.isArray(e.scopes)?e.scopes.filter(e=>typeof e==`string`):void 0;return ln({},{access_token:K(e.access_token),refresh_token:K(e.refresh_token),id_token:K(e.id_token),scopes:Array.isArray(e.scopes)&&t?.length===e.scopes.length?t:void 0})}function dn(e){if(!cn(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||sn(r)===void 0||typeof i!=`number`||!Number.isFinite(i)||i<0?null:ln({kind:t,attempt:n,nextAt:r,strikes:i},{from:K(e.from),failingSince:sn(e.failingSince)})}function fn(e){return ln({},{fp:K(e.fp),sub:K(e.sub),sid:K(e.sid),iat:sn(e.iat)})}function pn(e){if(!cn(e))return null;let t=e;if(t.v!==void 0&&t.v!==1)return null;let n=K(t.tabId);if(!n)return null;switch(t.type){case`tokens-refreshed`:{let e=un(t.tokens),r=K(t.from),i=K(t.to);return!e||!r||!i?null:ln({type:t.type,tabId:n,tokens:e,from:r,to:i},{fromIat:sn(t.fromIat),fromSid:typeof t.fromSid==`string`?t.fromSid:void 0,sentAt:sn(t.sentAt)})}case`session-refreshed`:{let e=sn(t.at);return e===void 0?null:ln({type:t.type,tabId:n,at:e},{sub:K(t.sub)})}case`still-refreshing`:{let e=t.retry===void 0?null:dn(t.retry);return e?{type:t.type,tabId:n,retry:e}:{type:t.type,tabId:n}}case`retry-scheduled`:{let e=dn(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,...fn(t)};case`rate-limited`:{let e=sn(t.until);return e===void 0?null:{type:t.type,tabId:n,until:e}}case`refresh-failed`:{let e=K(t.from);return e?{type:t.type,tabId:n,message:typeof t.message==`string`?t.message:``,from:e}:null}default:return null}}function mn(e,t){let n={v:1,tabId:e};if(t.type===`retry-scheduled`){let{retry:e,...r}=t;return ln(n,{...r,...e})}return ln(n,{...t})}var hn=`[passflow] navigator.locks or BroadcastChannel is unavailable (they need a secure context); each tab refreshes on its own, with the save checks only`,gn={now:()=>Date.now(),random:()=>Math.random(),setTimeout:(e,t)=>{let n=setTimeout(e,t);return n.unref?.(),()=>clearTimeout(n)}};function _n(){let e=globalThis.crypto;return typeof e?.randomUUID==`function`?e.randomUUID():`tab-${Math.random().toString(36).slice(2)}-${Date.now()}`}function vn(e){return e?{now:()=>e.now(),setTimeout:(t,n)=>e.setTimeout(t,n),random:e.random?()=>e.random?.()??Math.random():gn.random}:gn}function yn(e){return typeof window<`u`&&typeof document<`u`&&e.getDeviceType()===`web`}function bn(e){try{return e.storageSharedAcrossTabs===!0}catch{return!1}}function xn(){try{let e=globalThis.navigator?.locks;return e&&typeof e.request==`function`?e:void 0}catch{return}}function Sn(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 Cn(e){return{transports:null,names:on(e),clock:gn,warnOnFirstCycle:!1}}function wn(e,t,n,r){let i=on(n),a=yn(t),o=a?Sn(r.tokenKeys):void 0,s=e=>{let t={transports:null,names:i,clock:gn,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??_n()},names:i,clock:vn(e.clock),warnOnFirstCycle:!1};return e.onStorageChange&&(t.onStorageChange=e.onStorageChange),t}if(e===`none`||!a||!bn(t))return s(!1);let c=xn();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:_n()},names:i,clock:gn,warnOnFirstCycle:!1};return o&&(u.onStorageChange=o),u}var Tn=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`,En=32,Dn=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+=Tn.charAt(r>>2),t+=Tn.charAt((r&3)<<4|(i??0)>>4),i!==void 0&&(t+=Tn.charAt((i&15)<<2|(a??0)>>6)),a!==void 0&&(t+=Tn.charAt(a&63))}return t},On=()=>{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},kn=async e=>{let t=await On().subtle.digest(`SHA-256`,new TextEncoder().encode(e));return Dn(new Uint8Array(t))},An=async()=>{let e=Dn(On().getRandomValues(new Uint8Array(En)));return{verifier:e,challenge:await kn(e)}},jn=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 Mn(){return new jn}var Nn=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 Pn(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 Fn(e,t){if(typeof e==`number`)return!Number.isFinite(e)||e<0?void 0:Math.min(Zt,Math.floor(e)*1e3);if(typeof e!=`string`)return;let n=e.trim();if(n===``)return;if(/^\d+$/.test(n))return Math.min(Zt,Number.parseInt(n,10)*1e3);if(!/[a-z]/i.test(n))return;let r=Date.parse(n);if(!Number.isNaN(r))return Math.min(Zt,Math.max(0,r-t))}function In(e){return typeof e==`number`&&Number.isInteger(e)&&e>=100&&e<=599?e:void 0}function Ln(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 Rn(e,t=Date.now()){if(typeof e!=`object`||!e)return{kind:`transient`};let n=e,r=Ln(n),i=In(n.response?.status)??In(n.status),a={};if(i!==void 0&&(a.status=i),r!==void 0&&(a.id=r),r===`error.token.blocked`)return{kind:`blocked`,...a};if(r!==void 0&&Nn.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=Fn(n.retryAfter??Pn(n.response?.headers),t);return o===void 0?{kind:`transient`,...a}:{kind:`transient`,...a,retryAfterMs:o}}function zn(e,t,n){let r=Yt.length,i=Yt[(Number.isFinite(e)?Math.min(Math.max(Math.floor(e),1),r):1)-1]??Yt[r-1]??6e4,a=Number.isFinite(t)?Math.min(Math.max(t,0),.999):0,o=i+Math.floor(i*Xt*a);return Math.max(o,n!==void 0&&Number.isFinite(n)?Math.min(Math.max(n,0),Zt):0)}var Bn={onGranted:()=>!1,onLockLost:()=>void 0,onMessage:()=>void 0};function Vn(e){let{locks:t,channel:n,tabId:r,names:i,clock:a}=e,o=Bn,s=null,c=null,l=null,u=null,d=null,f=null,p=0,m,h=!1,g=!1,_=e=>{g||n.postMessage(mn(r,e))},v=()=>s!==null&&c===null,y=()=>{f?.(),f=null},b=e=>{p=Math.max(p,e),y(),f=a.setTimeout(()=>{f=null,O()},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())},Qt)},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()})},O=()=>{if(!v())return;let e=s;t.request(i.takeoverLock,{ifAvailable:!0},t=>{if(s===e&&v()){if(t===null)b(a.now()+G);else return _({type:`takeover`}),new Promise(t=>{u=t,e&&(e.dead=!0,e.abort.abort()),D(!0)})}}).catch(()=>{v()&&b(a.now()+G)})},ee=e=>{if(g)return;let t=pn(e.data);if(t&&t.tabId!==r){switch(t.type){case`still-refreshing`:h=!0,v()&&(b(a.now()+G),t.retry&&b(t.retry.nextAt+G));break;case`takeover`:h=!0,v()&&b(a.now()+G);break;case`retry-scheduled`:h=!0,v()&&b(Math.max(a.now(),t.retry.nextAt)+G);break;case`rate-limited`:v()&&b(t.until+G)}o.onMessage(t)}};return n.addEventListener(`message`,ee),{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()+G,e??0)),D(!1))},release:C,post:_,setRetryInfo:e=>{m=e},foreignHolderHeard:()=>h,dispose:()=>{g||(C(),g=!0,n.removeEventListener(`message`,ee),n.close())}}}function Hn(e=`local`){let t=Bn,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 q={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`},Un={"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},Wn={"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`},J=class extends H{constructor(e,t={}){super({id:e,message:t.message??Wn[e],status:Un[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)}},Gn=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 Kn(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 qn(e){return typeof e==`string`&&e!==``?e:void 0}function Y(e){let t=Kn(e);if(!e||!t)return;let n={};try{let t=M(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=qn(n.sub),o=qn(n.sid);return a!==void 0&&(i.sub=a),o!==void 0&&(i.sid=o),r!==void 0&&(i.iat=r),i}var Jn=`[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 Yn(e=e=>Mn().warn(e)){let t=new Map,n=new Set,r=!1,i=[],a=!1,o=()=>{a||(a=!0,e(Jn))},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 Xn=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}},Zn=class extends Error{constructor(){super(`The shared token storage holds another user's tokens`),this.name=`IdentityChanged`}};function Qn(e){if(e)try{let t=M(e).sub;return typeof t==`string`&&t!==``?t:void 0}catch{return}}function X(e){return Qn(e?.access_token)??Qn(e?.refresh_token)??Qn(e?.id_token)}function $n(e,t){return!t||e.iat===void 0||t.iat===void 0?!1:e.sid===t.sid&&e.iat<t.iat}function er(e){return typeof e==`object`&&!!e}function tr(e){let{storage:t,cache:n,schedule:r}=e,i=e.identity??(()=>void 0),a=e.warn??(e=>Mn().warn(e)),o=e.lineage??Yn(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=Kn(n)??``;return r!==c?.fp&&(c={fp:r,seq:l}),e},b=()=>Y(n.getTokens()?.refresh_token),x=()=>i()??X(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=>{let t=x();return d.some(n=>n.seq>e&&(!n.sub||!t||n.sub===t))},T=()=>{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}},E=()=>{if(!S())return`end`;let e=c?.seq??0,t=T();return w(t?Math.min(e,t.seq):e)?`end`:t?C(t)?`keep`:`end`:s?`wait`:`end`},D=()=>{h?.(),h=void 0},O=(e=!1)=>{let t=E();t===`wait`&&e&&(t=`end`),t!==`wait`&&D(),t===`wait`&&!h&&(h=r(()=>{h=void 0,y()?.refresh_token?A():O(!0)===`end`&&s?.(`emptied`)},tn));let n=t===`keep`?T():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},ee=e=>e.held!==void 0&&b()?.fp===e.held.cachedFp,k=e=>{let t=b();return!!t&&!o.isRetired(t)&&!o.isEnded(t)&&o.isAfter(t,e)},te=e=>{if(!k(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},ne=(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),re=e=>{let t=b();t&&t.fp!==Kn(e.refresh_token)&&o.retire(t),n.setTokensCache(e)},ie=e=>{let t=y(),n=t?.refresh_token;if(n===e.refreshToken)return null;if(!t||!n)return O()===`end`?{kind:`ended`,cause:`emptied`}:{kind:`superseded`,adopted:!1};let r=Qn(t.access_token)??Qn(n);if(e.sub&&r&&e.sub!==r)return{kind:`identity-changed`,saved:!1};let i=Y(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 ne(i,a)||i?.fp===a?.fp&&!o.isRetired(i)?(re(t),{kind:`superseded`,adopted:!0}):{kind:`superseded`,adopted:!1}},ae=e=>C(e)?{kind:`superseded`,adopted:!1}:{kind:`ended`,cause:`ended`},A=()=>{let t=y();if(!t?.refresh_token){O()===`end`&&s?.(`emptied`);return}D();let n=i(),r=X(t);n&&r&&n!==r?s?.(`identity-changed`):e.onStoredSessionSeen?.()},j=!!s||!!e.onStoredSessionSeen,M=j&&e.onStorageChange?e.onStorageChange(A):void 0,N=j&&e.onWake?e.onWake(A):void 0,P=()=>{let e=y();if(!e?.refresh_token){if(O()===`end`)throw new Xn(`emptied`);return`held`}let t=n.getTokens();if(e.refresh_token===t?.refresh_token)return`send`;let r=i()??X(t),a=X(e);if(r&&a&&r!==a)throw new Zn;let s=Y(e.refresh_token);if(o.isEnded(s)){if(s&&C(s))return`held`;throw new Xn(`ended`)}let c=Y(t?.refresh_token);return ne(s,c)?(re(e),`adopted`):s&&c&&s.sid!==c.sid?`send`:s&&k(s)?`held`:`send`},oe=e=>{let t=i(),r=Qn(e);if(t&&r&&t!==r)return{kind:`identity-changed`};let a=Y(e)??{fp:e};if(o.isEnded(a))return C(a)?{kind:`superseded`}:{kind:`ended`};if(o.isRetired(a)&&k(a))return{kind:`superseded`};let s={refreshToken:e,order:a},c=t??r??Qn(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}},se=(e,r)=>{if(o.isEnded(e.order))return ae(e.order);let i=ie(e);if(i)return i;if(!ee(e)&&te(e.order))return o.retire(e.order),a(`[passflow] Refused to save a late refresh result: it rotated ${e.order.fp} into ${Kn(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=X(r);if(e.sub&&s&&s!==e.sub)return t.saveTokens(r),{kind:`identity-changed`,saved:!0};let c=Y(r.refresh_token);return c&&($n(c,e.order)||$n(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`})},F=(e,t)=>{if(o.isEnded(e.order))return ae(e.order);let n=ie(e);if(n)return n.kind===`identity-changed`?{kind:`identity-changed`}:n;if(o.isRetired(e.order)&&k(e.order))return{kind:`superseded`,adopted:!1};let r=Rn(t),i=r.kind===`blocked`||r.kind===`auth`;return ee(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})},I=e=>{if(!er(e))return!1;let{from:t,fromIat:r,fromSid:a,to:c,tokens:l}=e;if(typeof t!=`string`||typeof c!=`string`||!er(l))return!1;let u=l;if(typeof u.access_token!=`string`||u.access_token===``||typeof u.refresh_token!=`string`||u.refresh_token===``||Kn(u.refresh_token)!==c)return!1;let d=y();if(!d?.refresh_token)return!1;let f=n.getTokens(),p=i()??X(f),m=X(u);if(p&&m&&p!==m)return s?.(`identity-changed`),!1;let h=Y(u.refresh_token),g=Y(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&&Kn(d.refresh_token)!==c?!1:(re({...u}),_())},L=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)},ce=()=>{let e=b();if(!e)return!1;if(L(e))return!0;let t=y(),r=Y(t?.refresh_token);if(!t||!r||r.fp===e.fp||!L(r)||!ne(r,e))return!1;let a=i()??X(n.getTokens()),o=X(t);return a&&o&&a!==o?(s?.(`identity-changed`),!1):(re(t),!0)},R=e=>{let t=Y(e?.refresh_token),n={},r=i()??X(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:P,beginSend:oe,commitSave:se,judgeFailure:F,adoptTokens:I,adoptSuccessor:ce,beginHeldSend:()=>{let e=Y(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&&O()===`end`&&s?.(`emptied`)},session:()=>R(n.getTokens()),storedSession:()=>R(y()),dropSession:()=>{n.setTokensCache(void 0),n.stopTokenCheck?.()},deleteIfStillDead:e=>{let n=Y(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:()=>{M?.(),N?.(),D()}}}function nr(){let e,t,n=new Promise((n,r)=>{e=n,t=r});return n.catch(()=>void 0),{promise:n,resolve:e,reject:t}}var rr={strikes:q.sessionEnded,"session-ended":q.sessionEnded,"stored-ended":q.sessionEnded,"signed-out":q.signedOut,emptied:q.signedOut,"signed-out-here":q.signedOut,"successor-timeout":q.successorTimeout,"identity-changed":q.identityChanged,disposed:q.disposed};function ir(e){throw Error(`Unexpected refresh state: ${JSON.stringify(e)}`)}function ar(e){if(e===void 0||!Number.isFinite(e))return 3;let t=Math.floor(e);return t>=1?t:3}function or(e,t){return e instanceof Error&&e.message?e.message:t}function sr(e){if(typeof e!=`object`||!e)return;let t=e.id;return typeof t==`string`||typeof t==`number`?t:void 0}function cr(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 lr(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 ur(e){let{emit:t,storage:n,cache:r,transport:i,coordination:a}=e,o=a.clock,s=e.logger??Mn(),c=ar(e.strikes),l=a.transports?Vn({locks:a.transports.locks,channel:a.transports.channel,tabId:a.transports.tabId,names:a.names,clock:o}):Hn(),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=()=>Kn(r.getTokens()?.refresh_token),O=()=>({...r.getTokens()??{}}),ee=()=>i.opaqueMarker?i.opaqueMarker():n.getTokens()?.id_token,k=()=>(S===void 0&&(S=X(r.getTokens()??n.getTokens())),S),te=new Set,ne=new Set,re=e=>()=>{for(let t of Array.from(e))t()},ie=a.onStorageChange?.(re(te)),ae=e.platform?.onForeground(re(ne)),A=tr({storage:n,cache:r,identity:k,schedule:(e,t)=>o.setTimeout(e,t),onStorageChange:e=>(te.add(e),()=>te.delete(e)),onWake:e=>(ne.add(e),()=>ne.delete(e)),onSessionLost:e=>de(e),onStoredSessionSeen:()=>{u.kind===`blocked-wait`&&Oe()},warn:e=>s.warn(e)}),j=e=>({trigger:e,startedAt:T(),plain:nr(),fresh:[]}),M=e=>e.kind===`idle`||e.kind===`ended`?void 0:e.pending,N=(e,t)=>{if(t===void 0)return e.plain.promise;let n={callTime:t,deferred:nr()};return e.fresh.push(n),n.deferred.promise},P=(e,t,n=!1)=>{e.plain.resolve(O());for(let r of e.fresh)n||t!==void 0&&t>=r.callTime?r.deferred.resolve(O()):H(`refresh-token`,r.callTime).then(r.deferred.resolve,r.deferred.reject);e.fresh=[]},oe=(e,t,n)=>{e.plain.reject(t);for(let r of e.fresh)n!==void 0&&n<r.callTime?H(`refresh-token`,r.callTime).then(r.deferred.resolve,r.deferred.reject):r.deferred.reject(t);e.fresh=[]},se=(e,t)=>{if(e){e.plain.reject(t);for(let n of e.fresh)n.deferred.reject(t);e.fresh=[]}},F=(e,n,r,i)=>{let a={message:or(r,`Token refresh failed`),originalError:r,operation:e,source:n},o=sr(r);o!==void 0&&(a.code=o),i&&(a.refresh=i),t(`error`,a)},I=(e,t)=>{let n={classification:e,willRetry:t!==void 0,strikes:h,maxStrikes:c};return t!==void 0&&(n.nextRetryAt=t),n},L=(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})}},ce=(e,n,r)=>{if(_)return;_={since:e};let i={since:e,origin:r};n!==void 0&&(i.nextRetryAt=n),t(`refresh:failing`,i)},R=(e,t)=>{let n=r.getTokens(),i=Kn(n?.refresh_token);e.fp&&i&&l.post({type:`tokens-refreshed`,tokens:cr(n),from:e.fp,...e.iat===void 0?{}:{fromIat:e.iat},fromSid:e.sid??``,to:i,...t===void 0?{}:{sentAt:t}})},le=()=>{p||(p=!0,s.warn(hn))},ue=e=>{(e.kind===`backoff`||e.kind===`blocked-wait`)&&e.cancel()},z=(e,n)=>{if(u.kind===`ended`)return;let r=M(u);ue(u);let a=A.session(),o=k();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},se(r,n??new J(rr[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:ir(e)}},B=()=>{if(u.kind!==`ended`||u.cause===`disposed`||f||E()!==`json`)return;let e=n.getTokens(),i=Y(e?.refresh_token);if(!e?.refresh_token||!e.access_token||!i||A.lineage.isEnded(i)||A.lineage.isRetired(i))return;let a=b,o=X(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`})},de=e=>{u.kind===`ended`||f||E()===`json`&&(z(e===`emptied`?`emptied`:`identity-changed`),e===`identity-changed`&&B())},fe=e=>{e instanceof Zn?(z(`identity-changed`),B()):e instanceof Xn?z(e.cause===`emptied`?`emptied`:`stored-ended`):z(`stored-ended`,e)},pe=()=>{u={kind:`idle`},w||l.release()},me=e=>!e.from||E()!==`json`||e.from===D()||e.from===Kn(n.getTokens()?.refresh_token),he=e=>{let t=g;if(!t)return;if(!l.holding){u={kind:`waiting`,pending:e},l.request(t.nextAt+G);return}l.setRetryInfo(t);let n=d,r=t.nextAt;u={kind:`backoff`,pending:e,dueAt:r,cancel:o.setTimeout(()=>{n===d&&ge()},Math.max(0,r-T()))}},ge=()=>{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())+G)):(u={kind:`waiting`,pending:e},ve()||_e())},_e=()=>{u.kind===`idle`&&l.release()},ve=()=>{if(u.kind!==`waiting`)return!1;let e=u.pending;if(E()!==`json`)return ye(e);let t=A.session(),n;try{n=A.checkStoredBeforeSend()}catch(e){return fe(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`},P(e,void 0,!0),!1):(v={fp:t,at:T()},A.beginHeldSend()?be(e,`held`):(u={kind:`idle`},P(e,void 0,!0),!1))}if(v=void 0,n===`adopted`){if(L(`adopted`,`other-tab`),R(t),e.fresh.length===0)return u={kind:`idle`},P(e,void 0),!1;e.plain.resolve(O())}return g&&!me(g)&&(g=void 0),g&&g.nextAt>T()?(m=g.attempt,h=g.strikes,g.failingSince!==void 0&&ce(g.failingSince,g.nextAt,`other-tab`),he(e),!0):(g&&(m=g.attempt,h=g.strikes),be(e,e.trigger===`held`?`refresh-token`:e.trigger))},ye=e=>y!==void 0&&y>=e.startedAt?(r.setTokensCache(n.getTokens()),L(`adopted`,`other-tab`),u={kind:`idle`},P(e,y),!1):g&&g.nextAt>T()?(m=g.attempt,h=g.strikes,he(e),!0):xe(e,e.trigger,void 0,void 0),be=(e,t)=>{let r=n.getTokens(),i=r?.refresh_token;if(!i)return u={kind:`idle`},P(e,void 0,!0),!1;let a=A.beginSend(i);switch(a.kind){case`superseded`:return A.endHeldSend(),L(`adopted`,`other-tab`),u={kind:`idle`},P(e,void 0),!1;case`ended`:return A.endHeldSend(),z(`stored-ended`),!1;case`identity-changed`:return A.endHeldSend(),z(`identity-changed`),B(),!1;case`send`:return xe(e,t,a.sent,r);default:return ir(a)}},xe=(e,n,r,a)=>{let o={generation:d,sentAt:T(),trigger:n,settled:nr()};r?o.sent=r:o.marker=ee(),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=>{Ce(o,e).catch(e=>s.error(`[passflow] Applying a refresh result failed`,e)).finally(()=>o.settled.resolve())},e=>{we(o,e),o.settled.resolve()}),!0},Se=e=>!f&&e.generation===d&&u.kind===`refreshing`&&u.request===e,Ce=async(e,t)=>{if(e.sent?.held&&A.endHeldSend(),!Se(e)||u.kind!==`refreshing`)return;let{pending:a}=u;if(!e.sent){let o=X({...t.id_token?{id_token:t.id_token}:{}}),s=k();if(o!==void 0&&s!==void 0&&o!==s){let t=new J(q.identityChanged);F(`refresh`,e.trigger,t,I(`auth`)),z(`identity-changed`,t);return}try{await i.applyOpaque(t)}catch(t){we(e,t);return}if(!Se(e))return;r.setTokensCache({...n.getTokens()??{},...lr(t,void 0)}),L(`refresh`,`this-tab`);let c=k();l.post(c===void 0?{type:`session-refreshed`,at:T()}:{type:`session-refreshed`,at:T(),sub:c}),pe(),P(a,e.sentAt);return}let o=D(),s=A.commitSave(e.sent,lr(t,e.stored));switch(s.kind){case`saved`:L(`refresh`,`this-tab`),R(e.sent.order,e.sentAt),pe(),P(a,e.sentAt);return;case`superseded`:e.outcome&&D()===o||L(`adopted`,`other-tab`),s.adopted&&R(e.sent.order),pe(),P(a,e.sentAt);return;case`ended`:{let t=new J(s.cause===`emptied`?q.signedOut:q.sessionEnded);F(`refresh`,e.trigger,t,I(`auth`)),z(s.cause===`emptied`?`emptied`:`stored-ended`,t);return}case`identity-changed`:{let t=new J(q.identityChanged);F(`refresh`,e.trigger,t,I(`auth`)),z(`identity-changed`,t),B();return}default:ir(s)}},we=(e,t)=>{if(e.sent?.held&&A.endHeldSend(),!Se(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||L(`adopted`,`other-tab`),pe(),P(n,e.sentAt);return;case`ended`:F(`refresh`,e.trigger,t,I(`auth`)),z(o.cause===`emptied`?`emptied`:`stored-ended`,t);return;case`identity-changed`:F(`refresh`,e.trigger,t,I(`auth`)),z(`identity-changed`,t),B();return;case`own`:r=o.failure,i=o.heldRefused;break;default:ir(o)}}else r=Rn(t,T());if(i)F(`refresh`,e.trigger,t,I(r.kind)),L(`adopted`,`other-tab`),pe(),P(n,void 0,!0);else switch(r.kind){case`blocked`:F(`refresh`,e.trigger,t,I(`blocked`)),De(n,e.sentAt,t,e.marker);return;case`auth`:if(h+=1,m+=1,h>=c){F(`refresh`,e.trigger,t,I(`auth`)),Ee(e,t);return}Te(e,n,t,r);return;case`transient`:m+=1,Te(e,n,t,r);return;default:ir(r.kind)}},Te=(e,t,n,r)=>{let i=T()+zn(m,o.random(),r.retryAfterMs),a=r.kind===`auth`?`auth`:`transient`;F(`refresh`,e.trigger,n,I(a,i)),a===`transient`&&ce(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:or(n,`Token refresh failed`),retry:s}),he(j(`retry`)),oe(t,n,e.sentAt)},Ee=(e,t)=>{let n=e.sent?.sub??k(),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),z(`strikes`,t)},De=(e,t,n,r)=>{l.release(),s.warn(`[passflow] The refresh token was already used, most likely by another tab; waiting for its successor: ${or(n,`blocked`)}`);let i=d,a=T()+$t,c={kind:`blocked-wait`,pending:e,deadline:a,sentAt:t,cancel:()=>void 0,marker:r};if(u=c,Oe())return;let f=E()!==`json`&&!l.coordinated&&!e.cookieRetried,p=()=>{i===d&&u===c&&(Oe()||(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.`),z(`successor-timeout`)):c.cancel=o.setTimeout(p,en)))};c.cancel=o.setTimeout(p,f?nn:en)},Oe=()=>{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=ee(),a=!l.coordinated&&i!==void 0&&i!==e.marker;if(!t&&!a)return!1;r.setTokensCache(n.getTokens())}return u===e&&(e.cancel(),L(`adopted`,`other-tab`),u={kind:`idle`},P(e.pending,void 0,!0),!0)},ke=e=>{let t=k(),n=!e.sub||!t||e.sub===t;return E()===`json`?!!e.fp&&e.fp===D()&&n:!e.fp&&n},Ae=(e,t)=>{if(e!==`signed-out`||!t.sub)return!1;let n=k();return n!==void 0&&t.sub===n},je=(e,t,n)=>{if(u.kind===`ended`||!me(e))return;let r=g?.nextAt;if(g=e,e.failingSince!==void 0&&ce(e.failingSince,e.nextAt,`other-tab`),!t||u.kind!==`waiting`)return;let i=new J(e.kind===`transient`?q.unavailable:q.authRetry,{nextRetryAt:e.nextAt,cause:n||void 0}),a=u.pending;u.pending=j(a.trigger),oe(a,i,r)},Me=(e,t)=>{switch(t&&L(`adopted`,`other-tab`),u.kind){case`waiting`:case`backoff`:{let t=u.pending;ue(u),pe(),P(t,e);return}case`blocked-wait`:{let e=u.pending;u.cancel(),u={kind:`idle`},P(e,void 0,!0);return}case`idle`:case`refreshing`:case`ended`:return;default:ir(u)}},V=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`&&(ke(t)||Ae(e.type,t));t.fp&&A.endLineage({...t,fp:t.fp}),n&&z(e.type===`signed-out`?`signed-out`:`session-ended`),A.endedElsewhere(e.type,t)},Ne=e=>{if(!f)switch(e.type){case`tokens-refreshed`:{if(u.kind===`ended`){B();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,Me(e.sentAt,n);return}case`session-refreshed`:{if(E()===`json`||u.kind===`ended`)return;let t=k();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`){Oe();return}Me(e.at,!0);return}case`still-refreshing`:e.retry&&je(e.retry,!1,``),Pe();return;case`retry-scheduled`:je(e.retry,!0,e.message),Pe();return;case`refresh-failed`:if(u.kind===`ended`||E()!==`json`||e.from!==D()&&e.from!==Kn(n.getTokens()?.refresh_token))return;if(ce(T(),void 0,`other-tab`),u.kind===`waiting`){let t=u.pending;u.pending=j(t.trigger),oe(t,new J(q.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())+G)}return;case`session-ended`:case`signed-out`:V(e);return;case`takeover`:case`rate-limited`:return;default:ir(e)}},Pe=()=>{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`&&ve()},onLockLost:()=>{if(u.kind===`backoff`){let e=u.pending;u.cancel(),u={kind:`waiting`,pending:e},l.request((g?.nextAt??T())+G)}},onMessage:Ne});let Fe=()=>{if(f)return;if(u.kind===`ended`){B();return}if(u.kind===`blocked-wait`&&E()!==`json`){Oe();return}if(u.kind!==`idle`||E()!==`json`||w)return;let e=A.session();try{if(A.checkStoredBeforeSend()!==`adopted`)return}catch{return}L(`adopted`,`other-tab`),l.coordinated&&R(e)};te.add(Fe),ne.add(Fe);let H=(e,t)=>{if(f)return Promise.reject(new J(q.disposed));switch(u.kind){case`ended`:return Promise.reject(new J(q.sessionEnded));case`idle`:{let n=j(e);u={kind:`waiting`,pending:n};let r=N(n,t);return l.holding&&!w?ve()||_e():l.request(g?g.nextAt+G:void 0),r}case`waiting`:case`refreshing`:case`backoff`:case`blocked-wait`:return N(u.pending,t);default:return ir(u)}},Ie=e=>{if(f)return Promise.reject(new J(q.disposed));if(le(),u.kind===`ended`)return Promise.reject(new J(q.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 F(`refresh`,e.trigger,n),Promise.reject(n)}}return H(e.trigger,e.fresh?T():void 0)},Le=e=>{if(f)return Promise.reject(new J(q.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()):Ie({trigger:e.trigger}).then(()=>r.getTokens())},Re=(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))}),ze=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()})})},Be=()=>{if(w=!1,!f&&l.holding){if(u.kind===`waiting`)ve()||_e();else if(u.kind===`backoff`){let e=u.pending;u.cancel(),he(e)}else u.kind===`idle`&&g&&g.nextAt>T()&&me(g)?(m=g.attempt,h=g.strikes,he(j(`retry`))):u.kind===`idle`&&l.release()}},Ve=async(e,t)=>{if(f)throw new J(q.disposed);le();let n=T()+rn;if(await ze(n-T()),(!l.holding||u.kind===`refreshing`)&&(u.kind===`refreshing`?`timeout`:await Re(`commit`,n-T()))===`timeout`){let e=new Gn(`lock-timeout`);throw F(`upgrade.commit`,`upgrade`,e),e}w=!0;try{return await He(e,t)}finally{Be()}},He=async(e,a)=>{let o,s;if(E()===`json`){let e=A.session();try{A.checkStoredBeforeSend()===`adopted`&&(L(`adopted`,`other-tab`),R(e))}catch{}s=n.getTokens();let t=s?.refresh_token;if(!t){let e=Error(s?`No refresh token found`:`No tokens found`);throw F(`upgrade.commit`,`upgrade`,e),e}let r=A.beginSend(t);o=r.kind===`send`?r.sent:{refreshToken:t,order:Y(t)??{fp:t}}}let c=T();t(`refresh:start`,{});let u;try{u=await i.send(s?{tokens:s,upgrade:e}:{upgrade:e})}catch(e){throw o&&A.judgeFailure(o,e),F(`upgrade.commit`,`upgrade`,e),e}try{i.assertPin(a)}catch(e){throw F(`upgrade.commit`,`upgrade`,e),e}if(!o){await i.applyOpaque(u),r.setTokensCache({...n.getTokens()??{},...lr(u,void 0)}),Ue(c);let e=k();return l.post(e===void 0?{type:`session-refreshed`,at:T()}:{type:`session-refreshed`,at:T(),sub:e}),O()}let d=A.commitSave(o,lr(u,s));if(d.kind===`saved`)return Ue(c),R(o.order,c),O();let f=new Gn(`superseded`);throw F(`upgrade.commit`,`upgrade`,f),d.kind===`superseded`&&d.adopted&&L(`adopted`,`other-tab`),f},Ue=e=>{if(L(`upgrade`,`this-tab`),u.kind===`waiting`||u.kind===`backoff`||u.kind===`blocked-wait`){let t=u.pending;ue(u),u={kind:`idle`},P(t,e)}},We=()=>{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}))},Ge=()=>{let e=M(u);se(e,new J(q.signedOut)),(u.kind===`backoff`||u.kind===`blocked-wait`||u.kind===`waiting`)&&(ue(u),u={kind:`idle`})};return{refresh:Ie,ensureFresh:Le,commitUpgrade:Ve,signOut:async e=>{if(f)return e(n.getTokens()?.refresh_token);let t=T()+an;Ge(),await ze(t-T()),Ge(),l.coordinated&&!l.holding&&await Re(`logout`,t-T());try{We(),await e(n.getTokens()?.refresh_token)}finally{u.kind!==`ended`&&z(`signed-out-here`),x=void 0,l.release()}},signOutNow:e=>{if(f)return e(n.getTokens()?.refresh_token);Ge();try{We(),e(n.getTokens()?.refresh_token)}finally{u.kind!==`ended`&&z(`signed-out-here`),x=void 0}},sessionStarted:()=>{if(f)return;let e=M(u);ue(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&&P(e,void 0,!0)},identity:k,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=M(u);ue(u),f=!0,d+=1,u={kind:`ended`,cause:`disposed`},se(e,new J(q.disposed)),C=void 0,A.stop(),l.dispose(),ie?.(),ae?.()}}}var Z=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}({}),dr=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`&&Gt(this,t?.originalError),this.subscribers.forEach((n,r)=>{(!n||n.has(e))&&r.onAuthChange?.(e,t)})}notifyError(e){return W(this,e)}},fr={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`}}},pr=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))},mr=()=>{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 hr(e,t,n,r,i){let[a=``,o=``,s=``]=e.split(`.`),c=JSON.parse(new TextDecoder().decode(pr(a))),l=c.alg===`ES256`||c.alg===`RS256`?fr[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=mr().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,pr(s),p))throw Error(`Token signature is not valid`);let m=M(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`||j(m,0))throw Error(`Token has expired`);if(i&&m.type!==i)throw Error(`Token type is not valid`)}async function gr(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`);mr();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 hr(n.access_token,s,o,t,N.access_token),n.refresh_token&&await hr(n.refresh_token,s,o,t,N.refresh_token),n.id_token&&await hr(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`},_r=Object.freeze([Q.twoFactorCodeInvalid,Q.twoFactorNotEnabled,Q.challengeInvalid,Q.challengeSessionMismatch,Q.challengeTooManyAttempts]),vr=Object.freeze([Q.tokenInvalid]),yr=Object.freeze([`wrong_code`,`challenge_spent`,`not_registered`,`prepare_not_required`]),br=e=>yr.includes(e),xr={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.`,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||xr[e.kind]),this.name=`UpgradeTransportError`,this.code=`upgrade_transport`,this.kind=e.kind,this.status=e.status,this.errorId=e.errorId,this.retryable=br(e.kind),e.cause!==void 0&&(this.cause=e.cause)}},Sr=Object.freeze([`upgrade_transport`,`upgrade_insufficient`,`upgrade_unavailable`,`upgrade_session_changed`,`upgrade_cancelled`,`upgrade_unsatisfiable`]),Cr=e=>typeof e==`object`&&!!e&&typeof e.code==`string`&&Sr.includes(e.code),wr=e=>e instanceof $||typeof e==`object`&&!!e&&e.code===`upgrade_transport`,Tr=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`}},Er=(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`;default:return}},Dr=(e,t)=>e===void 0?`network`:e===501?`unavailable`:e===400?`fatal`:e===401||e===403?t===`start`?`challenge_spent`:`session_changed`:e>=500?`network`:`fatal`,Or=(e,t)=>{if(e instanceof $)return e;let n=Tr(e);return n.hasResponse?new $({kind:Er(n.errorId,t)??Dr(n.status,t),message:n.message,status:n.status,errorId:n.errorId,cause:e}):new $({kind:`network`,message:n.message,cause:e})},kr=e=>e.errorId!==void 0&&_r.includes(e.errorId),Ar=e=>e.errorId!==void 0&&vr.includes(e.errorId),jr=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}},Mr=class extends Error{constructor(e=`Step-up verification is not available on this deployment`){super(e),this.name=`UpgradeUnavailableError`,this.code=`upgrade_unavailable`}},Nr=class extends Error{constructor(e=`The session changed during verification`){super(e),this.name=`UpgradeSessionChangedError`,this.code=`upgrade_session_changed`}},Pr=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}},Fr=(e,t)=>!t||t.sub!==e.sub?!1:e.sid!==void 0&&t.sid!==void 0?e.sid===t.sid:!0;function Ir(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 Lr(e){return e.replace(/<[^>]*>/g,``).substring(0,200)}function Rr(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return t.length!==0&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function zr(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return/^\+[1-9]\d{1,14}$/.test(t)}function Br(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 Vr(e,t=6){return!e||typeof e!=`string`?!1:(t===8?/^\d{8}$/:/^\d{6}$/).test(e)}function Hr(e){if(!e||typeof e!=`string`)return null;let t=e.toUpperCase().replace(/\s+/g,``);return/^[A-Z0-9-]{4,16}$/.test(t)?t:null}var Ur=`passflow_2fa_pkce`,Wr=3e5,Gr=`passflow_pwless_pending`,Kr=3e3,qr=`passflow_federated_pkce`,Jr=6e5,Yr=`AppId is required for federated auth`,Xr=10,Zr=`The sign-in answered with a PKCE code, but its verifier is gone`,Qr=(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})}),$r=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},ei=e=>{if(e)try{return M(e).email}catch{return}},ti=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d=R,f,p={coordination:Cn()}){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.emailChallenges=new Map,this.tokenExchangeConfig=u,this.tokenDeliveryManager=new se(n),u?.enabled&&this.tokenDeliveryManager.setMode(P.BFF),this.refresh=ur({emit:this.createRefreshEmit(),storage:n,cache:i,transport:this.createRefreshTransport(),coordination:p.coordination,platform:d,...p.strikes===void 0?{}:{strikes:p.strikes},logger:Mn()}),this.initializeSession()}async initializeSession(){(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode())&&await this.restoreSession()}async restoreSession(){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.statusUrl)try{let e=await fetch(this.tokenExchangeConfig.statusUrl,{method:`GET`,credentials:`include`});return e.ok&&(await e.json()).authenticated?(this.tokenDeliveryManager.setSessionValid(),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return this.tokenDeliveryManager.setSessionInvalid(),!1}if(!this.tokenDeliveryManager.isCookieMode())return!1;try{let e=await this.authApi.validateSession();return e.valid?(this.tokenDeliveryManager.setSessionValid(),e.user&&this.subscribeStore.notify(Z.SessionRestored,e.user),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return this.tokenDeliveryManager.setSessionInvalid(),!1}}async processAuthResponse(e,t){await this.applyAuthResponse(e,t),this.refresh.sessionStarted()}async applyAuthResponse(e,t){if(e.code&&!e.access_token)throw Error(`A PKCE authorization code was not exchanged, so there are no tokens to apply`);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()),this.tokenCacheService.setTokensCache(e),e.csrf_token&&this.storageManager.setCsrfToken(e.csrf_token)}handlePendingSecondFactor(e,t,n,r){return e.requires_2fa!==!0&&!e.tfa_token?!1:(n?this.rememberPkceSignIn(n.verifier,r):this.forgetPkceSignIn(),this.subscribeStore.notify(Z.TwoFactorRequired,{email:t||``,challengeId:e.challenge_id||``,tfaToken:e.tfa_token||``}),!0)}handleEmailVerificationStep(e,t,n,r,i){if(!Fe(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(Z.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<=Xr)break;this.emailChallenges.delete(e)}}rememberPkceSignIn(e,t){if(this.pendingPkce={verifier:e,scopes:t,expiresAt:Date.now()+Wr},typeof sessionStorage<`u`)try{sessionStorage.setItem(Ur,JSON.stringify(this.pendingPkce))}catch{}}readPendingPkce(){if(!this.pendingPkce&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(Ur);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(Ur)}catch{}}rememberPendingPasswordless(e){if(this.pendingPasswordless=e,typeof sessionStorage<`u`)try{sessionStorage.setItem(Gr,JSON.stringify(e))}catch{}}readPendingPasswordless(){if(!this.pendingPasswordless&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(Gr);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(Gr)}catch{}}rememberFederatedSlot(e,t){if(this.federatedSlot={verifier:e,scopes:t,expiresAt:Date.now()+Jr},typeof sessionStorage<`u`)try{sessionStorage.setItem(qr,JSON.stringify(this.federatedSlot))}catch{}}readFederatedSlot(){if(!this.federatedSlot&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(qr);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(qr)}catch{}}async startPkce(){let e=!1;try{e=await this.readPkceEnabled?.()??!1}catch(e){Mn().warn(`Passflow: could not read the app settings, so this sign-in sends no PKCE challenge`,e);return}return e?An():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(Zr);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 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){if(`email`in e&&e.email&&!Rr(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&&!Br(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&&!zr(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(Z.SignInStart,{email:e.email});let t=this.deviceService.getDeviceId(),n=He(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes;try{let r=await this.startPkce(),i=await this.authApi.signIn(r?{...e,code_challenge:r.challenge}:e,t,n);if(this.handleEmailVerificationStep(i,`sign-in`,e.email,r,e.scopes)||this.handlePendingSecondFactor(i,e.email,r,e.scopes))return i;let a=await this.exchangeCode(i,r);return this.handlePendingSecondFactor(a,e.email)||(await this.processAuthResponse(a,e.scopes),this.subscribeStore.notify(Z.SignIn,{tokens:a,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),a}catch(e){let t={operation:`sign-in`,message:e instanceof Error?e.message:`Sign in failed`,originalError:e,code:e instanceof H?e.id:void 0};throw W(this.subscribeStore,t),e}}async signUp(e){if(e.user.email&&!Rr(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&&!zr(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(Z.RegisterStart,{email:e.user.email}),e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{let t=await this.startPkce(),n=await this.authApi.signUp(t?{...e,code_challenge:t.challenge}:e);if(this.handleEmailVerificationStep(n,`sign-up`,e.user.email,t,e.scopes)||this.handlePendingSecondFactor(n,e.user.email,t,e.scopes))return n;let r=await this.exchangeCode(n,t);return this.handlePendingSecondFactor(r,e.user.email)||(await this.processAuthResponse(r,e.scopes),this.subscribeStore.notify(Z.Register,{tokens:r,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),r}catch(e){let t={operation:`sign-up`,message:e instanceof Error?e.message:`Sign up failed`,originalError:e,code:e instanceof H?e.id:void 0};throw W(this.subscribeStore,t),e}}async passwordlessSignIn(e){if(e.email&&!Rr(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&&!zr(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(Z.SignInStart,{email:e.email});let t=e.scopes??this.scopes,n=this.deviceService.getDeviceId(),r=He(this.platform.getDeviceType());try{let i=await this.startPkce(),a=await this.authApi.passwordlessSignIn({...e,scopes:t,...i?{code_challenge:i.challenge}:{}},n,r);return i&&a.challenge_id?this.rememberPendingPasswordless({challengeId:a.challenge_id,verifier:i.verifier,codeChallenge:i.challenge,matchCode:a.match_code,email:e.email,scopes:t,expiresAt:new Date(a.expires_at).getTime()}):this.forgetPendingPasswordless(),a}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 H?e.id:void 0};throw W(this.subscribeStore,t),e}}async passwordlessSignInComplete(e){this.subscribeStore.notify(Z.SignInStart,{}),e.scopes=e.scopes??this.scopes,e.device=this.deviceService.getDeviceId();let t=this.readPendingPasswordless(),n=t?.challengeId===e.challenge_id?t:void 0,r=!1;try{let t=await this.authApi.passwordlessSignInComplete(e);if(r=!0,this.handlePendingSecondFactor(t,n?.email,n&&{verifier:n.verifier},n?.scopes))return this.forgetPendingPasswordless(),t;let i=t;if(t.code){if(!n)throw Error(Zr);if(i=await this.authApi.pkceExchange(t.code,n.verifier),this.handlePendingSecondFactor(i))return this.forgetPendingPasswordless(),{...i,redirect_url:t.redirect_url??``}}let a=t.redirect_url?{...i,redirect_url:t.redirect_url}:i;return await this.processAuthResponse(a,n?.scopes??e.scopes),this.forgetPendingPasswordless(),this.subscribeStore.notify(Z.SignIn,{tokens:a,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),{...a,redirect_url:t.redirect_url??``}}catch(e){r&&this.forgetPendingPasswordless();let t={operation:`passwordless.complete`,message:e instanceof Error?e.message:`Passwordless sign in failed`,originalError:e,code:e instanceof H?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(Zr);for(;;){if(n?.aborted)throw n.reason;if(Date.now()>=t.expiresAt)return this.forgetPendingPasswordless(),{status:`expired`};if(this.readPendingPasswordless()?.challengeId!==e)throw Error(Zr);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 H&&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);await Qr(Kr,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 H?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(Z.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 H?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(Zr);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(Zr);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(),this.subscribeStore.notify(t?.operation===`sign-up`?Z.Register:Z.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 H?e.id:void 0};throw W(this.subscribeStore,t),e}}async logOut(){let e=this.refresh.identity();return await this.refresh.signOut(async e=>{await this.callLogoutApi(e),this.forgetPkceSignIn(),this.forgetPendingPasswordless(),this.emailChallenges.clear(),this.clearLocalSession()}),e}resetSession(){let e=this.refresh.identity();return this.refresh.signOutNow(()=>{this.emailChallenges.clear(),this.clearLocalSession()}),e}async callLogoutApi(e){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.logoutUrl){try{await fetch(this.tokenExchangeConfig.logoutUrl,{method:`POST`,credentials:`include`})}catch{}return}let t=e??this.storageManager.getToken(N.refresh_token),n=this.storageManager.getDeviceId();try{if((await this.authApi.logOut(n,t,!this.appId)).status!==`ok`)throw Error(`Logout failed`)}catch{}}clearLocalSession(){this.storageManager.deleteTokens(),this.storageManager.clearIdToken(),this.storageManager.clearCsrfToken(),this.tokenDeliveryManager.reset(),this.tokenCacheService.setTokensCache(void 0),this.tokenCacheService.stopTokenCheck?.()}readSessionPin(){try{let e=this.storageManager.getToken(N.access_token);return e?Pr(M(e)):void 0}catch{return}}assertSessionPin(e){if(e&&!Fr(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 Nr(`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(Z.Refresh,{tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens(),source:r});return}case`signin`:{let{tokens:e,origin:r}=t;n.notify(Z.SignIn,{tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens(),origin:r});return}case`error`:W(n,t);return;case`refresh:start`:n.notify(Z.RefreshStart,{});return;case`token-cache-expired`:n.notify(Z.TokenCacheExpired,t);return;case`refresh:failing`:n.notify(Z.RefreshFailing,t);return;case`refresh:recovered`:n.notify(Z.RefreshRecovered,t);return;case`session:expired`:n.notify(Z.SessionExpired,t);return;case`signout`:n.notify(Z.SignOut,t);return;default:Mn().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(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 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 H({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){try{return await this.authApi.sendPasswordResetEmail(e)}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 H?e.id:void 0};throw W(this.subscribeStore,t),e}}async resetPassword(e,t,n){this.subscribeStore.notify(Z.SignInStart,{});let r=n??$r(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`,ei(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(Z.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 H?e.id:void 0};throw W(this.subscribeStore,t),e}}async passkeyRegister(e){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);this.subscribeStore.notify(Z.RegisterStart,{});let t=this.deviceService.getDeviceId(),n=He(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{let r=await this.startPkce(),{challenge_id:i,publicKey:a}=await this.authApi.passkeyRegisterStart(r?{...e,code_challenge:r.challenge}:e,t,n,!this.appId);a.user.id=this.platform.btoa(a.user.id);let o=await this.platform.passkeys.startRegistration(a);if(!o)throw Error(`Passkey registration was not completed`);let s=await this.authApi.passkeyRegisterComplete(o,t,i,!this.appId);if(this.handlePendingSecondFactor(s,void 0,r,e.scopes))return s;let c=await this.exchangeCode(s,r);return this.handlePendingSecondFactor(c)||(await this.processAuthResponse(c,e.scopes),this.subscribeStore.notify(Z.Register,{tokens:c,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),c}catch(e){let t={operation:`passkey.register`,message:e instanceof Error?e.message:`Passkey registration failed`,originalError:e,code:e instanceof H?e.id:void 0};throw W(this.subscribeStore,t),e}}async passkeyAuthenticate(e){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);this.subscribeStore.notify(Z.SignInStart,{});let t=this.deviceService.getDeviceId(),n=He(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes;try{let r=await this.startPkce(),{challenge_id:i,publicKey:a}=await this.authApi.passkeyAuthenticateStart(r?{...e,code_challenge:r.challenge}:e,t,n,!this.appId),o=await this.platform.passkeys.startAuthentication(a);if(!o)throw Error(`Passkey authentication was not completed`);let s=await this.authApi.passkeyAuthenticateComplete(o,t,i,!this.appId);if(this.handlePendingSecondFactor(s,void 0,r,e.scopes))return s;let c=await this.exchangeCode(s,r);return this.handlePendingSecondFactor(c)||`access_token`in c&&(await this.processAuthResponse(c,e.scopes),this.subscribeStore.notify(Z.SignIn,{tokens:c,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),c}catch(e){let t={operation:`passkey.authenticate`,message:e instanceof Error?e.message:`Passkey authentication failed`,originalError:e,code:e instanceof H?e.id:void 0};throw W(this.subscribeStore,t),e}}createFederatedAuthUrl(e){let t=`/auth/federated/start/${e.provider}`;if(!this.appId)throw Error(Yr);let n={scopes:(e.scopes??this.scopes).join(` `),redirect_url:e.redirect_url??this.platform.getCurrentUrl()?.origin??``,appId:this.appId,...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}:{}},r=new URL(t,this.url);return r.search=new URLSearchParams(n).toString(),r.toString()}async federatedAuthWithPopup(e){if(this.subscribeStore.notify(Z.SignInStart,{provider:e.provider}),!this.appId)throw Error(Yr);let t=e.scopes??this.scopes,n=this.deviceService.getDeviceId();try{this.forgetFederatedSlot();let r=await this.startPkce(),i=this.createFederatedAuthUrl({...e,scopes:t,device:n,...r?{code_challenge:r.challenge,code_challenge_method:`S256`}:{}}),a=this.platform.openAuthUrl(i,{mode:`popup`,expectedReturnOrigin:this.platform.getCurrentUrl()?.origin??``});r&&this.rememberFederatedSlot(r.verifier,t);let o=await a;this.forgetFederatedSlot();let s=new URLSearchParams(o.callbackHash.replace(/^#/,``));if(this.handlePendingSecondFactor({tfa_token:s.get(`tfa_token`)??void 0}))return;let c=new URLSearchParams(o.callbackSearch),l=c.get(`code`),u=c.get(`access_token`)||``,d=c.get(`refresh_token`)||``,f=c.get(`id_token`)||``,p={access_token:u,refresh_token:d||void 0,id_token:f||void 0,scopes:t};if(l&&r){if(p=await this.authApi.pkceExchange(l,r.verifier),this.handlePendingSecondFactor(p))return}else await gr(this.url,this.appId,p);await this.processAuthResponse(p,t),this.subscribeStore.notify(Z.SignIn,{tokens:p,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.platform.navigateTo(this.platform.getCurrentUrl()?.origin??``)}catch(e){this.forgetFederatedSlot();let t={operation:`federated.popup`,message:e instanceof Error?e.message:`Authentication failed`,code:e instanceof L?`POPUP_CLOSED`:`AUTH_FAILED`,originalError:e};W(this.subscribeStore,t)}}federatedAuthWithRedirect(e){if(this.subscribeStore.notify(Z.SignInStart,{provider:e.provider}),!this.appId)throw Error(Yr);let t=e.scopes??this.scopes,n=this.deviceService.getDeviceId();this.startPkce().then(r=>{let i=this.createFederatedAuthUrl({...e,scopes:t,device:n,...r?{code_challenge:r.challenge,code_challenge_method:`S256`}:{}});r?this.rememberFederatedSlot(r.verifier,t):this.forgetFederatedSlot(),this.platform.navigateTo(i)}).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(Z.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 H?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}}authRedirect(e={}){try{this.platform.navigateTo(this.authRedirectUrl(e))}catch(e){let t={operation:`auth-redirect`,message:e instanceof Error?e.message:`Failed to redirect to auth page`,originalError:e};throw W(this.subscribeStore,t),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:!j(e.access_token)||e.refresh_token!==void 0&&!j(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 H?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();return!t||!t.access_token?void 0:j(M(t.access_token))?e?await this.refreshForSession():void 0: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}}},ni=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)}},ri=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}},ii=class{constructor(e,t,n){this.tenantApi=e,this.scopes=t,this.logger=n||Mn()}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 ri(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}`)}}},ai=class{constructor(e,t,n,r=R){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}j(M(t.access_token))?(this.stopTokenCheck(),this.tokenExpiredFlag||(this.tokenExpiredFlag=!0,this.subscribeStore.notify(Z.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(Z.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(Z.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?M(e.access_token):void 0,id_token:e.id_token?M(e.id_token):void 0,refresh_token:e.refresh_token?M(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(j(M(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?j(M(this.tokensCache.access_token)):!1:!0}},oi=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.totpDigits=6,this.subscribeStore.subscribe({onAuthChange:(e,t)=>{if(e===Z.TwoFactorRequired){let e=t;this.setPartialAuthState(e.email,e.challengeId,e.tfaToken)}(e===Z.SignIn||e===Z.Register)&&(this.clearPartialAuthState(),this.clearMagicLinkSession())}},[Z.TwoFactorRequired,Z.SignIn,Z.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 e.totp_digits&&(this.totpDigits=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{return await this.twoFactorApi.getEnrollment(this.requirePendingTfaToken())}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){if(!Vr(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`)}requirePendingTfaToken(){let e=this.pendingTfaToken();if(!e)throw Error(`2FA verification expired or not required. User must sign in first.`);return e}setupStarted(e){return e.totp_digits&&(this.totpDigits=e.totp_digits),this.subscribeStore.notify(Z.TwoFactorSetupStarted,{secret:e.secret}),e}setupConfirmed(e){return this.subscribeStore.notify(Z.TwoFactorEnabled,{recoveryCodes:e.recovery_codes,clearRecoveryCodes:()=>{e.recovery_codes.length=0}}),e}async verify(e,t){if(!Vr(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);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.`);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(Z.TwoFactorVerified,{tokens:r}),r}catch(e){this.emitErrorAndThrow(e,`2fa.verify`,`Verify 2FA code`)}}async useRecoveryCode(e,t){try{let n=Hr(e);if(!n)throw Error(`Invalid recovery code format. Expected format: XXXX-XXXX or XXXXXXXX (alphanumeric).`);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}:{}}));return r.remaining_recovery_codes===0?this.subscribeStore.notify(Z.TwoFactorRecoveryCodesExhausted,{tokens:r}):r.remaining_recovery_codes<=2&&this.subscribeStore.notify(Z.TwoFactorRecoveryCodesLow,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(Z.TwoFactorRecoveryUsed,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(Z.TwoFactorVerified,{tokens:r}),r}catch(e){this.emitErrorAndThrow(e,`2fa.recovery.use`,`Use recovery code`)}}async disable(e){if(!Vr(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{let t=await this.twoFactorApi.disable({code:e});return this.subscribeStore.notify(Z.TwoFactorDisabled,{}),t}catch(e){this.emitErrorAndThrow(e,`2fa.disable`,`Disable 2FA`)}}async regenerateRecoveryCodes(e){if(!Vr(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);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.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.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 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`,timestamp:Date.now(),expiresAt:Date.now()+(t.expiresIn||3600)*1e3},this.subscribeStore.notify(Z.TwoFactorSetupMagicLinkValidated,{userId:t.userId,appId:t.appId,expiresIn:t.expiresIn||3600,sessionToken:t.sessionToken})):t.error&&this.subscribeStore.notify(Z.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}async getAvailableMethods(){try{return await this.twoFactorApi.getAvailableMethods()}catch(e){this.emitErrorAndThrow(e,`2fa.methods.available`,`Get available 2FA methods`)}}async getRegisteredMethods(){try{return await this.twoFactorApi.getRegisteredMethods()}catch(e){this.emitErrorAndThrow(e,`2fa.methods.registered`,`Get registered 2FA methods`)}}async startMethodSetup(e,t){try{let n=await this.twoFactorApi.startMethodSetup(e,t);return this.subscribeStore.notify(Z.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(Z.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.subscribeStore.notify(Z.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());if(!t.success)return t;let n=await this.finishSignIn(t);return this.subscribeStore.notify(Z.TwoFactorVerified,{tokens:{access_token:n.access_token,refresh_token:n.refresh_token}}),n.device_trusted&&this.subscribeStore.notify(Z.TwoFactorDeviceTrusted,{}),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.subscribeStore.notify(Z.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`)}}},si=class{constructor(e,t,n=R){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=He(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)}},ci=class extends Error{constructor(e,t,n=!1){super(t),this.name=`UpgradeFactorError`,this.factor=e,this.cancelled=n}},li=(e,t)=>{let n=t?.trim();if(!n)throw new ci(e,`A verification code is required`);return n},ui={type:`totp`,requiresPrepare:!1,input:`code`,assert:async({code:e})=>({code:li(`totp`,e)})},di={type:`recovery_codes`,requiresPrepare:!1,input:`code`,assert:async({code:e})=>({code:li(`recovery_codes`,e)})},fi={type:`passkey`,requiresPrepare:!0,input:`none`,assert:async({prepared:e,platform:t})=>{if(!e?.webauthn)throw new ci(`passkey`,`The upgrade challenge carried no WebAuthn options`);let n=t.passkeys;if(!n)throw new ci(`passkey`,`This platform does not support passkeys`);let r;try{r=await n.startAuthentication(e.webauthn)}catch(e){throw new ci(`passkey`,e?.message||`Passkey verification was cancelled`,!0)}if(!r)throw new ci(`passkey`,`Passkey verification was cancelled`,!0);return{challenge_id:e.challengeId,credential:r}}},pi=Object.freeze([ui,fi,di]),mi=(e=pi)=>new Map(e.map(e=>[e.type,e])),hi=3,gi={passkey:0,totp:1,email_otp:2,sms_otp:3,recovery_codes:9},_i=e=>e.requiredLevel??de(e.acrValues),vi=(e,t)=>{let n=gi[e.type]??5,r=t!==void 0&&t>=hi,i=e.type===`passkey`;return(r&&!i?100:0)+n},yi=(e,t)=>{let n=_i(t);return[...e].sort((e,t)=>vi(e,n)-vi(t,n))},bi=class extends Error{constructor(e){super(`Upgrade authentication was cancelled`),this.code=`upgrade_cancelled`,this.name=`UpgradeCancelledError`,e!==void 0&&(this.cause=e)}},xi=class extends Error{constructor(e=`No available authentication factor can satisfy this challenge`){super(e),this.code=`upgrade_unsatisfiable`,this.name=`UpgradeUnsatisfiableError`}},Si=4,Ci=3e4,wi=()=>{let e=()=>void 0,t=()=>void 0;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},Ti=e=>({acrValues:e.acrValues,level:e.requiredLevel,maxAge:e.maxAge}),Ei=(e,t)=>t.level===void 0||e.level!==void 0&&e.level>=t.level,Di=(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??[]]));return{acrValues:r,requiredLevel:n,maxAge:i,status:e.status,...a.length>0?{channels:a}:{}}},Oi=(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},ki=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??pi,this.registry=mi(this.available),this.maxAttempts=e.maxAttempts??Si,this.readObtainedBar=e.readObtainedBar,this.onFlightSettled=e.onFlightSettled,this.settleTimeoutMs=e.replaySettleTimeoutMs??Ci}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:Ti(e),statedBar:n,settlement:wi(),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=Oi(t,e);this.requirement=Di(t,e),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?yi(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&&!Ei(t,e.demanded)){this.receiveReport(e,{outcome:`insufficient`,obtained:t,required:e.demanded}),e.settlement.reject(new jr(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=this.offeredFactors();if(t.length===0)return{status:`failed`,reason:new xi};let n=this.requirement,r;try{r=await this.collect(n,t,e)}catch(e){return{status:`failed`,reason:new bi(e)}}if(r.type===`cancel`)return{status:`failed`,reason:new bi};let i=this.registry.get(r.factor);if(!i)e=new xi(`Unknown authentication factor: ${r.factor}`),this.state=`collecting`,this.selected=null;else try{return await this.proveAndCommit(i,r.code),{status:`proven`,obtained:this.readObtainedBar?.()??Ti(this.rankedRequirement??n)}}catch(t){if(t instanceof ci&&t.cancelled)return{status:`failed`,reason:new bi};let n=this.classifyProofFailure(t);if(n)return{status:`failed`,reason:n};t instanceof $&&t.kind===`not_registered`&&this.pruned.add(i.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}};return this.openPrompt=r,this.prompt(r)}classifyProofFailure(e){if(e instanceof jr||e instanceof Mr||e instanceof Nr)return e;if(e instanceof $)switch(e.kind){case`unavailable`:return new Mr(e.message);case`exhausted`:case`attempts_exhausted`:case`fatal`:case`protocol`:case`network`:return e;case`session_changed`:return new Nr(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)}},Ai=e=>typeof e==`function`?e():e,ji=e=>{try{return new URL(e)}catch{return}},Mi=(e,t)=>{if(!t||t===`/`)return!0;let n=t.replace(/\/+$/,``);return e===n||e.startsWith(`${n}/`)},Ni=(e,t)=>!t||e.origin===void 0?!1:e.origin===t.origin&&Mi(e.pathname,t.pathPrefix),Pi=(e,t)=>{for(let n of t){if(n===``)continue;if(n.startsWith(`/`)){if(e.relativeToBase&&Mi(e.pathname,n))return!0;continue}let t=ji(n)??ji(`https://${n}`);if(t&&e.origin!==void 0&&e.origin===t.origin&&Mi(e.pathname,t.pathname))return!0}return!1},Fi=(e,t,n)=>Ni(e,t.passflow)||Pi(e,t.backend)?!n||n(e.href)!==!1:!1,Ii=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})},Li=(e,t)=>{let n=t.onUpgradeDiagnostic??Ii;return(t,r)=>{n({status:e.status,url:e.request.href,reason:t,detail:{method:e.request.method,...r??{}}})}},Ri=(e,t,n)=>{let r=n.onUpgradeDiagnostic??Ii;for(let n of e)r({...n,url:t.request.href,detail:{method:t.request.method,...n.detail??{}}})},zi=/\bjson\b/i,Bi=async(e,t)=>{let n=t.requireChallengeChannel===`header`,r=e.getHeader(`content-type`)??``,i=!n&&zi.test(r),a;if(i)try{a=await e.readBody()}catch{a=void 0}return Ce(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})},Vi=e=>Ce({status:e.status,getHeader:t=>e.getHeader(t)??void 0},{requireChallengeChannel:`header`}).challenge,Hi=(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.`,Ui=(e,t)=>e instanceof bi?{kind:`cancelled`}:e instanceof xi?{kind:`unsatisfiable`}:e instanceof Mr?{kind:`unavailable`}:e instanceof Nr?{kind:`session-changed`}:e instanceof jr?{kind:`insufficient`,obtained:e.obtained,required:e.required}:e instanceof $?e.kind===`exhausted`||e.kind===`attempts_exhausted`?{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))},Wi=async(e,t,n,r)=>{if(e.status!==401&&e.status!==403)return{kind:`replayed`,response:e};let{challenge:i,diagnostics:a}=await Bi(e,t);if(Ri(a,e,t),!i)return{kind:`replayed`,response:e};let o=Ti(i);return r(`elevated-insufficient`,{obtained:n,required:o}),{kind:`insufficient`,obtained:n,required:o,response:e}},Gi=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)}},Ki=async(e,t)=>{if(e.status!==401&&e.status!==403||e.markers.upgradeTransaction)return{kind:`not-a-challenge`};let n=Li(e,t);if(e.markers.replayed){if(!Fi(e.request,t.scope,t.shouldIntercept))return{kind:`not-a-challenge`};let{challenge:r,diagnostics:i}=await Bi(e,t);if(Ri(i,e,t),!r)return{kind:`not-a-challenge`};let a=t.readObtainedBar?.()??{},o=Ti(r);return n(`elevated-insufficient`,{obtained:a,required:o}),{kind:`insufficient`,obtained:a,required:o,response:e}}if(!Fi(e.request,t.scope,t.shouldIntercept))return Vi(e)?(n(`challenge-out-of-scope`,{header:e.getHeader(`www-authenticate`)??void 0,message:Hi(e.request.href,t.scope)}),{kind:`out-of-scope`}):{kind:`not-a-challenge`};let{challenge:r,diagnostics:i}=await Bi(e,t);if(Ri(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 Gi(s,e.signal)}catch(e){return Ui(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?.()??Ti(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 jr)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 Wi(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},qi=e=>{switch(e.kind){case`cancelled`:return new bi;case`unsatisfiable`:return new xi;case`unavailable`:return new Mr;case`session-changed`:return new Nr;case`insufficient`:return new jr(e.obtained,e.required);case`exhausted`:return e.error;case`transport-failure`:return e.error;default:return}},Ji=(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 bi}:{settle:`resolve`,value:ra(t,e)};case`insufficient`:return{settle:`resolve`,value:ra(e.response?.raw??t,e)};default:return{settle:`resolve`,value:ra(t,e)}}},Yi=(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:qi(e)??t}}},Xi=new WeakSet,Zi=new WeakSet,Qi=new WeakSet,$i=new WeakSet,ea=new WeakSet,ta=new WeakSet,na=new WeakSet,ra=(e,t)=>{switch(t.kind){case`cancelled`:Xi.add(e);break;case`exhausted`:Zi.add(e);break;case`insufficient`:Qi.add(e);break;case`unsatisfiable`:$i.add(e);break;case`unavailable`:ea.add(e);break;case`session-changed`:ta.add(e);break;case`transport-failure`:na.add(e)}return e},ia=e=>Xi.has(e),aa=e=>Zi.has(e),oa=e=>Qi.has(e),sa=e=>$i.has(e),ca=e=>ea.has(e),la=e=>ta.has(e),ua=e=>na.has(e),da=`https://passflow-relative.invalid`,fa=()=>{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:da},pa=(e,t=fa())=>{let n=t===da,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}},ma=(e,t)=>typeof t==`string`?[e.toLowerCase(),t]:void 0,ha=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=ma(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=ma(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=ma(n,Array.isArray(r)?r.join(`, `):r);e&&t.push(e)}return Object.freeze(t)},ga=e=>{let t=e.base===void 0?pa(e.url):pa(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:ha(e.headers),bodyKind:e.bodyKind,...`body`in e?{body:e.body}:{}};return Object.freeze(n)},_a=(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},va=e=>{let t={};for(let[n,r]of e)t[n]=r;return t},ya=new Set([`GET`,`HEAD`,`OPTIONS`]),ba=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.clone==`function`&&`method`in e,xa=e=>typeof e==`string`?e:ba(e)?e.url:String(e),Sa=(e,t)=>(t?.method??(ba(e)?e.method:void 0)??`GET`).toUpperCase(),Ca=e=>e==null?`none`:typeof e==`string`?`reusable`:typeof e.getReader==`function`?`one-shot`:`reusable`,wa=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},Ta=(e,t,n)=>e===void 0||e===`always`?!0:e===`idempotent-only`?ya.has(t.method):typeof e==`function`?e(t):!(e.maxBodyBytes!==void 0&&n!==void 0&&n>e.maxBodyBytes),Ea=(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}`))}),Da=(e,t)=>va(_a(e.headers,t?.authorizationSwap)),Oa=e=>{if(!e||!(`headers`in e))return e;let{headers:t,...n}=e;return n},ka=(e,t)=>t&&`headers`in t&&t.headers!==void 0?t.headers:ba(e)?e.headers:void 0,Aa=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},ja=(e,t,n)=>new Request(e,{headers:Da(t,n)}),Ma=(e,t,n)=>{let r=xa(e),i=Sa(e,t),a=ka(e,t),o=(e,t)=>ga({url:r,method:i,headers:a,bodyKind:e,...t===void 0?{}:{body:t}});if(ba(e)){if(e.body===null||e.body===void 0){let a=o(`none`);return Ta(n,{url:r,method:i,bodyKind:`none`})?{replayable:!0,bodyKind:`none`,forwardInput:e,forwardInit:t,snapshot:a,replay:(n,r)=>n(ja(e,a,r),Oa(t))}:Ea(`none`,`the replay policy refused this request`,e,a,t)}let a=o(`request-clone`);if(!Ta(n,{url:r,method:i,bodyKind:`request-clone`}))return Ea(`request-clone`,`the replay policy refused this request`,e,a,t);let s;try{s=e.clone()}catch{return Ea(`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(ja(s,a,n),Oa(t))}}let s=Ca(t?.body);if(s===`one-shot`)return Ea(`one-shot`,`a streaming request body is consumed by the first send`,e,o(`one-shot`),t);if(!Ta(n,{url:r,method:i,bodyKind:s},wa(t?.body)))return Ea(s,`the replay policy refused this request`,e,o(s),t);let c=t&&`body`in t?Aa(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,{...Oa(t),...c===void 0?{}:{body:c},headers:Da(l,n),method:l.method})}},Na=e=>typeof e==`object`&&!!e,Pa=e=>t=>{if(!Na(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},Fa=e=>{let t=e?.url??``,n=e?.baseURL;return!n||/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:`${n.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`},Ia=e=>(e?.method??`GET`).toUpperCase(),La=e=>e==null?`none`:Na(e)&&(typeof e.pipe==`function`||typeof e.getReader==`function`)?`one-shot`:`reusable`,Ra=(e,t,n)=>{let r=va(_a(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}:{}}},za=(e,t,n,r,i,a)=>{let o=t??e?.config,s=La(o?.data),c=a??ga({url:Fa(o),method:Ia(o),headers:o?.headers,bodyKind:s,body:o?.data}),l={url:c.href,method:c.method,bodyKind:s},u=s!==`one-shot`&&Ta(i.replay,l);return{status:e?.status??0,getHeader:Pa(e?.headers),readBody:async()=>e?.data,request:c,replay:async e=>{let t=Ae(Ra(o??{},c,e));try{let e=await r(t);return za(e,e?.config??t,e,r,i,c)}catch(e){let n=Na(e)?e:{};if(!n.response||typeof n.response.status!=`number`||Cr(e))throw e;return{...za(n.response,n.config??t,e,r,i,c),rejected:!0}}},markers:{...ke(o)?{upgradeTransaction:!0}:{},...je(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}},Ba=(e,t)=>async n=>{let r=Ai(e),i=Na(n)?n:{},a=Yi(await Ki(za(i.response,i.config,i.response,t,r),r),n);if(a.settle===`reject`)throw a.error;return a.value},Va=(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,Ba(t,i)),o=!1;return()=>{o||(o=!0,e.interceptors.response.eject(a))}},Ha=(e,t)=>{let n=c.default.create(e);return t(n),n},Ua=0,Wa=(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)}:{}}},Ga=e=>t=>e.headers?.get(t),Ka=(e,t,n,r,i)=>({status:e.status,getHeader:Ga(e),readBody:()=>e.clone().json(),request:t.snapshot,replay:async e=>Ka(await t.replay(n,e),t,n,r,i),markers:r,raw:e,replayable:t.replayable,replayUnsupportedReason:t.reason,signal:i,responseType:e.type}),qa=(e,t)=>{let n=(t,n)=>{Ua+=1;try{return e(t,n)}finally{--Ua}};return async(e,r)=>{if(Ua>0)return n(e,r);let i=Ai(t),a=Ma(e,r,i.replay),o=await n(a.forwardInput,a.forwardInit),s=Ji(await Ki(Ka(o,a,n,{},Wa(e,r)),i),o,i);if(s.settle===`reject`)throw s.error;return s.value}},Ja=new Set(pi.filter(e=>!e.requiresPrepare).map(e=>e.type)),Ya=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}},Xa=e=>Cr(e)&&!wr(e),Za=e=>({async prepare(t){if(!Ja.has(t))try{let n=e.relyingPartyId?.();return Ya(await e.startUpgrade(n?{method:t,relying_party_id:n}:{method:t}))}catch(e){if(Xa(e))throw e;let t=Or(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(Xa(t))throw t;let n=Or(t,`refresh`);throw n.status===401&&Ar(n)&&e.markSessionInvalid?.(),n}}}),Qa=e=>e===void 0?[]:(Array.isArray(e)?e:[e]).filter(e=>e!==``),$a=e=>{let t,n=e=>e!==void 0&&t===e,r=r=>{let i=()=>{if(!n(r()))throw new $({kind:`session_changed`})};return Za({...e,relyingPartyId:()=>t?.options.relyingPartyId??e.relyingPartyId?.(),startUpgrade:t=>(i(),e.startUpgrade(t)),commitRefresh:t=>(i(),e.commitRefresh(t,r()?.pin)),...e.markSessionInvalid?{markSessionInvalid:()=>{n(r())&&e.markSessionInvalid?.()}}:{}})},i=(t,n)=>{let i={},a={controller:new ki({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:Qa(t.backend)},generation:n};return i.current=a,a},a=async(r,i)=>{let a=t;if(!a)throw new Mr(`Step-up verification is not enabled on this Passflow instance`);a.controller.active||(a.pin=e.readSessionPin?.());let o=await a.controller.elevate(r,i);if(!n(a))throw new Nr;return o},o=()=>{let n=t,r=n?.scope??{passflow:e.passflowDomain,backend:[]},i=n?.options;return{elevate:a,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}:{}}},s;return Object.defineProperties(async e=>{let t=e?.acrValues===void 0?void 0:B(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}},o=(await a(n,{kind:`imperative`,...r?{requested:i}:{}})).obtained.acrValues;return{status:`elevated`,...o===void 0?{}:{acr:o}}},{enable:{value:n=>{s?.(),t=i(n,0);let r=[];if(e.attachInternalSeam){let t=e.attachInternalSeam;t(e=>Ba(o,e)),r.push(()=>t(void 0))}n.interceptFetch&&r.push(Nt((e,t,n)=>qa(e,o)(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 s=()=>{if(!a){a=!0;for(let e of r)e();t=void 0,s=void 0}},s},enumerable:!0},enabled:{enumerable:!0,get(){return t!==void 0&&e.canCommit().ok}},elevate:{enumerable:!0,value:(e,t)=>a(e,t??{kind:`imperative`})},withAuth:{enumerable:!0,value:e=>{if(e)return qa(e,o);let t=typeof globalThis>`u`?void 0:globalThis;if(!t||typeof t.fetch!=`function`)throw Error(`Passflow: withAuth() needs a fetch to wrap — this runtime has none.`);return qa(t.fetch.bind(t),o)}},attachAuth:{enumerable:!0,value:e=>Va(e,o)}})},eo,to=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??R,this.deferFederatedLanding=e.deferFederatedLanding??!1,this.storageManager=new F({prefix:e.keyStoragePrefix??``,storage:this.platform.storage}),this.deviceService=new I(this.storageManager),this.authApi=new ct(e,this.storageManager,this.deviceService),this.appApi=new nt(e,this.storageManager,this.deviceService),this.userApi=new yt(e,this.storageManager,this.deviceService),this.settingApi=new dt(e,this.storageManager,this.deviceService),this.tenantApi=new ft(e,this.storageManager,this.deviceService),this.invitationApi=new ut(e,this.storageManager,this.deviceService),this.twoFactorApi=new _t(e,this.storageManager,this.deviceService),this.upgradeApi=new vt(e,this.storageManager,this.deviceService),this.upgradeDomain=Pe(e.url),this.subscribeStore=new dr,this.tokenCacheService=new ai(this.storageManager,this.authApi,this.subscribeStore,this.platform),this.scopes=r??_,this.createTenantForNewUser=e.createTenantForNewUser??!1;let i=wn(e.refreshCoordination,this.platform,e.keyStoragePrefix,{tokenKeys:()=>this.storageManager.tokenKeys()});this.authService=new ti(this.authApi,this.deviceService,this.storageManager,this.subscribeStore,this.tokenCacheService,this.scopes,this.createTenantForNewUser,this.url,{createSession:this.createSessionCallback,expiredSession:this.expiredSessionCallback},this.appId??``,e.tokenExchange,this.platform,()=>this.readPkceEnabled(),{coordination:i,...e.refreshStrikes===void 0?{}:{strikes:e.refreshStrikes}}),this.tokenCacheService.attachRefreshController(this.authService.refresh);for(let e of this.axiosClients())e.setRefreshHandler(e=>this.authService.refresh.ensureFresh(e));this.userService=new si(this.userApi,this.deviceService,this.platform),this.tenantService=new ii(this.tenantApi,this.scopes),this.tenant=this.tenantService,this.invitationService=new ni(this.invitationApi),this.twoFactorService=new oi(this.twoFactorApi,this.subscribeStore,this.authService),this.twoFactor=this.twoFactorService,this.upgrade=$a({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(N.access_token);return e?{from:`Bearer ${e}`,to:`Bearer ${e}`}:void 0},attachInternalSeam:e=>this.attachUpgradeSeam(e),onSessionChange:e=>this.subscribeToSessionChange(e)}),e.parseQueryParams&&this.checkAndSetTokens(),this.setTokensToCacheFromLocalStorage()}readPkceEnabled(){if(!this.appId)return Promise.resolve(!1);if(!this.pkceEnabledRead){let e=this.appApi.getAppSettings().then(e=>e.pkce_enabled);this.pkceEnabledRead=e,e.catch(()=>{this.pkceEnabledRead===e&&(this.pkceEnabledRead=void 0)})}return this.pkceEnabledRead}setAppId(e){this.appId=e,this.pkceEnabledRead=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}withAuth(e){return this.upgrade.withAuth(e)}attachAuth(e){return this.upgrade.attachAuth(e)}createClient(e){return Ha(e,e=>this.upgrade.attachAuth(e))}readAssuranceBar(){let e=this.storageManager.getToken(N.access_token);if(e)try{let t=M(e),n=typeof t.acr==`string`?t.acr:void 0;if(!n)return;let r=B(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,[Z.SignIn,Z.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 H?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()}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(`scopes`)?.split(`,`)??this.scopes;if(n){if(!Ir(n)){W(this.subscribeStore,{operation:`tokens.from-url`,message:`Invalid access token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(e);return}if(r&&!Ir(r)){W(this.subscribeStore,{operation:`tokens.from-url`,message:`Invalid refresh token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(e);return}if(i&&!Ir(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:a};this.cleanupUrlParams(e),this.error=void 0,gr(this.url,this.appId,t).then(()=>{this.storageManager.clearDeliveryMode(),this.storageManager.saveTokens(t),this.tokenCacheService.setTokensCache(t),this.authService.refresh.sessionStarted()}).then(()=>(this.subscribeStore.notify(Z.SignIn,{tokens:t,parsedTokens:this.getParsedTokens(),source:`tokens-in-url`}),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:`TOKEN_NOT_VERIFIED`,originalError:e}))}else this.cleanupUrlParams(e),this.deferFederatedLanding||this.takeFederatedLanding(),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}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();return this.platform.replaceUrl(e.pathname+e.search+(r?`#${r}`:``)),Ir(n)?(this.subscribeStore.notify(Z.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=Lr(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=>r.get(e));if(!i&&!t.some(e=>n.get(e)))return;for(let e of[...t,`client_challenge`])n.delete(e);let a=n.toString();this.platform.replaceUrl(e.pathname+(a?`?${a}`:``)+(i?``:e.hash??``))}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===P.Cookie||e===P.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){return await this.authService.signIn(e)}async signUp(e){return await this.authService.signUp(e)}passwordlessSignIn(e){return this.authService.passwordlessSignIn(e)}async passwordlessSignInComplete(e){return await this.authService.passwordlessSignInComplete(e)}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`)}}handleError(e,t,n){let r={operation:t,message:e instanceof Error?e.message:`${n} failed`,originalError:e,code:e instanceof H?e.id:void 0};throw W(this.subscribeStore,r),e}async logOut(){try{let e=await this.authService.logOut();this.twoFactorService.clearPartialAuthState(),this.notifySignedOut(e),await this.submitSessionCheck()}catch(e){this.handleError(e,`log-out`,`Log out`)}}federatedAuthWithPopup(e){this.authService.federatedAuthWithPopup(e)}federatedAuthWithRedirect(e){this.authService.federatedAuthWithRedirect(e)}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(Z.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()}sendPasswordResetEmail(e){return this.authService.sendPasswordResetEmail(e)}async resetPassword(e,t,n){return await this.authService.resetPassword(e,t,n)}async getAppSettings(){try{return 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){return await this.authService.passkeyRegister(e)}async passkeyAuthenticate(e){return await this.authService.passkeyAuthenticate(e)}setTokens(e){let t=this.getDeliveryMode(),n=t===P.Cookie||t===P.BFF;this.storageManager.saveTokens(e,n?t:void 0),this.tokenCacheService.setTokensCache(e),this.authService.refresh.sessionStarted(),this.subscribeStore.notify(Z.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 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={}){this.authService.authRedirect(e)}getDeliveryMode(){return this.authService.tokenDeliveryManager.getMode()}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(Z.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(Z.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`)}}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()}};eo=to,eo.version=h,exports.APP_ID_HEADER_KEY=d,exports.APP_SECRET_NAMES=Le,exports.AUTHORIZATION_HEADER_KEY=f,exports.AppAPI=nt,exports.AuthAPI=ct,exports.AuthService=ti,exports.CLIAuthAPI=lt,exports.DEFAULT_GROUP_NAME=y,exports.DEFAULT_SCOPES=_,exports.DEFAULT_UPGRADE_FACTORS=pi,exports.DEVICE_ID_HEADER_KEY=p,exports.DEVICE_TYPE_HEADER_KEY=m,exports.ERROR_MESSAGE_MAX_LENGTH=D,exports.FETCH_PRIORITY_OIDC=bt,exports.FETCH_PRIORITY_UPGRADE=xt,exports.FetchMiddlewareContractError=St,exports.INSUFFICIENT_USER_AUTHENTICATION=fe,exports.InvitationAPI=ut,exports.InvitationService=ni,exports.M2MClient=Ht,exports.M2MConfigError=Lt,exports.M2MError=U,exports.M2MErrorCodes=Rt,exports.M2MNetworkError=Ft,exports.M2MTokenParseError=It,exports.M2M_DEFAULTS=zt,exports.MASKED_SECRET_PREFIX=Re,exports.MINIMAL_DEFAULT_SCOPES=g,exports.OS=Ve,exports.PASSFLOW_CLOUD_URL=v,exports.POPUP_HEIGHT=x,exports.POPUP_POLL_INTERVAL_MS=S,exports.POPUP_TIMEOUT_MS=C,exports.POPUP_WIDTH=b,exports.Passflow=to,exports.PassflowAdminEndpointPaths=Ne,exports.PassflowEndpointPaths=V,exports.PassflowError=H,exports.PassflowEvent=Z,exports.PassflowRefreshError=J,exports.PopupClosedError=L,exports.Providers=Ie,exports.RECOVERABLE_COMMIT_ERROR_IDS=_r,exports.REFRESH_AUTH_FAILURE_IDS=Nn,exports.RefreshErrorId=q,exports.RequestMethod=Me,exports.SDK_VERSION=h,exports.SESSION_INVALIDATING_COMMIT_ERROR_IDS=vr,exports.SETTINGS_MASKED_VALUE_UNKNOWN_ERROR_ID=ze,exports.SessionState=oe,exports.SettingAPI=dt,exports.TOKEN_EXPIRY_BUFFER_SECONDS=w,exports.TenantAPI=ft,exports.TenantService=ii,exports.TenantUserMembership=ri,exports.TokenCacheService=ai,exports.TokenDeliveryMode=P,exports.TokenType=N,exports.TwoFactorApiClient=_t,exports.TwoFactorPolicy=We,exports.TwoFactorService=oi,exports.UPGRADE_REQUIRED=pe,exports.USERNAME_MAX_LENGTH=E,exports.USERNAME_MIN_LENGTH=T,exports.UpgradeAPI=vt,exports.UpgradeCancelledError=bi,exports.UpgradeCommitInterruptedError=Gn,exports.UpgradeController=ki,exports.UpgradeErrorIds=Q,exports.UpgradeFactorError=ci,exports.UpgradeInsufficientError=jr,exports.UpgradeSessionChangedError=Nr,exports.UpgradeTransportError=$,exports.UpgradeUnavailableError=Mr,exports.UpgradeUnsatisfiableError=xi,exports.UserAPI=yt,exports.UserService=si,exports.WebAdapter=ce,exports.classifyUpgradeError=Or,exports.factorRegistry=mi,exports.fetchRegistryState=Pt,exports.getOSFromDeviceType=He,exports.invalidatesSessionOnCommit=Ar,exports.isEmailVerificationStep=Fe,exports.isMaskedSecret=Be,exports.isRecoverableCommitFailure=kr,exports.isRetryableUpgradeKind=br,exports.isTokenExpired=j,exports.isUpgradeCancelled=ia,exports.isUpgradeExhausted=aa,exports.isUpgradeInsufficient=oa,exports.isUpgradeSessionChanged=la,exports.isUpgradeTransportError=wr,exports.isUpgradeTransportFailure=ua,exports.isUpgradeUnavailable=ca,exports.isUpgradeUnsatisfiable=sa,exports.isValidEmail=Rr,exports.isValidJWTFormat=Ir,exports.isValidPhoneNumber=zr,exports.isValidUsername=Br,exports.parseChallengeBody=be,exports.parseChallengeHeader=ye,exports.parseToken=M,exports.parseUpgradeChallenge=we,exports.passkeyFactor=fi,exports.pathWithParams=Ue,exports.recoveryCodesFactor=di,exports.registerFetchMiddleware=Nt,exports.requiredAcrLevel=de,exports.resolveUpgradeDomain=Pe,exports.sanitizeErrorMessage=Lr,exports.selectFactors=yi,exports.totpFactor=ui,exports.webAdapter=R;
|
|
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=`0.28.0`,d=`X-Passflow-Clientid`,f=`Authorization`,p=`X-Passflow-DeviceId`,m=`X-Passflow-DeviceType`,h=u,g=[`id`,`offline`,`openid`],_=[`id`,`offline`,`tenant`,`email`,`oidc`,`openid`,`access:tenant:all`],v=`https://auth.passflow.cloud`,y=`default`,b=500,x=600,ee=100,S=6e4,C=30,w=3,T=30,E=200,D=[];for(let e=0;e<256;++e)D.push((e+256).toString(16).slice(1));function te(e,t=0){return(D[e[t+0]]+D[e[t+1]]+D[e[t+2]]+D[e[t+3]]+`-`+D[e[t+4]]+D[e[t+5]]+`-`+D[e[t+6]]+D[e[t+7]]+`-`+D[e[t+8]]+D[e[t+9]]+`-`+D[e[t+10]]+D[e[t+11]]+D[e[t+12]]+D[e[t+13]]+D[e[t+14]]+D[e[t+15]]).toLowerCase()}var O=new Uint8Array(16);function ne(){return crypto.getRandomValues(O)}function re(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():ie(e,t,n)}function ie(e,t,n){e=e||{};let r=e.random??e.rng?.()??ne();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 te(r)}var ae=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 oe(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 k=class{constructor(e){this.storageManager=e}isTokenTypeExpired(e){let t=this.storageManager.getToken(e);if(!t)return!0;let n=j(t);return!n||A(n)}parseTokenType(e){let t=this.storageManager.getToken(e);if(t)return j(t)}};function A(e,t=30){return Math.floor(Date.now()/1e3)+t>e.exp}function j(e){let t=e.split(`.`)[1];if(!t)throw Error(`Invalid token string`);let n=t.replace(/-/g,`+`).replace(/_/g,`/`),r=oe(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`?ae(a.passflow_tm):void 0,a}var M=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}({}),N=function(e){return e.JsonBody=`json_body`,e.Cookie=`cookie`,e.Mobile=`mobile`,e.BFF=`bff`,e}({}),se=function(e){return e.Unknown=`unknown`,e.Valid=`valid`,e.Invalid=`invalid`,e}({}),ce=class{constructor(e){this.storageManager=e,this.mode=`json_body`,this.sessionState=`unknown`,this.isInitializedFlag=!1,this.STORAGE_PREFIX=`passflow_`,this.DELIVERY_MODE_KEY=`${this.STORAGE_PREFIX}delivery_mode`,this.SESSION_STATE_KEY=`${this.STORAGE_PREFIX}session_state`,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.clearPersistedMode(),this.clearPersistedSessionState()}loadPersistedMode(){try{let e=this.storageManager.storage.getItem(this.DELIVERY_MODE_KEY);e&&Object.values(N).includes(e)&&(this.mode=e,this.isInitializedFlag=!0)}catch{}}loadPersistedSessionState(){try{let e=this.storageManager.storage.getItem(this.SESSION_STATE_KEY);e&&Object.values(se).includes(e)&&(this.sessionState=e)}catch{}}persistMode(){try{this.storageManager.storage.setItem(this.DELIVERY_MODE_KEY,this.mode)}catch{}}persistSessionState(){try{this.storageManager.storage.setItem(this.SESSION_STATE_KEY,this.sessionState)}catch{}}clearPersistedMode(){try{this.storageManager.storage.removeItem(this.DELIVERY_MODE_KEY)}catch{}}clearPersistedSessionState(){try{this.storageManager.storage.removeItem(this.SESSION_STATE_KEY)}catch{}}},P=class{constructor({storage:e,prefix:t}={}){this.keyStoragePrefix=``,this.scopes=`${this.keyStoragePrefix}tokens_scopes`,this.deviceId=`${this.keyStoragePrefix}passflowDeviceId`,this.invitationToken=`${this.keyStoragePrefix}passflowInvitationToken`,this.previousRedirectUrl=`${this.keyStoragePrefix}passflowPreviousRedirectUrl`,this.STORAGE_PREFIX=`passflow_`,this.ID_TOKEN_KEY=`${this.STORAGE_PREFIX}id_token`,this.CSRF_TOKEN_KEY=`${this.STORAGE_PREFIX}csrf_token`,this.DELIVERY_MODE_KEY=`${this.STORAGE_PREFIX}delivery_mode`,this.storage=e??localStorage,this.keyStoragePrefix=t?`${t}_`:``}saveTokens(e,t){let{id_token:n,access_token:r,refresh_token:i,scopes:a}=e;t===N.Cookie||t===N.BFF?n&&this.storage.setItem(this.ID_TOKEN_KEY,n):(n&&this.storage.setItem(this.getKeyForTokenType(M.id_token),n),r&&this.storage.setItem(this.getKeyForTokenType(M.access_token),r),i&&this.storage.setItem(this.getKeyForTokenType(M.refresh_token),i),a&&this.storage.setItem(this.scopes,a.join(`,`)))}getToken(e){let t=this.getKeyForTokenType(e);return this.storage.getItem(t)??void 0}getTokens(){let e=this.getDeliveryMode();if(e===N.Cookie||e===N.BFF){let e=this.storage.getItem(this.ID_TOKEN_KEY);return e?{id_token:e}:void 0}let t=this.storage.getItem(this.getKeyForTokenType(M.access_token));if(t)return{access_token:t,id_token:this.storage.getItem(this.getKeyForTokenType(M.id_token))??void 0,refresh_token:this.storage.getItem(this.getKeyForTokenType(M.refresh_token))??void 0,scopes:this.storage.getItem(this.scopes)?.split(`,`)??void 0}}getScopes(){return this.storage.getItem(this.scopes)?.split(`,`)??void 0}hasJsonModeTokens(){return!!this.storage.getItem(this.getKeyForTokenType(M.access_token))}hasCookieModeIdToken(){return!!this.storage.getItem(this.ID_TOKEN_KEY)}deleteToken(e){let t=this.getKeyForTokenType(e);this.storage.removeItem(t)}deleteTokens(){this.storage.removeItem(this.getKeyForTokenType(M.id_token)),this.storage.removeItem(this.getKeyForTokenType(M.access_token)),this.storage.removeItem(this.getKeyForTokenType(M.refresh_token)),this.storage.removeItem(this.scopes),this.clearIdToken(),this.clearDeliveryMode(),this.clearCsrfToken()}getDeviceId(){return this.storage.getItem(this.deviceId)??void 0}setDeviceId(e){this.storage.setItem(this.deviceId,e)}deleteDeviceId(){this.storage.removeItem(this.deviceId)}setInvitationToken(e){this.storage.setItem(this.invitationToken,e)}getInvitationToken(){return this.storage.getItem(this.invitationToken)??void 0}deleteInvitationToken(){this.storage.removeItem(this.invitationToken)}setPreviousRedirectUrl(e){this.storage.setItem(this.previousRedirectUrl,e)}getPreviousRedirectUrl(){return this.storage.getItem(this.previousRedirectUrl)??void 0}deletePreviousRedirectUrl(){this.storage.removeItem(this.previousRedirectUrl)}setDeliveryMode(e){try{this.storage.setItem(this.DELIVERY_MODE_KEY,e)}catch{}}getDeliveryMode(){try{let e=this.storage.getItem(this.DELIVERY_MODE_KEY);if(e&&Object.values(N).includes(e))return e}catch{}}clearDeliveryMode(){try{this.storage.removeItem(this.DELIVERY_MODE_KEY)}catch{}}getIdToken(){try{return this.storage.getItem(this.ID_TOKEN_KEY)??void 0}catch{return}}setIdToken(e){try{this.storage.setItem(this.ID_TOKEN_KEY,e)}catch{}}clearIdToken(){try{this.storage.removeItem(this.ID_TOKEN_KEY)}catch{}}getCsrfToken(){try{return this.storage.getItem(this.CSRF_TOKEN_KEY)??void 0}catch{return}}setCsrfToken(e){try{this.storage.setItem(this.CSRF_TOKEN_KEY,e)}catch{}}clearCsrfToken(){try{this.storage.removeItem(this.CSRF_TOKEN_KEY)}catch{}}tokenKeys(){return[this.getKeyForTokenType(M.id_token),this.getKeyForTokenType(M.access_token),this.getKeyForTokenType(M.refresh_token),this.scopes,this.ID_TOKEN_KEY,this.CSRF_TOKEN_KEY,this.DELIVERY_MODE_KEY]}getKeyForTokenType(e){return`${this.keyStoragePrefix}${e}`}},F=class{constructor(e){this.storageManager=e??new P}getDeviceId(){let e=this.storageManager.getDeviceId();if(!e){let e=this.generateUniqueDeviceId();return this.storageManager.setDeviceId(e),e}return e}generateUniqueDeviceId(){return re()}},I=class extends Error{constructor(e=`Authentication popup was closed`){super(e),this.name=`PopupClosedError`}},le=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?new Promise((e,t)=>{let n=Date.now(),r=setInterval(()=>{if(o.closed)clearInterval(r),t(new I);else if(Date.now()-n>6e4)clearInterval(r),o.close(),t(Error(`Authentication popup timed out`));else try{if(o.location.href.startsWith(a)){let t=o.location.search,n=o.location.hash;clearInterval(r),o.close(),e({callbackSearch:t,callbackHash:n})}}catch{}},100)}):(window.location.href=e,new Promise(()=>{}))}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`}},L=new le,ue=/^[0-9]+$/,de=Object.freeze({unorderable:!1,zero:!1}),R=e=>ue.test(e)?Number.parseInt(e,10):void 0,z=e=>{if(!e)return de;let t=e.split(/\s+/).filter(e=>e!==``);if(t.length===0)return de;let n=[];for(let e of t){let t=R(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}},fe=e=>z(e).level,pe=`insufficient_user_authentication`,me=`upgrade_required`,he=/([A-Za-z0-9!#$%&'*+\-.^_`|~]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]*))/g,ge=e=>e.replace(/\\(.)/g,`$1`),_e=e=>{let t={};he.lastIndex=0;for(let n of e.matchAll(he)){let e=n[1];if(!e)continue;let r=n[2],i=n[3];t[e.toLowerCase()]=r===void 0?i??``:ge(r)}return t},ve=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}},ye=e=>{let t=ve(e);return t.kind===`valid`?t.value:void 0},be=(e,t)=>{if(!e||!/(^|[\s,])Bearer\b/i.test(e))return;let n=_e(e);if(n.error===`insufficient_user_authentication`)return{acrValues:n.acr_values||void 0,maxAge:ye(n.max_age),status:t}},xe=(e,t)=>{if(!e||typeof e!=`object`)return;let n=e;if(n.error===`upgrade_required`)return{acrValues:typeof n.acr_values==`string`&&n.acr_values?n.acr_values:void 0,maxAge:ye(n.max_age),status:t}},Se=(e,t,n)=>({channel:e,acr:z(t.acrValues),maxAge:ve(n),raw:t.acrValues}),Ce=e=>e?_e(e):{},we=(e,t)=>{let{status:n}=e;if(n!==401&&n!==403)return{diagnostics:[]};let r=t?.requireChallengeChannel===`header`,i=e.getHeader(`www-authenticate`),a=be(i,n),o=r?void 0:xe(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(Se(`header`,a,Ce(i).max_age)),o){let t=e.body;l.push(Se(`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)},diagnostics:s}},Te=(e,t,n)=>we({status:e,getHeader:t,body:n}).challenge,Ee=`__passflowUpgradeTransaction`,De=`__passflowUpgradeReplayed`,Oe=(e,t)=>typeof e==`object`&&!!e&&e[t]===!0,ke=e=>({...e??{},[Ee]:!0}),Ae=e=>Oe(e,Ee),je=e=>({...e,[De]:!0}),Me=e=>Oe(e,De),Ne=function(e){return e.GET=`get`,e.POST=`post`,e.PUT=`put`,e.PATCH=`patch`,e.DELETE=`delete`,e}({}),B=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.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.cliAuthStatus=`/cli/auth/status/:sessionId`,e.cliAuthComplete=`/cli/auth/complete`,e.upgradeStart=`/auth/upgrade/start`,e}({}),Pe=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}({}),Fe=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}},Ie=e=>typeof e==`object`&&!!e&&e.email_verification_required===!0,Le=`error.service.unavailable`,Re=`Passflow is temporarily unavailable. Please try again in a moment.`,V=class extends Error{constructor(e,t){super(),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=function(e){return e.google=`google`,e.facebook=`facebook`,e}({}),Be=Object.freeze([`debug_otp_code_for_registration`,`fcm_server_key`,`webpush_vapid_private_key`]),Ve=`mask://`,He=`error.server.update.settings.masked.value.unknown`,Ue=e=>typeof e==`string`&&e.startsWith(`mask://`),We=function(e){return e.web=`web`,e.ios=`ios`,e.android=`android`,e}({});function Ge(e){return e}function H(e,t){let n=e;return Object.entries(t).forEach(([e,t])=>{n=n.replace(`:${e}`,t)}),n}var Ke=function(e){return e.Disabled=`disabled`,e.Optional=`optional`,e.Required=`required`,e}({}),qe=3,Je=1e3,Ye=e=>t=>{let n=e.headers?.[t]??e.headers?.[t.toLowerCase()];return Array.isArray(n)?n.join(`, `):n},Xe=e=>Te(e.status,Ye(e),e.data),Ze=e=>Xe(e)!==void 0,Qe=e=>c.default.isAxiosError(e)&&!e.response&&(e.code===c.AxiosError.ERR_NETWORK||!e.code&&e.cause instanceof TypeError),$e=[502,503,504],et=e=>typeof e==`object`&&!!e&&typeof e.error==`object`&&e.error!==null,tt=(e,t)=>{let n=new c.AxiosError(e.message,e.code);return e.cause instanceof TypeError&&(n.cause=e.cause),new V({id:Le,message:Re,status:t,location:e.config?.url??`unknown`,time:new Date().toISOString()},{cause:n})},nt=e=>e?.includes(B.refresh)??!1,rt=e=>e?.includes(`logout`)??!1,it=`__passflowOwnBearer`,at=e=>typeof e==`object`&&!!e&&e[it]===!0,ot=e=>e?{headers:{[f]:`Bearer ${e}`},[it]:!0}:{},st=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/`],this.protectedEndpoints=[`logout`,`refresh`,`upgrade`];let{url:r,appId:i,keyStoragePrefix:a}=e;this._platform=e.platform??L,this.url=r||`https://auth.passflow.cloud`,this.upgradeDomain=Fe(r),this.storageManager=t??new P({prefix:a??``}),this.deviceService=n??new F(this.storageManager),this.tokenService=new k(this.storageManager),this.tokenDeliveryManager=new ce(this.storageManager),i&&(this.appId=i,this.defaultHeaders={...this.defaultHeaders,[d]:i});let o=this.deviceService.getDeviceId();this.defaultHeaders={...this.defaultHeaders,[p]:o,[m]:this._platform.getDeviceType()},this.detectCookieSupport(),this.instance=c.default.create({baseURL:this.url,headers:{...this.defaultHeaders}}),this.instance.interceptors.request.use(async e=>{if(this.isNonAuthEndpoint(e.url)||at(e))return e;if(this.tokenDeliveryManager.isCookieMode()){e.withCredentials=!0;let t=this.storageManager.getCsrfToken();return t&&(e.headers[`X-CSRF-Token`]=t),e}if(nt(e.url))return e;let t=this.storageManager.getTokens();if(!t?.access_token)return e;let n=t.access_token;if(this.refreshHandler&&t.refresh_token&&!rt(e.url)){let e=j(t.access_token);if(A(e,30)){let t=!A(e,0);try{n=(await this.refreshHandler({trigger:`pre-request`,allowStale:t}))?.access_token??n}catch(e){if(!t)throw e}}}return e.headers[f]=`Bearer ${n}`,e}),this.instance.interceptors.response.use(e=>e,async e=>{if(e.response?.status!==401||nt(e.config?.url)||at(e.config)||this.isUpgradeTransactionError(e)||this.tokenDeliveryManager.setSessionInvalid(),e.response&&this.upgradeHandler){let t=Xe(e.response);if(t)try{return await this.upgradeHandler(e,t)}catch(t){if(t!==e)throw t}}return e.response?.status===429?await this.handleRateLimitError(e):this.handleAxiosError(e)})}isUpgradeTransactionError(e){return Ae(e.config)||e.response!==void 0&&Ze(e.response)}setUpgradeInterceptor(e){this.upgradeHandler=e}setRefreshHandler(e){this.refreshHandler=e}replay(e){return this.instance.request(e)}isProtectedEndpoint(e){return this.protectedEndpoints.some(t=>e?.includes(t))}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||nt(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>=qe)return Promise.reject(e);let i=Je*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(Qe(e))return Promise.reject(tt(e,0));if(!e.response)return Promise.reject(e);let t=e.response.status;if($e.includes(t)&&!et(e.response.data))return Promise.reject(tt(e,t));let n=e.response.data;if(`error`in n&&typeof n.error==`object`&&n.error!==null){let{error:e}=n;return Promise.reject(new V(e))}return Promise.reject(new V({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(Ne.GET,e,t)}post(e,t,n){return this.send(Ne.POST,e,{data:t,...n})}put(e,t,n){return this.send(Ne.PUT,e,{data:t,...n})}patch(e,t,n){return this.send(Ne.PATCH,e,{data:t,...n})}delete(e,t){return this.send(Ne.DELETE,e,t)}setAppId(e){this.appId=e,this.defaultHeaders={...this.defaultHeaders,[d]:e},this.instance.defaults.headers.common[d]=e}},ct=class{constructor(e,t,n){this.axiosClient=new st(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getAppSettings(){return this.axiosClient.get(B.appSettings)}},lt={withCredentials:!0},ut=15e3,dt=`Sign-in failed. Start again.`,ft=`Something went wrong. Try again later.`,pt=(e,t,n,r)=>{if(e instanceof V)return e;let i=e?.response?.data?.error;return new V({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()})},mt=class{constructor(e,t,n){this.axiosClient=new st(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}refreshToken(e,t,n,r){let i={access:n,scopes:t,...r?{upgrade:r}:{}},a={headers:{[f]:`Bearer ${e}`}};return this.axiosClient.post(B.refresh,i,r?ke(a):a)}signIn(e,t,n){let r={...e,device:t,os:n};return this.axiosClient.post(B.signin,r,lt)}signUp(e){let{create_tenant:t,anonymous:n}=e,r={...e,create_tenant:t??!1,anonymous:n??!1};return this.axiosClient.post(B.signup,r,lt)}async pkceExchange(e,t){try{return await this.axiosClient.post(B.pkceExchange,{authz_code:e,verifier:t},lt)}catch(e){throw pt(e,B.pkceExchange,`error.pkce.exchange`,dt)}}async passwordlessSignIn(e,t,n){let{create_tenant:r}=e,i={...e,create_tenant:r??!1,device:t,os:n};try{return await this.axiosClient.post(B.passwordless,i)}catch(e){throw pt(e,B.passwordless,`error.passwordless.start`,ft)}}async passwordlessSignInComplete(e){try{return await this.axiosClient.post(B.passwordlessComplete,e,lt)}catch(e){throw pt(e,B.passwordlessComplete,`error.passwordless.complete`,ft)}}async passwordlessStatus(e,t){try{return await this.axiosClient.post(B.passwordlessStatus,e,{...lt,timeout:ut,signal:t?.signal})}catch(e){throw pt(e,B.passwordlessStatus,`error.passwordless.status`,dt)}}async checkRedirectUrl(e){try{return(await this.axiosClient.post(B.redirectCheck,{redirect_url:e})).redirect_url}catch(e){throw pt(e,B.redirectCheck,`error.redirect.check`,ft)}}async passwordlessApprovalInfo(e){try{return await this.axiosClient.post(B.passwordlessApprovalInfo,e)}catch(e){throw pt(e,B.passwordlessApprovalInfo,`error.passwordless.approval`,ft)}}async passwordlessApprovalDecide(e){try{return await this.axiosClient.post(B.passwordlessApprovalDecide,e)}catch(e){throw pt(e,B.passwordlessApprovalDecide,`error.passwordless.approval`,ft)}}validateEmailCode(e){return this.axiosClient.post(B.passkeyValidate,{challenge_id:e.challenge_id,otp:e.otp},lt)}logOut(e,t,n=!1){let r=n?void 0:{refresh_token:t,device:e},i=n?Pe.logout:B.logout;return this.axiosClient.post(i,r)}validateSession(){return this.axiosClient.get(B.validateSession)}sendPasswordResetEmail(e){return this.axiosClient.post(B.sendPasswordResetEmail,e)}resetPassword(e,t,n,r){let i={password:e,scopes:t,...r?{code_challenge:r}:{}};return this.axiosClient.post(B.resetPassword,i,{headers:{[f]:`Bearer ${n}`,[d]:void 0}})}passkeyRegisterStart(e,t,n,r=!1){let{create_tenant:i}=e,a={...e,create_tenant:i??!1,device:t,os:n},o=r?Pe.passkeyRegisterStart:B.passkeyRegisterStart;return this.axiosClient.post(o,a)}passkeyRegisterComplete(e,t,n,r=!1){let i={challenge_id:n,device:t,passkey_data:e},a=r?Pe.passkeyRegisterComplete:B.passkeyRegisterComplete;return this.axiosClient.post(a,i,lt)}passkeyAuthenticateStart(e,t,n,r=!1){let i={...e,user_id:e.user_id??``,device:t,os:n},a=r?Pe.passkeyAuthenticateStart:B.passkeyAuthenticateStart;return this.axiosClient.post(a,i)}passkeyAuthenticateComplete(e,t,n,r=!1){let i={challenge_id:n,device:t,passkey_data:e},a=r?Pe.passkeyAuthenticateComplete:B.passkeyAuthenticateComplete;return this.axiosClient.post(a,i,lt)}passkeyValidate(e,t,n,r=!1,i){let a={otp:e,device:t,challenge_id:n},o=B.passkeyValidate;!i&&r&&(o=Pe.passkeyValidate);let s=i?{[d]:i}:{};return this.axiosClient.post(o,a,{headers:s})}},ht=class{constructor(e,t,n){this.axiosClient=new st(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getCLIAuthStatus(e){let t=H(B.cliAuthStatus,{sessionId:e});return this.axiosClient.get(t)}completeCLIAuth(e){return this.axiosClient.post(B.cliAuthComplete,e)}},gt=class{constructor(e,t,n){this.axiosClient=new st(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}requestInviteLink(e){return this.axiosClient.post(B.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=H(B.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=H(B.invitationDelete,{invitationID:e});return this.axiosClient.delete(t)}resendInvitation(e){let t=H(B.invitationResend,{invitationID:e});return this.axiosClient.post(t,{})}getInvitationLink(e){let t=H(B.invitationGetLink,{invitationID:e});return this.axiosClient.get(t)}},_t=class{constructor(e,t,n){this.axiosClient=new st(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getSettingsAll(){return this.axiosClient.get(B.settingsAll)}getPasswordPolicySettings(){return this.axiosClient.get(B.settingsPasswordPolicy)}getPasskeySettings(){return this.axiosClient.get(B.settingsPasskey)}},vt=class{constructor(e,t,n){this.axiosClient=new st(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}joinInvitation(e,t){let n={invite_token:e,scopes:t};return this.axiosClient.post(B.joinInvitation,n)}createTenant(e){let t={name:e};return this.axiosClient.post(B.tenantPath,t)}getTenantDetails(e){let t=`${B.tenantPath}/${e}`;return this.axiosClient.get(t)}updateTenant(e,t){let n=`${B.tenantPath}/${e}`,r={name:t};return this.axiosClient.put(n,r)}deleteTenant(e){let t=`${B.tenantPath}/${e}`;return this.axiosClient.delete(t)}getUserTenantMembership(){return this.axiosClient.get(B.tenantPath)}createGroup(e,t){let n=`${B.tenantPath}/${e}/group`,r={name:t};return this.axiosClient.post(n,r)}getGroupInfo(e,t){let n=`${B.tenantPath}/${e}/group/${t}`;return this.axiosClient.get(n)}updateGroup(e,t,n){let r=`${B.tenantPath}/${e}/group/${t}`,i={name:n};return this.axiosClient.put(r,i)}deleteGroup(e,t){let n=`${B.tenantPath}/${e}/group/${t}`;return this.axiosClient.delete(n)}addUserToGroup(e,t,n,r){let i=`${B.tenantPath}/${e}/group/${t}/add`,a={user_id:n,role:r};return this.axiosClient.post(i,a)}removeUserRolesFromGroup(e,t,n,r){let i=`${B.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=`${B.tenantPath}/${e}/group/${t}/change`,a={user_id:n,roles:r};return this.axiosClient.post(i,a)}deleteUserFromGroup(e,t,n){let r=`${B.tenantPath}/${e}/group/${t}/${n}`;return this.axiosClient.delete(r)}getRolesForTenant(e){let t=`${B.tenantPath}/${e}/role`;return this.axiosClient.get(t)}createRoleForTenant(e,t){let n=`${B.tenantPath}/${e}/role`,r={name:t};return this.axiosClient.post(n,r)}updateRole(e,t,n){let r=`${B.tenantPath}/${e}/role/${t}`,i={name:n};return this.axiosClient.put(r,i)}deleteRole(e,t){let n=`${B.tenantPath}/${e}/role/${t}`;return this.axiosClient.delete(n)}deleteUserFromTenant(e,t){let n=`${B.tenantPath}/${e}/user/${t}`;return this.axiosClient.delete(n)}getGroupInvitations(e,t,n,r){let i=`${B.tenantPath}/${e}/group/${t}/invitations`;return this.axiosClient.get(i,{params:{limit:n,skip:r}})}getTenantInvitations(e,t,n){let r=`${B.tenantPath}/${e}/invitations`;return this.axiosClient.get(r,{params:{limit:t,skip:n}})}invalidateInviteById(e,t,n){let r=`${B.tenantPath}/${e}/group/${t}/invite/${n}`;return this.axiosClient.delete(r)}invalidateInviteByEmail(e,t,n){let r=`${B.tenantPath}/${e}/group/${t}/invite/email/${n}`;return this.axiosClient.delete(r)}},yt=e=>e?{headers:{Authorization:`Bearer ${e}`}}:{},bt=e=>({withCredentials:!0,...yt(e)}),xt=({qr_code_image:e,qr_code:t,...n})=>({...n,qr_code:(t??e??``).replace(/^data:image\/png;base64,/,``)}),St={"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`},Ct=class{constructor(e,t,n){this.axiosClient=new st(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getStatus(e){return this.axiosClient.get(B.twoFactorStatus,ot(e))}async beginSetup(e){return xt(await this.axiosClient.post(B.twoFactorSetupBegin,{},ot(e)))}confirmSetup(e,t){return this.axiosClient.post(B.twoFactorSetupConfirm,e,ot(t))}async getEnrollment(e){return(await this.axiosClient.get(B.twoFactorEnrollment,ot(e))).enrollment}sendSetupLink(e){return this.axiosClient.post(B.twoFactorEnrollmentEmailLink,void 0,ot(e))}async beginEnrollment(e){return xt(await this.axiosClient.post(B.twoFactorEnrollmentBegin,void 0,ot(e)))}confirmEnrollment(e,t){return this.axiosClient.post(B.twoFactorEnrollmentConfirm,t,ot(e))}verify(e){let{tfa_token:t,code:n,trust_device:r}=e;return this.axiosClient.post(B.twoFactorVerify,{code:n,...r?{trust_device:!0}:{}},bt(t))}useRecoveryCode(e){let{tfa_token:t,recovery_code:n,trust_device:r}=e;return this.axiosClient.post(B.twoFactorRecovery,{recovery_code:n,...r?{trust_device:!0}:{}},bt(t))}disable(e){return this.axiosClient.delete(B.twoFactor,{data:e})}regenerateRecoveryCodes(e){return this.axiosClient.post(B.twoFactorRegenerateCodes,e)}validateTwoFactorSetupMagicLink(e){let t=`${B.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}}).catch(e=>{if(e instanceof V)return{success:!1,error:{code:St[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.`}}getAvailableMethods(){return this.axiosClient.get(B.TwoFactorMethodsAvailable)}getRegisteredMethods(){return this.axiosClient.get(B.TwoFactorMethodsRegistered)}startMethodSetup(e,t){return this.axiosClient.post(B.TwoFactorSetupStart,{...t,method:e})}completeMethodSetup(e,t){return this.axiosClient.post(B.TwoFactorSetupComplete,{...t,method:e})}removeMethod(e){let t=H(B.TwoFactorMethodRemove,{id:e});return this.axiosClient.delete(t)}requestChallenge(e,t){return this.axiosClient.post(B.TwoFactorChallenge,e,yt(t))}verifyV2(e,t){let{trust_device:n,...r}=e;return this.axiosClient.post(B.TwoFactorVerifyV2,{...r,...n?{trust_device:!0}:{}},bt(t))}switchToAlternative(e,t){return this.axiosClient.post(B.TwoFactorAlternative,e,yt(t))}async getTrustedDevices(){return(await this.axiosClient.get(B.TwoFactorTrustedDevices,{withCredentials:!0}))?.devices??[]}revokeTrustedDevice(e){let t=H(B.TwoFactorTrustedDeviceRevoke,{id:e});return this.axiosClient.delete(t)}},wt=class{constructor(e,t,n){this.axiosClient=new st(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}startUpgrade(e){return this.axiosClient.post(B.upgradeStart,e,ke({}))}},Tt=class{constructor(e,t,n){this.axiosClient=new st(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getUserPasskeys(){return this.axiosClient.get(B.userPasskey)}renameUserPasskey(e,t){return this.axiosClient.patch(`${B.userPasskey}/${t}`,{name:e})}deleteUserPasskey(e){return this.axiosClient.delete(`${B.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(B.addUserPasskey,a)}addUserPasskeyComplete(e,t,n){return this.axiosClient.post(B.completeAddUserPasskey,{challenge_id:n,device:t,passkey_data:e})}},Et=10,Dt=20,Ot=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}},kt=[],At=0,jt=!1,Mt,Nt,Pt=(e,t)=>e.priority-t.priority||e.seq-t.seq,Ft=()=>typeof globalThis>`u`?void 0:globalThis,It=async(e,t,n,r)=>{if(t>=e.length){let e=Mt;if(!e)throw Error(`Passflow fetch registry: no captured fetch to delegate to.`);return e(n,r)}let i=e[t];if(!i)return It(e,e.length,n,r);let a=!1,o=await i.middleware((n,r)=>(a=!0,It(e,t+1,n,r)),n,r);if(!a)throw new Ot(i.name);return o},Lt=()=>{let e=Ft();if(!e||typeof e.fetch!=`function`)return!1;let t=e.fetch.bind(e),n=(e,t)=>It([...kt].sort(Pt),0,e,t);return Mt=t,Nt=n,e.fetch=n,jt=!0,!0},Rt=()=>{let e=Ft();e&&Nt&&e.fetch===Nt&&(Mt&&(e.fetch=Mt),jt=!1,Nt=void 0,Mt=void 0)},zt=(e,t)=>{if(!jt&&!Lt())return()=>{};let n={middleware:e,name:t.name,priority:t.priority,seq:At++};kt.push(n);let r=!1;return()=>{r||(r=!0,kt=kt.filter(e=>e!==n),kt.length===0&&Rt())}},Bt=()=>{let e=Ft();return{installed:jt,names:[...kt].sort(Pt).map(e=>e.name),foreignPatch:jt&&!!e&&!!Nt&&e.fetch!==Nt}},U=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}},Vt=class extends U{constructor(e,t){super({code:`temporarily_unavailable`,message:e,status:0,cause:t}),this.name=`M2MNetworkError`}},Ht=class extends U{constructor(e,t){super({code:`invalid_request`,message:e,status:400,cause:t}),this.name=`M2MTokenParseError`}},Ut=class extends U{constructor(e){super({code:`invalid_request`,message:e,status:400}),this.name=`M2MConfigError`}},Wt={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`},Gt={TOKEN_ENDPOINT:`/oauth2/token`,TIMEOUT:1e4,RETRIES:3,RETRY_DELAY:1e3,REFRESH_THRESHOLD:30,CONTENT_TYPE:`application/x-www-form-urlencoded`},Kt=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()}},qt={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}},Jt=class{constructor(e){if(!e.url)throw new Ut(`M2M client requires a URL`);if(!e.clientId)throw new Ut(`M2M client requires a clientId`);if(!e.clientSecret)throw new Ut(`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??Gt.REFRESH_THRESHOLD,timeout:e.timeout??Gt.TIMEOUT,retries:e.retries??Gt.RETRIES,retryDelay:e.retryDelay??Gt.RETRY_DELAY,retryStrategy:e.retryStrategy,cache:e.cache,onTokenRequest:e.onTokenRequest,onTokenResponse:e.onTokenResponse,onError:e.onError},this.cache=e.cache??new Kt,this.retryStrategy=e.retryStrategy??qt,this.tokenEndpoint=`${t}${Gt.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":Gt.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=U.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 Vt(`Request timed out after ${this.config.timeout}ms`):e instanceof TypeError&&e.message.includes(`fetch`)?new Vt(`Network error: ${e.message}`,e):e instanceof U?e:U.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 U))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 U({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 Ht(`Invalid JWT format: expected 3 parts`);let n=t[1];if(!n)throw new Ht(`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 Ht?e:new Ht(`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":Gt.CONTENT_TYPE},body:n.toString()});if(!e.ok&&e.status!==200){let t=await e.json().catch(()=>({}));throw U.fromOAuthError({error:t.error||`server_error`,error_description:t.error_description||`Token revocation failed`},e.status)}this.clearCache()}catch(e){throw e instanceof U?e:U.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}},Yt=`error`,Xt=new WeakMap,Zt=(e,t)=>{if(typeof t!=`object`&&typeof t!=`function`||t===null)return!0;let n=Xt.get(e);return n||(n=new WeakSet,Xt.set(e,n)),!n.has(t)&&(n.add(t),!0)},W=(e,t)=>Zt(e,t.originalError)?(e.notify(Yt,t),!0):!1,Qt=`passflow-refresh`,$t=`passflow-refresh-takeover`,en=`passflow-auth`,tn=Object.freeze([1e3,3e3,1e4,3e4,6e4]),nn=.2,rn=6e5,an=5e3,G=2e4,on=2e4,sn=1e3,cn=2e3,ln=1e3,un=1e4,dn=5e3;function fn(e){let t=e?`:${e}`:``;return{lock:`${Qt}${t}`,takeoverLock:`${$t}${t}`,channel:`${en}${t}`}}function K(e){return typeof e==`string`&&e!==``?e:void 0}function pn(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function mn(e){return typeof e==`object`&&!!e}function hn(e,t){for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function gn(e){if(!mn(e))return null;let t=Array.isArray(e.scopes)?e.scopes.filter(e=>typeof e==`string`):void 0;return hn({},{access_token:K(e.access_token),refresh_token:K(e.refresh_token),id_token:K(e.id_token),scopes:Array.isArray(e.scopes)&&t?.length===e.scopes.length?t:void 0})}function _n(e){if(!mn(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||pn(r)===void 0||typeof i!=`number`||!Number.isFinite(i)||i<0?null:hn({kind:t,attempt:n,nextAt:r,strikes:i},{from:K(e.from),failingSince:pn(e.failingSince)})}function vn(e){return hn({},{fp:K(e.fp),sub:K(e.sub),sid:K(e.sid),iat:pn(e.iat)})}function yn(e){if(!mn(e))return null;let t=e;if(t.v!==void 0&&t.v!==1)return null;let n=K(t.tabId);if(!n)return null;switch(t.type){case`tokens-refreshed`:{let e=gn(t.tokens),r=K(t.from),i=K(t.to);return!e||!r||!i?null:hn({type:t.type,tabId:n,tokens:e,from:r,to:i},{fromIat:pn(t.fromIat),fromSid:typeof t.fromSid==`string`?t.fromSid:void 0,sentAt:pn(t.sentAt)})}case`session-refreshed`:{let e=pn(t.at);return e===void 0?null:hn({type:t.type,tabId:n,at:e},{sub:K(t.sub)})}case`still-refreshing`:{let e=t.retry===void 0?null:_n(t.retry);return e?{type:t.type,tabId:n,retry:e}:{type:t.type,tabId:n}}case`retry-scheduled`:{let e=_n(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,...vn(t)};case`rate-limited`:{let e=pn(t.until);return e===void 0?null:{type:t.type,tabId:n,until:e}}case`refresh-failed`:{let e=K(t.from);return e?{type:t.type,tabId:n,message:typeof t.message==`string`?t.message:``,from:e}:null}default:return null}}function bn(e,t){let n={v:1,tabId:e};if(t.type===`retry-scheduled`){let{retry:e,...r}=t;return hn(n,{...r,...e})}return hn(n,{...t})}var xn=`[passflow] navigator.locks or BroadcastChannel is unavailable (they need a secure context); each tab refreshes on its own, with the save checks only`,Sn={now:()=>Date.now(),random:()=>Math.random(),setTimeout:(e,t)=>{let n=setTimeout(e,t);return n.unref?.(),()=>clearTimeout(n)}};function Cn(){let e=globalThis.crypto;return typeof e?.randomUUID==`function`?e.randomUUID():`tab-${Math.random().toString(36).slice(2)}-${Date.now()}`}function wn(e){return e?{now:()=>e.now(),setTimeout:(t,n)=>e.setTimeout(t,n),random:e.random?()=>e.random?.()??Math.random():Sn.random}:Sn}function Tn(e){return typeof window<`u`&&typeof document<`u`&&e.getDeviceType()===`web`}function En(e){try{return e.storageSharedAcrossTabs===!0}catch{return!1}}function Dn(){try{let e=globalThis.navigator?.locks;return e&&typeof e.request==`function`?e:void 0}catch{return}}function On(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 kn(e){return{transports:null,names:fn(e),clock:Sn,warnOnFirstCycle:!1}}function An(e,t,n,r){let i=fn(n),a=Tn(t),o=a?On(r.tokenKeys):void 0,s=e=>{let t={transports:null,names:i,clock:Sn,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??Cn()},names:i,clock:wn(e.clock),warnOnFirstCycle:!1};return e.onStorageChange&&(t.onStorageChange=e.onStorageChange),t}if(e===`none`||!a||!En(t))return s(!1);let c=Dn();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:Cn()},names:i,clock:Sn,warnOnFirstCycle:!1};return o&&(u.onStorageChange=o),u}var jn=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`,Mn=32,Nn=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+=jn.charAt(r>>2),t+=jn.charAt((r&3)<<4|(i??0)>>4),i!==void 0&&(t+=jn.charAt((i&15)<<2|(a??0)>>6)),a!==void 0&&(t+=jn.charAt(a&63))}return t},Pn=()=>{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},Fn=async e=>{let t=await Pn().subtle.digest(`SHA-256`,new TextEncoder().encode(e));return Nn(new Uint8Array(t))},In=async()=>{let e=Nn(Pn().getRandomValues(new Uint8Array(Mn)));return{verifier:e,challenge:await Fn(e)}},Ln=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 Rn(){return new Ln}var zn=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 Bn(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 Vn(e,t){if(typeof e==`number`)return!Number.isFinite(e)||e<0?void 0:Math.min(rn,Math.floor(e)*1e3);if(typeof e!=`string`)return;let n=e.trim();if(n===``)return;if(/^\d+$/.test(n))return Math.min(rn,Number.parseInt(n,10)*1e3);if(!/[a-z]/i.test(n))return;let r=Date.parse(n);if(!Number.isNaN(r))return Math.min(rn,Math.max(0,r-t))}function Hn(e){return typeof e==`number`&&Number.isInteger(e)&&e>=100&&e<=599?e:void 0}function Un(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 Wn(e,t=Date.now()){if(typeof e!=`object`||!e)return{kind:`transient`};let n=e,r=Un(n),i=Hn(n.response?.status)??Hn(n.status),a={};if(i!==void 0&&(a.status=i),r!==void 0&&(a.id=r),r===`error.token.blocked`)return{kind:`blocked`,...a};if(r!==void 0&&zn.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=Vn(n.retryAfter??Bn(n.response?.headers),t);return o===void 0?{kind:`transient`,...a}:{kind:`transient`,...a,retryAfterMs:o}}function Gn(e,t,n){let r=tn.length,i=tn[(Number.isFinite(e)?Math.min(Math.max(Math.floor(e),1),r):1)-1]??tn[r-1]??6e4,a=Number.isFinite(t)?Math.min(Math.max(t,0),.999):0,o=i+Math.floor(i*nn*a);return Math.max(o,n!==void 0&&Number.isFinite(n)?Math.min(Math.max(n,0),rn):0)}var Kn={onGranted:()=>!1,onLockLost:()=>void 0,onMessage:()=>void 0};function qn(e){let{locks:t,channel:n,tabId:r,names:i,clock:a}=e,o=Kn,s=null,c=null,l=null,u=null,d=null,f=null,p=0,m,h=!1,g=!1,_=e=>{g||n.postMessage(bn(r,e))},v=()=>s!==null&&c===null,y=()=>{f?.(),f=null},b=e=>{p=Math.max(p,e),y(),f=a.setTimeout(()=>{f=null,D()},Math.max(0,p-a.now()))},x=()=>{d?.(),d=null},ee=()=>{d=a.setTimeout(()=>{d=null,c&&(h=!1,_(m?{type:`still-refreshing`,retry:m}:{type:`still-refreshing`}),ee())},an)},S=()=>{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?.()},C=()=>{x(),c=null,s=null,l=null,o.onLockLost()},w=(e,t)=>{if(e.dead||s!==e||g){t();return}y(),c=e,l=t,h=!1,ee();let n=!1;try{n=o.onGranted()}finally{!n&&c===e&&S()}},T=e=>{if(e.takeover&&(u?.(),u=null),!(e.dead||s!==e))return new Promise(t=>{a.setTimeout(()=>w(e,t),0)})},E=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,()=>T(n)).catch(()=>{n.dead=!0,c===n&&C()})},D=()=>{if(!v())return;let e=s;t.request(i.takeoverLock,{ifAvailable:!0},t=>{if(s===e&&v()){if(t===null)b(a.now()+G);else return _({type:`takeover`}),new Promise(t=>{u=t,e&&(e.dead=!0,e.abort.abort()),E(!0)})}}).catch(()=>{v()&&b(a.now()+G)})},te=e=>{if(g)return;let t=yn(e.data);if(t&&t.tabId!==r){switch(t.type){case`still-refreshing`:h=!0,v()&&(b(a.now()+G),t.retry&&b(t.retry.nextAt+G));break;case`takeover`:h=!0,v()&&b(a.now()+G);break;case`retry-scheduled`:h=!0,v()&&b(Math.max(a.now(),t.retry.nextAt)+G);break;case`rate-limited`:v()&&b(t.until+G)}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()+G,e??0)),E(!1))},release:S,post:_,setRetryInfo:e=>{m=e},foreignHolderHeard:()=>h,dispose:()=>{g||(S(),g=!0,n.removeEventListener(`message`,te),n.close())}}}function Jn(e=`local`){let t=Kn,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 q={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`},Yn={"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},Xn={"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`},J=class extends V{constructor(e,t={}){super({id:e,message:t.message??Xn[e],status:Yn[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)}},Zn=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 Qn(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 $n(e){return typeof e==`string`&&e!==``?e:void 0}function Y(e){let t=Qn(e);if(!e||!t)return;let n={};try{let t=j(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=$n(n.sub),o=$n(n.sid);return a!==void 0&&(i.sub=a),o!==void 0&&(i.sid=o),r!==void 0&&(i.iat=r),i}var er=`[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 tr(e=e=>Rn().warn(e)){let t=new Map,n=new Set,r=!1,i=[],a=!1,o=()=>{a||(a=!0,e(er))},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 nr=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}},rr=class extends Error{constructor(){super(`The shared token storage holds another user's tokens`),this.name=`IdentityChanged`}};function ir(e){if(e)try{let t=j(e).sub;return typeof t==`string`&&t!==``?t:void 0}catch{return}}function X(e){return ir(e?.access_token)??ir(e?.refresh_token)??ir(e?.id_token)}function ar(e,t){return!t||e.iat===void 0||t.iat===void 0?!1:e.sid===t.sid&&e.iat<t.iat}function or(e){return typeof e==`object`&&!!e}function sr(e){let{storage:t,cache:n,schedule:r}=e,i=e.identity??(()=>void 0),a=e.warn??(e=>Rn().warn(e)),o=e.lineage??tr(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=Qn(n)??``;return r!==c?.fp&&(c={fp:r,seq:l}),e},b=()=>Y(n.getTokens()?.refresh_token),x=()=>i()??X(n.getTokens()),ee=()=>{let e=b();return!e||e.iat===void 0||!x()?!1:!o.isRetired(e)&&!o.isEnded(e)},S=e=>{let t=b();if(!t||t.fp===e.fp||!ee())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)},C=e=>{let t=x();return d.some(n=>n.seq>e&&(!n.sub||!t||n.sub===t))},w=()=>{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}},T=()=>{if(!ee())return`end`;let e=c?.seq??0,t=w();return C(t?Math.min(e,t.seq):e)?`end`:t?S(t)?`keep`:`end`:s?`wait`:`end`},E=()=>{h?.(),h=void 0},D=(e=!1)=>{let t=T();t===`wait`&&e&&(t=`end`),t!==`wait`&&E(),t===`wait`&&!h&&(h=r(()=>{h=void 0,y()?.refresh_token?k():D(!0)===`end`&&s?.(`emptied`)},cn));let n=t===`keep`?w():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},te=e=>e.held!==void 0&&b()?.fp===e.held.cachedFp,O=e=>{let t=b();return!!t&&!o.isRetired(t)&&!o.isEnded(t)&&o.isAfter(t,e)},ne=e=>{if(!O(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},re=(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),ie=e=>{let t=b();t&&t.fp!==Qn(e.refresh_token)&&o.retire(t),n.setTokensCache(e)},ae=e=>{let t=y(),n=t?.refresh_token;if(n===e.refreshToken)return null;if(!t||!n)return D()===`end`?{kind:`ended`,cause:`emptied`}:{kind:`superseded`,adopted:!1};let r=ir(t.access_token)??ir(n);if(e.sub&&r&&e.sub!==r)return{kind:`identity-changed`,saved:!1};let i=Y(n);if(o.isEnded(i))return i&&S(i)?{kind:`superseded`,adopted:!1}:{kind:`ended`,cause:`ended`};o.retire(e.order);let a=b();return re(i,a)||i?.fp===a?.fp&&!o.isRetired(i)?(ie(t),{kind:`superseded`,adopted:!0}):{kind:`superseded`,adopted:!1}},oe=e=>S(e)?{kind:`superseded`,adopted:!1}:{kind:`ended`,cause:`ended`},k=()=>{let t=y();if(!t?.refresh_token){D()===`end`&&s?.(`emptied`);return}E();let n=i(),r=X(t);n&&r&&n!==r?s?.(`identity-changed`):e.onStoredSessionSeen?.()},A=!!s||!!e.onStoredSessionSeen,j=A&&e.onStorageChange?e.onStorageChange(k):void 0,M=A&&e.onWake?e.onWake(k):void 0,N=()=>{let e=y();if(!e?.refresh_token){if(D()===`end`)throw new nr(`emptied`);return`held`}let t=n.getTokens();if(e.refresh_token===t?.refresh_token)return`send`;let r=i()??X(t),a=X(e);if(r&&a&&r!==a)throw new rr;let s=Y(e.refresh_token);if(o.isEnded(s)){if(s&&S(s))return`held`;throw new nr(`ended`)}let c=Y(t?.refresh_token);return re(s,c)?(ie(e),`adopted`):s&&c&&s.sid!==c.sid?`send`:s&&O(s)?`held`:`send`},se=e=>{let t=i(),r=ir(e);if(t&&r&&t!==r)return{kind:`identity-changed`};let a=Y(e)??{fp:e};if(o.isEnded(a))return S(a)?{kind:`superseded`}:{kind:`ended`};if(o.isRetired(a)&&O(a))return{kind:`superseded`};let s={refreshToken:e,order:a},c=t??r??ir(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}},ce=(e,r)=>{if(o.isEnded(e.order))return oe(e.order);let i=ae(e);if(i)return i;if(!te(e)&&ne(e.order))return o.retire(e.order),a(`[passflow] Refused to save a late refresh result: it rotated ${e.order.fp} into ${Qn(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=X(r);if(e.sub&&s&&s!==e.sub)return t.saveTokens(r),{kind:`identity-changed`,saved:!0};let c=Y(r.refresh_token);return c&&(ar(c,e.order)||ar(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`})},P=(e,t)=>{if(o.isEnded(e.order))return oe(e.order);let n=ae(e);if(n)return n.kind===`identity-changed`?{kind:`identity-changed`}:n;if(o.isRetired(e.order)&&O(e.order))return{kind:`superseded`,adopted:!1};let r=Wn(t),i=r.kind===`blocked`||r.kind===`auth`;return te(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})},F=e=>{if(!or(e))return!1;let{from:t,fromIat:r,fromSid:a,to:c,tokens:l}=e;if(typeof t!=`string`||typeof c!=`string`||!or(l))return!1;let u=l;if(typeof u.access_token!=`string`||u.access_token===``||typeof u.refresh_token!=`string`||u.refresh_token===``||Qn(u.refresh_token)!==c)return!1;let d=y();if(!d?.refresh_token)return!1;let f=n.getTokens(),p=i()??X(f),m=X(u);if(p&&m&&p!==m)return s?.(`identity-changed`),!1;let h=Y(u.refresh_token),g=Y(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&&Qn(d.refresh_token)!==c?!1:(ie({...u}),_())},I=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)},le=()=>{let e=b();if(!e)return!1;if(I(e))return!0;let t=y(),r=Y(t?.refresh_token);if(!t||!r||r.fp===e.fp||!I(r)||!re(r,e))return!1;let a=i()??X(n.getTokens()),o=X(t);return a&&o&&a!==o?(s?.(`identity-changed`),!1):(ie(t),!0)},L=e=>{let t=Y(e?.refresh_token),n={},r=i()??X(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:N,beginSend:se,commitSave:ce,judgeFailure:P,adoptTokens:F,adoptSuccessor:le,beginHeldSend:()=>{let e=Y(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&&D()===`end`&&s?.(`emptied`)},session:()=>L(n.getTokens()),storedSession:()=>L(y()),dropSession:()=>{n.setTokensCache(void 0),n.stopTokenCheck?.()},deleteIfStillDead:e=>{let n=Y(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:()=>{j?.(),M?.(),E()}}}function cr(){let e,t,n=new Promise((n,r)=>{e=n,t=r});return n.catch(()=>void 0),{promise:n,resolve:e,reject:t}}var lr={strikes:q.sessionEnded,"session-ended":q.sessionEnded,"stored-ended":q.sessionEnded,"signed-out":q.signedOut,emptied:q.signedOut,"signed-out-here":q.signedOut,"successor-timeout":q.successorTimeout,"identity-changed":q.identityChanged,disposed:q.disposed};function ur(e){throw Error(`Unexpected refresh state: ${JSON.stringify(e)}`)}function dr(e){if(e===void 0||!Number.isFinite(e))return 3;let t=Math.floor(e);return t>=1?t:3}function fr(e,t){return e instanceof Error&&e.message?e.message:t}function pr(e){if(typeof e!=`object`||!e)return;let t=e.id;return typeof t==`string`||typeof t==`number`?t:void 0}function mr(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 hr(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 gr(e){let{emit:t,storage:n,cache:r,transport:i,coordination:a}=e,o=a.clock,s=e.logger??Rn(),c=dr(e.strikes),l=a.transports?qn({locks:a.transports.locks,channel:a.transports.channel,tabId:a.transports.tabId,names:a.names,clock:o}):Jn(),u={kind:`idle`},d=0,f=!1,p=!a.warnOnFirstCycle,m=0,h=0,g,_,v,y,b,x,ee,S,C=!1,w=()=>o.now(),T=()=>i.mode(),E=()=>Qn(r.getTokens()?.refresh_token),D=()=>({...r.getTokens()??{}}),te=()=>i.opaqueMarker?i.opaqueMarker():n.getTokens()?.id_token,O=()=>(ee===void 0&&(ee=X(r.getTokens()??n.getTokens())),ee),ne=new Set,re=new Set,ie=e=>()=>{for(let t of Array.from(e))t()},ae=a.onStorageChange?.(ie(ne)),oe=e.platform?.onForeground(ie(re)),k=sr({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=>fe(e),onStoredSessionSeen:()=>{u.kind===`blocked-wait`&&ke()},warn:e=>s.warn(e)}),A=e=>({trigger:e,startedAt:w(),plain:cr(),fresh:[]}),j=e=>e.kind===`idle`||e.kind===`ended`?void 0:e.pending,M=(e,t)=>{if(t===void 0)return e.plain.promise;let n={callTime:t,deferred:cr()};return e.fresh.push(n),n.deferred.promise},N=(e,t,n=!1)=>{e.plain.resolve(D());for(let r of e.fresh)n||t!==void 0&&t>=r.callTime?r.deferred.resolve(D()):Le(`refresh-token`,r.callTime).then(r.deferred.resolve,r.deferred.reject);e.fresh=[]},se=(e,t,n)=>{e.plain.reject(t);for(let r of e.fresh)n!==void 0&&n<r.callTime?Le(`refresh-token`,r.callTime).then(r.deferred.resolve,r.deferred.reject):r.deferred.reject(t);e.fresh=[]},ce=(e,t)=>{if(e){e.plain.reject(t);for(let n of e.fresh)n.deferred.reject(t);e.fresh=[]}},P=(e,n,r,i)=>{let a={message:fr(r,`Token refresh failed`),originalError:r,operation:e,source:n},o=pr(r);o!==void 0&&(a.code=o),i&&(a.refresh=i),t(`error`,a)},F=(e,t)=>{let n={classification:e,willRetry:t!==void 0,strikes:h,maxStrikes:c};return t!==void 0&&(n.nextRetryAt=t),n},I=(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})}},le=(e,n,r)=>{if(_)return;_={since:e};let i={since:e,origin:r};n!==void 0&&(i.nextRetryAt=n),t(`refresh:failing`,i)},L=(e,t)=>{let n=r.getTokens(),i=Qn(n?.refresh_token);e.fp&&i&&l.post({type:`tokens-refreshed`,tokens:mr(n),from:e.fp,...e.iat===void 0?{}:{fromIat:e.iat},fromSid:e.sid??``,to:i,...t===void 0?{}:{sentAt:t}})},ue=()=>{p||(p=!0,s.warn(xn))},de=e=>{(e.kind===`backoff`||e.kind===`blocked-wait`)&&e.cancel()},R=(e,n)=>{if(u.kind===`ended`)return;let r=j(u);de(u);let a=k.session(),o=O();switch(d+=1,m=0,h=0,g=void 0,_=void 0,v=void 0,l.setRetryInfo(void 0),C||l.release(),b={...a,cause:e},e!==`disposed`&&k.dropSession(),(e===`strikes`||e===`successor-timeout`)&&T()!==`json`&&i.invalidate(),u={kind:`ended`,cause:e},ce(r,n??new J(lr[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:ur(e)}},z=()=>{if(u.kind!==`ended`||u.cause===`disposed`||f||T()!==`json`)return;let e=n.getTokens(),i=Y(e?.refresh_token);if(!e?.refresh_token||!e.access_token||!i||k.lineage.isEnded(i)||k.lineage.isRetired(i))return;let a=b,o=X(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,ee=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`})},fe=e=>{u.kind===`ended`||f||T()===`json`&&(R(e===`emptied`?`emptied`:`identity-changed`),e===`identity-changed`&&z())},pe=e=>{e instanceof rr?(R(`identity-changed`),z()):e instanceof nr?R(e.cause===`emptied`?`emptied`:`stored-ended`):R(`stored-ended`,e)},me=()=>{u={kind:`idle`},C||l.release()},he=e=>!e.from||T()!==`json`||e.from===E()||e.from===Qn(n.getTokens()?.refresh_token),ge=e=>{let t=g;if(!t)return;if(!l.holding){u={kind:`waiting`,pending:e},l.request(t.nextAt+G);return}l.setRetryInfo(t);let n=d,r=t.nextAt;u={kind:`backoff`,pending:e,dueAt:r,cancel:o.setTimeout(()=>{n===d&&_e()},Math.max(0,r-w()))}},_e=()=>{if(u.kind!==`backoff`||C)return;let{pending:e,dueAt:t}=u;!l.holding||l.foreignHolderHeard()||w()-t>2e4?(l.release(),u={kind:`waiting`,pending:e},l.request((g?.nextAt??w())+G)):(u={kind:`waiting`,pending:e},ye()||ve())},ve=()=>{u.kind===`idle`&&l.release()},ye=()=>{if(u.kind!==`waiting`)return!1;let e=u.pending;if(T()!==`json`)return be(e);let t=k.session(),n;try{n=k.checkStoredBeforeSend()}catch(e){return pe(e),!1}if(n===`held`){let t=E();return!v||v.fp!==t||w()-v.at<2e4?(v&&v.fp===t||(v={fp:t,at:w()}),u={kind:`idle`},N(e,void 0,!0),!1):(v={fp:t,at:w()},k.beginHeldSend()?xe(e,`held`):(u={kind:`idle`},N(e,void 0,!0),!1))}if(v=void 0,n===`adopted`){if(I(`adopted`,`other-tab`),L(t),e.fresh.length===0)return u={kind:`idle`},N(e,void 0),!1;e.plain.resolve(D())}return g&&!he(g)&&(g=void 0),g&&g.nextAt>w()?(m=g.attempt,h=g.strikes,g.failingSince!==void 0&&le(g.failingSince,g.nextAt,`other-tab`),ge(e),!0):(g&&(m=g.attempt,h=g.strikes),xe(e,e.trigger===`held`?`refresh-token`:e.trigger))},be=e=>y!==void 0&&y>=e.startedAt?(r.setTokensCache(n.getTokens()),I(`adopted`,`other-tab`),u={kind:`idle`},N(e,y),!1):g&&g.nextAt>w()?(m=g.attempt,h=g.strikes,ge(e),!0):Se(e,e.trigger,void 0,void 0),xe=(e,t)=>{let r=n.getTokens(),i=r?.refresh_token;if(!i)return u={kind:`idle`},N(e,void 0,!0),!1;let a=k.beginSend(i);switch(a.kind){case`superseded`:return k.endHeldSend(),I(`adopted`,`other-tab`),u={kind:`idle`},N(e,void 0),!1;case`ended`:return k.endHeldSend(),R(`stored-ended`),!1;case`identity-changed`:return k.endHeldSend(),R(`identity-changed`),z(),!1;case`send`:return Se(e,t,a.sent,r);default:return ur(a)}},Se=(e,n,r,a)=>{let o={generation:d,sentAt:w(),trigger:n,settled:cr()};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=>{we(o,e).catch(e=>s.error(`[passflow] Applying a refresh result failed`,e)).finally(()=>o.settled.resolve())},e=>{Te(o,e),o.settled.resolve()}),!0},Ce=e=>!f&&e.generation===d&&u.kind===`refreshing`&&u.request===e,we=async(e,t)=>{if(e.sent?.held&&k.endHeldSend(),!Ce(e)||u.kind!==`refreshing`)return;let{pending:a}=u;if(!e.sent){let o=X({...t.id_token?{id_token:t.id_token}:{}}),s=O();if(o!==void 0&&s!==void 0&&o!==s){let t=new J(q.identityChanged);P(`refresh`,e.trigger,t,F(`auth`)),R(`identity-changed`,t);return}try{await i.applyOpaque(t)}catch(t){Te(e,t);return}if(!Ce(e))return;r.setTokensCache({...n.getTokens()??{},...hr(t,void 0)}),I(`refresh`,`this-tab`);let c=O();l.post(c===void 0?{type:`session-refreshed`,at:w()}:{type:`session-refreshed`,at:w(),sub:c}),me(),N(a,e.sentAt);return}let o=E(),s=k.commitSave(e.sent,hr(t,e.stored));switch(s.kind){case`saved`:I(`refresh`,`this-tab`),L(e.sent.order,e.sentAt),me(),N(a,e.sentAt);return;case`superseded`:e.outcome&&E()===o||I(`adopted`,`other-tab`),s.adopted&&L(e.sent.order),me(),N(a,e.sentAt);return;case`ended`:{let t=new J(s.cause===`emptied`?q.signedOut:q.sessionEnded);P(`refresh`,e.trigger,t,F(`auth`)),R(s.cause===`emptied`?`emptied`:`stored-ended`,t);return}case`identity-changed`:{let t=new J(q.identityChanged);P(`refresh`,e.trigger,t,F(`auth`)),R(`identity-changed`,t),z();return}default:ur(s)}},Te=(e,t)=>{if(e.sent?.held&&k.endHeldSend(),!Ce(e)||u.kind!==`refreshing`)return;let{pending:n}=u,r,i=!1;if(e.sent){let a=E(),o=k.judgeFailure(e.sent,t);switch(o.kind){case`superseded`:e.outcome&&E()===a||I(`adopted`,`other-tab`),me(),N(n,e.sentAt);return;case`ended`:P(`refresh`,e.trigger,t,F(`auth`)),R(o.cause===`emptied`?`emptied`:`stored-ended`,t);return;case`identity-changed`:P(`refresh`,e.trigger,t,F(`auth`)),R(`identity-changed`,t),z();return;case`own`:r=o.failure,i=o.heldRefused;break;default:ur(o)}}else r=Wn(t,w());if(i)P(`refresh`,e.trigger,t,F(r.kind)),I(`adopted`,`other-tab`),me(),N(n,void 0,!0);else switch(r.kind){case`blocked`:P(`refresh`,e.trigger,t,F(`blocked`)),Oe(n,e.sentAt,t,e.marker);return;case`auth`:if(h+=1,m+=1,h>=c){P(`refresh`,e.trigger,t,F(`auth`)),De(e,t);return}Ee(e,n,t,r);return;case`transient`:m+=1,Ee(e,n,t,r);return;default:ur(r.kind)}},Ee=(e,t,n,r)=>{let i=w()+Gn(m,o.random(),r.retryAfterMs),a=r.kind===`auth`?`auth`:`transient`;P(`refresh`,e.trigger,n,F(a,i)),a===`transient`&&le(w(),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:fr(n,`Token refresh failed`),retry:s}),ge(A(`retry`)),se(t,n,e.sentAt)},De=(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,k.endLineage({...i,fp:i.fp})),r&&k.deleteIfStillDead(r),R(`strikes`,t)},Oe=(e,t,n,r)=>{l.release(),s.warn(`[passflow] The refresh token was already used, most likely by another tab; waiting for its successor: ${fr(n,`blocked`)}`);let i=d,a=w()+on,c={kind:`blocked-wait`,pending:e,deadline:a,sentAt:t,cancel:()=>void 0,marker:r};if(u=c,ke())return;let f=T()!==`json`&&!l.coordinated&&!e.cookieRetried,p=()=>{i===d&&u===c&&(ke()||(f?(e.cookieRetried=!0,u={kind:`waiting`,pending:e},l.request()):w()>=a?(s.warn(`[passflow] No successor of the used refresh token appeared; ending the session in this tab only.`),R(`successor-timeout`)):c.cancel=o.setTimeout(p,sn)))};c.cancel=o.setTimeout(p,f?ln:sn)},ke=()=>{if(u.kind!==`blocked-wait`)return!1;let e=u;if(T()===`json`){if(!k.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(),I(`adopted`,`other-tab`),u={kind:`idle`},N(e.pending,void 0,!0),!0)},Ae=e=>{let t=O(),n=!e.sub||!t||e.sub===t;return T()===`json`?!!e.fp&&e.fp===E()&&n:!e.fp&&n},je=(e,t)=>{if(e!==`signed-out`||!t.sub)return!1;let n=O();return n!==void 0&&t.sub===n},Me=(e,t,n)=>{if(u.kind===`ended`||!he(e))return;let r=g?.nextAt;if(g=e,e.failingSince!==void 0&&le(e.failingSince,e.nextAt,`other-tab`),!t||u.kind!==`waiting`)return;let i=new J(e.kind===`transient`?q.unavailable:q.authRetry,{nextRetryAt:e.nextAt,cause:n||void 0}),a=u.pending;u.pending=A(a.trigger),se(a,i,r)},Ne=(e,t)=>{switch(t&&I(`adopted`,`other-tab`),u.kind){case`waiting`:case`backoff`:{let t=u.pending;de(u),me(),N(t,e);return}case`blocked-wait`:{let e=u.pending;u.cancel(),u={kind:`idle`},N(e,void 0,!0);return}case`idle`:case`refreshing`:case`ended`:return;default:ur(u)}},B=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`&&(Ae(t)||je(e.type,t));t.fp&&k.endLineage({...t,fp:t.fp}),n&&R(e.type===`signed-out`?`signed-out`:`session-ended`),k.endedElsewhere(e.type,t)},Pe=e=>{if(!f)switch(e.type){case`tokens-refreshed`:{if(u.kind===`ended`){z();return}if(T()!==`json`)return;let t=E();if(!k.adoptTokens(e))return;let n=E()!==t;if(!n&&u.kind===`idle`)return;g=void 0,Ne(e.sentAt,n);return}case`session-refreshed`:{if(T()===`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`){ke();return}Ne(e.at,!0);return}case`still-refreshing`:e.retry&&Me(e.retry,!1,``),Fe();return;case`retry-scheduled`:Me(e.retry,!0,e.message),Fe();return;case`refresh-failed`:if(u.kind===`ended`||T()!==`json`||e.from!==E()&&e.from!==Qn(n.getTokens()?.refresh_token))return;if(le(w(),void 0,`other-tab`),u.kind===`waiting`){let t=u.pending;u.pending=A(t.trigger),se(t,new J(q.unavailable,{cause:e.message}),void 0)}return;case`lock-wanted`:if(u.kind===`backoff`&&l.holding&&!C){let e=u.pending;u.cancel(),l.release(),u={kind:`waiting`,pending:e},l.request((g?.nextAt??w())+G)}return;case`session-ended`:case`signed-out`:B(e);return;case`takeover`:case`rate-limited`:return;default:ur(e)}},Fe=()=>{S&&!l.holding&&l.post({type:`lock-wanted`,purpose:S.purpose})};l.attach({onGranted:()=>{if(f)return!1;if(S){let e=S;return S=void 0,e.granted(),!0}return u.kind===`waiting`&&ye()},onLockLost:()=>{if(u.kind===`backoff`){let e=u.pending;u.cancel(),u={kind:`waiting`,pending:e},l.request((g?.nextAt??w())+G)}},onMessage:Pe});let Ie=()=>{if(f)return;if(u.kind===`ended`){z();return}if(u.kind===`blocked-wait`&&T()!==`json`){ke();return}if(u.kind!==`idle`||T()!==`json`||C)return;let e=k.session();try{if(k.checkStoredBeforeSend()!==`adopted`)return}catch{return}I(`adopted`,`other-tab`),l.coordinated&&L(e)};ne.add(Ie),re.add(Ie);let Le=(e,t)=>{if(f)return Promise.reject(new J(q.disposed));switch(u.kind){case`ended`:return Promise.reject(new J(q.sessionEnded));case`idle`:{let n=A(e);u={kind:`waiting`,pending:n};let r=M(n,t);return l.holding&&!C?ye()||ve():l.request(g?g.nextAt+G:void 0),r}case`waiting`:case`refreshing`:case`backoff`:case`blocked-wait`:return M(u.pending,t);default:return ur(u)}},Re=e=>{if(f)return Promise.reject(new J(q.disposed));if(ue(),u.kind===`ended`)return Promise.reject(new J(q.sessionEnded));if(T()===`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 P(`refresh`,e.trigger,n),Promise.reject(n)}}return Le(e.trigger,e.fresh?w():void 0)},V=e=>{if(f)return Promise.reject(new J(q.disposed));if(u.kind===`ended`)return Promise.resolve(r.getTokens());let t=u.kind===`backoff`||u.kind===`blocked-wait`||g!==void 0&&g.nextAt>w();return e.allowStale&&t?Promise.resolve(r.getTokens()):Re({trigger:e.trigger}).then(()=>r.getTokens())},ze=(e,t)=>l.holding?Promise.resolve(`granted`):new Promise(n=>{let r=()=>void 0,i={purpose:e,granted:()=>{r(),n(`granted`)}};S=i,l.post({type:`lock-wanted`,purpose:e}),l.request(),r=o.setTimeout(()=>{S===i&&(S=void 0,u.kind!==`waiting`&&l.release(),n(`timeout`))},Math.max(0,t))}),Be=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()})})},Ve=()=>{if(C=!1,!f&&l.holding){if(u.kind===`waiting`)ye()||ve();else if(u.kind===`backoff`){let e=u.pending;u.cancel(),ge(e)}else u.kind===`idle`&&g&&g.nextAt>w()&&he(g)?(m=g.attempt,h=g.strikes,ge(A(`retry`))):u.kind===`idle`&&l.release()}},He=async(e,t)=>{if(f)throw new J(q.disposed);ue();let n=w()+un;if(await Be(n-w()),(!l.holding||u.kind===`refreshing`)&&(u.kind===`refreshing`?`timeout`:await ze(`commit`,n-w()))===`timeout`){let e=new Zn(`lock-timeout`);throw P(`upgrade.commit`,`upgrade`,e),e}C=!0;try{return await Ue(e,t)}finally{Ve()}},Ue=async(e,a)=>{let o,s;if(T()===`json`){let e=k.session();try{k.checkStoredBeforeSend()===`adopted`&&(I(`adopted`,`other-tab`),L(e))}catch{}s=n.getTokens();let t=s?.refresh_token;if(!t){let e=Error(s?`No refresh token found`:`No tokens found`);throw P(`upgrade.commit`,`upgrade`,e),e}let r=k.beginSend(t);o=r.kind===`send`?r.sent:{refreshToken:t,order:Y(t)??{fp:t}}}let c=w();t(`refresh:start`,{});let u;try{u=await i.send(s?{tokens:s,upgrade:e}:{upgrade:e})}catch(e){throw o&&k.judgeFailure(o,e),P(`upgrade.commit`,`upgrade`,e),e}try{i.assertPin(a)}catch(e){throw P(`upgrade.commit`,`upgrade`,e),e}if(!o){await i.applyOpaque(u),r.setTokensCache({...n.getTokens()??{},...hr(u,void 0)}),We(c);let e=O();return l.post(e===void 0?{type:`session-refreshed`,at:w()}:{type:`session-refreshed`,at:w(),sub:e}),D()}let d=k.commitSave(o,hr(u,s));if(d.kind===`saved`)return We(c),L(o.order,c),D();let f=new Zn(`superseded`);throw P(`upgrade.commit`,`upgrade`,f),d.kind===`superseded`&&d.adopted&&I(`adopted`,`other-tab`),f},We=e=>{if(I(`upgrade`,`this-tab`),u.kind===`waiting`||u.kind===`backoff`||u.kind===`blocked-wait`){let t=u.pending;de(u),u={kind:`idle`},N(t,e)}},Ge=()=>{let e=k.storedSession(),t=e.fp?e:k.session();(T()===`json`?!t.fp:!t.sub)||t.fp&&t.fp===x||(l.post({type:`signed-out`,...t}),t.fp&&k.endLineage({...t,fp:t.fp}))},H=()=>{let e=j(u);ce(e,new J(q.signedOut)),(u.kind===`backoff`||u.kind===`blocked-wait`||u.kind===`waiting`)&&(de(u),u={kind:`idle`})};return{refresh:Re,ensureFresh:V,commitUpgrade:He,signOut:async e=>{if(f)return e(n.getTokens()?.refresh_token);let t=w()+dn;H(),await Be(t-w()),H(),l.coordinated&&!l.holding&&await ze(`logout`,t-w());try{Ge(),await e(n.getTokens()?.refresh_token)}finally{u.kind!==`ended`&&R(`signed-out-here`),x=void 0,l.release()}},signOutNow:e=>{if(f)return e(n.getTokens()?.refresh_token);H();try{Ge(),e(n.getTokens()?.refresh_token)}finally{u.kind!==`ended`&&R(`signed-out-here`),x=void 0}},sessionStarted:()=>{if(f)return;let e=j(u);de(u),d+=1,m=0,h=0,g=void 0,_=void 0,v=void 0,b=void 0,x=void 0,ee=void 0,l.setRetryInfo(void 0),u={kind:`idle`},C||l.release(),e&&N(e,void 0,!0)},identity:O,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=j(u);de(u),f=!0,d+=1,u={kind:`ended`,cause:`disposed`},ce(e,new J(q.disposed)),S=void 0,k.stop(),l.dispose(),ae?.(),oe?.()}}}var Z=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}({}),_r=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`&&Zt(this,t?.originalError),this.subscribers.forEach((n,r)=>{(!n||n.has(e))&&r.onAuthChange?.(e,t)})}notifyError(e){return W(this,e)}},vr={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`}}},yr=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))},br=()=>{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 xr(e,t,n,r,i){let[a=``,o=``,s=``]=e.split(`.`),c=JSON.parse(new TextDecoder().decode(yr(a))),l=c.alg===`ES256`||c.alg===`RS256`?vr[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=br().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,yr(s),p))throw Error(`Token signature is not valid`);let m=j(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`||A(m,0))throw Error(`Token has expired`);if(i&&m.type!==i)throw Error(`Token type is not valid`)}async function Sr(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`);br();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 xr(n.access_token,s,o,t,M.access_token),n.refresh_token&&await xr(n.refresh_token,s,o,t,M.refresh_token),n.id_token&&await xr(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`},Cr=Object.freeze([Q.twoFactorCodeInvalid,Q.twoFactorNotEnabled,Q.challengeInvalid,Q.challengeSessionMismatch,Q.challengeTooManyAttempts]),wr=Object.freeze([Q.tokenInvalid]),Tr=Object.freeze([`wrong_code`,`challenge_spent`,`not_registered`,`prepare_not_required`]),Er=e=>Tr.includes(e),Dr={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.`,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||Dr[e.kind]),this.name=`UpgradeTransportError`,this.code=`upgrade_transport`,this.kind=e.kind,this.status=e.status,this.errorId=e.errorId,this.retryable=Er(e.kind),e.cause!==void 0&&(this.cause=e.cause)}},Or=Object.freeze([`upgrade_transport`,`upgrade_insufficient`,`upgrade_unavailable`,`upgrade_session_changed`,`upgrade_cancelled`,`upgrade_unsatisfiable`]),kr=e=>typeof e==`object`&&!!e&&typeof e.code==`string`&&Or.includes(e.code),Ar=e=>e instanceof $||typeof e==`object`&&!!e&&e.code===`upgrade_transport`,jr=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`}},Mr=(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}},Nr=(e,t)=>e===void 0?`network`:e===501?`unavailable`:e===400?`fatal`:e===401||e===403?t===`start`?`challenge_spent`:`session_changed`:e>=500?`network`:`fatal`,Pr=(e,t)=>{if(e instanceof $)return e;let n=jr(e);return n.hasResponse?new $({kind:Mr(n.errorId,t)??Nr(n.status,t),message:n.message,status:n.status,errorId:n.errorId,cause:e}):new $({kind:`network`,message:n.message,cause:e})},Fr=e=>e.errorId!==void 0&&Cr.includes(e.errorId),Ir=e=>e.errorId!==void 0&&wr.includes(e.errorId),Lr=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}},Rr=class extends Error{constructor(e=`Step-up verification is not available on this deployment`){super(e),this.name=`UpgradeUnavailableError`,this.code=`upgrade_unavailable`}},zr=class extends Error{constructor(e=`The session changed during verification`){super(e),this.name=`UpgradeSessionChangedError`,this.code=`upgrade_session_changed`}},Br=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}},Vr=(e,t)=>!t||t.sub!==e.sub?!1:e.sid!==void 0&&t.sid!==void 0?e.sid===t.sid:!0;function Hr(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 Ur(e){return e.replace(/<[^>]*>/g,``).substring(0,200)}function Wr(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return t.length!==0&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function Gr(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return/^\+[1-9]\d{1,14}$/.test(t)}function Kr(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 qr(e,t=6){return!e||typeof e!=`string`?!1:(t===8?/^\d{8}$/:/^\d{6}$/).test(e)}function Jr(e){if(!e||typeof e!=`string`)return null;let t=e.toUpperCase().replace(/\s+/g,``);return/^[A-Z0-9-]{4,16}$/.test(t)?t:null}var Yr=`passflow_2fa_pkce`,Xr=3e5,Zr=`passflow_pwless_pending`,Qr=3e3,$r=`passflow_federated_pkce`,ei=6e5,ti=`AppId is required for federated auth`,ni=10,ri=`The sign-in answered with a PKCE code, but its verifier is gone`,ii=(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})}),ai=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},oi=e=>{if(e)try{return j(e).email}catch{return}},si=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d=L,f,p={coordination:kn()}){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.emailChallenges=new Map,this.tokenExchangeConfig=u,this.tokenDeliveryManager=new ce(n),u?.enabled&&this.tokenDeliveryManager.setMode(N.BFF),this.refresh=gr({emit:this.createRefreshEmit(),storage:n,cache:i,transport:this.createRefreshTransport(),coordination:p.coordination,platform:d,...p.strikes===void 0?{}:{strikes:p.strikes},logger:Rn()}),this.initializeSession()}async initializeSession(){(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode())&&await this.restoreSession()}async restoreSession(){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.statusUrl)try{let e=await fetch(this.tokenExchangeConfig.statusUrl,{method:`GET`,credentials:`include`});return e.ok&&(await e.json()).authenticated?(this.tokenDeliveryManager.setSessionValid(),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return this.tokenDeliveryManager.setSessionInvalid(),!1}if(!this.tokenDeliveryManager.isCookieMode())return!1;try{let e=await this.authApi.validateSession();return e.valid?(this.tokenDeliveryManager.setSessionValid(),e.user&&this.subscribeStore.notify(Z.SessionRestored,e.user),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return this.tokenDeliveryManager.setSessionInvalid(),!1}}async processAuthResponse(e,t){await this.applyAuthResponse(e,t),this.refresh.sessionStarted()}async applyAuthResponse(e,t){if(e.code&&!e.access_token)throw Error(`A PKCE authorization code was not exchanged, so there are no tokens to apply`);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()),this.tokenCacheService.setTokensCache(e),e.csrf_token&&this.storageManager.setCsrfToken(e.csrf_token)}handlePendingSecondFactor(e,t,n,r){return e.requires_2fa!==!0&&!e.tfa_token?!1:(n?this.rememberPkceSignIn(n.verifier,r):this.forgetPkceSignIn(),this.subscribeStore.notify(Z.TwoFactorRequired,{email:t||``,challengeId:e.challenge_id||``,tfaToken:e.tfa_token||``}),!0)}handleEmailVerificationStep(e,t,n,r,i){if(!Ie(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(Z.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<=ni)break;this.emailChallenges.delete(e)}}rememberPkceSignIn(e,t){if(this.pendingPkce={verifier:e,scopes:t,expiresAt:Date.now()+Xr},typeof sessionStorage<`u`)try{sessionStorage.setItem(Yr,JSON.stringify(this.pendingPkce))}catch{}}readPendingPkce(){if(!this.pendingPkce&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(Yr);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(Yr)}catch{}}rememberPendingPasswordless(e){if(this.pendingPasswordless=e,typeof sessionStorage<`u`)try{sessionStorage.setItem(Zr,JSON.stringify(e))}catch{}}readPendingPasswordless(){if(!this.pendingPasswordless&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(Zr);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(Zr)}catch{}}rememberFederatedSlot(e,t){if(this.federatedSlot={verifier:e,scopes:t,expiresAt:Date.now()+ei},typeof sessionStorage<`u`)try{sessionStorage.setItem($r,JSON.stringify(this.federatedSlot))}catch{}}readFederatedSlot(){if(!this.federatedSlot&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem($r);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($r)}catch{}}async startPkce(){let e=!1;try{e=await this.readPkceEnabled?.()??!1}catch(e){Rn().warn(`Passflow: could not read the app settings, so this sign-in sends no PKCE challenge`,e);return}return e?In():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(ri);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 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){if(`email`in e&&e.email&&!Wr(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&&!Kr(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&&!Gr(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(Z.SignInStart,{email:e.email});let t=this.deviceService.getDeviceId(),n=Ge(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes;try{let r=await this.startPkce(),i=await this.authApi.signIn(r?{...e,code_challenge:r.challenge}:e,t,n);if(this.handleEmailVerificationStep(i,`sign-in`,e.email,r,e.scopes)||this.handlePendingSecondFactor(i,e.email,r,e.scopes))return i;let a=await this.exchangeCode(i,r);return this.handlePendingSecondFactor(a,e.email)||(await this.processAuthResponse(a,e.scopes),this.subscribeStore.notify(Z.SignIn,{tokens:a,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),a}catch(e){let t={operation:`sign-in`,message:e instanceof Error?e.message:`Sign in failed`,originalError:e,code:e instanceof V?e.id:void 0};throw W(this.subscribeStore,t),e}}async signUp(e){if(e.user.email&&!Wr(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&&!Gr(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(Z.RegisterStart,{email:e.user.email}),e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{let t=await this.startPkce(),n=await this.authApi.signUp(t?{...e,code_challenge:t.challenge}:e);if(this.handleEmailVerificationStep(n,`sign-up`,e.user.email,t,e.scopes)||this.handlePendingSecondFactor(n,e.user.email,t,e.scopes))return n;let r=await this.exchangeCode(n,t);return this.handlePendingSecondFactor(r,e.user.email)||(await this.processAuthResponse(r,e.scopes),this.subscribeStore.notify(Z.Register,{tokens:r,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),r}catch(e){let t={operation:`sign-up`,message:e instanceof Error?e.message:`Sign up failed`,originalError:e,code:e instanceof V?e.id:void 0};throw W(this.subscribeStore,t),e}}async passwordlessSignIn(e){if(e.email&&!Wr(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&&!Gr(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(Z.SignInStart,{email:e.email});let t=e.scopes??this.scopes,n=this.deviceService.getDeviceId(),r=Ge(this.platform.getDeviceType());try{let i=await this.startPkce(),a=await this.authApi.passwordlessSignIn({...e,scopes:t,...i?{code_challenge:i.challenge}:{}},n,r);return i&&a.challenge_id?this.rememberPendingPasswordless({challengeId:a.challenge_id,verifier:i.verifier,codeChallenge:i.challenge,matchCode:a.match_code,email:e.email,scopes:t,expiresAt:new Date(a.expires_at).getTime()}):this.forgetPendingPasswordless(),a}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 V?e.id:void 0};throw W(this.subscribeStore,t),e}}async passwordlessSignInComplete(e){this.subscribeStore.notify(Z.SignInStart,{}),e.scopes=e.scopes??this.scopes,e.device=this.deviceService.getDeviceId();let t=this.readPendingPasswordless(),n=t?.challengeId===e.challenge_id?t:void 0,r=!1;try{let t=await this.authApi.passwordlessSignInComplete(e);if(r=!0,this.handlePendingSecondFactor(t,n?.email,n&&{verifier:n.verifier},n?.scopes))return this.forgetPendingPasswordless(),t;let i=t;if(t.code){if(!n)throw Error(ri);if(i=await this.authApi.pkceExchange(t.code,n.verifier),this.handlePendingSecondFactor(i))return this.forgetPendingPasswordless(),{...i,redirect_url:t.redirect_url??``}}let a=t.redirect_url?{...i,redirect_url:t.redirect_url}:i;return await this.processAuthResponse(a,n?.scopes??e.scopes),this.forgetPendingPasswordless(),this.subscribeStore.notify(Z.SignIn,{tokens:a,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),{...a,redirect_url:t.redirect_url??``}}catch(e){r&&this.forgetPendingPasswordless();let t={operation:`passwordless.complete`,message:e instanceof Error?e.message:`Passwordless sign in failed`,originalError:e,code:e instanceof V?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(ri);for(;;){if(n?.aborted)throw n.reason;if(Date.now()>=t.expiresAt)return this.forgetPendingPasswordless(),{status:`expired`};if(this.readPendingPasswordless()?.challengeId!==e)throw Error(ri);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 V&&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);await ii(Qr,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 V?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(Z.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 V?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(ri);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(ri);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(),this.subscribeStore.notify(t?.operation===`sign-up`?Z.Register:Z.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 V?e.id:void 0};throw W(this.subscribeStore,t),e}}async logOut(){let e=this.refresh.identity();return await this.refresh.signOut(async e=>{await this.callLogoutApi(e),this.forgetPkceSignIn(),this.forgetPendingPasswordless(),this.emailChallenges.clear(),this.clearLocalSession()}),e}resetSession(){let e=this.refresh.identity();return this.refresh.signOutNow(()=>{this.emailChallenges.clear(),this.clearLocalSession()}),e}async callLogoutApi(e){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.logoutUrl){try{await fetch(this.tokenExchangeConfig.logoutUrl,{method:`POST`,credentials:`include`})}catch{}return}let t=e??this.storageManager.getToken(M.refresh_token),n=this.storageManager.getDeviceId();try{if((await this.authApi.logOut(n,t,!this.appId)).status!==`ok`)throw Error(`Logout failed`)}catch{}}clearLocalSession(){this.storageManager.deleteTokens(),this.storageManager.clearIdToken(),this.storageManager.clearCsrfToken(),this.tokenDeliveryManager.reset(),this.tokenCacheService.setTokensCache(void 0),this.tokenCacheService.stopTokenCheck?.()}readSessionPin(){try{let e=this.storageManager.getToken(M.access_token);return e?Br(j(e)):void 0}catch{return}}assertSessionPin(e){if(e&&!Vr(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 zr(`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(Z.Refresh,{tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens(),source:r});return}case`signin`:{let{tokens:e,origin:r}=t;n.notify(Z.SignIn,{tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens(),origin:r});return}case`error`:W(n,t);return;case`refresh:start`:n.notify(Z.RefreshStart,{});return;case`token-cache-expired`:n.notify(Z.TokenCacheExpired,t);return;case`refresh:failing`:n.notify(Z.RefreshFailing,t);return;case`refresh:recovered`:n.notify(Z.RefreshRecovered,t);return;case`session:expired`:n.notify(Z.SessionExpired,t);return;case`signout`:n.notify(Z.SignOut,t);return;default:Rn().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(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 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 V({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){try{return await this.authApi.sendPasswordResetEmail(e)}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 V?e.id:void 0};throw W(this.subscribeStore,t),e}}async resetPassword(e,t,n){this.subscribeStore.notify(Z.SignInStart,{});let r=n??ai(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`,oi(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(Z.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 V?e.id:void 0};throw W(this.subscribeStore,t),e}}async passkeyRegister(e){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);this.subscribeStore.notify(Z.RegisterStart,{});let t=this.deviceService.getDeviceId(),n=Ge(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{let r=await this.startPkce(),{challenge_id:i,publicKey:a}=await this.authApi.passkeyRegisterStart(r?{...e,code_challenge:r.challenge}:e,t,n,!this.appId);a.user.id=this.platform.btoa(a.user.id);let o=await this.platform.passkeys.startRegistration(a);if(!o)throw Error(`Passkey registration was not completed`);let s=await this.authApi.passkeyRegisterComplete(o,t,i,!this.appId);if(this.handlePendingSecondFactor(s,void 0,r,e.scopes))return s;let c=await this.exchangeCode(s,r);return this.handlePendingSecondFactor(c)||(await this.processAuthResponse(c,e.scopes),this.subscribeStore.notify(Z.Register,{tokens:c,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),c}catch(e){let t={operation:`passkey.register`,message:e instanceof Error?e.message:`Passkey registration failed`,originalError:e,code:e instanceof V?e.id:void 0};throw W(this.subscribeStore,t),e}}async passkeyAuthenticate(e){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);this.subscribeStore.notify(Z.SignInStart,{});let t=this.deviceService.getDeviceId(),n=Ge(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes;try{let r=await this.startPkce(),{challenge_id:i,publicKey:a}=await this.authApi.passkeyAuthenticateStart(r?{...e,code_challenge:r.challenge}:e,t,n,!this.appId),o=await this.platform.passkeys.startAuthentication(a);if(!o)throw Error(`Passkey authentication was not completed`);let s=await this.authApi.passkeyAuthenticateComplete(o,t,i,!this.appId);if(this.handlePendingSecondFactor(s,void 0,r,e.scopes))return s;let c=await this.exchangeCode(s,r);return this.handlePendingSecondFactor(c)||`access_token`in c&&(await this.processAuthResponse(c,e.scopes),this.subscribeStore.notify(Z.SignIn,{tokens:c,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),c}catch(e){let t={operation:`passkey.authenticate`,message:e instanceof Error?e.message:`Passkey authentication failed`,originalError:e,code:e instanceof V?e.id:void 0};throw W(this.subscribeStore,t),e}}createFederatedAuthUrl(e){let t=`/auth/federated/start/${e.provider}`;if(!this.appId)throw Error(ti);let n={scopes:(e.scopes??this.scopes).join(` `),redirect_url:e.redirect_url??this.platform.getCurrentUrl()?.origin??``,appId:this.appId,...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}:{}},r=new URL(t,this.url);return r.search=new URLSearchParams(n).toString(),r.toString()}async federatedAuthWithPopup(e){if(this.subscribeStore.notify(Z.SignInStart,{provider:e.provider}),!this.appId)throw Error(ti);let t=e.scopes??this.scopes,n=this.deviceService.getDeviceId();try{this.forgetFederatedSlot();let r=await this.startPkce(),i=this.createFederatedAuthUrl({...e,scopes:t,device:n,...r?{code_challenge:r.challenge,code_challenge_method:`S256`}:{}}),a=this.platform.openAuthUrl(i,{mode:`popup`,expectedReturnOrigin:this.platform.getCurrentUrl()?.origin??``});r&&this.rememberFederatedSlot(r.verifier,t);let o=await a;this.forgetFederatedSlot();let s=new URLSearchParams(o.callbackHash.replace(/^#/,``));if(this.handlePendingSecondFactor({tfa_token:s.get(`tfa_token`)??void 0}))return;let c=new URLSearchParams(o.callbackSearch),l=c.get(`code`),u=c.get(`access_token`)||``,d=c.get(`refresh_token`)||``,f=c.get(`id_token`)||``,p={access_token:u,refresh_token:d||void 0,id_token:f||void 0,scopes:t};if(l&&r){if(p=await this.authApi.pkceExchange(l,r.verifier),this.handlePendingSecondFactor(p))return}else await Sr(this.url,this.appId,p);await this.processAuthResponse(p,t),this.subscribeStore.notify(Z.SignIn,{tokens:p,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.platform.navigateTo(this.platform.getCurrentUrl()?.origin??``)}catch(e){this.forgetFederatedSlot();let t={operation:`federated.popup`,message:e instanceof Error?e.message:`Authentication failed`,code:e instanceof I?`POPUP_CLOSED`:`AUTH_FAILED`,originalError:e};W(this.subscribeStore,t)}}federatedAuthWithRedirect(e){if(this.subscribeStore.notify(Z.SignInStart,{provider:e.provider}),!this.appId)throw Error(ti);let t=e.scopes??this.scopes,n=this.deviceService.getDeviceId();this.startPkce().then(r=>{let i=this.createFederatedAuthUrl({...e,scopes:t,device:n,...r?{code_challenge:r.challenge,code_challenge_method:`S256`}:{}});r?this.rememberFederatedSlot(r.verifier,t):this.forgetFederatedSlot(),this.platform.navigateTo(i)}).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(Z.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 V?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}}authRedirect(e={}){try{this.platform.navigateTo(this.authRedirectUrl(e))}catch(e){let t={operation:`auth-redirect`,message:e instanceof Error?e.message:`Failed to redirect to auth page`,originalError:e};throw W(this.subscribeStore,t),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:!A(e.access_token)||e.refresh_token!==void 0&&!A(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 V?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();return!t||!t.access_token?void 0:A(j(t.access_token))?e?await this.refreshForSession():void 0: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}}},ci=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)}},li=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}},ui=class{constructor(e,t,n){this.tenantApi=e,this.scopes=t,this.logger=n||Rn()}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 li(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}`)}}},di=class{constructor(e,t,n,r=L){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}A(j(t.access_token))?(this.stopTokenCheck(),this.tokenExpiredFlag||(this.tokenExpiredFlag=!0,this.subscribeStore.notify(Z.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(Z.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(Z.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?j(e.access_token):void 0,id_token:e.id_token?j(e.id_token):void 0,refresh_token:e.refresh_token?j(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(A(j(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?A(j(this.tokensCache.access_token)):!1:!0}},fi=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.totpDigits=6,this.subscribeStore.subscribe({onAuthChange:(e,t)=>{if(e===Z.TwoFactorRequired){let e=t;this.setPartialAuthState(e.email,e.challengeId,e.tfaToken)}(e===Z.SignIn||e===Z.Register)&&(this.clearPartialAuthState(),this.clearMagicLinkSession())}},[Z.TwoFactorRequired,Z.SignIn,Z.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 e.totp_digits&&(this.totpDigits=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{return await this.twoFactorApi.getEnrollment(this.requirePendingTfaToken())}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){if(!qr(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`)}requirePendingTfaToken(){let e=this.pendingTfaToken();if(!e)throw Error(`2FA verification expired or not required. User must sign in first.`);return e}setupStarted(e){return e.totp_digits&&(this.totpDigits=e.totp_digits),this.subscribeStore.notify(Z.TwoFactorSetupStarted,{secret:e.secret}),e}setupConfirmed(e){return this.subscribeStore.notify(Z.TwoFactorEnabled,{recoveryCodes:e.recovery_codes,clearRecoveryCodes:()=>{e.recovery_codes.length=0}}),e}async verify(e,t){if(!qr(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);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.`);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(Z.TwoFactorVerified,{tokens:r}),r}catch(e){this.emitErrorAndThrow(e,`2fa.verify`,`Verify 2FA code`)}}async useRecoveryCode(e,t){try{let n=Jr(e);if(!n)throw Error(`Invalid recovery code format. Expected format: XXXX-XXXX or XXXXXXXX (alphanumeric).`);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}:{}}));return r.remaining_recovery_codes===0?this.subscribeStore.notify(Z.TwoFactorRecoveryCodesExhausted,{tokens:r}):r.remaining_recovery_codes<=2&&this.subscribeStore.notify(Z.TwoFactorRecoveryCodesLow,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(Z.TwoFactorRecoveryUsed,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(Z.TwoFactorVerified,{tokens:r}),r}catch(e){this.emitErrorAndThrow(e,`2fa.recovery.use`,`Use recovery code`)}}async disable(e){if(!qr(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{let t=await this.twoFactorApi.disable({code:e});return this.subscribeStore.notify(Z.TwoFactorDisabled,{}),t}catch(e){this.emitErrorAndThrow(e,`2fa.disable`,`Disable 2FA`)}}async regenerateRecoveryCodes(e){if(!qr(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);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.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.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 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`,timestamp:Date.now(),expiresAt:Date.now()+(t.expiresIn||3600)*1e3},this.subscribeStore.notify(Z.TwoFactorSetupMagicLinkValidated,{userId:t.userId,appId:t.appId,expiresIn:t.expiresIn||3600,sessionToken:t.sessionToken})):t.error&&this.subscribeStore.notify(Z.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}async getAvailableMethods(){try{return await this.twoFactorApi.getAvailableMethods()}catch(e){this.emitErrorAndThrow(e,`2fa.methods.available`,`Get available 2FA methods`)}}async getRegisteredMethods(){try{return await this.twoFactorApi.getRegisteredMethods()}catch(e){this.emitErrorAndThrow(e,`2fa.methods.registered`,`Get registered 2FA methods`)}}async startMethodSetup(e,t){try{let n=await this.twoFactorApi.startMethodSetup(e,t);return this.subscribeStore.notify(Z.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(Z.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.subscribeStore.notify(Z.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());if(!t.success)return t;let n=await this.finishSignIn(t);return this.subscribeStore.notify(Z.TwoFactorVerified,{tokens:{access_token:n.access_token,refresh_token:n.refresh_token}}),n.device_trusted&&this.subscribeStore.notify(Z.TwoFactorDeviceTrusted,{}),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.subscribeStore.notify(Z.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`)}}},pi=class{constructor(e,t,n=L){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=Ge(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)}},mi=class extends Error{constructor(e,t,n=!1){super(t),this.name=`UpgradeFactorError`,this.factor=e,this.cancelled=n}},hi=(e,t)=>{let n=t?.trim();if(!n)throw new mi(e,`A verification code is required`);return n},gi={type:`totp`,requiresPrepare:!1,input:`code`,assert:async({code:e})=>({code:hi(`totp`,e)})},_i={type:`recovery_codes`,requiresPrepare:!1,input:`code`,assert:async({code:e})=>({code:hi(`recovery_codes`,e)})},vi={type:`passkey`,requiresPrepare:!0,input:`none`,assert:async({prepared:e,platform:t})=>{if(!e?.webauthn)throw new mi(`passkey`,`The upgrade challenge carried no WebAuthn options`);let n=t.passkeys;if(!n)throw new mi(`passkey`,`This platform does not support passkeys`);let r;try{r=await n.startAuthentication(e.webauthn)}catch(e){throw new mi(`passkey`,e?.message||`Passkey verification was cancelled`,!0)}if(!r)throw new mi(`passkey`,`Passkey verification was cancelled`,!0);return{challenge_id:e.challengeId,credential:r}}},yi=Object.freeze([gi,vi,_i]),bi=(e=yi)=>new Map(e.map(e=>[e.type,e])),xi=3,Si={passkey:0,totp:1,email_otp:2,sms_otp:3,recovery_codes:9},Ci=e=>e.requiredLevel??fe(e.acrValues),wi=(e,t)=>{let n=Si[e.type]??5,r=t!==void 0&&t>=xi,i=e.type===`passkey`;return(r&&!i?100:0)+n},Ti=(e,t)=>{let n=Ci(t);return[...e].sort((e,t)=>wi(e,n)-wi(t,n))},Ei=class extends Error{constructor(e){super(`Upgrade authentication was cancelled`),this.code=`upgrade_cancelled`,this.name=`UpgradeCancelledError`,e!==void 0&&(this.cause=e)}},Di=class extends Error{constructor(e=`No available authentication factor can satisfy this challenge`){super(e),this.code=`upgrade_unsatisfiable`,this.name=`UpgradeUnsatisfiableError`}},Oi=4,ki=3e4,Ai=()=>{let e=()=>void 0,t=()=>void 0;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},ji=e=>({acrValues:e.acrValues,level:e.requiredLevel,maxAge:e.maxAge}),Mi=(e,t)=>t.level===void 0||e.level!==void 0&&e.level>=t.level,Ni=(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??[]]));return{acrValues:r,requiredLevel:n,maxAge:i,status:e.status,...a.length>0?{channels:a}:{}}},Pi=(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},Fi=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??yi,this.registry=bi(this.available),this.maxAttempts=e.maxAttempts??Oi,this.readObtainedBar=e.readObtainedBar,this.onFlightSettled=e.onFlightSettled,this.settleTimeoutMs=e.replaySettleTimeoutMs??ki}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:ji(e),statedBar:n,settlement:Ai(),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=Pi(t,e);this.requirement=Ni(t,e),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?Ti(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&&!Mi(t,e.demanded)){this.receiveReport(e,{outcome:`insufficient`,obtained:t,required:e.demanded}),e.settlement.reject(new Lr(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=this.offeredFactors();if(t.length===0)return{status:`failed`,reason:new Di};let n=this.requirement,r;try{r=await this.collect(n,t,e)}catch(e){return{status:`failed`,reason:new Ei(e)}}if(r.type===`cancel`)return{status:`failed`,reason:new Ei};let i=this.registry.get(r.factor);if(!i)e=new Di(`Unknown authentication factor: ${r.factor}`),this.state=`collecting`,this.selected=null;else try{return await this.proveAndCommit(i,r.code),{status:`proven`,obtained:this.readObtainedBar?.()??ji(this.rankedRequirement??n)}}catch(t){if(t instanceof mi&&t.cancelled)return{status:`failed`,reason:new Ei};let n=this.classifyProofFailure(t);if(n)return{status:`failed`,reason:n};t instanceof $&&t.kind===`not_registered`&&this.pruned.add(i.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}};return this.openPrompt=r,this.prompt(r)}classifyProofFailure(e){if(e instanceof Lr||e instanceof Rr||e instanceof zr)return e;if(e instanceof $)switch(e.kind){case`unavailable`:return new Rr(e.message);case`exhausted`:case`attempts_exhausted`:case`fatal`:case`protocol`:case`network`:return e;case`session_changed`:return new zr(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)}},Ii=e=>typeof e==`function`?e():e,Li=e=>{try{return new URL(e)}catch{return}},Ri=(e,t)=>{if(!t||t===`/`)return!0;let n=t.replace(/\/+$/,``);return e===n||e.startsWith(`${n}/`)},zi=(e,t)=>!t||e.origin===void 0?!1:e.origin===t.origin&&Ri(e.pathname,t.pathPrefix),Bi=(e,t)=>{for(let n of t){if(n===``)continue;if(n.startsWith(`/`)){if(e.relativeToBase&&Ri(e.pathname,n))return!0;continue}let t=Li(n)??Li(`https://${n}`);if(t&&e.origin!==void 0&&e.origin===t.origin&&Ri(e.pathname,t.pathname))return!0}return!1},Vi=(e,t,n)=>zi(e,t.passflow)||Bi(e,t.backend)?!n||n(e.href)!==!1:!1,Hi=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})},Ui=(e,t)=>{let n=t.onUpgradeDiagnostic??Hi;return(t,r)=>{n({status:e.status,url:e.request.href,reason:t,detail:{method:e.request.method,...r??{}}})}},Wi=(e,t,n)=>{let r=n.onUpgradeDiagnostic??Hi;for(let n of e)r({...n,url:t.request.href,detail:{method:t.request.method,...n.detail??{}}})},Gi=/\bjson\b/i,Ki=async(e,t)=>{let n=t.requireChallengeChannel===`header`,r=e.getHeader(`content-type`)??``,i=!n&&Gi.test(r),a;if(i)try{a=await e.readBody()}catch{a=void 0}return we(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})},qi=e=>we({status:e.status,getHeader:t=>e.getHeader(t)??void 0},{requireChallengeChannel:`header`}).challenge,Ji=(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.`,Yi=(e,t)=>e instanceof Ei?{kind:`cancelled`}:e instanceof Di?{kind:`unsatisfiable`}:e instanceof Rr?{kind:`unavailable`}:e instanceof zr?{kind:`session-changed`}:e instanceof Lr?{kind:`insufficient`,obtained:e.obtained,required:e.required}:e instanceof $?e.kind===`exhausted`||e.kind===`attempts_exhausted`?{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))},Xi=async(e,t,n,r)=>{if(e.status!==401&&e.status!==403)return{kind:`replayed`,response:e};let{challenge:i,diagnostics:a}=await Ki(e,t);if(Wi(a,e,t),!i)return{kind:`replayed`,response:e};let o=ji(i);return r(`elevated-insufficient`,{obtained:n,required:o}),{kind:`insufficient`,obtained:n,required:o,response:e}},Zi=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)}},Qi=async(e,t)=>{if(e.status!==401&&e.status!==403||e.markers.upgradeTransaction)return{kind:`not-a-challenge`};let n=Ui(e,t);if(e.markers.replayed){if(!Vi(e.request,t.scope,t.shouldIntercept))return{kind:`not-a-challenge`};let{challenge:r,diagnostics:i}=await Ki(e,t);if(Wi(i,e,t),!r)return{kind:`not-a-challenge`};let a=t.readObtainedBar?.()??{},o=ji(r);return n(`elevated-insufficient`,{obtained:a,required:o}),{kind:`insufficient`,obtained:a,required:o,response:e}}if(!Vi(e.request,t.scope,t.shouldIntercept))return qi(e)?(n(`challenge-out-of-scope`,{header:e.getHeader(`www-authenticate`)??void 0,message:Ji(e.request.href,t.scope)}),{kind:`out-of-scope`}):{kind:`not-a-challenge`};let{challenge:r,diagnostics:i}=await Ki(e,t);if(Wi(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 Zi(s,e.signal)}catch(e){return Yi(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?.()??ji(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 Lr)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 Xi(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},$i=e=>{switch(e.kind){case`cancelled`:return new Ei;case`unsatisfiable`:return new Di;case`unavailable`:return new Rr;case`session-changed`:return new zr;case`insufficient`:return new Lr(e.obtained,e.required);case`exhausted`:return e.error;case`transport-failure`:return e.error;default:return}},ea=(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 Ei}:{settle:`resolve`,value:la(t,e)};case`insufficient`:return{settle:`resolve`,value:la(e.response?.raw??t,e)};default:return{settle:`resolve`,value:la(t,e)}}},ta=(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:$i(e)??t}}},na=new WeakSet,ra=new WeakSet,ia=new WeakSet,aa=new WeakSet,oa=new WeakSet,sa=new WeakSet,ca=new WeakSet,la=(e,t)=>{switch(t.kind){case`cancelled`:na.add(e);break;case`exhausted`:ra.add(e);break;case`insufficient`:ia.add(e);break;case`unsatisfiable`:aa.add(e);break;case`unavailable`:oa.add(e);break;case`session-changed`:sa.add(e);break;case`transport-failure`:ca.add(e)}return e},ua=e=>na.has(e),da=e=>ra.has(e),fa=e=>ia.has(e),pa=e=>aa.has(e),ma=e=>oa.has(e),ha=e=>sa.has(e),ga=e=>ca.has(e),_a=`https://passflow-relative.invalid`,va=()=>{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:_a},ya=(e,t=va())=>{let n=t===_a,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}},ba=(e,t)=>typeof t==`string`?[e.toLowerCase(),t]:void 0,xa=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=ba(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=ba(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=ba(n,Array.isArray(r)?r.join(`, `):r);e&&t.push(e)}return Object.freeze(t)},Sa=e=>{let t=e.base===void 0?ya(e.url):ya(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:xa(e.headers),bodyKind:e.bodyKind,...`body`in e?{body:e.body}:{}};return Object.freeze(n)},Ca=(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},wa=e=>{let t={};for(let[n,r]of e)t[n]=r;return t},Ta=new Set([`GET`,`HEAD`,`OPTIONS`]),Ea=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.clone==`function`&&`method`in e,Da=e=>typeof e==`string`?e:Ea(e)?e.url:String(e),Oa=(e,t)=>(t?.method??(Ea(e)?e.method:void 0)??`GET`).toUpperCase(),ka=e=>e==null?`none`:typeof e==`string`?`reusable`:typeof e.getReader==`function`?`one-shot`:`reusable`,Aa=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},ja=(e,t,n)=>e===void 0||e===`always`?!0:e===`idempotent-only`?Ta.has(t.method):typeof e==`function`?e(t):!(e.maxBodyBytes!==void 0&&n!==void 0&&n>e.maxBodyBytes),Ma=(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}`))}),Na=(e,t)=>wa(Ca(e.headers,t?.authorizationSwap)),Pa=e=>{if(!e||!(`headers`in e))return e;let{headers:t,...n}=e;return n},Fa=(e,t)=>t&&`headers`in t&&t.headers!==void 0?t.headers:Ea(e)?e.headers:void 0,Ia=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},La=(e,t,n)=>new Request(e,{headers:Na(t,n)}),Ra=(e,t,n)=>{let r=Da(e),i=Oa(e,t),a=Fa(e,t),o=(e,t)=>Sa({url:r,method:i,headers:a,bodyKind:e,...t===void 0?{}:{body:t}});if(Ea(e)){if(e.body===null||e.body===void 0){let a=o(`none`);return ja(n,{url:r,method:i,bodyKind:`none`})?{replayable:!0,bodyKind:`none`,forwardInput:e,forwardInit:t,snapshot:a,replay:(n,r)=>n(La(e,a,r),Pa(t))}:Ma(`none`,`the replay policy refused this request`,e,a,t)}let a=o(`request-clone`);if(!ja(n,{url:r,method:i,bodyKind:`request-clone`}))return Ma(`request-clone`,`the replay policy refused this request`,e,a,t);let s;try{s=e.clone()}catch{return Ma(`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(La(s,a,n),Pa(t))}}let s=ka(t?.body);if(s===`one-shot`)return Ma(`one-shot`,`a streaming request body is consumed by the first send`,e,o(`one-shot`),t);if(!ja(n,{url:r,method:i,bodyKind:s},Aa(t?.body)))return Ma(s,`the replay policy refused this request`,e,o(s),t);let c=t&&`body`in t?Ia(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,{...Pa(t),...c===void 0?{}:{body:c},headers:Na(l,n),method:l.method})}},za=e=>typeof e==`object`&&!!e,Ba=e=>t=>{if(!za(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},Va=e=>{let t=e?.url??``,n=e?.baseURL;return!n||/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:`${n.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`},Ha=e=>(e?.method??`GET`).toUpperCase(),Ua=e=>e==null?`none`:za(e)&&(typeof e.pipe==`function`||typeof e.getReader==`function`)?`one-shot`:`reusable`,Wa=(e,t,n)=>{let r=wa(Ca(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}:{}}},Ga=(e,t,n,r,i,a)=>{let o=t??e?.config,s=Ua(o?.data),c=a??Sa({url:Va(o),method:Ha(o),headers:o?.headers,bodyKind:s,body:o?.data}),l={url:c.href,method:c.method,bodyKind:s},u=s!==`one-shot`&&ja(i.replay,l);return{status:e?.status??0,getHeader:Ba(e?.headers),readBody:async()=>e?.data,request:c,replay:async e=>{let t=je(Wa(o??{},c,e));try{let e=await r(t);return Ga(e,e?.config??t,e,r,i,c)}catch(e){let n=za(e)?e:{};if(!n.response||typeof n.response.status!=`number`||kr(e))throw e;return{...Ga(n.response,n.config??t,e,r,i,c),rejected:!0}}},markers:{...Ae(o)?{upgradeTransaction:!0}:{},...Me(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}},Ka=(e,t)=>async n=>{let r=Ii(e),i=za(n)?n:{},a=ta(await Qi(Ga(i.response,i.config,i.response,t,r),r),n);if(a.settle===`reject`)throw a.error;return a.value},qa=(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,Ka(t,i)),o=!1;return()=>{o||(o=!0,e.interceptors.response.eject(a))}},Ja=(e,t)=>{let n=c.default.create(e);return t(n),n},Ya=0,Xa=(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)}:{}}},Za=e=>t=>e.headers?.get(t),Qa=(e,t,n,r,i)=>({status:e.status,getHeader:Za(e),readBody:()=>e.clone().json(),request:t.snapshot,replay:async e=>Qa(await t.replay(n,e),t,n,r,i),markers:r,raw:e,replayable:t.replayable,replayUnsupportedReason:t.reason,signal:i,responseType:e.type}),$a=(e,t)=>{let n=(t,n)=>{Ya+=1;try{return e(t,n)}finally{--Ya}};return async(e,r)=>{if(Ya>0)return n(e,r);let i=Ii(t),a=Ra(e,r,i.replay),o=await n(a.forwardInput,a.forwardInit),s=ea(await Qi(Qa(o,a,n,{},Xa(e,r)),i),o,i);if(s.settle===`reject`)throw s.error;return s.value}},eo=new Set(yi.filter(e=>!e.requiresPrepare).map(e=>e.type)),to=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}},no=e=>kr(e)&&!Ar(e),ro=e=>({async prepare(t){if(!eo.has(t))try{let n=e.relyingPartyId?.();return to(await e.startUpgrade(n?{method:t,relying_party_id:n}:{method:t}))}catch(e){if(no(e))throw e;let t=Pr(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(no(t))throw t;let n=Pr(t,`refresh`);throw n.status===401&&Ir(n)&&e.markSessionInvalid?.(),n}}}),io=e=>e===void 0?[]:(Array.isArray(e)?e:[e]).filter(e=>e!==``),ao=e=>{let t,n=e=>e!==void 0&&t===e,r=r=>{let i=()=>{if(!n(r()))throw new $({kind:`session_changed`})};return ro({...e,relyingPartyId:()=>t?.options.relyingPartyId??e.relyingPartyId?.(),startUpgrade:t=>(i(),e.startUpgrade(t)),commitRefresh:t=>(i(),e.commitRefresh(t,r()?.pin)),...e.markSessionInvalid?{markSessionInvalid:()=>{n(r())&&e.markSessionInvalid?.()}}:{}})},i=(t,n)=>{let i={},a={controller:new Fi({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:io(t.backend)},generation:n};return i.current=a,a},a=async(r,i)=>{let a=t;if(!a)throw new Rr(`Step-up verification is not enabled on this Passflow instance`);a.controller.active||(a.pin=e.readSessionPin?.());let o=await a.controller.elevate(r,i);if(!n(a))throw new zr;return o},o=()=>{let n=t,r=n?.scope??{passflow:e.passflowDomain,backend:[]},i=n?.options;return{elevate:a,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}:{}}},s;return Object.defineProperties(async e=>{let t=e?.acrValues===void 0?void 0:z(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}},o=(await a(n,{kind:`imperative`,...r?{requested:i}:{}})).obtained.acrValues;return{status:`elevated`,...o===void 0?{}:{acr:o}}},{enable:{value:n=>{s?.(),t=i(n,0);let r=[];if(e.attachInternalSeam){let t=e.attachInternalSeam;t(e=>Ka(o,e)),r.push(()=>t(void 0))}n.interceptFetch&&r.push(zt((e,t,n)=>$a(e,o)(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 s=()=>{if(!a){a=!0;for(let e of r)e();t=void 0,s=void 0}},s},enumerable:!0},enabled:{enumerable:!0,get(){return t!==void 0&&e.canCommit().ok}},elevate:{enumerable:!0,value:(e,t)=>a(e,t??{kind:`imperative`})},withAuth:{enumerable:!0,value:e=>{if(e)return $a(e,o);let t=typeof globalThis>`u`?void 0:globalThis;if(!t||typeof t.fetch!=`function`)throw Error(`Passflow: withAuth() needs a fetch to wrap — this runtime has none.`);return $a(t.fetch.bind(t),o)}},attachAuth:{enumerable:!0,value:e=>qa(e,o)}})},oo,so=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??L,this.deferFederatedLanding=e.deferFederatedLanding??!1,this.storageManager=new P({prefix:e.keyStoragePrefix??``,storage:this.platform.storage}),this.deviceService=new F(this.storageManager),this.authApi=new mt(e,this.storageManager,this.deviceService),this.appApi=new ct(e,this.storageManager,this.deviceService),this.userApi=new Tt(e,this.storageManager,this.deviceService),this.settingApi=new _t(e,this.storageManager,this.deviceService),this.tenantApi=new vt(e,this.storageManager,this.deviceService),this.invitationApi=new gt(e,this.storageManager,this.deviceService),this.twoFactorApi=new Ct(e,this.storageManager,this.deviceService),this.upgradeApi=new wt(e,this.storageManager,this.deviceService),this.upgradeDomain=Fe(e.url),this.subscribeStore=new _r,this.tokenCacheService=new di(this.storageManager,this.authApi,this.subscribeStore,this.platform),this.scopes=r??_,this.createTenantForNewUser=e.createTenantForNewUser??!1;let i=An(e.refreshCoordination,this.platform,e.keyStoragePrefix,{tokenKeys:()=>this.storageManager.tokenKeys()});this.authService=new si(this.authApi,this.deviceService,this.storageManager,this.subscribeStore,this.tokenCacheService,this.scopes,this.createTenantForNewUser,this.url,{createSession:this.createSessionCallback,expiredSession:this.expiredSessionCallback},this.appId??``,e.tokenExchange,this.platform,()=>this.readPkceEnabled(),{coordination:i,...e.refreshStrikes===void 0?{}:{strikes:e.refreshStrikes}}),this.tokenCacheService.attachRefreshController(this.authService.refresh);for(let e of this.axiosClients())e.setRefreshHandler(e=>this.authService.refresh.ensureFresh(e));this.userService=new pi(this.userApi,this.deviceService,this.platform),this.tenantService=new ui(this.tenantApi,this.scopes),this.tenant=this.tenantService,this.invitationService=new ci(this.invitationApi),this.twoFactorService=new fi(this.twoFactorApi,this.subscribeStore,this.authService),this.twoFactor=this.twoFactorService,this.upgrade=ao({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(M.access_token);return e?{from:`Bearer ${e}`,to:`Bearer ${e}`}:void 0},attachInternalSeam:e=>this.attachUpgradeSeam(e),onSessionChange:e=>this.subscribeToSessionChange(e)}),e.parseQueryParams&&this.checkAndSetTokens(),this.setTokensToCacheFromLocalStorage()}readPkceEnabled(){if(!this.appId)return Promise.resolve(!1);if(!this.pkceEnabledRead){let e=this.appApi.getAppSettings().then(e=>e.pkce_enabled);this.pkceEnabledRead=e,e.catch(()=>{this.pkceEnabledRead===e&&(this.pkceEnabledRead=void 0)})}return this.pkceEnabledRead}setAppId(e){this.appId=e,this.pkceEnabledRead=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}withAuth(e){return this.upgrade.withAuth(e)}attachAuth(e){return this.upgrade.attachAuth(e)}createClient(e){return Ja(e,e=>this.upgrade.attachAuth(e))}readAssuranceBar(){let e=this.storageManager.getToken(M.access_token);if(e)try{let t=j(e),n=typeof t.acr==`string`?t.acr:void 0;if(!n)return;let r=z(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,[Z.SignIn,Z.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 V?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()}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(`scopes`)?.split(`,`)??this.scopes;if(n){if(!Hr(n)){W(this.subscribeStore,{operation:`tokens.from-url`,message:`Invalid access token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(e);return}if(r&&!Hr(r)){W(this.subscribeStore,{operation:`tokens.from-url`,message:`Invalid refresh token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(e);return}if(i&&!Hr(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:a};this.cleanupUrlParams(e),this.error=void 0,Sr(this.url,this.appId,t).then(()=>{this.storageManager.clearDeliveryMode(),this.storageManager.saveTokens(t),this.tokenCacheService.setTokensCache(t),this.authService.refresh.sessionStarted()}).then(()=>(this.subscribeStore.notify(Z.SignIn,{tokens:t,parsedTokens:this.getParsedTokens(),source:`tokens-in-url`}),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:`TOKEN_NOT_VERIFIED`,originalError:e}))}else this.cleanupUrlParams(e),this.deferFederatedLanding||this.takeFederatedLanding(),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}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();return this.platform.replaceUrl(e.pathname+e.search+(r?`#${r}`:``)),Hr(n)?(this.subscribeStore.notify(Z.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=Ur(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=>r.get(e));if(!i&&!t.some(e=>n.get(e)))return;for(let e of[...t,`client_challenge`])n.delete(e);let a=n.toString();this.platform.replaceUrl(e.pathname+(a?`?${a}`:``)+(i?``:e.hash??``))}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===N.Cookie||e===N.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){return await this.authService.signIn(e)}async signUp(e){return await this.authService.signUp(e)}passwordlessSignIn(e){return this.authService.passwordlessSignIn(e)}async passwordlessSignInComplete(e){return await this.authService.passwordlessSignInComplete(e)}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`)}}handleError(e,t,n){let r={operation:t,message:e instanceof Error?e.message:`${n} failed`,originalError:e,code:e instanceof V?e.id:void 0};throw W(this.subscribeStore,r),e}async logOut(){try{let e=await this.authService.logOut();this.twoFactorService.clearPartialAuthState(),this.notifySignedOut(e),await this.submitSessionCheck()}catch(e){this.handleError(e,`log-out`,`Log out`)}}federatedAuthWithPopup(e){this.authService.federatedAuthWithPopup(e)}federatedAuthWithRedirect(e){this.authService.federatedAuthWithRedirect(e)}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(Z.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()}sendPasswordResetEmail(e){return this.authService.sendPasswordResetEmail(e)}async resetPassword(e,t,n){return await this.authService.resetPassword(e,t,n)}async getAppSettings(){try{return 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){return await this.authService.passkeyRegister(e)}async passkeyAuthenticate(e){return await this.authService.passkeyAuthenticate(e)}setTokens(e){let t=this.getDeliveryMode(),n=t===N.Cookie||t===N.BFF;this.storageManager.saveTokens(e,n?t:void 0),this.tokenCacheService.setTokensCache(e),this.authService.refresh.sessionStarted(),this.subscribeStore.notify(Z.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 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={}){this.authService.authRedirect(e)}getDeliveryMode(){return this.authService.tokenDeliveryManager.getMode()}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(Z.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(Z.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`)}}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()}};oo=so,oo.version=h,exports.APP_ID_HEADER_KEY=d,exports.APP_SECRET_NAMES=Be,exports.AUTHORIZATION_HEADER_KEY=f,exports.AppAPI=ct,exports.AuthAPI=mt,exports.AuthService=si,exports.CLIAuthAPI=ht,exports.DEFAULT_GROUP_NAME=y,exports.DEFAULT_SCOPES=_,exports.DEFAULT_UPGRADE_FACTORS=yi,exports.DEVICE_ID_HEADER_KEY=p,exports.DEVICE_TYPE_HEADER_KEY=m,exports.ERROR_MESSAGE_MAX_LENGTH=E,exports.FETCH_PRIORITY_OIDC=Et,exports.FETCH_PRIORITY_UPGRADE=Dt,exports.FetchMiddlewareContractError=Ot,exports.INSUFFICIENT_USER_AUTHENTICATION=pe,exports.InvitationAPI=gt,exports.InvitationService=ci,exports.M2MClient=Jt,exports.M2MConfigError=Ut,exports.M2MError=U,exports.M2MErrorCodes=Wt,exports.M2MNetworkError=Vt,exports.M2MTokenParseError=Ht,exports.M2M_DEFAULTS=Gt,exports.MASKED_SECRET_PREFIX=Ve,exports.MINIMAL_DEFAULT_SCOPES=g,exports.OS=We,exports.PASSFLOW_CLOUD_URL=v,exports.POPUP_HEIGHT=x,exports.POPUP_POLL_INTERVAL_MS=ee,exports.POPUP_TIMEOUT_MS=S,exports.POPUP_WIDTH=b,exports.Passflow=so,exports.PassflowAdminEndpointPaths=Pe,exports.PassflowEndpointPaths=B,exports.PassflowError=V,exports.PassflowEvent=Z,exports.PassflowRefreshError=J,exports.PopupClosedError=I,exports.Providers=ze,exports.RECOVERABLE_COMMIT_ERROR_IDS=Cr,exports.REFRESH_AUTH_FAILURE_IDS=zn,exports.RefreshErrorId=q,exports.RequestMethod=Ne,exports.SDK_VERSION=h,exports.SERVICE_UNAVAILABLE_ERROR_ID=Le,exports.SERVICE_UNAVAILABLE_MESSAGE=Re,exports.SESSION_INVALIDATING_COMMIT_ERROR_IDS=wr,exports.SETTINGS_MASKED_VALUE_UNKNOWN_ERROR_ID=He,exports.SessionState=se,exports.SettingAPI=_t,exports.TOKEN_EXPIRY_BUFFER_SECONDS=C,exports.TenantAPI=vt,exports.TenantService=ui,exports.TenantUserMembership=li,exports.TokenCacheService=di,exports.TokenDeliveryMode=N,exports.TokenType=M,exports.TwoFactorApiClient=Ct,exports.TwoFactorPolicy=Ke,exports.TwoFactorService=fi,exports.UPGRADE_REQUIRED=me,exports.USERNAME_MAX_LENGTH=T,exports.USERNAME_MIN_LENGTH=w,exports.UpgradeAPI=wt,exports.UpgradeCancelledError=Ei,exports.UpgradeCommitInterruptedError=Zn,exports.UpgradeController=Fi,exports.UpgradeErrorIds=Q,exports.UpgradeFactorError=mi,exports.UpgradeInsufficientError=Lr,exports.UpgradeSessionChangedError=zr,exports.UpgradeTransportError=$,exports.UpgradeUnavailableError=Rr,exports.UpgradeUnsatisfiableError=Di,exports.UserAPI=Tt,exports.UserService=pi,exports.WebAdapter=le,exports.classifyUpgradeError=Pr,exports.factorRegistry=bi,exports.fetchRegistryState=Bt,exports.getOSFromDeviceType=Ge,exports.invalidatesSessionOnCommit=Ir,exports.isEmailVerificationStep=Ie,exports.isMaskedSecret=Ue,exports.isRecoverableCommitFailure=Fr,exports.isRetryableUpgradeKind=Er,exports.isTokenExpired=A,exports.isUpgradeCancelled=ua,exports.isUpgradeExhausted=da,exports.isUpgradeInsufficient=fa,exports.isUpgradeSessionChanged=ha,exports.isUpgradeTransportError=Ar,exports.isUpgradeTransportFailure=ga,exports.isUpgradeUnavailable=ma,exports.isUpgradeUnsatisfiable=pa,exports.isValidEmail=Wr,exports.isValidJWTFormat=Hr,exports.isValidPhoneNumber=Gr,exports.isValidUsername=Kr,exports.parseChallengeBody=xe,exports.parseChallengeHeader=be,exports.parseToken=j,exports.parseUpgradeChallenge=Te,exports.passkeyFactor=vi,exports.pathWithParams=H,exports.recoveryCodesFactor=_i,exports.registerFetchMiddleware=zt,exports.requiredAcrLevel=fe,exports.resolveUpgradeDomain=Fe,exports.sanitizeErrorMessage=Ur,exports.selectFactors=Ti,exports.totpFactor=gi,exports.webAdapter=L;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|