Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(#124): resolve all *.localhost to localhost, and fix ipv6 issue #1114

Merged
merged 2 commits into from
Dec 4, 2023
Merged
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
44 changes: 43 additions & 1 deletion packages/bruno-electron/src/ipc/network/axios-instance.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
const URL = require('url');
const Socket = require('net').Socket;
const axios = require('axios');

const getTld = (hostname) => {
if (!hostname) {
return '';
}

return hostname.substring(hostname.lastIndexOf('.') + 1);
};

const checkConnection = (host, port) =>
new Promise((resolve) => {
const socket = new Socket();

socket.once('connect', () => {
socket.end();
resolve(true);
});

socket.once('error', () => {
resolve(false);
});

// Try to connect to the host and port
socket.connect(port, host);
});

/**
* Function that configures axios with timing interceptors
* Important to note here that the timings are not completely accurate.
Expand All @@ -10,7 +37,22 @@ function makeAxiosInstance() {
/** @type {axios.AxiosInstance} */
const instance = axios.create();

instance.interceptors.request.use((config) => {
instance.interceptors.request.use(async (config) => {
const url = URL.parse(config.url);

// Resolve all *.localhost to localhost and check if it should use IPv6 or IPv4
// RFC: 6761 section 6.3 (https://tools.ietf.org/html/rfc6761#section-6.3)
// @see https://github.com/usebruno/bruno/issues/124
if (getTld(url.hostname) === 'localhost') {
config.headers.Host = url.hostname; // Put original hostname in Host

const portNumber = Number(url.port) || (url.protocol.includes('https') ? 443 : 80);
const useIpv6 = await checkConnection('::1', portNumber);
url.hostname = useIpv6 ? '::1' : '127.0.0.1';
delete url.host; // Clear hostname cache
config.url = URL.format(url);
}

config.headers['request-start-time'] = Date.now();
return config;
});
Expand Down