|
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 | + @for @ember/template |
| 36 | + @class SafeString |
| 37 | + @since 4.12.0 |
| 38 | + @public |
| 39 | + */ |
7 | 40 | export class SafeString implements GlimmerSafeString {
|
8 | 41 | private __string: string;
|
9 | 42 |
|
10 | 43 | constructor(string: string) {
|
11 | 44 | this.__string = string;
|
12 | 45 | }
|
13 | 46 |
|
| 47 | + /** |
| 48 | + Get the string back to use as a string. |
| 49 | +
|
| 50 | + @public |
| 51 | + @method toString |
| 52 | + @returns {String} The string marked as trusted |
| 53 | + */ |
14 | 54 | toString(): string {
|
15 | 55 | return `${this.__string}`;
|
16 | 56 | }
|
17 | 57 |
|
| 58 | + /** |
| 59 | + Get the wrapped string as HTML to use without escaping. |
| 60 | +
|
| 61 | + @public |
| 62 | + @method toHTML |
| 63 | + @returns {String} the trusted string, without any escaping applied |
| 64 | + */ |
18 | 65 | toHTML(): string {
|
19 | 66 | return this.toString();
|
20 | 67 | }
|
@@ -115,8 +162,8 @@ export function htmlSafe(str: string): SafeString {
|
115 | 162 | ```javascript
|
116 | 163 | import { htmlSafe, isHTMLSafe } from '@ember/template';
|
117 | 164 |
|
118 |
| - var plainString = 'plain string', |
119 |
| - safeString = htmlSafe('<div>someValue</div>'); |
| 165 | + let plainString = 'plain string'; |
| 166 | + let safeString = htmlSafe('<div>someValue</div>'); |
120 | 167 |
|
121 | 168 | isHTMLSafe(plainString); // false
|
122 | 169 | isHTMLSafe(safeString); // true
|
|
0 commit comments