From 63dc43ebb3978e9757a361c6932cdab58538d5e3 Mon Sep 17 00:00:00 2001 From: Snipzil Date: Fri, 16 Oct 2026 02:46:16 -0400 Subject: [PATCH 01/14] test: bring the test suite up to date, and let it run on Windows The smoke, features, account and qol tests had fallen behind the server and failed before reaching their end. Each now checks what the server does on purpose today: - harness: the chat filter messages the server sends unasked ("xfl" after every login, "xfa" on the first room) are set aside like "zs". - smoke: a banned account's sign-in is refused with "account_banned", so the login-choices check uses a fresh account instead of the banned Carol. - features: a shop's name comes from its room file, read the first time anyone goes in (the first visitor sees a name made from the path). A scout goes in first until the file is read, so the check no longer depends on what an earlier run left in cache/. - account: a deleted account's name is held for NAME_HELD_DAYS, so taking it again right away is "username_taken". - qol: the commands page sets what to type in italics. And on Windows: withServer waits for the server process to exit before removing its data directory, and retries; the database stays locked until the process is gone, and the cleanup's EPERM hid the test's own result. All seven test files pass (smoke, features, account, qol, buddygames, restored, and staff in the next commit). Co-Authored-By: Claude Opus 5.5 --- test/account.js | 4 +++- test/features.js | 26 +++++++++++++++++++++++++- test/harness.js | 11 ++++++++++- test/qol.js | 2 +- test/smoke.js | 12 +++++++----- 5 files changed, 46 insertions(+), 9 deletions(-) diff --git a/test/account.js b/test/account.js index 77a28d7..286feba 100644 --- a/test/account.js +++ b/test/account.js @@ -219,7 +219,9 @@ const run = async () => { assert.strictEqual((await mine("me", undefined, ben)).status, 401); assert.strictEqual((await authenticate("Ben", "Password01")).status, 401); assert.ok(!(await panel("accounts", undefined, admin)).data.accounts.some(account => account.username === "Ben")); - assert.strictEqual((await register("Ben", 5)).status, 200); // the name is free again + // the name is held for a while (lib/accounts.js, NAME_HELD_DAYS): the + // players Ben met still know him by it. + assert.deepStrictEqual(await (await register("Ben", 5)).json(), {error: "username_taken"}); b2.socket.destroy(); a.socket.destroy(); b.socket.destroy(); diff --git a/test/features.js b/test/features.js index 65a5b84..7675b12 100644 --- a/test/features.js +++ b/test/features.js @@ -45,7 +45,7 @@ const wall = async body => (await postJson(`${BASE}/wall`, body)).json(); 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})}); - for (const username of ["Ann", "Ben", "Cat"]) { + for (const username of ["Ann", "Ben", "Cat", "Scout"]) { assert.strictEqual((await registerJson({username, password: "Password01"})).status, 200); } @@ -85,6 +85,30 @@ const run = async () => { await a.untilXt("ac"); await a.nextXt("il"); + // the shop's name and stalls come from its room file (lib/roominfo.js), + // read the first time anyone goes in; until then the name is made from its + // path. a scout goes in first and comes back until the file has been read, + // so that what follows does not depend on what an earlier run left in the + // cache. (the scout never enters the township, so a and b see nothing.) + const scoutAuth = await (await postJson(`${BASE}/authenticate`, {username: "Scout", password: "Password01"})).json(); + const scout = new harness.GameClient(GAME_PORT); + await scout.connect(); + assert.strictEqual((await scout.logIn("Scout", scoutAuth.auth_token)).status, "1"); + let scoutRoom = 1; + for (let tries = 0; ; tries++) { + scout.xt("rj", scoutRoom, "jamaa_township.clothes_shop#1", 1, 0, 0); + const there = await scout.untilXt("rj"); + if (there[14] === "Jam Mart Clothing") { + break; + } + assert.ok(tries < 40, `the shop's room file was never read (still "${there[14]}")`); + await new Promise(resolve => setTimeout(resolve, 500)); + scout.xt("rj", there[4], "sarepia.room_main#1", 1, 0, 0); + scoutRoom = (await scout.untilXt("rj"))[4]; + } + scout.socket.destroy(); + await new Promise(resolve => setTimeout(resolve, 300)); // gone before Ben walks in + // --- a shop's title is its room's name, as the id of the string that says so b.xt("rj", roomId, "jamaa_township.clothes_shop#1", 1, 0, 0); const shopRoom = await b.untilXt("rj"); diff --git a/test/harness.js b/test/harness.js index 7323600..e2caf58 100644 --- a/test/harness.js +++ b/test/harness.js @@ -100,6 +100,11 @@ class GameClient { this.varUpdates.push(fields); continue; } + // the chat filter settings ("xfl", after every login) and the one-time + // question which filter to use ("xfa", on the first room) come unasked. + if ((fields[0] === "xfl" || fields[0] === "xfa") && cmd !== fields[0]) { + continue; + } if (this.unasked(fields)) { continue; } @@ -165,8 +170,12 @@ const withServer = async (name, httpPort, gamePort, run) => { throw err; } finally { + // on Windows the database stays locked until the process has gone, so + // wait for it before throwing its files away. + const exited = server.exitCode !== null ? Promise.resolve() : new Promise(resolve => server.once("exit", resolve)); server.kill(); - fs.rmSync(dataDir, {recursive: true, force: true}); + await exited; + fs.rmSync(dataDir, {recursive: true, force: true, maxRetries: 10, retryDelay: 200}); } }; diff --git a/test/qol.js b/test/qol.js index 51545d2..787cc54 100644 --- a/test/qol.js +++ b/test/qol.js @@ -149,7 +149,7 @@ const run = async () => { assert.strictEqual(await owned(), before + 3); say(a, roomId, "!help"); // gone: the list is at /commands assert.strictEqual((await a.untilXt("uc"))[3], "!help"); - assert.match(await (await fetch(`${BASE}/commands`)).text(), /!outfit save NAME/); + assert.match(await (await fetch(`${BASE}/commands`)).text(), /!outfit save NAME<\/i>/); // the page sets what to type in italics // --- den undo, mail, music say(a, roomId, "!den undo"); diff --git a/test/smoke.js b/test/smoke.js index aee19c0..f28d00b 100644 --- a/test/smoke.js +++ b/test/smoke.js @@ -621,14 +621,16 @@ const run = async () => { // --- the custom client's login choices: honoured for that session only assert.strictEqual((await (await fetch(`${BASE}/flashvars`)).json()).loginChoices, true); - const chosen = await (await postJson(`${BASE}/authenticate`, {username: "Carol", password: "Password03", + // (a fresh account: Carol is banned by now, and a banned account's + // sign-in is refused with "account_banned", so it gets no token.) + assert.strictEqual((await registerJson({username: "Erin", password: "Password05"})).status, 200); + const chosen = await (await postJson(`${BASE}/authenticate`, {username: "Erin", password: "Password05", login_choices: {accountType: 0, isGuide: true, membershipDays: 12, isModerator: "yes"}})).json(); - // (Carol is banned from the game by now, so only the web side is checked.) assert.strictEqual((await (await fetch(`${BASE}/player`, {headers: {Authorization: `Bearer ${chosen.auth_token}`}})).json()).game_account_type, 0); - a.xt("ag", denId, "Carol", 0); + a.xt("ag", denId, "Erin", 0); assert.deepStrictEqual((await a.untilXt("ag")).slice(5, 7), ["0", "1"]); // account type, guide - await postJson(`${BASE}/authenticate`, {username: "Carol", password: "Password03"}); // and back to normal - a.xt("ag", denId, "Carol", 0); + await postJson(`${BASE}/authenticate`, {username: "Erin", password: "Password05"}); // and back to normal + a.xt("ag", denId, "Erin", 0); assert.deepStrictEqual((await a.untilXt("ag")).slice(5, 7), ["2", "0"]); // --- custom colours: an id for four RGB values, announced to everyone From 2fba9f1612a59248316c81888bb736b0487eb2a6 Mon Sep 17 00:00:00 2001 From: Snipzil Date: Fri, 16 Oct 2026 02:46:17 -0400 Subject: [PATCH 02/14] Staff roles with permissions, warnings, in-game staff commands Moderators were one flag on the account. Now an account can hold a staff role (lib/roles.js): helper, moderator or admin, each a list of named permissions, with a higher role holding everything below it. An account only marked `moderator` still counts as a moderator. Every staff action checks the permission it needs, and staff never act on staff of their own rank or above: - warnings: kept on the account (who, when, the reason, a note for staff), and shown to the player with the game's own warning popup for the reason ("fw": inappropriate behavior, bullying, personal information, scamming), which this server's strings already word as the Burrow Rules. - moderator panel: each action is checked against the role; new actions "warn" (with a reason and note), "summon" (bring a player to the room you are in) and "goto"; the player's page shows their warnings; GET /mod/api/me returns your role and permissions, and the page hides the buttons yours does not allow. - in the game: !staff, !summon, !goto, !kick, !silence (HOURS, 0, or off), !warn PLAYER [reason] [note], !warnings PLAYER and !message, for staff whose role allows each, written to the moderators' log like the panel's actions, marked "(in game)". To anyone else they are plain chat. Usernames with spaces work. - the login reply carries the player's own staffRole and staffPermissions (empty for everyone else), so a client can show staff tools only to staff. - admin panel: a role picker on the account, "role" on POST /admin/api/account, and GET /admin/api/roles listing what each allows. The old moderator switch still works. Also: the moderators' message box showed "--Message From Moderator--\n\n" with the "\n" as written (strings 11134 and 11135 keep it as two characters); they get real line breaks. Staff powers need 2FA turned on, as the moderator panel already did. In the game they come with the game session, which a trusted device opens without a code; requiring a recent code there is left for later. test/staff.js covers all of the above end to end. Co-Authored-By: Claude Opus 5.5 --- lib/commands.js | 203 +++++++++++++++++++++++++++++++++++++- lib/defpacks.js | 15 ++- lib/moderation.js | 31 +++++- lib/modpanel.js | 63 ++++++++++-- lib/panel.js | 34 +++++-- lib/roles.js | 89 +++++++++++++++++ lib/world.js | 35 +++++++ public/admin.html | 12 ++- public/mod.html | 50 +++++++++- test/staff.js | 245 ++++++++++++++++++++++++++++++++++++++++++++++ 10 files changed, 756 insertions(+), 21 deletions(-) create mode 100644 lib/roles.js create mode 100644 test/staff.js 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); +}); From 6563d5de999f84d19a4e6bcb93a56b11c91a5aa5 Mon Sep 17 00:00:00 2001 From: Snipzil Date: Fri, 16 Oct 2026 03:46:18 -0400 Subject: [PATCH 03/14] Custom items made while the server runs, and a Developer role Staff with the new items.create permission (admins, and the new Developer role) make clothing and den items from the game's own art: an existing item under a new id (50000 on), name, price, members-only flag and choice of its colours. No restart of the server or of anyone's game: - lib/customitems.js keeps them (custom_items table) and puts them into the server's tables and the packs new games fetch (defpacks.setCustomItem) - games already playing get the def rows in "xdi"; so does every game at login. The client adds them (ItemXtCommManager.addItemDefs, DenXtCommManager.addDenItemDefs, both now in swf-src; rebuild with tools/build-client.sh) - they are sold first in the two shops of oddities and found by the item finder; an item can be renamed, repriced, recoloured and taken off sale, never deleted (players may own it) - the moderator panel has an Items page; in game, "!item clothing|den ID NAME" and "!item list" - the Developer role holds only staff.list and items.create. The panel's pages that show players (players, chat, reports, requests, bans, paintings) now need player.view, which helpers and up have test/items.js covers it end to end, including a restart (withServer can keep its database for that). Co-Authored-By: Claude Opus 5.5 --- lib/admin.js | 6 +- lib/commands.js | 31 + lib/customitems.js | 229 +++++ lib/defpacks.js | 59 +- lib/modpanel.js | 62 ++ lib/roles.js | 9 +- lib/world.js | 15 +- public/admin.html | 3 +- public/mod.html | 184 +++- server.js | 2 + swf-src/AJClient.as | 25 + swf-src/DenXtCommManager.as | 1551 ++++++++++++++++++++++++++++++++++ swf-src/ItemXtCommManager.as | 1407 ++++++++++++++++++++++++++++++ swf-src/XtReplyDemuxer.as | 5 + test/harness.js | 10 +- test/items.js | 272 ++++++ test/staff.js | 2 +- tools/build-client.sh | 4 +- 18 files changed, 3853 insertions(+), 23 deletions(-) create mode 100644 lib/customitems.js create mode 100644 swf-src/DenXtCommManager.as create mode 100644 swf-src/ItemXtCommManager.as create mode 100644 test/items.js diff --git a/lib/admin.js b/lib/admin.js index 7361ba7..a0c573d 100644 --- a/lib/admin.js +++ b/lib/admin.js @@ -21,6 +21,7 @@ const MAX_FAVOURITES = 200; // finder items remembered per account const STARTER_ANIMALS = [1, 4, 5, 6, 7, 8, 13, 18, 24]; let catalog = null; +let catalogVersion = -1; // defpacks.customVersion() it was built at: staff add items as the server runs const buildCatalog = () => [ ...defpacks.clothingIds().map(id => { @@ -37,7 +38,10 @@ const buildCatalog = () => [ // items that account took most often come first, the latest first among // equals. (The in-game finder says whose search it is.) const search = (params, favourites = null) => { - catalog = catalog || buildCatalog(); + if (!catalog || catalogVersion !== defpacks.customVersion()) { + catalog = buildCatalog(); + catalogVersion = defpacks.customVersion(); + } const kind = params.get("kind") || "all"; const words = (params.get("q") || "").toLowerCase().split(/\s+/).filter(Boolean); const matches = catalog.filter(entry => (kind === "all" || entry.kind === kind) diff --git a/lib/commands.js b/lib/commands.js index b108b4d..a24d20d 100644 --- a/lib/commands.js +++ b/lib/commands.js @@ -2,6 +2,7 @@ const accounts = require("./accounts.js"); const chatlog = require("./chatlog.js"); +const customItems = require("./customitems.js"); const defpacks = require("./defpacks.js"); const disguises = require("./disguises.js"); const dens = require("./dens.js"); @@ -509,6 +510,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB const MAX_STAFF_HOURS = 24 * 365 * 10; const MAX_WARNING = 200; const MAX_WARNINGS_SHOWN = 5; + const MAX_ITEMS_LISTED = 8; const staffMay = (session, permission) => { const moderation = staffModeration(); @@ -563,6 +565,35 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB modlog.record(session.account.username, `${action} (in game)`, target.account.username, detail); const staffCommands = { + // "!item clothing|den ID NAME": a new item made from the game's item ID + // (lib/customitems.js), free, every colour of the one it is made from; + // everyone has it at once. the moderator panel's Items page does more. + // "!item list": the latest made. + item: { + permission: "items.create", + run(session, words) { + const usage = "Use: !item clothing|den ID NAME, or !item list"; + if ((words[0] || "").toLowerCase() === "list") { + const latest = customItems.list().slice(0, MAX_ITEMS_LISTED) + .map(entry => `${entry.id} ${entry.name} (${entry.kind === "den" ? "den" : "clothing"}${entry.inShop ? "" : ", off sale"})`); + tell(session, latest.length ? `Latest items made: ${latest.join("; ")}` : "No items made yet."); + return; + } + const kind = (words[0] || "").toLowerCase(); + if (!customItems.KINDS.includes(kind) || !/^\d+$/.test(words[1] || "") || words.length < 3) { + tell(session, usage); + return; + } + const result = customItems.create(kind, {base: words[1], name: words.slice(2).join(" ")}, session.account.username); + if (result.error) { + tell(session, result.error); + return; + } + const {item} = result; + tell(session, `Made ${item.name}, ${kind === "den" ? "den item" : "clothing"} ${item.id}. It is in the item finder now.`); + modlog.record(session.account.username, "item made (in game)", "", `${kind} ${item.id} ${item.name}`); + }, + }, staff: { permission: "staff.list", run(session) { diff --git a/lib/customitems.js b/lib/customitems.js new file mode 100644 index 0000000..bd06e41 --- /dev/null +++ b/lib/customitems.js @@ -0,0 +1,229 @@ +"use strict"; + +const accounts = require("./accounts.js"); +const defpacks = require("./defpacks.js"); + +// items the staff make while the server runs, with no restart of the server +// or of anybody's game. each is an existing item's art (the clothing piece +// or den item it is made from) under an id, name, price and colours of its +// own. the server's tables and the packs new games fetch have it at once +// (defpacks.setCustomItem); games already playing are sent its def row +// ("xdi", which the patched client adds to its tables), and so is every game +// at login, in case it was started before the item was made. +// +// an item is never removed, since players may have it: it can be taken out +// of the shop, renamed and repriced. + +// ids far above the game's own (clothing to about 4,600, den items to about +// 6,000), one range per pack; names go under localization ids above the +// server's other added strings (lib/defpacks.js ADDED_STRINGS, 9000001 on). +const FIRST_ID = 50000; +const STRING_BASE = {clothing: 9100000, den: 9200000}; +const KINDS = ["clothing", "den"]; +const MAX_NAME = 40; +const MAX_COST = 1000000; +const MAX_COLOURS = 16; +const MAX_ITEMS = 5000; // per kind +const CHUNK = 40; // def rows per "xdi" message +const TYPE_CLOTHING = "1"; +const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items that can be copied: plain, mannequin +const CURRENCY_GEMS = "0"; + +const SCHEMA = `CREATE TABLE IF NOT EXISTS custom_items ( + kind TEXT NOT NULL, id INTEGER NOT NULL, base INTEGER NOT NULL, name TEXT NOT NULL, + cost INTEGER NOT NULL, members INTEGER NOT NULL, colors TEXT NOT NULL, in_shop INTEGER NOT NULL, + created_by TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (kind, id))`; + +const items = new Map(KINDS.map(kind => [kind, new Map()])); // kind -> id -> entry +let made = 0; // entries in the order they were made (`seq`), for lists +let broadcast = () => {}; // (cmd, ...params) to every game playing; set by lib/world.js + +const db = () => accounts.database(); +const now = () => Math.floor(Date.now() / 1000); + +const baseDef = (kind, id) => (kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id)); + +// the def row of an entry: its base's row with its own id, name, price and +// colours, always on sale and marked new. +const rowOf = entry => { + const base = baseDef(entry.kind, entry.base); + const own = { + id: String(entry.id), + membersOnly: entry.members ? "1" : "0", + itemStatus: "1", + availabilityStartTime: "0", + availabilityEndTime: "0", + currencyType: CURRENCY_GEMS, + recycleValue: "0", + combinedCost: "", + }; + if (entry.kind === "den") { + return {...base, ...own, nameStrId: String(STRING_BASE.den + entry.id - FIRST_ID), cost: String(entry.cost)}; + } + return {...base, ...own, titleStrId: String(STRING_BASE.clothing + entry.id - FIRST_ID), value: String(entry.cost), colors: entry.colors.join(","), isGiftable: "1"}; +}; + +const apply = entry => defpacks.setCustomItem(entry.kind, rowOf(entry), entry.name, entry.inShop); + +// "xdi" [.., .., kind, json]: def rows with their names, as JSON. a field +// may not hold "%" (lib/sfs.js drops it), so a "%" in a name is written as +// JSON's %. +const messages = entries => { + const out = []; + for (const kind of KINDS) { + const rows = entries.filter(entry => entry.kind === kind).map(entry => ({...rowOf(entry), name: entry.name})); + for (let at = 0; at < rows.length; at += CHUNK) { + out.push([kind, JSON.stringify(rows.slice(at, at + CHUNK)).replace(/%/g, "\\u0025")]); + } + } + return out; +}; + +const announce = entry => { + for (const params of messages([entry])) { + broadcast("xdi", ...params); + } +}; + +const fromRow = row => ({ + kind: row.kind, id: row.id, base: row.base, name: row.name, cost: row.cost, members: row.members === 1, + colors: row.colors ? row.colors.split(",").map(Number) : [], inShop: row.in_shop === 1, createdBy: row.created_by, createdAt: row.created_at, +}); + +const load = () => { + db().exec(SCHEMA); + for (const row of db().prepare("SELECT * FROM custom_items ORDER BY rowid").all()) { + const entry = {...fromRow(row), seq: made++}; + if (!baseDef(entry.kind, entry.base)) { + console.log(`[custom items] ${entry.kind} ${entry.id} is made from ${entry.base}, which is not in the packs; left out`); + continue; + } + items.get(entry.kind).set(entry.id, entry); + apply(entry); + } + console.log(`[custom items] ${items.get("clothing").size} clothing, ${items.get("den").size} den items`); +}; + +// checks what staff typed. returns {error} or the cleaned values. +const NAME_PATTERN = /^[\p{L}\p{N} '&!?.,:()#+\-]+$/u; +const clean = (kind, fields, current = null) => { + const out = {}; + if (fields.name !== undefined || !current) { + const name = String(fields.name || "").trim().replace(/\s+/g, " "); + if (!name || name.length > MAX_NAME || !NAME_PATTERN.test(name)) { + return {error: `A name of 1 to ${MAX_NAME} letters, numbers, spaces and simple punctuation, please.`}; + } + out.name = name; + } + if (fields.cost !== undefined || !current) { + const cost = Number(fields.cost === undefined || fields.cost === "" ? 0 : fields.cost); + if (!Number.isInteger(cost) || cost < 0 || cost > MAX_COST) { + return {error: `A price from 0 to ${MAX_COST} gems, please.`}; + } + out.cost = cost; + } + if (fields.members !== undefined || !current) { + out.members = fields.members === true || fields.members === "1" || fields.members === 1; + } + if (fields.inShop !== undefined || !current) { + out.inShop = fields.inShop === undefined ? true : fields.inShop === true || fields.inShop === "1" || fields.inShop === 1; + } + if (kind === "clothing" && (fields.colors !== undefined || !current)) { + const base = baseDef(kind, current ? current.base : fields.base); + const baseColours = String(base.colors).split(",").map(Number); + let colors = fields.colors; + if (colors === undefined || colors === null || colors === "") { + colors = baseColours; + } + else { + colors = (Array.isArray(colors) ? colors : String(colors).split(",")).map(value => Number(String(value).trim())); + } + // a colour is a packed palette number, as in the packs (or a custom colour + // id, lib/colours.js). + if (colors.length === 0 || colors.length > MAX_COLOURS || !colors.every(value => Number.isInteger(value) && value >= 0 && value <= 0xFFFFFFFF)) { + return {error: `1 to ${MAX_COLOURS} colours, each a number as the packs have them.`}; + } + out.colors = colors; + } + return out; +}; + +// makes an item from `base`, an existing clothing piece or den item. +// returns {item} or {error}. +const create = (kind, fields, by) => { + if (!KINDS.includes(kind)) { + return {error: "The kind is clothing or den."}; + } + const baseId = Number(fields.base); + const base = Number.isInteger(baseId) ? baseDef(kind, baseId) : null; + if (!base || baseId >= FIRST_ID) { + return {error: `No ${kind === "den" ? "den item" : "clothing"} with the id ${fields.base} to make it from (it must be one of the game's own).`}; + } + if (kind === "clothing" && base.type !== TYPE_CLOTHING) { + return {error: `${baseId} is a body part, not clothing.`}; + } + if (kind === "den" && !OFFERED_SPECIAL_TYPES.includes(base.specialType)) { + return {error: `Den item ${baseId} does something of its own (a portal, a game, ...) and cannot be copied.`}; + } + if (items.get(kind).size >= MAX_ITEMS) { + return {error: "There are as many custom items of that kind as there can be."}; + } + const values = clean(kind, {...fields, base: baseId}); + if (values.error) { + return values; + } + const id = Math.max(FIRST_ID - 1, ...items.get(kind).keys()) + 1; + const entry = {kind, id, base: baseId, colors: [], ...values, createdBy: String(by), createdAt: now(), seq: made++}; + db().prepare("INSERT INTO custom_items (kind, id, base, name, cost, members, colors, in_shop, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") + .run(kind, id, baseId, entry.name, entry.cost, entry.members ? 1 : 0, entry.colors.join(","), entry.inShop ? 1 : 0, entry.createdBy, entry.createdAt); + items.get(kind).set(id, entry); + apply(entry); + announce(entry); + return {item: entry}; +}; + +// changes the name, price, members-only, colours or whether it is on sale. +const update = (kind, id, fields) => { + const entry = items.has(kind) && items.get(kind).get(Number(id)); + if (!entry) { + return {error: "No such custom item."}; + } + const values = clean(kind, fields, entry); + if (values.error) { + return values; + } + Object.assign(entry, values); + db().prepare("UPDATE custom_items SET name = ?, cost = ?, members = ?, colors = ?, in_shop = ? WHERE kind = ? AND id = ?") + .run(entry.name, entry.cost, entry.members ? 1 : 0, entry.colors.join(","), entry.inShop ? 1 : 0, kind, entry.id); + apply(entry); + announce(entry); + return {item: entry}; +}; + +const list = () => KINDS.flatMap(kind => [...items.get(kind).values()]) + .sort((one, other) => other.seq - one.seq); + +module.exports = { + KINDS, + FIRST_ID, + load, + create, + update, + list, + get: (kind, id) => (items.has(kind) && items.get(kind).get(Number(id))) || null, + // the base an item's art is from, for a list showing what each is. + baseName: entry => { + const def = baseDef(entry.kind, entry.base); + return def ? defpacks.string(entry.kind === "den" ? def.nameStrId : def.titleStrId) || String(def.abbrName || entry.base) : String(entry.base); + }, + // every custom item, for a game logging in. + sendAll(session) { + for (const params of messages(list().reverse())) { + session.sendXt("xdi", -1, ...params); + } + }, + // lib/world.js says how to reach every game playing. + connect(broadcastXt) { + broadcast = broadcastXt; + }, +}; diff --git a/lib/defpacks.js b/lib/defpacks.js index e014a6e..04c2acb 100644 --- a/lib/defpacks.js +++ b/lib/defpacks.js @@ -188,7 +188,26 @@ const withLineBreaks = pack => { return pack; }; -const withAddedStrings = pack => withLineBreaks(withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings()))); +// items the staff make while the server runs (lib/customitems.js): an +// existing item's art under a new id, name and price. their rows and names +// are kept here, and go into the packs like the rows above, after the +// renaming (a name staff chose is left as they wrote it). +const customRows = new Map([[DEF_ITEM, new Map()], [DEF_DEN_ITEM, new Map()]]); // pack -> id -> row +const customStrings = {}; // localization id -> name +const customInShop = {clothing: new Set(), den: new Set()}; // ids on sale +let customVersion = 0; // goes up with every change, for anything that keeps a list of items + +const withCustomRows = id => pack => { + const at = new Map(Object.entries(pack).map(([key, def]) => [String(def.id), key])); + let next = Math.max(-1, ...Object.keys(pack).map(Number).filter(Number.isInteger)) + 1; + for (const row of customRows.get(id).values()) { + // a changed row replaces the one the pack was made with. + pack[at.has(row.id) ? at.get(row.id) : next++] = {...row}; + } + return pack; +}; + +const withAddedStrings = pack => Object.assign(withLineBreaks(withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings()))), customStrings); // the extra music tracks (lib/extramusic.js), as den items like the // official tracks. @@ -249,8 +268,8 @@ const SHARED_CHANGES = new Map([ [DEF_ROOM, withRestoredRooms], [DEF_PARTY, withRestoredParties], [DEF_DEN_ROOM, withoutPrices(DEF_DEN_ROOM, withAddedDens)], - [DEF_DEN_ITEM, withoutPrices(DEF_DEN_ITEM, withExtraMusic)], - [DEF_ITEM, withoutPrices(DEF_ITEM)], + [DEF_DEN_ITEM, withoutPrices(DEF_DEN_ITEM, pack => withCustomRows(DEF_DEN_ITEM)(withExtraMusic(pack)))], + [DEF_ITEM, withoutPrices(DEF_ITEM, withCustomRows(DEF_ITEM))], [DEF_DIAMOND, withoutPrices(DEF_DIAMOND)], [DEF_PET, withoutPrices(DEF_PET)], [DEF_LOCALIZATION_EN, withAddedStrings], @@ -455,8 +474,42 @@ const init = async () => { console.log(`[defs] ${avatarDefs.size} avatars, ${roomDefsByPath.size} rooms, ${clothingIds.length} clothing items, ${denItemIds.length} den items, ${petIds.length} pets`); }; +// puts a custom item (lib/customitems.js) in, or changes one already in: +// `kind` "clothing" or "den", `row` its full def row (strings, as in the +// packs), `name` its English name under the row's string id. the server's +// tables have it at once, and the packs clients fetch are made again. +// `inShop` false takes it out of the shop (the ones players have still draw). +const setCustomItem = (kind, row, name, inShop = true) => { + const pack = kind === "den" ? DEF_DEN_ITEM : DEF_ITEM; + const id = Number(row.id); + const stringId = kind === "den" ? row.nameStrId : row.titleStrId; + customRows.get(pack).set(id, row); + customStrings[stringId] = name; + strings[stringId] = name; + stringIds = null; + if (packs.has(pack)) { + packs.set(pack, [...packs.get(pack).filter(def => Number(def.id) !== id), row]); + } + if (kind === "den") { + denItemDefs.set(id, row); + denItemIds = denItemIds.includes(id) ? denItemIds : [...denItemIds, id]; + } + else { + itemDefs.set(id, row); + clothingIds = clothingIds.includes(id) ? clothingIds : [...clothingIds, id]; + } + customInShop[kind][inShop ? "add" : "delete"](id); + clientPackBodies.delete(pack); + clientPackBodies.delete(DEF_LOCALIZATION_EN); + customVersion++; +}; + module.exports = { init, + setCustomItem, + // the custom items on sale, the newest first. + customShopIds: kind => [...customInShop[kind]].reverse(), + customVersion: () => customVersion, load, itemDef: id => itemDefs.get(Number(id)), clothingIds: () => clothingIds, diff --git a/lib/modpanel.js b/lib/modpanel.js index cd10252..f25e846 100644 --- a/lib/modpanel.js +++ b/lib/modpanel.js @@ -8,6 +8,8 @@ const bans = require("./bans.js"); const captcha = require("./captcha.js"); const chatlog = require("./chatlog.js"); const config = require("../config.js"); +const customItems = require("./customitems.js"); +const defpacks = require("./defpacks.js"); const limits = require("./limits.js"); const manage = require("./manage.js"); const masterpieces = require("./masterpieces.js"); @@ -376,7 +378,25 @@ const handle = async (req, res, url, from, web) => { case "GET /mod/api/me": reply(200, {username: mod.username, role: roles.roleOf(mod), permissions: roles.permissionsOf(mod)}); return; + } + // custom items (lib/customitems.js), for whoever may make them. + if (url.pathname.startsWith("/mod/api/items")) { + if (!roles.can(mod, "items.create")) { + reply(403, {error: "Your role does not allow that."}); + return; + } + itemRoutes(route, url, body, reply, done, mod); + return; + } + // everything else shows players and what they did: not for a role that + // only makes things. + if (!roles.can(mod, "player.view")) { + reply(403, {error: "Your role does not allow that."}); + return; + } + + switch (route) { 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}); @@ -511,6 +531,48 @@ const handle = async (req, res, url, from, web) => { } }; +// GET /mod/api/items: the custom items, the newest first. +// GET /mod/api/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. +// POST /mod/api/items {action: "create", kind, base, name, cost, members, colors} +// or {action: "update", kind, id, and any of name, cost, members, colors, inShop}. +const itemRoutes = (route, url, body, reply, done, mod) => { + switch (route) { + case "GET /mod/api/items": + reply(200, {items: customItems.list().map(entry => ({...entry, baseName: customItems.baseName(entry)})), firstId: customItems.FIRST_ID}); + return; + case "GET /mod/api/items/base": { + const kind = url.searchParams.get("kind") === "den" ? "den" : "clothing"; + const id = Number(url.searchParams.get("id")); + const def = kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id); + if (!def || id >= customItems.FIRST_ID || (kind === "clothing" && def.type !== "1")) { + reply(404, {error: `No ${kind === "den" ? "den item" : "clothing"} with that id.`}); + return; + } + reply(200, kind === "den" + ? {kind, id, name: defpacks.string(def.nameStrId) || def.abbrName, art: def.abbrName, cost: Number(def.cost)} + : {kind, id, name: defpacks.string(def.titleStrId), art: Number(def.layerDefId), cost: Number(def.value), colors: String(def.colors).split(",").map(Number)}); + return; + } + case "POST /mod/api/items": { + const kind = String(body.kind || ""); + const result = body.action === "update" + ? customItems.update(kind, body.id, body) + : body.action === "create" ? customItems.create(kind, body, mod.username) : {error: "Unknown action."}; + if (result.error) { + done(result); + return; + } + const {item} = result; + done({ok: `${item.name} (${item.kind === "den" ? "den item" : "clothing"} ${item.id}) ${body.action === "update" ? "changed" : "made"}.`}, + body.action === "update" ? "item changed" : "item made", "", `${item.kind} ${item.id} ${item.name}`); + return; + } + default: + reply(404, {error: "not_found"}); + } +}; + 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)); diff --git a/lib/roles.js b/lib/roles.js index daab1d8..3c554a7 100644 --- a/lib/roles.js +++ b/lib/roles.js @@ -14,6 +14,7 @@ const totp = require("./totp.js"); // higher up, and for the admin in the end. const PERMISSIONS = { + "player.view": "see players, chat, reports, requests, bans and paintings in the moderator panel", "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)", @@ -23,13 +24,17 @@ const PERMISSIONS = { "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", + "items.create": "make new items from the game's art, and change them (!item)", }; -const HELPER = ["staff.list", "player.warn", "player.goto", "chat.silence"]; +const HELPER = ["player.view", "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 ADMIN = [...MODERATOR, "items.create"]; +// a developer makes things, and moderates nobody. +const DEVELOPER = ["staff.list", "items.create"]; const ROLES = { + developer: {rank: 1, label: "Developer", permissions: DEVELOPER}, helper: {rank: 1, label: "Helper", permissions: HELPER}, moderator: {rank: 2, label: "Moderator", permissions: MODERATOR}, admin: {rank: 3, label: "Admin", permissions: ADMIN}, diff --git a/lib/world.js b/lib/world.js index 96123e4..dbd446d 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 customItems = require("./customitems.js"); const roles = require("./roles.js"); const commandModule = require("./commands.js"); const limits = require("./limits.js"); @@ -314,6 +315,9 @@ const login = (session, msg) => { for (const chunk of colours.chunks()) { session.sendXt("xcc", -1, chunk.length, ...chunk.flat()); } + // and the items staff have made (lib/customitems.js), for a game started + // before they were. + customItems.sendAll(session); sendFilter(session); buddies.announce(account); }; @@ -423,6 +427,8 @@ const sortStock = () => { // has the den items, the one in the Zios archives the clothing. see // oddDenItemIds in lib/defpacks.js. const ODDITY_SHOPS = new Map([[396, () => defpacks.oddDenItemIds()], [666, () => defpacks.oddClothingIds()]]); +// the items staff have made (lib/customitems.js) are sold there too, first. +const CUSTOM_ITEM_SHOPS = new Map([[396, "den"], [666, "clothing"]]); const ticketStock = kind => sortStock()[kind]; // the den shops of the lands (Coral Canyons, Deep Blue) and the one inside // a den: lists that mix kinds, selling den rooms. @@ -475,6 +481,13 @@ const makeColour = (account, rgbs, asker = null) => { return entry; }; +// a message for every game playing (custom items, lib/customitems.js). +customItems.connect((cmd, ...params) => { + for (const session of online.values()) { + session.sendXt(cmd, -1, ...params); + } +}); + // the account's chat filter, for its game to apply: [chosen, level, mode, own words]. const sendFilter = session => { const {filter} = session.account; @@ -688,7 +701,7 @@ const handlers = { else if (ODDITY_SHOPS.has(Number(listId))) { // what the shop really sold comes first. const real = shopStock.list(listId, type); - entries = [...new Set([...(real ? real.entries : []), ...ODDITY_SHOPS.get(Number(listId))()])]; + entries = [...new Set([...defpacks.customShopIds(CUSTOM_ITEM_SHOPS.get(Number(listId))), ...(real ? real.entries : []), ...ODDITY_SHOPS.get(Number(listId))()])]; } else if (Number(listId) === DIAMOND_DEN_LIST) { entries = defpacks.diamondIds().filter(id => { diff --git a/public/admin.html b/public/admin.html index f0c0521..8ea62b2 100644 --- a/public/admin.html +++ b/public/admin.html @@ -401,6 +401,7 @@ + + + + + +

      + +
      +

      The new item

      +
      +
      +
      +
      +
      + +
      +
      + +

      + +
      +

      Items made

      +
      + + +
      IdNameMade fromPriceBy
      + +
      + +