Skip to content

Commit

Permalink
Replace js-sha256 with sha.js (#281)
Browse files Browse the repository at this point in the history
* Replace js-sha256 with sha.js

* add typing on hash
  • Loading branch information
joe-statsig authored Jun 8, 2023
1 parent 0637f8d commit b9af50b
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 27 deletions.
64 changes: 45 additions & 19 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"homepage": "https://www.statsig.com",
"dependencies": {
"ip3country": "^5.0.0",
"js-sha256": "^0.9.0",
"sha.js": "^2.4.11",
"node-fetch": "^2.6.7",
"ua-parser-js": "^1.0.2",
"uuid": "^8.3.2"
Expand All @@ -39,6 +39,7 @@
"@types/jest": "^26.0.24",
"@types/node": "^14.18.26",
"@types/node-fetch": "^2.6.2",
"@types/sha.js": "^2.4.0",
"@types/ua-parser-js": "^0.7.36",
"@types/useragent": "^2.3.1",
"@types/uuid": "^8.3.4",
Expand Down
23 changes: 16 additions & 7 deletions src/Evaluator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import { StatsigUser } from './StatsigUser';
import { notEmpty } from './utils/core';
import parseUserAgent from './utils/parseUserAgent';
import StatsigFetcher from './utils/StatsigFetcher';
import { sha256 } from 'js-sha256';

const shajs = require('sha.js');
const ip3country = require('ip3country');

const CONDITION_SEGMENT_COUNT = 10 * 1000;
Expand Down Expand Up @@ -853,9 +853,20 @@ function computeUserHash(userHash: string) {
return existingHash;
}

var sha = sha256.create();
sha.update(userHash);
const hash = BigInt(`0x${sha.hex().substring(0, 16)}`);
let hash: bigint;
const buffer = shajs('sha256').update(userHash).digest();
if (buffer.readBigUInt64BE) {
hash = buffer.readBigUInt64BE();
}

const ab = new ArrayBuffer(buffer.length);
const view = new Uint8Array(ab);
for (let ii = 0; ii < buffer.length; ii++) {
view[ii] = buffer[ii];
}

const dv = new DataView(ab);
hash = dv.getBigUint64(0, false);

if (hashLookupTable.size > 100000) {
hashLookupTable.clear();
Expand All @@ -866,9 +877,7 @@ function computeUserHash(userHash: string) {
}

function getHashedName(name: string) {
var sha = sha256.create();
sha.update(name);
return Buffer.from(sha.hex(), 'hex').toString('base64');
return shajs('sha256').update(name).digest('base64');
}

function hashUnitIDForIDList(unitID: string) {
Expand Down

0 comments on commit b9af50b

Please sign in to comment.