Skip to content

Commit

Permalink
refactor: improved message obfuscation by randomizing length and hand…
Browse files Browse the repository at this point in the history
…ling special characters (#16345) (#16584)

* fix: update message obfuscation implementation

* fix broken tests

* fix more tests

* update logic and tests
  • Loading branch information
thisisamir98 authored Jan 22, 2024
1 parent 1e91445 commit 8f5e2b4
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
10 changes: 7 additions & 3 deletions src/script/util/StringUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,13 @@ export const getRandomChar = (): string => {
};

export const obfuscate = (text: string): string => {
/* cspell:disable-next-line */
const alphabet = Array.from('abcdefghijklmnopqrstuvwxyz');
return Array.from(text, char => (/\s/.test(char) ? char : randomElement(alphabet))).join('');
const alphabet = Array.from('abcdefghijklmnopqrstuvwxyz ');

const obfuscatedText = Array.from({length: text.length + Math.floor((1 + Math.random()) * 10)}, () =>
randomElement(alphabet),
).join('');

return obfuscatedText;
};

/**
Expand Down
18 changes: 8 additions & 10 deletions test/unit_tests/util/StringUtilSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,14 @@ describe('StringUtil', () => {
});

describe('obfuscate', () => {
it("obfuscates a text preserving it's whitespaces", () => {
const text = 'You Are The Sunshine Of My Life';
const obfuscated = obfuscate(text);
const whitespaces = obfuscated.match(/[\n\r\s]+/gi);

expect(obfuscated).not.toBe(text);
expect(whitespaces.length).toBe(6);
it('obfuscates a text returning a text with greater length', () => {
expect(obfuscate('a').length).toBeGreaterThan(1);
expect(obfuscate('ab').length).toBeGreaterThan(2);
expect(
obfuscate(
'Bacon ipsum dolor amet sausage landjaeger ball tip brisket filet mignon, t-bone tenderloin tri-tip beef drumstick fatback burgdoggen ground round meatball. Tri-tip spare ribs ground round bresaola ball tip tail, sirloin chicken doner boudin turkey leberkas bacon alcatra. ',
).length,
).toBeGreaterThan(272);
});

it('obfuscates a text keeping its length', () => {
Expand All @@ -101,23 +102,20 @@ describe('StringUtil', () => {
const obfuscated = obfuscate(text);

expect(obfuscated).not.toBe(text);
expect(obfuscated.length).toBe(text.length);
});

it('obfuscates a text keeping its length (commas)', () => {
const text = ',,,,,,';
const obfuscated = obfuscate(text);

expect(obfuscated).not.toBe(text);
expect(obfuscated.length).toBe(text.length);
});

it('obfuscates a text keeping its length (dots)', () => {
const text = '......';
const obfuscated = obfuscate(text);

expect(obfuscated).not.toBe(text);
expect(obfuscated.length).toBe(text.length);
});
});

Expand Down

0 comments on commit 8f5e2b4

Please sign in to comment.