]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/webfinger.ts
Begin moving video channel to actor
[github/Chocobozzz/PeerTube.git] / server / helpers / webfinger.ts
CommitLineData
e4f97bab 1import * as WebFinger from 'webfinger.js'
892211e8 2import { WebFingerData } from '../../shared'
50d6de9c 3import { ActorModel } from '../models/activitypub/actor'
e4f97bab 4import { isTestInstance } from './core-utils'
3fd3ab2d 5import { isActivityPubUrlValid } from './custom-validators/activitypub'
e4f97bab
C
6
7const webfinger = new WebFinger({
8 webfist_fallback: false,
9 tls_only: isTestInstance(),
10 uri_fallback: false,
11 request_timeout: 3000
12})
13
50d6de9c
C
14async function loadActorUrlOrGetFromWebfinger (name: string, host: string) {
15 const actor = await ActorModel.loadByNameAndHost(name, host)
16 if (actor) return actor.url
e4f97bab 17
50d6de9c
C
18 const webfingerData: WebFingerData = await webfingerLookup(name + '@' + host)
19 return getLinkOrThrow(webfingerData)
e4f97bab
C
20}
21
22// ---------------------------------------------------------------------------
23
24export {
50d6de9c 25 loadActorUrlOrGetFromWebfinger
e4f97bab
C
26}
27
28// ---------------------------------------------------------------------------
29
50d6de9c
C
30function 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
350e31d6 41function webfingerLookup (nameWithHost: string) {
e4f97bab 42 return new Promise<WebFingerData>((res, rej) => {
350e31d6 43 webfinger.lookup(nameWithHost, (err, p) => {
e4f97bab
C
44 if (err) return rej(err)
45
350e31d6 46 return res(p.object)
e4f97bab
C
47 })
48 })
49}