Path: blob/trunk/third_party/closure/goog/html/trustedresourceurl.js
4500 views
/**1* @license2* Copyright The Closure Library Authors.3* SPDX-License-Identifier: Apache-2.04*/56/**7* @fileoverview The TrustedResourceUrl type and its builders.8*9* TODO(xtof): Link to document stating type contract.10*/1112goog.provide('goog.html.TrustedResourceUrl');1314goog.require('goog.asserts');15goog.require('goog.fs.blob');16goog.require('goog.fs.url');17goog.require('goog.html.SafeScript');18goog.require('goog.html.trustedtypes');19goog.require('goog.string.Const');20goog.require('goog.string.TypedString');21goog.require('goog.utils');22232425/**26* A URL which is under application control and from which script, CSS, and27* other resources that represent executable code, can be fetched.28*29* Given that the URL can only be constructed from strings under application30* control and is used to load resources, bugs resulting in a malformed URL31* should not have a security impact and are likely to be easily detectable32* during testing. Given the wide number of non-RFC compliant URLs in use,33* stricter validation could prevent some applications from being able to use34* this type.35*36* Instances of this type must be created via the factory method,37* (`fromConstant`, `fromConstants`, `format` or `formatWithParams`), and not by38* invoking its constructor. The constructor intentionally takes an extra39* parameter that cannot be constructed outside of this file and the type is40* immutable; hence only a default instance corresponding to the empty string41* can be obtained via constructor invocation.42*43* Creating TrustedResourceUrl objects HAS SIDE-EFFECTS due to calling44* Trusted Types Web API.45*46* @see goog.html.TrustedResourceUrl#fromConstant47* @final48* @struct49* @implements {goog.string.TypedString}50*/51goog.html.TrustedResourceUrl = class {52/**53* @private54* @param {!TrustedScriptURL|string} value55* @param {!Object} token package-internal implementation detail.56*/57constructor(value, token) {58if (goog.DEBUG &&59token !== goog.html.TrustedResourceUrl.CONSTRUCTOR_TOKEN_PRIVATE_) {60throw Error('TrustedResourceUrl is not meant to be built directly');61}6263/**64* The contained value of this TrustedResourceUrl. The field has a65* purposely ugly name to make (non-compiled) code that attempts to directly66* access this field stand out.67* @const68* @private {!TrustedScriptURL|string}69*/70this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ = value;71}7273/**74* Returns a string-representation of this value.75*76* To obtain the actual string value wrapped in a TrustedResourceUrl, use77* `goog.html.TrustedResourceUrl.unwrap`.78*79* @return {string}80* @see goog.html.TrustedResourceUrl#unwrap81* @override82*/83toString() {84return this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ + '';85}86};878889/**90* @override91* @const92*/93goog.html.TrustedResourceUrl.prototype.implementsGoogStringTypedString = true;949596/**97* Returns this TrustedResourceUrl's value as a string.98*99* IMPORTANT: In code where it is security relevant that an object's type is100* indeed `TrustedResourceUrl`, use101* `goog.html.TrustedResourceUrl.unwrap` instead of this method. If in102* doubt, assume that it's security relevant. In particular, note that103* goog.html functions which return a goog.html type do not guarantee that104* the returned instance is of the right type. For example:105*106* <pre>107* var fakeSafeHtml = new String('fake');108* fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;109* var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);110* // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by111* // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml instanceof112* // goog.html.SafeHtml.113* </pre>114*115* @see goog.html.TrustedResourceUrl#unwrap116* @override117*/118goog.html.TrustedResourceUrl.prototype.getTypedStringValue = function() {119'use strict';120return this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_121.toString();122};123124125/**126* Creates a new TrustedResourceUrl with params added to URL. Both search and127* hash params can be specified.128*129* @param {string|?Object<string, *>|undefined} searchParams Search parameters130* to add to URL. See goog.html.TrustedResourceUrl.stringifyParams_ for131* exact format definition.132* @param {(string|?Object<string, *>)=} opt_hashParams Hash parameters to add133* to URL. See goog.html.TrustedResourceUrl.stringifyParams_ for exact134* format definition.135* @return {!goog.html.TrustedResourceUrl} New TrustedResourceUrl with params.136*/137goog.html.TrustedResourceUrl.prototype.cloneWithParams = function(138searchParams, opt_hashParams) {139'use strict';140var url = goog.html.TrustedResourceUrl.unwrap(this);141var parts = goog.html.TrustedResourceUrl.URL_PARAM_PARSER_.exec(url);142var urlBase = parts[1];143var urlSearch = parts[2] || '';144var urlHash = parts[3] || '';145146return goog.html.TrustedResourceUrl147.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(148urlBase +149goog.html.TrustedResourceUrl.stringifyParams_(150'?', urlSearch, searchParams) +151goog.html.TrustedResourceUrl.stringifyParams_(152'#', urlHash, opt_hashParams));153};154155/**156* Performs a runtime check that the provided object is indeed a157* TrustedResourceUrl object, and returns its value.158*159* @param {!goog.html.TrustedResourceUrl} trustedResourceUrl The object to160* extract from.161* @return {string} The trustedResourceUrl object's contained string, unless162* the run-time type check fails. In that case, `unwrap` returns an163* innocuous string, or, if assertions are enabled, throws164* `goog.asserts.AssertionError`.165*/166goog.html.TrustedResourceUrl.unwrap = function(trustedResourceUrl) {167'use strict';168return goog.html.TrustedResourceUrl.unwrapTrustedScriptURL(trustedResourceUrl)169.toString();170};171172173/**174* Unwraps value as TrustedScriptURL if supported or as a string if not.175* @param {!goog.html.TrustedResourceUrl} trustedResourceUrl176* @return {!TrustedScriptURL|string}177* @see goog.html.TrustedResourceUrl.unwrap178*/179goog.html.TrustedResourceUrl.unwrapTrustedScriptURL = function(180trustedResourceUrl) {181'use strict';182// Perform additional Run-time type-checking to ensure that183// trustedResourceUrl is indeed an instance of the expected type. This184// provides some additional protection against security bugs due to185// application code that disables type checks.186// Specifically, the following checks are performed:187// 1. The object is an instance of the expected type.188// 2. The object is not an instance of a subclass.189if (trustedResourceUrl instanceof goog.html.TrustedResourceUrl &&190trustedResourceUrl.constructor === goog.html.TrustedResourceUrl) {191return trustedResourceUrl192.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_;193} else {194goog.asserts.fail(195'expected object of type TrustedResourceUrl, got \'' +196trustedResourceUrl + '\' of type ' + goog.utils.typeOf(trustedResourceUrl));197return 'type_error:TrustedResourceUrl';198}199};200201202/**203* Creates a TrustedResourceUrl from a format string and arguments.204*205* The arguments for interpolation into the format string map labels to values.206* Values of type `goog.string.Const` are interpolated without modifcation.207* Values of other types are cast to string and encoded with208* encodeURIComponent.209*210* `%{<label>}` markers are used in the format string to indicate locations211* to be interpolated with the valued mapped to the given label. `<label>`212* must contain only alphanumeric and `_` characters.213*214* The format string must match goog.html.TrustedResourceUrl.BASE_URL_.215*216* Example usage:217*218* var url = goog.html.TrustedResourceUrl.format(goog.string.Const.from(219* 'https://www.google.com/search?q=%{query}'), {'query': searchTerm});220*221* var url = goog.html.TrustedResourceUrl.format(goog.string.Const.from(222* '//www.youtube.com/v/%{videoId}?hl=en&fs=1%{autoplay}'), {223* 'videoId': videoId,224* 'autoplay': opt_autoplay ?225* goog.string.Const.from('&autoplay=1') : goog.string.Const.EMPTY226* });227*228* While this function can be used to create a TrustedResourceUrl from only229* constants, fromConstant() and fromConstants() are generally preferable for230* that purpose.231*232* @param {!goog.string.Const} format The format string.233* @param {!Object<string, (string|number|!goog.string.Const)>} args Mapping234* of labels to values to be interpolated into the format string.235* goog.string.Const values are interpolated without encoding.236* @return {!goog.html.TrustedResourceUrl}237* @throws {!Error} On an invalid format string or if a label used in the238* the format string is not present in args.239*/240goog.html.TrustedResourceUrl.format = function(format, args) {241'use strict';242var formatStr = goog.string.Const.unwrap(format);243if (!goog.html.TrustedResourceUrl.BASE_URL_.test(formatStr)) {244throw new Error('Invalid TrustedResourceUrl format: ' + formatStr);245}246var result = formatStr.replace(247goog.html.TrustedResourceUrl.FORMAT_MARKER_, function(match, id) {248'use strict';249if (!Object.prototype.hasOwnProperty.call(args, id)) {250throw new Error(251'Found marker, "' + id + '", in format string, "' + formatStr +252'", but no valid label mapping found ' +253'in args: ' + JSON.stringify(args));254}255var arg = args[id];256if (arg instanceof goog.string.Const) {257return goog.string.Const.unwrap(arg);258} else {259return encodeURIComponent(String(arg));260}261});262return goog.html.TrustedResourceUrl263.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(result);264};265266267/**268* @private @const {!RegExp}269*/270goog.html.TrustedResourceUrl.FORMAT_MARKER_ = /%{(\w+)}/g;271272273/**274* The URL must be absolute, scheme-relative or path-absolute. So it must275* start with:276* - https:// followed by allowed origin characters.277* - // followed by allowed origin characters.278* - Any absolute or relative path.279*280* Based on281* https://url.spec.whatwg.org/commit-snapshots/56b74ce7cca8883eab62e9a12666e2fac665d03d/#url-parsing282* an initial / which is not followed by another / or \ will end up in the "path283* state" and from there it can only go to "fragment state" and "query state".284*285* We don't enforce a well-formed domain name. So '.' or '1.2' are valid.286* That's ok because the origin comes from a compile-time constant.287*288* A regular expression is used instead of goog.uri for several reasons:289* - Strictness. E.g. we don't want any userinfo component and we don't290* want '/./, nor \' in the first path component.291* - Small trusted base. goog.uri is generic and might need to change,292* reasoning about all the ways it can parse a URL now and in the future293* is error-prone.294* - Code size. We expect many calls to .format(), many of which might295* not be using goog.uri.296* - Simplicity. Using goog.uri would likely not result in simpler nor shorter297* code.298* @private @const {!RegExp}299*/300goog.html.TrustedResourceUrl.BASE_URL_ = new RegExp(301'^((https:)?//[0-9a-z.:[\\]-]+/' // Origin.302+ '|/[^/\\\\]' // Absolute path.303+ '|[^:/\\\\%]+/' // Relative path.304+ '|[^:/\\\\%]*[?#]' // Query string or fragment.305+ '|about:blank#' // about:blank with fragment.306+ ')',307'i');308309/**310* RegExp for splitting a URL into the base, search field, and hash field.311*312* @private @const {!RegExp}313*/314goog.html.TrustedResourceUrl.URL_PARAM_PARSER_ =315/^([^?#]*)(\?[^#]*)?(#[\s\S]*)?/;316317318/**319* Formats the URL same as TrustedResourceUrl.format and then adds extra URL320* parameters.321*322* Example usage:323*324* // Creates '//www.youtube.com/v/abc?autoplay=1' for videoId='abc' and325* // opt_autoplay=1. Creates '//www.youtube.com/v/abc' for videoId='abc'326* // and opt_autoplay=undefined.327* var url = goog.html.TrustedResourceUrl.formatWithParams(328* goog.string.Const.from('//www.youtube.com/v/%{videoId}'),329* {'videoId': videoId},330* {'autoplay': opt_autoplay});331*332* @param {!goog.string.Const} format The format string.333* @param {!Object<string, (string|number|!goog.string.Const)>} args Mapping334* of labels to values to be interpolated into the format string.335* goog.string.Const values are interpolated without encoding.336* @param {string|?Object<string, *>|undefined} searchParams Parameters to add337* to URL. See goog.html.TrustedResourceUrl.stringifyParams_ for exact338* format definition.339* @param {(string|?Object<string, *>)=} opt_hashParams Hash parameters to add340* to URL. See goog.html.TrustedResourceUrl.stringifyParams_ for exact341* format definition.342* @return {!goog.html.TrustedResourceUrl}343* @throws {!Error} On an invalid format string or if a label used in the344* the format string is not present in args.345*/346goog.html.TrustedResourceUrl.formatWithParams = function(347format, args, searchParams, opt_hashParams) {348'use strict';349var url = goog.html.TrustedResourceUrl.format(format, args);350return url.cloneWithParams(searchParams, opt_hashParams);351};352353354/**355* Creates a TrustedResourceUrl object from a compile-time constant string.356*357* Compile-time constant strings are inherently program-controlled and hence358* trusted.359*360* @param {!goog.string.Const} url A compile-time-constant string from which to361* create a TrustedResourceUrl.362* @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object363* initialized to `url`.364*/365goog.html.TrustedResourceUrl.fromConstant = function(url) {366'use strict';367return goog.html.TrustedResourceUrl368.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(369goog.string.Const.unwrap(url));370};371372373/**374* Creates a TrustedResourceUrl object from a compile-time constant strings.375*376* Compile-time constant strings are inherently program-controlled and hence377* trusted.378*379* @param {!Array<!goog.string.Const>} parts Compile-time-constant strings from380* which to create a TrustedResourceUrl.381* @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object382* initialized to concatenation of `parts`.383*/384goog.html.TrustedResourceUrl.fromConstants = function(parts) {385'use strict';386var unwrapped = '';387for (var i = 0; i < parts.length; i++) {388unwrapped += goog.string.Const.unwrap(parts[i]);389}390return goog.html.TrustedResourceUrl391.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(unwrapped);392};393394/**395* Creates a TrustedResourceUrl object by generating a Blob from a SafeScript396* object and then calling createObjectURL with that blob.397*398* SafeScript objects are trusted to contain executable JavaScript code.399*400* Caller must call goog.fs.url.revokeObjectUrl() on the unwrapped url to401* release the underlying blob.402*403* Throws if browser doesn't support blob construction.404*405* @param {!goog.html.SafeScript} safeScript A script from which to create a406* TrustedResourceUrl.407* @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object408* initialized to a new blob URL.409*/410goog.html.TrustedResourceUrl.fromSafeScript = function(safeScript) {411'use strict';412var blob = goog.fs.blob.getBlobWithProperties(413[goog.html.SafeScript.unwrap(safeScript)], 'text/javascript');414var url = goog.fs.url.createObjectUrl(blob);415return goog.html.TrustedResourceUrl416.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(url);417};418419420/**421* Token used to ensure that object is created only from this file. No code422* outside of this file can access this token.423* @private {!Object}424* @const425*/426goog.html.TrustedResourceUrl.CONSTRUCTOR_TOKEN_PRIVATE_ = {};427428429/**430* Package-internal utility method to create TrustedResourceUrl instances.431*432* @param {string} url The string to initialize the TrustedResourceUrl object433* with.434* @return {!goog.html.TrustedResourceUrl} The initialized TrustedResourceUrl435* object.436* @package437*/438goog.html.TrustedResourceUrl439.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse = function(url) {440'use strict';441/** @noinline */442const noinlineUrl = url;443const policy = goog.html.trustedtypes.getPolicyPrivateDoNotAccessOrElse();444const value = policy ? policy.createScriptURL(noinlineUrl) : noinlineUrl;445return new goog.html.TrustedResourceUrl(446value, goog.html.TrustedResourceUrl.CONSTRUCTOR_TOKEN_PRIVATE_);447};448449450/**451* Stringifies the passed params to be used as either a search or hash field of452* a URL.453*454* @param {string} prefix The prefix character for the given field ('?' or '#').455* @param {string} currentString The existing field value (including the prefix456* character, if the field is present).457* @param {string|?Object<string, *>|undefined} params The params to set or458* append to the field.459* - If `undefined` or `null`, the field remains unchanged.460* - If a string, then the string will be escaped and the field will be461* overwritten with that value.462* - If an Object, that object is treated as a set of key-value pairs to be463* appended to the current field. Note that JavaScript doesn't guarantee the464* order of values in an object which might result in non-deterministic order465* of the parameters. However, browsers currently preserve the order. The466* rules for each entry:467* - If an array, it will be processed as if each entry were an additional468* parameter with exactly the same key, following the same logic below.469* - If `undefined` or `null`, it will be skipped.470* - Otherwise, it will be turned into a string, escaped, and appended.471* @return {string}472* @private473*/474goog.html.TrustedResourceUrl.stringifyParams_ = function(475prefix, currentString, params) {476'use strict';477if (params == null) {478// Do not modify the field.479return currentString;480}481if (typeof params === 'string') {482// Set field to the passed string.483return params ? prefix + encodeURIComponent(params) : '';484}485// Add on parameters to field from key-value object.486for (var key in params) {487// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty#Using_hasOwnProperty_as_a_property_name488if (Object.prototype.hasOwnProperty.call(params, key)) {489var value = params[key];490var outputValues = Array.isArray(value) ? value : [value];491for (var i = 0; i < outputValues.length; i++) {492var outputValue = outputValues[i];493if (outputValue != null) {494if (!currentString) {495currentString = prefix;496}497currentString += (currentString.length > prefix.length ? '&' : '') +498encodeURIComponent(key) + '=' +499encodeURIComponent(String(outputValue));500}501}502}503}504return currentString;505};506507508