summary refs log tree commit diff
path: root/src/activitypub/Server.ts
blob: 97deb13778d800826605f3383fa083b017e368e9 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { BodyParser, CORS, ErrorHandler } from "@spacebar/api";
import {
	Config,
	JSONReplacer,
	initDatabase,
	registerRoutes,
} from "@spacebar/util";
import bodyParser from "body-parser";
import { Request, Response, Router } from "express";
import { Server, ServerOptions } from "lambert-server";
import path from "path";
import { setupListener } from "./listener";
import hostMeta from "./well-known/host-meta";
import webfinger from "./well-known/webfinger";

export class APServer extends Server {
	public declare options: ServerOptions;

	constructor(opts?: Partial<ServerOptions>) {
		// eslint-disable-next-line @typescript-eslint/ban-ts-comment
		// @ts-ignore
		super({ ...opts, errorHandler: false, jsonBody: false });
	}

	async start() {
		await initDatabase();
		await Config.init();
		setupListener();

		this.app.set("json replacer", JSONReplacer);

		this.app.use(CORS);
		this.app.use(
			BodyParser({
				inflate: true,
				limit: "10mb",
				type: "application/activity+json",
			}),
		);
		this.app.use(bodyParser.urlencoded({ extended: true }));

		const api = Router();
		const app = this.app;

		// eslint-disable-next-line @typescript-eslint/ban-ts-comment
		// @ts-ignore
		// lambert server is lame
		this.app = api;

		this.routes = await registerRoutes(
			this,
			path.join(__dirname, "routes", "/"),
		);

		api.use("*", (req: Request, res: Response) => {
			res.status(404).json({
				message: "404 endpoint not found",
				code: 0,
			});
		});

		this.app = app;

		this.app.use("*", (req, res, next) => {
			res.setHeader(
				"Content-Type",
				"application/activity+json; charset=utf-8",
			);
			next();
		});
		this.app.use("/fed", api);
		this.app.get("/fed", (req, res) => {
			res.json({ ping: "pong" });
		});

		this.app.use("/.well-known/webfinger", webfinger);
		this.app.use("/.well-known/host-meta", hostMeta);

		this.app.use(ErrorHandler);

		return super.start();
	}
}