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'
7 const webfinger = new WebFinger({
8 webfist_fallback: false,
9 tls_only: isTestInstance(),
14 async function loadActorUrlOrGetFromWebfinger (uri: string) {
15 const [ name, host ] = uri.split('@')
17 const actor = await ActorModel.loadByNameAndHost(name, host)
18 if (actor) return actor.url
20 return getUrlFromWebfinger(uri)
23 async function getUrlFromWebfinger (uri: string) {
24 const webfingerData: WebFingerData = await webfingerLookup(uri)
25 return getLinkOrThrow(webfingerData)
28 // ---------------------------------------------------------------------------
32 loadActorUrlOrGetFromWebfinger
35 // ---------------------------------------------------------------------------
37 function getLinkOrThrow (webfingerData: WebFingerData) {
38 if (Array.isArray(webfingerData.links) === false) throw new Error('WebFinger links is not an array.')
40 const selfLink = webfingerData.links.find(l => l.rel === 'self')
41 if (selfLink === undefined || isActivityPubUrlValid(selfLink.href) === false) {
42 throw new Error('Cannot find self link or href is not a valid URL.')
48 function webfingerLookup (nameWithHost: string) {
49 return new Promise<WebFingerData>((res, rej) => {
50 webfinger.lookup(nameWithHost, (err, p) => {
51 if (err) return rej(err)