Skip to content

nonce tag in __vitePreload (CSP) #9719

@vinicius73

Description

@vinicius73

Description

I am trying to migrate or default tooling from Webpack to Vite.

The main issue is nonce security police.

Actually, we handle it using __webpack_nonce__

https://webpack.js.org/guides/csp/

I can't interact with the preload function to change it.

function preload(
baseModule: () => Promise<{}>,
deps?: string[],
importerUrl?: string
) {
// @ts-ignore
if (!__VITE_IS_MODERN__ || !deps || deps.length === 0) {
return baseModule()
}
return Promise.all(
deps.map((dep) => {
// @ts-ignore
dep = assetsURL(dep, importerUrl)
// @ts-ignore
if (dep in seen) return
// @ts-ignore
seen[dep] = true
const isCss = dep.endsWith('.css')
const cssSelector = isCss ? '[rel="stylesheet"]' : ''
// @ts-ignore check if the file is already preloaded by SSR markup
if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
return
}
// @ts-ignore
const link = document.createElement('link')
// @ts-ignore
link.rel = isCss ? 'stylesheet' : scriptRel
if (!isCss) {
link.as = 'script'
link.crossOrigin = ''
}
link.href = dep
// @ts-ignore
document.head.appendChild(link)
if (isCss) {
return new Promise((res, rej) => {
link.addEventListener('load', res)
link.addEventListener('error', () =>
rej(new Error(`Unable to preload CSS for ${dep}`))
)
})
}
})
).then(() => baseModule())
}

I'm already injecting the preload tags manually, JavaScript and CSS files.

Suggested solution

A way to inject nonce value simular to webpack.

Alternative

No response

Additional context

Example Application

https://github.com/nextcloud/text/blob/48b21b6e524c4aef78a1046e1f19a2bbd85837c4/src/main.js#L3-L4

Nextcloud apps

Nextcloud is modular, and allow the users to install a variety of apps.
These apps can inject scripts in many parts of nextcloud.

For secure reasons, we use CSP to prevent malicious script injections.

Content-Security-Policy: default-src 'none';base-uri 'none';manifest-src 'self';script-src 'nonce-cHQ...bz0=';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-src 'self';frame-ancestors 'self';form-action 'self'

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    p3-minor-bugAn edge case that only affects very specific usage (priority)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions