Begin moving video channel to actor
[oweals/peertube.git] / server / helpers / webfinger.ts
1 import * as WebFinger from 'webfinger.js'
2 import { WebFingerData } from '../../shared'
3 import { ActorModel } from '../models/activitypub/actor'
4 import { isTestInstance } from './core-utils'
5 import { isActivityPubUrlValid } from './custom-validators/activitypub'
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 loadActorUrlOrGetFromWebfinger (name: string, host: string) {
15   const actor = await ActorModel.loadByNameAndHost(name, host)
16   if (actor) return actor.url
17
18   const webfingerData: WebFingerData = await webfingerLookup(name + '@' + host)
19   return getLinkOrThrow(webfingerData)
20 }
21
22 // ---------------------------------------------------------------------------
23
24 export {
25   loadActorUrlOrGetFromWebfinger
26 }
27
28 // ---------------------------------------------------------------------------
29
30 function getLinkOrThrow (webfingerData: WebFingerData) {
31   if (Array.isArray(webfingerData.links) === false) throw new Error('WebFinger links is not an array.')
32
33   const selfLink = webfingerData.links.find(l => l.rel === 'self')
34   if (selfLink === undefined || isActivityPubUrlValid(selfLink.href) === false) {
35     throw new Error('Cannot find self link or href is not a valid URL.')
36   }
37
38   return selfLink.href
39 }
40
41 function webfingerLookup (nameWithHost: string) {
42   return new Promise<WebFingerData>((res, rej) => {
43     webfinger.lookup(nameWithHost, (err, p) => {
44       if (err) return rej(err)
45
46       return res(p.object)
47     })
48   })
49 }