@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
  */
@@ -8,7 +8,7 @@
8
8
  * @see SDK_VERSION in core/config.ts
9
9
  */
10
10
  /** SDK Version */
11
- const SDK_VERSION = '1.6.4';
11
+ const SDK_VERSION = '1.6.6';
12
12
  /** Default API endpoint — reads from env or falls back to localhost */
13
13
  const getDefaultApiEndpoint = () => {
14
14
  // Next.js (process.env)
@@ -47,6 +47,7 @@ const DEFAULT_PLUGINS = [
47
47
  'exitIntent',
48
48
  'errors',
49
49
  'performance',
50
+ 'autoIdentify',
50
51
  ];
51
52
  /** Default configuration values */
52
53
  const DEFAULT_CONFIG = {
@@ -2239,6 +2240,316 @@ class PopupFormsPlugin extends BasePlugin {
2239
2240
  }
2240
2241
  }
2241
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(() => {
2316
+ try {
2317
+ this.checkForAuthUser();
2318
+ }
2319
+ catch { /* silently fail */ }
2320
+ }, 2000);
2321
+ // Then check periodically
2322
+ this.checkInterval = setInterval(() => {
2323
+ this.checkCount++;
2324
+ if (this.checkCount >= this.MAX_CHECKS) {
2325
+ if (this.checkInterval) {
2326
+ clearInterval(this.checkInterval);
2327
+ this.checkInterval = null;
2328
+ }
2329
+ return;
2330
+ }
2331
+ try {
2332
+ this.checkForAuthUser();
2333
+ }
2334
+ catch { /* silently fail */ }
2335
+ }, this.CHECK_INTERVAL_MS);
2336
+ }
2337
+ destroy() {
2338
+ if (this.checkInterval) {
2339
+ clearInterval(this.checkInterval);
2340
+ this.checkInterval = null;
2341
+ }
2342
+ super.destroy();
2343
+ }
2344
+ /**
2345
+ * Main check — scan all sources for auth tokens
2346
+ */
2347
+ checkForAuthUser() {
2348
+ if (!this.tracker || this.identifiedEmail)
2349
+ return;
2350
+ try {
2351
+ // 1. Check cookies for JWTs
2352
+ const cookieUser = this.checkCookies();
2353
+ if (cookieUser) {
2354
+ this.identifyUser(cookieUser);
2355
+ return;
2356
+ }
2357
+ }
2358
+ catch { /* cookie access blocked */ }
2359
+ try {
2360
+ // 2. Check localStorage
2361
+ if (typeof localStorage !== 'undefined') {
2362
+ const localUser = this.checkStorage(localStorage);
2363
+ if (localUser) {
2364
+ this.identifyUser(localUser);
2365
+ return;
2366
+ }
2367
+ }
2368
+ }
2369
+ catch { /* localStorage access blocked */ }
2370
+ try {
2371
+ // 3. Check sessionStorage
2372
+ if (typeof sessionStorage !== 'undefined') {
2373
+ const sessionUser = this.checkStorage(sessionStorage);
2374
+ if (sessionUser) {
2375
+ this.identifyUser(sessionUser);
2376
+ return;
2377
+ }
2378
+ }
2379
+ }
2380
+ catch { /* sessionStorage access blocked */ }
2381
+ }
2382
+ /**
2383
+ * Identify the user and stop checking
2384
+ */
2385
+ identifyUser(user) {
2386
+ if (!this.tracker || this.identifiedEmail === user.email)
2387
+ return;
2388
+ this.identifiedEmail = user.email;
2389
+ this.tracker.identify(user.email, {
2390
+ firstName: user.firstName,
2391
+ lastName: user.lastName,
2392
+ });
2393
+ // Stop interval — we found the user
2394
+ if (this.checkInterval) {
2395
+ clearInterval(this.checkInterval);
2396
+ this.checkInterval = null;
2397
+ }
2398
+ }
2399
+ /**
2400
+ * Scan cookies for JWT tokens
2401
+ */
2402
+ checkCookies() {
2403
+ if (typeof document === 'undefined')
2404
+ return null;
2405
+ try {
2406
+ const cookies = document.cookie.split(';').map(c => c.trim());
2407
+ for (const cookie of cookies) {
2408
+ const [name, ...valueParts] = cookie.split('=');
2409
+ const value = valueParts.join('=');
2410
+ const cookieName = name.trim().toLowerCase();
2411
+ // Check if this cookie matches known auth patterns
2412
+ const isAuthCookie = AUTH_COOKIE_PATTERNS.some(pattern => cookieName.includes(pattern.toLowerCase()));
2413
+ if (isAuthCookie && value) {
2414
+ const user = this.extractUserFromToken(decodeURIComponent(value));
2415
+ if (user)
2416
+ return user;
2417
+ }
2418
+ }
2419
+ }
2420
+ catch {
2421
+ // Cookie access may fail in some environments
2422
+ }
2423
+ return null;
2424
+ }
2425
+ /**
2426
+ * Scan localStorage or sessionStorage for auth tokens
2427
+ */
2428
+ checkStorage(storage) {
2429
+ try {
2430
+ for (let i = 0; i < storage.length; i++) {
2431
+ const key = storage.key(i);
2432
+ if (!key)
2433
+ continue;
2434
+ const keyLower = key.toLowerCase();
2435
+ const isAuthKey = STORAGE_KEY_PATTERNS.some(pattern => keyLower.includes(pattern.toLowerCase()));
2436
+ if (isAuthKey) {
2437
+ const value = storage.getItem(key);
2438
+ if (!value)
2439
+ continue;
2440
+ // Try as direct JWT
2441
+ const user = this.extractUserFromToken(value);
2442
+ if (user)
2443
+ return user;
2444
+ // Try as JSON containing a token
2445
+ try {
2446
+ const json = JSON.parse(value);
2447
+ const user = this.extractUserFromJson(json);
2448
+ if (user)
2449
+ return user;
2450
+ }
2451
+ catch {
2452
+ // Not JSON, skip
2453
+ }
2454
+ }
2455
+ }
2456
+ }
2457
+ catch {
2458
+ // Storage access may fail (iframe, security restrictions)
2459
+ }
2460
+ return null;
2461
+ }
2462
+ /**
2463
+ * Try to extract user info from a JWT token string
2464
+ */
2465
+ extractUserFromToken(token) {
2466
+ // JWT format: header.payload.signature
2467
+ const parts = token.split('.');
2468
+ if (parts.length !== 3)
2469
+ return null;
2470
+ try {
2471
+ const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')));
2472
+ return this.extractUserFromClaims(payload);
2473
+ }
2474
+ catch {
2475
+ return null;
2476
+ }
2477
+ }
2478
+ /**
2479
+ * Extract user info from a JSON object (e.g., Firebase auth user stored in localStorage)
2480
+ */
2481
+ extractUserFromJson(data) {
2482
+ if (!data || typeof data !== 'object')
2483
+ return null;
2484
+ // Direct user object
2485
+ const user = this.extractUserFromClaims(data);
2486
+ if (user)
2487
+ return user;
2488
+ // Nested: { user: { email } } or { data: { user: { email } } }
2489
+ for (const key of ['user', 'data', 'session', 'currentUser', 'authUser', 'access_token', 'token']) {
2490
+ if (data[key]) {
2491
+ if (typeof data[key] === 'string') {
2492
+ // Might be a JWT inside JSON
2493
+ const tokenUser = this.extractUserFromToken(data[key]);
2494
+ if (tokenUser)
2495
+ return tokenUser;
2496
+ }
2497
+ else if (typeof data[key] === 'object') {
2498
+ const nestedUser = this.extractUserFromClaims(data[key]);
2499
+ if (nestedUser)
2500
+ return nestedUser;
2501
+ }
2502
+ }
2503
+ }
2504
+ return null;
2505
+ }
2506
+ /**
2507
+ * Extract user from JWT claims or user object
2508
+ */
2509
+ extractUserFromClaims(claims) {
2510
+ if (!claims || typeof claims !== 'object')
2511
+ return null;
2512
+ // Find email
2513
+ let email = null;
2514
+ for (const claim of EMAIL_CLAIMS) {
2515
+ const value = claims[claim];
2516
+ if (value && typeof value === 'string' && value.includes('@') && value.includes('.')) {
2517
+ email = value;
2518
+ break;
2519
+ }
2520
+ }
2521
+ if (!email)
2522
+ return null;
2523
+ // Find name
2524
+ let firstName;
2525
+ let lastName;
2526
+ for (const claim of FIRST_NAME_CLAIMS) {
2527
+ if (claims[claim] && typeof claims[claim] === 'string') {
2528
+ firstName = claims[claim];
2529
+ break;
2530
+ }
2531
+ }
2532
+ for (const claim of LAST_NAME_CLAIMS) {
2533
+ if (claims[claim] && typeof claims[claim] === 'string') {
2534
+ lastName = claims[claim];
2535
+ break;
2536
+ }
2537
+ }
2538
+ // If no first/last name, try full name
2539
+ if (!firstName) {
2540
+ for (const claim of NAME_CLAIMS) {
2541
+ if (claims[claim] && typeof claims[claim] === 'string') {
2542
+ const parts = claims[claim].split(' ');
2543
+ firstName = parts[0];
2544
+ lastName = lastName || parts.slice(1).join(' ') || undefined;
2545
+ break;
2546
+ }
2547
+ }
2548
+ }
2549
+ return { email, firstName, lastName };
2550
+ }
2551
+ }
2552
+
2242
2553
  /**
2243
2554
  * Clianta SDK - Plugins Index
2244
2555
  * Version is defined in core/config.ts as SDK_VERSION
@@ -2268,6 +2579,8 @@ function getPlugin(name) {
2268
2579
  return new PerformancePlugin();
2269
2580
  case 'popupForms':
2270
2581
  return new PopupFormsPlugin();
2582
+ case 'autoIdentify':
2583
+ return new AutoIdentifyPlugin();
2271
2584
  default:
2272
2585
  throw new Error(`Unknown plugin: ${name}`);
2273
2586
  }