Skip to content

Node.js based forum software built for the modern web

1.6 KB
Raw Blame
'use strict';

const Intents = module.exports;

const activitypub = require('../../activitypub');
const meta = require('../../meta');

const helpers = require('../helpers');
const clientIp = require('../../ip');
const ratelimit = require('../../ratelimit');

const RATE_LIMIT_WINDOW = 5000; // 5 seconds

async function checkRateLimit(ip) {
	const withinLimit = await ratelimit.check(`locks:intents:query:${ip}`, {
		window: RATE_LIMIT_WINDOW,
		max: 1,
	});
	if (!withinLimit) {
		throw new Error('[[error:api.429]]');
	}
}

Intents.query = async (req, res, next) => {
	if (!meta.config.activitypubEnabled) {
		return next();
	}

	const ip = clientIp.getClientIp(req);
	await checkRateLimit(ip);

	let { handle } = req.params;
	handle = handle.trim().replace(/^@/, '');
	const webfinger = await activitypub.helpers.query(handle);

	// Parse out intents
	let intents = [];
	const prefix = 'https://w3id.org/fep/3b86/';
	if (!webfinger || !webfinger?._raw?.links) {
		helpers.formatApiResponse(200, res, { intents });
		return;
	}
	intents = webfinger._raw.links.reduce((memo, link) => {
		if (link.rel.startsWith(prefix)) {
			const intent = link.rel.slice(prefix.length).toLowerCase();
			// Reject non-http/https URLs to prevent XSS via javascript: data: etc.
			try {
				const parsed = new URL(link.template);
				if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
					return memo; // silently skip untrusted schemes
				}
			} catch (e) {
				return memo; // invalid URL, skip
			}
			memo[intent] = link.template;
		}
		return memo;
	}, {});
	helpers.formatApiResponse(200, res, { intents });
};