Harden bot, storage and web API

This commit is contained in:
Shinuwa 2026-06-30 17:25:00 +02:00
parent e974bc6660
commit 20624a5c9c
43 changed files with 1265 additions and 1012 deletions

View file

@ -1,11 +1,15 @@
import fs from "fs";
import path from "path";
import { v4 as uuid } from "uuid";
import { randomUUID } from "node:crypto";
const STORAGE_ROOT = path.join(process.cwd(), "storage");
const PERMANENT_DIR = path.join(STORAGE_ROOT, "permanent");
const TEMP_DIR = path.join(STORAGE_ROOT, "temp");
const LIBRARY_FILE = path.join(STORAGE_ROOT, "library.json");
const RUNTIME_DIR = path.join(STORAGE_ROOT, "runtime");
const LIBRARY_FILE = path.join(RUNTIME_DIR, "library.json");
const LEGACY_LIBRARY_FILE = path.join(STORAGE_ROOT, "library.json");
const TEMP_FILE_MAX_AGE = 24 * 60 * 60 * 1000;
const MAX_LIBRARY_SIZE = 2 * 1024 * 1024 * 1024;
function ensureStorageLayout() {
if (!fs.existsSync(STORAGE_ROOT)) {
@ -20,26 +24,71 @@ function ensureStorageLayout() {
fs.mkdirSync(TEMP_DIR, { recursive: true });
}
if (!fs.existsSync(RUNTIME_DIR)) {
fs.mkdirSync(RUNTIME_DIR, { recursive: true });
}
if (!fs.existsSync(LIBRARY_FILE)) {
fs.writeFileSync(LIBRARY_FILE, JSON.stringify([]));
let initialEntries = [];
if (fs.existsSync(LEGACY_LIBRARY_FILE)) {
try {
initialEntries = JSON.parse(
fs.readFileSync(LEGACY_LIBRARY_FILE, { encoding: "utf8" })
);
} catch (error) {
throw new Error("Impossible de migrer l'ancienne bibliothèque", {
cause: error,
});
}
}
const portableEntries = Array.isArray(initialEntries)
? initialEntries.map(({ path: _path, ...entry }) => entry)
: [];
fs.writeFileSync(LIBRARY_FILE, JSON.stringify(portableEntries, null, 2));
if (portableEntries.length > 0) {
console.log(
`[${new Date().toLocaleString()}] Migrated ${portableEntries.length} library entries`
);
}
}
}
function readLibrary() {
try {
const raw = fs.readFileSync(LIBRARY_FILE, { encoding: "utf8" });
return JSON.parse(raw);
const entries = JSON.parse(raw);
if (!Array.isArray(entries)) {
throw new TypeError("library.json doit contenir un tableau");
}
return entries
.filter(
(entry) =>
entry &&
typeof entry.storedName === "string" &&
path.basename(entry.storedName) === entry.storedName
)
.map((entry) => ({
...entry,
path: path.join(PERMANENT_DIR, entry.storedName),
}));
} catch (error) {
console.error("Failed to read library file", error);
return [];
throw new Error("Impossible de lire la bibliothèque", { cause: error });
}
}
function writeLibrary(entries) {
fs.writeFileSync(LIBRARY_FILE, JSON.stringify(entries, null, 2));
const persistedEntries = entries.map(({ path: _path, ...entry }) => entry);
const temporaryFile = `${LIBRARY_FILE}.${process.pid}.tmp`;
fs.writeFileSync(temporaryFile, JSON.stringify(persistedEntries, null, 2));
fs.renameSync(temporaryFile, LIBRARY_FILE);
}
function registerUploadedFile(file, { permanent, uploader = "unknown" }) {
function registerUploadedFile(
file,
{ permanent, uploader = "unknown", title = file.originalname }
) {
ensureStorageLayout();
const createdAt = new Date().toISOString();
let finalPath = file.path;
@ -47,13 +96,26 @@ function registerUploadedFile(file, { permanent, uploader = "unknown" }) {
let permanentEntry = null;
if (permanent) {
const extension = path.extname(file.originalname) || "";
storedName = `${uuid()}${extension}`;
const library = readLibrary();
const librarySize = library.reduce(
(total, entry) => total + (Number(entry.size) || 0),
0
);
if (librarySize + file.size > MAX_LIBRARY_SIZE) {
throw new Error("La bibliothèque permanente a atteint sa limite de 2 Go");
}
const rawExtension = path.extname(file.originalname).toLowerCase();
const extension = /^\.[a-z0-9]{1,10}$/.test(rawExtension)
? rawExtension
: "";
storedName = `${randomUUID()}${extension.toLowerCase()}`;
finalPath = path.join(PERMANENT_DIR, storedName);
fs.renameSync(file.path, finalPath);
permanentEntry = {
id: uuid(),
id: randomUUID(),
originalName: file.originalname,
title,
storedName,
path: finalPath,
size: file.size,
@ -61,14 +123,13 @@ function registerUploadedFile(file, { permanent, uploader = "unknown" }) {
uploader,
createdAt,
};
const library = readLibrary();
library.push(permanentEntry);
writeLibrary(library);
}
return {
id: uuid(),
title: file.originalname,
id: randomUUID(),
title,
originalName: file.originalname,
path: finalPath,
storedName,
@ -96,8 +157,8 @@ function createQueueTrackFromLibrary(libraryTrack, requestedBy = "library") {
}
return {
id: uuid(),
title: libraryTrack.originalName,
id: randomUUID(),
title: libraryTrack.title || libraryTrack.originalName,
originalName: libraryTrack.originalName,
path: libraryTrack.path,
storedName: libraryTrack.storedName,
@ -110,6 +171,26 @@ function createQueueTrackFromLibrary(libraryTrack, requestedBy = "library") {
};
}
function cleanupTemporaryFiles(maxAge = TEMP_FILE_MAX_AGE) {
ensureStorageLayout();
const cutoff = Date.now() - maxAge;
for (const entry of fs.readdirSync(TEMP_DIR, { withFileTypes: true })) {
if (!entry.isFile() || entry.name === ".gitkeep") {
continue;
}
const filePath = path.join(TEMP_DIR, entry.name);
try {
if (fs.statSync(filePath).mtimeMs < cutoff) {
fs.unlinkSync(filePath);
}
} catch (error) {
console.error(`Failed to clean temporary file ${filePath}`, error);
}
}
}
function deleteFileSafe(filePath) {
if (!filePath) {
return;
@ -122,6 +203,10 @@ function deleteFileSafe(filePath) {
}
}
function discardUploadedFile(file) {
deleteFileSafe(file?.path);
}
function deletePermanentTrack(id) {
const library = getPermanentLibrary();
const index = library.findIndex((entry) => entry.id === id);
@ -160,6 +245,8 @@ export {
getPermanentLibrary,
findPermanentTrack,
createQueueTrackFromLibrary,
cleanupTemporaryFiles,
discardUploadedFile,
deletePermanentTrack,
handleTrackCompletion,
deleteTrackFile,