如何将Buefy的对话框组件与用户提供的内容一起使用,并确保XSS的安全性

Buefy的对话框组件需要message属性字符串。根据一份文档,该字符串可以包含HTML。我希望在字符串中使用模板值,但当然这应该是XSS安全的。

当前不安全示例

这是不安全的,因为this.name不安全。我可以使用NPM包对名称进行html编码,但我真的更喜欢使用Vue。

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
  props: {
    name: { type: String, required: false },
  },
  methods: {
    showModal() {
      this.$buefy.dialog.confirm({
        title: 'myTitle',
        message: `<p>Hello ${this.name}</p>`, // unsafe - possible XSS!
        cancelText: 'Cancel',
        confirmText: 'OK',
        type: 'is-success',
        onConfirm: async () => {
          // something
        },
      });
    },
  },
});
</script>

这是已使用的Buefy组件的问题,文档here:

所需设置

我已经创建了一个新组件,在本例中我将其命名为ModalMessage.Vue

<template>
    <p>Hello {{name}}</p>
</template>

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
  props: {
    name: { type: String, required: true },
  },
});
</script>

然后,我希望将ModalMessage.Vue呈现为string在TypeScript:

<script lang="ts">
import Vue from 'vue';
import ModalMessage from 'ModalMessage.vue';

export default Vue.extend({
  props: {
    name: { type: String, required: false },
  },
  methods: {
    showModal() {
      this.$buefy.dialog.confirm({
        title: 'myTitle',
        message:, // todo render ModalMessage and pass name prop
        cancelText: 'Cancel',
        confirmText: 'OK',
        type: 'is-success',
        onConfirm: async () => {
          // something
        },
      });
    },
  },
});
</script>

问题

如何将ModalMessage.Vue呈现并将名称prop传递给string

我非常肯定这是可能的--我过去就见过。不幸的是,我在网络或StackOverflow上找不到它。我只能找到从到字符串呈现模板的问题,但我不需要它-它需要从到字符串。


解决方案

我的真正问题是

如何将Buefy的对话框组件与用户提供的内容一起使用并确保安全(&P> 因此,您需要创建一些HTML,在该HTML内容中包含一些用户提供内容(this.name),并在一个对话框中显示它。您说得对,将未过滤的用户输入放入Dialogmessage参数是不安全的(如Buefy docs中明确指出的)

但您所需的设置似乎不必要地复杂。最简单的方法是使用(文档很少)这样一个事实,即BuefyDialog配置对象的message参数可以是VNode的Array而不是字符串。它的文档很少,但从源代码here和here可以清楚地看出,如果您传递一个VNode数组,Buefy会将该内容放入Dialog的默认槽中,而不是使用v-html呈现它(这是危险的部分)

在Vue中获得VNodeArray最简单的方法是使用插槽...

因此组件:

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
  methods: {
    showModal() {
      this.$buefy.dialog.confirm({
        title: 'myTitle',
        message: this.$slots.default, // <- this is important part
        cancelText: 'Cancel',
        confirmText: 'OK',
        type: 'is-success',
        onConfirm: async () => {
          // something
        },
      });
    },
  },
});
</script>

及其用法:

<MyDialog>
  <p>Hello {{name}}</p>
</MyDialog>

<MyDialog>
  <ModalMessage :name="name" />
</MyDialog>

在这两种情况下,如果name包含任何HTML,则它将是encoded by Vue

Here是上述技术的简单演示(使用纯JS而不是TS)

相关文章

初识 XSS 3

2023-01-31 xss 初识