palico-bot/src/web/middlewares/auth.js
Shinuwa 399e851178 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>
2026-11-29 12:17:48 +01:00

67 lines
2.4 KiB
JavaScript

import { config } from "../../config.js";
import { createHash, timingSafeEqual } from "node:crypto";
function tokenDigest(value) {
return createHash("sha256").update(value).digest();
}
function readBearerToken(req) {
const header = req.headers.authorization || "";
const match = /^Bearer ([^\s]+)$/.exec(header);
return match?.[1] || "";
}
// Exige `Authorization: Bearer <clé>`. Sans clé configurée, la route est désactivée (503),
// jamais ouverte.
function createBearerAuth(getExpectedKey) {
return function bearerAuth(req, res, next) {
const expectedKey = getExpectedKey();
if (!expectedKey) {
return res.status(503).json({ error: "Service désactivé", code: "DISABLED" });
}
if (timingSafeEqual(tokenDigest(readBearerToken(req)), tokenDigest(expectedKey))) {
return next();
}
return res.status(401).json({ error: "Unauthorized" });
};
}
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) {
return LOOPBACK_ADDRESSES.has(address);
}
// N'accepte que les connexions ouvertes depuis la machine elle-même. On lit l'adresse de
// la socket, pas req.ip : une requête relayée par Caddy arrive de son adresse à lui.
function localOnly(req, res, next) {
if (isLoopbackAddress(req.socket?.remoteAddress)) {
return next();
}
return res.status(403).json({ error: "Route réservée aux applications locales", code: "LOCAL_ONLY" });
}
export { authMiddleware, createBearerAuth, createJukeboxAuth, isLoopbackAddress, localOnly };