Sanitizing HTML Input with Trix

1.6k views Asked by At

I have a strange issue at the moment, and I'm looking for any insight on how to deal with this.

I'm currently accepting HTML input using the Basecamp Trix editor.

When I send the input to my Laravel application, it is saved to my database as:

<div>&lt;script&gt;alert('test');&lt;/script&gt;</div>

However, the problem is that when I insert this into a Vue property using Laravel's blade, it somehow actually converts it back into valid HTML:

<reply :data-reply="{{ $reply }}"></reply>

Result:

enter image description here

It seems that Laravel converts the script tags to valid HTML using the blade echo statements?

My View:

{{ $reply }}

Result:

{"id":63,"created_at":"2017-09-07 13:30:53","updated_at":"2017-09-07 13:35:05","user_id":1,"body":"<div><script>alert('test');<\/script><\/div>","options":null}

The problem is, I can't sanitize this because the HTML data is actually escaped in my database, but when Laravel converts my reply to JSON, it actually unescapes the script tags, and it's actually ran in Vue when using the v-html directive.

I know I'm not supposed to accept user input while using the v-html directive, but I need HTML support for replies, and I can't sanitize already escaped HTML in my Laravel application.

Does anyone have any ideas how I can go about sanitizing Trix's content in some way?

1

There are 1 answers

9
Marcin Nabiałek On

Ok, I've put

<div>&lt;script&gt;alert('test');&lt;/script&gt;</div>

into email field of user.

In Laravel I'm just using:

return view('welcome', ['user' => App\User::find(1)]);

nothing special in model.

My view looks like this:

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div id="el">{{ $user }}</div>
<script>
    user = JSON.parse(document.getElementById("el").innerHTML);
    console.log(user.name);
</script>
</body>
</html>    

and in JS console I'm getting:

&lt;div&gt;&lt;script&gt;alert('test');&lt;/script&gt;&lt;/div&gt;

so it's not the same as in database but it doesn't look as you showed either.