Browse Source

[UI] Added a check to handle cases where the input is of type 'object' (#3786)

Ayush Goyal 1 year ago
parent
commit
53998b392c

+ 35 - 0
desktop/core/src/desktop/js/utils/html/deXSS.test.ts

@@ -66,4 +66,39 @@ describe('deXSS.ts', () => {
   it('should dump an uppercase javascript url', () => {
     expect(deXSS('<a href="JAVASCRIPT:alert(\'foo\')">Hax</a>')).toEqual('<a>Hax</a>');
   });
+
+  it('should return a comma-separated string for an array', () => {
+    expect(deXSS([1, 2, 3])).toEqual('1,2,3');
+  });
+
+  it('should return JSON string for an object', () => {
+    expect(deXSS({ key: 'value' })).toEqual('{"key":"value"}');
+  });
+
+  it('should return JSON string for a map', () => {
+    const map = new Map();
+    map.set('key', 'value');
+    expect(deXSS(Object.fromEntries(map))).toEqual('{"key":"value"}');
+  });
+
+  it('should return JSON string for a nested object', () => {
+    const nestedObject = {
+      key1: 'value1',
+      key2: {
+        nestedKey: 'nestedValue'
+      }
+    };
+    expect(deXSS(nestedObject)).toEqual('{"key1":"value1","key2":{"nestedKey":"nestedValue"}}');
+  });
+
+  it('should return JSON string for a complex map', () => {
+    const map = new Map();
+    map.set('struct', {
+      array1: [1, 2, 3],
+      array2: ['a', 'b', 'c']
+    });
+    expect(deXSS(Object.fromEntries(map))).toEqual(
+      '{"struct":{"array1":[1,2,3],"array2":["a","b","c"]}}'
+    );
+  });
 });

+ 13 - 2
desktop/core/src/desktop/js/utils/html/deXSS.ts

@@ -16,7 +16,10 @@
 
 import sanitizeHtml, { IOptions } from 'sanitize-html';
 
-const deXSS = (str?: undefined | boolean | string | number | null, options?: IOptions): string => {
+const deXSS = (
+  str?: undefined | boolean | string | number | null | unknown,
+  options?: IOptions
+): string => {
   if (str === null) {
     return 'null';
   }
@@ -25,7 +28,15 @@ const deXSS = (str?: undefined | boolean | string | number | null, options?: IOp
     return str.toString();
   }
   if (typeof str !== 'undefined') {
-    return sanitizeHtml(str as string, options) || '';
+    // This handles cases where 'str' is a object, ensuring it is properly
+    // serialized into a JSON format before sanitization.
+    let finalStr: string;
+    if (typeof str === 'object' && !Array.isArray(str)) {
+      finalStr = JSON.stringify(str);
+    } else {
+      finalStr = str.toString();
+    }
+    return sanitizeHtml(finalStr, options) || '';
   }
   return '';
 };