Skip to content

Commit

Permalink
fix: prevent numeric overflow with hashStr function (#141)
Browse files Browse the repository at this point in the history
The 'data-react-paypal-script-id' attribute uses the hash value from
this `hashStr(JSON.stringify(options))` function. This change fixes
an issue where a large `options` object could cause a numeric overflow.
  • Loading branch information
borodovisin authored and gregjopa committed Aug 17, 2021
1 parent 002059d commit 9914f60
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 5 deletions.
30 changes: 30 additions & 0 deletions src/utils.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { hashStr } from "./utils";

describe("hashStr", () => {
test("should match the hash from the argument string", () => {
expect(hashStr("react")).toMatchInlineSnapshot(`"xxhjw"`);
expect(hashStr("react-js.braintree")).toMatchInlineSnapshot(
`"xxhjbzppoallaomelb"`
);
expect(hashStr("react-js.paypal")).toMatchInlineSnapshot(
`"xxhjbzppiqfhtje"`
);
expect(hashStr("")).toMatchInlineSnapshot(`""`);
expect(
hashStr(
JSON.stringify({
"client-id":
"AfmdXiQAZD1rldTeFe9RNvsz8eBBG-Mltqh6h-iocQ1GUNuXIDnCie9tHcueD_NrMWB9dTlWl34xEK7V",
currency: "USD",
intent: "authorize",
debug: false,
vault: false,
locale: "US",
"data-namespace": "braintree",
})
)
).toMatchInlineSnapshot(
`"iiuovjsqddgseaaouopvvtcqciewjblfycugmepzoirvygvhquvfthtdttqasyqcdzbzaepjvxhbwsrjhhcurjzroipxqyishjiubldxsiumrlgiscmehhggkwzxusrrdpdxisuuektdeudjrtosskdpcksyhttbqsqsvdsoaugkffisgkusjvhthnqmlzgqccmutvqaztoqu"`
);
});
});
21 changes: 16 additions & 5 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,23 @@ export function getPayPalWindowNamespace(
}

/**
* Creates a numeric hash based on the string input.
* Creates a string hash code based on the string argument
*
* @param str the source input string to hash
* @returns string hash code
*/
export function hashStr(str: string): number {
let hash = 0;
export function hashStr(str: string): string {
let hash = "";

for (let i = 0; i < str.length; i++) {
hash += str[i].charCodeAt(0) * Math.pow((i % 10) + 1, 5);
let total = str[i].charCodeAt(0) * i;

if (str[i + 1]) {
total += str[i + 1].charCodeAt(0) * (i - 1);
}

hash += String.fromCharCode(97 + (Math.abs(total) % 26));
}
return Math.floor(Math.pow(Math.sqrt(hash), 5));

return hash;
}

0 comments on commit 9914f60

Please sign in to comment.