UNPKG

@devvai/devv-code-backend

Version:

Backend SDK for Devv Code - Provides authentication, data management, email and AI capabilities

62 lines (61 loc) 2.06 kB
"use strict"; /** * Device ID management for Devv Code Frontend SDK * Generates and persists a unique device identifier */ Object.defineProperty(exports, "__esModule", { value: true }); exports.getEncryptedDeviceId = getEncryptedDeviceId; exports.initializeDeviceId = initializeDeviceId; const js_sha256_1 = require("js-sha256"); const DEVICE_ID_KEY = 'DEVV_CODE_DEVICE_ID'; /** * Generate a UUID v4 */ function generateUUID() { // Use crypto.randomUUID if available (modern browsers) if (typeof crypto !== 'undefined' && crypto.randomUUID) { return crypto.randomUUID(); } // Fallback implementation return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { const r = Math.random() * 16 | 0; const v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } /** * Generate encrypted device ID * 1. Generate UUID * 2. First hash: sha256(uuid).slice(0, 32) * 3. Second hash: sha256(firstHash).slice(0, 8) + firstHash */ function generateEncryptedDeviceId() { const uuid = generateUUID(); const firstHash = (0, js_sha256_1.sha256)(uuid).slice(0, 32); const finalId = (0, js_sha256_1.sha256)(firstHash).slice(0, 8) + firstHash; return finalId; } /** * Get the device ID, creating it if it doesn't exist * Always returns the final encrypted format */ function getEncryptedDeviceId() { // Check if we're in a browser environment if (typeof globalThis === 'undefined' || typeof globalThis.localStorage === 'undefined') { console.warn('localStorage not available, generating temporary device ID'); return generateEncryptedDeviceId(); } let deviceId = localStorage.getItem(DEVICE_ID_KEY); if (!deviceId) { deviceId = generateEncryptedDeviceId(); localStorage.setItem(DEVICE_ID_KEY, deviceId); } return deviceId; } /** * Initialize device ID (called once when SDK is first loaded) */ function initializeDeviceId() { // This ensures device ID is created on first use getEncryptedDeviceId(); }