Headers: - Every JavaScript file (sources, front, scripts, tests) starts with a /** @file … */ header, in the three levels used by sokko-g: a short description for simple files; Utilisé par / Attention / @see for shared modules; a full header (context, entry points, callers, dependencies, pitfalls) for index.js, the music queue, the web server, the storage manager and the jukebox page script. - No @author, @version or @since: git already knows. - test/fileHeaders.test.js fails `npm run check` when a header is missing or a central file's header is incomplete. Stylesheet (no visual change, checked by comparing every element's computed styles in Chromium at 1280, 800 and 400 px, hover included): - Role header and section comments. - Transparent shades derive from the colour variables with color-mix() instead of copied rgba() values; new tokens for repeated values (text, text on accent, accent gradient, white veils, shadow). - Native nesting for buttons, the live indicator, upload rows and home cards; drop the unused .hero__visual--large and redundant rules. - Utility classes move to the end so they win over components. The library list's u-mt-1, which never applied (.list reset it), is removed to keep the layout as it was. Docs: CONTRIBUTING.md describes the language, header and stylesheet conventions; CLAUDE.md points to it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
207 lines
6.7 KiB
JavaScript
207 lines
6.7 KiB
JavaScript
/**
|
|
* @file Télécharge un fichier audio depuis un lien donné par un utilisateur, en refusant les adresses
|
|
* internes (même après une redirection) et les fichiers de plus de 150 Mo.
|
|
*
|
|
* Utilisé par : /play et l'ajout par lien de la page web (web/routes/uploads.js).
|
|
* Attention : l'adresse est vérifiée pendant la résolution DNS de la connexion elle-même
|
|
* (safeLookup), pas avant : un autre client HTTP devrait lui aussi passer par safeLookup, sinon la
|
|
* protection disparaît.
|
|
*/
|
|
|
|
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 };
|