Skip to content

Commit 6b1dd03

Browse files
authored
fix(error-response-plugin): sanitize input (#1141)
1 parent 2b75a5f commit 6b1dd03

File tree

5 files changed

+24
-2
lines changed

5 files changed

+24
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
## next
44

55
- fix(types): fix Logger type
6+
- fix(error-response-plugin): sanitize input
67

78
## [v3.0.5](https://github.com/chimurai/http-proxy-middleware/releases/tag/v3.0.5)
89

cspell.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
"path": "CONTRIBUTORS.txt"
2020
}
2121
],
22-
"ignoreRegExpList": ["[a-z]+path", "\\]\\(#[a-z-]+\\)"],
22+
"ignoreRegExpList": ["[a-z]+path", "\\]\\(#[a-z-]+\\)", "%[\\dA-Z]{2}"],
2323
"words": [
2424
"brotli",
2525
"camelcase",

src/plugins/default/error-response-plugin.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import type { Socket } from 'node:net';
33

44
import { getStatusCode } from '../../status-code';
55
import { Plugin } from '../../types';
6+
import { sanitize } from '../../utils/sanitize';
67

78
function isResponseLike(obj: any): obj is http.ServerResponse {
89
return obj && typeof obj.writeHead === 'function';
@@ -26,7 +27,7 @@ export const errorResponsePlugin: Plugin = (proxyServer, options) => {
2627
}
2728

2829
const host = req.headers && req.headers.host;
29-
res.end(`Error occurred while trying to proxy: ${host}${req.url}`);
30+
res.end(`Error occurred while trying to proxy: ${sanitize(host)}${sanitize(req.url)}`);
3031
} else if (isSocketLike(res)) {
3132
res.destroy();
3233
}

src/utils/sanitize.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export function sanitize(input: string | undefined): string {
2+
return input?.replace(/[<>]/g, (i) => encodeURIComponent(i)) ?? '';
3+
}

test/unit/utils/sanitize.spec.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { sanitize } from '../../../src/utils/sanitize';
2+
3+
describe('sanitize()', () => {
4+
it('should return empty string for undefined input', () => {
5+
expect(sanitize(undefined)).toEqual('');
6+
});
7+
8+
it('should replace special characters with their HTML entity equivalents', () => {
9+
const input = '<>';
10+
expect(sanitize(input)).toMatchInlineSnapshot(`"%3C%3E"`);
11+
});
12+
13+
it('should replace special characters with HTML entities', () => {
14+
const input = '<script>alert("XSS")</script>';
15+
expect(sanitize(input)).toMatchInlineSnapshot(`"%3Cscript%3Ealert("XSS")%3C/script%3E"`);
16+
});
17+
});

0 commit comments

Comments
 (0)