PeerTube/server/helpers/webfinger.ts

55 lines
1.6 KiB
TypeScript
Raw Normal View History

2017-11-09 17:51:58 +01:00
import * as WebFinger from 'webfinger.js'
import { WebFingerData } from '../../shared'
2017-12-14 17:38:41 +01:00
import { ActorModel } from '../models/activitypub/actor'
2017-11-09 17:51:58 +01:00
import { isTestInstance } from './core-utils'
2017-12-28 11:16:08 +01:00
import { isActivityPubUrlValid } from './custom-validators/activitypub/misc'
2017-11-09 17:51:58 +01:00
const webfinger = new WebFinger({
webfist_fallback: false,
tls_only: isTestInstance(),
uri_fallback: false,
request_timeout: 3000
})
2017-12-14 17:38:41 +01:00
async function loadActorUrlOrGetFromWebfinger (name: string, host: string) {
const actor = await ActorModel.loadByNameAndHost(name, host)
if (actor) return actor.url
2017-11-09 17:51:58 +01:00
2018-01-04 14:04:02 +01:00
return getUrlFromWebfinger(name, host)
}
async function getUrlFromWebfinger (name: string, host: string) {
2017-12-14 17:38:41 +01:00
const webfingerData: WebFingerData = await webfingerLookup(name + '@' + host)
return getLinkOrThrow(webfingerData)
2017-11-09 17:51:58 +01:00
}
// ---------------------------------------------------------------------------
export {
2018-01-04 14:04:02 +01:00
getUrlFromWebfinger,
2017-12-14 17:38:41 +01:00
loadActorUrlOrGetFromWebfinger
2017-11-09 17:51:58 +01:00
}
// ---------------------------------------------------------------------------
2017-12-14 17:38:41 +01:00
function getLinkOrThrow (webfingerData: WebFingerData) {
if (Array.isArray(webfingerData.links) === false) throw new Error('WebFinger links is not an array.')
const selfLink = webfingerData.links.find(l => l.rel === 'self')
if (selfLink === undefined || isActivityPubUrlValid(selfLink.href) === false) {
throw new Error('Cannot find self link or href is not a valid URL.')
}
return selfLink.href
}
2017-11-14 17:31:26 +01:00
function webfingerLookup (nameWithHost: string) {
2017-11-09 17:51:58 +01:00
return new Promise<WebFingerData>((res, rej) => {
2017-11-14 17:31:26 +01:00
webfinger.lookup(nameWithHost, (err, p) => {
2017-11-09 17:51:58 +01:00
if (err) return rej(err)
2017-11-14 17:31:26 +01:00
return res(p.object)
2017-11-09 17:51:58 +01:00
})
})
}