File size: 13,595 Bytes
168b0da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
"""
Minimal Privacy-Focused Fingerprint Manager
Automatically identifies unique users with minimal device data collection.
Maintains privacy through hashing and generates consistent UUIDs.
"""

import hashlib
import json
import platform
import psutil
import uuid
import os
from typing import Dict, Any, Optional
import logging
from pathlib import Path


class MinimalFingerprintManager:
    """
    Minimal device fingerprinting for automatic user identification.
    Collects only essential data needed for reliable identification.
    All sensitive data is hashed for privacy protection.
    """

    def __init__(self):
        """Initialize the fingerprint manager."""
        self.logger = logging.getLogger(__name__)
        self.cache_file = Path("user_fingerprints.json")
        self._load_cache()

    def _load_cache(self) -> None:
        """Load cached fingerprints and user mappings."""
        try:
            if self.cache_file.exists():
                with open(self.cache_file, "r") as f:
                    self.cache = json.load(f)
            else:
                self.cache = {
                    "fingerprints": {},  # fingerprint_hash -> user_uuid
                    "user_stats": {},  # user_uuid -> usage stats
                    "created_at": {},  # user_uuid -> first_seen timestamp
                }
        except Exception as e:
            self.logger.warning(f"Failed to load fingerprint cache: {e}")
            self.cache = {"fingerprints": {}, "user_stats": {}, "created_at": {}}

    def _save_cache(self) -> None:
        """Save fingerprint cache to disk."""
        try:
            with open(self.cache_file, "w") as f:
                json.dump(self.cache, f, indent=2)
        except Exception as e:
            self.logger.warning(f"Failed to save fingerprint cache: {e}")

    def _get_minimal_fingerprint(self) -> Dict[str, Any]:
        """
        Collect minimal device data for fingerprinting.
        Only essential data that's stable and privacy-safe.
        """
        try:
            # Core system information (stable across reboots)
            fingerprint = {
                # OS and architecture (stable)
                "os_system": platform.system(),
                "os_release": platform.release(),
                "architecture": platform.machine(),
                # Hardware characteristics (stable)
                "cpu_count_logical": psutil.cpu_count(logical=True),
                "cpu_count_physical": psutil.cpu_count(logical=False),
                "memory_total_gb": round(psutil.virtual_memory().total / (1024**3), 1),
                # System boot time hash (for session consistency)
                "boot_time_hash": hashlib.sha256(
                    str(int(psutil.boot_time())).encode()
                ).hexdigest()[:16],
                # User context hash (privacy-safe)
                "user_context_hash": hashlib.sha256(
                    (str(Path.home()) + os.getlogin()).encode()
                ).hexdigest()[:16],
            }

            # Add MAC address hash if available (most stable identifier)
            try:
                for interface, addrs in psutil.net_if_addrs().items():
                    for addr in addrs:
                        if (
                            addr.family == psutil.AF_LINK
                            and addr.address != "00:00:00:00:00:00"
                        ):
                            fingerprint["mac_hash"] = hashlib.sha256(
                                addr.address.encode()
                            ).hexdigest()[:16]
                            break
                    if "mac_hash" in fingerprint:
                        break
            except Exception:
                pass  # MAC address not available, continue without it

            return fingerprint

        except Exception as e:
            self.logger.error(f"Error generating fingerprint: {e}")
            # Fallback minimal fingerprint
            return {
                "os_system": platform.system(),
                "fallback": True,
                "error": str(e)[:50],
            }

    def _generate_fingerprint_hash(self, fingerprint: Dict[str, Any]) -> str:
        """Generate a consistent hash from fingerprint data."""
        # Sort keys for consistent hashing
        fingerprint_str = json.dumps(fingerprint, sort_keys=True)
        return hashlib.sha256(fingerprint_str.encode()).hexdigest()

    def get_user_uuid(self) -> str:
        """
        Get or create a consistent UUID for the current user.

        Returns:
            str: Consistent UUID for this user/device combination
        """
        # Generate current device fingerprint
        fingerprint = self._get_minimal_fingerprint()
        fingerprint_hash = self._generate_fingerprint_hash(fingerprint)

        # Check if we've seen this fingerprint before
        if fingerprint_hash in self.cache["fingerprints"]:
            user_uuid = self.cache["fingerprints"][fingerprint_hash]
            self.logger.info(f"Recognized returning user: {user_uuid[:8]}...")
        else:
            # New user - generate UUID
            user_uuid = str(uuid.uuid4())
            self.cache["fingerprints"][fingerprint_hash] = user_uuid
            self.cache["created_at"][user_uuid] = psutil.boot_time()
            self.cache["user_stats"][user_uuid] = {
                "total_operations": 0,
                "memories_stored": 0,
                "searches_performed": 0,
                "videos_built": 0,
                "first_seen": psutil.boot_time(),
                "last_seen": psutil.boot_time(),
                "device_info": {
                    "os": fingerprint.get("os_system", "unknown"),
                    "architecture": fingerprint.get("architecture", "unknown"),
                    "cpu_cores": fingerprint.get("cpu_count_logical", 0),
                    "memory_gb": fingerprint.get("memory_total_gb", 0),
                },
            }
            self._save_cache()
            self.logger.info(f"New user registered: {user_uuid[:8]}...")

        # Update last seen
        if user_uuid in self.cache["user_stats"]:
            self.cache["user_stats"][user_uuid]["last_seen"] = psutil.boot_time()
            self._save_cache()

        return user_uuid

    def update_user_stats(self, user_uuid: str, operation_type: str) -> None:
        """
        Update usage statistics for a user.

        Args:
            user_uuid (str): User's UUID
            operation_type (str): Type of operation performed
        """
        if user_uuid not in self.cache["user_stats"]:
            # Initialize stats for existing user
            self.cache["user_stats"][user_uuid] = {
                "total_operations": 0,
                "memories_stored": 0,
                "searches_performed": 0,
                "videos_built": 0,
                "first_seen": psutil.boot_time(),
                "last_seen": psutil.boot_time(),
                "device_info": {
                    "os": "unknown",
                    "architecture": "unknown",
                    "cpu_cores": 0,
                    "memory_gb": 0,
                },
            }

        # Update counters
        stats = self.cache["user_stats"][user_uuid]
        stats["total_operations"] += 1
        stats["last_seen"] = psutil.boot_time()

        # Update specific operation counters
        if operation_type in ["store_memory", "store_document"]:
            stats["memories_stored"] += 1
        elif operation_type in ["search_memory", "chat_with_memory"]:
            stats["searches_performed"] += 1
        elif operation_type == "build_memory_video":
            stats["videos_built"] += 1

        self._save_cache()

    def get_user_stats(self, user_uuid: str) -> Dict[str, Any]:
        """
        Get usage statistics for a user.

        Args:
            user_uuid (str): User's UUID

        Returns:
            Dict: User's usage statistics
        """
        if user_uuid not in self.cache["user_stats"]:
            return {"error": "User not found", "user_uuid": user_uuid}

        stats = self.cache["user_stats"][user_uuid].copy()

        # Add computed fields
        import time

        current_time = time.time()
        stats["days_since_first_seen"] = round(
            (current_time - stats["first_seen"]) / 86400, 1
        )
        stats["days_since_last_seen"] = round(
            (current_time - stats["last_seen"]) / 86400, 1
        )

        return {
            "user_uuid": user_uuid,
            "user_id_short": user_uuid[:8],
            "statistics": stats,
            "privacy_note": "All device data is hashed for privacy protection",
        }

    def get_all_users_stats(self) -> Dict[str, Any]:
        """Get aggregated statistics for all users."""
        total_users = len(self.cache["user_stats"])
        if total_users == 0:
            return {"total_users": 0, "message": "No users registered yet"}

        # Aggregate statistics
        total_operations = sum(
            stats["total_operations"] for stats in self.cache["user_stats"].values()
        )
        total_memories = sum(
            stats["memories_stored"] for stats in self.cache["user_stats"].values()
        )
        total_searches = sum(
            stats["searches_performed"] for stats in self.cache["user_stats"].values()
        )
        total_videos = sum(
            stats["videos_built"] for stats in self.cache["user_stats"].values()
        )

        # Device diversity
        os_counts = {}
        arch_counts = {}
        for stats in self.cache["user_stats"].values():
            device_info = stats.get("device_info", {})
            os_name = device_info.get("os", "unknown")
            arch_name = device_info.get("architecture", "unknown")

            os_counts[os_name] = os_counts.get(os_name, 0) + 1
            arch_counts[arch_name] = arch_counts.get(arch_name, 0) + 1

        return {
            "total_users": total_users,
            "aggregated_stats": {
                "total_operations": total_operations,
                "total_memories_stored": total_memories,
                "total_searches_performed": total_searches,
                "total_videos_built": total_videos,
                "avg_operations_per_user": round(total_operations / total_users, 1),
            },
            "device_diversity": {
                "operating_systems": os_counts,
                "architectures": arch_counts,
            },
            "privacy_note": "All statistics are aggregated and anonymized",
        }

    def get_fingerprint_info(self) -> Dict[str, Any]:
        """Get information about the current device fingerprint."""
        fingerprint = self._get_minimal_fingerprint()
        fingerprint_hash = self._generate_fingerprint_hash(fingerprint)
        user_uuid = self.get_user_uuid()

        return {
            "user_uuid": user_uuid,
            "user_id_short": user_uuid[:8],
            "fingerprint_hash": fingerprint_hash[:16],
            "device_characteristics": {
                "os": fingerprint.get("os_system", "unknown"),
                "architecture": fingerprint.get("architecture", "unknown"),
                "cpu_cores": fingerprint.get("cpu_count_logical", 0),
                "memory_gb": fingerprint.get("memory_total_gb", 0),
                "has_mac_hash": "mac_hash" in fingerprint,
            },
            "privacy_protection": {
                "data_collection": "Minimal - only essential system characteristics",
                "sensitive_data": "All identifying information is hashed",
                "storage": "Local cache only, no external transmission",
                "consistency": "Same device always generates same UUID",
            },
        }


