/** * @file Couvre l'application web : route des messages privés (clé, limite, connexions locales), * /readyz, ancienne adresse du jukebox, déplacement dans le morceau en cours et flux * d'événements. */ import test from "node:test"; import assert from "node:assert/strict"; Object.assign(process.env, { NODE_ENV: "test", DISCORD_GUILD_ID: "1", SHINUWA_USER_ID: "1", WEB_SERVER_PORT: "3000", WEB_API_KEY: "web-key", NOTIFICATIONS_API_KEY: "notifications-key", DISCORD_APPLICATION_ID: "1", DISCORD_TOKEN: "test-token", VOICE_CHANNEL_ID: "1", TEXT_CHANNEL_ID: "1", GAME_SERVERS_MESSAGE_ID: "1", }); const { createApp } = await import("../src/web/server.js"); const { isLoopbackAddress } = await import("../src/web/middlewares/auth.js"); const USER_ID = "123456789012345678"; const CLOSED_USER_ID = "223456789012345678"; function fakeClient() { const sent = []; return { sent, users: { async fetch(userId) { return { async send(message) { if (userId === CLOSED_USER_ID) { throw Object.assign(new Error("Cannot send messages to this user"), { code: 50007 }); } sent.push({ userId, ...message }); }, }; }, }, }; } const fakeQueue = { snapshot: () => ({ current: null, upcoming: [], status: "idle" }), // Aucun morceau en cours, sauf quand la position demandée vaut 42. seek: (seconds) => (seconds === 42 ? { position: 42_000 } : null), }; async function withServer(options, run) { const client = fakeClient(); const app = createApp({ queue: fakeQueue, client }, options); const server = app.listen(0, "127.0.0.1"); await new Promise((resolve) => server.once("listening", resolve)); const base = `http://127.0.0.1:${server.address().port}`; try { await run({ base, client }); } finally { await new Promise((resolve) => server.close(resolve)); } } function sendDm(base, key, userId = USER_ID) { return fetch(`${base}/api/notifications/dm`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}` }, body: JSON.stringify({ userId, content: "Votre expédition est de retour !" }), }); } test("the DM route accepts only the notifications key", async () => { await withServer({}, async ({ base, client }) => { assert.equal((await sendDm(base, "notifications-key")).status, 204); assert.equal((await sendDm(base, "web-key")).status, 401); assert.equal(client.sent.length, 1); }); }); test("refused DMs do not lock out an authenticated application", async () => { await withServer({}, async ({ base, client }) => { for (let index = 0; index < 25; index++) { assert.equal((await sendDm(base, "notifications-key", CLOSED_USER_ID)).status, 422); } assert.equal((await sendDm(base, "notifications-key")).status, 204); assert.equal(client.sent.length, 1); }); }); test("repeated wrong keys are still rate limited", async () => { await withServer({}, async ({ base }) => { for (let index = 0; index < 20; index++) { const response = await fetch(`${base}/api/queue`, { headers: { Authorization: "Bearer wrong-key" }, }); assert.equal(response.status, 401); } const blocked = await fetch(`${base}/api/queue`, { headers: { Authorization: "Bearer web-key" }, }); assert.equal(blocked.status, 429); }); }); test("the DM route is disabled without a notifications key", async () => { await withServer({ notificationsApiKey: null }, async ({ base, client }) => { const response = await sendDm(base, "notifications-key"); assert.equal(response.status, 503); assert.equal(client.sent.length, 0); }); }); test("only loopback connections count as local", () => { for (const address of ["127.0.0.1", "::1", "::ffff:127.0.0.1"]) { assert.equal(isLoopbackAddress(address), true); } for (const address of ["192.168.0.104", "213.251.163.57", "::ffff:192.168.0.104", undefined]) { assert.equal(isLoopbackAddress(address), false); } }); test("/readyz reports whether the bot is connected to Discord", async () => { const app = createApp({ queue: fakeQueue, client: { isReady: () => false } }); const server = app.listen(0, "127.0.0.1"); await new Promise((resolve) => server.once("listening", resolve)); const base = `http://127.0.0.1:${server.address().port}`; try { assert.equal((await fetch(`${base}/healthz`)).status, 200); assert.equal((await fetch(`${base}/readyz`)).status, 503); } finally { await new Promise((resolve) => server.close(resolve)); } }); test("the events stream sends the queue state, then every update", async () => { const { EventEmitter } = await import("node:events"); const queue = new EventEmitter(); let snapshot = { current: null, upcoming: [], status: "idle", loop: false, position: 0 }; queue.snapshot = () => snapshot; queue.setLoop = (enabled) => { snapshot = { ...snapshot, loop: enabled }; queue.emit("queueUpdate", snapshot); return snapshot; }; const app = createApp({ queue, client: fakeClient() }); const server = app.listen(0, "127.0.0.1"); await new Promise((resolve) => server.once("listening", resolve)); const base = `http://127.0.0.1:${server.address().port}`; const controller = new AbortController(); try { const response = await fetch(`${base}/api/events`, { headers: { authorization: "Bearer web-key" }, signal: controller.signal, }); assert.equal(response.status, 200); assert.match(response.headers.get("content-type"), /text\/event-stream/); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let received = ""; const readUntil = async (pattern) => { while (!pattern.test(received)) { const { value, done } = await reader.read(); if (done) break; received += value; } }; await readUntil(/event: queue\ndata: .*"loop":false/); const loopResponse = await fetch(`${base}/api/player/loop`, { method: "POST", headers: { authorization: "Bearer web-key", "content-type": "application/json" }, body: JSON.stringify({ enabled: true }), }); assert.equal(loopResponse.status, 200); await readUntil(/"loop":true/); assert.match(received, /"loop":true/); const invalid = await fetch(`${base}/api/player/loop`, { method: "POST", headers: { authorization: "Bearer web-key", "content-type": "application/json" }, body: JSON.stringify({ enabled: "yes" }), }); assert.equal(invalid.status, 400); // Le client se déconnecte : le serveur cesse d'écouter la file. assert.equal(queue.listenerCount("queueUpdate"), 1); controller.abort(); for (let attempt = 0; attempt < 50 && queue.listenerCount("queueUpdate") > 0; attempt++) { await new Promise((resolve) => setTimeout(resolve, 10)); } assert.equal(queue.listenerCount("queueUpdate"), 0); } finally { controller.abort(); server.closeAllConnections(); await new Promise((resolve) => server.close(resolve)); } }); test("the old jukebox address redirects to the home page", async () => { await withServer({}, async ({ base }) => { const get = (path) => fetch(`${base}${path}`, { redirect: "manual" }); const plain = await get("/jukebox/"); assert.equal(plain.status, 301); assert.equal(plain.headers.get("location"), "/"); assert.equal((await get("/jukebox?login=denied")).headers.get("location"), "/?login=denied"); const home = await get("/"); assert.equal(home.status, 200); assert.match(await home.text(), /Palico Jukebox<\/title>/); }); }); test("seeking needs a position in seconds and a track playing", async () => { await withServer({}, async ({ base }) => { const seek = (body) => fetch(`${base}/api/player/seek`, { method: "POST", headers: { authorization: "Bearer web-key", "content-type": "application/json" }, body: JSON.stringify(body), }); assert.equal((await seek({ position: 42 })).status, 200); assert.equal((await seek({ position: 10 })).status, 409); assert.equal((await seek({ position: "42" })).status, 400); assert.equal((await seek({ position: -1 })).status, 400); assert.equal((await seek({})).status, 400); }); }); test("the events stream requires the jukebox key", async () => { await withServer({}, async ({ base }) => { assert.equal((await fetch(`${base}/api/events`)).status, 401); }); });