Skip to content

Commit

Permalink
Strip __proto__ and constructor JSON properties in getSafeJson (#…
Browse files Browse the repository at this point in the history
…105)

Strip __proto__ and constructor JSON properties
  • Loading branch information
FrederikBolding authored Jun 14, 2023
1 parent 719854b commit 2148af4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
7 changes: 7 additions & 0 deletions src/json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,13 @@ describe('json', () => {
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(descriptor?.set).toBeUndefined();
});

it('strips __proto__ and constructor', () => {
const input =
'{ "test": { "__proto__": { "foo": "bar" } }, "test2": { "constructor": { "baz": "qux" } } }';
const parsed = JSON.parse(input);
expect(getSafeJson(parsed)).toStrictEqual({ test: {}, test2: {} });
});
});

describe('isValidJson', () => {
Expand Down
10 changes: 9 additions & 1 deletion src/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,15 @@ export const UnsafeJsonStruct: Struct<Json> = union([
*/
export const JsonStruct = coerce(UnsafeJsonStruct, any(), (value) => {
assertStruct(value, UnsafeJsonStruct);
return JSON.parse(JSON.stringify(value));
return JSON.parse(
JSON.stringify(value, (propKey, propValue) => {
// Strip __proto__ and constructor properties to prevent prototype pollution.
if (propKey === '__proto__' || propKey === 'constructor') {
return undefined;
}
return propValue;
}),
);
});

/**
Expand Down

0 comments on commit 2148af4

Please sign in to comment.