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