palico-bot/test/webServer.test.js
Shinuwa 3795ee06cb Add file headers, tidy the stylesheet and document the conventions
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>
2026-12-01 21:05:59 +01:00

205 lines
6.9 KiB
JavaScript

/**
* @file Couvre l'application web : route des messages privés (clé, limite, connexions locales),
* /readyz 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" }),
};
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 events stream requires the jukebox key", async () => {
await withServer({}, async ({ base }) => {
assert.equal((await fetch(`${base}/api/events`)).status, 401);
});
});