]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/webfinger.ts
emit more specific status codes on video upload (#3423)
[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'
da854ddd 5import { isActivityPubUrlValid } from './custom-validators/activitypub/misc'
6dd9de95 6import { WEBSERVER } from '../initializers/constants'
26d6bf65 7import { MActorFull } from '../types/models'
e4f97bab
C
8
9const webfinger = new WebFinger({
10 webfist_fallback: false,
11 tls_only: isTestInstance(),
12 uri_fallback: false,
13 request_timeout: 3000
14})
15
2ff83ae2
C
16async function loadActorUrlOrGetFromWebfinger (uriArg: string) {
17 // Handle strings like @toto@example.com
18 const uri = uriArg.startsWith('@') ? uriArg.slice(1) : uriArg
19
06a05d5f 20 const [ name, host ] = uri.split('@')
453e83ea 21 let actor: MActorFull
f5b0af50 22
cce1b3df 23 if (!host || host === WEBSERVER.HOST) {
f5b0af50
C
24 actor = await ActorModel.loadLocalByName(name)
25 } else {
26 actor = await ActorModel.loadByNameAndHost(name, host)
27 }
06a05d5f 28
50d6de9c 29 if (actor) return actor.url
e4f97bab 30
06a05d5f 31 return getUrlFromWebfinger(uri)
a5625b41
C
32}
33
06a05d5f
C
34async function getUrlFromWebfinger (uri: string) {
35 const webfingerData: WebFingerData = await webfingerLookup(uri)
50d6de9c 36 return getLinkOrThrow(webfingerData)
e4f97bab
C
37}
38
39// ---------------------------------------------------------------------------
40
41export {
a5625b41 42 getUrlFromWebfinger,
50d6de9c 43 loadActorUrlOrGetFromWebfinger
e4f97bab
C
44}
45
46// ---------------------------------------------------------------------------
47
50d6de9c
C
48function getLinkOrThrow (webfingerData: WebFingerData) {
49 if (Array.isArray(webfingerData.links) === false) throw new Error('WebFinger links is not an array.')
50
51 const selfLink = webfingerData.links.find(l => l.rel === 'self')
52 if (selfLink === undefined || isActivityPubUrlValid(selfLink.href) === false) {
53 throw new Error('Cannot find self link or href is not a valid URL.')
54 }
55
56 return selfLink.href
57}
58
350e31d6 59function webfingerLookup (nameWithHost: string) {
e4f97bab 60 return new Promise<WebFingerData>((res, rej) => {
350e31d6 61 webfinger.lookup(nameWithHost, (err, p) => {
e4f97bab
C
62 if (err) return rej(err)
63
350e31d6 64 return res(p.object)
e4f97bab
C
65 })
66 })
67}