1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-28 05:12:18 +01:00
metamask-extension/app/scripts/lib/ens-ipfs/setup.js

83 lines
2.6 KiB
JavaScript
Raw Normal View History

import extension from 'extensionizer'
import resolveEnsToIpfsContentId from './resolver'
const supportedTopLevelDomains = ['eth']
2020-11-03 00:41:28 +01:00
export default function setupEnsIpfsResolver({
provider,
getCurrentNetwork,
getIpfsGateway,
}) {
// install listener
2020-02-15 21:34:12 +01:00
const urlPatterns = supportedTopLevelDomains.map((tld) => `*://*.${tld}/*`)
2020-11-03 00:41:28 +01:00
extension.webRequest.onErrorOccurred.addListener(webRequestDidFail, {
urls: urlPatterns,
types: ['main_frame'],
})
// return api object
return {
// uninstall listener
2020-11-03 00:41:28 +01:00
remove() {
extension.webRequest.onErrorOccurred.removeListener(webRequestDidFail)
},
}
2020-11-03 00:41:28 +01:00
async function webRequestDidFail(details) {
const { tabId, url } = details
// ignore requests that are not associated with tabs
// only attempt ENS resolution on mainnet
if (tabId === -1 || getCurrentNetwork() !== '1') {
return
}
// parse ens name
const { hostname: name, pathname, search, hash: fragment } = new URL(url)
const domainParts = name.split('.')
const topLevelDomain = domainParts[domainParts.length - 1]
// if unsupported TLD, abort
if (!supportedTopLevelDomains.includes(topLevelDomain)) {
return
}
// otherwise attempt resolve
attemptResolve({ tabId, name, pathname, search, fragment })
}
2020-11-03 00:41:28 +01:00
async function attemptResolve({ tabId, name, pathname, search, fragment }) {
const ipfsGateway = getIpfsGateway()
extension.tabs.update(tabId, { url: `loading.html` })
let url = `https://app.ens.domains/name/${name}`
try {
2019-12-03 21:50:55 +01:00
const { type, hash } = await resolveEnsToIpfsContentId({ provider, name })
if (type === 'ipfs-ns' || type === 'ipns-ns') {
2020-11-03 00:41:28 +01:00
const resolvedUrl = `https://${hash}.${type.slice(
0,
4,
)}.${ipfsGateway}${pathname}${search || ''}${fragment || ''}`
2019-04-04 17:15:57 +02:00
try {
// check if ipfs gateway has result
const response = await window.fetch(resolvedUrl, { method: 'HEAD' })
if (response.status === 200) {
url = resolvedUrl
}
2019-04-04 17:15:57 +02:00
} catch (err) {
console.warn(err)
}
2019-04-04 17:15:57 +02:00
} else if (type === 'swarm-ns') {
2020-11-03 00:41:28 +01:00
url = `https://swarm-gateways.net/bzz:/${hash}${pathname}${
search || ''
}${fragment || ''}`
} else if (type === 'onion' || type === 'onion3') {
url = `http://${hash}.onion${pathname}${search || ''}${fragment || ''}`
2019-10-31 19:37:06 +01:00
} else if (type === 'zeronet') {
2020-11-03 00:41:28 +01:00
url = `http://127.0.0.1:43110/${hash}${pathname}${search || ''}${
fragment || ''
}`
}
} catch (err) {
console.warn(err)
2019-05-04 18:57:19 +02:00
} finally {
extension.tabs.update(tabId, { url })
}
}
}