Skip to content

Commit e920a8e

Browse files
fix: fix for code scanning alert no. 39: Insecure randomness
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
1 parent 1f86df3 commit e920a8e

File tree

1 file changed

+37
-2
lines changed
  • packages/cli/templates/webcomponents/igc-ts/grid/grid-editing/files/src/app/__path__

1 file changed

+37
-2
lines changed

packages/cli/templates/webcomponents/igc-ts/grid/grid-editing/files/src/app/__path__/DataGridSharedData.ts

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,24 @@ export class DataGridSharedData {
202202
private static roadNames: string[] = ['Main', 'Garden', 'Broad', 'Oak', 'Cedar', 'Park', 'Pine', 'Elm', 'Market', 'Hill'];
203203

204204
private static getRandomNumber(min: number, max: number): number {
205-
return Math.round(min + Math.random() * (max - min));
205+
// Use crypto.getRandomValues for cryptographically secure random numbers
206+
if (window && window.crypto && typeof window.crypto.getRandomValues === "function") {
207+
const range = max - min + 1;
208+
if (range <= 0) return min;
209+
// Find the nearest greater power-of-2 for range, but not above 2^32-1
210+
const maxUint32 = 0xFFFFFFFF;
211+
const maxAcceptable = maxUint32 - (maxUint32 % range);
212+
let rand32: number;
213+
do {
214+
const arr = new Uint32Array(1);
215+
window.crypto.getRandomValues(arr);
216+
rand32 = arr[0];
217+
} while (rand32 > maxAcceptable);
218+
return min + (rand32 % range);
219+
} else {
220+
// fallback to Math.random (not secure)
221+
return Math.round(min + Math.random() * (max - min));
222+
}
206223
}
207224

208225
private static getRandomItem(array: any[]): any {
@@ -211,7 +228,25 @@ export class DataGridSharedData {
211228
}
212229

213230
private static getRandomDate(start: Date, end: Date) {
214-
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
231+
const startMillis = start.getTime();
232+
const endMillis = end.getTime();
233+
const range = endMillis - startMillis + 1;
234+
let randMillis: number;
235+
if (window && window.crypto && typeof window.crypto.getRandomValues === "function") {
236+
const maxUint32 = 0xFFFFFFFF;
237+
const maxAcceptable = maxUint32 - (maxUint32 % range);
238+
let rand32: number;
239+
do {
240+
const arr = new Uint32Array(1);
241+
window.crypto.getRandomValues(arr);
242+
rand32 = arr[0];
243+
} while (rand32 > maxAcceptable);
244+
randMillis = startMillis + (rand32 % range);
245+
} else {
246+
// fallback to Math.random (not secure)
247+
randMillis = startMillis + Math.floor(Math.random() * range);
248+
}
249+
return new Date(randMillis);
215250
}
216251

217252
private static getRandomPhone(): string {

0 commit comments

Comments
 (0)