@kinde-oss/kinde-auth-react
Version:
Kinde React SDK for authentication
1,116 lines (1,115 loc) • 31.2 kB
JavaScript
var J = /* @__PURE__ */ ((e) => (e.email = "email", e.profile = "profile", e.openid = "openid", e.offline_access = "offline", e))(J || {}), M = /* @__PURE__ */ ((e) => (e.none = "none", e.create = "create", e.login = "login", e))(M || {}), K = /* @__PURE__ */ ((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))(K || {}), W = /* @__PURE__ */ ((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))(W || {}), E = /* @__PURE__ */ ((e) => (e.logout = "logout", e.login = "login", e.register = "registration", e.token = "token", e.profile = "profile", e))(E || {}), k = /* @__PURE__ */ ((e) => (e[e.refreshToken = 0] = "refreshToken", e[e.cookie = 1] = "cookie", e))(k || {});
const O = (e) => {
const r = (o) => btoa(o).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
if (e instanceof ArrayBuffer) {
const o = new Uint8Array(e), a = String.fromCharCode(...o);
return r(a);
}
const t = new TextEncoder().encode(e), n = String.fromCharCode(...t);
return r(n);
}, C = (e = 28) => {
if (crypto) {
const r = new Uint8Array(e / 2);
return crypto.getRandomValues(r), Array.from(r, Z).join("");
} else
return Y(e);
};
function Z(e) {
return e.toString(16).padStart(2, "0");
}
function Y(e = 28) {
const r = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let t = "";
const n = r.length;
for (let o = 0; o < e; o++)
t += r.charAt(Math.floor(Math.random() * n));
return t;
}
const ve = (e) => {
e = e.split("?")[1];
const r = new URLSearchParams(e);
return {
accessToken: r.get("access_token"),
idToken: r.get("id_token"),
expiresIn: +(r.get("expires_in") || 0)
};
}, z = (e) => e.replace(/\/$/, ""), Q = (e, r = !1) => {
const t = 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 ? r ? e.redirectURL : z(e.redirectURL) : void 0,
audience: t,
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;
}, R = (e) => typeof e != "object" || e === null ? e : Array.isArray(e) ? e.map((r) => R(r)) : Object.fromEntries(
Object.entries(e).map(([r, t]) => [
r.replace(/_([a-z])/g, (n, o) => o.toUpperCase()),
R(t)
])
), X = [
// UTM tags
"utm_source",
"utm_medium",
"utm_campaign",
"utm_content",
"utm_term",
// Google Ads smart campaign tracking
"gclid",
"click_id",
"hsa_acc",
"hsa_cam",
"hsa_grp",
"hsa_ad",
"hsa_src",
"hsa_tgt",
"hsa_kw",
"hsa_mt",
"hsa_net",
"hsa_ver",
// Marketing category
"match_type",
"keyword",
"device",
"ad_group_id",
"campaign_id",
"creative",
"network",
"ad_position",
"fbclid",
"li_fat_id",
"msclkid",
"twclid",
"ttclid"
], $e = async (e, r = E.login, t, n) => {
const o = `${e}/oauth2/auth`, a = x();
if (t.reauthState)
try {
const u = R(
JSON.parse(atob(t.reauthState))
);
t = {
...t,
...u
}, delete t.reauthState;
} catch (u) {
const m = u instanceof Error ? u.message : "Unknown error";
throw new Error(`Error handing reauth state: ${m}`);
}
if (!t.clientId)
throw new Error("Error generating auth URL: Client ID missing");
const i = {
client_id: t.clientId,
response_type: t.responseType || "code",
...Q(t, n?.disableUrlSanitization)
};
t.state || (t.state = C(32)), a && a.setSessionItem(s.state, t.state), i.state = t.state, t.nonce || (t.nonce = C(16)), i.nonce = t.nonce, a && a.setSessionItem(s.nonce, t.nonce);
let f = "";
if (t.codeChallenge)
i.code_challenge = t.codeChallenge;
else {
const { codeVerifier: u, codeChallenge: m } = await ee();
f = u, a && a.setSessionItem(s.codeVerifier, u), i.code_challenge = m;
}
i.code_challenge_method = "S256", t.codeChallengeMethod && (i.code_challenge_method = t.codeChallengeMethod), !t.prompt && r === E.register && (i.prompt = M.create), t.properties && Object.keys(t.properties).forEach((u) => {
if (!X.includes(u)) {
console.warn("Unsupported Property for url generation: ", u);
return;
}
const m = t.properties?.[u];
m !== void 0 && (i[u] = m);
});
const l = new URLSearchParams(i).toString();
return {
url: new URL(`${o}?${l}`),
state: i.state,
nonce: i.nonce,
codeChallenge: i.code_challenge,
codeVerifier: f
};
};
async function ee() {
const e = C(52), r = new TextEncoder().encode(e);
let t = "";
if (!crypto)
t = O(btoa(e));
else {
const n = await crypto.subtle.digest("SHA-256", r);
t = O(n);
}
return { codeVerifier: e, codeChallenge: t };
}
let I;
function q(e, r) {
if (L(), typeof window > "u")
throw new Error("setRefreshTimer requires a browser environment");
if (e <= 0)
throw new Error("Timer duration must be positive");
I = window.setTimeout(
r,
Math.min(e * 1e3 - 1e4, 864e5)
);
}
function L() {
I !== void 0 && (window.clearTimeout(I), I = void 0);
}
const v = {
framework: "",
frameworkVersion: "",
sdkVersion: ""
}, V = async () => {
await x()?.removeItems(
s.state,
s.nonce,
s.codeVerifier
);
}, re = () => `${v.framework}/${v.sdkVersion}/${v.frameworkVersion}/Javascript`, Se = async ({
urlParams: e,
domain: r,
clientId: t,
redirectURL: n,
autoRefresh: o = !1,
onRefresh: a
}) => {
const i = e.get("state"), f = e.get("code");
if (!i || !f)
return console.error("Invalid state or code"), {
success: !1,
error: "Invalid state or code"
};
const l = x();
if (!l)
return console.error("No active storage found"), {
success: !1,
error: "Authentication storage is not initialized"
};
(!v.framework || !v.frameworkVersion) && console.warn(
"Framework and version not set. Please set the framework and version in the config object"
);
const u = await l.getSessionItem(s.state);
if (i !== u)
return console.error("Invalid state"), {
success: !1,
error: `Invalid state; supplied ${i}, expected ${u}`
};
const m = await l.getSessionItem(
s.codeVerifier
);
if (m === null)
return console.error("Code verifier not found"), {
success: !1,
error: "Code verifier not found"
};
const y = {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
};
v.framework && (y["Kinde-SDK"] = re());
const S = {
method: "POST",
...!c.useInsecureForRefreshToken && T(r) ? {
credentials: "include"
} : {},
headers: new Headers(y),
body: new URLSearchParams({
client_id: t,
code: f,
code_verifier: m,
grant_type: "authorization_code",
redirect_uri: n
})
};
let g;
L();
try {
if (g = await fetch(`${r}/oauth2/token`, S), !g?.ok) {
const w = await g.text();
return console.error("Token exchange failed:", g.status, w), {
success: !1,
error: `Token exchange failed: ${g.status} - ${w}`
};
}
} catch (w) {
return V(), console.error("Token exchange failed:", w), {
success: !1,
error: `Token exchange failed: ${w}`
};
}
const d = await g.json(), D = _();
D && D.setItems({
[s.accessToken]: d.access_token,
[s.idToken]: d.id_token,
[s.refreshToken]: d.refresh_token
}), (c.useInsecureForRefreshToken || !T(r)) && l.setSessionItem(s.refreshToken, d.refresh_token), o && q(d.expires_in, async () => {
b({ domain: r, clientId: t, onRefresh: a });
}), V();
const H = ((w) => (w.search = "", w))(new URL(window.location.toString()));
return window.history.replaceState(window.history.state, "", H), !d.access_token || !d.id_token || !d.refresh_token ? {
success: !1,
error: "No access token received"
} : {
success: !0,
[s.accessToken]: d.access_token,
[s.idToken]: d.id_token,
[s.refreshToken]: d.refresh_token
};
};
function te(e) {
const r = document.cookie.split("; ").find((t) => t.startsWith(`${e}=`));
if (!r) return null;
try {
const t = r.split("=")[1];
return t ? decodeURIComponent(t) : null;
} catch (t) {
return console.error(`Error parsing cookie ${e}:`, t), null;
}
}
const ne = "_kbrte", Ie = async ({
domain: e,
clientId: r
}) => {
if (!e)
return {
success: !1,
error: "Domain is required for authentication check"
};
if (!r)
return {
success: !1,
error: "Client ID is required for authentication check"
};
const t = T(e), n = c.useInsecureForRefreshToken;
let o = null;
return t && !n && (o = te(ne)), await b({
domain: e,
clientId: r,
refreshType: o ? k.cookie : k.refreshToken
});
}, T = (e) => !e.match(
/^(?:https?:\/\/)?[a-zA-Z0-9][.-a-zA-Z0-9]*\.kinde\.com$/i
);
function j(e, r) {
return r <= 0 ? [] : e.match(new RegExp(`.{1,${r}}`, "g")) || [];
}
var s = /* @__PURE__ */ ((e) => (e.accessToken = "accessToken", e.idToken = "idToken", e.refreshToken = "refreshToken", e.state = "state", e.nonce = "nonce", e.codeVerifier = "codeVerifier", e))(s || {});
class N {
async setItems(r) {
await Promise.all(
Object.entries(r).map(
([t, n]) => this.setSessionItem(t, n)
)
);
}
async removeItems(...r) {
await Promise.all(
r.map((t) => this.removeSessionItem(t))
);
}
}
class Te extends N {
memCache = {};
/**
* Clears all items from session store.
* @returns {void}
*/
async destroySession() {
this.memCache = {};
}
/**
* Sets the provided key-value store to the memory cache.
* @param {string} itemKey
* @param {unknown} itemValue
* @returns {void}
*/
async setSessionItem(r, t) {
if (await this.removeSessionItem(r), typeof t == "string") {
j(t, c.maxLength).forEach(
(n, o) => {
this.memCache[`${c.keyPrefix}${r}${o}`] = n;
}
);
return;
}
this.memCache[`${c.keyPrefix}${String(r)}0`] = t;
}
/**
* Gets the item for the provided key from the memory cache.
* @param {string} itemKey
* @returns {unknown | null}
*/
async getSessionItem(r) {
if (this.memCache[`${c.keyPrefix}${String(r)}0`] === void 0)
return null;
let t = "", n = 0, o = `${c.keyPrefix}${String(r)}${n}`;
for (; this.memCache[o] !== void 0; )
t += this.memCache[o], n++, o = `${c.keyPrefix}${String(r)}${n}`;
return t;
}
/**
* Removes the item for the provided key from the memory cache.
* @param {string} itemKey
* @returns {void}
*/
async removeSessionItem(r) {
for (const t in this.memCache)
t.startsWith(`${c.keyPrefix}${String(r)}`) && delete this.memCache[t];
}
}
function P(e) {
return new Promise((r, t) => {
chrome.storage.local.get([e], function(n) {
chrome.runtime.lastError ? t(void 0) : r(n[e]);
});
});
}
class be extends N {
/**
* Clears all items from session store.
* @returns {void}
*/
async destroySession() {
await chrome.storage.local.clear();
}
/**
* Sets the provided key-value store to the chrome.store.local.
* @param {string} itemKey
* @param {unknown} itemValue
* @returns {void}
*/
async setSessionItem(r, t) {
if (await this.removeSessionItem(r), typeof t == "string") {
j(t, c.maxLength).forEach(
async (n, o) => {
await chrome.storage.local.set({
[`${c.keyPrefix}${r}${o}`]: n
});
}
);
return;
}
await chrome.storage.local.set({
[`${c.keyPrefix}${r}0`]: t
});
}
/**
* Gets the item for the provided key from the chrome.store.local cache.
* @param {string} itemKey
* @returns {unknown | null}
*/
async getSessionItem(r) {
let t = "", n = 0, o = `${c.keyPrefix}${String(r)}${n}`;
for (; await P(
`${c.keyPrefix}${String(r)}${n}`
) !== void 0; )
t += await P(o), n++, o = `${c.keyPrefix}${String(r)}${n}`;
return t;
}
/**
* Removes the item for the provided key from the chrome.store.local cache.
* @param {string} itemKey
* @returns {void}
*/
async removeSessionItem(r) {
let t = 0;
for (; await P(
`${c.keyPrefix}${String(r)}${t}`
) !== void 0; )
await chrome.storage.local.remove(
`${c.keyPrefix}${String(r)}${t}`
), t++;
}
}
class xe extends N {
constructor() {
super(), c.useInsecureForRefreshToken && console.warn("LocalStorage store should not be used in production");
}
internalItems = /* @__PURE__ */ new Set();
/**
* Clears all items from session store.
* @returns {void}
*/
async destroySession() {
this.internalItems.forEach((r) => {
this.removeSessionItem(r);
});
}
/**
* Sets the provided key-value store to the localStorage cache.
* @param {V} itemKey
* @param {unknown} itemValue
* @returns {void}
*/
async setSessionItem(r, t) {
if (await this.removeSessionItem(r), this.internalItems.add(r), typeof t == "string") {
j(t, c.maxLength).forEach(
(n, o) => {
localStorage.setItem(
`${c.keyPrefix}${r}${o}`,
n
);
}
);
return;
}
localStorage.setItem(
`${c.keyPrefix}${r}0`,
t
);
}
/**
* Gets the item for the provided key from the localStorage cache.
* @param {string} itemKey
* @returns {unknown | null}
*/
async getSessionItem(r) {
if (localStorage.getItem(`${c.keyPrefix}${r}0`) === null)
return null;
let t = "", n = 0, o = `${c.keyPrefix}${String(r)}${n}`;
for (; localStorage.getItem(o) !== null; )
t += localStorage.getItem(o), n++, o = `${c.keyPrefix}${String(r)}${n}`;
return t;
}
/**
* Removes the item for the provided key from the localStorage cache.
* @param {V} itemKey
* @returns {void}
*/
async removeSessionItem(r) {
let t = 0;
for (; localStorage.getItem(
`${c.keyPrefix}${String(r)}${t}`
) !== null; )
localStorage.removeItem(
`${c.keyPrefix}${String(r)}${t}`
), t++;
this.internalItems.delete(r);
}
}
const c = {
/**
* The prefix to use for the storage keys.
*/
keyPrefix: "kinde-",
/**
* The maximum length of the storage.
*
* If the length is exceeded the items will be split into multiple storage items.
*/
maxLength: 2e3,
/**
* Use insecure storage for refresh token.
*
* Warning: This should only be used when you're not using a custom domain and no backend app to authenticate on.
*/
useInsecureForRefreshToken: !1
}, B = (e, r) => {
if (Array.isArray(e) && Array.isArray(r))
return Array.from(/* @__PURE__ */ new Set([...e, ...r]));
if (e && typeof e == "object" && r && typeof r == "object") {
const t = { ...e };
for (const n of Object.keys(r))
n in t ? t[n] = B(t[n], r[n]) : t[n] = r[n];
return t;
}
return r;
};
async function U(e) {
const r = _();
if (!r)
throw new Error("No active storage found.");
const t = await r.getSessionItem(s.accessToken);
if (!t)
throw new Error("Authentication token not found.");
const n = await F("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 ${t}`,
"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 $ = async ({
url: e
}) => {
let r = [], t = await U(e);
if (r = t.data, t.metadata?.has_more) {
let n = t.metadata.next_page_starting_after;
for (; t.metadata.has_more; )
t = await U(
`${e}?starting_after=${n}`
), r = B(r, t.data), n = t.metadata.next_page_starting_after;
}
return r;
}, oe = async (e) => {
if (e?.forceApi) {
const n = await $({
url: "account_api/v1/permissions"
});
return {
orgCode: n.org_code,
permissions: n.permissions?.map((o) => o.key) || []
};
}
const r = await p();
if (!r)
return {
orgCode: null,
permissions: []
};
const t = r.permissions || r["x-hasura-permissions"] || [];
return {
orgCode: r.org_code || r["x-hasura-org-code"],
permissions: t
};
}, se = (e) => typeof e == "object" && e !== null && "permission" in e && "condition" in e, ae = async (e) => {
if (!e || !e.permissions || e?.permissions?.length === 0)
return !0;
const { permissions: r } = e;
let t;
try {
t = await oe({
forceApi: e.forceApi
});
} catch (n) {
return console.error("[hasPermissions] Error getting permissions", n), !1;
}
return (await Promise.all(
r.map(async (n) => se(n) ? t.permissions.find(
(o) => o === n.permission
) ? await n.condition({
permissionKey: n.permission,
orgCode: t.orgCode
}) : !1 : !!t.permissions.find(
(o) => o === n
))
)).every((n) => n === !0);
}, ie = async (e) => {
const r = await F("roles");
if (e?.forceApi || !r?.value)
return (await $({
url: "account_api/v1/roles"
})).roles?.map((n) => ({
id: n.id,
name: n.name,
key: n.key
})) || [];
const t = await p();
return t ? !t.roles && !t["x-hasura-roles"] ? (console.warn(
"No roles found in token, ensure roles have been included in the token customisation within the application settings"
), []) : t.roles || t["x-hasura-roles"] : [];
}, ce = (e) => typeof e == "object" && e !== null && "role" in e && "condition" in e, le = async (e) => {
if (!e || !e.roles || e?.roles?.length === 0)
return !0;
const { roles: r } = e;
let t;
try {
t = await ie({ forceApi: e.forceApi });
} catch (n) {
return console.error("[hasRoles] Error getting roles", n), !1;
}
return (await Promise.all(
r.map(async (n) => {
if (ce(n)) {
const o = t.find(
(a) => a.key === n.role
);
return o ? await n.condition(o) : !1;
} else
return t.map((o) => o.key).includes(n);
})
)).every((n) => n === !0);
}, ue = async (e) => {
if (e?.forceApi)
return (await $({
url: "account_api/v1/feature_flags"
})).feature_flags?.map((n) => ({
key: n.key,
value: n.value,
type: n.type
})) || [];
const r = await p();
if (!r)
return null;
const t = r.feature_flags || r["x-hasura-feature-flags"];
return t ? Object.entries(t).map(([n, o]) => ({
key: n,
value: o.v,
type: o.t
})) : null;
}, fe = (e) => typeof e == "object" && e !== null && "flag" in e && "value" in e, de = async (e) => {
if (!e || !e.featureFlags || e?.featureFlags?.length === 0)
return !0;
const { featureFlags: r } = e;
let t;
try {
t = await ue({ forceApi: e.forceApi });
} catch (n) {
return console.error("[hasFeatureFlags] Error getting feature flags", n), !1;
}
return r.map((n) => {
if (fe(n)) {
const o = t?.find((a) => a.key === n.flag);
return o !== void 0 && o.value === n.value;
} else
return t?.find((o) => o.key === n) !== void 0;
}).every((n) => n === !0);
}, me = async () => {
const e = await $({
url: "account_api/v1/entitlements"
});
return {
orgCode: e.org_code,
plans: e.plans?.map((r) => ({
key: r.key,
subscribedOn: r.subscribed_on
})) || [],
entitlements: e.entitlements?.map((r) => ({
id: r.id,
fixedCharge: r.fixed_charge,
priceName: r.price_name,
unitAmount: r.unit_amount,
featureKey: r.feature_key,
featureName: r.feature_name,
entitlementLimitMax: r.entitlement_limit_max,
entitlementLimitMin: r.entitlement_limit_min
})) || []
};
}, he = (e) => typeof e == "object" && e !== null && "entitlement" in e && "condition" in e, pe = async (e) => {
if (!e || !e.billingEntitlements || e?.billingEntitlements?.length === 0)
return !0;
const { billingEntitlements: r } = e;
let t;
try {
t = await me();
} catch (n) {
return console.error("[hasBillingEntitlements] Error getting entitlements", n), !1;
}
return (await Promise.all(
r.map(async (n) => {
if (he(n)) {
const o = t.entitlements.find(
(a) => a.priceName === n.entitlement
);
return o ? await n.condition(o) : !1;
} else
return t.entitlements.map(
(o) => o.priceName
).includes(n);
})
)).every((n) => n === !0);
}, A = (e) => e !== void 0 && typeof e == "object", Pe = async (e) => {
const r = [];
return e.roles && r.push(
le({
roles: e.roles,
forceApi: A(e.forceApi) ? e.forceApi.roles : e.forceApi
})
), e.permissions && r.push(
ae({
permissions: e.permissions,
forceApi: A(e.forceApi) ? e.forceApi.permissions : e.forceApi
})
), e.featureFlags && r.push(
de({
featureFlags: e.featureFlags,
forceApi: A(e.forceApi) ? e.forceApi.featureFlags : e.forceApi
})
), e.billingEntitlements && r.push(
pe({
billingEntitlements: e.billingEntitlements
})
), (await Promise.all(r)).every(Boolean);
};
function ge(e, r) {
if (!e)
return null;
const t = e.split(".");
if (t.length !== 3)
return null;
const n = t[
1
/* body */
].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 p = async (e = s.accessToken) => {
const r = _();
if (!r)
return null;
const t = await r.getSessionItem(
e === "accessToken" ? s.accessToken : s.idToken
);
if (!t)
return null;
const n = ge(t);
return n || console.warn("No decoded token found"), n;
}, G = async (e = "accessToken") => p(e), F = async (e, r = "accessToken") => {
const t = await G(r);
return t ? {
name: e,
value: t[e]
} : null;
}, Ae = async () => {
const e = await p();
return e ? e.org_code || e["x-hasura-org-code"] : null;
}, Ee = async (e = s.accessToken) => {
const r = _();
return r && await r.getSessionItem(
e === "accessToken" ? s.accessToken : s.idToken
) || null;
}, Ce = async (e, r) => {
if (r?.forceApi) {
const o = (await $({
url: "account_api/v1/feature_flags"
})).feature_flags.find((a) => a.name === e);
return o ? o.value : null;
}
const t = await p();
if (!t)
return null;
const n = t.feature_flags || t["x-hasura-feature-flags"];
return n ? n[e]?.v ?? null : null;
}, Re = async () => {
const e = await G("idToken");
if (!e)
return null;
const { sub: r } = e;
return r ? {
id: e.sub,
givenName: e.given_name,
familyName: e.family_name,
email: e.email,
picture: e.picture
} : (console.error("No sub in idToken"), null);
}, Ue = async (e, r) => {
if (r?.forceApi)
return U(
`account_api/v1/permission/${encodeURIComponent(e)}`
);
const t = await p();
if (!t)
return {
permissionKey: e,
orgCode: null,
isGranted: !1
};
const n = t.permissions || [];
return {
permissionKey: e,
orgCode: t.org_code,
isGranted: !!n.includes(e)
};
}, ze = async () => {
const e = await p("idToken");
return 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;
}, Le = async (e) => {
try {
const r = await p("accessToken");
if (!r) return !1;
if (!r.exp)
return console.error("Token does not have an expiry"), !1;
const t = r.exp < Math.floor(Date.now() / 1e3);
return t && e?.useRefreshToken ? (await b({
domain: e.domain,
clientId: e.clientId
})).success : !t;
} catch (r) {
return console.error("Error checking authentication:", r), !1;
}
}, b = async ({
domain: e,
clientId: r,
refreshType: t = k.refreshToken,
onRefresh: n
}) => {
const o = (f) => (n && n(f), f);
if (!e)
return o({
success: !1,
error: "Domain is required for token refresh"
});
if (!r)
return o({
success: !1,
error: "Client ID is required for token refresh"
});
let a = "", i;
if (c.useInsecureForRefreshToken || !T(e) ? i = x() : i = _(), t === k.refreshToken) {
if (!i)
return o({
success: !1,
error: "No active storage found"
});
if (a = await i.getSessionItem(
s.refreshToken
), !a)
return o({
success: !1,
error: "No refresh token found"
});
}
L();
try {
const f = await fetch(`${z(e)}/oauth2/token`, {
method: "POST",
...t === k.cookie && { credentials: "include" },
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: new URLSearchParams({
...t === k.refreshToken && {
refresh_token: a
},
grant_type: "refresh_token",
client_id: r
}).toString()
});
if (!f.ok)
return o({
success: !1,
error: "Failed to refresh token"
});
const l = await f.json();
if (l.access_token) {
const u = _();
return u ? (q(l.expires_in, async () => {
b({ domain: e, clientId: r, refreshType: t, onRefresh: n });
}), i && (await u.setSessionItem(
s.accessToken,
l.access_token
), l.id_token && await u.setSessionItem(s.idToken, l.id_token), l.refresh_token && await i.setSessionItem(
s.refreshToken,
l.refresh_token
)), o({
success: !0,
[s.accessToken]: l.access_token,
[s.idToken]: l.id_token,
[s.refreshToken]: l.refresh_token
})) : o({
success: !1,
error: "No active storage found"
});
}
} catch (f) {
return o({
success: !1,
error: `No access token received: ${f}`
});
}
return o({
success: !1,
error: "No access token received"
});
}, h = {
secure: null,
insecure: null
}, je = (e) => {
h.secure = e;
}, _ = () => h.secure || null, Ne = () => h.secure !== null, Fe = () => {
h.secure = null;
}, De = (e) => {
h.insecure = e;
}, x = () => h.insecure || h.secure || null, Oe = () => h.insecure !== null, Ve = () => {
h.insecure = null;
}, Me = async (e) => (console.warn(
"Warning: generateProfileUrl is deprecated. Please use generatePortalUrl instead."
), ye({
domain: e.domain,
returnUrl: e.returnUrl,
subNav: e.subNav
}));
function we(e, r = []) {
try {
const t = new URL(e);
return !r.includes(t.protocol) && !!t.host;
} catch {
return !1;
}
}
const ye = async ({
domain: e,
returnUrl: r,
subNav: t
}) => {
const n = _();
if (!n)
throw new Error("generatePortalUrl: Active storage not found");
const o = await n.getSessionItem(
s.accessToken
);
if (!o)
throw new Error("generatePortalUrl: Access Token not found");
if (!e || typeof e != "string") {
const l = await F("iss");
if (!l?.value || typeof l.value != "string")
throw new Error(
"generatePortalUrl: Unable to determine domain from access token"
);
e = l.value;
}
if (!we(r, ["ftp:", "ws:"]))
throw new Error("generatePortalUrl: returnUrl must be an absolute URL");
const a = new URLSearchParams({
subnav: t || K.profile,
return_url: r
}), i = await fetch(
`${z(e)}/account_api/v1/portal_link?${a.toString()}`,
{
headers: {
Authorization: `Bearer ${o}`
}
}
);
if (!i.ok)
throw new Error(
`Failed to fetch profile URL: ${i.status} ${i.statusText}`
);
const f = await i.json();
if (!f.url || typeof f.url != "string")
throw new Error("Invalid URL received from API");
try {
return {
url: new URL(f.url)
};
} catch (l) {
throw console.error(l), new Error(`Invalid URL format received from API: ${f.url}`);
}
}, ke = () => window.self !== window.top, Ke = async ({
url: e,
popupOptions: r = {},
handleResult: t,
forcePopup: n = !1
}) => {
ke() || n ? await _e({
url: e,
popupOptions: r,
handleResult: t
}) : document.location = e;
}, _e = async ({
url: e,
popupOptions: r = {},
handleResult: t
}) => {
const {
width: n = 500,
height: o = 600,
left: a = (window.screen.width - n) / 2,
top: i = (window.screen.height - o) / 2
} = r, f = window.open(
e,
"kinde_auth_popup",
`width=${n},height=${o},left=${a},top=${i},scrollbars=yes,resizable=yes,toolbar=no,menubar=no,location=no,status=no`
);
if (!f)
throw new Error("Popup was blocked by the browser");
const l = () => new Promise((u) => {
const m = (y) => {
if (y.origin === window.location.origin && y.data && y.data.type === "KINDE_AUTH_RESULT") {
window.removeEventListener("message", m);
const S = new URLSearchParams();
Object.entries(y.data.result).forEach(([g, d]) => {
S.append(g, d);
}), t?.(S).then(() => u());
}
};
window.addEventListener("message", m);
});
try {
await l();
} catch (u) {
throw new Error("Popup authentication failed: " + u);
}
return f;
}, qe = {
__esModule: !0,
default: async () => (await import(
/* webpackIgnore: true */
"./expoSecureStore-ClB_OEoC-D7mupKas.js"
)).ExpoSecureStore
};
export {
ve as $,
be as A,
Oe as B,
Ie as C,
N as D,
xe as E,
ze as F,
Ke as G,
M as H,
Te as I,
qe as J,
ae as K,
Re as L,
F as M,
j as N,
le as O,
Pe as P,
J as Q,
Ce as R,
v as S,
$e as T,
C as U,
Fe as V,
G as W,
W as X,
Le as Y,
T as Z,
ye as _,
je as a,
Q as a0,
z as a1,
q as a2,
O as b,
c,
E as d,
ie as e,
Ae as f,
Se as g,
k as h,
s as i,
De as j,
Ve as k,
L as l,
Me as m,
p as n,
oe as o,
me as p,
K as q,
re as r,
x as s,
Ee as t,
Ne as u,
pe as v,
de as w,
b as x,
_ as y,
Ue as z
};