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