diff --git a/README.md b/README.md index 01844d1..6c78641 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,23 @@ Variables facultatives : - `INVITE_LINK` : lien publié par `/invitation` quand la commande ne reçoit pas de lien. +## Jukebox + +La page `/jukebox` et les commandes `/play`, `/skip` et `/queue` pilotent la même +file d'attente. + +- `/play fichier:` (pièce jointe), `/play lien:` (lien direct vers un fichier + audio) ou `/play morceau:` (bibliothèque, avec autocomplétion) ; l'option + `garder` ajoute le fichier à la bibliothèque. La page web accepte aussi un + lien direct. YouTube et Spotify ne sont pas pris en charge. +- Le serveur télécharge lui-même les liens et refuse les adresses internes + (réseau local, boucle locale…), y compris après une redirection. +- Chaque morceau passe par `ffmpeg`, qui normalise le volume (EBU R128) et + encode en Opus : Discord reçoit l'audio sans réencodage. + +Après l'ajout ou la modification d'une commande, relancer `npm run deploy` pour +les enregistrer auprès de Discord. + ## Invitations Les membres ne peuvent pas créer d'invitation : un seul lien, à adhésion diff --git a/index.js b/index.js index 3ee14a5..c05868d 100644 --- a/index.js +++ b/index.js @@ -57,6 +57,8 @@ for (const file of eventFiles) { } const musicQueue = new MusicQueue(client); +// Les commandes du jukebox (/play, /skip, /queue) y accèdent par interaction.client. +client.musicQueue = musicQueue; await client.login(config.token); const { server } = startWebServer({ queue: musicQueue, client }); diff --git a/src/commands/jukebox/play.js b/src/commands/jukebox/play.js new file mode 100644 index 0000000..aa45584 --- /dev/null +++ b/src/commands/jukebox/play.js @@ -0,0 +1,126 @@ +import { MessageFlags, SlashCommandBuilder, escapeMarkdown } from "discord.js"; +import { downloadAudio } from "../../media/downloadAudio.js"; +import { ingestAudioFile } from "../../music/ingest.js"; +import { trackLabel } from "../../features/formatTrack.js"; +import { + TEMP_DIR, + createQueueTrackFromLibrary, + findPermanentTrack, + getPermanentLibrary, +} from "../../web/storage/storageManager.js"; + +const MAX_ATTACHMENT_SIZE = 150 * 1024 * 1024; + +function positionMessage(queue, track) { + if (queue.currentTrack?.id === track.id) { + return "c'est parti ! 🎶"; + } + const index = queue.queue.findIndex((queued) => queued.id === track.id); + return index >= 0 ? `position ${index + 1} dans la file.` : "ajouté à la file."; +} + +const command = { + data: new SlashCommandBuilder() + .setName("play") + .setDescription("Ajoute un morceau à la file du jukebox") + .addAttachmentOption((option) => + option.setName("fichier").setDescription("Fichier audio à jouer") + ) + .addStringOption((option) => + option + .setName("lien") + .setDescription("Lien direct vers un fichier audio (pas YouTube ni Spotify)") + .setMaxLength(2000) + ) + .addStringOption((option) => + option + .setName("morceau") + .setDescription("Morceau de la bibliothèque") + .setAutocomplete(true) + ) + .addBooleanOption((option) => + option + .setName("garder") + .setDescription("Garder le fichier ou le lien dans la bibliothèque") + ), + + async autocomplete(interaction) { + const query = interaction.options.getFocused().toLowerCase(); + const choices = getPermanentLibrary() + .filter((entry) => + `${entry.title || ""} ${entry.originalName || ""}`.toLowerCase().includes(query) + ) + .slice(0, 25) + .map((entry) => ({ name: trackLabel(entry).slice(0, 100), value: entry.id })); + await interaction.respond(choices); + }, + + async execute(interaction) { + const queue = interaction.client.musicQueue; + const attachment = interaction.options.getAttachment("fichier"); + const link = interaction.options.getString("lien"); + const libraryId = interaction.options.getString("morceau"); + const keep = interaction.options.getBoolean("garder") ?? false; + const sources = [attachment, link, libraryId].filter(Boolean); + + if (sources.length !== 1) { + await interaction.reply({ + content: "Choisis une seule source : `fichier`, `lien` ou `morceau`.", + flags: MessageFlags.Ephemeral, + }); + return; + } + + const uploader = interaction.member?.displayName || interaction.user.username; + + if (libraryId) { + const entry = findPermanentTrack(libraryId); + if (!entry) { + await interaction.reply({ + content: "Morceau introuvable dans la bibliothèque.", + flags: MessageFlags.Ephemeral, + }); + return; + } + const track = queue.enqueue(createQueueTrackFromLibrary(entry, uploader)); + await interaction.reply( + `**${escapeMarkdown(trackLabel(track))}** : ${positionMessage(queue, track)}` + ); + return; + } + + if (attachment && attachment.size > MAX_ATTACHMENT_SIZE) { + await interaction.reply({ + content: "Fichier trop volumineux (150 Mo au plus).", + flags: MessageFlags.Ephemeral, + }); + return; + } + + await interaction.deferReply(); + try { + const file = await downloadAudio(attachment?.url ?? link, { destinationDir: TEMP_DIR }); + if (attachment?.name) { + file.originalname = attachment.name; + } + const track = await ingestAudioFile( + file, + { permanent: keep, enqueue: true, uploader }, + { queue } + ); + await interaction.editReply( + `**${escapeMarkdown(trackLabel(track))}** : ${positionMessage(queue, track)}` + ); + } catch (error) { + if (!error.status) throw error; + // Erreur attendue (lien invalide, fichier non audio…) : on l'explique sans la publier. + await interaction.deleteReply().catch(() => {}); + await interaction.followUp({ + content: `Impossible d'ajouter ce morceau : ${error.message}`, + flags: MessageFlags.Ephemeral, + }); + } + }, +}; + +export { command }; diff --git a/src/commands/jukebox/queue.js b/src/commands/jukebox/queue.js new file mode 100644 index 0000000..17f9511 --- /dev/null +++ b/src/commands/jukebox/queue.js @@ -0,0 +1,41 @@ +import { MessageFlags, SlashCommandBuilder, escapeMarkdown } from "discord.js"; +import { trackLabel } from "../../features/formatTrack.js"; + +const SHOWN_TRACKS = 10; + +function buildQueueMessage(queue) { + const lines = []; + lines.push( + queue.currentTrack + ? `🎶 En cours : **${escapeMarkdown(trackLabel(queue.currentTrack))}**` + : "🎶 Rien en cours de lecture." + ); + + if (queue.queue.length === 0) { + lines.push("La file est vide. Ajoute un morceau avec `/play`."); + } else { + lines.push("", "__À suivre__ :"); + queue.queue.slice(0, SHOWN_TRACKS).forEach((track, index) => { + lines.push(`${index + 1}. ${escapeMarkdown(trackLabel(track))}`); + }); + const hidden = queue.queue.length - SHOWN_TRACKS; + if (hidden > 0) { + lines.push(`… et ${hidden} autre(s).`); + } + } + return lines.join("\n"); +} + +const command = { + data: new SlashCommandBuilder() + .setName("queue") + .setDescription("Affiche la file d'attente du jukebox"), + async execute(interaction) { + await interaction.reply({ + content: buildQueueMessage(interaction.client.musicQueue), + flags: MessageFlags.Ephemeral, + }); + }, +}; + +export { buildQueueMessage, command }; diff --git a/src/commands/jukebox/skip.js b/src/commands/jukebox/skip.js new file mode 100644 index 0000000..9d088c2 --- /dev/null +++ b/src/commands/jukebox/skip.js @@ -0,0 +1,24 @@ +import { MessageFlags, SlashCommandBuilder, escapeMarkdown } from "discord.js"; +import { trackLabel } from "../../features/formatTrack.js"; + +const command = { + data: new SlashCommandBuilder() + .setName("skip") + .setDescription("Passe au morceau suivant du jukebox"), + async execute(interaction) { + const queue = interaction.client.musicQueue; + const current = queue.currentTrack; + if (!current) { + await interaction.reply({ + content: "Rien n'est en cours de lecture.", + flags: MessageFlags.Ephemeral, + }); + return; + } + + queue.skip(); + await interaction.reply(`⏭️ **${escapeMarkdown(trackLabel(current))}** passé.`); + }, +}; + +export { command }; diff --git a/src/commands/utility/listcommand.js b/src/commands/utility/listcommand.js index 6551b46..3d3460b 100644 --- a/src/commands/utility/listcommand.js +++ b/src/commands/utility/listcommand.js @@ -10,6 +10,11 @@ const command = { \`/deletemsgs\`: Supprime les 100 derniers messages non épinglés \`/invitation\`: Publie le message d'invitation temporaire (lien vérifié) + __Categorie Jukebox__ : + \`/play\`: Ajoute un morceau (fichier, lien direct ou morceau de la bibliothèque) + \`/skip\`: Passe au morceau suivant + \`/queue\`: Affiche la file d'attente + __Categorie Vocal__ : \`/muteall\`: Rends tout le monde muet \`/unmuteall\`: Rends la parole à tout le monde diff --git a/src/features/formatTrack.js b/src/features/formatTrack.js new file mode 100644 index 0000000..64ff866 --- /dev/null +++ b/src/features/formatTrack.js @@ -0,0 +1,17 @@ +// Durée lisible : 3:07, 1:05:09. +function formatDuration(seconds) { + if (!Number.isFinite(seconds) || seconds < 0) return null; + const total = Math.round(seconds); + const hours = Math.floor(total / 3600); + const minutes = Math.floor((total % 3600) / 60); + const secs = String(total % 60).padStart(2, "0"); + return hours > 0 ? `${hours}:${String(minutes).padStart(2, "0")}:${secs}` : `${minutes}:${secs}`; +} + +function trackLabel(track) { + const title = track.title || track.originalName || "Sans titre"; + const duration = formatDuration(track.duration); + return duration ? `${title} (${duration})` : title; +} + +export { formatDuration, trackLabel }; diff --git a/src/media/downloadAudio.js b/src/media/downloadAudio.js new file mode 100644 index 0000000..d96d30d --- /dev/null +++ b/src/media/downloadAudio.js @@ -0,0 +1,197 @@ +import dns from "node:dns"; +import fs from "node:fs"; +import http from "node:http"; +import https from "node:https"; +import net from "node:net"; +import path from "node:path"; +import { randomUUID } from "node:crypto"; +import { pipeline } from "node:stream/promises"; + +const MAX_DOWNLOAD_SIZE = 150 * 1024 * 1024; +const MAX_REDIRECTS = 5; +const SOCKET_TIMEOUT = 30_000; +const TOTAL_TIMEOUT = 5 * 60_000; + +// Adresses jamais contactées : le bot tourne sur un réseau qui héberge d'autres services, et +// l'URL vient d'un utilisateur (protection contre la falsification de requêtes côté serveur). +const blockedAddresses = new net.BlockList(); +for (const [network, prefix] of [ + ["0.0.0.0", 8], + ["10.0.0.0", 8], + ["100.64.0.0", 10], + ["127.0.0.0", 8], + ["169.254.0.0", 16], + ["172.16.0.0", 12], + ["192.0.0.0", 24], + ["192.168.0.0", 16], + ["198.18.0.0", 15], + ["224.0.0.0", 4], + ["240.0.0.0", 4], +]) { + blockedAddresses.addSubnet(network, prefix, "ipv4"); +} +for (const [network, prefix] of [ + ["::", 128], + ["::1", 128], + ["fc00::", 7], + ["fe80::", 10], + ["ff00::", 8], + ["64:ff9b::", 96], + ["2002::", 16], +]) { + blockedAddresses.addSubnet(network, prefix, "ipv6"); +} + +function downloadError(message, status = 400) { + const error = new Error(message); + error.status = status; + return error; +} + +function isBlockedAddress(address) { + const family = net.isIP(address); + if (family === 0) return true; + if (family === 6) { + // Adresse IPv4 écrite en IPv6 (::ffff:10.0.0.1) : on vérifie la partie IPv4. + const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address); + if (mapped) return blockedAddresses.check(mapped[1], "ipv4"); + return blockedAddresses.check(address, "ipv6"); + } + return blockedAddresses.check(address, "ipv4"); +} + +// Résolution DNS qui refuse les adresses internes. Elle est appelée par la connexion elle-même : +// l'adresse vérifiée est celle qu'on contacte (pas de changement entre vérification et usage). +function safeLookup(hostname, options, callback) { + dns.lookup(hostname, { ...options, all: true }, (error, addresses) => { + if (error) return callback(error); + const allowed = addresses.filter(({ address }) => !isBlockedAddress(address)); + if (allowed.length === 0) { + return callback(downloadError("Adresse non autorisée")); + } + if (options.all) return callback(null, allowed); + return callback(null, allowed[0].address, allowed[0].family); + }); +} + +function parseUrl(value) { + let url; + try { + url = new URL(value); + } catch { + throw downloadError("Lien invalide"); + } + if (url.protocol !== "https:" && url.protocol !== "http:") { + throw downloadError("Seuls les liens http et https sont acceptés"); + } + if (url.username || url.password) { + throw downloadError("Les liens avec identifiants ne sont pas acceptés"); + } + // Les adresses IP écrites en clair ne passent pas par la résolution DNS : on les vérifie ici. + const hostname = url.hostname.replace(/^\[|\]$/g, ""); + if (net.isIP(hostname) && isBlockedAddress(hostname)) { + throw downloadError("Adresse non autorisée"); + } + return url; +} + +function fileNameFrom(response, url) { + const disposition = response.headers["content-disposition"] || ""; + const encoded = /filename\*=UTF-8''([^;]+)/i.exec(disposition)?.[1]; + const plain = /filename="?([^";]+)"?/i.exec(disposition)?.[1]; + let name = encoded || plain || path.posix.basename(url.pathname); + try { + name = decodeURIComponent(name); + } catch { + // Nom laissé tel quel. + } + name = path.basename(name).replace(/[\u0000-\u001f]/g, "").trim().slice(0, 255); + return name || "audio"; +} + +function request(url, { signal, lookup }) { + const client = url.protocol === "https:" ? https : http; + return new Promise((resolve, reject) => { + const req = client.get( + url, + { + lookup, + signal, + timeout: SOCKET_TIMEOUT, + headers: { "user-agent": "palico-bot", accept: "audio/*, */*;q=0.5" }, + }, + resolve + ); + req.on("timeout", () => req.destroy(downloadError("Le serveur distant ne répond pas", 504))); + req.on("error", reject); + }); +} + +// Télécharge un fichier dans destinationDir et renvoie un objet de la même forme qu'un fichier +// reçu par multer ({ path, originalname, size, mimetype }). +async function downloadAudio( + value, + { destinationDir, maxSize = MAX_DOWNLOAD_SIZE, lookup = safeLookup } = {} +) { + let url = parseUrl(value); + const signal = AbortSignal.timeout(TOTAL_TIMEOUT); + + for (let redirects = 0; ; redirects++) { + let response; + try { + response = await request(url, { signal, lookup }); + } catch (error) { + if (error.status) throw error; + throw downloadError(`Téléchargement impossible : ${error.message}`, 502); + } + + const status = response.statusCode; + if (status >= 300 && status < 400 && response.headers.location) { + response.resume(); + if (redirects >= MAX_REDIRECTS) { + throw downloadError("Trop de redirections", 502); + } + url = parseUrl(new URL(response.headers.location, url).href); + continue; + } + + if (status !== 200) { + response.resume(); + throw downloadError(`Le serveur distant a répondu ${status}`, 502); + } + + const announced = Number(response.headers["content-length"]); + if (Number.isFinite(announced) && announced > maxSize) { + response.destroy(); + throw downloadError("Fichier trop volumineux (150 Mo au plus)", 413); + } + + const filePath = path.join(destinationDir, `download-${randomUUID()}`); + let size = 0; + response.on("data", (chunk) => { + size += chunk.length; + if (size > maxSize) { + response.destroy(downloadError("Fichier trop volumineux (150 Mo au plus)", 413)); + } + }); + + try { + await pipeline(response, fs.createWriteStream(filePath)); + } catch (error) { + fs.rmSync(filePath, { force: true }); + if (error.status) throw error; + throw downloadError(`Téléchargement interrompu : ${error.message}`, 502); + } + + return { + path: filePath, + originalname: fileNameFrom(response, url), + size, + mimetype: String(response.headers["content-type"] || "application/octet-stream") + .split(";")[0] + .trim(), + }; + } +} + +export { downloadAudio, isBlockedAddress, safeLookup }; diff --git a/src/music/ingest.js b/src/music/ingest.js new file mode 100644 index 0000000..3025d7b --- /dev/null +++ b/src/music/ingest.js @@ -0,0 +1,60 @@ +import { probeAudioFile } from "../media/validateAudioFile.js"; +import { + discardUploadedFile, + registerUploadedFile, +} from "../web/storage/storageManager.js"; + +function cleanText(value, maxLength) { + return String(value ?? "") + .replace(/[\u0000-\u001f]/g, "") + .trim() + .slice(0, maxLength); +} + +// Titre par défaut : « Artiste - Titre » d'après les tags, sinon le nom du fichier sans +// son extension. +function defaultTitle({ title, artist }, originalName) { + if (title) { + return (artist ? `${artist} - ${title}` : title).slice(0, 200); + } + return originalName.replace(/\.[a-z0-9]{1,10}$/i, "").slice(0, 200) || originalName; +} + +// Ajoute un fichier déjà présent dans storage/temp (upload, lien, pièce jointe Discord) : +// vérifie que c'est de l'audio, l'enregistre (bibliothèque si permanent) et le met en file. +// En cas d'échec, le fichier est supprimé. +async function ingestAudioFile( + file, + { permanent = false, enqueue = true, uploader, title } = {}, + { queue, probe = probeAudioFile } +) { + try { + if (!permanent && !enqueue) { + const error = new Error("Un fichier temporaire doit être ajouté à la file d'attente"); + error.status = 400; + throw error; + } + + const metadata = await probe(file.path); + const track = registerUploadedFile(file, { + permanent, + uploader: cleanText(uploader, 80) || "inconnu", + title: cleanText(title, 200) || defaultTitle(metadata, file.originalname), + duration: metadata.duration, + artist: metadata.artist, + }); + + if (permanent) { + queue.emit("libraryUpdate"); + } + if (enqueue) { + queue.enqueue(track); + } + return track; + } catch (error) { + discardUploadedFile(file); + throw error; + } +} + +export { defaultTitle, ingestAudioFile }; diff --git a/src/web/routes/uploads.js b/src/web/routes/uploads.js index 7366602..510f005 100644 --- a/src/web/routes/uploads.js +++ b/src/web/routes/uploads.js @@ -1,12 +1,9 @@ import { Router } from "express"; import multer from "multer"; -import { probeAudioFile } from "../../media/validateAudioFile.js"; +import { downloadAudio } from "../../media/downloadAudio.js"; +import { ingestAudioFile } from "../../music/ingest.js"; import { serializeTrack } from "../serializers.js"; -import { - TEMP_DIR, - discardUploadedFile, - registerUploadedFile, -} from "../storage/storageManager.js"; +import { TEMP_DIR } from "../storage/storageManager.js"; // Pas de filtre sur le type MIME : il vient du navigateur et varie selon le système (un MP3 // peut arriver en « audio/mp3 », un FLAC sans type). Les fichiers refusés disparaissaient sans @@ -29,65 +26,47 @@ const upload = multer({ }, }); -// Titre par défaut : « Artiste - Titre » d'après les tags, sinon le nom du fichier sans -// son extension. -function defaultTitle({ title, artist }, originalName) { - if (title) { - return (artist ? `${artist} - ${title}` : title).slice(0, 200); - } - return originalName.replace(/\.[a-z0-9]{1,10}$/i, "").slice(0, 200) || originalName; -} - function uploadsRouter({ queue }) { const router = Router(); + const options = (body) => ({ + permanent: body?.permanent === "true" || body?.permanent === true, + enqueue: body?.enqueue !== "false" && body?.enqueue !== false, + uploader: body?.uploader || "web-ui", + title: body?.notes, + }); + router.post("/", upload.single("file"), async (req, res, next) => { if (!req.file) { return res.status(400).json({ error: "Aucun fichier reçu" }); } - const permanent = req.body?.permanent === "true"; - const enqueue = req.body?.enqueue !== "false"; - const uploader = String(req.body?.uploader || "web-ui") - .replace(/[\u0000-\u001f]/g, "") - .trim() - .slice(0, 80); - const customTitle = String(req.body?.notes || "") - .replace(/[\u0000-\u001f]/g, "") - .trim() - .slice(0, 200); - try { - if (!permanent && !enqueue) { - const error = new Error( - "Un fichier temporaire doit être ajouté à la file d'attente" - ); - error.status = 400; - throw error; - } - - const metadata = await probeAudioFile(req.file.path); - const track = registerUploadedFile(req.file, { - permanent, - uploader, - title: customTitle || defaultTitle(metadata, req.file.originalname), - duration: metadata.duration, - artist: metadata.artist, - }); - if (permanent) { - queue.emit("libraryUpdate"); - } - - if (enqueue) { - queue.enqueue(track); - } - + const track = await ingestAudioFile(req.file, options(req.body), { queue }); return res.status(201).json({ track: serializeTrack(track), - enqueued: enqueue, + enqueued: options(req.body).enqueue, + }); + } catch (error) { + return next(error); + } + }); + + // Ajout depuis un lien direct vers un fichier audio : le serveur le télécharge lui-même. + router.post("/url", async (req, res, next) => { + const url = req.body?.url; + if (typeof url !== "string" || url.length > 2_000) { + return res.status(400).json({ error: "Lien manquant" }); + } + + try { + const file = await downloadAudio(url, { destinationDir: TEMP_DIR }); + const track = await ingestAudioFile(file, options(req.body), { queue }); + return res.status(201).json({ + track: serializeTrack(track), + enqueued: options(req.body).enqueue, }); } catch (error) { - discardUploadedFile(req.file); return next(error); } }); diff --git a/src/web/storage/storageManager.js b/src/web/storage/storageManager.js index 7bfbcd6..f814037 100644 --- a/src/web/storage/storageManager.js +++ b/src/web/storage/storageManager.js @@ -108,7 +108,9 @@ function registerUploadedFile( 0 ); if (librarySize + file.size > MAX_LIBRARY_SIZE) { - throw new Error("La bibliothèque permanente a atteint sa limite de 2 Go"); + const error = new Error("La bibliothèque permanente a atteint sa limite de 2 Go"); + error.status = 413; + throw error; } const rawExtension = path.extname(file.originalname).toLowerCase(); diff --git a/test/commands.test.js b/test/commands.test.js index e19f76f..5c30d0e 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, 10); + assert.equal(modules.length, 13); for (const module of modules) { assert.doesNotThrow(() => module.command.data.toJSON()); assert.equal(typeof module.command.execute, "function"); @@ -57,3 +57,13 @@ test("administrative commands require Discord permissions", async () => { } } }); + +test("/queue lists the current track and what comes next", async () => { + const { buildQueueMessage } = await import("../src/commands/jukebox/queue.js"); + const message = buildQueueMessage({ + currentTrack: { title: "Thème *principal*", duration: 187 }, + queue: [{ title: "Suite", duration: 3909 }], + }); + assert.match(message, /En cours : \*\*Thème \\\*principal\\\* \(3:07\)\*\*/); + assert.match(message, /1\. Suite \(1:05:09\)/); +}); diff --git a/test/downloadAudio.test.js b/test/downloadAudio.test.js new file mode 100644 index 0000000..92f9eb4 --- /dev/null +++ b/test/downloadAudio.test.js @@ -0,0 +1,114 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import dns from "node:dns"; +import fs from "node:fs"; +import http from "node:http"; +import os from "node:os"; +import path from "node:path"; +import { downloadAudio, isBlockedAddress } from "../src/media/downloadAudio.js"; + +const directory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-download-")); +test.after(() => fs.rmSync(directory, { recursive: true, force: true })); + +// Le serveur de test écoute en local, adresse que le téléchargeur refuse : les tests qui +// doivent l'atteindre passent une résolution DNS sans filtre. +const allowLocal = (hostname, options, callback) => dns.lookup(hostname, options, callback); + +async function withServer(handler, run) { + const server = http.createServer(handler); + server.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", resolve)); + try { + await run(`http://localhost:${server.address().port}`); + } finally { + await new Promise((resolve) => server.close(resolve)); + } +} + +test("internal and special addresses are blocked", () => { + for (const address of ["127.0.0.1", "10.1.2.3", "192.168.0.100", "172.20.0.1", "169.254.169.254", "100.64.0.1", "::1", "fd00::1", "fe80::1", "::ffff:10.0.0.1"]) { + assert.equal(isBlockedAddress(address), true, address); + } + for (const address of ["1.1.1.1", "151.101.130.132", "2606:4700::1111"]) { + assert.equal(isBlockedAddress(address), false, address); + } +}); + +test("a direct link is downloaded with its file name", async () => { + await withServer( + (req, res) => { + res.writeHead(200, { + "content-type": "audio/mpeg", + "content-disposition": "attachment; filename=\"chanson.mp3\"", + }); + res.end("fake audio"); + }, + async (base) => { + const file = await downloadAudio(`${base}/download?id=1`, { + destinationDir: directory, + lookup: allowLocal, + }); + assert.equal(file.originalname, "chanson.mp3"); + assert.equal(file.mimetype, "audio/mpeg"); + assert.equal(file.size, 10); + assert.equal(fs.readFileSync(file.path, "utf8"), "fake audio"); + } + ); +}); + +test("local addresses are refused, written as an IP or behind a host name", async () => { + await assert.rejects(downloadAudio("http://127.0.0.1:1/a.mp3", { destinationDir: directory }), { + status: 400, + }); + await withServer( + (req, res) => res.end("secret"), + async (base) => { + await assert.rejects(downloadAudio(`${base}/a.mp3`, { destinationDir: directory }), { + message: /non autorisée/, + }); + } + ); +}); + +test("a redirect towards an internal address is refused", async () => { + await withServer( + (req, res) => { + res.writeHead(302, { location: "http://192.168.0.100/admin" }); + res.end(); + }, + async (base) => { + await assert.rejects( + downloadAudio(`${base}/a.mp3`, { destinationDir: directory, lookup: allowLocal }), + { message: /non autorisée/ } + ); + } + ); +}); + +test("files over the size limit are refused and removed", async () => { + await withServer( + (req, res) => { + res.writeHead(200); + res.write(Buffer.alloc(600)); + res.end(Buffer.alloc(600)); + }, + async (base) => { + const before = fs.readdirSync(directory).length; + await assert.rejects( + downloadAudio(`${base}/big.mp3`, { + destinationDir: directory, + lookup: allowLocal, + maxSize: 1000, + }), + { status: 413 } + ); + assert.equal(fs.readdirSync(directory).length, before); + } + ); +}); + +test("only http and https links are accepted", async () => { + await assert.rejects(downloadAudio("file:///etc/passwd", { destinationDir: directory }), { + status: 400, + }); +}); diff --git a/test/ingest.test.js b/test/ingest.test.js new file mode 100644 index 0000000..26ba4a0 --- /dev/null +++ b/test/ingest.test.js @@ -0,0 +1,67 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { EventEmitter } from "node:events"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +// storageManager.js fixe ses dossiers au chargement, d'après le répertoire de travail. +const originalDirectory = process.cwd(); +const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-ingest-")); +process.chdir(temporaryDirectory); +const storage = await import("../src/web/storage/storageManager.js"); +const { defaultTitle, ingestAudioFile } = await import("../src/music/ingest.js"); +storage.ensureStorageLayout(); +test.after(() => { + process.chdir(originalDirectory); + fs.rmSync(temporaryDirectory, { recursive: true, force: true }); +}); + +function fakeQueue() { + const queue = new EventEmitter(); + queue.enqueued = []; + queue.enqueue = (track) => queue.enqueued.push(track); + return queue; +} + +function tempFile(name) { + const filePath = path.join(storage.TEMP_DIR, `upload-${name}`); + fs.writeFileSync(filePath, "audio"); + return { path: filePath, originalname: name, size: 5, mimetype: "audio/mpeg" }; +} + +test("default titles come from the tags, else from the file name", () => { + assert.equal(defaultTitle({ title: "Song", artist: "Band" }, "x.mp3"), "Band - Song"); + assert.equal(defaultTitle({ title: "Song", artist: null }, "x.mp3"), "Song"); + assert.equal(defaultTitle({ title: null, artist: null }, "Mon morceau.flac"), "Mon morceau"); +}); + +test("an ingested file is queued with its metadata", async () => { + const queue = fakeQueue(); + let libraryUpdates = 0; + queue.on("libraryUpdate", () => libraryUpdates++); + + const track = await ingestAudioFile( + tempFile("a.mp3"), + { permanent: true, uploader: "Shinuwa\u0007" }, + { queue, probe: async () => ({ duration: 61, title: "Titre", artist: "Artiste" }) } + ); + + assert.equal(track.title, "Artiste - Titre"); + assert.equal(track.duration, 61); + assert.equal(track.uploader, "Shinuwa"); + assert.deepEqual(queue.enqueued, [track]); + assert.equal(libraryUpdates, 1); + assert.equal(storage.getPermanentLibrary()[0].duration, 61); +}); + +test("a file that is not audio is deleted", async () => { + const file = tempFile("b.mp3"); + const invalid = Object.assign(new Error("pas de l'audio"), { status: 400 }); + + await assert.rejects( + ingestAudioFile(file, {}, { queue: fakeQueue(), probe: async () => { throw invalid; } }), + invalid + ); + assert.equal(fs.existsSync(file.path), false); +});