Skip to content

Commit

Permalink
feat(sanitizer): add sanitizeValues and isSecureLink
Browse files Browse the repository at this point in the history
  • Loading branch information
luancurti committed Feb 17, 2023
1 parent 12da052 commit 1b68838
Show file tree
Hide file tree
Showing 4 changed files with 461 additions and 12 deletions.
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"@babel/preset-env": "7.20.2",
"@babel/preset-react": "7.18.6",
"@babel/runtime": "7.20.1",
"@types/dompurify": "^2.4.0",
"@types/jest": "29.2.3",
"@types/lodash": "4.14.189",
"@types/numeral": "2.0.2",
Expand Down Expand Up @@ -91,5 +92,8 @@
"ts-jest": "29.0.3",
"typescript": "4.9.3",
"uglify-js": "3.17.4"
},
"dependencies": {
"isomorphic-dompurify": "^1.0.0"
}
}
44 changes: 44 additions & 0 deletions src/__tests__/sanitizer.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { isSecureLink, sanitizeValues } from '../shared/sanitizer';

describe('Sanitizer', () => {
describe('isSecureLink', () => {
it('should return isSecure false when pass link without http protocol', () => {
const isSecure = isSecureLink('wss://google.com');
expect(isSecure).toBeFalsy();
});

it('should return isSecure false when pass invalid link', () => {
const isSecure = isSecureLink('ja
vascript:alert(1)');
expect(isSecure).toBeFalsy();
});
});

describe('sanitizeValues', () => {
it('should return same values when pass secure values', () => {
const objectValues = {
a: 1,
b: 2,
};

const purifiedValues = sanitizeValues(objectValues);

expect(objectValues).toStrictEqual(purifiedValues);
});

it('should return purified values when pass insecure values', () => {
const objectValues = {
a: '<b>hello there</b>',
b: 2,
};

const expectedValues = {
a: 'hello there',
b: 2,
};

const purifiedValues = sanitizeValues(objectValues);

expect(expectedValues).toStrictEqual(purifiedValues);
});
});
});
33 changes: 33 additions & 0 deletions src/shared/sanitizer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import * as DOMPurify from 'isomorphic-dompurify';

type ConfigSanitize = DOMPurify.Config & {
RETURN_DOM_FRAGMENT?: false | undefined;
RETURN_DOM?: false | undefined;
};

const defaultConfig: ConfigSanitize = {
RETURN_DOM_FRAGMENT: false,
SANITIZE_DOM: true,
USE_PROFILES: { html: false },
};

export const sanitizeValues = <T = Record<string, any>>(
values: T,
config?: ConfigSanitize,
): T => {
const purifiedValues = DOMPurify.sanitize(JSON.stringify(values), {
...defaultConfig,
...config,
});

return JSON.parse(purifiedValues);
};

export const isSecureLink = (url: string): boolean => {
try {
const parsed = new URL(url);
return ['https:', 'http:'].includes(parsed.protocol);
} catch (error) {
return false;
}
};
Loading

0 comments on commit 1b68838

Please sign in to comment.