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
|
|
@ -14,3 +14,11 @@ WEB_TRUSTED_PROXIES=
|
||||||
NOTIFICATIONS_API_KEY=
|
NOTIFICATIONS_API_KEY=
|
||||||
# Facultatif : lien d'invitation temporaire publié par /invitation sans option « lien ».
|
# Facultatif : lien d'invitation temporaire publié par /invitation sans option « lien ».
|
||||||
INVITE_LINK=
|
INVITE_LINK=
|
||||||
|
# Facultatif : connexion avec Discord sur la page web (active si les trois sont définies).
|
||||||
|
# Secret OAuth2 de l'application (portail développeur Discord, onglet OAuth2).
|
||||||
|
DISCORD_CLIENT_SECRET=
|
||||||
|
# Adresse publique du site, sans / final (https://…). Ajouter <adresse>/auth/discord/callback
|
||||||
|
# aux « Redirects » OAuth2 de l'application.
|
||||||
|
WEB_PUBLIC_URL=
|
||||||
|
# 32 caractères au moins (openssl rand -hex 32) ; le changer déconnecte tout le monde.
|
||||||
|
SESSION_SECRET=
|
||||||
|
|
|
||||||
16
README.md
16
README.md
|
|
@ -98,6 +98,22 @@ file d'attente.
|
||||||
- La page web reçoit les changements en direct par `GET /api/events`
|
- La page web reçoit les changements en direct par `GET /api/events`
|
||||||
(Server-Sent Events, même clé que le reste de l'API).
|
(Server-Sent Events, même clé que le reste de l'API).
|
||||||
|
|
||||||
|
### Connexion avec Discord
|
||||||
|
|
||||||
|
Facultative : sans elle, la page web demande le mot de passe (`WEB_API_KEY`), qui
|
||||||
|
reste utilisable dans tous les cas. Pour l'activer :
|
||||||
|
|
||||||
|
1. Portail développeur Discord, application du bot, onglet OAuth2 : copier le
|
||||||
|
secret client et ajouter la redirection `<WEB_PUBLIC_URL>/auth/discord/callback`.
|
||||||
|
2. Définir `DISCORD_CLIENT_SECRET`, `WEB_PUBLIC_URL` (par exemple
|
||||||
|
`https://palico.example.com`) et `SESSION_SECRET` (`openssl rand -hex 32`).
|
||||||
|
|
||||||
|
Seuls les membres du serveur (`DISCORD_GUILD_ID`) peuvent se connecter. La
|
||||||
|
session dure 30 jours (cookie signé, sans stockage côté serveur) et le nom
|
||||||
|
affiché dans la file est celui du membre sur le serveur. Une personne qui quitte
|
||||||
|
le serveur garde l'accès jusqu'à l'expiration de sa session ; changer
|
||||||
|
`SESSION_SECRET` déconnecte tout le monde.
|
||||||
|
|
||||||
Après l'ajout ou la modification d'une commande, relancer `npm run deploy` pour
|
Après l'ajout ou la modification d'une commande, relancer `npm run deploy` pour
|
||||||
les enregistrer auprès de Discord.
|
les enregistrer auprès de Discord.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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.
|
// INVITE_LINK : lien publié par /invitation quand la commande ne reçoit pas de lien.
|
||||||
const inviteLink = process.env.INVITE_LINK?.trim() || null;
|
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) {
|
if (notificationsApiKey && notificationsApiKey === process.env.WEB_API_KEY) {
|
||||||
throw new Error("NOTIFICATIONS_API_KEY doit être différente de 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,
|
webTrustedProxies,
|
||||||
notificationsApiKey,
|
notificationsApiKey,
|
||||||
inviteLink,
|
inviteLink,
|
||||||
|
discordOAuthEnabled,
|
||||||
|
discordClientSecret,
|
||||||
|
webPublicUrl,
|
||||||
|
sessionSecret,
|
||||||
applicationId: process.env.DISCORD_APPLICATION_ID,
|
applicationId: process.env.DISCORD_APPLICATION_ID,
|
||||||
token: process.env.DISCORD_TOKEN,
|
token: process.env.DISCORD_TOKEN,
|
||||||
voiceChannelId: process.env.VOICE_CHANNEL_ID,
|
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);
|
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"]);
|
const LOOPBACK_ADDRESSES = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
|
||||||
|
|
||||||
function isLoopbackAddress(address) {
|
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" });
|
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) =>
|
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) });
|
res.status(201).json({ tracks: serializeTracks(tracks) });
|
||||||
});
|
});
|
||||||
|
|
@ -70,7 +70,7 @@ function libraryRouter({ queue }) {
|
||||||
|
|
||||||
const queueTrack = createQueueTrackFromLibrary(
|
const queueTrack = createQueueTrackFromLibrary(
|
||||||
baseTrack,
|
baseTrack,
|
||||||
req.body?.requestedBy
|
req.user?.name ?? req.body?.requestedBy
|
||||||
);
|
);
|
||||||
queue.enqueue(queueTrack);
|
queue.enqueue(queueTrack);
|
||||||
res.status(201).json({ track: serializeTrack(queueTrack) });
|
res.status(201).json({ track: serializeTrack(queueTrack) });
|
||||||
|
|
|
||||||
|
|
@ -22,7 +22,7 @@ function queueRouter({ queue }) {
|
||||||
return res.status(404).json({ error: "Fichier permanent introuvable" });
|
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);
|
queue.enqueue(track);
|
||||||
res.status(201).json({ track: serializeTrack(track) });
|
res.status(201).json({ track: serializeTrack(track) });
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -29,10 +29,11 @@ const upload = multer({
|
||||||
function uploadsRouter({ queue }) {
|
function uploadsRouter({ queue }) {
|
||||||
const router = Router();
|
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,
|
permanent: body?.permanent === "true" || body?.permanent === true,
|
||||||
enqueue: body?.enqueue !== "false" && body?.enqueue !== false,
|
enqueue: body?.enqueue !== "false" && body?.enqueue !== false,
|
||||||
uploader: body?.uploader || "web-ui",
|
uploader: user?.name || body?.uploader || "web-ui",
|
||||||
title: body?.notes,
|
title: body?.notes,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -42,10 +43,10 @@ function uploadsRouter({ queue }) {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
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({
|
return res.status(201).json({
|
||||||
track: serializeTrack(track),
|
track: serializeTrack(track),
|
||||||
enqueued: options(req.body).enqueue,
|
enqueued: options(req).enqueue,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return next(error);
|
return next(error);
|
||||||
|
|
@ -61,10 +62,10 @@ function uploadsRouter({ queue }) {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const file = await downloadAudio(url, { destinationDir: TEMP_DIR });
|
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({
|
return res.status(201).json({
|
||||||
track: serializeTrack(track),
|
track: serializeTrack(track),
|
||||||
enqueued: options(req.body).enqueue,
|
enqueued: options(req).enqueue,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return next(error);
|
return next(error);
|
||||||
|
|
|
||||||
|
|
@ -5,10 +5,11 @@ import multer from "multer";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import { config } from "../config.js";
|
import { config } from "../config.js";
|
||||||
import {
|
import {
|
||||||
authMiddleware,
|
|
||||||
createBearerAuth,
|
createBearerAuth,
|
||||||
|
createJukeboxAuth,
|
||||||
localOnly,
|
localOnly,
|
||||||
} from "./middlewares/auth.js";
|
} from "./middlewares/auth.js";
|
||||||
|
import { authRouter, sessionMiddleware } from "./routes/auth.js";
|
||||||
import { eventsRouter } from "./routes/events.js";
|
import { eventsRouter } from "./routes/events.js";
|
||||||
import { libraryRouter } from "./routes/library.js";
|
import { libraryRouter } from "./routes/library.js";
|
||||||
import { notificationsRouter } from "./routes/notifications.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(
|
function createApp(
|
||||||
dependencies,
|
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();
|
const app = express();
|
||||||
app.disable("x-powered-by");
|
app.disable("x-powered-by");
|
||||||
app.set("trust proxy", config.webTrustedProxies);
|
app.set("trust proxy", config.webTrustedProxies);
|
||||||
app.use(helmet());
|
app.use(helmet());
|
||||||
app.use(express.json({ limit: "32kb" }));
|
app.use(express.json({ limit: "32kb" }));
|
||||||
|
app.use(sessionMiddleware(oauth));
|
||||||
|
|
||||||
// /healthz : le processus répond (sonde de vie). /readyz : le bot est aussi connecté à
|
// /healthz : le processus répond (sonde de vie). /readyz : le bot est aussi connecté à
|
||||||
// Discord, sinon 503 (à utiliser pour la supervision).
|
// Discord, sinon 503 (à utiliser pour la supervision).
|
||||||
|
|
@ -75,10 +105,17 @@ function createApp(
|
||||||
notificationsRouter(dependencies)
|
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();
|
const apiRouter = express.Router();
|
||||||
apiRouter.use(apiRateLimit({ windowMs: 60_000, limit: 120 }));
|
apiRouter.use(apiRateLimit({ windowMs: 60_000, limit: 120 }));
|
||||||
apiRouter.use(authFailureLimit());
|
apiRouter.use(authFailureLimit());
|
||||||
apiRouter.use(authMiddleware);
|
apiRouter.use(createJukeboxAuth({ publicUrl: oauth.publicUrl }));
|
||||||
apiRouter.use(
|
apiRouter.use(
|
||||||
"/uploads",
|
"/uploads",
|
||||||
apiRateLimit({ windowMs: 15 * 60_000, limit: 10 }),
|
apiRateLimit({ windowMs: 15 * 60_000, limit: 10 }),
|
||||||
|
|
|
||||||
165
test/discordAuth.test.js
Normal file
165
test/discordAuth.test.js
Normal file
|
|
@ -0,0 +1,165 @@
|
||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
|
||||||
|
Object.assign(process.env, {
|
||||||
|
NODE_ENV: "test",
|
||||||
|
DISCORD_GUILD_ID: "1",
|
||||||
|
SHINUWA_USER_ID: "1",
|
||||||
|
WEB_SERVER_PORT: "3000",
|
||||||
|
WEB_API_KEY: "web-key",
|
||||||
|
DISCORD_APPLICATION_ID: "client-id",
|
||||||
|
DISCORD_TOKEN: "test-token",
|
||||||
|
VOICE_CHANNEL_ID: "1",
|
||||||
|
TEXT_CHANNEL_ID: "1",
|
||||||
|
GAME_SERVERS_MESSAGE_ID: "1",
|
||||||
|
});
|
||||||
|
|
||||||
|
const { createApp } = await import("../src/web/server.js");
|
||||||
|
const { createSessionToken, readSessionToken } = await import("../src/web/auth/session.js");
|
||||||
|
|
||||||
|
const SECRET = "s".repeat(40);
|
||||||
|
const MEMBER_ID = "111111111111111111";
|
||||||
|
const STRANGER_ID = "222222222222222222";
|
||||||
|
|
||||||
|
const oauth = {
|
||||||
|
enabled: true,
|
||||||
|
clientId: "client-id",
|
||||||
|
clientSecret: "client-secret",
|
||||||
|
publicUrl: "http://localhost",
|
||||||
|
sessionSecret: SECRET,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Faux Discord : le code « member » identifie un membre du serveur, « stranger » un inconnu.
|
||||||
|
function fakeDiscordFetch(calls) {
|
||||||
|
return async (url, options = {}) => {
|
||||||
|
calls.push({ url, options });
|
||||||
|
if (url.endsWith("/oauth2/token")) {
|
||||||
|
const code = options.body.get("code");
|
||||||
|
return Response.json({ access_token: `token-${code}` });
|
||||||
|
}
|
||||||
|
if (url.endsWith("/users/@me")) {
|
||||||
|
const token = options.headers.authorization;
|
||||||
|
const id = token === "Bearer token-member" ? MEMBER_ID : STRANGER_ID;
|
||||||
|
return Response.json({ id, username: "palico", global_name: "Palico" });
|
||||||
|
}
|
||||||
|
return new Response(null, { status: 404 });
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const fakeQueue = {
|
||||||
|
snapshot: () => ({ current: null, upcoming: [], status: "idle", loop: false, position: 0 }),
|
||||||
|
};
|
||||||
|
|
||||||
|
async function withApp(run) {
|
||||||
|
const calls = [];
|
||||||
|
const app = createApp(
|
||||||
|
{ queue: fakeQueue, client: {} },
|
||||||
|
{
|
||||||
|
oauth,
|
||||||
|
fetchImpl: fakeDiscordFetch(calls),
|
||||||
|
findMember: async (id) => (id === MEMBER_ID ? { displayName: "Chef Palico" } : null),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
const server = app.listen(0, "127.0.0.1");
|
||||||
|
await new Promise((resolve) => server.once("listening", resolve));
|
||||||
|
try {
|
||||||
|
await run(`http://127.0.0.1:${server.address().port}`, calls);
|
||||||
|
} finally {
|
||||||
|
await new Promise((resolve) => server.close(resolve));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function cookieValue(response, name) {
|
||||||
|
const header = response.headers.getSetCookie().find((cookie) => cookie.startsWith(`${name}=`));
|
||||||
|
return header ? decodeURIComponent(header.split(";")[0].slice(name.length + 1)) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function login(base, code) {
|
||||||
|
const start = await fetch(`${base}/auth/discord`, { redirect: "manual" });
|
||||||
|
assert.equal(start.status, 303);
|
||||||
|
const authorizeUrl = new URL(start.headers.get("location"));
|
||||||
|
assert.equal(authorizeUrl.hostname, "discord.com");
|
||||||
|
assert.equal(authorizeUrl.searchParams.get("scope"), "identify");
|
||||||
|
const state = authorizeUrl.searchParams.get("state");
|
||||||
|
const stateCookie = cookieValue(start, "palico_oauth_state");
|
||||||
|
assert.equal(stateCookie, state);
|
||||||
|
|
||||||
|
return fetch(`${base}/auth/discord/callback?code=${code}&state=${state}`, {
|
||||||
|
redirect: "manual",
|
||||||
|
headers: { cookie: `palico_oauth_state=${stateCookie}` },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test("a guild member logs in with Discord and uses the jukebox API", async () => {
|
||||||
|
await withApp(async (base) => {
|
||||||
|
const callback = await login(base, "member");
|
||||||
|
assert.equal(callback.status, 303);
|
||||||
|
assert.equal(callback.headers.get("location"), "/jukebox/");
|
||||||
|
const session = cookieValue(callback, "palico_session");
|
||||||
|
assert.ok(session);
|
||||||
|
|
||||||
|
const me = await (await fetch(`${base}/auth/me`, { headers: { cookie: `palico_session=${session}` } })).json();
|
||||||
|
assert.deepEqual(me, { oauthEnabled: true, user: { id: MEMBER_ID, name: "Chef Palico" } });
|
||||||
|
|
||||||
|
const queue = await fetch(`${base}/api/queue`, { headers: { cookie: `palico_session=${session}` } });
|
||||||
|
assert.equal(queue.status, 200);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("someone outside the guild is turned away", async () => {
|
||||||
|
await withApp(async (base) => {
|
||||||
|
const callback = await login(base, "stranger");
|
||||||
|
assert.equal(callback.headers.get("location"), "/jukebox/?login=not-member");
|
||||||
|
assert.equal(cookieValue(callback, "palico_session"), null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a callback without the matching state is refused", async () => {
|
||||||
|
await withApp(async (base, calls) => {
|
||||||
|
const callback = await fetch(`${base}/auth/discord/callback?code=member&state=forged`, {
|
||||||
|
redirect: "manual",
|
||||||
|
headers: { cookie: "palico_oauth_state=other" },
|
||||||
|
});
|
||||||
|
assert.equal(callback.headers.get("location"), "/jukebox/?login=state");
|
||||||
|
assert.equal(calls.length, 0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a cookie session cannot change anything from another site", async () => {
|
||||||
|
await withApp(async (base) => {
|
||||||
|
const session = createSessionToken({ id: MEMBER_ID, name: "Chef Palico" }, SECRET);
|
||||||
|
const response = await fetch(`${base}/api/player/skip`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { cookie: `palico_session=${session}`, origin: "https://evil.example" },
|
||||||
|
});
|
||||||
|
assert.equal(response.status, 403);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("tampered or expired session tokens are rejected", () => {
|
||||||
|
const token = createSessionToken({ id: MEMBER_ID, name: "Chef" }, SECRET, 0);
|
||||||
|
assert.equal(readSessionToken(token, SECRET, 1)?.id, MEMBER_ID);
|
||||||
|
assert.equal(readSessionToken(token, "x".repeat(40), 1), null);
|
||||||
|
const [payload, signature] = token.split(".");
|
||||||
|
const forged = Buffer.from(JSON.stringify({ sub: STRANGER_ID, name: "x", exp: 9e15 })).toString("base64url");
|
||||||
|
assert.equal(readSessionToken(`${forged}.${signature}`, SECRET, 1), null);
|
||||||
|
assert.equal(readSessionToken(`${payload}.${signature}`, SECRET, 31 * 24 * 3600 * 1000), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("without OAuth the API still needs the key", async () => {
|
||||||
|
const app = createApp({ queue: fakeQueue, client: {} });
|
||||||
|
const server = app.listen(0, "127.0.0.1");
|
||||||
|
await new Promise((resolve) => server.once("listening", resolve));
|
||||||
|
const base = `http://127.0.0.1:${server.address().port}`;
|
||||||
|
try {
|
||||||
|
const me = await (await fetch(`${base}/auth/me`)).json();
|
||||||
|
assert.equal(me.oauthEnabled, false);
|
||||||
|
assert.equal((await fetch(`${base}/api/queue`)).status, 401);
|
||||||
|
assert.equal(
|
||||||
|
(await fetch(`${base}/api/queue`, { headers: { authorization: "Bearer web-key" } })).status,
|
||||||
|
200
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await new Promise((resolve) => server.close(resolve));
|
||||||
|
}
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue