aboutsummaryrefslogtreecommitdiffstats
path: root/lib/app.ts
blob: fc86a3f2225c477d42c7e6ae70eac989dca277b1 (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
import config from "$config";
import fastify from "fastify";
import fastifyMultipart from "@fastify/multipart";
import fastifyStatic from "@fastify/static";
import fastifyPassport from "@fastify/passport";
import fastifySecureSession from "@fastify/secure-session";
import fastifyProxy from "@fastify/http-proxy";
import fastifyRateLimit from "@fastify/rate-limit";
import cors from "@fastify/cors";

import * as path from "path";
import pino from "pino";

import { jwtStrategy } from "$lib/auth";

const app = fastify({
  logger: pino(),
  disableRequestLogging: true,
  maxParamLength: 500,
});

app.register(fastifyRateLimit, {
  allowList: (req) => req.raw.url?.includes("public"),
  max: 100,
  timeWindow: 2000,
  keyGenerator: (req) => req.headers["cf-connecting-ip"] as string,
  errorResponseBuilder: () => {
    return {
      statusCode: 429,
      error: "Too Many Requests",
      message: "Rate limit exceeded, retry in 2 seconds",
    };
  },
});

app.register(fastifyProxy, {
  upstream: "http://localhost:3120",
  prefix: "/ws",
  rewritePrefix: "/ws",
  websocket: true
});

app.register(fastifySecureSession, {
  key: Buffer.from(config.jwt, "hex"),
});

app.register(fastifyPassport.initialize());
app.register(fastifyPassport.secureSession());

fastifyPassport.use("jwt", jwtStrategy);

app.register(fastifyMultipart, { limits: { fileSize: 10 ** 7 } });

app.register(fastifyStatic, {
  root: path.join("/home/bun/app/data/uploads"),
  prefix: "/public/",
});

await app.register(cors, { origin: true });

app.setErrorHandler((error, _, reply) => {
  if (error instanceof fastify.errorCodes.FST_ERR_BAD_STATUS_CODE) {
    reply.status(500).send({ ok: false });
  } else {
    reply.send(error);
  }
});

app.setNotFoundHandler((_, reply) =>
  reply.code(404).type("text/html").send("Not Found"),
);

export default app;