# Global instance for easy access
_fingerprint_manager = None


def get_fingerprint_manager() -> MinimalFingerprintManager:
    """Get the global fingerprint manager instance."""
    global _fingerprint_manager
    if _fingerprint_manager is None:
        _fingerprint_manager = MinimalFingerprintManager()
    return _fingerprint_manager


def get_auto_user_uuid() -> str:
    """
    Convenience function to get automatic user UUID.

    Returns:
        str: Consistent UUID for the current user/device
    """
    return get_fingerprint_manager().get_user_uuid()


def update_user_operation_stats(user_uuid: str, operation_type: str) -> None:
    """
    Convenience function to update user operation statistics.

    Args:
        user_uuid (str): User's UUID
        operation_type (str): Type of operation performed
    """
    get_fingerprint_manager().update_user_stats(user_uuid, operation_type)


if __name__ == "__main__":
    # Test the fingerprinting system
    print("πŸ” Testing Minimal Fingerprint Manager...")

    manager = MinimalFingerprintManager()

    # Test basic functionality
    user_uuid = manager.get_user_uuid()
    print(f"Generated User UUID: {user_uuid}")

    # Test fingerprint info
    info = manager.get_fingerprint_info()
    print(f"Device OS: {info['device_characteristics']['os']}")
    print(f"CPU Cores: {info['device_characteristics']['cpu_cores']}")
    print(f"Memory: {info['device_characteristics']['memory_gb']} GB")

    # Test stats
    manager.update_user_stats(user_uuid, "store_memory")
    manager.update_user_stats(user_uuid, "search_memory")

    stats = manager.get_user_stats(user_uuid)
    print(f"User Stats: {stats['statistics']['total_operations']} operations")

    print("βœ… Fingerprint Manager Test Complete")