feat(util): mint UUIDs without crypto.randomUUID in every context

This commit is contained in:
imccyu
2026-08-21 20:35:34 +08:00
parent 99db143e37
commit 0bee546177
33 changed files with 363 additions and 32 deletions
@@ -5,6 +5,7 @@
*/
import { sha1 } from '@noble/hashes/legacy.js'
import { sha256, sha512 } from '@noble/hashes/sha2.js'
import { randomUUID as mintUUID } from '@deepseek-ai/dsh-util-crypto'
import { Buffer } from 'buffer'
type Hasher = (input: Uint8Array) => Uint8Array
@@ -73,11 +74,13 @@ export function randomBytes(size: number): Buffer<ArrayBuffer> {
}
/**
* Random v4 UUID.
* Random v4 UUID. Delegated to the repository's own mint rather than to
* `crypto.randomUUID`, which browsers expose only in secure contexts — a
* preview served over plain HTTP on a LAN address has no `randomUUID`.
* @returns the UUID string.
*/
export function randomUUID(): import('node:crypto').UUID {
return globalThis.crypto.randomUUID()
return mintUUID()
}
/**
@@ -200,7 +200,8 @@ export function mkdirSync(path: PathArg, options?: { recursive?: boolean }): str
* @returns the created directory path.
*/
export function mkdtempSync(prefix: string): string {
const suffix = globalThis.crypto.randomUUID().replaceAll('-', '').slice(0, 6)
// Not crypto.randomUUID: browsers expose that only in secure contexts.
const suffix = Array.from(globalThis.crypto.getRandomValues(new Uint8Array(3)), byte => byte.toString(16).padStart(2, '0')).join('')
const target = `${prefix}${suffix}`
vfs().mkdirSync(target, { recursive: true })
return target
@@ -0,0 +1,19 @@
/**
* Fill the `crypto.randomUUID` gap on insecure origins. Browsers expose
* `randomUUID` only in secure contexts, and a preview served over plain HTTP
* on a LAN address is not one — while product code (bundled and VFS-loaded
* alike) reaches the global directly, Node-style. The worker patches the one
* `crypto` instance instead of teaching every caller.
*/
import { randomUUID } from '@deepseek-ai/dsh-util-crypto'
/** Install `crypto.randomUUID` when the context withholds it. */
export function installCryptoGlobals(): void {
// In a secure context the platform method is present and stays untouched.
if (typeof globalThis.crypto.randomUUID === 'function') return
Object.defineProperty(globalThis.crypto, 'randomUUID', {
value: randomUUID,
configurable: true,
writable: true,
})
}