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