From 3e1d6f59033d004c3ed9545b58898d50c790ec48 Mon Sep 17 00:00:00 2001 From: MarsLuay <70299537+MarsLuay@users.noreply.github.com> Date: Sun, 6 Sep 2026 04:50:59 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20replace=20insecure=20Math.random?= =?UTF-8?q?=20with=20crypto.getRandomValues=20for=20UUID=20generation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ShapeClipboard.ts | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/src/ShapeClipboard.ts b/src/ShapeClipboard.ts index 9dc92fa..e6da508 100644 --- a/src/ShapeClipboard.ts +++ b/src/ShapeClipboard.ts @@ -217,14 +217,30 @@ function generateOoxmlGuid(): string { // typeof so the headless test bundle (no DOM globals) falls back cleanly. const cryptoApi = (typeof activeWindow !== 'undefined' ? activeWindow.crypto : undefined) - ?? (typeof window !== 'undefined' ? window.crypto : undefined); - const uuid = cryptoApi?.randomUUID?.() ?? fallbackUuid(); + ?? (typeof window !== 'undefined' ? window.crypto : undefined) + ?? (typeof crypto !== 'undefined' ? crypto : undefined); + const uuid = cryptoApi?.randomUUID?.() ?? fallbackUuid(cryptoApi); return `{${uuid.toUpperCase()}}`; } -function fallbackUuid(): string { +function fallbackUuid(cryptoApi?: Crypto): string { + let bytes: Uint8Array | undefined; + let byteIndex = 0; + + if (cryptoApi?.getRandomValues) { + // 30 'x' and 1 'y' character = 31 hex digits to replace + bytes = new Uint8Array(31); + // TypeScript lib typings for `Crypto.getRandomValues` can be strict about `ArrayBuffer` vs `SharedArrayBuffer` depending on the version. + cryptoApi.getRandomValues(bytes as unknown as Uint8Array & { buffer: ArrayBuffer }); + } + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (character) => { - const random = Math.floor(Math.random() * 16); + let random: number; + if (bytes) { + random = bytes[byteIndex++]! % 16; + } else { + random = Math.floor(Math.random() * 16); + } const value = character === 'x' ? random : (random & 0x3) | 0x8; return value.toString(16); });