|
4 | 4 |
|
5 | 5 | import type { SafeString as GlimmerSafeString } from '@glimmer/runtime';
|
6 | 6 |
|
| 7 | +/** |
| 8 | + A wrapper around a string that has been marked as safe ("trusted"). **When |
| 9 | + rendered in HTML, Ember will not perform any escaping.** |
| 10 | +
|
| 11 | + Note: |
| 12 | +
|
| 13 | + 1. This does not *make* the string safe; it means that some code in your |
| 14 | + application has *marked* it as safe using the `htmlSafe()` function. |
| 15 | +
|
| 16 | + 2. The only public API for getting a `SafeString` is calling `htmlSafe()`. It |
| 17 | + is *not* user-constructible. |
| 18 | +
|
| 19 | + If a string contains user inputs or other untrusted data, you must sanitize |
| 20 | + the string before using the `htmlSafe` method. Otherwise your code is |
| 21 | + vulnerable to [Cross-Site Scripting][xss]. There are many open source |
| 22 | + sanitization libraries to choose from, both for front end and server-side |
| 23 | + sanitization. |
| 24 | +
|
| 25 | + [xss]: https://owasp.org/www-community/attacks/DOM_Based_XSS |
| 26 | +
|
| 27 | + ```javascript |
| 28 | + import { htmlSafe } from '@ember/template'; |
| 29 | +
|
| 30 | + let someTrustedOrSanitizedString = "<div>Hello!</div>" |
| 31 | +
|
| 32 | + htmlSafe(someTrustedorSanitizedString); |
| 33 | + ``` |
| 34 | +
|
| 35 | + @public |
| 36 | + @since 4.12.0 |
| 37 | + @class SafeString |
| 38 | + */ |
7 | 39 | export class SafeString implements GlimmerSafeString {
|
8 | 40 | private __string: string;
|
9 | 41 |
|
10 | 42 | constructor(string: string) {
|
11 | 43 | this.__string = string;
|
12 | 44 | }
|
13 | 45 |
|
| 46 | + /** |
| 47 | + Get the string back to use as a string. |
| 48 | +
|
| 49 | + @public |
| 50 | + @method toString |
| 51 | + @returns The string marked as trusted |
| 52 | + */ |
14 | 53 | toString(): string {
|
15 | 54 | return `${this.__string}`;
|
16 | 55 | }
|
17 | 56 |
|
| 57 | + /** |
| 58 | + Get the wrapped string as HTML to use without escaping. |
| 59 | +
|
| 60 | + @public |
| 61 | + @method toHTML |
| 62 | + @returns string |
| 63 | + */ |
18 | 64 | toHTML(): string {
|
19 | 65 | return this.toString();
|
20 | 66 | }
|
@@ -115,8 +161,8 @@ export function htmlSafe(str: string): SafeString {
|
115 | 161 | ```javascript
|
116 | 162 | import { htmlSafe, isHTMLSafe } from '@ember/template';
|
117 | 163 |
|
118 |
| - var plainString = 'plain string', |
119 |
| - safeString = htmlSafe('<div>someValue</div>'); |
| 164 | + let plainString = 'plain string'; |
| 165 | + let safeString = htmlSafe('<div>someValue</div>'); |
120 | 166 |
|
121 | 167 | isHTMLSafe(plainString); // false
|
122 | 168 | isHTMLSafe(safeString); // true
|
|
0 commit comments