Skip to content

Commit

Permalink
feat: prefer subdomain gw on localhost
Browse files Browse the repository at this point in the history
  • Loading branch information
lidel committed Aug 28, 2020
1 parent dd6ac9d commit 7c8b455
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/bundles/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import toUri from 'multiaddr-to-uri'
import { createAsyncResourceBundle, createSelector } from 'redux-bundler'

const DEFAULT_URI = 'https://ipfs.io'
const LOCAL_HOSTNAMES = ['127.0.0.1', '[::1]', '0.0.0.0', '[::]']

const bundle = createAsyncResourceBundle({
name: 'config',
Expand All @@ -20,10 +21,22 @@ const bundle = createAsyncResourceBundle({
conf = JSON.stringify(rawConf, null, '\t')
}

// More info: https://github.com/ipfs-shipyard/ipfs-webui/issues/1490#issuecomment-671633602
const config = JSON.parse(conf)
const url = getURLFromAddress('Gateway', config) || DEFAULT_URI

// Normalize local hostnames to localhost
// to leverage subdomain gateway, if present
// https://github.com/ipfs-shipyard/ipfs-webui/issues/1490
const gw = new URL(url)
if (LOCAL_HOSTNAMES.includes(gw.hostname)) {
gw.hostname = 'localhost'
const localUrl = gw.toString().replace(/\/+$/, '') // no trailing slashes
if (await checkIfSubdomainGatewayUrlIsAccessible(localUrl)) {
store.doSetAvailableGateway(localUrl)
return conf
}
}

if (!await checkIfGatewayUrlIsAccessible(url)) {
store.doSetAvailableGateway(DEFAULT_URI)
}
Expand Down Expand Up @@ -104,4 +117,19 @@ const checkIfGatewayUrlIsAccessible = memoize(async (url) => {
}
})

// Separate test is necessary to see if subdomain mode is possible,
// because some browser+OS combinations won't resolve them:
// https://github.com/ipfs/go-ipfs/issues/7527
const checkIfSubdomainGatewayUrlIsAccessible = memoize(async (url) => {
try {
url = new URL(url)
url.hostname = `bafkqaaa.ipfs.${url.hostname}`
const { status } = await fetch(url.toString())
return status === 200
} catch (e) {
console.error(`Unable to use the subdomain gateway at ${url}. Regular gateway will be used as a fallback`, e)
return false
}
})

export default bundle

0 comments on commit 7c8b455

Please sign in to comment.