]> Untitled Git - lemmy-ui.git/blob - src/server/index.tsx
Fix symbols issue. Fixes #319
[lemmy-ui.git] / src / server / index.tsx
1 import serialize from "serialize-javascript";
2 import express from "express";
3 import { StaticRouter } from "inferno-router";
4 import { renderToString } from "inferno-server";
5 import { matchPath } from "inferno-router";
6 import path from "path";
7 import { App } from "../shared/components/app";
8 import {
9   ILemmyConfig,
10   InitialFetchRequest,
11   IsoData,
12 } from "../shared/interfaces";
13 import { routes } from "../shared/routes";
14 import IsomorphicCookie from "isomorphic-cookie";
15 import { GetSite, GetSiteResponse, LemmyHttp } from "lemmy-js-client";
16 import process from "process";
17 import { Helmet } from "inferno-helmet";
18 import { SYMBOLS } from "../shared/components/symbols";
19 import { initializeSite } from "../shared/initialize";
20 import { httpBaseInternal } from "../shared/env";
21 import { IncomingHttpHeaders } from "http";
22 import { setOptionalAuth } 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
29 server.use(express.json());
30 server.use(express.urlencoded({ extended: false }));
31 server.use("/static", express.static(path.resolve("./dist")));
32
33 // server.use(cookieParser());
34
35 server.get("/*", async (req, res) => {
36   const activeRoute = routes.find(route => matchPath(req.path, route)) || {};
37   const context = {} as any;
38   let auth: string = IsomorphicCookie.load("jwt", req);
39
40   let getSiteForm: GetSite = {};
41   setOptionalAuth(getSiteForm, auth);
42
43   let promises: Promise<any>[] = [];
44
45   let headers = setForwardedHeaders(req.headers);
46
47   let initialFetchReq: InitialFetchRequest = {
48     client: new LemmyHttp(httpBaseInternal, headers),
49     auth,
50     path: req.path,
51   };
52
53   // Get site data first
54   // This bypasses errors, so that the client can hit the error on its own,
55   // in order to remove the jwt on the browser. Necessary for wrong jwts
56   let try_site: any = await initialFetchReq.client.getSite(getSiteForm);
57   if (try_site.error == "not_logged_in") {
58     console.error(
59       "Incorrect JWT token, skipping auth so frontend can remove jwt cookie"
60     );
61     delete getSiteForm.auth;
62     delete initialFetchReq.auth;
63     try_site = await initialFetchReq.client.getSite(getSiteForm);
64   }
65   let site: GetSiteResponse = try_site;
66   initializeSite(site);
67
68   if (activeRoute.fetchInitialData) {
69     promises.push(...activeRoute.fetchInitialData(initialFetchReq));
70   }
71
72   let routeData = await Promise.all(promises);
73
74   // Redirect to the 404 if there's an API error
75   if (routeData[0] && routeData[0].error) {
76     let errCode = routeData[0].error;
77     return res.redirect(`/404?err=${errCode}`);
78   }
79
80   let acceptLang = req.headers["accept-language"]
81     ? req.headers["accept-language"].split(",")[0]
82     : "en";
83   let lang = site.my_user
84     ? site.my_user.local_user.lang == "browser"
85       ? acceptLang
86       : "en"
87     : acceptLang;
88
89   let isoData: IsoData = {
90     path: req.path,
91     site_res: site,
92     routeData,
93     lang,
94   };
95
96   const wrapper = (
97     <StaticRouter location={req.url} context={isoData}>
98       <App siteRes={isoData.site_res} />
99     </StaticRouter>
100   );
101   if (context.url) {
102     return res.redirect(context.url);
103   }
104
105   const cspHtml = (
106     <meta
107       http-equiv="Content-Security-Policy"
108       content="default-src data: 'self'; connect-src * ws: wss:; frame-src *; img-src * data:; script-src 'self'; style-src 'self' 'unsafe-inline'; manifest-src 'self'"
109     />
110   );
111
112   const root = renderToString(wrapper);
113   const symbols = renderToString(SYMBOLS);
114   const cspStr = process.env.LEMMY_EXTERNAL_HOST ? renderToString(cspHtml) : "";
115   const helmet = Helmet.renderStatic();
116
117   const config: ILemmyConfig = { wsHost: process.env.LEMMY_WS_HOST };
118
119   res.send(`
120            <!DOCTYPE html>
121            <html ${helmet.htmlAttributes.toString()} lang="en">
122            <head>
123            <script>window.isoData = ${serialize(isoData)}</script>
124            <script>window.lemmyConfig = ${serialize(config)}</script>
125
126            ${helmet.title.toString()}
127            ${helmet.meta.toString()}
128
129            <!-- Required meta tags -->
130            <meta name="Description" content="Lemmy">
131            <meta charset="utf-8">
132            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
133
134            <!-- Content Security Policy -->
135            ${cspStr}
136
137            <!-- Web app manifest -->
138            <link rel="manifest" href="/static/assets/manifest.webmanifest">
139
140            <!-- Styles -->
141            <link rel="stylesheet" type="text/css" href="/static/styles/styles.css" />
142
143            <!-- Current theme and more -->
144            ${helmet.link.toString()}
145            
146            <!-- Icons -->
147            ${symbols}
148
149            </head>
150
151            <body ${helmet.bodyAttributes.toString()}>
152              <noscript>
153                <div class="alert alert-danger rounded-0" role="alert">
154                  <b>Javascript is disabled. Actions will not work.</b>
155                </div>
156              </noscript>
157
158              <div id='root'>${root}</div>
159              <script defer src='/static/js/client.js'></script>
160            </body>
161          </html>
162 `);
163 });
164
165 server.listen(Number(port), hostname, () => {
166   console.log(`http://${hostname}:${port}`);
167 });
168
169 function setForwardedHeaders(headers: IncomingHttpHeaders): {
170   [key: string]: string;
171 } {
172   let out = {
173     host: headers.host,
174   };
175   if (headers["x-real-ip"]) {
176     out["x-real-ip"] = headers["x-real-ip"];
177   }
178   if (headers["x-forwarded-for"]) {
179     out["x-forwarded-for"] = headers["x-forwarded-for"];
180   }
181
182   return out;
183 }
184
185 process.on("SIGINT", () => {
186   console.info("Interrupted");
187   process.exit(0);
188 });