class DeviceService { getDeviceFingerprint(): string { // 生成设备指纹 const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); ctx?.fillText('NovelForge', 10, 10); const canvasFingerprint = canvas.toDataURL(); const fingerprint = { userAgent: navigator.userAgent, language: navigator.language, platform: navigator.platform, screen: `${screen.width}x${screen.height}`, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, canvas: canvasFingerprint.slice(-20), plugins: Array.from(navigator.plugins).map(p => p.name).join(','), }; // 生成哈希 return this.simpleHash(JSON.stringify(fingerprint)); } getDeviceInfo() { return { platform: navigator.platform, userAgent: navigator.userAgent, language: navigator.language, screen: { width: screen.width, height: screen.height, colorDepth: screen.colorDepth, }, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, timestamp: new Date().toISOString(), }; } private simpleHash(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 32bit integer } return Math.abs(hash).toString(16); } async verifyDevice(userId: string, deviceFingerprint: string): Promise { // 模拟设备验证 const savedDevices = localStorage.getItem(`devices_${userId}`); if (!savedDevices) { // 第一次登录,保存设备信息 localStorage.setItem(`devices_${userId}`, JSON.stringify([deviceFingerprint])); return true; } const devices = JSON.parse(savedDevices); return devices.includes(deviceFingerprint); } async bindDevice(userId: string, deviceFingerprint: string): Promise { const savedDevices = localStorage.getItem(`devices_${userId}`); const devices = savedDevices ? JSON.parse(savedDevices) : []; if (!devices.includes(deviceFingerprint)) { devices.push(deviceFingerprint); localStorage.setItem(`devices_${userId}`, JSON.stringify(devices)); } } async unbindDevice(userId: string, deviceFingerprint: string): Promise { const savedDevices = localStorage.getItem(`devices_${userId}`); if (savedDevices) { const devices = JSON.parse(savedDevices); const filteredDevices = devices.filter((d: string) => d !== deviceFingerprint); localStorage.setItem(`devices_${userId}`, JSON.stringify(filteredDevices)); } } } export const deviceService = new DeviceService();