Harden bot, storage and web API
This commit is contained in:
parent
e974bc6660
commit
20624a5c9c
43 changed files with 1265 additions and 1012 deletions
|
|
@ -1,4 +1,9 @@
|
|||
import { config } from "../../config.js";
|
||||
import { createHash, timingSafeEqual } from "node:crypto";
|
||||
|
||||
function tokenDigest(value) {
|
||||
return createHash("sha256").update(value).digest();
|
||||
}
|
||||
|
||||
function authMiddleware(req, res, next) {
|
||||
if (!config.webApiKey) {
|
||||
|
|
@ -6,9 +11,10 @@ function authMiddleware(req, res, next) {
|
|||
}
|
||||
|
||||
const header = req.headers.authorization || "";
|
||||
const token = header.replace("Bearer ", "");
|
||||
const match = /^Bearer ([^\s]+)$/.exec(header);
|
||||
const token = match?.[1] || "";
|
||||
|
||||
if (token === config.webApiKey) {
|
||||
if (timingSafeEqual(tokenDigest(token), tokenDigest(config.webApiKey))) {
|
||||
return next();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,12 +5,13 @@ import {
|
|||
findPermanentTrack,
|
||||
getPermanentLibrary,
|
||||
} from "../storage/storageManager.js";
|
||||
import { serializeTrack, serializeTracks } from "../serializers.js";
|
||||
|
||||
function libraryRouter({ queue }) {
|
||||
const router = Router();
|
||||
|
||||
router.get("/", (req, res) => {
|
||||
res.json({ tracks: getPermanentLibrary() });
|
||||
res.json({ tracks: serializeTracks(getPermanentLibrary()) });
|
||||
});
|
||||
|
||||
router.delete("/:libraryId", (req, res) => {
|
||||
|
|
@ -21,7 +22,7 @@ function libraryRouter({ queue }) {
|
|||
}
|
||||
|
||||
queue.removeByLibraryId(track.id);
|
||||
res.json({ removed: track });
|
||||
res.json({ removed: serializeTrack(track) });
|
||||
});
|
||||
|
||||
router.post("/:libraryId/enqueue", (req, res) => {
|
||||
|
|
@ -35,7 +36,7 @@ function libraryRouter({ queue }) {
|
|||
req.body?.requestedBy
|
||||
);
|
||||
queue.enqueue(queueTrack);
|
||||
res.status(201).json({ track: queueTrack });
|
||||
res.status(201).json({ track: serializeTrack(queueTrack) });
|
||||
});
|
||||
|
||||
return router;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Router } from "express";
|
||||
import { createQueueTrackFromLibrary, findPermanentTrack } from "../storage/storageManager.js";
|
||||
import { serializeTrack } from "../serializers.js";
|
||||
|
||||
function queueRouter({ queue }) {
|
||||
const router = Router();
|
||||
|
|
@ -9,7 +10,7 @@ function queueRouter({ queue }) {
|
|||
});
|
||||
|
||||
router.post("/", (req, res) => {
|
||||
const { libraryTrackId, requestedBy } = req.body;
|
||||
const { libraryTrackId, requestedBy } = req.body || {};
|
||||
|
||||
if (!libraryTrackId) {
|
||||
return res.status(400).json({ error: "libraryTrackId manquant" });
|
||||
|
|
@ -23,7 +24,7 @@ function queueRouter({ queue }) {
|
|||
|
||||
const track = createQueueTrackFromLibrary(libraryTrack, requestedBy);
|
||||
queue.enqueue(track);
|
||||
res.status(201).json({ track });
|
||||
res.status(201).json({ track: serializeTrack(track) });
|
||||
});
|
||||
|
||||
router.delete("/:trackId", async (req, res) => {
|
||||
|
|
@ -32,13 +33,13 @@ function queueRouter({ queue }) {
|
|||
return res.status(404).json({ error: "Piste introuvable" });
|
||||
}
|
||||
|
||||
res.json({ removed });
|
||||
res.json({ removed: serializeTrack(removed) });
|
||||
});
|
||||
|
||||
router.patch("/:trackId/move", (req, res) => {
|
||||
const position = Number(req.body?.position);
|
||||
if (Number.isNaN(position)) {
|
||||
return res.status(400).json({ error: "position doit être un nombre" });
|
||||
if (!Number.isInteger(position) || position < 0) {
|
||||
return res.status(400).json({ error: "position doit être un entier positif" });
|
||||
}
|
||||
|
||||
const snapshot = queue.move(req.params.trackId, position);
|
||||
|
|
|
|||
|
|
@ -1,11 +1,41 @@
|
|||
import { Router } from "express";
|
||||
import multer from "multer";
|
||||
import { TEMP_DIR, registerUploadedFile } from "../storage/storageManager.js";
|
||||
import { validateAudioFile } from "../../media/validateAudioFile.js";
|
||||
import { serializeTrack } from "../serializers.js";
|
||||
import {
|
||||
TEMP_DIR,
|
||||
discardUploadedFile,
|
||||
registerUploadedFile,
|
||||
} from "../storage/storageManager.js";
|
||||
|
||||
const ALLOWED_AUDIO_TYPES = new Set([
|
||||
"audio/aac",
|
||||
"audio/flac",
|
||||
"audio/mp4",
|
||||
"audio/mpeg",
|
||||
"audio/ogg",
|
||||
"audio/wav",
|
||||
"audio/webm",
|
||||
"audio/x-flac",
|
||||
"audio/x-m4a",
|
||||
"audio/x-wav",
|
||||
]);
|
||||
|
||||
const upload = multer({
|
||||
dest: TEMP_DIR,
|
||||
limits: {
|
||||
fileSize: 150 * 1024 * 1024,
|
||||
fields: 4,
|
||||
fieldSize: 512,
|
||||
},
|
||||
fileFilter: (_req, file, callback) => {
|
||||
if (file.originalname.length > 255) {
|
||||
const error = new Error("Le nom du fichier est trop long");
|
||||
error.status = 400;
|
||||
callback(error);
|
||||
return;
|
||||
}
|
||||
callback(null, ALLOWED_AUDIO_TYPES.has(file.mimetype));
|
||||
},
|
||||
});
|
||||
|
||||
|
|
@ -19,17 +49,41 @@ function uploadsRouter({ queue }) {
|
|||
|
||||
const permanent = req.body?.permanent === "true";
|
||||
const enqueue = req.body?.enqueue !== "false";
|
||||
const uploader = req.body?.uploader || "web-ui";
|
||||
const uploader = String(req.body?.uploader || "web-ui")
|
||||
.replace(/[\u0000-\u001f]/g, "")
|
||||
.trim()
|
||||
.slice(0, 80);
|
||||
const title = String(req.body?.notes || req.file.originalname)
|
||||
.replace(/[\u0000-\u001f]/g, "")
|
||||
.trim()
|
||||
.slice(0, 200);
|
||||
|
||||
try {
|
||||
const track = registerUploadedFile(req.file, { permanent, uploader });
|
||||
if (!permanent && !enqueue) {
|
||||
const error = new Error(
|
||||
"Un fichier temporaire doit être ajouté à la file d'attente"
|
||||
);
|
||||
error.status = 400;
|
||||
throw error;
|
||||
}
|
||||
|
||||
await validateAudioFile(req.file.path);
|
||||
const track = registerUploadedFile(req.file, {
|
||||
permanent,
|
||||
uploader,
|
||||
title: title || req.file.originalname,
|
||||
});
|
||||
|
||||
if (enqueue) {
|
||||
queue.enqueue(track);
|
||||
}
|
||||
|
||||
return res.status(201).json({ track, enqueued: enqueue });
|
||||
return res.status(201).json({
|
||||
track: serializeTrack(track),
|
||||
enqueued: enqueue,
|
||||
});
|
||||
} catch (error) {
|
||||
discardUploadedFile(req.file);
|
||||
return next(error);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
14
src/web/serializers.js
Normal file
14
src/web/serializers.js
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
function serializeTrack(track) {
|
||||
if (!track) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { path: _path, storedName: _storedName, ...publicTrack } = track;
|
||||
return publicTrack;
|
||||
}
|
||||
|
||||
function serializeTracks(tracks = []) {
|
||||
return tracks.map(serializeTrack);
|
||||
}
|
||||
|
||||
export { serializeTrack, serializeTracks };
|
||||
|
|
@ -1,4 +1,7 @@
|
|||
import express from "express";
|
||||
import helmet from "helmet";
|
||||
import { rateLimit } from "express-rate-limit";
|
||||
import multer from "multer";
|
||||
import path from "path";
|
||||
import { config } from "../config.js";
|
||||
import { authMiddleware } from "./middlewares/auth.js";
|
||||
|
|
@ -6,19 +9,56 @@ import { libraryRouter } from "./routes/library.js";
|
|||
import { playerRouter } from "./routes/player.js";
|
||||
import { queueRouter } from "./routes/queue.js";
|
||||
import { uploadsRouter } from "./routes/uploads.js";
|
||||
import { ensureStorageLayout } from "./storage/storageManager.js";
|
||||
import {
|
||||
cleanupTemporaryFiles,
|
||||
ensureStorageLayout,
|
||||
} from "./storage/storageManager.js";
|
||||
|
||||
const PUBLIC_DIR = path.join(process.cwd(), "public");
|
||||
|
||||
function startWebServer(dependencies) {
|
||||
ensureStorageLayout();
|
||||
cleanupTemporaryFiles();
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.disable("x-powered-by");
|
||||
app.use(helmet());
|
||||
app.use(express.json({ limit: "32kb" }));
|
||||
|
||||
app.get("/healthz", (_req, res) => {
|
||||
res.json({ status: "ok" });
|
||||
});
|
||||
|
||||
const apiRouter = express.Router();
|
||||
apiRouter.use(
|
||||
rateLimit({
|
||||
windowMs: 60_000,
|
||||
limit: 120,
|
||||
standardHeaders: "draft-8",
|
||||
legacyHeaders: false,
|
||||
})
|
||||
);
|
||||
apiRouter.use(
|
||||
rateLimit({
|
||||
windowMs: 15 * 60_000,
|
||||
limit: 20,
|
||||
skipSuccessfulRequests: true,
|
||||
standardHeaders: "draft-8",
|
||||
legacyHeaders: false,
|
||||
message: { error: "Trop de tentatives d'authentification" },
|
||||
})
|
||||
);
|
||||
apiRouter.use(authMiddleware);
|
||||
apiRouter.use("/uploads", uploadsRouter(dependencies));
|
||||
apiRouter.use(
|
||||
"/uploads",
|
||||
rateLimit({
|
||||
windowMs: 15 * 60_000,
|
||||
limit: 10,
|
||||
standardHeaders: "draft-8",
|
||||
legacyHeaders: false,
|
||||
}),
|
||||
uploadsRouter(dependencies)
|
||||
);
|
||||
apiRouter.use("/queue", queueRouter(dependencies));
|
||||
apiRouter.use("/library", libraryRouter(dependencies));
|
||||
apiRouter.use("/player", playerRouter(dependencies));
|
||||
|
|
@ -29,15 +69,28 @@ function startWebServer(dependencies) {
|
|||
);
|
||||
app.use(express.static(PUBLIC_DIR));
|
||||
|
||||
app.use((error, _req, res, _next) => {
|
||||
let status = Number(error?.status) || 500;
|
||||
if (error instanceof multer.MulterError) {
|
||||
status = error.code === "LIMIT_FILE_SIZE" ? 413 : 400;
|
||||
}
|
||||
if (status >= 500) {
|
||||
console.error("Unhandled HTTP error", error);
|
||||
}
|
||||
res.status(status).json({
|
||||
error: status >= 500 ? "Erreur interne du serveur" : error.message,
|
||||
});
|
||||
});
|
||||
|
||||
const port = Number(process.env.PORT || config.webServerPort || 3000);
|
||||
|
||||
app.listen(port, () => {
|
||||
const server = app.listen(port, () => {
|
||||
console.log(
|
||||
`[${new Date().toLocaleString()}] Web control server listening on port ${port}`
|
||||
);
|
||||
});
|
||||
|
||||
return app;
|
||||
return { app, server };
|
||||
}
|
||||
|
||||
export { startWebServer };
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue