Sections: - The library can be split into named, ordered sections, stored in storage/runtime/sections.json; each track keeps its sectionId. - Sections are created, renamed, reordered and deleted from the page (/api/library/sections). Deleting one keeps its tracks, without a section. - A section, or the tracks without one, can be queued in one go, shuffled or not (enqueue-all takes a sectionId). - The upload form (file or link) picks the section of a kept track. - Without any section, the library stays a plain list. Covers: - A kept track takes the cover embedded in its file (MP3, FLAC...), from the web page or /play garder:. Older tracks are looked at once on startup; a track without one keeps cover: null. - "Renommer" becomes "Modifier": a dialog to change the title, the section and the cover (upload with preview, or removal). - ffmpeg turns covers into JPEGs of at most 512 px, stored in storage/covers and deleted with their track. An uploaded image is only passed to ffmpeg after its signature is checked (PNG, JPEG, WebP, GIF), with that decoder forced, so ffmpeg never guesses the format of an unknown file. - Covers are served under /covers without authentication, since an <img> cannot send the key; their random names are only given by the API and never change content (one-year cache). - The current track and the queue show the cover of their library track. Docs: README lists the new data to back up; storage/covers is ignored. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
213 lines
7.3 KiB
JavaScript
213 lines
7.3 KiB
JavaScript
/**
|
|
* @file Serveur web du jukebox : API protégée, connexion avec Discord, flux en direct, pages statiques
|
|
* et messages privés pour les applications locales.
|
|
*
|
|
* Contexte : démarré par index.js dans le même processus que le bot, derrière Caddy en production.
|
|
* Points d'entrée : createApp (application Express seule, utilisée par les tests) et startWebServer
|
|
* (écoute, nettoyage horaire de storage/temp, complément des métadonnées de la bibliothèque).
|
|
* Utilisé par : index.js et les tests web.
|
|
* Dépend de : routes/, middlewares/auth.js, storage/.
|
|
* Attention :
|
|
* - Chaque groupe de routes a sa propre limite de requêtes ; seules les réponses 401 comptent dans
|
|
* la limite contre la force brute.
|
|
* - /api/notifications n'accepte que les connexions locales et sa propre clé, distincte de celle du
|
|
* jukebox.
|
|
* - Les pochettes (/covers) sont servies sans authentification : une balise <img> n'envoie pas la
|
|
* clé. Leurs noms aléatoires ne sont donnés que par l'API, et un nom ne change jamais de
|
|
* contenu (cache d'un an).
|
|
* @see README.md#jukebox
|
|
*/
|
|
|
|
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 {
|
|
createBearerAuth,
|
|
createJukeboxAuth,
|
|
localOnly,
|
|
} from "./middlewares/auth.js";
|
|
import { authRouter, sessionMiddleware } from "./routes/auth.js";
|
|
import { eventsRouter } from "./routes/events.js";
|
|
import { libraryRouter } from "./routes/library.js";
|
|
import { notificationsRouter } from "./routes/notifications.js";
|
|
import { playerRouter } from "./routes/player.js";
|
|
import { queueRouter } from "./routes/queue.js";
|
|
import { uploadsRouter } from "./routes/uploads.js";
|
|
import { backfillLibraryMetadata } from "./storage/libraryMetadata.js";
|
|
import {
|
|
cleanupTemporaryFiles,
|
|
COVERS_DIR,
|
|
ensureStorageLayout,
|
|
} from "./storage/storageManager.js";
|
|
|
|
const PUBLIC_DIR = path.join(process.cwd(), "public");
|
|
|
|
function apiRateLimit(options) {
|
|
return rateLimit({
|
|
standardHeaders: "draft-8",
|
|
legacyHeaders: false,
|
|
...options,
|
|
});
|
|
}
|
|
|
|
// Freine les essais de clé : seules les réponses 401 comptent. Les autres erreurs (404 d'un
|
|
// utilisateur inconnu, 422 messages privés fermés…) ne doivent pas bloquer un client authentifié.
|
|
function authFailureLimit() {
|
|
return apiRateLimit({
|
|
windowMs: 15 * 60_000,
|
|
limit: 20,
|
|
skipSuccessfulRequests: true,
|
|
requestWasSuccessful: (_req, res) => res.statusCode !== 401,
|
|
message: { error: "Trop de tentatives d'authentification" },
|
|
});
|
|
}
|
|
|
|
const UNKNOWN_MEMBER = 10007;
|
|
|
|
// Membre du serveur Discord configuré, ou null s'il n'en fait pas partie.
|
|
function guildMemberFinder(client) {
|
|
return async (userId) => {
|
|
const guild =
|
|
client.guilds?.cache.get(config.discordGuildId) ??
|
|
(await client.guilds.fetch(config.discordGuildId));
|
|
try {
|
|
return await guild.members.fetch(userId);
|
|
} catch (error) {
|
|
if (error?.code === UNKNOWN_MEMBER) return null;
|
|
throw error;
|
|
}
|
|
};
|
|
}
|
|
|
|
function createApp(
|
|
dependencies,
|
|
{
|
|
notificationsApiKey = config.notificationsApiKey,
|
|
oauth = {
|
|
enabled: config.discordOAuthEnabled,
|
|
clientId: config.applicationId,
|
|
clientSecret: config.discordClientSecret,
|
|
publicUrl: config.webPublicUrl,
|
|
sessionSecret: config.sessionSecret,
|
|
},
|
|
findMember = guildMemberFinder(dependencies.client),
|
|
fetchImpl = fetch,
|
|
} = {}
|
|
) {
|
|
const app = express();
|
|
app.disable("x-powered-by");
|
|
app.set("trust proxy", config.webTrustedProxies);
|
|
app.use(helmet());
|
|
app.use(express.json({ limit: "32kb" }));
|
|
app.use(sessionMiddleware(oauth));
|
|
|
|
// /healthz : le processus répond (sonde de vie). /readyz : le bot est aussi connecté à
|
|
// Discord, sinon 503 (à utiliser pour la supervision).
|
|
const discordReady = () => dependencies.client?.isReady?.() ?? false;
|
|
app.get("/healthz", (_req, res) => {
|
|
res.json({ status: "ok", discord: discordReady() ? "ready" : "not-ready" });
|
|
});
|
|
app.get("/readyz", (_req, res) => {
|
|
const ready = discordReady();
|
|
res.status(ready ? 200 : 503).json({ status: ready ? "ready" : "not-ready" });
|
|
});
|
|
|
|
// Messages privés pour les applications de confiance : connexions locales uniquement,
|
|
// avec leur propre clé (pas celle du jukebox, connue de ses utilisateurs).
|
|
app.use(
|
|
"/api/notifications",
|
|
localOnly,
|
|
apiRateLimit({ windowMs: 60_000, limit: 60 }),
|
|
authFailureLimit(),
|
|
createBearerAuth(() => notificationsApiKey),
|
|
notificationsRouter(dependencies)
|
|
);
|
|
|
|
app.use(
|
|
"/auth",
|
|
// /auth/me est appelée à chaque chargement de page : seule la connexion est limitée.
|
|
apiRateLimit({ windowMs: 15 * 60_000, limit: 60, skip: (req) => req.path === "/me" }),
|
|
authRouter({ oauth, findMember, fetchImpl })
|
|
);
|
|
|
|
const apiRouter = express.Router();
|
|
apiRouter.use(apiRateLimit({ windowMs: 60_000, limit: 120 }));
|
|
apiRouter.use(authFailureLimit());
|
|
apiRouter.use(createJukeboxAuth({ publicUrl: oauth.publicUrl }));
|
|
apiRouter.use(
|
|
"/uploads",
|
|
// Envoi de plusieurs fichiers d'un coup : une requête par fichier.
|
|
apiRateLimit({ windowMs: 15 * 60_000, limit: 40 }),
|
|
uploadsRouter(dependencies)
|
|
);
|
|
apiRouter.use("/queue", queueRouter(dependencies));
|
|
apiRouter.use("/library", libraryRouter(dependencies));
|
|
apiRouter.use("/player", playerRouter(dependencies));
|
|
apiRouter.use("/events", eventsRouter(dependencies));
|
|
|
|
app.use("/api", apiRouter);
|
|
app.use(
|
|
"/covers",
|
|
express.static(COVERS_DIR, { immutable: true, maxAge: "365d", index: false, redirect: false })
|
|
);
|
|
app.get(["/jukebox", "/jukebox/"], (_req, res) =>
|
|
res.sendFile(path.join(PUBLIC_DIR, "jukebox.html"))
|
|
);
|
|
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,
|
|
});
|
|
});
|
|
|
|
return app;
|
|
}
|
|
|
|
const TEMP_CLEANUP_INTERVAL = 60 * 60_000;
|
|
|
|
function startWebServer(dependencies) {
|
|
ensureStorageLayout();
|
|
const cleanup = () =>
|
|
cleanupTemporaryFiles(undefined, { keep: dependencies.queue.inUsePaths() });
|
|
cleanup();
|
|
// Les fichiers temporaires de plus de 24 h sont supprimés pendant que le bot tourne,
|
|
// pas seulement à son démarrage.
|
|
const cleanupInterval = setInterval(cleanup, TEMP_CLEANUP_INTERVAL);
|
|
cleanupInterval.unref();
|
|
|
|
backfillLibraryMetadata()
|
|
.then((updated) => {
|
|
if (updated.length > 0) {
|
|
console.log(
|
|
`[${new Date().toLocaleString()}] Library metadata completed for ${updated.length} track(s)`
|
|
);
|
|
dependencies.queue.emit("libraryUpdate");
|
|
}
|
|
})
|
|
.catch((error) => console.error("Unable to complete library metadata", error));
|
|
|
|
const app = createApp(dependencies);
|
|
const port = config.webServerPort;
|
|
|
|
const server = app.listen(port, () => {
|
|
console.log(
|
|
`[${new Date().toLocaleString()}] Web control server listening on port ${port}`
|
|
);
|
|
});
|
|
server.on("close", () => clearInterval(cleanupInterval));
|
|
|
|
return { app, server };
|
|
}
|
|
|
|
export { createApp, startWebServer };
|