| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | * |
| 7 | * @flow |
| 8 | */ |
| 9 | |
| 10 | // A javascript: URL can contain leading C0 control or \u0020 SPACE, |
| 11 | // and any newline or tab are filtered out as if they're not part of the URL. |
| 12 | // https://url.spec.whatwg.org/#url-parsing |
| 13 | // Tab or newline are defined as \r\n\t: |
| 14 | // https://infra.spec.whatwg.org/#ascii-tab-or-newline |
| 15 | // A C0 control is a code point in the range \u0000 NULL to \u001F |
| 16 | // INFORMATION SEPARATOR ONE, inclusive: |
| 17 | // https://infra.spec.whatwg.org/#c0-control-or-space |
| 18 | |
| 19 | const isJavaScriptProtocol = |
| 20 | /^[\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; |
| 21 | |
| 22 | function sanitizeURL<T>(url: T): T | string { |
| 23 | // We should never have symbols here because they get filtered out elsewhere. |
| 24 | // eslint-disable-next-line react-internal/safe-string-coercion |
| 25 | if (isJavaScriptProtocol.test('' + (url as any))) { |
| 26 | // Return a different javascript: url that doesn't cause any side-effects and just |
| 27 | // throws if ever visited. |
| 28 | // eslint-disable-next-line no-script-url |
| 29 | return "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')"; |
| 30 | } |
| 31 | return url; |
| 32 | } |
| 33 | |
| 34 | export default sanitizeURL; |