Skip to content

Commit c87a43f

Browse files
committed
feat: improve generateRandomState() (#56)
1 parent 4c41ca0 commit c87a43f

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

src/sdk.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,21 @@ export interface Permission {
165165
state: string;
166166
}
167167

168+
function generateRandomState(): string {
169+
const array = new Uint8Array(16);
170+
if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
171+
window.crypto.getRandomValues(array);
172+
} else if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) {
173+
global.crypto.getRandomValues(array);
174+
} else {
175+
// Fallback for test environments - this should not be used in production
176+
for (let i = 0; i < array.length; i++) {
177+
array[i] = Math.floor(Math.random() * 256);
178+
}
179+
}
180+
return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
181+
}
182+
168183
class Sdk {
169184
private config: SdkConfig
170185
private pkce: PKCE
@@ -194,7 +209,7 @@ class Sdk {
194209
if (state !== null) {
195210
return state;
196211
} else {
197-
const state = Math.random().toString(36).slice(2);
212+
const state = generateRandomState();
198213
sessionStorage.setItem("casdoor-state", state);
199214
return state;
200215
}

0 commit comments

Comments
 (0)