Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { createServer } from '../../../server'
const FIXTURE_DIR = path.resolve(import.meta.dirname, 'fixtures')
const HTML_PATH = path.resolve(FIXTURE_DIR, 'root/index.html')
const HTML_CONTENT = fs.readFileSync(HTML_PATH, 'utf-8')
const VITE_PACKAGE_DIR = path.resolve(import.meta.dirname, '../../../../..')

async function createTestServer(rootDir?: string) {
const root = path.resolve(import.meta.dirname, rootDir ?? 'fixtures/root')
Expand All @@ -29,7 +30,7 @@ async function createTestServer(rootDir?: string) {
return server
}

describe('indexHtml middleware — /@fs/ inline script proxy cache', () => {
describe('indexHtml middleware — inline script proxy cache', () => {
test('inline <script type="module"> in an /@fs/ HTML file is loadable via the html-proxy module', async () => {
const server = await createTestServer()
const fsUrl = path.posix.join(FS_PREFIX, HTML_PATH)
Expand Down Expand Up @@ -85,6 +86,25 @@ describe('indexHtml middleware — /@fs/ inline script proxy cache', () => {
expect(result, 'proxy module should resolve without error').not.toBeNull()
expect(result!.code).toContain('module loaded')
})

for (const prefix of ['//', '///']) {
test(`does not preserve a protocol-relative request URL (${prefix}) as the inline module proxy URL`, async () => {
const server = await createTestServer(VITE_PACKAGE_DIR)
const url = prefix + 'evil.example.com/payload.js?/../../package.json'

const transformed = await server.transformIndexHtml(url, HTML_CONTENT)
const proxyUrlMatch = transformed.match(/src="([^"]*html-proxy[^"]*)"/)

expect(
proxyUrlMatch,
'devHtmlHook should have rewritten the inline <script> to a ?html-proxy src',
).toBeTruthy()
expect(proxyUrlMatch![1]).toMatchInlineSnapshot(
`"/@id/__x00__/evil.example.com/payload.js?/../../package.json?html-proxy&index=0.js"`,
)
expect(proxyUrlMatch![1]).not.toMatch(/^\/\//)
})
}
})

describe('indexHtml middleware — HMR timestamp injection with non-root base', () => {
Expand Down
16 changes: 13 additions & 3 deletions packages/vite/src/node/server/middlewares/indexHtml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,12 @@ export function createDevHtmlTransformFn(
}

function getHtmlFilename(url: string, server: ViteDevServer) {
if (url.startsWith(FS_PREFIX)) {
return decodeURIComponent(fsPathFromId(url))
const urlPath = cleanUrl(url)
if (urlPath.startsWith(FS_PREFIX)) {
return decodeURIComponent(fsPathFromId(urlPath))
} else {
return decodeURIComponent(
normalizePath(path.join(server.config.root, url.slice(1))),
normalizePath(path.join(server.config.root, urlPath.slice(1))),
)
}
}
Expand All @@ -131,6 +132,8 @@ function getHtmlDirnameForRelativeUrl(htmlPath: string): string {
return htmlPath.endsWith('/') ? htmlPath : path.posix.dirname(htmlPath)
}

const multipleLeadingSlashesRE = /^\/{2,}/g

const processNodeUrl = (
url: string,
useSrcSetReplacer: boolean,
Expand Down Expand Up @@ -205,6 +208,13 @@ const devHtmlHook: IndexHtmlTransformHook = async (
html,
{ path: htmlPath, filename, server, originalUrl },
) => {
// There's no way to express a relative URL that starts with `//`. URLs starting with `//` is relative to the scheme.
// The relative URL is needed to generate the URL in script tags and link tags.
// We replace `//` with `/` here for workaround, which is the best we can do.
if (htmlPath.startsWith('//')) {
htmlPath = htmlPath.replace(multipleLeadingSlashesRE, '/')
}

const { config, watcher } = server!
const base = config.base || '/'
const decodedBase = config.decodedBase || '/'
Expand Down
26 changes: 26 additions & 0 deletions playground/html/__tests__/html.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,32 @@ test('invalidate inline proxy module on reload', async () => {
expect(await page.textContent('.test')).toContain('ok')
})

test.runIf(!isBundled)(
'normalizes protocol-relative HTML proxy URLs',
async () => {
const response = await fetchHtml('//protocol-relative.html')
const html = await response.text()

expect(response.status).toBe(200)
expect(html).toContain('url(./protocol-relative.png)')
expect(html).toContain(
'src="/protocol-relative.html?html-proxy&index=0.js"',
)
expect(html).not.toContain('url(//protocol-relative.png)')
expect(html).not.toContain('src="//protocol-relative.html?html-proxy')
expect(
viteServer.environments.client.moduleGraph.urlToModuleMap.has(
'/protocol-relative.html?html-proxy&direct&index=0.css',
),
).toBe(true)
expect(
viteServer.environments.client.moduleGraph.urlToModuleMap.has(
'//protocol-relative.html?html-proxy&direct&index=0.css',
),
).toBe(false)
},
)

test.runIf(isServe)(
'malformed URLs in src attributes should show errors',
async () => {
Expand Down
8 changes: 8 additions & 0 deletions playground/html/protocol-relative.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<style>
body {
background: url(./protocol-relative.png);
}
</style>
<script type="module">
document.body.dataset.loaded = 'true'
</script>
Loading