Skip to content

Commit

Permalink
chore: bye bye xss
Browse files Browse the repository at this point in the history
  • Loading branch information
SrIzan10 committed Jun 10, 2024
1 parent dca60d0 commit 292b913
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/util/replaceInterps.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { InterpolationObject } from "./types";
import sanitizeText from "./sanitizeText";

export default function replaceInterps(str: string, interp?: InterpolationObject) {
console.log(interp)
for (const key in interp) {
str = str.replaceAll(`{{${key}}}`, interp[key] as string);
// sanitize the key to prevent XSS
str = str.replaceAll(`{{${key}}}`, sanitizeText(interp[key] as string));
}
return str;
}
17 changes: 17 additions & 0 deletions src/util/sanitizeText.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const entityMap = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
// '"': '&quot;',
// "'": '&#39;',
// '/': '&#x2F;',
// '`': '&#x60;',
// '=': '&#x3D;'
};

export default function sanitizeText(text: string) {
return text.replace(/[&<>]/g, function (s) {
// @ts-ignore should be fine :clueless:
return entityMap[s];
});
}
3 changes: 3 additions & 0 deletions tests/getInterps.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,7 @@ it("should return values with interpolations replaced", () => {

// test to handle nonexistent interpolaitons, should return the normal {{}} string
expect(locales.t("interp.hello", {}, 'en')).toBe("Hello {{int}}");

// check to prevent XSS
expect(locales.t("interp.hello", { int: '<script>alert("XSS")</script>' }, 'en')).toBe(`Hello &lt;script&gt;alert("XSS")&lt;/script&gt;`);
});

0 comments on commit 292b913

Please sign in to comment.