@passflow/core 0.7.0 → 0.8.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/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U=require("axios"),we=require("uuid"),O=require("@simplewebauthn/browser"),Te="0.7.0",Ee={version:Te},A="X-Passflow-Clientid",I="Authorization",Y="X-Passflow-DeviceId",H="X-Passflow-DeviceType",B=Ee.version,_e=["id","offline","openid"],j=["id","offline","tenant","email","oidc","openid","access:tenant:all"],N="https://auth.passflow.cloud",Ie="default",X=500,z=600,W=100,J=6e4,K=30,Z=3,Q=30,ee=200,be=i=>{const e=[];let t;for(t in i){const r=i[t];if(r===void 0)continue;const s={tenant:{id:r.tenant_id,name:r.tenant_name}};s.groups=r.groups?Object.keys(r.groups).map(o=>{const a=r.groups[o]||[];return{group:{id:o,name:r.group_names?.[o]??"unknown"},roles:a}}):[],s.tenantRoles=s.groups?.find(o=>o.group.id===r.root_group_id),e.push(s)}return{raw:i,tenants:e}};function Ae(i){if(typeof window<"u"&&typeof window.atob=="function")return window.atob(i);if(typeof Buffer<"u")return Buffer.from(i,"base64").toString("utf-8");throw new Error("No Base64 decoding method available in this environment")}class Ce{constructor(e){this.storageManager=e}isTokenTypeExpired(e){const t=this.storageManager.getToken(e);if(!t)return!0;const r=v(t);return r?m(r):!0}parseTokenType(e){const t=this.storageManager.getToken(e);if(t)return v(t)}}function m(i,e=K){return Math.floor(Date.now()/1e3)+e>i.exp}function v(i){const e=i.split(".")[1];if(!e)throw new Error("Invalid token string");const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4),s=Ae(r),o=decodeURIComponent(s.split("").map(d=>"%"+("00"+d.charCodeAt(0).toString(16)).slice(-2)).join("")),a=JSON.parse(o);return a.membership=a.passflow_tm&&a.type!=="invite"?be(a.passflow_tm):void 0,a}var p=(i=>(i.id_token="id_token",i.access_token="access",i.refresh_token="refresh",i.invite_token="invite",i.reset_token="reset",i.web_cookie="web-cookie",i.management="management",i.signin="signin",i.actor="actor",i.two_factor="2fa",i))(p||{}),S=(i=>(i.JsonBody="json_body",i.Cookie="cookie",i.Mobile="mobile",i.BFF="bff",i))(S||{}),V=(i=>(i.Unknown="unknown",i.Valid="valid",i.Invalid="invalid",i))(V||{});class te{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{const e=this.storageManager.storage.getItem(this.DELIVERY_MODE_KEY);e&&Object.values(S).includes(e)&&(this.mode=e,this.isInitializedFlag=!0)}catch{}}loadPersistedSessionState(){try{const e=this.storageManager.storage.getItem(this.SESSION_STATE_KEY);e&&Object.values(V).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{}}}class G{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){const{id_token:r,access_token:s,refresh_token:o,scopes:a}=e;t===S.Cookie||t===S.BFF?r&&this.storage.setItem(this.ID_TOKEN_KEY,r):(r&&this.storage.setItem(this.getKeyForTokenType(p.id_token),r),s&&this.storage.setItem(this.getKeyForTokenType(p.access_token),s),o&&this.storage.setItem(this.getKeyForTokenType(p.refresh_token),o),a&&this.storage.setItem(this.scopes,a.join(",")))}getToken(e){const t=this.getKeyForTokenType(e);return this.storage.getItem(t)??void 0}getTokens(){const e=this.getDeliveryMode();if(e===S.Cookie||e===S.BFF){const r=this.storage.getItem(this.ID_TOKEN_KEY);return r?{id_token:r}:void 0}const t=this.storage.getItem(this.getKeyForTokenType(p.access_token));if(t)return{access_token:t,id_token:this.storage.getItem(this.getKeyForTokenType(p.id_token))??void 0,refresh_token:this.storage.getItem(this.getKeyForTokenType(p.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(p.access_token))}hasCookieModeIdToken(){return!!this.storage.getItem(this.ID_TOKEN_KEY)}deleteToken(e){const t=this.getKeyForTokenType(e);this.storage.removeItem(t)}deleteTokens(){this.storage.removeItem(this.getKeyForTokenType(p.id_token)),this.storage.removeItem(this.getKeyForTokenType(p.access_token)),this.storage.removeItem(this.getKeyForTokenType(p.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{const e=this.storage.getItem(this.DELIVERY_MODE_KEY);if(e&&Object.values(S).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{}}getKeyForTokenType(e){return`${this.keyStoragePrefix}${e}`}}class re{constructor(e){this.storageManager=e??new G}getDeviceId(){const e=this.storageManager.getDeviceId();if(!e){const t=this.generateUniqueDeviceId();return this.storageManager.setDeviceId(t),t}return e}generateUniqueDeviceId(){return we.v4()}}var _=(i=>(i.GET="get",i.POST="post",i.PUT="put",i.PATCH="patch",i.DELETE="delete",i))(_||{}),c=(i=>(i.signin="/auth/login",i.signup="/auth/register",i.signInWithProvider="/auth/federated/start/",i.passwordless="/auth/passwordless/start",i.passwordlessComplete="/auth/passwordless/complete",i.logout="/user/logout",i.refresh="/auth/refresh",i.validateSession="/user/me",i.sendPasswordResetEmail="/auth/password/reset",i.resetPassword="/auth/password/change",i.appSettings="/app/settings",i.passkeyRegisterStart="/auth/passkey/register/start",i.passkeyRegisterComplete="/auth/passkey/register/complete",i.passkeyAuthenticateStart="/auth/passkey/authenticate/start",i.passkeyAuthenticateComplete="/auth/passkey/authenticate/complete",i.passkeyValidate="/auth/validate",i.settingsAll="/settings",i.settingsPasswordPolicy="/settings/password",i.settingsPasskey="/settings/passkey",i.userPasskey="/user/passkey",i.addUserPasskey="/user/passkey/add/start",i.completeAddUserPasskey="/user/passkey/add/complete",i.joinInvitation="/user/tenant/join",i.tenantPath="/user/tenant",i.invitationsPath="/user/tenant/:tenantID/invitations",i.requestInvitation="/user/invite",i.invitationDelete="/user/invite/:invitationID",i.invitationResend="/user/invite/:invitationID/resend",i.invitationGetLink="/user/invite/:invitationID/link",i.twoFactor="/user/2fa",i.twoFactorStatus="/user/2fa/status",i.twoFactorSetupBegin="/user/2fa/setup/begin",i.twoFactorSetupConfirm="/user/2fa/setup/confirm",i.twoFactorVerify="/auth/2fa/verify",i.twoFactorRecovery="/auth/2fa/recovery",i.twoFactorRegenerateCodes="/user/2fa/recovery-codes/regenerate",i.twoFactorSetupMagicLink="/auth/2fa-setup",i.TwoFactorMethodsAvailable="/v2/user/2fa/methods/available",i.TwoFactorMethodsRegistered="/v2/user/2fa/methods",i.TwoFactorMethodSetupBegin="/v2/user/2fa/methods/:method/setup/begin",i.TwoFactorMethodSetupConfirm="/v2/user/2fa/methods/:method/setup/confirm",i.TwoFactorMethodRemove="/v2/user/2fa/methods/:id",i.TwoFactorChallenge="/v2/auth/2fa/challenge",i.TwoFactorVerifyV2="/v2/auth/2fa/verify",i.TwoFactorAlternative="/v2/auth/2fa/alternative",i.TwoFactorTrustedDevices="/v2/user/2fa/trusted-devices",i.TwoFactorTrustedDeviceRevoke="/v2/user/2fa/trusted-devices/:id",i.cliAuthStatus="/cli/auth/status/:sessionId",i.cliAuthComplete="/cli/auth/complete",i))(c||{}),T=(i=>(i.passkeyRegisterStart="/admin/auth/passkey/register/start",i.passkeyRegisterComplete="/admin/auth/passkey/register/complete",i.passkeyAuthenticateStart="/admin/auth/passkey/authenticate/start",i.passkeyAuthenticateComplete="/admin/auth/passkey/authenticate/complete",i.passkeyValidate="/admin/auth/validate",i.logout="/admin/auth/logout",i))(T||{});class u 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()}}var se=(i=>(i.google="google",i.facebook="facebook",i))(se||{}),b=(i=>(i.web="web",i))(b||{});function y(i,e){let t=i;return Object.entries(e).forEach(([r,s])=>{t=t.replace(`:${r}`,s)}),t}var ie=(i=>(i.Disabled="disabled",i.Optional="optional",i.Required="required",i))(ie||{});const Re=3,Me=1e3;class E{constructor(e,t,r){this.refreshPromise=null,this.isRefreshing=!1,this.origin=typeof window<"u"?window.location.origin:"",this.defaultHeaders={Accept:"application/json","Content-Type":"application/json"},this.nonAccessTokenEndpoints=["/auth/","/settings","/settings/"],this.protectedEndpoints=["logout","refresh"];const{url:s,appId:o,keyStoragePrefix:a}=e;this.url=s||N,this.storageManager=t??new G({prefix:a??""}),this.deviceService=r??new re(this.storageManager),this.tokenService=new Ce(this.storageManager),this.tokenDeliveryManager=new te(this.storageManager),o&&(this.appId=o,this.defaultHeaders={...this.defaultHeaders,[A]:o});const d=this.deviceService.getDeviceId();this.defaultHeaders={...this.defaultHeaders,[Y]:d,[H]:"web"},this.detectCookieSupport(),this.instance=U.create({baseURL:this.url,headers:{...this.defaultHeaders}}),this.instance.interceptors.request.use(async h=>{if(this.isNonAuthEndpoint(h.url))return h;if(this.tokenDeliveryManager.isCookieMode()){h.withCredentials=!0;const f=this.storageManager.getCsrfToken();return f&&(h.headers["X-CSRF-Token"]=f),h}if(h.url?.includes("refresh")){if(this.isRefreshing){const f=new AbortController;return f.abort(),h.signal=f.signal,h}return h}const g=this.storageManager.getTokens();if(g?.access_token){const f=v(g.access_token);if(m(f,K)&&g.refresh_token)try{if(this.refreshPromise){const k=await this.refreshPromise;return k?.data?.access_token&&(h.headers[I]=`Bearer ${k.data.access_token}`),h}this.refreshPromise=this.refreshTokens();try{const k=await this.refreshPromise;return k?.data?.access_token&&(h.headers[I]=`Bearer ${k.data.access_token}`),h}finally{this.refreshPromise=null}}catch(k){return this.refreshPromise=null,this.isRefreshing=!1,this.storageManager.deleteTokens(),Promise.reject(k)}return h.headers[I]=`Bearer ${g.access_token}`,h}return h}),this.instance.interceptors.response.use(h=>h,async h=>(h.response?.status===401&&this.tokenDeliveryManager.setSessionInvalid(),h.response?.status===429?await this.handleRateLimitError(h):this.handleAxiosError(h)))}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(!(typeof document>"u"))try{document.cookie="passflow_test=1; SameSite=Lax";const e=document.cookie.indexOf("passflow_test=1")!==-1;document.cookie="passflow_test=; expires=Thu, 01 Jan 1970 00:00:00 UTC",!e&&this.tokenDeliveryManager.isCookieMode()}catch{}}async refreshTokens(){if(this.tokenDeliveryManager.isCookieMode()){const e=await this.instance.post(c.refresh,{},{withCredentials:!0});return this.tokenDeliveryManager.setSessionValid(),e.data.csrf_token&&this.storageManager.setCsrfToken(e.data.csrf_token),e.data.id_token&&this.storageManager.setIdToken(e.data.id_token),e}else{const e=this.storageManager.getTokens(),t=this.storageManager.getScopes();if(!e?.refresh_token)throw new Error("No refresh token available");this.isRefreshing=!0;const r={refresh_token:e.refresh_token,scopes:t},s=await this.instance.post(c.refresh,r,{headers:{[I]:`Bearer ${e.refresh_token}`}});return s.data&&this.storageManager.saveTokens(s.data),this.isRefreshing=!1,s}}async handleRateLimitError(e){const t=e.config;if(!t)return Promise.reject(e);const r=t.method?.toUpperCase();if(!["GET","HEAD","OPTIONS"].includes(r||""))return Promise.reject(e);const o=t._retryCount||0;if(o>=Re)return Promise.reject(e);let a=Me*Math.pow(2,o);const d=e.response?.headers?.["retry-after"];if(d){const h=Number.parseInt(d,10);if(!Number.isNaN(h))a=h*1e3;else{const g=new Date(d);Number.isNaN(g.getTime())||(a=Math.max(0,g.getTime()-Date.now()))}}return await new Promise(h=>setTimeout(h,a)),t._retryCount=o+1,this.instance.request(t)}async handleAxiosError(e){if(!e.response)return Promise.reject(e);const t=e.response.status,r=e.response.data;if("error"in r&&typeof r.error=="object"&&r.error!==null){const{error:s}=r;return Promise.reject(new u(s))}return Promise.reject(new u({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,r){return(await this.instance.request({method:e,url:t,...r})).data}get(e,t){return this.send(_.GET,e,t)}post(e,t,r){return this.send(_.POST,e,{data:t,...r})}put(e,t,r){return this.send(_.PUT,e,{data:t,...r})}patch(e,t,r){return this.send(_.PATCH,e,{data:t,...r})}delete(e,t){return this.send(_.DELETE,e,t)}setAppId(e){this.appId=e,this.defaultHeaders={...this.defaultHeaders,[A]:e},this.instance.defaults.headers.common[A]=e}}class oe{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getAppSettings(){return this.axiosClient.get(c.appSettings)}}class ne{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}refreshToken(e,t,r){const s={access:r,scopes:t};return this.axiosClient.post(c.refresh,s,{headers:{[I]:`Bearer ${e}`}})}signIn(e,t,r){const s={...e,device:t,os:r};return this.axiosClient.post(c.signin,s)}signUp(e){const{create_tenant:t,anonymous:r}=e,s={...e,create_tenant:t??!1,anonymous:r??!1};return this.axiosClient.post(c.signup,s)}passwordlessSignIn(e,t,r){const{create_tenant:s}=e,o={...e,create_tenant:s??!1,device:t,os:r};return this.axiosClient.post(c.passwordless,o)}passwordlessSignInComplete(e){return this.axiosClient.post(c.passwordlessComplete,e)}logOut(e,t,r=!1){const s=r?void 0:{refresh_token:t,device:e},o=r?T.logout:c.logout;return this.axiosClient.post(o,s)}validateSession(){return this.axiosClient.get(c.validateSession)}sendPasswordResetEmail(e){return this.axiosClient.post(c.sendPasswordResetEmail,e)}resetPassword(e,t,r){const s={password:e,scopes:t};return this.axiosClient.post(c.resetPassword,s,{headers:{[I]:`Bearer ${r}`,[A]:void 0}})}passkeyRegisterStart(e,t,r,s=!1){const{create_tenant:o}=e,a={...e,create_tenant:o??!1,device:t,os:r},d=s?T.passkeyRegisterStart:c.passkeyRegisterStart;return this.axiosClient.post(d,a)}passkeyRegisterComplete(e,t,r,s=!1){const o={challenge_id:r,device:t,passkey_data:e},a=s?T.passkeyRegisterComplete:c.passkeyRegisterComplete;return this.axiosClient.post(a,o)}passkeyAuthenticateStart(e,t,r,s=!1){const o={...e,user_id:e.user_id??"",device:t,os:r},a=s?T.passkeyAuthenticateStart:c.passkeyAuthenticateStart;return this.axiosClient.post(a,o)}passkeyAuthenticateComplete(e,t,r,s=!1){const o={challenge_id:r,device:t,passkey_data:e},a=s?T.passkeyAuthenticateComplete:c.passkeyAuthenticateComplete;return this.axiosClient.post(a,o)}passkeyValidate(e,t,r,s=!1,o){const a={otp:e,device:t,challenge_id:r};let d=c.passkeyValidate;!o&&s&&(d=T.passkeyValidate);const h=o?{[A]:o}:{};return this.axiosClient.post(d,a,{headers:h})}}class Fe{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getCLIAuthStatus(e){const t=y(c.cliAuthStatus,{sessionId:e});return this.axiosClient.get(t)}completeCLIAuth(e){return this.axiosClient.post(c.cliAuthComplete,e)}}class ae{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}requestInviteLink(e){return this.axiosClient.post(c.requestInvitation,e)}getInvitations(e){const 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());const r=y(c.invitationsPath,{tenantID:e.tenantID});return this.axiosClient.get(r,{params:t}).then(s=>({invites:s.invites,nextPageSkip:s.next_page_skip}))}deleteInvitation(e){const t=y(c.invitationDelete,{invitationID:e});return this.axiosClient.delete(t)}resendInvitation(e){const t=y(c.invitationResend,{invitationID:e});return this.axiosClient.post(t,{})}getInvitationLink(e){const t=y(c.invitationGetLink,{invitationID:e});return this.axiosClient.get(t)}}class ce{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getSettingsAll(){return this.axiosClient.get(c.settingsAll)}getPasswordPolicySettings(){return this.axiosClient.get(c.settingsPasswordPolicy)}getPasskeySettings(){return this.axiosClient.get(c.settingsPasskey)}}class he{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}joinInvitation(e,t){const r={invite_token:e,scopes:t};return this.axiosClient.post(c.joinInvitation,r)}createTenant(e){const t={name:e};return this.axiosClient.post(c.tenantPath,t)}getTenantDetails(e){const t=`${c.tenantPath}/${e}`;return this.axiosClient.get(t)}updateTenant(e,t){const r=`${c.tenantPath}/${e}`,s={name:t};return this.axiosClient.put(r,s)}deleteTenant(e){const t=`${c.tenantPath}/${e}`;return this.axiosClient.delete(t)}getUserTenantMembership(){return this.axiosClient.get(c.tenantPath)}createGroup(e,t){const r=`${c.tenantPath}/${e}/group`,s={name:t};return this.axiosClient.post(r,s)}getGroupInfo(e,t){const r=`${c.tenantPath}/${e}/group/${t}`;return this.axiosClient.get(r)}updateGroup(e,t,r){const s=`${c.tenantPath}/${e}/group/${t}`,o={name:r};return this.axiosClient.put(s,o)}deleteGroup(e,t){const r=`${c.tenantPath}/${e}/group/${t}`;return this.axiosClient.delete(r)}addUserToGroup(e,t,r,s){const o=`${c.tenantPath}/${e}/group/${t}/add`,a={user_id:r,role:s};return this.axiosClient.post(o,a)}removeUserRolesFromGroup(e,t,r,s){const o=`${c.tenantPath}/${e}/group/${t}/remove_roles`,a={user_id:r,roles:s};return this.axiosClient.post(o,a)}changeUserRoles(e,t,r,s){const o=`${c.tenantPath}/${e}/group/${t}/change`,a={user_id:r,roles:s};return this.axiosClient.post(o,a)}deleteUserFromGroup(e,t,r){const s=`${c.tenantPath}/${e}/group/${t}/${r}`;return this.axiosClient.delete(s)}getRolesForTenant(e){const t=`${c.tenantPath}/${e}/role`;return this.axiosClient.get(t)}createRoleForTenant(e,t){const r=`${c.tenantPath}/${e}/role`,s={name:t};return this.axiosClient.post(r,s)}updateRole(e,t,r){const s=`${c.tenantPath}/${e}/role/${t}`,o={name:r};return this.axiosClient.put(s,o)}deleteRole(e,t){const r=`${c.tenantPath}/${e}/role/${t}`;return this.axiosClient.delete(r)}deleteUserFromTenant(e,t){const r=`${c.tenantPath}/${e}/user/${t}`;return this.axiosClient.delete(r)}getGroupInvitations(e,t,r,s){const o=`${c.tenantPath}/${e}/group/${t}/invitations`;return this.axiosClient.get(o,{params:{limit:r,skip:s}})}getTenantInvitations(e,t,r){const s=`${c.tenantPath}/${e}/invitations`;return this.axiosClient.get(s,{params:{limit:t,skip:r}})}invalidateInviteById(e,t,r){const s=`${c.tenantPath}/${e}/group/${t}/invite/${r}`;return this.axiosClient.delete(s)}invalidateInviteByEmail(e,t,r){const s=`${c.tenantPath}/${e}/group/${t}/invite/email/${r}`;return this.axiosClient.delete(s)}}class de{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getStatus(){return this.axiosClient.get(c.twoFactorStatus)}beginSetup(){return this.axiosClient.post(c.twoFactorSetupBegin,{})}confirmSetup(e){return this.axiosClient.post(c.twoFactorSetupConfirm,e)}verify(e){const{tfa_token:t,code:r}=e;return this.axiosClient.post(c.twoFactorVerify,{code:r},{headers:{Authorization:`Bearer ${t}`}})}useRecoveryCode(e){const{tfa_token:t,recovery_code:r}=e;return this.axiosClient.post(c.twoFactorRecovery,{recovery_code:r},{headers:{Authorization:`Bearer ${t}`}})}disable(e){return this.axiosClient.delete(c.twoFactor,{data:e})}regenerateRecoveryCodes(e){return this.axiosClient.post(c.twoFactorRegenerateCodes,e)}validateTwoFactorSetupMagicLink(e){const t=`${c.twoFactorSetupMagicLink}/${e}`;return this.axiosClient.get(t,{transformRequest:[(r,s)=>(s&&delete s.Authorization,r)]}).then(r=>{const s=r;return{success:!0,sessionToken:s.session_token,userId:s.user_id,expiresIn:s.expires_in,appId:s.app_id}}).catch(r=>{if(r.response){const s=r.response.status,o=r.response.data||{},a=r.response.headers?.["retry-after"]?parseInt(r.response.headers["retry-after"],10):void 0;return{success:!1,error:{code:o.error||this.mapStatusToErrorCode(s),message:o.message||this.getDefaultErrorMessage(s),retryAfter:a}}}return{success:!1,error:{code:"SERVER_ERROR",message:r instanceof Error?r.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(c.TwoFactorMethodsAvailable)}getRegisteredMethods(){return this.axiosClient.get(c.TwoFactorMethodsRegistered)}beginMethodSetup(e){const t=y(c.TwoFactorMethodSetupBegin,{method:e});return this.axiosClient.post(t,{})}confirmMethodSetup(e,t){const r=y(c.TwoFactorMethodSetupConfirm,{method:e});return this.axiosClient.post(r,t)}removeMethod(e){const t=y(c.TwoFactorMethodRemove,{id:e});return this.axiosClient.delete(t)}requestChallenge(e){return this.axiosClient.post(c.TwoFactorChallenge,e)}verifyV2(e){return this.axiosClient.post(c.TwoFactorVerifyV2,e)}switchToAlternative(e){return this.axiosClient.post(c.TwoFactorAlternative,e)}getTrustedDevices(){return this.axiosClient.get(c.TwoFactorTrustedDevices)}revokeTrustedDevice(e){const t=y(c.TwoFactorTrustedDeviceRevoke,{id:e});return this.axiosClient.delete(t)}}class ue{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getUserPasskeys(){return this.axiosClient.get(c.userPasskey)}renameUserPasskey(e,t){return this.axiosClient.patch(`${c.userPasskey}/${t}`,{name:e})}deleteUserPasskey(e){return this.axiosClient.delete(`${c.userPasskey}/${e}`)}addUserPasskeyStart({relyingPartyId:e,deviceId:t,os:r,passkeyDisplayName:s,passkeyUsername:o}){const a={passkey_display_name:s,passkey_username:o,relying_party_id:e,deviceId:t,os:r};return this.axiosClient.post(c.addUserPasskey,a)}addUserPasskeyComplete(e,t,r){return this.axiosClient.post(c.completeAddUserPasskey,{challenge_id:r,device:t,passkey_data:e})}}var n=(i=>(i.SignIn="signin",i.SignInStart="signin:start",i.Register="register",i.RegisterStart="register:start",i.SignOut="signout",i.SessionRestored="session:restored",i.SessionExpired="session:expired",i.Error="error",i.Refresh="refresh",i.RefreshStart="refresh:start",i.TokenCacheExpired="token-cache-expired",i.TwoFactorRequired="2fa:required",i.TwoFactorSetupStarted="2fa:setup_started",i.TwoFactorEnabled="2fa:enabled",i.TwoFactorDisabled="2fa:disabled",i.TwoFactorVerified="2fa:verified",i.TwoFactorRecoveryUsed="2fa:recovery_used",i.TwoFactorRecoveryCodesLow="2fa:recovery_low",i.TwoFactorRecoveryCodesExhausted="2fa:recovery_exhausted",i.TwoFactorSetupMagicLinkValidated="2fa:magic_link_validated",i.TwoFactorSetupMagicLinkFailed="2fa:magic_link_failed",i.TwoFactorChallengeReceived="two_factor_challenge_received",i.TwoFactorMethodSwitched="two_factor_method_switched",i.TwoFactorDeviceTrusted="two_factor_device_trusted",i))(n||{});class Pe{constructor(){this.subscribers=new Map}subscribe(e,t){if(t?.length){const r=new Set(t);this.subscribers.set(e,r)}else this.subscribers.set(e,null)}unsubscribe(e,t){if(!t?.length){this.subscribers.delete(e);return}const r=this.subscribers.get(e);r&&(t.forEach(s=>r.delete(s)),r.size===0&&this.subscribers.delete(e))}notify(e,t){this.subscribers.forEach((r,s)=>{(!r||r.has(e))&&s.onAuthChange?.(e,t)})}}function F(i){if(!i||typeof i!="string")return!1;const e=i.split(".");if(e.length!==3)return!1;const t=/^[A-Za-z0-9_-]+$/;return e.every(r=>t.test(r)&&r.length>0)}function le(i){return i.replace(/<[^>]*>/g,"").substring(0,ee)}function P(i){if(!i||typeof i!="string")return!1;const e=i.trim();return e.length===0?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}function D(i){if(!i||typeof i!="string")return!1;const e=i.trim();return/^\+[1-9]\d{1,14}$/.test(e)}function ge(i){if(!i||typeof i!="string")return!1;const e=i.trim();return e.length<Z||e.length>Q?!1:/^[a-zA-Z0-9_-]+$/.test(e)}function M(i,e=6){return!i||typeof i!="string"?!1:(e===8?/^\d{8}$/:/^\d{6}$/).test(i)}function De(i){if(!i||typeof i!="string")return null;const e=i.toUpperCase().replace(/\s+/g,"");return/^[A-Z0-9-]{4,16}$/.test(e)?e:null}class pe{constructor(e,t,r,s,o,a,d,h,g,f,k,C){this.authApi=e,this.deviceService=t,this.storageManager=r,this.subscribeStore=s,this.tokenCacheService=o,this.scopes=a,this.createTenantForNewUser=d,this.origin=h,this.url=g,this.sessionCallbacks=f,this.appId=k,this.tokenExchangeConfig=C,this.tokenDeliveryManager=new te(r),C?.enabled&&this.tokenDeliveryManager.setMode(S.BFF),this.initializeSession()}async initializeSession(){(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode())&&await this.restoreSession()}async restoreSession(){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.statusUrl)try{const 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{const e=await this.authApi.validateSession();return e.valid?(this.tokenDeliveryManager.setSessionValid(),e.user&&this.subscribeStore.notify(n.SessionRestored,e.user),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return this.tokenDeliveryManager.setSessionInvalid(),!1}}async processAuthResponse(e,t){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)}async forwardTokensToBFF(e){if(!this.tokenExchangeConfig?.callbackUrl)return;const 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 new Error(`BFF token storage failed: ${t.status}`)}async signIn(e){if("email"in e&&e.email&&!P(e.email)){const s=new Error("Invalid email format"),o={message:"Invalid email format",originalError:s,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(n.Error,o),s}if("username"in e&&e.username&&!ge(e.username)){const s=new Error("Invalid username format. Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens"),o={message:"Invalid username format. Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens",originalError:s,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(n.Error,o),s}if("phone"in e&&e.phone&&!D(e.phone)){const s=new Error("Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)"),o={message:"Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)",originalError:s,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(n.Error,o),s}this.subscribeStore.notify(n.SignInStart,{email:e.email});const t=this.deviceService.getDeviceId(),r=b.web;e.scopes=e.scopes??this.scopes;try{const s=await this.authApi.signIn(e,t,r);return"requires_2fa"in s&&s.requires_2fa===!0||"tfa_token"in s&&s.tfa_token?(this.subscribeStore.notify(n.TwoFactorRequired,{email:e.email||"",challengeId:s.challenge_id||"",tfaToken:s.tfa_token||""}),s):(await this.processAuthResponse(s,e.scopes),this.subscribeStore.notify(n.SignIn,{tokens:s,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),s)}catch(s){const o={message:s instanceof Error?s.message:"Sign in failed",originalError:s,code:s instanceof u?s.id:void 0};throw this.subscribeStore.notify(n.Error,o),s}}async signUp(e){if(e.user.email&&!P(e.user.email)){const t=new Error("Invalid email format"),r={message:"Invalid email format",originalError:t,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(n.Error,r),t}if(e.user.phone_number&&!D(e.user.phone_number)){const t=new Error("Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)"),r={message:"Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)",originalError:t,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(n.Error,r),t}this.subscribeStore.notify(n.RegisterStart,{email:e.user.email}),e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{const t=await this.authApi.signUp(e);return await this.processAuthResponse(t,e.scopes),this.subscribeStore.notify(n.Register,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),t}catch(t){const r={message:t instanceof Error?t.message:"Sign up failed",originalError:t,code:t instanceof u?t.id:void 0};throw this.subscribeStore.notify(n.Error,r),t}}async passwordlessSignIn(e){if(e.email&&!P(e.email)){const s=new Error("Invalid email format"),o={message:"Invalid email format",originalError:s,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(n.Error,o),s}if(e.phone&&!D(e.phone)){const s=new Error("Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)"),o={message:"Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)",originalError:s,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(n.Error,o),s}this.subscribeStore.notify(n.SignInStart,{email:e.email}),e.scopes=e.scopes??this.scopes;const t=this.deviceService.getDeviceId(),r=b.web;try{return await this.authApi.passwordlessSignIn(e,t,r)}catch(s){const o={message:s instanceof Error?s.message:"Failed to send passwordless sign-in link",originalError:s,code:s instanceof u?s.id:void 0};throw this.subscribeStore.notify(n.Error,o),s}}async passwordlessSignInComplete(e){this.subscribeStore.notify(n.SignInStart,{}),e.scopes=e.scopes??this.scopes,e.device=this.deviceService.getDeviceId();try{const t=await this.authApi.passwordlessSignInComplete(e);return await this.processAuthResponse(t,e.scopes),this.subscribeStore.notify(n.SignIn,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),t}catch(t){const r={message:t instanceof Error?t.message:"Passwordless sign in failed",originalError:t,code:t instanceof u?t.id:void 0};throw this.subscribeStore.notify(n.Error,r),t}}async logOut(){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.logoutUrl)try{(await fetch(this.tokenExchangeConfig.logoutUrl,{method:"POST",credentials:"include"})).ok}catch{}else{const e=this.storageManager.getToken(p.refresh_token),t=this.storageManager.getDeviceId();try{if((await this.authApi.logOut(t,e,!this.appId)).status!=="ok")throw new Error("Logout failed")}catch{}}this.storageManager.deleteTokens(),this.storageManager.clearIdToken(),this.storageManager.clearCsrfToken(),this.tokenDeliveryManager.reset(),this.subscribeStore.notify(n.SignOut,{})}async refreshToken(){if(this.subscribeStore.notify(n.RefreshStart,{}),this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.refreshUrl)try{const r=await fetch(this.tokenExchangeConfig.refreshUrl,{method:"POST",credentials:"include"});if(!r.ok)throw this.tokenDeliveryManager.setSessionInvalid(),new Error("BFF token refresh failed");const s=await r.json();return this.tokenDeliveryManager.setSessionValid(),s.id_token&&this.storageManager.setIdToken(s.id_token),this.subscribeStore.notify(n.Refresh,{tokens:s,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(n.TokenCacheExpired,{isExpired:!1}),this.tokenCacheService.isRefreshing=!1,this.tokenCacheService.tokenExpiredFlag=!1,s}catch(r){this.tokenDeliveryManager.setSessionInvalid();const s={message:r instanceof Error?r.message:"Token refresh failed",originalError:r};throw this.subscribeStore.notify(n.Error,s),r}if(this.tokenDeliveryManager.isCookieMode())try{const r=await this.authApi.refreshToken("",this.scopes);return this.tokenDeliveryManager.setSessionValid(),await this.processAuthResponse(r,this.scopes),this.subscribeStore.notify(n.Refresh,{tokens:r,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(n.TokenCacheExpired,{isExpired:!1}),this.tokenCacheService.isRefreshing=!1,this.tokenCacheService.tokenExpiredFlag=!1,r}catch(r){this.tokenDeliveryManager.setSessionInvalid();const s={message:r instanceof Error?r.message:"Token refresh failed",originalError:r,code:r instanceof u?r.id:void 0};throw this.subscribeStore.notify(n.Error,s),r}const e=this.storageManager.getTokens();if(e){if(!e?.refresh_token){const r=new Error("No refresh token found"),s={message:"No refresh token found",originalError:r};throw this.subscribeStore.notify(n.Error,s),r}}else{const r=new Error("No tokens found"),s={message:"No tokens found",originalError:r};throw this.subscribeStore.notify(n.Error,s),r}const t=e?.scopes??this.scopes;try{const r=await this.authApi.refreshToken(e?.refresh_token??"",t,e?.access_token);return r.scopes=t,this.storageManager.saveTokens(r),this.tokenCacheService.setTokensCache(r),this.subscribeStore.notify(n.Refresh,{tokens:r,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(n.TokenCacheExpired,{isExpired:!1}),this.tokenCacheService.isRefreshing=!1,this.tokenCacheService.tokenExpiredFlag=!1,this.tokenCacheService.startTokenCheck(),r}catch(r){const s={message:r instanceof Error?r.message:"Token refresh failed",originalError:r,code:r instanceof u?r.id:void 0,details:U.isAxiosError(r)&&r.response?{status:r.response.status,data:r.response.data}:void 0};this.subscribeStore.notify(n.Error,s);const o=U.isAxiosError(r)&&r.response?.status&&r.response.status>=400&&r.response.status<500;throw o&&(this.tokenCacheService.tokenExpiredFlag=!0,this.tokenCacheService.setTokensCache(void 0),this.storageManager.deleteTokens(),this.subscribeStore.notify(n.SessionExpired,{reason:"refresh_failed"})),r instanceof u?r:o?new Error(`Getting unknown error message from server with code:${r.response?.status}`):r}}async sendPasswordResetEmail(e){try{return await this.authApi.sendPasswordResetEmail(e)}catch(t){const r={message:t instanceof Error?t.message:"Failed to send password reset email",originalError:t,code:t instanceof u?t.id:void 0};throw this.subscribeStore.notify(n.Error,r),t}}async resetPassword(e,t){this.subscribeStore.notify(n.SignInStart,{});const s=new URLSearchParams(window.location.search).get("token")??void 0,o=t??this.scopes;try{const a=await this.authApi.resetPassword(e,o,s);return await this.processAuthResponse(a,o),this.subscribeStore.notify(n.SignIn,{tokens:a,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),a}catch(a){const d={message:a instanceof Error?a.message:"Password reset failed",originalError:a,code:a instanceof u?a.id:void 0};throw this.subscribeStore.notify(n.Error,d),a}}async passkeyRegister(e){this.subscribeStore.notify(n.RegisterStart,{});const t=this.deviceService.getDeviceId(),r=b.web;e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{const{challenge_id:s,publicKey:o}=await this.authApi.passkeyRegisterStart(e,t,r,!this.appId);o.user.id=btoa(o.user.id);const a=await O.startRegistration({optionsJSON:o}),d=await this.authApi.passkeyRegisterComplete(a,t,s,!this.appId);return await this.processAuthResponse(d,e.scopes),this.subscribeStore.notify(n.Register,{tokens:d,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),d}catch(s){const o={message:s instanceof Error?s.message:"Passkey registration failed",originalError:s,code:s instanceof u?s.id:void 0};throw this.subscribeStore.notify(n.Error,o),s}}async passkeyAuthenticate(e){this.subscribeStore.notify(n.SignInStart,{});const t=this.deviceService.getDeviceId(),r=b.web;e.scopes=e.scopes??this.scopes;try{const{challenge_id:s,publicKey:o}=await this.authApi.passkeyAuthenticateStart(e,t,r,!this.appId),a=await O.startAuthentication({optionsJSON:o}),d=await this.authApi.passkeyAuthenticateComplete(a,t,s,!this.appId);return"access_token"in d&&(await this.processAuthResponse(d,e.scopes),this.subscribeStore.notify(n.SignIn,{tokens:d,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),d}catch(s){const o={message:s instanceof Error?s.message:"Passkey authentication failed",originalError:s,code:s instanceof u?s.id:void 0};throw this.subscribeStore.notify(n.Error,o),s}}createFederatedAuthUrl(e){const t=`/auth/federated/start/${e.provider}`;if(!this.appId)throw new Error("AppId is required for federated auth");const s={scopes:(e.scopes??this.scopes).join(" "),redirect_url:e.redirect_url??this.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}:{}},o=new URL(t,this.url),a=new URLSearchParams(s);return o.search=a.toString(),o.toString()}federatedAuthWithPopup(e){this.subscribeStore.notify(n.SignInStart,{provider:e.provider});const t=e.scopes??this.scopes,r=this.deviceService.getDeviceId(),s=this.createFederatedAuthUrl({...e,scopes:t,device:r}),o=window.open(s,"_blank",`width=${X},height=${z}`);if(!o){this.federatedAuthWithRedirect(e);return}const a=Date.now(),d=setInterval(()=>{if(o.closed){clearInterval(d);const h={message:"Authentication popup was closed",code:"POPUP_CLOSED"};this.subscribeStore.notify(n.Error,h);return}if(Date.now()-a>J){clearInterval(d),o.close();const h={message:"Authentication popup timed out",code:"POPUP_TIMEOUT"};this.subscribeStore.notify(n.Error,h);return}try{if(o.location.href.startsWith(this.origin)){const h=new URLSearchParams(o.location.search),g=h.get("access_token")||"",f=h.get("refresh_token")||"",k=h.get("id_token")||"",C={access_token:g,refresh_token:f||void 0,id_token:k||void 0,scopes:t};this.processAuthResponse(C,t).then(()=>{this.subscribeStore.notify(n.SignIn,{tokens:C,parsedTokens:this.tokenCacheService.getParsedTokens()}),window.location.href=`${this.origin}`}),clearInterval(d),o.close()}}catch{}},W)}federatedAuthWithRedirect(e){this.subscribeStore.notify(n.SignInStart,{provider:e.provider});const t=e.scopes??this.scopes,r=this.deviceService.getDeviceId(),s=this.createFederatedAuthUrl({...e,scopes:t,device:r});window.location.href=s}authRedirectUrl(e={}){try{const{url:t,redirectUrl:r,scopes:s,appId:o}=e??{},a=new URL(t??this.url);a.pathname=(a.pathname.endsWith("/")?a.pathname:a.pathname+"/")+"web";const d=s??this.scopes,h={appId:o??this.appId??"",redirectto:r??window.location.href,scopes:d.join(",")},g=new URLSearchParams(h);return a.search=g.toString(),a.toString()}catch(t){const r={message:t instanceof Error?t.message:"Failed to create auth redirect URL",originalError:t};throw this.subscribeStore.notify(n.Error,r),t}}authRedirect(e={}){try{window.location.href=this.authRedirectUrl(e)}catch(t){const r={message:t instanceof Error?t.message:"Failed to redirect to auth page",originalError:t};throw this.subscribeStore.notify(n.Error,r),t}}isAuthenticated(e){try{if(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode()){const t=!!e?.id_token||!!this.storageManager.getIdToken(),r=this.tokenDeliveryManager.isSessionValid(),s=this.tokenDeliveryManager.isSessionUnknown();return t&&(r||s)}return!e||!e.access_token?!1:!m(e.access_token)||e.refresh_token!==void 0&&!m(e.refresh_token)}catch(t){const r={message:t instanceof Error?t.message:"Failed to check authentication status",originalError:t};return this.subscribeStore.notify(n.Error,r),!1}}async submitSessionCheck(e=!1){let t,r;try{t=await this.getTokens(e),r=this.tokenCacheService.getParsedTokens()}catch(s){const o={message:s instanceof Error||s instanceof u?s.message:"Session check failed",originalError:s};this.subscribeStore.notify(n.Error,o),t=void 0}return t&&this.sessionCallbacks.createSession&&await this.sessionCallbacks.createSession({tokens:t,parsedTokens:r}),!t&&this.sessionCallbacks.expiredSession&&await this.sessionCallbacks.expiredSession(),t}async getTokens(e){try{if(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode()){const s=this.storageManager.getTokens();return s?.id_token?this.tokenDeliveryManager.isSessionInvalid()&&e?await this.refreshToken():s:void 0}const t=this.storageManager.getTokens();if(!t||!t.access_token)return;const r=v(t.access_token);return m(r)?e?await this.refreshToken():void 0:t}catch(t){const r={message:t instanceof Error?t.message:"Failed to get tokens",originalError:t};this.subscribeStore.notify(n.Error,r);return}}}class fe{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)}}class xe{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 Ue(){return new xe}class ke{constructor(e){this.data=this.normalize(e)}normalize(e){const t=new Map,r=new Map,s=new Map,o=[];return e.groups?.forEach(a=>{r.set(a.id,{id:a.id,name:a.name,default:a.default??!1,updated_at:a.updated_at,created_at:a.created_at})}),e.roles?.forEach(a=>{s.set(a.id,{id:a.id,tenant_id:a.tenant_id,name:a.name})}),e.users_in_groups?.forEach(a=>{const d=a.user;d&&!t.has(d.id)&&t.set(d.id,{id:d.id,name:d.name??null,email:d.email??null,phone:d.phone??null}),d&&a.group_id&&r.has(a.group_id)&&o.push({userId:d.id,groupId:a.group_id,roleIds:a.roles?.map(h=>h.id)??[]})}),{tenant_id:e.tenant_id,tenant_name:e.tenant_name,users:Array.from(t.values()),groups:Array.from(r.values()),roles:Array.from(s.values()),memberships:o,usersById:t,groupsById:r,rolesById:s}}getUsersInGroup(e){return this.data.memberships.filter(t=>t.groupId===e).map(t=>this.data.usersById.get(t.userId)).filter(t=>t!==void 0)}getGroupsForUser(e){return this.data.memberships.filter(t=>t.userId===e).map(t=>this.data.groupsById.get(t.groupId)).filter(t=>t!==void 0)}getUserRolesInGroup(e,t){const r=this.data.memberships.find(s=>s.userId===e&&s.groupId===t);return r?r.roleIds.map(s=>this.data.rolesById.get(s)).filter(s=>s!==void 0):[]}getData(){return this.data}}class ve{constructor(e,t,r){this.tenantApi=e,this.scopes=t,this.logger=r||Ue()}handlePassflowError(e,t){if(U.isAxiosError(e)&&e.response?.data){const r=e.response.data;if(typeof r=="object"&&r!==null&&"error"in r&&typeof r.error=="object"&&r.error!==null){const s=r.error;throw this.logger.error(`${t}: ${s.id} - ${s.message} (Status: ${s.status})`),new Error(`Passflow API Error: ${s.id} - ${s.message} (Status: ${s.status})`)}}throw this.logger.error(`${t}:`,e),e instanceof Error?e:new Error(String(e))}async joinInvitation(e,t){try{const r=t??this.scopes;return await this.tenantApi.joinInvitation(e,r)}catch(r){this.handlePassflowError(r,"Join invitation failed")}}async createTenant(e){try{return await this.tenantApi.createTenant(e)}catch(t){this.handlePassflowError(t,"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{const t=await this.tenantApi.getTenantDetails(e);return new ke(t)}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(r){this.handlePassflowError(r,`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(r){this.handlePassflowError(r,`Group creation failed for tenant ID ${e}`)}}async getGroupInfo(e,t){try{return await this.tenantApi.getGroupInfo(e,t)}catch(r){this.handlePassflowError(r,`Get group info failed for tenant ID ${e}, group ID ${t}`)}}async updateGroup(e,t,r){try{return await this.tenantApi.updateGroup(e,t,r)}catch(s){this.handlePassflowError(s,`Update group failed for tenant ID ${e}, group ID ${t}`)}}async deleteGroup(e,t){try{return await this.tenantApi.deleteGroup(e,t)}catch(r){this.handlePassflowError(r,`Delete group failed for tenant ID ${e}, group ID ${t}`)}}async addUserToGroup(e,t,r,s){try{return await this.tenantApi.addUserToGroup(e,t,r,s)}catch(o){this.handlePassflowError(o,`Add user to group failed for tenant ID ${e}, group ID ${t}, user ID ${r}`)}}async removeUserRolesFromGroup(e,t,r,s){try{return await this.tenantApi.removeUserRolesFromGroup(e,t,r,s)}catch(o){this.handlePassflowError(o,`Remove user roles from group failed for tenant ID ${e}, group ID ${t}, user ID ${r}`)}}async changeUserRoles(e,t,r,s){try{return await this.tenantApi.changeUserRoles(e,t,r,s)}catch(o){this.handlePassflowError(o,`Change user roles failed for tenant ID ${e}, group ID ${t}, user ID ${r}`)}}async deleteUserFromGroup(e,t,r){try{return await this.tenantApi.deleteUserFromGroup(e,t,r)}catch(s){this.handlePassflowError(s,`Delete user from group failed for tenant ID ${e}, group ID ${t}, user ID ${r}`)}}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(r){this.handlePassflowError(r,`Create role for tenant failed for tenant ID ${e}`)}}async updateRole(e,t,r){try{return await this.tenantApi.updateRole(e,t,r)}catch(s){this.handlePassflowError(s,`Update role failed for tenant ID ${e}, role ID ${t}`)}}async deleteRole(e,t){try{return await this.tenantApi.deleteRole(e,t)}catch(r){this.handlePassflowError(r,`Delete role failed for tenant ID ${e}, role ID ${t}`)}}async deleteUserFromTenant(e,t){try{return await this.tenantApi.deleteUserFromTenant(e,t)}catch(r){this.handlePassflowError(r,`Delete user from tenant failed for tenant ID ${e}, user ID ${t}`)}}async getGroupInvitations(e,t,r,s){try{return await this.tenantApi.getGroupInvitations(e,t,r,s)}catch(o){this.handlePassflowError(o,`Get group invitations failed for tenant ID ${e}, group ID ${t}`)}}async getTenantInvitations(e,t,r){try{return await this.tenantApi.getTenantInvitations(e,t,r)}catch(s){this.handlePassflowError(s,`Get tenant invitations failed for tenant ID ${e}`)}}async invalidateInviteById(e,t,r){try{return await this.tenantApi.invalidateInviteById(e,t,r)}catch(s){this.handlePassflowError(s,`Invalidate invite by ID failed for tenant ID ${e}, group ID ${t}, invite ID ${r}`)}}async invalidateInviteByEmail(e,t,r){try{return await this.tenantApi.invalidateInviteByEmail(e,t,r)}catch(s){this.handlePassflowError(s,`Invalidate invite by email failed for tenant ID ${e}, group ID ${t}, email ${r}`)}}}class ye{constructor(e,t,r){this.storageManager=e,this.authApi=t,this.subscribeStore=r,this.checkInterval=null,this.CHECK_INTERVAL=6e4,this.visibilityChangeHandler=null,this.isRefreshing=!1,this.tokenExpiredFlag=!1,this.storageManager=e,this.authApi=t,this.setupPageUnloadHandler()}initialize(){try{const e=this.storageManager.getTokens();if(!e){this.startTokenCheck();return}if(!e.access_token){this.setTokensCache(e),this.startTokenCheck();return}const t=v(e.access_token);m(t)?(this.tokenExpiredFlag=!0,this.stopTokenCheck(),this.subscribeStore.notify(n.TokenCacheExpired,{isExpired:!0})):(this.setTokensCache(e),this.startTokenCheck())}catch(e){const t={message:e instanceof Error?e.message:"Failed to get tokens",originalError:e};this.subscribeStore.notify(n.Error,t),this.setTokensCache(void 0)}}async refreshTokensCache(e){if(!this.isRefreshing)try{this.isRefreshing=!0,this.subscribeStore.notify(n.RefreshStart,{});const t=await this.authApi.refreshToken(e?.refresh_token??"",e.scopes??[],e.access_token);this.setTokensCache(t),this.subscribeStore.notify(n.Refresh,{tokens:t,parsedTokens:this.getParsedTokens()}),this.subscribeStore.notify(n.TokenCacheExpired,{isExpired:!1}),this.tokenExpiredFlag=!1,this.startTokenCheck()}catch(t){const r={message:t instanceof Error?t.message:"Failed to get tokens",originalError:t};this.subscribeStore.notify(n.Error,r),this.tokenExpiredFlag=!0,this.setTokensCache(void 0),this.stopTokenCheck(),this.storageManager.deleteTokens(),this.subscribeStore.notify(n.SessionExpired,{reason:"refresh_failed"})}finally{this.isRefreshing=!1}}startTokenCheck(){this.checkInterval&&clearInterval(this.checkInterval),!this.tokenExpiredFlag&&(this.setupVisibilityListener(),this.checkInterval=setInterval(()=>{typeof document<"u"&&document.hidden||this.isRefreshing||this.tokenExpiredFlag||this.isExpired()&&!this.tokenExpiredFlag&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(n.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck())},this.CHECK_INTERVAL))}setupVisibilityListener(){typeof document>"u"||(this.visibilityChangeHandler&&document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=()=>{!document.hidden&&this.checkInterval&&!this.isRefreshing&&!this.tokenExpiredFlag&&this.isExpired()&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(n.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck())},document.addEventListener("visibilitychange",this.visibilityChangeHandler))}setupPageUnloadHandler(){typeof window>"u"||window.addEventListener("beforeunload",()=>{this.destroy()})}stopTokenCheck(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null),this.visibilityChangeHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=null)}destroy(){this.stopTokenCheck()}setTokensCache(e){this.tokensCache=e,e?this.parsedTokensCache={access_token:e.access_token?v(e.access_token):void 0,id_token:e.id_token?v(e.id_token):void 0,refresh_token:e.refresh_token?v(e.refresh_token):void 0,scopes:e.scopes}:this.parsedTokensCache=void 0}getTokens(){return this.tokensCache}async getTokensWithRefresh(){try{if(!this.tokensCache)return this.tokensCache;if(!this.tokensCache.access_token)return this.tokensCache;const e=v(this.tokensCache.access_token);return m(e)&&!this.tokenExpiredFlag?(await this.refreshTokensCache(this.tokensCache),this.tokensCache):this.tokensCache}catch(e){const t={message:e instanceof Error?e.message:"Failed to get tokens",originalError:e};this.subscribeStore.notify(n.Error,t);return}}getParsedTokens(){return this.parsedTokensCache}isExpired(){if(!this.tokensCache)return!0;if(!this.tokensCache.access_token)return!1;const e=v(this.tokensCache.access_token);return m(e)}}class Se{constructor(e,t){this.twoFactorApi=e,this.subscribeStore=t,this.PARTIAL_AUTH_TIMEOUT_MS=300*1e3,this.SESSION_STORAGE_KEY="passflow_2fa_challenge",this.totpDigits=6;const r={onAuthChange:(s,o)=>{if(s===n.TwoFactorRequired){const a=o;this.setPartialAuthState(a.email,a.challengeId,a.tfaToken)}}};this.subscribeStore.subscribe(r,[n.TwoFactorRequired])}emitErrorAndThrow(e,t){const r=e,s={message:e instanceof Error?e.message:`${t} failed`,originalError:e,code:r?.id||void 0};throw this.subscribeStore.notify(n.Error,s),e}async getStatus(){try{const e=await this.twoFactorApi.getStatus();return e.totp_digits&&(this.totpDigits=e.totp_digits),e}catch(e){this.emitErrorAndThrow(e,"Get 2FA status")}}async beginSetup(){try{const e=await this.twoFactorApi.beginSetup();return e.totp_digits&&(this.totpDigits=e.totp_digits),this.subscribeStore.notify(n.TwoFactorSetupStarted,{secret:e.secret}),e}catch(e){this.emitErrorAndThrow(e,"Begin 2FA setup")}}async confirmSetup(e){if(!M(e,this.totpDigits))throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{const t=await this.twoFactorApi.confirmSetup({code:e});return this.subscribeStore.notify(n.TwoFactorEnabled,{recoveryCodes:t.recovery_codes,clearRecoveryCodes:()=>{t.recovery_codes.length=0}}),t}catch(t){this.emitErrorAndThrow(t,"Confirm 2FA setup")}}async verify(e){if(!M(e,this.totpDigits))throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);if(this.recoverPartialAuthState(),!this.isVerificationRequired())throw new Error("2FA verification expired or not required. User must sign in first.");if(!this.partialAuthState?.tfaToken)throw new Error("No TFA token found. User must sign in first.");try{const t=await this.twoFactorApi.verify({code:e,tfa_token:this.partialAuthState.tfaToken});return this.clearPartialAuthState(),this.subscribeStore.notify(n.TwoFactorVerified,{tokens:t}),t}catch(t){this.emitErrorAndThrow(t,"Verify 2FA code")}}async useRecoveryCode(e){try{const t=De(e);if(!t)throw new Error("Invalid recovery code format. Expected format: XXXX-XXXX or XXXXXXXX (alphanumeric).");if(this.recoverPartialAuthState(),!this.isVerificationRequired())throw new Error("2FA verification expired or not required. User must sign in first.");if(!this.partialAuthState?.tfaToken)throw new Error("No TFA token found. User must sign in first.");const r=await this.twoFactorApi.useRecoveryCode({recovery_code:t,tfa_token:this.partialAuthState.tfaToken});return this.clearPartialAuthState(),r.remaining_recovery_codes===0?this.subscribeStore.notify(n.TwoFactorRecoveryCodesExhausted,{tokens:r}):r.remaining_recovery_codes<=2&&this.subscribeStore.notify(n.TwoFactorRecoveryCodesLow,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(n.TwoFactorRecoveryUsed,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(n.TwoFactorVerified,{tokens:r}),r}catch(t){this.emitErrorAndThrow(t,"Use recovery code")}}async disable(e){if(!M(e,this.totpDigits))throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{const t=await this.twoFactorApi.disable({code:e});return this.subscribeStore.notify(n.TwoFactorDisabled,{}),t}catch(t){this.emitErrorAndThrow(t,"Disable 2FA")}}async regenerateRecoveryCodes(e){if(!M(e,this.totpDigits))throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{const t=await this.twoFactorApi.regenerateRecoveryCodes({code:e}),r=[...t.recovery_codes];return t.recovery_codes=[],t.recovery_codes=r,t}catch(t){this.emitErrorAndThrow(t,"Regenerate recovery codes")}}isVerificationRequired(){return this.recoverPartialAuthState(),this.partialAuthState?Date.now()>this.partialAuthState.expiresAt?(this.clearPartialAuthState(),!1):!0:!1}setPartialAuthState(e,t,r){if(this.partialAuthState={email:e,challengeId:t,tfaToken:r,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,typeof sessionStorage<"u")try{sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{}}recoverPartialAuthState(){if(!this.partialAuthState&&!(typeof sessionStorage>"u"))try{const e=sessionStorage.getItem(this.SESSION_STORAGE_KEY);if(!e)return;const 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){const 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(n.TwoFactorSetupMagicLinkValidated,{userId:t.userId,appId:t.appId,expiresIn:t.expiresIn||3600,sessionToken:t.sessionToken})):t.error&&this.subscribeStore.notify(n.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,"Get available 2FA methods")}}async getRegisteredMethods(){try{return await this.twoFactorApi.getRegisteredMethods()}catch(e){this.emitErrorAndThrow(e,"Get registered 2FA methods")}}async beginMethodSetup(e){try{const t=await this.twoFactorApi.beginMethodSetup(e);return this.subscribeStore.notify(n.TwoFactorSetupStarted,{secret:"",method:e}),t}catch(t){this.emitErrorAndThrow(t,"Begin 2FA method setup")}}async confirmMethodSetup(e,t){try{const r=await this.twoFactorApi.confirmMethodSetup(e,t);return this.subscribeStore.notify(n.TwoFactorEnabled,{recoveryCodes:[],clearRecoveryCodes:()=>{}}),r}catch(r){this.emitErrorAndThrow(r,"Confirm 2FA method setup")}}async removeMethod(e){try{await this.twoFactorApi.removeMethod(e)}catch(t){this.emitErrorAndThrow(t,"Remove 2FA method")}}async requestChallenge(e){try{const t=await this.twoFactorApi.requestChallenge(e);return this.subscribeStore.notify(n.TwoFactorChallengeReceived,{challengeId:t.challenge_id,method:t.method,alternativeMethods:t.alternative_methods}),t}catch(t){this.emitErrorAndThrow(t,"Request 2FA challenge")}}async verifyV2(e){try{const t=await this.twoFactorApi.verifyV2(e);return t.success&&(this.subscribeStore.notify(n.TwoFactorVerified,{tokens:{access_token:t.access_token,refresh_token:t.refresh_token}}),t.device_trusted&&this.subscribeStore.notify(n.TwoFactorDeviceTrusted,{})),t}catch(t){this.emitErrorAndThrow(t,"Verify 2FA challenge")}}async switchToAlternative(e){try{const t=await this.twoFactorApi.switchToAlternative(e);return this.subscribeStore.notify(n.TwoFactorMethodSwitched,{challengeId:t.challenge_id,method:t.method,alternativeMethods:t.alternative_methods}),t}catch(t){this.emitErrorAndThrow(t,"Switch to alternative 2FA method")}}async getTrustedDevices(){try{return await this.twoFactorApi.getTrustedDevices()}catch(e){this.emitErrorAndThrow(e,"Get trusted devices")}}async revokeTrustedDevice(e){try{await this.twoFactorApi.revokeTrustedDevice(e)}catch(t){this.emitErrorAndThrow(t,"Revoke trusted device")}}}class me{constructor(e,t){this.userAPI=e,this.deviceService=t}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:r}={}){const s=this.deviceService.getDeviceId(),o=b.web,{challenge_id:a,publicKey:d}=await this.userAPI.addUserPasskeyStart({relyingPartyId:e||window?.location?.hostname,deviceId:s,os:o,passkeyDisplayName:r,passkeyUsername:t});d.user.id=btoa(d.user.id);const h=await O.startRegistration({optionsJSON:d});return await this.userAPI.addUserPasskeyComplete(h,s,a)}}const q=class q{constructor(e){this.doRefreshTokens=!1,this.origin=window.location.origin,this.session=async({createSession:o,expiredSession:a,doRefresh:d=!1})=>{this.createSessionCallback=o,this.expiredSessionCallback=a,this.doRefreshTokens=d,await this.submitSessionCheck()};const{url:t,appId:r,scopes:s}=e;this.url=t||N,this.appId=r,this.storageManager=new G({prefix:e.keyStoragePrefix??""}),this.deviceService=new re(this.storageManager),this.authApi=new ne(e,this.storageManager,this.deviceService),this.appApi=new oe(e,this.storageManager,this.deviceService),this.userApi=new ue(e,this.storageManager,this.deviceService),this.settingApi=new ce(e,this.storageManager,this.deviceService),this.tenantApi=new he(e,this.storageManager,this.deviceService),this.invitationApi=new ae(e,this.storageManager,this.deviceService),this.twoFactorApi=new de(e,this.storageManager,this.deviceService),this.subscribeStore=new Pe,this.tokenCacheService=new ye(this.storageManager,this.authApi,this.subscribeStore),this.scopes=s??j,this.createTenantForNewUser=e.createTenantForNewUser??!1,this.authService=new pe(this.authApi,this.deviceService,this.storageManager,this.subscribeStore,this.tokenCacheService,this.scopes,this.createTenantForNewUser,this.origin,this.url,{createSession:this.createSessionCallback,expiredSession:this.expiredSessionCallback},this.appId??"",e.tokenExchange),this.userService=new me(this.userApi,this.deviceService),this.tenantService=new ve(this.tenantApi,this.scopes),this.tenant=this.tenantService,this.invitationService=new fe(this.invitationApi),this.twoFactorService=new Se(this.twoFactorApi,this.subscribeStore),this.twoFactor=this.twoFactorService,e.parseQueryParams&&this.checkAndSetTokens(),this.setTokensToCacheFromLocalStorage()}setAppId(e){this.appId=e,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.authService}async submitSessionCheck(){let e,t;try{e=await this.authService.getTokens(this.doRefreshTokens),t=this.tokenCacheService.getParsedTokens()}catch(r){const s={message:r instanceof Error||r instanceof u?r.message:"Session check failed",originalError:r};this.subscribeStore.notify(n.Error,s),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(){return this.checkAndSetTokens()}checkAndSetTokens(){let e=new URLSearchParams(window.location.search),t=!1;if(!e.get("access_token")&&window.location.hash){const h=new URLSearchParams(window.location.hash.substring(1));h.get("access_token")&&(e=h,t=!0)}const r=e.get("access_token"),s=e.get("refresh_token"),o=e.get("id_token"),a=e.get("scopes")?.split(",")??this.scopes;let d;if(r){if(!F(r)){const h={message:"Invalid access token format received",code:"INVALID_TOKEN_FORMAT"};this.subscribeStore.notify(n.Error,h),this.cleanupUrlParams(t);return}if(s&&!F(s)){const h={message:"Invalid refresh token format received",code:"INVALID_TOKEN_FORMAT"};this.subscribeStore.notify(n.Error,h),this.cleanupUrlParams(t);return}if(o&&!F(o)){const h={message:"Invalid ID token format received",code:"INVALID_TOKEN_FORMAT"};this.subscribeStore.notify(n.Error,h),this.cleanupUrlParams(t);return}return d={access_token:r,refresh_token:s??void 0,id_token:o??void 0,scopes:a},this.storageManager.clearDeliveryMode(),this.storageManager.saveTokens(d),this.tokenCacheService.setTokensCache(d),this.subscribeStore.notify(n.SignIn,{tokens:d,parsedTokens:this.getParsedTokens()}),this.submitSessionCheck(),this.cleanupUrlParams(t),this.error=void 0,d}else this.error=this.checkErrorsFromURL()}checkErrorsFromURL(){const t=new URLSearchParams(window.location.search).get("error");if(t){const r=le(t);return new Error(r)}}cleanupUrlParams(e=!1){if(e)window.history.replaceState({},document.title,window.location.pathname+window.location.search);else{const t=new URLSearchParams(window.location.search);t.delete("access_token"),t.delete("refresh_token"),t.delete("id_token"),t.delete("client_challenge"),t.size>0?window.history.replaceState({},document.title,`${window.location.pathname}?${t.toString()}`):window.history.replaceState({},document.title,window.location.pathname)}}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(){const e=this.storageManager.getTokens();if(!e||!e.access_token)return!1;const t=this.tokenCacheService.getParsedTokens();return t?this.authService.isAuthenticated(t):!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)}handleError(e,t){const r={message:e instanceof Error?e.message:`${t} failed`,originalError:e,code:e instanceof u?e.id:void 0};throw this.subscribeStore.notify(n.Error,r),e}async logOut(){try{await this.authService.logOut(),this.storageManager.deleteTokens(),this.tokenCacheService.setTokensCache(void 0),this.twoFactorService.clearPartialAuthState(),await this.submitSessionCheck(),this.subscribeStore.notify(n.SignOut,{})}catch(e){this.handleError(e,"Log out")}}federatedAuthWithPopup(e){this.authService.federatedAuthWithPopup(e)}federatedAuthWithRedirect(e){this.authService.federatedAuthWithRedirect(e)}reset(e){if(this.storageManager.deleteTokens(),this.tokenCacheService.setTokensCache(void 0),this.subscribeStore.notify(n.SignOut,{}),e){this.error=new Error(e);const t={message:e,code:"RESET_ERROR"};throw this.subscribeStore.notify(n.Error,t),this.error}}async refreshToken(){if(!this.tokenCacheService.parsedTokensCache?.refresh_token)throw new Error("No refresh token found");try{return await this.authService.refreshToken()}catch(e){throw e instanceof u||this.subscribeStore.notify(n.Error,{message:"Failed to refresh token",originalError:e}),e}}sendPasswordResetEmail(e){return this.authService.sendPasswordResetEmail(e)}async resetPassword(e,t){return await this.authService.resetPassword(e,t)}async getAppSettings(){try{return await this.appApi.getAppSettings()}catch(e){this.handleError(e,"Get app settings")}}async getSettingsAll(){try{return await this.settingApi.getSettingsAll()}catch(e){this.handleError(e,"Get all settings")}}async getPasswordPolicySettings(){try{return await this.settingApi.getPasswordPolicySettings()}catch(e){this.handleError(e,"Get password policy settings")}}async getPasskeySettings(){try{return await this.settingApi.getPasskeySettings()}catch(e){this.handleError(e,"Get passkey settings")}}async passkeyRegister(e){return await this.authService.passkeyRegister(e)}async passkeyAuthenticate(e){return await this.authService.passkeyAuthenticate(e)}setTokens(e){this.storageManager.saveTokens(e),this.tokenCacheService.setTokensCache(e),this.subscribeStore.notify(n.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,"Get user passkeys")}}async renameUserPasskey(e,t){try{return await this.userService.renameUserPasskey(e,t)}catch(r){this.handleError(r,"Rename user passkey")}}async deleteUserPasskey(e){try{return await this.userService.deleteUserPasskey(e)}catch(t){this.handleError(t,"Delete user passkey")}}async addUserPasskey(e){try{return await this.userService.addUserPasskey(e)}catch(t){this.handleError(t,"Add user passkey")}}async joinInvitation(e,t){try{const r=await this.tenant.joinInvitation(e,t);return r.scopes=t??this.scopes,this.storageManager.saveTokens(r),this.tokenCacheService.setTokensCache(r),r}catch(r){this.handleError(r,"Join invitation")}}async createTenant(e,t){try{const r=await this.tenant.createTenant(e);return t&&await this.refreshToken(),r}catch(r){this.handleError(r,"Create tenant")}}async requestInviteLink(e){try{return e.send_to_email===void 0&&(e.send_to_email=!0),await this.invitationService.requestInviteLink(e)}catch(t){this.handleError(t,"Request invite link")}}async getInvitations(e){try{return await this.invitationService.getInvitations(e)}catch(t){this.handleError(t,"Get invitations")}}async deleteInvitation(e){try{return await this.invitationService.deleteInvitation(e)}catch(t){this.handleError(t,"Delete invitation")}}async resendInvitation(e){try{return await this.invitationService.resendInvitation(e)}catch(t){this.handleError(t,"Resend invitation")}}async getInvitationLink(e){try{return await this.invitationService.getInvitationLink(e)}catch(t){this.handleError(t,"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,"Get 2FA status")}}async beginTwoFactorSetup(){try{return await this.twoFactorService.beginSetup()}catch(e){this.handleError(e,"Begin 2FA setup")}}async confirmTwoFactorSetup(e){try{return await this.twoFactorService.confirmSetup(e)}catch(t){this.handleError(t,"Confirm 2FA setup")}}async verifyTwoFactor(e){try{const t=await this.twoFactorService.verify(e);return this.storageManager.saveTokens(t),this.tokenCacheService.setTokensCache(t),this.subscribeStore.notify(n.SignIn,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),t}catch(t){this.handleError(t,"Verify 2FA")}}async useTwoFactorRecoveryCode(e){try{const t=await this.twoFactorService.useRecoveryCode(e);return this.storageManager.saveTokens(t),this.tokenCacheService.setTokensCache(t),this.subscribeStore.notify(n.SignIn,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),t}catch(t){this.handleError(t,"Use 2FA recovery code")}}async disableTwoFactor(e){try{return await this.twoFactorService.disable(e)}catch(t){this.handleError(t,"Disable 2FA")}}async regenerateTwoFactorRecoveryCodes(e){try{return await this.twoFactorService.regenerateRecoveryCodes(e)}catch(t){this.handleError(t,"Regenerate 2FA recovery codes")}}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()}};q.version=B;let $=q;class l extends Error{constructor(e){super(e.message),this.name="M2MError",this.code=e.code,this.status=e.status??400,this.errorUri=e.errorUri,this.rateLimitInfo=e.rateLimitInfo,this.headers=e.headers,this.cause=e.cause,this.timestamp=new Date().toISOString(),Error.captureStackTrace&&Error.captureStackTrace(this,l)}static fromOAuthError(e,t,r){const s=r?l.parseRateLimitHeaders(r):void 0;return new l({code:e.error,message:e.error_description??l.getDefaultMessage(e.error),status:t,errorUri:e.error_uri,rateLimitInfo:s,headers:r})}static fromError(e,t="server_error"){return new l({code:t,message:e.message||"An unexpected error occurred",status:500,cause:e})}static parseRateLimitHeaders(e){const t=e["x-ratelimit-limit"],r=e["x-ratelimit-remaining"],s=e["x-ratelimit-reset"]||e["retry-after"];if(t&&r&&s)return{limit:parseInt(t,10),remaining:parseInt(r,10),reset:parseInt(s,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){const 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}}class L extends l{constructor(e,t){super({code:"temporarily_unavailable",message:e,status:0,cause:t}),this.name="M2MNetworkError"}}class R extends l{constructor(e,t){super({code:"invalid_request",message:e,status:400,cause:t}),this.name="M2MTokenParseError"}}class x extends l{constructor(e){super({code:"invalid_request",message:e,status:400}),this.name="M2MConfigError"}}const Oe={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"},w={TOKEN_ENDPOINT:"/oauth2/token",TIMEOUT:1e4,RETRIES:3,RETRY_DELAY:1e3,REFRESH_THRESHOLD:30,CONTENT_TYPE:"application/x-www-form-urlencoded"};class $e{constructor(){this.cache=new Map}get(e){const 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,r){return this.cache.set(e,{token:t,expiresAt:Date.now()+r*1e3}),Promise.resolve()}delete(e){return this.cache.delete(e),Promise.resolve()}}const Le={shouldRetry(i,e){return e>=3?!1:i.code==="server_error"||i.code==="temporarily_unavailable"||i.code==="rate_limit_exceeded"||i.status!==void 0&&i.status>=500},getDelay(i){return Math.pow(2,i-1)*1e3}};class Ne{constructor(e){if(!e.url)throw new x("M2M client requires a URL");if(!e.clientId)throw new x("M2M client requires a clientId");if(!e.clientSecret)throw new x("M2M client requires a clientSecret");const 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??w.REFRESH_THRESHOLD,timeout:e.timeout??w.TIMEOUT,retries:e.retries??w.RETRIES,retryDelay:e.retryDelay??w.RETRY_DELAY,retryStrategy:e.retryStrategy,cache:e.cache,onTokenRequest:e.onTokenRequest,onTokenResponse:e.onTokenResponse,onError:e.onError},this.cache=e.cache??new $e,this.retryStrategy=e.retryStrategy??Le,this.tokenEndpoint=`${t}${w.TOKEN_ENDPOINT}`}getCacheKey(e,t){const r=e?.sort().join(",")||"",s=t?.sort().join(",")||"";return`m2m:${this.config.clientId}:${r}:${s}`}async getToken(e){const t=e?.scopes??this.config.scopes,r=e?.audience??this.config.audience,s=this.getCacheKey(t,r);if(!e?.forceRefresh){const o=await this.cache.get(s);if(o&&!this.isTokenExpired(o))return o}return this.requestToken(t,r,s)}async getValidToken(){const e=this.config.scopes,t=this.config.audience,r=this.getCacheKey(e,t),s=await this.cache.get(r);if(s){if(this.config.autoRefresh&&this.isTokenExpired(s,this.config.refreshThreshold))return this.requestToken(e,t,r);if(!this.isTokenExpired(s))return s}return this.requestToken(e,t,r)}async requestToken(e,t,r){const s={grant_type:"client_credentials",client_id:this.config.clientId,client_secret:this.config.clientSecret};e&&e.length>0&&(s.scope=e.join(" ")),t&&t.length>0&&(s.audience=t.join(" ")),this.config.onTokenRequest&&this.config.onTokenRequest({clientId:this.config.clientId,scopes:e??[],audience:t??[],timestamp:new Date().toISOString()});const o=await this.executeWithRetry(()=>this.doTokenRequest(s));return o.issued_at=Math.floor(Date.now()/1e3),r&&await this.cache.set(r,o,o.expires_in),this.config.onTokenResponse&&this.config.onTokenResponse(o),o}async doTokenRequest(e){const 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);const r=new AbortController,s=setTimeout(()=>r.abort(),this.config.timeout);try{const o=await fetch(this.tokenEndpoint,{method:"POST",headers:{"Content-Type":w.CONTENT_TYPE,Accept:"application/json"},body:t.toString(),signal:r.signal});clearTimeout(s);const a={};o.headers.forEach((h,g)=>{a[g.toLowerCase()]=h});const d=await o.json();if(!o.ok){const h=l.fromOAuthError({error:d.error||"server_error",error_description:d.error_description||d.message,error_uri:d.error_uri},o.status,a);throw this.config.onError&&this.config.onError({error:h.code,error_description:h.message}),h}return d}catch(o){throw clearTimeout(s),o instanceof Error&&o.name==="AbortError"?new L(`Request timed out after ${this.config.timeout}ms`):o instanceof TypeError&&o.message.includes("fetch")?new L(`Network error: ${o.message}`,o):o instanceof l?o:l.fromError(o instanceof Error?o:new Error(String(o)))}}async executeWithRetry(e){let t;for(let r=1;r<=this.config.retries;r++)try{return await e()}catch(s){if(!(s instanceof l))throw s;if(t=s,r<this.config.retries&&this.retryStrategy.shouldRetry({code:s.code,status:s.status},r)){const o=this.retryStrategy.getDelay(r);await this.sleep(o);continue}throw s}throw t??new l({code:"server_error",message:"Request failed after retries"})}sleep(e){return new Promise(t=>setTimeout(t,e))}getCachedToken(){const e=this.cache;if("cache"in e){const 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;const r=Math.floor(Date.now()/1e3),o=(e.issued_at??r-e.expires_in)+e.expires_in;return r>=o-t}parseToken(e){try{const t=e.split(".");if(t.length!==3)throw new R("Invalid JWT format: expected 3 parts");const r=t[1];if(!r)throw new R("Invalid JWT format: missing payload");const s=atob(r.replace(/-/g,"+").replace(/_/g,"/")),o=JSON.parse(s);return o.scopes&&typeof o.scopes=="string"?o.scopes=o.scopes.split(" "):o.scopes||(o.scopes=[]),o}catch(t){throw t instanceof R?t:new R(`Failed to parse token: ${t instanceof Error?t.message:"Unknown error"}`)}}clearCache(){const e=this.getCacheKey(this.config.scopes,this.config.audience);this.cache.delete(e)}async revokeToken(){const e=this.getCachedToken();if(!e)return;const t=`${this.config.url}/oauth2/revoke`,r=new URLSearchParams;r.append("token",e.access_token),r.append("client_id",this.config.clientId),r.append("client_secret",this.config.clientSecret);try{const s=await fetch(t,{method:"POST",headers:{"Content-Type":w.CONTENT_TYPE},body:r.toString()});if(!s.ok&&s.status!==200){const o=await s.json().catch(()=>({}));throw l.fromOAuthError({error:o.error||"server_error",error_description:o.error_description||"Token revocation failed"},s.status)}this.clearCache()}catch(s){throw s instanceof l?s:l.fromError(s instanceof Error?s:new Error(String(s)))}}get url(){return this.config.url}get clientId(){return this.config.clientId}get scopes(){return this.config.scopes}get audience(){return this.config.audience}}exports.APP_ID_HEADER_KEY=A;exports.AUTHORIZATION_HEADER_KEY=I;exports.AppAPI=oe;exports.AuthAPI=ne;exports.AuthService=pe;exports.CLIAuthAPI=Fe;exports.DEFAULT_GROUP_NAME=Ie;exports.DEFAULT_SCOPES=j;exports.DEVICE_ID_HEADER_KEY=Y;exports.DEVICE_TYPE_HEADER_KEY=H;exports.ERROR_MESSAGE_MAX_LENGTH=ee;exports.InvitationAPI=ae;exports.InvitationService=fe;exports.M2MClient=Ne;exports.M2MConfigError=x;exports.M2MError=l;exports.M2MErrorCodes=Oe;exports.M2MNetworkError=L;exports.M2MTokenParseError=R;exports.M2M_DEFAULTS=w;exports.MINIMAL_DEFAULT_SCOPES=_e;exports.OS=b;exports.PASSFLOW_CLOUD_URL=N;exports.POPUP_HEIGHT=z;exports.POPUP_POLL_INTERVAL_MS=W;exports.POPUP_TIMEOUT_MS=J;exports.POPUP_WIDTH=X;exports.Passflow=$;exports.PassflowAdminEndpointPaths=T;exports.PassflowEndpointPaths=c;exports.PassflowError=u;exports.PassflowEvent=n;exports.Providers=se;exports.RequestMethod=_;exports.SDK_VERSION=B;exports.SessionState=V;exports.SettingAPI=ce;exports.TOKEN_EXPIRY_BUFFER_SECONDS=K;exports.TenantAPI=he;exports.TenantService=ve;exports.TenantUserMembership=ke;exports.TokenCacheService=ye;exports.TokenDeliveryMode=S;exports.TokenType=p;exports.TwoFactorApiClient=de;exports.TwoFactorPolicy=ie;exports.TwoFactorService=Se;exports.USERNAME_MAX_LENGTH=Q;exports.USERNAME_MIN_LENGTH=Z;exports.UserAPI=ue;exports.UserService=me;exports.isTokenExpired=m;exports.isValidEmail=P;exports.isValidJWTFormat=F;exports.isValidPhoneNumber=D;exports.isValidUsername=ge;exports.parseToken=v;exports.pathWithParams=y;exports.sanitizeErrorMessage=le;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U=require("axios"),we=require("uuid"),O=require("@simplewebauthn/browser"),Te="0.8.0",Ee={version:Te},A="X-Passflow-Clientid",I="Authorization",Y="X-Passflow-DeviceId",H="X-Passflow-DeviceType",B=Ee.version,_e=["id","offline","openid"],j=["id","offline","tenant","email","oidc","openid","access:tenant:all"],N="https://auth.passflow.cloud",Ie="default",X=500,z=600,W=100,J=6e4,K=30,Z=3,Q=30,ee=200,be=i=>{const e=[];let t;for(t in i){const r=i[t];if(r===void 0)continue;const s={tenant:{id:r.tenant_id,name:r.tenant_name}};s.groups=r.groups?Object.keys(r.groups).map(o=>{const a=r.groups[o]||[];return{group:{id:o,name:r.group_names?.[o]??"unknown"},roles:a}}):[],s.tenantRoles=s.groups?.find(o=>o.group.id===r.root_group_id),e.push(s)}return{raw:i,tenants:e}};function Ae(i){if(typeof window<"u"&&typeof window.atob=="function")return window.atob(i);if(typeof Buffer<"u")return Buffer.from(i,"base64").toString("utf-8");throw new Error("No Base64 decoding method available in this environment")}class Ce{constructor(e){this.storageManager=e}isTokenTypeExpired(e){const t=this.storageManager.getToken(e);if(!t)return!0;const r=v(t);return r?m(r):!0}parseTokenType(e){const t=this.storageManager.getToken(e);if(t)return v(t)}}function m(i,e=K){return Math.floor(Date.now()/1e3)+e>i.exp}function v(i){const e=i.split(".")[1];if(!e)throw new Error("Invalid token string");const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4),s=Ae(r),o=decodeURIComponent(s.split("").map(d=>"%"+("00"+d.charCodeAt(0).toString(16)).slice(-2)).join("")),a=JSON.parse(o);return a.membership=a.passflow_tm&&a.type!=="invite"?be(a.passflow_tm):void 0,a}var p=(i=>(i.id_token="id_token",i.access_token="access",i.refresh_token="refresh",i.invite_token="invite",i.reset_token="reset",i.web_cookie="web-cookie",i.management="management",i.signin="signin",i.actor="actor",i.two_factor="2fa",i))(p||{}),S=(i=>(i.JsonBody="json_body",i.Cookie="cookie",i.Mobile="mobile",i.BFF="bff",i))(S||{}),V=(i=>(i.Unknown="unknown",i.Valid="valid",i.Invalid="invalid",i))(V||{});class te{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{const e=this.storageManager.storage.getItem(this.DELIVERY_MODE_KEY);e&&Object.values(S).includes(e)&&(this.mode=e,this.isInitializedFlag=!0)}catch{}}loadPersistedSessionState(){try{const e=this.storageManager.storage.getItem(this.SESSION_STATE_KEY);e&&Object.values(V).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{}}}class G{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){const{id_token:r,access_token:s,refresh_token:o,scopes:a}=e;t===S.Cookie||t===S.BFF?r&&this.storage.setItem(this.ID_TOKEN_KEY,r):(r&&this.storage.setItem(this.getKeyForTokenType(p.id_token),r),s&&this.storage.setItem(this.getKeyForTokenType(p.access_token),s),o&&this.storage.setItem(this.getKeyForTokenType(p.refresh_token),o),a&&this.storage.setItem(this.scopes,a.join(",")))}getToken(e){const t=this.getKeyForTokenType(e);return this.storage.getItem(t)??void 0}getTokens(){const e=this.getDeliveryMode();if(e===S.Cookie||e===S.BFF){const r=this.storage.getItem(this.ID_TOKEN_KEY);return r?{id_token:r}:void 0}const t=this.storage.getItem(this.getKeyForTokenType(p.access_token));if(t)return{access_token:t,id_token:this.storage.getItem(this.getKeyForTokenType(p.id_token))??void 0,refresh_token:this.storage.getItem(this.getKeyForTokenType(p.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(p.access_token))}hasCookieModeIdToken(){return!!this.storage.getItem(this.ID_TOKEN_KEY)}deleteToken(e){const t=this.getKeyForTokenType(e);this.storage.removeItem(t)}deleteTokens(){this.storage.removeItem(this.getKeyForTokenType(p.id_token)),this.storage.removeItem(this.getKeyForTokenType(p.access_token)),this.storage.removeItem(this.getKeyForTokenType(p.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{const e=this.storage.getItem(this.DELIVERY_MODE_KEY);if(e&&Object.values(S).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{}}getKeyForTokenType(e){return`${this.keyStoragePrefix}${e}`}}class re{constructor(e){this.storageManager=e??new G}getDeviceId(){const e=this.storageManager.getDeviceId();if(!e){const t=this.generateUniqueDeviceId();return this.storageManager.setDeviceId(t),t}return e}generateUniqueDeviceId(){return we.v4()}}var _=(i=>(i.GET="get",i.POST="post",i.PUT="put",i.PATCH="patch",i.DELETE="delete",i))(_||{}),c=(i=>(i.signin="/auth/login",i.signup="/auth/register",i.signInWithProvider="/auth/federated/start/",i.passwordless="/auth/passwordless/start",i.passwordlessComplete="/auth/passwordless/complete",i.logout="/user/logout",i.refresh="/auth/refresh",i.validateSession="/user/me",i.sendPasswordResetEmail="/auth/password/reset",i.resetPassword="/auth/password/change",i.appSettings="/app/settings",i.passkeyRegisterStart="/auth/passkey/register/start",i.passkeyRegisterComplete="/auth/passkey/register/complete",i.passkeyAuthenticateStart="/auth/passkey/authenticate/start",i.passkeyAuthenticateComplete="/auth/passkey/authenticate/complete",i.passkeyValidate="/auth/validate",i.settingsAll="/settings",i.settingsPasswordPolicy="/settings/password",i.settingsPasskey="/settings/passkey",i.userPasskey="/user/passkey",i.addUserPasskey="/user/passkey/add/start",i.completeAddUserPasskey="/user/passkey/add/complete",i.joinInvitation="/user/tenant/join",i.tenantPath="/user/tenant",i.invitationsPath="/user/tenant/:tenantID/invitations",i.requestInvitation="/user/invite",i.invitationDelete="/user/invite/:invitationID",i.invitationResend="/user/invite/:invitationID/resend",i.invitationGetLink="/user/invite/:invitationID/link",i.twoFactor="/user/2fa",i.twoFactorStatus="/user/2fa/status",i.twoFactorSetupBegin="/user/2fa/setup/begin",i.twoFactorSetupConfirm="/user/2fa/setup/confirm",i.twoFactorVerify="/auth/2fa/verify",i.twoFactorRecovery="/auth/2fa/recovery",i.twoFactorRegenerateCodes="/user/2fa/recovery-codes/regenerate",i.twoFactorSetupMagicLink="/auth/2fa-setup",i.TwoFactorMethodsAvailable="/v2/user/2fa/methods/available",i.TwoFactorMethodsRegistered="/v2/user/2fa/methods",i.TwoFactorMethodSetupBegin="/v2/user/2fa/methods/:method/setup/begin",i.TwoFactorMethodSetupConfirm="/v2/user/2fa/methods/:method/setup/confirm",i.TwoFactorMethodRemove="/v2/user/2fa/methods/:id",i.TwoFactorChallenge="/v2/auth/2fa/challenge",i.TwoFactorVerifyV2="/v2/auth/2fa/verify",i.TwoFactorAlternative="/v2/auth/2fa/alternative",i.TwoFactorTrustedDevices="/v2/user/2fa/trusted-devices",i.TwoFactorTrustedDeviceRevoke="/v2/user/2fa/trusted-devices/:id",i.cliAuthStatus="/cli/auth/status/:sessionId",i.cliAuthComplete="/cli/auth/complete",i))(c||{}),T=(i=>(i.passkeyRegisterStart="/admin/auth/passkey/register/start",i.passkeyRegisterComplete="/admin/auth/passkey/register/complete",i.passkeyAuthenticateStart="/admin/auth/passkey/authenticate/start",i.passkeyAuthenticateComplete="/admin/auth/passkey/authenticate/complete",i.passkeyValidate="/admin/auth/validate",i.logout="/admin/auth/logout",i))(T||{});class u 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()}}var se=(i=>(i.google="google",i.facebook="facebook",i))(se||{}),b=(i=>(i.web="web",i))(b||{});function y(i,e){let t=i;return Object.entries(e).forEach(([r,s])=>{t=t.replace(`:${r}`,s)}),t}var ie=(i=>(i.Disabled="disabled",i.Optional="optional",i.Required="required",i))(ie||{});const Re=3,Me=1e3;class E{constructor(e,t,r){this.refreshPromise=null,this.isRefreshing=!1,this.origin=typeof window<"u"?window.location.origin:"",this.defaultHeaders={Accept:"application/json","Content-Type":"application/json"},this.nonAccessTokenEndpoints=["/auth/","/settings","/settings/"],this.protectedEndpoints=["logout","refresh"];const{url:s,appId:o,keyStoragePrefix:a}=e;this.url=s||N,this.storageManager=t??new G({prefix:a??""}),this.deviceService=r??new re(this.storageManager),this.tokenService=new Ce(this.storageManager),this.tokenDeliveryManager=new te(this.storageManager),o&&(this.appId=o,this.defaultHeaders={...this.defaultHeaders,[A]:o});const d=this.deviceService.getDeviceId();this.defaultHeaders={...this.defaultHeaders,[Y]:d,[H]:"web"},this.detectCookieSupport(),this.instance=U.create({baseURL:this.url,headers:{...this.defaultHeaders}}),this.instance.interceptors.request.use(async h=>{if(this.isNonAuthEndpoint(h.url))return h;if(this.tokenDeliveryManager.isCookieMode()){h.withCredentials=!0;const f=this.storageManager.getCsrfToken();return f&&(h.headers["X-CSRF-Token"]=f),h}if(h.url?.includes("refresh")){if(this.isRefreshing){const f=new AbortController;return f.abort(),h.signal=f.signal,h}return h}const g=this.storageManager.getTokens();if(g?.access_token){const f=v(g.access_token);if(m(f,K)&&g.refresh_token)try{if(this.refreshPromise){const k=await this.refreshPromise;return k?.data?.access_token&&(h.headers[I]=`Bearer ${k.data.access_token}`),h}this.refreshPromise=this.refreshTokens();try{const k=await this.refreshPromise;return k?.data?.access_token&&(h.headers[I]=`Bearer ${k.data.access_token}`),h}finally{this.refreshPromise=null}}catch(k){return this.refreshPromise=null,this.isRefreshing=!1,this.storageManager.deleteTokens(),Promise.reject(k)}return h.headers[I]=`Bearer ${g.access_token}`,h}return h}),this.instance.interceptors.response.use(h=>h,async h=>(h.response?.status===401&&this.tokenDeliveryManager.setSessionInvalid(),h.response?.status===429?await this.handleRateLimitError(h):this.handleAxiosError(h)))}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(!(typeof document>"u"))try{document.cookie="passflow_test=1; SameSite=Lax";const e=document.cookie.indexOf("passflow_test=1")!==-1;document.cookie="passflow_test=; expires=Thu, 01 Jan 1970 00:00:00 UTC",!e&&this.tokenDeliveryManager.isCookieMode()}catch{}}async refreshTokens(){if(this.tokenDeliveryManager.isCookieMode()){const e=await this.instance.post(c.refresh,{},{withCredentials:!0});return this.tokenDeliveryManager.setSessionValid(),e.data.csrf_token&&this.storageManager.setCsrfToken(e.data.csrf_token),e.data.id_token&&this.storageManager.setIdToken(e.data.id_token),e}else{const e=this.storageManager.getTokens(),t=this.storageManager.getScopes();if(!e?.refresh_token)throw new Error("No refresh token available");this.isRefreshing=!0;const r={refresh_token:e.refresh_token,scopes:t},s=await this.instance.post(c.refresh,r,{headers:{[I]:`Bearer ${e.refresh_token}`}});return s.data&&this.storageManager.saveTokens(s.data),this.isRefreshing=!1,s}}async handleRateLimitError(e){const t=e.config;if(!t)return Promise.reject(e);const r=t.method?.toUpperCase();if(!["GET","HEAD","OPTIONS"].includes(r||""))return Promise.reject(e);const o=t._retryCount||0;if(o>=Re)return Promise.reject(e);let a=Me*Math.pow(2,o);const d=e.response?.headers?.["retry-after"];if(d){const h=Number.parseInt(d,10);if(!Number.isNaN(h))a=h*1e3;else{const g=new Date(d);Number.isNaN(g.getTime())||(a=Math.max(0,g.getTime()-Date.now()))}}return await new Promise(h=>setTimeout(h,a)),t._retryCount=o+1,this.instance.request(t)}async handleAxiosError(e){if(!e.response)return Promise.reject(e);const t=e.response.status,r=e.response.data;if("error"in r&&typeof r.error=="object"&&r.error!==null){const{error:s}=r;return Promise.reject(new u(s))}return Promise.reject(new u({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,r){return(await this.instance.request({method:e,url:t,...r})).data}get(e,t){return this.send(_.GET,e,t)}post(e,t,r){return this.send(_.POST,e,{data:t,...r})}put(e,t,r){return this.send(_.PUT,e,{data:t,...r})}patch(e,t,r){return this.send(_.PATCH,e,{data:t,...r})}delete(e,t){return this.send(_.DELETE,e,t)}setAppId(e){this.appId=e,this.defaultHeaders={...this.defaultHeaders,[A]:e},this.instance.defaults.headers.common[A]=e}}class oe{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getAppSettings(){return this.axiosClient.get(c.appSettings)}}class ne{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}refreshToken(e,t,r){const s={access:r,scopes:t};return this.axiosClient.post(c.refresh,s,{headers:{[I]:`Bearer ${e}`}})}signIn(e,t,r){const s={...e,device:t,os:r};return this.axiosClient.post(c.signin,s)}signUp(e){const{create_tenant:t,anonymous:r}=e,s={...e,create_tenant:t??!1,anonymous:r??!1};return this.axiosClient.post(c.signup,s)}passwordlessSignIn(e,t,r){const{create_tenant:s}=e,o={...e,create_tenant:s??!1,device:t,os:r};return this.axiosClient.post(c.passwordless,o)}passwordlessSignInComplete(e){return this.axiosClient.post(c.passwordlessComplete,e)}logOut(e,t,r=!1){const s=r?void 0:{refresh_token:t,device:e},o=r?T.logout:c.logout;return this.axiosClient.post(o,s)}validateSession(){return this.axiosClient.get(c.validateSession)}sendPasswordResetEmail(e){return this.axiosClient.post(c.sendPasswordResetEmail,e)}resetPassword(e,t,r){const s={password:e,scopes:t};return this.axiosClient.post(c.resetPassword,s,{headers:{[I]:`Bearer ${r}`,[A]:void 0}})}passkeyRegisterStart(e,t,r,s=!1){const{create_tenant:o}=e,a={...e,create_tenant:o??!1,device:t,os:r},d=s?T.passkeyRegisterStart:c.passkeyRegisterStart;return this.axiosClient.post(d,a)}passkeyRegisterComplete(e,t,r,s=!1){const o={challenge_id:r,device:t,passkey_data:e},a=s?T.passkeyRegisterComplete:c.passkeyRegisterComplete;return this.axiosClient.post(a,o)}passkeyAuthenticateStart(e,t,r,s=!1){const o={...e,user_id:e.user_id??"",device:t,os:r},a=s?T.passkeyAuthenticateStart:c.passkeyAuthenticateStart;return this.axiosClient.post(a,o)}passkeyAuthenticateComplete(e,t,r,s=!1){const o={challenge_id:r,device:t,passkey_data:e},a=s?T.passkeyAuthenticateComplete:c.passkeyAuthenticateComplete;return this.axiosClient.post(a,o)}passkeyValidate(e,t,r,s=!1,o){const a={otp:e,device:t,challenge_id:r};let d=c.passkeyValidate;!o&&s&&(d=T.passkeyValidate);const h=o?{[A]:o}:{};return this.axiosClient.post(d,a,{headers:h})}}class Fe{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getCLIAuthStatus(e){const t=y(c.cliAuthStatus,{sessionId:e});return this.axiosClient.get(t)}completeCLIAuth(e){return this.axiosClient.post(c.cliAuthComplete,e)}}class ae{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}requestInviteLink(e){return this.axiosClient.post(c.requestInvitation,e)}getInvitations(e){const 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());const r=y(c.invitationsPath,{tenantID:e.tenantID});return this.axiosClient.get(r,{params:t}).then(s=>({invites:s.invites,nextPageSkip:s.next_page_skip}))}deleteInvitation(e){const t=y(c.invitationDelete,{invitationID:e});return this.axiosClient.delete(t)}resendInvitation(e){const t=y(c.invitationResend,{invitationID:e});return this.axiosClient.post(t,{})}getInvitationLink(e){const t=y(c.invitationGetLink,{invitationID:e});return this.axiosClient.get(t)}}class ce{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getSettingsAll(){return this.axiosClient.get(c.settingsAll)}getPasswordPolicySettings(){return this.axiosClient.get(c.settingsPasswordPolicy)}getPasskeySettings(){return this.axiosClient.get(c.settingsPasskey)}}class he{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}joinInvitation(e,t){const r={invite_token:e,scopes:t};return this.axiosClient.post(c.joinInvitation,r)}createTenant(e){const t={name:e};return this.axiosClient.post(c.tenantPath,t)}getTenantDetails(e){const t=`${c.tenantPath}/${e}`;return this.axiosClient.get(t)}updateTenant(e,t){const r=`${c.tenantPath}/${e}`,s={name:t};return this.axiosClient.put(r,s)}deleteTenant(e){const t=`${c.tenantPath}/${e}`;return this.axiosClient.delete(t)}getUserTenantMembership(){return this.axiosClient.get(c.tenantPath)}createGroup(e,t){const r=`${c.tenantPath}/${e}/group`,s={name:t};return this.axiosClient.post(r,s)}getGroupInfo(e,t){const r=`${c.tenantPath}/${e}/group/${t}`;return this.axiosClient.get(r)}updateGroup(e,t,r){const s=`${c.tenantPath}/${e}/group/${t}`,o={name:r};return this.axiosClient.put(s,o)}deleteGroup(e,t){const r=`${c.tenantPath}/${e}/group/${t}`;return this.axiosClient.delete(r)}addUserToGroup(e,t,r,s){const o=`${c.tenantPath}/${e}/group/${t}/add`,a={user_id:r,role:s};return this.axiosClient.post(o,a)}removeUserRolesFromGroup(e,t,r,s){const o=`${c.tenantPath}/${e}/group/${t}/remove_roles`,a={user_id:r,roles:s};return this.axiosClient.post(o,a)}changeUserRoles(e,t,r,s){const o=`${c.tenantPath}/${e}/group/${t}/change`,a={user_id:r,roles:s};return this.axiosClient.post(o,a)}deleteUserFromGroup(e,t,r){const s=`${c.tenantPath}/${e}/group/${t}/${r}`;return this.axiosClient.delete(s)}getRolesForTenant(e){const t=`${c.tenantPath}/${e}/role`;return this.axiosClient.get(t)}createRoleForTenant(e,t){const r=`${c.tenantPath}/${e}/role`,s={name:t};return this.axiosClient.post(r,s)}updateRole(e,t,r){const s=`${c.tenantPath}/${e}/role/${t}`,o={name:r};return this.axiosClient.put(s,o)}deleteRole(e,t){const r=`${c.tenantPath}/${e}/role/${t}`;return this.axiosClient.delete(r)}deleteUserFromTenant(e,t){const r=`${c.tenantPath}/${e}/user/${t}`;return this.axiosClient.delete(r)}getGroupInvitations(e,t,r,s){const o=`${c.tenantPath}/${e}/group/${t}/invitations`;return this.axiosClient.get(o,{params:{limit:r,skip:s}})}getTenantInvitations(e,t,r){const s=`${c.tenantPath}/${e}/invitations`;return this.axiosClient.get(s,{params:{limit:t,skip:r}})}invalidateInviteById(e,t,r){const s=`${c.tenantPath}/${e}/group/${t}/invite/${r}`;return this.axiosClient.delete(s)}invalidateInviteByEmail(e,t,r){const s=`${c.tenantPath}/${e}/group/${t}/invite/email/${r}`;return this.axiosClient.delete(s)}}class de{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getStatus(){return this.axiosClient.get(c.twoFactorStatus)}beginSetup(){return this.axiosClient.post(c.twoFactorSetupBegin,{})}confirmSetup(e){return this.axiosClient.post(c.twoFactorSetupConfirm,e)}verify(e){const{tfa_token:t,code:r}=e;return this.axiosClient.post(c.twoFactorVerify,{code:r},{headers:{Authorization:`Bearer ${t}`}})}useRecoveryCode(e){const{tfa_token:t,recovery_code:r}=e;return this.axiosClient.post(c.twoFactorRecovery,{recovery_code:r},{headers:{Authorization:`Bearer ${t}`}})}disable(e){return this.axiosClient.delete(c.twoFactor,{data:e})}regenerateRecoveryCodes(e){return this.axiosClient.post(c.twoFactorRegenerateCodes,e)}validateTwoFactorSetupMagicLink(e){const t=`${c.twoFactorSetupMagicLink}/${e}`;return this.axiosClient.get(t,{transformRequest:[(r,s)=>(s&&delete s.Authorization,r)]}).then(r=>{const s=r;return{success:!0,sessionToken:s.session_token,userId:s.user_id,expiresIn:s.expires_in,appId:s.app_id}}).catch(r=>{if(r.response){const s=r.response.status,o=r.response.data||{},a=r.response.headers?.["retry-after"]?parseInt(r.response.headers["retry-after"],10):void 0;return{success:!1,error:{code:o.error||this.mapStatusToErrorCode(s),message:o.message||this.getDefaultErrorMessage(s),retryAfter:a}}}return{success:!1,error:{code:"SERVER_ERROR",message:r instanceof Error?r.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(c.TwoFactorMethodsAvailable)}getRegisteredMethods(){return this.axiosClient.get(c.TwoFactorMethodsRegistered)}beginMethodSetup(e){const t=y(c.TwoFactorMethodSetupBegin,{method:e});return this.axiosClient.post(t,{})}confirmMethodSetup(e,t){const r=y(c.TwoFactorMethodSetupConfirm,{method:e});return this.axiosClient.post(r,t)}removeMethod(e){const t=y(c.TwoFactorMethodRemove,{id:e});return this.axiosClient.delete(t)}requestChallenge(e){return this.axiosClient.post(c.TwoFactorChallenge,e)}verifyV2(e){return this.axiosClient.post(c.TwoFactorVerifyV2,e)}switchToAlternative(e){return this.axiosClient.post(c.TwoFactorAlternative,e)}getTrustedDevices(){return this.axiosClient.get(c.TwoFactorTrustedDevices)}revokeTrustedDevice(e){const t=y(c.TwoFactorTrustedDeviceRevoke,{id:e});return this.axiosClient.delete(t)}}class ue{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getUserPasskeys(){return this.axiosClient.get(c.userPasskey)}renameUserPasskey(e,t){return this.axiosClient.patch(`${c.userPasskey}/${t}`,{name:e})}deleteUserPasskey(e){return this.axiosClient.delete(`${c.userPasskey}/${e}`)}addUserPasskeyStart({relyingPartyId:e,deviceId:t,os:r,passkeyDisplayName:s,passkeyUsername:o}){const a={passkey_display_name:s,passkey_username:o,relying_party_id:e,deviceId:t,os:r};return this.axiosClient.post(c.addUserPasskey,a)}addUserPasskeyComplete(e,t,r){return this.axiosClient.post(c.completeAddUserPasskey,{challenge_id:r,device:t,passkey_data:e})}}var n=(i=>(i.SignIn="signin",i.SignInStart="signin:start",i.Register="register",i.RegisterStart="register:start",i.SignOut="signout",i.SessionRestored="session:restored",i.SessionExpired="session:expired",i.Error="error",i.Refresh="refresh",i.RefreshStart="refresh:start",i.TokenCacheExpired="token-cache-expired",i.TwoFactorRequired="2fa:required",i.TwoFactorSetupStarted="2fa:setup_started",i.TwoFactorEnabled="2fa:enabled",i.TwoFactorDisabled="2fa:disabled",i.TwoFactorVerified="2fa:verified",i.TwoFactorRecoveryUsed="2fa:recovery_used",i.TwoFactorRecoveryCodesLow="2fa:recovery_low",i.TwoFactorRecoveryCodesExhausted="2fa:recovery_exhausted",i.TwoFactorSetupMagicLinkValidated="2fa:magic_link_validated",i.TwoFactorSetupMagicLinkFailed="2fa:magic_link_failed",i.TwoFactorChallengeReceived="two_factor_challenge_received",i.TwoFactorMethodSwitched="two_factor_method_switched",i.TwoFactorDeviceTrusted="two_factor_device_trusted",i))(n||{});class Pe{constructor(){this.subscribers=new Map}subscribe(e,t){if(t?.length){const r=new Set(t);this.subscribers.set(e,r)}else this.subscribers.set(e,null)}unsubscribe(e,t){if(!t?.length){this.subscribers.delete(e);return}const r=this.subscribers.get(e);r&&(t.forEach(s=>r.delete(s)),r.size===0&&this.subscribers.delete(e))}notify(e,t){this.subscribers.forEach((r,s)=>{(!r||r.has(e))&&s.onAuthChange?.(e,t)})}}function F(i){if(!i||typeof i!="string")return!1;const e=i.split(".");if(e.length!==3)return!1;const t=/^[A-Za-z0-9_-]+$/;return e.every(r=>t.test(r)&&r.length>0)}function le(i){return i.replace(/<[^>]*>/g,"").substring(0,ee)}function P(i){if(!i||typeof i!="string")return!1;const e=i.trim();return e.length===0?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}function D(i){if(!i||typeof i!="string")return!1;const e=i.trim();return/^\+[1-9]\d{1,14}$/.test(e)}function ge(i){if(!i||typeof i!="string")return!1;const e=i.trim();return e.length<Z||e.length>Q?!1:/^[a-zA-Z0-9_-]+$/.test(e)}function M(i,e=6){return!i||typeof i!="string"?!1:(e===8?/^\d{8}$/:/^\d{6}$/).test(i)}function De(i){if(!i||typeof i!="string")return null;const e=i.toUpperCase().replace(/\s+/g,"");return/^[A-Z0-9-]{4,16}$/.test(e)?e:null}class pe{constructor(e,t,r,s,o,a,d,h,g,f,k,C){this.authApi=e,this.deviceService=t,this.storageManager=r,this.subscribeStore=s,this.tokenCacheService=o,this.scopes=a,this.createTenantForNewUser=d,this.origin=h,this.url=g,this.sessionCallbacks=f,this.appId=k,this.tokenExchangeConfig=C,this.tokenDeliveryManager=new te(r),C?.enabled&&this.tokenDeliveryManager.setMode(S.BFF),this.initializeSession()}async initializeSession(){(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode())&&await this.restoreSession()}async restoreSession(){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.statusUrl)try{const 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{const e=await this.authApi.validateSession();return e.valid?(this.tokenDeliveryManager.setSessionValid(),e.user&&this.subscribeStore.notify(n.SessionRestored,e.user),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return this.tokenDeliveryManager.setSessionInvalid(),!1}}async processAuthResponse(e,t){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)}async forwardTokensToBFF(e){if(!this.tokenExchangeConfig?.callbackUrl)return;const 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 new Error(`BFF token storage failed: ${t.status}`)}async signIn(e){if("email"in e&&e.email&&!P(e.email)){const s=new Error("Invalid email format"),o={message:"Invalid email format",originalError:s,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(n.Error,o),s}if("username"in e&&e.username&&!ge(e.username)){const s=new Error("Invalid username format. Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens"),o={message:"Invalid username format. Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens",originalError:s,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(n.Error,o),s}if("phone"in e&&e.phone&&!D(e.phone)){const s=new Error("Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)"),o={message:"Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)",originalError:s,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(n.Error,o),s}this.subscribeStore.notify(n.SignInStart,{email:e.email});const t=this.deviceService.getDeviceId(),r=b.web;e.scopes=e.scopes??this.scopes;try{const s=await this.authApi.signIn(e,t,r);return"requires_2fa"in s&&s.requires_2fa===!0||"tfa_token"in s&&s.tfa_token?(this.subscribeStore.notify(n.TwoFactorRequired,{email:e.email||"",challengeId:s.challenge_id||"",tfaToken:s.tfa_token||""}),s):(await this.processAuthResponse(s,e.scopes),this.subscribeStore.notify(n.SignIn,{tokens:s,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),s)}catch(s){const o={message:s instanceof Error?s.message:"Sign in failed",originalError:s,code:s instanceof u?s.id:void 0};throw this.subscribeStore.notify(n.Error,o),s}}async signUp(e){if(e.user.email&&!P(e.user.email)){const t=new Error("Invalid email format"),r={message:"Invalid email format",originalError:t,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(n.Error,r),t}if(e.user.phone_number&&!D(e.user.phone_number)){const t=new Error("Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)"),r={message:"Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)",originalError:t,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(n.Error,r),t}this.subscribeStore.notify(n.RegisterStart,{email:e.user.email}),e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{const t=await this.authApi.signUp(e);return await this.processAuthResponse(t,e.scopes),this.subscribeStore.notify(n.Register,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),t}catch(t){const r={message:t instanceof Error?t.message:"Sign up failed",originalError:t,code:t instanceof u?t.id:void 0};throw this.subscribeStore.notify(n.Error,r),t}}async passwordlessSignIn(e){if(e.email&&!P(e.email)){const s=new Error("Invalid email format"),o={message:"Invalid email format",originalError:s,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(n.Error,o),s}if(e.phone&&!D(e.phone)){const s=new Error("Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)"),o={message:"Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)",originalError:s,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(n.Error,o),s}this.subscribeStore.notify(n.SignInStart,{email:e.email}),e.scopes=e.scopes??this.scopes;const t=this.deviceService.getDeviceId(),r=b.web;try{return await this.authApi.passwordlessSignIn(e,t,r)}catch(s){const o={message:s instanceof Error?s.message:"Failed to send passwordless sign-in link",originalError:s,code:s instanceof u?s.id:void 0};throw this.subscribeStore.notify(n.Error,o),s}}async passwordlessSignInComplete(e){this.subscribeStore.notify(n.SignInStart,{}),e.scopes=e.scopes??this.scopes,e.device=this.deviceService.getDeviceId();try{const t=await this.authApi.passwordlessSignInComplete(e);return await this.processAuthResponse(t,e.scopes),this.subscribeStore.notify(n.SignIn,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),t}catch(t){const r={message:t instanceof Error?t.message:"Passwordless sign in failed",originalError:t,code:t instanceof u?t.id:void 0};throw this.subscribeStore.notify(n.Error,r),t}}async logOut(){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.logoutUrl)try{(await fetch(this.tokenExchangeConfig.logoutUrl,{method:"POST",credentials:"include"})).ok}catch{}else{const e=this.storageManager.getToken(p.refresh_token),t=this.storageManager.getDeviceId();try{if((await this.authApi.logOut(t,e,!this.appId)).status!=="ok")throw new Error("Logout failed")}catch{}}this.storageManager.deleteTokens(),this.storageManager.clearIdToken(),this.storageManager.clearCsrfToken(),this.tokenDeliveryManager.reset(),this.subscribeStore.notify(n.SignOut,{})}async refreshToken(){if(this.subscribeStore.notify(n.RefreshStart,{}),this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.refreshUrl)try{const r=await fetch(this.tokenExchangeConfig.refreshUrl,{method:"POST",credentials:"include"});if(!r.ok)throw this.tokenDeliveryManager.setSessionInvalid(),new Error("BFF token refresh failed");const s=await r.json();return this.tokenDeliveryManager.setSessionValid(),s.id_token&&this.storageManager.setIdToken(s.id_token),this.subscribeStore.notify(n.Refresh,{tokens:s,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(n.TokenCacheExpired,{isExpired:!1}),this.tokenCacheService.isRefreshing=!1,this.tokenCacheService.tokenExpiredFlag=!1,s}catch(r){this.tokenDeliveryManager.setSessionInvalid();const s={message:r instanceof Error?r.message:"Token refresh failed",originalError:r};throw this.subscribeStore.notify(n.Error,s),r}if(this.tokenDeliveryManager.isCookieMode())try{const r=await this.authApi.refreshToken("",this.scopes);return this.tokenDeliveryManager.setSessionValid(),await this.processAuthResponse(r,this.scopes),this.subscribeStore.notify(n.Refresh,{tokens:r,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(n.TokenCacheExpired,{isExpired:!1}),this.tokenCacheService.isRefreshing=!1,this.tokenCacheService.tokenExpiredFlag=!1,r}catch(r){this.tokenDeliveryManager.setSessionInvalid();const s={message:r instanceof Error?r.message:"Token refresh failed",originalError:r,code:r instanceof u?r.id:void 0};throw this.subscribeStore.notify(n.Error,s),r}const e=this.storageManager.getTokens();if(e){if(!e?.refresh_token){const r=new Error("No refresh token found"),s={message:"No refresh token found",originalError:r};throw this.subscribeStore.notify(n.Error,s),r}}else{const r=new Error("No tokens found"),s={message:"No tokens found",originalError:r};throw this.subscribeStore.notify(n.Error,s),r}const t=e?.scopes??this.scopes;try{const r=await this.authApi.refreshToken(e?.refresh_token??"",t,e?.access_token);return r.scopes=t,this.storageManager.saveTokens(r),this.tokenCacheService.setTokensCache(r),this.subscribeStore.notify(n.Refresh,{tokens:r,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(n.TokenCacheExpired,{isExpired:!1}),this.tokenCacheService.isRefreshing=!1,this.tokenCacheService.tokenExpiredFlag=!1,this.tokenCacheService.startTokenCheck(),r}catch(r){const s={message:r instanceof Error?r.message:"Token refresh failed",originalError:r,code:r instanceof u?r.id:void 0,details:U.isAxiosError(r)&&r.response?{status:r.response.status,data:r.response.data}:void 0};this.subscribeStore.notify(n.Error,s);const o=U.isAxiosError(r)&&r.response?.status&&r.response.status>=400&&r.response.status<500;throw o&&(this.tokenCacheService.tokenExpiredFlag=!0,this.tokenCacheService.setTokensCache(void 0),this.storageManager.deleteTokens(),this.subscribeStore.notify(n.SessionExpired,{reason:"refresh_failed"})),r instanceof u?r:o?new Error(`Getting unknown error message from server with code:${r.response?.status}`):r}}async sendPasswordResetEmail(e){try{return await this.authApi.sendPasswordResetEmail(e)}catch(t){const r={message:t instanceof Error?t.message:"Failed to send password reset email",originalError:t,code:t instanceof u?t.id:void 0};throw this.subscribeStore.notify(n.Error,r),t}}async resetPassword(e,t){this.subscribeStore.notify(n.SignInStart,{});const s=new URLSearchParams(window.location.search).get("token")??void 0,o=t??this.scopes;try{const a=await this.authApi.resetPassword(e,o,s);return await this.processAuthResponse(a,o),this.subscribeStore.notify(n.SignIn,{tokens:a,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),a}catch(a){const d={message:a instanceof Error?a.message:"Password reset failed",originalError:a,code:a instanceof u?a.id:void 0};throw this.subscribeStore.notify(n.Error,d),a}}async passkeyRegister(e){this.subscribeStore.notify(n.RegisterStart,{});const t=this.deviceService.getDeviceId(),r=b.web;e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{const{challenge_id:s,publicKey:o}=await this.authApi.passkeyRegisterStart(e,t,r,!this.appId);o.user.id=btoa(o.user.id);const a=await O.startRegistration({optionsJSON:o}),d=await this.authApi.passkeyRegisterComplete(a,t,s,!this.appId);return await this.processAuthResponse(d,e.scopes),this.subscribeStore.notify(n.Register,{tokens:d,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),d}catch(s){const o={message:s instanceof Error?s.message:"Passkey registration failed",originalError:s,code:s instanceof u?s.id:void 0};throw this.subscribeStore.notify(n.Error,o),s}}async passkeyAuthenticate(e){this.subscribeStore.notify(n.SignInStart,{});const t=this.deviceService.getDeviceId(),r=b.web;e.scopes=e.scopes??this.scopes;try{const{challenge_id:s,publicKey:o}=await this.authApi.passkeyAuthenticateStart(e,t,r,!this.appId),a=await O.startAuthentication({optionsJSON:o}),d=await this.authApi.passkeyAuthenticateComplete(a,t,s,!this.appId);return"access_token"in d&&(await this.processAuthResponse(d,e.scopes),this.subscribeStore.notify(n.SignIn,{tokens:d,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),d}catch(s){const o={message:s instanceof Error?s.message:"Passkey authentication failed",originalError:s,code:s instanceof u?s.id:void 0};throw this.subscribeStore.notify(n.Error,o),s}}createFederatedAuthUrl(e){const t=`/auth/federated/start/${e.provider}`;if(!this.appId)throw new Error("AppId is required for federated auth");const s={scopes:(e.scopes??this.scopes).join(" "),redirect_url:e.redirect_url??this.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}:{}},o=new URL(t,this.url),a=new URLSearchParams(s);return o.search=a.toString(),o.toString()}federatedAuthWithPopup(e){this.subscribeStore.notify(n.SignInStart,{provider:e.provider});const t=e.scopes??this.scopes,r=this.deviceService.getDeviceId(),s=this.createFederatedAuthUrl({...e,scopes:t,device:r}),o=window.open(s,"_blank",`width=${X},height=${z}`);if(!o){this.federatedAuthWithRedirect(e);return}const a=Date.now(),d=setInterval(()=>{if(o.closed){clearInterval(d);const h={message:"Authentication popup was closed",code:"POPUP_CLOSED"};this.subscribeStore.notify(n.Error,h);return}if(Date.now()-a>J){clearInterval(d),o.close();const h={message:"Authentication popup timed out",code:"POPUP_TIMEOUT"};this.subscribeStore.notify(n.Error,h);return}try{if(o.location.href.startsWith(this.origin)){const h=new URLSearchParams(o.location.search),g=h.get("access_token")||"",f=h.get("refresh_token")||"",k=h.get("id_token")||"",C={access_token:g,refresh_token:f||void 0,id_token:k||void 0,scopes:t};this.processAuthResponse(C,t).then(()=>{this.subscribeStore.notify(n.SignIn,{tokens:C,parsedTokens:this.tokenCacheService.getParsedTokens()}),window.location.href=`${this.origin}`}),clearInterval(d),o.close()}}catch{}},W)}federatedAuthWithRedirect(e){this.subscribeStore.notify(n.SignInStart,{provider:e.provider});const t=e.scopes??this.scopes,r=this.deviceService.getDeviceId(),s=this.createFederatedAuthUrl({...e,scopes:t,device:r});window.location.href=s}authRedirectUrl(e={}){try{const{url:t,redirectUrl:r,scopes:s,appId:o}=e??{},a=new URL(t??this.url);a.pathname=(a.pathname.endsWith("/")?a.pathname:a.pathname+"/")+"web";const d=s??this.scopes,h={appId:o??this.appId??"",redirectto:r??window.location.href,scopes:d.join(",")},g=new URLSearchParams(h);return a.search=g.toString(),a.toString()}catch(t){const r={message:t instanceof Error?t.message:"Failed to create auth redirect URL",originalError:t};throw this.subscribeStore.notify(n.Error,r),t}}authRedirect(e={}){try{window.location.href=this.authRedirectUrl(e)}catch(t){const r={message:t instanceof Error?t.message:"Failed to redirect to auth page",originalError:t};throw this.subscribeStore.notify(n.Error,r),t}}isAuthenticated(e){try{if(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode()){const t=!!e?.id_token||!!this.storageManager.getIdToken(),r=this.tokenDeliveryManager.isSessionValid(),s=this.tokenDeliveryManager.isSessionUnknown();return t&&(r||s)}return!e||!e.access_token?!1:!m(e.access_token)||e.refresh_token!==void 0&&!m(e.refresh_token)}catch(t){const r={message:t instanceof Error?t.message:"Failed to check authentication status",originalError:t};return this.subscribeStore.notify(n.Error,r),!1}}async submitSessionCheck(e=!1){let t,r;try{t=await this.getTokens(e),r=this.tokenCacheService.getParsedTokens()}catch(s){const o={message:s instanceof Error||s instanceof u?s.message:"Session check failed",originalError:s};this.subscribeStore.notify(n.Error,o),t=void 0}return t&&this.sessionCallbacks.createSession&&await this.sessionCallbacks.createSession({tokens:t,parsedTokens:r}),!t&&this.sessionCallbacks.expiredSession&&await this.sessionCallbacks.expiredSession(),t}async getTokens(e){try{if(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode()){const s=this.storageManager.getTokens();return s?.id_token?this.tokenDeliveryManager.isSessionInvalid()&&e?await this.refreshToken():s:void 0}const t=this.storageManager.getTokens();if(!t||!t.access_token)return;const r=v(t.access_token);return m(r)?e?await this.refreshToken():void 0:t}catch(t){const r={message:t instanceof Error?t.message:"Failed to get tokens",originalError:t};this.subscribeStore.notify(n.Error,r);return}}}class fe{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)}}class xe{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 Ue(){return new xe}class ke{constructor(e){this.data=this.normalize(e)}normalize(e){const t=new Map,r=new Map,s=new Map,o=[];return e.groups?.forEach(a=>{r.set(a.id,{id:a.id,name:a.name,default:a.default??!1,updated_at:a.updated_at,created_at:a.created_at})}),e.roles?.forEach(a=>{s.set(a.id,{id:a.id,tenant_id:a.tenant_id,name:a.name})}),e.users_in_groups?.forEach(a=>{const d=a.user;d&&!t.has(d.id)&&t.set(d.id,{id:d.id,name:d.name??null,email:d.email??null,phone:d.phone??null}),d&&a.group_id&&r.has(a.group_id)&&o.push({userId:d.id,groupId:a.group_id,roleIds:a.roles?.map(h=>h.id)??[]})}),{tenant_id:e.tenant_id,tenant_name:e.tenant_name,users:Array.from(t.values()),groups:Array.from(r.values()),roles:Array.from(s.values()),memberships:o,usersById:t,groupsById:r,rolesById:s}}getUsersInGroup(e){return this.data.memberships.filter(t=>t.groupId===e).map(t=>this.data.usersById.get(t.userId)).filter(t=>t!==void 0)}getGroupsForUser(e){return this.data.memberships.filter(t=>t.userId===e).map(t=>this.data.groupsById.get(t.groupId)).filter(t=>t!==void 0)}getUserRolesInGroup(e,t){const r=this.data.memberships.find(s=>s.userId===e&&s.groupId===t);return r?r.roleIds.map(s=>this.data.rolesById.get(s)).filter(s=>s!==void 0):[]}getData(){return this.data}}class ve{constructor(e,t,r){this.tenantApi=e,this.scopes=t,this.logger=r||Ue()}handlePassflowError(e,t){if(U.isAxiosError(e)&&e.response?.data){const r=e.response.data;if(typeof r=="object"&&r!==null&&"error"in r&&typeof r.error=="object"&&r.error!==null){const s=r.error;throw this.logger.error(`${t}: ${s.id} - ${s.message} (Status: ${s.status})`),new Error(`Passflow API Error: ${s.id} - ${s.message} (Status: ${s.status})`)}}throw this.logger.error(`${t}:`,e),e instanceof Error?e:new Error(String(e))}async joinInvitation(e,t){try{const r=t??this.scopes;return await this.tenantApi.joinInvitation(e,r)}catch(r){this.handlePassflowError(r,"Join invitation failed")}}async createTenant(e){try{return await this.tenantApi.createTenant(e)}catch(t){this.handlePassflowError(t,"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{const t=await this.tenantApi.getTenantDetails(e);return new ke(t)}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(r){this.handlePassflowError(r,`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(r){this.handlePassflowError(r,`Group creation failed for tenant ID ${e}`)}}async getGroupInfo(e,t){try{return await this.tenantApi.getGroupInfo(e,t)}catch(r){this.handlePassflowError(r,`Get group info failed for tenant ID ${e}, group ID ${t}`)}}async updateGroup(e,t,r){try{return await this.tenantApi.updateGroup(e,t,r)}catch(s){this.handlePassflowError(s,`Update group failed for tenant ID ${e}, group ID ${t}`)}}async deleteGroup(e,t){try{return await this.tenantApi.deleteGroup(e,t)}catch(r){this.handlePassflowError(r,`Delete group failed for tenant ID ${e}, group ID ${t}`)}}async addUserToGroup(e,t,r,s){try{return await this.tenantApi.addUserToGroup(e,t,r,s)}catch(o){this.handlePassflowError(o,`Add user to group failed for tenant ID ${e}, group ID ${t}, user ID ${r}`)}}async removeUserRolesFromGroup(e,t,r,s){try{return await this.tenantApi.removeUserRolesFromGroup(e,t,r,s)}catch(o){this.handlePassflowError(o,`Remove user roles from group failed for tenant ID ${e}, group ID ${t}, user ID ${r}`)}}async changeUserRoles(e,t,r,s){try{return await this.tenantApi.changeUserRoles(e,t,r,s)}catch(o){this.handlePassflowError(o,`Change user roles failed for tenant ID ${e}, group ID ${t}, user ID ${r}`)}}async deleteUserFromGroup(e,t,r){try{return await this.tenantApi.deleteUserFromGroup(e,t,r)}catch(s){this.handlePassflowError(s,`Delete user from group failed for tenant ID ${e}, group ID ${t}, user ID ${r}`)}}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(r){this.handlePassflowError(r,`Create role for tenant failed for tenant ID ${e}`)}}async updateRole(e,t,r){try{return await this.tenantApi.updateRole(e,t,r)}catch(s){this.handlePassflowError(s,`Update role failed for tenant ID ${e}, role ID ${t}`)}}async deleteRole(e,t){try{return await this.tenantApi.deleteRole(e,t)}catch(r){this.handlePassflowError(r,`Delete role failed for tenant ID ${e}, role ID ${t}`)}}async deleteUserFromTenant(e,t){try{return await this.tenantApi.deleteUserFromTenant(e,t)}catch(r){this.handlePassflowError(r,`Delete user from tenant failed for tenant ID ${e}, user ID ${t}`)}}async getGroupInvitations(e,t,r,s){try{return await this.tenantApi.getGroupInvitations(e,t,r,s)}catch(o){this.handlePassflowError(o,`Get group invitations failed for tenant ID ${e}, group ID ${t}`)}}async getTenantInvitations(e,t,r){try{return await this.tenantApi.getTenantInvitations(e,t,r)}catch(s){this.handlePassflowError(s,`Get tenant invitations failed for tenant ID ${e}`)}}async invalidateInviteById(e,t,r){try{return await this.tenantApi.invalidateInviteById(e,t,r)}catch(s){this.handlePassflowError(s,`Invalidate invite by ID failed for tenant ID ${e}, group ID ${t}, invite ID ${r}`)}}async invalidateInviteByEmail(e,t,r){try{return await this.tenantApi.invalidateInviteByEmail(e,t,r)}catch(s){this.handlePassflowError(s,`Invalidate invite by email failed for tenant ID ${e}, group ID ${t}, email ${r}`)}}}class ye{constructor(e,t,r){this.storageManager=e,this.authApi=t,this.subscribeStore=r,this.checkInterval=null,this.CHECK_INTERVAL=6e4,this.visibilityChangeHandler=null,this.isRefreshing=!1,this.tokenExpiredFlag=!1,this.storageManager=e,this.authApi=t,this.setupPageUnloadHandler()}initialize(){try{const e=this.storageManager.getTokens();if(!e){this.startTokenCheck();return}if(!e.access_token){this.setTokensCache(e),this.startTokenCheck();return}const t=v(e.access_token);m(t)?(this.tokenExpiredFlag=!0,this.stopTokenCheck(),this.subscribeStore.notify(n.TokenCacheExpired,{isExpired:!0})):(this.setTokensCache(e),this.startTokenCheck())}catch(e){const t={message:e instanceof Error?e.message:"Failed to get tokens",originalError:e};this.subscribeStore.notify(n.Error,t),this.setTokensCache(void 0)}}async refreshTokensCache(e){if(!this.isRefreshing)try{this.isRefreshing=!0,this.subscribeStore.notify(n.RefreshStart,{});const t=await this.authApi.refreshToken(e?.refresh_token??"",e.scopes??[],e.access_token);this.setTokensCache(t),this.subscribeStore.notify(n.Refresh,{tokens:t,parsedTokens:this.getParsedTokens()}),this.subscribeStore.notify(n.TokenCacheExpired,{isExpired:!1}),this.tokenExpiredFlag=!1,this.startTokenCheck()}catch(t){const r={message:t instanceof Error?t.message:"Failed to get tokens",originalError:t};this.subscribeStore.notify(n.Error,r),this.tokenExpiredFlag=!0,this.setTokensCache(void 0),this.stopTokenCheck(),this.storageManager.deleteTokens(),this.subscribeStore.notify(n.SessionExpired,{reason:"refresh_failed"})}finally{this.isRefreshing=!1}}startTokenCheck(){this.checkInterval&&clearInterval(this.checkInterval),!this.tokenExpiredFlag&&(this.setupVisibilityListener(),this.checkInterval=setInterval(()=>{typeof document<"u"&&document.hidden||this.isRefreshing||this.tokenExpiredFlag||this.isExpired()&&!this.tokenExpiredFlag&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(n.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck())},this.CHECK_INTERVAL))}setupVisibilityListener(){typeof document>"u"||(this.visibilityChangeHandler&&document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=()=>{!document.hidden&&this.checkInterval&&!this.isRefreshing&&!this.tokenExpiredFlag&&this.isExpired()&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(n.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck())},document.addEventListener("visibilitychange",this.visibilityChangeHandler))}setupPageUnloadHandler(){typeof window>"u"||window.addEventListener("beforeunload",()=>{this.destroy()})}stopTokenCheck(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null),this.visibilityChangeHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=null)}destroy(){this.stopTokenCheck()}setTokensCache(e){this.tokensCache=e,e?this.parsedTokensCache={access_token:e.access_token?v(e.access_token):void 0,id_token:e.id_token?v(e.id_token):void 0,refresh_token:e.refresh_token?v(e.refresh_token):void 0,scopes:e.scopes}:this.parsedTokensCache=void 0}getTokens(){return this.tokensCache}async getTokensWithRefresh(){try{if(!this.tokensCache)return this.tokensCache;if(!this.tokensCache.access_token)return this.tokensCache;const e=v(this.tokensCache.access_token);return m(e)&&!this.tokenExpiredFlag?(await this.refreshTokensCache(this.tokensCache),this.tokensCache):this.tokensCache}catch(e){const t={message:e instanceof Error?e.message:"Failed to get tokens",originalError:e};this.subscribeStore.notify(n.Error,t);return}}getParsedTokens(){return this.parsedTokensCache}isExpired(){if(!this.tokensCache)return!0;if(!this.tokensCache.access_token)return!1;const e=v(this.tokensCache.access_token);return m(e)}}class Se{constructor(e,t){this.twoFactorApi=e,this.subscribeStore=t,this.PARTIAL_AUTH_TIMEOUT_MS=300*1e3,this.SESSION_STORAGE_KEY="passflow_2fa_challenge",this.totpDigits=6;const r={onAuthChange:(s,o)=>{if(s===n.TwoFactorRequired){const a=o;this.setPartialAuthState(a.email,a.challengeId,a.tfaToken)}}};this.subscribeStore.subscribe(r,[n.TwoFactorRequired])}emitErrorAndThrow(e,t){const r=e,s={message:e instanceof Error?e.message:`${t} failed`,originalError:e,code:r?.id||void 0};throw this.subscribeStore.notify(n.Error,s),e}async getStatus(){try{const e=await this.twoFactorApi.getStatus();return e.totp_digits&&(this.totpDigits=e.totp_digits),e}catch(e){this.emitErrorAndThrow(e,"Get 2FA status")}}async beginSetup(){try{const e=await this.twoFactorApi.beginSetup();return e.totp_digits&&(this.totpDigits=e.totp_digits),this.subscribeStore.notify(n.TwoFactorSetupStarted,{secret:e.secret}),e}catch(e){this.emitErrorAndThrow(e,"Begin 2FA setup")}}async confirmSetup(e){if(!M(e,this.totpDigits))throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{const t=await this.twoFactorApi.confirmSetup({code:e});return this.subscribeStore.notify(n.TwoFactorEnabled,{recoveryCodes:t.recovery_codes,clearRecoveryCodes:()=>{t.recovery_codes.length=0}}),t}catch(t){this.emitErrorAndThrow(t,"Confirm 2FA setup")}}async verify(e){if(!M(e,this.totpDigits))throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);if(this.recoverPartialAuthState(),!this.isVerificationRequired())throw new Error("2FA verification expired or not required. User must sign in first.");if(!this.partialAuthState?.tfaToken)throw new Error("No TFA token found. User must sign in first.");try{const t=await this.twoFactorApi.verify({code:e,tfa_token:this.partialAuthState.tfaToken});return this.clearPartialAuthState(),this.subscribeStore.notify(n.TwoFactorVerified,{tokens:t}),t}catch(t){this.emitErrorAndThrow(t,"Verify 2FA code")}}async useRecoveryCode(e){try{const t=De(e);if(!t)throw new Error("Invalid recovery code format. Expected format: XXXX-XXXX or XXXXXXXX (alphanumeric).");if(this.recoverPartialAuthState(),!this.isVerificationRequired())throw new Error("2FA verification expired or not required. User must sign in first.");if(!this.partialAuthState?.tfaToken)throw new Error("No TFA token found. User must sign in first.");const r=await this.twoFactorApi.useRecoveryCode({recovery_code:t,tfa_token:this.partialAuthState.tfaToken});return this.clearPartialAuthState(),r.remaining_recovery_codes===0?this.subscribeStore.notify(n.TwoFactorRecoveryCodesExhausted,{tokens:r}):r.remaining_recovery_codes<=2&&this.subscribeStore.notify(n.TwoFactorRecoveryCodesLow,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(n.TwoFactorRecoveryUsed,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(n.TwoFactorVerified,{tokens:r}),r}catch(t){this.emitErrorAndThrow(t,"Use recovery code")}}async disable(e){if(!M(e,this.totpDigits))throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{const t=await this.twoFactorApi.disable({code:e});return this.subscribeStore.notify(n.TwoFactorDisabled,{}),t}catch(t){this.emitErrorAndThrow(t,"Disable 2FA")}}async regenerateRecoveryCodes(e){if(!M(e,this.totpDigits))throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{const t=await this.twoFactorApi.regenerateRecoveryCodes({code:e}),r=[...t.recovery_codes];return t.recovery_codes=[],t.recovery_codes=r,t}catch(t){this.emitErrorAndThrow(t,"Regenerate recovery codes")}}isVerificationRequired(){return this.recoverPartialAuthState(),this.partialAuthState?Date.now()>this.partialAuthState.expiresAt?(this.clearPartialAuthState(),!1):!0:!1}setPartialAuthState(e,t,r){if(this.partialAuthState={email:e,challengeId:t,tfaToken:r,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,typeof sessionStorage<"u")try{sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{}}recoverPartialAuthState(){if(!this.partialAuthState&&!(typeof sessionStorage>"u"))try{const e=sessionStorage.getItem(this.SESSION_STORAGE_KEY);if(!e)return;const 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){const 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(n.TwoFactorSetupMagicLinkValidated,{userId:t.userId,appId:t.appId,expiresIn:t.expiresIn||3600,sessionToken:t.sessionToken})):t.error&&this.subscribeStore.notify(n.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,"Get available 2FA methods")}}async getRegisteredMethods(){try{return await this.twoFactorApi.getRegisteredMethods()}catch(e){this.emitErrorAndThrow(e,"Get registered 2FA methods")}}async beginMethodSetup(e){try{const t=await this.twoFactorApi.beginMethodSetup(e);return this.subscribeStore.notify(n.TwoFactorSetupStarted,{secret:"",method:e}),t}catch(t){this.emitErrorAndThrow(t,"Begin 2FA method setup")}}async confirmMethodSetup(e,t){try{const r=await this.twoFactorApi.confirmMethodSetup(e,t);return this.subscribeStore.notify(n.TwoFactorEnabled,{recoveryCodes:[],clearRecoveryCodes:()=>{}}),r}catch(r){this.emitErrorAndThrow(r,"Confirm 2FA method setup")}}async removeMethod(e){try{await this.twoFactorApi.removeMethod(e)}catch(t){this.emitErrorAndThrow(t,"Remove 2FA method")}}async requestChallenge(e){try{const t=await this.twoFactorApi.requestChallenge(e);return this.subscribeStore.notify(n.TwoFactorChallengeReceived,{challengeId:t.challenge_id,method:t.method,alternativeMethods:t.alternative_methods}),t}catch(t){this.emitErrorAndThrow(t,"Request 2FA challenge")}}async verifyV2(e){try{const t=await this.twoFactorApi.verifyV2(e);return t.success&&(this.subscribeStore.notify(n.TwoFactorVerified,{tokens:{access_token:t.access_token,refresh_token:t.refresh_token}}),t.device_trusted&&this.subscribeStore.notify(n.TwoFactorDeviceTrusted,{})),t}catch(t){this.emitErrorAndThrow(t,"Verify 2FA challenge")}}async switchToAlternative(e){try{const t=await this.twoFactorApi.switchToAlternative(e);return this.subscribeStore.notify(n.TwoFactorMethodSwitched,{challengeId:t.challenge_id,method:t.method,alternativeMethods:t.alternative_methods}),t}catch(t){this.emitErrorAndThrow(t,"Switch to alternative 2FA method")}}async getTrustedDevices(){try{return await this.twoFactorApi.getTrustedDevices()}catch(e){this.emitErrorAndThrow(e,"Get trusted devices")}}async revokeTrustedDevice(e){try{await this.twoFactorApi.revokeTrustedDevice(e)}catch(t){this.emitErrorAndThrow(t,"Revoke trusted device")}}}class me{constructor(e,t){this.userAPI=e,this.deviceService=t}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:r}={}){const s=this.deviceService.getDeviceId(),o=b.web,{challenge_id:a,publicKey:d}=await this.userAPI.addUserPasskeyStart({relyingPartyId:e||window?.location?.hostname,deviceId:s,os:o,passkeyDisplayName:r,passkeyUsername:t});d.user.id=btoa(d.user.id);const h=await O.startRegistration({optionsJSON:d});return await this.userAPI.addUserPasskeyComplete(h,s,a)}}const q=class q{constructor(e){this.doRefreshTokens=!1,this.origin=window.location.origin,this.session=async({createSession:o,expiredSession:a,doRefresh:d=!1})=>{this.createSessionCallback=o,this.expiredSessionCallback=a,this.doRefreshTokens=d,await this.submitSessionCheck()};const{url:t,appId:r,scopes:s}=e;this.url=t||N,this.appId=r,this.storageManager=new G({prefix:e.keyStoragePrefix??""}),this.deviceService=new re(this.storageManager),this.authApi=new ne(e,this.storageManager,this.deviceService),this.appApi=new oe(e,this.storageManager,this.deviceService),this.userApi=new ue(e,this.storageManager,this.deviceService),this.settingApi=new ce(e,this.storageManager,this.deviceService),this.tenantApi=new he(e,this.storageManager,this.deviceService),this.invitationApi=new ae(e,this.storageManager,this.deviceService),this.twoFactorApi=new de(e,this.storageManager,this.deviceService),this.subscribeStore=new Pe,this.tokenCacheService=new ye(this.storageManager,this.authApi,this.subscribeStore),this.scopes=s??j,this.createTenantForNewUser=e.createTenantForNewUser??!1,this.authService=new pe(this.authApi,this.deviceService,this.storageManager,this.subscribeStore,this.tokenCacheService,this.scopes,this.createTenantForNewUser,this.origin,this.url,{createSession:this.createSessionCallback,expiredSession:this.expiredSessionCallback},this.appId??"",e.tokenExchange),this.userService=new me(this.userApi,this.deviceService),this.tenantService=new ve(this.tenantApi,this.scopes),this.tenant=this.tenantService,this.invitationService=new fe(this.invitationApi),this.twoFactorService=new Se(this.twoFactorApi,this.subscribeStore),this.twoFactor=this.twoFactorService,e.parseQueryParams&&this.checkAndSetTokens(),this.setTokensToCacheFromLocalStorage()}setAppId(e){this.appId=e,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.authService}async submitSessionCheck(){let e,t;try{e=await this.authService.getTokens(this.doRefreshTokens),t=this.tokenCacheService.getParsedTokens()}catch(r){const s={message:r instanceof Error||r instanceof u?r.message:"Session check failed",originalError:r};this.subscribeStore.notify(n.Error,s),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(){return this.checkAndSetTokens()}checkAndSetTokens(){let e=new URLSearchParams(window.location.search),t=!1;if(!e.get("access_token")&&window.location.hash){const h=new URLSearchParams(window.location.hash.substring(1));h.get("access_token")&&(e=h,t=!0)}const r=e.get("access_token"),s=e.get("refresh_token"),o=e.get("id_token"),a=e.get("scopes")?.split(",")??this.scopes;let d;if(r){if(!F(r)){const h={message:"Invalid access token format received",code:"INVALID_TOKEN_FORMAT"};this.subscribeStore.notify(n.Error,h),this.cleanupUrlParams(t);return}if(s&&!F(s)){const h={message:"Invalid refresh token format received",code:"INVALID_TOKEN_FORMAT"};this.subscribeStore.notify(n.Error,h),this.cleanupUrlParams(t);return}if(o&&!F(o)){const h={message:"Invalid ID token format received",code:"INVALID_TOKEN_FORMAT"};this.subscribeStore.notify(n.Error,h),this.cleanupUrlParams(t);return}return d={access_token:r,refresh_token:s??void 0,id_token:o??void 0,scopes:a},this.storageManager.clearDeliveryMode(),this.storageManager.saveTokens(d),this.tokenCacheService.setTokensCache(d),this.subscribeStore.notify(n.SignIn,{tokens:d,parsedTokens:this.getParsedTokens()}),this.submitSessionCheck(),this.cleanupUrlParams(t),this.error=void 0,d}else this.error=this.checkErrorsFromURL()}checkErrorsFromURL(){const t=new URLSearchParams(window.location.search).get("error");if(t){const r=le(t);return new Error(r)}}cleanupUrlParams(e=!1){if(e)window.history.replaceState({},document.title,window.location.pathname+window.location.search);else{const t=new URLSearchParams(window.location.search);t.delete("access_token"),t.delete("refresh_token"),t.delete("id_token"),t.delete("client_challenge"),t.size>0?window.history.replaceState({},document.title,`${window.location.pathname}?${t.toString()}`):window.history.replaceState({},document.title,window.location.pathname)}}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(){const e=this.storageManager.getTokens();if(!e||!e.access_token)return!1;const t=this.tokenCacheService.getParsedTokens();return t?this.authService.isAuthenticated(t):!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)}handleError(e,t){const r={message:e instanceof Error?e.message:`${t} failed`,originalError:e,code:e instanceof u?e.id:void 0};throw this.subscribeStore.notify(n.Error,r),e}async logOut(){try{await this.authService.logOut(),this.storageManager.deleteTokens(),this.tokenCacheService.setTokensCache(void 0),this.twoFactorService.clearPartialAuthState(),await this.submitSessionCheck(),this.subscribeStore.notify(n.SignOut,{})}catch(e){this.handleError(e,"Log out")}}federatedAuthWithPopup(e){this.authService.federatedAuthWithPopup(e)}federatedAuthWithRedirect(e){this.authService.federatedAuthWithRedirect(e)}reset(e){if(this.storageManager.deleteTokens(),this.tokenCacheService.setTokensCache(void 0),this.subscribeStore.notify(n.SignOut,{}),e){this.error=new Error(e);const t={message:e,code:"RESET_ERROR"};throw this.subscribeStore.notify(n.Error,t),this.error}}async refreshToken(){if(!this.tokenCacheService.parsedTokensCache?.refresh_token)throw new Error("No refresh token found");try{return await this.authService.refreshToken()}catch(e){throw e instanceof u||this.subscribeStore.notify(n.Error,{message:"Failed to refresh token",originalError:e}),e}}sendPasswordResetEmail(e){return this.authService.sendPasswordResetEmail(e)}async resetPassword(e,t){return await this.authService.resetPassword(e,t)}async getAppSettings(){try{return await this.appApi.getAppSettings()}catch(e){this.handleError(e,"Get app settings")}}async getSettingsAll(){try{return await this.settingApi.getSettingsAll()}catch(e){this.handleError(e,"Get all settings")}}async getPasswordPolicySettings(){try{return await this.settingApi.getPasswordPolicySettings()}catch(e){this.handleError(e,"Get password policy settings")}}async getPasskeySettings(){try{return await this.settingApi.getPasskeySettings()}catch(e){this.handleError(e,"Get passkey settings")}}async passkeyRegister(e){return await this.authService.passkeyRegister(e)}async passkeyAuthenticate(e){return await this.authService.passkeyAuthenticate(e)}setTokens(e){this.storageManager.saveTokens(e),this.tokenCacheService.setTokensCache(e),this.subscribeStore.notify(n.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,"Get user passkeys")}}async renameUserPasskey(e,t){try{return await this.userService.renameUserPasskey(e,t)}catch(r){this.handleError(r,"Rename user passkey")}}async deleteUserPasskey(e){try{return await this.userService.deleteUserPasskey(e)}catch(t){this.handleError(t,"Delete user passkey")}}async addUserPasskey(e){try{return await this.userService.addUserPasskey(e)}catch(t){this.handleError(t,"Add user passkey")}}async joinInvitation(e,t){try{const r=await this.tenant.joinInvitation(e,t);return r.scopes=t??this.scopes,this.storageManager.saveTokens(r),this.tokenCacheService.setTokensCache(r),r}catch(r){this.handleError(r,"Join invitation")}}async createTenant(e,t){try{const r=await this.tenant.createTenant(e);return t&&await this.refreshToken(),r}catch(r){this.handleError(r,"Create tenant")}}async requestInviteLink(e){try{return e.send_to_email===void 0&&(e.send_to_email=!0),await this.invitationService.requestInviteLink(e)}catch(t){this.handleError(t,"Request invite link")}}async getInvitations(e){try{return await this.invitationService.getInvitations(e)}catch(t){this.handleError(t,"Get invitations")}}async deleteInvitation(e){try{return await this.invitationService.deleteInvitation(e)}catch(t){this.handleError(t,"Delete invitation")}}async resendInvitation(e){try{return await this.invitationService.resendInvitation(e)}catch(t){this.handleError(t,"Resend invitation")}}async getInvitationLink(e){try{return await this.invitationService.getInvitationLink(e)}catch(t){this.handleError(t,"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,"Get 2FA status")}}async beginTwoFactorSetup(){try{return await this.twoFactorService.beginSetup()}catch(e){this.handleError(e,"Begin 2FA setup")}}async confirmTwoFactorSetup(e){try{return await this.twoFactorService.confirmSetup(e)}catch(t){this.handleError(t,"Confirm 2FA setup")}}async verifyTwoFactor(e){try{const t=await this.twoFactorService.verify(e);return this.storageManager.saveTokens(t),this.tokenCacheService.setTokensCache(t),this.subscribeStore.notify(n.SignIn,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),t}catch(t){this.handleError(t,"Verify 2FA")}}async useTwoFactorRecoveryCode(e){try{const t=await this.twoFactorService.useRecoveryCode(e);return this.storageManager.saveTokens(t),this.tokenCacheService.setTokensCache(t),this.subscribeStore.notify(n.SignIn,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),t}catch(t){this.handleError(t,"Use 2FA recovery code")}}async disableTwoFactor(e){try{return await this.twoFactorService.disable(e)}catch(t){this.handleError(t,"Disable 2FA")}}async regenerateTwoFactorRecoveryCodes(e){try{return await this.twoFactorService.regenerateRecoveryCodes(e)}catch(t){this.handleError(t,"Regenerate 2FA recovery codes")}}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()}};q.version=B;let $=q;class l extends Error{constructor(e){super(e.message),this.name="M2MError",this.code=e.code,this.status=e.status??400,this.errorUri=e.errorUri,this.rateLimitInfo=e.rateLimitInfo,this.headers=e.headers,this.cause=e.cause,this.timestamp=new Date().toISOString(),Error.captureStackTrace&&Error.captureStackTrace(this,l)}static fromOAuthError(e,t,r){const s=r?l.parseRateLimitHeaders(r):void 0;return new l({code:e.error,message:e.error_description??l.getDefaultMessage(e.error),status:t,errorUri:e.error_uri,rateLimitInfo:s,headers:r})}static fromError(e,t="server_error"){return new l({code:t,message:e.message||"An unexpected error occurred",status:500,cause:e})}static parseRateLimitHeaders(e){const t=e["x-ratelimit-limit"],r=e["x-ratelimit-remaining"],s=e["x-ratelimit-reset"]||e["retry-after"];if(t&&r&&s)return{limit:parseInt(t,10),remaining:parseInt(r,10),reset:parseInt(s,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){const 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}}class L extends l{constructor(e,t){super({code:"temporarily_unavailable",message:e,status:0,cause:t}),this.name="M2MNetworkError"}}class R extends l{constructor(e,t){super({code:"invalid_request",message:e,status:400,cause:t}),this.name="M2MTokenParseError"}}class x extends l{constructor(e){super({code:"invalid_request",message:e,status:400}),this.name="M2MConfigError"}}const Oe={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"},w={TOKEN_ENDPOINT:"/oauth2/token",TIMEOUT:1e4,RETRIES:3,RETRY_DELAY:1e3,REFRESH_THRESHOLD:30,CONTENT_TYPE:"application/x-www-form-urlencoded"};class $e{constructor(){this.cache=new Map}get(e){const 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,r){return this.cache.set(e,{token:t,expiresAt:Date.now()+r*1e3}),Promise.resolve()}delete(e){return this.cache.delete(e),Promise.resolve()}}const Le={shouldRetry(i,e){return e>=3?!1:i.code==="server_error"||i.code==="temporarily_unavailable"||i.code==="rate_limit_exceeded"||i.status!==void 0&&i.status>=500},getDelay(i){return Math.pow(2,i-1)*1e3}};class Ne{constructor(e){if(!e.url)throw new x("M2M client requires a URL");if(!e.clientId)throw new x("M2M client requires a clientId");if(!e.clientSecret)throw new x("M2M client requires a clientSecret");const 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??w.REFRESH_THRESHOLD,timeout:e.timeout??w.TIMEOUT,retries:e.retries??w.RETRIES,retryDelay:e.retryDelay??w.RETRY_DELAY,retryStrategy:e.retryStrategy,cache:e.cache,onTokenRequest:e.onTokenRequest,onTokenResponse:e.onTokenResponse,onError:e.onError},this.cache=e.cache??new $e,this.retryStrategy=e.retryStrategy??Le,this.tokenEndpoint=`${t}${w.TOKEN_ENDPOINT}`}getCacheKey(e,t){const r=e?.sort().join(",")||"",s=t?.sort().join(",")||"";return`m2m:${this.config.clientId}:${r}:${s}`}async getToken(e){const t=e?.scopes??this.config.scopes,r=e?.audience??this.config.audience,s=this.getCacheKey(t,r);if(!e?.forceRefresh){const o=await this.cache.get(s);if(o&&!this.isTokenExpired(o))return o}return this.requestToken(t,r,s)}async getValidToken(){const e=this.config.scopes,t=this.config.audience,r=this.getCacheKey(e,t),s=await this.cache.get(r);if(s){if(this.config.autoRefresh&&this.isTokenExpired(s,this.config.refreshThreshold))return this.requestToken(e,t,r);if(!this.isTokenExpired(s))return s}return this.requestToken(e,t,r)}async requestToken(e,t,r){const s={grant_type:"client_credentials",client_id:this.config.clientId,client_secret:this.config.clientSecret};e&&e.length>0&&(s.scope=e.join(" ")),t&&t.length>0&&(s.audience=t.join(" ")),this.config.onTokenRequest&&this.config.onTokenRequest({clientId:this.config.clientId,scopes:e??[],audience:t??[],timestamp:new Date().toISOString()});const o=await this.executeWithRetry(()=>this.doTokenRequest(s));return o.issued_at=Math.floor(Date.now()/1e3),r&&await this.cache.set(r,o,o.expires_in),this.config.onTokenResponse&&this.config.onTokenResponse(o),o}async doTokenRequest(e){const 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);const r=new AbortController,s=setTimeout(()=>r.abort(),this.config.timeout);try{const o=await fetch(this.tokenEndpoint,{method:"POST",headers:{"Content-Type":w.CONTENT_TYPE,Accept:"application/json"},body:t.toString(),signal:r.signal});clearTimeout(s);const a={};o.headers.forEach((h,g)=>{a[g.toLowerCase()]=h});const d=await o.json();if(!o.ok){const h=l.fromOAuthError({error:d.error||"server_error",error_description:d.error_description||d.message,error_uri:d.error_uri},o.status,a);throw this.config.onError&&this.config.onError({error:h.code,error_description:h.message}),h}return d}catch(o){throw clearTimeout(s),o instanceof Error&&o.name==="AbortError"?new L(`Request timed out after ${this.config.timeout}ms`):o instanceof TypeError&&o.message.includes("fetch")?new L(`Network error: ${o.message}`,o):o instanceof l?o:l.fromError(o instanceof Error?o:new Error(String(o)))}}async executeWithRetry(e){let t;for(let r=1;r<=this.config.retries;r++)try{return await e()}catch(s){if(!(s instanceof l))throw s;if(t=s,r<this.config.retries&&this.retryStrategy.shouldRetry({code:s.code,status:s.status},r)){const o=this.retryStrategy.getDelay(r);await this.sleep(o);continue}throw s}throw t??new l({code:"server_error",message:"Request failed after retries"})}sleep(e){return new Promise(t=>setTimeout(t,e))}getCachedToken(){const e=this.cache;if("cache"in e){const 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;const r=Math.floor(Date.now()/1e3),o=(e.issued_at??r-e.expires_in)+e.expires_in;return r>=o-t}parseToken(e){try{const t=e.split(".");if(t.length!==3)throw new R("Invalid JWT format: expected 3 parts");const r=t[1];if(!r)throw new R("Invalid JWT format: missing payload");const s=atob(r.replace(/-/g,"+").replace(/_/g,"/")),o=JSON.parse(s);return o.scopes&&typeof o.scopes=="string"?o.scopes=o.scopes.split(" "):o.scopes||(o.scopes=[]),o}catch(t){throw t instanceof R?t:new R(`Failed to parse token: ${t instanceof Error?t.message:"Unknown error"}`)}}clearCache(){const e=this.getCacheKey(this.config.scopes,this.config.audience);this.cache.delete(e)}async revokeToken(){const e=this.getCachedToken();if(!e)return;const t=`${this.config.url}/oauth2/revoke`,r=new URLSearchParams;r.append("token",e.access_token),r.append("client_id",this.config.clientId),r.append("client_secret",this.config.clientSecret);try{const s=await fetch(t,{method:"POST",headers:{"Content-Type":w.CONTENT_TYPE},body:r.toString()});if(!s.ok&&s.status!==200){const o=await s.json().catch(()=>({}));throw l.fromOAuthError({error:o.error||"server_error",error_description:o.error_description||"Token revocation failed"},s.status)}this.clearCache()}catch(s){throw s instanceof l?s:l.fromError(s instanceof Error?s:new Error(String(s)))}}get url(){return this.config.url}get clientId(){return this.config.clientId}get scopes(){return this.config.scopes}get audience(){return this.config.audience}}exports.APP_ID_HEADER_KEY=A;exports.AUTHORIZATION_HEADER_KEY=I;exports.AppAPI=oe;exports.AuthAPI=ne;exports.AuthService=pe;exports.CLIAuthAPI=Fe;exports.DEFAULT_GROUP_NAME=Ie;exports.DEFAULT_SCOPES=j;exports.DEVICE_ID_HEADER_KEY=Y;exports.DEVICE_TYPE_HEADER_KEY=H;exports.ERROR_MESSAGE_MAX_LENGTH=ee;exports.InvitationAPI=ae;exports.InvitationService=fe;exports.M2MClient=Ne;exports.M2MConfigError=x;exports.M2MError=l;exports.M2MErrorCodes=Oe;exports.M2MNetworkError=L;exports.M2MTokenParseError=R;exports.M2M_DEFAULTS=w;exports.MINIMAL_DEFAULT_SCOPES=_e;exports.OS=b;exports.PASSFLOW_CLOUD_URL=N;exports.POPUP_HEIGHT=z;exports.POPUP_POLL_INTERVAL_MS=W;exports.POPUP_TIMEOUT_MS=J;exports.POPUP_WIDTH=X;exports.Passflow=$;exports.PassflowAdminEndpointPaths=T;exports.PassflowEndpointPaths=c;exports.PassflowError=u;exports.PassflowEvent=n;exports.Providers=se;exports.RequestMethod=_;exports.SDK_VERSION=B;exports.SessionState=V;exports.SettingAPI=ce;exports.TOKEN_EXPIRY_BUFFER_SECONDS=K;exports.TenantAPI=he;exports.TenantService=ve;exports.TenantUserMembership=ke;exports.TokenCacheService=ye;exports.TokenDeliveryMode=S;exports.TokenType=p;exports.TwoFactorApiClient=de;exports.TwoFactorPolicy=ie;exports.TwoFactorService=Se;exports.USERNAME_MAX_LENGTH=Q;exports.USERNAME_MIN_LENGTH=Z;exports.UserAPI=ue;exports.UserService=me;exports.isTokenExpired=m;exports.isValidEmail=P;exports.isValidJWTFormat=F;exports.isValidPhoneNumber=D;exports.isValidUsername=ge;exports.parseToken=v;exports.pathWithParams=y;exports.sanitizeErrorMessage=le;
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import F from "axios";
2
2
  import { v4 as H } from "uuid";
3
3
  import { startRegistration as K, startAuthentication as j } from "@simplewebauthn/browser";
4
- const z = "0.7.0", X = {
4
+ const z = "0.8.0", X = {
5
5
  version: z
6
6
  }, C = "X-Passflow-Clientid", I = "Authorization", W = "X-Passflow-DeviceId", J = "X-Passflow-DeviceType", Z = X.version, Ne = ["id", "offline", "openid"], Q = ["id", "offline", "tenant", "email", "oidc", "openid", "access:tenant:all"], V = "https://auth.passflow.cloud", Ke = "default", ee = 500, te = 600, re = 100, se = 6e4, G = 30, ie = 3, oe = 30, ne = 200, ae = (i) => {
7
7
  const e = [];
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@passflow/core",
3
3
  "description": "Passflow JS SDK",
4
- "version": "0.7.0",
4
+ "version": "0.8.0",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "module": "./dist/index.mjs",