Skip to content

Commit

Permalink
use normalizeFilePath instead of URL
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe committed Sep 21, 2024
1 parent a93839a commit 5f07dd7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
11 changes: 11 additions & 0 deletions src/utils/filepath.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,17 @@ describe('getFilePath', () => {
expect(
getFilePath({ filename: 'foo.txt', root: slashToBackslash('/p/../p2'), allowAbsoluteRoot })
).toBe('/p2/foo.txt')
expect(
getFilePath({ filename: 'foo.txt', root: slashToBackslash('/p/.../p2'), allowAbsoluteRoot })
).toBe('/p/.../p2/foo.txt')

expect(
getFilePathWithoutDefaultDocument({
filename: '/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd',
root: '/p/p2',
allowAbsoluteRoot: true,
})
).toBe('/p/p2/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd') // /etc/passwd
})
})

Expand Down
23 changes: 20 additions & 3 deletions src/utils/filepath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,24 @@ export const getFilePath = (options: FilePathOptions): string | undefined => {
return path
}

const normalizeFilePath = (filePath: string) => {
const parts = filePath.split(/[\/\\]/)

const result = []

for (const part of parts) {
if (part === '' || part === '.') {
continue
} else if (part === '..') {
result.pop()
} else {
result.push(part)
}
}

return '/' + (result.length === 1 ? result[0] : result.join('/'))
}

export const getFilePathWithoutDefaultDocument = (
options: Omit<FilePathOptions, 'defaultDocument'>
): string | undefined => {
Expand Down Expand Up @@ -61,9 +79,8 @@ export const getFilePathWithoutDefaultDocument = (
} else {
// assets => /assets
path = path.replace(/^(?!\/)/, '/')
// Using URL to normalize the path.
const url = new URL(`file://${path}`)
path = url.pathname
// /assets/foo/../bar => /assets/bar
path = normalizeFilePath(path)
}

return path
Expand Down

0 comments on commit 5f07dd7

Please sign in to comment.