]> Untitled Git - lemmy-ui.git/blob - src/server/middleware.ts
Fixing comment report showing dot. (#1989)
[lemmy-ui.git] / src / server / middleware.ts
1 import * as crypto from "crypto";
2 import type { NextFunction, Request, Response } from "express";
3 import { hasJwtCookie } from "./utils/has-jwt-cookie";
4
5 export function setDefaultCsp({
6   res,
7   next,
8 }: {
9   res: Response;
10   next: NextFunction;
11 }) {
12   res.locals.cspNonce = crypto.randomBytes(16).toString("hex");
13
14   res.setHeader(
15     "Content-Security-Policy",
16     `default-src 'self';
17      manifest-src *;
18      connect-src *;
19      img-src * data:;
20      script-src 'self' 'nonce-${res.locals.cspNonce}';
21      style-src 'self' 'unsafe-inline';
22      form-action 'self';
23      base-uri 'self';
24      frame-src *;
25      media-src * data:`.replace(/\s+/g, " ")
26   );
27
28   next();
29 }
30
31 // Set cache-control headers. If user is logged in, set `private` to prevent storing data in
32 // shared caches (eg nginx) and leaking of private data. If user is not logged in, allow caching
33 // all responses for 5 seconds to reduce load on backend and database. The specific cache
34 // interval is rather arbitrary and could be set higher (less server load) or lower (fresher data).
35 //
36 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
37 export function setCacheControl(
38   req: Request,
39   res: Response,
40   next: NextFunction
41 ) {
42   if (process.env.NODE_ENV !== "production") {
43     return next();
44   }
45
46   let caching: string;
47
48   if (
49     req.path.match(/\.(js|css|txt|manifest\.webmanifest)\/?$/) ||
50     req.path.includes("/css/themelist")
51   ) {
52     // Static content gets cached publicly for a day
53     caching = "public, max-age=86400";
54   } else {
55     if (hasJwtCookie(req)) {
56       caching = "private";
57     } else {
58       caching = "public, max-age=5";
59     }
60   }
61
62   res.setHeader("Cache-Control", caching);
63
64   next();
65 }