feat: unique device id

This commit is contained in:
2025-05-21 22:10:46 +02:00
parent d4adc1b538
commit b8f3fa0a32
2 changed files with 40 additions and 2 deletions

View File

@ -1,7 +1,14 @@
import type { FC } from "react";
import { useEffect, useState, type FC } from "react";
import { getDeviceId } from "./util/deviceId";
const App: FC = () => {
return <div>Hello</div>;
const [deviceId, setDeviceId] = useState("");
useEffect(() => {
getDeviceId().then((id) => setDeviceId(id));
}, []);
return <div>{deviceId}</div>;
};
export default App;

31
web/src/util/deviceId.ts Normal file
View File

@ -0,0 +1,31 @@
export const getDeviceId = async () => {
const existing = localStorage.getItem("guard-device-id");
if (existing) return existing;
const fingerprintParts = [
navigator.userAgent, // Browser and OS
screen.width + "x" + screen.height, // Screen resolution
screen.colorDepth, // Color depth
Intl.DateTimeFormat().resolvedOptions().timeZone, // Time zone
navigator.platform, // OS platform
navigator.hardwareConcurrency, // Number of CPU cores
navigator.language, // Primary language
navigator.maxTouchPoints, // Touch capability
];
console.log(fingerprintParts);
const rawFingerprint = fingerprintParts.join("|");
const encoder = new TextEncoder();
const data = encoder.encode(rawFingerprint);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const deviceId = hashArray
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
localStorage.setItem("guard-device-id", deviceId);
return deviceId; // A 64-character hex string
};