feat(server): staff tools, player-made items, picture safety, chat, multiplayer games

Staff and moderation
- Invisible staff (!invisible, "xiv"): hidden from players, half see-through
  to other staff, cannot chat while hidden. New permission staff.invisible.
- Summon and goto land on the player's exact spot ("xgt" before the move).
- Custom warnings (!warn PLAYER custom TEXT), shown in the warning popup.
- Mod notes (!note, !notes; lib/modnotes.js), on the player page and the
  dashboard.
- Granular permissions: per-role overrides (setting rolePermissions) and
  per-account grants and denies, applied live to staff who are playing
  (refreshStaff re-sends "xsp").
- Item control (lib/itemcontrol.js): lock items out of the item finder
  (!lock, !unlock, !locked), take an item from a player (!take), delete a
  custom item from the game and every inventory.
- GET items/find: search any item by name or id, marked locked, for the
  dashboards' quick lock.

Player-made items (lib/playeritems.js, "xcm")
- The Item Maker: make, rename, set the worn look, delete. 5 a day, 20 in all;
  names go through the name filter.
- Admin switches: Item Maker on/off, new items wait for approval, and a
  separate switch (on by default) that holds every player-uploaded picture
  for a moderator. Review queue for items.approve (moderator and up).
- Pictures (lib/itemart.js): PNG, JPEG and GIF cleaned of metadata, BMP
  converted to PNG; 512px and 300KB at most once cleaned.
