]>
Commit | Line | Data |
---|---|---|
e4f97bab | 1 | import * as WebFinger from 'webfinger.js' |
892211e8 | 2 | import { WebFingerData } from '../../shared' |
50d6de9c | 3 | import { ActorModel } from '../models/activitypub/actor' |
e4f97bab | 4 | import { isTestInstance } from './core-utils' |
da854ddd | 5 | import { isActivityPubUrlValid } from './custom-validators/activitypub/misc' |
f5b0af50 | 6 | import { CONFIG } from '../initializers' |
e4f97bab C |
7 | |
8 | const webfinger = new WebFinger({ | |
9 | webfist_fallback: false, | |
10 | tls_only: isTestInstance(), | |
11 | uri_fallback: false, | |
12 | request_timeout: 3000 | |
13 | }) | |
14 | ||
06a05d5f C |
15 | async function loadActorUrlOrGetFromWebfinger (uri: string) { |
16 | const [ name, host ] = uri.split('@') | |
f5b0af50 C |
17 | let actor: ActorModel |
18 | ||
19 | if (host === CONFIG.WEBSERVER.HOST) { | |
20 | actor = await ActorModel.loadLocalByName(name) | |
21 | } else { | |
22 | actor = await ActorModel.loadByNameAndHost(name, host) | |
23 | } | |
06a05d5f | 24 | |
50d6de9c | 25 | if (actor) return actor.url |
e4f97bab | 26 | |
06a05d5f | 27 | return getUrlFromWebfinger(uri) |
a5625b41 C |
28 | } |
29 | ||
06a05d5f C |
30 | async function getUrlFromWebfinger (uri: string) { |
31 | const webfingerData: WebFingerData = await webfingerLookup(uri) | |
50d6de9c | 32 | return getLinkOrThrow(webfingerData) |
e4f97bab C |
33 | } |
34 | ||
35 | // --------------------------------------------------------------------------- | |
36 | ||
37 | export { | |
a5625b41 | 38 | getUrlFromWebfinger, |
50d6de9c | 39 | loadActorUrlOrGetFromWebfinger |
e4f97bab C |
40 | } |
41 | ||
42 | // --------------------------------------------------------------------------- | |
43 | ||
50d6de9c C |
44 | function getLinkOrThrow (webfingerData: WebFingerData) { |
45 | if (Array.isArray(webfingerData.links) === false) throw new Error('WebFinger links is not an array.') | |
46 | ||
47 | const selfLink = webfingerData.links.find(l => l.rel === 'self') | |
48 | if (selfLink === undefined || isActivityPubUrlValid(selfLink.href) === false) { | |
49 | throw new Error('Cannot find self link or href is not a valid URL.') | |
50 | } | |
51 | ||
52 | return selfLink.href | |
53 | } | |
54 | ||
350e31d6 | 55 | function webfingerLookup (nameWithHost: string) { |
e4f97bab | 56 | return new Promise<WebFingerData>((res, rej) => { |
350e31d6 | 57 | webfinger.lookup(nameWithHost, (err, p) => { |
e4f97bab C |
58 | if (err) return rej(err) |
59 | ||
350e31d6 | 60 | return res(p.object) |
e4f97bab C |
61 | }) |
62 | }) | |
63 | } |