forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sanitizeURL.js
58 lines (52 loc) · 1.87 KB
/
sanitizeURL.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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import invariant from 'shared/invariant';
import {
disableJavaScriptURLs,
enableTrustedTypesIntegration,
} from 'shared/ReactFeatureFlags';
// A javascript: URL can contain leading C0 control or \u0020 SPACE,
// and any newline or tab are filtered out as if they're not part of the URL.
// https://url.spec.whatwg.org/#url-parsing
// Tab or newline are defined as \r\n\t:
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
// A C0 control is a code point in the range \u0000 NULL to \u001F
// INFORMATION SEPARATOR ONE, inclusive:
// https://infra.spec.whatwg.org/#c0-control-or-space
/* eslint-disable max-len */
const isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
let didWarn = false;
function sanitizeURL(url: any): any {
if (
!enableTrustedTypesIntegration ||
typeof trustedTypes === 'undefined' ||
!trustedTypes.isScriptURL(url)
) {
// Coerce to a string, unless we know it's an immutable TrustedScriptURL object.
url = '' + url;
}
if (disableJavaScriptURLs) {
invariant(
!isJavaScriptProtocol.test(url),
'React has blocked a javascript: URL as a security precaution.',
);
} else if (__DEV__) {
if (!didWarn && isJavaScriptProtocol.test(url)) {
didWarn = true;
console.error(
'A future version of React will block javascript: URLs as a security precaution. ' +
'Use event handlers instead if you can. If you need to generate unsafe HTML try ' +
'using dangerouslySetInnerHTML instead. React was passed %s.',
JSON.stringify(url),
);
}
}
return url;
}
export default sanitizeURL;