@workos-inc/authkit-js0.20.540.9 kB
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
// src/index.ts
var src_exports = {};
__export(src_exports, {
AuthKitError: () => AuthKitError,
LoginRequiredError: () => LoginRequiredError,
NoSessionError: () => NoSessionError,
RefreshError: () => RefreshError,
RefreshTimeoutError: () => RefreshTimeoutError,
createClient: () => createClient,
getClaims: () => getClaims
});
module.exports = __toCommonJS(src_exports);
// src/exceptions/no-client-id-provided.exception.ts
var NoClientIdProvidedException = class extends Error {
constructor() {
super(...arguments);
this.status = 500;
this.name = "NoClientIdProvidedException";
this.message = `Missing Client ID. Pass it to the constructor (createClient("client_01HXRMBQ9BJ3E7QSTQ9X2PHVB7"))`;
}
};
// src/utils/is-redirect-callback.ts
function isRedirectCallback(redirectUri, searchParams) {
const hasCode = searchParams.has("code");
if (!hasCode) return false;
const { pathname: currentPathName } = window.location;
const redirectPathname = new URL(redirectUri).pathname;
return currentPathName === redirectPathname || currentPathName === `${redirectPathname}/`;
}
// src/utils/memory-storage.ts
function createMemoryStorage() {
let _store = {};
function setItem(key, value) {
_store[key] = value;
}
function getItem(key) {
return _store[key];
}
function removeItem(key) {
delete _store[key];
}
function reset() {
_store = {};
}
return {
setItem,
getItem,
removeItem,
reset
};
}
var memoryStorage = createMemoryStorage();
// src/utils/pkce.ts
async function createPkceChallenge() {
const codeVerifier = createCodeVerifier();
const codeChallenge = await createCodeChallenge(codeVerifier);
return { codeVerifier, codeChallenge };
}
function createCodeVerifier() {
const randomBytes = crypto.getRandomValues(new Uint32Array(96));
return base64urlEncode(randomBytes);
}
async function createCodeChallenge(codeVerifier) {
const hashed = await sha256(codeVerifier);
return base64urlEncode(hashed);
}
function base64urlEncode(buffer) {
return btoa(
Array.from(new Uint8Array(buffer), (b) => String.fromCharCode(b)).join("")
).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function sha256(plain) {
const encoder = new TextEncoder();
const data = encoder.encode(plain);
return crypto.subtle.digest("SHA-256", data);
}
// src/utils/jwt.ts
function decodeBase64Url(input) {
const base64 = input.replace(/-/g, "+").replace(/_/g, "/");
const padding = "=".repeat((4 - base64.length % 4) % 4);
const binary = atob(base64 + padding);
return new TextDecoder().decode(
Uint8Array.from(binary, (c) => c.charCodeAt(0))
);
}
function decodeJwt(token) {
const parts = token.split(".");
if (parts.length !== 3) {
throw new Error("Invalid JWT format");
}
try {
const header = JSON.parse(decodeBase64Url(parts[0]));
const payload = JSON.parse(decodeBase64Url(parts[1]));
return { header, payload };
} catch (error) {
throw new Error(
`Failed to decode JWT: ${error instanceof Error ? error.message : String(error)}`
);
}
}
// src/utils/storage-keys.ts
var storageKeys = {
codeVerifier: "workos:code-verifier",
user: "workos:user",
accessToken: "workos:access-token",
refreshToken: "workos:refresh-token",
expiresAt: "workos:expires-at",
authenticationMethod: "workos:authentication-method"
};
// src/utils/session-data.ts
function getClaims(accessToken) {
return decodeJwt(accessToken).payload;
}
function refreshTokenKey(clientId) {
return `${storageKeys.refreshToken}:${clientId}`;
}
function setSessionData(data, { devMode = false, clientId }) {
const { user, accessToken, refreshToken, authenticationMethod } = data;
memoryStorage.setItem(storageKeys.user, user);
memoryStorage.setItem(storageKeys.accessToken, accessToken);
memoryStorage.setItem(storageKeys.authenticationMethod, authenticationMethod);
const storage = devMode ? window.localStorage : memoryStorage;
storage.setItem(refreshTokenKey(clientId), refreshToken);
const { exp, iat } = getClaims(accessToken);
const expiresIn = exp - iat;
const expiresAt = Date.now() + expiresIn * 1e3;
memoryStorage.setItem(storageKeys.expiresAt, expiresAt);
}
function removeSessionData({
devMode = false,
clientId
}) {
memoryStorage.removeItem(storageKeys.user);
memoryStorage.removeItem(storageKeys.accessToken);
memoryStorage.removeItem(storageKeys.authenticationMethod);
const storage = devMode ? window.localStorage : memoryStorage;
storage.removeItem(refreshTokenKey(clientId));
storage.removeItem(storageKeys.refreshToken);
}
function getRefreshToken({
devMode = false,
clientId
}) {
const storage = devMode ? window.localStorage : memoryStorage;
const token = storage.getItem(refreshTokenKey(clientId)) ?? storage.getItem(storageKeys.refreshToken);
return typeof token === "string" ? token : void 0;
}
// src/utils/to-query-string.ts
function toQueryString(options) {
const searchParams = new URLSearchParams();
const keys = Object.keys(options).sort();
for (const key of keys) {
const value = options[key];
if (value) {
searchParams.append(key, value);
}
}
return searchParams.toString();
}
// src/errors.ts
var AuthKitError = class extends Error {
};
var RefreshError = class extends AuthKitError {
constructor(message, options = {}) {
super(
message,
options.cause != null ? { cause: options.cause } : void 0
);
this.name = "RefreshError";
this.status = options.status;
this.error = options.error;
this.isTransient = options.isTransient ?? false;
}
};
var CodeExchangeError = class extends AuthKitError {
};
var LoginRequiredError = class extends AuthKitError {
constructor() {
super(...arguments);
this.message = "No access token available";
}
};
var RefreshTimeoutError = class extends RefreshError {
constructor(message = "Timed out waiting to refresh the session.", options) {
super(message, { cause: options?.cause, isTransient: true });
this.name = "RefreshTimeoutError";
}
};
var NoSessionError = class extends AuthKitError {
constructor() {
super(...arguments);
this.message = "SignOut() called without an active session. Provide a returnTo URL to redirect anyway.";
}
};
// src/vendor/browser-tabs-lock/processLock.ts
var ProcessLocking = class _ProcessLocking {
constructor() {
this.locked = /* @__PURE__ */ new Map();
this.addToLocked = (key, toAdd) => {
let callbacks = this.locked.get(key);
if (callbacks === void 0) {
if (toAdd === void 0) {
this.locked.set(key, []);
} else {
this.locked.set(key, [toAdd]);
}
} else {
if (toAdd !== void 0) {
callbacks.unshift(toAdd);
this.locked.set(key, callbacks);
}
}
};
this.isLocked = (key) => {
return this.locked.has(key);
};
this.lock = (key) => {
return new Promise((resolve, reject) => {
if (this.isLocked(key)) {
this.addToLocked(key, resolve);
} else {
this.addToLocked(key);
resolve();
}
});
};
this.unlock = (key) => {
let callbacks = this.locked.get(key);
if (callbacks === void 0 || callbacks.length === 0) {
this.locked.delete(key);
return;
}
let toCall = callbacks.pop();
this.locked.set(key, callbacks);
if (toCall !== void 0) {
setTimeout(toCall, 0);
}
};
}
static getInstance() {
if (_ProcessLocking.instance === void 0) {
_ProcessLocking.instance = new _ProcessLocking();
}
return _ProcessLocking.instance;
}
};
function getLock() {
return ProcessLocking.getInstance();
}
// src/vendor/browser-tabs-lock/index.ts
var LOCK_STORAGE_KEY = "browser-tabs-lock-key";
var DEFAULT_STORAGE_HANDLER = {
key: async (index) => {
throw new Error("Unsupported");
},
getItem: async (key) => {
throw new Error("Unsupported");
},
clear: async () => {
return window.localStorage.clear();
},
removeItem: async (key) => {
throw new Error("Unsupported");
},
setItem: async (key, value) => {
throw new Error("Unsupported");
},
keySync: (index) => {
return window.localStorage.key(index);
},
getItemSync: (key) => {
return window.localStorage.getItem(key);
},
clearSync: () => {
return window.localStorage.clear();
},
removeItemSync: (key) => {
return window.localStorage.removeItem(key);
},
setItemSync: (key, value) => {
return window.localStorage.setItem(key, value);
}
};
function delay(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
function generateRandomString(length) {
const CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
let randomstring = "";
for (let i = 0; i < length; i++) {
const INDEX = Math.floor(Math.random() * CHARS.length);
randomstring += CHARS[INDEX];
}
return randomstring;
}
function getLockId() {
return Date.now().toString() + generateRandomString(15);
}
var _SuperTokensLock = class _SuperTokensLock {
constructor(storageHandler) {
this.acquiredIatSet = /* @__PURE__ */ new Set();
this.storageHandler = void 0;
this.id = getLockId();
this.acquireLock = this.acquireLock.bind(this);
this.releaseLock = this.releaseLock.bind(this);
this.releaseLock__private__ = this.releaseLock__private__.bind(this);
this.waitForSomethingToChange = this.waitForSomethingToChange.bind(this);
this.refreshLockWhileAcquired = this.refreshLockWhileAcquired.bind(this);
this.storageHandler = storageHandler;
if (_SuperTokensLock.waiters === void 0) {
_SuperTokensLock.waiters = [];
}
}
/**
* @async
* @memberOf Lock
* @function acquireLock
* @param {string} lockKey - Key for which the lock is being acquired
* @param {number} [timeout=5000] - Maximum time for which the function will wait to acquire the lock
* @returns {Promise<boolean>}
* @description Will return true if lock is being acquired, else false.
* Also the lock can be acquired for maximum 10 secs
*/
async acquireLock(lockKey, timeout = 5e3) {
let iat = Date.now() + generateRandomString(4);
const MAX_TIME = Date.now() + timeout;
const STORAGE_KEY = `${LOCK_STORAGE_KEY}-${lockKey}`;
const STORAGE = this.storageHandler === void 0 ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
while (Date.now() < MAX_TIME) {
await delay(30);
let lockObj = STORAGE.getItemSync(STORAGE_KEY);
if (lockObj === null) {
const TIMEOUT_KEY = `${this.id}-${lockKey}-${iat}`;
await delay(Math.floor(Math.random() * 25));
STORAGE.setItemSync(STORAGE_KEY, JSON.stringify({
id: this.id,
iat,
timeoutKey: TIMEOUT_KEY,
timeAcquired: Date.now(),
timeRefreshed: Date.now()
}));
await delay(30);
let lockObjPostDelay = STORAGE.getItemSync(STORAGE_KEY);
if (lockObjPostDelay !== null) {
let parsedLockObjPostDelay = JSON.parse(lockObjPostDelay);
if (parsedLockObjPostDelay.id === this.id && parsedLockObjPostDelay.iat === iat) {
this.acquiredIatSet.add(iat);
this.refreshLockWhileAcquired(STORAGE_KEY, iat);
return true;
}
}
} else {
_SuperTokensLock.lockCorrector(this.storageHandler === void 0 ? DEFAULT_STORAGE_HANDLER : this.storageHandler);
await this.waitForSomethingToChange(MAX_TIME);
}
iat = Date.now() + generateRandomString(4);
}
return false;
}
async refreshLockWhileAcquired(storageKey, iat) {
setTimeout(async () => {
await getLock().lock(iat);
if (!this.acquiredIatSet.has(iat)) {
getLock().unlock(iat);
return;
}
const STORAGE = this.storageHandler === void 0 ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
let lockObj = STORAGE.getItemSync(storageKey);
if (lockObj !== null) {
let parsedLockObj = JSON.parse(lockObj);
parsedLockObj.timeRefreshed = Date.now();
STORAGE.setItemSync(storageKey, JSON.stringify(parsedLockObj));
getLock().unlock(iat);
} else {
getLock().unlock(iat);
return;
}
this.refreshLockWhileAcquired(storageKey, iat);
}, 1e3);
}
async waitForSomethingToChange(MAX_TIME) {
await new Promise((resolve) => {
let resolvedCalled = false;
let startedAt = Date.now();
const MIN_TIME_TO_WAIT = 50;
let removedListeners = false;
function stopWaiting() {
if (!removedListeners) {
window.removeEventListener("storage", stopWaiting);
_SuperTokensLock.removeFromWaiting(stopWaiting);
clearTimeout(timeOutId);
removedListeners = true;
}
if (!resolvedCalled) {
resolvedCalled = true;
let timeToWait = MIN_TIME_TO_WAIT - (Date.now() - startedAt);
if (timeToWait > 0) {
setTimeout(resolve, timeToWait);
} else {
resolve(null);
}
}
}
window.addEventListener("storage", stopWaiting);
_SuperTokensLock.addToWaiting(stopWaiting);
let timeOutId = setTimeout(stopWaiting, Math.max(0, MAX_TIME - Date.now()));
});
}
static addToWaiting(func) {
this.removeFromWaiting(func);
if (_SuperTokensLock.waiters === void 0) {
return;
}
_SuperTokensLock.waiters.push(func);
}
static removeFromWaiting(func) {
if (_SuperTokensLock.waiters === void 0) {
return;
}
_SuperTokensLock.waiters = _SuperTokensLock.waiters.filter((i) => i !== func);
}
static notifyWaiters() {
if (_SuperTokensLock.waiters === void 0) {
return;
}
let waiters = [..._SuperTokensLock.waiters];
waiters.forEach((i) => i());
}
/**
* @function releaseLock
* @memberOf Lock
* @param {string} lockKey - Key for which lock is being released
* @returns {void}
* @description Release a lock.
*/
async releaseLock(lockKey) {
return await this.releaseLock__private__(lockKey);
}
/**
* @function releaseLock
* @memberOf Lock
* @param {string} lockKey - Key for which lock is being released
* @returns {void}
* @description Release a lock.
*/
async releaseLock__private__(lockKey) {
const STORAGE = this.storageHandler === void 0 ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
const STORAGE_KEY = `${LOCK_STORAGE_KEY}-${lockKey}`;
let lockObj = STORAGE.getItemSync(STORAGE_KEY);
if (lockObj === null) {
return;
}
let parsedlockObj = JSON.parse(lockObj);
if (parsedlockObj.id === this.id) {
await getLock().lock(parsedlockObj.iat);
this.acquiredIatSet.delete(parsedlockObj.iat);
STORAGE.removeItemSync(STORAGE_KEY);
getLock().unlock(parsedlockObj.iat);
_SuperTokensLock.notifyWaiters();
}
}
/**
* @function lockCorrector
* @returns {void}
* @description If a lock is acquired by a tab and the tab is closed before the lock is
* released, this function will release those locks
*/
static lockCorrector(storageHandler) {
const MIN_ALLOWED_TIME = Date.now() - 5e3;
const STORAGE = storageHandler;
const KEYS = [];
let currIndex = 0;
while (true) {
let key = STORAGE.keySync(currIndex);
if (key === null) {
break;
}
KEYS.push(key);
currIndex++;
}
let notifyWaiters = false;
for (let i = 0; i < KEYS.length; i++) {
const LOCK_KEY = KEYS[i];
if (LOCK_KEY.includes(LOCK_STORAGE_KEY)) {
let lockObj = STORAGE.getItemSync(LOCK_KEY);
if (lockObj !== null) {
let parsedlockObj = JSON.parse(lockObj);
if (parsedlockObj.timeRefreshed === void 0 && parsedlockObj.timeAcquired < MIN_ALLOWED_TIME || parsedlockObj.timeRefreshed !== void 0 && parsedlockObj.timeRefreshed < MIN_ALLOWED_TIME) {
STORAGE.removeItemSync(LOCK_KEY);
notifyWaiters = true;
}
}
}
}
if (notifyWaiters) {
_SuperTokensLock.notifyWaiters();
}
}
};
_SuperTokensLock.waiters = void 0;
var SuperTokensLock = _SuperTokensLock;
// src/utils/locking.ts
var DEFAULT_LOCK_TIMEOUT_MS = 1e4;
function withLock(lockName, callback, { timeout = DEFAULT_LOCK_TIMEOUT_MS } = {}) {
if (!lockName) {
throw new TypeError("lockName is required and must be a non-empty string.");
}
return "locks" in navigator ? withNativeLock(lockName, callback, timeout) : withVendorLock(lockName, callback, timeout);
}
async function withNativeLock(lockName, callback, timeout) {
try {
return await navigator.locks.request(
lockName,
{ signal: AbortSignal.timeout(timeout) },
callback
);
} catch (error) {
if (error instanceof DOMException) {
switch (error.name) {
case "TimeoutError":
case "AbortError":
throw new LockError("AcquisitionTimeoutError", lockName, "Native");
case "InvalidStateError":
case "NotSupportedError":
case "SecurityError":
}
}
throw error;
}
}
async function withVendorLock(lockName, callback, timeout) {
const lock = new SuperTokensLock();
try {
if (await lock.acquireLock(lockName, timeout)) {
return await callback();
} else {
throw new LockError("AcquisitionTimeoutError", lockName, "Vendor");
}
} finally {
await lock.releaseLock(lockName);
}
}
var LockError = class extends Error {
constructor(name, lockName, type) {
super(`Lock acquisition timed out for "${lockName}" (${type})`);
this.name = name;
this.lockName = lockName;
}
};
// src/serializers/user.serializer.ts
var deserializeUser = (user) => ({
object: user.object,
id: user.id,
email: user.email,
emailVerified: user.email_verified,
firstName: user.first_name,
profilePictureUrl: user.profile_picture_url,
lastName: user.last_name,
lastSignInAt: user.last_sign_in_at,
externalId: user.external_id,
createdAt: user.created_at,
updatedAt: user.updated_at
});
// src/serializers/authentication-response.serializer.ts
var deserializeAuthenticationResponse = (authenticationResponse) => {
const {
user,
organization_id,
access_token,
refresh_token,
authentication_method,
impersonator,
...rest
} = authenticationResponse;
return {
user: deserializeUser(user),
organizationId: organization_id,
accessToken: access_token,
refreshToken: refresh_token,
authenticationMethod: authentication_method,
impersonator,
...rest
};
};
// src/http-client.ts
var DEFAULT_HOSTNAME = "api.workos.com";
var RETRYABLE_REFRESH_STATUS_CODES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
var _baseUrl, _clientId, _HttpClient_instances, parseErrorBody_fn, post_fn;
var HttpClient = class {
constructor({
clientId,
hostname = DEFAULT_HOSTNAME,
port,
https = true
}) {
__privateAdd(this, _HttpClient_instances);
__privateAdd(this, _baseUrl);
__privateAdd(this, _clientId);
__privateSet(this, _baseUrl, `${https ? "https" : "http"}://${hostname}${port ? `:${port}` : ""}`);
__privateSet(this, _clientId, clientId);
}
async authenticateWithRefreshToken({
refreshToken,
organizationId,
useCookie
}) {
const response = await __privateMethod(this, _HttpClient_instances, post_fn).call(this, "/user_management/authenticate", {
useCookie,
body: {
client_id: __privateGet(this, _clientId),
grant_type: "refresh_token",
...!useCookie && { refresh_token: refreshToken },
organization_id: organizationId
}
});
if (response.ok) {
const data = await response.json();
return deserializeAuthenticationResponse(data);
}
const { status } = response;
const body = await __privateMethod(this, _HttpClient_instances, parseErrorBody_fn).call(this, response);
throw new RefreshError(body.error_description, {
status,
error: body.error,
isTransient: RETRYABLE_REFRESH_STATUS_CODES.has(status)
});
}
async authenticateWithCode({
code,
codeVerifier,
useCookie
}) {
const response = await __privateMethod(this, _HttpClient_instances, post_fn).call(this, "/user_management/authenticate", {
useCookie,
body: {
code,
client_id: __privateGet(this, _clientId),
grant_type: "authorization_code",
code_verifier: codeVerifier
}
});
if (response.ok) {
const data = await response.json();
return deserializeAuthenticationResponse(data);
}
const error = await response.json();
throw new CodeExchangeError(error.error_description);
}
getAuthorizationUrl({
connectionId,
context,
domainHint,
loginHint,
organizationId,
provider = "authkit",
redirectUri,
state,
screenHint,
passwordResetToken,
invitationToken,
codeChallenge,
codeChallengeMethod
}) {
if (!provider && !connectionId && !organizationId) {
throw new TypeError(
`Incomplete arguments. Need to specify either a 'connectionId', 'organizationId', or 'provider'.`
);
}
if (provider !== "authkit" && screenHint) {
throw new TypeError(
`'screenHint' is only supported for 'authkit' provider`
);
}
if (context) {
console.warn(
`\`context\` is deprecated. We previously required initiate login endpoints to return the
\`context\` query parameter when getting the authorization URL. This is no longer necessary.`
);
}
const query = toQueryString({
connection_id: connectionId,
organization_id: organizationId,
domain_hint: domainHint,
login_hint: loginHint,
provider,
client_id: __privateGet(this, _clientId),
redirect_uri: redirectUri,
response_type: "code",
state,
screen_hint: screenHint,
invitation_token: invitationToken,
password_reset_token: passwordResetToken,
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod
});
return `${__privateGet(this, _baseUrl)}/user_management/authorize?${query}`;
}
getLogoutUrl({
sessionId,
returnTo
}) {
const url = new URL("/user_management/sessions/logout", __privateGet(this, _baseUrl));
url.searchParams.set("session_id", sessionId);
if (returnTo) {
url.searchParams.set("return_to", returnTo);
}
return url;
}
};
_baseUrl = new WeakMap();
_clientId = new WeakMap();
_HttpClient_instances = new WeakSet();
parseErrorBody_fn = async function(response) {
try {
return await response.json();
} catch {
return {};
}
};
post_fn = function(path, { body, useCookie }) {
return fetch(new URL(path, __privateGet(this, _baseUrl)), {
method: "POST",
...useCookie && { credentials: "include" },
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
},
body: JSON.stringify(body)
});
};
// src/create-client.ts
var LEGACY_ORG_ID_KEY = "workos_organization_id";
function orgIdKey(clientId) {
return `workos-org-id:${clientId}`;
}
var REFRESH_LOCK_NAME = "WORKOS_REFRESH_SESSION";
function hasSessionCookie(clientId) {
const matches = document.cookie.matchAll(
/(?:^|;\s*)workos-has-session=([^;]*)/g
);
for (const [, cookieValue] of matches) {
if (cookieValue === "1" || cookieValue.split(".").includes(clientId)) {
return true;
}
}
return false;
}
var _state, _refreshTimer, _clientId2, _httpClient, _redirectUri, _devMode, _onBeforeAutoRefresh, _onRedirectCallback, _onRefreshCallback, _onRefreshFailure, _refreshBufferInterval, _Client_instances, handleCallback_fn, scheduleAutomaticRefreshIfAuthenticated_fn, scheduleAutomaticRefresh_fn, refreshSession_fn, doRefresh_fn, assertNotSignedOut_fn, shouldRefresh_fn, getAuthorizationUrl_fn, getAccessToken_fn, getUnexpiredAccessToken_fn, useCookie_get, onRefresh_fn;
var Client = class {
constructor(clientId, {
apiHostname: hostname,
https,
port,
redirectUri = window.origin,
devMode = location.hostname === "localhost" || location.hostname === "127.0.0.1",
// refresh if this is true
onBeforeAutoRefresh = () => {
return !document.hidden;
},
onRedirectCallback = (_) => {
},
onRefresh,
onRefreshFailure,
refreshBufferInterval = 10
} = {}) {
__privateAdd(this, _Client_instances);
__privateAdd(this, _state);
__privateAdd(this, _refreshTimer);
__privateAdd(this, _clientId2);
__privateAdd(this, _httpClient);
__privateAdd(this, _redirectUri);
__privateAdd(this, _devMode);
__privateAdd(this, _onBeforeAutoRefresh);
__privateAdd(this, _onRedirectCallback);
__privateAdd(this, _onRefreshCallback);
__privateAdd(this, _onRefreshFailure);
__privateAdd(this, _refreshBufferInterval);
if (!clientId) {
throw new NoClientIdProvidedException();
}
__privateSet(this, _clientId2, clientId);
__privateSet(this, _httpClient, new HttpClient({ clientId, hostname, port, https }));
__privateSet(this, _devMode, devMode);
__privateSet(this, _redirectUri, redirectUri);
__privateSet(this, _state, { tag: "INITIAL" });
__privateSet(this, _onBeforeAutoRefresh, onBeforeAutoRefresh);
__privateSet(this, _onRedirectCallback, onRedirectCallback);
__privateSet(this, _onRefreshCallback, onRefresh);
__privateSet(this, _onRefreshFailure, onRefreshFailure);
__privateSet(this, _refreshBufferInterval, refreshBufferInterval);
}
async initialize() {
if (__privateGet(this, _state).tag !== "INITIAL") {
return;
}
const searchParams = new URLSearchParams(window.location.search);
if (isRedirectCallback(__privateGet(this, _redirectUri), searchParams)) {
await __privateMethod(this, _Client_instances, handleCallback_fn).call(this);
} else if (hasSessionCookie(__privateGet(this, _clientId2)) || getRefreshToken({ devMode: __privateGet(this, _devMode), clientId: __privateGet(this, _clientId2) })) {
try {
await __privateMethod(this, _Client_instances, refreshSession_fn).call(this);
__privateMethod(this, _Client_instances, scheduleAutomaticRefresh_fn).call(this);
} catch {
__privateMethod(this, _Client_instances, scheduleAutomaticRefreshIfAuthenticated_fn).call(this);
}
}
}
async getSignInUrl(opts = {}) {
const url = await __privateMethod(this, _Client_instances, getAuthorizationUrl_fn).call(this, { ...opts });
return url;
}
async getSignUpUrl(opts = {}) {
const url = await __privateMethod(this, _Client_instances, getAuthorizationUrl_fn).call(this, {
...opts,
screenHint: "sign-up"
});
return url;
}
async signIn(opts = {}) {
const url = await __privateMethod(this, _Client_instances, getAuthorizationUrl_fn).call(this, { ...opts });
window.location.assign(url);
}
async signUp(opts = {}) {
const url = await __privateMethod(this, _Client_instances, getAuthorizationUrl_fn).call(this, {
...opts,
screenHint: "sign-up"
});
window.location.assign(url);
}
signOut(options = { navigate: true }) {
const { navigate = true, returnTo } = options;
const accessToken = memoryStorage.getItem(storageKeys.accessToken);
if (typeof accessToken !== "string") {
if (navigate) {
throw new NoSessionError();
}
return Promise.reject(new NoSessionError());
}
const { sid: sessionId } = getClaims(accessToken);
const url = __privateGet(this, _httpClient).getLogoutUrl({
sessionId,
returnTo
});
if (url) {
__privateSet(this, _state, { tag: "SIGNED_OUT" });
clearTimeout(__privateGet(this, _refreshTimer));
removeSessionData({ devMode: __privateGet(this, _devMode), clientId: __privateGet(this, _clientId2) });
sessionStorage.removeItem(orgIdKey(__privateGet(this, _clientId2)));
sessionStorage.removeItem(LEGACY_ORG_ID_KEY);
if (navigate) {
window.location.assign(url);
} else {
return new Promise(async (resolve) => {
fetch(url, {
mode: "no-cors",
credentials: "include"
}).catch((error) => {
console.warn("AuthKit: Failed to send logout request", error);
}).finally(resolve);
});
}
}
}
async getAccessToken(options) {
if (options?.forceRefresh || __privateMethod(this, _Client_instances, shouldRefresh_fn).call(this)) {
try {
await __privateMethod(this, _Client_instances, refreshSession_fn).call(this);
} catch (err) {
if (err instanceof RefreshTimeoutError) {
const token = !options?.forceRefresh ? __privateMethod(this, _Client_instances, getUnexpiredAccessToken_fn).call(this) : void 0;
if (token) return token;
try {
await __privateMethod(this, _Client_instances, refreshSession_fn).call(this);
} catch (retryErr) {
if (retryErr instanceof RefreshTimeoutError) throw retryErr;
if (retryErr instanceof RefreshError) {
if (retryErr.isTransient) throw retryErr;
throw new LoginRequiredError();
}
throw retryErr;
}
} else if (err instanceof RefreshError) {
if (err.isTransient) {
const token = !options?.forceRefresh ? __privateMethod(this, _Client_instances, getUnexpiredAccessToken_fn).call(this) : void 0;
if (token) return token;
throw err;
}
throw new LoginRequiredError();
} else {
throw err;
}
}
}
const accessToken = __privateMethod(this, _Client_instances, getAccessToken_fn).call(this);
if (!accessToken) {
throw new LoginRequiredError();
}
return accessToken;
}
getUser() {
const user = memoryStorage.getItem(storageKeys.user);
return user ? user : null;
}
dispose() {
clearTimeout(__privateGet(this, _refreshTimer));
memoryStorage.reset();
}
/**
* Switches to the requested organization.
*
* Redirects to the hosted login page for the given organization if the
* switch is unsuccessful.
*/
async switchToOrganization({
organizationId,
signInOpts = {}
}) {
try {
await __privateMethod(this, _Client_instances, refreshSession_fn).call(this, { organizationId });
} catch (error) {
if (error instanceof RefreshTimeoutError) {
console.warn(
"Couldn't switch organization: lock acquisition timed out."
);
} else if (error instanceof RefreshError) {
if (error.isTransient) {
throw error;
}
this.signIn({ ...signInOpts, organizationId });
} else {
throw error;
}
}
}
};
_state = new WeakMap();
_refreshTimer = new WeakMap();
_clientId2 = new WeakMap();
_httpClient = new WeakMap();
_redirectUri = new WeakMap();
_devMode = new WeakMap();
_onBeforeAutoRefresh = new WeakMap();
_onRedirectCallback = new WeakMap();
_onRefreshCallback = new WeakMap();
_onRefreshFailure = new WeakMap();
_refreshBufferInterval = new WeakMap();
_Client_instances = new WeakSet();
handleCallback_fn = async function() {
if (__privateGet(this, _state).tag !== "INITIAL") {
return;
}
const url = new URL(window.location.href);
const code = url.searchParams.get("code");
const stateParam = url.searchParams.get("state");
let state = void 0;
if (stateParam) {
try {
state = JSON.parse(stateParam);
} catch {
console.warn("AuthKit: ignoring malformed `state` parameter");
}
}
const codeVerifier = window.sessionStorage.getItem(
storageKeys.codeVerifier
);
if (code) {
if (codeVerifier) {
try {
__privateSet(this, _state, {
tag: "AUTHENTICATING",
response: __privateGet(this, _httpClient).authenticateWithCode({
code,
codeVerifier,
useCookie: __privateGet(this, _Client_instances, useCookie_get)
})
});
const authenticationResponse = await __privateGet(this, _state).response;
if (authenticationResponse) {
__privateSet(this, _state, { tag: "AUTHENTICATED" });
__privateMethod(this, _Client_instances, scheduleAutomaticRefresh_fn).call(this);
setSessionData(authenticationResponse, {
devMode: __privateGet(this, _devMode),
clientId: __privateGet(this, _clientId2)
});
__privateMethod(this, _Client_instances, onRefresh_fn).call(this, authenticationResponse);
__privateGet(this, _onRedirectCallback).call(this, { state, ...authenticationResponse });
}
} catch (error) {
__privateSet(this, _state, { tag: "ERROR" });
console.error(error);
}
} else {
__privateSet(this, _state, { tag: "ERROR" });
console.error(`Couldn't exchange code.
An authorization_code was supplied for a login which did not originate at the application. This could happen for various reasons:
* This could have been an attempted Login CSRF attack. You were not affected.
* The developer may not have configured a Login Initiation endpoint.`);
}
}
const cleanUrl = new URL(window.location.toString());
cleanUrl.searchParams.delete("code");
cleanUrl.searchParams.delete("state");
window.sessionStorage.removeItem(storageKeys.codeVerifier);
window.history.replaceState({}, "", cleanUrl);
};
scheduleAutomaticRefreshIfAuthenticated_fn = function() {
if (__privateGet(this, _state).tag === "AUTHENTICATED") {
__privateMethod(this, _Client_instances, scheduleAutomaticRefresh_fn).call(this);
}
};
scheduleAutomaticRefresh_fn = async function() {
if (__privateGet(this, _state).tag === "SIGNED_OUT") return;
__privateSet(this, _refreshTimer, setTimeout(() => {
if (__privateMethod(this, _Client_instances, shouldRefresh_fn).call(this) && __privateGet(this, _onBeforeAutoRefresh).call(this)) {
__privateMethod(this, _Client_instances, refreshSession_fn).call(this).catch((e) => {
if (__privateGet(this, _state).tag !== "SIGNED_OUT") console.debug(e);
}).finally(() => __privateMethod(this, _Client_instances, scheduleAutomaticRefresh_fn).call(this));
} else {
__privateMethod(this, _Client_instances, scheduleAutomaticRefresh_fn).call(this);
}
}, 1e3));
};
refreshSession_fn = async function({ organizationId } = {}) {
__privateMethod(this, _Client_instances, assertNotSignedOut_fn).call(this);
if (__privateGet(this, _state).tag === "AUTHENTICATING") {
await __privateGet(this, _state).response;
return;
}
const beginningState = __privateGet(this, _state);
__privateSet(this, _state, {
tag: "AUTHENTICATING",
response: __privateMethod(this, _Client_instances, doRefresh_fn).call(this, { organizationId, beginningState })
});
await __privateGet(this, _state).response;
};
doRefresh_fn = async function({
organizationId,
beginningState
}) {
try {
return await withLock(REFRESH_LOCK_NAME, async () => {
__privateMethod(this, _Client_instances, assertNotSignedOut_fn).call(this);
if (organizationId) {
sessionStorage.setItem(orgIdKey(__privateGet(this, _clientId2)), organizationId);
} else {
const accessToken = __privateMethod(this, _Client_instances, getAccessToken_fn).call(this);
if (accessToken) {
organizationId = getClaims(accessToken)?.org_id;
} else {
organizationId = sessionStorage.getItem(orgIdKey(__privateGet(this, _clientId2))) ?? sessionStorage.getItem(LEGACY_ORG_ID_KEY) ?? void 0;
}
}
const authenticationResponse = await __privateGet(this, _httpClient).authenticateWithRefreshToken({
refreshToken: getRefreshToken({
devMode: __privateGet(this, _devMode),
clientId: __privateGet(this, _clientId2)
}),
organizationId,
useCookie: __privateGet(this, _Client_instances, useCookie_get)
});
__privateMethod(this, _Client_instances, assertNotSignedOut_fn).call(this);
__privateSet(this, _state, { tag: "AUTHENTICATED" });
setSessionData(authenticationResponse, {
devMode: __privateGet(this, _devMode),
clientId: __privateGet(this, _clientId2)
});
__privateMethod(this, _Client_instances, onRefresh_fn).call(this, authenticationResponse);
return authenticationResponse;
});
} catch (error) {
__privateMethod(this, _Client_instances, assertNotSignedOut_fn).call(this);
if (error instanceof LockError && error.name === "AcquisitionTimeoutError") {
console.warn("Couldn't acquire refresh lock.");
__privateSet(this, _state, beginningState);
throw new RefreshTimeoutError(void 0, { cause: error });
}
if (beginningState.tag !== "INITIAL") {
console.debug(error);
}
if (error instanceof RefreshError && !error.isTransient) {
removeSessionData({ devMode: __privateGet(this, _devMode), clientId: __privateGet(this, _clientId2) });
sessionStorage.removeItem(orgIdKey(__privateGet(this, _clientId2)));
sessionStorage.removeItem(LEGACY_ORG_ID_KEY);
beginningState.tag !== "INITIAL" && __privateGet(this, _onRefreshFailure) && __privateGet(this, _onRefreshFailure).call(this, { signIn: this.signIn.bind(this) });
__privateSet(this, _state, { tag: "ERROR" });
} else {
__privateSet(this, _state, { tag: "AUTHENTICATED" });
}
throw error;
}
};
assertNotSignedOut_fn = function() {
if (__privateGet(this, _state).tag === "SIGNED_OUT") throw new LoginRequiredError();
};
shouldRefresh_fn = function() {
switch (__privateGet(this, _state).tag) {
case "INITIAL":
case "AUTHENTICATING":
return true;
case "SIGNED_OUT":
case "ERROR":
return false;
case "AUTHENTICATED":
const accessToken = memoryStorage.getItem(storageKeys.accessToken);
const expiresAt = memoryStorage.getItem(storageKeys.expiresAt);
if (!accessToken || !expiresAt) {
return true;
}
const tokenRefreshBufferInSeconds = __privateGet(this, _refreshBufferInterval) * 1e3;
const refreshTime = expiresAt - tokenRefreshBufferInSeconds;
return refreshTime < Date.now();
}
};
getAuthorizationUrl_fn = async function({
context,
invitationToken,
loginHint,
organizationId,
passwordResetToken,
state,
screenHint
}) {
const { codeVerifier, codeChallenge } = await createPkceChallenge();
window.sessionStorage.setItem(storageKeys.codeVerifier, codeVerifier);
const url = __privateGet(this, _httpClient).getAuthorizationUrl({
codeChallenge,
codeChallengeMethod: "S256",
context,
invitationToken,
loginHint,
organizationId,
passwordResetToken,
redirectUri: __privateGet(this, _redirectUri),
screenHint,
state: state ? JSON.stringify(state) : void 0
});
return url;
};
getAccessToken_fn = function() {
return memoryStorage.getItem(storageKeys.accessToken);
};
getUnexpiredAccessToken_fn = function() {
const accessToken = __privateMethod(this, _Client_instances, getAccessToken_fn).call(this);
const expiresAt = memoryStorage.getItem(storageKeys.expiresAt);
return accessToken && expiresAt && expiresAt > Date.now() ? accessToken : void 0;
};
useCookie_get = function() {
return !__privateGet(this, _devMode);
};
onRefresh_fn = async function(authenticationResponse) {
if (__privateGet(this, _onRefreshCallback)) {
const { refreshToken: _refreshToken, ...onRefreshData } = authenticationResponse;
__privateGet(this, _onRefreshCallback).call(this, onRefreshData);
}
};
async function createClient(clientId, options = {}) {
const client = new Client(clientId, options);
await client.initialize();
return client;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
AuthKitError,
LoginRequiredError,
NoSessionError,
RefreshError,
RefreshTimeoutError,
createClient,
getClaims
});
//# sourceMappingURL=index.js.map
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.