Files
Website/src/pages/admin/admin.ts
T
2026-11-24 22:05:11 +01:00

571 lines
19 KiB
TypeScript

import { json, Router, urlencoded } from "express";
import fs from "fs";
import { getConfig, getDatabase, updateConfig } from "../../config";
import { SelfCleaningMap } from "../../self-cleaning-map";
import {
generateNonExistingId,
getAndPrepareLogFolder,
getClientIp,
getDateString,
getExtension,
prepareLogFolder,
randomString,
} from "../../utils";
import multer from "multer";
import FileType from "file-type";
import sharp from "sharp";
import path from "path";
import pngToIco from "png-to-ico";
import { getPageVariables } from "../../page-variables";
import { IconDirectory } from "../../db/icon-directory";
import {
createBadgeEditor,
createLinkEditor,
createProjectEditor,
createUrlRedirectEditor,
} from "./link-editor";
import { createGalleryEditor } from "./gallery-editor";
import { createAccessCodeEditor } from "./access-code-editor";
import { createStalker } from "./stalk";
import { createAnalytics } from "./analytics";
import { createStorageEditor } from "./storage-editor";
import { LOCATION_FONTS, LOCATION_ICONS, LOCATION_SITE } from "../../const";
interface AdminData {
loggined: Date;
}
const maxCookieAge = 1000 * 60 * 60;
const SITE_FONT_FAMILY = "site_font";
const SITE_FONT_PREFIX = "custom-font.";
const sessions = new SelfCleaningMap<string, AdminData>(maxCookieAge);
const failedLogins = new Map<string, { count: number; resetAt: number }>();
const MAX_LOGIN_ATTEMPTS = 5;
const LOGIN_LOCKOUT_MS = 1000 * 60 * 5;
export function createAdminEndpoint(endpoint: string) {
const adminRouter = Router();
adminRouter.use(urlencoded({ extended: true })); // parses form POST data
adminRouter.use(json());
const upload = multer({ storage: multer.memoryStorage() }); // keep it in memory, not disk
const cfg = getConfig();
adminRouter.get(`/`, (req, res) => {
const currentSession = sessions.get(req.cookies.id);
if (currentSession) {
res.redirect(`${endpoint}/dashboard`);
} else {
res.redirect(`${endpoint}/login`);
}
});
adminRouter.get("/login", (req, res) => {
res.render("admin/login", getPageVariables(req, { endpoint }));
});
adminRouter.post("/login", (req, res) => {
const ip = getClientIp(req);
const now = Date.now();
if (failedLogins.size > 1000) {
for (const [failedIp, rec] of failedLogins) {
if (rec.resetAt < now) {
failedLogins.delete(failedIp);
}
}
}
const record = failedLogins.get(ip);
if (record && record.resetAt > now && record.count >= MAX_LOGIN_ATTEMPTS) {
return res.render(
"admin/login",
getPageVariables(req, {
endpoint,
error: "Too many login attempts. Try again later.",
}),
);
}
const { username, password } = req.body;
const cfg = getConfig();
if (username === cfg.admin.username && password === cfg.admin.password) {
failedLogins.delete(ip);
let id = randomString(32);
do {
id = randomString(32);
} while (sessions.has(id));
sessions.set(id, {
loggined: new Date(),
});
res.cookie("id", id, { httpOnly: true, sameSite: "lax" });
res.redirect(`${endpoint}/dashboard`);
} else {
if (record && record.resetAt > now) {
record.count++;
} else {
failedLogins.set(ip, { count: 1, resetAt: now + LOGIN_LOCKOUT_MS });
}
res.render(
"admin/login",
getPageVariables(req, {
endpoint,
error: "Invalid username or password.",
}),
);
}
});
adminRouter.use((req, res, next) => {
const currentSession = sessions.get(req.cookies.id);
if (currentSession) {
next();
} else {
res.redirect("/");
}
});
adminRouter.get("/dashboard", async (req, res) => {
const links: string[] = [];
if (cfg.stats) {
const date = getDateString();
links.push(`${endpoint}/stats-today-${cfg.stats.today}/`);
links.push(`${endpoint}/stats-today-${cfg.stats.today}/real`);
links.push(`${endpoint}/stats-today-${cfg.stats.today}/real/${date}`);
links.push(`${endpoint}/stats-today-${cfg.stats.today}/${date}`);
links.push(`${endpoint}/stats-trace-${cfg.stats.trace}/id`);
links.push(`${endpoint}/stats-overall-${cfg.stats.overall}`);
}
let stats = { visits: 0, visitors: 0, countries: 0, last24h: 0 };
try {
const db = getDatabase();
const [visits] = await db.query(`SELECT COUNT(*) AS c FROM ip_log`);
const [visitors] = await db.query(`SELECT COUNT(*) AS c FROM ip`);
const [countries] = await db.query(
`SELECT COUNT(DISTINCT json_extract(data, '$.country')) AS c
FROM ip WHERE json_valid(data) AND json_extract(data, '$.country') != ''`,
);
const [recent] = await db.query(
`SELECT COUNT(*) AS c FROM ip_log WHERE accessed >= ?`,
[
new Date(Date.now() - 86_400_000)
.toISOString()
.slice(0, 19)
.replace("T", " "),
],
);
stats = {
visits: Number(visits?.c ?? 0),
visitors: Number(visitors?.c ?? 0),
countries: Number(countries?.c ?? 0),
last24h: Number(recent?.c ?? 0),
};
} catch {
/* stats are best-effort */
}
res.render(
"admin/dashboard",
getPageVariables(req, { endpoint, links, stats }),
);
});
adminRouter.get("/meta-editor", (req, res) => {
res.render("admin/meta-editor", getPageVariables(req, { endpoint }));
});
adminRouter.post("/edit-meta", async (req, res) => {
const body = req.body || {};
const newConfig = { ...getConfig() };
if (typeof body.title === "string") {
newConfig.title = body.title;
}
if (typeof body.titleShort === "string") {
newConfig.titleShort = body.titleShort;
}
if (typeof body.description === "string") {
newConfig.description = body.description;
}
const bioEntries = Object.entries(body)
.filter((e) => /^\d+$/.test(e[0]))
.map((e) => [parseInt(e[0], 10), e[1]]) as [number, string][];
newConfig.bio = [
...bioEntries.sort((a, b) => (a[0] > b[0] ? 1 : -1)).map((e) => e[1]),
body.new,
]
.map((e) => String(e ?? "").trim())
.filter((e) => e);
await updateConfig(newConfig);
res.redirect(`${endpoint}/meta-editor`);
});
const rencodeImageWebP = async (buffer: Buffer) => {
const type = await FileType.fileTypeFromBuffer(new Uint8Array(buffer));
if (!type || !type.mime.startsWith("image/")) {
throw new Error("Not an image");
}
const webpBuffer = await sharp(buffer).webp({ lossless: true }).toBuffer();
return webpBuffer;
};
const rencodeImagePngP = async (buffer: Buffer) => {
const type = await FileType.fileTypeFromBuffer(new Uint8Array(buffer));
if (!type || !type.mime.startsWith("image/")) {
throw new Error("Not an image");
}
const webpBuffer = await sharp(buffer).png({}).toBuffer();
return webpBuffer;
};
adminRouter.post(
"/update/background",
upload.single("background"),
async (req, res) => {
try {
if (req.file) {
const webPBuffer = await rencodeImageWebP(req.file.buffer);
await fs.promises.mkdir(LOCATION_SITE, { recursive: true });
const location = path.join(LOCATION_SITE, "background.webp");
await fs.promises.writeFile(location, new Uint8Array(webPBuffer));
}
} catch (error) {
console.error("Failed to update background:", error);
}
return res.redirect(`${endpoint}/meta-editor`);
},
);
adminRouter.post(
"/update/avatar",
upload.single("avatar"),
async (req, res) => {
try {
if (req.file) {
const webPBuffer = await rencodeImageWebP(req.file.buffer);
const pngPBuffer = await rencodeImagePngP(req.file.buffer);
await fs.promises.mkdir(LOCATION_SITE, { recursive: true });
const location = path.join(LOCATION_SITE, "avatar.webp");
const location2 = path.join(LOCATION_SITE, "avatar.png");
await fs.promises.writeFile(location, new Uint8Array(webPBuffer));
await fs.promises.writeFile(location2, new Uint8Array(pngPBuffer));
}
} catch (error) {
console.error("Failed to update avatar:", error);
}
return res.redirect(`${endpoint}/meta-editor`);
},
);
adminRouter.post(
"/update/favicon",
upload.single("favicon"),
async (req, res) => {
try {
if (req.file) {
await fs.promises.mkdir(LOCATION_SITE, { recursive: true });
const sizes = [
{ name: "android-chrome-192x192.png", size: 192 },
{ name: "android-chrome-512x512.png", size: 512 },
{ name: "apple-touch-icon.png", size: 180 },
{ name: "favicon-16x16.png", size: 16 },
{ name: "favicon-32x32.png", size: 32 },
{ name: "favicon-48x48.png", size: 48 },
];
await Promise.all(
sizes.map((s) =>
sharp(req.file!.buffer)
.resize(s.size, s.size)
.png()
.toFile(path.join(LOCATION_SITE, s.name)),
),
);
const icoBuffer = await pngToIco([
path.join(LOCATION_SITE, "favicon-16x16.png"),
path.join(LOCATION_SITE, "favicon-32x32.png"),
path.join(LOCATION_SITE, "favicon-48x48.png"),
]);
await fs.promises.writeFile(
path.join(LOCATION_SITE, "favicon.ico"),
icoBuffer,
);
}
} catch (error) {
console.error("Failed to update favicon:", error);
}
return res.redirect(`${endpoint}/meta-editor`);
},
);
const removeCustomFonts = async () => {
const entries = await fs.promises
.readdir(LOCATION_FONTS)
.catch(() => [] as string[]);
await Promise.all(
entries
.filter((entry) => entry.startsWith(SITE_FONT_PREFIX))
.map((entry) =>
fs.promises.rm(path.join(LOCATION_FONTS, entry), { force: true }),
),
);
};
adminRouter.post("/update/font", upload.single("font"), async (req, res) => {
try {
if (req.file) {
const type = await FileType.fileTypeFromBuffer(
new Uint8Array(req.file.buffer),
);
if (type && type.mime.startsWith("font/")) {
await fs.promises.mkdir(LOCATION_FONTS, { recursive: true });
await removeCustomFonts();
const file = `${SITE_FONT_PREFIX}${type.ext}`;
await fs.promises.writeFile(
path.join(LOCATION_FONTS, file),
req.file.buffer,
);
const newConfig = { ...getConfig() };
newConfig.font = {
file,
family: SITE_FONT_FAMILY,
name: req.file.originalname,
updated: Date.now(),
};
await updateConfig(newConfig);
} else {
console.error("Failed to update font: unsupported file type");
}
}
} catch (error) {
console.error("Failed to update font:", error);
}
return res.redirect(`${endpoint}/meta-editor`);
});
adminRouter.post("/remove/font", async (_req, res) => {
try {
await removeCustomFonts();
const newConfig = { ...getConfig() };
delete newConfig.font;
await updateConfig(newConfig);
} catch (error) {
console.error("Failed to remove font:", error);
}
return res.redirect(`${endpoint}/meta-editor`);
});
adminRouter.get("/logout", (_req, res) => {
res.clearCookie("id");
res.redirect(`${endpoint}/login`);
});
adminRouter.get("/icon-editor", async (req, res) => {
const iconDirectory = getDatabase().getRepository(IconDirectory);
const icons = await iconDirectory.find();
res.render("admin/icon-editor", getPageVariables(req, { endpoint, icons }));
});
adminRouter.post("/add-icon", upload.single("icon"), async (req, res) => {
try {
if (req.file && req.body.alt) {
const icon = new IconDirectory();
const webPBuffer = await rencodeImageWebP(req.file.buffer);
const { name } = generateNonExistingId(LOCATION_ICONS, "webp", 32);
icon.alt = req.body.alt;
icon.path = name;
icon.name =
req.body.alt + (getExtension(req.file.originalname) || ".bin");
const iconDirectory = getDatabase().getRepository(IconDirectory);
const iconLocation = path.join(LOCATION_ICONS, name);
await fs.promises.writeFile(iconLocation, webPBuffer);
try {
await iconDirectory.save(icon);
} catch (error) {
await fs.promises.rm(iconLocation);
console.error(error);
}
}
} catch (error) {
console.error(error);
}
return res.redirect(`${endpoint}/icon-editor`);
});
adminRouter.post("/edit-alt-text-icon", async (req, res) => {
if (req.body.id && req.body.alt) {
const iconDirectory = getDatabase().getRepository(IconDirectory);
const image = await iconDirectory.findOne({
where: {
id: req.body.id,
},
});
if (image) {
image.alt = req.body.alt;
await iconDirectory.save(image);
}
}
return res.redirect(`${endpoint}/icon-editor`);
});
adminRouter.post("/delete-icon", async (req, res) => {
if (req.body.id) {
const iconDirectory = getDatabase().getRepository(IconDirectory);
const image = await iconDirectory.findOne({
where: {
id: req.body.id,
},
});
if (image) {
const iconLocation = path.join(LOCATION_ICONS, image.path);
if (fs.existsSync(iconLocation)) {
await fs.promises.rm(iconLocation);
await iconDirectory.remove(image);
}
}
}
return res.redirect(`${endpoint}/icon-editor`);
});
createLinkEditor(adminRouter, endpoint);
createProjectEditor(adminRouter, endpoint);
createBadgeEditor(adminRouter, endpoint);
createUrlRedirectEditor(adminRouter, endpoint);
createGalleryEditor(adminRouter, endpoint);
createStorageEditor(adminRouter, endpoint);
createAccessCodeEditor(adminRouter, endpoint);
createStalker(adminRouter, endpoint);
createAnalytics(adminRouter, endpoint);
if (cfg.stats) {
adminRouter.get(`/stats-today-${cfg.stats.today}/`, async (_req, res) => {
const folder = prepareLogFolder();
try {
const logs = await fs.promises.readFile(path.join(folder, `logs.txt`));
res.end(logs);
} catch {
res.end("no logs for today");
}
});
adminRouter.get(
`/stats-today-${cfg.stats.today}/real`,
async (_req, res) => {
const folder = prepareLogFolder();
try {
const logs = await fs.promises.readFile(
path.join(folder, `science.txt`),
);
res.end(logs);
} catch {
res.end("no logs for today");
}
},
);
adminRouter.get(
`/stats-today-${cfg.stats.today}/real/:date`,
async (req, res) => {
if (req.params.date && req.params.date.includes(".")) {
return res.end("no logs for specified date");
}
const folder = getAndPrepareLogFolder(req.params.date);
try {
const logs = await fs.promises.readFile(
path.join(folder, `science.txt`),
);
res.end(logs);
} catch {
res.end("no logs for today");
}
},
);
adminRouter.get(
`/stats-today-${cfg.stats.today}/:date`,
async (req, res) => {
if (req.params.date && req.params.date.includes(".")) {
return res.end("no logs for specified date");
}
const folder = getAndPrepareLogFolder(req.params.date);
try {
const logs = await fs.promises.readFile(
path.join(folder, `logs.txt`),
);
res.end(logs);
} catch {
return res.end("no logs for specified date");
}
},
);
adminRouter.get(`/stats-trace-${cfg.stats.trace}/:id`, async (req, res) => {
const folder = prepareLogFolder();
const logs = await fs.promises
.readFile(path.join(folder, req.params.id, `logs.txt`), "utf8")
.catch(() => "No logs");
const script = await fs.promises
.readFile(path.join(folder, req.params.id, `script-dump.txt`), "utf8")
.catch(() => "No script dumps");
res.end(`${logs}\n${script.substring(0, 8192)}`);
});
adminRouter.get(
`/stats-overall-${cfg.stats.overall}`,
async (_req, res) => {
const dirs = await fs.promises.readdir("./logs");
let dailyReport = "";
for (const dir of dirs.reverse()) {
try {
const daily = await fs.promises.readFile(
`./logs/${dir}/science.txt`,
"utf8",
);
const lines = daily.split("\n");
const ips = lines
.map((e) =>
e.match(/\[\d+-\d+-\d+ \d+:\d+:\d+\] \[([0-9.A-z:]+)\]/),
)
.filter((e) => e)
.map((e) => (e as any)[1]);
const domains = lines.map((e) => {
const secondSpace = e.indexOf(" ", e.indexOf("] [") + 4);
return e.substring(secondSpace + 1);
});
const ipCount = new Map<string, number>();
for (const ip of ips) {
let i = ipCount.get(ip) || 0;
i++;
ipCount.set(ip, i);
}
const domainsCount = new Map<string, number>();
for (const domain of domains) {
if (domain && domain !== "undefined") {
let i = domainsCount.get(domain) || 0;
i++;
domainsCount.set(domain, i);
}
}
dailyReport += `${dir}\n`;
dailyReport += `IPS:\n`;
for (const [ip, count] of Array.from(ipCount)) {
dailyReport += ` ${ip}: ${count}\n`;
}
dailyReport += `DOMAINS:\n`;
for (const [domain, count] of Array.from(domainsCount)) {
dailyReport += ` ${domain}: ${count}\n`;
}
dailyReport += "\n";
} catch {
/* ignore */
}
}
res.end(dailyReport);
},
);
}
return adminRouter;
}