]> Untitled Git - lemmy-ui.git/blob - src/server/index.tsx
Set content security policy http header for all responses (#608)
[lemmy-ui.git] / src / server / index.tsx
1 import express from "express";
2 import fs from "fs";
3 import { IncomingHttpHeaders } from "http";
4 import { Helmet } from "inferno-helmet";
5 import { matchPath, StaticRouter } from "inferno-router";
6 import { renderToString } from "inferno-server";
7 import IsomorphicCookie from "isomorphic-cookie";
8 import { GetSite, GetSiteResponse, LemmyHttp } from "lemmy-js-client";
9 import path from "path";
10 import process from "process";
11 import serialize from "serialize-javascript";
12 import { App } from "../shared/components/app/app";
13 import { SYMBOLS } from "../shared/components/common/symbols";
14 import { httpBaseInternal } from "../shared/env";
15 import {
16   ILemmyConfig,
17   InitialFetchRequest,
18   IsoData,
19 } from "../shared/interfaces";
20 import { routes } from "../shared/routes";
21 import { initializeSite, setOptionalAuth } from "../shared/utils";
22
23 const server = express();
24 const [hostname, port] = process.env["LEMMY_UI_HOST"]
25   ? process.env["LEMMY_UI_HOST"].split(":")
26   : ["0.0.0.0", "1234"];
27 const extraThemesFolder =
28   process.env["LEMMY_UI_EXTRA_THEMES_FOLDER"] || "./extra_themes";
29
30 server.use(function (_req, res, next) {
31   res.setHeader(
32     "Content-Security-Policy",
33     "default-src data: 'self'; connect-src * ws: wss:; frame-src *; img-src * data:; script-src 'self'; style-src 'self' 'unsafe-inline'; manifest-src 'self'"
34   );
35   next();
36 });
37 server.use(express.json());
38 server.use(express.urlencoded({ extended: false }));
39 server.use("/static", express.static(path.resolve("./dist")));
40
41 const robotstxt = `User-Agent: *
42 Disallow: /login
43 Disallow: /settings
44 Disallow: /create_community
45 Disallow: /create_post
46 Disallow: /create_private_message
47 Disallow: /inbox
48 Disallow: /setup
49 Disallow: /admin
50 Disallow: /password_change
51 Disallow: /search/
52 `;
53
54 server.get("/robots.txt", async (_req, res) => {
55   res.setHeader("content-type", "text/plain; charset=utf-8");
56   res.send(robotstxt);
57 });
58
59 server.get("/css/themes/:name", async (req, res) => {
60   res.contentType("text/css");
61   const theme = req.params.name;
62   if (!theme.endsWith(".css")) {
63     res.send("Theme must be a css file");
64   }
65
66   const customTheme = path.resolve(`./${extraThemesFolder}/${theme}`);
67   if (fs.existsSync(customTheme)) {
68     res.sendFile(customTheme);
69   } else {
70     const internalTheme = path.resolve(`./dist/assets/css/themes/${theme}`);
71     res.sendFile(internalTheme);
72   }
73 });
74
75 function buildThemeList(): string[] {
76   let themes = [
77     "litera",
78     "materia",
79     "minty",
80     "solar",
81     "united",
82     "cyborg",
83     "darkly",
84     "journal",
85     "sketchy",
86     "vaporwave",
87     "vaporwave-dark",
88     "i386",
89     "litely",
90     "nord",
91   ];
92   if (fs.existsSync(extraThemesFolder)) {
93     let dirThemes = fs.readdirSync(extraThemesFolder);
94     let cssThemes = dirThemes
95       .filter(d => d.endsWith(".css"))
96       .map(d => d.replace(".css", ""));
97     themes.push(...cssThemes);
98   }
99   return themes;
100 }
101
102 server.get("/css/themelist", async (_req, res) => {
103   res.type("json");
104   res.send(JSON.stringify(buildThemeList()));
105 });
106
107 // server.use(cookieParser());
108 server.get("/*", async (req, res) => {
109   try {
110     const activeRoute = routes.find(route => matchPath(req.path, route)) || {};
111     const context = {} as any;
112     let auth: string = IsomorphicCookie.load("jwt", req);
113
114     let getSiteForm: GetSite = {};
115     setOptionalAuth(getSiteForm, auth);
116
117     let promises: Promise<any>[] = [];
118
119     let headers = setForwardedHeaders(req.headers);
120
121     let initialFetchReq: InitialFetchRequest = {
122       client: new LemmyHttp(httpBaseInternal, headers),
123       auth,
124       path: req.path,
125     };
126
127     // Get site data first
128     // This bypasses errors, so that the client can hit the error on its own,
129     // in order to remove the jwt on the browser. Necessary for wrong jwts
130     let try_site: any = await initialFetchReq.client.getSite(getSiteForm);
131     if (try_site.error == "not_logged_in") {
132       console.error(
133         "Incorrect JWT token, skipping auth so frontend can remove jwt cookie"
134       );
135       delete getSiteForm.auth;
136       delete initialFetchReq.auth;
137       try_site = await initialFetchReq.client.getSite(getSiteForm);
138     }
139     let site: GetSiteResponse = try_site;
140     initializeSite(site);
141
142     if (activeRoute.fetchInitialData) {
143       promises.push(...activeRoute.fetchInitialData(initialFetchReq));
144     }
145
146     let routeData = await Promise.all(promises);
147
148     // Redirect to the 404 if there's an API error
149     if (routeData[0] && routeData[0].error) {
150       let errCode = routeData[0].error;
151       console.error(errCode);
152       if (errCode == "instance_is_private") {
153         return res.redirect(`/signup`);
154       } else {
155         return res.send(`404: ${removeAuthParam(errCode)}`);
156       }
157     }
158
159     let isoData: IsoData = {
160       path: req.path,
161       site_res: site,
162       routeData,
163     };
164
165     const wrapper = (
166       <StaticRouter location={req.url} context={isoData}>
167         <App siteRes={isoData.site_res} />
168       </StaticRouter>
169     );
170     if (context.url) {
171       return res.redirect(context.url);
172     }
173
174     const root = renderToString(wrapper);
175     const symbols = renderToString(SYMBOLS);
176     const helmet = Helmet.renderStatic();
177
178     const config: ILemmyConfig = { wsHost: process.env.LEMMY_WS_HOST };
179
180     res.send(`
181            <!DOCTYPE html>
182            <html ${helmet.htmlAttributes.toString()} lang="en">
183            <head>
184            <script>window.isoData = ${serialize(isoData)}</script>
185            <script>window.lemmyConfig = ${serialize(config)}</script>
186
187            <!-- A remote debugging utility for mobile
188            <script src="//cdn.jsdelivr.net/npm/eruda"></script>
189            <script>eruda.init();</script>
190            -->
191
192            ${helmet.title.toString()}
193            ${helmet.meta.toString()}
194
195            <!-- Required meta tags -->
196            <meta name="Description" content="Lemmy">
197            <meta charset="utf-8">
198            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
199
200            <!-- Web app manifest -->
201            <link rel="manifest" href="/static/assets/manifest.webmanifest">
202
203            <!-- Styles -->
204            <link rel="stylesheet" type="text/css" href="/static/styles/styles.css" />
205
206            <!-- Current theme and more -->
207            ${helmet.link.toString()}
208            
209            <!-- Icons -->
210            ${symbols}
211
212            </head>
213
214            <body ${helmet.bodyAttributes.toString()}>
215              <noscript>
216                <div class="alert alert-danger rounded-0" role="alert">
217                  <b>Javascript is disabled. Actions will not work.</b>
218                </div>
219              </noscript>
220
221              <div id='root'>${root}</div>
222              <script defer src='/static/js/client.js'></script>
223            </body>
224          </html>
225 `);
226   } catch (err) {
227     console.error(err);
228     return res.send(`404: ${removeAuthParam(err)}`);
229   }
230 });
231
232 server.listen(Number(port), hostname, () => {
233   console.log(`http://${hostname}:${port}`);
234 });
235
236 function setForwardedHeaders(headers: IncomingHttpHeaders): {
237   [key: string]: string;
238 } {
239   let out = {
240     host: headers.host,
241   };
242   if (headers["x-real-ip"]) {
243     out["x-real-ip"] = headers["x-real-ip"];
244   }
245   if (headers["x-forwarded-for"]) {
246     out["x-forwarded-for"] = headers["x-forwarded-for"];
247   }
248
249   return out;
250 }
251
252 process.on("SIGINT", () => {
253   console.info("Interrupted");
254   process.exit(0);
255 });
256
257 function removeAuthParam(err: any): string {
258   return removeParam(err.toString(), "auth");
259 }
260
261 function removeParam(url: string, parameter: string): string {
262   return url
263     .replace(new RegExp("[?&]" + parameter + "=[^&#]*(#.*)?$"), "$1")
264     .replace(new RegExp("([?&])" + parameter + "=[^&]*&"), "$1");
265 }