feat(dashboard): unify secure staff administration

Provide a single /dashboard entry point for owner and staff tools, with Discord OAuth sign-in for approved owner accounts and active staff. Add owner-managed dashboard access grants, staff server health and update visibility, filtering, moderation improvements, item controls, and per-animal clothing restrictions.

Replace staff-triggered password and 2FA resets with email-verified account recovery. Persist validated recovery addresses, use short-lived hashed recovery tokens, expose recovery flows in registration and account pages, and keep mail delivery disabled until its webhook configuration is present.

Cover dashboard aliases, recovery restrictions, Discord access, monitoring, item locks, wear rules, and staff behavior with regression tests.
This commit is contained in:
Snipzil committed 2026-10-19 10:09:35 -04:00
1 parent 4997315239
commit 7dee29010a
27 files changed
+2303 -346

No files matched your search

+225 -9
View File
@@ -1,6 +1,7 @@
"use strict";
const crypto = require("crypto");
const {execFileSync} = require("child_process");
const fs = require("fs");
const path = require("path");
const accounts = require("./accounts.js");
@@ -15,6 +16,7 @@ const itemArt = require("./itemart.js");
const playerItems = require("./playeritems.js");
const defpacks = require("./defpacks.js");
const devices = require("./devices.js");
const discordLinks = require("./discord.js");
const limits = require("./limits.js");
const manage = require("./manage.js");
const masterpieces = require("./masterpieces.js");
@@ -24,6 +26,7 @@ const reports = require("./reports.js");
const roles = require("./roles.js");
const staff = require("./staff.js");
const stats = require("./stats.js");
const sfs = require("./sfs.js");
const support = require("./support.js");
const totp = require("./totp.js");
const world = require("./world.js");
@@ -50,11 +53,15 @@ const world = require("./world.js");
// moderator's name, for the admin panel.
const COOKIE = "ajc_mod";
const DISCORD_COOKIE = "ajc_mod_discord";
const SESSION_HOURS = 12;
const TEN_MINUTES_MS = 600000;
const MAX_BAN_HOURS = 24 * 365 * 10;
const MAX_MESSAGE_LENGTH = 200;
const MAX_RECENT_NOTES = 15;
const RECENT_PAINTINGS = 12;
const GIT_STATUS_CACHE_MS = 10000;
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
@@ -64,13 +71,75 @@ const addressSearched = new Map(); // moderator's account id -> the address they
const sha256 = text => crypto.createHash("sha256").update(text).digest("hex");
// This is read-only and intentionally never fetches, pulls or pushes. It
// gives staff a conspicuous reminder that the running checkout contains work
// which has not made it to its tracked remote yet.
let gitStatusCachedAt = 0;
let gitStatusCached = null;
const gitUpdateState = () => {
if (gitStatusCached && Date.now() - gitStatusCachedAt < GIT_STATUS_CACHE_MS) {
return gitStatusCached;
}
try {
const runGit = args => execFileSync("git", args, {cwd: PROJECT_ROOT, encoding: "utf8", timeout: 1500, maxBuffer: 128 * 1024}).trim();
const raw = runGit(["status", "--porcelain=v1", "-z"]);
const entries = raw ? raw.split("\0").filter(Boolean) : [];
const changed = [];
for (let index = 0; index < entries.length; index++) {
const entry = entries[index];
const status = entry.slice(0, 2);
changed.push({status: status.trim() || "?", path: entry.slice(3)});
// A rename/copy has another NUL-delimited source path. The destination
// is the useful file to show in the warning.
if (status[0] === "R" || status[0] === "C") {
index++;
}
}
let ahead = 0;
let behind = 0;
let remoteKnown = true;
try {
const [behindText, aheadText] = runGit(["rev-list", "--left-right", "--count", "@{upstream}...HEAD"]).split(/\s+/);
behind = Number(behindText) || 0;
ahead = Number(aheadText) || 0;
}
catch (_) {
remoteKnown = false;
}
gitStatusCached = {available: true, changed, ahead, behind, remoteKnown,
needsPublish: changed.length > 0 || ahead > 0};
}
catch (err) {
gitStatusCached = {available: false, changed: [], ahead: 0, behind: 0, remoteKnown: false,
needsPublish: false, error: "Git status could not be read."};
}
gitStatusCachedAt = Date.now();
return gitStatusCached;
};
const cookieToken = req => {
const match = new RegExp(`(?:^|;\\s*)${COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "");
return match ? match[1] : null;
};
const cookieHeader = (token, maxAgeSeconds) =>
`${COOKIE}=${token}; Path=/mod; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
`${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const discordCookie = (value, maxAgeSeconds) =>
`${DISCORD_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const beginSession = (account, res, address, detail = "") => {
accounts.recordLogin(account, "mod", address);
accounts.save(account);
for (const [hash, session] of sessions) {
if (session.expiry < Date.now()) {
sessions.delete(hash);
}
}
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));
modlog.record(account.username, "signed in", "", detail);
};
// may this account use the panel (still)?
const mayModerate = account => Boolean(account && roles.isActiveStaff(account, world.moderation.banRemaining(account) !== 0));
@@ -116,10 +185,18 @@ const playerRow = (account, playing) => {
const playing = () => new Map(world.players().map(player => [player.username, player.room || "(between rooms)"]));
// by name (lib/staff.js says in what order).
const findPlayers = query => {
// what the Players page's list can be narrowed to (lib/staff.js `keep`).
const ONLY = {
online: (account, online) => online.has(account.username),
banned: account => world.moderation.banRemaining(account) !== 0 || devices.bannedId(account) !== 0,
silenced: account => world.moderation.silenceRemaining(account) !== 0,
staff: account => Boolean(roles.roleOf(account)),
};
// by name (lib/staff.js says in what order), and `only` one of ONLY's.
const findPlayers = (query, only) => {
const online = playing();
const {found, total} = staff.findAccounts(query);
const {found, total} = staff.findAccounts(query, Object.hasOwn(ONLY, only) ? ONLY[only] : undefined);
return {players: found.map(account => playerRow(account, online)), total};
};
@@ -334,6 +411,38 @@ const handle = async (req, res, url, from, web) => {
web.send(res, 200, captcha.withScriptVersion(await stats.withView(await fs.promises.readFile(path.join(config.publicDir, "mod.html")))), "text/html; charset=utf-8");
return;
}
// The nonce cookie is Lax only for Discord's cross-site return. The normal
// staff-session cookie remains Strict and is issued after the callback.
if (route === "GET /mod/discord/login") {
if (!discordLinks.linking()) {
res.writeHead(302, {Location: "/dashboard/staff?discord=off"});
res.end();
return;
}
const {url: to, nonce} = discordLinks.startStaff();
res.setHeader("Set-Cookie", discordCookie(nonce, 600));
res.writeHead(302, {Location: to});
res.end();
return;
}
if (route === "GET /mod/discord/callback") {
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.finishStaff(url.searchParams.get("state"), nonce, url.searchParams.get("code"));
if (result.ok && !mayModerate(result.account)) {
result.ok = false;
result.error = "denied";
}
if (result.ok) {
beginSession(result.account, res, from.address, "through Discord");
console.log(`[mod] ${result.account.username} signed in with Discord from ${from.address}`);
}
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.end();
return;
}
if (req.method === "POST" && !limits.originAllowed(req)) {
reply(403, {error: "forbidden"});
return;
@@ -343,7 +452,7 @@ const handle = async (req, res, url, from, web) => {
switch (route) {
case "GET /mod/api/state": {
const mod = signedInAs(req);
reply(200, {signedIn: Boolean(mod), username: mod ? mod.username : ""});
reply(200, {signedIn: Boolean(mod), username: mod ? mod.username : "", discordLogin: discordLinks.linking()});
return;
}
// username, password and a code, all three every time.
@@ -400,6 +509,50 @@ const handle = async (req, res, url, from, web) => {
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
// (so the game's own sign-in took a code), who are in the game now, and
// asking from the address that game connected from: the token alone,
// copied elsewhere, opens nothing.
case "POST /mod/api/game-login": {
if (!from.local && failuresByAddress.blocked(from.key)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
const account = accounts.byToken(body.token);
const session = account ? world.findOnline(account.username) : null;
if (!account || !roles.roleOf(account)) {
failuresByAddress.record(from.key);
reply(401, {error: "Sign in with your password and code."});
return;
}
if (!totp.isOn(account)) {
reply(403, {error: "Turn on 2FA on your account page first."});
return;
}
if (!mayModerate(account)) {
reply(403, {error: "This account cannot sign in here now."});
return;
}
if (!session || limits.key(session.address) !== from.key) {
reply(401, {error: "Be in the game on this computer, or sign in with your password and code."});
return;
}
accounts.recordLogin(account, "mod", from.address);
accounts.save(account);
for (const [hash, kept] of sessions) {
if (kept.expiry < Date.now()) {
sessions.delete(hash);
}
}
const cookie = crypto.randomBytes(24).toString("hex");
sessions.set(sha256(cookie), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000});
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});
return;
}
case "POST /mod/api/logout": {
const token = cookieToken(req);
if (token) {
@@ -462,6 +615,22 @@ const handle = async (req, res, url, from, web) => {
reviewRoutes(route.replace(" /mod/api/", " "), body, reply, done, mod.username, "/mod/api/itemart");
return;
}
// This deliberately precedes the broad /items branch. Moderators may
// receive the narrow items.restrict permission without also being allowed
// to make, delete, lock or take items.
if (/^\/mod\/api\/items\/wear-rules\/?$/.test(url.pathname)) {
if (!roles.can(mod, "items.restrict")) {
reply(403, {error: "Your role does not allow that."});
return;
}
// Normalize the harmless trailing-slash spelling before dispatching it.
itemRoutes(`${req.method} items/wear-rules`, url, body, reply, done, {
username: mod.username,
artBase: "/mod/api/itemart",
mayTake: () => false,
});
return;
}
// custom items (lib/customitems.js), for whoever may make them.
if (url.pathname.startsWith("/mod/api/items")) {
if (!roles.can(mod, "items.create")) {
@@ -475,6 +644,32 @@ const handle = async (req, res, url, from, web) => {
});
return;
}
// Service health is intentionally separate from player data: every staff
// role may see it, including developers who have no player-view access.
if (route === "GET /mod/api/server") {
if (!roles.can(mod, "server.view")) {
reply(403, {error: "Your role does not allow that."});
return;
}
const memory = process.memoryUsage();
const players = world.players();
const rooms = new Set(players.map(player => player.room).filter(Boolean));
reply(200, {
uptimeSeconds: Math.floor(process.uptime()),
players: players.length,
rooms: rooms.size,
memory: {
rssMb: Math.round(memory.rss / 1048576),
heapUsedMb: Math.round(memory.heapUsed / 1048576),
heapTotalMb: Math.round(memory.heapTotal / 1048576),
},
sockets: sfs.health(),
update: gitUpdateState(),
now: Date.now(),
});
return;
}
// everything else shows players and what they did: not for a role that
// only makes things.
if (!roles.can(mod, "player.view")) {
@@ -488,6 +683,7 @@ const handle = async (req, res, url, from, web) => {
paintings: masterpieces.list(masterpieces.PENDING).length});
return;
// other accounts the same person may have, and their story (lib/staff.js).
case "GET /mod/api/alts": {
const account = accounts.byName(url.searchParams.get("username") || "");
@@ -517,7 +713,7 @@ const handle = async (req, res, url, from, web) => {
return;
}
if (searchBy !== "address") {
reply(200, findPlayers(url.searchParams.get("q")));
reply(200, findPlayers(url.searchParams.get("q"), url.searchParams.get("only")));
return;
}
// by address: only the address typed, which is written down (once
@@ -670,9 +866,12 @@ const handle = async (req, res, url, from, web) => {
return;
}
// paintings players framed (lib/masterpieces.js).
// paintings players framed (lib/masterpieces.js), and the ones approved
// last, to take one back that should not have been (mine=1: only the
// ones this moderator approved).
case "GET /mod/api/masterpieces":
reply(200, {...masterpieces.listsFor(url.searchParams.get("creator")), waitingCount: masterpieces.list(masterpieces.PENDING).length});
reply(200, {...masterpieces.listsFor(url.searchParams.get("creator")), waitingCount: masterpieces.list(masterpieces.PENDING).length,
recent: masterpieces.recentlyApproved(RECENT_PAINTINGS, url.searchParams.get("mine") === "1" ? mod.username : "")});
return;
case "GET /mod/api/masterpiece": {
@@ -700,7 +899,7 @@ const handle = async (req, res, url, from, web) => {
return;
}
const result = body.action === "approve"
? (world.approveMasterpiece(id) ? {ok: "Approved."} : {error: "No such painting waiting."})
? (world.approveMasterpiece(id, mod.username) ? {ok: "Approved."} : {error: "No such painting waiting."})
: body.action === "reject" || body.action === "remove"
? (world.removeMasterpiece(id) ? {ok: "Removed for good. Its maker was told and given a Masterpiece Token."} : {error: "No such painting."})
: {error: "Unknown action."};
@@ -723,6 +922,8 @@ const handle = async (req, res, url, from, web) => {
// whether it is locked out of the finder: for the dashboards' lock.
// GET items/base?kind=clothing|den&id=N: an item of the game's to
// make one from (its name and colours), to check before making it.
// GET items/wear-rules?q=WORDS: clothing search results, animal choices and
// current per-animal wear blocks. POST it with {id, blockedTypes} to set.
// POST items {action: "create", kind, base, name, cost, members, colors}
// or {action: "update", kind, id, and any of name, cost, members, colors, inShop}
// or {action: "lock" | "unlock", kind, id}: kept out of the item finder
@@ -730,6 +931,21 @@ const handle = async (req, res, url, from, web) => {
// or {action: "delete", kind, id}: a custom item, out of the game and every inventory.
const itemRoutes = (route, url, body, reply, done, actor) => {
switch (route) {
case "GET items/wear-rules": {
const search = new URLSearchParams({kind: "clothing", q: url.searchParams.get("q") || ""});
const found = admin.search(search, null, true);
const rules = itemControl.wearRuleList();
const blockedByItem = new Map(rules.map(rule => [rule.id, rule.blockedTypes]));
reply(200, {animals: itemControl.wearAnimals(), rules, total: found.total,
results: found.results.slice(0, 20).map(entry => ({id: entry.id, name: entry.locked ? entry.name.replace(/ \(locked\)$/, "") : entry.name,
custom: entry.id >= customItems.FIRST_ID, blockedTypes: blockedByItem.get(entry.id) || []}))});
return;
}
case "POST items/wear-rules": {
const result = itemControl.setWearRule(body.id, body.blockedTypes, world);
done(result, result.ok ? "item wear rule changed" : "", "", `clothing ${body.id}`);
return;
}
case "GET items":
reply(200, {items: customItems.list().map(entry => ({...entry, baseName: customItems.baseName(entry), locked: itemControl.isLocked(entry.kind, entry.id),
artUrl: itemArt.urlOf(entry, actor.artBase)})),