Fix lint
[oweals/peertube.git] / server / helpers / webfinger.ts
1 import * as WebFinger from 'webfinger.js'
2 import { WebFingerData } from '../../shared'
3 import { fetchRemoteAccount } from '../lib/activitypub/account'
4
5 import { isTestInstance } from './core-utils'
6 import { isActivityPubUrlValid } from './custom-validators'
7
8 const webfinger = new WebFinger({
9   webfist_fallback: false,
10   tls_only: isTestInstance(),
11   uri_fallback: false,
12   request_timeout: 3000
13 })
14
15 async function getAccountFromWebfinger (nameWithHost: string) {
16   const webfingerData: WebFingerData = await webfingerLookup(nameWithHost)
17
18   if (Array.isArray(webfingerData.links) === false) throw new Error('WebFinger links is not an array.')
19
20   const selfLink = webfingerData.links.find(l => l.rel === 'self')
21   if (selfLink === undefined || isActivityPubUrlValid(selfLink.href) === false) {
22     throw new Error('Cannot find self link or href is not a valid URL.')
23   }
24
25   const account = await fetchRemoteAccount(selfLink.href)
26   if (account === undefined) throw new Error('Cannot fetch remote account ' + selfLink.href)
27
28   return account
29 }
30
31 // ---------------------------------------------------------------------------
32
33 export {
34   getAccountFromWebfinger
35 }
36
37 // ---------------------------------------------------------------------------
38
39 function webfingerLookup (nameWithHost: string) {
40   return new Promise<WebFingerData>((res, rej) => {
41     webfinger.lookup(nameWithHost, (err, p) => {
42       if (err) return rej(err)
43
44       return res(p.object)
45     })
46   })
47 }