-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresolve.js
355 lines (302 loc) · 9.11 KB
/
resolve.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
const { unpack, keyRing } = require('ara-network/keys')
const { readFile, stat } = require('fs')
const { createChannel } = require('ara-network/discovery/channel')
const isDomainName = require('is-domain-name')
const isBrowser = require('is-browser')
const isBuffer = require('is-buffer')
const { DID } = require('did-uri')
const debug = require('debug')('ara:identity:resolve')
const fetch = require('node-fetch')
const path = require('path')
const pify = require('pify')
const url = require('url')
const os = require('os')
const fs = require('./fs')
const { resolveDNS, writeCache } = require('./util')
const rc = require('./rc')()
const DID_IDENTIFIER_LENGTH = 64
const DID_METHOD = 'ara'
const RESOLUTION_TIMEOUT = 5000
const MAX_PEER_RESOLVERS = 8
function notFound() {
return Object.assign(
new Error('Could not resolve DID. No peer found'),
{ status: 404, code: 'ENOTFOUND' }
)
}
async function resolve(uri, opts = {}) {
if ('object' !== typeof opts) {
throw new TypeError('Expecting options to be an object.')
}
let conf
try {
conf = {
secret:
rc.network.identity.resolver.secret || rc.network.identity.secret,
keyring:
rc.network.identity.resolver.keyring || rc.network.identity.keyring,
network:
rc.network.identity.resolver.network,
servers:
rc.network.identity.resolver.servers
}
} finally {
conf = conf || {}
}
opts.secret = opts.secret || conf.secret
opts.keyring = opts.keyring || conf.keyring
opts.network = opts.network || conf.network
opts.servers = opts.servers || conf.servers
// is DID ?
if (uri && 'object' === typeof uri && uri.did) {
if ('string' === typeof uri.did) {
uri = uri.did
} else if ('object' === typeof uri.did) {
uri = uri.did.reference
}
} else if ('string' === typeof uri && isDomainName(uri)) {
try {
uri = await resolveDNS(uri, rc.network.dns)
} catch (err) {
debug(err)
}
}
if (0 !== uri.indexOf('did:ara:')) {
// eslint-disable-next-line no-param-reassign
uri = `did:ara:${uri}`
}
const did = new DID(uri)
if (DID_METHOD !== did.method) {
throw new TypeError(`Invalid DID method (${did.method}). `
+ `Expecting 'did:${DID_METHOD}:...'.`)
}
if (did.identifier && -1 !== did.identifier.indexOf('.')) {
throw new TypeError(`Unable to resolve DID for domain: ${did.identifier}`)
}
if (!did.identifier || DID_IDENTIFIER_LENGTH !== did.identifier.length) {
throw new TypeError('Invalid DID identifier length.')
}
const state = { aborted: false }
const resolutions = []
resolutions.push(async () => {
if (isBrowser) { return null }
try {
const ddo = await fs.readFile(did.identifier, 'ddo.json')
return (opts.parse || JSON.parse)(String(ddo))
} catch (err) {
debug(err)
}
return null
})
resolutions.push(async () => {
if (isBrowser || !opts.cache) { return null }
try {
const cachePath = path.join(os.tmpdir(), 'aid', did.identifier, 'ddo.json')
const stats = await pify(stat)(cachePath)
const ttl = 1000 * 30
const now = Date.now()
if ((now - stats.ctime) / ttl < 1) {
const json = await pify(readFile)(cachePath, 'utf8')
return (opts.parse || JSON.parse)(String(json))
}
} catch (err) {
debug(err)
}
return null
})
resolutions.push(async () => {
if (!opts) {
return null
}
if (!opts.servers && (!opts.secret || !opts.keyring || !opts.network)) {
return null
}
if (opts.secret && 'string' !== typeof opts.secret && !isBuffer(opts.secret)) {
return new TypeError('Expecting shared secret to be a string or buffer.')
}
if (opts.secret && 0 === opts.secret.length) {
return new TypeError('Shared secret cannot be empty.')
}
if (opts.network && 'string' !== typeof opts.network) {
throw new TypeError('Expecting network name for the resolver.')
}
if (null === opts.timeout || 'number' !== typeof opts.timeout) {
// eslint-disable-next-line no-param-reassign
opts.timeout = RESOLUTION_TIMEOUT
}
return findResolution(did, opts, state)
})
return pify(async (done) => {
let resolved = false
let pending = 0
const queue = false === opts.cache ? resolutions.reverse() : resolutions
for (let i = 0; i < queue.length; ++i) {
const resolution = queue[i]
if (resolved || state.aborted) {
break
} else {
pending++
process.nextTick(() => resolution().then(onthen).catch(onerror))
}
}
function onerror(err) {
state.aborted = true
done(err)
}
async function onthen(result) {
pending--
if (result) {
resolved = true
state.aborted = true
process.nextTick(done, null, result)
}
if (!resolved && 0 === pending) {
state.aborted = true
done(notFound())
}
}
})()
}
const keyrings = {}
async function findResolution(did, opts, state) {
return pify((done) => {
const resolvers = []
let discoveryKey = null
let didResolve = false
let pending = 0
let channel = null
let timeout = null
let keyring = null
let result = null
if (!isBrowser && opts.secret && opts.keyring && opts.network) {
const secret = Buffer.from(opts.secret)
keyring = keyrings[opts.keyrings] || keyRing(opts.keyring, { secret })
keyrings[opts.keyring] = keyring
keyring.get(opts.network, (err, buffer) => {
if (err) {
debug(err)
} else {
const unpacked = unpack({ buffer })
// eslint-disable-next-line prefer-destructuring
discoveryKey = unpacked.discoveryKey
channel = createChannel()
channel.on('peer', onpeer)
channel.join(discoveryKey)
}
})
}
if (opts.servers && opts.servers.length) {
for (const server of opts.servers) {
const uri = url.parse(server)
const { host } = uri
let { port } = uri
// eslint-disable-next-line no-undef
const { protocol = isBrowser ? window.location.protocol : 'http:' } = uri
if (!port) {
if ('https:' === protocol) {
port = 443
} else {
port = 80
}
}
resolvers.push({
id: null,
peer: { host, port },
type: protocol ? protocol.replace(':', '') : isBrowser,
})
}
}
for (let i = 0; i < resolvers.length; ++i) {
process.nextTick(doResolution)
}
function onpeer(id, peer, type) {
if (state.aborted) {
cleanup()
} else if (resolvers.length < MAX_PEER_RESOLVERS) {
resolvers.push({ id, peer, type })
if (1 === resolvers.length) {
process.nextTick(doResolution)
}
}
}
async function doResolution() {
clearTimeout(timeout)
if (state.aborted) {
process.nextTick(cleanup)
process.nextTick(done)
return
}
if (
0 === pending
&& !didResolve
&& 0 === resolvers.length
&& !state.aborted
) {
// Revert to expired cache copy if present
if (false === isBrowser) {
try {
const cachePath = path.join(os.tmpdir(), 'aid', did.identifier, 'ddo.json')
const json = await pify(readFile)(cachePath, 'utf8')
done(null, (opts.parse || JSON.parse)(String(json)))
} catch (err) {
debug(err)
}
}
cleanup()
done(null, result)
} else if (resolvers.length && !state.aborted && !didResolve) {
for (const { peer, type } of resolvers) {
resolvers.shift()
const { host, port } = peer
let uri = ''
if ('https' === type || 'http' === type) {
uri = `${type}://${host}`
} else {
uri = `http://${host}:${port}`
}
uri += `/1.0/identifiers/${did.did}`
timeout = setTimeout(doResolution, opts.timeout)
/* eslint-disable no-loop-func */
pending++
fetch(uri, { mode: 'cors' })
.then(async (res) => {
const json = await res.json()
result = json.didDocument
// Write DDO to temp cache folder
if (false === isBrowser && result) {
await writeCache(did.identifier, 'ddo.json', JSON.stringify(result))
}
didResolve = true
cleanup()
pending--
done(null, result)
})
.catch((err) => {
debug(err)
if (0 === --pending) {
process.nextTick(doResolution)
}
})
/* eslint-enable no-loop-func */
}
}
}
function cleanup() {
if (channel) {
clearTimeout(timeout)
channel.removeListener('peer', onpeer)
channel.destroy()
}
if (keyring) {
delete keyrings[opts.keyring]
keyring.storage.close()
}
if (!didResolve && !state.aborted) {
done(notFound())
}
}
})()
}
module.exports = {
resolve
}