Skip to content

Commit

Permalink
feat: support files for fs.allow (#12863)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ph0tonic authored Jun 6, 2023
1 parent b9a6ba0 commit 4a06e66
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
5 changes: 4 additions & 1 deletion docs/config/server-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,8 @@ Restrict serving files outside of workspace root.

Restrict files that could be served via `/@fs/`. When `server.fs.strict` is set to `true`, accessing files outside this directory list that aren't imported from an allowed file will result in a 403.

Both directories and files can be provided.

Vite will search for the root of the potential workspace and use it as default. A valid workspace met the following conditions, otherwise will fall back to the [project root](/guide/#index-html-and-project-root).

- contains `workspaces` field in `package.json`
Expand Down Expand Up @@ -298,7 +300,8 @@ export default defineConfig({
// search up for workspace root
searchForWorkspaceRoot(process.cwd()),
// your custom rules
'/path/to/custom/allow',
'/path/to/custom/allow_directory',
'/path/to/custom/allow_file.demo',
],
},
},
Expand Down
7 changes: 6 additions & 1 deletion packages/vite/src/node/server/middlewares/static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
isImportRequest,
isInternalRequest,
isParentDirectory,
isSameFileUri,
isWindows,
removeLeadingSlash,
shouldServeFile,
Expand Down Expand Up @@ -199,7 +200,11 @@ export function isFileServingAllowed(

if (server.moduleGraph.safeModulesPath.has(file)) return true

if (server.config.server.fs.allow.some((dir) => isParentDirectory(dir, file)))
if (
server.config.server.fs.allow.some(
(uri) => isSameFileUri(uri, file) || isParentDirectory(uri, file),
)
)
return true

return false
Expand Down
16 changes: 16 additions & 0 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,22 @@ export function isParentDirectory(dir: string, file: string): boolean {
)
}

/**
* Check if 2 file name are identical
*
* Warning: parameters are not validated, only works with normalized absolute paths
*
* @param file1 - normalized absolute path
* @param file2 - normalized absolute path
* @returns true if both files url are identical
*/
export function isSameFileUri(file1: string, file2: string): boolean {
return (
file1 === file2 ||
(isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase())
)
}

export const queryRE = /\?.*$/s

const postfixRE = /[?#].*$/s
Expand Down

0 comments on commit 4a06e66

Please sign in to comment.