Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(CSP): nonce support #11958

Closed
wants to merge 1 commit into from
Closed
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
55 changes: 54 additions & 1 deletion packages/vite/src/node/__tests__/build.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import colors from 'picocolors'
import { describe, expect, test, vi } from 'vitest'
import type { OutputChunk, OutputOptions, RollupOutput } from 'rollup'
import type {
OutputAsset,
OutputChunk,
OutputOptions,
RollupOutput,
} from 'rollup'
import type { LibraryFormats, LibraryOptions } from '../build'
import { build, resolveBuildOutputs, resolveLibFilename } from '../build'
import type { Logger } from '../logger'
Expand Down Expand Up @@ -102,6 +107,54 @@ describe('build', () => {
])
assertOutputHashContentChange(result[0], result[1])
})

describe('nonce placeholder', () => {
const buildProject = async (noncePlaceholder?: string) => {
return (await build({
root: resolve(__dirname, 'packages/build-project'),
logLevel: 'silent',
build: {
write: false,
noncePlaceholder,
},
plugins: [
{
name: 'test',
resolveId(id) {
if (id === 'entry.js') {
return '\0' + id
}
},
load(id) {
if (id === '\0entry.js') {
return `console.log('hello world')`
}
},
},
],
})) as RollupOutput
}

test('nonce placeholder should be added to html script tag', async () => {
const result = await buildProject('TEST_NONCE')

expect(result.output).toHaveLength(2)

const htmlAsset = result.output[1] as OutputAsset

expect(htmlAsset.source).toMatch(`nonce=\"TEST_NONCE\"`)
})

test('nonce placeholder should not be added to html script tag', async () => {
const result = await buildProject()

expect(result.output).toHaveLength(2)

const htmlAsset = result.output[1] as OutputAsset

expect(htmlAsset.source).not.toMatch(`nonce`)
})
})
})

const baseLibOptions: LibraryOptions = {
Expand Down
5 changes: 5 additions & 0 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,11 @@ export interface BuildOptions {
* @default null
*/
watch?: WatcherOptions | null

/**
* If specified, adds a `nonce` attribute to HTML script and link tags with the placeholder value.
*/
noncePlaceholder?: string
}

export interface LibraryOptions {
Expand Down
7 changes: 7 additions & 0 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,9 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
return chunks
}

const hasNonce = config.build.noncePlaceholder?.length > 0
const nonce = config.build.noncePlaceholder

const toScriptTag = (
chunk: OutputChunk,
toOutputPath: (filename: string) => string,
Expand All @@ -636,6 +639,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
type: 'module',
crossorigin: true,
src: toOutputPath(chunk.fileName),
...(hasNonce ? { nonce } : {}),
},
})

Expand All @@ -648,6 +652,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
rel: 'modulepreload',
crossorigin: true,
href: toOutputPath(filename),
...(hasNonce ? { nonce } : {}),
},
})

Expand Down Expand Up @@ -675,6 +680,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
attrs: {
rel: 'stylesheet',
href: toOutputPath(file),
...(hasNonce ? { nonce } : {}),
},
})
}
Expand Down Expand Up @@ -782,6 +788,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
attrs: {
rel: 'stylesheet',
href: toOutputAssetFilePath(cssChunk.fileName),
...(hasNonce ? { nonce } : {}),
},
},
])
Expand Down
22 changes: 22 additions & 0 deletions playground/html/__tests__/html.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,28 @@ describe.runIf(isBuild)('build', () => {
)
})
})

describe('nonce', () => {
beforeAll(async () => {
await page.goto(viteTestUrl + '/nonce.html')
})

test('nonce should be included in html tags', async () => {
const scripts = await page.locator('script').all()
const links = await page.locator('link[rel=stylesheet]').all()

await Promise.all(
scripts.map(async (script) =>
expect(await script.getAttribute('nonce')).toBe('TEST_NONCE'),
),
)
await Promise.all(
links.map(async (link) =>
expect(await link.getAttribute('nonce')).toBe('TEST_NONCE'),
),
)
})
})
})

describe('noHead', () => {
Expand Down
17 changes: 17 additions & 0 deletions playground/html/nonce.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/main.css" />
<title>Nonce</title>
</head>
<body>
<h1>Nonce.html</h1>
<script nonce="TEST_NONCE">
console.log('hello world')
</script>
<script type="module" src="/main.js"></script>
</body>
</html>
6 changes: 5 additions & 1 deletion playground/html/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ export default defineConfig({
env: resolve(__dirname, 'env.html'),
sideEffects: resolve(__dirname, 'side-effects/index.html'),
'a á': resolve(__dirname, 'a á.html'),
nonce: resolve(__dirname, 'nonce.html'),
},
},
noncePlaceholder: 'TEST_NONCE',
},

define: {
Expand Down Expand Up @@ -175,7 +177,9 @@ ${
{
name: 'head-prepend-importmap',
transformIndexHtml(_, ctx) {
if (ctx.path.includes('importmapOrder')) return
if (ctx.path.includes('importmapOrder') || ctx.path.includes('nonce')) {
return
}

return [
{
Expand Down