diff --git a/lib/commands.js b/lib/commands.js index 46e2122..b108b4d 100644 --- a/lib/commands.js +++ b/lib/commands.js @@ -6,6 +6,8 @@ const defpacks = require("./defpacks.js"); const disguises = require("./disguises.js"); const dens = require("./dens.js"); const {isSilenced} = require("./moderation.js"); +const modlog = require("./modlog.js"); +const roles = require("./roles.js"); const {MAX_DEN_ITEMS, MAX_WORN, activeAvatar, wornItems} = require("./player.js"); // things players can do by typing "!something" in the chat box, for what @@ -47,7 +49,7 @@ const MAX_AGAIN = 100; // A hosted party's own name is three string ids, no use outside the game. const roomTitle = room => (room.partyHost ? `${room.partyHost.username}'s party` : room.displayName); -module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideBlocked, refreshForOthers, travel, reloadRoom, buyAgain, ask}) => { +module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideBlocked, refreshForOthers, travel, reloadRoom, buyAgain, ask, staffMove, staffModeration}) => { // A plain message box with an OK button. const tell = (session, text) => session.sendXt("xtl", -1, String(text).replace(/%/g, " percent")); @@ -500,6 +502,201 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB }; + // ---- staff commands (lib/roles.js). each checks the role's permission on + // every use, and what is done is written down under the staff member's + // name, as in the moderator panel. to anyone without the permission they + // are plain chat, like any other "!word" the server does not know. + const MAX_STAFF_HOURS = 24 * 365 * 10; + const MAX_WARNING = 200; + const MAX_WARNINGS_SHOWN = 5; + + const staffMay = (session, permission) => { + const moderation = staffModeration(); + return roles.can(session.account, permission, moderation.banRemaining(session.account) !== 0); + }; + + // the longest run of leading words naming an online player, and the words + // after it: usernames may have spaces in them. + const splitName = words => { + for (let count = words.length; count > 0; count--) { + const target = findOnline(words.slice(0, count).join(" ")); + if (target) { + return {target, rest: words.slice(count)}; + } + } + return {target: null, rest: words}; + }; + + // the same for any account, online or not. + const splitAccount = words => { + for (let count = words.length; count > 0; count--) { + const account = accounts.byName(words.slice(0, count).join(" ")); + if (account) { + return account; + } + } + return null; + }; + + // finds the player the command is about, and checks the staff member may + // act on them (`onStaff`: also on staff below their rank). + const withTarget = (session, words, usage, onStaff, run) => { + const {target, rest} = splitName(words); + if (!words.length) { + tell(session, usage); + } + else if (!target) { + tell(session, `${words.join(" ")} is not online.`); + } + else if (target === session) { + tell(session, "That is you."); + } + else if (onStaff && !roles.outranks(session.account, target.account)) { + tell(session, "Staff of your rank or above are for someone higher up to deal with."); + } + else { + run(target, rest); + } + }; + + const logged = (session, action, target, detail = "") => + modlog.record(session.account.username, `${action} (in game)`, target.account.username, detail); + + const staffCommands = { + staff: { + permission: "staff.list", + run(session) { + const on = players().filter(other => roles.isActiveStaff(other.account)) + .map(other => `${other.account.username} (${roles.ROLES[roles.roleOf(other.account)].label})`); + tell(session, on.length ? `Staff online: ${on.join(", ")}` : "No staff online."); + }, + }, + summon: { + permission: "player.summon", + run(session, words) { + withTarget(session, words, "Use: !summon PLAYER", true, target => { + const result = staffMove(target.account.username, session.account.username); + if (!result.ok) { + tell(session, result.error); + return; + } + tell(session, `${target.account.username} was brought here.`); + logged(session, "summon", target, result.room); + }); + }, + }, + goto: { + permission: "player.goto", + run(session, words) { + withTarget(session, words, "Use: !goto PLAYER", false, target => { + const result = staffMove(session.account.username, target.account.username); + if (!result.ok) { + tell(session, result.error); + return; + } + logged(session, "goto", target, result.room); + }); + }, + }, + kick: { + permission: "player.kick", + run(session, words) { + withTarget(session, words, "Use: !kick PLAYER", true, target => { + const name = target.account.username; + if (staffModeration().actions.kick(target.account)) { + tell(session, `${name} was disconnected.`); + logged(session, "kick", target); + } + else { + tell(session, `${name} is not online.`); + } + }); + }, + }, + // "!silence PLAYER HOURS" (0: until lifted), "!silence PLAYER off". + silence: { + permission: "chat.silence", + run(session, words) { + withTarget(session, words, "Use: !silence PLAYER HOURS (0 until lifted), or !silence PLAYER off", true, (target, rest) => { + const {actions, PERMANENT} = staffModeration(); + const name = target.account.username; + const amount = (rest[0] || "").toLowerCase(); + if (amount === "off") { + actions.silence(target.account, 0); + tell(session, `${name} can chat again.`); + logged(session, "unsilence", target); + return; + } + const hours = /^\d{1,6}$/.test(amount) ? Number(amount) : NaN; + if (!(hours >= 0 && hours <= MAX_STAFF_HOURS)) { + tell(session, "Use: !silence PLAYER HOURS (0 until lifted), or !silence PLAYER off"); + return; + } + actions.silence(target.account, hours === 0 ? PERMANENT : hours * 3600); + tell(session, hours === 0 ? `${name} cannot chat until it is lifted.` : `${name} cannot chat for ${hours} hours.`); + logged(session, "silence", target, String(hours || "until lifted")); + }); + }, + }, + // "!warn PLAYER [REASON] [note]": a warning, kept on the account and + // shown with the game's own warning popup. REASON is behavior (the + // default), bullying, personal or scamming; the note is for staff. + warn: { + permission: "player.warn", + run(session, words) { + const usage = `Use: !warn PLAYER [${staffModeration().WARNINGS.join("|")}] [note]`; + withTarget(session, words, usage, true, (target, rest) => { + const {WARNINGS, actions} = staffModeration(); + const asked = (rest[0] || "").toLowerCase(); + const reason = WARNINGS.includes(asked) ? asked : "behavior"; + const note = (WARNINGS.includes(asked) ? rest.slice(1) : rest).join(" ").trim().slice(0, MAX_WARNING); + const result = actions.warn(target.account, reason, session.account.username, note); + tell(session, `${target.account.username} warned (${reason}): warning ${result.count}.`); + logged(session, "warn", target, note ? `${reason} · ${note}` : reason); + }); + }, + }, + // "!message PLAYER text": a message box from the moderators. + message: { + permission: "player.warn", + run(session, words) { + withTarget(session, words, "Use: !message PLAYER text", true, (target, rest) => { + const text = rest.join(" ").trim().slice(0, MAX_WARNING); + if (!text) { + tell(session, "Use: !message PLAYER text"); + return; + } + if (staffModeration().actions.message(target.account, text)) { + tell(session, `Shown to ${target.account.username}.`); + logged(session, "message", target, text); + } + else { + tell(session, `${target.account.username} is not online.`); + } + }); + }, + }, + // "!warnings PLAYER": their latest warnings, online or not. + warnings: { + permission: "player.warn", + run(session, words) { + const account = splitAccount(words); + if (!account) { + tell(session, words.length ? `No player called ${words.join(" ")}.` : "Use: !warnings PLAYER"); + return; + } + const list = account.warnings || []; + if (!list.length) { + tell(session, `${account.username} has no warnings.`); + return; + } + const latest = list.slice(-MAX_WARNINGS_SHOWN).reverse() + .map(entry => `${new Date(entry.at * 1000).toISOString().slice(0, 10)} ${entry.reason} by ${entry.by}${entry.note ? ` (${entry.note})` : ""}`); + tell(session, `${account.username} has ${list.length} warning${list.length === 1 ? "" : "s"}. Latest: ${latest.join("; ")}`); + }, + }, + }; + return { // runs `text` if it is a command. returns what to do with the chat line: // null to swallow it, or the text everyone should see in its place. @@ -509,6 +706,10 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB } const typed = text.slice(PREFIX.length).trim().split(/\s+/); const [name, ...words] = typed.map(word => word.toLowerCase()); + if (Object.hasOwn(staffCommands, name) && staffMay(session, staffCommands[name].permission)) { + staffCommands[name].run(session, typed.slice(1)); + return null; + } if (Object.hasOwn(asTyped, name) && (name !== "den" || typed.length > 1)) { asTyped[name](session, typed.slice(1)); return null; diff --git a/lib/defpacks.js b/lib/defpacks.js index ceeabbc..e014a6e 100644 --- a/lib/defpacks.js +++ b/lib/defpacks.js @@ -175,7 +175,20 @@ const withOurName = pack => { return pack; }; -const withAddedStrings = pack => withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings())); +// the moderators' message boxes (FacilitatorXtCommManager "fp") keep +// "\n" as two characters, which the client shows just as written +// ("--Message From Moderator--\n\nhello"). real line breaks in their place. +const LITERAL_LINE_BREAKS = ["11134", "11135"]; +const withLineBreaks = pack => { + for (const id of LITERAL_LINE_BREAKS) { + if (typeof pack[id] === "string") { + pack[id] = pack[id].replace(/\\n/g, "\n"); + } + } + return pack; +}; + +const withAddedStrings = pack => withLineBreaks(withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings()))); // the extra music tracks (lib/extramusic.js), as den items like the // official tracks. diff --git a/lib/moderation.js b/lib/moderation.js index ca6772f..60331f0 100644 --- a/lib/moderation.js +++ b/lib/moderation.js @@ -18,6 +18,18 @@ const CURRENCY_GEMS = 0; // client says "You earned N ..." in a popup when the amount went up. const REASON_ANNOUNCE = 3; +// a warning's reason, and the client's own warning popup for it +// (FacilitatorXtCommManager.showContextualWarningPopup, "fw"): its artwork +// and its words, which this server's strings already say in its own name. +const WARNINGS = { + behavior: 4, // "Inappropriate Behavior" + bullying: 1, // "Bullying" + personal: 3, // "Personal Information" + scamming: 9, // "Scamming" +}; +const MAX_WARNINGS_KEPT = 100; +const MAX_WARNING_NOTE = 200; + const now = () => Math.floor(Date.now() / 1000); // seconds of ban left, PERMANENT, or 0 when not banned. @@ -171,6 +183,23 @@ module.exports = ({findOnline}) => { notify(session, text); return true; }, + + // a warning: kept on the account (who, when, why and a note for staff), + // and shown with the game's own warning popup if they are online. + // returns {count, online}, or null for a reason that is not one. + warn(target, reason, by, note = "") { + if (!Object.hasOwn(WARNINGS, reason)) { + return null; + } + target.warnings = [...(target.warnings || []), {at: now(), by, reason, note: String(note).slice(0, MAX_WARNING_NOTE)}] + .slice(-MAX_WARNINGS_KEPT); + accounts.save(); + const session = findOnline(target.username); + if (session) { + discipline(session, "fw", WARNINGS[reason]); + } + return {count: target.warnings.length, online: Boolean(session)}; + }, }; // the client's moderator requests, refused whoever sends them. each @@ -178,7 +207,7 @@ module.exports = ({findOnline}) => { const refuse = reply => session => session.sendXt(reply, -1, 0); const handlers = {fk: refuse("fk"), fb: refuse("fb"), fs: refuse("fs"), fm: refuse("fm"), fg: refuse("fg"), fp: refuse("fp"), fc() {}}; - return {handlers, actions, banRemaining, banOf, isSilenced, silenceRemaining, PERMANENT}; + return {handlers, actions, banRemaining, banOf, isSilenced, silenceRemaining, PERMANENT, WARNINGS: Object.keys(WARNINGS)}; }; Object.assign(module.exports, {isSilenced, banRemaining, banOf}); diff --git a/lib/modpanel.js b/lib/modpanel.js index 7cb2c34..cd10252 100644 --- a/lib/modpanel.js +++ b/lib/modpanel.js @@ -13,6 +13,7 @@ const manage = require("./manage.js"); const masterpieces = require("./masterpieces.js"); const modlog = require("./modlog.js"); const reports = require("./reports.js"); +const roles = require("./roles.js"); const staff = require("./staff.js"); const stats = require("./stats.js"); const support = require("./support.js"); @@ -23,8 +24,9 @@ const world = require("./world.js"); // players, and no more. it is apart from the admin panel (lib/panel.js), // which stays whoever runs the server's alone. // -// A moderator is a game account the admin marked as one (`moderator` on the -// account). they sign in here with that account's username and password and +// A moderator is a game account the admin gave a staff role (lib/roles.js: +// helper, moderator or admin; `moderator` on an older account counts as a +// moderator), and what they may do here is what their role allows. they sign in here with that account's username and password and // a code from their authenticator app, every time: an account without 2FA // cannot sign in at all, and a trusted device is not taken for a code. // being a moderator gives the account nothing in the game itself. @@ -63,8 +65,7 @@ const cookieHeader = (token, maxAgeSeconds) => `${COOKIE}=${token}; Path=/mod; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`; // may this account use the panel (still)? -const mayModerate = account => Boolean(account && account.moderator && totp.isOn(account) && !account.locked - && world.moderation.banRemaining(account) === 0); +const mayModerate = account => Boolean(account && roles.isActiveStaff(account, world.moderation.banRemaining(account) !== 0)); const signedInAs = req => { const token = cookieToken(req); @@ -95,7 +96,9 @@ const playerRow = (account, playing) => { banReason: ban ? ban.reason : "", silenced: world.moderation.silenceRemaining(account), nameRejected: Boolean(account.nameRejected), - moderator: Boolean(account.moderator), + moderator: Boolean(roles.roleOf(account)), + role: roles.roleOf(account), + warnings: (account.warnings || []).length, playtime: account.playtime, bio: account.bio, discord: account.discord, @@ -120,6 +123,7 @@ const playerDetail = account => ({ ...playerRow(account, playing()), history: bans.historyOf(account).map(({at, action, seconds, reason, by}) => ({at, action, seconds, reason, by})), appeal: bans.appealOf(account), + warningList: (account.warnings || []).slice(-20).reverse(), openReports: reports.list(false).filter(report => report.target.toLowerCase() === account.username.toLowerCase()).length, }); @@ -134,6 +138,16 @@ const maskedAddress = ban => ({ const wholeNumber = (value, min, max) => (Number.isInteger(value) && value >= min && value <= max ? value : null); +// the permission (lib/roles.js) each action needs. +const ACTION_PERMISSIONS = { + ban: "player.ban", banReason: "player.ban", unban: "player.ban", + silence: "chat.silence", unsilence: "chat.silence", + kick: "player.kick", message: "player.warn", warn: "player.warn", + rejectName: "player.names", acceptName: "player.names", clearBio: "player.names", + banAddress: "address.ban", + summon: "player.summon", goto: "player.goto", +}; + const act = (mod, target, body) => { const {actions, PERMANENT} = world.moderation; const name = target.username; @@ -141,8 +155,12 @@ const act = (mod, target, body) => { if (target === mod) { return {error: "That is you."}; } - if (target.moderator) { - return {error: "Another moderator is the admin's to deal with."}; + if (!roles.outranks(mod, target)) { + return {error: "Staff of your rank or above are for someone higher up to deal with."}; + } + const permission = ACTION_PERMISSIONS[body.action]; + if (permission && !roles.can(mod, permission)) { + return {error: "Your role cannot do that."}; } switch (body.action) { case "ban": { @@ -183,6 +201,15 @@ const act = (mod, target, body) => { } return actions.message(target, text) ? {ok: `Shown to ${name}.`, detail: text} : {error: `${name} is not online.`}; } + case "warn": { + const reason = String(body.reason || "behavior"); + const result = actions.warn(target, reason, by, body.note); + if (!result) { + return {error: `A warning's reason: ${world.moderation.WARNINGS.join(", ")}.`}; + } + return {ok: `${name} warned (${reason}): warning ${result.count}.${result.online ? "" : " They are offline, so they will not see it."}`, + detail: `${reason}${body.note ? ` · ${String(body.note).slice(0, 200)}` : ""}`}; + } case "rejectName": if (target.nameRejected) { return {error: "Already rejected."}; @@ -213,6 +240,16 @@ const act = (mod, target, body) => { } return {ok: "Their address is banned.", detail: result.ban.reason}; } + // the moderator's own animal and the player's, in the game: both have + // to be online, the moderator in a room. + case "summon": { + const result = world.staffMove(target.username, mod.username); + return result.ok ? {ok: `${name} was brought to ${result.room}.`, detail: result.room} : {error: result.error}; + } + case "goto": { + const result = world.staffMove(mod.username, target.username); + return result.ok ? {ok: `You went to ${name} (${result.room}).`, detail: result.room} : {error: result.error}; + } default: return {error: "Unknown action."}; } @@ -267,7 +304,7 @@ const handle = async (req, res, url, from, web) => { const account = known && await accounts.authenticateAsync(known.username, body.password) === known ? known : null; // one answer for a wrong password and for an account that is no // moderator: who the moderators are is nobody's to find out here. - if (!account || !account.moderator) { + if (!account || !roles.roleOf(account)) { failuresByAddress.record(from.key); if (known && !account) { accounts.recordLogin(known, "mod", from.address, false); @@ -334,6 +371,12 @@ const handle = async (req, res, url, from, web) => { }; switch (route) { + // who is signed in here, their role and what it allows: for a client to + // show only the buttons that will work. + case "GET /mod/api/me": + reply(200, {username: mod.username, role: roles.roleOf(mod), permissions: roles.permissionsOf(mod)}); + return; + case "GET /mod/api/overview": reply(200, {online: world.players().length, reports: reports.openCount(), requests: support.nameRequests(false).length + bans.openAppeals(), paintings: masterpieces.list(masterpieces.PENDING).length}); @@ -468,8 +511,8 @@ const handle = async (req, res, url, from, web) => { } }; -const moderators = () => accounts.all().filter(account => account.moderator) - .map(account => ({username: account.username, twoStep: totp.isOn(account), lastSeen: account.lastSeen || null})) +const moderators = () => accounts.all().filter(account => roles.roleOf(account)) + .map(account => ({username: account.username, role: roles.roleOf(account), twoStep: totp.isOn(account), lastSeen: account.lastSeen || null})) .sort((a, b) => a.username.localeCompare(b.username)); module.exports = {handle, forget, moderators}; diff --git a/lib/panel.js b/lib/panel.js index 1d769a8..538ad74 100644 --- a/lib/panel.js +++ b/lib/panel.js @@ -18,6 +18,7 @@ const modlog = require("./modlog.js"); const modpanel = require("./modpanel.js"); const erase = require("./erase.js"); const reports = require("./reports.js"); +const roles = require("./roles.js"); const sales = require("./sales.js"); const stats = require("./stats.js"); const staff = require("./staff.js"); @@ -148,7 +149,8 @@ const accountRow = (account, playing) => { // seconds left, -1 for permanent, 0 for not banned banned: ban, banReason: ban === 0 ? "" : account.banReason || bans.NO_REASON, - moderator: Boolean(account.moderator), + moderator: Boolean(roles.roleOf(account)), + role: roles.roleOf(account), nameRejected: Boolean(account.nameRejected), silenced: world.moderation.isSilenced(account), animals: account.avatars.length, @@ -488,18 +490,33 @@ const act = (account, body) => { } // A moderator may use the moderator panel (lib/modpanel.js), with this // account's password and its 2FA, which it has to have. + // (the older on/off switch; "role" below is the full one.) case "moderator": - if (body.on === true) { - account.moderator = true; - } - else { - delete account.moderator; + roles.setRole(account, body.on === true ? "moderator" : null); + if (body.on !== true) { modpanel.forget(account); } accounts.save(); return {ok: body.on === true ? `${name} is a moderator.${totp.isOn(account) ? "" : " They have no 2FA yet and cannot sign in to the moderator panel until they turn it on."}` : `${name} is no longer a moderator.`}; + // A staff role (lib/roles.js): helper, moderator, admin, or none. What + // each allows is listed under "GET /admin/api/roles". + case "role": { + const role = body.role === null || body.role === "" || body.role === "none" ? null : String(body.role); + if (!roles.setRole(account, role)) { + return {error: `No such role. Roles: ${Object.keys(roles.ROLES).join(", ")}, or none.`}; + } + if (role === null) { + modpanel.forget(account); + } + accounts.save(); + if (role === null) { + return {ok: `${name} has no staff role.`}; + } + const label = roles.ROLES[role].label.toLowerCase(); + return {ok: `${name} is now ${/^[aeiou]/.test(label) ? "an" : "a"} ${label}.${totp.isOn(account) ? "" : " They have no 2FA yet, so their role does nothing until they turn it on."}`}; + } case "rejectName": actions.rejectName(account, BY); manage.forget(account); @@ -692,6 +709,11 @@ const handle = async (req, res, url, from, web) => { return; // who may use the moderator panel, and what each did there. + // the staff roles and what each may do. + case "GET /admin/api/roles": + reply(200, {roles: Object.entries(roles.ROLES).map(([id, role]) => ({id, label: role.label, rank: role.rank, permissions: role.permissions})), + permissions: roles.PERMISSIONS}); + return; case "GET /admin/api/moderators": reply(200, {moderators: modpanel.moderators(), log: modlog.recent()}); return; diff --git a/lib/roles.js b/lib/roles.js new file mode 100644 index 0000000..daab1d8 --- /dev/null +++ b/lib/roles.js @@ -0,0 +1,89 @@ +"use strict"; + +const totp = require("./totp.js"); + +// staff roles, and what each may do. an account holds at most one role +// (`role` on the account), set by the admin. an account from before roles +// that is only marked `moderator` counts as a moderator, so nothing that +// worked before stops working. +// +// a role is a list of permissions, and every staff action checks the one it +// needs, in the moderator panel (lib/modpanel.js) and in the game +// (lib/commands.js) alike. a higher role holds everything a lower one does. +// staff never act on staff of their own rank or above: that is for someone +// higher up, and for the admin in the end. + +const PERMISSIONS = { + "staff.list": "see which staff are online (!staff)", + "player.warn": "warn a player and send them a message (!warn, !warnings, !message)", + "player.goto": "go to the room a player is in (!goto)", + "chat.silence": "silence and unsilence a player (!silence)", + "player.kick": "disconnect a player (!kick)", + "player.summon": "bring a player to the room you are in (!summon)", + "player.ban": "ban, unban and change a ban's reason", + "player.names": "reject or accept a name, clear a bio", + "address.ban": "ban the address a player last signed in from", +}; + +const HELPER = ["staff.list", "player.warn", "player.goto", "chat.silence"]; +const MODERATOR = [...HELPER, "player.kick", "player.summon", "player.ban", "player.names", "address.ban"]; +const ADMIN = [...MODERATOR]; + +const ROLES = { + helper: {rank: 1, label: "Helper", permissions: HELPER}, + moderator: {rank: 2, label: "Moderator", permissions: MODERATOR}, + admin: {rank: 3, label: "Admin", permissions: ADMIN}, +}; + +// the role an account holds, or null. +const roleOf = account => { + if (!account) { + return null; + } + if (Object.hasOwn(ROLES, account.role)) { + return account.role; + } + return account.moderator ? "moderator" : null; +}; + +const rankOf = account => { + const role = roleOf(account); + return role ? ROLES[role].rank : 0; +}; + +// may this account act as staff at all right now? as for the moderator +// panel: a role, 2FA turned on, not locked and not banned. `banned` says +// whether the account is banned (passed in, so that this file needs nothing +// of the world's). +const isActiveStaff = (account, banned = false) => + Boolean(roleOf(account) && totp.isOn(account) && !account.locked && !banned); + +const permissionsOf = account => { + const role = roleOf(account); + return role ? [...ROLES[role].permissions] : []; +}; + +const can = (account, permission, banned = false) => + isActiveStaff(account, banned) && ROLES[roleOf(account)].permissions.includes(permission); + +// may `actor` act on `target`? never on themselves, nor on staff of their +// own rank or above. +const outranks = (actor, target) => actor !== target && rankOf(actor) > rankOf(target); + +// sets the role (one of ROLES, or null for none). `moderator` is kept in +// step for anything that still reads it. +const setRole = (account, role) => { + if (role === null || role === "" || role === "none") { + delete account.role; + delete account.moderator; + return true; + } + if (!Object.hasOwn(ROLES, role)) { + return false; + } + account.role = role; + account.moderator = true; + return true; +}; + +module.exports = {PERMISSIONS, ROLES, roleOf, rankOf, isActiveStaff, permissionsOf, can, outranks, setRole}; diff --git a/lib/world.js b/lib/world.js index 4c334dc..96123e4 100644 --- a/lib/world.js +++ b/lib/world.js @@ -5,6 +5,7 @@ const achievements = require("./achievements.js"); const adopt = require("./adopt.js"); const config = require("../config.js"); const colours = require("./colours.js"); +const roles = require("./roles.js"); const commandModule = require("./commands.js"); const limits = require("./limits.js"); const masterpieces = require("./masterpieces.js"); @@ -185,6 +186,11 @@ const loginParams = session => { // from bit 8 up: the name tag badges the admin gave this account // (lib/badges.js). pendingFlags: 7 | badges.loginFlags(account), + // this account's own staff role and what it allows (lib/roles.js), for a + // client to show staff tools only to staff. empty for everyone else, and + // only ever about the account logging in. + staffRole: roles.isActiveStaff(account) ? roles.roleOf(account) : "", + staffPermissions: roles.isActiveStaff(account) ? roles.permissionsOf(account).join(",") : "", dailyGiftIndex: -1, hasOnlineBuddies: buddies.hasOnlineBuddies(account), // one bit per kind of interaction (Utility.canBuddy, canTrade, canGift, @@ -896,6 +902,31 @@ const fileReport = (session, username, reason, detail = "", about = "") => { // what the modules below may use of this one. `others` here is everyone who // should see the player's animal change; dens get everyone in the room. +// staff moving a player: `whoName` to the room `toName` is in (summon is +// the player to the staff member, goto the staff member to the player). both +// online, `toName` in a room. the room's own rules still apply: a full room +// or a locked den keeps them out. +const staffMove = (whoName, toName) => { + const who = findOnline(whoName); + const to = findOnline(toName); + if (!who) { + return {error: `${whoName} is not online.`}; + } + if (!to || !to.room) { + return {error: `${toName} is not in a room.`}; + } + const room = to.room; + const shown = room.displayName || room.name; + if (who.room === room) { + return {error: "Already in the same room."}; + } + if (room.sessions.size >= config.maxUsersPerRoom) { + return {error: `${shown} is full.`}; + } + joinRoom(who, room.name); + return who.room === room ? {ok: true, room: shown} : {error: `Could not get into ${shown}.`}; +}; + const context = { others: watchers, watchers, @@ -917,6 +948,9 @@ const context = { ask: (...args) => ask(...args), travel: (session, base) => joinRoom(session, `${base}#${config.shards[0].id}`), joinRoom: (...args) => joinRoom(...args), + staffMove: (...args) => staffMove(...args), + // the moderation module, made after this context (lib/commands.js uses it) + staffModeration: () => moderation, reloadRoom: session => reloadRoom(session), buyAgain: session => handlers[session.lastPurchase.cmd](session, session.lastPurchase.roomId, session.lastPurchase.params), }; @@ -1429,6 +1463,7 @@ module.exports = { return true; }, moderation, + staffMove, walls, ecards, // called when the admin changed an account's badges: a name tag showing diff --git a/public/admin.html b/public/admin.html index 7b4fd99..f0c0521 100644 --- a/public/admin.html +++ b/public/admin.html @@ -399,6 +399,13 @@ + + @@ -747,7 +754,8 @@ tags.push(el("span", "Name rejected", "tag bad")); } if (account.moderator) { - tags.push(el("span", "Moderator", "tag good")); + const label = {helper: "Helper", moderator: "Moderator", admin: "Admin"}[account.role] || "Moderator"; + tags.push(el("span", label, "tag good")); } if (account.twoStep) { tags.push(el("span", "2FA", "tag")); @@ -959,6 +967,7 @@ $("quest-level").value = current ? current.level : ""; $("ban-reason").value = current ? current.banReason : ""; $("moderator-toggle").textContent = current && current.moderator ? "Remove moderator" : "Make moderator"; + $("role-select").value = current && current.role ? current.role : "none"; }; const select = username => { @@ -1000,6 +1009,7 @@ case "banReason": return {reason: $("ban-reason").value}; case "silence": return {hours: numberFrom("silence-hours")}; case "moderator": return {on: !(accounts.find(account => account.username === selected) || {}).moderator}; + case "role": return {role: $("role-select").value}; case "message": return {text: $("message-text").value}; case "gems": return {amount: numberFrom("gems-amount")}; case "gift": return giftBody(); diff --git a/public/mod.html b/public/mod.html index 3b5d0a2..e4bc32b 100644 --- a/public/mod.html +++ b/public/mod.html @@ -226,7 +226,7 @@ #chat-context { margin: 0; padding: 0; list-style: none; } #chat-context li.this { background: var(--raised); border-radius: 10px; } #player-facts { margin-bottom: 14px; } - #player-history { margin: 0; padding-left: 18px; font-size: 13px; overflow-wrap: anywhere; } + #player-history, #player-warnings { margin: 0; padding-left: 18px; font-size: 13px; overflow-wrap: anywhere; } .actions { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 12px; } @@ -303,11 +303,25 @@
+
+

