Skip to content

Commit

Permalink
fix: only purge constructor.prototype keys (#26)
Browse files Browse the repository at this point in the history
Co-authored-by: Pooya Parsa <pooya@pi0.io>
  • Loading branch information
manniL and pi0 committed Dec 2, 2022
1 parent 8faa0a8 commit 87918d5
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
6 changes: 5 additions & 1 deletion src/index.ts
Expand Up @@ -6,7 +6,11 @@ const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s
const JsonSigRx = /^["[{]|^-?\d[\d.]{0,14}$/;

function jsonParseTransform (key: string, value: any): any {
if (key === "__proto__" || key === "constructor") {
if (key === "__proto__") {
return;
}
if (key === "constructor" && value && typeof value === "object" && ("prototype" in value)) {
// Has possible malicious prototype
return;
}
return value;
Expand Down
6 changes: 5 additions & 1 deletion test/index.test.ts
Expand Up @@ -57,6 +57,9 @@ describe("destr", () => {
{ input: "{}", output: {} },
{ input: "[]", output: [] },
{ input: "{ \"key\": \"value\" }", output: { key: "value" } },
{ input: "{ \"constructor\": \"value\" }", output: { constructor: "value" } },
// eslint-disable-next-line unicorn/no-null
{ input: '{ "constructor": null }', output: { constructor: null } },
{ input: "[1,2,3]", output: [1, 2, 3] }
];

Expand All @@ -68,7 +71,8 @@ describe("destr", () => {
it("prevents prototype pollution", () => {
const testCases = [
{ input: '{ "__proto__": {} }', output: {} },
{ input: '{ "constructor": {} }', output: {} }
{ input: '{ "constructor": { "prototype": {} } }', output: {} },
{ input: '{ "constructor": { "prototype": null } }', output: {} }
];

for (const testCase of testCases) {
Expand Down

0 comments on commit 87918d5

Please sign in to comment.