Skip to content
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
25 changes: 25 additions & 0 deletions packages/utils/src/__tests__/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,31 @@ describe('Service/Utilies', () => {
e: 2,
});
});

it('should ignore prototype pollution keys while merging objects', () => {
delete (Object.prototype as any).polluted;

const input1 = {};
const input2 = JSON.parse('{"__proto__":{"polluted":"yes"},"constructor":{"prototype":{"polluted":"yes"}},"prototype":{"polluted":"yes"}}');

const output = deepMerge(input1, input2);

expect(output).toEqual({});
expect((Object.prototype as any).polluted).toBeUndefined();
expect(({} as any).polluted).toBeUndefined();
});

it('should not recursively merge into inherited target properties', () => {
const inheritedOptions = { inherited: true };
const target = Object.create({ options: inheritedOptions });
const source = { options: { own: true } };

const output = deepMerge(target, source);

expect(output.options).toEqual({ own: true });
expect(Object.prototype.hasOwnProperty.call(output, 'options')).toBe(true);
expect(inheritedOptions).toEqual({ inherited: true });
});
});

describe('emptyObject() method', () => {
Expand Down
6 changes: 4 additions & 2 deletions packages/utils/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { AnyFunction } from './models/types.js';

const unsafeMergeKeys = new Set(['__proto__', 'constructor', 'prototype']);

/**
* Add an item to an array only when the item does not exists, when the item is an object we will be using their "id" to compare
* @param inputArray
Expand Down Expand Up @@ -107,8 +109,8 @@ export function deepMerge(target: any, ...sources: any[]): any {

if (isObject(target) && isObject(source)) {
Object.keys(source).forEach((prop) => {
if (source.hasOwnProperty(prop)) {
if (prop in target) {
if (Object.prototype.hasOwnProperty.call(source, prop) && !unsafeMergeKeys.has(prop)) {
if (Object.prototype.hasOwnProperty.call(target, prop)) {
// handling merging of two properties with equal names
if (typeof (target as any)[prop] !== 'object') {
(target as any)[prop] = (source as any)[prop];
Expand Down
Loading