Skip to content

Commit

Permalink
fix: replace Math.random with crypto (#140)
Browse files Browse the repository at this point in the history
Co-authored-by: Donat Nagy <donat.nagy@bitpanda.com>
  • Loading branch information
doatech and Donat Nagy authored Jun 30, 2021
1 parent 200ba07 commit cdc0b7d
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
3 changes: 3 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,7 @@ module.exports = {
// "^.+\\.(ts|tsx)$": "ts-jest"
// },
testEnvironment: 'node',
globals: {
window: {}
}
};
7 changes: 6 additions & 1 deletion src/web-utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import {OAuth2AuthenticateOptions} from "./definitions";
import {CryptoUtils, WebUtils} from "./web-utils";
import { CryptoUtils, WebUtils } from "./web-utils";

const mGetRandomValues = jest.fn().mockReturnValueOnce(new Uint32Array(10));
Object.defineProperty(window, 'crypto', {
value: { getRandomValues: mGetRandomValues },
});

const googleOptions: OAuth2AuthenticateOptions = {
appId: "appId",
Expand Down
10 changes: 5 additions & 5 deletions src/web-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,12 @@ export class WebUtils {
static randomString(length: number = 10) {
const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

let text = "";
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
let array = new Uint8Array(length);

window.crypto.getRandomValues(array);
array = array.map(x => possible.charCodeAt(x % possible.length));

return text;
return String.fromCharCode.apply(null, array);
}

static async buildWebOptions(configOptions: OAuth2AuthenticateOptions): Promise<WebOptions> {
Expand Down

0 comments on commit cdc0b7d

Please sign in to comment.