Merge origin/main into moderator-tools

Hardware bans, panel search and logs, two worlds and the verified badge,
with the branch's staff roles kept: full rooms let in active staff, and
address search stays with the roles that may ban addresses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
SnipzilandClaude Opus 5.5 committed 2026-10-17 17:58:28 -04:00
commit da7eb9af58
33 files changed
+2771 -166

No files matched your search

+2
View File
@@ -270,6 +270,8 @@ const normalize = account => {
account.totp = account.totp || null;
account.totpSetup = account.totpSetup || null;
account.devices = Array.isArray(account.devices) ? account.devices : [];
// the computers it signed in from, keyed (lib/devices.js): [{kind, id, first, last}].
account.hwids = Array.isArray(account.hwids) ? account.hwids : [];
account.nextInv = account.nextInv || 2;
account.numLogins = account.numLogins || 0;
account.uuid = account.uuid || crypto.randomUUID();
+10 -1
View File
@@ -4,6 +4,7 @@ const accounts = require("./accounts.js");
const bans = require("./bans.js");
const captcha = require("./captcha.js");
const defpacks = require("./defpacks.js");
const devices = require("./devices.js");
const config = require("../config.js");
const dens = require("./dens.js");
const limits = require("./limits.js");
@@ -208,13 +209,21 @@ const handle = async (route, params, body, from) => {
}
const ban = world.moderation.banOf(account);
const addressBan = ban ? null : bans.addressBan(from.address);
const deviceBan = ban || addressBan ? null : devices.banOfAccount(account);
return {status: 200, body: ban ? {banned: "account", banned_seconds: ban.seconds, ban_reason: ban.reason}
: addressBan ? {banned: "address", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason} : {banned: null}};
: addressBan ? {banned: "address", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason}
: deviceBan ? {banned: "device", banned_seconds: world.moderation.PERMANENT, ban_reason: deviceBan.reason} : {banned: null}};
}
case "POST /api/register": {
if (bans.addressBan(from.address)) {
return {status: 403, body: {error: "address_banned"}};
}
// the client says which computer it is on (lib/devices.js); the sign-up
// page cannot, and an account made there still signs in through the client.
const device = devices.read((body || {}).device);
if (device && devices.banOf(device)) {
return {status: 403, body: {error: "device_banned"}};
}
const {username, password, avatarType} = body || {};
// the terms and the privacy policy, and old enough to agree to them:
// said by the one signing up, on the page or in the client.
+2
View File
@@ -35,6 +35,8 @@ const cdn = require("./cdn.js");
// in the order they are listed and drawn.
const BADGES = [
// first, so its tick comes straight after the name, as on other sites.
{id: "verified", label: "Verified", tag: {def: 76, media: 20014, bit: 21}},
{id: "owner", label: "Owner", tag: {def: 63, media: 20001, bit: 8}},
{id: "moderator", label: "Moderator", tag: {def: 64, media: 20002, bit: 9}},
{id: "contributor", label: "Contributor", tag: {def: 65, media: 20003, bit: 10}},
+8 -3
View File
@@ -40,7 +40,7 @@ const requestsPerTenMinutes = limits.limiter(20, 600000);
// and reads a hosted party's name as three string ids.
const roomTitle = room => room.displayName;
module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft, worldOf, worldName}) => {
// BuddyXtCommManager.buddyStatusResponse: [1, username, uuid, moderatedFlag,
// online, accountType, buddyFlag, avatarName, perUserAvId, partyTimeLeft]
const sendStatus = (to, account, buddyFlag) => {
@@ -195,11 +195,16 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
// gets [roomName, displayName, displayNameStringId, cannotGoThere]; an
// empty room means offline. the last field greys out the card's "go to"
// button (BuddyCard.checkBuddyRoomAgainstMine), so it is 0: every room
// here can be walked into. someone who blocked the asker looks offline.
// here can be walked into. the room's name carries its world, and "go
// to" joins it by that name, so it leads into the buddy's world, which
// is named after the room when it is not the asker's. someone who
// blocked the asker looks offline.
br(session, roomId, [username]) {
const target = findOnline(username);
if (target && target.room && !target.account.blocked.includes(key(session.account))) {
session.sendXt("br", -1, target.room.name, roomTitle(target.room), 0, 0);
const world = worldOf(target.room.name);
const elsewhere = world !== 0 && world !== session.worldId;
session.sendXt("br", -1, target.room.name, `${roomTitle(target.room)}${elsewhere ? ` (${worldName(world)})` : ""}`, 0, 0);
}
else {
session.sendXt("br", -1, "", "", 0, 0);
+68 -11
View File
@@ -3,7 +3,8 @@
const accounts = require("./accounts.js");
const config = require("../config.js");
// what players typed: chat in a room, and whispers. kept for the moderator
// what players typed: chat in a room, whispers, Jam-a-Grams and posts on
// each other's Jammer Walls. kept for the moderator
// panel (lib/modpanel.js), which is where a moderator reads what was said
// before deciding anything; nothing else reads it. lines older than
// config.chatLogDays are deleted, and an account's lines go when the
@@ -26,6 +27,11 @@ const SCHEMA = `
const CHAT = "chat";
const WHISPER = "whisper";
const JAMAGRAM = "jamagram";
const WALL = "wall";
const KINDS = [CHAT, WHISPER, JAMAGRAM, WALL];
// what the server's filter kept from being sent is kept with this in front.
const NOT_SENT = "(not sent) ";
const DAY_SECONDS = 86400;
const MAX_TEXT = 600;
const PAGE = 100;
@@ -40,28 +46,69 @@ const prune = () => {
const load = () => {
db().exec(SCHEMA);
// lines the filter stopped are marked, and found by a small index of their own.
if (!db().prepare("PRAGMA table_info(chat_log)").all().some(column => column.name === "stopped")) {
db().exec("ALTER TABLE chat_log ADD COLUMN stopped INTEGER NOT NULL DEFAULT 0");
db().prepare("UPDATE chat_log SET stopped = 1 WHERE substr(text, 1, ?) = ?").run(NOT_SENT.length, NOT_SENT);
}
db().exec("CREATE INDEX IF NOT EXISTS chat_log_stopped ON chat_log (at) WHERE stopped = 1");
prune();
setInterval(prune, DAY_SECONDS * 1000 / 4).unref();
};
const stoppedFlag = text => (String(text).startsWith(NOT_SENT) ? 1 : 0);
// A line said in `room` (its name as the world knows it), or with `to` a
// whisper to that player.
const record = (account, room, text, to = "") => {
if (config.chatLogDays <= 0) {
return;
}
db().prepare("INSERT INTO chat_log (at, account_id, username, room, kind, to_name, text) VALUES (?, ?, ?, ?, ?, ?, ?)")
.run(now(), account.id, account.username, String(room || ""), to ? WHISPER : CHAT, to, String(text).slice(0, MAX_TEXT));
db().prepare("INSERT INTO chat_log (at, account_id, username, room, kind, to_name, text, stopped) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
.run(now(), account.id, account.username, String(room || ""), to ? WHISPER : CHAT, to, String(text).slice(0, MAX_TEXT), stoppedFlag(text));
};
const row = line => ({id: line.id, at: line.at, username: line.username, room: line.room, whisperTo: line.kind === WHISPER ? line.to_name : "", text: line.text});
// A Jam-a-Gram's words (`kind` JAMAGRAM), or a post on a Jammer Wall
// (WALL): `to` is who it was sent to, or whose wall it is.
const recordTo = (account, kind, to, text) => {
if (config.chatLogDays <= 0 || !KINDS.includes(kind)) {
return;
}
db().prepare("INSERT INTO chat_log (at, account_id, username, room, kind, to_name, text, stopped) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
.run(now(), account.id, account.username, "", kind, String(to || ""), String(text).slice(0, MAX_TEXT), stoppedFlag(text));
};
const row = line => ({id: line.id, at: line.at, username: line.username, room: line.room, kind: line.kind, to: line.to_name,
whisperTo: line.kind === WHISPER ? line.to_name : "", text: line.text});
// lines newest first, a page at a time: by who said them (or was whispered
// to), by room, by words in them, and `before` an id for the next page.
const search = ({username = "", room = "", text = "", before = 0}) => {
// to, or sent to), by room, by words in them, by kind (one of KINDS, or
// "notsent" for what the filter stopped), from `until` (seconds) back, and
// `before` an id for the next page. `direction` narrows the username to
// what they sent ("sent") or what was sent to them ("received").
const search = ({username = "", room = "", text = "", kind = "", direction = "", until = 0, before = 0}) => {
const where = [];
const values = [];
if (username) {
if (KINDS.includes(kind)) {
where.push("kind = ?");
values.push(kind);
}
else if (kind === "notsent") {
where.push("stopped = 1");
}
if (until > 0) {
where.push("at <= ?");
values.push(Math.floor(until));
}
if (username && direction === "sent") {
where.push("username = ? COLLATE NOCASE");
values.push(username);
}
else if (username && direction === "received") {
where.push("to_name = ? COLLATE NOCASE");
values.push(username);
}
else if (username) {
where.push("(username = ? COLLATE NOCASE OR to_name = ? COLLATE NOCASE)");
values.push(username, username);
}
@@ -87,9 +134,9 @@ const around = id => {
if (!line) {
return null;
}
const [same, values] = line.kind === WHISPER
? ["kind = ? AND ((username = ? AND to_name = ?) OR (username = ? AND to_name = ?))", [WHISPER, line.username, line.to_name, line.to_name, line.username]]
: ["kind = ? AND room = ?", [CHAT, line.room]];
const [same, values] = line.kind === CHAT
? ["kind = ? AND room = ?", [CHAT, line.room]]
: ["kind = ? AND ((username = ? AND to_name = ?) OR (username = ? AND to_name = ?))", [line.kind, line.username, line.to_name, line.to_name, line.username]];
const earlier = db().prepare(`SELECT * FROM chat_log WHERE ${same} AND id < ? ORDER BY id DESC LIMIT ?`).all(...values, line.id, AROUND).reverse();
const later = db().prepare(`SELECT * FROM chat_log WHERE ${same} AND id > ? ORDER BY id LIMIT ?`).all(...values, line.id, AROUND);
return {line: row(line), lines: [...earlier, line, ...later].map(row)};
@@ -99,9 +146,19 @@ const around = id => {
// of their data a player may ask for (lib/manage.js).
const saidBy = account => db().prepare("SELECT * FROM chat_log WHERE account_id = ? ORDER BY id").all(account.id).map(row);
// how many of an account's lines the server's filter stopped, in the last
// `days` days.
const notSentCount = (account, days) => db().prepare("SELECT COUNT(*) AS n FROM chat_log WHERE account_id = ? AND at > ? AND stopped = 1")
.get(account.id, now() - days * DAY_SECONDS).n;
// those the filter stopped most often in the last `days` days: [{username, count, last}].
const mostStopped = (days, limit) => db().prepare(`SELECT username, COUNT(*) AS count, MAX(at) AS last FROM chat_log
WHERE stopped = 1 AND at > ? GROUP BY account_id ORDER BY count DESC LIMIT ?`)
.all(now() - days * DAY_SECONDS, limit).map(entry => ({username: entry.username, count: entry.count, last: entry.last}));
// an account being deleted: what it said goes with it.
const forget = account => {
db().prepare("DELETE FROM chat_log WHERE account_id = ?").run(account.id);
};
module.exports = {load, record, search, around, saidBy, forget, PAGE};
module.exports = {load, record, recordTo, search, around, saidBy, notSentCount, mostStopped, forget, PAGE, JAMAGRAM, WALL, NOT_SENT};
+399
View File
@@ -0,0 +1,399 @@
"use strict";
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const accounts = require("./accounts.js");
const config = require("../config.js");
// the computers players sign in from, for telling alts apart and keeping a
// banned player's computer out (the "device ban" of the panels).
//
// the client (1.3.0 and on) sends, with every sign-in, hashes of what it
// can read about the computer: the system's own id (MachineGuid on Windows,
// IOPlatformUUID on macOS, /etc/machine-id on Linux), the board's id or
// serial, the disks' serials, the network cards' addresses, and an id of
// its own it keeps in two or three places. none of them is sent as it is:
// each is SHA-256 of "burrow-device:<kind>:<value>", and here that is keyed
// again with a secret of this server's (data/device-key), so what is kept
// is of no use anywhere else.
//
// any one of them is a match: someone who edits /etc/machine-id or deletes
// MachineGuid still has the same disks and the client's own id. the network
// card's address alone (MAC_KIND) is a weak match: it is easily changed and
// sometimes shared, so it bans nothing; it is written down for the
// moderators instead. values every cheap board or VM has ("To be filled by
// O.E.M.", all zeros) are left out here, so that no ban falls on everyone
// who has one. what the client noticed was wrong (the system id missing, or
// not shaped as it always is) comes as notes, and is written down too.
//
// the client is open source, so a player who builds their own can send
// anything; this keeps out the usual ban evader (a VPN, a new account),
// not a determined one. the moderators see the alerts and decide.
const SCHEMA = `
CREATE TABLE IF NOT EXISTS device_bans (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ids TEXT NOT NULL,
reason TEXT NOT NULL,
by TEXT NOT NULL,
created_at INTEGER NOT NULL,
account_id INTEGER,
username TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS device_alerts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
at INTEGER NOT NULL,
account_id INTEGER NOT NULL,
username TEXT NOT NULL,
kind TEXT NOT NULL,
detail TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS device_alerts_account ON device_alerts (account_id, id);
`;
const KINDS = ["os", "board", "disk", "install", "mac"];
const STRONG = ["os", "board", "disk", "install"];
const MAC_KIND = "mac";
const LISTS = ["disk", "mac"]; // sent as lists; the rest one each
const MAX_IN_LIST = 8;
const MAX_KEPT = 60; // ids an account keeps, the latest
const DAYS_KEPT = 90; // what a ban by account takes, and alts look at
const ALERT_EVERY_SECONDS = 86400; // one alert of a kind for an account a day
const MAX_ALERTS_SHOWN = 200;
const MAX_REASON = 300;
const HASH = /^[0-9a-f]{64}$/;
const NOTE = /^[a-z_]{1,24}$/;
// notes from the client that mean someone has been at the computer's ids.
const TAMPER_NOTES = {
os_missing: "the system id is missing",
os_odd: "the system id is not shaped like one",
install_mismatch: "the client's own ids disagree",
};
// values that are everyone's: on cheap boards, in VMs, or where the maker
// wrote nothing. the client sends them hashed like any other, so they are
// hashed here the same way to be known.
const JUNK = {
os: ["00000000-0000-0000-0000-000000000000", "ffffffff-ffff-ffff-ffff-ffffffffffff", "00000000000000000000000000000000",
"ffffffffffffffffffffffffffffffff"],
board: ["00000000-0000-0000-0000-000000000000", "ffffffff-ffff-ffff-ffff-ffffffffffff", "03000200-0400-0500-0006-000700080009",
"12345678-1234-5678-90ab-cddeefaabbcc", "to be filled by o.e.m.", "default string", "system serial number", "chassis serial number",
"not applicable", "not specified", "none", "n/a", "0", "0123456789", "123456789", "1234567890", "serial", "invalid"],
disk: ["0", "none", "0000_0000_0000_0000", "default string", "to be filled by o.e.m.", "not specified"],
mac: ["00:00:00:00:00:00", "ff:ff:ff:ff:ff:ff"],
};
const clientHash = (kind, value) => crypto.createHash("sha256").update(`burrow-device:${kind}:${value}`).digest("hex");
const JUNK_HASHES = new Set(Object.entries(JUNK).flatMap(([kind, values]) => values.map(value => clientHash(kind, value))));
const now = () => Math.floor(Date.now() / 1000);
const db = () => accounts.database();
const clean = (text, max) => String(text === undefined || text === null ? "" : text).replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, max);
const NO_REASON = "Not provided";
let key = null; // this server's secret for keying the ids
const banned = new Map(); // "kind:id" -> ban {id, ids, reason, by, createdAt, accountId, username}
const holders = new Map(); // "kind:id" -> Set of account ids that used it
const keyFile = () => path.join(config.dataDir, "device-key");
// the account's ids: [{kind, id, first, last}], the latest first.
const idsOf = account => {
if (!Array.isArray(account.hwids)) {
account.hwids = [];
}
return account.hwids;
};
const tag = entry => `${entry.kind}:${entry.id}`;
const banRow = row => ({id: row.id, ids: JSON.parse(row.ids), reason: row.reason, by: row.by, createdAt: row.created_at,
accountId: row.account_id, username: row.username});
const load = () => {
try {
key = fs.readFileSync(keyFile());
}
catch (err) {
key = crypto.randomBytes(32);
fs.writeFileSync(keyFile(), key, {mode: 0o600});
}
db().exec(SCHEMA);
for (const row of db().prepare("SELECT * FROM device_bans").all()) {
const ban = banRow(row);
for (const id of ban.ids) {
banned.set(id, ban);
}
}
for (const account of accounts.all()) {
for (const entry of idsOf(account)) {
remember(account, tag(entry));
}
}
};
const remember = (account, id) => {
if (!holders.has(id)) {
holders.set(id, new Set());
}
holders.get(id).add(account.id);
};
// what a sign-in said about its computer (`device` from its body), keyed:
// {ids: [{kind, id}], notes: [..]}, or null when it said nothing usable.
const read = device => {
if (!device || typeof device !== "object" || device.v !== 1 || !device.ids || typeof device.ids !== "object") {
return null;
}
const ids = [];
for (const kind of KINDS) {
const given = device.ids[kind];
const values = LISTS.includes(kind) ? (Array.isArray(given) ? given.slice(0, MAX_IN_LIST) : []) : [given];
for (const value of values) {
const hash = String(value || "").toLowerCase();
if (HASH.test(hash) && !JUNK_HASHES.has(hash)) {
ids.push({kind, id: crypto.createHmac("sha256", key).update(`${kind}:${hash}`).digest("hex").slice(0, 32)});
}
}
}
const notes = Array.isArray(device.notes) ? device.notes.slice(0, 8).map(String).filter(note => NOTE.test(note)) : [];
// something to tell one computer by, beyond a network card.
return ids.some(entry => STRONG.includes(entry.kind)) ? {ids, notes} : null;
};
// the ban that keeps this computer out, or null. a network card's address
// alone keeps nobody out (see the top).
const banOf = device => {
for (const entry of device.ids) {
if (STRONG.includes(entry.kind) && banned.has(tag(entry))) {
return banned.get(tag(entry));
}
}
return null;
};
// the ban on any computer the account signed in from lately, or null: for
// the client asking why its game was stopped.
const banOfAccount = account => {
for (const entry of idsOf(account)) {
if (STRONG.includes(entry.kind) && entry.last > now() - DAYS_KEPT * 86400 && banned.has(tag(entry))) {
return banned.get(tag(entry));
}
}
return null;
};
const alert = (account, kind, detail) => {
const last = db().prepare("SELECT at FROM device_alerts WHERE account_id = ? AND kind = ? ORDER BY id DESC LIMIT 1").get(account.id, kind);
if (last && last.at > now() - ALERT_EVERY_SECONDS) {
return;
}
db().prepare("INSERT INTO device_alerts (at, account_id, username, kind, detail) VALUES (?, ?, ?, ?, ?)").run(now(), account.id, account.username, kind, detail);
console.log(`[devices] ${account.username}: ${kind} (${detail})`);
};
// an account signed in from this computer: its ids are kept, and what looks
// wrong is written down. `isBanned(account)` says whether another account is
// banned now (lib/moderation.js), for "shares a computer with a banned one".
const seen = (account, device, isBanned) => {
const list = idsOf(account);
const at = now();
for (const entry of device.ids) {
const kept = list.find(other => other.kind === entry.kind && other.id === entry.id);
if (kept) {
kept.last = at;
}
else {
list.push({kind: entry.kind, id: entry.id, first: at, last: at});
}
remember(account, tag(entry));
}
list.sort((one, other) => other.last - one.last);
for (const dropped of list.splice(MAX_KEPT)) {
const set = holders.get(tag(dropped));
if (set) {
set.delete(account.id);
}
}
const tampered = device.notes.filter(note => TAMPER_NOTES[note]).map(note => TAMPER_NOTES[note]);
if (tampered.length) {
alert(account, "tampered", tampered.join(", "));
}
const nearBan = device.ids.find(entry => entry.kind === MAC_KIND && banned.has(tag(entry)));
if (nearBan) {
alert(account, "near_ban", `same network card as a hardware ban (${banned.get(tag(nearBan)).username || "no account"})`);
}
const sharers = new Set();
for (const entry of device.ids.filter(one => STRONG.includes(one.kind))) {
for (const id of holders.get(tag(entry)) || []) {
const other = id === account.id ? null : accounts.byId(id);
if (other && isBanned(other)) {
sharers.add(other.username);
}
}
}
if (sharers.size) {
alert(account, "shares_banned", `same hardware as banned ${[...sharers].slice(0, 5).join(", ")}`);
}
};
// the other accounts that used any of this one's computers: [{username,
// kinds: [kind], weak: true when only a network card}], most in common first.
const alts = account => {
const found = new Map(); // account id -> Set of kinds
for (const entry of idsOf(account)) {
for (const id of holders.get(tag(entry)) || []) {
if (id !== account.id) {
if (!found.has(id)) {
found.set(id, new Set());
}
found.get(id).add(entry.kind);
}
}
}
return [...found].map(([id, kinds]) => ({account: accounts.byId(id), kinds: [...kinds]}))
.filter(entry => entry.account)
.map(entry => ({username: entry.account.username, kinds: entry.kinds, weak: entry.kinds.every(kind => kind === MAC_KIND)}))
.sort((one, other) => Number(one.weak) - Number(other.weak) || other.kinds.length - one.kinds.length || one.username.localeCompare(other.username));
};
// how many computers' worth of ids an account has, for the panels.
const knownFor = account => ({ids: idsOf(account).length, lastAt: idsOf(account).reduce((latest, entry) => Math.max(latest, entry.last), 0)});
// bans every computer the account signed in from in the last DAYS_KEPT
// days. returns {ban} or {error}. `out(ban)` puts out whoever plays from
// one of them.
const banAccount = (account, reason, by) => {
const ids = [...new Set(idsOf(account).filter(entry => entry.last > now() - DAYS_KEPT * 86400).map(tag))];
if (!ids.some(id => STRONG.includes(id.split(":")[0]))) {
return {error: "No hardware IDs known for them."};
}
if (ids.filter(id => STRONG.includes(id.split(":")[0])).every(id => banned.has(id))) {
return {error: "Their hardware is banned already."};
}
const text = clean(reason, MAX_REASON) || NO_REASON;
const result = db().prepare("INSERT INTO device_bans (ids, reason, by, created_at, account_id, username) VALUES (?, ?, ?, ?, ?, ?)")
.run(JSON.stringify(ids), text, by, now(), account.id, account.username);
const ban = {id: Number(result.lastInsertRowid), ids, reason: text, by, createdAt: now(), accountId: account.id, username: account.username};
for (const id of ids) {
banned.set(id, ban);
}
return {ban};
};
// the accounts playing from one of a ban's computers, by their latest ids.
const accountsUnder = ban => {
const ids = new Set(ban.ids.filter(id => STRONG.includes(id.split(":")[0])));
const found = new Set();
for (const id of ids) {
for (const accountId of holders.get(id) || []) {
found.add(accountId);
}
}
return [...found].map(id => accounts.byId(id)).filter(Boolean);
};
const unban = id => {
const row = db().prepare("SELECT * FROM device_bans WHERE id = ?").get(Number(id));
if (!row) {
return null;
}
const ban = banRow(row);
db().prepare("DELETE FROM device_bans WHERE id = ?").run(ban.id);
for (const one of ban.ids) {
if (banned.get(one) && banned.get(one).id === ban.id) {
banned.delete(one);
}
}
return ban;
};
// the bans, newest first: their ids, and the accounts that used them.
const MAX_LISTED_ACCOUNTS = 20;
const list = () => db().prepare("SELECT * FROM device_bans ORDER BY id DESC").all().map(banRow)
.map(ban => ({id: ban.id, username: ban.username, reason: ban.reason, by: ban.by, createdAt: ban.createdAt,
ids: ban.ids.map(one => ({kind: one.split(":")[0], id: one.split(":")[1]})),
accounts: accountsUnder(ban).map(account => account.username).sort().slice(0, MAX_LISTED_ACCOUNTS)}));
// the account's ids for the panels, the latest first: [{kind, id, first,
// last, banned: the ban's id or 0, others: how many other accounts used it}].
const idsFor = account => idsOf(account).map(entry => {
const ban = banned.get(tag(entry));
const set = holders.get(tag(entry));
return {kind: entry.kind, id: entry.id, first: entry.first, last: entry.last, banned: ban ? ban.id : 0,
others: set ? [...set].filter(id => id !== account.id).length : 0};
});
// the bans that keep the account's computers out (by any of its ids but a
// network card's, however old), and those made with it: what "unban
// computers" on its page lifts.
const bansOfAccount = account => {
const found = new Map();
for (const entry of idsOf(account)) {
const ban = banned.get(tag(entry));
if (ban && STRONG.includes(entry.kind)) {
found.set(ban.id, ban);
}
}
for (const ban of banned.values()) {
if (ban.accountId === account.id) {
found.set(ban.id, ban);
}
}
return [...found.values()];
};
// the accounts that used an id, or any id starting with what was typed (a
// "kind:" in front is let be): {error} or {players: [{account, kinds,
// lastAt}]}, the latest first.
const MIN_ID_QUERY = 6;
const MAX_ID_FOUND = 100;
const search = query => {
const wanted = String(query || "").trim().toLowerCase().replace(/^[a-z]+:/, "").slice(0, 32);
if (wanted.length < MIN_ID_QUERY || !/^[0-9a-f]+$/.test(wanted)) {
return {error: `Type at least ${MIN_ID_QUERY} characters of a hardware ID.`};
}
const found = new Map(); // account id -> {kinds, lastAt}
for (const [key, set] of holders) {
const [kind, id] = key.split(":");
if (!id.startsWith(wanted)) {
continue;
}
for (const accountId of set) {
const account = accounts.byId(accountId);
const entry = account && idsOf(account).find(one => one.kind === kind && one.id === id);
if (entry) {
const kept = found.get(accountId) || {account, kinds: new Set(), lastAt: 0};
kept.kinds.add(kind);
kept.lastAt = Math.max(kept.lastAt, entry.last);
found.set(accountId, kept);
}
}
}
return {players: [...found.values()].map(entry => ({...entry, kinds: [...entry.kinds]}))
.sort((one, other) => other.lastAt - one.lastAt).slice(0, MAX_ID_FOUND)};
};
// is any of the account's computers banned? the ban's id, or 0.
const bannedId = account => {
const ban = banOfAccount(account);
return ban ? ban.id : 0;
};
const ALERT_NAMES = {tampered: "Hardware IDs tampered with", near_ban: "Network card of a hardware ban", shares_banned: "Same hardware as a banned player"};
const alertRow = row => ({id: row.id, at: row.at, username: row.username, kind: row.kind, name: ALERT_NAMES[row.kind] || row.kind, detail: row.detail});
const alerts = () => db().prepare("SELECT * FROM device_alerts ORDER BY id DESC LIMIT ?").all(MAX_ALERTS_SHOWN).map(alertRow);
const alertsOf = account => db().prepare("SELECT * FROM device_alerts WHERE account_id = ? ORDER BY id DESC LIMIT 50").all(account.id).map(alertRow);
// an account being deleted: its ids and alerts go. bans stay: they are of
// computers, not of the account.
const forget = account => {
for (const entry of idsOf(account)) {
const set = holders.get(tag(entry));
if (set) {
set.delete(account.id);
}
}
db().prepare("DELETE FROM device_alerts WHERE account_id = ?").run(account.id);
};
module.exports = {load, read, banOf, banOfAccount, seen, alts, knownFor, banAccount, accountsUnder, unban, list, idsFor, bansOfAccount, search, bannedId, alerts, alertsOf, forget, clientHash};
+4
View File
@@ -5,6 +5,7 @@ const path = require("path");
const accounts = require("./accounts.js");
const achievements = require("./achievements.js");
const chatFilter = require("./chatfilter.js");
const chatlog = require("./chatlog.js");
const defpacks = require("./defpacks.js");
const dens = require("./dens.js");
const limits = require("./limits.js");
@@ -261,6 +262,7 @@ module.exports = ({findOnline, blocks}) => {
if (rule) {
chatFilter.warn(session);
console.log(`[filter] ${account.username} in a Jam-a-Gram to ${to.username}: "${clean(message || "")}" (${rule})`);
chatlog.recordTo(account, chatlog.JAMAGRAM, to.username, chatlog.NOT_SENT + clean(message || ""));
reply(FAILED);
return;
}
@@ -279,6 +281,8 @@ module.exports = ({findOnline, blocks}) => {
return;
}
deliver(to, {from: account.username, fromId: account.id, card: Number(card), stamp: Number(stamp), msg: clean(message || ""), gift});
// for the panels (lib/chatlog.js), as typed chat is.
chatlog.recordTo(account, chatlog.JAMAGRAM, to.username, clean(message || "") + (gift ? " [with a gift]" : ""));
achievements.add(account, achievements.VARS.jamAGramsSent);
if (gift) {
achievements.add(account, achievements.VARS.giftsSent);
+4 -1
View File
@@ -3,13 +3,15 @@
const accounts = require("./accounts.js");
const bans = require("./bans.js");
const chatlog = require("./chatlog.js");
const devices = require("./devices.js");
const masterpieces = require("./masterpieces.js");
const support = require("./support.js");
const world = require("./world.js");
// an account deleted for good, by its owner (lib/manage.js) or by the admin
// (lib/panel.js), and what was kept about it elsewhere with it: its chat
// lines, its appeal, its feedback and username requests, and the paintings
// lines, its appeal, its feedback and username requests, the computers it
// was used from (lib/devices.js), and the paintings
// it made (from whoever holds one by now). what stays is said in the
// privacy policy (public/privacy.html): the record of bans and of what
// moderators did, under the name it had, until lib/retention.js ends it.
@@ -20,6 +22,7 @@ module.exports = account => {
}
bans.forget(account);
chatlog.forget(account);
devices.forget(account);
support.forget(account);
accounts.remove(account);
};
+22 -1
View File
@@ -11,6 +11,7 @@ const bans = require("./bans.js");
const captcha = require("./captcha.js");
const cdn = require("./cdn.js");
const config = require("../config.js");
const devices = require("./devices.js");
const defpacks = require("./defpacks.js");
const limits = require("./limits.js");
const manage = require("./manage.js");
@@ -383,6 +384,14 @@ const authenticate = async (req, res, from) => {
renameAndSignIn(res, body, from);
return;
}
// the computer it is on (lib/devices.js): a client that does not say is
// out of date (before 1.3.0) or not ours. 1.2 shows "The server refused
// the login (426)", and still offers its update.
const device = devices.read(body.device);
if (!device && config.requireDevice) {
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)) {
@@ -430,6 +439,15 @@ const authenticate = async (req, res, from) => {
send(res, 401, {error_code: 101, error: "address_banned", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason});
return;
}
// A banned computer (lib/devices.js): for good, whichever account. a
// client that sent no ids (before 1.3.0) is judged by the hardware the
// 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})`);
send(res, 401, {error_code: 101, error: "device_banned", banned_seconds: world.moderation.PERMANENT, ban_reason: deviceBan.reason});
return;
}
// locked by its owner on the account page: the password is right, and
// still nobody gets in. the launcher shows this as a failed sign-in.
if (account.locked) {
@@ -466,10 +484,13 @@ const authenticate = async (req, res, from) => {
send(res, 401, {error_code: 101, error: "name_rejected", rename_ticket: renameTicket(account, deviceToken)});
return;
}
if (device) {
devices.seen(account, device, other => world.moderation.banRemaining(other) !== 0);
}
if (!byRefresh) {
accounts.recordLogin(account, "launcher", from.address);
accounts.save(account);
}
accounts.save(account);
// the custom client's advanced settings; the official launcher sends none.
accounts.setLoginChoices(account, body.login_choices);
const token = byRefresh ? body.refresh_token : accounts.issueToken(account);
+11 -1
View File
@@ -319,6 +319,16 @@ const list = status => [...known.values()].filter(painting => painting.status ==
return {id: painting.id, creator: maker ? maker.username : "(deleted account)", createdAt: painting.createdAt, frame: painting.frame, likes: painting.likes.length};
});
// both lists for the panels, narrowed to makers whose names have
// `creator` in them (the one of exactly that name first): {waiting,
// approved}, newest first.
const listsFor = creator => {
const wanted = String(creator || "").trim().toLowerCase().slice(0, 100);
const narrowed = paintings => (wanted ? paintings.filter(painting => painting.creator.toLowerCase().includes(wanted))
.sort((one, other) => Number(other.creator.toLowerCase() === wanted) - Number(one.creator.toLowerCase() === wanted)) : paintings);
return {waiting: narrowed(list(PENDING)), approved: narrowed(list(APPROVED))};
};
const madeBy = account => [...known.values()].filter(painting => painting.creator === account.id).map(painting => painting.id);
// generic lists: (mediaId, name string id) pairs, or null when `listId` is
@@ -327,7 +337,7 @@ const frameList = listId =>
([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null);
module.exports = {
load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, frameList,
load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, frameList,
needsReview, setNeedsReview, madeBy,
PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES,
};
+5 -1
View File
@@ -28,4 +28,8 @@ const record = (by, action, target = "", detail = "") => {
const recent = () => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log ORDER BY id DESC LIMIT ?").all(SHOWN);
module.exports = {load, record, recent};
// what staff did to one player, newest first, for their timeline.
const about = username => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log WHERE target = ? COLLATE NOCASE ORDER BY id DESC LIMIT 100")
.all(String(username));
module.exports = {load, record, recent, about};
+53 -12
View File
@@ -10,6 +10,7 @@ const chatlog = require("./chatlog.js");
const config = require("../config.js");
const customItems = require("./customitems.js");
const defpacks = require("./defpacks.js");
const devices = require("./devices.js");
const limits = require("./limits.js");
const manage = require("./manage.js");
const masterpieces = require("./masterpieces.js");
@@ -48,7 +49,6 @@ const SESSION_HOURS = 12;
const TEN_MINUTES_MS = 600000;
const MAX_BAN_HOURS = 24 * 365 * 10;
const MAX_MESSAGE_LENGTH = 200;
const MAX_FOUND = 50;
const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS);
const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator
@@ -104,19 +104,17 @@ const playerRow = (account, playing) => {
playtime: account.playtime,
bio: account.bio,
discord: account.discord,
deviceBanned: devices.bannedId(account) !== 0,
};
};
const playing = () => new Map(world.players().map(player => [player.username, player.room || "(between rooms)"]));
// by name (lib/staff.js says in what order).
const findPlayers = query => {
const wanted = String(query || "").trim().toLowerCase().slice(0, 100);
const online = playing();
return accounts.all()
.filter(account => account.username.toLowerCase().includes(wanted))
.sort((a, b) => Number(online.has(b.username)) - Number(online.has(a.username)) || a.username.localeCompare(b.username))
.slice(0, MAX_FOUND)
.map(account => playerRow(account, online));
const {found, total} = staff.findAccounts(query);
return {players: found.map(account => playerRow(account, online)), total};
};
// one player: the row, what was done about their bans (without addresses),
@@ -127,6 +125,9 @@ const playerDetail = account => ({
appeal: bans.appealOf(account),
warningList: (account.warnings || []).slice(-20).reverse(),
openReports: reports.list(false).filter(report => report.target.toLowerCase() === account.username.toLowerCase()).length,
devicesKnown: devices.knownFor(account).ids,
stoppedThisWeek: chatlog.notSentCount(account, 7),
paintings: masterpieces.madeBy(account).length,
});
// an address with its end left out, and a name to lift its ban by.
@@ -264,6 +265,11 @@ const act = (mod, target, body) => {
const result = world.staffMove(mod.username, target.username);
return result.ok ? {ok: `You went to ${name} (${result.room}).`, detail: result.room} : {error: result.error};
}
// every computer they signed in from lately (lib/devices.js).
case "banDevices":
return staff.banDevices(target, body.reason, by);
case "unbanDevices":
return staff.unbanDevicesOf(target, by);
default:
return {error: "Unknown action."};
}
@@ -414,9 +420,36 @@ const handle = async (req, res, url, from, web) => {
paintings: masterpieces.list(masterpieces.PENDING).length});
return;
// other accounts the same person may have, and their story (lib/staff.js).
case "GET /mod/api/alts": {
const account = accounts.byName(url.searchParams.get("username") || "");
reply(account ? 200 : 404, account ? {alts: staff.altsOf(account), ids: devices.idsFor(account)} : {error: "No such player."});
return;
}
case "GET /mod/api/timeline": {
const account = accounts.byName(url.searchParams.get("username") || "");
reply(account ? 200 : 404, account ? {events: staff.timelineOf(account)} : {error: "No such player."});
return;
}
// who the server's chat filter stopped most this week.
case "GET /mod/api/filterhits":
reply(200, {players: chatlog.mostStopped(7, 50)});
return;
case "GET /mod/api/players": {
if (url.searchParams.get("by") !== "address") {
reply(200, {players: findPlayers(url.searchParams.get("q"))});
const searchBy = url.searchParams.get("by");
if (searchBy === "device") {
const found = staff.byDevice(url.searchParams.get("q"));
if (found.error) {
reply(400, found);
return;
}
const online = playing();
reply(200, {players: found.players.map(entry => ({...playerRow(accounts.byName(entry.username), online), matchedAt: entry.lastAt}))});
return;
}
if (searchBy !== "address") {
reply(200, findPlayers(url.searchParams.get("q")));
return;
}
// by address: only the address typed, which is written down (once
@@ -466,7 +499,8 @@ const handle = async (req, res, url, from, web) => {
case "GET /mod/api/chat": {
const params = url.searchParams;
const lines = chatlog.search({username: (params.get("username") || "").trim().slice(0, 100), room: (params.get("room") || "").trim().slice(0, 100),
text: (params.get("text") || "").trim().slice(0, 100), before: Number(params.get("before")) || 0});
text: (params.get("text") || "").trim().slice(0, 100), kind: params.get("kind") || "", direction: params.get("direction") || "", until: Number(params.get("until")) || 0,
before: Number(params.get("before")) || 0});
reply(200, {lines, more: lines.length === chatlog.PAGE, days: config.chatLogDays});
return;
}
@@ -506,7 +540,7 @@ const handle = async (req, res, url, from, web) => {
}
case "GET /mod/api/bans":
reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans().map(maskedAddress)});
reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans().map(maskedAddress), devices: devices.list(), alerts: devices.alerts()});
return;
case "POST /mod/api/address": {
@@ -519,9 +553,16 @@ const handle = async (req, res, url, from, web) => {
return;
}
// A device ban lifted (lib/devices.js).
case "POST /mod/api/device": {
const result = staff.unbanDevices(body.id, mod.username);
done(result, "hardware ban lifted", result.username || "");
return;
}
// paintings players framed (lib/masterpieces.js).
case "GET /mod/api/masterpieces":
reply(200, {waiting: masterpieces.list(masterpieces.PENDING), approved: masterpieces.list(masterpieces.APPROVED)});
reply(200, {...masterpieces.listsFor(url.searchParams.get("creator")), waitingCount: masterpieces.list(masterpieces.PENDING).length});
return;
case "GET /mod/api/masterpiece": {
+89 -4
View File
@@ -9,7 +9,9 @@ const adopt = require("./adopt.js");
const badges = require("./badges.js");
const bans = require("./bans.js");
const colours = require("./colours.js");
const chatlog = require("./chatlog.js");
const config = require("../config.js");
const devices = require("./devices.js");
const defpacks = require("./defpacks.js");
const limits = require("./limits.js");
const log = require("./log.js");
@@ -48,6 +50,7 @@ const TEN_MINUTES_MS = 600000;
const DAY_SECONDS = 86400;
const MAX_ANNOUNCEMENT = 300;
const MAX_OWNED_LISTED = 300;
const MAX_LISTED = 100; // accounts in one search of the Accounts page
// currencies the panel can hand out, as indexes into CURRENCIES.
const GIFT_CURRENCIES = {gems: 0, tickets: 1, diamonds: 3};
// who a ban is written down as given by. the panel has one password and so
@@ -157,6 +160,10 @@ const accountRow = (account, playing) => {
level: activeAvatar(account).questLevel || 0,
items: account.items.length + account.denItems.length,
gems: account.currency.gems || 0,
deviceBanned: devices.bannedId(account) !== 0,
devicesKnown: devices.knownFor(account).ids,
stoppedThisWeek: chatlog.notSentCount(account, 7),
paintings: masterpieces.madeBy(account).length,
};
};
@@ -479,6 +486,11 @@ const act = (account, body) => {
return {ok: `${name} is no longer banned.`};
case "kick":
return actions.kick(account) ? {ok: `${name} was disconnected.`} : {error: `${name} is not online.`};
// every computer they signed in from lately (lib/devices.js).
case "banDevices":
return staff.banDevices(account, body.reason, BY);
case "unbanDevices":
return staff.unbanDevicesOf(account, BY);
// counted in hours; the game's own notice counts minutes.
case "silence": {
const hours = wholeNumber(body.hours, 0, MAX_BAN_HOURS);
@@ -660,9 +672,24 @@ const handle = async (req, res, url, from, web) => {
reply(200, overview());
return;
// a page of accounts by name (lib/staff.js says in what order), never
// all of them: with thousands, sending every one every few seconds
// slowed the page and the game alike.
case "GET /admin/api/accounts": {
const playing = new Map(world.players().map(player => [player.username, player.room || "(between rooms)"]));
reply(200, {accounts: accounts.all().map(account => accountRow(account, playing)), badges: badges.BADGES});
const filter = url.searchParams.get("filter");
const keep = filter === "online" ? (account, online) => online.has(account.username)
: filter === "banned" ? account => world.moderation.banRemaining(account) !== 0 : () => true;
const {found, total} = staff.findAccounts(url.searchParams.get("q"), keep, MAX_LISTED);
reply(200, {accounts: found.map(account => accountRow(account, playing)), total, badges: badges.BADGES});
return;
}
// one account's row, for the one that is open whatever the list shows.
case "GET /admin/api/account": {
const account = accounts.byName(url.searchParams.get("username") || "");
const playing = new Map(world.players().map(player => [player.username, player.room || "(between rooms)"]));
reply(account ? 200 : 404, account ? {account: accountRow(account, playing), badges: badges.BADGES} : {error: "No such account."});
return;
}
@@ -677,6 +704,28 @@ const handle = async (req, res, url, from, web) => {
reply(found.error ? 400 : 200, found);
return;
}
// who signed in from a computer, by one of its ids or the start of one.
case "GET /admin/api/device-search": {
const found = staff.byDevice(url.searchParams.get("q"));
reply(found.error ? 400 : 200, found.error ? found : {players: found.players.map(entry => ({...entry,
online: Boolean(world.findOnline(entry.username))}))});
return;
}
// what players typed, sent and posted (lib/chatlog.js), as the moderators see it.
case "GET /admin/api/chat": {
const params = url.searchParams;
const lines = chatlog.search({username: (params.get("username") || "").trim().slice(0, 100), room: (params.get("room") || "").trim().slice(0, 100),
text: (params.get("text") || "").trim().slice(0, 100), kind: params.get("kind") || "", direction: params.get("direction") || "", until: Number(params.get("until")) || 0,
before: Number(params.get("before")) || 0});
reply(200, {lines, more: lines.length === chatlog.PAGE, days: config.chatLogDays});
return;
}
case "GET /admin/api/chat/around": {
const found = chatlog.around(url.searchParams.get("id"));
reply(found ? 200 : 404, found || {error: "No such line."});
return;
}
case "GET /admin/api/logs": {
const lines = log.recent(Number(url.searchParams.get("after")) || 0, (url.searchParams.get("filter") || "").slice(0, 100));
@@ -693,6 +742,10 @@ const handle = async (req, res, url, from, web) => {
const result = act(account, body);
if (result.ok) {
console.log(`[admin] ${body.action} on "${account.username}"`);
// in the record beside the moderators', for the player's timeline.
if (!["password", "lastSeen", "level"].includes(body.action)) {
modlog.record(BY, body.action, account.username, result.detail || "");
}
}
reply(result.ok ? 200 : 400, result);
return;
@@ -705,7 +758,39 @@ const handle = async (req, res, url, from, web) => {
}
case "GET /admin/api/bans":
reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans()});
reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans(), devices: devices.list(), alerts: devices.alerts()});
return;
// A device ban lifted (lib/devices.js).
case "POST /admin/api/device": {
const result = staff.unbanDevices(body.id, BY);
if (result.ok) {
console.log(`[admin] device ban ${Number(body.id)} lifted`);
modlog.record(BY, "hardware ban lifted", result.username || "");
}
reply(result.ok ? 200 : 400, result);
return;
}
// other accounts the same person may have, their story, and who the
// chat filter stopped most this week (lib/staff.js, lib/chatlog.js).
case "GET /admin/api/alts": {
const account = accounts.byName(url.searchParams.get("username") || "");
reply(account ? 200 : 404, account ? {alts: staff.altsOf(account), ids: devices.idsFor(account)} : {error: "No such account."});
return;
}
case "GET /admin/api/timeline": {
const account = accounts.byName(url.searchParams.get("username") || "");
reply(account ? 200 : 404, account ? {events: staff.timelineOf(account)} : {error: "No such account."});
return;
}
case "GET /admin/api/filterhits":
reply(200, {players: chatlog.mostStopped(7, 50)});
return;
// what waits, for the tabs and the page's title, on every page.
case "GET /admin/api/counts":
reply(200, {reports: reports.openCount(), support: support.openCount() + bans.openAppeals(), masterpieces: masterpieces.list(masterpieces.PENDING).length});
return;
// who may use the moderator panel, and what each did there.
@@ -775,8 +860,8 @@ const handle = async (req, res, url, from, web) => {
case "GET /admin/api/masterpieces":
reply(200, {
review: masterpieces.needsReview(),
waiting: masterpieces.list(masterpieces.PENDING),
approved: masterpieces.list(masterpieces.APPROVED),
...masterpieces.listsFor(url.searchParams.get("creator")),
waitingCount: masterpieces.list(masterpieces.PENDING).length,
});
return;
+5 -1
View File
@@ -94,4 +94,8 @@ const list = (handled = false) => accounts.database()
const markHandled = id => accounts.database().prepare("UPDATE reports SET handled_at = ? WHERE id = ? AND handled_at IS NULL").run(now(), id).changes > 0;
module.exports = {load, file, list, markHandled, openCount, MAX_DETAIL};
// the reports about one player, newest first, for their timeline.
const about = username => accounts.database().prepare("SELECT * FROM reports WHERE target = ? COLLATE NOCASE ORDER BY id DESC LIMIT 100")
.all(String(username)).map(row);
module.exports = {load, file, list, about, markHandled, openCount, MAX_DETAIL};
+132 -1
View File
@@ -2,7 +2,11 @@
const accounts = require("./accounts.js");
const bans = require("./bans.js");
const devices = require("./devices.js");
const limits = require("./limits.js");
const manage = require("./manage.js");
const modlog = require("./modlog.js");
const reports = require("./reports.js");
const support = require("./support.js");
const world = require("./world.js");
@@ -25,6 +29,29 @@ const disciplined = () => accounts.all()
.filter(entry => entry.banned !== 0 || entry.silenced !== 0)
.sort((a, b) => a.username.localeCompare(b.username));
// accounts by name, for both panels' search: at most `limit`, those named
// exactly what was typed first, then those whose names start with it, then
// those with it anywhere, online players first within each and then by
// name. so "John" is never lost among John123 and Johnathan. with nothing
// typed: online players, then the ones seen last. `keep` narrows it
// (online, banned...). returns {found, total}: total is how many matched.
const MAX_FOUND = 50;
const findAccounts = (query, keep = () => true, limit = MAX_FOUND) => {
const wanted = String(query || "").trim().toLowerCase().slice(0, 100);
const online = new Set(world.players().map(player => player.username));
const rank = name => {
const low = name.toLowerCase();
return low === wanted ? 0 : low.startsWith(wanted) ? 1 : 2;
};
const matched = accounts.all().filter(account => account.username.toLowerCase().includes(wanted) && keep(account, online));
const sorted = wanted
? matched.sort((a, b) => rank(a.username) - rank(b.username) || Number(online.has(b.username)) - Number(online.has(a.username))
|| a.username.localeCompare(b.username))
: matched.sort((a, b) => Number(online.has(b.username)) - Number(online.has(a.username))
|| (b.lastSeen || b.lastLogin || 0) - (a.lastSeen || a.lastLogin || 0));
return {found: sorted.slice(0, limit), total: matched.length};
};
// the accounts that signed in from an address, or from any address that
// starts with what was typed ("203.0.113." for the lot): from the sign-in
// histories, which hold the last 90 days (lib/accounts.js). failed tries
@@ -67,6 +94,110 @@ const banAddress = (address, reason, by) => {
return result.error ? {error: ADDRESS_ERRORS[result.error]} : {ban: result.ban, out: world.disconnectAddress(result.ban.address)};
};
// bans every computer the account signed in from lately (lib/devices.js),
// and puts out whoever plays from one of them, whichever account. their
// sign-ins stay, as with an address ban: the client asks with one why its
// game stopped, and the account page stays open to them for an appeal; the
// game itself turns them away (lib/world.js). returns {ok, detail} or {error}.
const banDevices = (account, reason, by) => {
const result = devices.banAccount(account, reason, by);
if (result.error) {
return result;
}
const under = devices.accountsUnder(result.ban);
const out = world.disconnectBanned(under);
bans.record({account, action: "device_ban", seconds: -1, reason: result.ban.reason, by});
const others = under.filter(one => one !== account).map(one => one.username);
return {ok: `${account.username} is hardware banned (${result.ban.ids.length} IDs).${out ? ` ${out} playing from them ${out === 1 ? "was" : "were"} put out.` : ""}`
+ `${others.length ? ` Also used by: ${others.slice(0, 10).join(", ")}${others.length > 10 ? "…" : ""}.` : ""}`, detail: result.ban.reason};
};
const unbanDevices = (id, by) => {
const ban = devices.unban(id);
if (!ban) {
return {error: "No such hardware ban."};
}
bans.record({account: accounts.byId(ban.accountId), action: "device_unban", by});
return {ok: `The hardware ban made with ${ban.username || "that account"} is lifted.`, username: ban.username};
};
// every computer ban that keeps the account out, or was made with it, lifted.
const unbanDevicesOf = (account, by) => {
const lifted = devices.bansOfAccount(account).map(ban => unbanDevices(ban.id, by)).filter(result => result.ok);
if (!lifted.length) {
return {error: "None of their hardware is banned."};
}
const names = [...new Set(lifted.map(result => result.username).filter(Boolean))];
return {ok: `${lifted.length === 1 ? "1 hardware ban was" : `${lifted.length} hardware bans were`} lifted${names.length ? ` (made with ${names.join(", ")})` : ""}.`,
detail: names.join(", ")};
};
// the accounts that used a computer id, or one starting with what was
// typed (lib/devices.js): {error} or {players: [{username, kinds, lastAt}]}.
const byDevice = query => {
const found = devices.search(query);
return found.error ? found : {players: found.players.map(entry => ({username: entry.account.username, kinds: entry.kinds, lastAt: entry.lastAt}))};
};
// other accounts the same person may have: those that used one of its
// computers (lib/devices.js), and those that signed in from one of its
// addresses in the last 90 days. [{username, devices: [kind], weak,
// addresses: count, online, banned}], the likeliest first. the addresses
// themselves are not given: moderators do not see them.
const altsOf = account => {
const found = new Map();
const entry = username => {
if (!found.has(username)) {
found.set(username, {username, devices: [], weak: false, addresses: 0});
}
return found.get(username);
};
for (const alt of devices.alts(account)) {
Object.assign(entry(alt.username), {devices: alt.kinds, weak: alt.weak});
}
const mine = new Set(account.logins.filter(login => login.ok && login.address && !limits.isLoopback(login.address)).map(login => login.address));
if (mine.size) {
for (const other of accounts.all()) {
if (other !== account) {
const shared = new Set(other.logins.filter(login => login.ok && mine.has(login.address)).map(login => login.address));
if (shared.size) {
entry(other.username).addresses = shared.size;
}
}
}
}
return [...found.values()].map(alt => {
const other = accounts.byName(alt.username);
return {...alt, online: Boolean(world.findOnline(alt.username)), banned: other ? world.moderation.banRemaining(other) : 0,
deviceBanned: other ? devices.bannedId(other) !== 0 : false};
}).sort((one, other) => Number(other.devices.length > 0 && !other.weak) - Number(one.devices.length > 0 && !one.weak)
|| other.devices.length - one.devices.length || other.addresses - one.addresses || one.username.localeCompare(other.username)).slice(0, 100);
};
// one player's story, newest first: bans given and lifted, what staff did
// to them, the reports about them, and what their computers gave away
// (lib/devices.js). [{at, kind, text, by}].
const BAN_WORDS = {ban: "Banned", unban: "Ban lifted", reason: "Ban reason changed", appeal: "Appealed", appeal_approved: "Appeal approved",
appeal_denied: "Appeal denied", device_ban: "Hardware banned", device_unban: "Hardware ban lifted"};
const timelineOf = account => {
const events = [];
for (const entry of bans.historyOf(account)) {
const length = entry.action === "ban" ? (entry.seconds === -1 ? "for good" : `${Math.round(entry.seconds / 3600)} h`) : "";
events.push({at: entry.at, kind: "ban", text: [BAN_WORDS[entry.action] || entry.action, length, entry.reason].filter(Boolean).join(" · "), by: entry.by});
}
for (const entry of modlog.about(account.username)) {
events.push({at: entry.at, kind: "staff", text: [entry.action, entry.detail].filter(Boolean).join(" · "), by: entry.by});
}
for (const report of reports.about(account.username)) {
events.push({at: report.createdAt, kind: "report", text: `Reported: ${report.reason}${report.detail ? ` · ${report.detail}` : ""}${report.handledAt ? "" : " (waiting)"}`,
by: report.reporter});
}
for (const entry of devices.alertsOf(account)) {
events.push({at: entry.at, kind: "alert", text: `${entry.name} · ${entry.detail}`, by: ""});
}
return events.sort((one, other) => other.at - one.at).slice(0, 200);
};
// appeals with what each is against, as it stands now.
const appealsFor = handled => bans.appeals(handled).map(appeal => {
const account = accounts.byId(appeal.accountId);
@@ -122,4 +253,4 @@ const answerNameRequest = (id, approve) => {
return {ok: `${oldName} is now called ${account.username}. They log in with the new name and the same password.`, username: account.username};
};
module.exports = {disciplined, byAddress, banAddress, appealsFor, answerAppeal, answerNameRequest};
module.exports = {disciplined, findAccounts, byAddress, banAddress, banDevices, unbanDevices, unbanDevicesOf, byDevice, altsOf, timelineOf, appealsFor, answerAppeal, answerNameRequest};
+4
View File
@@ -5,6 +5,7 @@ const fs = require("fs");
const path = require("path");
const accounts = require("./accounts.js");
const chatFilter = require("./chatfilter.js");
const chatlog = require("./chatlog.js");
const masterpieces = require("./masterpieces.js");
const limits = require("./limits.js");
const {isUint} = require("./player.js");
@@ -155,6 +156,7 @@ module.exports = ({blocks, findOnline}) => {
const rule = message ? chatFilter.broken(message) : null;
if (rule) {
console.log(`[filter] ${viewer.username} on ${owner.username}'s wall: "${message}" (${rule})`);
chatlog.recordTo(viewer, chatlog.WALL, owner.username, chatlog.NOT_SENT + message);
const session = findOnline(viewer.username);
if (session) {
chatFilter.warn(session);
@@ -184,6 +186,8 @@ module.exports = ({blocks, findOnline}) => {
if (typeof body.pp === "string" && owner.wall.posts.some(other => other.x === body.pp)) {
post.pp = body.pp; // a reply to that post
}
// for the panels (lib/chatlog.js), as typed chat is.
chatlog.recordTo(viewer, chatlog.WALL, owner.username, message);
owner.wall.posts.push(post);
owner.wall.posts = owner.wall.posts.slice(-MAX_POSTS);
owner.wall.modified = post.t;
+143 -14
View File
@@ -14,6 +14,7 @@ const defpacks = require("./defpacks.js");
const avatarHandlers = require("./avatars.js");
const badges = require("./badges.js");
const bans = require("./bans.js");
const devices = require("./devices.js");
const chatlog = require("./chatlog.js");
const chatFilter = require("./chatfilter.js");
const buddyModule = require("./buddies.js");
@@ -43,6 +44,14 @@ const {CURRENCIES, DIAMOND_TYPES, activeAvatar, avatarById, activePet, equippedB
const GENERIC_LIST_AVATARS = 64;
const GENERIC_LIST_NEWSPAPER = 627;
// the worlds' names (ServerSelector.getShardName): localization ids, the
// game's own river names, world N being the Nth.
const GENERIC_LIST_WORLD_NAMES = 16;
const WORLD_NAME_IDS = Array.from({length: 29}, (_, i) => 551 + i);
// the settings menu's "Find Open World" switch (gui.MySettings
// SETTINGS_AUTO_SERVER_TRAVEL): a set bit is off. on, a room that is full in
// the player's world is joined in another world that has space.
const SETTING_FIND_OPEN_WORLD = 3;
const USER_VAR_NEWSPAPER_READ = 455;
const USER_VAR_GEM_BONUS = 214;
// not one of the game's: the patched client's "hide blocked players" setting
@@ -138,6 +147,19 @@ const THEME_PATH_PREFIX = "theme_"; // lib/http.js looks for this
const chatLines = limits.limiter(config.chatLinesPerWindow, config.chatWindowMs);
const online = new Map(); // lowercased username -> session
const rooms = new Map(); // "path.name#shard" -> room
// worlds (config.shards): a land room's name ends in "#<world>"; dens,
// parties and adventures have none and belong to no world. each player has
// a world (session.worldId), picked when they arrive and changed by walking
// into a room of another.
const worldOf = name => {
const found = /#(\d+)$/.exec(name || "");
return found && config.shards.some(shard => shard.id === Number(found[1])) ? Number(found[1]) : 0;
};
const worldName = id => (config.shards.find(shard => shard.id === id) || {name: `World ${id}`}).name;
const inWorld = id => [...online.values()].filter(session => session.worldId === id);
const findOpenWorld = account => !((Number((account.userVars || {})[USER_VAR_SETTINGS]) >> SETTING_FIND_OPEN_WORLD) & 1)
|| Number((account.userVars || {})[USER_VAR_SETTINGS]) < 0;
let nextRoomId = 100;
const others = session => session.room ? [...session.room.sessions].filter(s => s !== session) : [];
@@ -268,6 +290,18 @@ const login = (session, msg) => {
loginFailed(session, LOGIN_BANNED, "Banned");
return;
}
// a banned computer (lib/devices.js), and a game that never said which
// computer it is on: told at /authenticate too, which is the way in.
if (devices.banOfAccount(account)) {
console.log(`[world] login rejected for "${account.username}": hardware banned`);
loginFailed(session, LOGIN_BANNED, "Banned");
return;
}
if (config.requireDevice && devices.knownFor(account).lastAt < Math.floor(Date.now() / 1000) - 90 * 86400) {
console.log(`[world] login rejected for "${account.username}": no device ids`);
loginFailed(session, 0, "Update the client");
return;
}
// its username was rejected (lib/moderation.js): a new one first, which
// the client or the account page asks for.
if (account.nameRejected) {
@@ -632,6 +666,23 @@ const handlers = {
// defPack. list contents live on the official servers, so apart from the two
// kinds that can be rebuilt from defPacks every list is answered empty; that
// still releases whatever the client had waiting on it.
// the settings menu's world list (ServerSelector, GamePlay.showServerSelectorMore):
// a node's name, then each world as id, language, how full (0 to 4, 4
// being full) and how many of the player's buddies are in it. the game
// leaves out the world the player is in.
rm(session) {
const fields = [];
const capacity = config.spawnRooms.length * config.maxUsersPerRoom;
for (const shard of config.shards) {
const here = inWorld(shard.id);
const full = config.spawnRooms.every(base => roomFull(`${base}#${shard.id}`));
const bars = full ? 4 : Math.min(3, Math.ceil(4 * here.length / capacity));
const buddyCount = here.filter(other => session.account.buddies.includes(other.account.username.toLowerCase())).length;
fields.push(shard.id, LANG_ENG, bars, buddyCount);
}
session.sendXt("rm", -1, "burrow", ...fields);
},
gl(session, roomId, [listId]) {
if (Number(listId) === GENERIC_LIST_NEWSPAPER) {
// the client decides whether to pop the newspaper open when this list
@@ -649,6 +700,9 @@ const handlers = {
if (Number(listId) === GENERIC_LIST_AVATARS) {
entries = defpacks.avatarTypes();
}
else if (Number(listId) === GENERIC_LIST_WORLD_NAMES) {
entries = WORLD_NAME_IDS;
}
else if (defpacks.patternList(listId)) {
entries = defpacks.patternList(listId);
}
@@ -977,7 +1031,9 @@ const context = {
tell: (...args) => tell(...args),
leaveRoom: (...args) => leaveRoom(...args),
ask: (...args) => ask(...args),
travel: (session, base) => joinRoom(session, `${base}#${config.shards[0].id}`),
travel: (session, base) => joinRoom(session, `${base}#${session.worldId || config.shards[0].id}`),
worldOf,
worldName,
joinRoom: (...args) => joinRoom(...args),
staffMove: (...args) => staffMove(...args),
// the moderation module, made after this context (lib/commands.js uses it)
@@ -1157,8 +1213,11 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
if (room && room === session.room) {
return;
}
// moderators (marked so in the admin panel) are let into a full room.
if (room && room.sessions.size >= config.maxUsersPerRoom && !roles.isActiveStaff(session.account)) {
// moderators (marked so in the admin panel) are let into a full room, and
// so is a player arriving when every spawn room is full (spawnRoom).
const overflow = session.spawnOverflow;
session.spawnOverflow = false;
if (room && room.sessions.size >= config.maxUsersPerRoom && !roles.isActiveStaff(session.account) && !overflow) {
joinFailed(session, "This room is currently full");
return;
}
@@ -1171,6 +1230,13 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
}
room.sessions.add(session);
session.room = room;
// a land room is in a world, which is the player's now; a den or a party
// is in none, and the game is told the world the player was in, which it
// goes back to when they walk out (RoomManagerWorld.shardId).
if (worldOf(name)) {
session.worldId = worldOf(name);
}
const worldId = session.worldId || shardId;
if (props.denOwner && props.denOwner !== session.account) {
noteDenVisit(props.denOwner, session.account);
}
@@ -1192,7 +1258,7 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
avatar.petInvId,
LANG_ENG,
room.customMusicDef,
shardId);
worldId);
dens.sendRoomProperties(session, roomAsSeenBy(session, room));
for (const other of others(session)) {
@@ -1204,8 +1270,8 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
};
const sendHome = session => {
const shard = config.shards[0];
enterRoom(session, `${config.startupRoom}#${shard.id}`, config.startupRoom, roomInfo.name(config.startupRoom), shard.id);
const shard = session.worldId || config.shards[0].id;
enterRoom(session, `${config.startupRoom}#${shard}`, config.startupRoom, roomInfo.name(config.startupRoom), shard);
};
const emptyRoom = name => {
@@ -1267,6 +1333,37 @@ const onUnblocked = (session, target) => {
}
};
// a world for a player arriving: one at random of those whose spawn rooms
// are not all full; with every one full, the emptiest.
const pickWorld = () => {
const open = config.shards.filter(shard => config.spawnRooms.some(base => !roomFull(`${base}#${shard.id}`)));
if (open.length > 0) {
return open[Math.floor(Math.random() * open.length)].id;
}
return config.shards.reduce((emptiest, shard) => (inWorld(shard.id).length < inWorld(emptiest.id).length ? shard : emptiest)).id;
};
const roomFull = name => {
const room = rooms.get(name);
return Boolean(room) && room.sessions.size >= config.maxUsersPerRoom;
};
// a spawn room (config.spawnRooms) at random, of those with space; with
// all of them full, the emptiest, which lets this player in over the cap.
const spawnRoom = (session, shardId) => {
const known = config.spawnRooms.filter(base => defpacks.roomDef(base));
if (known.length === 0) {
return config.startupRoom;
}
const open = known.filter(base => !roomFull(`${base}#${shardId}`));
if (open.length > 0) {
return open[Math.floor(Math.random() * open.length)];
}
const size = base => (rooms.get(`${base}#${shardId}`) || {sessions: new Set()}).sessions.size;
session.spawnOverflow = true;
return known.reduce((emptiest, base) => (size(base) < size(emptiest) ? base : emptiest));
};
const joinRoom = (session, requested) => {
// "jamaa_township.room_main#-1": path, then shard (-1 = pick one for me).
let [base, shardText] = requested.split("@")[0].split("#");
@@ -1291,23 +1388,41 @@ const joinRoom = (session, requested) => {
// non-buddy's until then: it is sent ahead of the first room, as the
// client takes it unasked (BuddyManager.buddyListResponseHandler).
handlers.bl(session);
// the game asks for world -1 ("pick one for me") unless it is going back
// to one (after a reconnect, say).
session.worldId = worldOf(`#${shardText}`) || pickWorld();
const {startInDen, startRoom, username} = session.account;
const den = startInDen ? username : /^den/i.test(startRoom || "") ? startRoom.slice(3) : null;
if (den !== null && accounts.byName(den)) {
joinDen(session, `den${den}`);
return;
}
// any other name asked for that is a room here; else the usual one.
// any other name asked for that is a room here and has space; else one
// of the spawn rooms that has, so nobody's login ends at "room is full".
const asked = (startRoom || "").split("#")[0].toLowerCase();
if (!startInDen && defpacks.roomDef(asked) && !asked.startsWith("den")) {
base = asked;
}
const shardId = session.worldId;
base = !startInDen && defpacks.roomDef(asked) && !asked.startsWith("den") && !roomFull(`${asked}#${shardId}`)
? asked : spawnRoom(session, shardId);
shardText = String(shardId);
}
// switching worlds (the settings menu's world list asks for the township of
// the one picked): a full room there is swapped for one with space.
else if (worldOf(`#${shardText}`) && session.worldId && worldOf(`#${shardText}`) !== session.worldId
&& roomFull(`${base}#${shardText}`) && config.spawnRooms.includes(base)) {
base = spawnRoom(session, Number(shardText));
}
if (!defpacks.roomDef(base) || base.startsWith("den")) {
joinFailed(session, `Room "${requested}" is not supported by this server`);
return;
}
const shard = config.shards.find(s => s.id === Number(shardText)) || config.shards[0];
// a world that is not one here (-1, or one the game made up because every
// world was full) is the player's own.
let shard = config.shards.find(s => s.id === Number(shardText)) || config.shards.find(s => s.id === session.worldId) || config.shards[0];
// full there: with "Find Open World" on, the same room in a world that
// has space (moderators get into a full room anyway).
if (roomFull(`${base}#${shard.id}`) && !session.account.moderator && findOpenWorld(session.account)) {
shard = config.shards.find(other => !roomFull(`${base}#${other.id}`)) || shard;
}
enterRoom(session, `${base}#${shard.id}`, base, roomInfo.name(base), shard.id);
};
@@ -1319,7 +1434,7 @@ const joinDen = (session, requested) => {
// room like any other (lib/epicdens.js). A player of that name comes first.
const showcase = owner ? null : epicDens.byName(requested.slice(3));
if (showcase) {
const shard = config.shards[0].id;
const shard = session.worldId || config.shards[0].id;
enterRoom(session, `${showcase.base}#${shard}`, showcase.base, showcase.name, shard);
return;
}
@@ -1639,7 +1754,7 @@ module.exports = {
return "There is no such room";
}
minigames.leave(session);
const shard = config.shards[0].id;
const shard = session.worldId || config.shards[0].id;
enterRoom(session, `${base}#${shard}`, base, roomInfo.name(base), shard);
return null;
},
@@ -1653,6 +1768,20 @@ module.exports = {
}
return there.length;
},
// puts out these accounts, if playing, with the game's banned notice:
// their computer was banned (lib/devices.js). returns how many were.
disconnectBanned(list) {
let out = 0;
for (const account of list) {
const session = findOnline(account.username);
if (session) {
session.sendXt("fd", -1, "fb", 1, moderation.PERMANENT);
session.close();
out++;
}
}
return out;
},
// takes the account out of the world at once (not when its socket gets
// round to closing), so the caller can go on to rename or delete it.
disconnect(account) {
@@ -1665,7 +1794,7 @@ module.exports = {
},
players: () => [...online.values()].map(session => ({
username: session.account.username,
room: session.room ? session.room.name : null,
room: session.room ? session.room.name.replace(/#(\d+)$/, (whole, id) => (worldOf(whole) ? ` (${worldName(Number(id))})` : whole)) : null,
address: session.address,
})),
};