Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
seleniumhq
GitHub Repository: seleniumhq/selenium
Path: blob/trunk/third_party/closure/goog/html/safehtml.js
4507 views
1
/**
2
* @license
3
* Copyright The Closure Library Authors.
4
* SPDX-License-Identifier: Apache-2.0
5
*/
6
7
8
/**
9
* @fileoverview The SafeHtml type and its builders.
10
*
11
* TODO(xtof): Link to document stating type contract.
12
*/
13
14
goog.module('goog.html.SafeHtml');
15
goog.module.declareLegacyNamespace();
16
17
const Const = goog.require('goog.string.Const');
18
const SafeScript = goog.require('goog.html.SafeScript');
19
const SafeStyle = goog.require('goog.html.SafeStyle');
20
const SafeStyleSheet = goog.require('goog.html.SafeStyleSheet');
21
const SafeUrl = goog.require('goog.html.SafeUrl');
22
const TagName = goog.require('goog.dom.TagName');
23
const TrustedResourceUrl = goog.require('goog.html.TrustedResourceUrl');
24
const TypedString = goog.require('goog.string.TypedString');
25
const asserts = goog.require('goog.asserts');
26
const browser = goog.require('goog.labs.userAgent.browser');
27
const googArray = goog.require('goog.array');
28
const googObject = goog.require('goog.object');
29
const internal = goog.require('goog.string.internal');
30
const tags = goog.require('goog.dom.tags');
31
const trustedtypes = goog.require('goog.html.trustedtypes');
32
const utils = goog.require('goog.utils');
33
34
35
/**
36
* Token used to ensure that object is created only from this file. No code
37
* outside of this file can access this token.
38
* @type {!Object}
39
* @const
40
*/
41
const CONSTRUCTOR_TOKEN_PRIVATE = {};
42
43
/**
44
* A string that is safe to use in HTML context in DOM APIs and HTML documents.
45
*
46
* A SafeHtml is a string-like object that carries the security type contract
47
* that its value as a string will not cause untrusted script execution when
48
* evaluated as HTML in a browser.
49
*
50
* Values of this type are guaranteed to be safe to use in HTML contexts,
51
* such as, assignment to the innerHTML DOM property, or interpolation into
52
* a HTML template in HTML PC_DATA context, in the sense that the use will not
53
* result in a Cross-Site-Scripting vulnerability.
54
*
55
* Instances of this type must be created via the factory methods
56
* (`SafeHtml.create`, `SafeHtml.htmlEscape`),
57
* etc and not by invoking its constructor. The constructor intentionally takes
58
* an extra parameter that cannot be constructed outside of this file and the
59
* type is immutable; hence only a default instance corresponding to the empty
60
* string can be obtained via constructor invocation.
61
*
62
* Creating SafeHtml objects HAS SIDE-EFFECTS due to calling Trusted Types Web
63
* API.
64
*
65
* Note that there is no `SafeHtml.fromConstant`. The reason is that
66
* the following code would create an unsafe HTML:
67
*
68
* ```
69
* SafeHtml.concat(
70
* SafeHtml.fromConstant(Const.from('<script>')),
71
* SafeHtml.htmlEscape(userInput),
72
* SafeHtml.fromConstant(Const.from('<\/script>')));
73
* ```
74
*
75
* There's `goog.dom.constHtmlToNode` to create a node from constant strings
76
* only.
77
*
78
* @see SafeHtml.create
79
* @see SafeHtml.htmlEscape
80
* @final
81
* @struct
82
* @implements {TypedString}
83
*/
84
class SafeHtml {
85
/**
86
* @private
87
* @param {!TrustedHTML|string} value
88
* @param {!Object} token package-internal implementation detail.
89
*/
90
constructor(value, token) {
91
if (goog.DEBUG && token !== CONSTRUCTOR_TOKEN_PRIVATE) {
92
throw Error('SafeHtml is not meant to be built directly');
93
}
94
95
/**
96
* The contained value of this SafeHtml. The field has a purposely ugly
97
* name to make (non-compiled) code that attempts to directly access this
98
* field stand out.
99
* @const
100
* @private {!TrustedHTML|string}
101
*/
102
this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = value;
103
104
/**
105
* @override
106
* @const {boolean}
107
*/
108
this.implementsGoogStringTypedString = true;
109
}
110
111
112
/**
113
* Returns this SafeHtml's value as string.
114
*
115
* IMPORTANT: In code where it is security relevant that an object's type is
116
* indeed `SafeHtml`, use `SafeHtml.unwrap` instead of
117
* this method. If in doubt, assume that it's security relevant. In
118
* particular, note that goog.html functions which return a goog.html type do
119
* not guarantee that the returned instance is of the right type. For example:
120
*
121
* <pre>
122
* var fakeSafeHtml = new String('fake');
123
* fakeSafeHtml.__proto__ = SafeHtml.prototype;
124
* var newSafeHtml = SafeHtml.htmlEscape(fakeSafeHtml);
125
* // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
126
* // SafeHtml.htmlEscape() as fakeSafeHtml
127
* // instanceof SafeHtml.
128
* </pre>
129
*
130
* @return {string}
131
* @see SafeHtml.unwrap
132
* @override
133
*/
134
getTypedStringValue() {
135
return this.privateDoNotAccessOrElseSafeHtmlWrappedValue_.toString();
136
}
137
138
139
/**
140
* Returns a string-representation of this value.
141
*
142
* To obtain the actual string value wrapped in a SafeHtml, use
143
* `SafeHtml.unwrap`.
144
*
145
* @return {string}
146
* @see SafeHtml.unwrap
147
* @override
148
*/
149
toString() {
150
return this.privateDoNotAccessOrElseSafeHtmlWrappedValue_.toString();
151
}
152
153
/**
154
* Performs a runtime check that the provided object is indeed a SafeHtml
155
* object, and returns its value.
156
* @param {!SafeHtml} safeHtml The object to extract from.
157
* @return {string} The SafeHtml object's contained string, unless the
158
* run-time type check fails. In that case, `unwrap` returns an innocuous
159
* string, or, if assertions are enabled, throws
160
* `asserts.AssertionError`.
161
*/
162
static unwrap(safeHtml) {
163
return SafeHtml.unwrapTrustedHTML(safeHtml).toString();
164
}
165
166
167
/**
168
* Unwraps value as TrustedHTML if supported or as a string if not.
169
* @param {!SafeHtml} safeHtml
170
* @return {!TrustedHTML|string}
171
* @see SafeHtml.unwrap
172
*/
173
static unwrapTrustedHTML(safeHtml) {
174
// Perform additional run-time type-checking to ensure that safeHtml is
175
// indeed an instance of the expected type. This provides some additional
176
// protection against security bugs due to application code that disables
177
// type checks. Specifically, the following checks are performed:
178
// 1. The object is an instance of the expected type.
179
// 2. The object is not an instance of a subclass.
180
if (safeHtml instanceof SafeHtml && safeHtml.constructor === SafeHtml) {
181
return safeHtml.privateDoNotAccessOrElseSafeHtmlWrappedValue_;
182
} else {
183
asserts.fail(
184
`expected object of type SafeHtml, got '${safeHtml}' of type ` +
185
utils.typeOf(safeHtml));
186
return 'type_error:SafeHtml';
187
}
188
}
189
190
/**
191
* Returns HTML-escaped text as a SafeHtml object.
192
*
193
* @param {!SafeHtml.TextOrHtml_} textOrHtml The text to escape. If
194
* the parameter is of type SafeHtml it is returned directly (no escaping
195
* is done).
196
* @return {!SafeHtml} The escaped text, wrapped as a SafeHtml.
197
*/
198
static htmlEscape(textOrHtml) {
199
if (textOrHtml instanceof SafeHtml) {
200
return textOrHtml;
201
}
202
const textIsObject = typeof textOrHtml == 'object';
203
let textAsString;
204
if (textIsObject &&
205
/** @type {?} */ (textOrHtml).implementsGoogStringTypedString) {
206
textAsString =
207
/** @type {!TypedString} */ (textOrHtml).getTypedStringValue();
208
} else {
209
textAsString = String(textOrHtml);
210
}
211
return SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
212
internal.htmlEscape(textAsString));
213
}
214
215
216
/**
217
* Returns HTML-escaped text as a SafeHtml object, with newlines changed to
218
* &lt;br&gt;.
219
* @param {!SafeHtml.TextOrHtml_} textOrHtml The text to escape. If
220
* the parameter is of type SafeHtml it is returned directly (no escaping
221
* is done).
222
* @return {!SafeHtml} The escaped text, wrapped as a SafeHtml.
223
*/
224
static htmlEscapePreservingNewlines(textOrHtml) {
225
if (textOrHtml instanceof SafeHtml) {
226
return textOrHtml;
227
}
228
const html = SafeHtml.htmlEscape(textOrHtml);
229
return SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
230
internal.newLineToBr(SafeHtml.unwrap(html)));
231
}
232
233
234
/**
235
* Returns HTML-escaped text as a SafeHtml object, with newlines changed to
236
* &lt;br&gt; and escaping whitespace to preserve spatial formatting.
237
* Character entity #160 is used to make it safer for XML.
238
* @param {!SafeHtml.TextOrHtml_} textOrHtml The text to escape. If
239
* the parameter is of type SafeHtml it is returned directly (no escaping
240
* is done).
241
* @return {!SafeHtml} The escaped text, wrapped as a SafeHtml.
242
*/
243
static htmlEscapePreservingNewlinesAndSpaces(textOrHtml) {
244
if (textOrHtml instanceof SafeHtml) {
245
return textOrHtml;
246
}
247
const html = SafeHtml.htmlEscape(textOrHtml);
248
return SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
249
internal.whitespaceEscape(SafeHtml.unwrap(html)));
250
}
251
252
/**
253
* Converts an arbitrary string into an HTML comment by HTML-escaping the
254
* contents and embedding the result between HTML comment markers.
255
*
256
* Escaping is needed because Internet Explorer supports conditional comments
257
* and so may render HTML markup within comments.
258
*
259
* @param {string} text
260
* @return {!SafeHtml}
261
*/
262
static comment(text) {
263
return SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
264
'<!--' + internal.htmlEscape(text) + '-->');
265
}
266
267
/**
268
* Creates a SafeHtml content consisting of a tag with optional attributes and
269
* optional content.
270
*
271
* For convenience tag names and attribute names are accepted as regular
272
* strings, instead of Const. Nevertheless, you should not pass
273
* user-controlled values to these parameters. Note that these parameters are
274
* syntactically validated at runtime, and invalid values will result in
275
* an exception.
276
*
277
* Example usage:
278
*
279
* SafeHtml.create('br');
280
* SafeHtml.create('div', {'class': 'a'});
281
* SafeHtml.create('p', {}, 'a');
282
* SafeHtml.create('p', {}, SafeHtml.create('br'));
283
*
284
* SafeHtml.create('span', {
285
* 'style': {'margin': '0'}
286
* });
287
*
288
* To guarantee SafeHtml's type contract is upheld there are restrictions on
289
* attribute values and tag names.
290
*
291
* - For attributes which contain script code (on*), a Const is
292
* required.
293
* - For attributes which contain style (style), a SafeStyle or a
294
* SafeStyle.PropertyMap is required.
295
* - For attributes which are interpreted as URLs (e.g. src, href) a
296
* SafeUrl, Const or string is required. If a string
297
* is passed, it will be sanitized with SafeUrl.sanitize().
298
* - For tags which can load code or set security relevant page metadata,
299
* more specific SafeHtml.create*() functions must be used. Tags
300
* which are not supported by this function are applet, base, embed, iframe,
301
* link, math, meta, object, script, style, svg, and template.
302
*
303
* @param {!TagName|string} tagName The name of the tag. Only tag names
304
* consisting of [a-zA-Z0-9-] are allowed. Tag names documented above are
305
* disallowed.
306
* @param {?Object<string, ?SafeHtml.AttributeValue>=} attributes Mapping
307
* from attribute names to their values. Only attribute names consisting
308
* of [a-zA-Z0-9-] are allowed. Value of null or undefined causes the
309
* attribute to be omitted.
310
* @param {!SafeHtml.TextOrHtml_|
311
* !Array<!SafeHtml.TextOrHtml_>=} content Content to HTML-escape and put
312
* inside the tag. This must be empty for void tags like <br>. Array elements
313
* are concatenated.
314
* @return {!SafeHtml} The SafeHtml content with the tag.
315
* @throws {!Error} If invalid tag name, attribute name, or attribute value is
316
* provided.
317
* @throws {!asserts.AssertionError} If content for void tag is provided.
318
* @deprecated Use a recommended templating system like Lit instead.
319
* More information: go/goog.html-readme // LINE-INTERNAL
320
*/
321
static create(tagName, attributes = undefined, content = undefined) {
322
SafeHtml.verifyTagName(String(tagName));
323
return SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
324
String(tagName), attributes, content);
325
}
326
327
328
/**
329
* Verifies if the tag name is valid and if it doesn't change the context.
330
* E.g. STRONG is fine but SCRIPT throws because it changes context. See
331
* SafeHtml.create for an explanation of allowed tags.
332
* @param {string} tagName
333
* @return {void}
334
* @throws {!Error} If invalid tag name is provided.
335
* @package
336
*/
337
static verifyTagName(tagName) {
338
if (!VALID_NAMES_IN_TAG.test(tagName)) {
339
throw new Error(
340
SafeHtml.ENABLE_ERROR_MESSAGES ? `Invalid tag name <${tagName}>.` :
341
'');
342
}
343
if (tagName.toUpperCase() in NOT_ALLOWED_TAG_NAMES) {
344
throw new Error(
345
SafeHtml.ENABLE_ERROR_MESSAGES ?
346
347
`Tag name <${tagName}> is not allowed for SafeHtml.` :
348
'');
349
}
350
}
351
352
353
/**
354
* Creates a SafeHtml representing an iframe tag.
355
*
356
* This by default restricts the iframe as much as possible by setting the
357
* sandbox attribute to the empty string. If the iframe requires less
358
* restrictions, set the sandbox attribute as tight as possible, but do not
359
* rely on the sandbox as a security feature because it is not supported by
360
* older browsers. If a sandbox is essential to security (e.g. for third-party
361
* frames), use createSandboxIframe which checks for browser support.
362
*
363
* @see https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe#attr-sandbox
364
*
365
* @param {?TrustedResourceUrl=} src The value of the src
366
* attribute. If null or undefined src will not be set.
367
* @param {?SafeHtml=} srcdoc The value of the srcdoc attribute.
368
* If null or undefined srcdoc will not be set.
369
* @param {?Object<string, ?SafeHtml.AttributeValue>=} attributes Mapping
370
* from attribute names to their values. Only attribute names consisting
371
* of [a-zA-Z0-9-] are allowed. Value of null or undefined causes the
372
* attribute to be omitted.
373
* @param {!SafeHtml.TextOrHtml_|
374
* !Array<!SafeHtml.TextOrHtml_>=} content Content to HTML-escape and put
375
* inside the tag. Array elements are concatenated.
376
* @return {!SafeHtml} The SafeHtml content with the tag.
377
* @throws {!Error} If invalid tag name, attribute name, or attribute value is
378
* provided. If attributes
379
* contains the src or srcdoc attributes.
380
*/
381
static createIframe(
382
src = undefined, srcdoc = undefined, attributes = undefined,
383
content = undefined) {
384
if (src) {
385
// Check whether this is really TrustedResourceUrl.
386
TrustedResourceUrl.unwrap(src);
387
}
388
389
const fixedAttributes = {};
390
fixedAttributes['src'] = src || null;
391
fixedAttributes['srcdoc'] = srcdoc && SafeHtml.unwrap(srcdoc);
392
const defaultAttributes = {'sandbox': ''};
393
const combinedAttrs = SafeHtml.combineAttributes(
394
fixedAttributes, defaultAttributes, attributes);
395
return SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
396
'iframe', combinedAttrs, content);
397
}
398
399
400
/**
401
* Creates a SafeHtml representing a sandboxed iframe tag.
402
*
403
* The sandbox attribute is enforced in its most restrictive mode, an empty
404
* string. Consequently, the security requirements for the src and srcdoc
405
* attributes are relaxed compared to SafeHtml.createIframe. This function
406
* will throw on browsers that do not support the sandbox attribute, as
407
* determined by SafeHtml.canUseSandboxIframe.
408
*
409
* The SafeHtml returned by this function can trigger downloads with no
410
* user interaction on Chrome (though only a few, further attempts are
411
* blocked). Firefox and IE will block all downloads from the sandbox.
412
*
413
* @see https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe#attr-sandbox
414
* @see https://lists.w3.org/Archives/Public/public-whatwg-archive/2013Feb/0112.html
415
*
416
* @param {string|!SafeUrl=} src The value of the src
417
* attribute. If null or undefined src will not be set.
418
* @param {string=} srcdoc The value of the srcdoc attribute.
419
* If null or undefined srcdoc will not be set. Will not be sanitized.
420
* @param {!Object<string, ?SafeHtml.AttributeValue>=} attributes Mapping
421
* from attribute names to their values. Only attribute names consisting
422
* of [a-zA-Z0-9-] are allowed. Value of null or undefined causes the
423
* attribute to be omitted.
424
* @param {!SafeHtml.TextOrHtml_|
425
* !Array<!SafeHtml.TextOrHtml_>=} content Content to HTML-escape and put
426
* inside the tag. Array elements are concatenated.
427
* @return {!SafeHtml} The SafeHtml content with the tag.
428
* @throws {!Error} If invalid tag name, attribute name, or attribute value is
429
* provided. If attributes
430
* contains the src, srcdoc or sandbox attributes. If browser does not support
431
* the sandbox attribute on iframe.
432
*/
433
static createSandboxIframe(
434
src = undefined, srcdoc = undefined, attributes = undefined,
435
content = undefined) {
436
if (!SafeHtml.canUseSandboxIframe()) {
437
throw new Error(
438
SafeHtml.ENABLE_ERROR_MESSAGES ?
439
'The browser does not support sandboxed iframes.' :
440
'');
441
}
442
443
const fixedAttributes = {};
444
if (src) {
445
// Note that sanitize is a no-op on SafeUrl.
446
fixedAttributes['src'] = SafeUrl.unwrap(SafeUrl.sanitize(src));
447
} else {
448
fixedAttributes['src'] = null;
449
}
450
fixedAttributes['srcdoc'] = srcdoc || null;
451
fixedAttributes['sandbox'] = '';
452
const combinedAttrs =
453
SafeHtml.combineAttributes(fixedAttributes, {}, attributes);
454
return SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
455
'iframe', combinedAttrs, content);
456
}
457
458
459
/**
460
* Checks if the user agent supports sandboxed iframes.
461
* @return {boolean}
462
*/
463
static canUseSandboxIframe() {
464
return goog.global['HTMLIFrameElement'] &&
465
('sandbox' in goog.global['HTMLIFrameElement'].prototype);
466
}
467
468
469
/**
470
* Creates a SafeHtml representing a script tag with the src attribute.
471
* @param {!TrustedResourceUrl} src The value of the src
472
* attribute.
473
* @param {?Object<string, ?SafeHtml.AttributeValue>=}
474
* attributes
475
* Mapping from attribute names to their values. Only attribute names
476
* consisting of [a-zA-Z0-9-] are allowed. Value of null or undefined
477
* causes the attribute to be omitted.
478
* @return {!SafeHtml} The SafeHtml content with the tag.
479
* @throws {!Error} If invalid attribute name or value is provided. If
480
* attributes contains the
481
* src attribute.
482
*/
483
static createScriptSrc(src, attributes = undefined) {
484
// TODO(mlourenco): The charset attribute should probably be blocked. If
485
// its value is attacker controlled, the script contains attacker controlled
486
// sub-strings (even if properly escaped) and the server does not set
487
// charset then XSS is likely possible.
488
// https://html.spec.whatwg.org/multipage/scripting.html#dom-script-charset
489
490
// Check whether this is really TrustedResourceUrl.
491
TrustedResourceUrl.unwrap(src);
492
493
const fixedAttributes = {'src': src};
494
const defaultAttributes = {};
495
const combinedAttrs = SafeHtml.combineAttributes(
496
fixedAttributes, defaultAttributes, attributes);
497
return SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
498
'script', combinedAttrs);
499
}
500
501
/**
502
* Creates a SafeHtml representing a script tag. Does not allow the language,
503
* src, text or type attributes to be set.
504
* @param {!SafeScript|!Array<!SafeScript>}
505
* script Content to put inside the tag. Array elements are
506
* concatenated.
507
* @param {?Object<string, ?SafeHtml.AttributeValue>=} attributes Mapping
508
* from attribute names to their values. Only attribute names consisting
509
* of [a-zA-Z0-9-] are allowed. Value of null or undefined causes the
510
* attribute to be omitted.
511
* @return {!SafeHtml} The SafeHtml content with the tag.
512
* @throws {!Error} If invalid attribute name or attribute value is provided.
513
* If attributes contains the
514
* language, src or text attribute.
515
* @deprecated Use safevalues.scriptToHtml instead.
516
*/
517
static createScript(script, attributes = undefined) {
518
for (let attr in attributes) {
519
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty#Using_hasOwnProperty_as_a_property_name
520
if (Object.prototype.hasOwnProperty.call(attributes, attr)) {
521
const attrLower = attr.toLowerCase();
522
if (attrLower == 'language' || attrLower == 'src' ||
523
attrLower == 'text') {
524
throw new Error(
525
SafeHtml.ENABLE_ERROR_MESSAGES ?
526
`Cannot set "${attrLower}" attribute` :
527
'');
528
}
529
}
530
}
531
532
let content = '';
533
script = googArray.concat(script);
534
for (let i = 0; i < script.length; i++) {
535
content += SafeScript.unwrap(script[i]);
536
}
537
// Convert to SafeHtml so that it's not HTML-escaped. This is safe because
538
// as part of its contract, SafeScript should have no dangerous '<'.
539
const htmlContent =
540
SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(content);
541
return SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
542
'script', attributes, htmlContent);
543
}
544
545
546
/**
547
* Creates a SafeHtml representing a style tag. The type attribute is set
548
* to "text/css".
549
* @param {!SafeStyleSheet|!Array<!SafeStyleSheet>}
550
* styleSheet Content to put inside the tag. Array elements are
551
* concatenated.
552
* @param {?Object<string, ?SafeHtml.AttributeValue>=} attributes Mapping
553
* from attribute names to their values. Only attribute names consisting
554
* of [a-zA-Z0-9-] are allowed. Value of null or undefined causes the
555
* attribute to be omitted.
556
* @return {!SafeHtml} The SafeHtml content with the tag.
557
* @throws {!Error} If invalid attribute name or attribute value is provided.
558
* If attributes contains the
559
* type attribute.
560
*/
561
static createStyle(styleSheet, attributes = undefined) {
562
const fixedAttributes = {'type': 'text/css'};
563
const defaultAttributes = {};
564
const combinedAttrs = SafeHtml.combineAttributes(
565
fixedAttributes, defaultAttributes, attributes);
566
567
let content = '';
568
styleSheet = googArray.concat(styleSheet);
569
for (let i = 0; i < styleSheet.length; i++) {
570
content += SafeStyleSheet.unwrap(styleSheet[i]);
571
}
572
// Convert to SafeHtml so that it's not HTML-escaped. This is safe because
573
// as part of its contract, SafeStyleSheet should have no dangerous '<'.
574
const htmlContent =
575
SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(content);
576
return SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
577
'style', combinedAttrs, htmlContent);
578
}
579
580
581
/**
582
* Creates a SafeHtml representing a meta refresh tag.
583
* @param {!SafeUrl|string} url Where to redirect. If a string is
584
* passed, it will be sanitized with SafeUrl.sanitize().
585
* @param {number=} secs Number of seconds until the page should be
586
* reloaded. Will be set to 0 if unspecified.
587
* @return {!SafeHtml} The SafeHtml content with the tag.
588
*/
589
static createMetaRefresh(url, secs = undefined) {
590
// Note that sanitize is a no-op on SafeUrl.
591
let unwrappedUrl = SafeUrl.unwrap(SafeUrl.sanitize(url));
592
593
if (browser.isIE() || browser.isEdge()) {
594
// IE/EDGE can't parse the content attribute if the url contains a
595
// semicolon. We can fix this by adding quotes around the url, but then we
596
// can't parse quotes in the URL correctly. Also, it seems that IE/EDGE
597
// did not unescape semicolons in these URLs at some point in the past. We
598
// take a best-effort approach.
599
//
600
// If the URL has semicolons (which may happen in some cases, see
601
// http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.2
602
// for instance), wrap it in single quotes to protect the semicolons.
603
// If the URL has semicolons and single quotes, url-encode the single
604
// quotes as well.
605
//
606
// This is imperfect. Notice that both ' and ; are reserved characters in
607
// URIs, so this could do the wrong thing, but at least it will do the
608
// wrong thing in only rare cases.
609
if (internal.contains(unwrappedUrl, ';')) {
610
unwrappedUrl = '\'' + unwrappedUrl.replace(/'/g, '%27') + '\'';
611
}
612
}
613
const attributes = {
614
'http-equiv': 'refresh',
615
'content': (secs || 0) + '; url=' + unwrappedUrl,
616
};
617
618
// This function will handle the HTML escaping for attributes.
619
return SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
620
'meta', attributes);
621
}
622
623
/**
624
* Creates a new SafeHtml object by joining the parts with separator.
625
* @param {!SafeHtml.TextOrHtml_} separator
626
* @param {!Array<!SafeHtml.TextOrHtml_|
627
* !Array<!SafeHtml.TextOrHtml_>>} parts Parts to join. If a part
628
* contains an array then each member of this array is also joined with
629
* the separator.
630
* @return {!SafeHtml}
631
*/
632
static join(separator, parts) {
633
const separatorHtml = SafeHtml.htmlEscape(separator);
634
const content = [];
635
636
/**
637
* @param {!SafeHtml.TextOrHtml_|
638
* !Array<!SafeHtml.TextOrHtml_>} argument
639
*/
640
const addArgument = (argument) => {
641
if (Array.isArray(argument)) {
642
argument.forEach(addArgument);
643
} else {
644
const html = SafeHtml.htmlEscape(argument);
645
content.push(SafeHtml.unwrap(html));
646
}
647
};
648
649
parts.forEach(addArgument);
650
return SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
651
content.join(SafeHtml.unwrap(separatorHtml)));
652
}
653
654
655
/**
656
* Creates a new SafeHtml object by concatenating values.
657
* @param {...(!SafeHtml.TextOrHtml_|
658
* !Array<!SafeHtml.TextOrHtml_>)} var_args Values to concatenate.
659
* @return {!SafeHtml}
660
*/
661
static concat(var_args) {
662
return SafeHtml.join(SafeHtml.EMPTY, Array.prototype.slice.call(arguments));
663
}
664
665
/**
666
* Package-internal utility method to create SafeHtml instances.
667
*
668
* @param {string} html The string to initialize the SafeHtml object with.
669
* @return {!SafeHtml} The initialized SafeHtml object.
670
* @package
671
*/
672
static createSafeHtmlSecurityPrivateDoNotAccessOrElse(html) {
673
/** @noinline */
674
const noinlineHtml = html;
675
const policy = trustedtypes.getPolicyPrivateDoNotAccessOrElse();
676
const trustedHtml = policy ? policy.createHTML(noinlineHtml) : noinlineHtml;
677
return new SafeHtml(trustedHtml, CONSTRUCTOR_TOKEN_PRIVATE);
678
}
679
680
681
/**
682
* Like create() but does not restrict which tags can be constructed.
683
*
684
* @param {string} tagName Tag name. Set or validated by caller.
685
* @param {?Object<string, ?SafeHtml.AttributeValue>=} attributes
686
* @param {(!SafeHtml.TextOrHtml_|
687
* !Array<!SafeHtml.TextOrHtml_>)=} content
688
* @return {!SafeHtml}
689
* @throws {!Error} If invalid or unsafe attribute name or value is provided.
690
* @throws {!asserts.AssertionError} If content for void tag is provided.
691
* @package
692
*/
693
static createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
694
tagName, attributes = undefined, content = undefined) {
695
let result = `<${tagName}`;
696
result += SafeHtml.stringifyAttributes(tagName, attributes);
697
698
if (content == null) {
699
content = [];
700
} else if (!Array.isArray(content)) {
701
content = [content];
702
}
703
704
if (tags.isVoidTag(tagName.toLowerCase())) {
705
asserts.assert(
706
!content.length, `Void tag <${tagName}> does not allow content.`);
707
result += '>';
708
} else {
709
const html = SafeHtml.concat(content);
710
result += '>' + SafeHtml.unwrap(html) + '</' + tagName + '>';
711
}
712
713
return SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(result);
714
}
715
716
717
/**
718
* Creates a string with attributes to insert after tagName.
719
* @param {string} tagName
720
* @param {?Object<string, ?SafeHtml.AttributeValue>=} attributes
721
* @return {string} Returns an empty string if there are no attributes,
722
* returns a string starting with a space otherwise.
723
* @throws {!Error} If attribute value is unsafe for the given tag and
724
* attribute.
725
* @package
726
*/
727
static stringifyAttributes(tagName, attributes = undefined) {
728
let result = '';
729
if (attributes) {
730
for (let name in attributes) {
731
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty#Using_hasOwnProperty_as_a_property_name
732
if (Object.prototype.hasOwnProperty.call(attributes, name)) {
733
if (!VALID_NAMES_IN_TAG.test(name)) {
734
throw new Error(
735
SafeHtml.ENABLE_ERROR_MESSAGES ?
736
`Invalid attribute name "${name}".` :
737
'');
738
}
739
const value = attributes[name];
740
if (value == null) {
741
continue;
742
}
743
result += ' ' + getAttrNameAndValue(tagName, name, value);
744
}
745
}
746
}
747
return result;
748
}
749
750
751
/**
752
* @param {!Object<string, ?SafeHtml.AttributeValue>} fixedAttributes
753
* @param {!Object<string, string>} defaultAttributes
754
* @param {?Object<string, ?SafeHtml.AttributeValue>=} attributes Optional
755
* attributes passed to create*().
756
* @return {!Object<string, ?SafeHtml.AttributeValue>}
757
* @throws {!Error} If attributes contains an attribute with the same name as
758
* an attribute in fixedAttributes.
759
* @package
760
*/
761
static combineAttributes(
762
fixedAttributes, defaultAttributes, attributes = undefined) {
763
const combinedAttributes = {};
764
765
for (const name in fixedAttributes) {
766
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty#Using_hasOwnProperty_as_a_property_name
767
if (Object.prototype.hasOwnProperty.call(fixedAttributes, name)) {
768
asserts.assert(name.toLowerCase() == name, 'Must be lower case');
769
combinedAttributes[name] = fixedAttributes[name];
770
}
771
}
772
for (const name in defaultAttributes) {
773
if (Object.prototype.hasOwnProperty.call(defaultAttributes, name)) {
774
asserts.assert(name.toLowerCase() == name, 'Must be lower case');
775
combinedAttributes[name] = defaultAttributes[name];
776
}
777
}
778
779
if (attributes) {
780
for (const name in attributes) {
781
if (Object.prototype.hasOwnProperty.call(attributes, name)) {
782
const nameLower = name.toLowerCase();
783
if (nameLower in fixedAttributes) {
784
throw new Error(
785
SafeHtml.ENABLE_ERROR_MESSAGES ?
786
`Cannot override "${nameLower}" attribute, got "` + name +
787
'" with value "' + attributes[name] + '"' :
788
'');
789
}
790
if (nameLower in defaultAttributes) {
791
delete combinedAttributes[nameLower];
792
}
793
combinedAttributes[name] = attributes[name];
794
}
795
}
796
}
797
798
return combinedAttributes;
799
}
800
}
801
802
803
/**
804
* @define {boolean} Whether to strip out error messages or to leave them in.
805
*/
806
SafeHtml.ENABLE_ERROR_MESSAGES =
807
goog.define('goog.html.SafeHtml.ENABLE_ERROR_MESSAGES', goog.DEBUG);
808
809
810
/**
811
* Whether the `style` attribute is supported. Set to false to avoid the byte
812
* weight of `SafeStyle` where unneeded. An error will be thrown if
813
* the `style` attribute is used.
814
* @define {boolean}
815
*/
816
SafeHtml.SUPPORT_STYLE_ATTRIBUTE =
817
goog.define('goog.html.SafeHtml.SUPPORT_STYLE_ATTRIBUTE', true);
818
819
820
/**
821
* Shorthand for union of types that can sensibly be converted to strings
822
* or might already be SafeHtml (as SafeHtml is a TypedString).
823
* @private
824
* @typedef {string|number|boolean|!TypedString}
825
*/
826
SafeHtml.TextOrHtml_;
827
828
829
/**
830
* Coerces an arbitrary object into a SafeHtml object.
831
*
832
* If `textOrHtml` is already of type `SafeHtml`, the same
833
* object is returned. Otherwise, `textOrHtml` is coerced to string, and
834
* HTML-escaped.
835
*
836
* @param {!SafeHtml.TextOrHtml_} textOrHtml The text or SafeHtml to
837
* coerce.
838
* @return {!SafeHtml} The resulting SafeHtml object.
839
* @deprecated Use SafeHtml.htmlEscape.
840
*/
841
SafeHtml.from = SafeHtml.htmlEscape;
842
843
844
/**
845
* @const
846
*/
847
const VALID_NAMES_IN_TAG = /^[a-zA-Z0-9-]+$/;
848
849
850
/**
851
* Set of attributes containing URL as defined at
852
* http://www.w3.org/TR/html5/index.html#attributes-1.
853
* @const {!Object<string,boolean>}
854
*/
855
const URL_ATTRIBUTES = googObject.createSet(
856
'action', 'cite', 'data', 'formaction', 'href', 'manifest', 'poster',
857
'src');
858
859
860
/**
861
* Tags which are unsupported via create(). They might be supported via a
862
* tag-specific create method. These are tags which might require a
863
* TrustedResourceUrl in one of their attributes or a restricted type for
864
* their content.
865
* @const {!Object<string,boolean>}
866
*/
867
const NOT_ALLOWED_TAG_NAMES = googObject.createSet(
868
TagName.APPLET, TagName.BASE, TagName.EMBED, TagName.IFRAME, TagName.LINK,
869
TagName.MATH, TagName.META, TagName.OBJECT, TagName.SCRIPT, TagName.STYLE,
870
TagName.SVG, TagName.TEMPLATE);
871
872
873
/**
874
* @typedef {string|number|!TypedString|
875
* !SafeStyle.PropertyMap|undefined|null}
876
*/
877
SafeHtml.AttributeValue;
878
879
880
/**
881
* @param {string} tagName The tag name.
882
* @param {string} name The attribute name.
883
* @param {!SafeHtml.AttributeValue} value The attribute value.
884
* @return {string} A "name=value" string.
885
* @throws {!Error} If attribute value is unsafe for the given tag and
886
* attribute.
887
* @private
888
*/
889
function getAttrNameAndValue(tagName, name, value) {
890
// If it's goog.string.Const, allow any valid attribute name.
891
if (value instanceof Const) {
892
value = Const.unwrap(value);
893
} else if (name.toLowerCase() == 'style') {
894
if (SafeHtml.SUPPORT_STYLE_ATTRIBUTE) {
895
value = getStyleValue(value);
896
} else {
897
throw new Error(
898
SafeHtml.ENABLE_ERROR_MESSAGES ? 'Attribute "style" not supported.' :
899
'');
900
}
901
} else if (/^on/i.test(name)) {
902
// TODO(jakubvrana): Disallow more attributes with a special meaning.
903
throw new Error(
904
SafeHtml.ENABLE_ERROR_MESSAGES ? `Attribute "${name}` +
905
'" requires goog.string.Const value, "' + value + '" given.' :
906
'');
907
// URL attributes handled differently according to tag.
908
} else if (name.toLowerCase() in URL_ATTRIBUTES) {
909
if (value instanceof TrustedResourceUrl) {
910
value = TrustedResourceUrl.unwrap(value);
911
} else if (value instanceof SafeUrl) {
912
value = SafeUrl.unwrap(value);
913
} else if (typeof value === 'string') {
914
value = SafeUrl.sanitize(value).getTypedStringValue();
915
} else {
916
throw new Error(
917
SafeHtml.ENABLE_ERROR_MESSAGES ?
918
`Attribute "${name}" on tag "${tagName}` +
919
'" requires goog.html.SafeUrl, goog.string.Const, or' +
920
' string, value "' + value + '" given.' :
921
'');
922
}
923
}
924
925
// Accept SafeUrl, TrustedResourceUrl, etc. for attributes which only require
926
// HTML-escaping.
927
if (/** @type {?} */ (value).implementsGoogStringTypedString) {
928
// Ok to call getTypedStringValue() since there's no reliance on the type
929
// contract for security here.
930
value =
931
/** @type {!TypedString} */ (value).getTypedStringValue();
932
}
933
934
asserts.assert(
935
typeof value === 'string' || typeof value === 'number',
936
'String or number value expected, got ' + (typeof value) +
937
' with value: ' + value);
938
return `${name}="` + internal.htmlEscape(String(value)) + '"';
939
}
940
941
942
/**
943
* Gets value allowed in "style" attribute.
944
* @param {!SafeHtml.AttributeValue} value It could be SafeStyle or a
945
* map which will be passed to SafeStyle.create.
946
* @return {string} Unwrapped value.
947
* @throws {!Error} If string value is given.
948
* @private
949
*/
950
function getStyleValue(value) {
951
if (!utils.isObject(value)) {
952
throw new Error(
953
SafeHtml.ENABLE_ERROR_MESSAGES ?
954
'The "style" attribute requires goog.html.SafeStyle or map ' +
955
'of style properties, ' + (typeof value) + ' given: ' + value :
956
'');
957
}
958
if (!(value instanceof SafeStyle)) {
959
// Process the property bag into a style object.
960
value = SafeStyle.create(/** @type {!SafeStyle.PropertyMap} */ (value));
961
}
962
return SafeStyle.unwrap(value);
963
}
964
965
966
/**
967
* A SafeHtml instance corresponding to the HTML doctype: "<!DOCTYPE html>".
968
* @const {!SafeHtml}
969
*/
970
SafeHtml.DOCTYPE_HTML = /** @type {!SafeHtml} */ ({
971
// NOTE: this compiles to nothing, but hides the possible side effect of
972
// SafeHtml creation (due to calling trustedTypes.createPolicy) from the
973
// compiler so that the entire call can be removed if the result is not used.
974
valueOf: function() {
975
return SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
976
'<!DOCTYPE html>');
977
},
978
}.valueOf());
979
980
/**
981
* A SafeHtml instance corresponding to the empty string.
982
* @const {!SafeHtml}
983
*/
984
SafeHtml.EMPTY = new SafeHtml(
985
(goog.global.trustedTypes && goog.global.trustedTypes.emptyHTML) || '',
986
CONSTRUCTOR_TOKEN_PRIVATE);
987
988
/**
989
* A SafeHtml instance corresponding to the <br> tag.
990
* @const {!SafeHtml}
991
*/
992
SafeHtml.BR = /** @type {!SafeHtml} */ ({
993
// NOTE: this compiles to nothing, but hides the possible side effect of
994
// SafeHtml creation (due to calling trustedTypes.createPolicy) from the
995
// compiler so that the entire call can be removed if the result is not used.
996
valueOf: function() {
997
return SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse('<br>');
998
},
999
}.valueOf());
1000
1001
1002
exports = SafeHtml;
1003
1004