PeerTube/server/helpers/webfinger.ts

48 lines
1.4 KiB
TypeScript
Raw Normal View History

2017-11-09 10:51:58 -06:00
import * as WebFinger from 'webfinger.js'
import { WebFingerData } from '../../shared'
2017-11-21 06:43:29 -06:00
import { fetchRemoteAccount } from '../lib/activitypub/account'
2017-11-09 10:51:58 -06:00
import { isTestInstance } from './core-utils'
import { isActivityPubUrlValid } from './custom-validators'
const webfinger = new WebFinger({
webfist_fallback: false,
tls_only: isTestInstance(),
uri_fallback: false,
request_timeout: 3000
})
2017-11-14 10:31:26 -06:00
async function getAccountFromWebfinger (nameWithHost: string) {
const webfingerData: WebFingerData = await webfingerLookup(nameWithHost)
2017-11-09 10:51:58 -06:00
2017-11-14 10:31:26 -06:00
if (Array.isArray(webfingerData.links) === false) throw new Error('WebFinger links is not an array.')
2017-11-09 10:51:58 -06:00
const selfLink = webfingerData.links.find(l => l.rel === 'self')
2017-11-14 10:31:26 -06:00
if (selfLink === undefined || isActivityPubUrlValid(selfLink.href) === false) {
throw new Error('Cannot find self link or href is not a valid URL.')
}
2017-11-09 10:51:58 -06:00
2017-11-21 06:43:29 -06:00
const account = await fetchRemoteAccount(selfLink.href)
if (account === undefined) throw new Error('Cannot fetch remote account ' + selfLink.href)
2017-11-09 10:51:58 -06:00
2017-11-21 06:43:29 -06:00
return account
2017-11-09 10:51:58 -06:00
}
// ---------------------------------------------------------------------------
export {
getAccountFromWebfinger
}
// ---------------------------------------------------------------------------
2017-11-14 10:31:26 -06:00
function webfingerLookup (nameWithHost: string) {
2017-11-09 10:51:58 -06:00
return new Promise<WebFingerData>((res, rej) => {
2017-11-14 10:31:26 -06:00
webfinger.lookup(nameWithHost, (err, p) => {
2017-11-09 10:51:58 -06:00
if (err) return rej(err)
2017-11-14 10:31:26 -06:00
return res(p.object)
2017-11-09 10:51:58 -06:00
})
})
}