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";
20 } from "../shared/interfaces";
21 import { routes } from "../shared/routes";
22 import { favIconPngUrl, favIconUrl, initializeSite } from "../shared/utils";
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";
31 if (!process.env["LEMMY_UI_DISABLE_CSP"] && !process.env["LEMMY_UI_DEBUG"]) {
32 server.use(function (_req, res, next) {
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 *`
40 const customHtmlHeader = process.env["LEMMY_UI_CUSTOM_HTML_HEADER"] || "";
42 server.use(express.json());
43 server.use(express.urlencoded({ extended: false }));
44 server.use("/static", express.static(path.resolve("./dist")));
46 const robotstxt = `User-Agent: *
49 Disallow: /create_community
50 Disallow: /create_post
51 Disallow: /create_private_message
55 Disallow: /password_change
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"));
64 server.get("/robots.txt", async (_req, res) => {
65 res.setHeader("content-type", "text/plain; charset=utf-8");
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");
76 const customTheme = path.resolve(`./${extraThemesFolder}/${theme}`);
77 if (existsSync(customTheme)) {
78 res.sendFile(customTheme);
80 const internalTheme = path.resolve(`./dist/assets/css/themes/${theme}`);
82 // If the theme doesn't exist, just send litely
83 if (existsSync(internalTheme)) {
84 res.sendFile(internalTheme);
86 res.sendFile(path.resolve("./dist/assets/css/themes/litely.css"));
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);
103 server.get("/css/themelist", async (_req, res) => {
105 res.send(JSON.stringify(await buildThemeList()));
108 // server.use(cookieParser());
109 server.get("/*", async (req, res) => {
111 const activeRoute = routes.find(route => matchPath(req.path, route));
112 const context = {} as any;
113 let auth: string | undefined = IsomorphicCookie.load("jwt", req);
115 const getSiteForm: GetSite = { auth };
117 const promises: Promise<any>[] = [];
119 const headers = setForwardedHeaders(req.headers);
120 const client = new LemmyHttp(getHttpBaseInternal(), headers);
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") {
128 "Incorrect JWT token, skipping auth so frontend can remove jwt cookie"
130 getSiteForm.auth = undefined;
132 try_site = await client.getSite(getSiteForm);
134 const site: GetSiteResponse = try_site;
135 initializeSite(site);
137 const initialFetchReq: InitialFetchRequest = {
145 if (activeRoute?.fetchInitialData) {
146 promises.push(...activeRoute.fetchInitialData(initialFetchReq));
149 const routeData = await Promise.all(promises);
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`);
158 return res.send(`404: ${removeAuthParam(error)}`);
162 const isoData: IsoData = {
169 <StaticRouter location={req.url} context={isoData}>
174 return res.redirect(context.url);
179 <script src="//cdn.jsdelivr.net/npm/eruda"></script>
180 <script>eruda.init();</script>
184 const erudaStr = process.env["LEMMY_UI_DEBUG"] ? renderToString(eruda) : "";
185 const root = renderToString(wrapper);
186 const helmet = Helmet.renderStatic();
188 const config: ILemmyConfig = { wsHost: process.env.LEMMY_UI_LEMMY_WS_HOST };
190 const appleTouchIcon = site.site_view.site.icon
191 ? `data:image/png;base64,${sharp(
192 await fetchIconPng(site.site_view.site.icon)
200 background: "#222222",
204 .then(buf => buf.toString("base64"))}`
209 <html ${helmet.htmlAttributes.toString()} lang="en">
211 <script>window.isoData = ${JSON.stringify(isoData)}</script>
212 <script>window.lemmyConfig = ${serialize(config)}</script>
214 <!-- A remote debugging utility for mobile -->
217 <!-- Custom injected script -->
220 ${helmet.title.toString()}
221 ${helmet.meta.toString()}
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">
231 href=${site.site_view.site.icon ?? favIconUrl}
234 <!-- Web app manifest -->
235 <link rel="manifest" href="data:application/manifest+json;base64,${await generateManifestBase64(
238 <link rel="apple-touch-icon" href=${appleTouchIcon} />
239 <link rel="apple-touch-startup-image" href=${appleTouchIcon} />
242 <link rel="stylesheet" type="text/css" href="/static/styles/styles.css" />
244 <!-- Current theme and more -->
245 ${helmet.link.toString()}
249 <body ${helmet.bodyAttributes.toString()}>
251 <div class="alert alert-danger rounded-0" role="alert">
252 <b>Javascript is disabled. Actions will not work.</b>
256 <div id='root'>${root}</div>
257 <script defer src='/static/js/client.js'></script>
263 return res.send(`404: ${removeAuthParam(err)}`);
267 server.listen(Number(port), hostname, () => {
268 console.log(`http://${hostname}:${port}`);
271 function setForwardedHeaders(headers: IncomingHttpHeaders): {
272 [key: string]: string;
274 let out: { [key: string]: string } = {};
276 out.host = headers.host;
278 let realIp = headers["x-real-ip"];
280 out["x-real-ip"] = realIp as string;
282 let forwardedFor = headers["x-forwarded-for"];
284 out["x-forwarded-for"] = forwardedFor as string;
290 process.on("SIGINT", () => {
291 console.info("Interrupted");
295 function removeAuthParam(err: any): string {
296 return removeParam(err.toString(), "auth");
299 function removeParam(url: string, parameter: string): string {
301 .replace(new RegExp("[?&]" + parameter + "=[^&#]*(#.*)?$"), "$1")
302 .replace(new RegExp("([?&])" + parameter + "=[^&]*&"), "$1");
305 const iconSizes = [72, 96, 128, 144, 152, 192, 384, 512];
306 const defaultLogoPathDirectory = path.join(
313 export async function generateManifestBase64(site: Site) {
315 process.env.NODE_ENV === "development"
316 ? "http://localhost:1236/"
318 ).replace(/\/$/g, "");
319 const icon = site.icon ? await fetchIconPng(site.icon) : null;
323 description: site.description ?? "A link aggregator for the fediverse",
326 display: "standalone",
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"));
337 src = await sharp(icon)
341 .then(buf => buf.toString("base64"));
345 sizes: `${size}x${size}`,
347 src: `data:image/png;base64,${src}`,
348 purpose: "any maskable",
354 return Buffer.from(JSON.stringify(manifest)).toString("base64");
357 async function fetchIconPng(iconUrl: string) {
359 iconUrl.replace(/https?:\/\/localhost:\d+/g, getHttpBaseInternal())
361 .then(res => res.blob())
362 .then(blob => blob.arrayBuffer());