32 lines
1.4 KiB
TypeScript
32 lines
1.4 KiB
TypeScript
/**
|
|
* ID generation that survives insecure contexts.
|
|
*
|
|
* `crypto.randomUUID()` is only exposed on secure contexts (HTTPS or
|
|
* localhost/127.0.0.1). On a LAN HTTP deployment (e.g.
|
|
* `http://192.168.200.15:8080`) the method is missing and direct calls crash
|
|
* with "crypto.randomUUID is not a function". `crypto.getRandomValues()` has
|
|
* no secure-context requirement, so the fallback builds a real RFC 4122 v4
|
|
* UUID from it; only when `crypto` is absent entirely do we degrade to a
|
|
* best-effort Math.random id.
|
|
*/
|
|
export function randomId(): string {
|
|
const c = globalThis.crypto;
|
|
if (c && typeof c.randomUUID === "function") return c.randomUUID();
|
|
if (c && typeof c.getRandomValues === "function")
|
|
return uuidV4(c.getRandomValues.bind(c));
|
|
return `id-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}${Math.random()
|
|
.toString(36)
|
|
.slice(2)}${Math.random().toString(36).slice(2)}`;
|
|
}
|
|
|
|
/** RFC 4122 version 4 UUID from a crypto-strength byte source. */
|
|
function uuidV4(getRandomValues: (array: Uint8Array) => Uint8Array): string {
|
|
const bytes = getRandomValues(new Uint8Array(16));
|
|
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
const hex = Array.from(bytes, (b) => b.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)}`;
|
|
}
|