Security
Vue escapes interpolated text ({{ comment.body }}) automatically—but two template bindings remain XSS vectors: v-html renders raw HTML, and dynamic :href bindings accept javascript: URLs.
In short
- Guard
v-html: render plain text whenever possible, or pass HTML through adefineSanitizerreturning theHtmlproof type (vue-v-html). - Validate dynamic URLs: wrap user-supplied
:href/:srcvalues withsafeHref(...)from@evobug_com/safe-ts-vue/url(vue-unsafe-url).
Both unguarded v-html and unvalidated :href are rejected statically:
✕ Rejectedvue-v-htmlvue-unsafe-url
vue
<script setup lang="ts">
type Comment = { readonly author: string; readonly website: string; readonly body: string };
const props = defineProps<{ comment: Comment }>();
</script>
<template>
<a :href="props.comment.website">{{ props.comment.author }}</a>
<div v-html="props.comment.body"></div>
</template>✓ Accepted0 diagnostics
vue
<script setup lang="ts">
import { safeHref } from "@evobug_com/safe-ts-vue/url";
type Comment = { readonly author: string; readonly website: string; readonly body: string };
const props = defineProps<{ comment: Comment }>();
</script>
<template>
<a :href="safeHref(props.comment.website)">{{ props.comment.author }}</a>
<p>{{ props.comment.body }}</p>
</template>safeHref(url) returns the URL when it is relative or uses http:, https:, mailto: or tel:, and "#" otherwise. It reads the scheme the way browsers do, so JaVaScRiPt: and " java\tscript:" don't get through. When the HTML must be rendered as HTML, pass it through a sanitizer: v-html="DOMPurify.sanitize(html)", or a computed or function of yours that returns its result. A function isn't trusted for its name, only for what it returns.
Another scheme your app opens (its own flow:, blob: for an object URL) is allowed when you list it: safeHref(url, { schemes: ["flow"] }), with fallback there too if # isn't the one you want (the fallback is checked with the same schemes: a refused one gives #). javascript:, vbscript: and data: stay refused even when listed. A URL written out in the template that safeHref would refuse (safeHref('flow://watch') without the option) is reported, because that link always goes to #.
To check once and bind the result anywhere, keep the types the helpers return: safeHref gives a SafeUrl, and a sanitizer declared with defineSanitizer (from @evobug_com/safe-ts-vue/html) gives an Html. Both rules accept a value of those types from a computed, a prop or a ?:, next to what they accept as written (a sanitizer's result, a computed of it, safeHref(...)), and a prop typed SafeUrl or Html can only be given a checked value: vue-tsc refuses a plain string. See Proof types.
Rules on this page: vue-v-html, vue-unsafe-url