Warn

+
+ +
+

Message

+
+ +

Username and bio

@@ -319,6 +333,8 @@
+ + @@ -569,6 +585,7 @@ ["Ban", player.banned === 0 ? "—" : `${left(player.banned)} · ${player.banReason}`], ["Chat", player.silenced === 0 ? "—" : `Silenced: ${left(player.silenced).toLowerCase()}`], ["Reports waiting", String(player.openReports)], + ["Warnings", String(player.warnings || 0)], ["Appeal", player.appeal ? `${player.appeal.status} · ${player.appeal.text}` : "—"], ["Discord", player.discord || "—"], ["Bio", player.bio || "—"], @@ -584,6 +601,11 @@ if (document.activeElement !== $("ban-reason")) { $("ban-reason").value = player.banned === 0 ? "" : player.banReason; } + const WARNING_REASONS = {behavior: "Inappropriate behavior", bullying: "Bullying", personal: "Personal information", scamming: "Scamming"}; + const warnings = player.warningList || []; + $("warnings-title").hidden = warnings.length === 0; + $("player-warnings").replaceChildren(...warnings.map(entry => el("li", [when(entry.at), WARNING_REASONS[entry.reason] || entry.reason, + entry.note, entry.by && `by ${entry.by}`].filter(Boolean).join(" · ")))); $("history-title").hidden = player.history.length === 0; $("player-history").replaceChildren(...player.history.map(entry => el("li", [when(entry.at), HISTORY[entry.action] || entry.action, entry.action === "ban" ? (entry.seconds === -1 ? "for good" : duration(entry.seconds)) : "", entry.reason, entry.by && `by ${entry.by}`] @@ -614,6 +636,7 @@ case "banReason": case "banAddress": return {reason: $("ban-reason").value}; case "silence": return {hours: numberFrom("silence-hours")}; case "message": return {text: $("message-text").value}; + case "warn": return {reason: $("warn-reason").value, note: $("warn-note").value}; default: return {}; } }; @@ -976,12 +999,37 @@ one.addEventListener("click", () => showTab(one.dataset.tab)); } + // the permission (lib/roles.js) each button needs: one the signed-in + // role does not hold is not shown. the server checks again either way. + const ACTION_PERMISSIONS = { + ban: "player.ban", banReason: "player.ban", unban: "player.ban", + silence: "chat.silence", unsilence: "chat.silence", + kick: "player.kick", message: "player.warn", warn: "player.warn", + rejectName: "player.names", acceptName: "player.names", clearBio: "player.names", + banAddress: "address.ban", summon: "player.summon", goto: "player.goto", + }; + const applyPermissions = async () => { + const result = await api("me"); + if (!result.ok) { + return; + } + const allowed = new Set(result.data.permissions || []); + for (const pressed of document.querySelectorAll("button[data-action]")) { + const needed = ACTION_PERMISSIONS[pressed.dataset.action]; + pressed.hidden = Boolean(needed) && !allowed.has(needed); + } + if (result.data.role) { + $("who").textContent = `${result.data.username} (${result.data.role})`; + } + }; + const showPanel = username => { signedIn = true; $("who").textContent = username; $("gate").hidden = true; $("panel").hidden = false; showTab(tab); + applyPermissions(); }; $("gate-form").addEventListener("submit", async event => { diff --git a/test/staff.js b/test/staff.js new file mode 100644 index 0000000..6f888ae --- /dev/null +++ b/test/staff.js @@ -0,0 +1,245 @@ +"use strict"; + +// end to end: staff roles (lib/roles.js), the staff chat commands +// (lib/commands.js) and the moderator panel's role checks +// (lib/modpanel.js), against a real server with a database of its own. + +const assert = require("assert"); +const crypto = require("crypto"); +const harness = require("./harness.js"); + +const HTTP_PORT = 18091; +const GAME_PORT = 19350; +const BASE = `http://127.0.0.1:${HTTP_PORT}`; +const TOWNSHIP = "jamaa_township.room_main#1"; +const SAREPIA = "sarepia.room_main#1"; +const {postJson} = harness; + +// the authenticator app's side of 2FA (lib/totp.js): a base32 secret, +// HMAC-SHA1, 30-second steps, six digits. +const STEP = 30; +const base32Decode = text => { + const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + const bits = text.replace(/=+$/, "").toUpperCase().split("").map(c => alphabet.indexOf(c).toString(2).padStart(5, "0")).join(""); + const bytes = []; + for (let i = 0; i + 8 <= bits.length; i += 8) { + bytes.push(parseInt(bits.slice(i, i + 8), 2)); + } + return Buffer.from(bytes); +}; +const codeAt = (secret, step) => { + const counter = Buffer.alloc(8); + counter.writeBigUInt64BE(BigInt(step)); + const mac = crypto.createHmac("sha1", base32Decode(secret)).update(counter).digest(); + const offset = mac[mac.length - 1] & 0x0F; + return String((mac.readUInt32BE(offset) & 0x7FFFFFFF) % 1000000).padStart(6, "0"); +}; +const stepNow = () => Math.floor(Date.now() / 1000 / STEP); +const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); +// a code is taken once: each use needs a later step than the last. +const waitForStep = async step => { + while (stepNow() < step) { + await sleep(250); + } +}; + +// a web panel's session: keeps the cookie it is given. +const webSession = () => { + let cookie = ""; + return async (path, body) => { + const headers = {cookie}; + const options = body === undefined ? {headers} : {method: "POST", headers: {...headers, "Content-Type": "application/json"}, body: JSON.stringify(body)}; + const res = await fetch(`${BASE}${path}`, options); + const set = res.headers.get("set-cookie"); + if (set) { + cookie = set.split(";")[0]; + } + return {status: res.status, data: await res.json().catch(() => ({}))}; + }; +}; + +const say = (client, roomId, text) => + client.send(``); + +// logs in (with a 2FA code when given) and walks into `room`. +const arrive = async (username, password, room, totp) => { + const res = await postJson(`${BASE}/authenticate`, {username, password, ...(totp ? {totp} : {})}); + const auth = await res.json(); + assert.strictEqual(res.status, 200, `${username} could not sign in: ${JSON.stringify(auth)}`); + const client = new harness.GameClient(GAME_PORT); + await client.connect(); + const login = await client.logIn(username, auth.auth_token); + assert.strictEqual(login.status, "1"); + client.xt("rj", 1, room, 1, 0, 0); + const rj = await client.untilXt("rj"); + await client.untilXt("rp"); + client.xt("au", rj[4], 1, 400, 400, 14, 1); + return {client, login, roomId: rj[4], room: rj[3]}; +}; + +// the next moderator popup ("fd") of this kind, skipping earlier ones (a +// silence notice, say) still waiting. +const untilPopup = async (client, kind) => { + for (;;) { + const fields = await client.untilXt("fd"); + if (fields[2] === kind) { + return fields; + } + } +}; + +// the next message box ("xtl") the server shows this client. +const nextBox = async client => (await client.untilXt("xtl"))[2]; + +// the chat line `text` coming back (every typed line, a command too, is +// shown to its sender, so skip those before it). +const untilChat = async (client, text) => { + for (;;) { + const line = await client.untilXt("uc"); + if (line[3] === text) { + return line; + } + } +}; + +const run = async () => { + const registerJson = body => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({avatarType: 1, agreed: true, ...body})}); + const people = {Mira: "Password11", Hal: "Password12", Pip: "Password13", Ann: "Password14"}; + for (const [username, password] of Object.entries(people)) { + assert.strictEqual((await registerJson({username, password})).status, 200); + } + + // --- the admin gives roles + const admin = webSession(); + assert.strictEqual((await admin("/admin/api/setup", {password: "AdminPass99!"})).status, 200); + assert.strictEqual((await admin("/admin/api/login", {password: "AdminPass99!"})).status, 200); + const roleList = await admin("/admin/api/roles"); + assert.deepStrictEqual(roleList.data.roles.map(role => role.id), ["helper", "moderator", "admin"]); + assert.match((await admin("/admin/api/account", {username: "Mira", action: "role", role: "boss"})).data.error, /No such role/); + + // staff need 2FA: turned on from the account page. + const secrets = {}; + const usedStep = {}; + for (const username of ["Mira", "Hal"]) { + const page = webSession(); + assert.strictEqual((await page("/account/api/login", {username, password: people[username]})).status, 200); + const begun = await page("/account/api/act", {action: "twoStepStart", current: people[username]}); + secrets[username] = begun.data.setup.secret; + usedStep[username] = stepNow(); + const confirmed = await page("/account/api/act", {action: "twoStepConfirm", code: codeAt(secrets[username], usedStep[username])}); + assert.ok(confirmed.data.ok, JSON.stringify(confirmed.data)); + } + assert.match((await admin("/admin/api/account", {username: "Mira", action: "role", role: "moderator"})).data.ok, /moderator/); + assert.match((await admin("/admin/api/account", {username: "Hal", action: "role", role: "helper"})).data.ok, /helper/); + + // --- the game: the login reply carries your own role, and nobody else's + usedStep.Mira++; + const mira = await arrive("Mira", people.Mira, TOWNSHIP, codeAt(secrets.Mira, usedStep.Mira)); + assert.strictEqual(mira.login.params.staffRole, "moderator"); + assert.ok(mira.login.params.staffPermissions.split(",").includes("player.summon")); + usedStep.Hal++; + const hal = await arrive("Hal", people.Hal, TOWNSHIP, codeAt(secrets.Hal, usedStep.Hal)); + assert.strictEqual(hal.login.params.staffRole, "helper"); + const pip = await arrive("Pip", people.Pip, SAREPIA); + assert.strictEqual(pip.login.params.staffRole, ""); + const ann = await arrive("Ann", people.Ann, SAREPIA); + + // a staff command from a player is plain chat + say(pip.client, pip.roomId, "!kick Mira"); + await untilChat(pip.client, "!kick Mira"); + + say(mira.client, mira.roomId, "!staff"); + const staffBox = await nextBox(mira.client); + assert.match(staffBox, /Mira \(Moderator\)/); + assert.match(staffBox, /Hal \(Helper\)/); + + // summon: Pip is brought from Sarepia to Mira in the township + say(mira.client, mira.roomId, "!summon Pip"); + assert.strictEqual((await pip.client.untilXt("rj"))[3], TOWNSHIP); + assert.strictEqual(await nextBox(mira.client), "Pip was brought here."); + + // a helper may silence a player, but not kick, nor act on a moderator + say(hal.client, hal.roomId, "!silence Pip 1"); + assert.strictEqual(await nextBox(hal.client), "Pip cannot chat for 1 hours."); + say(hal.client, hal.roomId, "!silence Pip off"); + assert.strictEqual(await nextBox(hal.client), "Pip can chat again."); + say(hal.client, hal.roomId, "!silence Mira 1"); + assert.match(await nextBox(hal.client), /your rank or above/); + say(hal.client, hal.roomId, "!kick Pip"); + // no permission: just chat, seen by the room (Mira, in the township) + await untilChat(mira.client, "!kick Pip"); + + // goto: Mira goes to Ann in Sarepia + say(mira.client, mira.roomId, "!goto Ann"); + assert.strictEqual((await mira.client.untilXt("rj"))[3], SAREPIA); + + // a warning: the game's own popup for the reason ("fw", 1 = bullying), + // kept on the account; a message box; the count; then kick disconnects + say(mira.client, ann.roomId, "!warn Ann bullying called names"); + assert.deepStrictEqual((await ann.client.untilXt("fd")).slice(2, 4), ["fw", "1"]); + assert.strictEqual(await nextBox(mira.client), "Ann warned (bullying): warning 1."); + say(mira.client, ann.roomId, "!warn Ann"); + assert.deepStrictEqual((await ann.client.untilXt("fd")).slice(2, 4), ["fw", "4"]); // behavior, the default + assert.strictEqual(await nextBox(mira.client), "Ann warned (behavior): warning 2."); + say(mira.client, ann.roomId, "!message Ann please be kind"); + assert.deepStrictEqual((await ann.client.untilXt("fd")).slice(2, 4), ["fp", "please be kind"]); + assert.strictEqual(await nextBox(mira.client), "Shown to Ann."); + say(mira.client, ann.roomId, "!warnings Ann"); + assert.match(await nextBox(mira.client), /^Ann has 2 warnings\. Latest: \S+ behavior by Mira; \S+ bullying by Mira \(called names\)$/); + say(mira.client, ann.roomId, "!kick Ann"); + assert.strictEqual((await ann.client.untilXt("fd"))[2], "fk"); + assert.strictEqual(await nextBox(mira.client), "Ann was disconnected."); + + // --- the moderator panel: what the role allows, checked by the server + for (const username of ["Mira", "Hal"]) { + usedStep[username]++; + } + await waitForStep(Math.max(usedStep.Mira, usedStep.Hal) - 1); + const modPage = webSession(); + assert.strictEqual((await modPage("/mod/api/login", {username: "Mira", password: people.Mira, code: codeAt(secrets.Mira, usedStep.Mira)})).status, 200); + const miraMe = (await modPage("/mod/api/me")).data; + assert.strictEqual(miraMe.role, "moderator"); + assert.ok(miraMe.permissions.includes("player.ban")); + const halPage = webSession(); + assert.strictEqual((await halPage("/mod/api/login", {username: "Hal", password: people.Hal, code: codeAt(secrets.Hal, usedStep.Hal)})).status, 200); + const halMe = (await halPage("/mod/api/me")).data; + assert.strictEqual(halMe.role, "helper"); + assert.ok(!halMe.permissions.includes("player.ban")); + assert.strictEqual((await halPage("/mod/api/act", {username: "Pip", action: "ban", hours: 1, reason: "x"})).data.error, "Your role cannot do that."); + assert.match((await halPage("/mod/api/act", {username: "Mira", action: "silence", hours: 1})).data.error, /your rank or above/); + // a warning from the panel, and on the player's page + assert.match((await modPage("/mod/api/act", {username: "Pip", action: "warn", reason: "scamming", note: "fake trade"})).data.ok, /^Pip warned \(scamming\): warning 1\./); + assert.match((await modPage("/mod/api/act", {username: "Pip", action: "warn", reason: "nonsense"})).data.error, /reason/); + assert.deepStrictEqual((await untilPopup(pip.client, "fw")).slice(2, 4), ["fw", "9"]); + const pipPage = (await modPage("/mod/api/player?username=Pip")).data; + assert.strictEqual(pipPage.warnings, 1); + assert.deepStrictEqual([pipPage.warningList[0].reason, pipPage.warningList[0].note, pipPage.warningList[0].by], ["scamming", "fake trade", "Mira"]); + + // the panel's summon brings Pip to Mira (now in Sarepia) + assert.match((await modPage("/mod/api/act", {username: "Pip", action: "summon"})).data.ok || "", /^Pip was brought to /); + assert.strictEqual((await pip.client.untilXt("rj"))[3], SAREPIA); + + // everything above is in the moderators' log, the in-game ones marked so + const log = (await admin("/admin/api/moderators")).data.log.map(entry => `${entry.by} ${entry.action} ${entry.target}`); + for (const line of ["Mira summon (in game) Pip", "Hal silence (in game) Pip", "Mira goto (in game) Ann", "Mira warn (in game) Ann", + "Mira message (in game) Ann", "Mira kick (in game) Ann", "Mira warn Pip", "Mira summon Pip"]) { + assert.ok(log.includes(line), `missing from the log: ${line}\n${log.join("\n")}`); + } + + // the moderators' message box header has real line breaks, not "\\n" + const zlib = require("zlib"); + const {decode} = require("../lib/amf3.js"); + const stringsPath = require("../lib/cdn.js").hashedPath("defPacks/10230"); + const strings = decode(zlib.inflateRawSync(Buffer.from(await (await fetch(`${BASE}/${stringsPath}`)).arrayBuffer()))); + assert.strictEqual(strings[11134], "--Message From Moderator--\n\n"); + assert.ok(!strings[11135].includes("\\n")); + + for (const {client} of [mira, hal, pip]) { + client.socket.destroy(); + } +}; + +harness.withServer("staff test", HTTP_PORT, GAME_PORT, run).catch(err => { + console.error(err); + process.exit(1); +});