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

fix: only emit prototype pollution error when there's metadata emitted #281

Closed
Closed
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
22 changes: 21 additions & 1 deletion src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,21 @@ describe('stringify & parse', () => {
},
},
},
'repro #281': {
input: {
schema: { constructor: { type: 'string' } },
createdAt: new Date('2023-12-06T10:49:28.911Z'),
},
output: {
schema: { constructor: { type: 'string' } },
createdAt: '2023-12-06T10:49:28.911Z',
},
outputAnnotations: {
values: {
createdAt: ['Date'],
},
},
},
};

function deepFreeze(object: any, alreadySeenObjects = new Set()) {
Expand Down Expand Up @@ -1059,7 +1074,7 @@ test.each(['__proto__', 'prototype', 'constructor'])(
forbidden => {
expect(() => {
SuperJSON.serialize({
[forbidden]: 1,
[forbidden]: NaN,
});
}).toThrowError(/This is a prototype pollution risk/);
}
Expand Down Expand Up @@ -1229,3 +1244,8 @@ test('dedupe=true on a large complicated schema', () => {
expect(nondedupedOut).toEqual(deserialized);
expect(dedupedOut).toEqual(deserialized);
});

test("prototype pollution detector doesn't trigger when there's no meta", () => {
const { meta } = SuperJSON.serialize({ constructor: { name: 'hello' } });
expect(meta).toBeUndefined();
});
22 changes: 12 additions & 10 deletions src/plainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,16 +216,6 @@ export const walker = (
const innerAnnotations: Record<string, Tree<TypeAnnotation>> = {};

forEach(transformed, (value, index) => {
if (
index === '__proto__' ||
index === 'constructor' ||
index === 'prototype'
) {
throw new Error(
`Detected property ${index}. This is a prototype pollution risk, please remove it from your object.`
);
}

const recursiveResult = walker(
value,
identities,
Expand All @@ -236,6 +226,18 @@ export const walker = (
seenObjects
);

const emitsMeta = recursiveResult.annotations !== undefined;
if (
emitsMeta &&
(index === '__proto__' ||
index === 'constructor' ||
index === 'prototype')
) {
throw new Error(
`Detected property ${index}. This is a prototype pollution risk, please remove it from your object.`
);
}

transformedValue[index] = recursiveResult.transformedValue;

if (isArray(recursiveResult.annotations)) {
Expand Down
Loading