-
Notifications
You must be signed in to change notification settings - Fork 0
/
did.js
78 lines (64 loc) · 1.83 KB
/
did.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
const { DID, parse } = require('did-uri')
const isDomainName = require('is-domain-name')
const isBuffer = require('is-buffer')
const { toHex } = require('./util')
const DID_ARA_METHOD = 'ara'
const IDENTIFIER_LENGTH = 64
/**
* Creates a DID document (DDO) from an identifier.
* @public
* @param {String|Buffer} identifier
* @param {?(String)} [method]
* @return {Object}
* @throws TypeError
*/
function create(identifier, method) {
if (!identifier) {
throw new TypeError('Expecting identifier.')
}
if ('string' !== typeof identifier && false === isBuffer(identifier)) {
throw new TypeError('Expecting identifier to be a string or buffer.')
}
if (method && 'string' !== typeof method) {
throw new TypeError('Expecting method to be a string.')
}
const id = toHex(identifier)
const didMethod = method || DID_ARA_METHOD
const uri = `did:${didMethod}:${id}`
return new DID(uri)
}
/**
* Normalizes a given DID URI to Prefix & Identifier
* @public
* @return {String}
* @throws TypeError
*/
function normalize(uri, method) {
if (!uri) {
throw new TypeError('Expecting URI.')
}
if ('string' !== typeof uri) {
throw new TypeError('Expecting URI to be a string or buffer.')
}
if (isDomainName(uri)) {
throw new Error('DNS resolvable names are not allowed')
}
if (method && 'string' !== typeof method) {
throw new TypeError('Expecting method to be a string.')
}
method = method || DID_ARA_METHOD
const prefix = `did:${method}:`
if (prefix !== uri.slice(0, prefix.length)) {
if (DID_ARA_METHOD === method && uri.length !== IDENTIFIER_LENGTH) {
throw new Error(`Expecting Ara URI to be of length ${IDENTIFIER_LENGTH}. Got ${uri}. Ensure Ara URI is a valid hex string.`)
}
return prefix + uri
}
return uri
}
module.exports = {
normalize,
create,
parse,
DID,
}