]> Untitled Git - lemmy-ui.git/blob - src/server/index.tsx
Fix server redirect error
[lemmy-ui.git] / src / server / index.tsx
1 import express from "express";
2 import { existsSync } from "fs";
3 import { readdir, readFile } from "fs/promises";
4 import { IncomingHttpHeaders } from "http";
5 import { Helmet } from "inferno-helmet";
6 import { matchPath, StaticRouter } from "inferno-router";
7 import { renderToString } from "inferno-server";
8 import IsomorphicCookie from "isomorphic-cookie";
9 import { GetSite, GetSiteResponse, LemmyHttp, Site } from "lemmy-js-client";
10 import path from "path";
11 import process from "process";
12 import serialize from "serialize-javascript";
13 import sharp from "sharp";
14 import { App } from "../shared/components/app/app";
15 import { getHttpBase, getHttpBaseInternal } from "../shared/env";
16 import {
17   ILemmyConfig,
18   InitialFetchRequest,
19   IsoData,
20 } from "../shared/interfaces";
21 import { routes } from "../shared/routes";
22 import {
23   ErrorPageData,
24   favIconPngUrl,
25   favIconUrl,
26   initializeSite,
27   isAuthPath,
28 } from "../shared/utils";
29 import { VERSION } from "../shared/version";
30
31 const server = express();
32 const [hostname, port] = process.env["LEMMY_UI_HOST"]
33   ? process.env["LEMMY_UI_HOST"].split(":")
34   : ["0.0.0.0", "1234"];
35 const extraThemesFolder =
36   process.env["LEMMY_UI_EXTRA_THEMES_FOLDER"] || "./extra_themes";
37
38 if (!process.env["LEMMY_UI_DISABLE_CSP"] && !process.env["LEMMY_UI_DEBUG"]) {
39   server.use(function (_req, res, next) {
40     res.setHeader(
41       "Content-Security-Policy",
42       `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 *`
43     );
44     next();
45   });
46 }
47 const customHtmlHeader = process.env["LEMMY_UI_CUSTOM_HTML_HEADER"] || "";
48
49 server.use(express.json());
50 server.use(express.urlencoded({ extended: false }));
51 server.use("/static", express.static(path.resolve("./dist")));
52
53 const robotstxt = `User-Agent: *
54 Disallow: /login
55 Disallow: /settings
56 Disallow: /create_community
57 Disallow: /create_post
58 Disallow: /create_private_message
59 Disallow: /inbox
60 Disallow: /setup
61 Disallow: /admin
62 Disallow: /password_change
63 Disallow: /search/
64 `;
65
66 server.get("/service-worker.js", async (_req, res) => {
67   res.setHeader("Content-Type", "application/javascript");
68   res.sendFile(path.resolve("./dist/service-worker.js"));
69 });
70
71 server.get("/robots.txt", async (_req, res) => {
72   res.setHeader("content-type", "text/plain; charset=utf-8");
73   res.send(robotstxt);
74 });
75
76 server.get("/css/themes/:name", async (req, res) => {
77   res.contentType("text/css");
78   const theme = req.params.name;
79   if (!theme.endsWith(".css")) {
80     res.send("Theme must be a css file");
81   }
82
83   const customTheme = path.resolve(`./${extraThemesFolder}/${theme}`);
84   if (existsSync(customTheme)) {
85     res.sendFile(customTheme);
86   } else {
87     const internalTheme = path.resolve(`./dist/assets/css/themes/${theme}`);
88
89     // If the theme doesn't exist, just send litely
90     if (existsSync(internalTheme)) {
91       res.sendFile(internalTheme);
92     } else {
93       res.sendFile(path.resolve("./dist/assets/css/themes/litely.css"));
94     }
95   }
96 });
97
98 async function buildThemeList(): Promise<string[]> {
99   const themes = ["darkly", "darkly-red", "litely", "litely-red"];
100   if (existsSync(extraThemesFolder)) {
101     const dirThemes = await readdir(extraThemesFolder);
102     const cssThemes = dirThemes
103       .filter(d => d.endsWith(".css"))
104       .map(d => d.replace(".css", ""));
105     themes.push(...cssThemes);
106   }
107   return themes;
108 }
109
110 server.get("/css/themelist", async (_req, res) => {
111   res.type("json");
112   res.send(JSON.stringify(await buildThemeList()));
113 });
114
115 // server.use(cookieParser());
116 server.get("/*", async (req, res) => {
117   try {
118     const activeRoute = routes.find(route => matchPath(req.path, route));
119     let auth: string | undefined = IsomorphicCookie.load("jwt", req);
120
121     const getSiteForm: GetSite = { auth };
122
123     const promises: Promise<any>[] = [];
124
125     const headers = setForwardedHeaders(req.headers);
126     const client = new LemmyHttp(getHttpBaseInternal(), headers);
127
128     const { path, url, query } = req;
129
130     // Get site data first
131     // This bypasses errors, so that the client can hit the error on its own,
132     // in order to remove the jwt on the browser. Necessary for wrong jwts
133     let try_site: any = await client.getSite(getSiteForm);
134     if (try_site.error == "not_logged_in") {
135       console.error(
136         "Incorrect JWT token, skipping auth so frontend can remove jwt cookie"
137       );
138       getSiteForm.auth = undefined;
139       auth = undefined;
140       try_site = await client.getSite(getSiteForm);
141     }
142
143     if (!auth && isAuthPath(path)) {
144       res.redirect("/");
145       return;
146     }
147
148     const site: GetSiteResponse = try_site;
149     initializeSite(site);
150
151     const initialFetchReq: InitialFetchRequest = {
152       client,
153       auth,
154       path,
155       query,
156       site,
157     };
158
159     if (activeRoute?.fetchInitialData) {
160       promises.push(...activeRoute.fetchInitialData(initialFetchReq));
161     }
162
163     let routeData = await Promise.all(promises);
164
165     // Redirect to the 404 if there's an API error
166     if (routeData[0] && routeData[0].error) {
167       const error = routeData[0].error;
168       console.error(error);
169       if (error === "instance_is_private") {
170         return res.redirect(`/signup`);
171       } else {
172         const errorPageData: ErrorPageData = { type: "error" };
173
174         // Exact error should only be seen in a development environment. Users
175         // in production will get a more generic message.
176         if (VERSION === "dev") {
177           errorPageData.error = error;
178         }
179
180         const adminMatrixIds = site.admins
181           .map(({ person: { matrix_user_id } }) => matrix_user_id)
182           .filter(id => id) as string[];
183         if (adminMatrixIds.length > 0) {
184           errorPageData.adminMatrixIds = adminMatrixIds;
185         }
186
187         routeData = [errorPageData];
188       }
189     }
190
191     const isoData: IsoData = {
192       path,
193       site_res: site,
194       routeData,
195     };
196
197     const wrapper = (
198       <StaticRouter location={url} context={isoData}>
199         <App />
200       </StaticRouter>
201     );
202
203     const eruda = (
204       <>
205         <script src="//cdn.jsdelivr.net/npm/eruda"></script>
206         <script>eruda.init();</script>
207       </>
208     );
209
210     const erudaStr = process.env["LEMMY_UI_DEBUG"] ? renderToString(eruda) : "";
211     const root = renderToString(wrapper);
212     const helmet = Helmet.renderStatic();
213
214     const config: ILemmyConfig = { wsHost: process.env.LEMMY_UI_LEMMY_WS_HOST };
215
216     const appleTouchIcon = site.site_view.site.icon
217       ? `data:image/png;base64,${sharp(
218           await fetchIconPng(site.site_view.site.icon)
219         )
220           .resize(180, 180)
221           .extend({
222             bottom: 20,
223             top: 20,
224             left: 20,
225             right: 20,
226             background: "#222222",
227           })
228           .png()
229           .toBuffer()
230           .then(buf => buf.toString("base64"))}`
231       : favIconPngUrl;
232
233     res.send(`
234            <!DOCTYPE html>
235            <html ${helmet.htmlAttributes.toString()} lang="en">
236            <head>
237            <script>window.isoData = ${JSON.stringify(isoData)}</script>
238            <script>window.lemmyConfig = ${serialize(config)}</script>
239
240            <!-- A remote debugging utility for mobile -->
241            ${erudaStr}
242
243            <!-- Custom injected script -->
244            ${customHtmlHeader}
245
246            ${helmet.title.toString()}
247            ${helmet.meta.toString()}
248
249            <!-- Required meta tags -->
250            <meta name="Description" content="Lemmy">
251            <meta charset="utf-8">
252            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
253            <link
254               id="favicon"
255               rel="shortcut icon"
256               type="image/x-icon"
257               href=${site.site_view.site.icon ?? favIconUrl}
258             />
259
260            <!-- Web app manifest -->
261            <link rel="manifest" href="data:application/manifest+json;base64,${await generateManifestBase64(
262              site.site_view.site
263            )}">
264            <link rel="apple-touch-icon" href=${appleTouchIcon} />
265            <link rel="apple-touch-startup-image" href=${appleTouchIcon} />
266
267            <!-- Styles -->
268            <link rel="stylesheet" type="text/css" href="/static/styles/styles.css" />
269
270            <!-- Current theme and more -->
271            ${helmet.link.toString()}
272            
273            </head>
274
275            <body ${helmet.bodyAttributes.toString()}>
276              <noscript>
277                <div class="alert alert-danger rounded-0" role="alert">
278                  <b>Javascript is disabled. Actions will not work.</b>
279                </div>
280              </noscript>
281
282              <div id='root'>${root}</div>
283              <script defer src='/static/js/client.js'></script>
284            </body>
285          </html>
286 `);
287   } catch (err) {
288     console.error(err);
289     res.statusCode = 500;
290     return res.send(VERSION === "dev" ? err.message : "Server error");
291   }
292 });
293
294 server.listen(Number(port), hostname, () => {
295   console.log(`http://${hostname}:${port}`);
296 });
297
298 function setForwardedHeaders(headers: IncomingHttpHeaders): {
299   [key: string]: string;
300 } {
301   let out: { [key: string]: string } = {};
302   if (headers.host) {
303     out.host = headers.host;
304   }
305   let realIp = headers["x-real-ip"];
306   if (realIp) {
307     out["x-real-ip"] = realIp as string;
308   }
309   let forwardedFor = headers["x-forwarded-for"];
310   if (forwardedFor) {
311     out["x-forwarded-for"] = forwardedFor as string;
312   }
313
314   return out;
315 }
316
317 process.on("SIGINT", () => {
318   console.info("Interrupted");
319   process.exit(0);
320 });
321
322 const iconSizes = [72, 96, 128, 144, 152, 192, 384, 512];
323 const defaultLogoPathDirectory = path.join(
324   process.cwd(),
325   "dist",
326   "assets",
327   "icons"
328 );
329
330 export async function generateManifestBase64(site: Site) {
331   const url = (
332     process.env.NODE_ENV === "development"
333       ? "http://localhost:1236/"
334       : getHttpBase()
335   ).replace(/\/$/g, "");
336   const icon = site.icon ? await fetchIconPng(site.icon) : null;
337
338   const manifest = {
339     name: site.name,
340     description: site.description ?? "A link aggregator for the fediverse",
341     start_url: url,
342     scope: url,
343     display: "standalone",
344     id: "/",
345     background_color: "#222222",
346     theme_color: "#222222",
347     icons: await Promise.all(
348       iconSizes.map(async size => {
349         let src = await readFile(
350           path.join(defaultLogoPathDirectory, `icon-${size}x${size}.png`)
351         ).then(buf => buf.toString("base64"));
352
353         if (icon) {
354           src = await sharp(icon)
355             .resize(size, size)
356             .png()
357             .toBuffer()
358             .then(buf => buf.toString("base64"));
359         }
360
361         return {
362           sizes: `${size}x${size}`,
363           type: "image/png",
364           src: `data:image/png;base64,${src}`,
365           purpose: "any maskable",
366         };
367       })
368     ),
369   };
370
371   return Buffer.from(JSON.stringify(manifest)).toString("base64");
372 }
373
374 async function fetchIconPng(iconUrl: string) {
375   return await fetch(
376     iconUrl.replace(/https?:\/\/localhost:\d+/g, getHttpBaseInternal())
377   )
378     .then(res => res.blob())
379     .then(blob => blob.arrayBuffer());
380 }