Skip to content

Commit

Permalink
fix: skip fs fallback for out of root urls, fix vitejs#3364 (vitejs#3431
Browse files Browse the repository at this point in the history
)
  • Loading branch information
patak-dev authored and fi3ework committed May 22, 2021
1 parent 15234ed commit 14276e4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 13 deletions.
14 changes: 11 additions & 3 deletions packages/vite/src/node/server/middlewares/static.ts
Expand Up @@ -109,16 +109,24 @@ export function serveRawFsMiddleware(
}
}

export function isFileAccessAllowed(
url: string,
{ root, strict }: Required<FileSystemServeOptions>
): boolean {
return !strict || normalizePath(url).startsWith(root + path.posix.sep)
}

export function ensureServingAccess(
url: string,
{ root, strict }: Required<FileSystemServeOptions>,
serveOptions: Required<FileSystemServeOptions>,
logger: Logger
): void {
const { strict, root } = serveOptions
// TODO: early return, should remove once we polished the restriction logic
if (!strict) return

const normalizedUrl = normalizePath(url)
if (!normalizedUrl.startsWith(root + path.posix.sep)) {
if (!isFileAccessAllowed(url, serveOptions)) {
const normalizedUrl = normalizePath(url)
if (strict) {
throw new AccessRestrictedError(
`The request url "${normalizedUrl}" is outside of vite dev server root "${root}".
Expand Down
21 changes: 11 additions & 10 deletions packages/vite/src/node/server/transformRequest.ts
Expand Up @@ -16,7 +16,7 @@ import {
import { checkPublicFile } from '../plugins/asset'
import { ssrTransform } from '../ssr/ssrTransform'
import { injectSourcesContent } from './sourcemap'
import { ensureServingAccess } from './middlewares/static'
import { isFileAccessAllowed } from './middlewares/static'

const debugLoad = createDebugger('vite:load')
const debugTransform = createDebugger('vite:transform')
Expand Down Expand Up @@ -73,15 +73,16 @@ export async function transformRequest(
// try fallback loading it from fs as string
// if the file is a binary, there should be a plugin that already loaded it
// as string
try {
if (!options.ssr) {
ensureServingAccess(file, config.server.fsServe, config.logger)
}
code = await fs.readFile(file, 'utf-8')
isDebug && debugLoad(`${timeFrom(loadStart)} [fs] ${prettyUrl}`)
} catch (e) {
if (e.code !== 'ENOENT') {
throw e
// only try the fallback if access is allowed, skip for out of root url
// like /service-worker.js or /api/users
if (options.ssr || isFileAccessAllowed(file, config.server.fsServe)) {
try {
code = await fs.readFile(file, 'utf-8')
isDebug && debugLoad(`${timeFrom(loadStart)} [fs] ${prettyUrl}`)
} catch (e) {
if (e.code !== 'ENOENT') {
throw e
}
}
}
if (code) {
Expand Down

0 comments on commit 14276e4

Please sign in to comment.