From 3b53c8dab88deb4355b8e747533bf95b8cff65a7 Mon Sep 17 00:00:00 2001 From: Snipzil Date: Wed, 21 Oct 2026 22:54:26 -0400 Subject: [PATCH] fix(staff): a Discord sign-in asks for the 2FA code, and the bot needs one too Since 7dee290 a Discord account linked to a staff member opened the moderator panel for 12 hours on Discord's word alone, with no password and no 2FA code, though the normal sign-in asks for both every time; and since b11ae1d the bot took /moderate and /burrow commands from that Discord account alone. The link outlives a new password and "sign out everywhere", so a taken-over Discord account was enough to act as the staff member. The admin dashboard's Discord sign-in (adminDashboardAccess) skipped its password the same way. - /mod/discord/callback and /admin/discord/callback no longer sign in: they keep a pending sign-in for 5 minutes (a Strict cookie) and the page asks for the linked account's 2FA code (POST .../api/discord/code). Five wrong codes and it must start again at Discord. The admin one also needs the account to have 2FA on and not be locked. - the bot's commands and buttons count only for a staff member with a panel session that took a code (modpanel.discordBot.commandActor): the password sign-in, or Discord and a code; not the game's token sign-in. A new password, signing out everywhere or 2FA turned off end those sessions (forget), and so the bot's use. Whose Discord it is still keeps linked staff out of /discord moderation, and lets them close tickets. Co-Authored-By: Claude Opus 5.5 --- lib/discordbot.js | 6 ++- lib/modpanel.js | 119 ++++++++++++++++++++++++++++++++++++++++------ lib/panel.js | 81 +++++++++++++++++++++++++++---- public/admin.html | 52 ++++++++++++++++++++ public/mod.html | 45 +++++++++++++++++- 5 files changed, 278 insertions(+), 25 deletions(-) diff --git a/lib/discordbot.js b/lib/discordbot.js index d82275e..bf48e81 100644 --- a/lib/discordbot.js +++ b/lib/discordbot.js @@ -322,7 +322,9 @@ const commandDefinitions = () => [ .addSubcommand(command => command.setName("close").setDescription("Close this support ticket")), ].map(command => command.toJSON()); -const actorFor = interaction => modpanel.discordBot.actor(interaction.user.id); +// a command or button counts for a staff member signed in to the panel with +// their 2FA code (modpanel.discordBot.commandActor): Discord alone is not them. +const actorFor = interaction => modpanel.discordBot.commandActor(interaction.user.id); const reportButton = report => new ActionRowBuilder().addComponents( new ButtonBuilder().setCustomId(`${REPORT_BUTTON_PREFIX}${report.id}:handled`).setLabel("Mark handled").setStyle(ButtonStyle.Success), @@ -543,7 +545,7 @@ const handleTicket = async interaction => { return; } const owner = ticketOwner(interaction.channel); - const staff = actorFor(interaction); + const staff = modpanel.discordBot.actor(interaction.user.id); if (!owner || (owner !== interaction.user.id && !staff)) { await interaction.editReply(failure("Only the ticket opener or linked Burrow staff can close this ticket.")); return; diff --git a/lib/modpanel.js b/lib/modpanel.js index 2bd8a51..3de64c2 100644 --- a/lib/modpanel.js +++ b/lib/modpanel.js @@ -30,6 +30,7 @@ const sfs = require("./sfs.js"); const support = require("./support.js"); const totp = require("./totp.js"); const world = require("./world.js"); +const {logText} = require("./logtext.js"); // the moderator panel at /mod: what a moderator needs to look after the // players, and no more. it is apart from the admin panel (lib/panel.js), @@ -66,7 +67,17 @@ const PROJECT_ROOT = path.resolve(__dirname, ".."); const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS); const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator -const sessions = new Map(); // SHA-256 of a session token -> {id: account id, expiry: ms} +// SHA-256 of a session token -> {id: account id, expiry: ms, code}. `code`: +// a 2FA code was given for it (the password sign-in, and Discord's with a +// code after it), which the Discord bot's commands need (discordCommandActor). +const sessions = new Map(); +// a Discord sign-in waiting for its 2FA code: SHA-256 of the token in its +// cookie -> {id, expiry, tries}. Discord says who it is; the code says it is +// still them, as the password sign-in asks. +const pendingDiscord = new Map(); +const PENDING_COOKIE = "ajc_mod_pending"; +const PENDING_MINUTES = 5; +const PENDING_TRIES = 5; const addressSearched = new Map(); // moderator's account id -> the address they last searched for const sha256 = text => crypto.createHash("sha256").update(text).digest("hex"); @@ -127,7 +138,12 @@ const cookieHeader = (token, maxAgeSeconds) => const discordCookie = (value, maxAgeSeconds) => `${DISCORD_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`; -const beginSession = (account, res, address, detail = "") => { +const pendingCookieHeader = (token, maxAgeSeconds) => + `${PENDING_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`; +const pendingToken = req => (new RegExp(`(?:^|;\\s*)${PENDING_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1] || null; + +// `extraCookies` go out with the session's own. +const beginSession = (account, res, address, detail = "", code = true, extraCookies = []) => { accounts.recordLogin(account, "mod", address); accounts.save(account); for (const [hash, session] of sessions) { @@ -136,8 +152,8 @@ const beginSession = (account, res, address, detail = "") => { } } const token = crypto.randomBytes(24).toString("hex"); - sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000}); - res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600)); + sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000, code}); + res.setHeader("Set-Cookie", [cookieHeader(token, SESSION_HOURS * 3600), ...extraCookies]); modlog.record(account.username, "signed in", "", detail); }; @@ -159,6 +175,11 @@ const forget = account => { sessions.delete(hash); } } + for (const [hash, pending] of pendingDiscord) { + if (pending.id === account.id) { + pendingDiscord.delete(hash); + } + } }; const playerRow = (account, playing) => { @@ -433,13 +454,22 @@ const handle = async (req, res, url, from, web) => { result.ok = false; result.error = "denied"; } + // Discord has said who this is; the panel opens once their 2FA code is + // given too (POST /mod/api/discord/code), so a Discord account alone, + // taken over or linked by someone else, opens nothing. + const cookies = [discordCookie("", 0)]; if (result.ok) { - beginSession(result.account, res, from.address, "through Discord"); - console.log(`[mod] ${result.account.username} signed in with Discord from ${from.address}`); + for (const [hash, pending] of pendingDiscord) { + if (pending.expiry < Date.now()) { + pendingDiscord.delete(hash); + } + } + const token = crypto.randomBytes(24).toString("hex"); + pendingDiscord.set(sha256(token), {id: result.account.id, expiry: Date.now() + PENDING_MINUTES * 60000, tries: 0}); + cookies.push(pendingCookieHeader(token, PENDING_MINUTES * 60)); } - const sessionCookie = res.getHeader("Set-Cookie"); - res.setHeader("Set-Cookie", sessionCookie ? [sessionCookie, discordCookie("", 0)] : discordCookie("", 0)); - res.writeHead(302, {Location: `/dashboard/staff?discord=${result.ok ? "ok" : result.error}`}); + res.setHeader("Set-Cookie", cookies); + res.writeHead(302, {Location: `/dashboard/staff?discord=${result.ok ? "code" : result.error}`}); res.end(); return; } @@ -503,12 +533,52 @@ const handle = async (req, res, url, from, web) => { } } const token = crypto.randomBytes(24).toString("hex"); - sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000}); + sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000, code: true}); res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600)); modlog.record(account.username, "signed in"); reply(200, {ok: true, username: account.username}); return; } + // the second half of a Discord sign-in (GET /mod/discord/callback): the + // account's 2FA code, from the browser Discord sent back here. a few + // wrong codes and the sign-in is gone; it must start again at Discord. + case "POST /mod/api/discord/code": { + if (!from.local && failuresByAddress.blocked(from.key)) { + reply(429, {error: "Too many attempts. Try later."}); + return; + } + const token = pendingToken(req); + const hash = token ? sha256(token) : null; + const pending = hash ? pendingDiscord.get(hash) : null; + const account = pending && pending.expiry > Date.now() ? accounts.byId(pending.id) : null; + if (!account || !mayModerate(account)) { + if (hash) { + pendingDiscord.delete(hash); + } + res.setHeader("Set-Cookie", pendingCookieHeader("", 0)); + reply(401, {error: "The Discord sign-in expired. Sign in with Discord again.", expired: true}); + return; + } + if (!totp.verify(account, String(body.code || ""))) { + failuresByAddress.record(from.key); + accounts.recordLogin(account, "mod", from.address, false); + accounts.save(account); + pending.tries++; + if (pending.tries >= PENDING_TRIES) { + pendingDiscord.delete(hash); + res.setHeader("Set-Cookie", pendingCookieHeader("", 0)); + reply(401, {error: "Too many wrong codes. Sign in with Discord again.", expired: true}); + return; + } + reply(401, {error: "Wrong code."}); + return; + } + pendingDiscord.delete(hash); + beginSession(account, res, from.address, "through Discord", true, [pendingCookieHeader("", 0)]); + console.log(`[mod] ${logText(account.username)} signed in with Discord and a code from ${logText(from.address)}`); + reply(200, {ok: true, username: account.username}); + return; + } // signed in through the game instead: a client the moderator is playing // in hands over the game's login token, so they need not type their // password and a code again. taken only for active staff with 2FA on @@ -547,7 +617,8 @@ const handle = async (req, res, url, from, web) => { } } const cookie = crypto.randomBytes(24).toString("hex"); - sessions.set(sha256(cookie), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000}); + // no code given here, so not one the Discord bot's commands count + sessions.set(sha256(cookie), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000, code: false}); res.setHeader("Set-Cookie", cookieHeader(cookie, SESSION_HOURS * 3600)); modlog.record(account.username, "signed in", "", "through the game"); reply(200, {ok: true, username: account.username}); @@ -1089,13 +1160,33 @@ const moderators = () => accounts.all().filter(account => roles.roleOf(account)) // linked to one Burrow account. From there these methods use the same role, // rank, permission and action checks as POST /mod/api/act, and log every // successful change under the staff member's normal Burrow username. +// whose Discord this is: the active staff member it is linked to, or null. +// it says who someone is (the bot leaves staff alone), not that they may act. const discordActor = discordId => { const account = accounts.all().find(candidate => candidate.discordId === String(discordId)); return mayModerate(account) ? account : null; }; +// who may use the bot's commands: the staff member above, while they are +// signed in to the panel with a code (a session above with `code`). a +// Discord account alone is not them, and a new password, signing out +// everywhere or 2FA turned off end those sessions (forget), and the bot's +// use with them. +const discordCommandActor = discordId => { + const account = discordActor(discordId); + if (!account) { + return null; + } + for (const session of sessions.values()) { + if (session.id === account.id && session.code && session.expiry > Date.now()) { + return account; + } + } + return null; +}; + const discordError = (actor, permission) => !actor - ? {error: "Link this Discord account to an active Burrow staff account first."} + ? {error: "Link this Discord account to your active Burrow staff account, then sign in to the staff dashboard with your 2FA code. Discord commands work while that sign-in lasts (12 hours)."} : !roles.can(actor, permission) ? {error: "Your Burrow role cannot do that."} : null; const discordStatus = actor => { @@ -1153,7 +1244,7 @@ const discordHandleReport = (actor, id) => { const discordAct = (actor, username, body) => { if (!actor) { - return {error: "Link this Discord account to an active Burrow staff account first."}; + return discordError(null); } const target = accounts.byName(String(username || "").trim()); if (!target) { @@ -1166,7 +1257,7 @@ const discordAct = (actor, username, body) => { return result; }; -const discordBot = {actor: discordActor, authorize: discordError, status: discordStatus, player: discordPlayer, reports: discordReports, +const discordBot = {actor: discordActor, commandActor: discordCommandActor, authorize: discordError, status: discordStatus, player: discordPlayer, reports: discordReports, staff: discordStaff, announce: discordAnnounce, handleReport: discordHandleReport, act: discordAct}; module.exports = {handle, forget, moderators, signedInAs, itemRoutes, reviewRoutes, discordBot}; diff --git a/lib/panel.js b/lib/panel.js index 0d2fd8d..18382f8 100644 --- a/lib/panel.js +++ b/lib/panel.js @@ -119,7 +119,22 @@ const cookieHeader = (token, maxAgeSeconds) => const discordCookie = (value, maxAgeSeconds) => `${DISCORD_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`; -const signIn = res => { +// a Discord sign-in waiting for the 2FA code of the account it is linked +// to: SHA-256 of the token in its cookie -> {id, expiry, tries}. Discord +// alone does not open this panel, as the password alone does not open the +// moderator panel. +const pendingDiscord = new Map(); +const PENDING_COOKIE = "ajc_admin_pending"; +const PENDING_MINUTES = 5; +const PENDING_TRIES = 5; +const pendingCookieHeader = (token, maxAgeSeconds) => + `${PENDING_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`; +const pendingToken = req => (new RegExp(`(?:^|;\\s*)${PENDING_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1] || null; +// may this account still sign in here with Discord? +const discordAdmin = account => Boolean(account && account.adminDashboardAccess && account.discordId && totp.isOn(account) && !account.locked); + +// `extraCookies` go out with the session's own. +const signIn = (res, extraCookies = []) => { for (const [hash, expiry] of sessions) { if (expiry < Date.now()) { sessions.delete(hash); @@ -127,7 +142,7 @@ const signIn = res => { } const token = crypto.randomBytes(24).toString("hex"); sessions.set(sha256(token), Date.now() + SESSION_HOURS * 3600000); - res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600)); + res.setHeader("Set-Cookie", [cookieHeader(token, SESSION_HOURS * 3600), ...extraCookies]); }; const signOut = (req, res) => { @@ -692,13 +707,25 @@ const handle = async (req, res, url, from, web) => { const nonce = (new RegExp(`(?:^|;\\s*)${DISCORD_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1]; const result = url.searchParams.get("error") ? {error: "cancelled"} : await discordLinks.finishAdmin(url.searchParams.get("state"), nonce, url.searchParams.get("code")); - if (result.ok) { - signIn(res); - console.log(`[admin] ${logText(result.account.username)} signed in with Discord from ${logText(from.address)}`); + // Discord has said who this is; the panel opens once that account's 2FA + // code is given too (POST /admin/api/discord/code). + if (result.ok && !discordAdmin(result.account)) { + result.ok = false; + result.error = totp.isOn(result.account) ? "denied" : "twostep"; } - const adminCookie = res.getHeader("Set-Cookie"); - res.setHeader("Set-Cookie", adminCookie ? [adminCookie, discordCookie("", 0)] : discordCookie("", 0)); - res.writeHead(302, {Location: `/dashboard/admin?discord=${result.ok ? "ok" : result.error}`}); + const cookies = [discordCookie("", 0)]; + if (result.ok) { + for (const [hash, pending] of pendingDiscord) { + if (pending.expiry < Date.now()) { + pendingDiscord.delete(hash); + } + } + const token = crypto.randomBytes(24).toString("hex"); + pendingDiscord.set(sha256(token), {id: result.account.id, expiry: Date.now() + PENDING_MINUTES * 60000, tries: 0}); + cookies.push(pendingCookieHeader(token, PENDING_MINUTES * 60)); + } + res.setHeader("Set-Cookie", cookies); + res.writeHead(302, {Location: `/dashboard/admin?discord=${result.ok ? "code" : result.error}`}); res.end(); return; } @@ -760,6 +787,44 @@ const handle = async (req, res, url, from, web) => { return; } + // the second half of a Discord sign-in: the linked account's 2FA code. + case "POST /admin/api/discord/code": { + if (tooManyFailures(from.key)) { + reply(429, {error: "Too many attempts. Try again in a few minutes."}); + return; + } + const token = pendingToken(req); + const hash = token ? sha256(token) : null; + const pending = hash ? pendingDiscord.get(hash) : null; + const account = pending && pending.expiry > Date.now() ? accounts.byId(pending.id) : null; + if (!discordAdmin(account)) { + if (hash) { + pendingDiscord.delete(hash); + } + res.setHeader("Set-Cookie", pendingCookieHeader("", 0)); + reply(401, {error: "The Discord sign-in expired. Sign in with Discord again.", expired: true}); + return; + } + if (!totp.verify(account, String(body.code || ""))) { + recordFailure(from.key); + console.log(`[admin] wrong 2FA code after Discord for ${logText(account.username)} from ${logText(from.address)}`); + pending.tries++; + if (pending.tries >= PENDING_TRIES) { + pendingDiscord.delete(hash); + res.setHeader("Set-Cookie", pendingCookieHeader("", 0)); + reply(401, {error: "Too many wrong codes. Sign in with Discord again.", expired: true}); + return; + } + reply(401, {error: "Wrong code."}); + return; + } + pendingDiscord.delete(hash); + signIn(res, [pendingCookieHeader("", 0)]); + console.log(`[admin] ${logText(account.username)} signed in with Discord and a code from ${logText(from.address)}`); + reply(200, {ok: true}); + return; + } + case "POST /admin/api/logout": signOut(req, res); reply(200, {ok: true}); diff --git a/public/admin.html b/public/admin.html index a2fcefb..4b511a3 100644 --- a/public/admin.html +++ b/public/admin.html @@ -392,6 +392,12 @@ +

