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