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 <[email protected]>
This commit is contained in:
SnipzilandClaude Opus 5.5 committed 2026-10-21 22:54:26 -04:00
1 parent 83c2fc3b0b
commit 3b53c8dab8
5 files changed
+278 -25

No files matched your search

+4 -2
View File
@@ -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;
+105 -14
View File
@@ -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};
+73 -8
View File
@@ -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});