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