UNPKG

@kinde-oss/kinde-auth-react

Version:

Kinde React SDK for authentication

2 lines (1 loc) 29.9 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var ne=(e=>(e.email="email",e.profile="profile",e.openid="openid",e.offline_access="offline",e))(ne||{}),G=(e=>(e.none="none",e.create="create",e.login="login",e))(G||{}),J=(e=>(e.organizationDetails="organization_details",e.organizationMembers="organization_members",e.organizationPlanDetails="organization_plan_details",e.organizationPaymentDetails="organization_payment_details",e.organizationPlanSelection="organization_plan_selection",e.paymentDetails="payment_details",e.planSelection="plan_selection",e.planDetails="plan_details",e.profile="profile",e))(J||{}),oe=(e=>(e.organizationDetails="organization_details",e.organizationMembers="organization_members",e.organizationPlanDetails="organization_plan_details",e.organizationPaymentDetails="organization_payment_details",e.organizationPlanSelection="organization_plan_selection",e.profile="profile",e))(oe||{}),U=(e=>(e.logout="logout",e.login="login",e.register="registration",e.token="token",e.profile="profile",e))(U||{}),k=(e=>(e[e.refreshToken=0]="refreshToken",e[e.cookie=1]="cookie",e))(k||{});const B=e=>{const t=o=>btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");if(e instanceof ArrayBuffer){const o=new Uint8Array(e),a=String.fromCharCode(...o);return t(a)}const r=new TextEncoder().encode(e),n=String.fromCharCode(...r);return t(n)},L=(e=28)=>{if(crypto){const t=new Uint8Array(e/2);return crypto.getRandomValues(t),Array.from(t,be).join("")}else return xe(e)};function be(e){return e.toString(16).padStart(2,"0")}function xe(e=28){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let r="";const n=t.length;for(let o=0;o<e;o++)r+=t.charAt(Math.floor(Math.random()*n));return r}const Ee=e=>{e=e.split("?")[1];const t=new URLSearchParams(e);return{accessToken:t.get("access_token"),idToken:t.get("id_token"),expiresIn:+(t.get("expires_in")||0)}},F=e=>{let t=e.replace(/([^:]\/)\/+/g,"$1");return t.match(/^\/\/[^/?]+/)&&t.includes(".")?t=t.replace(/^\/\/\/+/,"//"):t.match(/^\/\/+/)&&(t=t.replace(/^\/\/+/,"/")),t!=="/"&&(t=t.replace(/\/$/,"")),t},ie=(e,t=!1)=>{const r=Array.isArray(e.audience)?e.audience.join(" "):e.audience||"",n={login_hint:e.loginHint,is_create_org:e.isCreateOrg?.toString(),connection_id:e.connectionId,redirect_uri:e.redirectURL?t?e.redirectURL:F(e.redirectURL):void 0,audience:r,scope:e.scope?.join(" ")||"email profile openid offline",prompt:e.prompt,lang:e.lang,org_code:e.orgCode,org_name:e.orgName,has_success_page:e.hasSuccessPage?.toString(),workflow_deployment_id:e.workflowDeploymentId,supports_reauth:e.supportsReauth?.toString(),plan_interest:e.planInterest,pricing_table_key:e.pricingTableKey,pages_mode:e.pagesMode};return Object.keys(n).forEach(o=>n[o]===void 0&&delete n[o]),n},H=e=>typeof e!="object"||e===null?e:Array.isArray(e)?e.map(t=>H(t)):Object.fromEntries(Object.entries(e).map(([t,r])=>[t.replace(/_([a-z])/g,(n,o)=>o.toUpperCase()),H(r)])),Ce=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gclid","click_id","hsa_acc","hsa_cam","hsa_grp","hsa_ad","hsa_src","hsa_tgt","hsa_kw","hsa_mt","hsa_net","hsa_ver","match_type","keyword","device","ad_group_id","campaign_id","creative","network","ad_position","fbclid","li_fat_id","msclkid","twclid","ttclid"],Re=async(e,t=U.login,r,n)=>{const o=`${e}/oauth2/auth`,a=v();if(r.reauthState)try{const c=H(JSON.parse(atob(r.reauthState)));r={...r,...c},delete r.reauthState}catch(c){const d=c instanceof Error?c.message:"Unknown error";throw new Error(`Error handing reauth state: ${d}`)}if(!r.clientId)throw new Error("Error generating auth URL: Client ID missing");const l={client_id:r.clientId,response_type:r.responseType||"code",...ie(r,n?.disableUrlSanitization)};r.state||(r.state=L(32)),a&&a.setSessionItem(i.state,r.state),l.state=r.state,r.nonce||(r.nonce=L(16)),l.nonce=r.nonce,a&&a.setSessionItem(i.nonce,r.nonce);let f="";if(r.codeChallenge)l.code_challenge=r.codeChallenge;else{const{codeVerifier:c,codeChallenge:d}=await Ue();f=c,a&&a.setSessionItem(i.codeVerifier,c),l.code_challenge=d}l.code_challenge_method="S256",r.codeChallengeMethod&&(l.code_challenge_method=r.codeChallengeMethod),!r.prompt&&t===U.register&&(l.prompt=G.create),r.properties&&Object.keys(r.properties).forEach(c=>{if(!Ce.includes(c)){console.warn("Unsupported Property for url generation: ",c);return}const d=r.properties?.[c];d!==void 0&&(l[c]=d)});const u=new URLSearchParams(l).toString();return{url:new URL(`${o}?${u}`),state:l.state,nonce:l.nonce,codeChallenge:l.code_challenge,codeVerifier:f}};async function Ue(){const e=L(52),t=new TextEncoder().encode(e);let r="";if(!crypto)r=B(btoa(e));else{const n=await crypto.subtle.digest("SHA-256",t);r=B(n)}return{codeVerifier:e,codeChallenge:r}}const P=()=>typeof window<"u";let R;function Z(e,t){if(N(),!P())throw new Error("setRefreshTimer requires a browser environment");if(e<=0)throw new Error("Timer duration must be positive");R=window.setTimeout(t,Math.min(e*1e3-1e4,864e5))}function N(){P()&&R!==void 0&&(window.clearTimeout(R),R=void 0)}const S={framework:"",frameworkVersion:"",sdkVersion:""},re=async()=>{await v()?.removeItems(i.state,i.nonce,i.codeVerifier)},se=()=>`${S.framework}/${S.sdkVersion}/${S.frameworkVersion}/Javascript`,Le=async({urlParams:e,domain:t,clientId:r,clientSecret:n,redirectURL:o,autoRefresh:a=!1,onRefresh:l})=>{const f=e.get("state"),u=e.get("code");if(!f||!u)return console.error("Invalid state or code"),{success:!1,error:"Invalid state or code"};const c=v();if(!c)return console.error("No active storage found"),{success:!1,error:"Authentication storage is not initialized"};(!S.framework||!S.frameworkVersion)&&console.warn("Framework and version not set. Please set the framework and version in the config object");const d=await c.getSessionItem(i.state);if(f!==d)return console.error("Invalid state"),{success:!1,error:`Invalid state; supplied ${f}, expected ${d}`};const m=await c.getSessionItem(i.codeVerifier);if(m===null)return console.error("Code verifier not found"),{success:!1,error:"Code verifier not found"};const T={"Content-type":"application/x-www-form-urlencoded; charset=UTF-8"};S.framework&&(T["Kinde-SDK"]=se());const A=!s.useInsecureForRefreshToken&&b(t)?{credentials:"include"}:{},C=new URLSearchParams({client_id:r,code:u,code_verifier:m,grant_type:"authorization_code",redirect_uri:o});n&&C.append("client_secret",n);const Pe={method:"POST",...A,headers:new Headers(T),body:C};let $;N();try{if($=await fetch(`${t}/oauth2/token`,Pe),!$?.ok){const h=await $.text();return console.error("Token exchange failed:",$.status,h),{success:!1,error:`Token exchange failed: ${$.status} - ${h}`}}}catch(h){return re(),console.error("Token exchange failed:",h),{success:!1,error:`Token exchange failed: ${h}`}}const p=await $.json(),te=g();if(te)try{await te.setItems({[i.accessToken]:p.access_token,[i.idToken]:p.id_token,[i.refreshToken]:p.refresh_token})}catch(h){return console.error("Failed to persist tokens to secure storage:",h),{success:!1,error:`Failed to persist tokens: ${h}`}}(s.useInsecureForRefreshToken||!b(t))&&c.setSessionItem(i.refreshToken,p.refresh_token),a&&Z(p.expires_in,async()=>{I({domain:t,clientId:r,onRefresh:l})}),re();const Ae=h=>(h.search="",h);if(P()){const h=Ae(new URL(window.location.toString()));window.history.replaceState(window.history.state,"",h)}return!p.access_token||!p.id_token||!p.refresh_token?{success:!1,error:"No access token received"}:{success:!0,[i.accessToken]:p.access_token,[i.idToken]:p.id_token,[i.refreshToken]:p.refresh_token}};function Me(e){const t=document.cookie.split("; ").find(r=>r.startsWith(`${e}=`));if(!t)return null;try{const r=t.split("=")[1];return r?decodeURIComponent(r):null}catch(r){return console.error(`Error parsing cookie ${e}:`,r),null}}const ze="_kbrte",Fe=async({domain:e,clientId:t})=>{if(!e)return{success:!1,error:"Domain is required for authentication check"};if(!t)return{success:!1,error:"Client ID is required for authentication check"};const r=g();if(r){const{[i.accessToken]:l,[i.idToken]:f,[i.refreshToken]:u}=await r.getItems(i.accessToken,i.idToken,i.refreshToken);if(l&&f&&u)return await ee({threshold:10})?await I({domain:e,clientId:t,refreshType:k.refreshToken}):{success:!0,accessToken:l,idToken:f,refreshToken:u}}const n=b(e),o=s.useInsecureForRefreshToken;let a=null;return n&&!o&&(a=Me(ze)),await I({domain:e,clientId:t,refreshType:a?k.cookie:k.refreshToken})},b=e=>!e.match(/^(?:https?:\/\/)?[a-zA-Z0-9][.-a-zA-Z0-9]*\.kinde\.com$/i);function j(e,t){return t<=0?[]:e.match(new RegExp(`.{1,${t}}`,"g"))||[]}var i=(e=>(e.accessToken="accessToken",e.idToken="idToken",e.refreshToken="refreshToken",e.state="state",e.nonce="nonce",e.codeVerifier="codeVerifier",e))(i||{}),M=(e=>(e.preWarning="preWarning",e.timeout="timeout",e))(M||{});class O{listeners=new Set;notificationScheduled=!1;notifyListeners(){this.listeners.size!==0&&this.scheduleNotification()}async scheduleNotification(){this.notificationScheduled||(this.notificationScheduled=!0,await new Promise(t=>{setTimeout(async()=>{await Promise.all(Array.from(this.listeners).map(r=>r())),this.notificationScheduled=!1,t()},0)}))}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}async setItems(t){await Promise.all(Object.entries(t).map(([r,n])=>this.setSessionItem(r,n)))}async getItems(...t){const r=t.map(async o=>{const a=await this.getSessionItem(o);return[o,a]}),n=await Promise.all(r);return Object.fromEntries(n)}async removeItems(...t){await Promise.all(t.map(r=>this.removeSessionItem(r)))}}class Ne extends O{asyncStore=!1;memCache={};destroySession(){this.memCache={},this.notifyListeners()}setSessionItem(t,r){if(this.removeSessionItem(t),typeof r=="string"){j(r,s.maxLength).forEach((n,o)=>{this.memCache[`${s.keyPrefix}${t}${o}`]=n}),this.notifyListeners();return}this.memCache[`${s.keyPrefix}${String(t)}0`]=r,this.notifyListeners()}getSessionItem(t){if(this.memCache[`${s.keyPrefix}${String(t)}0`]===void 0)return null;let r="",n=0,o=`${s.keyPrefix}${String(t)}${n}`;for(;this.memCache[o]!==void 0;)r+=this.memCache[o],n++,o=`${s.keyPrefix}${String(t)}${n}`;return r}removeSessionItem(t){for(const r in this.memCache)r.startsWith(`${s.keyPrefix}${String(t)}`)&&delete this.memCache[r];this.notifyListeners()}}function D(e){return new Promise((t,r)=>{chrome.storage.local.get([e],function(n){chrome.runtime.lastError?r(void 0):t(n[e])})})}class je extends O{asyncStore=!0;async destroySession(){await chrome.storage.local.clear(),this.notifyListeners()}async setSessionItem(t,r){if(await this.removeSessionItem(t),typeof r=="string"){const n=j(r,s.maxLength);await Promise.all(n.map((o,a)=>chrome.storage.local.set({[`${s.keyPrefix}${t}${a}`]:o}))),this.notifyListeners();return}await chrome.storage.local.set({[`${s.keyPrefix}${t}0`]:r}),this.notifyListeners()}async getSessionItem(t){let r="",n=0,o=`${s.keyPrefix}${String(t)}${n}`;for(;await D(`${s.keyPrefix}${String(t)}${n}`)!==void 0;)r+=await D(o),n++,o=`${s.keyPrefix}${String(t)}${n}`;return r}async removeSessionItem(t){let r=0;for(;await D(`${s.keyPrefix}${String(t)}${r}`)!==void 0;)await chrome.storage.local.remove(`${s.keyPrefix}${String(t)}${r}`),r++;this.notifyListeners()}}class Oe extends O{asyncStore=!1;constructor(){super(),s.useInsecureForRefreshToken&&console.warn("LocalStorage store should not be used in production")}internalItems=new Set;destroySession(){Array.from(this.internalItems).forEach(t=>this.removeSessionItem(t)),this.notifyListeners()}setSessionItem(t,r){if(this.removeSessionItem(t),this.internalItems.add(t),typeof r=="string"){j(r,s.maxLength).forEach((n,o)=>{localStorage.setItem(`${s.keyPrefix}${t}${o}`,n)}),this.notifyListeners();return}localStorage.setItem(`${s.keyPrefix}${t}0`,r),this.notifyListeners()}getSessionItem(t){if(localStorage.getItem(`${s.keyPrefix}${t}0`)===null)return null;let r="",n=0,o=`${s.keyPrefix}${String(t)}${n}`;for(;localStorage.getItem(o)!==null;)r+=localStorage.getItem(o),n++,o=`${s.keyPrefix}${String(t)}${n}`;return r}removeSessionItem(t){let r=0;for(;localStorage.getItem(`${s.keyPrefix}${String(t)}${r}`)!==null;)localStorage.removeItem(`${s.keyPrefix}${String(t)}${r}`),r++;this.internalItems.delete(t),this.notifyListeners()}}const s={keyPrefix:"kinde-",maxLength:2e3,useInsecureForRefreshToken:!1,activityTimeoutMinutes:void 0,activityTimeoutPreWarningMinutes:void 0,onActivityTimeout:void 0};let W=null,V=null,K=!1;const ae=()=>{if(K)return;const e=g()??v();if(!e)throw new Error("Session manager not found");if(!s.activityTimeoutMinutes)throw new Error("No activity timeout minutes set");if(s.activityTimeoutPreWarningMinutes!==void 0&&s.activityTimeoutPreWarningMinutes>=s.activityTimeoutMinutes)throw new Error("activityTimeoutPreWarningMinutes must be less than activityTimeoutMinutes");W&&clearTimeout(W),V&&clearTimeout(V),V=setTimeout(async()=>{K=!0;const t={accessToken:null,idToken:null,refreshToken:null};try{const n=await e.getItems(i.accessToken,i.idToken,i.refreshToken);t.accessToken=n[i.accessToken]??null,t.idToken=n[i.idToken]??null,t.refreshToken=n[i.refreshToken]??null}catch(n){console.error("Failed to capture tokens:",n)}const r=v();if(r&&r!==e)try{const n=await r.getItems(i.refreshToken);t.refreshToken=n[i.refreshToken]??null}catch(n){console.error("Failed to capture refresh token from insecure storage:",n)}K=!1;try{await e.destroySession()}catch(n){console.error("Failed to destroy secure session:",n)}if(r&&r!==e)try{await r.destroySession()}catch(n){console.error("Failed to destroy insecure session:",n)}try{s.onActivityTimeout?.(M.timeout,t)}catch(n){console.error("[activityTimeout] onActivityTimeout(timeout) threw:",n)}},s.activityTimeoutMinutes*60*1e3),s.activityTimeoutPreWarningMinutes!==void 0&&(W=setTimeout(()=>{try{s.onActivityTimeout?.(M.preWarning)}catch(t){console.error("[activityTimeout] onActivityTimeout(preWarning) threw:",t)}},s.activityTimeoutPreWarningMinutes*60*1e3))},Q=e=>{if(!e)throw new Error("Session manager not found");if(!s.activityTimeoutMinutes)return e;if(s.activityTimeoutPreWarningMinutes!==void 0&&s.activityTimeoutPreWarningMinutes>=s.activityTimeoutMinutes)throw new Error("activityTimeoutPreWarningMinutes must be less than activityTimeoutMinutes");const t={get(r,n){const o=r[n];return typeof o=="function"?(n!=="destroySession"&&ae(),o.bind(r)):o}};return new Proxy(e,t)};function De(e,t){if(!e)return null;const r=e.split(".");if(r.length!==3)return null;const n=r[1].replace(/-/g,"+").replace(/_/g,"/"),o=decodeURIComponent(atob(n).split("").map(a=>"%"+("00"+a.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(o)}const ce=e=>{if(!e)return null;const t=De(e);return t||console.warn("No decoded token found"),t},w=async(e=i.accessToken)=>{const t=g();if(!t)return null;const r=await t.getSessionItem(e==="accessToken"?i.accessToken:i.idToken);return ce(r)},_=(e=i.accessToken)=>{const t=g();if(!t)return null;if(t.asyncStore)throw new Error("Active storage is async-only. Use the async helpers.");const r=t.getSessionItem(e==="accessToken"?i.accessToken:i.idToken);return ce(r)},le=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return Array.from(new Set([...e,...t]));if(e&&typeof e=="object"&&t&&typeof t=="object"){const r={...e};for(const n of Object.keys(t))n in r?r[n]=le(r[n],t[n]):r[n]=t[n];return r}return t};async function z(e){const t=g();if(!t)throw new Error("No active storage found.");const r=await t.getSessionItem(i.accessToken);if(!r)throw new Error("Authentication token not found.");const n=await E("iss");if(!n?.value)throw new Error("Domain (iss claim) not found.");let o;try{o=await fetch(`${n.value}/${e}`,{method:"GET",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})}catch(a){throw new Error(`Failed to fetch from ${n.value}/${e}: ${a}`)}if(!o.ok)throw new Error(`API request failed with status ${o.status}`);return await o.json()}const x=async({url:e})=>{let t=[],r=await z(e);if(t=r.data,r.metadata?.has_more){let n=r.metadata.next_page_starting_after;for(;r.metadata.has_more;)r=await z(`${e}?starting_after=${n}`),t=le(t,r.data),n=r.metadata.next_page_starting_after}return t},ue=e=>{if(!e)return{orgCode:null,permissions:[]};const t=e.permissions||e["x-hasura-permissions"]||[];return{orgCode:e.org_code||e["x-hasura-org-code"],permissions:t}},fe=async e=>{if(e?.forceApi){const r=await x({url:"account_api/v1/permissions"});return{orgCode:r.org_code,permissions:r.permissions?.map(n=>n.key)||[]}}const t=await w();return ue(t)},We=e=>{if(e?.forceApi)throw new Error("forceApi cannot be used in sync mode");const t=_();return ue(t)},Ve=e=>typeof e=="object"&&e!==null&&"permission"in e&&"condition"in e,de=async e=>{if(!e||!e.permissions||e?.permissions?.length===0)return!0;const{permissions:t}=e;let r;try{r=await fe({forceApi:e.forceApi})}catch(n){return console.error("[hasPermissions] Error getting permissions",n),!1}return(await Promise.all(t.map(async n=>Ve(n)?r.permissions.find(o=>o===n.permission)?await n.condition({permissionKey:n.permission,orgCode:r.orgCode}):!1:!!r.permissions.find(o=>o===n)))).every(n=>n===!0)},me=e=>e?!e.roles&&!e["x-hasura-roles"]?(console.warn("No roles found in token, ensure roles have been included in the token customisation within the application settings"),[]):e.roles||e["x-hasura-roles"]:[],he=async e=>{const t=await E("roles");if(e?.forceApi||!t?.value)return(await x({url:"account_api/v1/roles"})).roles?.map(n=>({id:n.id,name:n.name,key:n.key}))||[];const r=await w();return me(r)},Ke=e=>{if(e?.forceApi)throw new Error("forceApi cannot be used in sync mode");const t=_();if(!t)throw new Error("Authentication token not found.");return me(t)},qe=e=>typeof e=="object"&&e!==null&&"role"in e&&"condition"in e,ge=async e=>{if(!e||!e.roles||e?.roles?.length===0)return!0;const{roles:t}=e;let r;try{r=await he({forceApi:e.forceApi})}catch(n){return console.error("[hasRoles] Error getting roles",n),!1}return(await Promise.all(t.map(async n=>{if(qe(n)){const o=r.find(a=>a.key===n.role);return o?await n.condition(o):!1}else return r.map(o=>o.key).includes(n)}))).every(n=>n===!0)},Be=async e=>{if(e?.forceApi)return(await x({url:"account_api/v1/feature_flags"})).feature_flags?.map(r=>({key:r.key,value:r.value,type:r.type}))||[];const t=await w();return He(t)},He=e=>{if(!e)return null;const t=e.feature_flags||e["x-hasura-feature-flags"];return t?Object.entries(t).map(([r,n])=>({key:r,value:n.v,type:n.t})):null},Ge=e=>typeof e=="object"&&e!==null&&"flag"in e&&"value"in e,pe=async e=>{if(!e||!e.featureFlags||e?.featureFlags?.length===0)return!0;const{featureFlags:t}=e;let r;try{r=await Be({forceApi:e.forceApi})}catch(n){return console.error("[hasFeatureFlags] Error getting feature flags",n),!1}return t.map(n=>{if(Ge(n)){const o=r?.find(a=>a.key===n.flag);return o!==void 0&&o.value===n.value}else return r?.find(o=>o.key===n)!==void 0}).every(n=>n===!0)},ye=async()=>{const e=await x({url:"account_api/v1/entitlements"});return{orgCode:e.org_code,plans:e.plans?.map(t=>({key:t.key,subscribedOn:t.subscribed_on}))||[],entitlements:e.entitlements?.map(t=>({id:t.id,fixedCharge:t.fixed_charge,priceName:t.price_name,unitAmount:t.unit_amount,featureKey:t.feature_key,featureName:t.feature_name,entitlementLimitMax:t.entitlement_limit_max,entitlementLimitMin:t.entitlement_limit_min}))||[]}},Je=e=>typeof e=="object"&&e!==null&&"entitlement"in e&&"condition"in e,we=async e=>{if(!e||!e.billingEntitlements||e?.billingEntitlements?.length===0)return!0;const{billingEntitlements:t}=e;let r;try{r=await ye()}catch(n){return console.error("[hasBillingEntitlements] Error getting entitlements",n),!1}return(await Promise.all(t.map(async n=>{if(Je(n)){const o=r.entitlements.find(a=>a.priceName===n.entitlement);return o?await n.condition(o):!1}else return r.entitlements.map(o=>o.priceName).includes(n)}))).every(n=>n===!0)},q=e=>e!==void 0&&typeof e=="object",Ze=async e=>{const t=[];return e.roles&&t.push(ge({roles:e.roles,forceApi:q(e.forceApi)?e.forceApi.roles:e.forceApi})),e.permissions&&t.push(de({permissions:e.permissions,forceApi:q(e.forceApi)?e.forceApi.permissions:e.forceApi})),e.featureFlags&&t.push(pe({featureFlags:e.featureFlags,forceApi:q(e.forceApi)?e.forceApi.featureFlags:e.forceApi})),e.billingEntitlements&&t.push(we({billingEntitlements:e.billingEntitlements})),(await Promise.all(t)).every(Boolean)},X=async(e="accessToken")=>w(e),Y=(e="accessToken")=>_(e),ke=(e,t)=>e?{name:t,value:e[t]}:null,E=async(e,t="accessToken")=>{const r=await X(t);return ke(r,e)},Qe=(e,t="accessToken")=>{const r=Y(t);return ke(r,e)},Xe=async()=>{const e=await w();return Te(e)},Ye=()=>{const e=_();return Te(e)},Te=e=>e?e.org_code||e["x-hasura-org-code"]:null,et=async(e=i.accessToken)=>{const t=g();return t&&await t.getSessionItem(e==="accessToken"?i.accessToken:i.idToken)||null},tt=(e=i.accessToken)=>{const t=g();if(!t)return null;if(t.asyncStore)throw new Error("Active storage is async-only. Use the async helpers.");return t.getSessionItem(e==="accessToken"?i.accessToken:i.idToken)||null},rt=async(e,t)=>{if(t?.forceApi){const n=(await x({url:"account_api/v1/feature_flags"})).feature_flags.find(o=>o.name===e);return n?n.value:null}const r=await w();return _e(r,e)},nt=(e,t)=>{if(t?.forceApi)throw new Error("forceApi cannot be used in sync mode");const r=_();return _e(r,e)},_e=(e,t)=>{if(!e)return null;const r=e.feature_flags||e["x-hasura-feature-flags"];return r?r[t]?.v??null:null},Se=e=>{if(!e)return null;const{sub:t}=e;return t?{id:e.sub,givenName:e.given_name,familyName:e.family_name,email:e.email,picture:e.picture}:(console.error("No sub in idToken"),null)},ot=async()=>{const e=await X("idToken");return Se(e)},it=()=>{const e=Y("idToken");return Se(e)},ve=(e,t)=>{if(!e)return{permissionKey:t,orgCode:null,isGranted:!1};const r=e.permissions||e["x-hasura-permissions"]||[],n=e.org_code||e["x-hasura-org-code"]||null;return{permissionKey:t,orgCode:n,isGranted:!!r.includes(t)}},st=async(e,t)=>{if(t?.forceApi)return z(`account_api/v1/permission/${encodeURIComponent(e)}`);const r=await w();return ve(r,e)},at=(e,t)=>{if(t?.forceApi)throw new Error("forceApi cannot be used in sync mode");const r=_();return ve(r,e)},ct=async()=>{const e=await w("idToken");return $e(e)},lt=()=>{const e=_("idToken");return $e(e)},$e=e=>e?!e.org_codes&&!e["x-hasura-org-codes"]?(console.warn("Org codes not found in token, ensure org codes have been included in the token customisation within the application settings"),null):e.org_codes||e["x-hasura-org-codes"]:null,ut=async e=>{try{const t=await ee({threshold:e?.expiredThreshold});return t&&e?.useRefreshToken?(await I({domain:e.domain,clientId:e.clientId})).success:!t}catch(t){return console.error("Error checking authentication:",t),!1}},ee=async e=>{try{const t=await w("accessToken");return t?t.exp?t.exp<Math.floor(Date.now()/1e3)+(e?.threshold||0):(console.error("Token does not have an expiry"),!0):!0}catch(t){return console.error("Error checking authentication:",t),!1}},I=async({domain:e,clientId:t,clientSecret:r,refreshType:n=k.refreshToken,onRefresh:o})=>{const a=d=>(o&&o(d),d);if(!e)return a({success:!1,error:"Domain is required for token refresh"});if(!t)return a({success:!1,error:"Client ID is required for token refresh"});let l="",f;if(s.useInsecureForRefreshToken||!b(e)?f=v():f=g(),n===k.refreshToken){if(!f)return a({success:!1,error:"No active storage found"});if(l=await f.getSessionItem(i.refreshToken),!l)return a({success:!1,error:"No refresh token found"})}N();let u,c;try{if(s.onRefreshHandler)u=await s.onRefreshHandler(n);else{const d=new URLSearchParams({...n===k.refreshToken&&{refresh_token:l},grant_type:"refresh_token",client_id:t});r&&d.append("client_secret",r);const m=await fetch(`${F(e)}/oauth2/token`,{method:"POST",...n===k.cookie&&{credentials:"include"},headers:{"Content-type":"application/x-www-form-urlencoded; charset=UTF-8"},body:d.toString()});if(!m.ok)return a({success:!1,error:"Failed to refresh token"});c=await m.json(),u={success:!0,[i.accessToken]:c.access_token,[i.idToken]:c.id_token,[i.refreshToken]:c.refresh_token}}if(u.accessToken){const d=g();if(!d)return a({success:!1,error:"No active storage found"});if(await d.setSessionItem(i.accessToken,u.accessToken),u.idToken&&await d.setSessionItem(i.idToken,u.idToken),f&&u.refreshToken&&await f.setSessionItem(i.refreshToken,u.refreshToken),P()){const m=Number((await E("exp"))?.value);if(Number.isFinite(m)||c?.expires_in){let T=0;if(!c?.expires_in){const A=Math.floor(Date.now()/1e3);T=Math.max(m-A,1)}Z(c?.expires_in||T,async()=>{I({domain:e,clientId:t,refreshType:n,onRefresh:o})})}}return a(u)}}catch(d){return a({success:!1,error:`No access token received: ${d}`})}return a({success:!1,error:"No access token received"})},ft=async e=>{const t=await z(`account_api/v1/entitlement/${encodeURIComponent(e)}`);return{orgCode:t.data.org_code,entitlement:{id:t.data.entitlement.id,fixedCharge:t.data.entitlement.fixed_charge,priceName:t.data.entitlement.price_name,unitAmount:t.data.entitlement.unit_amount,featureKey:t.data.entitlement.feature_key,featureName:t.data.entitlement.feature_name,entitlementLimitMax:t.data.entitlement.entitlement_limit_max,entitlementLimitMin:t.data.entitlement.entitlement_limit_min}}},y={secure:null,insecure:null},dt=e=>{if(s.activityTimeoutMinutes){y.secure=Q(e);return}y.secure=e},g=()=>y.secure||null,mt=()=>y.secure!==null,ht=()=>{y.secure=null},gt=e=>{if(s.activityTimeoutMinutes){y.insecure=Q(e);return}y.insecure=e},v=()=>y.insecure||y.secure||null,pt=()=>y.insecure!==null,yt=()=>{y.insecure=null},wt=async e=>(console.warn("Warning: generateProfileUrl is deprecated. Please use generatePortalUrl instead."),Ie({domain:e.domain,returnUrl:e.returnUrl,subNav:e.subNav}));function kt(e,t=[]){try{const r=new URL(e);return!t.includes(r.protocol)&&!!r.host}catch{return!1}}const Ie=async({domain:e,returnUrl:t,subNav:r})=>{const n=g();if(!n)throw new Error("generatePortalUrl: Active storage not found");const o=await n.getSessionItem(i.accessToken);if(!o)throw new Error("generatePortalUrl: Access Token not found");if(!e||typeof e!="string"){const u=await E("iss");if(!u?.value||typeof u.value!="string")throw new Error("generatePortalUrl: Unable to determine domain from access token");e=u.value}if(!kt(t,["ftp:","ws:"]))throw new Error("generatePortalUrl: returnUrl must be an absolute URL");const a=new URLSearchParams({subnav:r||J.profile,return_url:t}),l=await fetch(`${F(e)}/account_api/v1/portal_link?${a.toString()}`,{headers:{Authorization:`Bearer ${o}`}});if(!l.ok)throw new Error(`Failed to fetch profile URL: ${l.status} ${l.statusText}`);const f=await l.json();if(!f.url||typeof f.url!="string")throw new Error("Invalid URL received from API");try{return{url:new URL(f.url)}}catch(u){throw console.error(u),new Error(`Invalid URL format received from API: ${f.url}`)}},Tt=()=>window.self!==window.top,_t=async({url:e,popupOptions:t={},handleResult:r,forcePopup:n=!1})=>{Tt()||n?await St({url:e,popupOptions:t,handleResult:r}):document.location=e},St=async({url:e,popupOptions:t={},handleResult:r})=>{const{width:n=500,height:o=600,left:a=(window.screen.width-n)/2,top:l=(window.screen.height-o)/2}=t,f=window.open(e,"kinde_auth_popup",`width=${n},height=${o},left=${a},top=${l},scrollbars=yes,resizable=yes,toolbar=no,menubar=no,location=no,status=no`);if(!f)throw new Error("Popup was blocked by the browser");const u=()=>new Promise(c=>{const d=m=>{if(m.origin===window.location.origin&&m.data&&m.data.type==="KINDE_AUTH_RESULT"){window.removeEventListener("message",d);const T=new URLSearchParams;Object.entries(m.data.result).forEach(([A,C])=>{T.append(A,C)}),r?.(T).then(()=>c())}};window.addEventListener("message",d)});try{await u()}catch(c){throw new Error("Popup authentication failed: "+c)}return f},vt=()=>!P(),$t={__esModule:!0,default:async()=>(await Promise.resolve().then(()=>require("./expoSecureStore-D7t_Z1p2-CdgLfIAv.cjs"))).ExpoSecureStore};exports.ChromeStore=je;exports.ExpoSecureStore=$t;exports.IssuerRouteTypes=U;exports.LocalStorage=Oe;exports.MemoryStorage=Ne;exports.PortalPage=J;exports.ProfilePage=oe;exports.PromptTypes=G;exports.RefreshType=k;exports.Scopes=ne;exports.SessionBase=O;exports.StorageKeys=i;exports.TimeoutActivityType=M;exports.base64UrlEncode=B;exports.checkAuth=Fe;exports.clearActiveStorage=ht;exports.clearInsecureStorage=yt;exports.clearRefreshTimer=N;exports.exchangeAuthCode=Le;exports.extractAuthResults=Ee;exports.frameworkSettings=S;exports.generateAuthUrl=Re;exports.generateKindeSDKHeader=se;exports.generatePortalUrl=Ie;exports.generateProfileUrl=wt;exports.generateRandomString=L;exports.getActiveStorage=g;exports.getClaim=E;exports.getClaimSync=Qe;exports.getClaims=X;exports.getClaimsSync=Y;exports.getCurrentOrganization=Xe;exports.getCurrentOrganizationSync=Ye;exports.getDecodedToken=w;exports.getDecodedTokenSync=_;exports.getEntitlement=ft;exports.getEntitlements=ye;exports.getFlag=rt;exports.getFlagSync=nt;exports.getInsecureStorage=v;exports.getPermission=st;exports.getPermissionSync=at;exports.getPermissions=fe;exports.getPermissionsSync=We;exports.getRawToken=et;exports.getRawTokenSync=tt;exports.getRoles=he;exports.getRolesSync=Ke;exports.getUserOrganizations=ct;exports.getUserOrganizationsSync=lt;exports.getUserProfile=ot;exports.getUserProfileSync=it;exports.has=Ze;exports.hasActiveStorage=mt;exports.hasBillingEntitlements=we;exports.hasFeatureFlags=pe;exports.hasInsecureStorage=pt;exports.hasPermissions=de;exports.hasRoles=ge;exports.isAuthenticated=ut;exports.isClient=P;exports.isCustomDomain=b;exports.isServer=vt;exports.isTokenExpired=ee;exports.mapLoginMethodParamsForUrl=ie;exports.navigateToKinde=_t;exports.refreshToken=I;exports.sanitizeUrl=F;exports.sessionManagerActivityProxy=Q;exports.setActiveStorage=dt;exports.setInsecureStorage=gt;exports.setRefreshTimer=Z;exports.splitString=j;exports.storageSettings=s;exports.updateActivityTimestamp=ae;