- Optional Discord OAuth2 login (identify scope), enabled by DISCORD_CLIENT_SECRET, WEB_PUBLIC_URL and SESSION_SECRET; restricted to members of the configured guild, checked at login. - Stateless 30-day session in a signed HttpOnly SameSite=Lax cookie; the OAuth state is checked against its own short-lived cookie. - The jukebox API accepts the key or the session; with the session, changes must come from the site's own origin. The member's server name becomes the uploader name. - GET /auth/me tells the page whether the login is enabled and who is logged in. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
187 lines
6 KiB
JavaScript
187 lines
6 KiB
JavaScript
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,
|
|
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",
|
|
apiRateLimit({ windowMs: 15 * 60_000, limit: 10 }),
|
|
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.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 = Number(process.env.PORT || config.webServerPort || 3000);
|
|
|
|
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 };
|