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