- Worn as the maker chooses: a sticker (the picture) or a texture (the
  item's shape painted with the picture).

Picture safety
- A picture waiting for approval is never served publicly: /itemart/ 404s it,
  and it is only shown through /account|/mod|/admin/api/itemart to its maker
  and to staff who review or make items.
- A picture turned away or taken off is remembered by SHA-256 and cannot be
  uploaded again.
- Three strikes: three pictures turned away stops a player's uploads until a
  moderator lets them again. Staff can stop or allow uploads by hand.
- Accounts under 24 hours old cannot upload pictures (AJ_ITEM_ART_MIN_HOURS);
  uploads capped at 10 a day.
- Optional Google Cloud Vision SafeSearch (lib/image-moderation.js) for item
  pictures and Art Studio paintings when AJ_GOOGLE_VISION_API_KEY is set;
  fails closed when the scanner is unreachable.

Chat
- Emoji: Twemoji pictures served at /emoji/<codepoints>.png and cached in
  data/emoji (lib/emoji.js).
- Smart spam filtering before the word filter (lib/chatspam.js): long runs of
  one character, repeated words and lines, huge words and emoji floods are
  tidied, and repeats within 20 seconds are dropped.
- Typing indicator: "xty" is passed on to everyone in the room who can see
  the player, at most every 2 seconds.

Games (lib/minigames.js)
- Room games can be played together: a MULTIPLAYER table gives a game a
  waiting list (Single Player / Multiplayer). Players in the same room are
  matched, taken into the game together, and each one's moves are relayed to
  the others. Gem Breaker is the first: two players, "pos", "shoot" and
  "playerLost" relayed.
- Gem Breaker's start message now lists each player's id. Without it no
  player counted as local, so even single player could not aim.

Other
- Players stay connected through the client's new 75-minute AFK limit
  (idleTimeoutMs 80 minutes).
- Jam-a-Grams carry custom items and colours; Jammer Wall avatar photos are
  validated (walls.js photoParam).
- Weak passwords refused (common words, or containing the username).
- Code-scanning fixes: every logged value goes through logText
  (lib/logtext.js) against log injection, HSTS, path-only error logs, a
  single file read in lib/names.js.

Tests: items (pictures, approval, strikes, re-upload refusal, the hidden
waiting picture, the dashboard search), staff (invisibility, goto and summon
spots, custom warnings, notes), buddygames (two-player Gem Breaker, the
typing relay), and updates for main's verified badge and spawn rooms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
SnipzilandClaude Opus 5.5 committed 2026-10-17 21:44:10 -04:00
1 parent da7eb9af58
commit e05565787f
50 files changed
+2904 -277

No files matched your search

+191 -23
View File
@@ -1,11 +1,17 @@
"use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto");
const fs = require("fs");
const http = require("http");
const https = require("https");
const path = require("path");
const accounts = require("./accounts.js");
const customItems = require("./customitems.js");
const itemArt = require("./itemart.js");
const emoji = require("./emoji.js");
const modlog = require("./modlog.js");
const roles = require("./roles.js");
const admin = require("./admin.js");
const bans = require("./bans.js");
const captcha = require("./captcha.js");
@@ -139,6 +145,92 @@ const formParts = (contentType, body) => {
return parts;
};
// a custom item's picture set or taken away (?kind=&id=[&remove=1], the
// picture as the body): by its maker, or by staff who make items. who asks
// is the holder of a game's token (/api/itemart?token=, the client's Item
// Maker), or `signedIn` (req) -> account: the account page's or the
// moderator panel's session, whose cookies only go to their own paths
// (/account/api/itemart, /mod/api/itemart), from this server's own pages.
// every answer is 200, with {ok} or {error}: the game's Flash cannot read
// the body of any other.
// `adminSignedIn` (req) -> boolean: the admin panel's session, which acts as
// staff who make items, and is written down as "admin".
const itemArtUpload = async (req, res, url, from, signedIn = null, adminSignedIn = null) => {
if ((req.method === "GET" || req.method === "HEAD") && (signedIn || adminSignedIn)) {
itemArtView(req, res, url, signedIn, adminSignedIn);
return;
}
if (req.method !== "POST" || !limits.originAllowed(req)) {
send(res, 200, {error: "forbidden"});
return;
}
const token = url.searchParams.get("token");
const holder = token ? accounts.byToken(token) : null;
const asAdmin = Boolean(adminSignedIn && adminSignedIn(req));
const account = asAdmin ? null : signedIn ? signedIn(req) : holder && world.moderation.banRemaining(holder) === 0 ? holder : null;
if (!account && !asAdmin) {
send(res, 200, {error: "Sign in first."});
return;
}
const kind = url.searchParams.get("kind");
const entry = customItems.get(kind, url.searchParams.get("id"));
if (!entry) {
send(res, 200, {error: "No such custom item."});
return;
}
const staffMay = asAdmin || roles.can(account, "items.create");
if (!staffMay && entry.ownerId !== account.id) {
send(res, 200, {error: "That is not one of your items."});
return;
}
const playerItems = require("./playeritems.js");
const refusal = staffMay || url.searchParams.get("remove") === "1" ? null : playerItems.uploadRefusal(account, from.local);
if (refusal) {
send(res, 200, refusal);
return;
}
if (!from.local && !asAdmin && !artUploads.allow(account.id)) {
send(res, 200, {error: "Too many pictures today. Try again tomorrow."});
return;
}
let result;
if (url.searchParams.get("remove") === "1") {
result = itemArt.remove(kind, entry.id);
}
else {
const data = await readBody(req, itemArt.MAX_UPLOAD + 1).catch(() => null);
// a player's own picture waits for a moderator unless the admin says not;
// one turned away before may not come back.
const waits = !staffMay && playerItems.pictureWaits();
result = data ? await itemArt.set(kind, entry.id, data, waits, staffMay ? null : playerItems.pictureRefused)
: {error: `That picture is too big: ${Math.round(itemArt.MAX_UPLOAD / 1024 / 1024)} MB at most.`};
}
if (result.ok) {
const owner = entry.ownerId === null ? null : accounts.byId(entry.ownerId);
modlog.record(asAdmin ? "admin" : account.username, url.searchParams.get("remove") === "1" ? "item picture removed" : "item picture set",
owner && owner !== account ? owner.username : "", `${kind} ${entry.id} ${entry.name}`);
}
send(res, 200, result);
};
// a picture still waiting for a moderator, which /itemart/ does not serve:
// to its maker (the account page) and to staff who review or make items.
const itemArtView = (req, res, url, signedIn, adminSignedIn) => {
res.setHeader("Cache-Control", "private, no-store");
const asAdmin = Boolean(adminSignedIn && adminSignedIn(req));
const account = asAdmin ? null : signedIn ? signedIn(req) : null;
const entry = customItems.get(url.searchParams.get("kind"), url.searchParams.get("id"));
const allowed = entry && (asAdmin || (account && (entry.ownerId === account.id || roles.can(account, "items.approve") || roles.can(account, "items.create"))));
const picture = allowed ? itemArt.file(entry.kind, entry.id, true) : null;
if (!picture) {
send(res, 404, "Not found", "text/plain");
return;
}
res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox");
res.setHeader("X-Content-Type-Options", "nosniff");
send(res, 200, picture.data, `image/${picture.type}`);
};
const send = (res, status, body, type = "application/json") => {
const data = Buffer.isBuffer(body) ? body : Buffer.from(typeof body === "string" ? body : JSON.stringify(body));
res.writeHead(status, {"Content-Type": type, "Content-Length": data.length});
@@ -156,6 +248,8 @@ const MISSING_ASSET_SECONDS = 600; // how long a client may keep the CDN's "no s
const cacheMisses = limits.limiter(config.cacheMissesPerTenMinutes, TEN_MINUTES_MS); // files fetched from the official CDN for one address
const errorReports = limits.limiter(config.errorReportsPerMinute, 60000);
const paintingPosts = limits.limiter(60, TEN_MINUTES_MS); // per address; each also needs a token from the game
const artUploads = limits.limiter(10, 24 * 3600000); // custom items' pictures, per account a day
const emojiFetches = limits.limiter(600, TEN_MINUTES_MS); // emoji pictures not kept yet, asked of the upstream, per address
const PAINTING_PATH = /^\/masterpieces\/([0-9a-f-]{36})$/;
// where clients ask for the HUD artwork; ours is a changed copy.
@@ -372,7 +466,7 @@ const renameAndSignIn = (res, body, from) => {
manage.forget(account);
accounts.recordLogin(account, "launcher", from.address);
accounts.save(account);
console.log(`[accounts] a rejected username was replaced by "${account.username}"`);
console.log(`[accounts] a rejected username was replaced by "${logText(account.username)}"`);
accounts.setLoginChoices(account, body.login_choices);
const token = accounts.issueToken(account);
send(res, 200, {auth_token: token, refresh_token: token, device_token: entry.deviceToken});
@@ -392,36 +486,57 @@ const authenticate = async (req, res, from) => {
send(res, 426, {error_code: 101, error: "client_outdated"});
return;
}
const byRefresh = body.refresh_token !== undefined;
const accountKey = String(body.username).trim().toLowerCase();
if (!from.local && failuresByAddress.blocked(from.key)) {
send(res, 429, {error_code: 429, error: "too_many_attempts"});
return;
}
// A saved sign-in ("remember me"): the account its token is good for,
// which is what the rest goes by. a token is only ever given after a
// whole sign-in (password, captcha and 2FA code), so one that is good
// stands in for them; one that is not is refused here, whatever else
// the request says. (Whether the request offers a token is not what
// decides: only the server's own answer for it.)
if (body.refresh_token !== undefined) {
const saved = accounts.byToken(body.refresh_token);
if (!saved) {
failuresByAddress.record(from.key);
// error_code 100 = expired refresh token
send(res, 401, {error_code: 100});
return;
}
await signInChecked(res, body, from, saved, true, device);
return;
}
// a password is not looked at before the captcha. the custom client
// knows these errors; the official launcher shows them as a wrong password.
const captchaProblem = byRefresh ? null : await captcha.check(body, from, "login", accounts.byName(accountKey));
const captchaProblem = await captcha.check(body, from, "login", accounts.byName(accountKey));
if (captchaProblem) {
send(res, captchaProblem === "captcha_unavailable" ? 503 : 401, {error_code: 101, error: captchaProblem});
return;
}
const account = byRefresh
? accounts.byToken(body.refresh_token)
: await accounts.authenticateAsync(body.username, body.password);
const account = await accounts.authenticateAsync(body.username, body.password);
if (!account) {
failuresByAddress.record(from.key);
if (!byRefresh) {
// A wrong password shows in the account's own login history.
const tried = accounts.byName(accountKey);
if (tried) {
accounts.recordLogin(tried, "launcher", from.address, false);
accounts.save(tried);
}
// A wrong password shows in the account's own login history.
const tried = accounts.byName(accountKey);
if (tried) {
accounts.recordLogin(tried, "launcher", from.address, false);
accounts.save(tried);
}
// error_code 100 = expired refresh token, 101 = wrong credentials
send(res, 401, {error_code: byRefresh ? 100 : 101});
// error_code 101 = wrong credentials
send(res, 401, {error_code: 101});
return;
}
await signInChecked(res, body, from, account, false, device);
};
// the rest of a sign-in, for an account whose password was right (`saved`
// false) or whose saved sign-in's token was good (`saved` true; then it is
// not asked for a 2FA code again, and the token it has is the one it keeps).
// `device`: the computer it is on (lib/devices.js), or null for a client that does not say.
const signInChecked = async (res, body, from, account, saved, device) => {
const byRefresh = saved === true;
// banned: said here, with how long is left (-1 for good), where a client
// can show it. the game itself would only be refused at its socket with
// the one line it has for that, which says neither. the password (or the
@@ -444,7 +559,7 @@ const authenticate = async (req, res, from) => {
// account was seen on.
const deviceBan = device ? devices.banOf(device) : devices.banOfAccount(account);
if (deviceBan) {
console.log(`[devices] "${account.username}" refused: hardware banned (ban ${deviceBan.id})`);
console.log(`[devices] "${logText(account.username)}" refused: hardware banned (ban ${logText(deviceBan.id)})`);
send(res, 401, {error_code: 101, error: "device_banned", banned_seconds: world.moderation.PERMANENT, ban_reason: deviceBan.reason});
return;
}
@@ -514,6 +629,10 @@ const player = (req, res) => {
};
const handle = async (req, res) => {
// over https, browsers are told to keep to it (a year)
if (config.secureCookies) {
res.setHeader("Strict-Transport-Security", "max-age=31536000");
}
const url = new URL(req.url, config.baseUrl);
const route = `${req.method} ${url.pathname}`;
@@ -553,10 +672,20 @@ const handle = async (req, res) => {
send(res, 404, "Not found", "text/plain");
return;
}
if (url.pathname === "/admin/api/itemart") {
res.setHeader("Cache-Control", "no-store");
await itemArtUpload(req, res, url, from, null, panel.signedIn);
return;
}
await panel.handle(req, res, url, from, {send, readJson});
return;
}
if (isAccount && url.pathname === "/account/api/itemart") {
res.setHeader("Cache-Control", "no-store");
await itemArtUpload(req, res, url, from, manage.signedInAs);
return;
}
if (isAccount) {
await manage.handle(req, res, url, from, {send, readJson});
return;
@@ -564,6 +693,11 @@ const handle = async (req, res) => {
// and the moderator panel (lib/modpanel.js), which is there for anyone to
// reach: its moderators are players, wherever they are.
if (isMod && url.pathname === "/mod/api/itemart") {
res.setHeader("Cache-Control", "no-store");
await itemArtUpload(req, res, url, from, modpanel.signedInAs);
return;
}
if (isMod) {
await modpanel.handle(req, res, url, from, {send, readJson});
return;
@@ -589,6 +723,39 @@ const handle = async (req, res) => {
return;
}
// custom items' own pictures (lib/itemart.js): served as the picture
// they are and nothing else.
const artPath = /^\/itemart\/(clothing|den)\/(\d{1,9})\.png$/.exec(url.pathname);
if (artPath && (req.method === "GET" || req.method === "HEAD")) {
const picture = itemArt.file(artPath[1], artPath[2]);
if (!picture) {
send(res, 404, "Not found", "text/plain");
return;
}
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox");
res.setHeader("Content-Disposition", "inline");
send(res, 200, picture.data, `image/${picture.type}`);
return;
}
// emoji pictures for chat bubbles (lib/emoji.js)
const emojiPath = /^\/emoji\/([0-9a-f-]{2,80})\.png$/.exec(url.pathname);
if (emojiPath && (req.method === "GET" || req.method === "HEAD")) {
const picture = await emoji.get(emojiPath[1], () => from.local || emojiFetches.allow(from.key));
if (!picture) {
send(res, 404, "Not found", "text/plain");
return;
}
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox");
send(res, 200, picture, "image/png");
return;
}
if (url.pathname === "/api/itemart") {
await itemArtUpload(req, res, url, from);
return;
}
if (url.pathname.startsWith("/api/")) {
// the item finder's API changes accounts, so other sites open in a
// browser on this machine must not be able to call it.
@@ -732,7 +899,7 @@ const handle = async (req, res) => {
if (trace ? config.logPackets : from.local || errorReports.allow(from.key)) {
const again = trace ? "" : repeatedError(`${section} ${message}`);
if (again !== null) {
console.log(`[${trace ? "client-trace" : "client-error"}] (${section}) ${message}${again}`);
console.log(`[${logText(trace ? "client-trace" : "client-error")}] (${logText(section)}) ${logText(message)}${logText(again)}`);
if (!trace) {
keepClientError(`${new Date().toISOString()} (${section}) ${message}${again}\n`);
}
@@ -755,7 +922,7 @@ const handle = async (req, res) => {
return;
}
const parts = formParts(req.headers["content-type"], await readBody(req, masterpieces.MAX_IMAGE_BYTES + 16 * 1024));
const uuid = masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image"));
const uuid = await masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image"));
send(res, 200, uuid ? {success: true, uuid} : {success: false});
return;
}
@@ -771,13 +938,13 @@ const handle = async (req, res) => {
}
if (req.method !== "GET" && req.method !== "HEAD") {
console.log(`[http] unhandled ${route}`);
console.log(`[http] unhandled ${logText(route)}`);
send(res, 404, {error: "not_found"});
return;
}
if (config.logPackets) {
console.log(`[http] GET ${url.pathname}`);
console.log(`[http] GET ${logText(url.pathname)}`);
}
// asset SWFs import their fonts from this fixed path next to the game page;
@@ -843,7 +1010,7 @@ const handle = async (req, res) => {
res.setHeader("Cache-Control", `public, max-age=${MISSING_ASSET_SECONDS}`);
}
else {
console.log(`[http] 404 ${url.pathname}`);
console.log(`[http] 404 ${logText(url.pathname)}`);
}
send(res, 404, "Not found", "text/plain");
return;
@@ -855,7 +1022,8 @@ const handle = async (req, res) => {
const start = () => new Promise((resolve, reject) => {
const onRequest = (req, res) => {
handle(req, res).catch(err => {
console.log(`[http] ${req.method} ${req.url} failed: ${err.message}`);
// the path only: a query may hold a login token (the item finder's, the Item Maker's)
console.log(`[http] ${logText(req.method)} ${logText(String(req.url).split("?")[0])} failed: ${logText(err.message)}`);
if (!res.headersSent) {
send(res, 500, {error: "server_error"});
}
@@ -904,7 +1072,7 @@ const start = () => new Promise((resolve, reject) => {
});
server.once("error", reject);
server.listen(config.httpPort, config.bindAddress, () => {
console.log(`[http] listening on ${config.bindAddress}:${config.httpPort}${config.webTls ? " (TLS)" : ""}`);
console.log(`[http] listening on ${logText(config.bindAddress)}:${logText(config.httpPort)}${logText(config.webTls ? " (TLS)" : "")}`);
resolve(server);
});
});