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