()
| 57 | } |
| 58 | |
| 59 | public static generate(): string { |
| 60 | const cryptoObj: Crypto | undefined = globalThis.crypto; |
| 61 | |
| 62 | if (cryptoObj && typeof cryptoObj.randomUUID === "function") { |
| 63 | return cryptoObj.randomUUID(); |
| 64 | } |
| 65 | |
| 66 | /* |
| 67 | * crypto.randomUUID() is gated behind a secure context in browsers, so it is |
| 68 | * missing when the dashboard is served over plain HTTP from a non-localhost |
| 69 | * origin. crypto.getRandomValues() has no secure-context requirement, so use |
| 70 | * it to build an RFC 4122 §4.4 v4 UUID. |
| 71 | */ |
| 72 | if (cryptoObj && typeof cryptoObj.getRandomValues === "function") { |
| 73 | const bytes: Uint8Array = new Uint8Array(16); |
| 74 | cryptoObj.getRandomValues(bytes); |
| 75 | bytes[6] = ((bytes[6] as number) & 0x0f) | 0x40; |
| 76 | bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80; |
| 77 | const hex: string = Array.from(bytes, (b: number) => { |
| 78 | return b.toString(16).padStart(2, "0"); |
| 79 | }).join(""); |
| 80 | return ( |
| 81 | hex.slice(0, 8) + |
| 82 | "-" + |
| 83 | hex.slice(8, 12) + |
| 84 | "-" + |
| 85 | hex.slice(12, 16) + |
| 86 | "-" + |
| 87 | hex.slice(16, 20) + |
| 88 | "-" + |
| 89 | hex.slice(20, 32) |
| 90 | ); |
| 91 | } |
| 92 | |
| 93 | /* |
| 94 | * Last-resort fallback for environments without any Web Crypto API. Not |
| 95 | * cryptographically random, but produces a well-formed v4 UUID so callers |
| 96 | * that only need a unique key (e.g. form rows) keep working. |
| 97 | */ |
| 98 | return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace( |
| 99 | /[xy]/g, |
| 100 | (char: string) => { |
| 101 | const r: number = (Math.random() * 16) | 0; |
| 102 | const v: number = char === "x" ? r : (r & 0x3) | 0x8; |
| 103 | return v.toString(16); |
| 104 | }, |
| 105 | ); |
| 106 | } |
| 107 | } |
no test coverage detected