-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
324 lines (280 loc) · 8.4 KB
/
index.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
const { createIdentityKeyPath } = require('ara-identity/key-path')
const hasDIDMethod = require('has-did-method')
const { blake2b } = require('ara-crypto')
const ss = require('ara-secret-storage')
const { deprecate } = require('util')
const aid = require('ara-identity')
const { resolve } = require('path')
const diduri = require('did-uri')
const pify = require('pify')
const fs = require('fs')
const os = require('os')
const kAraKeystore = 'keystore/ara'
const {
kEd25519VerificationKey2018,
kSecp256k1VerificationKey2018
} = require('ld-cryptosuite-registry')
const { kEthHexPrefix } = require('./constants')
const transform = require('./transform')
const errors = require('./errors')
const web3 = require('./web3')
const ETH_ADDRESS_LENGTH = 40
/**
* Blake2b hashes a DID URI.
* @param {String} did
* @param {String} encoding
* @return {String}
* @throws {TypeError}
*/
function hashDID(did, encoding = 'hex') {
if (!did || 'string' !== typeof did) {
throw new TypeError('DID to hash must be non-empty string.')
} else if (encoding && 'string' !== typeof encoding) {
throw new TypeError('Encoding must be of type string.')
}
did = getIdentifier(did)
return hash(did, encoding)
}
/**
* Gets the identifier from the DID URI
* @param {String} did
* @return {String}
* @throws {TypeError}
*/
function getIdentifier(did) {
if (!did || 'string' !== typeof did) {
throw new TypeError('DID must be a non-empty string.')
}
if (0 === did.indexOf(kEthHexPrefix)) {
return did.substring(kEthHexPrefix.length)
}
const uri = diduri.parse(aid.did.normalize(did))
return uri.identifier
}
/**
* Verifies if a password for an identity is correct
* by attempting to decrypt the ARA keystore
* @param {Object} opts
* @param {Object} opts.ddo
* @param {String} opts.password
* @return {Boolean}
* @throws {TypeError}
*/
async function isCorrectPassword(opts) {
if (!opts || 'object' !== typeof opts) {
throw new TypeError('Expecting opts object.')
} else if (!opts.ddo || 'object' !== typeof opts.ddo) {
throw new TypeError('Expecting valid DDO object on opts.')
} else if (!opts.password || 'string' !== typeof opts.password) {
throw new TypeError('Expecting password to be non-empty string.')
}
const { ddo } = opts
const publicKeyHex = getDocumentKeyHex(ddo)
const password = blake2b(Buffer.from(opts.password))
const identityPath = resolve(createIdentityKeyPath(ddo), kAraKeystore)
let keys
try {
keys = JSON.parse(await pify(fs.readFile)(identityPath, 'utf8'))
} catch (err) {
throw new Error(`Identity ${ddo.id} does not exist locally. Please recover this AraID locally using the mnemonic then try again.`)
}
let secretKey
try {
secretKey = ss.decrypt(keys, { key: password.slice(0, 16) })
} catch (err) {
return false
}
const publicKey = secretKey.slice(32).toString('hex')
return publicKeyHex === publicKey
}
/**
* Retrieves the ethereum address given a DID
* @param {String} did
* @param {Object} [keyringOpts]
* @return {String}
* @throws {TypeError}
*/
async function getAddressFromDID(did, keyringOpts = {}) {
if (!did || 'string' !== typeof did) {
throw new TypeError(`Expected DID to be a non-empty string. Got ${did}. Ensure identity exists.`)
}
const ddo = await aid.resolve(did, keyringOpts)
const { publicKeyHex } = ddo.publicKey.find((element) => {
const { type } = element
return type === kSecp256k1VerificationKey2018
})
const hashpk = web3.sha3(`${kEthHexPrefix}${publicKeyHex}`)
return transform.toHexString(hashpk.slice(-ETH_ADDRESS_LENGTH), { encoding: 'hex', ethify: true })
}
/**
* Get the creating owner of an identity
* @param {Object} ddo
* @return {String}
* @throws {TypeError,RangeError}
*/
function getDocumentOwner(ddo) {
if (!ddo || 'object' !== typeof ddo) {
throw new TypeError('Expecting valid DDO object.')
}
const doc = _getDocument(ddo)
if (0 === doc.authentication.length) {
throw new RangeError('Identity doesn\'t list an owner in authentication.')
}
// eslint-disable-next-line arrow-body-style
const { publicKey } = doc.authentication.find(({ type }) => {
return type === kEd25519VerificationKey2018
})
const id = publicKey.slice(0, publicKey.indexOf('#'))
return getIdentifier(id)
}
/**
* Extracts the publicKey, or raw identifier, from a DDO.
* @param {Object} ddo
* @return {String}
* @throws {TypeError}
*/
function getDocumentKeyHex(ddo) {
if (!ddo || 'object' !== typeof ddo) {
throw new TypeError('Expecting valid DDO object.')
}
const doc = _getDocument(ddo)
const { publicKeyHex } = doc.publicKey[0]
return publicKeyHex
}
/**
* Blake2b hash a string
* @param {String} str
* @param {String} encoding
* @return {String}
* @throws {TypeError}
*/
function hash(str, encoding = 'hex') {
if (!str || 'string' !== typeof str) {
throw new TypeError('Expecting input to be valid string.')
} else if (encoding && 'string' !== typeof encoding) {
throw new TypeError('Encoding must be of type string.')
} else if (0 === Buffer.from(str, encoding).length) {
throw new Error(`${str} with ${encoding} results in an empty buffer`)
}
const result = blake2b(Buffer.from(str, encoding))
if ('hex' === encoding) {
return transform.toHexString(result)
}
return result.toString(encoding)
}
/**
* Recreates an owning identity
* @param {Object} opts
* @param {String} opts.did
* @param {String} opts.mnemonic
* @param {String} opts.password
* @param {Object} [opts.keyringOpts]
* @return {Object}
* @throws {TypeError}
*/
async function getAFSOwnerIdentity(opts) {
let err
if (!opts || 'object' !== typeof opts) {
err = new TypeError('Expecting opts object.')
} else if (!opts.did || 'string' !== typeof opts.did) {
err = new TypeError('Expecting DID URI to be valid string.')
} else if (!opts.mnemonic || 'string' !== typeof opts.mnemonic) {
err = new TypeError('Expecting mnemonic to be valid string.')
} else if (!opts.password || 'string' !== typeof opts.password) {
err = new TypeError('Expecting password to be valid string.')
}
if (err) {
throw err
}
const {
did, mnemonic, password, keyringOpts = {}
} = opts
const ddo = await aid.resolve(did, keyringOpts)
const owner = getDocumentOwner(ddo)
return aid.create({
mnemonic, owner, password
})
}
/**
* Checks if an AFS exists in local files
*
* @param {Object} opts
* @param {String} opts.did DID of AFS to check for
*
* @return {Boolean} Whether AFS exists locally
*/
function checkAFSExistence(opts) {
if (!opts) {
throw new Error('Expecting opts to be defined, got null')
} else if ('object' !== typeof opts) {
throw new TypeError('Expecting opts to be an Object')
} else if (!opts.did) {
throw new Error(`Expecting opts.did to be defined, got ${JSON.stringify(opts)}`)
}
const { did } = opts
try {
const hashedDid = hashDID(did).toString('hex')
// If the file exists, an error will be thrown
fs.accessSync(resolve(`${os.homedir()}/.ara/afs`, hashedDid))
return true
} catch (e) {
return false
}
}
/**
* Resolves a DID, validates ownership by comparing
* passwords and returns the DDO.
* @param {Object} opts
* @param {String} opts.password
* @param {String} opts.did
* @param {Object} [opts.ddo]
* @param {Object} [opts.keyringOpts]
* @return {Object}
* @throws {Error,TypeError}
*/
async function validate(opts) {
if (!opts || 'object' !== typeof opts) {
throw new TypeError('Expecting opts object.')
} else if (!opts.did || 'string' !== typeof opts.did) {
throw new TypeError('DID URI must be valid string.')
}
let { did, ddo } = opts
const { password, keyringOpts = {} } = opts
did = getIdentifier(did)
if (!ddo) {
ddo = await aid.resolve(did, keyringOpts)
}
if (!ddo) {
throw new TypeError('Unable to resolve DID.')
}
const writable = Boolean(password)
if (writable) {
if (!(await isCorrectPassword({ ddo, password }))) {
throw new Error('Incorrect password.')
}
}
return {
did,
ddo
}
}
function _getDocument(ddo) {
return ddo.didDocument ? ddo.didDocument : ddo
}
module.exports = {
getAFSOwnerIdentity,
checkAFSExistence,
isCorrectPassword,
getAddressFromDID,
getDocumentKeyHex,
getDocumentOwner,
hasDIDMethod,
normalize: deprecate(getIdentifier, '`normalize` is deprecated, use `getIdentifier`'),
getIdentifier,
transform,
validate,
hashDID,
errors,
hash,
web3
}