-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathresolver.ts
46 lines (38 loc) · 1.19 KB
/
resolver.ts
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
import fetch from 'cross-fetch'
import { DIDDocument, ParsedDID } from 'did-resolver'
const DOC_PATH = '/.well-known/did.json'
async function get(url: string): Promise<any> {
const res = await fetch(url, { mode: 'cors' })
if (res.status >= 400) {
throw new Error(`Bad response ${res.statusText}`)
}
return res.json()
}
export function getResolver() {
async function resolve(
did: string,
parsed: ParsedDID
): Promise<DIDDocument | null> {
let path = parsed.id + DOC_PATH
const id = parsed.id.split(':')
if (id.length > 1) path = id.join('/') + '/did.json'
const url: string = `https://${path}`
let data: any = null
try {
data = await get(url)
} catch (error) {
throw new Error(
`DID must resolve to a valid https URL containing a JSON document: ${error.message}`
)
}
const docIdMatchesDid = data.id === did
if (!docIdMatchesDid) {
throw new Error('DID document id does not match requested did')
}
const docHasPublicKey =
Array.isArray(data.publicKey) && data.publicKey.length > 0
if (!docHasPublicKey) throw new Error('DID document has no public keys')
return data
}
return { web: resolve }
}