Add an authenticated route that sends Discord direct messages for trusted apps
Some checks failed
Deploy Palico Bot / deploy (push) Failing after 3s
Some checks failed
Deploy Palico Bot / deploy (push) Failing after 3s
- POST /api/notifications/dm takes a user id and a text, sends it as a direct message with no active mentions, and answers 204, 400, 404 or 422. - The send logic lives in src/features/directMessages.js with its own tests; the route gets its own per-minute rate limit behind the existing API key. - Sokko TCG uses it for its opt-in Expedition alerts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
20624a5c9c
commit
3655b1ad74
6 changed files with 183 additions and 56 deletions
|
|
@ -62,3 +62,11 @@ cp src/static/gameservers-list.example.json src/static/gameservers-list.json
|
|||
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`.
|
||||
|
||||
## Messages privés pour les applications
|
||||
|
||||
`POST /api/notifications/dm` (clé `WEB_API_KEY` en `Authorization: Bearer …`) envoie un message
|
||||
privé Discord : corps `{ "userId": "<identifiant Discord>", "content": "<texte, 2000 caractères au plus>" }`.
|
||||
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.
|
||||
|
|
|
|||
112
index.js
112
index.js
|
|
@ -1,65 +1,65 @@
|
|||
import { Client, Collection, GatewayIntentBits } from "discord.js";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { Client, Collection, GatewayIntentBits } from "discord.js";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { config } from "./src/config.js";
|
||||
import { MusicQueue } from "./src/music/queue.js";
|
||||
import { startWebServer } from "./src/web/server.js";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const client = new Client({
|
||||
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates],
|
||||
});
|
||||
|
||||
client.commands = new Collection();
|
||||
const foldersPath = path.join(__dirname, "src/commands");
|
||||
const commandFolders = fs.readdirSync(foldersPath);
|
||||
|
||||
for (const folder of commandFolders) {
|
||||
if (folder.indexOf("[disabled]") === -1 || config.environnement === "test") {
|
||||
const commandsPath = path.join(foldersPath, folder);
|
||||
const commandFiles = fs
|
||||
.readdirSync(commandsPath)
|
||||
.filter((file) => file.endsWith(".js"));
|
||||
for (const file of commandFiles) {
|
||||
const filePath = path.join(commandsPath, file);
|
||||
const commandFile = await import(filePath);
|
||||
if ("data" in commandFile.command && "execute" in commandFile.command) {
|
||||
client.commands.set(commandFile.command.data.name, commandFile);
|
||||
} else {
|
||||
console.log(
|
||||
`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const eventsPath = path.join(__dirname, "src/events");
|
||||
const eventFiles = fs
|
||||
.readdirSync(eventsPath)
|
||||
.filter((file) => file.endsWith(".js"));
|
||||
|
||||
for (const file of eventFiles) {
|
||||
const filePath = path.join(eventsPath, file);
|
||||
const eventFile = await import(filePath);
|
||||
if (eventFile.event.once) {
|
||||
client.once(eventFile.event.name, (...args) =>
|
||||
eventFile.event.execute(...args)
|
||||
);
|
||||
} else {
|
||||
client.on(eventFile.event.name, (...args) =>
|
||||
eventFile.event.execute(...args)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const client = new Client({
|
||||
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates],
|
||||
});
|
||||
|
||||
client.commands = new Collection();
|
||||
const foldersPath = path.join(__dirname, "src/commands");
|
||||
const commandFolders = fs.readdirSync(foldersPath);
|
||||
|
||||
for (const folder of commandFolders) {
|
||||
if (folder.indexOf("[disabled]") === -1 || config.environnement === "test") {
|
||||
const commandsPath = path.join(foldersPath, folder);
|
||||
const commandFiles = fs
|
||||
.readdirSync(commandsPath)
|
||||
.filter((file) => file.endsWith(".js"));
|
||||
for (const file of commandFiles) {
|
||||
const filePath = path.join(commandsPath, file);
|
||||
const commandFile = await import(filePath);
|
||||
if ("data" in commandFile.command && "execute" in commandFile.command) {
|
||||
client.commands.set(commandFile.command.data.name, commandFile);
|
||||
} else {
|
||||
console.log(
|
||||
`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const eventsPath = path.join(__dirname, "src/events");
|
||||
const eventFiles = fs
|
||||
.readdirSync(eventsPath)
|
||||
.filter((file) => file.endsWith(".js"));
|
||||
|
||||
for (const file of eventFiles) {
|
||||
const filePath = path.join(eventsPath, file);
|
||||
const eventFile = await import(filePath);
|
||||
if (eventFile.event.once) {
|
||||
client.once(eventFile.event.name, (...args) =>
|
||||
eventFile.event.execute(...args)
|
||||
);
|
||||
} else {
|
||||
client.on(eventFile.event.name, (...args) =>
|
||||
eventFile.event.execute(...args)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const musicQueue = new MusicQueue(client);
|
||||
await client.login(config.token);
|
||||
|
||||
const { server } = startWebServer({ queue: musicQueue });
|
||||
const { server } = startWebServer({ queue: musicQueue, client });
|
||||
|
||||
server.on("error", (error) => {
|
||||
console.error("HTTP server error", error);
|
||||
|
|
|
|||
39
src/features/directMessages.js
Normal file
39
src/features/directMessages.js
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
// Envoie un message privé Discord à la demande d'une application de confiance (Sokko TCG : alertes d'expédition).
|
||||
// Le texte est envoyé tel quel, sans aucune mention active.
|
||||
|
||||
const USER_ID_PATTERN = /^\d{17,20}$/;
|
||||
const MAX_CONTENT_LENGTH = 2000;
|
||||
// Codes de l'API Discord : utilisateur inconnu, messages privés impossibles (aucun serveur commun ou messages fermés).
|
||||
const UNKNOWN_USER = 10013;
|
||||
const CANNOT_SEND = 50007;
|
||||
|
||||
class DirectMessageError extends Error {
|
||||
constructor(status, code, message) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
async function sendDirectMessage(client, { userId, content } = {}) {
|
||||
if (typeof userId !== "string" || !USER_ID_PATTERN.test(userId)) {
|
||||
throw new DirectMessageError(400, "INVALID_USER", "Identifiant Discord invalide");
|
||||
}
|
||||
if (typeof content !== "string" || !content.trim() || content.length > MAX_CONTENT_LENGTH) {
|
||||
throw new DirectMessageError(400, "INVALID_CONTENT", `Message vide ou de plus de ${MAX_CONTENT_LENGTH} caractères`);
|
||||
}
|
||||
try {
|
||||
const user = await client.users.fetch(userId);
|
||||
await user.send({ content, allowedMentions: { parse: [] } });
|
||||
} catch (error) {
|
||||
if (error?.code === UNKNOWN_USER) {
|
||||
throw new DirectMessageError(404, "UNKNOWN_USER", "Utilisateur Discord introuvable");
|
||||
}
|
||||
if (error?.code === CANNOT_SEND) {
|
||||
throw new DirectMessageError(422, "DM_CLOSED", "Cet utilisateur n'accepte pas les messages privés du bot");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export { DirectMessageError, sendDirectMessage, MAX_CONTENT_LENGTH };
|
||||
23
src/web/routes/notifications.js
Normal file
23
src/web/routes/notifications.js
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { Router } from "express";
|
||||
import { DirectMessageError, sendDirectMessage } from "../../features/directMessages.js";
|
||||
|
||||
// Messages privés envoyés pour une application de confiance (clé d'API) : `{ userId, content }`.
|
||||
function notificationsRouter({ client }) {
|
||||
const router = Router();
|
||||
|
||||
router.post("/dm", async (req, res) => {
|
||||
try {
|
||||
await sendDirectMessage(client, req.body);
|
||||
res.status(204).end();
|
||||
} catch (error) {
|
||||
if (error instanceof DirectMessageError) {
|
||||
return res.status(error.status).json({ error: error.message, code: error.code });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
export { notificationsRouter };
|
||||
|
|
@ -6,6 +6,7 @@ import path from "path";
|
|||
import { config } from "../config.js";
|
||||
import { authMiddleware } from "./middlewares/auth.js";
|
||||
import { libraryRouter } from "./routes/library.js";
|
||||
import { notificationsRouter } from "./routes/notifications.js";
|
||||
import { playerRouter } from "./routes/player.js";
|
||||
import { queueRouter } from "./routes/queue.js";
|
||||
import { uploadsRouter } from "./routes/uploads.js";
|
||||
|
|
@ -62,6 +63,16 @@ function startWebServer(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) =>
|
||||
|
|
|
|||
46
test/directMessages.test.js
Normal file
46
test/directMessages.test.js
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { DirectMessageError, sendDirectMessage } from "../src/features/directMessages.js";
|
||||
|
||||
const USER_ID = "123456789012345678";
|
||||
|
||||
function fakeClient({ fetchError = null, sendError = null } = {}) {
|
||||
const sent = [];
|
||||
return {
|
||||
sent,
|
||||
users: {
|
||||
async fetch(userId) {
|
||||
if (fetchError) throw fetchError;
|
||||
return {
|
||||
id: userId,
|
||||
async send(message) {
|
||||
if (sendError) throw sendError;
|
||||
sent.push({ userId, ...message });
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("sendDirectMessage sends the text to the user without active mentions", async () => {
|
||||
const client = fakeClient();
|
||||
await sendDirectMessage(client, { userId: USER_ID, content: "Votre expédition est de retour !" });
|
||||
assert.deepEqual(client.sent, [
|
||||
{ userId: USER_ID, content: "Votre expédition est de retour !", allowedMentions: { parse: [] } },
|
||||
]);
|
||||
});
|
||||
|
||||
test("sendDirectMessage rejects invalid users and contents before calling Discord", async () => {
|
||||
const client = fakeClient();
|
||||
for (const body of [{ userId: "dev-admin", content: "x" }, { userId: USER_ID, content: " " }, { userId: USER_ID, content: "x".repeat(2001) }, undefined]) {
|
||||
await assert.rejects(sendDirectMessage(client, body), (error) => error instanceof DirectMessageError && error.status === 400);
|
||||
}
|
||||
assert.equal(client.sent.length, 0);
|
||||
});
|
||||
|
||||
test("sendDirectMessage maps unknown users and closed messages to client errors", async () => {
|
||||
await assert.rejects(sendDirectMessage(fakeClient({ fetchError: { code: 10013 } }), { userId: USER_ID, content: "x" }), (error) => error.status === 404 && error.code === "UNKNOWN_USER");
|
||||
await assert.rejects(sendDirectMessage(fakeClient({ sendError: { code: 50007 } }), { userId: USER_ID, content: "x" }), (error) => error.status === 422 && error.code === "DM_CLOSED");
|
||||
await assert.rejects(sendDirectMessage(fakeClient({ sendError: new Error("network") }), { userId: USER_ID, content: "x" }), /network/);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue