Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
seleniumhq
GitHub Repository: seleniumhq/selenium
Path: blob/trunk/third_party/closure/goog/html/trustedresourceurl.js
4500 views
1
/**
2
* @license
3
* Copyright The Closure Library Authors.
4
* SPDX-License-Identifier: Apache-2.0
5
*/
6
7
/**
8
* @fileoverview The TrustedResourceUrl type and its builders.
9
*
10
* TODO(xtof): Link to document stating type contract.
11
*/
12
13
goog.provide('goog.html.TrustedResourceUrl');
14
15
goog.require('goog.asserts');
16
goog.require('goog.fs.blob');
17
goog.require('goog.fs.url');
18
goog.require('goog.html.SafeScript');
19
goog.require('goog.html.trustedtypes');
20
goog.require('goog.string.Const');
21
goog.require('goog.string.TypedString');
22
goog.require('goog.utils');
23
24
25
26
/**
27
* A URL which is under application control and from which script, CSS, and
28
* other resources that represent executable code, can be fetched.
29
*
30
* Given that the URL can only be constructed from strings under application
31
* control and is used to load resources, bugs resulting in a malformed URL
32
* should not have a security impact and are likely to be easily detectable
33
* during testing. Given the wide number of non-RFC compliant URLs in use,
34
* stricter validation could prevent some applications from being able to use
35
* this type.
36
*
37
* Instances of this type must be created via the factory method,
38
* (`fromConstant`, `fromConstants`, `format` or `formatWithParams`), and not by
39
* invoking its constructor. The constructor intentionally takes an extra
40
* parameter that cannot be constructed outside of this file and the type is
41
* immutable; hence only a default instance corresponding to the empty string
42
* can be obtained via constructor invocation.
43
*
44
* Creating TrustedResourceUrl objects HAS SIDE-EFFECTS due to calling
45
* Trusted Types Web API.
46
*
47
* @see goog.html.TrustedResourceUrl#fromConstant
48
* @final
49
* @struct
50
* @implements {goog.string.TypedString}
51
*/
52
goog.html.TrustedResourceUrl = class {
53
/**
54
* @private
55
* @param {!TrustedScriptURL|string} value
56
* @param {!Object} token package-internal implementation detail.
57
*/
58
constructor(value, token) {
59
if (goog.DEBUG &&
60
token !== goog.html.TrustedResourceUrl.CONSTRUCTOR_TOKEN_PRIVATE_) {
61
throw Error('TrustedResourceUrl is not meant to be built directly');
62
}
63
64
/**
65
* The contained value of this TrustedResourceUrl. The field has a
66
* purposely ugly name to make (non-compiled) code that attempts to directly
67
* access this field stand out.
68
* @const
69
* @private {!TrustedScriptURL|string}
70
*/
71
this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ = value;
72
}
73
74
/**
75
* Returns a string-representation of this value.
76
*
77
* To obtain the actual string value wrapped in a TrustedResourceUrl, use
78
* `goog.html.TrustedResourceUrl.unwrap`.
79
*
80
* @return {string}
81
* @see goog.html.TrustedResourceUrl#unwrap
82
* @override
83
*/
84
toString() {
85
return this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ + '';
86
}
87
};
88
89
90
/**
91
* @override
92
* @const
93
*/
94
goog.html.TrustedResourceUrl.prototype.implementsGoogStringTypedString = true;
95
96
97
/**
98
* Returns this TrustedResourceUrl's value as a string.
99
*
100
* IMPORTANT: In code where it is security relevant that an object's type is
101
* indeed `TrustedResourceUrl`, use
102
* `goog.html.TrustedResourceUrl.unwrap` instead of this method. If in
103
* doubt, assume that it's security relevant. In particular, note that
104
* goog.html functions which return a goog.html type do not guarantee that
105
* the returned instance is of the right type. For example:
106
*
107
* <pre>
108
* var fakeSafeHtml = new String('fake');
109
* fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
110
* var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
111
* // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
112
* // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml instanceof
113
* // goog.html.SafeHtml.
114
* </pre>
115
*
116
* @see goog.html.TrustedResourceUrl#unwrap
117
* @override
118
*/
119
goog.html.TrustedResourceUrl.prototype.getTypedStringValue = function() {
120
'use strict';
121
return this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_
122
.toString();
123
};
124
125
126
/**
127
* Creates a new TrustedResourceUrl with params added to URL. Both search and
128
* hash params can be specified.
129
*
130
* @param {string|?Object<string, *>|undefined} searchParams Search parameters
131
* to add to URL. See goog.html.TrustedResourceUrl.stringifyParams_ for
132
* exact format definition.
133
* @param {(string|?Object<string, *>)=} opt_hashParams Hash parameters to add
134
* to URL. See goog.html.TrustedResourceUrl.stringifyParams_ for exact
135
* format definition.
136
* @return {!goog.html.TrustedResourceUrl} New TrustedResourceUrl with params.
137
*/
138
goog.html.TrustedResourceUrl.prototype.cloneWithParams = function(
139
searchParams, opt_hashParams) {
140
'use strict';
141
var url = goog.html.TrustedResourceUrl.unwrap(this);
142
var parts = goog.html.TrustedResourceUrl.URL_PARAM_PARSER_.exec(url);
143
var urlBase = parts[1];
144
var urlSearch = parts[2] || '';
145
var urlHash = parts[3] || '';
146
147
return goog.html.TrustedResourceUrl
148
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(
149
urlBase +
150
goog.html.TrustedResourceUrl.stringifyParams_(
151
'?', urlSearch, searchParams) +
152
goog.html.TrustedResourceUrl.stringifyParams_(
153
'#', urlHash, opt_hashParams));
154
};
155
156
/**
157
* Performs a runtime check that the provided object is indeed a
158
* TrustedResourceUrl object, and returns its value.
159
*
160
* @param {!goog.html.TrustedResourceUrl} trustedResourceUrl The object to
161
* extract from.
162
* @return {string} The trustedResourceUrl object's contained string, unless
163
* the run-time type check fails. In that case, `unwrap` returns an
164
* innocuous string, or, if assertions are enabled, throws
165
* `goog.asserts.AssertionError`.
166
*/
167
goog.html.TrustedResourceUrl.unwrap = function(trustedResourceUrl) {
168
'use strict';
169
return goog.html.TrustedResourceUrl.unwrapTrustedScriptURL(trustedResourceUrl)
170
.toString();
171
};
172
173
174
/**
175
* Unwraps value as TrustedScriptURL if supported or as a string if not.
176
* @param {!goog.html.TrustedResourceUrl} trustedResourceUrl
177
* @return {!TrustedScriptURL|string}
178
* @see goog.html.TrustedResourceUrl.unwrap
179
*/
180
goog.html.TrustedResourceUrl.unwrapTrustedScriptURL = function(
181
trustedResourceUrl) {
182
'use strict';
183
// Perform additional Run-time type-checking to ensure that
184
// trustedResourceUrl is indeed an instance of the expected type. This
185
// provides some additional protection against security bugs due to
186
// application code that disables type checks.
187
// Specifically, the following checks are performed:
188
// 1. The object is an instance of the expected type.
189
// 2. The object is not an instance of a subclass.
190
if (trustedResourceUrl instanceof goog.html.TrustedResourceUrl &&
191
trustedResourceUrl.constructor === goog.html.TrustedResourceUrl) {
192
return trustedResourceUrl
193
.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_;
194
} else {
195
goog.asserts.fail(
196
'expected object of type TrustedResourceUrl, got \'' +
197
trustedResourceUrl + '\' of type ' + goog.utils.typeOf(trustedResourceUrl));
198
return 'type_error:TrustedResourceUrl';
199
}
200
};
201
202
203
/**
204
* Creates a TrustedResourceUrl from a format string and arguments.
205
*
206
* The arguments for interpolation into the format string map labels to values.
207
* Values of type `goog.string.Const` are interpolated without modifcation.
208
* Values of other types are cast to string and encoded with
209
* encodeURIComponent.
210
*
211
* `%{<label>}` markers are used in the format string to indicate locations
212
* to be interpolated with the valued mapped to the given label. `<label>`
213
* must contain only alphanumeric and `_` characters.
214
*
215
* The format string must match goog.html.TrustedResourceUrl.BASE_URL_.
216
*
217
* Example usage:
218
*
219
* var url = goog.html.TrustedResourceUrl.format(goog.string.Const.from(
220
* 'https://www.google.com/search?q=%{query}'), {'query': searchTerm});
221
*
222
* var url = goog.html.TrustedResourceUrl.format(goog.string.Const.from(
223
* '//www.youtube.com/v/%{videoId}?hl=en&fs=1%{autoplay}'), {
224
* 'videoId': videoId,
225
* 'autoplay': opt_autoplay ?
226
* goog.string.Const.from('&autoplay=1') : goog.string.Const.EMPTY
227
* });
228
*
229
* While this function can be used to create a TrustedResourceUrl from only
230
* constants, fromConstant() and fromConstants() are generally preferable for
231
* that purpose.
232
*
233
* @param {!goog.string.Const} format The format string.
234
* @param {!Object<string, (string|number|!goog.string.Const)>} args Mapping
235
* of labels to values to be interpolated into the format string.
236
* goog.string.Const values are interpolated without encoding.
237
* @return {!goog.html.TrustedResourceUrl}
238
* @throws {!Error} On an invalid format string or if a label used in the
239
* the format string is not present in args.
240
*/
241
goog.html.TrustedResourceUrl.format = function(format, args) {
242
'use strict';
243
var formatStr = goog.string.Const.unwrap(format);
244
if (!goog.html.TrustedResourceUrl.BASE_URL_.test(formatStr)) {
245
throw new Error('Invalid TrustedResourceUrl format: ' + formatStr);
246
}
247
var result = formatStr.replace(
248
goog.html.TrustedResourceUrl.FORMAT_MARKER_, function(match, id) {
249
'use strict';
250
if (!Object.prototype.hasOwnProperty.call(args, id)) {
251
throw new Error(
252
'Found marker, "' + id + '", in format string, "' + formatStr +
253
'", but no valid label mapping found ' +
254
'in args: ' + JSON.stringify(args));
255
}
256
var arg = args[id];
257
if (arg instanceof goog.string.Const) {
258
return goog.string.Const.unwrap(arg);
259
} else {
260
return encodeURIComponent(String(arg));
261
}
262
});
263
return goog.html.TrustedResourceUrl
264
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(result);
265
};
266
267
268
/**
269
* @private @const {!RegExp}
270
*/
271
goog.html.TrustedResourceUrl.FORMAT_MARKER_ = /%{(\w+)}/g;
272
273
274
/**
275
* The URL must be absolute, scheme-relative or path-absolute. So it must
276
* start with:
277
* - https:// followed by allowed origin characters.
278
* - // followed by allowed origin characters.
279
* - Any absolute or relative path.
280
*
281
* Based on
282
* https://url.spec.whatwg.org/commit-snapshots/56b74ce7cca8883eab62e9a12666e2fac665d03d/#url-parsing
283
* an initial / which is not followed by another / or \ will end up in the "path
284
* state" and from there it can only go to "fragment state" and "query state".
285
*
286
* We don't enforce a well-formed domain name. So '.' or '1.2' are valid.
287
* That's ok because the origin comes from a compile-time constant.
288
*
289
* A regular expression is used instead of goog.uri for several reasons:
290
* - Strictness. E.g. we don't want any userinfo component and we don't
291
* want '/./, nor \' in the first path component.
292
* - Small trusted base. goog.uri is generic and might need to change,
293
* reasoning about all the ways it can parse a URL now and in the future
294
* is error-prone.
295
* - Code size. We expect many calls to .format(), many of which might
296
* not be using goog.uri.
297
* - Simplicity. Using goog.uri would likely not result in simpler nor shorter
298
* code.
299
* @private @const {!RegExp}
300
*/
301
goog.html.TrustedResourceUrl.BASE_URL_ = new RegExp(
302
'^((https:)?//[0-9a-z.:[\\]-]+/' // Origin.
303
+ '|/[^/\\\\]' // Absolute path.
304
+ '|[^:/\\\\%]+/' // Relative path.
305
+ '|[^:/\\\\%]*[?#]' // Query string or fragment.
306
+ '|about:blank#' // about:blank with fragment.
307
+ ')',
308
'i');
309
310
/**
311
* RegExp for splitting a URL into the base, search field, and hash field.
312
*
313
* @private @const {!RegExp}
314
*/
315
goog.html.TrustedResourceUrl.URL_PARAM_PARSER_ =
316
/^([^?#]*)(\?[^#]*)?(#[\s\S]*)?/;
317
318
319
/**
320
* Formats the URL same as TrustedResourceUrl.format and then adds extra URL
321
* parameters.
322
*
323
* Example usage:
324
*
325
* // Creates '//www.youtube.com/v/abc?autoplay=1' for videoId='abc' and
326
* // opt_autoplay=1. Creates '//www.youtube.com/v/abc' for videoId='abc'
327
* // and opt_autoplay=undefined.
328
* var url = goog.html.TrustedResourceUrl.formatWithParams(
329
* goog.string.Const.from('//www.youtube.com/v/%{videoId}'),
330
* {'videoId': videoId},
331
* {'autoplay': opt_autoplay});
332
*
333
* @param {!goog.string.Const} format The format string.
334
* @param {!Object<string, (string|number|!goog.string.Const)>} args Mapping
335
* of labels to values to be interpolated into the format string.
336
* goog.string.Const values are interpolated without encoding.
337
* @param {string|?Object<string, *>|undefined} searchParams Parameters to add
338
* to URL. See goog.html.TrustedResourceUrl.stringifyParams_ for exact
339
* format definition.
340
* @param {(string|?Object<string, *>)=} opt_hashParams Hash parameters to add
341
* to URL. See goog.html.TrustedResourceUrl.stringifyParams_ for exact
342
* format definition.
343
* @return {!goog.html.TrustedResourceUrl}
344
* @throws {!Error} On an invalid format string or if a label used in the
345
* the format string is not present in args.
346
*/
347
goog.html.TrustedResourceUrl.formatWithParams = function(
348
format, args, searchParams, opt_hashParams) {
349
'use strict';
350
var url = goog.html.TrustedResourceUrl.format(format, args);
351
return url.cloneWithParams(searchParams, opt_hashParams);
352
};
353
354
355
/**
356
* Creates a TrustedResourceUrl object from a compile-time constant string.
357
*
358
* Compile-time constant strings are inherently program-controlled and hence
359
* trusted.
360
*
361
* @param {!goog.string.Const} url A compile-time-constant string from which to
362
* create a TrustedResourceUrl.
363
* @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object
364
* initialized to `url`.
365
*/
366
goog.html.TrustedResourceUrl.fromConstant = function(url) {
367
'use strict';
368
return goog.html.TrustedResourceUrl
369
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(
370
goog.string.Const.unwrap(url));
371
};
372
373
374
/**
375
* Creates a TrustedResourceUrl object from a compile-time constant strings.
376
*
377
* Compile-time constant strings are inherently program-controlled and hence
378
* trusted.
379
*
380
* @param {!Array<!goog.string.Const>} parts Compile-time-constant strings from
381
* which to create a TrustedResourceUrl.
382
* @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object
383
* initialized to concatenation of `parts`.
384
*/
385
goog.html.TrustedResourceUrl.fromConstants = function(parts) {
386
'use strict';
387
var unwrapped = '';
388
for (var i = 0; i < parts.length; i++) {
389
unwrapped += goog.string.Const.unwrap(parts[i]);
390
}
391
return goog.html.TrustedResourceUrl
392
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(unwrapped);
393
};
394
395
/**
396
* Creates a TrustedResourceUrl object by generating a Blob from a SafeScript
397
* object and then calling createObjectURL with that blob.
398
*
399
* SafeScript objects are trusted to contain executable JavaScript code.
400
*
401
* Caller must call goog.fs.url.revokeObjectUrl() on the unwrapped url to
402
* release the underlying blob.
403
*
404
* Throws if browser doesn't support blob construction.
405
*
406
* @param {!goog.html.SafeScript} safeScript A script from which to create a
407
* TrustedResourceUrl.
408
* @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object
409
* initialized to a new blob URL.
410
*/
411
goog.html.TrustedResourceUrl.fromSafeScript = function(safeScript) {
412
'use strict';
413
var blob = goog.fs.blob.getBlobWithProperties(
414
[goog.html.SafeScript.unwrap(safeScript)], 'text/javascript');
415
var url = goog.fs.url.createObjectUrl(blob);
416
return goog.html.TrustedResourceUrl
417
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(url);
418
};
419
420
421
/**
422
* Token used to ensure that object is created only from this file. No code
423
* outside of this file can access this token.
424
* @private {!Object}
425
* @const
426
*/
427
goog.html.TrustedResourceUrl.CONSTRUCTOR_TOKEN_PRIVATE_ = {};
428
429
430
/**
431
* Package-internal utility method to create TrustedResourceUrl instances.
432
*
433
* @param {string} url The string to initialize the TrustedResourceUrl object
434
* with.
435
* @return {!goog.html.TrustedResourceUrl} The initialized TrustedResourceUrl
436
* object.
437
* @package
438
*/
439
goog.html.TrustedResourceUrl
440
.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse = function(url) {
441
'use strict';
442
/** @noinline */
443
const noinlineUrl = url;
444
const policy = goog.html.trustedtypes.getPolicyPrivateDoNotAccessOrElse();
445
const value = policy ? policy.createScriptURL(noinlineUrl) : noinlineUrl;
446
return new goog.html.TrustedResourceUrl(
447
value, goog.html.TrustedResourceUrl.CONSTRUCTOR_TOKEN_PRIVATE_);
448
};
449
450
451
/**
452
* Stringifies the passed params to be used as either a search or hash field of
453
* a URL.
454
*
455
* @param {string} prefix The prefix character for the given field ('?' or '#').
456
* @param {string} currentString The existing field value (including the prefix
457
* character, if the field is present).
458
* @param {string|?Object<string, *>|undefined} params The params to set or
459
* append to the field.
460
* - If `undefined` or `null`, the field remains unchanged.
461
* - If a string, then the string will be escaped and the field will be
462
* overwritten with that value.
463
* - If an Object, that object is treated as a set of key-value pairs to be
464
* appended to the current field. Note that JavaScript doesn't guarantee the
465
* order of values in an object which might result in non-deterministic order
466
* of the parameters. However, browsers currently preserve the order. The
467
* rules for each entry:
468
* - If an array, it will be processed as if each entry were an additional
469
* parameter with exactly the same key, following the same logic below.
470
* - If `undefined` or `null`, it will be skipped.
471
* - Otherwise, it will be turned into a string, escaped, and appended.
472
* @return {string}
473
* @private
474
*/
475
goog.html.TrustedResourceUrl.stringifyParams_ = function(
476
prefix, currentString, params) {
477
'use strict';
478
if (params == null) {
479
// Do not modify the field.
480
return currentString;
481
}
482
if (typeof params === 'string') {
483
// Set field to the passed string.
484
return params ? prefix + encodeURIComponent(params) : '';
485
}
486
// Add on parameters to field from key-value object.
487
for (var key in params) {
488
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty#Using_hasOwnProperty_as_a_property_name
489
if (Object.prototype.hasOwnProperty.call(params, key)) {
490
var value = params[key];
491
var outputValues = Array.isArray(value) ? value : [value];
492
for (var i = 0; i < outputValues.length; i++) {
493
var outputValue = outputValues[i];
494
if (outputValue != null) {
495
if (!currentString) {
496
currentString = prefix;
497
}
498
currentString += (currentString.length > prefix.length ? '&' : '') +
499
encodeURIComponent(key) + '=' +
500
encodeURIComponent(String(outputValue));
501
}
502
}
503
}
504
}
505
return currentString;
506
};
507
508