]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/webfinger.ts
remove isAdministration
[github/Chocobozzz/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/misc'
6 import { CONFIG } from '../initializers'
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 loadActorUrlOrGetFromWebfinger (uriArg: string) {
16 // Handle strings like @toto@example.com
17 const uri = uriArg.startsWith('@') ? uriArg.slice(1) : uriArg
18
19 const [ name, host ] = uri.split('@')
20 let actor: ActorModel
21
22 if (host === CONFIG.WEBSERVER.HOST) {
23 actor = await ActorModel.loadLocalByName(name)
24 } else {
25 actor = await ActorModel.loadByNameAndHost(name, host)
26 }
27
28 if (actor) return actor.url
29
30 return getUrlFromWebfinger(uri)
31 }
32
33 async function getUrlFromWebfinger (uri: string) {
34 const webfingerData: WebFingerData = await webfingerLookup(uri)
35 return getLinkOrThrow(webfingerData)
36 }
37
38 // ---------------------------------------------------------------------------
39
40 export {
41 getUrlFromWebfinger,
42 loadActorUrlOrGetFromWebfinger
43 }
44
45 // ---------------------------------------------------------------------------
46
47 function getLinkOrThrow (webfingerData: WebFingerData) {
48 if (Array.isArray(webfingerData.links) === false) throw new Error('WebFinger links is not an array.')
49
50 const selfLink = webfingerData.links.find(l => l.rel === 'self')
51 if (selfLink === undefined || isActivityPubUrlValid(selfLink.href) === false) {
52 throw new Error('Cannot find self link or href is not a valid URL.')
53 }
54
55 return selfLink.href
56 }
57
58 function webfingerLookup (nameWithHost: string) {
59 return new Promise<WebFingerData>((res, rej) => {
60 webfinger.lookup(nameWithHost, (err, p) => {
61 if (err) return rej(err)
62
63 return res(p.object)
64 })
65 })
66 }