]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/webfinger.ts
Optimize account creation
[github/Chocobozzz/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 { fetchRemoteAccountAndCreateServer } 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 (nameWithHost: string) {
16 const webfingerData: WebFingerData = await webfingerLookup(nameWithHost)
17
18 if (Array.isArray(webfingerData.links) === false) throw new Error('WebFinger links is not an array.')
19
20 const selfLink = webfingerData.links.find(l => l.rel === 'self')
21 if (selfLink === undefined || isActivityPubUrlValid(selfLink.href) === false) {
22 throw new Error('Cannot find self link or href is not a valid URL.')
23 }
24
25 const res = await fetchRemoteAccountAndCreateServer(selfLink.href)
26 if (res === undefined) throw new Error('Cannot fetch and create server of remote account ' + selfLink.href)
27
28 return res.account
29 }
30
31 // ---------------------------------------------------------------------------
32
33 export {
34 getAccountFromWebfinger
35 }
36
37 // ---------------------------------------------------------------------------
38
39 function webfingerLookup (nameWithHost: string) {
40 return new Promise<WebFingerData>((res, rej) => {
41 webfinger.lookup(nameWithHost, (err, p) => {
42 if (err) return rej(err)
43
44 return res(p.object)
45 })
46 })
47 }