diff --git a/ui/src/ui/uuid.test.ts b/ui/src/ui/uuid.test.ts index 9f7ccbf81..2d5421bdd 100644 --- a/ui/src/ui/uuid.test.ts +++ b/ui/src/ui/uuid.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { generateUUID } from "./uuid"; @@ -26,7 +26,13 @@ describe("generateUUID", () => { }); it("still returns a v4 UUID when crypto is missing", () => { - const id = generateUUID(null); - expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const id = generateUUID(null); + expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + expect(warnSpy).toHaveBeenCalled(); + } finally { + warnSpy.mockRestore(); + } }); }); diff --git a/ui/src/ui/uuid.ts b/ui/src/ui/uuid.ts index f231d0f7f..7c927cda1 100644 --- a/ui/src/ui/uuid.ts +++ b/ui/src/ui/uuid.ts @@ -3,6 +3,8 @@ export type CryptoLike = { getRandomValues?: ((array: Uint8Array) => Uint8Array) | undefined; }; +let warnedWeakCrypto = false; + function uuidFromBytes(bytes: Uint8Array): string { bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4 bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 1 @@ -29,6 +31,12 @@ function weakRandomBytes(): Uint8Array { return bytes; } +function warnWeakCryptoOnce() { + if (warnedWeakCrypto) return; + warnedWeakCrypto = true; + console.warn("[uuid] crypto API missing; falling back to weak randomness"); +} + export function generateUUID(cryptoLike: CryptoLike | null = globalThis.crypto): string { if (cryptoLike && typeof cryptoLike.randomUUID === "function") return cryptoLike.randomUUID(); @@ -38,5 +46,6 @@ export function generateUUID(cryptoLike: CryptoLike | null = globalThis.crypto): return uuidFromBytes(bytes); } + warnWeakCryptoOnce(); return uuidFromBytes(weakRandomBytes()); }