palico-bot/src/media/downloadAudio.js
Shinuwa 39d2b6acfb Add tracks from a direct link and from Discord with /play, /skip, /queue
- Download direct audio links server side (web page and /play), refusing
  internal and special addresses at connection time and after every
  redirect, with size and time limits.
- /play takes an attachment, a direct link or a library track
  (autocomplete), and can keep the file in the library; /skip and /queue
  control and show the shared queue.
- Share one ingest path between uploads, links and Discord attachments.
- Answer 413 instead of 500 when the library is full.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:13:12 +01:00

197 lines
6.2 KiB
JavaScript

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