59 行
1.4 KiB
TypeScript
59 行
1.4 KiB
TypeScript
export const DEVICE_FINGERPRINT_KEY = "hyb_oa_device_fingerprint";
|
|
|
|
function readCookieFingerprint() {
|
|
if (typeof document === "undefined") {
|
|
return null;
|
|
}
|
|
|
|
const prefix = `${DEVICE_FINGERPRINT_KEY}=`;
|
|
const item = document.cookie
|
|
.split(";")
|
|
.map((value) => value.trim())
|
|
.find((value) => value.startsWith(prefix));
|
|
|
|
if (!item) {
|
|
return null;
|
|
}
|
|
|
|
const rawValue = item.slice(prefix.length);
|
|
try {
|
|
const decoded = decodeURIComponent(rawValue);
|
|
return decoded.trim() ? decoded : null;
|
|
} catch {
|
|
return rawValue.trim() ? rawValue : null;
|
|
}
|
|
}
|
|
|
|
function fallbackFingerprint() {
|
|
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
}
|
|
|
|
function generateFingerprint() {
|
|
if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
|
|
return crypto.randomUUID();
|
|
}
|
|
|
|
return fallbackFingerprint();
|
|
}
|
|
|
|
export function getDeviceFingerprint() {
|
|
if (typeof window === "undefined") {
|
|
return "server-render";
|
|
}
|
|
|
|
const cookieFingerprint = readCookieFingerprint();
|
|
if (cookieFingerprint) {
|
|
window.localStorage.setItem(DEVICE_FINGERPRINT_KEY, cookieFingerprint);
|
|
return cookieFingerprint;
|
|
}
|
|
|
|
const existing = window.localStorage.getItem(DEVICE_FINGERPRINT_KEY);
|
|
if (existing) {
|
|
return existing;
|
|
}
|
|
|
|
const next = generateFingerprint();
|
|
window.localStorage.setItem(DEVICE_FINGERPRINT_KEY, next);
|
|
return next;
|
|
}
|