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