mirror of
https://github.com/wu736139669/hapi.git
synced 2026-08-05 06:24:37 +00:00
crypto.randomUUID is only exposed in secure contexts (HTTPS or localhost). When the web app is served over HTTP on a LAN IP the attachment adapter, toast provider, message localId helper, file attachment metadata and terminal id creation all call crypto.randomUUID() synchronously and throw TypeError, so the UI silently does nothing (e.g. the file picker opens and closes with no chip). Add a small web/src/lib/randomId helper that tries crypto.randomUUID first, then falls back to crypto.getRandomValues-derived UUID v4, and finally to a Date.now/Math.random string for very old environments. Route all five call sites through it. Output format is identical for secure contexts and UUID v4 for the getRandomValues path, so existing DB/SSE/RPC consumers see the same shape.
37 lines
1.5 KiB
TypeScript
37 lines
1.5 KiB
TypeScript
/**
|
|
* Generates a random ID string that works in both secure and non-secure contexts.
|
|
*
|
|
* crypto.randomUUID() is only available in secure contexts (HTTPS or localhost).
|
|
* When accessed over HTTP on a LAN IP, it throws TypeError, breaking file
|
|
* attachment and other ID-generation paths.
|
|
*
|
|
* Fallback chain:
|
|
* 1. crypto.randomUUID() — secure context (HTTPS / localhost)
|
|
* 2. crypto.getRandomValues() — available in non-secure contexts on modern browsers
|
|
* 3. Date.now() + Math.random() — last resort for very old environments
|
|
*
|
|
* All paths return a UUID v4-format string or a similarly unique string,
|
|
* maintaining compatibility with existing ID consumers (DB, SSE, RPC payloads).
|
|
*/
|
|
export function randomId(): string {
|
|
const c = globalThis.crypto
|
|
|
|
if (typeof c?.randomUUID === 'function') {
|
|
return c.randomUUID()
|
|
}
|
|
|
|
if (typeof c?.getRandomValues === 'function') {
|
|
const bytes = new Uint8Array(16)
|
|
c.getRandomValues(bytes)
|
|
// Set version 4 bits
|
|
bytes[6] = (bytes[6] & 0x0f) | 0x40
|
|
// Set variant bits
|
|
bytes[8] = (bytes[8] & 0x3f) | 0x80
|
|
const hex = Array.from(bytes).map((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)}`
|
|
}
|
|
|
|
// Fallback for environments without any crypto support
|
|
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`
|
|
}
|