@@ -1261,6 +1267,38 @@ location.href = "/dashboard/admin/discord/login"; }); + // after Discord: the linked account's 2FA code (POST discord/code) + const discordGate = (codeStep, message) => { + history.replaceState(null, "", location.pathname + location.hash); + showGate(message); + $("gate-form").hidden = codeStep; + $("discord-code-form").hidden = !codeStep; + if (codeStep) { + $("discord-sign-in").textContent = "Start again with Discord"; + $("discord-code").focus(); + } + }; + + $("discord-code-form").addEventListener("submit", async event => { + event.preventDefault(); + $("discord-code-button").disabled = true; + const result = await api("discord/code", {code: $("discord-code").value.trim()}); + $("discord-code-button").disabled = false; + $("discord-code").value = ""; + if (result.ok) { + $("discord-code-form").hidden = true; + $("gate-form").hidden = false; + state = {needsSetup: false, needsSetupCode: false, signedIn: true}; + showPanel(); + } + else if (result.data.expired) { + discordGate(false, result.data.error); + } + else { + setStatus($("gate-status"), result.data.error || "That did not work.", true); + } + }); + $("sign-out").addEventListener("click", async () => { await api("logout", {}); state.signedIn = false; @@ -3514,9 +3552,23 @@ showGate("The server did not answer."); return; } + const discordResult = new URLSearchParams(location.search).get("discord"); if (state.signedIn) { showPanel(); } + else if (discordResult === "code") { + discordGate(true, ""); + } + else if (discordResult) { + discordGate(false, { + denied: "That Discord account is not allowed to sign in here.", + twostep: "Turn on 2FA for the linked account first.", + expired: "The Discord sign-in request expired. Try again.", + cancelled: "Discord sign-in was cancelled.", + discord: "Discord could not confirm that sign-in. Try again.", + off: "Discord sign-in is not configured.", + }[discordResult] || ""); + } else { showGate(); } diff --git a/public/mod.html b/public/mod.html index f7a225a..45e96fb 100644 --- a/public/mod.html +++ b/public/mod.html @@ -454,6 +454,12 @@
+

