All files / src/lib device-id.ts

87.33% Statements 131/150
47.82% Branches 11/23
100% Functions 6/6
87.33% Lines 131/150

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 1511x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 28x 28x 28x     28x 28x 28x 28x 28x 28x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 26x 26x 28x 2x 2x 2x 2x 28x 1x 1x 1x 1x 1x 25x 25x     25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x       25x 1x 1x 1x 1x 1x 25x 25x 25x 25x 2425x 2425x 2425x 2425x 25x 25x 25x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x     4x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x     3x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x                 5x 5x 5x 5x 5x 5x 5x 5x 5x  
/**
 * Device Identification System
 *
 * Generates and maintains a unique device ID for tracking cart synchronization
 * across multiple devices for the same user.
 */
 
import { logger } from '@/lib/logging';
 
const DEVICE_ID_KEY = 'device_id_v1';
 
/**
 * Get or create a unique device ID
 * Stored in localStorage for persistence
 */
export function getOrCreateDeviceId(): string {
  // Server-side rendering check
  if (typeof window === 'undefined') {
    return 'server';
  }
 
  try {
    // Try to get existing device ID
    let deviceId = localStorage.getItem(DEVICE_ID_KEY);
 
    if (!deviceId) {
      // Generate new device ID
      const fingerprint = generateDeviceFingerprint();
      const random = Math.random().toString(36).substr(2, 9);
      const timestamp = Date.now().toString(36);
 
      deviceId = `${fingerprint}-${timestamp}-${random}`;
 
      // Save to localStorage
      localStorage.setItem(DEVICE_ID_KEY, deviceId);
    }
 
    return deviceId;
  } catch (error) {
    logger.error('Failed to get/create device ID', error instanceof Error ? error : new Error(String(error)), { category: 'DEVICE' });
    // Fallback to session-based ID
    return `fallback-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }
}
 
/**
 * Generate a basic device fingerprint
 * Based on browser characteristics (not for security, just for identification)
 */
function generateDeviceFingerprint(): string {
  if (typeof window === 'undefined') {
    return 'server';
  }
 
  try {
    // Collect browser info
    const userAgent = navigator.userAgent || '';
    const language = navigator.language || '';
    const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || '';
    const platform = navigator.platform || '';
    const screenResolution = `${window.screen.width}x${window.screen.height}`;
 
    // Combine into fingerprint string
    const fingerprintString = [
      userAgent,
      language,
      timezone,
      platform,
      screenResolution,
    ].join('|');
 
    // Hash the fingerprint
    return hashString(fingerprintString).substr(0, 8);
  } catch (error) {
    logger.error('Failed to generate device fingerprint', error instanceof Error ? error : new Error(String(error)), { category: 'DEVICE' });
    return 'unknown';
  }
}
 
/**
 * Simple hash function for string
 * Not cryptographically secure - just for identification
 */
function hashString(str: string): string {
  let hash = 0;
 
  for (let i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash = hash & hash; // Convert to 32-bit integer
  }
 
  return Math.abs(hash).toString(16);
}
 
/**
 * Reset device ID (useful for testing or logout)
 */
export function resetDeviceId(): void {
  if (typeof window === 'undefined') return;
 
  try {
    localStorage.removeItem(DEVICE_ID_KEY);
  } catch (error) {
    logger.error('Failed to reset device ID', error instanceof Error ? error : new Error(String(error)), { category: 'DEVICE' });
  }
}
 
/**
 * Check if device ID exists
 */
export function hasDeviceId(): boolean {
  if (typeof window === 'undefined') return false;
 
  try {
    return localStorage.getItem(DEVICE_ID_KEY) !== null;
  } catch {
    return false;
  }
}
 
/**
 * Get device info for debugging
 */
export function getDeviceInfo(): {
  deviceId: string;
  userAgent: string;
  language: string;
  timezone: string;
  platform: string;
  screenResolution: string;
} {
  if (typeof window === 'undefined') {
    return {
      deviceId: 'server',
      userAgent: '',
      language: '',
      timezone: '',
      platform: '',
      screenResolution: ''};
  }
 
  return {
    deviceId: getOrCreateDeviceId(),
    userAgent: navigator.userAgent,
    language: navigator.language,
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    platform: navigator.platform,
    screenResolution: `${window.screen.width}x${window.screen.height}`};
}