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'
8 const webfinger = new WebFinger({
9 webfist_fallback: false,
10 tls_only: isTestInstance(),
15 async function loadActorUrlOrGetFromWebfinger (uri: string) {
16 const [ name, host ] = uri.split('@')
19 if (host === CONFIG.WEBSERVER.HOST) {
20 actor = await ActorModel.loadLocalByName(name)
22 actor = await ActorModel.loadByNameAndHost(name, host)
25 if (actor) return actor.url
27 return getUrlFromWebfinger(uri)
30 async function getUrlFromWebfinger (uri: string) {
31 const webfingerData: WebFingerData = await webfingerLookup(uri)
32 return getLinkOrThrow(webfingerData)
35 // ---------------------------------------------------------------------------
39 loadActorUrlOrGetFromWebfinger
42 // ---------------------------------------------------------------------------
44 function getLinkOrThrow (webfingerData: WebFingerData) {
45 if (Array.isArray(webfingerData.links) === false) throw new Error('WebFinger links is not an array.')
47 const selfLink = webfingerData.links.find(l => l.rel === 'self')
48 if (selfLink === undefined || isActivityPubUrlValid(selfLink.href) === false) {
49 throw new Error('Cannot find self link or href is not a valid URL.')
55 function webfingerLookup (nameWithHost: string) {
56 return new Promise<WebFingerData>((res, rej) => {
57 webfinger.lookup(nameWithHost, (err, p) => {
58 if (err) return rej(err)