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

feat(runtime-dom): a new __VUE_PROD_TRUSTED_TYPES__ flag for trusted types compatibility #10844

Open
wants to merge 11 commits into
base: minor
Choose a base branch
from
Open
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
"@types/minimist": "^1.2.5",
"@types/node": "^20.12.12",
"@types/semver": "^7.5.8",
"@types/serve-handler": "^6.1.4",
"@vitest/coverage-istanbul": "^1.5.2",
"@vue/consolidate": "1.0.0",
"conventional-changelog-cli": "^4.1.0",
Expand Down Expand Up @@ -103,6 +104,7 @@
"rollup-plugin-polyfill-node": "^0.13.0",
"semver": "^7.6.2",
"serve": "^14.2.3",
"serve-handler": "^6.1.5",
"simple-git-hooks": "^2.11.1",
"terser": "^5.31.0",
"todomvc-app-css": "^2.4.3",
Expand Down
1 change: 1 addition & 0 deletions packages/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ declare var __FEATURE_OPTIONS_API__: boolean
declare var __FEATURE_PROD_DEVTOOLS__: boolean
declare var __FEATURE_SUSPENSE__: boolean
declare var __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__: boolean
declare var __FEATURE_PROD_TRUSTED_TYPES__: boolean

// for tests
declare namespace jest {
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime-core/src/compat/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ function installCompatMount(
}

// clear content before mounting
container.innerHTML = ''
container.textContent = ''

// TODO hydration
render(vnode, container, namespace)
Expand Down
5 changes: 5 additions & 0 deletions packages/runtime-core/src/featureFlags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ export function initFeatureFlags() {
getGlobalThis().__VUE_PROD_HYDRATION_MISMATCH_DETAILS__ = false
}

if (typeof __FEATURE_PROD_TRUSTED_TYPES__ !== 'boolean') {
__DEV__ && needWarn.push(`__VUE_PROD_TRUSTED_TYPES__`)
getGlobalThis().__VUE_PROD_TRUSTED_TYPES__ = false
}

if (__DEV__ && needWarn.length) {
const multi = needWarn.length > 1
console.warn(
Expand Down
5 changes: 4 additions & 1 deletion packages/runtime-dom/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,11 @@
},
"homepage": "https://github.com/vuejs/core/tree/main/packages/runtime-dom#readme",
"dependencies": {
"@vue/shared": "workspace:*",
"@vue/runtime-core": "workspace:*",
"@vue/shared": "workspace:*",
"csstype": "^3.1.3"
},
"devDependencies": {
"@types/trusted-types": "^2.0.7"
}
}
2 changes: 1 addition & 1 deletion packages/runtime-dom/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ export const createApp = ((...args) => {
}

// clear content before mounting
container.innerHTML = ''
container.textContent = ''
const proxy = mount(container, false, resolveRootNamespace(container))
if (container instanceof Element) {
container.removeAttribute('v-cloak')
Expand Down
49 changes: 47 additions & 2 deletions packages/runtime-dom/src/nodeOps.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,48 @@
import { warn } from '@vue/runtime-core'
import type { RendererOptions } from '@vue/runtime-core'
import type {
TrustedHTML,
TrustedTypePolicy,
TrustedTypesWindow,
} from 'trusted-types/lib'

type VueTrustedTypePolicy =
| Pick<TrustedTypePolicy, 'name' | 'createHTML'>
| undefined

let policy: VueTrustedTypePolicy = undefined
function getPolicy(): VueTrustedTypePolicy {
const ttWindow = window as unknown as TrustedTypesWindow
if (
(__DEV__ || __FEATURE_PROD_TRUSTED_TYPES__) &&
ttWindow.trustedTypes &&
!policy
) {
try {
policy = ttWindow.trustedTypes.createPolicy('vue', {
createHTML: val => val,
})
} catch (e: unknown) {
// `createPolicy` throws a TypeError if the name is a duplicate
// and the CSP trusted-types directive is not using `allow-duplicates`.
// So we have to catch that error.
warn(`Error creating trusted types policy: ${e}`)
}
}
return policy
}

// __UNSAFE__
// Reason: potentially setting innerHTML.
// This function merely perform a type-level trusted type conversion
// for use in `innerHTML` assignment, etc.
// Be careful of whatever value passed to this function.
function unsafeToTrustedHTML(value: string): TrustedHTML | string {
/* eslint-disable-next-line no-restricted-syntax --
* the minified compilation result of a single `()?.` isn't very verbose,
* we use the syntax for readability here. */
return getPolicy()?.createHTML(value) || value
}

export const svgNS = 'http://www.w3.org/2000/svg'
export const mathmlNS = 'http://www.w3.org/1998/Math/MathML'
Expand Down Expand Up @@ -74,12 +118,13 @@ export const nodeOps: Omit<RendererOptions<Node, Element>, 'patchProp'> = {
}
} else {
// fresh insert
templateContainer.innerHTML =
templateContainer.innerHTML = unsafeToTrustedHTML(
namespace === 'svg'
? `<svg>${content}</svg>`
: namespace === 'mathml'
? `<math>${content}</math>`
: content
: content,
) as string

const template = templateContainer.content
if (namespace === 'svg' || namespace === 'mathml') {
Expand Down
4 changes: 4 additions & 0 deletions packages/vue/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@
- Default: `false`
- Enable / disable detailed warnings for hydration mismatches in production

- `__VUE_PROD_TRUSTED_TYPES__`
- Default: `false`
- Enable / disable built-in Trusted Types Policy for compatibility with the [`trusted-types` CSP directive](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/trusted-types)

The build will work without configuring these flags, however it is **strongly recommended** to properly configure them in order to get proper tree-shaking in the final bundle.

### For Server-Side Rendering
Expand Down
17 changes: 17 additions & 0 deletions packages/vue/__tests__/e2e/trusted-types.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="data:;base64,iVBORw0KGgo=">
<meta
http-equiv="content-security-policy"
content="require-trusted-types-for 'script'"
/>
<title>Vue App</title>
<script src="../../dist/vue.global.js"></script>
</head>

<body>
<div id="app"></div>
</body>
</html>
103 changes: 103 additions & 0 deletions packages/vue/__tests__/e2e/trusted-types.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { once } from 'node:events'
import { createServer } from 'node:http'
import path from 'node:path'
import { beforeAll } from 'vitest'
import serveHandler from 'serve-handler'

import { E2E_TIMEOUT, setupPuppeteer } from './e2eUtils'

// use the `vue` package root as the public directory
// because we need to serve the Vue runtime for the tests
const serverRoot = path.resolve(import.meta.dirname, '../../')
const testPort = 9090
const basePath = path.relative(
serverRoot,
path.resolve(import.meta.dirname, './trusted-types.html'),
)
const baseUrl = `http://localhost:${testPort}/${basePath}`

const { page, html } = setupPuppeteer()

let server: ReturnType<typeof createServer>
beforeAll(async () => {
// sets up the static server
server = createServer((req, res) => {
return serveHandler(req, res, {
public: serverRoot,
cleanUrls: false,
})
})

server.listen(testPort)
await once(server, 'listening')
})

afterAll(async () => {
server.close()
await once(server, 'close')
})

describe('e2e: trusted types', () => {
beforeEach(async () => {
await page().goto(baseUrl)
await page().waitForSelector('#app')
})

test(
'should render the hello world app',
async () => {
await page().evaluate(() => {
const { createApp, ref, h } = (window as any).Vue
createApp({
setup() {
const msg = ref('✅success: hello world')
return function render() {
return h('div', msg.value)
}
},
}).mount('#app')
})
expect(await html('#app')).toContain('<div>✅success: hello world</div>')
},
E2E_TIMEOUT,
)

test(
'should render static vnode without error',
async () => {
await page().evaluate(() => {
const { createApp, createStaticVNode } = (window as any).Vue
createApp({
render() {
return createStaticVNode('<div>✅success: static vnode</div>')
},
}).mount('#app')
})
expect(await html('#app')).toContain('<div>✅success: static vnode</div>')
},
E2E_TIMEOUT,
)

test(
'should accept v-html with custom policy',
async () => {
await page().evaluate(() => {
const testPolicy = (window as any).trustedTypes.createPolicy('test', {
createHTML: (input: string): string => input,
})

const { createApp, ref, h } = (window as any).Vue
createApp({
setup() {
const msg = ref('✅success: v-html')
return function render() {
return h('div', { innerHTML: testPolicy.createHTML(msg.value) })
}
},
}).mount('#app')
})
expect(await html('#app')).toContain('<div>✅success: v-html</div>')
},
E2E_TIMEOUT,
)
})
22 changes: 22 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,9 @@ function createConfig(format, output, plugins = []) {
__FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__: isBundlerESMBuild
? `__VUE_PROD_HYDRATION_MISMATCH_DETAILS__`
: `false`,
__FEATURE_PROD_TRUSTED_TYPES__: isBundlerESMBuild
? `__VUE_PROD_TRUSTED_TYPES__`
: `false`,
}

if (!isBundlerESMBuild) {
Expand Down
1 change: 1 addition & 0 deletions scripts/dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ for (const target of targets) {
__FEATURE_OPTIONS_API__: `true`,
__FEATURE_PROD_DEVTOOLS__: `false`,
__FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__: `false`,
__FEATURE_PROD_TRUSTED_TYPES__: `false`,
},
})
.then(ctx => ctx.watch())
Expand Down
1 change: 1 addition & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export default defineConfig({
__FEATURE_SUSPENSE__: true,
__FEATURE_PROD_DEVTOOLS__: false,
__FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__: false,
__FEATURE_PROD_TRUSTED_TYPES__: false,
__COMPAT__: true,
},
resolve: {
Expand Down