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 (name: string, host: string) {
15 const actor = await ActorModel.loadByNameAndHost(name, host)
16 if (actor) return actor.url
18 return getUrlFromWebfinger(name, host)
21 async function getUrlFromWebfinger (name: string, host: string) {
22 const webfingerData: WebFingerData = await webfingerLookup(name + '@' + host)
23 return getLinkOrThrow(webfingerData)
26 // ---------------------------------------------------------------------------
30 loadActorUrlOrGetFromWebfinger
33 // ---------------------------------------------------------------------------
35 function getLinkOrThrow (webfingerData: WebFingerData) {
36 if (Array.isArray(webfingerData.links) === false) throw new Error('WebFinger links is not an array.')
38 const selfLink = webfingerData.links.find(l => l.rel === 'self')
39 if (selfLink === undefined || isActivityPubUrlValid(selfLink.href) === false) {
40 throw new Error('Cannot find self link or href is not a valid URL.')
46 function webfingerLookup (nameWithHost: string) {
47 return new Promise<WebFingerData>((res, rej) => {
48 webfinger.lookup(nameWithHost, (err, p) => {
49 if (err) return rej(err)