From b9e9fb4fa0ab1e0f4bc9ac8d8cf493f5f8507dc3 Mon Sep 17 00:00:00 2001 From: Dmitriy Mozgovoy Date: Wed, 27 Apr 2022 12:30:50 +0300 Subject: [PATCH] Enhanced protocol parsing implementation to fix #4633; (#4639) Added unit tests; Co-authored-by: Jay --- lib/adapters/xhr.js | 4 ++-- lib/helpers/parseProtocol.js | 6 ++++++ test/unit/helpers/parseProtocol.js | 24 ++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 lib/helpers/parseProtocol.js create mode 100644 test/unit/helpers/parseProtocol.js diff --git a/lib/adapters/xhr.js b/lib/adapters/xhr.js index d1a7b804b5..76d7e7ac1d 100644 --- a/lib/adapters/xhr.js +++ b/lib/adapters/xhr.js @@ -10,6 +10,7 @@ var isURLSameOrigin = require('./../helpers/isURLSameOrigin'); var transitionalDefaults = require('../defaults/transitional'); var AxiosError = require('../core/AxiosError'); var CanceledError = require('../cancel/CanceledError'); +var parseProtocol = require('../helpers/parseProtocol'); module.exports = function xhrAdapter(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { @@ -207,8 +208,7 @@ module.exports = function xhrAdapter(config) { requestData = null; } - var tokens = fullPath.split(':', 2); - var protocol = tokens.length > 1 && tokens[0]; + var protocol = parseProtocol(fullPath); if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) { reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); diff --git a/lib/helpers/parseProtocol.js b/lib/helpers/parseProtocol.js new file mode 100644 index 0000000000..10f3f0297d --- /dev/null +++ b/lib/helpers/parseProtocol.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function parseProtocol(url) { + var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ''; +}; diff --git a/test/unit/helpers/parseProtocol.js b/test/unit/helpers/parseProtocol.js new file mode 100644 index 0000000000..0900419647 --- /dev/null +++ b/test/unit/helpers/parseProtocol.js @@ -0,0 +1,24 @@ +var assert = require('assert'); +var utils = require('../../../lib/utils'); +var parseProtocol = require('../../../lib/helpers/parseProtocol'); + +describe('helpers::parseProtocol', function () { + it('should parse protocol part if it exists', function () { + utils.forEach({ + 'http://username:password@example.com/': 'http', + 'ftp:google.com': 'ftp', + 'sms:+15105550101?body=hello%20there': 'sms', + 'tel:0123456789' : 'tel', + '//google.com': '', + 'google.com': '', + 'admin://etc/default/grub' : 'admin', + 'stratum+tcp://server:port': 'stratum+tcp', + '/api/resource:customVerb': '', + 'https://stackoverflow.com/questions/': 'https', + 'mailto:jsmith@example.com' : 'mailto', + 'chrome-extension://1234/.html' : 'chrome-extension' + }, (expectedProtocol, url) => { + assert.strictEqual(parseProtocol(url), expectedProtocol); + }); + }); +});