Files
Sybil-2/web/src/lib/browser-uuid.ts
T

13 lines
813 B
TypeScript

type BrowserCrypto = Pick<Crypto, "getRandomValues"> & Partial<Pick<Crypto, "randomUUID">>;
/** Secure UUIDs also work on browsers that predate Crypto.randomUUID(). */
export function browserUuid(source: BrowserCrypto | undefined = typeof crypto === "undefined" ? undefined : crypto): string {
if (typeof source?.randomUUID === "function") return source.randomUUID();
if (typeof source?.getRandomValues !== "function") throw new Error("Secure browser identifiers are unavailable.");
const bytes = source.getRandomValues(new Uint8Array(16));
bytes[6] = bytes[6] & 15 | 64;
bytes[8] = bytes[8] & 63 | 128;
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, "0")).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}