aboutsummaryrefslogtreecommitdiff
path: root/vnext/server/middleware/webfinger.js
blob: 873387b37d4b2cf9ebd765aa744c7745ee736ebb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import config from 'config'
import addrparser from 'address-rfc2822'
import debug from 'debug'
var log = debug('webfinger')

import { getUserByName } from '../db/Users'

const baseUrl = config.get('service.baseURL')

/**
 * WebFinger endpoint
 * @type {import('express').RequestParamHandler}
 */
export const webfinger = async (req, res) => {
    const resource = req.query.resource
    if (resource) {
        const acct = resource.substring(5) // drop "acct:"
        const addresses = parseAddress(acct)
        if (addresses && addresses.length == 1) {
            const address = addresses[0]
            const ourAddress = new URL(baseUrl)
            if (address.host() === ourAddress.hostname) {
                const name = addresses[0].user()
                const user = await getUserByName(name)
                if (user) {
                    return res.json({
                        subject: resource,
                        links: [
                            {
                                rel: 'self',
                                type: 'application/activity+json',
                                href: `${baseUrl}/u/${user.nick}`
                            }
                        ]
                    })
                } else {
                    log(`User not found: ${name}`)
                    return res.status(404).end()
                }
            } else {
                log(`Address not found: ${address.host()}`)
                return res.status(404).end()
            }
        } else {
            log(`Invalid resource: ${resource}`)
            return res.status(400).end()
        }
    }
    log('Missing `resource` param')
    res.status(400)
}

const parseAddress = (address = '') => {
    try {
        return addrparser.parse(address, { startAt: 'address' })
    } catch {
        return undefined
    }
}