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