Fix deploy and lock down the DM route; add /invitation
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:
Shinuwa 2026-11-29 10:57:22 +01:00
parent 3655b1ad74
commit 6895d20459
16 changed files with 554 additions and 99 deletions

View file

@ -8,3 +8,9 @@ DISCORD_TOKEN=
VOICE_CHANNEL_ID= VOICE_CHANNEL_ID=
TEXT_CHANNEL_ID= TEXT_CHANNEL_ID=
GAME_SERVERS_MESSAGE_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=

View file

@ -8,14 +8,21 @@ on:
jobs: jobs:
deploy: deploy:
runs-on: docker 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: steps:
- name: Deploy on WebApps - name: Deploy on WebApps
env: env:
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }} DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
run: | run: |
# 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 update
apt-get install -y openssh-client apt-get install -y --no-install-recommends openssh-client
fi
mkdir -p ~/.ssh mkdir -p ~/.ssh
printf '%s\n' "$DEPLOY_SSH_KEY" > ~/.ssh/id_ed25519 printf '%s\n' "$DEPLOY_SSH_KEY" > ~/.ssh/id_ed25519

3
.gitignore vendored
View file

@ -10,8 +10,9 @@ coverage/
# Local configuration and test data # Local configuration and test data
src/static/gameservers-list.json src/static/gameservers-list.json
# Runtime storage # Runtime storage (storage/library.json : ancien emplacement de la bibliothèque)
storage/runtime/ storage/runtime/
storage/library.json
storage/permanent/* storage/permanent/*
!storage/permanent/.gitkeep !storage/permanent/.gitkeep
storage/temp/* storage/temp/*

View file

@ -59,14 +59,47 @@ cp src/static/gameservers-list.example.json src/static/gameservers-list.json
## Déploiement ## Déploiement
Un push sur `main` exécute les contrôles syntaxiques, les tests et l'audit npm Un push sur `main` lance `.forgejo/workflows/deploy.yml`, qui se connecte en SSH
avant d'appeler `/usr/local/bin/deploy-palico-bot` sur le serveur. Le workflow à la VM et exécute `/usr/local/bin/deploy-palico-bot` (mise à jour du dépôt,
vérifie ensuite la route publique `/healthz`. 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 ## Messages privés pour les applications
`POST /api/notifications/dm` (clé `WEB_API_KEY` en `Authorization: Bearer …`) envoie un message `POST /api/notifications/dm` envoie un message privé Discord. La route n'accepte
privé Discord : corps `{ "userId": "<identifiant Discord>", "content": "<texte, 2000 caractères au plus>" }`. que les connexions locales (pas celles relayées par Caddy) et la clé
Réponses : `204` envoyé, `400` corps invalide, `404` utilisateur inconnu, `422` messages privés `NOTIFICATIONS_API_KEY` en `Authorization: Bearer …` ; sans cette variable, elle
impossibles (aucun serveur en commun avec le bot, ou messages privés fermés). Aucune mention n'est répond `503`.
active dans le texte. Sokko TCG s'en sert pour ses alertes d'expédition, que chaque joueur active.
Corps : `{ "userId": "<identifiant Discord>", "content": "<texte, 2000 caractères au plus>" }`.
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.

View file

@ -110,7 +110,9 @@ export function createApiClient({ getApiKey, basePath = "" } = {}) {
if (!response.ok) { if (!response.ok) {
const errorMessage = payload?.error || payload?.message || response.statusText; 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; return payload;

View file

@ -65,6 +65,12 @@ function refreshAll(options = {}) {
} }
async function performRefresh({ silent = false } = {}) { 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) { if (!silent) {
clearStatus(); clearStatus();
} }
@ -85,6 +91,12 @@ async function performRefresh({ silent = false } = {}) {
renderLibrary(); renderLibrary();
updatePauseResumeButton(); updatePauseResumeButton();
} catch (error) { } 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); setStatus(`Erreur: ${error.message}`, "error", false);
} }
} }
@ -253,10 +265,15 @@ async function handleLibraryAction(action, libraryId) {
} }
function startPolling() { function startPolling() {
clearInterval(pollIntervalId); stopPolling();
pollIntervalId = setInterval(() => refreshAll({ silent: true }), 5000); pollIntervalId = setInterval(() => refreshAll({ silent: true }), 5000);
} }
function stopPolling() {
clearInterval(pollIntervalId);
pollIntervalId = null;
}
function bindEvents() { function bindEvents() {
elements.settingsForm?.addEventListener("submit", (event) => { elements.settingsForm?.addEventListener("submit", (event) => {
event.preventDefault(); event.preventDefault();
@ -266,6 +283,9 @@ function bindEvents() {
setStoredDisplayName(state.displayName); setStoredDisplayName(state.displayName);
setStatus("Paramètres sauvegardés", "success"); setStatus("Paramètres sauvegardés", "success");
refreshAll({ silent: true }); refreshAll({ silent: true });
if (state.apiKey) {
startPolling();
}
}); });
elements.uploadForm?.addEventListener("submit", async (event) => { elements.uploadForm?.addEventListener("submit", async (event) => {
@ -329,7 +349,9 @@ function initialize() {
bindEvents(); bindEvents();
updatePauseResumeButton(); updatePauseResumeButton();
refreshAll(); refreshAll();
if (state.apiKey) {
startPolling(); startPolling();
} }
}
initialize(); initialize();

View 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 };

View file

@ -8,6 +8,7 @@ const command = {
let message = `Voila la liste des commandes que tu peux utiliser : let message = `Voila la liste des commandes que tu peux utiliser :
__Categorie Utililaires__ : __Categorie Utililaires__ :
\`/deletemsgs\`: Supprime les 100 derniers messages non épinglés \`/deletemsgs\`: Supprime les 100 derniers messages non épinglés
\`/invitation\`: Publie le message d'invitation temporaire (lien vérifié)
__Categorie Vocal__ : __Categorie Vocal__ :
\`/muteall\`: Rends tout le monde muet \`/muteall\`: Rends tout le monde muet

View file

@ -31,12 +31,29 @@ if (
throw new Error("WEB_SERVER_PORT doit être compris entre 1 et 65535"); 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({ const config = Object.freeze({
environnement: process.env.NODE_ENV, environnement: process.env.NODE_ENV,
discordGuildId: process.env.DISCORD_GUILD_ID, discordGuildId: process.env.DISCORD_GUILD_ID,
shinuwaUserId: process.env.SHINUWA_USER_ID, shinuwaUserId: process.env.SHINUWA_USER_ID,
webServerPort, webServerPort,
webApiKey: process.env.WEB_API_KEY, webApiKey: process.env.WEB_API_KEY,
webTrustedProxies,
notificationsApiKey,
inviteLink,
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,

View 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 };

View file

@ -5,20 +5,44 @@ function tokenDigest(value) {
return createHash("sha256").update(value).digest(); return createHash("sha256").update(value).digest();
} }
function authMiddleware(req, res, next) { function readBearerToken(req) {
if (!config.webApiKey) {
return next();
}
const header = req.headers.authorization || ""; const header = req.headers.authorization || "";
const match = /^Bearer ([^\s]+)$/.exec(header); const match = /^Bearer ([^\s]+)$/.exec(header);
const token = match?.[1] || ""; return match?.[1] || "";
}
if (timingSafeEqual(tokenDigest(token), tokenDigest(config.webApiKey))) { // 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 next();
} }
return res.status(401).json({ error: "Unauthorized" }); return res.status(401).json({ error: "Unauthorized" });
};
} }
export { authMiddleware }; 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 };

View file

@ -4,7 +4,11 @@ import { rateLimit } from "express-rate-limit";
import multer from "multer"; import multer from "multer";
import path from "path"; import path from "path";
import { config } from "../config.js"; 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 { libraryRouter } from "./routes/library.js";
import { notificationsRouter } from "./routes/notifications.js"; import { notificationsRouter } from "./routes/notifications.js";
import { playerRouter } from "./routes/player.js"; import { playerRouter } from "./routes/player.js";
@ -17,12 +21,33 @@ import {
const PUBLIC_DIR = path.join(process.cwd(), "public"); const PUBLIC_DIR = path.join(process.cwd(), "public");
function startWebServer(dependencies) { function apiRateLimit(options) {
ensureStorageLayout(); return rateLimit({
cleanupTemporaryFiles(); 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(); const app = express();
app.disable("x-powered-by"); app.disable("x-powered-by");
app.set("trust proxy", config.webTrustedProxies);
app.use(helmet()); app.use(helmet());
app.use(express.json({ limit: "32kb" })); app.use(express.json({ limit: "32kb" }));
@ -30,49 +55,29 @@ function startWebServer(dependencies) {
res.json({ status: "ok" }); 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(); const apiRouter = express.Router();
apiRouter.use( apiRouter.use(apiRateLimit({ windowMs: 60_000, limit: 120 }));
rateLimit({ apiRouter.use(authFailureLimit());
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(authMiddleware); apiRouter.use(authMiddleware);
apiRouter.use( apiRouter.use(
"/uploads", "/uploads",
rateLimit({ apiRateLimit({ windowMs: 15 * 60_000, limit: 10 }),
windowMs: 15 * 60_000,
limit: 10,
standardHeaders: "draft-8",
legacyHeaders: false,
}),
uploadsRouter(dependencies) uploadsRouter(dependencies)
); );
apiRouter.use("/queue", queueRouter(dependencies)); apiRouter.use("/queue", queueRouter(dependencies));
apiRouter.use("/library", libraryRouter(dependencies)); apiRouter.use("/library", libraryRouter(dependencies));
apiRouter.use("/player", playerRouter(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.use("/api", apiRouter);
app.get(["/jukebox", "/jukebox/"], (_req, res) => 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 port = Number(process.env.PORT || config.webServerPort || 3000);
const server = app.listen(port, () => { const server = app.listen(port, () => {
@ -104,4 +117,4 @@ function startWebServer(dependencies) {
return { app, server }; return { app, server };
} }
export { startWebServer }; export { createApp, startWebServer };

View file

@ -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"
}
]

View file

@ -31,7 +31,7 @@ async function loadCommands() {
test("all Discord commands expose valid command data", async () => { test("all Discord commands expose valid command data", async () => {
const modules = await loadCommands(); const modules = await loadCommands();
assert.equal(modules.length, 9); assert.equal(modules.length, 10);
for (const module of modules) { for (const module of modules) {
assert.doesNotThrow(() => module.command.data.toJSON()); assert.doesNotThrow(() => module.command.data.toJSON());
assert.equal(typeof module.command.execute, "function"); assert.equal(typeof module.command.execute, "function");
@ -42,6 +42,7 @@ test("administrative commands require Discord permissions", async () => {
const modules = await loadCommands(); const modules = await loadCommands();
const protectedCommands = new Set([ const protectedCommands = new Set([
"deletemsgs", "deletemsgs",
"invitation",
"muteall", "muteall",
"unmuteall", "unmuteall",
"deafall", "deafall",

84
test/invitation.test.js Normal file
View file

@ -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/);
});

116
test/webServer.test.js Normal file
View file

@ -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);
}
});