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