@@ -3195,6 +3201,38 @@ location.href = "/dashboard/staff/discord/login"; }); + // after Discord: the 2FA code, which opens the panel (POST discord/code) + const showDiscordCode = message => { + showGate(message); + $("gate-form").hidden = true; + $("discord-code-form").hidden = false; + $("discord-sign-in").textContent = "Start again with Discord"; + $("discord-code").focus(); + }; + + $("discord-code-form").addEventListener("submit", async event => { + event.preventDefault(); + $("discord-code-button").disabled = true; + const result = await api("discord/code", {code: $("discord-code").value.trim()}); + $("discord-code-button").disabled = false; + $("discord-code").value = ""; + if (result.ok) { + history.replaceState(null, "", location.pathname + location.hash); + $("discord-code-form").hidden = true; + $("gate-form").hidden = false; + showPanel(result.data.username); + } + else if (result.data.expired) { + history.replaceState(null, "", location.pathname + location.hash); + $("discord-code-form").hidden = true; + $("gate-form").hidden = false; + showGate(said(result)); + } + else { + setStatus($("gate-status"), said(result), true); + } + }); + $("sign-out").addEventListener("click", async () => { await api("logout", {}); showGate(""); @@ -3215,7 +3253,12 @@ discord: "Discord could not confirm that sign-in. Try again.", off: "Discord sign-in is not configured.", }[discordResult] || ""; - showGate(result.status === 0 ? result.data.error : discordMessage); + if (discordResult === "code" && result.status !== 0) { + showDiscordCode(""); + } + else { + showGate(result.status === 0 ? result.data.error : discordMessage); + } } };