Skip to content

Commit 1c771fd

Browse files
fix: Add failsafes for queryStringParser (#983)
1 parent f5026f9 commit 1c771fd

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

src/utils.ts

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -292,14 +292,19 @@ interface URLSearchParamsFallback {
292292
}
293293

294294
const queryStringParserFallback = (url: string): URLSearchParamsFallback => {
295-
let params: Dictionary<string> = {};
295+
const params: Dictionary<string> = {};
296296
const queryString = url.split('?')[1] || '';
297297
const pairs = queryString.split('&');
298298

299299
pairs.forEach(pair => {
300-
var [key, value] = pair.split('=');
301-
if (key && value) {
302-
params[key] = decodeURIComponent(value || '');
300+
const [key, ...valueParts] = pair.split('=');
301+
const value = valueParts.join('=');
302+
if (key && value !== undefined) {
303+
try {
304+
params[key] = decodeURIComponent(value || '');
305+
} catch (e) {
306+
console.error(`Failed to decode value for key ${key}: ${e}`);
307+
}
303308
}
304309
});
305310

test/jest/utils.spec.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,27 @@ describe('Utils', () => {
146146

147147
expect(queryStringParser(url, [])).toEqual(expectedResult);
148148
});
149+
150+
it('should handle non-standard characters or malformed urls', () => {
151+
const malformedUrl = 'https://www.example.com?foo=bar&baz=qux&mal=%E0%A4%A&narf=poit&param0=你好&*;<script>alert("hi")</script>&http://a.com/?c=7&d=8#!/asd+/%^^%zz%%%world你好&param1&param2=&param3=%E0%A4%A&param4=value1=value2&param5=a%AFc';
152+
const keys = [
153+
'foo',
154+
'narf',
155+
'param0',
156+
'param1',
157+
'param2',
158+
'param3',
159+
'param4'
160+
];
161+
162+
const expectedResult = {
163+
foo: 'bar',
164+
narf: 'poit',
165+
param0: '你好',
166+
};
167+
168+
expect(queryStringParser(malformedUrl, keys)).toEqual(expectedResult);
169+
});
149170
});
150171
});
151172

0 commit comments

Comments
 (0)