9586fa5624b568c1eb2052ef8eec54028bf3f978
[oweals/peertube.git] / server / helpers / webfinger.ts
1 import * as WebFinger from 'webfinger.js'
2
3 import { isTestInstance } from './core-utils'
4 import { isActivityPubUrlValid } from './custom-validators'
5 import { WebFingerData } from '../../shared'
6 import { fetchRemoteAccountAndCreatePod } from './activitypub'
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 (url: string) {
16   const webfingerData: WebFingerData = await webfingerLookup(url)
17
18   if (Array.isArray(webfingerData.links) === false) return undefined
19
20   const selfLink = webfingerData.links.find(l => l.rel === 'self')
21   if (selfLink === undefined || isActivityPubUrlValid(selfLink.href) === false) return undefined
22
23   const { account } = await fetchRemoteAccountAndCreatePod(selfLink.href)
24
25   return account
26 }
27
28 // ---------------------------------------------------------------------------
29
30 export {
31   getAccountFromWebfinger
32 }
33
34 // ---------------------------------------------------------------------------
35
36 function webfingerLookup (url: string) {
37   return new Promise<WebFingerData>((res, rej) => {
38     webfinger.lookup('nick@silverbucket.net', (err, p) => {
39       if (err) return rej(err)
40
41       return p
42     })
43   })
44 }