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