Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Strip __proto__ and constructor JSON properties in getSafeJson #105

Merged
merged 1 commit into from
Jun 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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