@passflow/core 0.14.0 → 0.14.1

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.cjs ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O=require("axios"),qe=require("uuid"),z=require("@simplewebauthn/browser"),Ye="0.14.1",Be={version:Ye},A="X-Passflow-Clientid",I="Authorization",J="X-Passflow-DeviceId",Z="X-Passflow-DeviceType",Q=Be.version,He=["id","offline","openid"],ee=["id","offline","tenant","email","oidc","openid","access:tenant:all"],G="https://auth.passflow.cloud",je="default",te=500,re=600,se=100,ie=6e4,V=30,oe=3,ne=30,ae=200,ze=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 n=r.groups[o]||[];return{group:{id:o,name:r.group_names?.[o]??"unknown"},roles:n}}):[],s.tenantRoles=s.groups?.find(o=>o.group.id===r.root_group_id),e.push(s)}return{raw:i,tenants:e}};function Xe(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 We{constructor(e){this.storageManager=e}isTokenTypeExpired(e){const t=this.storageManager.getToken(e);if(!t)return!0;const r=m(t);return r?y(r):!0}parseTokenType(e){const t=this.storageManager.getToken(e);if(t)return m(t)}}function y(i,e=V){return Math.floor(Date.now()/1e3)+e>i.exp}function m(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=Xe(r),o=decodeURIComponent(s.split("").map(h=>"%"+("00"+h.charCodeAt(0).toString(16)).slice(-2)).join("")),n=JSON.parse(o);return n.membership=n.passflow_tm&&n.type!=="invite"?ze(n.passflow_tm):void 0,n}var k=(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))(k||{}),v=(i=>(i.JsonBody="json_body",i.Cookie="cookie",i.Mobile="mobile",i.BFF="bff",i))(v||{}),q=(i=>(i.Unknown="unknown",i.Valid="valid",i.Invalid="invalid",i))(q||{});class ce{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(v).includes(e)&&(this.mode=e,this.isInitializedFlag=!0)}catch{}}loadPersistedSessionState(){try{const e=this.storageManager.storage.getItem(this.SESSION_STATE_KEY);e&&Object.values(q).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 Y{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:n}=e;t===v.Cookie||t===v.BFF?r&&this.storage.setItem(this.ID_TOKEN_KEY,r):(r&&this.storage.setItem(this.getKeyForTokenType(k.id_token),r),s&&this.storage.setItem(this.getKeyForTokenType(k.access_token),s),o&&this.storage.setItem(this.getKeyForTokenType(k.refresh_token),o),n&&this.storage.setItem(this.scopes,n.join(",")))}getToken(e){const t=this.getKeyForTokenType(e);return this.storage.getItem(t)??void 0}getTokens(){const e=this.getDeliveryMode();if(e===v.Cookie||e===v.BFF){const r=this.storage.getItem(this.ID_TOKEN_KEY);return r?{id_token:r}:void 0}const t=this.storage.getItem(this.getKeyForTokenType(k.access_token));if(t)return{access_token:t,id_token:this.storage.getItem(this.getKeyForTokenType(k.id_token))??void 0,refresh_token:this.storage.getItem(this.getKeyForTokenType(k.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(k.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(k.id_token)),this.storage.removeItem(this.getKeyForTokenType(k.access_token)),this.storage.removeItem(this.getKeyForTokenType(k.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(v).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 he{constructor(e){this.storageManager=e??new Y}getDeviceId(){const e=this.storageManager.getDeviceId();if(!e){const t=this.generateUniqueDeviceId();return this.storageManager.setDeviceId(t),t}return e}generateUniqueDeviceId(){return qe.v4()}}class B extends Error{constructor(e="Authentication popup was closed"){super(e),this.name="PopupClosedError"}}class de{constructor(){this.passkeys={startRegistration:e=>z.startRegistration({optionsJSON:e}),startAuthentication:e=>z.startAuthentication({optionsJSON:e})}}get storage(){return typeof localStorage>"u"?{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}:localStorage}getCurrentUrl(){return typeof window>"u"?null:{href:window.location.href,origin:window.location.origin,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,hostname:window.location.hostname}}replaceUrl(e){typeof window>"u"||window.history.replaceState({},document.title,e)}navigateTo(e){typeof window>"u"||(window.location.href=e)}onForeground(e){if(typeof document>"u")return()=>{};const t=()=>{document.hidden||e()};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}onBackground(e){if(typeof document>"u")return()=>{};const t=()=>{document.hidden&&e()};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}onBeforeUnload(e){return typeof window>"u"?()=>{}:(window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e))}isInForeground(){return typeof document>"u"?!0:!document.hidden}openAuthUrl(e,t={}){const r=t.mode??"popup";if(r==="redirect")return window.location.href=e,new Promise(()=>{});if(r==="deeplink")return Promise.reject(new Error('openAuthUrl: "deeplink" mode is not supported on web. Use "popup" or "redirect" instead, or provide a native platform adapter.'));const s=t.width??te,o=t.height??re,n=t.expectedReturnOrigin??window.location.origin,h=window.open(e,"_blank",`width=${s},height=${o}`);return h?new Promise((d,u)=>{const g=Date.now(),f=setInterval(()=>{if(h.closed){clearInterval(f),u(new B);return}if(Date.now()-g>ie){clearInterval(f),h.close(),u(new Error("Authentication popup timed out"));return}try{if(h.location.href.startsWith(n)){const L=h.location.search,Ve=h.location.hash;clearInterval(f),h.close(),d({callbackSearch:L,callbackHash:Ve})}}catch{}},se)}):(window.location.href=e,new Promise(()=>{}))}btoa(e){return btoa(e)}atob(e){if(typeof window<"u"&&typeof window.atob=="function")return window.atob(e);if(typeof Buffer<"u")return Buffer.from(e,"base64").toString("utf-8");throw new Error("No Base64 decoding method available in this environment")}cookiesSupported(){if(typeof document>"u")return!1;try{document.cookie="passflow_test=1; SameSite=Lax";const e=document.cookie.indexOf("passflow_test=1")!==-1;return document.cookie="passflow_test=; expires=Thu, 01 Jan 1970 00:00:00 UTC",e}catch{return!1}}getDeviceType(){return"web"}}const C=new de,ue="insufficient_user_authentication",le="upgrade_required",X=/([A-Za-z0-9!#$%&'*+\-.^_`|~]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]*))/g,Je=i=>i.replace(/\\(.)/g,"$1"),Ze=i=>{const e={};X.lastIndex=0;for(const t of i.matchAll(X)){const r=t[1];if(!r)continue;const s=t[2],o=t[3];e[r.toLowerCase()]=s!==void 0?Je(s):o??""}return e},pe=i=>{const e=typeof i=="number"?i:Number.parseInt(String(i??""),10);return Number.isFinite(e)&&e>0?e:void 0},ge=(i,e)=>{if(!i||!/(^|[\s,])Bearer\b/i.test(i))return;const t=Ze(i);if(t.error===ue)return{acrValues:t.acr_values||void 0,maxAge:pe(t.max_age),status:e}},fe=(i,e)=>{if(!i||typeof i!="object")return;const t=i;if(t.error===le)return{acrValues:typeof t.acr_values=="string"&&t.acr_values?t.acr_values:void 0,maxAge:pe(t.max_age),status:e}},ke=(i,e,t)=>{if(!(i!==401&&i!==403))return ge(e("www-authenticate"),i)??fe(t,i)};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.TwoFactorSetupStart="/v2/user/2fa/setup/start",i.TwoFactorSetupComplete="/v2/user/2fa/setup/complete",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||{}),w=(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))(w||{});class l 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 me=(i=>(i.google="google",i.facebook="facebook",i))(me||{}),ve=(i=>(i.web="web",i.ios="ios",i.android="android",i))(ve||{});function Qe(i){return i}function T(i,e){let t=i;return Object.entries(e).forEach(([r,s])=>{t=t.replace(`:${r}`,s)}),t}var ye=(i=>(i.Disabled="disabled",i.Optional="optional",i.Required="required",i))(ye||{});const et=3,tt=1e3,rt=i=>ke(i.status,e=>{const t=i.headers?.[e]??i.headers?.[e.toLowerCase()];return Array.isArray(t)?t.join(", "):t},i.data)!==void 0;class E{constructor(e,t,r){this.refreshPromise=null,this.isRefreshing=!1,this.defaultHeaders={Accept:"application/json","Content-Type":"application/json"},this.nonAccessTokenEndpoints=["/auth/","/settings","/settings/"],this.protectedEndpoints=["logout","refresh"];const{url:s,appId:o,keyStoragePrefix:n}=e;this._platform=e.platform??C,this.url=s||G,this.storageManager=t??new Y({prefix:n??""}),this.deviceService=r??new he(this.storageManager),this.tokenService=new We(this.storageManager),this.tokenDeliveryManager=new ce(this.storageManager),o&&(this.appId=o,this.defaultHeaders={...this.defaultHeaders,[A]:o});const h=this.deviceService.getDeviceId();this.defaultHeaders={...this.defaultHeaders,[J]:h,[Z]:this._platform.getDeviceType()},this.detectCookieSupport(),this.instance=O.create({baseURL:this.url,headers:{...this.defaultHeaders}}),this.instance.interceptors.request.use(async d=>{if(this.isNonAuthEndpoint(d.url))return d;if(this.tokenDeliveryManager.isCookieMode()){d.withCredentials=!0;const g=this.storageManager.getCsrfToken();return g&&(d.headers["X-CSRF-Token"]=g),d}if(d.url?.includes("refresh")){if(this.isRefreshing){const g=new AbortController;return g.abort(),d.signal=g.signal,d}return d}const u=this.storageManager.getTokens();if(u?.access_token){const g=m(u.access_token);if(y(g,V)&&u.refresh_token)try{if(this.refreshPromise){const f=await this.refreshPromise;return f?.data?.access_token&&(d.headers[I]=`Bearer ${f.data.access_token}`),d}this.refreshPromise=this.refreshTokens();try{const f=await this.refreshPromise;return f?.data?.access_token&&(d.headers[I]=`Bearer ${f.data.access_token}`),d}finally{this.refreshPromise=null}}catch(f){return this.refreshPromise=null,this.isRefreshing=!1,this.storageManager.deleteTokens(),Promise.reject(f)}return d.headers[I]=`Bearer ${u.access_token}`,d}return d}),this.instance.interceptors.response.use(d=>d,async d=>(d.response?.status===401&&!rt(d.response)&&this.tokenDeliveryManager.setSessionInvalid(),d.response?.status===429?await this.handleRateLimitError(d):this.handleAxiosError(d)))}get origin(){return this._platform.getCurrentUrl()?.origin??""}isProtectedEndpoint(e){return this.protectedEndpoints.some(t=>e?.includes(t))}isNonAuthEndpoint(e){return this.nonAccessTokenEndpoints.some(t=>e?.includes(t))&&!this.isProtectedEndpoint(e)}detectCookieSupport(){if(!this._platform.cookiesSupported()&&this.tokenDeliveryManager.isCookieMode())throw new Error("Passflow SDK: Cookie delivery mode is configured but cookies are not supported in this environment. Use a platform adapter that supports cookies or configure the server to use JSON token delivery.")}async 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>=et)return Promise.reject(e);let n=tt*Math.pow(2,o);const h=e.response?.headers?.["retry-after"];if(h){const d=Number.parseInt(h,10);if(!Number.isNaN(d))n=d*1e3;else{const u=new Date(h);Number.isNaN(u.getTime())||(n=Math.max(0,u.getTime()-Date.now()))}}return await new Promise(d=>setTimeout(d,n)),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 l(s))}return Promise.reject(new l({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 Se{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 we{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?w.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,n={...e,create_tenant:o??!1,device:t,os:r},h=s?w.passkeyRegisterStart:c.passkeyRegisterStart;return this.axiosClient.post(h,n)}passkeyRegisterComplete(e,t,r,s=!1){const o={challenge_id:r,device:t,passkey_data:e},n=s?w.passkeyRegisterComplete:c.passkeyRegisterComplete;return this.axiosClient.post(n,o)}passkeyAuthenticateStart(e,t,r,s=!1){const o={...e,user_id:e.user_id??"",device:t,os:r},n=s?w.passkeyAuthenticateStart:c.passkeyAuthenticateStart;return this.axiosClient.post(n,o)}passkeyAuthenticateComplete(e,t,r,s=!1){const o={challenge_id:r,device:t,passkey_data:e},n=s?w.passkeyAuthenticateComplete:c.passkeyAuthenticateComplete;return this.axiosClient.post(n,o)}passkeyValidate(e,t,r,s=!1,o){const n={otp:e,device:t,challenge_id:r};let h=c.passkeyValidate;!o&&s&&(h=w.passkeyValidate);const d=o?{[A]:o}:{};return this.axiosClient.post(h,n,{headers:d})}}class st{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getCLIAuthStatus(e){const t=T(c.cliAuthStatus,{sessionId:e});return this.axiosClient.get(t)}completeCLIAuth(e){return this.axiosClient.post(c.cliAuthComplete,e)}}class Te{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=T(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=T(c.invitationDelete,{invitationID:e});return this.axiosClient.delete(t)}resendInvitation(e){const t=T(c.invitationResend,{invitationID:e});return this.axiosClient.post(t,{})}getInvitationLink(e){const t=T(c.invitationGetLink,{invitationID:e});return this.axiosClient.get(t)}}class Ee{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 _e{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`,n={user_id:r,role:s};return this.axiosClient.post(o,n)}removeUserRolesFromGroup(e,t,r,s){const o=`${c.tenantPath}/${e}/group/${t}/remove_roles`,n={user_id:r,roles:s};return this.axiosClient.post(o,n)}changeUserRoles(e,t,r,s){const o=`${c.tenantPath}/${e}/group/${t}/change`,n={user_id:r,roles:s};return this.axiosClient.post(o,n)}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 Ie{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||{},n=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:n}}}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)}startMethodSetup(e,t){return this.axiosClient.post(c.TwoFactorSetupStart,{...t,method:e})}completeMethodSetup(e,t){return this.axiosClient.post(c.TwoFactorSetupComplete,{...t,method:e})}removeMethod(e){const t=T(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=T(c.TwoFactorTrustedDeviceRevoke,{id:e});return this.axiosClient.delete(t)}}class be{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 n={passkey_display_name:s,passkey_username:o,relying_party_id:e,deviceId:t,os:r};return this.axiosClient.post(c.addUserPasskey,n)}addUserPasskeyComplete(e,t,r){return this.axiosClient.post(c.completeAddUserPasskey,{challenge_id:r,device:t,passkey_data:e})}}var a=(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))(a||{});class it{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 M(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 Ae(i){return i.replace(/<[^>]*>/g,"").substring(0,ae)}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 Ce(i){if(!i||typeof i!="string")return!1;const e=i.trim();return e.length<oe||e.length>ne?!1:/^[a-zA-Z0-9_-]+$/.test(e)}function F(i,e=6){return!i||typeof i!="string"?!1:(e===8?/^\d{8}$/:/^\d{6}$/).test(i)}function ot(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 Re{constructor(e,t,r,s,o,n,h,d,u,g,f,L=C){this.authApi=e,this.deviceService=t,this.storageManager=r,this.subscribeStore=s,this.tokenCacheService=o,this.scopes=n,this.createTenantForNewUser=h,this.url=d,this.sessionCallbacks=u,this.appId=g,this.platform=L,this.tokenExchangeConfig=f,this.tokenDeliveryManager=new ce(r),f?.enabled&&this.tokenDeliveryManager.setMode(v.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(a.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(a.Error,o),s}if("username"in e&&e.username&&!Ce(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(a.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(a.Error,o),s}this.subscribeStore.notify(a.SignInStart,{email:e.email});const t=this.deviceService.getDeviceId(),r=this.platform.getDeviceType();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(a.TwoFactorRequired,{email:e.email||"",challengeId:s.challenge_id||"",tfaToken:s.tfa_token||""}),s):(await this.processAuthResponse(s,e.scopes),this.subscribeStore.notify(a.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 l?s.id:void 0};throw this.subscribeStore.notify(a.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(a.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(a.Error,r),t}this.subscribeStore.notify(a.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(a.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 l?t.id:void 0};throw this.subscribeStore.notify(a.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(a.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(a.Error,o),s}this.subscribeStore.notify(a.SignInStart,{email:e.email}),e.scopes=e.scopes??this.scopes;const t=this.deviceService.getDeviceId(),r=this.platform.getDeviceType();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 l?s.id:void 0};throw this.subscribeStore.notify(a.Error,o),s}}async passwordlessSignInComplete(e){this.subscribeStore.notify(a.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(a.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 l?t.id:void 0};throw this.subscribeStore.notify(a.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(k.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(a.SignOut,{})}async refreshToken(){if(this.subscribeStore.notify(a.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(a.Refresh,{tokens:s,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(a.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(a.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(a.Refresh,{tokens:r,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(a.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 l?r.id:void 0};throw this.subscribeStore.notify(a.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(a.Error,s),r}}else{const r=new Error("No tokens found"),s={message:"No tokens found",originalError:r};throw this.subscribeStore.notify(a.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(a.Refresh,{tokens:r,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(a.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 l?r.id:void 0,details:O.isAxiosError(r)&&r.response?{status:r.response.status,data:r.response.data}:void 0};this.subscribeStore.notify(a.Error,s);const o=O.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(a.SessionExpired,{reason:"refresh_failed"})),r instanceof l?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 l?t.id:void 0};throw this.subscribeStore.notify(a.Error,r),t}}async resetPassword(e,t){this.subscribeStore.notify(a.SignInStart,{});const s=new URLSearchParams(this.platform.getCurrentUrl()?.search??"").get("token")??void 0,o=t??this.scopes;try{const n=await this.authApi.resetPassword(e,o,s);return await this.processAuthResponse(n,o),this.subscribeStore.notify(a.SignIn,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),n}catch(n){const h={message:n instanceof Error?n.message:"Password reset failed",originalError:n,code:n instanceof l?n.id:void 0};throw this.subscribeStore.notify(a.Error,h),n}}async passkeyRegister(e){if(!this.platform.passkeys)throw new Error("Passkeys are not supported on this platform");this.subscribeStore.notify(a.RegisterStart,{});const t=this.deviceService.getDeviceId(),r=this.platform.getDeviceType();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=this.platform.btoa(o.user.id);const n=await this.platform.passkeys.startRegistration(o);if(!n)throw new Error("Passkey registration was not completed");const h=await this.authApi.passkeyRegisterComplete(n,t,s,!this.appId);return await this.processAuthResponse(h,e.scopes),this.subscribeStore.notify(a.Register,{tokens:h,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),h}catch(s){const o={message:s instanceof Error?s.message:"Passkey registration failed",originalError:s,code:s instanceof l?s.id:void 0};throw this.subscribeStore.notify(a.Error,o),s}}async passkeyAuthenticate(e){if(!this.platform.passkeys)throw new Error("Passkeys are not supported on this platform");this.subscribeStore.notify(a.SignInStart,{});const t=this.deviceService.getDeviceId(),r=this.platform.getDeviceType();e.scopes=e.scopes??this.scopes;try{const{challenge_id:s,publicKey:o}=await this.authApi.passkeyAuthenticateStart(e,t,r,!this.appId),n=await this.platform.passkeys.startAuthentication(o);if(!n)throw new Error("Passkey authentication was not completed");const h=await this.authApi.passkeyAuthenticateComplete(n,t,s,!this.appId);return"access_token"in h&&(await this.processAuthResponse(h,e.scopes),this.subscribeStore.notify(a.SignIn,{tokens:h,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),h}catch(s){const o={message:s instanceof Error?s.message:"Passkey authentication failed",originalError:s,code:s instanceof l?s.id:void 0};throw this.subscribeStore.notify(a.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.platform.getCurrentUrl()?.origin??"",appId:this.appId,...e.invite_token?{invite_token:e.invite_token}:{},...e.create_tenant?{create_tenant:e.create_tenant.toString()}:{},...e.device?{device:e.device}:{}},o=new URL(t,this.url),n=new URLSearchParams(s);return o.search=n.toString(),o.toString()}async federatedAuthWithPopup(e){this.subscribeStore.notify(a.SignInStart,{provider:e.provider});const t=e.scopes??this.scopes,r=this.deviceService.getDeviceId(),s=this.createFederatedAuthUrl({...e,scopes:t,device:r});try{const o=await this.platform.openAuthUrl(s,{mode:"popup",expectedReturnOrigin:this.platform.getCurrentUrl()?.origin??""}),n=new URLSearchParams(o.callbackSearch),h=n.get("access_token")||"",d=n.get("refresh_token")||"",u=n.get("id_token")||"",g={access_token:h,refresh_token:d||void 0,id_token:u||void 0,scopes:t};await this.processAuthResponse(g,t),this.subscribeStore.notify(a.SignIn,{tokens:g,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.platform.navigateTo(this.platform.getCurrentUrl()?.origin??"")}catch(o){const n={message:o instanceof Error?o.message:"Authentication failed",code:o instanceof B?"POPUP_CLOSED":"AUTH_FAILED",originalError:o};this.subscribeStore.notify(a.Error,n)}}federatedAuthWithRedirect(e){this.subscribeStore.notify(a.SignInStart,{provider:e.provider});const t=e.scopes??this.scopes,r=this.deviceService.getDeviceId(),s=this.createFederatedAuthUrl({...e,scopes:t,device:r});this.platform.navigateTo(s)}authRedirectUrl(e={}){try{const{url:t,redirectUrl:r,scopes:s,appId:o}=e??{},n=new URL(t??this.url);n.pathname=(n.pathname.endsWith("/")?n.pathname:n.pathname+"/")+"web";const h=s??this.scopes,d={appId:o??this.appId??"",redirectto:r??this.platform.getCurrentUrl()?.href??"",scopes:h.join(",")},u=new URLSearchParams(d);return n.search=u.toString(),n.toString()}catch(t){const r={message:t instanceof Error?t.message:"Failed to create auth redirect URL",originalError:t};throw this.subscribeStore.notify(a.Error,r),t}}authRedirect(e={}){try{this.platform.navigateTo(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(a.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:!y(e.access_token)||e.refresh_token!==void 0&&!y(e.refresh_token)}catch(t){const r={message:t instanceof Error?t.message:"Failed to check authentication status",originalError:t};return this.subscribeStore.notify(a.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 l?s.message:"Session check failed",originalError:s};this.subscribeStore.notify(a.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=m(t.access_token);return y(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(a.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 nt{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 at(){return new nt}class Me{constructor(e){this.data=this.normalize(e)}normalize(e){const t=new Map,r=new Map,s=new Map,o=[];return e.groups?.forEach(n=>{r.set(n.id,{id:n.id,name:n.name,default:n.default??!1,updated_at:n.updated_at,created_at:n.created_at})}),e.roles?.forEach(n=>{s.set(n.id,{id:n.id,tenant_id:n.tenant_id,name:n.name})}),e.users_in_groups?.forEach(n=>{const h=n.user;h&&!t.has(h.id)&&t.set(h.id,{id:h.id,name:h.name??null,email:h.email??null,phone:h.phone??null}),h&&n.group_id&&r.has(n.group_id)&&o.push({userId:h.id,groupId:n.group_id,roleIds:n.roles?.map(d=>d.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 Pe{constructor(e,t,r){this.tenantApi=e,this.scopes=t,this.logger=r||at()}handlePassflowError(e,t){if(O.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 Me(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 De{constructor(e,t,r,s=C){this.storageManager=e,this.authApi=t,this.subscribeStore=r,this.platform=s,this.checkInterval=null,this.CHECK_INTERVAL=6e4,this.unsubscribeForeground=null,this.unsubscribeUnload=null,this.isRefreshing=!1,this.tokenExpiredFlag=!1,this.storageManager=e,this.authApi=t,this.setupLifecycleListeners()}initialize(){try{const e=this.storageManager.getTokens();if(!e)return;if(!e.access_token){this.setTokensCache(e),this.startTokenCheck();return}const t=m(e.access_token);y(t)?(this.tokenExpiredFlag=!0,this.stopTokenCheck(),this.subscribeStore.notify(a.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(a.Error,t),this.setTokensCache(void 0)}}async refreshTokensCache(e){if(!this.isRefreshing)try{this.isRefreshing=!0,this.subscribeStore.notify(a.RefreshStart,{});const t=await this.authApi.refreshToken(e?.refresh_token??"",e.scopes??[],e.access_token);this.setTokensCache(t),this.subscribeStore.notify(a.Refresh,{tokens:t,parsedTokens:this.getParsedTokens()}),this.subscribeStore.notify(a.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(a.Error,r),this.tokenExpiredFlag=!0,this.setTokensCache(void 0),this.stopTokenCheck(),this.storageManager.deleteTokens(),this.subscribeStore.notify(a.SessionExpired,{reason:"refresh_failed"})}finally{this.isRefreshing=!1}}startTokenCheck(){this.checkInterval&&clearInterval(this.checkInterval),!this.tokenExpiredFlag&&(this.setupLifecycleListeners(),this.checkInterval=setInterval(()=>{this.platform.isInForeground()&&(this.isRefreshing||this.tokenExpiredFlag||this.isExpired()&&!this.tokenExpiredFlag&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(a.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck()))},this.CHECK_INTERVAL))}setupLifecycleListeners(){this.unsubscribeForeground&&(this.unsubscribeForeground(),this.unsubscribeForeground=null),this.unsubscribeForeground=this.platform.onForeground(()=>{this.checkInterval&&!this.isRefreshing&&!this.tokenExpiredFlag&&this.isExpired()&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(a.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck())}),this.unsubscribeUnload||(this.unsubscribeUnload=this.platform.onBeforeUnload(()=>{this.destroy()}))}stopTokenCheck(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null),this.unsubscribeForeground&&(this.unsubscribeForeground(),this.unsubscribeForeground=null)}destroy(){this.stopTokenCheck(),this.unsubscribeUnload&&(this.unsubscribeUnload(),this.unsubscribeUnload=null)}setTokensCache(e){this.tokensCache=e,e?this.parsedTokensCache={access_token:e.access_token?m(e.access_token):void 0,id_token:e.id_token?m(e.id_token):void 0,refresh_token:e.refresh_token?m(e.refresh_token):void 0,scopes:e.scopes}: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=m(this.tokensCache.access_token);return y(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(a.Error,t);return}}getParsedTokens(){return this.parsedTokensCache}isExpired(){if(!this.tokensCache)return!0;if(!this.tokensCache.access_token)return!1;const e=m(this.tokensCache.access_token);return y(e)}}class Ue{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===a.TwoFactorRequired){const n=o;this.setPartialAuthState(n.email,n.challengeId,n.tfaToken)}}};this.subscribeStore.subscribe(r,[a.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(a.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(a.TwoFactorSetupStarted,{secret:e.secret}),e}catch(e){this.emitErrorAndThrow(e,"Begin 2FA setup")}}async confirmSetup(e){if(!F(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(a.TwoFactorEnabled,{recoveryCodes:t.recovery_codes,clearRecoveryCodes:()=>{t.recovery_codes.length=0}}),t}catch(t){this.emitErrorAndThrow(t,"Confirm 2FA setup")}}async verify(e){if(!F(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(a.TwoFactorVerified,{tokens:t}),t}catch(t){this.emitErrorAndThrow(t,"Verify 2FA code")}}async useRecoveryCode(e){try{const t=ot(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(a.TwoFactorRecoveryCodesExhausted,{tokens:r}):r.remaining_recovery_codes<=2&&this.subscribeStore.notify(a.TwoFactorRecoveryCodesLow,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(a.TwoFactorRecoveryUsed,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(a.TwoFactorVerified,{tokens:r}),r}catch(t){this.emitErrorAndThrow(t,"Use recovery code")}}async disable(e){if(!F(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(a.TwoFactorDisabled,{}),t}catch(t){this.emitErrorAndThrow(t,"Disable 2FA")}}async regenerateRecoveryCodes(e){if(!F(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(a.TwoFactorSetupMagicLinkValidated,{userId:t.userId,appId:t.appId,expiresIn:t.expiresIn||3600,sessionToken:t.sessionToken})):t.error&&this.subscribeStore.notify(a.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 startMethodSetup(e,t){try{const r=await this.twoFactorApi.startMethodSetup(e,t);return this.subscribeStore.notify(a.TwoFactorSetupStarted,{secret:"",method:e}),r}catch(r){this.emitErrorAndThrow(r,"Start 2FA method setup")}}async completeMethodSetup(e,t){try{const r=await this.twoFactorApi.completeMethodSetup(e,t);return this.subscribeStore.notify(a.TwoFactorEnabled,{recoveryCodes:[],clearRecoveryCodes:()=>{}}),r}catch(r){this.emitErrorAndThrow(r,"Complete 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(a.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(a.TwoFactorVerified,{tokens:{access_token:t.access_token,refresh_token:t.refresh_token}}),t.device_trusted&&this.subscribeStore.notify(a.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(a.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 xe{constructor(e,t,r=C){this.userAPI=e,this.deviceService=t,this.platform=r}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}={}){if(!this.platform.passkeys)throw new Error("Passkeys are not supported on this platform");const s=this.deviceService.getDeviceId(),o=this.platform.getDeviceType(),{challenge_id:n,publicKey:h}=await this.userAPI.addUserPasskeyStart({relyingPartyId:(e||this.platform.getCurrentUrl()?.hostname)??"",deviceId:s,os:o,passkeyDisplayName:r,passkeyUsername:t});h.user.id=this.platform.btoa(h.user.id);const d=await this.platform.passkeys.startRegistration(h);if(!d)throw new Error("Passkey registration was not completed");return await this.userAPI.addUserPasskeyComplete(d,s,n)}}const j=class j{constructor(e){this.doRefreshTokens=!1,this.session=async({createSession:o,expiredSession:n,doRefresh:h=!1})=>{this.createSessionCallback=o,this.expiredSessionCallback=n,this.doRefreshTokens=h,await this.submitSessionCheck()};const{url:t,appId:r,scopes:s}=e;this.url=t||G,this.appId=r,this.platform=e.platform??C,this.storageManager=new Y({prefix:e.keyStoragePrefix??"",storage:this.platform.storage}),this.deviceService=new he(this.storageManager),this.authApi=new we(e,this.storageManager,this.deviceService),this.appApi=new Se(e,this.storageManager,this.deviceService),this.userApi=new be(e,this.storageManager,this.deviceService),this.settingApi=new Ee(e,this.storageManager,this.deviceService),this.tenantApi=new _e(e,this.storageManager,this.deviceService),this.invitationApi=new Te(e,this.storageManager,this.deviceService),this.twoFactorApi=new Ie(e,this.storageManager,this.deviceService),this.subscribeStore=new it,this.tokenCacheService=new De(this.storageManager,this.authApi,this.subscribeStore,this.platform),this.scopes=s??ee,this.createTenantForNewUser=e.createTenantForNewUser??!1,this.authService=new Re(this.authApi,this.deviceService,this.storageManager,this.subscribeStore,this.tokenCacheService,this.scopes,this.createTenantForNewUser,this.url,{createSession:this.createSessionCallback,expiredSession:this.expiredSessionCallback},this.appId??"",e.tokenExchange,this.platform),this.userService=new xe(this.userApi,this.deviceService,this.platform),this.tenantService=new Pe(this.tenantApi,this.scopes),this.tenant=this.tenantService,this.invitationService=new Fe(this.invitationApi),this.twoFactorService=new Ue(this.twoFactorApi,this.subscribeStore),this.twoFactor=this.twoFactorService,e.parseQueryParams&&this.checkAndSetTokens(),this.setTokensToCacheFromLocalStorage()}get origin(){return this.platform.getCurrentUrl()?.origin??""}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 l?r.message:"Session check failed",originalError:r};this.subscribeStore.notify(a.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(){const e=this.platform.getCurrentUrl();let t=new URLSearchParams(e?.search??""),r=!1;if(!t.get("access_token")&&e?.hash){const u=new URLSearchParams(e.hash.substring(1));u.get("access_token")&&(t=u,r=!0)}const s=t.get("access_token"),o=t.get("refresh_token"),n=t.get("id_token"),h=t.get("scopes")?.split(",")??this.scopes;let d;if(s){if(!M(s)){const u={message:"Invalid access token format received",code:"INVALID_TOKEN_FORMAT"};this.subscribeStore.notify(a.Error,u),this.cleanupUrlParams(r,e);return}if(o&&!M(o)){const u={message:"Invalid refresh token format received",code:"INVALID_TOKEN_FORMAT"};this.subscribeStore.notify(a.Error,u),this.cleanupUrlParams(r,e);return}if(n&&!M(n)){const u={message:"Invalid ID token format received",code:"INVALID_TOKEN_FORMAT"};this.subscribeStore.notify(a.Error,u),this.cleanupUrlParams(r,e);return}return d={access_token:s,refresh_token:o??void 0,id_token:n??void 0,scopes:h},this.storageManager.clearDeliveryMode(),this.storageManager.saveTokens(d),this.tokenCacheService.setTokensCache(d),this.subscribeStore.notify(a.SignIn,{tokens:d,parsedTokens:this.getParsedTokens()}),this.submitSessionCheck(),this.cleanupUrlParams(r,e),this.error=void 0,d}else this.error=this.checkErrorsFromURL()}checkErrorsFromURL(){const t=new URLSearchParams(this.platform.getCurrentUrl()?.search??"").get("error");if(t){const r=Ae(t);return new Error(r)}}cleanupUrlParams(e=!1,t=null){const r=t??this.platform.getCurrentUrl();if(r)if(e)this.platform.replaceUrl(r.pathname+r.search);else{const s=new URLSearchParams(r.search);s.delete("access_token"),s.delete("refresh_token"),s.delete("id_token"),s.delete("client_challenge"),s.size>0?this.platform.replaceUrl(`${r.pathname}?${s.toString()}`):this.platform.replaceUrl(r.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 l?e.id:void 0};throw this.subscribeStore.notify(a.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(a.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(a.SignOut,{}),e){this.error=new Error(e);const t={message:e,code:"RESET_ERROR"};throw this.subscribeStore.notify(a.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 l||this.subscribeStore.notify(a.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(a.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(a.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(a.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()}};j.version=Q;let $=j;class p 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,p)}static fromOAuthError(e,t,r){const s=r?p.parseRateLimitHeaders(r):void 0;return new p({code:e.error,message:e.error_description??p.getDefaultMessage(e.error),status:t,errorUri:e.error_uri,rateLimitInfo:s,headers:r})}static fromError(e,t="server_error"){return new p({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 N extends p{constructor(e,t){super({code:"temporarily_unavailable",message:e,status:0,cause:t}),this.name="M2MNetworkError"}}class R extends p{constructor(e,t){super({code:"invalid_request",message:e,status:400,cause:t}),this.name="M2MTokenParseError"}}class U extends p{constructor(e){super({code:"invalid_request",message:e,status:400}),this.name="M2MConfigError"}}const ct={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"},S={TOKEN_ENDPOINT:"/oauth2/token",TIMEOUT:1e4,RETRIES:3,RETRY_DELAY:1e3,REFRESH_THRESHOLD:30,CONTENT_TYPE:"application/x-www-form-urlencoded"};class ht{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 dt={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 ut{constructor(e){if(!e.url)throw new U("M2M client requires a URL");if(!e.clientId)throw new U("M2M client requires a clientId");if(!e.clientSecret)throw new U("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??S.REFRESH_THRESHOLD,timeout:e.timeout??S.TIMEOUT,retries:e.retries??S.RETRIES,retryDelay:e.retryDelay??S.RETRY_DELAY,retryStrategy:e.retryStrategy,cache:e.cache,onTokenRequest:e.onTokenRequest,onTokenResponse:e.onTokenResponse,onError:e.onError},this.cache=e.cache??new ht,this.retryStrategy=e.retryStrategy??dt,this.tokenEndpoint=`${t}${S.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":S.CONTENT_TYPE,Accept:"application/json"},body:t.toString(),signal:r.signal});clearTimeout(s);const n={};o.headers.forEach((d,u)=>{n[u.toLowerCase()]=d});const h=await o.json();if(!o.ok){const d=p.fromOAuthError({error:h.error||"server_error",error_description:h.error_description||h.message,error_uri:h.error_uri},o.status,n);throw this.config.onError&&this.config.onError({error:d.code,error_description:d.message}),d}return h}catch(o){throw clearTimeout(s),o instanceof Error&&o.name==="AbortError"?new N(`Request timed out after ${this.config.timeout}ms`):o instanceof TypeError&&o.message.includes("fetch")?new N(`Network error: ${o.message}`,o):o instanceof p?o:p.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 p))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 p({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":S.CONTENT_TYPE},body:r.toString()});if(!s.ok&&s.status!==200){const o=await s.json().catch(()=>({}));throw p.fromOAuthError({error:o.error||"server_error",error_description:o.error_description||"Token revocation failed"},s.status)}this.clearCache()}catch(s){throw s instanceof p?s:p.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}}class b extends Error{constructor(e,t,r=!1){super(t),this.name="UpgradeFactorError",this.factor=e,this.cancelled=r}}const Oe=(i,e)=>{const t=e?.trim();if(!t)throw new b(i,"A verification code is required");return t},Le={type:"totp",requiresPrepare:!1,input:"code",assert:async({code:i})=>({code:Oe("totp",i)})},$e={type:"recovery_codes",requiresPrepare:!1,input:"code",assert:async({code:i})=>({code:Oe("recovery_codes",i)})},Ne={type:"passkey",requiresPrepare:!0,input:"none",assert:async({prepared:i,platform:e})=>{if(!i?.webauthn)throw new b("passkey","The upgrade challenge carried no WebAuthn options");const t=e.passkeys;if(!t)throw new b("passkey","This platform does not support passkeys");let r;try{r=await t.startAuthentication(i.webauthn)}catch(s){throw new b("passkey",s?.message||"Passkey verification was cancelled",!0)}if(!r)throw new b("passkey","Passkey verification was cancelled",!0);return{challenge_id:i.challengeId,credential:r}}},H=Object.freeze([Le,Ne,$e]),Ke=(i=H)=>new Map(i.map(e=>[e.type,e])),lt=3,pt={passkey:0,totp:1,email_otp:2,sms_otp:3,recovery_codes:9},gt=i=>{if(!i)return;const e=i.split(/\s+/).map(t=>Number.parseInt(t,10)).filter(t=>Number.isFinite(t));return e.length>0?Math.min(...e):void 0},W=(i,e)=>{const t=pt[i.type]??5,r=e!==void 0&&e>=lt,s=i.type==="passkey";return(r&&!s?100:0)+t},Ge=(i,e)=>{const t=gt(e.acrValues);return[...i].sort((r,s)=>W(r,t)-W(s,t))};class K extends Error{constructor(){super("Upgrade authentication was cancelled"),this.name="UpgradeCancelledError"}}class x extends Error{constructor(e="No available authentication factor can satisfy this challenge"){super(e),this.name="UpgradeUnsatisfiableError"}}const ft=3;class kt{constructor(e){this.inFlight=null,this.transport=e.transport,this.prompt=e.prompt,this.platform=e.platform,this.available=e.factors??H,this.registry=Ke(this.available),this.maxAttempts=e.maxAttempts??ft}elevate(e){return this.inFlight?this.inFlight:(this.inFlight=this.run(e).finally(()=>{this.inFlight=null}),this.inFlight)}async run(e){const t=Ge(this.available,e);if(t.length===0)throw new x;let r;for(let s=0;s<this.maxAttempts;s++){const o=await this.prompt({challenge:e,factors:t,previousError:r});if(o.type==="cancel")throw new K;const n=this.registry.get(o.factor);if(!n){r=new x(`Unknown authentication factor: ${o.factor}`);continue}try{await this.proveAndCommit(n,o.code);return}catch(h){if(h instanceof b&&h.cancelled)throw new K;r=h}}throw r??new x("Upgrade authentication failed")}async proveAndCommit(e,t){const r=e.requiresPrepare?await this.transport.prepare(e.type):void 0,s=await e.assert({code:t,prepared:r,platform:this.platform});await this.transport.commit(e.type,s)}}exports.APP_ID_HEADER_KEY=A;exports.AUTHORIZATION_HEADER_KEY=I;exports.AppAPI=Se;exports.AuthAPI=we;exports.AuthService=Re;exports.CLIAuthAPI=st;exports.DEFAULT_GROUP_NAME=je;exports.DEFAULT_SCOPES=ee;exports.DEFAULT_UPGRADE_FACTORS=H;exports.DEVICE_ID_HEADER_KEY=J;exports.DEVICE_TYPE_HEADER_KEY=Z;exports.ERROR_MESSAGE_MAX_LENGTH=ae;exports.INSUFFICIENT_USER_AUTHENTICATION=ue;exports.InvitationAPI=Te;exports.InvitationService=Fe;exports.M2MClient=ut;exports.M2MConfigError=U;exports.M2MError=p;exports.M2MErrorCodes=ct;exports.M2MNetworkError=N;exports.M2MTokenParseError=R;exports.M2M_DEFAULTS=S;exports.MINIMAL_DEFAULT_SCOPES=He;exports.OS=ve;exports.PASSFLOW_CLOUD_URL=G;exports.POPUP_HEIGHT=re;exports.POPUP_POLL_INTERVAL_MS=se;exports.POPUP_TIMEOUT_MS=ie;exports.POPUP_WIDTH=te;exports.Passflow=$;exports.PassflowAdminEndpointPaths=w;exports.PassflowEndpointPaths=c;exports.PassflowError=l;exports.PassflowEvent=a;exports.PopupClosedError=B;exports.Providers=me;exports.RequestMethod=_;exports.SDK_VERSION=Q;exports.SessionState=q;exports.SettingAPI=Ee;exports.TOKEN_EXPIRY_BUFFER_SECONDS=V;exports.TenantAPI=_e;exports.TenantService=Pe;exports.TenantUserMembership=Me;exports.TokenCacheService=De;exports.TokenDeliveryMode=v;exports.TokenType=k;exports.TwoFactorApiClient=Ie;exports.TwoFactorPolicy=ye;exports.TwoFactorService=Ue;exports.UPGRADE_REQUIRED=le;exports.USERNAME_MAX_LENGTH=ne;exports.USERNAME_MIN_LENGTH=oe;exports.UpgradeCancelledError=K;exports.UpgradeController=kt;exports.UpgradeFactorError=b;exports.UpgradeUnsatisfiableError=x;exports.UserAPI=be;exports.UserService=xe;exports.WebAdapter=de;exports.factorRegistry=Ke;exports.getOSFromDeviceType=Qe;exports.isTokenExpired=y;exports.isValidEmail=P;exports.isValidJWTFormat=M;exports.isValidPhoneNumber=D;exports.isValidUsername=Ce;exports.parseChallengeBody=fe;exports.parseChallengeHeader=ge;exports.parseToken=m;exports.parseUpgradeChallenge=ke;exports.passkeyFactor=Ne;exports.pathWithParams=T;exports.recoveryCodesFactor=$e;exports.sanitizeErrorMessage=Ae;exports.selectFactors=Ge;exports.totpFactor=Le;exports.webAdapter=C;
2
+ //# sourceMappingURL=index.cjs.map