Fix deploy and lock down the DM route; add /invitation
All checks were successful
Deploy Palico Bot / deploy (push) Successful in 32s
All checks were successful
Deploy Palico Bot / deploy (push) Successful in 32s
- Deploy workflow: pin node:24-bookworm; install openssh-client only if missing - Auth failure limiter counts only 401s (422/404 no longer lock out clients) - trust proxy configurable (WEB_TRUSTED_PROXIES), never "true" - DM route: loopback connections only, dedicated NOTIFICATIONS_API_KEY, 503 when unset - Jukebox: no polling without a key, stop on 401 - /invitation: posts the temporary invite message after checking the link - Stop tracking storage/library.json; README describes the real deployment Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
3655b1ad74
commit
6895d20459
16 changed files with 554 additions and 99 deletions
70
src/commands/utility/invitation.js
Normal file
70
src/commands/utility/invitation.js
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
|
||||
import { config } from "../../config.js";
|
||||
import { requirePermission } from "../../features/permissions.js";
|
||||
import {
|
||||
InvitationError,
|
||||
buildInvitationMessage,
|
||||
checkInvitation,
|
||||
} from "../../features/invitation.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("invitation")
|
||||
.setDescription("Publie le message d'invitation temporaire dans ce salon")
|
||||
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
|
||||
.addStringOption((option) =>
|
||||
option
|
||||
.setName("lien")
|
||||
.setDescription("Lien d'invitation (par défaut : celui de la configuration)")
|
||||
.setMaxLength(300)
|
||||
),
|
||||
async execute(interaction) {
|
||||
if (!(await requirePermission(interaction, PermissionFlagsBits.ManageGuild))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const channel = interaction.channel;
|
||||
if (!interaction.guild || !channel?.isTextBased()) {
|
||||
await interaction.reply({
|
||||
content: "Cette commande doit être utilisée dans un salon textuel du serveur.",
|
||||
ephemeral: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const input = interaction.options.getString("lien") || config.inviteLink;
|
||||
if (!input) {
|
||||
await interaction.reply({
|
||||
content: "Aucun lien : passe l'option `lien` ou définis `INVITE_LINK`.",
|
||||
ephemeral: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await interaction.deferReply({ ephemeral: true });
|
||||
|
||||
let checked;
|
||||
try {
|
||||
checked = await checkInvitation(interaction.guild, interaction.client, input);
|
||||
} catch (error) {
|
||||
if (error instanceof InvitationError) {
|
||||
await interaction.editReply(`Message non publié : ${error.message}`);
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
await channel.send({
|
||||
content: buildInvitationMessage(checked.link),
|
||||
allowedMentions: { parse: [] },
|
||||
});
|
||||
await interaction.editReply(
|
||||
[
|
||||
"Message publié. Pense à l'épingler (`/deletemsgs` garde les messages épinglés) et à désépingler l'ancien.",
|
||||
...checked.warnings.map((warning) => `⚠️ ${warning}`),
|
||||
].join("\n")
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
export { command };
|
||||
|
|
@ -8,6 +8,7 @@ const command = {
|
|||
let message = `Voila la liste des commandes que tu peux utiliser :
|
||||
__Categorie Utililaires__ :
|
||||
\`/deletemsgs\`: Supprime les 100 derniers messages non épinglés
|
||||
\`/invitation\`: Publie le message d'invitation temporaire (lien vérifié)
|
||||
|
||||
__Categorie Vocal__ :
|
||||
\`/muteall\`: Rends tout le monde muet
|
||||
|
|
|
|||
|
|
@ -31,12 +31,29 @@ if (
|
|||
throw new Error("WEB_SERVER_PORT doit être compris entre 1 et 65535");
|
||||
}
|
||||
|
||||
// Variables facultatives.
|
||||
// WEB_TRUSTED_PROXIES : proxys dont on accepte l'en-tête X-Forwarded-For (syntaxe
|
||||
// « trust proxy » d'Express). Ne jamais mettre « true » : le port est joignable sans proxy.
|
||||
const webTrustedProxies = process.env.WEB_TRUSTED_PROXIES?.trim() || "loopback";
|
||||
// NOTIFICATIONS_API_KEY : clé des applications de confiance (Sokko TCG). Sans elle, la
|
||||
// route des messages privés est désactivée.
|
||||
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;
|
||||
|
||||
if (notificationsApiKey && notificationsApiKey === process.env.WEB_API_KEY) {
|
||||
throw new Error("NOTIFICATIONS_API_KEY doit être différente de WEB_API_KEY");
|
||||
}
|
||||
|
||||
const config = Object.freeze({
|
||||
environnement: process.env.NODE_ENV,
|
||||
discordGuildId: process.env.DISCORD_GUILD_ID,
|
||||
shinuwaUserId: process.env.SHINUWA_USER_ID,
|
||||
webServerPort,
|
||||
webApiKey: process.env.WEB_API_KEY,
|
||||
webTrustedProxies,
|
||||
notificationsApiKey,
|
||||
inviteLink,
|
||||
applicationId: process.env.DISCORD_APPLICATION_ID,
|
||||
token: process.env.DISCORD_TOKEN,
|
||||
voiceChannelId: process.env.VOICE_CHANNEL_ID,
|
||||
|
|
|
|||
90
src/features/invitation.js
Normal file
90
src/features/invitation.js
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
// Message d'invitation : le serveur n'autorise pas ses membres à créer des invitations ; un seul
|
||||
// lien à adhésion temporaire est partagé par le bot. Pour garder quelqu'un, on lui donne un rôle.
|
||||
import { codeBlock, DiscordjsErrorCodes } from "discord.js";
|
||||
|
||||
const INVITE_URL_PATTERN =
|
||||
/^(?:https?:\/\/)?(?:www\.)?discord(?:(?:app)?\.com\/invite|\.gg(?:\/invite)?)\/([\w-]{2,255})\/?$/i;
|
||||
const INVITE_CODE_PATTERN = /^[\w-]{2,255}$/;
|
||||
// Codes de l'API Discord : invitation inconnue, permission manquante.
|
||||
const UNKNOWN_INVITE = 10006;
|
||||
const MISSING_PERMISSIONS = 50013;
|
||||
|
||||
class InvitationError extends Error {}
|
||||
|
||||
function parseInviteCode(input) {
|
||||
const value = String(input ?? "").trim();
|
||||
const match = INVITE_URL_PATTERN.exec(value);
|
||||
if (match) return match[1];
|
||||
return INVITE_CODE_PATTERN.test(value) ? value : null;
|
||||
}
|
||||
|
||||
async function fetchPublicInvite(client, code, guild) {
|
||||
let invite;
|
||||
try {
|
||||
invite = await client.fetchInvite(code);
|
||||
} catch (error) {
|
||||
if (error?.code === UNKNOWN_INVITE) {
|
||||
throw new InvitationError("Cette invitation n'existe pas ou a expiré.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (invite.guild?.id !== guild.id) {
|
||||
throw new InvitationError("Cette invitation mène à un autre serveur.");
|
||||
}
|
||||
return invite;
|
||||
}
|
||||
|
||||
// Vérifie le lien avant de le publier. Renvoie le lien normalisé et des avertissements ;
|
||||
// lève InvitationError si le lien ne doit pas être publié.
|
||||
async function checkInvitation(guild, client, input) {
|
||||
const code = parseInviteCode(input);
|
||||
if (!code) {
|
||||
throw new InvitationError("Lien d'invitation invalide.");
|
||||
}
|
||||
|
||||
const warnings = [];
|
||||
let invite;
|
||||
try {
|
||||
// Seule la liste des invitations du serveur dit si l'invitation est temporaire
|
||||
// (permission « Gérer le serveur »).
|
||||
invite = await guild.invites.fetch({ code, force: true, cache: false });
|
||||
} catch (error) {
|
||||
if (error?.code === DiscordjsErrorCodes.InviteNotFound) {
|
||||
throw new InvitationError("Cette invitation n'existe pas sur ce serveur.");
|
||||
}
|
||||
if (error?.code !== MISSING_PERMISSIONS) {
|
||||
throw error;
|
||||
}
|
||||
invite = await fetchPublicInvite(client, code, guild);
|
||||
warnings.push(
|
||||
"Le bot n'a pas la permission « Gérer le serveur » : impossible de vérifier que l'invitation est temporaire."
|
||||
);
|
||||
}
|
||||
|
||||
if (invite.temporary === false) {
|
||||
throw new InvitationError(
|
||||
"Cette invitation donne un accès permanent : crée-la avec l'option « Accorder une adhésion temporaire »."
|
||||
);
|
||||
}
|
||||
if (invite.maxUses) {
|
||||
warnings.push(`Utilisations limitées : ${invite.uses ?? 0}/${invite.maxUses}.`);
|
||||
}
|
||||
if (invite.expiresTimestamp) {
|
||||
warnings.push(`Elle expire le <t:${Math.floor(invite.expiresTimestamp / 1000)}:f>.`);
|
||||
}
|
||||
|
||||
return { link: `https://discord.gg/${invite.code}`, warnings };
|
||||
}
|
||||
|
||||
function buildInvitationMessage(link) {
|
||||
return (
|
||||
"Pour inviter quelqu'un, il faut utiliser cette invitation temporaire !\n" +
|
||||
codeBlock(link) +
|
||||
"*Pour une invitation permanente, il suffit d'attribuer le role*" +
|
||||
" ***Hangaround*** " +
|
||||
"*à la personne concernée.*\n\n" +
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
export { InvitationError, buildInvitationMessage, checkInvitation, parseInviteCode };
|
||||
|
|
@ -5,20 +5,44 @@ function tokenDigest(value) {
|
|||
return createHash("sha256").update(value).digest();
|
||||
}
|
||||
|
||||
function authMiddleware(req, res, next) {
|
||||
if (!config.webApiKey) {
|
||||
return next();
|
||||
}
|
||||
|
||||
function readBearerToken(req) {
|
||||
const header = req.headers.authorization || "";
|
||||
const match = /^Bearer ([^\s]+)$/.exec(header);
|
||||
const token = match?.[1] || "";
|
||||
|
||||
if (timingSafeEqual(tokenDigest(token), tokenDigest(config.webApiKey))) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(401).json({ error: "Unauthorized" });
|
||||
return match?.[1] || "";
|
||||
}
|
||||
|
||||
export { authMiddleware };
|
||||
// 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);
|
||||
|
||||
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, isLoopbackAddress, localOnly };
|
||||
|
|
|
|||
|
|
@ -4,7 +4,11 @@ import { rateLimit } from "express-rate-limit";
|
|||
import multer from "multer";
|
||||
import path from "path";
|
||||
import { config } from "../config.js";
|
||||
import { authMiddleware } from "./middlewares/auth.js";
|
||||
import {
|
||||
authMiddleware,
|
||||
createBearerAuth,
|
||||
localOnly,
|
||||
} from "./middlewares/auth.js";
|
||||
import { libraryRouter } from "./routes/library.js";
|
||||
import { notificationsRouter } from "./routes/notifications.js";
|
||||
import { playerRouter } from "./routes/player.js";
|
||||
|
|
@ -17,12 +21,33 @@ import {
|
|||
|
||||
const PUBLIC_DIR = path.join(process.cwd(), "public");
|
||||
|
||||
function startWebServer(dependencies) {
|
||||
ensureStorageLayout();
|
||||
cleanupTemporaryFiles();
|
||||
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" },
|
||||
});
|
||||
}
|
||||
|
||||
function createApp(
|
||||
dependencies,
|
||||
{ notificationsApiKey = config.notificationsApiKey } = {}
|
||||
) {
|
||||
const app = express();
|
||||
app.disable("x-powered-by");
|
||||
app.set("trust proxy", config.webTrustedProxies);
|
||||
app.use(helmet());
|
||||
app.use(express.json({ limit: "32kb" }));
|
||||
|
||||
|
|
@ -30,49 +55,29 @@ function startWebServer(dependencies) {
|
|||
res.json({ status: "ok" });
|
||||
});
|
||||
|
||||
// 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)
|
||||
);
|
||||
|
||||
const apiRouter = express.Router();
|
||||
apiRouter.use(
|
||||
rateLimit({
|
||||
windowMs: 60_000,
|
||||
limit: 120,
|
||||
standardHeaders: "draft-8",
|
||||
legacyHeaders: false,
|
||||
})
|
||||
);
|
||||
apiRouter.use(
|
||||
rateLimit({
|
||||
windowMs: 15 * 60_000,
|
||||
limit: 20,
|
||||
skipSuccessfulRequests: true,
|
||||
standardHeaders: "draft-8",
|
||||
legacyHeaders: false,
|
||||
message: { error: "Trop de tentatives d'authentification" },
|
||||
})
|
||||
);
|
||||
apiRouter.use(apiRateLimit({ windowMs: 60_000, limit: 120 }));
|
||||
apiRouter.use(authFailureLimit());
|
||||
apiRouter.use(authMiddleware);
|
||||
apiRouter.use(
|
||||
"/uploads",
|
||||
rateLimit({
|
||||
windowMs: 15 * 60_000,
|
||||
limit: 10,
|
||||
standardHeaders: "draft-8",
|
||||
legacyHeaders: false,
|
||||
}),
|
||||
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(
|
||||
"/notifications",
|
||||
rateLimit({
|
||||
windowMs: 60_000,
|
||||
limit: 60,
|
||||
standardHeaders: "draft-8",
|
||||
legacyHeaders: false,
|
||||
}),
|
||||
notificationsRouter(dependencies)
|
||||
);
|
||||
|
||||
app.use("/api", apiRouter);
|
||||
app.get(["/jukebox", "/jukebox/"], (_req, res) =>
|
||||
|
|
@ -93,6 +98,14 @@ function startWebServer(dependencies) {
|
|||
});
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
function startWebServer(dependencies) {
|
||||
ensureStorageLayout();
|
||||
cleanupTemporaryFiles();
|
||||
|
||||
const app = createApp(dependencies);
|
||||
const port = Number(process.env.PORT || config.webServerPort || 3000);
|
||||
|
||||
const server = app.listen(port, () => {
|
||||
|
|
@ -104,4 +117,4 @@ function startWebServer(dependencies) {
|
|||
return { app, server };
|
||||
}
|
||||
|
||||
export { startWebServer };
|
||||
export { createApp, startWebServer };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue