]> Untitled Git - lemmy-ui.git/blob - src/server/index.tsx
Set up logic for handling errors
[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     }
146     const site: GetSiteResponse = try_site;
147     initializeSite(site);
148
149     const initialFetchReq: InitialFetchRequest = {
150       client,
151       auth,
152       path,
153       query,
154       site,
155     };
156
157     if (activeRoute?.fetchInitialData) {
158       promises.push(...activeRoute.fetchInitialData(initialFetchReq));
159     }
160
161     let routeData = await Promise.all(promises);
162
163     // Redirect to the 404 if there's an API error
164     if (routeData[0] && routeData[0].error) {
165       const error = routeData[0].error;
166       console.error(error);
167       if (error === "instance_is_private") {
168         return res.redirect(`/signup`);
169       } else {
170         const errorPageData: ErrorPageData = { type: "error" };
171
172         // Exact error should only be seen in a development environment. Users
173         // in production will get a more generic message.
174         if (VERSION === "dev") {
175           errorPageData.error = error;
176         }
177
178         const adminMatrixIds = site.admins
179           .map(({ person: { matrix_user_id } }) => matrix_user_id)
180           .filter(id => id) as string[];
181         if (adminMatrixIds.length > 0) {
182           errorPageData.adminMatrixIds = adminMatrixIds;
183         }
184
185         routeData = [errorPageData];
186       }
187     }
188
189     const isoData: IsoData = {
190       path,
191       site_res: site,
192       routeData,
193     };
194
195     const wrapper = (
196       <StaticRouter location={url} context={isoData}>
197         <App />
198       </StaticRouter>
199     );
200
201     const eruda = (
202       <>
203         <script src="//cdn.jsdelivr.net/npm/eruda"></script>
204         <script>eruda.init();</script>
205       </>
206     );
207
208     const erudaStr = process.env["LEMMY_UI_DEBUG"] ? renderToString(eruda) : "";
209     const root = renderToString(wrapper);
210     const helmet = Helmet.renderStatic();
211
212     const config: ILemmyConfig = { wsHost: process.env.LEMMY_UI_LEMMY_WS_HOST };
213
214     const appleTouchIcon = site.site_view.site.icon
215       ? `data:image/png;base64,${sharp(
216           await fetchIconPng(site.site_view.site.icon)
217         )
218           .resize(180, 180)
219           .extend({
220             bottom: 20,
221             top: 20,
222             left: 20,
223             right: 20,
224             background: "#222222",
225           })
226           .png()
227           .toBuffer()
228           .then(buf => buf.toString("base64"))}`
229       : favIconPngUrl;
230
231     res.send(`
232            <!DOCTYPE html>
233            <html ${helmet.htmlAttributes.toString()} lang="en">
234            <head>
235            <script>window.isoData = ${JSON.stringify(isoData)}</script>
236            <script>window.lemmyConfig = ${serialize(config)}</script>
237
238            <!-- A remote debugging utility for mobile -->
239            ${erudaStr}
240
241            <!-- Custom injected script -->
242            ${customHtmlHeader}
243
244            ${helmet.title.toString()}
245            ${helmet.meta.toString()}
246
247            <!-- Required meta tags -->
248            <meta name="Description" content="Lemmy">
249            <meta charset="utf-8">
250            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
251            <link
252               id="favicon"
253               rel="shortcut icon"
254               type="image/x-icon"
255               href=${site.site_view.site.icon ?? favIconUrl}
256             />
257
258            <!-- Web app manifest -->
259            <link rel="manifest" href="data:application/manifest+json;base64,${await generateManifestBase64(
260              site.site_view.site
261            )}">
262            <link rel="apple-touch-icon" href=${appleTouchIcon} />
263            <link rel="apple-touch-startup-image" href=${appleTouchIcon} />
264
265            <!-- Styles -->
266            <link rel="stylesheet" type="text/css" href="/static/styles/styles.css" />
267
268            <!-- Current theme and more -->
269            ${helmet.link.toString()}
270            
271            </head>
272
273            <body ${helmet.bodyAttributes.toString()}>
274              <noscript>
275                <div class="alert alert-danger rounded-0" role="alert">
276                  <b>Javascript is disabled. Actions will not work.</b>
277                </div>
278              </noscript>
279
280              <div id='root'>${root}</div>
281              <script defer src='/static/js/client.js'></script>
282            </body>
283          </html>
284 `);
285   } catch (err) {
286     console.error(err);
287     res.statusCode = 500;
288     return res.send(VERSION === "dev" ? err.message : "Server error");
289   }
290 });
291
292 server.listen(Number(port), hostname, () => {
293   console.log(`http://${hostname}:${port}`);
294 });
295
296 function setForwardedHeaders(headers: IncomingHttpHeaders): {
297   [key: string]: string;
298 } {
299   let out: { [key: string]: string } = {};
300   if (headers.host) {
301     out.host = headers.host;
302   }
303   let realIp = headers["x-real-ip"];
304   if (realIp) {
305     out["x-real-ip"] = realIp as string;
306   }
307   let forwardedFor = headers["x-forwarded-for"];
308   if (forwardedFor) {
309     out["x-forwarded-for"] = forwardedFor as string;
310   }
311
312   return out;
313 }
314
315 process.on("SIGINT", () => {
316   console.info("Interrupted");
317   process.exit(0);
318 });
319
320 const iconSizes = [72, 96, 128, 144, 152, 192, 384, 512];
321 const defaultLogoPathDirectory = path.join(
322   process.cwd(),
323   "dist",
324   "assets",
325   "icons"
326 );
327
328 export async function generateManifestBase64(site: Site) {
329   const url = (
330     process.env.NODE_ENV === "development"
331       ? "http://localhost:1236/"
332       : getHttpBase()
333   ).replace(/\/$/g, "");
334   const icon = site.icon ? await fetchIconPng(site.icon) : null;
335
336   const manifest = {
337     name: site.name,
338     description: site.description ?? "A link aggregator for the fediverse",
339     start_url: url,
340     scope: url,
341     display: "standalone",
342     id: "/",
343     background_color: "#222222",
344     theme_color: "#222222",
345     icons: await Promise.all(
346       iconSizes.map(async size => {
347         let src = await readFile(
348           path.join(defaultLogoPathDirectory, `icon-${size}x${size}.png`)
349         ).then(buf => buf.toString("base64"));
350
351         if (icon) {
352           src = await sharp(icon)
353             .resize(size, size)
354             .png()
355             .toBuffer()
356             .then(buf => buf.toString("base64"));
357         }
358
359         return {
360           sizes: `${size}x${size}`,
361           type: "image/png",
362           src: `data:image/png;base64,${src}`,
363           purpose: "any maskable",
364         };
365       })
366     ),
367   };
368
369   return Buffer.from(JSON.stringify(manifest)).toString("base64");
370 }
371
372 async function fetchIconPng(iconUrl: string) {
373   return await fetch(
374     iconUrl.replace(/https?:\/\/localhost:\d+/g, getHttpBaseInternal())
375   )
376     .then(res => res.blob())
377     .then(blob => blob.arrayBuffer());
378 }