Let guild members log in to the jukebox with Discord
- 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>
This commit is contained in:
parent
9fb54798dd
commit
399e851178
11 changed files with 489 additions and 13 deletions
|
|
@ -41,6 +41,29 @@ const notificationsApiKey = process.env.NOTIFICATIONS_API_KEY?.trim() || null;
|
|||
// INVITE_LINK : lien publié par /invitation quand la commande ne reçoit pas de lien.
|
||||
const inviteLink = process.env.INVITE_LINK?.trim() || null;
|
||||
|
||||
// Connexion avec Discord sur la page web (facultative, active si les trois sont définies) :
|
||||
// DISCORD_CLIENT_SECRET (portail développeur, OAuth2), WEB_PUBLIC_URL (adresse publique du
|
||||
// site, sans / final) et SESSION_SECRET (32 caractères au moins, signe les sessions).
|
||||
const discordClientSecret = process.env.DISCORD_CLIENT_SECRET?.trim() || null;
|
||||
const webPublicUrl = process.env.WEB_PUBLIC_URL?.trim().replace(/\/+$/, "") || null;
|
||||
const sessionSecret = process.env.SESSION_SECRET?.trim() || null;
|
||||
const discordOAuthEnabled = Boolean(discordClientSecret && webPublicUrl && sessionSecret);
|
||||
|
||||
if (discordOAuthEnabled) {
|
||||
let publicUrl;
|
||||
try {
|
||||
publicUrl = new URL(webPublicUrl);
|
||||
} catch {
|
||||
throw new Error("WEB_PUBLIC_URL doit être une adresse complète (https://…)");
|
||||
}
|
||||
if (publicUrl.protocol !== "https:" && publicUrl.hostname !== "localhost") {
|
||||
throw new Error("WEB_PUBLIC_URL doit être en https");
|
||||
}
|
||||
if (sessionSecret.length < 32) {
|
||||
throw new Error("SESSION_SECRET doit contenir au moins 32 caractères");
|
||||
}
|
||||
}
|
||||
|
||||
if (notificationsApiKey && notificationsApiKey === process.env.WEB_API_KEY) {
|
||||
throw new Error("NOTIFICATIONS_API_KEY doit être différente de WEB_API_KEY");
|
||||
}
|
||||
|
|
@ -54,6 +77,10 @@ const config = Object.freeze({
|
|||
webTrustedProxies,
|
||||
notificationsApiKey,
|
||||
inviteLink,
|
||||
discordOAuthEnabled,
|
||||
discordClientSecret,
|
||||
webPublicUrl,
|
||||
sessionSecret,
|
||||
applicationId: process.env.DISCORD_APPLICATION_ID,
|
||||
token: process.env.DISCORD_TOKEN,
|
||||
voiceChannelId: process.env.VOICE_CHANNEL_ID,
|
||||
|
|
|
|||
78
src/web/auth/session.js
Normal file
78
src/web/auth/session.js
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
|
||||
const SESSION_COOKIE = "palico_session";
|
||||
const STATE_COOKIE = "palico_oauth_state";
|
||||
const SESSION_DURATION = 30 * 24 * 60 * 60 * 1000;
|
||||
|
||||
function sign(payload, secret) {
|
||||
return createHmac("sha256", secret).update(payload).digest("base64url");
|
||||
}
|
||||
|
||||
// Jeton de session sans stockage côté serveur : « données.signature », signé par HMAC.
|
||||
// Changer SESSION_SECRET déconnecte tout le monde.
|
||||
function createSessionToken({ id, name }, secret, now = Date.now()) {
|
||||
const payload = Buffer.from(
|
||||
JSON.stringify({ sub: id, name, exp: now + SESSION_DURATION })
|
||||
).toString("base64url");
|
||||
return `${payload}.${sign(payload, secret)}`;
|
||||
}
|
||||
|
||||
function readSessionToken(token, secret, now = Date.now()) {
|
||||
if (typeof token !== "string" || !secret) return null;
|
||||
const [payload, signature, extra] = token.split(".");
|
||||
if (!payload || !signature || extra !== undefined) return null;
|
||||
|
||||
const expected = Buffer.from(sign(payload, secret));
|
||||
const received = Buffer.from(signature);
|
||||
if (expected.length !== received.length || !timingSafeEqual(expected, received)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
||||
if (typeof data.sub !== "string" || typeof data.exp !== "number" || data.exp < now) {
|
||||
return null;
|
||||
}
|
||||
return { id: data.sub, name: String(data.name || "").slice(0, 80) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseCookies(header = "") {
|
||||
const cookies = {};
|
||||
for (const part of header.split(";")) {
|
||||
const index = part.indexOf("=");
|
||||
if (index === -1) continue;
|
||||
const name = part.slice(0, index).trim();
|
||||
try {
|
||||
cookies[name] = decodeURIComponent(part.slice(index + 1).trim());
|
||||
} catch {
|
||||
// Cookie mal formé : ignoré.
|
||||
}
|
||||
}
|
||||
return cookies;
|
||||
}
|
||||
|
||||
function serializeCookie(name, value, { maxAge, path = "/", secure = true } = {}) {
|
||||
return [
|
||||
`${name}=${encodeURIComponent(value)}`,
|
||||
`Path=${path}`,
|
||||
"HttpOnly",
|
||||
"SameSite=Lax",
|
||||
secure ? "Secure" : null,
|
||||
maxAge !== undefined ? `Max-Age=${Math.floor(maxAge / 1000)}` : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("; ");
|
||||
}
|
||||
|
||||
export {
|
||||
SESSION_COOKIE,
|
||||
SESSION_DURATION,
|
||||
STATE_COOKIE,
|
||||
createSessionToken,
|
||||
parseCookies,
|
||||
readSessionToken,
|
||||
serializeCookie,
|
||||
};
|
||||
|
|
@ -30,6 +30,25 @@ function createBearerAuth(getExpectedKey) {
|
|||
|
||||
const authMiddleware = createBearerAuth(() => config.webApiKey);
|
||||
|
||||
// API du jukebox : la clé (en-tête Authorization) ou une session Discord (cookie, voir
|
||||
// sessionMiddleware). Avec le cookie, une requête qui modifie quelque chose doit venir du site
|
||||
// lui-même (en-tête Origin), en plus de la protection SameSite du cookie.
|
||||
function createJukeboxAuth({ publicUrl } = {}) {
|
||||
const allowedOrigin = publicUrl ? new URL(publicUrl).origin : null;
|
||||
return function jukeboxAuth(req, res, next) {
|
||||
if (req.headers.authorization || !req.user) {
|
||||
return authMiddleware(req, res, next);
|
||||
}
|
||||
|
||||
const safeMethod = req.method === "GET" || req.method === "HEAD";
|
||||
const origin = req.headers.origin;
|
||||
if (!safeMethod && origin && origin !== allowedOrigin) {
|
||||
return res.status(403).json({ error: "Origine refusée" });
|
||||
}
|
||||
return next();
|
||||
};
|
||||
}
|
||||
|
||||
const LOOPBACK_ADDRESSES = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
|
||||
|
||||
function isLoopbackAddress(address) {
|
||||
|
|
@ -45,4 +64,4 @@ function localOnly(req, res, next) {
|
|||
return res.status(403).json({ error: "Route réservée aux applications locales", code: "LOCAL_ONLY" });
|
||||
}
|
||||
|
||||
export { authMiddleware, createBearerAuth, isLoopbackAddress, localOnly };
|
||||
export { authMiddleware, createBearerAuth, createJukeboxAuth, isLoopbackAddress, localOnly };
|
||||
|
|
|
|||
125
src/web/routes/auth.js
Normal file
125
src/web/routes/auth.js
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
import { Router } from "express";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import {
|
||||
SESSION_COOKIE,
|
||||
SESSION_DURATION,
|
||||
STATE_COOKIE,
|
||||
createSessionToken,
|
||||
parseCookies,
|
||||
readSessionToken,
|
||||
serializeCookie,
|
||||
} from "../auth/session.js";
|
||||
|
||||
const DISCORD_API = "https://discord.com/api/v10";
|
||||
const STATE_DURATION = 10 * 60 * 1000;
|
||||
|
||||
// Lit la session (cookie signé) et place l'utilisateur dans req.user.
|
||||
function sessionMiddleware(oauth) {
|
||||
return function readSession(req, _res, next) {
|
||||
if (oauth.enabled) {
|
||||
const token = parseCookies(req.headers.cookie)[SESSION_COOKIE];
|
||||
req.user = readSessionToken(token, oauth.sessionSecret);
|
||||
}
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
// Connexion avec Discord (OAuth2, portée « identify ») réservée aux membres du serveur.
|
||||
// oauth : { enabled, clientId, clientSecret, publicUrl, sessionSecret }.
|
||||
// findMember(userId) renvoie le membre du serveur ou null.
|
||||
function authRouter({ oauth, findMember, fetchImpl = fetch }) {
|
||||
const router = Router();
|
||||
const secure = oauth.enabled && new URL(oauth.publicUrl).protocol === "https:";
|
||||
const redirectUri = oauth.enabled ? `${oauth.publicUrl}/auth/discord/callback` : null;
|
||||
const fail = (res, reason) => res.redirect(303, `/jukebox/?login=${reason}`);
|
||||
|
||||
router.get("/me", (req, res) => {
|
||||
res.set("Cache-Control", "no-store");
|
||||
res.json({ oauthEnabled: oauth.enabled, user: req.user ?? null });
|
||||
});
|
||||
|
||||
router.get("/discord", (req, res) => {
|
||||
if (!oauth.enabled) {
|
||||
return res.status(404).json({ error: "Connexion avec Discord désactivée" });
|
||||
}
|
||||
|
||||
const state = randomBytes(24).toString("base64url");
|
||||
res.append(
|
||||
"Set-Cookie",
|
||||
serializeCookie(STATE_COOKIE, state, { maxAge: STATE_DURATION, path: "/auth", secure })
|
||||
);
|
||||
const params = new URLSearchParams({
|
||||
client_id: oauth.clientId,
|
||||
response_type: "code",
|
||||
redirect_uri: redirectUri,
|
||||
scope: "identify",
|
||||
state,
|
||||
prompt: "none",
|
||||
});
|
||||
res.redirect(303, `https://discord.com/oauth2/authorize?${params}`);
|
||||
});
|
||||
|
||||
router.get("/discord/callback", async (req, res) => {
|
||||
if (!oauth.enabled) {
|
||||
return res.status(404).json({ error: "Connexion avec Discord désactivée" });
|
||||
}
|
||||
|
||||
const expectedState = parseCookies(req.headers.cookie)[STATE_COOKIE];
|
||||
res.append(
|
||||
"Set-Cookie",
|
||||
serializeCookie(STATE_COOKIE, "", { maxAge: 0, path: "/auth", secure })
|
||||
);
|
||||
if (req.query.error) return fail(res, "denied");
|
||||
if (!expectedState || req.query.state !== expectedState) return fail(res, "state");
|
||||
if (typeof req.query.code !== "string") return fail(res, "failed");
|
||||
|
||||
try {
|
||||
const tokenResponse = await fetchImpl(`${DISCORD_API}/oauth2/token`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
client_id: oauth.clientId,
|
||||
client_secret: oauth.clientSecret,
|
||||
grant_type: "authorization_code",
|
||||
code: req.query.code,
|
||||
redirect_uri: redirectUri,
|
||||
}),
|
||||
});
|
||||
if (!tokenResponse.ok) throw new Error(`token exchange: ${tokenResponse.status}`);
|
||||
const { access_token: accessToken } = await tokenResponse.json();
|
||||
|
||||
const userResponse = await fetchImpl(`${DISCORD_API}/users/@me`, {
|
||||
headers: { authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
if (!userResponse.ok) throw new Error(`user lookup: ${userResponse.status}`);
|
||||
const user = await userResponse.json();
|
||||
|
||||
const member = await findMember(user.id);
|
||||
if (!member) return fail(res, "not-member");
|
||||
|
||||
const name = member.displayName || user.global_name || user.username;
|
||||
res.append(
|
||||
"Set-Cookie",
|
||||
serializeCookie(
|
||||
SESSION_COOKIE,
|
||||
createSessionToken({ id: user.id, name }, oauth.sessionSecret),
|
||||
{ maxAge: SESSION_DURATION, secure }
|
||||
)
|
||||
);
|
||||
console.log(`[${new Date().toLocaleString()}] Web login: ${user.id}`);
|
||||
return res.redirect(303, "/jukebox/");
|
||||
} catch (error) {
|
||||
console.error("Discord login failed", error);
|
||||
return fail(res, "failed");
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/logout", (req, res) => {
|
||||
res.append("Set-Cookie", serializeCookie(SESSION_COOKIE, "", { maxAge: 0, secure }));
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
export { authRouter, sessionMiddleware };
|
||||
|
|
@ -57,7 +57,7 @@ function libraryRouter({ queue }) {
|
|||
}
|
||||
|
||||
const tracks = entries.map((entry) =>
|
||||
queue.enqueue(createQueueTrackFromLibrary(entry, req.body?.requestedBy))
|
||||
queue.enqueue(createQueueTrackFromLibrary(entry, req.user?.name ?? req.body?.requestedBy))
|
||||
);
|
||||
res.status(201).json({ tracks: serializeTracks(tracks) });
|
||||
});
|
||||
|
|
@ -70,7 +70,7 @@ function libraryRouter({ queue }) {
|
|||
|
||||
const queueTrack = createQueueTrackFromLibrary(
|
||||
baseTrack,
|
||||
req.body?.requestedBy
|
||||
req.user?.name ?? req.body?.requestedBy
|
||||
);
|
||||
queue.enqueue(queueTrack);
|
||||
res.status(201).json({ track: serializeTrack(queueTrack) });
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ function queueRouter({ queue }) {
|
|||
return res.status(404).json({ error: "Fichier permanent introuvable" });
|
||||
}
|
||||
|
||||
const track = createQueueTrackFromLibrary(libraryTrack, requestedBy);
|
||||
const track = createQueueTrackFromLibrary(libraryTrack, req.user?.name ?? requestedBy);
|
||||
queue.enqueue(track);
|
||||
res.status(201).json({ track: serializeTrack(track) });
|
||||
});
|
||||
|
|
|
|||
|
|
@ -29,10 +29,11 @@ const upload = multer({
|
|||
function uploadsRouter({ queue }) {
|
||||
const router = Router();
|
||||
|
||||
const options = (body) => ({
|
||||
// Connecté avec Discord, le nom vient de la session et non du formulaire.
|
||||
const options = ({ body, user }) => ({
|
||||
permanent: body?.permanent === "true" || body?.permanent === true,
|
||||
enqueue: body?.enqueue !== "false" && body?.enqueue !== false,
|
||||
uploader: body?.uploader || "web-ui",
|
||||
uploader: user?.name || body?.uploader || "web-ui",
|
||||
title: body?.notes,
|
||||
});
|
||||
|
||||
|
|
@ -42,10 +43,10 @@ function uploadsRouter({ queue }) {
|
|||
}
|
||||
|
||||
try {
|
||||
const track = await ingestAudioFile(req.file, options(req.body), { queue });
|
||||
const track = await ingestAudioFile(req.file, options(req), { queue });
|
||||
return res.status(201).json({
|
||||
track: serializeTrack(track),
|
||||
enqueued: options(req.body).enqueue,
|
||||
enqueued: options(req).enqueue,
|
||||
});
|
||||
} catch (error) {
|
||||
return next(error);
|
||||
|
|
@ -61,10 +62,10 @@ function uploadsRouter({ queue }) {
|
|||
|
||||
try {
|
||||
const file = await downloadAudio(url, { destinationDir: TEMP_DIR });
|
||||
const track = await ingestAudioFile(file, options(req.body), { queue });
|
||||
const track = await ingestAudioFile(file, options(req), { queue });
|
||||
return res.status(201).json({
|
||||
track: serializeTrack(track),
|
||||
enqueued: options(req.body).enqueue,
|
||||
enqueued: options(req).enqueue,
|
||||
});
|
||||
} catch (error) {
|
||||
return next(error);
|
||||
|
|
|
|||
|
|
@ -5,10 +5,11 @@ import multer from "multer";
|
|||
import path from "path";
|
||||
import { config } from "../config.js";
|
||||
import {
|
||||
authMiddleware,
|
||||
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";
|
||||
|
|
@ -43,15 +44,44 @@ function authFailureLimit() {
|
|||
});
|
||||
}
|
||||
|
||||
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 } = {}
|
||||
{
|
||||
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).
|
||||
|
|
@ -75,10 +105,17 @@ function createApp(
|
|||
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(authMiddleware);
|
||||
apiRouter.use(createJukeboxAuth({ publicUrl: oauth.publicUrl }));
|
||||
apiRouter.use(
|
||||
"/uploads",
|
||||
apiRateLimit({ windowMs: 15 * 60_000, limit: 10 }),
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue