forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsanitation.js
359 lines (330 loc) · 9.52 KB
/
sanitation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/**
* Copyright 2019 The AMP HTML 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.
*/
import {dict, map} from './utils/object';
import {isAmp4Email} from './format';
import {isUrlAttribute} from './url-rewrite';
import {startsWith} from './string';
/** @const {string} */
export const BIND_PREFIX = 'data-amp-bind-';
/** @const {string} */
export const DIFF_KEY = 'i-amphtml-key';
/** @const {string} */
export const DIFF_IGNORE = 'i-amphtml-ignore';
/**
* Map of AMP element tag name to attributes that, if changed, require
* replacement of the original element.
* @const {!Object<string, !Array<string>>}
*/
export const DIFFABLE_AMP_ELEMENTS = {
'AMP-IMG': ['src', 'srcset', 'layout', 'width', 'height'],
};
/**
* Most AMP elements don't support ad hoc mutation and should be replaced
* instead of DOM diff'ed. Some AMP elements can be manually diff'ed.
*
* Both of these cases require a special attribute to enable special handling in
* the diffing algorithm. This function sets the appropriate attribute.
*
* @param {!Element} element
* @param {function(): string} generateKey
*/
export function markElementForDiffing(element, generateKey) {
const isAmpElement = startsWith(element.tagName, 'AMP-');
// Don't DOM diff nodes with bindings because amp-bind scans newly rendered
// elements and discards _all_ old elements _before_ diffing, so preserving
// old elements would cause loss of functionality.
const hasBinding = element.hasAttribute('i-amphtml-binding');
if (!hasBinding && DIFFABLE_AMP_ELEMENTS[element.tagName]) {
// Nodes marked with "ignore" will not be touched (old element stays).
// We want this to allow manual diffing afterwards.
element.setAttribute(DIFF_IGNORE, '');
} else if (hasBinding || isAmpElement) {
// Diff'ed node pairs with unique "key" will always be replaced.
if (!element.hasAttribute(DIFF_KEY)) {
element.setAttribute(DIFF_KEY, generateKey());
}
}
}
/**
* @const {!Object<string, boolean>}
* @see https://github.com/ampproject/amphtml/blob/master/spec/amp-html-format.md
*/
export const BLACKLISTED_TAGS = {
'applet': true,
'audio': true,
'base': true,
'embed': true,
'frame': true,
'frameset': true,
'iframe': true,
'img': true,
'link': true,
'meta': true,
'object': true,
'style': true,
'video': true,
};
/**
* AMP elements allowed in AMP4EMAIL, modulo:
* - amp-list, which cannot be nested.
* - amp-lightbox and amp-image-lightbox, which are deprecated.
* @const {!Object<string, boolean>}
* @see https://github.com/ampproject/amphtml/blob/master/spec/email/amp-email-components.md
*/
export const EMAIL_WHITELISTED_AMP_TAGS = {
'amp-accordion': true,
'amp-anim': true,
'amp-bind-macro': true,
'amp-carousel': true,
'amp-fit-text': true,
'amp-img': true,
'amp-layout': true,
'amp-selector': true,
'amp-sidebar': true,
'amp-state': true,
'amp-timeago': true,
};
/**
* Whitelist of tags allowed in triple mustache e.g. {{{name}}}.
* Very restrictive by design since the triple mustache renders unescaped HTML
* which, unlike double mustache, won't be processed by the AMP Validator.
* @const {!Array<string>}
*/
export const TRIPLE_MUSTACHE_WHITELISTED_TAGS = [
'a',
'b',
'br',
'caption',
'colgroup',
'code',
'del',
'div',
'em',
'hr',
'i',
'ins',
'li',
'mark',
'ol',
'p',
'q',
's',
'small',
'span',
'strong',
'sub',
'sup',
'table',
'tbody',
'time',
'td',
'th',
'thead',
'tfoot',
'tr',
'u',
'ul',
];
/**
* Tag-agnostic attribute whitelisted used by both Caja and DOMPurify.
* @const {!Array<string>}
*/
export const WHITELISTED_ATTRS = [
// AMP-only attributes that don't exist in HTML.
'amp-fx',
'fallback',
'heights',
'layout',
'min-font-size',
'max-font-size',
'on',
'option',
'placeholder',
// Attributes related to amp-form.
'submitting',
'submit-success',
'submit-error',
'validation-for',
'verify-error',
'visible-when-invalid',
// HTML attributes that are scrubbed by Caja but we handle specially.
'href',
'style',
// Attributes for amp-bind that exist in "[foo]" form.
'text',
// Attributes for amp-subscriptions.
'subscriptions-action',
'subscriptions-actions',
'subscriptions-decorate',
'subscriptions-dialog',
'subscriptions-display',
'subscriptions-section',
'subscriptions-service',
// A global attribute used for structured data.
// https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemprop
'itemprop',
];
/**
* Attributes that are only whitelisted for specific, non-AMP elements.
* @const {!Object<string, !Array<string>>}
*/
export const WHITELISTED_ATTRS_BY_TAGS = {
'a': ['rel', 'target'],
'div': ['template'],
'form': ['action-xhr', 'verify-xhr', 'custom-validation-reporting', 'target'],
'input': ['mask-output'],
'template': ['type'],
'textarea': ['autoexpand'],
};
/** @const {!Array<string>} */
export const WHITELISTED_TARGETS = ['_top', '_blank'];
/** @const {!Array<string>} */
const BLACKLISTED_ATTR_VALUES = Object.freeze([
/*eslint no-script-url: 0*/ 'javascript:',
/*eslint no-script-url: 0*/ 'vbscript:',
/*eslint no-script-url: 0*/ 'data:',
/*eslint no-script-url: 0*/ '<script',
/*eslint no-script-url: 0*/ '</script',
]);
/** @const {!Object<string, !Object<string, !RegExp>>} */
const BLACKLISTED_TAG_SPECIFIC_ATTR_VALUES = Object.freeze(
dict({
'input': {
'type': /(?:image|button)/i,
},
})
);
/**
* Rules in addition to BLACKLISTED_TAG_SPECIFIC_ATTR_VALUES for AMP4EMAIL.
* @const {!Object<string, !Object<string, !RegExp>>}
*/
const EMAIL_BLACKLISTED_TAG_SPECIFIC_ATTR_VALUES = Object.freeze(
dict({
'input': {
'type': /(?:button|file|image|password)/i,
},
})
);
/** @const {!Array<string>} */
const BLACKLISTED_FIELDS_ATTR = Object.freeze([
'form',
'formaction',
'formmethod',
'formtarget',
'formnovalidate',
'formenctype',
]);
/** @const {!Object<string, !Array<string>>} */
const BLACKLISTED_TAG_SPECIFIC_ATTRS = Object.freeze(
dict({
'input': BLACKLISTED_FIELDS_ATTR,
'textarea': BLACKLISTED_FIELDS_ATTR,
'select': BLACKLISTED_FIELDS_ATTR,
})
);
/**
* Rules in addition to BLACKLISTED_TAG_SPECIFIC_ATTRS for AMP4EMAIL.
* @const {!Object<string, !Array<string>>}
*/
const EMAIL_BLACKLISTED_TAG_SPECIFIC_ATTRS = Object.freeze(
dict({
'amp-anim': ['controls'],
'form': ['name'],
})
);
/**
* Test for invalid `style` attribute values.
*
* !important avoids overriding AMP styles, while `position:fixed|sticky` is a
* FixedLayer limitation (it only scans the style[amp-custom] stylesheet
* for potential fixed/sticky elements). Note that the latter can be
* circumvented with CSS comments -- not a big deal.
*
* @const {!RegExp}
*/
const INVALID_INLINE_STYLE_REGEX = /!important|position\s*:\s*fixed|position\s*:\s*sticky/i;
/**
* Whether the attribute/value is valid.
* @param {string} tagName Lowercase tag name.
* @param {string} attrName Lowercase attribute name.
* @param {string} attrValue attribute value
* @param {!Document} doc
* @param {boolean} opt_purify Is true, skips some attribute sanitizations
* that are already covered by DOMPurify.
* @return {boolean}
*/
export function isValidAttr(
tagName,
attrName,
attrValue,
doc,
opt_purify = false
) {
if (!opt_purify) {
// "on*" attributes are not allowed.
if (startsWith(attrName, 'on') && attrName != 'on') {
return false;
}
// No attributes with "javascript" or other blacklisted substrings in them.
if (attrValue) {
const normalized = attrValue.toLowerCase().replace(/[\s,\u0000]+/g, '');
for (let i = 0; i < BLACKLISTED_ATTR_VALUES.length; i++) {
if (normalized.indexOf(BLACKLISTED_ATTR_VALUES[i]) >= 0) {
return false;
}
}
}
}
// Don't allow certain inline style values.
if (attrName == 'style') {
return !INVALID_INLINE_STYLE_REGEX.test(attrValue);
}
// Don't allow CSS class names with internal AMP prefix.
if (attrName == 'class' && attrValue && /(^|\W)i-amphtml-/i.test(attrValue)) {
return false;
}
// Don't allow '__amp_source_origin' in URLs.
if (isUrlAttribute(attrName) && /__amp_source_origin/.test(attrValue)) {
return false;
}
const isEmail = isAmp4Email(doc);
// Remove blacklisted attributes from specific tags e.g. input[formaction].
const attrBlacklist = Object.assign(
map(),
BLACKLISTED_TAG_SPECIFIC_ATTRS,
isEmail ? EMAIL_BLACKLISTED_TAG_SPECIFIC_ATTRS : {}
)[tagName];
if (attrBlacklist && attrBlacklist.indexOf(attrName) != -1) {
return false;
}
// Remove blacklisted values for specific attributes for specific tags
// e.g. input[type=image].
const attrValueBlacklist = Object.assign(
map(),
BLACKLISTED_TAG_SPECIFIC_ATTR_VALUES,
isEmail ? EMAIL_BLACKLISTED_TAG_SPECIFIC_ATTR_VALUES : {}
)[tagName];
if (attrValueBlacklist) {
const blacklistedValuesRegex = attrValueBlacklist[attrName];
if (
blacklistedValuesRegex &&
attrValue.search(blacklistedValuesRegex) != -1
) {
return false;
}
}
return true;
}