@tradly/auth
Version:
Auth package for Tradly - handles authentication (email, phone, social login)
825 lines (824 loc) • 27 kB
JavaScript
;
/**
* Auth Key and UUID retrieval utility
* This function will be shared across all packages
* Handles cookies and localStorage automatically
* All keys are scoped to the domain from initializeAuth
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.setAuthKeySource = setAuthKeySource;
exports.getAuthKey = getAuthKey;
exports.getUUID = getUUID;
exports.hasAuthKey = hasAuthKey;
exports.hasUUID = hasUUID;
exports.setAuthKey = setAuthKey;
exports.setUUID = setUUID;
exports.clearAuthKey = clearAuthKey;
exports.clearUUID = clearUUID;
exports.getRefreshKey = getRefreshKey;
exports.setRefreshKey = setRefreshKey;
exports.getFirebaseToken = getFirebaseToken;
exports.setFirebaseToken = setFirebaseToken;
exports.getUserInfo = getUserInfo;
exports.setUserInfo = setUserInfo;
exports.clearRefreshKey = clearRefreshKey;
exports.clearFirebaseToken = clearFirebaseToken;
exports.clearUserInfo = clearUserInfo;
exports.clearAllUserData = clearAllUserData;
const config_1 = require("./config");
const cache_1 = require("./cache");
let authKeySource = null;
/**
* Set the auth key source (optional - for custom implementations)
* If not set, will use default cookie/localStorage implementation
*/
function setAuthKeySource(source) {
authKeySource = source;
}
/**
* Get current domain/host
* Priority: 1. Custom source, 2. Config domain (from initializeAuth), 3. window.location.host
*/
function getDomain() {
if (authKeySource?.getDomain) {
return authKeySource.getDomain();
}
// Use domain from config (from initializeAuth) - this is the main source
const configDomain = (0, config_1.getDomain)();
if (configDomain) {
return configDomain;
}
// Fallback to browser environment (for backward compatibility)
if (typeof window !== "undefined") {
return window.location.host;
}
// Server environment - would need to be passed via options
return null;
}
/**
* Get cookie value (works in both browser and Node.js)
*/
function getCookieValue(name) {
if (authKeySource?.getAuthKey && name.includes("auth_key")) {
// Custom source takes precedence
return null; // Will fall through to custom source
}
if (authKeySource?.getUUID && name.includes("uuid")) {
return null; // Will fall through to custom source
}
// Browser environment - use document.cookie
if (typeof document !== "undefined") {
const cookies = document.cookie.split(";");
for (let cookie of cookies) {
const [key, value] = cookie.trim().split("=");
if (key === name) {
return decodeURIComponent(value);
}
}
}
return null;
}
/**
* Get localStorage value (browser only)
*/
function getLocalStorageValue(key) {
if (typeof window === "undefined" || !window.localStorage) {
return null;
}
try {
return window.localStorage.getItem(key);
}
catch {
return null;
}
}
/**
* Get auth key from cookies or localStorage
* Cookie format: `${domain}_auth_key`
* localStorage format: `${domain}_auth_key`
*/
function getAuthKey() {
// Use custom source if provided
if (authKeySource?.getAuthKey) {
const customKey = authKeySource.getAuthKey();
if (customKey)
return customKey;
}
const domain = getDomain();
if (!domain)
return null;
const cacheKey = `auth_key_${domain}`;
const cookieName = `${domain}_auth_key`;
// Check cache first
if (cache_1.cache && typeof cache_1.cache.get === "function") {
try {
const cached = cache_1.cache.get(cacheKey);
if (cached)
return cached;
}
catch (e) {
// Cache access failed, continue
}
}
// Try cookie
const cookieValue = getCookieValue(cookieName);
if (cookieValue) {
// Store in cache
if (cache_1.cache && typeof cache_1.cache.set === "function") {
try {
cache_1.cache.set(cacheKey, cookieValue, 36000000); // 10 hours
}
catch (e) {
// Cache set failed, continue
}
}
return cookieValue;
}
// Fallback to localStorage (browser only)
const localStorageValue = getLocalStorageValue(cookieName);
if (localStorageValue) {
// Store in cache
if (cache_1.cache && typeof cache_1.cache.set === "function") {
try {
cache_1.cache.set(cacheKey, localStorageValue, 36000000); // 10 hours
}
catch (e) {
// Cache set failed, continue
}
}
return localStorageValue;
}
return null;
}
/**
* Get UUID from cache, cookies, or localStorage
* Cookie format: `${domain}_uuid` (may be encrypted)
* localStorage format: `${domain}_uuid`
* Cache format: `uuid_${domain}`
*/
function getUUID() {
const domain = getDomain();
if (!domain)
return null;
const cacheKey = `uuid_${domain}`;
const cookieName = `${domain}_uuid`;
// On client-side, prioritize cookie/localStorage over cache (they persist across reloads)
// On server-side, prioritize cache (it's set during initializeAuth)
if (typeof window !== "undefined") {
// Client-side: Check cookie first (most persistent)
const cookieValue = getCookieValue(cookieName);
if (cookieValue) {
// Store in cache for future access
if (cache_1.cache && typeof cache_1.cache.set === "function") {
try {
cache_1.cache.set(cacheKey, cookieValue, 365 * 24 * 60 * 60 * 1000);
}
catch (e) {
// Cache set failed, continue
}
}
return cookieValue;
}
// Then check localStorage
const localStorageValue = getLocalStorageValue(cookieName);
if (localStorageValue) {
// Store in cache for future access
if (cache_1.cache && typeof cache_1.cache.set === "function") {
try {
cache_1.cache.set(cacheKey, localStorageValue, 365 * 24 * 60 * 60 * 1000);
}
catch (e) {
// Cache set failed, continue
}
}
return localStorageValue;
}
// Then check cache (might have been set during initializeAuth)
if (cache_1.cache && typeof cache_1.cache.get === "function") {
try {
const cachedUUID = cache_1.cache.get(cacheKey);
if (cachedUUID) {
return cachedUUID;
}
}
catch (e) {
// Cache access failed, continue
}
}
}
else {
// Server-side: Check cache first (fastest)
if (cache_1.cache && typeof cache_1.cache.get === "function") {
try {
const cachedUUID = cache_1.cache.get(cacheKey);
if (cachedUUID) {
return cachedUUID;
}
}
catch (e) {
// Cache access failed, continue
}
}
}
// Use custom source if provided (but check if it returns a Promise)
// This is mainly for server-side Next.js
if (authKeySource?.getUUID) {
try {
const customUUID = authKeySource.getUUID();
// Check if it's a Promise (React Server Components can wrap in Promise)
if (customUUID &&
typeof customUUID === "object" &&
typeof customUUID.then === "function") {
// It's a Promise - skip custom source and continue to other fallbacks
console.warn("getUUID: Custom source returned a Promise, skipping");
}
else if (customUUID && typeof customUUID === "string") {
// Valid string UUID - store in cache for future use
if (cache_1.cache && typeof cache_1.cache.set === "function") {
try {
cache_1.cache.set(cacheKey, customUUID, 365 * 24 * 60 * 60 * 1000); // 1 year
}
catch (e) {
// Cache set failed, continue
}
}
return customUUID;
}
}
catch (e) {
// Custom source failed, continue to fallback
console.warn("getUUID: Custom source error, falling back:", e);
}
}
// Also try without domain prefix (legacy support)
const legacyCookie = getCookieValue("uuid");
if (legacyCookie) {
if (cache_1.cache && typeof cache_1.cache.set === "function") {
try {
cache_1.cache.set(cacheKey, legacyCookie, 365 * 24 * 60 * 60 * 1000); // 1 year
}
catch (e) {
// Cache set failed, continue
}
}
return legacyCookie;
}
const legacyStorage = getLocalStorageValue("uuid");
if (legacyStorage) {
if (cache_1.cache && typeof cache_1.cache.set === "function") {
try {
cache_1.cache.set(cacheKey, legacyStorage, 365 * 24 * 60 * 60 * 1000); // 1 year
}
catch (e) {
// Cache set failed, continue
}
}
return legacyStorage;
}
// If still no UUID found and we have a domain, try to get from initializeAuth's cache
// This ensures UUID is available even if custom source returned a Promise
// The UUID should have been set during initializeAuth
if (domain) {
// Try globalThis cache as fallback (for server-side persistence)
try {
const globalCache = globalThis
.__tradly_auth_cache__;
if (globalCache && typeof globalCache.get === "function") {
const globalUUID = globalCache.get(cacheKey);
if (globalUUID) {
// Store in local cache too
if (cache_1.cache &&
typeof cache_1.cache.set === "function") {
try {
cache_1.cache.set(cacheKey, globalUUID, 365 *
24 *
60 *
60 *
1000);
}
catch (e) {
// Cache set failed, continue
}
}
return globalUUID;
}
}
}
catch (e) {
// Global cache access failed, continue
}
}
return null;
}
/**
* Check if auth key is available
*/
function hasAuthKey() {
return getAuthKey() !== null;
}
/**
* Check if UUID is available
*/
function hasUUID() {
return getUUID() !== null;
}
/**
* Set auth key (for browser environments)
* Stores in cache, cookie, and localStorage
* Note: For server-side, use cookies-next or similar
*/
function setAuthKey(authKey, domain) {
if (typeof window === "undefined") {
console.warn("setAuthKey: Not available in server environment. Use cookies-next instead.");
return;
}
const host = domain || getDomain() || window.location.host;
const cookieName = `${host}_auth_key`;
const cacheKey = `auth_key_${host}`;
// Set in cache (10 hours TTL)
try {
if (cache_1.cache && typeof cache_1.cache.set === "function") {
cache_1.cache.set(cacheKey, authKey, 36000000); // 10 hours
}
}
catch (e) {
console.warn("Failed to set auth key in cache:", e);
}
// Set in localStorage
try {
window.localStorage.setItem(cookieName, authKey);
}
catch (e) {
console.warn("Failed to set auth key in localStorage:", e);
}
// Set in cookie (browser)
const maxAge = 36000; // 10 hours in seconds
document.cookie = `${cookieName}=${encodeURIComponent(authKey)}; max-age=${maxAge}; path=/; SameSite=Lax`;
}
/**
* Set UUID (works on both server and client)
* Stores in cache (always), cookie and localStorage (client-side only)
*/
function setUUID(uuid, domain) {
const host = domain || getDomain();
if (!host) {
// On client-side, try to get from window.location
if (typeof window !== "undefined") {
const fallbackHost = window.location.host;
if (fallbackHost) {
_setUUIDForHost(uuid, fallbackHost);
}
}
return;
}
_setUUIDForHost(uuid, host);
}
/**
* Internal helper to set UUID for a specific host
*/
function _setUUIDForHost(uuid, host) {
const cookieName = `${host}_uuid`;
const cacheKey = `uuid_${host}`;
// Always set in cache (works on both server and client)
if (cache_1.cache && typeof cache_1.cache.set === "function") {
try {
cache_1.cache.set(cacheKey, uuid, 365 * 24 * 60 * 60 * 1000); // 1 year
}
catch (e) {
console.warn("Failed to set UUID in cache:", e);
}
}
// Client-side only: Set in localStorage and cookie
if (typeof window !== "undefined") {
// Set in localStorage
try {
window.localStorage.setItem(cookieName, uuid);
}
catch (e) {
console.warn("Failed to set UUID in localStorage:", e);
}
// Set in cookie (browser) - with 1 year expiration
if (typeof document !== "undefined") {
const maxAge = 365 * 24 * 60 * 60; // 1 year in seconds
document.cookie = `${cookieName}=${encodeURIComponent(uuid)}; max-age=${maxAge}; path=/; SameSite=Lax`;
}
}
// Server-side: UUID is in cache, cookies will be handled by setAuthKeySource if needed
}
/**
* Clear auth key (logout)
*/
function clearAuthKey(domain) {
const host = domain || getDomain();
if (!host)
return;
const cookieName = `${host}_auth_key`;
// Clear from cache
if (cache_1.cache && typeof cache_1.cache.delete === "function") {
try {
cache_1.cache.delete(`auth_key_${host}`);
}
catch (e) {
console.warn("Failed to delete auth key from cache:", e);
}
}
// Clear from localStorage
if (typeof window !== "undefined" && window.localStorage) {
try {
window.localStorage.removeItem(cookieName);
}
catch (e) {
console.warn("Failed to remove auth key from localStorage:", e);
}
}
// Clear from cookie
if (typeof document !== "undefined") {
document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
}
}
/**
* Clear UUID
*/
function clearUUID(domain) {
const host = domain || getDomain();
if (!host)
return;
const cookieName = `${host}_uuid`;
const cacheKey = `uuid_${host}`;
// Clear from cache
if (cache_1.cache && typeof cache_1.cache.delete === "function") {
try {
cache_1.cache.delete(cacheKey);
}
catch (e) {
console.warn("Failed to delete UUID from cache:", e);
}
}
// Clear from localStorage
if (typeof window !== "undefined" && window.localStorage) {
try {
window.localStorage.removeItem(cookieName);
}
catch (e) {
console.warn("Failed to remove UUID from localStorage:", e);
}
}
// Clear from cookie
if (typeof document !== "undefined") {
document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
}
}
/**
* Get refresh key from cache, cookies, or localStorage
*/
function getRefreshKey() {
// Use custom source if provided (for server-side)
if (authKeySource?.getRefreshKey) {
const customKey = authKeySource.getRefreshKey();
if (customKey)
return customKey;
}
const domain = getDomain();
if (!domain)
return null;
const cacheKey = `refresh_key_${domain}`;
const cookieName = `${domain}_refresh_key`;
// Check cache first
if (cache_1.cache && typeof cache_1.cache.get === "function") {
try {
const cached = cache_1.cache.get(cacheKey);
if (cached)
return cached;
}
catch (e) {
// Cache access failed, continue
}
}
// Try cookie
const cookieValue = getCookieValue(cookieName);
if (cookieValue) {
// Store in cache
if (cache_1.cache && typeof cache_1.cache.set === "function") {
try {
cache_1.cache.set(cacheKey, cookieValue, 36000000); // 10 hours
}
catch (e) {
// Cache set failed, continue
}
}
return cookieValue;
}
// Fallback to localStorage
const localStorageValue = getLocalStorageValue(cookieName);
if (localStorageValue) {
// Store in cache
if (cache_1.cache && typeof cache_1.cache.set === "function") {
try {
cache_1.cache.set(cacheKey, localStorageValue, 36000000); // 10 hours
}
catch (e) {
// Cache set failed, continue
}
}
return localStorageValue;
}
return null;
}
/**
* Set refresh key (for browser environments)
* Stores in cache, cookie, and localStorage
*/
function setRefreshKey(refreshKey, domain) {
if (typeof window === "undefined") {
console.warn("setRefreshKey: Not available in server environment. Use cookies-next instead.");
return;
}
const host = domain || getDomain() || window.location.host;
const cookieName = `${host}_refresh_key`;
const cacheKey = `refresh_key_${host}`;
// Set in cache (10 hours TTL)
try {
if (cache_1.cache && typeof cache_1.cache.set === "function") {
cache_1.cache.set(cacheKey, refreshKey, 36000000); // 10 hours
}
}
catch (e) {
console.warn("Failed to set refresh key in cache:", e);
}
// Set in localStorage
try {
window.localStorage.setItem(cookieName, refreshKey);
}
catch (e) {
console.warn("Failed to set refresh key in localStorage:", e);
}
// Set in cookie (browser)
const maxAge = 36000; // 10 hours in seconds
document.cookie = `${cookieName}=${encodeURIComponent(refreshKey)}; max-age=${maxAge}; path=/; SameSite=Lax`;
}
/**
* Get firebase token from cache, cookies, or localStorage
*/
function getFirebaseToken() {
// Use custom source if provided (for server-side)
if (authKeySource?.getFirebaseToken) {
const customToken = authKeySource.getFirebaseToken();
if (customToken)
return customToken;
}
const domain = getDomain();
if (!domain)
return null;
const cacheKey = `firebase_token_${domain}`;
const cookieName = `${domain}_firebase_token`;
// Check cache first
if (cache_1.cache && typeof cache_1.cache.get === "function") {
try {
const cached = cache_1.cache.get(cacheKey);
if (cached)
return cached;
}
catch (e) {
// Cache access failed, continue
}
}
// Try cookie
const cookieValue = getCookieValue(cookieName);
if (cookieValue) {
// Store in cache
if (cache_1.cache && typeof cache_1.cache.set === "function") {
try {
cache_1.cache.set(cacheKey, cookieValue, 36000000); // 10 hours
}
catch (e) {
// Cache set failed, continue
}
}
return cookieValue;
}
// Fallback to localStorage
const localStorageValue = getLocalStorageValue(cookieName);
if (localStorageValue) {
// Store in cache
if (cache_1.cache && typeof cache_1.cache.set === "function") {
try {
cache_1.cache.set(cacheKey, localStorageValue, 36000000); // 10 hours
}
catch (e) {
// Cache set failed, continue
}
}
return localStorageValue;
}
return null;
}
/**
* Set firebase token (for browser environments)
* Stores in cache, cookie, and localStorage
*/
function setFirebaseToken(firebaseToken, domain) {
if (typeof window === "undefined") {
console.warn("setFirebaseToken: Not available in server environment. Use cookies-next instead.");
return;
}
const host = domain || getDomain() || window.location.host;
const cookieName = `${host}_firebase_token`;
const cacheKey = `firebase_token_${host}`;
// Set in cache (10 hours TTL)
try {
if (cache_1.cache && typeof cache_1.cache.set === "function") {
cache_1.cache.set(cacheKey, firebaseToken, 36000000); // 10 hours
}
}
catch (e) {
console.warn("Failed to set firebase token in cache:", e);
}
// Set in localStorage
try {
window.localStorage.setItem(cookieName, firebaseToken);
}
catch (e) {
console.warn("Failed to set firebase token in localStorage:", e);
}
// Set in cookie (browser)
const maxAge = 36000; // 10 hours in seconds
document.cookie = `${cookieName}=${encodeURIComponent(firebaseToken)}; max-age=${maxAge}; path=/; SameSite=Lax`;
}
/**
* Get user info from cache, cookies, or localStorage
*/
function getUserInfo() {
// Use custom source if provided (for server-side)
if (authKeySource?.getUserInfo) {
const customUserInfo = authKeySource.getUserInfo();
if (customUserInfo)
return customUserInfo;
}
const domain = getDomain();
if (!domain)
return null;
const cacheKey = `user_info_${domain}`;
const cookieName = `${domain}_user_info`;
// Check cache first
if (cache_1.cache && typeof cache_1.cache.get === "function") {
try {
const cached = cache_1.cache.get(cacheKey);
if (cached)
return cached;
}
catch (e) {
// Cache access failed, continue
}
}
// Try localStorage (user info is too large for cookies)
const localStorageValue = getLocalStorageValue(cookieName);
if (localStorageValue) {
try {
const userInfo = JSON.parse(localStorageValue);
// Store in cache
if (cache_1.cache && typeof cache_1.cache.set === "function") {
try {
cache_1.cache.set(cacheKey, userInfo, 36000000); // 10 hours
}
catch (e) {
// Cache set failed, continue
}
}
return userInfo;
}
catch (e) {
console.warn("Failed to parse user info from localStorage:", e);
}
}
return null;
}
/**
* Set user info (for browser environments)
* Stores in cache and localStorage (too large for cookies)
*/
function setUserInfo(userInfo, domain) {
if (typeof window === "undefined") {
console.warn("setUserInfo: Not available in server environment. Use cookies-next or similar.");
return;
}
const host = domain || getDomain() || window.location.host;
const cookieName = `${host}_user_info`;
const cacheKey = `user_info_${host}`;
// Set in cache (10 hours TTL)
try {
if (cache_1.cache && typeof cache_1.cache.set === "function") {
cache_1.cache.set(cacheKey, userInfo, 36000000); // 10 hours
}
}
catch (e) {
console.warn("Failed to set user info in cache:", e);
}
// Set in localStorage (user info is too large for cookies)
try {
window.localStorage.setItem(cookieName, JSON.stringify(userInfo));
}
catch (e) {
console.warn("Failed to set user info in localStorage:", e);
}
}
/**
* Clear refresh key
*/
function clearRefreshKey(domain) {
const host = domain || getDomain();
if (!host)
return;
const cookieName = `${host}_refresh_key`;
const cacheKey = `refresh_key_${host}`;
// Clear from cache
if (cache_1.cache && typeof cache_1.cache.delete === "function") {
try {
cache_1.cache.delete(cacheKey);
}
catch (e) {
console.warn("Failed to delete refresh key from cache:", e);
}
}
// Clear from localStorage
if (typeof window !== "undefined" && window.localStorage) {
try {
window.localStorage.removeItem(cookieName);
}
catch (e) {
console.warn("Failed to remove refresh key from localStorage:", e);
}
}
// Clear from cookie
if (typeof document !== "undefined") {
document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
}
}
/**
* Clear firebase token
*/
function clearFirebaseToken(domain) {
const host = domain || getDomain();
if (!host)
return;
const cookieName = `${host}_firebase_token`;
const cacheKey = `firebase_token_${host}`;
// Clear from cache
if (cache_1.cache && typeof cache_1.cache.delete === "function") {
try {
cache_1.cache.delete(cacheKey);
}
catch (e) {
console.warn("Failed to delete firebase token from cache:", e);
}
}
// Clear from localStorage
if (typeof window !== "undefined" && window.localStorage) {
try {
window.localStorage.removeItem(cookieName);
}
catch (e) {
console.warn("Failed to remove firebase token from localStorage:", e);
}
}
// Clear from cookie
if (typeof document !== "undefined") {
document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
}
}
/**
* Clear user info
*/
function clearUserInfo(domain) {
const host = domain || getDomain();
if (!host)
return;
const cookieName = `${host}_user_info`;
const cacheKey = `user_info_${host}`;
// Clear from cache
if (cache_1.cache && typeof cache_1.cache.delete === "function") {
try {
cache_1.cache.delete(cacheKey);
}
catch (e) {
console.warn("Failed to delete user info from cache:", e);
}
}
// Clear from localStorage
if (typeof window !== "undefined" && window.localStorage) {
try {
window.localStorage.removeItem(cookieName);
}
catch (e) {
console.warn("Failed to remove user info from localStorage:", e);
}
}
}
/**
* Clear all user data (logout)
*/
function clearAllUserData(domain) {
clearAuthKey(domain);
clearRefreshKey(domain);
clearFirebaseToken(domain);
clearUserInfo(domain);
}