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