chore: warn on weak uuid fallback
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import { generateUUID } from "./uuid";
|
import { generateUUID } from "./uuid";
|
||||||
|
|
||||||
@@ -26,7 +26,13 @@ describe("generateUUID", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("still returns a v4 UUID when crypto is missing", () => {
|
it("still returns a v4 UUID when crypto is missing", () => {
|
||||||
const id = generateUUID(null);
|
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||||
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}$/);
|
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();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ export type CryptoLike = {
|
|||||||
getRandomValues?: ((array: Uint8Array) => Uint8Array) | undefined;
|
getRandomValues?: ((array: Uint8Array) => Uint8Array) | undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let warnedWeakCrypto = false;
|
||||||
|
|
||||||
function uuidFromBytes(bytes: Uint8Array): string {
|
function uuidFromBytes(bytes: Uint8Array): string {
|
||||||
bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
|
bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
|
||||||
bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 1
|
bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 1
|
||||||
@@ -29,6 +31,12 @@ function weakRandomBytes(): Uint8Array {
|
|||||||
return bytes;
|
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 {
|
export function generateUUID(cryptoLike: CryptoLike | null = globalThis.crypto): string {
|
||||||
if (cryptoLike && typeof cryptoLike.randomUUID === "function") return cryptoLike.randomUUID();
|
if (cryptoLike && typeof cryptoLike.randomUUID === "function") return cryptoLike.randomUUID();
|
||||||
|
|
||||||
@@ -38,5 +46,6 @@ export function generateUUID(cryptoLike: CryptoLike | null = globalThis.crypto):
|
|||||||
return uuidFromBytes(bytes);
|
return uuidFromBytes(bytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
warnWeakCryptoOnce();
|
||||||
return uuidFromBytes(weakRandomBytes());
|
return uuidFromBytes(weakRandomBytes());
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user