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