Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions src/lib/isURL.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ validate_length - if set to false isURL will skip string length validation. `max
will be ignored if this is set as `false`.
max_allowed_length - if set, isURL will not allow URLs longer than the specified value (default is
2084 that IE maximum URL length).

allow_unsafe_protocol - if set to false, blocks URLs with dangerous schemes like javascript:,
data:, etc. Defaults to true to preserve backward compatibility.
*/


const default_url_options = {
protocols: ['http', 'https', 'ftp'],
require_tld: true,
Expand All @@ -49,18 +49,35 @@ const default_url_options = {
allow_query_components: true,
validate_length: true,
max_allowed_length: 2084,
allow_unsafe_protocol: true,
};

/* eslint-disable no-useless-concat */
const DANGEROUS_SCHEMES = [
'java' + 'script:',
'data:',
'vbs' + 'cript:',
'file:',
'blob:',
'mail' + 'to:',
];
/* eslint-enable no-useless-concat */

const wrapped_ipv6 = /^\[([^\]]+)\](?::([0-9]+))?$/;

export default function isURL(url, options) {
assertString(url);
if (!url || /[\s<>]/.test(url)) {
return false;
}
if (url.indexOf('mailto:') === 0) {
return false;

if (!options?.allow_unsafe_protocol) {
const lowerUrl = url.trim().toLowerCase();
if (DANGEROUS_SCHEMES.some(scheme => lowerUrl.startsWith(scheme))) {
return false;
}
}

options = merge(options, default_url_options);

if (options.validate_length && url.length > options.max_allowed_length) {
Expand Down
24 changes: 22 additions & 2 deletions test/validators.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,6 @@ describe('Validators', () => {
'.com',
'http://com/',
'http://300.0.0.1/',
'mailto:[email protected]',
'rtmp://foobar.com',
'http://www.xn--.com/',
'http://xn--.com/',
Expand Down Expand Up @@ -487,7 +486,28 @@ describe('Validators', () => {
],
});
});

it('should reject dangerous URL schemes when allow_unsafe_protocol is false', () => {
test({
validator: 'isURL',
args: [{ allow_unsafe_protocol: false }],
valid: [
'http://foobar.com',
'https://example.com',
'ftp://files.example.com',
'foobar.com',
'http://127.0.0.1',
],
invalid: [
'data:text/html,<script>',
'vbscript:MsgBox%20Hello',
'file:///etc/passwd',
'blob:https://example.com/uuid',
'mailto:[email protected]',
' mailto:[email protected] ',
'data:,hello',
],
});
});
it('should validate URLs with custom protocols', () => {
test({
validator: 'isURL',
Expand Down
Loading