Skip to content

Commit feb9b10

Browse files
authored
fix: don't throw on malformed URLs (#10901)
1 parent a9978dd commit feb9b10

File tree

2 files changed

+28
-15
lines changed

2 files changed

+28
-15
lines changed

packages/vite/src/node/__tests__/utils.spec.ts

+8-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ import {
99
isFileReadable,
1010
isWindows,
1111
posToNumber,
12-
resolveHostname
12+
resolveHostname,
13+
shouldServe
1314
} from '../utils'
1415

1516
describe('injectQuery', () => {
@@ -239,6 +240,12 @@ describe('asyncFlatten', () => {
239240
})
240241
})
241242

243+
describe('shouldServe', () => {
244+
test('returns false for malformed URLs', () => {
245+
expect(shouldServe('/%c0%ae%c0%ae/etc/passwd', '/assets/dir')).toBe(false)
246+
})
247+
})
248+
242249
describe('isFileReadable', () => {
243250
test("file doesn't exist", async () => {
244251
expect(isFileReadable('/does_not_exist')).toBe(false)

packages/vite/src/node/utils.ts

+20-14
Original file line numberDiff line numberDiff line change
@@ -1198,22 +1198,28 @@ export const isNonDriveRelativeAbsolutePath = (p: string): boolean => {
11981198
* consistent behaviour between dev and prod and across operating systems.
11991199
*/
12001200
export function shouldServe(url: string, assetsDir: string): boolean {
1201-
// viteTestUrl is set to something like http://localhost:4173/ and then many tests make calls
1202-
// like `await page.goto(viteTestUrl + '/example')` giving us URLs beginning with a double slash
1203-
const pathname = decodeURI(
1204-
new URL(url.startsWith('//') ? url.substring(1) : url, 'http://example.com')
1205-
.pathname
1206-
)
1207-
const file = path.join(assetsDir, pathname)
1208-
if (
1209-
!fs.existsSync(file) ||
1210-
(isCaseInsensitiveFS && // can skip case check on Linux
1211-
!fs.statSync(file).isDirectory() &&
1212-
!hasCorrectCase(file, assetsDir))
1213-
) {
1201+
try {
1202+
// viteTestUrl is set to something like http://localhost:4173/ and then many tests make calls
1203+
// like `await page.goto(viteTestUrl + '/example')` giving us URLs beginning with a double slash
1204+
const pathname = decodeURI(
1205+
new URL(
1206+
url.startsWith('//') ? url.substring(1) : url,
1207+
'http://example.com'
1208+
).pathname
1209+
)
1210+
const file = path.join(assetsDir, pathname)
1211+
if (
1212+
!fs.existsSync(file) ||
1213+
(isCaseInsensitiveFS && // can skip case check on Linux
1214+
!fs.statSync(file).isDirectory() &&
1215+
!hasCorrectCase(file, assetsDir))
1216+
) {
1217+
return false
1218+
}
1219+
return true
1220+
} catch (err) {
12141221
return false
12151222
}
1216-
return true
12171223
}
12181224

12191225
/**

0 commit comments

Comments
 (0)