2 * @license AngularJS v1.5.8
3 * (c) 2010-2016 Google, Inc. http://angularjs.org
6 (function(window, angular) {'use strict';
8 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
9 * Any commits to this file should be reviewed with security in mind. *
10 * Changes to this file can potentially create security vulnerabilities. *
11 * An approval from 2 Core members with history of modifying *
12 * this file is required. *
14 * Does the change somehow allow for arbitrary javascript to be executed? *
15 * Or allows for someone to change the prototype of built-in objects? *
16 * Or gives undesired access to variables likes document or window? *
17 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
19 var $sanitizeMinErr = angular.$$minErr('$sanitize');
27 var htmlSanitizeWriter;
36 * The `ngSanitize` module provides functionality to sanitize HTML.
39 * <div doc-module-components="ngSanitize"></div>
41 * See {@link ngSanitize.$sanitize `$sanitize`} for usage.
50 * Sanitizes an html string by stripping all potentially dangerous tokens.
52 * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are
53 * then serialized back to properly escaped html string. This means that no unsafe input can make
54 * it into the returned string.
56 * The whitelist for URL sanitization of attribute values is configured using the functions
57 * `aHrefSanitizationWhitelist` and `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider
58 * `$compileProvider`}.
60 * The input may also contain SVG markup if this is enabled via {@link $sanitizeProvider}.
62 * @param {string} html HTML input.
63 * @returns {string} Sanitized HTML.
66 <example module="sanitizeExample" deps="angular-sanitize.js">
67 <file name="index.html">
69 angular.module('sanitizeExample', ['ngSanitize'])
70 .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
72 '<p style="color:blue">an html\n' +
73 '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
75 $scope.deliberatelyTrustDangerousSnippet = function() {
76 return $sce.trustAsHtml($scope.snippet);
80 <div ng-controller="ExampleController">
81 Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
89 <tr id="bind-html-with-sanitize">
91 <td>Automatically uses $sanitize</td>
92 <td><pre><div ng-bind-html="snippet"><br/></div></pre></td>
93 <td><div ng-bind-html="snippet"></div></td>
95 <tr id="bind-html-with-trust">
97 <td>Bypass $sanitize by explicitly trusting the dangerous value</td>
99 <pre><div ng-bind-html="deliberatelyTrustDangerousSnippet()">
102 <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
104 <tr id="bind-default">
106 <td>Automatically escapes</td>
107 <td><pre><div ng-bind="snippet"><br/></div></pre></td>
108 <td><div ng-bind="snippet"></div></td>
113 <file name="protractor.js" type="protractor">
114 it('should sanitize the html snippet by default', function() {
115 expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
116 toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
119 it('should inline raw snippet if bound to a trusted value', function() {
120 expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).
121 toBe("<p style=\"color:blue\">an html\n" +
122 "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
126 it('should escape snippet without any filter', function() {
127 expect(element(by.css('#bind-default div')).getInnerHtml()).
128 toBe("<p style=\"color:blue\">an html\n" +
129 "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
130 "snippet</p>");
133 it('should update', function() {
134 element(by.model('snippet')).clear();
135 element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
136 expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
137 toBe('new <b>text</b>');
138 expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(
139 'new <b onclick="alert(1)">text</b>');
140 expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(
141 "new <b onclick=\"alert(1)\">text</b>");
150 * @name $sanitizeProvider
153 * Creates and configures {@link $sanitize} instance.
155 function $SanitizeProvider() {
156 var svgEnabled = false;
158 this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
160 extend(validElements, svgElements);
162 return function(html) {
164 htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {
165 return !/^unsafe:/.test($$sanitizeUri(uri, isImage));
174 * @name $sanitizeProvider#enableSvg
178 * Enables a subset of svg to be supported by the sanitizer.
180 * <div class="alert alert-warning">
181 * <p>By enabling this setting without taking other precautions, you might expose your
182 * application to click-hijacking attacks. In these attacks, sanitized svg elements could be positioned
183 * outside of the containing element and be rendered over other elements on the page (e.g. a login
184 * link). Such behavior can then result in phishing incidents.</p>
186 * <p>To protect against these, explicitly setup `overflow: hidden` css rule for all potential svg
187 * tags within the sanitized content:</p>
192 * .rootOfTheIncludedContent svg {
193 * overflow: hidden !important;
198 * @param {boolean=} flag Enable or disable SVG support in the sanitizer.
199 * @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called
200 * without an argument or self for chaining otherwise.
202 this.enableSvg = function(enableSvg) {
203 if (isDefined(enableSvg)) {
204 svgEnabled = enableSvg;
211 //////////////////////////////////////////////////////////////////////////////////////////////////
213 //////////////////////////////////////////////////////////////////////////////////////////////////
216 extend = angular.extend;
217 forEach = angular.forEach;
218 isDefined = angular.isDefined;
219 lowercase = angular.lowercase;
222 htmlParser = htmlParserImpl;
223 htmlSanitizeWriter = htmlSanitizeWriterImpl;
225 // Regular Expressions for parsing tags and attributes
226 var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
227 // Match everything outside of normal chars and " (quote character)
228 NON_ALPHANUMERIC_REGEXP = /([^\#-~ |!])/g;
231 // Good source of info about elements and attributes
232 // http://dev.w3.org/html5/spec/Overview.html#semantics
233 // http://simon.html5.org/html-elements
235 // Safe Void Elements - HTML5
236 // http://dev.w3.org/html5/spec/Overview.html#void-elements
237 var voidElements = toMap("area,br,col,hr,img,wbr");
239 // Elements that you can, intentionally, leave open (and which close themselves)
240 // http://dev.w3.org/html5/spec/Overview.html#optional-tags
241 var optionalEndTagBlockElements = toMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),
242 optionalEndTagInlineElements = toMap("rp,rt"),
243 optionalEndTagElements = extend({},
244 optionalEndTagInlineElements,
245 optionalEndTagBlockElements);
247 // Safe Block Elements - HTML5
248 var blockElements = extend({}, optionalEndTagBlockElements, toMap("address,article," +
249 "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," +
250 "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul"));
252 // Inline Elements - HTML5
253 var inlineElements = extend({}, optionalEndTagInlineElements, toMap("a,abbr,acronym,b," +
254 "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," +
255 "samp,small,span,strike,strong,sub,sup,time,tt,u,var"));
258 // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements
259 // Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted.
260 // They can potentially allow for arbitrary javascript to be executed. See #11290
261 var svgElements = toMap("circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph," +
262 "hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline," +
263 "radialGradient,rect,stop,svg,switch,text,title,tspan");
265 // Blocked Elements (will be stripped)
266 var blockedElements = toMap("script,style");
268 var validElements = extend({},
272 optionalEndTagElements);
274 //Attributes that have href and hence need to be sanitized
275 var uriAttrs = toMap("background,cite,href,longdesc,src,xlink:href");
277 var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +
278 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +
279 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +
280 'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' +
281 'valign,value,vspace,width');
283 // SVG attributes (without "id" and "name" attributes)
284 // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes
285 var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
286 'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' +
287 'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' +
288 'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' +
289 'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' +
290 'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' +
291 'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' +
292 'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' +
293 'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' +
294 'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' +
295 'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' +
296 'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' +
297 'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' +
298 'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' +
299 'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true);
301 var validAttrs = extend({},
306 function toMap(str, lowercaseKeys) {
307 var obj = {}, items = str.split(','), i;
308 for (i = 0; i < items.length; i++) {
309 obj[lowercaseKeys ? lowercase(items[i]) : items[i]] = true;
314 var inertBodyElement;
317 if (window.document && window.document.implementation) {
318 doc = window.document.implementation.createHTMLDocument("inert");
320 throw $sanitizeMinErr('noinert', "Can't create an inert html document");
322 var docElement = doc.documentElement || doc.getDocumentElement();
323 var bodyElements = docElement.getElementsByTagName('body');
325 // usually there should be only one body element in the document, but IE doesn't have any, so we need to create one
326 if (bodyElements.length === 1) {
327 inertBodyElement = bodyElements[0];
329 var html = doc.createElement('html');
330 inertBodyElement = doc.createElement('body');
331 html.appendChild(inertBodyElement);
332 doc.appendChild(html);
338 * htmlParser(htmlString, {
339 * start: function(tag, attrs) {},
340 * end: function(tag) {},
341 * chars: function(text) {},
342 * comment: function(text) {}
345 * @param {string} html string
346 * @param {object} handler
348 function htmlParserImpl(html, handler) {
349 if (html === null || html === undefined) {
351 } else if (typeof html !== 'string') {
354 inertBodyElement.innerHTML = html;
357 var mXSSAttempts = 5;
359 if (mXSSAttempts === 0) {
360 throw $sanitizeMinErr('uinput', "Failed to sanitize html because the input is unstable");
364 // strip custom-namespaced attributes on IE<=11
365 if (window.document.documentMode) {
366 stripCustomNsAttrs(inertBodyElement);
368 html = inertBodyElement.innerHTML; //trigger mXSS
369 inertBodyElement.innerHTML = html;
370 } while (html !== inertBodyElement.innerHTML);
372 var node = inertBodyElement.firstChild;
374 switch (node.nodeType) {
375 case 1: // ELEMENT_NODE
376 handler.start(node.nodeName.toLowerCase(), attrToMap(node.attributes));
379 handler.chars(node.textContent);
384 if (!(nextNode = node.firstChild)) {
385 if (node.nodeType == 1) {
386 handler.end(node.nodeName.toLowerCase());
388 nextNode = node.nextSibling;
390 while (nextNode == null) {
391 node = node.parentNode;
392 if (node === inertBodyElement) break;
393 nextNode = node.nextSibling;
394 if (node.nodeType == 1) {
395 handler.end(node.nodeName.toLowerCase());
403 while (node = inertBodyElement.firstChild) {
404 inertBodyElement.removeChild(node);
408 function attrToMap(attrs) {
410 for (var i = 0, ii = attrs.length; i < ii; i++) {
412 map[attr.name] = attr.value;
419 * Escapes all potentially dangerous characters, so that the
420 * resulting string can be safely inserted into attribute or
423 * @returns {string} escaped text
425 function encodeEntities(value) {
427 replace(/&/g, '&').
428 replace(SURROGATE_PAIR_REGEXP, function(value) {
429 var hi = value.charCodeAt(0);
430 var low = value.charCodeAt(1);
431 return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
433 replace(NON_ALPHANUMERIC_REGEXP, function(value) {
434 return '&#' + value.charCodeAt(0) + ';';
436 replace(/</g, '<').
437 replace(/>/g, '>');
441 * create an HTML/XML writer which writes to buffer
442 * @param {Array} buf use buf.join('') to get out sanitized html string
443 * @returns {object} in the form of {
444 * start: function(tag, attrs) {},
445 * end: function(tag) {},
446 * chars: function(text) {},
447 * comment: function(text) {}
450 function htmlSanitizeWriterImpl(buf, uriValidator) {
451 var ignoreCurrentElement = false;
452 var out = bind(buf, buf.push);
454 start: function(tag, attrs) {
455 tag = lowercase(tag);
456 if (!ignoreCurrentElement && blockedElements[tag]) {
457 ignoreCurrentElement = tag;
459 if (!ignoreCurrentElement && validElements[tag] === true) {
462 forEach(attrs, function(value, key) {
463 var lkey = lowercase(key);
464 var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');
465 if (validAttrs[lkey] === true &&
466 (uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
470 out(encodeEntities(value));
478 tag = lowercase(tag);
479 if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) {
484 if (tag == ignoreCurrentElement) {
485 ignoreCurrentElement = false;
488 chars: function(chars) {
489 if (!ignoreCurrentElement) {
490 out(encodeEntities(chars));
498 * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' attribute to declare
499 * ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). This is undesirable since we don't want
500 * to allow any of these custom attributes. This method strips them all.
502 * @param node Root element to process
504 function stripCustomNsAttrs(node) {
505 if (node.nodeType === window.Node.ELEMENT_NODE) {
506 var attrs = node.attributes;
507 for (var i = 0, l = attrs.length; i < l; i++) {
508 var attrNode = attrs[i];
509 var attrName = attrNode.name.toLowerCase();
510 if (attrName === 'xmlns:ns1' || attrName.lastIndexOf('ns1:', 0) === 0) {
511 node.removeAttributeNode(attrNode);
518 var nextNode = node.firstChild;
520 stripCustomNsAttrs(nextNode);
523 nextNode = node.nextSibling;
525 stripCustomNsAttrs(nextNode);
530 function sanitizeText(chars) {
532 var writer = htmlSanitizeWriter(buf, noop);
538 // define ngSanitize module and register $sanitize service
539 angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
547 * Finds links in text input and turns them into html links. Supports `http/https/ftp/mailto` and
548 * plain email address links.
550 * Requires the {@link ngSanitize `ngSanitize`} module to be installed.
552 * @param {string} text Input text.
553 * @param {string} target Window (`_blank|_self|_parent|_top`) or named frame to open links in.
554 * @param {object|function(url)} [attributes] Add custom attributes to the link element.
558 * - `object`: A map of attributes
559 * - `function`: Takes the url as a parameter and returns a map of attributes
561 * If the map of attributes contains a value for `target`, it overrides the value of
562 * the target parameter.
565 * @returns {string} Html-linkified and {@link $sanitize sanitized} text.
568 <span ng-bind-html="linky_expression | linky"></span>
571 <example module="linkyExample" deps="angular-sanitize.js">
572 <file name="index.html">
573 <div ng-controller="ExampleController">
574 Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
581 <tr id="linky-filter">
582 <td>linky filter</td>
584 <pre><div ng-bind-html="snippet | linky"><br></div></pre>
587 <div ng-bind-html="snippet | linky"></div>
590 <tr id="linky-target">
591 <td>linky target</td>
593 <pre><div ng-bind-html="snippetWithSingleURL | linky:'_blank'"><br></div></pre>
596 <div ng-bind-html="snippetWithSingleURL | linky:'_blank'"></div>
599 <tr id="linky-custom-attributes">
600 <td>linky custom attributes</td>
602 <pre><div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"><br></div></pre>
605 <div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"></div>
608 <tr id="escaped-html">
610 <td><pre><div ng-bind="snippet"><br></div></pre></td>
611 <td><div ng-bind="snippet"></div></td>
615 <file name="script.js">
616 angular.module('linkyExample', ['ngSanitize'])
617 .controller('ExampleController', ['$scope', function($scope) {
619 'Pretty text with some links:\n'+
620 'http://angularjs.org/,\n'+
621 'mailto:us@somewhere.org,\n'+
622 'another@somewhere.org,\n'+
623 'and one more: ftp://127.0.0.1/.';
624 $scope.snippetWithSingleURL = 'http://angularjs.org/';
627 <file name="protractor.js" type="protractor">
628 it('should linkify the snippet with urls', function() {
629 expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
630 toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +
631 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
632 expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
635 it('should not linkify snippet without the linky filter', function() {
636 expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
637 toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +
638 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
639 expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
642 it('should update', function() {
643 element(by.model('snippet')).clear();
644 element(by.model('snippet')).sendKeys('new http://link.');
645 expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
646 toBe('new http://link.');
647 expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
648 expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
649 .toBe('new http://link.');
652 it('should work with the target property', function() {
653 expect(element(by.id('linky-target')).
654 element(by.binding("snippetWithSingleURL | linky:'_blank'")).getText()).
655 toBe('http://angularjs.org/');
656 expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
659 it('should optionally add custom attributes', function() {
660 expect(element(by.id('linky-custom-attributes')).
661 element(by.binding("snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}")).getText()).
662 toBe('http://angularjs.org/');
663 expect(element(by.css('#linky-custom-attributes a')).getAttribute('rel')).toEqual('nofollow');
668 angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
669 var LINKY_URL_REGEXP =
670 /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i,
671 MAILTO_REGEXP = /^mailto:/i;
673 var linkyMinErr = angular.$$minErr('linky');
674 var isDefined = angular.isDefined;
675 var isFunction = angular.isFunction;
676 var isObject = angular.isObject;
677 var isString = angular.isString;
679 return function(text, target, attributes) {
680 if (text == null || text === '') return text;
681 if (!isString(text)) throw linkyMinErr('notstring', 'Expected string but received: {0}', text);
684 isFunction(attributes) ? attributes :
685 isObject(attributes) ? function getAttributesObject() {return attributes;} :
686 function getEmptyAttributesObject() {return {};};
693 while ((match = raw.match(LINKY_URL_REGEXP))) {
694 // We can not end in these as they are sometimes found at the end of the sentence
696 // if we did not match ftp/http/www/mailto then assume mailto
697 if (!match[2] && !match[4]) {
698 url = (match[3] ? 'http://' : 'mailto:') + url;
701 addText(raw.substr(0, i));
702 addLink(url, match[0].replace(MAILTO_REGEXP, ''));
703 raw = raw.substring(i + match[0].length);
706 return $sanitize(html.join(''));
708 function addText(text) {
712 html.push(sanitizeText(text));
715 function addLink(url, text) {
716 var key, linkAttributes = attributesFn(url);
719 for (key in linkAttributes) {
720 html.push(key + '="' + linkAttributes[key] + '" ');
723 if (isDefined(target) && !('target' in linkAttributes)) {
724 html.push('target="',
729 url.replace(/"/g, '"'),
738 })(window, window.angular);