-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathdns-web.js
64 lines (50 loc) · 1.18 KB
/
dns-web.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* global fetch */
// TODO: Persist to local storage
const DEFAULT_DNS_PROXY = 'gateway.mauve.moe'
const NEWLINE_REGEX = /\r?\n/
const DAT_PROTOCOL = 'dat://'
module.exports = ({
dnsProxy = DEFAULT_DNS_PROXY
} = {}) => {
let cache = {}
return {
async resolveName (url, opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
if (!cb) cb = noop
let domain = url
if (domain.startsWith(DAT_PROTOCOL)) {
domain = url.slice(DAT_PROTOCOL.length)
}
if (cache[domain]) {
if (cb) {
cb(null, cache[domain])
return
} else {
return cache[domain]
}
}
try {
const toFetch = `//${dnsProxy}/${domain}/.well-known/dat`
const response = await fetch(toFetch)
const text = await response.text()
const lines = text.split(NEWLINE_REGEX)
const resolved = lines[0]
cache[domain] = resolved
if (cb) cb(null, resolved)
} catch (e) {
if (cb) cb(e)
else throw e
}
},
listCache () {
return cache
},
flushCache () {
cache = {}
}
}
}
function noop () {}