1
0
Fork 0
peertube/server/lib/activitypub/actors/webfinger.ts

68 lines
2 KiB
TypeScript
Raw Normal View History

2021-08-27 08:32:44 -04:00
import WebFinger from 'webfinger.js'
2021-07-01 11:04:13 -04:00
import { isProdInstance } from '@server/helpers/core-utils'
import { isActivityPubUrlValid } from '@server/helpers/custom-validators/activitypub/misc'
2021-11-29 09:45:02 -05:00
import { REQUEST_TIMEOUTS, WEBSERVER } from '@server/initializers/constants'
import { ActorModel } from '@server/models/actor/actor'
import { MActorFull } from '@server/types/models'
import { WebFingerData } from '@shared/models'
2017-11-09 11:51:58 -05:00
const webfinger = new WebFinger({
webfist_fallback: false,
2021-07-01 11:04:13 -04:00
tls_only: isProdInstance(),
2017-11-09 11:51:58 -05:00
uri_fallback: false,
2021-11-29 09:45:02 -05:00
request_timeout: REQUEST_TIMEOUTS.DEFAULT
2017-11-09 11:51:58 -05:00
})
async function loadActorUrlOrGetFromWebfinger (uriArg: string) {
// Handle strings like @toto@example.com
const uri = uriArg.startsWith('@') ? uriArg.slice(1) : uriArg
const [ name, host ] = uri.split('@')
2019-08-15 05:53:26 -04:00
let actor: MActorFull
2018-08-24 05:04:02 -04:00
2019-05-28 04:04:07 -04:00
if (!host || host === WEBSERVER.HOST) {
2018-08-24 05:04:02 -04:00
actor = await ActorModel.loadLocalByName(name)
} else {
actor = await ActorModel.loadByNameAndHost(name, host)
}
2017-12-14 11:38:41 -05:00
if (actor) return actor.url
2017-11-09 11:51:58 -05:00
return getUrlFromWebfinger(uri)
2018-01-04 08:04:02 -05:00
}
async function getUrlFromWebfinger (uri: string) {
const webfingerData: WebFingerData = await webfingerLookup(uri)
2017-12-14 11:38:41 -05:00
return getLinkOrThrow(webfingerData)
2017-11-09 11:51:58 -05:00
}
// ---------------------------------------------------------------------------
export {
2018-01-04 08:04:02 -05:00
getUrlFromWebfinger,
2017-12-14 11:38:41 -05:00
loadActorUrlOrGetFromWebfinger
2017-11-09 11:51:58 -05:00
}
// ---------------------------------------------------------------------------
2017-12-14 11:38:41 -05: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 11:31:26 -05:00
function webfingerLookup (nameWithHost: string) {
2017-11-09 11:51:58 -05:00
return new Promise<WebFingerData>((res, rej) => {
2017-11-14 11:31:26 -05:00
webfinger.lookup(nameWithHost, (err, p) => {
2017-11-09 11:51:58 -05:00
if (err) return rej(err)
2017-11-14 11:31:26 -05:00
return res(p.object)
2017-11-09 11:51:58 -05:00
})
})
}