Skip to content

Commit 77c1824

Browse files
committed
add fallback for browsers that do not have crypto.randomUUID
1 parent c54a2ae commit 77c1824

1 file changed

Lines changed: 26 additions & 1 deletion

File tree

frontend/src/utils/identity.ts

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,31 @@ const COLORS = [
8080
"#f43f5e", // rose-500
8181
];
8282

83+
const generateClientId = (): string => {
84+
const cryptoObj: Crypto | undefined =
85+
typeof globalThis !== "undefined"
86+
? globalThis.crypto || (globalThis as any).msCrypto
87+
: undefined;
88+
89+
if (cryptoObj?.randomUUID) {
90+
return cryptoObj.randomUUID();
91+
}
92+
93+
if (cryptoObj?.getRandomValues) {
94+
const bytes = new Uint8Array(16);
95+
cryptoObj.getRandomValues(bytes);
96+
bytes[6] = (bytes[6] & 0x0f) | 0x40; // RFC 4122 variant
97+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
98+
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
99+
return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex
100+
.slice(6, 8)
101+
.join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
102+
}
103+
104+
// Final fallback for very old browsers; uniqueness window-scoped only.
105+
return `id-${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`;
106+
};
107+
83108
export const getUserIdentity = (): UserIdentity => {
84109
const stored = localStorage.getItem("excalidash-user-id");
85110
if (stored) {
@@ -91,7 +116,7 @@ export const getUserIdentity = (): UserIdentity => {
91116
const randomColor = COLORS[Math.floor(Math.random() * COLORS.length)];
92117

93118
const identity: UserIdentity = {
94-
id: crypto.randomUUID(),
119+
id: generateClientId(),
95120
name: randomTransformer.name,
96121
initials: randomTransformer.initials,
97122
color: randomColor,

0 commit comments

Comments
 (0)