From 6895d20459f4e800913a7efa58f022b106ab6ce2 Mon Sep 17 00:00:00 2001 From: Shinuwa Date: Sun, 29 Nov 2026 10:57:22 +0100 Subject: [PATCH] Fix deploy and lock down the DM route; add /invitation - 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 --- .env.example | 6 ++ .forgejo/workflows/deploy.yml | 11 ++- .gitignore | 3 +- README.md | 49 ++++++++++-- public/scripts/common.js | 4 +- public/scripts/jukebox.js | 26 ++++++- src/commands/utility/invitation.js | 70 +++++++++++++++++ src/commands/utility/listcommand.js | 1 + src/config.js | 17 ++++ src/features/invitation.js | 90 +++++++++++++++++++++ src/web/middlewares/auth.js | 50 ++++++++---- src/web/server.js | 91 ++++++++++++---------- storage/library.json | 32 -------- test/commands.test.js | 3 +- test/invitation.test.js | 84 ++++++++++++++++++++ test/webServer.test.js | 116 ++++++++++++++++++++++++++++ 16 files changed, 554 insertions(+), 99 deletions(-) create mode 100644 src/commands/utility/invitation.js create mode 100644 src/features/invitation.js delete mode 100644 storage/library.json create mode 100644 test/invitation.test.js create mode 100644 test/webServer.test.js diff --git a/.env.example b/.env.example index 1b7bc24..4db695b 100644 --- a/.env.example +++ b/.env.example @@ -8,3 +8,9 @@ DISCORD_TOKEN= VOICE_CHANNEL_ID= TEXT_CHANNEL_ID= GAME_SERVERS_MESSAGE_ID= +# Facultatif : proxys de confiance (adresse IP de Caddy en production), « loopback » par défaut. +WEB_TRUSTED_PROXIES= +# Facultatif : clé des applications de confiance (Sokko TCG) ; sans elle, pas de messages privés. +NOTIFICATIONS_API_KEY= +# Facultatif : lien d'invitation temporaire publié par /invitation sans option « lien ». +INVITE_LINK= diff --git a/.forgejo/workflows/deploy.yml b/.forgejo/workflows/deploy.yml index 053561b..8d9f98d 100644 --- a/.forgejo/workflows/deploy.yml +++ b/.forgejo/workflows/deploy.yml @@ -8,14 +8,21 @@ on: jobs: deploy: runs-on: docker + # Image fixée ici : celle du label « docker » (node:20-bullseye) n'est plus maintenue, + # et son miroir de sécurité renvoie 404 (échec du run 4). + container: + image: node:24-bookworm steps: - name: Deploy on WebApps env: DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }} run: | - apt-get update - apt-get install -y openssh-client + # L'image contient déjà le client SSH ; ne l'installer que s'il manque. + if ! command -v ssh >/dev/null; then + apt-get update + apt-get install -y --no-install-recommends openssh-client + fi mkdir -p ~/.ssh printf '%s\n' "$DEPLOY_SSH_KEY" > ~/.ssh/id_ed25519 diff --git a/.gitignore b/.gitignore index d9ecbe6..30118f3 100644 --- a/.gitignore +++ b/.gitignore @@ -10,8 +10,9 @@ coverage/ # Local configuration and test data src/static/gameservers-list.json -# Runtime storage +# Runtime storage (storage/library.json : ancien emplacement de la bibliothèque) storage/runtime/ +storage/library.json storage/permanent/* !storage/permanent/.gitkeep storage/temp/* diff --git a/README.md b/README.md index 3f7769d..65fd4ed 100644 --- a/README.md +++ b/README.md @@ -59,14 +59,47 @@ cp src/static/gameservers-list.example.json src/static/gameservers-list.json ## Déploiement -Un push sur `main` exécute les contrôles syntaxiques, les tests et l'audit npm -avant d'appeler `/usr/local/bin/deploy-palico-bot` sur le serveur. Le workflow -vérifie ensuite la route publique `/healthz`. +Un push sur `main` lance `.forgejo/workflows/deploy.yml`, qui se connecte en SSH +à la VM et exécute `/usr/local/bin/deploy-palico-bot` (mise à jour du dépôt, +dépendances, redémarrage du service `palico-bot`). Le workflow ne lance ni les +contrôles ni les tests : lancer `npm run check` avant de pousser. + +Variables facultatives : + +- `WEB_TRUSTED_PROXIES` : proxys dont l'en-tête `X-Forwarded-For` est accepté + (syntaxe « trust proxy » d'Express, `loopback` par défaut). En production, + l'adresse IP de Caddy. Ne jamais mettre `true` : le port du bot est joignable + sans passer par le proxy. +- `NOTIFICATIONS_API_KEY` : clé des applications de confiance (voir plus bas), + différente de `WEB_API_KEY`. +- `INVITE_LINK` : lien publié par `/invitation` quand la commande ne reçoit pas + de lien. + +## Invitations + +Les membres ne peuvent pas créer d'invitation : un seul lien, à adhésion +temporaire, est partagé dans un message du bot. Pour garder une personne, on lui +attribue le rôle Hangaround. + +`/invitation [lien]` (permission « Gérer le serveur ») publie ce message dans le +salon courant, avec le lien donné ou `INVITE_LINK`. Avant de publier, le bot +vérifie que l'invitation existe, mène à ce serveur et est temporaire ; il signale +une limite d'utilisations ou une date d'expiration. La vérification du caractère +temporaire demande que le bot ait lui-même la permission « Gérer le serveur ». +Épingler le nouveau message (`/deletemsgs` garde les messages épinglés) et +désépingler l'ancien. ## Messages privés pour les applications -`POST /api/notifications/dm` (clé `WEB_API_KEY` en `Authorization: Bearer …`) envoie un message -privé Discord : corps `{ "userId": "", "content": "" }`. -Réponses : `204` envoyé, `400` corps invalide, `404` utilisateur inconnu, `422` messages privés -impossibles (aucun serveur en commun avec le bot, ou messages privés fermés). Aucune mention n'est -active dans le texte. Sokko TCG s'en sert pour ses alertes d'expédition, que chaque joueur active. +`POST /api/notifications/dm` envoie un message privé Discord. La route n'accepte +que les connexions locales (pas celles relayées par Caddy) et la clé +`NOTIFICATIONS_API_KEY` en `Authorization: Bearer …` ; sans cette variable, elle +répond `503`. + +Corps : `{ "userId": "", "content": "" }`. +Réponses : `204` envoyé, `400` corps invalide, `401` mauvaise clé, `403` +connexion non locale, `404` utilisateur inconnu (`UNKNOWN_USER`), `422` messages +privés impossibles (`DM_CLOSED` : aucun serveur en commun avec le bot, ou messages +privés fermés), `429` trop de requêtes (60 par minute), `503` route désactivée. +Aucune mention n'est active dans le texte. Sokko TCG s'en sert pour ses alertes +d'expédition, que chaque joueur active. diff --git a/public/scripts/common.js b/public/scripts/common.js index f73a60d..bf328bb 100644 --- a/public/scripts/common.js +++ b/public/scripts/common.js @@ -110,7 +110,9 @@ export function createApiClient({ getApiKey, basePath = "" } = {}) { if (!response.ok) { const errorMessage = payload?.error || payload?.message || response.statusText; - throw new Error(errorMessage); + const error = new Error(errorMessage); + error.status = response.status; + throw error; } return payload; diff --git a/public/scripts/jukebox.js b/public/scripts/jukebox.js index ff3c8d8..51f0342 100644 --- a/public/scripts/jukebox.js +++ b/public/scripts/jukebox.js @@ -65,6 +65,12 @@ function refreshAll(options = {}) { } async function performRefresh({ silent = false } = {}) { + if (!state.apiKey) { + stopPolling(); + setStatus("Renseigne le mot de passe pour accéder au jukebox", "info", false); + return; + } + if (!silent) { clearStatus(); } @@ -85,6 +91,12 @@ async function performRefresh({ silent = false } = {}) { renderLibrary(); updatePauseResumeButton(); } catch (error) { + if (error.status === 401) { + // Inutile d'insister : chaque échec compte dans la limite anti-force brute du serveur. + stopPolling(); + setStatus("Mot de passe refusé, vérifie-le puis sauvegarde", "error", false); + return; + } setStatus(`Erreur: ${error.message}`, "error", false); } } @@ -253,10 +265,15 @@ async function handleLibraryAction(action, libraryId) { } function startPolling() { - clearInterval(pollIntervalId); + stopPolling(); pollIntervalId = setInterval(() => refreshAll({ silent: true }), 5000); } +function stopPolling() { + clearInterval(pollIntervalId); + pollIntervalId = null; +} + function bindEvents() { elements.settingsForm?.addEventListener("submit", (event) => { event.preventDefault(); @@ -266,6 +283,9 @@ function bindEvents() { setStoredDisplayName(state.displayName); setStatus("Paramètres sauvegardés", "success"); refreshAll({ silent: true }); + if (state.apiKey) { + startPolling(); + } }); elements.uploadForm?.addEventListener("submit", async (event) => { @@ -329,7 +349,9 @@ function initialize() { bindEvents(); updatePauseResumeButton(); refreshAll(); - startPolling(); + if (state.apiKey) { + startPolling(); + } } initialize(); diff --git a/src/commands/utility/invitation.js b/src/commands/utility/invitation.js new file mode 100644 index 0000000..c6162f8 --- /dev/null +++ b/src/commands/utility/invitation.js @@ -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 }; diff --git a/src/commands/utility/listcommand.js b/src/commands/utility/listcommand.js index fb0fc3d..ea192b3 100644 --- a/src/commands/utility/listcommand.js +++ b/src/commands/utility/listcommand.js @@ -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 diff --git a/src/config.js b/src/config.js index 4aa7883..0afe09d 100644 --- a/src/config.js +++ b/src/config.js @@ -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, diff --git a/src/features/invitation.js b/src/features/invitation.js new file mode 100644 index 0000000..189da93 --- /dev/null +++ b/src/features/invitation.js @@ -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 .`); + } + + 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 }; diff --git a/src/web/middlewares/auth.js b/src/web/middlewares/auth.js index 46bc954..f6ed74a 100644 --- a/src/web/middlewares/auth.js +++ b/src/web/middlewares/auth.js @@ -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 `. 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 }; diff --git a/src/web/server.js b/src/web/server.js index 69d3e54..e180f7d 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -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 }; diff --git a/storage/library.json b/storage/library.json deleted file mode 100644 index cf447c4..0000000 --- a/storage/library.json +++ /dev/null @@ -1,32 +0,0 @@ -[ - { - "id": "67e8cb3f-c079-4961-b9ff-4b3b16cd8dc5", - "originalName": "Monster Hunter Wilds [OST] - Credits Music (Wyverian Song).mp3", - "storedName": "7d39cc0e-3a29-43c4-b265-1eb15b9b52b9.mp3", - "path": "/home/shinuwa/projects/palico-bot/storage/permanent/7d39cc0e-3a29-43c4-b265-1eb15b9b52b9.mp3", - "size": 3813641, - "mimetype": "audio/mpeg", - "uploader": "Shinuwa", - "createdAt": "2025-11-18T16:48:46.726Z" - }, - { - "id": "2b461bf4-2917-4faa-ae39-1111b6c478f7", - "originalName": "Dark Hallway.mp3", - "storedName": "3f4c096b-e316-4614-86f7-3f223ad9e362.mp3", - "path": "/home/shinuwa/projects/palico-bot/storage/permanent/3f4c096b-e316-4614-86f7-3f223ad9e362.mp3", - "size": 3090274, - "mimetype": "audio/mpeg", - "uploader": "Shinuwa", - "createdAt": "2025-11-18T16:50:42.461Z" - }, - { - "id": "c96b0e12-df38-4967-aeca-96335a3cf2a2", - "originalName": "Nintendo - Christmas Mix.mp3", - "storedName": "3c790e19-35a2-4e04-9956-736cb34e010a.mp3", - "path": "/home/shinuwa/projects/palico-bot/storage/permanent/3c790e19-35a2-4e04-9956-736cb34e010a.mp3", - "size": 122621211, - "mimetype": "audio/mpeg", - "uploader": "Shinuwa", - "createdAt": "2025-11-18T20:50:10.029Z" - } -] \ No newline at end of file diff --git a/test/commands.test.js b/test/commands.test.js index 92a0184..e19f76f 100644 --- a/test/commands.test.js +++ b/test/commands.test.js @@ -31,7 +31,7 @@ async function loadCommands() { test("all Discord commands expose valid command data", async () => { const modules = await loadCommands(); - assert.equal(modules.length, 9); + assert.equal(modules.length, 10); for (const module of modules) { assert.doesNotThrow(() => module.command.data.toJSON()); assert.equal(typeof module.command.execute, "function"); @@ -42,6 +42,7 @@ test("administrative commands require Discord permissions", async () => { const modules = await loadCommands(); const protectedCommands = new Set([ "deletemsgs", + "invitation", "muteall", "unmuteall", "deafall", diff --git a/test/invitation.test.js b/test/invitation.test.js new file mode 100644 index 0000000..a7aed2d --- /dev/null +++ b/test/invitation.test.js @@ -0,0 +1,84 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { DiscordjsErrorCodes } from "discord.js"; +import { + InvitationError, + buildInvitationMessage, + checkInvitation, + parseInviteCode, +} from "../src/features/invitation.js"; + +const GUILD_ID = "111111111111111111"; + +function fakeGuild({ invite = null, fetchError = null } = {}) { + return { + id: GUILD_ID, + invites: { + async fetch() { + if (fetchError) throw fetchError; + if (!invite) throw Object.assign(new Error("not found"), { code: DiscordjsErrorCodes.InviteNotFound }); + return invite; + }, + }, + }; +} + +function fakeClient(publicInvite) { + return { + async fetchInvite() { + if (!publicInvite) throw Object.assign(new Error("Unknown Invite"), { code: 10006 }); + return publicInvite; + }, + }; +} + +test("parseInviteCode accepts invite links and bare codes only", () => { + for (const input of ["https://discord.gg/AbC-12", "discord.gg/AbC-12", "https://discord.com/invite/AbC-12", " AbC-12 "]) { + assert.equal(parseInviteCode(input), "AbC-12", input); + } + for (const input of ["https://evil.example/AbC-12", "https://discord.gg/", "a b", "", undefined]) { + assert.equal(parseInviteCode(input), null, String(input)); + } +}); + +test("a temporary invite without limits is published as is", async () => { + const guild = fakeGuild({ invite: { code: "AbC-12", temporary: true, maxUses: 0, expiresTimestamp: null } }); + assert.deepEqual(await checkInvitation(guild, fakeClient(), "discord.gg/AbC-12"), { + link: "https://discord.gg/AbC-12", + warnings: [], + }); +}); + +test("permanent and unknown invites are refused", async () => { + const permanent = fakeGuild({ invite: { code: "AbC-12", temporary: false } }); + await assert.rejects(checkInvitation(permanent, fakeClient(), "AbC-12"), InvitationError); + await assert.rejects(checkInvitation(fakeGuild(), fakeClient(), "AbC-12"), InvitationError); + await assert.rejects(checkInvitation(fakeGuild(), fakeClient(), "pas un lien"), InvitationError); +}); + +test("limited or expiring invites are published with warnings", async () => { + const guild = fakeGuild({ + invite: { code: "AbC-12", temporary: true, maxUses: 5, uses: 2, expiresTimestamp: 1_800_000_000_000 }, + }); + const { warnings } = await checkInvitation(guild, fakeClient(), "AbC-12"); + assert.equal(warnings.length, 2); +}); + +test("without Manage Server the bot checks only the guild", async () => { + const missingPermissions = Object.assign(new Error("Missing Permissions"), { code: 50013 }); + const guild = fakeGuild({ fetchError: missingPermissions }); + + const sameGuild = fakeClient({ code: "AbC-12", guild: { id: GUILD_ID }, temporary: null }); + const result = await checkInvitation(guild, sameGuild, "AbC-12"); + assert.equal(result.link, "https://discord.gg/AbC-12"); + assert.equal(result.warnings.length, 1); + + const otherGuild = fakeClient({ code: "AbC-12", guild: { id: "222222222222222222" }, temporary: null }); + await assert.rejects(checkInvitation(guild, otherGuild, "AbC-12"), InvitationError); +}); + +test("the invitation message shows the link and how to stay permanently", () => { + const message = buildInvitationMessage("https://discord.gg/AbC-12"); + assert.match(message, /```\nhttps:\/\/discord\.gg\/AbC-12\n```/); + assert.match(message, /Hangaround/); +}); diff --git a/test/webServer.test.js b/test/webServer.test.js new file mode 100644 index 0000000..da68460 --- /dev/null +++ b/test/webServer.test.js @@ -0,0 +1,116 @@ +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", + NOTIFICATIONS_API_KEY: "notifications-key", + DISCORD_APPLICATION_ID: "1", + 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 { isLoopbackAddress } = await import("../src/web/middlewares/auth.js"); + +const USER_ID = "123456789012345678"; +const CLOSED_USER_ID = "223456789012345678"; + +function fakeClient() { + const sent = []; + return { + sent, + users: { + async fetch(userId) { + return { + async send(message) { + if (userId === CLOSED_USER_ID) { + throw Object.assign(new Error("Cannot send messages to this user"), { code: 50007 }); + } + sent.push({ userId, ...message }); + }, + }; + }, + }, + }; +} + +const fakeQueue = { + snapshot: () => ({ current: null, upcoming: [], status: "idle" }), +}; + +async function withServer(options, run) { + const client = fakeClient(); + const app = createApp({ queue: fakeQueue, client }, options); + 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 { + await run({ base, client }); + } finally { + await new Promise((resolve) => server.close(resolve)); + } +} + +function sendDm(base, key, userId = USER_ID) { + return fetch(`${base}/api/notifications/dm`, { + method: "POST", + headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}` }, + body: JSON.stringify({ userId, content: "Votre expédition est de retour !" }), + }); +} + +test("the DM route accepts only the notifications key", async () => { + await withServer({}, async ({ base, client }) => { + assert.equal((await sendDm(base, "notifications-key")).status, 204); + assert.equal((await sendDm(base, "web-key")).status, 401); + assert.equal(client.sent.length, 1); + }); +}); + +test("refused DMs do not lock out an authenticated application", async () => { + await withServer({}, async ({ base, client }) => { + for (let index = 0; index < 25; index++) { + assert.equal((await sendDm(base, "notifications-key", CLOSED_USER_ID)).status, 422); + } + assert.equal((await sendDm(base, "notifications-key")).status, 204); + assert.equal(client.sent.length, 1); + }); +}); + +test("repeated wrong keys are still rate limited", async () => { + await withServer({}, async ({ base }) => { + for (let index = 0; index < 20; index++) { + const response = await fetch(`${base}/api/queue`, { + headers: { Authorization: "Bearer wrong-key" }, + }); + assert.equal(response.status, 401); + } + const blocked = await fetch(`${base}/api/queue`, { + headers: { Authorization: "Bearer web-key" }, + }); + assert.equal(blocked.status, 429); + }); +}); + +test("the DM route is disabled without a notifications key", async () => { + await withServer({ notificationsApiKey: null }, async ({ base, client }) => { + const response = await sendDm(base, "notifications-key"); + assert.equal(response.status, 503); + assert.equal(client.sent.length, 0); + }); +}); + +test("only loopback connections count as local", () => { + for (const address of ["127.0.0.1", "::1", "::ffff:127.0.0.1"]) { + assert.equal(isLoopbackAddress(address), true); + } + for (const address of ["192.168.0.104", "213.251.163.57", "::ffff:192.168.0.104", undefined]) { + assert.equal(isLoopbackAddress(address), false); + } +});