Skip to content

Commit

Permalink
feat: re-handle embedded encoding, add tests
Browse files Browse the repository at this point in the history
Co-authored-by: Iris Booker <[email protected]>
  • Loading branch information
braintreeps and Iris Booker committed Jul 8, 2024
1 parent 5a77047 commit ccb54da
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,23 @@ describe("sanitizeUrl", () => {
expect(sanitizeUrl(vector)).toBe(BLANK_URL);
});
});

Check failure on line 149 in src/__tests__/index.test.ts

View workflow job for this annotation

GitHub Actions / Unit Tests on Ubuntu

Delete `··`
it("backslash prefixed attack vectors", () => {
const attackVectors = [
"\fjavascript:alert()",
"\vjavascript:alert()",
"\tjavascript:alert()",
"\njavascript:alert()",
"\rjavascript:alert()",
"\u0000javascript:alert()",
"\u0001javascript:alert()",
"\j\av\a\s\cript:alert()",

Check failure on line 159 in src/__tests__/index.test.ts

View workflow job for this annotation

GitHub Actions / Unit Tests on Ubuntu

Replace `\j\av\a\s\` with `javas`
];

attackVectors.forEach((vector) => {
expect(sanitizeUrl(vector)).toBe(BLANK_URL);
});
});

describe("invalid protocols", () => {
describe.each(["javascript", "data", "vbscript"])("%s", (protocol) => {
Expand Down
16 changes: 15 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ function isValidUrl(url: string): boolean {
}
}

function decodeURI(uri: string): string {
try {
return decodeURIComponent(uri);
} catch (e: unknown) {
// Ignoring error
// It is possible that the URI contains a `%` not associated
// with URI/URL-encoding.
return uri;
}
}

function sanitizeString(str: string): string {

Check warning on line 43 in src/index.ts

View workflow job for this annotation

GitHub Actions / Unit Tests on Ubuntu

'sanitizeString' is defined but never used
return str
.replace(/[^a-zA-Z0-9-_./]/g, '')

Check failure on line 45 in src/index.ts

View workflow job for this annotation

GitHub Actions / Unit Tests on Ubuntu

Replace `''` with `""`
Expand All @@ -43,14 +54,17 @@ export function sanitizeUrl(url?: string): string {
}

let charsToDecode;
let decodedUrl = url.trim();
let decodedUrl = decodeURI(url.trim());

do {
decodedUrl = decodeHtmlCharacters(decodedUrl)
.replace(htmlCtrlEntityRegex, "")
.replace(ctrlCharactersRegex, "")
.replace(whitespaceEscapeCharsRegex, "")
.trim();

decodedUrl = decodeURI(decodedUrl);

charsToDecode =
decodedUrl.match(ctrlCharactersRegex) ||
decodedUrl.match(htmlEntitiesRegex) ||
Expand Down

0 comments on commit ccb54da

Please sign in to comment.