Let trusted apps add an embed and a link button to Discord direct messages
All checks were successful
Deploy Palico Bot / deploy (push) Successful in 7s

- POST /api/notifications/dm accepts optional embed (title, description, url, color, thumbnail, fields, footer, timestamp) and link fields; plain text stays required for phone notifications.
- Every value is checked against Discord's limits, and urls and thumbnails must use https; a refused embed answers 400 INVALID_EMBED.
- Sokko TCG uses it to show the destination, the result and the loot of its expedition alerts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-29 11:24:20 +01:00
parent 2471b5f6f7
commit 6ca17264e0
4 changed files with 131 additions and 5 deletions

View file

@ -96,7 +96,16 @@ que les connexions locales (pas celles relayées par Caddy) et la clé
`NOTIFICATIONS_API_KEY` en `Authorization: Bearer …` ; sans cette variable, elle `NOTIFICATIONS_API_KEY` en `Authorization: Bearer …` ; sans cette variable, elle
répond `503`. répond `503`.
Corps : `{ "userId": "<identifiant Discord>", "content": "<texte, 2000 caractères au plus>" }`. Corps : `{ "userId": "<identifiant Discord>", "content": "<texte, 2000 caractères au plus>" }`,
plus deux champs facultatifs :
- `embed` : `{ "title", "description"?, "url"?, "color"?, "thumbnail"?, "fields"?: [{ "name", "value", "inline"? }], "footer"?, "timestamp"? }`
(limites de Discord : titre 256 caractères, description 4096, 25 champs de 256/1024, pied 2048,
6000 au total ; adresse et vignette en `https` uniquement, couleur entière de `0` à `0xFFFFFF`) ;
- `link` : `{ "label", "url" }`, un bouton de lien sous le message (libellé de 80 caractères au plus,
adresse `https`).
Le texte reste obligatoire : c'est lui que montre la notification du téléphone.
Réponses : `204` envoyé, `400` corps invalide, `401` mauvaise clé, `403` Réponses : `204` envoyé, `400` corps invalide, `401` mauvaise clé, `403`
connexion non locale, `404` utilisateur inconnu (`UNKNOWN_USER`), `422` messages 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 impossibles (`DM_CLOSED` : aucun serveur en commun avec le bot, ou messages

View file

@ -1,8 +1,12 @@
// Envoie un message privé Discord à la demande d'une application de confiance (Sokko TCG : alertes d'expédition). // 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. // Le texte est envoyé tel quel, sans aucune mention active ; un embed et un bouton de lien peuvent l'accompagner.
import { ButtonStyle, ComponentType } from "discord.js";
const USER_ID_PATTERN = /^\d{17,20}$/; const USER_ID_PATTERN = /^\d{17,20}$/;
const MAX_CONTENT_LENGTH = 2000; const MAX_CONTENT_LENGTH = 2000;
// Limites des embeds Discord (titre, description, champs, pied, total des textes).
const EMBED_LIMITS = Object.freeze({ title: 256, description: 4096, fields: 25, fieldName: 256, fieldValue: 1024, footer: 2048, total: 6000 });
const MAX_LINK_LABEL = 80;
// Codes de l'API Discord : utilisateur inconnu, messages privés impossibles (aucun serveur commun ou messages fermés). // Codes de l'API Discord : utilisateur inconnu, messages privés impossibles (aucun serveur commun ou messages fermés).
const UNKNOWN_USER = 10013; const UNKNOWN_USER = 10013;
const CANNOT_SEND = 50007; const CANNOT_SEND = 50007;
@ -15,16 +19,82 @@ class DirectMessageError extends Error {
} }
} }
async function sendDirectMessage(client, { userId, content } = {}) { const invalid = (message) => new DirectMessageError(400, "INVALID_EMBED", message);
function isHttpsUrl(value) {
try {
return typeof value === "string" && value.length <= 2048 && new URL(value).protocol === "https:";
} catch {
return false;
}
}
function text(value, max, label, { required = false } = {}) {
if (value == null && !required) return undefined;
if (typeof value !== "string" || !value.trim() || value.length > max) throw invalid(`${label} vide ou de plus de ${max} caractères`);
return value;
}
// Embed accepté : titre obligatoire ; description, adresse, couleur, vignette, champs, pied et horodatage facultatifs.
function buildEmbed(embed) {
if (embed == null) return null;
if (typeof embed !== "object" || Array.isArray(embed)) throw invalid("Embed invalide");
const result = { title: text(embed.title, EMBED_LIMITS.title, "Titre", { required: true }) };
if (embed.description != null) result.description = text(embed.description, EMBED_LIMITS.description, "Description");
if (embed.url != null) {
if (!isHttpsUrl(embed.url)) throw invalid("Adresse de l'embed invalide : https uniquement");
result.url = embed.url;
}
if (embed.color != null) {
if (!Number.isInteger(embed.color) || embed.color < 0 || embed.color > 0xffffff) throw invalid("Couleur invalide");
result.color = embed.color;
}
if (embed.thumbnail != null) {
if (!isHttpsUrl(embed.thumbnail)) throw invalid("Vignette invalide : https uniquement");
result.thumbnail = { url: embed.thumbnail };
}
if (embed.fields != null) {
if (!Array.isArray(embed.fields) || embed.fields.length > EMBED_LIMITS.fields) throw invalid(`${EMBED_LIMITS.fields} champs au plus`);
result.fields = embed.fields.map((field) => ({
name: text(field?.name, EMBED_LIMITS.fieldName, "Nom de champ", { required: true }),
value: text(field?.value, EMBED_LIMITS.fieldValue, "Valeur de champ", { required: true }),
inline: field?.inline === true
}));
}
if (embed.footer != null) result.footer = { text: text(embed.footer, EMBED_LIMITS.footer, "Pied") };
if (embed.timestamp != null) {
const date = new Date(embed.timestamp);
if (Number.isNaN(date.getTime())) throw invalid("Horodatage invalide");
result.timestamp = date.toISOString();
}
const total = [result.title, result.description, result.footer?.text, ...(result.fields || []).flatMap((field) => [field.name, field.value])].filter(Boolean).join("").length;
if (total > EMBED_LIMITS.total) throw invalid(`Embed de plus de ${EMBED_LIMITS.total} caractères`);
return result;
}
// Bouton de lien sous le message : un libellé et une adresse https.
function buildLink(link) {
if (link == null) return null;
if (typeof link !== "object" || !isHttpsUrl(link.url)) throw invalid("Lien invalide : https uniquement");
const label = text(link.label, MAX_LINK_LABEL, "Libellé du lien", { required: true });
return { type: ComponentType.ActionRow, components: [{ type: ComponentType.Button, style: ButtonStyle.Link, label, url: link.url }] };
}
async function sendDirectMessage(client, { userId, content, embed = null, link = null } = {}) {
if (typeof userId !== "string" || !USER_ID_PATTERN.test(userId)) { if (typeof userId !== "string" || !USER_ID_PATTERN.test(userId)) {
throw new DirectMessageError(400, "INVALID_USER", "Identifiant Discord invalide"); throw new DirectMessageError(400, "INVALID_USER", "Identifiant Discord invalide");
} }
if (typeof content !== "string" || !content.trim() || content.length > MAX_CONTENT_LENGTH) { 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`); throw new DirectMessageError(400, "INVALID_CONTENT", `Message vide ou de plus de ${MAX_CONTENT_LENGTH} caractères`);
} }
const message = { content, allowedMentions: { parse: [] } };
const builtEmbed = buildEmbed(embed);
const row = buildLink(link);
if (builtEmbed) message.embeds = [builtEmbed];
if (row) message.components = [row];
try { try {
const user = await client.users.fetch(userId); const user = await client.users.fetch(userId);
await user.send({ content, allowedMentions: { parse: [] } }); await user.send(message);
} catch (error) { } catch (error) {
if (error?.code === UNKNOWN_USER) { if (error?.code === UNKNOWN_USER) {
throw new DirectMessageError(404, "UNKNOWN_USER", "Utilisateur Discord introuvable"); throw new DirectMessageError(404, "UNKNOWN_USER", "Utilisateur Discord introuvable");

View file

@ -9,7 +9,7 @@ function logDirectMessage(userId, status) {
console.log(`[${new Date().toLocaleString()}] DM ${target} → ${status}`); console.log(`[${new Date().toLocaleString()}] DM ${target} → ${status}`);
} }
// Messages privés envoyés pour une application de confiance (clé d'API) : `{ userId, content }`. // Messages privés envoyés pour une application de confiance (clé d'API) : `{ userId, content, embed?, link? }`.
function notificationsRouter({ client }) { function notificationsRouter({ client }) {
const router = Router(); const router = Router();

View file

@ -44,3 +44,50 @@ test("sendDirectMessage maps unknown users and closed messages to client errors"
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: { 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/); await assert.rejects(sendDirectMessage(fakeClient({ sendError: new Error("network") }), { userId: USER_ID, content: "x" }), /network/);
}); });
test("sendDirectMessage adds an embed and a link button when given", async () => {
const client = fakeClient();
await sendDirectMessage(client, {
userId: USER_ID,
content: "Votre expédition est de retour !",
embed: {
title: "Votre expédition est de retour !",
description: "Les Glaces de la Longue Nuit · ★★★ · 6 h",
url: "https://sokko.example/#/cards/expeditions/abc",
color: 0xf6c453,
thumbnail: "https://sokko.example/static/img/cards/x.webp",
fields: [{ name: "Butin", value: "+16 Éclats" }],
footer: "Sokko TCG",
timestamp: 1_800_000_000_000,
},
link: { label: "Voir l'expédition", url: "https://sokko.example/#/cards/expeditions/abc" },
});
const [message] = client.sent;
assert.equal(message.embeds[0].title, "Votre expédition est de retour !");
assert.deepEqual(message.embeds[0].thumbnail, { url: "https://sokko.example/static/img/cards/x.webp" });
assert.deepEqual(message.embeds[0].fields, [{ name: "Butin", value: "+16 Éclats", inline: false }]);
assert.deepEqual(message.embeds[0].footer, { text: "Sokko TCG" });
assert.equal(message.embeds[0].timestamp, new Date(1_800_000_000_000).toISOString());
assert.deepEqual(message.components, [{ type: 1, components: [{ type: 2, style: 5, label: "Voir l'expédition", url: "https://sokko.example/#/cards/expeditions/abc" }] }]);
assert.deepEqual(message.allowedMentions, { parse: [] });
});
test("sendDirectMessage refuses embeds and links that Discord would reject", async () => {
const client = fakeClient();
const send = (extra) => sendDirectMessage(client, { userId: USER_ID, content: "x", ...extra });
for (const extra of [
{ embed: { description: "sans titre" } },
{ embed: { title: "x".repeat(257) } },
{ embed: { title: "t", url: "http://sokko.example" } },
{ embed: { title: "t", thumbnail: "javascript:alert(1)" } },
{ embed: { title: "t", color: 0x1000000 } },
{ embed: { title: "t", fields: Array.from({ length: 26 }, () => ({ name: "n", value: "v" })) } },
{ embed: { title: "t", fields: [{ name: "n", value: "" }] } },
{ embed: { title: "t", description: "x".repeat(4096), fields: Array.from({ length: 2 }, () => ({ name: "n", value: "x".repeat(1024) })) } },
{ link: { label: "Voir", url: "ftp://sokko.example" } },
{ link: { url: "https://sokko.example" } },
]) {
await assert.rejects(send(extra), (error) => error instanceof DirectMessageError && error.status === 400 && error.code === "INVALID_EMBED");
}
assert.equal(client.sent.length, 0);
});