Return-Path: X-Original-To: apmail-flex-commits-archive@www.apache.org Delivered-To: apmail-flex-commits-archive@www.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id 9939D104F6 for ; Thu, 17 Sep 2015 15:28:39 +0000 (UTC) Received: (qmail 73689 invoked by uid 500); 17 Sep 2015 15:28:17 -0000 Delivered-To: apmail-flex-commits-archive@flex.apache.org Received: (qmail 73597 invoked by uid 500); 17 Sep 2015 15:28:17 -0000 Mailing-List: contact commits-help@flex.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@flex.apache.org Delivered-To: mailing list commits@flex.apache.org Received: (qmail 72881 invoked by uid 99); 17 Sep 2015 15:28:17 -0000 Received: from git1-us-west.apache.org (HELO git1-us-west.apache.org) (140.211.11.23) by apache.org (qpsmtpd/0.29) with ESMTP; Thu, 17 Sep 2015 15:28:17 +0000 Received: by git1-us-west.apache.org (ASF Mail Server at git1-us-west.apache.org, from userid 33) id C5AD9E109B; Thu, 17 Sep 2015 15:28:16 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: fthomas@apache.org To: commits@flex.apache.org Date: Thu, 17 Sep 2015 15:28:23 -0000 Message-Id: In-Reply-To: <761aedb1e31440a28bc60df134c87d98@git.apache.org> References: <761aedb1e31440a28bc60df134c87d98@git.apache.org> X-Mailer: ASF-Git Admin Mailer Subject: [08/51] [abbrv] [partial] git commit: [flex-falcon] [refs/heads/JsToAs] - Added GCL extern. http://git-wip-us.apache.org/repos/asf/flex-falcon/blob/e2cad6e6/externs/GCL/externs/goog/history/html5history.js ---------------------------------------------------------------------- diff --git a/externs/GCL/externs/goog/history/html5history.js b/externs/GCL/externs/goog/history/html5history.js new file mode 100644 index 0000000..038d711 --- /dev/null +++ b/externs/GCL/externs/goog/history/html5history.js @@ -0,0 +1,303 @@ +// Copyright 2010 The Closure Library Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * @fileoverview HTML5 based history implementation, compatible with + * goog.History. + * + * TODO(user): There should really be a history interface and multiple + * implementations. + * + */ + + +goog.provide('goog.history.Html5History'); +goog.provide('goog.history.Html5History.TokenTransformer'); + +goog.require('goog.asserts'); +goog.require('goog.events'); +goog.require('goog.events.EventTarget'); +goog.require('goog.events.EventType'); +goog.require('goog.history.Event'); + + + +/** + * An implementation compatible with goog.History that uses the HTML5 + * history APIs. + * + * @param {Window=} opt_win The window to listen/dispatch history events on. + * @param {goog.history.Html5History.TokenTransformer=} opt_transformer + * The token transformer that is used to create URL from the token + * when storing token without using hash fragment. + * @constructor + * @extends {goog.events.EventTarget} + * @final + */ +goog.history.Html5History = function(opt_win, opt_transformer) { + goog.events.EventTarget.call(this); + goog.asserts.assert(goog.history.Html5History.isSupported(opt_win), + 'HTML5 history is not supported.'); + + /** + * The window object to use for history tokens. Typically the top window. + * @type {Window} + * @private + */ + this.window_ = opt_win || window; + + /** + * The token transformer that is used to create URL from the token + * when storing token without using hash fragment. + * @type {goog.history.Html5History.TokenTransformer} + * @private + */ + this.transformer_ = opt_transformer || null; + + goog.events.listen(this.window_, goog.events.EventType.POPSTATE, + this.onHistoryEvent_, false, this); + goog.events.listen(this.window_, goog.events.EventType.HASHCHANGE, + this.onHistoryEvent_, false, this); +}; +goog.inherits(goog.history.Html5History, goog.events.EventTarget); + + +/** + * Returns whether Html5History is supported. + * @param {Window=} opt_win Optional window to check. + * @return {boolean} Whether html5 history is supported. + */ +goog.history.Html5History.isSupported = function(opt_win) { + var win = opt_win || window; + return !!(win.history && win.history.pushState); +}; + + +/** + * Status of when the object is active and dispatching events. + * @type {boolean} + * @private + */ +goog.history.Html5History.prototype.enabled_ = false; + + +/** + * Whether to use the fragment to store the token, defaults to true. + * @type {boolean} + * @private + */ +goog.history.Html5History.prototype.useFragment_ = true; + + +/** + * If useFragment is false the path will be used, the path prefix will be + * prepended to all tokens. Defaults to '/'. + * @type {string} + * @private + */ +goog.history.Html5History.prototype.pathPrefix_ = '/'; + + +/** + * Starts or stops the History. When enabled, the History object + * will immediately fire an event for the current location. The caller can set + * up event listeners between the call to the constructor and the call to + * setEnabled. + * + * @param {boolean} enable Whether to enable history. + */ +goog.history.Html5History.prototype.setEnabled = function(enable) { + if (enable == this.enabled_) { + return; + } + + this.enabled_ = enable; + + if (enable) { + this.dispatchEvent(new goog.history.Event(this.getToken(), false)); + } +}; + + +/** + * Returns the current token. + * @return {string} The current token. + */ +goog.history.Html5History.prototype.getToken = function() { + if (this.useFragment_) { + var loc = this.window_.location.href; + var index = loc.indexOf('#'); + return index < 0 ? '' : loc.substring(index + 1); + } else { + return this.transformer_ ? + this.transformer_.retrieveToken( + this.pathPrefix_, this.window_.location) : + this.window_.location.pathname.substr(this.pathPrefix_.length); + } +}; + + +/** + * Sets the history state. + * @param {string} token The history state identifier. + * @param {string=} opt_title Optional title to associate with history entry. + */ +goog.history.Html5History.prototype.setToken = function(token, opt_title) { + if (token == this.getToken()) { + return; + } + + // Per externs/gecko_dom.js document.title can be null. + this.window_.history.pushState(null, + opt_title || this.window_.document.title || '', this.getUrl_(token)); + this.dispatchEvent(new goog.history.Event(token, false)); +}; + + +/** + * Replaces the current history state without affecting the rest of the history + * stack. + * @param {string} token The history state identifier. + * @param {string=} opt_title Optional title to associate with history entry. + */ +goog.history.Html5History.prototype.replaceToken = function(token, opt_title) { + // Per externs/gecko_dom.js document.title can be null. + this.window_.history.replaceState(null, + opt_title || this.window_.document.title || '', this.getUrl_(token)); + this.dispatchEvent(new goog.history.Event(token, false)); +}; + + +/** @override */ +goog.history.Html5History.prototype.disposeInternal = function() { + goog.events.unlisten(this.window_, goog.events.EventType.POPSTATE, + this.onHistoryEvent_, false, this); + if (this.useFragment_) { + goog.events.unlisten(this.window_, goog.events.EventType.HASHCHANGE, + this.onHistoryEvent_, false, this); + } +}; + + +/** + * Sets whether to use the fragment to store tokens. + * @param {boolean} useFragment Whether to use the fragment. + */ +goog.history.Html5History.prototype.setUseFragment = function(useFragment) { + if (this.useFragment_ != useFragment) { + if (useFragment) { + goog.events.listen(this.window_, goog.events.EventType.HASHCHANGE, + this.onHistoryEvent_, false, this); + } else { + goog.events.unlisten(this.window_, goog.events.EventType.HASHCHANGE, + this.onHistoryEvent_, false, this); + } + this.useFragment_ = useFragment; + } +}; + + +/** + * Sets the path prefix to use if storing tokens in the path. The path + * prefix should start and end with slash. + * @param {string} pathPrefix Sets the path prefix. + */ +goog.history.Html5History.prototype.setPathPrefix = function(pathPrefix) { + this.pathPrefix_ = pathPrefix; +}; + + +/** + * Gets the path prefix. + * @return {string} The path prefix. + */ +goog.history.Html5History.prototype.getPathPrefix = function() { + return this.pathPrefix_; +}; + + +/** + * Gets the URL to set when calling history.pushState + * @param {string} token The history token. + * @return {string} The URL. + * @private + */ +goog.history.Html5History.prototype.getUrl_ = function(token) { + if (this.useFragment_) { + return '#' + token; + } else { + return this.transformer_ ? + this.transformer_.createUrl( + token, this.pathPrefix_, this.window_.location) : + this.pathPrefix_ + token + this.window_.location.search; + } +}; + + +/** + * Handles history events dispatched by the browser. + * @param {goog.events.BrowserEvent} e The browser event object. + * @private + */ +goog.history.Html5History.prototype.onHistoryEvent_ = function(e) { + if (this.enabled_) { + this.dispatchEvent(new goog.history.Event(this.getToken(), true)); + } +}; + + + +/** + * A token transformer that can create a URL from a history + * token. This is used by {@code goog.history.Html5History} to create + * URL when storing token without the hash fragment. + * + * Given a {@code window.location} object containing the location + * created by {@code createUrl}, the token transformer allows + * retrieval of the token back via {@code retrieveToken}. + * + * @interface + */ +goog.history.Html5History.TokenTransformer = function() {}; + + +/** + * Retrieves a history token given the path prefix and + * {@code window.location} object. + * + * @param {string} pathPrefix The path prefix to use when storing token + * in a path; always begin with a slash. + * @param {Location} location The {@code window.location} object. + * Treat this object as read-only. + * @return {string} token The history token. + */ +goog.history.Html5History.TokenTransformer.prototype.retrieveToken = function( + pathPrefix, location) {}; + + +/** + * Creates a URL to be pushed into HTML5 history stack when storing + * token without using hash fragment. + * + * @param {string} token The history token. + * @param {string} pathPrefix The path prefix to use when storing token + * in a path; always begin with a slash. + * @param {Location} location The {@code window.location} object. + * Treat this object as read-only. + * @return {string} url The complete URL string from path onwards + * (without {@code protocol://host:port} part); must begin with a + * slash. + */ +goog.history.Html5History.TokenTransformer.prototype.createUrl = function( + token, pathPrefix, location) {}; http://git-wip-us.apache.org/repos/asf/flex-falcon/blob/e2cad6e6/externs/GCL/externs/goog/html/flash.js ---------------------------------------------------------------------- diff --git a/externs/GCL/externs/goog/html/flash.js b/externs/GCL/externs/goog/html/flash.js new file mode 100644 index 0000000..9f72665 --- /dev/null +++ b/externs/GCL/externs/goog/html/flash.js @@ -0,0 +1,177 @@ +// Copyright 2014 The Closure Library Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +/** + * @fileoverview SafeHtml factory methods for creating object and embed tags + * for loading Flash files. + */ + +goog.provide('goog.html.flash'); + +goog.require('goog.asserts'); +goog.require('goog.html.SafeHtml'); + + +/** + * Attributes and param tag name attributes not allowed to be overriden + * when calling createObject() and createObjectForOldIe(). + * + * While values that should be specified as params are probably not + * recognized as attributes, we block them anyway just to be sure. + * @const {!Array} + * @private + */ +goog.html.flash.FORBIDDEN_ATTRS_AND_PARAMS_ON_FLASH_ = [ + 'classid', // Used on old IE. + 'data', // Used in to specify a URL. + 'movie', // Used on old IE. + 'type', // Used in on for non-IE/modern IE. + 'typemustmatch' // Always set to a fixed value. +]; + + +goog.html.flash.createEmbed = function(src, opt_attributes) { + var fixedAttributes = { + 'src': src, + 'type': 'application/x-shockwave-flash', + 'pluginspage': 'https://www.macromedia.com/go/getflashplayer' + }; + var defaultAttributes = { + 'allownetworking': 'none', + 'allowscriptaccess': 'never' + }; + var attributes = goog.html.SafeHtml.combineAttributes( + fixedAttributes, defaultAttributes, opt_attributes); + return goog.html.SafeHtml. + createSafeHtmlTagSecurityPrivateDoNotAccessOrElse('embed', attributes); +}; + + +goog.html.flash.createObject = function( + data, opt_params, opt_attributes) { + goog.html.flash.verifyKeysNotInMaps( + goog.html.flash.FORBIDDEN_ATTRS_AND_PARAMS_ON_FLASH_, + opt_attributes, + opt_params); + + var paramTags = goog.html.flash.combineParams( + { + 'allownetworking': 'none', + 'allowscriptaccess': 'never' + }, + opt_params); + var fixedAttributes = { + 'data': data, + 'type': 'application/x-shockwave-flash', + 'typemustmatch': '' + }; + var attributes = goog.html.SafeHtml.combineAttributes( + fixedAttributes, {}, opt_attributes); + + return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( + 'object', attributes, paramTags); +}; + + +goog.html.flash.createObjectForOldIe = function( + movie, opt_params, opt_attributes) { + goog.html.flash.verifyKeysNotInMaps( + goog.html.flash.FORBIDDEN_ATTRS_AND_PARAMS_ON_FLASH_, + opt_attributes, + opt_params); + + var paramTags = goog.html.flash.combineParams( + { + 'allownetworking': 'none', + 'allowscriptaccess': 'never', + 'movie': movie + }, + opt_params); + var fixedAttributes = + {'classid': 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000'}; + var attributes = goog.html.SafeHtml.combineAttributes( + fixedAttributes, {}, opt_attributes); + + return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( + 'object', attributes, paramTags); +}; + + +/** + * @param {!Object} defaultParams + * @param {!Object=} + * opt_params Optional params passed to create*(). + * @return {!Array} Combined params. + * @throws {Error} If opt_attributes contains an attribute with the same name + * as an attribute in fixedAttributes. + * @package + */ +goog.html.flash.combineParams = function(defaultParams, opt_params) { + var combinedParams = {}; + var name; + + for (name in defaultParams) { + goog.asserts.assert(name.toLowerCase() == name, 'Must be lower case'); + combinedParams[name] = defaultParams[name]; + } + for (name in opt_params) { + var nameLower = name.toLowerCase(); + if (nameLower in defaultParams) { + delete combinedParams[nameLower]; + } + combinedParams[name] = opt_params[name]; + } + + var paramTags = []; + for (name in combinedParams) { + paramTags.push( + goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( + 'param', {'name': name, 'value': combinedParams[name]})); + + } + return paramTags; +}; + + +/** + * Checks that keys are not present as keys in maps. + * @param {!Array} keys Keys that must not be present, lower-case. + * @param {!Object=} + * opt_attributes Optional attributes passed to create*(). + * @param {!Object=} opt_params Optional params passed to + * createObject*(). + * @throws {Error} If any of keys exist as a key, ignoring case, in + * opt_attributes or opt_params. + * @package + */ +goog.html.flash.verifyKeysNotInMaps = function( + keys, opt_attributes, opt_params) { + var verifyNotInMap = function(keys, map, type) { + for (var keyMap in map) { + var keyMapLower = keyMap.toLowerCase(); + for (var i = 0; i < keys.length; i++) { + var keyToCheck = keys[i]; + goog.asserts.assert(keyToCheck.toLowerCase() == keyToCheck); + if (keyMapLower == keyToCheck) { + throw Error('Cannot override "' + keyToCheck + '" ' + type + + ', got "' + keyMap + '" with value "' + map[keyMap] + '"'); + } + } + } + }; + + verifyNotInMap(keys, opt_attributes, 'attribute'); + verifyNotInMap(keys, opt_params, 'param'); +}; http://git-wip-us.apache.org/repos/asf/flex-falcon/blob/e2cad6e6/externs/GCL/externs/goog/html/legacyconversions.js ---------------------------------------------------------------------- diff --git a/externs/GCL/externs/goog/html/legacyconversions.js b/externs/GCL/externs/goog/html/legacyconversions.js new file mode 100644 index 0000000..89a4c6d --- /dev/null +++ b/externs/GCL/externs/goog/html/legacyconversions.js @@ -0,0 +1,200 @@ +// Copyright 2013 The Closure Library Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * @fileoverview Conversions from plain string to goog.html types for use in + * legacy APIs that do not use goog.html types. + * + * This file provides conversions to create values of goog.html types from plain + * strings. These conversions are intended for use in legacy APIs that consume + * HTML in the form of plain string types, but whose implementations use + * goog.html types internally (and expose such types in an augmented, HTML-type- + * safe API). + * + * IMPORTANT: No new code should use the conversion functions in this file. + * + * The conversion functions in this file are guarded with global flag + * (goog.html.legacyconversions.ALLOW_LEGACY_CONVERSIONS). If set to false, it + * effectively "locks in" an entire application to only use HTML-type-safe APIs. + * + * Intended use of the functions in this file are as follows: + * + * Many Closure and application-specific classes expose methods that consume + * values that in the class' implementation are forwarded to DOM APIs that can + * result in security vulnerabilities. For example, goog.ui.Dialog's setContent + * method consumes a string that is assigned to an element's innerHTML property; + * if this string contains untrusted (attacker-controlled) data, this can result + * in a cross-site-scripting vulnerability. + * + * Widgets such as goog.ui.Dialog are being augmented to expose safe APIs + * expressed in terms of goog.html types. For instance, goog.ui.Dialog has a + * method setSafeHtmlContent that consumes an object of type goog.html.SafeHtml, + * a type whose contract guarantees that its value is safe to use in HTML + * context, i.e. can be safely assigned to .innerHTML. An application that only + * uses this API is forced to only supply values of this type, i.e. values that + * are safe. + * + * However, the legacy method setContent cannot (for the time being) be removed + * from goog.ui.Dialog, due to a large number of existing callers. The + * implementation of goog.ui.Dialog has been refactored to use + * goog.html.SafeHtml throughout. This in turn requires that the value consumed + * by its setContent method is converted to goog.html.SafeHtml in an unchecked + * conversion. The conversion function is provided by this file: + * goog.html.legacyconversions.safeHtmlFromString. + * + * Note that the semantics of the conversions in goog.html.legacyconversions are + * very different from the ones provided by goog.html.uncheckedconversions: The + * latter are for use in code where it has been established through manual + * security review that the value produced by a piece of code must always + * satisfy the SafeHtml contract (e.g., the output of a secure HTML sanitizer). + * In uses of goog.html.legacyconversions, this guarantee is not given -- the + * value in question originates in unreviewed legacy code and there is no + * guarantee that it satisfies the SafeHtml contract. + * + * To establish correctness with confidence, application code should be + * refactored to use SafeHtml instead of plain string to represent HTML markup, + * and to use goog.html-typed APIs (e.g., goog.ui.Dialog#setSafeHtmlContent + * instead of goog.ui.Dialog#setContent). + * + * To prevent introduction of new vulnerabilities, application owners can + * effectively disable unsafe legacy APIs by compiling with the define + * goog.html.legacyconversions.ALLOW_LEGACY_CONVERSIONS set to false. When + * set, this define causes the conversion methods in this file to + * unconditionally throw an exception. + * + * Note that new code should always be compiled with + * ALLOW_LEGACY_CONVERSIONS=false. At some future point, the default for this + * define may change to false. + */ + + +goog.provide('goog.html.legacyconversions'); + +goog.require('goog.html.SafeHtml'); +goog.require('goog.html.SafeStyle'); +goog.require('goog.html.SafeUrl'); +goog.require('goog.html.TrustedResourceUrl'); + + +/** + * @define {boolean} Whether conversion from string to goog.html types for + * legacy API purposes is permitted. + * + * If false, the conversion functions in this file unconditionally throw an + * exception. + */ +goog.define('goog.html.legacyconversions.ALLOW_LEGACY_CONVERSIONS', true); + + +/** + * Performs an "unchecked conversion" from string to SafeHtml for legacy API + * purposes. + * + * Unchecked conversion will not proceed if ALLOW_LEGACY_CONVERSIONS is false, + * and instead this function unconditionally throws an exception. + * + * @param {string} html A string to be converted to SafeHtml. + * @return {!goog.html.SafeHtml} The value of html, wrapped in a SafeHtml + * object. + */ +goog.html.legacyconversions.safeHtmlFromString = function(html) { + goog.html.legacyconversions.throwIfConversionsDisallowed(); + return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( + html, null /* dir */); +}; + + +/** + * Performs an "unchecked conversion" from string to SafeStyle for legacy API + * purposes. + * + * Unchecked conversion will not proceed if ALLOW_LEGACY_CONVERSIONS is false, + * and instead this function unconditionally throws an exception. + * + * @param {string} style A string to be converted to SafeStyle. + * @return {!goog.html.SafeStyle} The value of style, wrapped in a SafeStyle + * object. + */ +goog.html.legacyconversions.safeStyleFromString = function(style) { + goog.html.legacyconversions.throwIfConversionsDisallowed(); + return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse( + style); +}; + + +/** + * Performs an "unchecked conversion" from string to TrustedResourceUrl for + * legacy API purposes. + * + * Unchecked conversion will not proceed if ALLOW_LEGACY_CONVERSIONS is false, + * and instead this function unconditionally throws an exception. + * + * @param {string} url A string to be converted to TrustedResourceUrl. + * @return {!goog.html.TrustedResourceUrl} The value of url, wrapped in a + * TrustedResourceUrl object. + */ +goog.html.legacyconversions.trustedResourceUrlFromString = function(url) { + goog.html.legacyconversions.throwIfConversionsDisallowed(); + return goog.html.TrustedResourceUrl. + createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(url); +}; + + +/** + * Performs an "unchecked conversion" from string to SafeUrl for legacy API + * purposes. + * + * Unchecked conversion will not proceed if ALLOW_LEGACY_CONVERSIONS is false, + * and instead this function unconditionally throws an exception. + * + * @param {string} url A string to be converted to SafeUrl. + * @return {!goog.html.SafeUrl} The value of url, wrapped in a SafeUrl + * object. + */ +goog.html.legacyconversions.safeUrlFromString = function(url) { + goog.html.legacyconversions.throwIfConversionsDisallowed(); + return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url); +}; + + +/** + * @private {function(): undefined} + */ +goog.html.legacyconversions.reportCallback_ = goog.nullFunction; + + +/** + * Sets a function that will be called every time a legacy conversion is + * performed. The function is called with no parameters but it can use + * goog.debug.getStacktrace to get a stacktrace. + * + * @param {function(): undefined} callback Error callback as defined above. + */ +goog.html.legacyconversions.setReportCallback = function(callback) { + goog.html.legacyconversions.reportCallback_ = callback; +}; + + +/** + * Throws an exception if ALLOW_LEGACY_CONVERSIONS is false. This is useful + * for legacy APIs which consume HTML in the form of plain string types, but + * do not provide an alternative HTML-type-safe API. + */ +goog.html.legacyconversions.throwIfConversionsDisallowed = function() { + if (!goog.html.legacyconversions.ALLOW_LEGACY_CONVERSIONS) { + throw Error( + 'Error: Legacy conversion from string to goog.html types is disabled'); + } + goog.html.legacyconversions.reportCallback_(); +}; http://git-wip-us.apache.org/repos/asf/flex-falcon/blob/e2cad6e6/externs/GCL/externs/goog/html/safehtml.js ---------------------------------------------------------------------- diff --git a/externs/GCL/externs/goog/html/safehtml.js b/externs/GCL/externs/goog/html/safehtml.js new file mode 100644 index 0000000..ef6a2ae --- /dev/null +++ b/externs/GCL/externs/goog/html/safehtml.js @@ -0,0 +1,756 @@ +// Copyright 2013 The Closure Library Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +/** + * @fileoverview The SafeHtml type and its builders. + * + * TODO(user): Link to document stating type contract. + */ + +goog.provide('goog.html.SafeHtml'); + +goog.require('goog.array'); +goog.require('goog.asserts'); +goog.require('goog.dom.TagName'); +goog.require('goog.dom.tags'); +goog.require('goog.html.SafeStyle'); +goog.require('goog.html.SafeStyleSheet'); +goog.require('goog.html.SafeUrl'); +goog.require('goog.html.TrustedResourceUrl'); +goog.require('goog.i18n.bidi.Dir'); +goog.require('goog.i18n.bidi.DirectionalString'); +goog.require('goog.object'); +goog.require('goog.string'); +goog.require('goog.string.Const'); +goog.require('goog.string.TypedString'); + + + +/** + * A string that is safe to use in HTML context in DOM APIs and HTML documents. + * + * A SafeHtml is a string-like object that carries the security type contract + * that its value as a string will not cause untrusted script execution when + * evaluated as HTML in a browser. + * + * Values of this type are guaranteed to be safe to use in HTML contexts, + * such as, assignment to the innerHTML DOM property, or interpolation into + * a HTML template in HTML PC_DATA context, in the sense that the use will not + * result in a Cross-Site-Scripting vulnerability. + * + * Instances of this type must be created via the factory methods + * ({@code goog.html.SafeHtml.create}, {@code goog.html.SafeHtml.htmlEscape}), + * etc and not by invoking its constructor. The constructor intentionally + * takes no parameters and the type is immutable; hence only a default instance + * corresponding to the empty string can be obtained via constructor invocation. + * + * @see goog.html.SafeHtml#create + * @see goog.html.SafeHtml#htmlEscape + * @constructor + * @final + * @struct + * @implements {goog.i18n.bidi.DirectionalString} + * @implements {goog.string.TypedString} + */ +goog.html.SafeHtml = function() { + /** + * The contained value of this SafeHtml. The field has a purposely ugly + * name to make (non-compiled) code that attempts to directly access this + * field stand out. + * @private {string} + */ + this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = ''; + + /** + * A type marker used to implement additional run-time type checking. + * @see goog.html.SafeHtml#unwrap + * @const + * @private + */ + this.SAFE_HTML_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = + goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; + + /** + * This SafeHtml's directionality, or null if unknown. + * @private {?goog.i18n.bidi.Dir} + */ + this.dir_ = null; +}; + + +/** + * @override + * @const + */ +goog.html.SafeHtml.prototype.implementsGoogI18nBidiDirectionalString = true; + + +/** @override */ +goog.html.SafeHtml.prototype.getDirection = function() { + return this.dir_; +}; + + +/** + * @override + * @const + */ +goog.html.SafeHtml.prototype.implementsGoogStringTypedString = true; + + +/** + * Returns this SafeHtml's value a string. + * + * IMPORTANT: In code where it is security relevant that an object's type is + * indeed {@code SafeHtml}, use {@code goog.html.SafeHtml.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: + * + *
+ * 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.
+ * 
+ * + * @see goog.html.SafeHtml#unwrap + * @override + */ +goog.html.SafeHtml.prototype.getTypedStringValue = function() { + return this.privateDoNotAccessOrElseSafeHtmlWrappedValue_; +}; + + +if (goog.DEBUG) { + /** + * Returns a debug string-representation of this value. + * + * To obtain the actual string value wrapped in a SafeHtml, use + * {@code goog.html.SafeHtml.unwrap}. + * + * @see goog.html.SafeHtml#unwrap + * @override + */ + goog.html.SafeHtml.prototype.toString = function() { + return 'SafeHtml{' + this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ + + '}'; + }; +} + + +/** + * Performs a runtime check that the provided object is indeed a SafeHtml + * object, and returns its value. + * @param {!goog.html.SafeHtml} safeHtml The object to extract from. + * @return {string} The SafeHtml object's contained string, unless the run-time + * type check fails. In that case, {@code unwrap} returns an innocuous + * string, or, if assertions are enabled, throws + * {@code goog.asserts.AssertionError}. + */ +goog.html.SafeHtml.unwrap = function(safeHtml) { + // Perform additional run-time type-checking to ensure that safeHtml 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. + // 3. The object carries a type marker for the expected type. "Faking" an + // object requires a reference to the type marker, which has names intended + // to stand out in code reviews. + if (safeHtml instanceof goog.html.SafeHtml && + safeHtml.constructor === goog.html.SafeHtml && + safeHtml.SAFE_HTML_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === + goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { + return safeHtml.privateDoNotAccessOrElseSafeHtmlWrappedValue_; + } else { + goog.asserts.fail('expected object of type SafeHtml, got \'' + + safeHtml + '\''); + return 'type_error:SafeHtml'; + } +}; + + +/** + * Shorthand for union of types that can sensibly be converted to strings + * or might already be SafeHtml (as SafeHtml is a goog.string.TypedString). + * @private + * @typedef {string|number|boolean|!goog.string.TypedString| + * !goog.i18n.bidi.DirectionalString} + */ +goog.html.SafeHtml.TextOrHtml_; + + +/** + * Returns HTML-escaped text as a SafeHtml object. + * + * If text is of a type that implements + * {@code goog.i18n.bidi.DirectionalString}, the directionality of the new + * {@code SafeHtml} object is set to {@code text}'s directionality, if known. + * Otherwise, the directionality of the resulting SafeHtml is unknown (i.e., + * {@code null}). + * + * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If + * the parameter is of type SafeHtml it is returned directly (no escaping + * is done). + * @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml. + */ +goog.html.SafeHtml.htmlEscape = function(textOrHtml) { + if (textOrHtml instanceof goog.html.SafeHtml) { + return textOrHtml; + } + var dir = null; + if (textOrHtml.implementsGoogI18nBidiDirectionalString) { + dir = textOrHtml.getDirection(); + } + var textAsString; + if (textOrHtml.implementsGoogStringTypedString) { + textAsString = textOrHtml.getTypedStringValue(); + } else { + textAsString = String(textOrHtml); + } + return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( + goog.string.htmlEscape(textAsString), dir); +}; + + +/** + * Returns HTML-escaped text as a SafeHtml object, with newlines changed to + * <br>. + * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If + * the parameter is of type SafeHtml it is returned directly (no escaping + * is done). + * @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml. + */ +goog.html.SafeHtml.htmlEscapePreservingNewlines = function(textOrHtml) { + if (textOrHtml instanceof goog.html.SafeHtml) { + return textOrHtml; + } + var html = goog.html.SafeHtml.htmlEscape(textOrHtml); + return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( + goog.string.newLineToBr(goog.html.SafeHtml.unwrap(html)), + html.getDirection()); +}; + + +/** + * Returns HTML-escaped text as a SafeHtml object, with newlines changed to + * <br> and escaping whitespace to preserve spatial formatting. Character + * entity #160 is used to make it safer for XML. + * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If + * the parameter is of type SafeHtml it is returned directly (no escaping + * is done). + * @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml. + */ +goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces = function( + textOrHtml) { + if (textOrHtml instanceof goog.html.SafeHtml) { + return textOrHtml; + } + var html = goog.html.SafeHtml.htmlEscape(textOrHtml); + return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( + goog.string.whitespaceEscape(goog.html.SafeHtml.unwrap(html)), + html.getDirection()); +}; + + +/** + * Coerces an arbitrary object into a SafeHtml object. + * + * If {@code textOrHtml} is already of type {@code goog.html.SafeHtml}, the same + * object is returned. Otherwise, {@code textOrHtml} is coerced to string, and + * HTML-escaped. If {@code textOrHtml} is of a type that implements + * {@code goog.i18n.bidi.DirectionalString}, its directionality, if known, is + * preserved. + * + * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text or SafeHtml to + * coerce. + * @return {!goog.html.SafeHtml} The resulting SafeHtml object. + * @deprecated Use goog.html.SafeHtml.htmlEscape. + */ +goog.html.SafeHtml.from = goog.html.SafeHtml.htmlEscape; + + +/** + * @const + * @private + */ +goog.html.SafeHtml.VALID_NAMES_IN_TAG_ = /^[a-zA-Z0-9-]+$/; + + +/** + * Set of attributes containing URL as defined at + * http://www.w3.org/TR/html5/index.html#attributes-1. + * @private @const {!Object} + */ +goog.html.SafeHtml.URL_ATTRIBUTES_ = goog.object.createSet('action', 'cite', + 'data', 'formaction', 'href', 'manifest', 'poster', 'src'); + + +/** + * Tags which are unsupported via create(). They might be supported via a + * tag-specific create method. These are tags which might require a + * TrustedResourceUrl in one of their attributes or a restricted type for + * their content. + * @private @const {!Object} + */ +goog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_ = goog.object.createSet( + goog.dom.TagName.EMBED, goog.dom.TagName.IFRAME, goog.dom.TagName.LINK, + goog.dom.TagName.OBJECT, goog.dom.TagName.SCRIPT, goog.dom.TagName.STYLE, + goog.dom.TagName.TEMPLATE); + + +/** + * @typedef {string|number|goog.string.TypedString| + * goog.html.SafeStyle.PropertyMap} + * @private + */ +goog.html.SafeHtml.AttributeValue_; + + +/** + * Creates a SafeHtml content consisting of a tag with optional attributes and + * optional content. + * + * For convenience tag names and attribute names are accepted as regular + * strings, instead of goog.string.Const. Nevertheless, you should not pass + * user-controlled values to these parameters. Note that these parameters are + * syntactically validated at runtime, and invalid values will result in + * an exception. + * + * Example usage: + * + * goog.html.SafeHtml.create('br'); + * goog.html.SafeHtml.create('div', {'class': 'a'}); + * goog.html.SafeHtml.create('p', {}, 'a'); + * goog.html.SafeHtml.create('p', {}, goog.html.SafeHtml.create('br')); + * + * goog.html.SafeHtml.create('span', { + * 'style': {'margin': '0'} + * }); + * + * To guarantee SafeHtml's type contract is upheld there are restrictions on + * attribute values and tag names. + * + * - For attributes which contain script code (on*), a goog.string.Const is + * required. + * - For attributes which contain style (style), a goog.html.SafeStyle or a + * goog.html.SafeStyle.PropertyMap is required. + * - For attributes which are interpreted as URLs (e.g. src, href) a + * goog.html.SafeUrl or goog.string.Const is required. + * - For tags which can load code, more specific goog.html.SafeHtml.create*() + * functions must be used. Tags which can load code and are not supported by + * this function are embed, iframe, link, object, script, style, and template. + * + * @param {string} tagName The name of the tag. Only tag names consisting of + * [a-zA-Z0-9-] are allowed. Tag names documented above are disallowed. + * @param {!Object=} + * opt_attributes Mapping from attribute names to their values. Only + * attribute names consisting of [a-zA-Z0-9-] are allowed. Value of null or + * undefined causes the attribute to be omitted. + * @param {!goog.html.SafeHtml.TextOrHtml_| + * !Array=} opt_content Content to + * HTML-escape and put inside the tag. This must be empty for void tags + * like
. Array elements are concatenated. + * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. + * @throws {Error} If invalid tag name, attribute name, or attribute value is + * provided. + * @throws {goog.asserts.AssertionError} If content for void tag is provided. + */ +goog.html.SafeHtml.create = function(tagName, opt_attributes, opt_content) { + if (!goog.html.SafeHtml.VALID_NAMES_IN_TAG_.test(tagName)) { + throw Error('Invalid tag name <' + tagName + '>.'); + } + if (tagName.toUpperCase() in goog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_) { + throw Error('Tag name <' + tagName + '> is not allowed for SafeHtml.'); + } + return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( + tagName, opt_attributes, opt_content); +}; + + +/** + * Creates a SafeHtml representing an iframe tag. + * + * By default the sandbox attribute is set to an empty value, which is the most + * secure option, as it confers the iframe the least privileges. If this + * is too restrictive then granting individual privileges is the preferable + * option. Unsetting the attribute entirely is the least secure option and + * should never be done unless it's stricly necessary. + * + * @param {goog.html.TrustedResourceUrl=} opt_src The value of the src + * attribute. If null or undefined src will not be set. + * @param {goog.html.SafeHtml=} opt_srcdoc The value of the srcdoc attribute. + * If null or undefined srcdoc will not be set. + * @param {!Object=} + * opt_attributes Mapping from attribute names to their values. Only + * attribute names consisting of [a-zA-Z0-9-] are allowed. Value of null or + * undefined causes the attribute to be omitted. + * @param {!goog.html.SafeHtml.TextOrHtml_| + * !Array=} opt_content Content to + * HTML-escape and put inside the tag. Array elements are concatenated. + * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. + * @throws {Error} If invalid tag name, attribute name, or attribute value is + * provided. If opt_attributes contains the src or srcdoc attributes. + */ +goog.html.SafeHtml.createIframe = function( + opt_src, opt_srcdoc, opt_attributes, opt_content) { + var fixedAttributes = {}; + fixedAttributes['src'] = opt_src || null; + fixedAttributes['srcdoc'] = opt_srcdoc || null; + var defaultAttributes = {'sandbox': ''}; + var attributes = goog.html.SafeHtml.combineAttributes( + fixedAttributes, defaultAttributes, opt_attributes); + return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( + 'iframe', attributes, opt_content); +}; + + +/** + * Creates a SafeHtml representing a style tag. The type attribute is set + * to "text/css". + * @param {!goog.html.SafeStyleSheet|!Array} + * styleSheet Content to put inside the tag. Array elements are + * concatenated. + * @param {!Object=} + * opt_attributes Mapping from attribute names to their values. Only + * attribute names consisting of [a-zA-Z0-9-] are allowed. Value of null or + * undefined causes the attribute to be omitted. + * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. + * @throws {Error} If invalid attribute name or attribute value is provided. If + * opt_attributes contains the type attribute. + */ +goog.html.SafeHtml.createStyle = function(styleSheet, opt_attributes) { + var fixedAttributes = {'type': 'text/css'}; + var defaultAttributes = {}; + var attributes = goog.html.SafeHtml.combineAttributes( + fixedAttributes, defaultAttributes, opt_attributes); + + var content = ''; + styleSheet = goog.array.concat(styleSheet); + for (var i = 0; i < styleSheet.length; i++) { + content += goog.html.SafeStyleSheet.unwrap(styleSheet[i]); + } + // Convert to SafeHtml so that it's not HTML-escaped. + var htmlContent = goog.html.SafeHtml + .createSafeHtmlSecurityPrivateDoNotAccessOrElse( + content, goog.i18n.bidi.Dir.NEUTRAL); + return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( + 'style', attributes, htmlContent); +}; + + +/** + * @param {string} tagName The tag name. + * @param {string} name The attribute name. + * @param {!goog.html.SafeHtml.AttributeValue_} value The attribute value. + * @return {string} A "name=value" string. + * @throws {Error} If attribute value is unsafe for the given tag and attribute. + * @private + */ +goog.html.SafeHtml.getAttrNameAndValue_ = function(tagName, name, value) { + // If it's goog.string.Const, allow any valid attribute name. + if (value instanceof goog.string.Const) { + value = goog.string.Const.unwrap(value); + } else if (name.toLowerCase() == 'style') { + value = goog.html.SafeHtml.getStyleValue_(value); + } else if (/^on/i.test(name)) { + // TODO(jakubvrana): Disallow more attributes with a special meaning. + throw Error('Attribute "' + name + + '" requires goog.string.Const value, "' + value + '" given.'); + // URL attributes handled differently accroding to tag. + } else if (name.toLowerCase() in goog.html.SafeHtml.URL_ATTRIBUTES_) { + if (value instanceof goog.html.TrustedResourceUrl) { + value = goog.html.TrustedResourceUrl.unwrap(value); + } else if (value instanceof goog.html.SafeUrl) { + value = goog.html.SafeUrl.unwrap(value); + } else { + // TODO(user): Allow strings and sanitize them automatically, + // so that it's consistent with accepting a map directly for "style". + throw Error('Attribute "' + name + '" on tag "' + tagName + + '" requires goog.html.SafeUrl or goog.string.Const value, "' + + value + '" given.'); + } + } + + // Accept SafeUrl, TrustedResourceUrl, etc. for attributes which only require + // HTML-escaping. + if (value.implementsGoogStringTypedString) { + // Ok to call getTypedStringValue() since there's no reliance on the type + // contract for security here. + value = value.getTypedStringValue(); + } + + goog.asserts.assert(goog.isString(value) || goog.isNumber(value), + 'String or number value expected, got ' + + (typeof value) + ' with value: ' + value); + return name + '="' + goog.string.htmlEscape(String(value)) + '"'; +}; + + +/** + * Gets value allowed in "style" attribute. + * @param {goog.html.SafeHtml.AttributeValue_} value It could be SafeStyle or a + * map which will be passed to goog.html.SafeStyle.create. + * @return {string} Unwrapped value. + * @throws {Error} If string value is given. + * @private + */ +goog.html.SafeHtml.getStyleValue_ = function(value) { + if (!goog.isObject(value)) { + throw Error('The "style" attribute requires goog.html.SafeStyle or map ' + + 'of style properties, ' + (typeof value) + ' given: ' + value); + } + if (!(value instanceof goog.html.SafeStyle)) { + // Process the property bag into a style object. + value = goog.html.SafeStyle.create(value); + } + return goog.html.SafeStyle.unwrap(value); +}; + + +/** + * Creates a SafeHtml content with known directionality consisting of a tag with + * optional attributes and optional content. + * @param {!goog.i18n.bidi.Dir} dir Directionality. + * @param {string} tagName + * @param {!Object=} opt_attributes + * @param {!goog.html.SafeHtml.TextOrHtml_| + * !Array=} opt_content + * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. + */ +goog.html.SafeHtml.createWithDir = function(dir, tagName, opt_attributes, + opt_content) { + var html = goog.html.SafeHtml.create(tagName, opt_attributes, opt_content); + html.dir_ = dir; + return html; +}; + + +/** + * Creates a new SafeHtml object by concatenating values. + * @param {...(!goog.html.SafeHtml.TextOrHtml_| + * !Array)} var_args Values to concatenate. + * @return {!goog.html.SafeHtml} + */ +goog.html.SafeHtml.concat = function(var_args) { + var dir = goog.i18n.bidi.Dir.NEUTRAL; + var content = ''; + + /** + * @param {!goog.html.SafeHtml.TextOrHtml_| + * !Array} argument + */ + var addArgument = function(argument) { + if (goog.isArray(argument)) { + goog.array.forEach(argument, addArgument); + } else { + var html = goog.html.SafeHtml.htmlEscape(argument); + content += goog.html.SafeHtml.unwrap(html); + var htmlDir = html.getDirection(); + if (dir == goog.i18n.bidi.Dir.NEUTRAL) { + dir = htmlDir; + } else if (htmlDir != goog.i18n.bidi.Dir.NEUTRAL && dir != htmlDir) { + dir = null; + } + } + }; + + goog.array.forEach(arguments, addArgument); + return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( + content, dir); +}; + + +/** + * Creates a new SafeHtml object with known directionality by concatenating the + * values. + * @param {!goog.i18n.bidi.Dir} dir Directionality. + * @param {...(!goog.html.SafeHtml.TextOrHtml_| + * !Array)} var_args Elements of array + * arguments would be processed recursively. + * @return {!goog.html.SafeHtml} + */ +goog.html.SafeHtml.concatWithDir = function(dir, var_args) { + var html = goog.html.SafeHtml.concat(goog.array.slice(arguments, 1)); + html.dir_ = dir; + return html; +}; + + +/** + * Type marker for the SafeHtml type, used to implement additional run-time + * type checking. + * @const + * @private + */ +goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; + + +/** + * Package-internal utility method to create SafeHtml instances. + * + * @param {string} html The string to initialize the SafeHtml object with. + * @param {?goog.i18n.bidi.Dir} dir The directionality of the SafeHtml to be + * constructed, or null if unknown. + * @return {!goog.html.SafeHtml} The initialized SafeHtml object. + * @package + */ +goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse = function( + html, dir) { + return new goog.html.SafeHtml().initSecurityPrivateDoNotAccessOrElse_( + html, dir); +}; + + +/** + * Called from createSafeHtmlSecurityPrivateDoNotAccessOrElse(). This + * method exists only so that the compiler can dead code eliminate static + * fields (like EMPTY) when they're not accessed. + * @param {string} html + * @param {?goog.i18n.bidi.Dir} dir + * @return {!goog.html.SafeHtml} + * @private + */ +goog.html.SafeHtml.prototype.initSecurityPrivateDoNotAccessOrElse_ = function( + html, dir) { + this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = html; + this.dir_ = dir; + return this; +}; + + +/** + * Like create() but does not restrict which tags can be constructed. + * + * @param {string} tagName Tag name. Set or validated by caller. + * @param {!Object=} opt_attributes + * @param {(!goog.html.SafeHtml.TextOrHtml_| + * !Array)=} opt_content + * @return {!goog.html.SafeHtml} + * @throws {Error} If invalid or unsafe attribute name or value is provided. + * @throws {goog.asserts.AssertionError} If content for void tag is provided. + * @package + */ +goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse = + function(tagName, opt_attributes, opt_content) { + var dir = null; + var result = '<' + tagName; + + if (opt_attributes) { + for (var name in opt_attributes) { + if (!goog.html.SafeHtml.VALID_NAMES_IN_TAG_.test(name)) { + throw Error('Invalid attribute name "' + name + '".'); + } + var value = opt_attributes[name]; + if (!goog.isDefAndNotNull(value)) { + continue; + } + result += ' ' + + goog.html.SafeHtml.getAttrNameAndValue_(tagName, name, value); + } + } + + var content = opt_content; + if (!goog.isDefAndNotNull(content)) { + content = []; + } else if (!goog.isArray(content)) { + content = [content]; + } + + if (goog.dom.tags.isVoidTag(tagName.toLowerCase())) { + goog.asserts.assert(!content.length, + 'Void tag <' + tagName + '> does not allow content.'); + result += '>'; + } else { + var html = goog.html.SafeHtml.concat(content); + result += '>' + goog.html.SafeHtml.unwrap(html) + ''; + dir = html.getDirection(); + } + + var dirAttribute = opt_attributes && opt_attributes['dir']; + if (dirAttribute) { + if (/^(ltr|rtl|auto)$/i.test(dirAttribute)) { + // If the tag has the "dir" attribute specified then its direction is + // neutral because it can be safely used in any context. + dir = goog.i18n.bidi.Dir.NEUTRAL; + } else { + dir = null; + } + } + + return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( + result, dir); +}; + + +/** + * @param {!Object} fixedAttributes + * @param {!Object} defaultAttributes + * @param {!Object=} + * opt_attributes Optional attributes passed to create*(). + * @return {!Object} + * @throws {Error} If opt_attributes contains an attribute with the same name + * as an attribute in fixedAttributes. + * @package + */ +goog.html.SafeHtml.combineAttributes = function( + fixedAttributes, defaultAttributes, opt_attributes) { + var combinedAttributes = {}; + var name; + + for (name in fixedAttributes) { + goog.asserts.assert(name.toLowerCase() == name, 'Must be lower case'); + combinedAttributes[name] = fixedAttributes[name]; + } + for (name in defaultAttributes) { + goog.asserts.assert(name.toLowerCase() == name, 'Must be lower case'); + combinedAttributes[name] = defaultAttributes[name]; + } + + for (name in opt_attributes) { + var nameLower = name.toLowerCase(); + if (nameLower in fixedAttributes) { + throw Error('Cannot override "' + nameLower + '" attribute, got "' + + name + '" with value "' + opt_attributes[name] + '"'); + } + if (nameLower in defaultAttributes) { + delete combinedAttributes[nameLower]; + } + combinedAttributes[name] = opt_attributes[name]; + } + + return combinedAttributes; +}; + + +/** + * A SafeHtml instance corresponding to the HTML doctype: "". + * @const {!goog.html.SafeHtml} + */ +goog.html.SafeHtml.DOCTYPE_HTML = + goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( + '', goog.i18n.bidi.Dir.NEUTRAL); + + +/** + * A SafeHtml instance corresponding to the empty string. + * @const {!goog.html.SafeHtml} + */ +goog.html.SafeHtml.EMPTY = + goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( + '', goog.i18n.bidi.Dir.NEUTRAL); http://git-wip-us.apache.org/repos/asf/flex-falcon/blob/e2cad6e6/externs/GCL/externs/goog/html/safescript.js ---------------------------------------------------------------------- diff --git a/externs/GCL/externs/goog/html/safescript.js b/externs/GCL/externs/goog/html/safescript.js new file mode 100644 index 0000000..83995aa --- /dev/null +++ b/externs/GCL/externs/goog/html/safescript.js @@ -0,0 +1,234 @@ +// Copyright 2014 The Closure Library Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * @fileoverview The SafeScript type and its builders. + * + * TODO(user): Link to document stating type contract. + */ + +goog.provide('goog.html.SafeScript'); + +goog.require('goog.asserts'); +goog.require('goog.string.Const'); +goog.require('goog.string.TypedString'); + + + +/** + * A string-like object which represents JavaScript code and that carries the + * security type contract that its value, as a string, will not cause execution + * of unconstrained attacker controlled code (XSS) when evaluated as JavaScript + * in a browser. + * + * Instances of this type must be created via the factory method + * {@code goog.html.SafeScript.fromConstant} and not by invoking its + * constructor. The constructor intentionally takes no parameters and the type + * is immutable; hence only a default instance corresponding to the empty string + * can be obtained via constructor invocation. + * + * A SafeScript's string representation can safely be interpolated as the + * content of a script element within HTML. The SafeScript string should not be + * escaped before interpolation. + * + * Note that the SafeScript might contain text that is attacker-controlled but + * that text should have been interpolated with appropriate escaping, + * sanitization and/or validation into the right location in the script, such + * that it is highly constrained in its effect (for example, it had to match a + * set of whitelisted words). + * + * A SafeScript can be constructed via security-reviewed unchecked + * conversions. In this case producers of SafeScript must ensure themselves that + * the SafeScript does not contain unsafe script. Note in particular that + * {@code <} is dangerous, even when inside JavaScript strings, and so should + * always be forbidden or JavaScript escaped in user controlled input. For + * example, if {@code </script><script>evil</script>"} were + * interpolated inside a JavaScript string, it would break out of the context + * of the original script element and {@code evil} would execute. Also note + * that within an HTML script (raw text) element, HTML character references, + * such as "<" are not allowed. See + * http://www.w3.org/TR/html5/scripting-1.html#restrictions-for-contents-of-script-elements. + * + * @see goog.html.SafeScript#fromConstant + * @constructor + * @final + * @struct + * @implements {goog.string.TypedString} + */ +goog.html.SafeScript = function() { + /** + * The contained value of this SafeScript. The field has a purposely + * ugly name to make (non-compiled) code that attempts to directly access this + * field stand out. + * @private {string} + */ + this.privateDoNotAccessOrElseSafeScriptWrappedValue_ = ''; + + /** + * A type marker used to implement additional run-time type checking. + * @see goog.html.SafeScript#unwrap + * @const + * @private + */ + this.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = + goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; +}; + + +/** + * @override + * @const + */ +goog.html.SafeScript.prototype.implementsGoogStringTypedString = true; + + +/** + * Type marker for the SafeScript type, used to implement additional + * run-time type checking. + * @const + * @private + */ +goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; + + +/** + * Creates a SafeScript object from a compile-time constant string. + * + * @param {!goog.string.Const} script A compile-time-constant string from which + * to create a SafeScript. + * @return {!goog.html.SafeScript} A SafeScript object initialized to + * {@code script}. + */ +goog.html.SafeScript.fromConstant = function(script) { + var scriptString = goog.string.Const.unwrap(script); + if (scriptString.length === 0) { + return goog.html.SafeScript.EMPTY; + } + return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse( + scriptString); +}; + + +/** + * Returns this SafeScript's value as a string. + * + * IMPORTANT: In code where it is security relevant that an object's type is + * indeed {@code SafeScript}, use {@code goog.html.SafeScript.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 + * the returned instance is of the right type. For example: + * + *
+ * 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.
+ * 
+ * + * @see goog.html.SafeScript#unwrap + * @override + */ +goog.html.SafeScript.prototype.getTypedStringValue = function() { + return this.privateDoNotAccessOrElseSafeScriptWrappedValue_; +}; + + +if (goog.DEBUG) { + /** + * Returns a debug string-representation of this value. + * + * To obtain the actual string value wrapped in a SafeScript, use + * {@code goog.html.SafeScript.unwrap}. + * + * @see goog.html.SafeScript#unwrap + * @override + */ + goog.html.SafeScript.prototype.toString = function() { + return 'SafeScript{' + + this.privateDoNotAccessOrElseSafeScriptWrappedValue_ + '}'; + }; +} + + +/** + * Performs a runtime check that the provided object is indeed a + * SafeScript object, and returns its value. + * + * @param {!goog.html.SafeScript} safeScript The object to extract from. + * @return {string} The safeScript object's contained string, unless + * the run-time type check fails. In that case, {@code unwrap} returns an + * innocuous string, or, if assertions are enabled, throws + * {@code goog.asserts.AssertionError}. + */ +goog.html.SafeScript.unwrap = function(safeScript) { + // Perform additional Run-time type-checking to ensure that + // safeScript 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. + // 3. The object carries a type marker for the expected type. "Faking" an + // object requires a reference to the type marker, which has names intended + // to stand out in code reviews. + if (safeScript instanceof goog.html.SafeScript && + safeScript.constructor === goog.html.SafeScript && + safeScript.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === + goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { + return safeScript.privateDoNotAccessOrElseSafeScriptWrappedValue_; + } else { + goog.asserts.fail( + 'expected object of type SafeScript, got \'' + safeScript + '\''); + return 'type_error:SafeScript'; + } +}; + + +/** + * Package-internal utility method to create SafeScript instances. + * + * @param {string} script The string to initialize the SafeScript object with. + * @return {!goog.html.SafeScript} The initialized SafeScript object. + * @package + */ +goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse = + function(script) { + return new goog.html.SafeScript().initSecurityPrivateDoNotAccessOrElse_( + script); +}; + + +/** + * Called from createSafeScriptSecurityPrivateDoNotAccessOrElse(). This + * method exists only so that the compiler can dead code eliminate static + * fields (like EMPTY) when they're not accessed. + * @param {string} script + * @return {!goog.html.SafeScript} + * @private + */ +goog.html.SafeScript.prototype.initSecurityPrivateDoNotAccessOrElse_ = function( + script) { + this.privateDoNotAccessOrElseSafeScriptWrappedValue_ = script; + return this; +}; + + +/** + * A SafeScript instance corresponding to the empty string. + * @const {!goog.html.SafeScript} + */ +goog.html.SafeScript.EMPTY = + goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse(''); http://git-wip-us.apache.org/repos/asf/flex-falcon/blob/e2cad6e6/externs/GCL/externs/goog/html/safestyle.js ---------------------------------------------------------------------- diff --git a/externs/GCL/externs/goog/html/safestyle.js b/externs/GCL/externs/goog/html/safestyle.js new file mode 100644 index 0000000..2f9f288 --- /dev/null +++ b/externs/GCL/externs/goog/html/safestyle.js @@ -0,0 +1,442 @@ +// Copyright 2014 The Closure Library Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * @fileoverview The SafeStyle type and its builders. + * + * TODO(user): Link to document stating type contract. + */ + +goog.provide('goog.html.SafeStyle'); + +goog.require('goog.array'); +goog.require('goog.asserts'); +goog.require('goog.string'); +goog.require('goog.string.Const'); +goog.require('goog.string.TypedString'); + + + +/** + * A string-like object which represents a sequence of CSS declarations + * ({@code propertyName1: propertyvalue1; propertyName2: propertyValue2; ...}) + * and that carries the security type contract that its value, as a string, + * will not cause untrusted script execution (XSS) when evaluated as CSS in a + * browser. + * + * Instances of this type must be created via the factory methods + * ({@code goog.html.SafeStyle.create} or + * {@code goog.html.SafeStyle.fromConstant}) and not by invoking its + * constructor. The constructor intentionally takes no parameters and the type + * is immutable; hence only a default instance corresponding to the empty string + * can be obtained via constructor invocation. + * + * A SafeStyle's string representation ({@link #getSafeStyleString()}) can + * safely: + *
    + *
  • Be interpolated as the entire content of a *quoted* HTML style + * attribute, or before already existing properties. The SafeStyle string + * *must be HTML-attribute-escaped* (where " and ' are escaped) before + * interpolation. + *
  • Be interpolated as the entire content of a {}-wrapped block within a + * stylesheet, or before already existing properties. The SafeStyle string + * should not be escaped before interpolation. SafeStyle's contract also + * guarantees that the string will not be able to introduce new properties + * or elide existing ones. + *
  • Be assigned to the style property of a DOM node. The SafeStyle string + * should not be escaped before being assigned to the property. + *
+ * + * A SafeStyle may never contain literal angle brackets. Otherwise, it could + * be unsafe to place a SafeStyle into a <style> tag (where it can't + * be HTML escaped). For example, if the SafeStyle containing + * "{@code font: 'foo <style/><script>evil</script>'}" were + * interpolated within a <style> tag, this would then break out of the + * style context into HTML. + * + * A SafeStyle may contain literal single or double quotes, and as such the + * entire style string must be escaped when used in a style attribute (if + * this were not the case, the string could contain a matching quote that + * would escape from the style attribute). + * + * Values of this type must be composable, i.e. for any two values + * {@code style1} and {@code style2} of this type, + * {@code goog.html.SafeStyle.unwrap(style1) + + * goog.html.SafeStyle.unwrap(style2)} must itself be a value that satisfies + * the SafeStyle type constraint. This requirement implies that for any value + * {@code style} of this type, {@code goog.html.SafeStyle.unwrap(style)} must + * not end in a "property value" or "property name" context. For example, + * a value of {@code background:url("} or {@code font-} would not satisfy the + * SafeStyle contract. This is because concatenating such strings with a + * second value that itself does not contain unsafe CSS can result in an + * overall string that does. For example, if {@code javascript:evil())"} is + * appended to {@code background:url("}, the resulting string may result in + * the execution of a malicious script. + * + * TODO(user): Consider whether we should implement UTF-8 interchange + * validity checks and blacklisting of newlines (including Unicode ones) and + * other whitespace characters (\t, \f). Document here if so and also update + * SafeStyle.fromConstant(). + * + * The following example values comply with this type's contract: + *
    + *
  • width: 1em;
    + *
  • height:1em;
    + *
  • width: 1em;height: 1em;
    + *
  • background:url('http://url');
    + *
+ * In addition, the empty string is safe for use in a CSS attribute. + * + * The following example values do NOT comply with this type's contract: + *
    + *
  • background: red
    (missing a trailing semi-colon) + *
  • background:
    (missing a value and a trailing semi-colon) + *
  • 1em
    (missing an attribute name, which provides context for + * the value) + *
+ * + * @see goog.html.SafeStyle#create + * @see goog.html.SafeStyle#fromConstant + * @see http://www.w3.org/TR/css3-syntax/ + * @constructor + * @final + * @struct + * @implements {goog.string.TypedString} + */ +goog.html.SafeStyle = function() { + /** + * The contained value of this SafeStyle. The field has a purposely + * ugly name to make (non-compiled) code that attempts to directly access this + * field stand out. + * @private {string} + */ + this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = ''; + + /** + * A type marker used to implement additional run-time type checking. + * @see goog.html.SafeStyle#unwrap + * @const + * @private + */ + this.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = + goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; +}; + + +/** + * @override + * @const + */ +goog.html.SafeStyle.prototype.implementsGoogStringTypedString = true; + + +/** + * Type marker for the SafeStyle type, used to implement additional + * run-time type checking. + * @const + * @private + */ +goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; + + +/** + * Creates a SafeStyle object from a compile-time constant string. + * + * {@code style} should be in the format + * {@code name: value; [name: value; ...]} and must not have any < or > + * characters in it. This is so that SafeStyle's contract is preserved, + * allowing the SafeStyle to correctly be interpreted as a sequence of CSS + * declarations and without affecting the syntactic structure of any + * surrounding CSS and HTML. + * + * This method performs basic sanity checks on the format of {@code style} + * but does not constrain the format of {@code name} and {@code value}, except + * for disallowing tag characters. + * + * @param {!goog.string.Const} style A compile-time-constant string from which + * to create a SafeStyle. + * @return {!goog.html.SafeStyle} A SafeStyle object initialized to + * {@code style}. + */ +goog.html.SafeStyle.fromConstant = function(style) { + var styleString = goog.string.Const.unwrap(style); + if (styleString.length === 0) { + return goog.html.SafeStyle.EMPTY; + } + goog.html.SafeStyle.checkStyle_(styleString); + goog.asserts.assert(goog.string.endsWith(styleString, ';'), + 'Last character of style string is not \';\': ' + styleString); + goog.asserts.assert(goog.string.contains(styleString, ':'), + 'Style string must contain at least one \':\', to ' + + 'specify a "name: value" pair: ' + styleString); + return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse( + styleString); +}; + + +/** + * Checks if the style definition is valid. + * @param {string} style + * @private + */ +goog.html.SafeStyle.checkStyle_ = function(style) { + goog.asserts.assert(!/[<>]/.test(style), + 'Forbidden characters in style string: ' + style); +}; + + +/** + * Returns this SafeStyle's value as a string. + * + * IMPORTANT: In code where it is security relevant that an object's type is + * indeed {@code SafeStyle}, use {@code goog.html.SafeStyle.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 + * the returned instance is of the right type. For example: + * + *
+ * 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.
+ * 
+ * + * @see goog.html.SafeStyle#unwrap + * @override + */ +goog.html.SafeStyle.prototype.getTypedStringValue = function() { + return this.privateDoNotAccessOrElseSafeStyleWrappedValue_; +}; + + +if (goog.DEBUG) { + /** + * Returns a debug string-representation of this value. + * + * To obtain the actual string value wrapped in a SafeStyle, use + * {@code goog.html.SafeStyle.unwrap}. + * + * @see goog.html.SafeStyle#unwrap + * @override + */ + goog.html.SafeStyle.prototype.toString = function() { + return 'SafeStyle{' + + this.privateDoNotAccessOrElseSafeStyleWrappedValue_ + '}'; + }; +} + + +/** + * Performs a runtime check that the provided object is indeed a + * SafeStyle object, and returns its value. + * + * @param {!goog.html.SafeStyle} safeStyle The object to extract from. + * @return {string} The safeStyle object's contained string, unless + * the run-time type check fails. In that case, {@code unwrap} returns an + * innocuous string, or, if assertions are enabled, throws + * {@code goog.asserts.AssertionError}. + */ +goog.html.SafeStyle.unwrap = function(safeStyle) { + // Perform additional Run-time type-checking to ensure that + // safeStyle 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. + // 3. The object carries a type marker for the expected type. "Faking" an + // object requires a reference to the type marker, which has names intended + // to stand out in code reviews. + if (safeStyle instanceof goog.html.SafeStyle && + safeStyle.constructor === goog.html.SafeStyle && + safeStyle.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === + goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { + return safeStyle.privateDoNotAccessOrElseSafeStyleWrappedValue_; + } else { + goog.asserts.fail( + 'expected object of type SafeStyle, got \'' + safeStyle + '\''); + return 'type_error:SafeStyle'; + } +}; + + +/** + * Package-internal utility method to create SafeStyle instances. + * + * @param {string} style The string to initialize the SafeStyle object with. + * @return {!goog.html.SafeStyle} The initialized SafeStyle object. + * @package + */ +goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse = + function(style) { + return new goog.html.SafeStyle().initSecurityPrivateDoNotAccessOrElse_(style); +}; + + +/** + * Called from createSafeStyleSecurityPrivateDoNotAccessOrElse(). This + * method exists only so that the compiler can dead code eliminate static + * fields (like EMPTY) when they're not accessed. + * @param {string} style + * @return {!goog.html.SafeStyle} + * @private + */ +goog.html.SafeStyle.prototype.initSecurityPrivateDoNotAccessOrElse_ = function( + style) { + this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = style; + return this; +}; + + +/** + * A SafeStyle instance corresponding to the empty string. + * @const {!goog.html.SafeStyle} + */ +goog.html.SafeStyle.EMPTY = + goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(''); + + +/** + * The innocuous string generated by goog.html.SafeUrl.create when passed + * an unsafe value. + * @const {string} + */ +goog.html.SafeStyle.INNOCUOUS_STRING = 'zClosurez'; + + +/** + * Mapping of property names to their values. + * @typedef {!Object} + */ +goog.html.SafeStyle.PropertyMap; + + +/** + * Creates a new SafeStyle object from the properties specified in the map. + * @param {goog.html.SafeStyle.PropertyMap} map Mapping of property names to + * their values, for example {'margin': '1px'}. Names must consist of + * [-_a-zA-Z0-9]. Values might be strings consisting of + * [-,.'"%_!# a-zA-Z0-9], where " and ' must be properly balanced. + * Other values must be wrapped in goog.string.Const. Null value causes + * skipping the property. + * @return {!goog.html.SafeStyle} + * @throws {Error} If invalid name is provided. + * @throws {goog.asserts.AssertionError} If invalid value is provided. With + * disabled assertions, invalid value is replaced by + * goog.html.SafeStyle.INNOCUOUS_STRING. + */ +goog.html.SafeStyle.create = function(map) { + var style = ''; + for (var name in map) { + if (!/^[-_a-zA-Z0-9]+$/.test(name)) { + throw Error('Name allows only [-_a-zA-Z0-9], got: ' + name); + } + var value = map[name]; + if (value == null) { + continue; + } + if (value instanceof goog.string.Const) { + value = goog.string.Const.unwrap(value); + // These characters can be used to change context and we don't want that + // even with const values. + goog.asserts.assert(!/[{;}]/.test(value), 'Value does not allow [{;}].'); + } else if (!goog.html.SafeStyle.VALUE_RE_.test(value)) { + goog.asserts.fail( + 'String value allows only [-,."\'%_!# a-zA-Z0-9], got: ' + value); + value = goog.html.SafeStyle.INNOCUOUS_STRING; + } else if (!goog.html.SafeStyle.hasBalancedQuotes_(value)) { + goog.asserts.fail('String value requires balanced quotes, got: ' + value); + value = goog.html.SafeStyle.INNOCUOUS_STRING; + } + style += name + ':' + value + ';'; + } + if (!style) { + return goog.html.SafeStyle.EMPTY; + } + goog.html.SafeStyle.checkStyle_(style); + return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse( + style); +}; + + +/** + * Checks that quotes (" and ') are properly balanced inside a string. Assumes + * that neither escape (\) nor any other character that could result in + * breaking out of a string parsing context are allowed; + * see http://www.w3.org/TR/css3-syntax/#string-token-diagram. + * @param {string} value Untrusted CSS property value. + * @return {boolean} True if property value is safe with respect to quote + * balancedness. + * @private + */ +goog.html.SafeStyle.hasBalancedQuotes_ = function(value) { + var outsideSingle = true; + var outsideDouble = true; + for (var i = 0; i < value.length; i++) { + var c = value.charAt(i); + if (c == "'" && outsideDouble) { + outsideSingle = !outsideSingle; + } else if (c == '"' && outsideSingle) { + outsideDouble = !outsideDouble; + } + } + return outsideSingle && outsideDouble; +}; + + +// Keep in sync with the error string in create(). +/** + * Regular expression for safe values. + * + * Quotes (" and ') are allowed, but a check must be done elsewhere to ensure + * they're balanced. + * + * ',' allows multiple values to be assigned to the same property + * (e.g. background-attachment or font-family) and hence could allow + * multiple values to get injected, but that should pose no risk of XSS. + * @const {!RegExp} + * @private + */ +goog.html.SafeStyle.VALUE_RE_ = /^[-,."'%_!# a-zA-Z0-9]+$/; + + +/** + * Creates a new SafeStyle object by concatenating the values. + * @param {...(!goog.html.SafeStyle|!Array)} var_args + * SafeStyles to concatenate. + * @return {!goog.html.SafeStyle} + */ +goog.html.SafeStyle.concat = function(var_args) { + var style = ''; + + /** + * @param {!goog.html.SafeStyle|!Array} argument + */ + var addArgument = function(argument) { + if (goog.isArray(argument)) { + goog.array.forEach(argument, addArgument); + } else { + style += goog.html.SafeStyle.unwrap(argument); + } + }; + + goog.array.forEach(arguments, addArgument); + if (!style) { + return goog.html.SafeStyle.EMPTY; + } + return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse( + style); +};