77 lines
2.5 KiB
TypeScript
77 lines
2.5 KiB
TypeScript
import type { NextFunction, Request, Response } from "express";
|
|
import type { SessionOptions } from "express-session";
|
|
import { Liquid } from "liquidjs";
|
|
import { readFileSync, readdirSync } from "fs";
|
|
import crypto from "crypto";
|
|
import express from "express";
|
|
import expressSession from "express-session";
|
|
import path from "path";
|
|
|
|
const isProduction = process.env.NODE_ENV === "production";
|
|
const LAYOUTS_DIRECTORY = path.join(__dirname, "layouts");
|
|
const PARTIALS_DIRECTORY = path.join(__dirname, "partials");
|
|
const PUBLIC_DIRECTORY = path.join(__dirname, "public");
|
|
const VIEWS_DIRECTORY = path.join(__dirname, "views");
|
|
const cookieSecret = crypto.randomBytes(48).toString("hex");
|
|
|
|
export function startWebserver() {
|
|
const app = express();
|
|
app.disable("x-powered-by");
|
|
|
|
app.use((_req, res, next) => {
|
|
res.header("Permissions-Policy", "interest-cohort=()");
|
|
next();
|
|
});
|
|
|
|
const noCache = (_req: Request, res: Response, next: NextFunction) => {
|
|
res.header("Cache-Control", "no-cache");
|
|
next();
|
|
};
|
|
|
|
const sessionOptions: SessionOptions = {
|
|
secret: cookieSecret,
|
|
name: "Session",
|
|
resave: false,
|
|
saveUninitialized: false,
|
|
unset: "destroy",
|
|
cookie: {
|
|
maxAge: 1000 * 60 * 60 * 24 * 7,
|
|
signed: true,
|
|
path: "/",
|
|
httpOnly: true,
|
|
sameSite: "lax",
|
|
// If you are getting infinite redirects, set this to "false" if you don't have a HTTPS-only environment setup.
|
|
|
|
},
|
|
};
|
|
|
|
|
|
app.use(expressSession(sessionOptions));
|
|
app.use(express.urlencoded({ extended: true, limit: "1mb" }));
|
|
app.use(express.json({ limit: "1mb" }));
|
|
|
|
const engine = new Liquid({
|
|
root: [VIEWS_DIRECTORY, PARTIALS_DIRECTORY, LAYOUTS_DIRECTORY],
|
|
cache: isProduction,
|
|
lenientIf: true,
|
|
jsTruthy: true,
|
|
extname: ".liquid",
|
|
});
|
|
|
|
app.engine("liquid", engine.express());
|
|
app.set("views", [VIEWS_DIRECTORY, PARTIALS_DIRECTORY, LAYOUTS_DIRECTORY]);
|
|
app.set("view engine", "liquid");
|
|
|
|
app.use("/public/", express.static(PUBLIC_DIRECTORY));
|
|
|
|
// 404
|
|
app.use((req, res) => {
|
|
if (req.accepts("html")) return res.status(404).render("404", { url: req.url, errorCode: 404 });
|
|
else if (req.accepts("json")) return res.status(404).send({ error: "404" });
|
|
else res.status(404).type("txt").send("404");
|
|
});
|
|
|
|
app.listen(3430, "0.0.0.0", () => {
|
|
console.log(`Webserver running on port 3430`);
|
|
});
|
|
} |