@clianta/sdk 1.6.3 → 1.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.6.3
2
+ * Clianta SDK v1.6.5
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -8,19 +8,29 @@
8
8
  * @see SDK_VERSION in core/config.ts
9
9
  */
10
10
  /** SDK Version */
11
- const SDK_VERSION = '1.6.2';
11
+ const SDK_VERSION = '1.6.5';
12
12
  /** Default API endpoint — reads from env or falls back to localhost */
13
13
  const getDefaultApiEndpoint = () => {
14
- // Build-time env var (works with Next.js, Vite, CRA, etc.)
14
+ // Next.js (process.env)
15
15
  if (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_CLIANTA_API_ENDPOINT) {
16
16
  return process.env.NEXT_PUBLIC_CLIANTA_API_ENDPOINT;
17
17
  }
18
- if (typeof process !== 'undefined' && process.env?.VITE_CLIANTA_API_ENDPOINT) {
19
- return process.env.VITE_CLIANTA_API_ENDPOINT;
18
+ // Vite / Vue / Svelte / SvelteKit (import.meta.env)
19
+ try {
20
+ // @ts-ignore — import.meta.env is Vite-specific
21
+ if (typeof import.meta !== 'undefined' && import.meta.env?.VITE_CLIANTA_API_ENDPOINT) {
22
+ // @ts-ignore
23
+ return import.meta.env.VITE_CLIANTA_API_ENDPOINT;
24
+ }
25
+ }
26
+ catch {
27
+ // import.meta not available in this environment
20
28
  }
29
+ // Create React App (process.env)
21
30
  if (typeof process !== 'undefined' && process.env?.REACT_APP_CLIANTA_API_ENDPOINT) {
22
31
  return process.env.REACT_APP_CLIANTA_API_ENDPOINT;
23
32
  }
33
+ // Generic fallback
24
34
  if (typeof process !== 'undefined' && process.env?.CLIANTA_API_ENDPOINT) {
25
35
  return process.env.CLIANTA_API_ENDPOINT;
26
36
  }
@@ -37,6 +47,7 @@ const DEFAULT_PLUGINS = [
37
47
  'exitIntent',
38
48
  'errors',
39
49
  'performance',
50
+ 'autoIdentify',
40
51
  ];
41
52
  /** Default configuration values */
42
53
  const DEFAULT_CONFIG = {
@@ -2229,6 +2240,296 @@ class PopupFormsPlugin extends BasePlugin {
2229
2240
  }
2230
2241
  }
2231
2242
 
2243
+ /**
2244
+ * Clianta SDK - Auto-Identify Plugin
2245
+ * Automatically detects logged-in users by checking JWT tokens in
2246
+ * cookies, localStorage, and sessionStorage. Works with any auth provider:
2247
+ * Clerk, Firebase, Auth0, Supabase, NextAuth, Passport, custom JWT, etc.
2248
+ *
2249
+ * How it works:
2250
+ * 1. On init + periodically, scans for JWT tokens
2251
+ * 2. Decodes the JWT payload (base64, no secret needed)
2252
+ * 3. Extracts email/name from standard JWT claims
2253
+ * 4. Calls tracker.identify() automatically
2254
+ *
2255
+ * @see SDK_VERSION in core/config.ts
2256
+ */
2257
+ /** Known auth cookie patterns and their JWT locations */
2258
+ const AUTH_COOKIE_PATTERNS = [
2259
+ // Clerk
2260
+ '__session',
2261
+ '__clerk_db_jwt',
2262
+ // NextAuth
2263
+ 'next-auth.session-token',
2264
+ '__Secure-next-auth.session-token',
2265
+ // Supabase
2266
+ 'sb-access-token',
2267
+ // Auth0
2268
+ 'auth0.is.authenticated',
2269
+ // Firebase — uses localStorage, handled separately
2270
+ // Generic patterns
2271
+ 'token',
2272
+ 'jwt',
2273
+ 'access_token',
2274
+ 'session_token',
2275
+ 'auth_token',
2276
+ 'id_token',
2277
+ ];
2278
+ /** localStorage/sessionStorage key patterns for auth tokens */
2279
+ const STORAGE_KEY_PATTERNS = [
2280
+ // Supabase
2281
+ 'sb-',
2282
+ 'supabase.auth.',
2283
+ // Firebase
2284
+ 'firebase:authUser:',
2285
+ // Auth0
2286
+ 'auth0spajs',
2287
+ '@@auth0spajs@@',
2288
+ // Generic
2289
+ 'token',
2290
+ 'jwt',
2291
+ 'auth',
2292
+ 'user',
2293
+ 'session',
2294
+ ];
2295
+ /** Standard JWT claim fields for email */
2296
+ const EMAIL_CLAIMS = ['email', 'sub', 'preferred_username', 'user_email', 'mail'];
2297
+ const NAME_CLAIMS = ['name', 'full_name', 'display_name', 'given_name'];
2298
+ const FIRST_NAME_CLAIMS = ['given_name', 'first_name', 'firstName'];
2299
+ const LAST_NAME_CLAIMS = ['family_name', 'last_name', 'lastName'];
2300
+ class AutoIdentifyPlugin extends BasePlugin {
2301
+ constructor() {
2302
+ super(...arguments);
2303
+ this.name = 'autoIdentify';
2304
+ this.checkInterval = null;
2305
+ this.identifiedEmail = null;
2306
+ this.checkCount = 0;
2307
+ this.MAX_CHECKS = 30; // Stop checking after ~5 minutes
2308
+ this.CHECK_INTERVAL_MS = 10000; // Check every 10 seconds
2309
+ }
2310
+ init(tracker) {
2311
+ super.init(tracker);
2312
+ if (typeof window === 'undefined')
2313
+ return;
2314
+ // First check after 2 seconds (give auth providers time to init)
2315
+ setTimeout(() => this.checkForAuthUser(), 2000);
2316
+ // Then check periodically
2317
+ this.checkInterval = setInterval(() => {
2318
+ this.checkCount++;
2319
+ if (this.checkCount >= this.MAX_CHECKS) {
2320
+ // Stop checking after MAX_CHECKS — user probably isn't logged in
2321
+ if (this.checkInterval) {
2322
+ clearInterval(this.checkInterval);
2323
+ this.checkInterval = null;
2324
+ }
2325
+ return;
2326
+ }
2327
+ this.checkForAuthUser();
2328
+ }, this.CHECK_INTERVAL_MS);
2329
+ }
2330
+ destroy() {
2331
+ if (this.checkInterval) {
2332
+ clearInterval(this.checkInterval);
2333
+ this.checkInterval = null;
2334
+ }
2335
+ super.destroy();
2336
+ }
2337
+ /**
2338
+ * Main check — scan all sources for auth tokens
2339
+ */
2340
+ checkForAuthUser() {
2341
+ if (!this.tracker || this.identifiedEmail)
2342
+ return;
2343
+ // 1. Check cookies for JWTs
2344
+ const cookieUser = this.checkCookies();
2345
+ if (cookieUser) {
2346
+ this.identifyUser(cookieUser);
2347
+ return;
2348
+ }
2349
+ // 2. Check localStorage
2350
+ const localUser = this.checkStorage(localStorage);
2351
+ if (localUser) {
2352
+ this.identifyUser(localUser);
2353
+ return;
2354
+ }
2355
+ // 3. Check sessionStorage
2356
+ const sessionUser = this.checkStorage(sessionStorage);
2357
+ if (sessionUser) {
2358
+ this.identifyUser(sessionUser);
2359
+ return;
2360
+ }
2361
+ }
2362
+ /**
2363
+ * Identify the user and stop checking
2364
+ */
2365
+ identifyUser(user) {
2366
+ if (!this.tracker || this.identifiedEmail === user.email)
2367
+ return;
2368
+ this.identifiedEmail = user.email;
2369
+ this.tracker.identify(user.email, {
2370
+ firstName: user.firstName,
2371
+ lastName: user.lastName,
2372
+ });
2373
+ // Stop interval — we found the user
2374
+ if (this.checkInterval) {
2375
+ clearInterval(this.checkInterval);
2376
+ this.checkInterval = null;
2377
+ }
2378
+ }
2379
+ /**
2380
+ * Scan cookies for JWT tokens
2381
+ */
2382
+ checkCookies() {
2383
+ if (typeof document === 'undefined')
2384
+ return null;
2385
+ try {
2386
+ const cookies = document.cookie.split(';').map(c => c.trim());
2387
+ for (const cookie of cookies) {
2388
+ const [name, ...valueParts] = cookie.split('=');
2389
+ const value = valueParts.join('=');
2390
+ const cookieName = name.trim().toLowerCase();
2391
+ // Check if this cookie matches known auth patterns
2392
+ const isAuthCookie = AUTH_COOKIE_PATTERNS.some(pattern => cookieName.includes(pattern.toLowerCase()));
2393
+ if (isAuthCookie && value) {
2394
+ const user = this.extractUserFromToken(decodeURIComponent(value));
2395
+ if (user)
2396
+ return user;
2397
+ }
2398
+ }
2399
+ }
2400
+ catch {
2401
+ // Cookie access may fail in some environments
2402
+ }
2403
+ return null;
2404
+ }
2405
+ /**
2406
+ * Scan localStorage or sessionStorage for auth tokens
2407
+ */
2408
+ checkStorage(storage) {
2409
+ try {
2410
+ for (let i = 0; i < storage.length; i++) {
2411
+ const key = storage.key(i);
2412
+ if (!key)
2413
+ continue;
2414
+ const keyLower = key.toLowerCase();
2415
+ const isAuthKey = STORAGE_KEY_PATTERNS.some(pattern => keyLower.includes(pattern.toLowerCase()));
2416
+ if (isAuthKey) {
2417
+ const value = storage.getItem(key);
2418
+ if (!value)
2419
+ continue;
2420
+ // Try as direct JWT
2421
+ const user = this.extractUserFromToken(value);
2422
+ if (user)
2423
+ return user;
2424
+ // Try as JSON containing a token
2425
+ try {
2426
+ const json = JSON.parse(value);
2427
+ const user = this.extractUserFromJson(json);
2428
+ if (user)
2429
+ return user;
2430
+ }
2431
+ catch {
2432
+ // Not JSON, skip
2433
+ }
2434
+ }
2435
+ }
2436
+ }
2437
+ catch {
2438
+ // Storage access may fail (iframe, security restrictions)
2439
+ }
2440
+ return null;
2441
+ }
2442
+ /**
2443
+ * Try to extract user info from a JWT token string
2444
+ */
2445
+ extractUserFromToken(token) {
2446
+ // JWT format: header.payload.signature
2447
+ const parts = token.split('.');
2448
+ if (parts.length !== 3)
2449
+ return null;
2450
+ try {
2451
+ const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')));
2452
+ return this.extractUserFromClaims(payload);
2453
+ }
2454
+ catch {
2455
+ return null;
2456
+ }
2457
+ }
2458
+ /**
2459
+ * Extract user info from a JSON object (e.g., Firebase auth user stored in localStorage)
2460
+ */
2461
+ extractUserFromJson(data) {
2462
+ if (!data || typeof data !== 'object')
2463
+ return null;
2464
+ // Direct user object
2465
+ const user = this.extractUserFromClaims(data);
2466
+ if (user)
2467
+ return user;
2468
+ // Nested: { user: { email } } or { data: { user: { email } } }
2469
+ for (const key of ['user', 'data', 'session', 'currentUser', 'authUser', 'access_token', 'token']) {
2470
+ if (data[key]) {
2471
+ if (typeof data[key] === 'string') {
2472
+ // Might be a JWT inside JSON
2473
+ const tokenUser = this.extractUserFromToken(data[key]);
2474
+ if (tokenUser)
2475
+ return tokenUser;
2476
+ }
2477
+ else if (typeof data[key] === 'object') {
2478
+ const nestedUser = this.extractUserFromClaims(data[key]);
2479
+ if (nestedUser)
2480
+ return nestedUser;
2481
+ }
2482
+ }
2483
+ }
2484
+ return null;
2485
+ }
2486
+ /**
2487
+ * Extract user from JWT claims or user object
2488
+ */
2489
+ extractUserFromClaims(claims) {
2490
+ if (!claims || typeof claims !== 'object')
2491
+ return null;
2492
+ // Find email
2493
+ let email = null;
2494
+ for (const claim of EMAIL_CLAIMS) {
2495
+ const value = claims[claim];
2496
+ if (value && typeof value === 'string' && value.includes('@') && value.includes('.')) {
2497
+ email = value;
2498
+ break;
2499
+ }
2500
+ }
2501
+ if (!email)
2502
+ return null;
2503
+ // Find name
2504
+ let firstName;
2505
+ let lastName;
2506
+ for (const claim of FIRST_NAME_CLAIMS) {
2507
+ if (claims[claim] && typeof claims[claim] === 'string') {
2508
+ firstName = claims[claim];
2509
+ break;
2510
+ }
2511
+ }
2512
+ for (const claim of LAST_NAME_CLAIMS) {
2513
+ if (claims[claim] && typeof claims[claim] === 'string') {
2514
+ lastName = claims[claim];
2515
+ break;
2516
+ }
2517
+ }
2518
+ // If no first/last name, try full name
2519
+ if (!firstName) {
2520
+ for (const claim of NAME_CLAIMS) {
2521
+ if (claims[claim] && typeof claims[claim] === 'string') {
2522
+ const parts = claims[claim].split(' ');
2523
+ firstName = parts[0];
2524
+ lastName = lastName || parts.slice(1).join(' ') || undefined;
2525
+ break;
2526
+ }
2527
+ }
2528
+ }
2529
+ return { email, firstName, lastName };
2530
+ }
2531
+ }
2532
+
2232
2533
  /**
2233
2534
  * Clianta SDK - Plugins Index
2234
2535
  * Version is defined in core/config.ts as SDK_VERSION
@@ -2258,6 +2559,8 @@ function getPlugin(name) {
2258
2559
  return new PerformancePlugin();
2259
2560
  case 'popupForms':
2260
2561
  return new PopupFormsPlugin();
2562
+ case 'autoIdentify':
2563
+ return new AutoIdentifyPlugin();
2261
2564
  default:
2262
2565
  throw new Error(`Unknown plugin: ${name}`);
2263
2566
  }