]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/helpers/webfinger.ts
Improve video torrent AP object validator
[github/Chocobozzz/PeerTube.git] / server / helpers / webfinger.ts
... / ...
CommitLineData
1import * as WebFinger from 'webfinger.js'
2import { WebFingerData } from '../../shared'
3import { ActorModel } from '../models/activitypub/actor'
4import { isTestInstance } from './core-utils'
5import { isActivityPubUrlValid } from './custom-validators/activitypub/misc'
6
7const webfinger = new WebFinger({
8 webfist_fallback: false,
9 tls_only: isTestInstance(),
10 uri_fallback: false,
11 request_timeout: 3000
12})
13
14async function loadActorUrlOrGetFromWebfinger (name: string, host: string) {
15 const actor = await ActorModel.loadByNameAndHost(name, host)
16 if (actor) return actor.url
17
18 return getUrlFromWebfinger(name, host)
19}
20
21async function getUrlFromWebfinger (name: string, host: string) {
22 const webfingerData: WebFingerData = await webfingerLookup(name + '@' + host)
23 return getLinkOrThrow(webfingerData)
24}
25
26// ---------------------------------------------------------------------------
27
28export {
29 getUrlFromWebfinger,
30 loadActorUrlOrGetFromWebfinger
31}
32
33// ---------------------------------------------------------------------------
34
35function getLinkOrThrow (webfingerData: WebFingerData) {
36 if (Array.isArray(webfingerData.links) === false) throw new Error('WebFinger links is not an array.')
37
38 const selfLink = webfingerData.links.find(l => l.rel === 'self')
39 if (selfLink === undefined || isActivityPubUrlValid(selfLink.href) === false) {
40 throw new Error('Cannot find self link or href is not a valid URL.')
41 }
42
43 return selfLink.href
44}
45
46function webfingerLookup (nameWithHost: string) {
47 return new Promise<WebFingerData>((res, rej) => {
48 webfinger.lookup(nameWithHost, (err, p) => {
49 if (err) return rej(err)
50
51 return res(p.object)
52 })
53 })
54}