Skip to content

Commit 8af4dd3

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

1 file changed

Lines changed: 25 additions & 2 deletions

File tree

packages/dashboard/src/store/SessionContext.tsx

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,29 @@ interface SessionProviderProps {
4545
export function SessionProvider({ children }: SessionProviderProps) {
4646
const [state, dispatch] = useReducer(sessionReducer, initialState);
4747

48+
/**
49+
* Generates a cryptographically secure random string of given length, using base-36 chars.
50+
*/
51+
function generateSecureId(length: number): string {
52+
const bytes = new Uint8Array(length);
53+
window.crypto.getRandomValues(bytes);
54+
// Convert each byte to base36 char: '0'-'9','a'-'z' (36 chars)
55+
// Use only values < 36 to avoid modulo bias
56+
let chars = '';
57+
for (let i = 0; i < bytes.length; ) {
58+
const val = bytes[i] % 36;
59+
// Accept byte if within 0..251 to limit bias (since 252 is divisible by 36)
60+
if (bytes[i] < 252) {
61+
chars += val.toString(36);
62+
i++;
63+
} else {
64+
// re-generate this byte
65+
window.crypto.getRandomValues(bytes.subarray(i, i+1));
66+
}
67+
}
68+
return chars;
69+
}
70+
4871
/**
4972
* Global istatistikleri API'den getirir
5073
*/
@@ -94,7 +117,7 @@ export function SessionProvider({ children }: SessionProviderProps) {
94117
* Yeni session oluşturur
95118
*/
96119
const createSession = useCallback(async (name: string) => {
97-
const newSessionId = Math.random().toString(36).substring(2, 11);
120+
const newSessionId = generateSecureId(9); // 9 chars to match previous substring length
98121

99122
const payload: Partial<Session> = {
100123
id: newSessionId,
@@ -108,7 +131,7 @@ export function SessionProvider({ children }: SessionProviderProps) {
108131
userAgent: navigator.userAgent,
109132
url: window.location.href,
110133
user: {
111-
id: `user-${Math.floor(Math.random() * 1000)}`,
134+
id: `user-${generateSecureId(4)}`, // Optional: make user id secure too (4 chars for ~10000 possible values)
112135
email: 'dev@example.com',
113136
name,
114137
},

0 commit comments

Comments
 (0)