-
Notifications
You must be signed in to change notification settings - Fork 0
/
dns.js
95 lines (79 loc) · 2.27 KB
/
dns.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const isDomainName = require('is-domain-name')
const { DID } = require('did-uri')
const dns = require('ara-identity-dns')
const { resolve } = require('./resolve')
const { update } = require('./update')
const RFC4501 = 'RFC4501'
const DNS_SERVICE_TYPE = 'DNSURIRecord'
async function query(domain, opts) {
const resolutions = await dns.resolve(domain, opts)
return resolutions
}
async function bind(identifier, domain, opts) {
if (!isDomainName(domain)) {
throw new TypeError(`Expecting '${domain}' to be a valid domain name.`)
}
const ddo = opts.ddo || await resolve(identifier, opts)
let isBound = false
for (const service of ddo.service) {
if (DNS_SERVICE_TYPE === service.type || RFC4501 === service.type) {
const p = service.id.split(';')
const { did } = new DID(p[0])
const name = p[1]
if (did === ddo.id && name === domain) {
isBound = true
break
}
}
}
if (isBound) {
throw new Error(`Domain '${domain}' is already bound to identity.`)
}
const authority = opts.authority ? `//${opts.authority}/` : ''
ddo.service.push({
id: `${ddo.id};${domain}`,
type: DNS_SERVICE_TYPE,
serviceEndpoint: `dns://${authority}${domain}?type=${opts.type || 'TXT'}`
})
return update(ddo.id, {
password: opts.password,
publicKey: opts.publicKey,
secretKey: opts.secretKey,
ddo,
})
}
async function unbind(identifier, domain, opts) {
if (!isDomainName(domain)) {
throw new TypeError(`Expecting '${domain}' to be a valid domain name.`)
}
const ddo = opts.ddo || await resolve(identifier, opts)
let wasBound = false
for (let i = 0; i < ddo.service.length; ++i) {
const service = ddo.service[i]
if (DNS_SERVICE_TYPE === service.type || RFC4501 === service.type) {
const p = service.id.split(';')
const { did } = new DID(p[0])
const name = p[1]
if (did === ddo.id && name === domain) {
ddo.service.splice(i, 1)
wasBound = true
break
}
}
}
if (wasBound) {
return update(ddo.id, {
password: opts.password,
publicKey: opts.publicKey,
secretKey: opts.secretKey,
ddo,
})
}
throw new Error(`Domain '${domain}' not bound to identity.`)
}
module.exports = {
resolve,
unbind,
query,
bind,
}