@clianta/sdk 1.6.4 → 1.6.6

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