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