Let guild members log in to the jukebox with Discord
- Optional Discord OAuth2 login (identify scope), enabled by DISCORD_CLIENT_SECRET, WEB_PUBLIC_URL and SESSION_SECRET; restricted to members of the configured guild, checked at login. - Stateless 30-day session in a signed HttpOnly SameSite=Lax cookie; the OAuth state is checked against its own short-lived cookie. - The jukebox API accepts the key or the session; with the session, changes must come from the site's own origin. The member's server name becomes the uploader name. - GET /auth/me tells the page whether the login is enabled and who is logged in. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9fb54798dd
commit
399e851178
11 changed files with 489 additions and 13 deletions
165
test/discordAuth.test.js
Normal file
165
test/discordAuth.test.js
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
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",
|
||||
DISCORD_APPLICATION_ID: "client-id",
|
||||
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 { createSessionToken, readSessionToken } = await import("../src/web/auth/session.js");
|
||||
|
||||
const SECRET = "s".repeat(40);
|
||||
const MEMBER_ID = "111111111111111111";
|
||||
const STRANGER_ID = "222222222222222222";
|
||||
|
||||
const oauth = {
|
||||
enabled: true,
|
||||
clientId: "client-id",
|
||||
clientSecret: "client-secret",
|
||||
publicUrl: "http://localhost",
|
||||
sessionSecret: SECRET,
|
||||
};
|
||||
|
||||
// Faux Discord : le code « member » identifie un membre du serveur, « stranger » un inconnu.
|
||||
function fakeDiscordFetch(calls) {
|
||||
return async (url, options = {}) => {
|
||||
calls.push({ url, options });
|
||||
if (url.endsWith("/oauth2/token")) {
|
||||
const code = options.body.get("code");
|
||||
return Response.json({ access_token: `token-${code}` });
|
||||
}
|
||||
if (url.endsWith("/users/@me")) {
|
||||
const token = options.headers.authorization;
|
||||
const id = token === "Bearer token-member" ? MEMBER_ID : STRANGER_ID;
|
||||
return Response.json({ id, username: "palico", global_name: "Palico" });
|
||||
}
|
||||
return new Response(null, { status: 404 });
|
||||
};
|
||||
}
|
||||
|
||||
const fakeQueue = {
|
||||
snapshot: () => ({ current: null, upcoming: [], status: "idle", loop: false, position: 0 }),
|
||||
};
|
||||
|
||||
async function withApp(run) {
|
||||
const calls = [];
|
||||
const app = createApp(
|
||||
{ queue: fakeQueue, client: {} },
|
||||
{
|
||||
oauth,
|
||||
fetchImpl: fakeDiscordFetch(calls),
|
||||
findMember: async (id) => (id === MEMBER_ID ? { displayName: "Chef Palico" } : null),
|
||||
}
|
||||
);
|
||||
const server = app.listen(0, "127.0.0.1");
|
||||
await new Promise((resolve) => server.once("listening", resolve));
|
||||
try {
|
||||
await run(`http://127.0.0.1:${server.address().port}`, calls);
|
||||
} finally {
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
}
|
||||
|
||||
function cookieValue(response, name) {
|
||||
const header = response.headers.getSetCookie().find((cookie) => cookie.startsWith(`${name}=`));
|
||||
return header ? decodeURIComponent(header.split(";")[0].slice(name.length + 1)) : null;
|
||||
}
|
||||
|
||||
async function login(base, code) {
|
||||
const start = await fetch(`${base}/auth/discord`, { redirect: "manual" });
|
||||
assert.equal(start.status, 303);
|
||||
const authorizeUrl = new URL(start.headers.get("location"));
|
||||
assert.equal(authorizeUrl.hostname, "discord.com");
|
||||
assert.equal(authorizeUrl.searchParams.get("scope"), "identify");
|
||||
const state = authorizeUrl.searchParams.get("state");
|
||||
const stateCookie = cookieValue(start, "palico_oauth_state");
|
||||
assert.equal(stateCookie, state);
|
||||
|
||||
return fetch(`${base}/auth/discord/callback?code=${code}&state=${state}`, {
|
||||
redirect: "manual",
|
||||
headers: { cookie: `palico_oauth_state=${stateCookie}` },
|
||||
});
|
||||
}
|
||||
|
||||
test("a guild member logs in with Discord and uses the jukebox API", async () => {
|
||||
await withApp(async (base) => {
|
||||
const callback = await login(base, "member");
|
||||
assert.equal(callback.status, 303);
|
||||
assert.equal(callback.headers.get("location"), "/jukebox/");
|
||||
const session = cookieValue(callback, "palico_session");
|
||||
assert.ok(session);
|
||||
|
||||
const me = await (await fetch(`${base}/auth/me`, { headers: { cookie: `palico_session=${session}` } })).json();
|
||||
assert.deepEqual(me, { oauthEnabled: true, user: { id: MEMBER_ID, name: "Chef Palico" } });
|
||||
|
||||
const queue = await fetch(`${base}/api/queue`, { headers: { cookie: `palico_session=${session}` } });
|
||||
assert.equal(queue.status, 200);
|
||||
});
|
||||
});
|
||||
|
||||
test("someone outside the guild is turned away", async () => {
|
||||
await withApp(async (base) => {
|
||||
const callback = await login(base, "stranger");
|
||||
assert.equal(callback.headers.get("location"), "/jukebox/?login=not-member");
|
||||
assert.equal(cookieValue(callback, "palico_session"), null);
|
||||
});
|
||||
});
|
||||
|
||||
test("a callback without the matching state is refused", async () => {
|
||||
await withApp(async (base, calls) => {
|
||||
const callback = await fetch(`${base}/auth/discord/callback?code=member&state=forged`, {
|
||||
redirect: "manual",
|
||||
headers: { cookie: "palico_oauth_state=other" },
|
||||
});
|
||||
assert.equal(callback.headers.get("location"), "/jukebox/?login=state");
|
||||
assert.equal(calls.length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
test("a cookie session cannot change anything from another site", async () => {
|
||||
await withApp(async (base) => {
|
||||
const session = createSessionToken({ id: MEMBER_ID, name: "Chef Palico" }, SECRET);
|
||||
const response = await fetch(`${base}/api/player/skip`, {
|
||||
method: "POST",
|
||||
headers: { cookie: `palico_session=${session}`, origin: "https://evil.example" },
|
||||
});
|
||||
assert.equal(response.status, 403);
|
||||
});
|
||||
});
|
||||
|
||||
test("tampered or expired session tokens are rejected", () => {
|
||||
const token = createSessionToken({ id: MEMBER_ID, name: "Chef" }, SECRET, 0);
|
||||
assert.equal(readSessionToken(token, SECRET, 1)?.id, MEMBER_ID);
|
||||
assert.equal(readSessionToken(token, "x".repeat(40), 1), null);
|
||||
const [payload, signature] = token.split(".");
|
||||
const forged = Buffer.from(JSON.stringify({ sub: STRANGER_ID, name: "x", exp: 9e15 })).toString("base64url");
|
||||
assert.equal(readSessionToken(`${forged}.${signature}`, SECRET, 1), null);
|
||||
assert.equal(readSessionToken(`${payload}.${signature}`, SECRET, 31 * 24 * 3600 * 1000), null);
|
||||
});
|
||||
|
||||
test("without OAuth the API still needs the key", async () => {
|
||||
const app = createApp({ queue: fakeQueue, client: {} });
|
||||
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 {
|
||||
const me = await (await fetch(`${base}/auth/me`)).json();
|
||||
assert.equal(me.oauthEnabled, false);
|
||||
assert.equal((await fetch(`${base}/api/queue`)).status, 401);
|
||||
assert.equal(
|
||||
(await fetch(`${base}/api/queue`, { headers: { authorization: "Bearer web-key" } })).status,
|
||||
200
|
||||
);
|
||||
} finally {
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue