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

+22 -3
View File
@@ -98,6 +98,12 @@ module.exports = {
// cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only.
upstreamContent: env.AJ_UPSTREAM || "https://ajcontent.akamaized.net/",
offline: env.AJ_OFFLINE === "1",
// the client's device ids (lib/devices.js): with AJ_REQUIRE_DEVICE=1, a
// sign-in without them (a client from before 1.3.0, the official
// launcher, or one that left them out) is refused. off for now, while
// players update to 1.3.0: they are let in, and an account seen on banned
// hardware before is still kept out.
requireDevice: env.AJ_REQUIRE_DEVICE === "1",
deployVersion: env.AJ_DEPLOY_VERSION || "1830",
// older builds the CDN still serves, asked in turn for a room file the
// current build has dropped. 1828 is the last with the Summer Carnival.
@@ -116,7 +122,7 @@ module.exports = {
// 41: the game's text says "Burrow" where it said Animal Jam.
// 48: the item giver (the item finder renamed) with previews and hex colours;
// 49 and 50: its link to a colour picker.
buildVersion: env.AJ_BUILD_VERSION || "57",
buildVersion: env.AJ_BUILD_VERSION || "60",
// what the official CDN is asked for; not ours to change.
upstreamBuildVersion: "3",
@@ -246,8 +252,21 @@ module.exports = {
{room: "appondale.room_museum", shown: "appondale.room_museum_ant", months: [2, 4, 6, 8, 10, 12]},
],
startupRoom: "jamaa_township.room_main",
shards: [{id: 1, name: "Aldan"}],
maxUsersPerRoom: 80,
// where a player who does not start in their den arrives: one of these at
// random, of those that are not full (lib/world.js). AJ_SPAWN_ROOMS: a
// list of its own, comma-separated (the tests' is the township alone).
spawnRooms: env.AJ_SPAWN_ROOMS ? env.AJ_SPAWN_ROOMS.split(",").map(room => room.trim()).filter(Boolean)
: ["jamaa_township.room_main", "sarepia.room_main", "crystal_sands.room_main", "coral_canyons.room_main",
"mountains_of_shivveer.room_main", "appondale.room_main", "lost_temple_of_zios.room_main", "aussie.room_main", "balloosh.room_main"],
// the worlds, each its own copy of every land (rooms are "path#world";
// dens and parties are everyone's). a player arrives in one at random and
// can switch in the settings menu (gui.ServerSelector). the game names
// world N after the Nth name of its own list (551 Aldan, 552 Congo...,
// generic list 16), so the names here are only for the panels and logs.
// AJ_WORLDS: how many (the tests' is one).
shards: ["Aldan", "Congo", "Draa", "Grande", "Kama", "Nile", "Pecos", "Ramu", "Tigris", "Zambezi"]
.slice(0, Math.min(10, Math.max(1, Number(env.AJ_WORLDS) || 2))).map((name, i) => ({id: i + 1, name})),
maxUsersPerRoom: 40,
// everything in every shop for nothing (AJ_FREE_SHOPS=1). off unless
// asked for: what the game's shops make of a price of 0 has not been seen.
freeShops: env.AJ_FREE_SHOPS === "1",
+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,
})),
};
+621 -53
View File
@@ -158,6 +158,8 @@
tbody tr:last-child td { border-bottom: 0; }
tbody tr.selected td { background: var(--raised); }
tbody tr.pick { cursor: pointer; }
.device-id { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 12px; }
button.link { background: none; border: 0; padding: 0; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; font-weight: 400; }
.empty { color: var(--muted); padding: 8px 0; }
.toolbar { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; }
.toolbar input[type="search"] { flex: 1; min-width: 180px; }
@@ -193,11 +195,26 @@
.report .typed { margin: 8px 0; padding: 8px 12px; background: var(--bg); border: 1px solid var(--line); border-radius: 14px; overflow-wrap: anywhere; }
.report pre { margin: 8px 0; padding: 8px 12px; background: var(--bg); border: 1px solid var(--line); border-radius: 14px; font: 12px/1.5 ui-monospace, Consolas, monospace; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 180px; overflow: auto; }
.report .buttons { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; }
.chat-list { margin: 0; padding: 0; list-style: none; }
.chat-list li { display: flex; gap: 10px; align-items: baseline; padding: 6px 4px; border-bottom: 1px solid var(--line); }
.chat-list li:last-child { border-bottom: 0; }
.chat-list li.this { background: var(--raised); border-radius: 10px; }
.chat-time { flex: none; width: 128px; color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
.chat-who { flex: none; max-width: 190px; padding: 0; border: 0; font-weight: 700; text-align: left; overflow: hidden; text-overflow: ellipsis; }
.chat-who:hover { background: none; text-decoration: underline; }
.chat-text { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.chat-room { display: block; color: var(--muted); font-size: 12px; }
.chat-more { flex: none; padding: 2px 10px 3px; font-size: 12px; }
#timeline { margin: 0; padding-left: 18px; font-size: 13px; overflow-wrap: anywhere; }
.paintings { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 12px; }
.painting { border: 1px solid var(--line); border-radius: 18px; padding: 14px; }
.painting img { display: block; width: 100%; height: auto; border-radius: 10px; background: #fff; }
.painting h3 { margin: 8px 0 2px; }
.painting .buttons { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; }
.painting img { cursor: zoom-in; }
.preview { position: fixed; inset: 0; z-index: 50; display: flex; align-items: center; justify-content: center; padding: 16px; background: rgba(0, 0, 0, 0.85); cursor: zoom-out; }
.preview[hidden] { display: none; }
.preview img { max-width: 100%; max-height: 100%; border-radius: 10px; background: #fff; }
textarea { width: 100%; resize: vertical; }
.send-row { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; align-items: center; }
#owned { margin-top: 16px; }
@@ -245,6 +262,7 @@
<nav role="tablist">
<button role="tab" data-tab="overview" aria-selected="true">Overview</button>
<button role="tab" data-tab="accounts" aria-selected="false">Accounts</button>
<button role="tab" data-tab="chat" aria-selected="false">Chat</button>
<button role="tab" data-tab="stats" aria-selected="false">Stats</button>
<button role="tab" data-tab="reports" aria-selected="false">Reports<span id="report-count"></span></button>
<button role="tab" data-tab="support" aria-selected="false">Requests<span id="support-count"></span></button>
@@ -285,6 +303,7 @@
<select id="account-search-by" aria-label="Search by">
<option value="name">By name</option>
<option value="address">By IP address</option>
<option value="device">By hardware ID</option>
</select>
<input id="account-search" type="search" placeholder="Search" aria-label="Search accounts">
<select id="account-filter" aria-label="Which accounts">
@@ -294,10 +313,9 @@
</select>
</div>
<div id="address-view" hidden>
<p class="hint">Accounts that signed in from this address, or from addresses starting with it, in the last 90 days.</p>
<p class="status" id="address-status" role="status"></p>
<div class="table-wrap"><table>
<thead><tr><th>Name</th><th>State</th><th>Addresses</th><th>Last from there</th></tr></thead>
<thead><tr><th>Name</th><th>State</th><th id="found-what">Addresses</th><th id="found-when">Last from there</th></tr></thead>
<tbody id="address-results"></tbody>
</table></div>
</div>
@@ -306,6 +324,7 @@
<tbody id="accounts"></tbody>
</table></div>
<div class="empty" id="no-accounts" hidden>No accounts match.</div>
<p class="hint" id="account-more" hidden></p>
<div id="detail" hidden>
<h2 id="detail-name"></h2>
@@ -355,7 +374,9 @@
<div class="row" style="margin-top:8px">
<button type="button" data-action="ban" class="danger">Ban</button>
<button type="button" data-action="banReason">Save reason</button>
<button type="button" data-action="unban">Lift</button></div>
<button type="button" data-action="unban">Lift</button>
<button type="button" data-action="banDevices" class="danger">Hardware ban</button>
<button type="button" data-action="unbanDevices">Lift hardware ban</button></div>
<div id="ban-record"></div>
</div>
<div class="action">
@@ -369,6 +390,14 @@
<div class="row"><input id="message-text" maxlength="200" placeholder="Text" aria-label="Message">
<button type="button" data-action="message">Send</button></div>
</div>
<div class="action">
<h3>Look into</h3>
<p class="hint" id="look-facts"></p>
<div class="buttons">
<button type="button" id="open-chat">Chat history</button>
<button type="button" id="open-paintings">Paintings</button>
</div>
</div>
<div class="action">
<h3>Gems</h3>
<div class="row"><input id="gems-amount" type="number" placeholder="Amount" aria-label="Gems to add">
@@ -412,11 +441,69 @@
</div>
</div>
</div>
<h2 style="margin-top:20px">Other accounts</h2>
<div class="table-wrap"><table>
<thead><tr><th>Name</th><th>State</th><th>Same hardware</th><th class="num">Same addresses</th></tr></thead>
<tbody id="alts"></tbody>
</table></div>
<div class="empty" id="no-alts" hidden>None found.</div>
<h2 style="margin-top:20px">Hardware IDs</h2>
<div class="table-wrap"><table>
<thead><tr><th>Kind</th><th>Id</th><th>First seen</th><th>Last seen</th><th class="num">Other accounts</th><th>State</th></tr></thead>
<tbody id="device-ids"></tbody>
</table></div>
<div class="empty" id="no-device-ids" hidden>None.</div>
<h2 style="margin-top:20px">Jam-a-Grams and wall posts</h2>
<div class="toolbar">
<select id="mail-kind" aria-label="Which">
<option value="jamagram">Jam-a-Grams</option>
<option value="wall">Jammer Wall posts</option>
</select>
<select id="mail-direction" aria-label="Sent or received">
<option value="">Sent and received</option>
<option value="sent">Sent by them</option>
<option value="received">Sent to them</option>
</select>
</div>
<ul id="mail-lines" class="chat-list"></ul>
<div class="empty" id="no-mail" hidden>Nothing kept.</div>
<button type="button" id="mail-older" hidden>Older</button>
<h2 style="margin-top:20px">Timeline</h2>
<ul id="timeline"></ul>
<div class="empty" id="no-timeline" hidden>Nothing yet.</div>
<div id="owned"></div>
</div>
</section>
</div>
<div data-view="chat" hidden>
<section>
<form id="chat-form" class="toolbar">
<input id="chat-player" maxlength="100" placeholder="Player" autocomplete="off" spellcheck="false" aria-label="Player">
<input id="chat-room" maxlength="100" placeholder="Room" autocomplete="off" spellcheck="false" aria-label="Room">
<input id="chat-text" maxlength="100" placeholder="Words" autocomplete="off" aria-label="Words" style="flex:1">
<select id="chat-kind" aria-label="What">
<option value="">Everything</option>
<option value="chat">Chat</option>
<option value="whisper">Whispers</option>
<option value="jamagram">Jam-a-Grams</option>
<option value="wall">Wall posts</option>
<option value="notsent">Stopped by the filter</option>
</select>
<input id="chat-until" type="datetime-local" aria-label="From this time back">
<button class="primary" type="submit">Search</button>
</form>
<p class="status" id="chat-status" role="status"></p>
<div id="context-box" hidden>
<div class="toolbar"><h2 style="margin:0;flex:1" id="context-title"></h2><button type="button" id="context-close">Close</button></div>
<ul class="chat-list" id="chat-context"></ul>
</div>
<ul class="chat-list" id="chat-lines"></ul>
<div class="empty" id="no-chat" hidden>Nothing here.</div>
<div class="send-row"><button type="button" id="chat-older" hidden>Older</button></div>
</section>
</div>
<div data-view="reports" hidden>
<section>
<div class="toolbar">
@@ -498,6 +585,31 @@
</table></div>
<div class="empty" id="no-addresses" hidden>No address is banned.</div>
</section>
<section>
<h2>Hardware bans</h2>
<p class="status" id="device-status" role="status"></p>
<div class="table-wrap"><table>
<thead><tr><th>Banned with</th><th>Reason</th><th>By</th><th>Since</th><th>Accounts</th><th>Ids</th><th></th></tr></thead>
<tbody id="device-bans"></tbody>
</table></div>
<div class="empty" id="no-device-bans" hidden>No hardware bans.</div>
</section>
<section>
<h2>Hardware alerts</h2>
<div class="table-wrap"><table>
<thead><tr><th>When</th><th>Player</th><th>What</th><th>Detail</th></tr></thead>
<tbody id="device-alerts"></tbody>
</table></div>
<div class="empty" id="no-device-alerts" hidden>Nothing yet.</div>
</section>
<section>
<h2>Stopped most by the filter</h2>
<div class="table-wrap"><table>
<thead><tr><th>Player</th><th class="num">Stopped</th><th>Last</th><th></th></tr></thead>
<tbody id="filter-hits"></tbody>
</table></div>
<div class="empty" id="no-filter-hits" hidden>Nobody.</div>
</section>
</div>
<div data-view="messages" hidden>
@@ -527,12 +639,15 @@
<select id="masterpiece-filter" aria-label="Which masterpieces">
<option value="waiting">Waiting</option>
<option value="approved">Approved</option>
<option value="all">All</option>
</select>
<input id="masterpiece-creator" type="search" maxlength="100" placeholder="Maker's username" autocomplete="off" spellcheck="false" aria-label="Maker's username">
</div>
<label class="check"><input id="masterpiece-review" type="checkbox"> Review new masterpieces</label>
<p class="status" id="masterpiece-status" role="status"></p>
<div class="paintings" id="masterpieces"></div>
<div class="empty" id="no-masterpieces" hidden>Nothing here.</div>
<div class="preview" id="preview" hidden><img id="preview-img" alt=""></div>
</section>
</div>
@@ -600,7 +715,9 @@
const MAX_LOG_LINES = 2000;
let state = null; // {needsSetup, needsSetupCode, signedIn}
let accounts = [];
let accounts = []; // the rows the search found (at most a page)
let accountTotal = 0; // how many matched in all
let current = null; // the open account's row, fetched on its own
let badges = []; // {id, label}: the badges an account's card can show
let selected = null; // username whose actions are shown
let tab = "overview";
@@ -639,6 +756,18 @@
};
const when = seconds => (seconds ? new Date(seconds * 1000).toLocaleString([], {dateStyle: "medium", timeStyle: "short"}) : "never");
const said = result => result.data.ok || result.data.error || "That did not work.";
// a button that does something, and cannot be pressed again until it is done.
const btn = (label, onClick, className) => {
const node = el("button", label, className);
node.type = "button";
node.addEventListener("click", async () => {
node.disabled = true;
await onClick();
node.disabled = false;
});
return node;
};
const duration = seconds => {
const units = [[86400, "day"], [3600, "hour"], [60, "minute"]];
@@ -748,6 +877,9 @@
if (account.silenced) {
tags.push(el("span", "Silenced", "tag bad"));
}
if (account.deviceBanned) {
tags.push(el("span", "Hardware banned", "tag bad"));
}
if (account.locked) {
tags.push(el("span", "Locked", "tag bad"));
}
@@ -778,9 +910,10 @@
return days > 0 ? `${days.toLocaleString()}d ${hours}h` : hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
};
// by IP address: the server looks through the sign-in histories.
let addressFound = null; // {query, players} or null
// by IP address (the sign-in histories) or hardware ID (lib/devices.js).
let addressFound = null; // {query, by, players} or null
const searchByAddress = async () => {
const by = $("account-search-by").value;
const query = $("account-search").value.trim();
if (query === "") {
addressFound = null;
@@ -788,11 +921,11 @@
renderAccounts();
return;
}
const result = await api(`address-search?q=${encodeURIComponent(query)}`);
if (query !== $("account-search").value.trim()) {
const result = await api(`${by}-search?q=${encodeURIComponent(query)}`);
if (query !== $("account-search").value.trim() || by !== $("account-search-by").value) {
return; // typed on meanwhile
}
addressFound = result.ok ? {query, players: result.data.players} : null;
addressFound = result.ok ? {query, by, players: result.data.players} : null;
setStatus($("address-status"), result.ok ? (result.data.players.length ? "" : "Nobody signed in from there.") : result.data.error || "That did not work.", !result.ok);
renderAccounts();
};
@@ -811,25 +944,30 @@
stateCell.append(...accountState(account).flatMap(tag => [tag, " "]));
}
row.addEventListener("click", () => select(entry.username));
row.append(nameCell, stateCell, el("td", entry.addresses.map(one => one.address).join(", ")), el("td", when(entry.lastAt)));
if (!account && entry.online) {
stateCell.append(el("span", "Online", "tag"));
}
row.append(nameCell, stateCell, el("td", entry.addresses ? entry.addresses.map(one => one.address).join(", ") : entry.kinds.map(kind => KIND_NAMES[kind] || kind).join(", ")),
el("td", when(entry.lastAt)));
return row;
}));
};
const renderAccounts = () => {
const byAddress = $("account-search-by").value === "address";
const searchBy = $("account-search-by").value;
const byAddress = searchBy !== "name";
$("address-view").hidden = !byAddress;
$("found-what").textContent = searchBy === "device" ? "Ids matched" : "Addresses";
$("found-when").textContent = searchBy === "device" ? "Last used" : "Last from there";
$("account-list").hidden = byAddress;
if (byAddress) {
renderAddressResults();
$("no-accounts").hidden = true;
}
const query = byAddress ? "" : $("account-search").value.trim().toLowerCase();
const filter = $("account-filter").value;
const shown = accounts
.filter(account => account.username.toLowerCase().includes(query))
.filter(account => filter === "all" || (filter === "online" ? account.online : account.banned !== 0))
.sort((a, b) => Number(b.online) - Number(a.online) || a.username.localeCompare(b.username));
// found and put in order by the server (exact name first).
const shown = byAddress ? [] : accounts;
$("account-more").hidden = byAddress || accountTotal <= shown.length;
$("account-more").textContent = `Showing ${shown.length} of ${accountTotal.toLocaleString()}. Type more of the name to narrow it down.`;
$("accounts").replaceChildren(...shown.map(account => {
const row = el("tr", undefined, account.username === selected ? "pick selected" : "pick");
const stateCell = el("td");
@@ -851,10 +989,11 @@
if (!byAddress) {
$("no-accounts").hidden = shown.length > 0;
}
const current = accounts.find(account => account.username === selected);
$("detail").hidden = !current;
if (current) {
$("detail-name").textContent = `${current.username} · ${current.gems.toLocaleString()} gems · played ${played(current.playtime || 0)}${current.playtimePublic ? " (public)" : ""}`;
$("look-facts").textContent = `Stopped by the filter: ${current.stoppedThisWeek} in the last 7 days · Hardware IDs: `
+ `${current.devicesKnown || "none yet"} · Paintings: ${current.paintings}`;
}
};
@@ -953,7 +1092,6 @@
};
const fillCard = () => {
const current = accounts.find(account => account.username === selected);
$("badge-boxes").replaceChildren(...badges.map(badge => {
const label = el("label", undefined, "check");
const box = el("input");
@@ -971,16 +1109,151 @@
$("role-select").value = current && current.role ? current.role : "none";
};
const select = username => {
selected = selected === username ? null : username;
// the open account's own row, whatever the search shows.
const loadCurrent = async () => {
const username = selected;
if (!username) {
current = null;
return;
}
const result = await api(`account?username=${encodeURIComponent(username)}`);
if (username !== selected) {
return;
}
current = result.ok ? result.data.account : null;
badges = result.ok ? result.data.badges : badges;
if (!current) {
selected = null;
}
};
// an account to open, from this page or another: its row, card and records.
const openAccount = async username => {
selected = username;
current = null;
setStatus($("detail-status"), "");
for (const id of ["new-name", "new-password", "ban-hours", "silence-hours", "message-text", "gems-amount", "gift-value", "gift-text"]) {
$(id).value = "";
}
hashArg = username;
setHash();
await loadCurrent();
renderAccounts();
fillCard();
loadOwned();
loadBanRecord();
loadExtras();
};
// every account that used a hardware ID: the account list, searched by it.
const searchDevice = id => {
$("account-search-by").value = "device";
$("account-search").placeholder = "Hardware ID, or the start of one";
$("account-search").value = id;
showTab("accounts");
searchByAddress();
window.scrollTo(0, 0);
};
// from another page.
const openAccountTab = username => {
hashArg = username;
showTab("accounts");
openAccount(username);
};
// the player's Jam-a-Grams or wall posts, sent and received
// (lib/chatlog.js): asked with the rest of the extras, and a page more
// with Older. "(not sent)" in front is one the filter stopped.
let mailLines = [];
const loadMail = async older => {
const username = selected;
if (!username) {
return;
}
const before = older && mailLines.length ? mailLines[mailLines.length - 1].id : 0;
const result = await api(`chat?username=${encodeURIComponent(username)}&kind=${$("mail-kind").value}`
+ `&direction=${$("mail-direction").value}&before=${before}`);
if (username !== selected) {
return;
}
const lines = result.ok ? result.data.lines : [];
mailLines = older ? [...mailLines, ...lines] : lines;
$("mail-lines").replaceChildren(...mailLines.map(line => lineNode(line, true)));
$("no-mail").hidden = mailLines.length > 0;
$("mail-older").hidden = !(result.ok && result.data.more);
};
$("mail-kind").addEventListener("change", () => loadMail(false));
$("mail-direction").addEventListener("change", () => loadMail(false));
$("mail-older").addEventListener("click", () => loadMail(true));
// other accounts the same person may have, and what happened to them:
// asked when an account is opened and after an action, not every few
// seconds (finding alts looks through every account).
const KIND_NAMES = {os: "system id", board: "board", disk: "disk", install: "client id", mac: "network card"};
const TIMELINE_NAMES = {ban: "Ban", staff: "Staff", report: "Report", alert: "Alert"};
const loadExtras = async () => {
const username = selected;
$("alts").replaceChildren();
$("device-ids").replaceChildren();
$("mail-lines").replaceChildren();
$("timeline").replaceChildren();
if (!username) {
return;
}
loadMail(false);
const [alts, timeline] = await Promise.all([api(`alts?username=${encodeURIComponent(username)}`), api(`timeline?username=${encodeURIComponent(username)}`)]);
if (username !== selected) {
return;
}
const altList = alts.ok ? alts.data.alts : [];
$("alts").replaceChildren(...altList.map(alt => {
const row = el("tr", undefined, "pick");
const stateCell = el("td");
if (alt.online) {
stateCell.append(el("span", "Online", "tag"), " ");
}
if (alt.banned !== 0) {
stateCell.append(el("span", alt.banned === -1 ? "Banned" : `Banned ${duration(alt.banned)}`, "tag bad"), " ");
}
if (alt.deviceBanned) {
stateCell.append(el("span", "Hardware banned", "tag bad"));
}
row.append(el("td", alt.username), stateCell,
el("td", alt.devices.length ? `${alt.devices.map(kind => KIND_NAMES[kind] || kind).join(", ")}${alt.weak ? " (weak)" : ""}` : "—"),
el("td", alt.addresses ? String(alt.addresses) : "—", "num"));
row.addEventListener("click", () => openAccount(alt.username));
return row;
}));
$("no-alts").hidden = altList.length > 0;
const ids = alts.ok ? alts.data.ids : [];
$("device-ids").replaceChildren(...ids.map(entry => {
const row = el("tr", undefined, "pick");
row.title = "Every account that used this id";
row.append(el("td", KIND_NAMES[entry.kind] || entry.kind), el("td", entry.id, "device-id"), el("td", when(entry.first)), el("td", when(entry.last)),
el("td", String(entry.others), "num"), el("td", !entry.banned ? "—" : entry.kind === "mac" ? "Banned (alerts only)" : "Banned"));
row.addEventListener("click", () => searchDevice(entry.id));
return row;
}));
$("no-device-ids").hidden = ids.length > 0;
const events = timeline.ok ? timeline.data.events : [];
$("timeline").replaceChildren(...events.map(entry => el("li", [when(entry.at), TIMELINE_NAMES[entry.kind] || entry.kind, entry.text, entry.by && `by ${entry.by}`]
.filter(Boolean).join(" · "))));
$("no-timeline").hidden = events.length > 0;
};
const select = username => {
if (selected === username) {
selected = null;
current = null;
hashArg = "";
setHash();
renderAccounts();
loadOwned();
loadBanRecord();
loadExtras();
return;
}
openAccount(username);
};
const GIFT_PLACEHOLDERS = {gems: "Amount", diamonds: "Amount", tickets: "Amount", clothing: "Item id", den: "Item id",
@@ -1007,9 +1280,9 @@
case "password": return {password: $("new-password").value};
case "lastSeen": return {when: Math.floor(new Date($("last-seen").value).getTime() / 1000)};
case "ban": return {hours: numberFrom("ban-hours"), reason: $("ban-reason").value};
case "banReason": return {reason: $("ban-reason").value};
case "banReason": case "banDevices": return {reason: $("ban-reason").value};
case "silence": return {hours: numberFrom("silence-hours")};
case "moderator": return {on: !(accounts.find(account => account.username === selected) || {}).moderator};
case "moderator": return {on: !(current || {}).moderator};
case "role": return {role: $("role-select").value};
case "message": return {text: $("message-text").value};
case "gems": return {amount: numberFrom("gems-amount")};
@@ -1042,6 +1315,12 @@
if (action === "delete" && !window.confirm(`Delete ${selected} and everything they own? This cannot be undone.`)) {
return;
}
if (action === "unbanDevices" && !window.confirm(`Lift the hardware bans on ${selected}?`)) {
return;
}
if (action === "banDevices" && !window.confirm(`Hardware ban ${selected}? Everyone on their hardware is put out.`)) {
return;
}
button.disabled = true;
const result = await api("account", {username: selected, action, ...actionBody(action)});
button.disabled = false;
@@ -1059,30 +1338,40 @@
fillCard();
loadOwned();
loadBanRecord();
loadExtras();
}
});
// the server searches, once typing stops for a moment.
let addressWait = null;
$("account-search").addEventListener("input", () => {
if ($("account-search-by").value === "address") {
clearTimeout(addressWait);
addressWait = setTimeout(searchByAddress, 400);
clearTimeout(addressWait);
addressWait = setTimeout($("account-search-by").value !== "name" ? searchByAddress : refresh, $("account-search-by").value !== "name" ? 400 : 250);
});
// Enter opens the account of exactly that name, when there is one.
$("account-search").addEventListener("keydown", async event => {
if (event.key !== "Enter" || $("account-search-by").value !== "name") {
return;
}
else {
renderAccounts();
clearTimeout(addressWait);
await refresh();
const wanted = $("account-search").value.trim().toLowerCase();
const exact = accounts.find(account => account.username.toLowerCase() === wanted);
if (exact && exact.username !== selected) {
openAccount(exact.username);
}
});
$("account-search-by").addEventListener("change", () => {
const byAddress = $("account-search-by").value === "address";
$("account-search").placeholder = byAddress ? "203.0.113.7, or the start of one" : "Search";
const byAddress = $("account-search-by").value !== "name";
$("account-search").placeholder = {address: "203.0.113.7, or the start of one", device: "Hardware ID, or the start of one"}[$("account-search-by").value] || "Search";
if (byAddress) {
searchByAddress();
}
else {
renderAccounts();
refresh();
}
});
$("account-filter").addEventListener("change", renderAccounts);
$("account-filter").addEventListener("change", () => refresh());
const act = async (username, action, extra, statusElement) => {
const result = await api("account", {username, action, ...extra});
@@ -1090,9 +1379,91 @@
return result.ok;
};
const renderReports = data => {
// ---- the Chat page: what players typed, sent and posted (lib/chatlog.js).
let chatQuery = null; // {username, room, text, kind, until}
let chatLines = [];
const chatUrl = before => `chat?username=${encodeURIComponent(chatQuery.username)}&room=${encodeURIComponent(chatQuery.room)}`
+ `&text=${encodeURIComponent(chatQuery.text)}&kind=${chatQuery.kind || ""}&until=${chatQuery.until || 0}&before=${before}`;
// where a line was said: a room, or who it went to.
const placeOf = line => (line.kind === "whisper" ? `Whisper to ${line.to}` : line.kind === "jamagram" ? `Jam-a-Gram to ${line.to}`
: line.kind === "wall" ? `On ${line.to}'s wall` : line.room);
const lineNode = (line, inContext = false) => {
const item = el("li", undefined, inContext && line.marked ? "this" : "");
const who = btn(line.username, () => openAccountTab(line.username), "chat-who");
const text = el("span", undefined, "chat-text");
text.append(line.text || "(no words)", el("span", placeOf(line), "chat-room"));
item.append(el("span", when(line.at), "chat-time"), who, text);
if (!inContext) {
item.append(btn("Around", () => showContext(line.id), "chat-more"));
}
return item;
};
const loadChat = async older => {
if (!chatQuery) {
chatQuery = {username: "", room: "", text: "", kind: "", until: 0};
}
const before = older && chatLines.length ? chatLines[chatLines.length - 1].id : 0;
const result = await api(chatUrl(before));
if (!result.ok) {
setStatus($("chat-status"), said(result), true);
return;
}
chatLines = older ? [...chatLines, ...result.data.lines] : result.data.lines;
setStatus($("chat-status"), result.data.days > 0 ? `Kept ${result.data.days} days.` : "Chat is not being kept.");
$("chat-lines").replaceChildren(...chatLines.map(line => lineNode(line)));
$("no-chat").hidden = chatLines.length > 0;
$("chat-older").hidden = !result.data.more;
};
const showContext = async id => {
const result = await api(`chat/around?id=${id}`);
if (!result.ok) {
setStatus($("chat-status"), said(result), true);
return;
}
const {line, lines} = result.data;
$("context-title").textContent = line.kind === "chat" ? line.room : `${line.username} and ${line.to}`;
$("chat-context").replaceChildren(...lines.map(entry => lineNode({...entry, marked: entry.id === line.id}, true)));
$("context-box").hidden = false;
$("context-box").scrollIntoView({block: "nearest"});
};
$("context-close").addEventListener("click", () => {
$("context-box").hidden = true;
});
$("chat-form").addEventListener("submit", event => {
event.preventDefault();
const until = $("chat-until").value ? Math.floor(new Date($("chat-until").value).getTime() / 1000) : 0;
chatQuery = {username: $("chat-player").value.trim(), room: $("chat-room").value.trim(), text: $("chat-text").value.trim(), kind: $("chat-kind").value, until};
$("context-box").hidden = true;
loadChat(false);
});
$("chat-older").addEventListener("click", () => loadChat(true));
const openChat = (username, kind = "") => {
$("chat-player").value = username;
$("chat-room").value = "";
$("chat-text").value = "";
$("chat-kind").value = kind;
$("chat-until").value = "";
chatQuery = {username, room: "", text: "", kind, until: 0};
$("context-box").hidden = true;
hashArg = username;
showTab("chat");
};
// what the reported player said up to the report, once asked for: report id -> lines.
const reportChat = new Map();
let reportsShown = "";
let lastReports = null;
const renderReports = (data, force = false) => {
const handled = $("report-filter").value === "1";
$("report-count").textContent = data.open ? ` (${data.open})` : "";
lastReports = data;
// drawn again only when the list changed.
const shown = `${handled} ${data.reports.map(report => report.id).join(",")}`;
if (shown === reportsShown && !force) {
return;
}
reportsShown = shown;
$("reports").replaceChildren(...data.reports.map(report => {
const box = el("div", undefined, "report");
box.append(el("h3", `${report.target} — ${report.reason}`),
@@ -1103,6 +1474,22 @@
if (report.context) {
box.append(el("pre", report.context));
}
if (reportChat.has(report.id)) {
const lines = reportChat.get(report.id);
const list = el("ul", undefined, "chat-list");
list.append(...lines.map(line => lineNode(line, true)));
box.append(el("h3", `What ${report.target} said up to the report`), lines.length ? list : el("div", "Nothing kept.", "hint"));
}
const chatButton = btn(reportChat.has(report.id) ? "Hide chat" : "Chat at the time", async () => {
if (reportChat.has(report.id)) {
reportChat.delete(report.id);
}
else {
const result = await api(`chat?username=${encodeURIComponent(report.target)}&until=${report.createdAt + 60}&before=0`);
reportChat.set(report.id, result.ok ? result.data.lines.slice(0, 20).reverse() : []);
}
renderReports(lastReports, true);
});
if (!handled) {
const buttons = el("div", undefined, "buttons");
const button = (label, run, className) => {
@@ -1123,15 +1510,18 @@
}, "primary"),
button("Silence 1 hour", () => act(report.target, "silence", {hours: 1}, $("report-status"))),
button("Ban 1 day", () => act(report.target, "ban", {hours: 24}, $("report-status")), "danger"),
chatButton,
button("Chat history", async () => openChat(report.target)),
button("Open account", async () => {
selected = report.target;
showTab("accounts");
loadOwned();
openAccountTab(report.target);
}));
box.append(buttons);
}
else {
box.append(el("div", `Dealt with on ${when(report.handledAt)}`, "hint"));
const buttons = el("div", undefined, "buttons");
buttons.append(chatButton);
box.append(buttons);
}
return box;
}));
@@ -1231,14 +1621,29 @@
$("support-filter").addEventListener("change", () => refresh());
let paintingsShown = "";
// the picture full size, over the page; a click puts it away.
const showPreview = src => {
$("preview-img").src = src;
$("preview").hidden = false;
};
$("preview").addEventListener("click", () => {
$("preview").hidden = true;
});
document.addEventListener("keydown", event => {
if (event.key === "Escape") {
$("preview").hidden = true;
}
});
const renderMasterpieces = data => {
const which = $("masterpiece-filter").value;
const paintings = data[which];
$("masterpiece-count").textContent = data.waiting.length ? ` (${data.waiting.length})` : "";
const marked = (list, status) => list.map(painting => ({...painting, status}));
const paintings = which === "all" ? [...marked(data.waiting, "waiting"), ...marked(data.approved, "approved")] : marked(data[which], which);
$("masterpiece-count").textContent = data.waitingCount ? ` (${data.waitingCount})` : "";
$("masterpiece-review").checked = data.review;
$("no-masterpieces").hidden = paintings.length > 0;
// drawn again only when the list changed, so the pictures do not flicker.
const shown = `${which} ${paintings.map(painting => `${painting.id}:${painting.likes}`).join(" ")}`;
const shown = `${which} ${paintings.map(painting => `${painting.id}:${painting.likes}:${painting.status}`).join(" ")}`;
if (shown === paintingsShown) {
return;
}
@@ -1249,8 +1654,10 @@
picture.src = `/admin/api/masterpiece?id=${encodeURIComponent(painting.id)}`;
picture.alt = `Painting by ${painting.creator}`;
picture.loading = "lazy";
picture.addEventListener("click", () => showPreview(picture.src));
box.append(picture, el("h3", painting.creator),
el("div", `${when(painting.createdAt)}${which === "approved" ? `, ${painting.likes} like${painting.likes === 1 ? "" : "s"}` : ""}`, "hint"));
el("div", `${when(painting.createdAt)}${painting.status === "approved" ? `, ${painting.likes} like${painting.likes === 1 ? "" : "s"}` : ""}`
+ `${which === "all" ? (painting.status === "waiting" ? " · waiting" : " · approved") : ""}`, "hint"));
const buttons = el("div", undefined, "buttons");
const button = (label, action, className) => {
const node = el("button", label, className);
@@ -1263,7 +1670,7 @@
});
return node;
};
if (which === "waiting") {
if (painting.status === "waiting") {
buttons.append(button("Approve", "approve", "primary"), button("Reject", "reject", "danger"));
}
else {
@@ -1272,9 +1679,7 @@
const open = el("button", "Open account");
open.type = "button";
open.addEventListener("click", () => {
selected = painting.creator;
showTab("accounts");
loadOwned();
openAccountTab(painting.creator);
});
buttons.append(open);
box.append(buttons);
@@ -1283,11 +1688,62 @@
};
$("masterpiece-filter").addEventListener("change", () => refresh());
let creatorWait = null;
$("masterpiece-creator").addEventListener("input", () => {
clearTimeout(creatorWait);
creatorWait = setTimeout(refresh, 250);
});
// a player's paintings, waiting and approved.
const openPaintings = username => {
$("masterpiece-creator").value = username;
$("masterpiece-filter").value = "all";
hashArg = username;
showTab("masterpieces");
};
$("masterpiece-review").addEventListener("change", async () => {
const result = await api("masterpiece", {action: "review", on: $("masterpiece-review").checked});
setStatus($("masterpiece-status"), result.data.ok || result.data.error || "That did not work.", !result.ok);
});
// a hardware ban's accounts and ids, each one a link.
const deviceAccounts = names => {
const cell = el("td");
cell.style.whiteSpace = "normal";
cell.append(...(names.length ? names.flatMap((name, index) => {
const link = el("button", name, "link");
link.type = "button";
link.addEventListener("click", () => openAccountTab(name));
return index ? [", ", link] : [link];
}) : ["—"]));
return cell;
};
const openBanIds = new Set();
const deviceIds = ban => {
const cell = el("td");
const shown = openBanIds.has(ban.id);
const toggle = el("button", shown ? `Hide ${ban.ids.length}` : `Show ${ban.ids.length}`, "link");
toggle.type = "button";
toggle.addEventListener("click", () => {
if (openBanIds.has(ban.id)) {
openBanIds.delete(ban.id);
}
else {
openBanIds.add(ban.id);
}
refresh();
});
cell.append(toggle);
if (shown) {
for (const entry of ban.ids) {
const link = el("button", `${KIND_NAMES[entry.kind] || entry.kind} ${entry.id}`, "link device-id");
link.type = "button";
link.addEventListener("click", () => searchDevice(entry.id));
cell.append(el("br"), link);
}
}
return cell;
};
const renderBans = data => {
const left = seconds => (seconds === -1 ? "Until lifted" : seconds ? `${duration(seconds)} left` : "—");
$("bans").replaceChildren(...data.accounts.map(account => {
@@ -1330,6 +1786,42 @@
return row;
}));
$("no-addresses").hidden = data.addresses.length > 0;
$("device-bans").replaceChildren(...data.devices.map(ban => {
const row = el("tr");
const buttons = el("td");
buttons.append(btn("Unban", async () => {
if (!window.confirm(`Lift the hardware ban made with ${ban.username}?`)) {
return;
}
const result = await api("device", {id: ban.id});
setStatus($("device-status"), said(result), !result.ok);
refresh();
}), " ", btn("Open account", async () => openAccountTab(ban.username)));
row.append(el("td", ban.username || "—"), el("td", ban.reason), el("td", ban.by || "—"), el("td", when(ban.createdAt)),
deviceAccounts(ban.accounts), deviceIds(ban), buttons);
return row;
}));
$("no-device-bans").hidden = data.devices.length > 0;
$("device-alerts").replaceChildren(...data.alerts.map(entry => {
const row = el("tr", undefined, "pick");
const detail = el("td", entry.detail);
detail.style.whiteSpace = "normal";
row.append(el("td", when(entry.at)), el("td", entry.username), el("td", entry.name), detail);
row.addEventListener("click", () => openAccountTab(entry.username));
return row;
}));
$("no-device-alerts").hidden = data.alerts.length > 0;
};
const renderFilterHits = list => {
$("filter-hits").replaceChildren(...list.map(entry => {
const row = el("tr");
const buttons = el("td");
buttons.append(btn("Lines", async () => openChat(entry.username, "notsent")), " ", btn("Open account", async () => openAccountTab(entry.username)));
row.append(el("td", entry.username), el("td", String(entry.count), "num"), el("td", when(entry.last)), buttons);
return row;
}));
$("no-filter-hits").hidden = list.length > 0;
};
$("address-form").addEventListener("submit", async event => {
@@ -1465,6 +1957,21 @@
if (!state || !state.signedIn) {
return;
}
// what waits, on the tabs and in the page's title (for when it is in
// another tab).
const counts = await api("counts");
if (counts.ok) {
$("report-count").textContent = counts.data.reports ? ` (${counts.data.reports})` : "";
$("support-count").textContent = counts.data.support ? ` (${counts.data.support})` : "";
$("masterpiece-count").textContent = counts.data.masterpieces ? ` (${counts.data.masterpieces})` : "";
const waiting = counts.data.reports + counts.data.support + counts.data.masterpieces;
document.title = waiting ? `(${waiting}) Server admin` : "Server admin";
}
// out of sight, only that; the rest when it is back.
if (document.hidden) {
timer = setTimeout(refresh, REFRESH_MS);
return;
}
let result = null;
if (tab === "overview") {
result = await api("overview");
@@ -1473,10 +1980,13 @@
}
}
else if (tab === "accounts") {
result = await api("accounts");
const query = $("account-search-by").value !== "name" ? "" : $("account-search").value.trim();
result = await api(`accounts?q=${encodeURIComponent(query)}&filter=${$("account-filter").value}`);
if (result.ok) {
accounts = result.data.accounts;
accountTotal = result.data.total;
badges = result.data.badges || [];
await loadCurrent();
renderAccounts();
}
}
@@ -1496,7 +2006,7 @@
}
}
else if (tab === "masterpieces") {
result = await api("masterpieces");
result = await api(`masterpieces?creator=${encodeURIComponent($("masterpiece-creator").value.trim())}`);
if (result.ok) {
renderMasterpieces(result.data);
}
@@ -1509,11 +2019,7 @@
const open = el("button", "Open account");
open.type = "button";
open.addEventListener("click", () => {
selected = mod.username;
showTab("accounts");
fillCard();
loadOwned();
loadBanRecord();
openAccountTab(mod.username);
});
const cell = el("td");
cell.append(open);
@@ -1532,10 +2038,22 @@
}
}
else if (tab === "bans") {
const hits = api("filterhits");
result = await api("bans");
if (result.ok) {
renderBans(result.data);
}
const hitsResult = await hits;
if (hitsResult.ok) {
renderFilterHits(hitsResult.data.players);
}
}
else if (tab === "chat") {
// only the first page keeps itself up to date: older pages stay as they were read.
if (!chatQuery || chatLines.length <= 100) {
await loadChat(false);
result = {ok: true};
}
}
else if (tab === "messages") {
result = await api("messages");
@@ -1563,8 +2081,48 @@
}
};
// the page's address follows what is shown ("#accounts/John",
// "#chat/John"), for links to paste, and for Back.
let hashArg = "";
let applyingHash = false;
const setHash = () => {
const wanted = `#${tab}${hashArg ? `/${encodeURIComponent(hashArg)}` : ""}`;
if (location.hash !== wanted) {
history[applyingHash ? "replaceState" : "pushState"](null, "", wanted);
}
};
const applyHash = () => {
const [name, arg] = location.hash.slice(1).split("/");
if (![...document.querySelectorAll("nav button")].some(button => button.dataset.tab === name)) {
return false;
}
const value = arg ? decodeURIComponent(arg) : "";
applyingHash = true;
if (name === "accounts" && value) {
openAccountTab(value);
}
else if (name === "chat" && value) {
openChat(value);
}
else if (name === "masterpieces" && value) {
openPaintings(value);
}
else {
hashArg = "";
showTab(name);
}
applyingHash = false;
return true;
};
window.addEventListener("popstate", () => {
if (state && state.signedIn) {
applyHash();
}
});
const showTab = name => {
tab = name;
setHash();
for (const button of document.querySelectorAll("nav button")) {
button.setAttribute("aria-selected", String(button.dataset.tab === name));
}
@@ -1575,13 +2133,23 @@
};
for (const button of document.querySelectorAll("nav button")) {
button.addEventListener("click", () => showTab(button.dataset.tab));
button.addEventListener("click", () => {
hashArg = "";
showTab(button.dataset.tab);
});
}
document.addEventListener("visibilitychange", () => {
if (!document.hidden) {
refresh();
}
});
const showPanel = () => {
$("gate").hidden = true;
$("panel").hidden = false;
showTab(tab);
if (!applyHash()) {
showTab(tab);
}
};
const start = async () => {
Binary file not shown.

After

Width:  |  Height:  |  Size: 945 B

+422 -43
View File
@@ -162,6 +162,8 @@
tbody tr:last-child td { border-bottom: 0; }
tbody tr.selected td { background: var(--raised); }
tbody tr.pick { cursor: pointer; }
.device-id { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 12px; }
button.link { background: none; border: 0; padding: 0; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; font-weight: 400; }
.empty { color: var(--muted); padding: 8px 0; }
.toolbar { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; }
.toolbar input[type="search"] { flex: 1; min-width: 180px; }
@@ -202,6 +204,10 @@
.painting img { display: block; width: 100%; height: auto; border-radius: 10px; background: #fff; }
.painting h3 { margin: 8px 0 2px; }
.painting .buttons { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; }
.painting img { cursor: zoom-in; }
.preview { position: fixed; inset: 0; z-index: 50; display: flex; align-items: center; justify-content: center; padding: 16px; background: rgba(0, 0, 0, 0.85); cursor: zoom-out; }
.preview[hidden] { display: none; }
.preview img { max-width: 100%; max-height: 100%; border-radius: 10px; background: #fff; }
textarea { width: 100%; resize: vertical; }
.send-row { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; align-items: center; }
#owned { margin-top: 16px; }
@@ -217,7 +223,8 @@
.logo { display: block; height: 72px; margin: 0 0 12px; }
.mark { height: 34px; flex: none; }
#chat-lines { margin: 0; padding: 0; list-style: none; }
#chat-lines li, #chat-context li { display: flex; gap: 10px; align-items: baseline; padding: 6px 4px; border-bottom: 1px solid var(--line); }
.report-chat { margin: 0 0 8px; padding: 0; list-style: none; }
#chat-lines li, #chat-context li, .report-chat li { display: flex; gap: 10px; align-items: baseline; padding: 6px 4px; border-bottom: 1px solid var(--line); }
#chat-lines li:last-child, #chat-context li:last-child { border-bottom: 0; }
.chat-time { flex: none; width: 128px; color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
.chat-who { flex: none; max-width: 190px; padding: 0; border: 0; font-weight: 700; text-align: left; overflow: hidden; text-overflow: ellipsis; }
@@ -229,6 +236,7 @@
#chat-context li.this { background: var(--raised); border-radius: 10px; }
#player-facts { margin-bottom: 14px; }
#player-history, #player-warnings { margin: 0; padding-left: 18px; font-size: 13px; overflow-wrap: anywhere; }
#timeline { 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; }
</style>
</head>
@@ -273,6 +281,7 @@
<select id="player-search-by" aria-label="Search by">
<option value="name">By name</option>
<option value="address" data-needs="address.ban">By IP address</option>
<option value="device">By hardware ID</option>
</select>
<input id="player-search" type="search" placeholder="Search" aria-label="Search players">
<span class="hint" id="online-count"></span>
@@ -282,7 +291,8 @@
<tbody id="players"></tbody>
</table></div>
<div class="empty" id="no-players" hidden>No players match.</div>
<p class="hint" id="address-hint" hidden>Players who signed in from this address, or from addresses starting with it, in the last 90 days. Each search is written in the moderator log.</p>
<p class="hint" id="players-more" hidden></p>
<p class="hint" id="address-hint" hidden>Searches by address are logged.</p>
</section>
<section id="detail" hidden>
<h2 id="detail-name"></h2>
@@ -297,14 +307,17 @@
<button type="button" data-action="ban" class="danger">Ban</button>
<button type="button" data-action="banReason">Save reason</button>
<button type="button" data-action="unban">Lift</button>
<button type="button" data-action="banAddress" class="danger">Ban address</button></div>
<button type="button" data-action="banAddress" class="danger">Ban address</button>
<button type="button" data-action="banDevices" class="danger">Hardware ban</button>
<button type="button" data-action="unbanDevices">Lift hardware ban</button></div>
</div>
<div class="action">
<h3>Chat</h3>
<div class="row"><input id="silence-hours" type="number" min="0" placeholder="Hours (0 = until lifted)" aria-label="Silence length in hours">
<button type="button" data-action="silence">Silence</button>
<button type="button" data-action="unsilence">Lift</button></div>
<div class="row" style="margin-top:8px"><button type="button" id="open-chat">Chat history</button></div>
<div class="row" style="margin-top:8px"><button type="button" id="open-chat">Chat history</button>
<button type="button" id="open-paintings">Paintings</button></div>
</div>
<div class="action">
<h3>Warn</h3>
@@ -335,10 +348,36 @@
<button type="button" data-action="clearBio">Clear bio</button></div>
</div>
</div>
<h3 style="margin:16px 0 4px" id="history-title" hidden>Ban history</h3>
<ul id="player-history"></ul>
<h3 style="margin:16px 0 4px" id="warnings-title" hidden>Warnings</h3>
<ul id="player-warnings"></ul>
<h3 style="margin:16px 0 4px">Other accounts</h3>
<div class="table-wrap"><table>
<thead><tr><th>Name</th><th>State</th><th>Same hardware</th><th class="num">Same addresses</th></tr></thead>
<tbody id="alts"></tbody>
</table></div>
<div class="empty" id="no-alts" hidden>None found.</div>
<h3 style="margin:16px 0 4px">Hardware IDs</h3>
<div class="table-wrap"><table>
<thead><tr><th>Kind</th><th>Id</th><th>First seen</th><th>Last seen</th><th class="num">Other accounts</th><th>State</th></tr></thead>
<tbody id="device-ids"></tbody>
</table></div>
<div class="empty" id="no-device-ids" hidden>None.</div>
<h3 style="margin:16px 0 4px">Jam-a-Grams and wall posts</h3>
<div class="toolbar">
<select id="mail-kind" aria-label="Which">
<option value="jamagram">Jam-a-Grams</option>
<option value="wall">Jammer Wall posts</option>
</select>
<select id="mail-direction" aria-label="Sent or received">
<option value="">Sent and received</option>
<option value="sent">Sent by them</option>
<option value="received">Sent to them</option>
</select>
</div>
<ul id="mail-lines" class="report-chat"></ul>
<div class="empty" id="no-mail" hidden>Nothing kept.</div>
<button type="button" id="mail-older" hidden>Older</button>
<h3 style="margin:16px 0 4px">Timeline</h3>
<ul id="timeline"></ul>
<div class="empty" id="no-timeline" hidden>Nothing yet.</div>
</section>
</div>
@@ -352,6 +391,15 @@
<input id="chat-player" maxlength="100" placeholder="Player" autocomplete="off" spellcheck="false" aria-label="Player">
<input id="chat-room" maxlength="100" placeholder="Room" autocomplete="off" spellcheck="false" aria-label="Room">
<input id="chat-text" maxlength="100" placeholder="Words" autocomplete="off" aria-label="Words" style="flex:1">
<select id="chat-kind" aria-label="What">
<option value="">Everything</option>
<option value="chat">Chat</option>
<option value="whisper">Whispers</option>
<option value="jamagram">Jam-a-Grams</option>
<option value="wall">Wall posts</option>
<option value="notsent">Stopped by the filter</option>
</select>
<input id="chat-until" type="datetime-local" aria-label="From this time back">
<button class="primary" type="submit">Search</button>
</form>
<p class="status" id="chat-status" role="status"></p>
@@ -406,11 +454,14 @@
<select id="masterpiece-filter" aria-label="Which masterpieces">
<option value="waiting">Waiting</option>
<option value="approved">On show</option>
<option value="all">All</option>
</select>
<input id="masterpiece-creator" type="search" maxlength="100" placeholder="Maker's username" autocomplete="off" spellcheck="false" aria-label="Maker's username">
</div>
<p class="status" id="masterpiece-status" role="status"></p>
<div class="paintings" id="masterpieces"></div>
<div class="empty" id="no-masterpieces" hidden>Nothing here.</div>
<div class="preview" id="preview" hidden><img id="preview-img" alt=""></div>
</section>
</div>
@@ -471,6 +522,30 @@
</table></div>
<div class="empty" id="no-addresses" hidden>No address is banned.</div>
</section>
<section>
<h2>Hardware bans</h2>
<div class="table-wrap"><table>
<thead><tr><th>Banned with</th><th>Reason</th><th>By</th><th>Since</th><th>Accounts</th><th>Ids</th><th></th></tr></thead>
<tbody id="device-bans"></tbody>
</table></div>
<div class="empty" id="no-device-bans" hidden>No hardware bans.</div>
</section>
<section>
<h2>Hardware alerts</h2>
<div class="table-wrap"><table>
<thead><tr><th>When</th><th>Player</th><th>What</th><th>Detail</th></tr></thead>
<tbody id="device-alerts"></tbody>
</table></div>
<div class="empty" id="no-device-alerts" hidden>Nothing yet.</div>
</section>
<section>
<h2>Stopped most by the filter</h2>
<div class="table-wrap"><table>
<thead><tr><th>Player</th><th class="num">Stopped</th><th>Last</th><th></th></tr></thead>
<tbody id="filter-hits"></tbody>
</table></div>
<div class="empty" id="no-filter-hits" hidden>Nobody.</div>
</section>
</div>
</div>
@@ -577,6 +652,9 @@
if (player.silenced !== 0) {
tags.push(el("span", "Silenced", "tag bad"));
}
if (player.deviceBanned) {
tags.push(el("span", "Hardware banned", "tag bad"));
}
if (player.nameRejected) {
tags.push(el("span", "Name rejected", "tag bad"));
}
@@ -600,8 +678,6 @@
$("no-players").hidden = players.length > 0;
};
const HISTORY = {ban: "Banned", unban: "Ban lifted", reason: "Reason changed", appeal: "Appealed",
appeal_approved: "Appeal approved", appeal_denied: "Appeal denied"};
const loadDetail = async () => {
$("detail").hidden = !selected;
if (!selected) {
@@ -629,6 +705,9 @@
["Chat", player.silenced === 0 ? "—" : `Silenced: ${left(player.silenced).toLowerCase()}`],
["Reports waiting", String(player.openReports)],
["Warnings", String(player.warnings || 0)],
["Stopped by the filter", `${player.stoppedThisWeek} in the last 7 days`],
["Hardware IDs", player.devicesKnown ? String(player.devicesKnown) : "None"],
["Paintings", String(player.paintings)],
["Appeal", player.appeal ? `${player.appeal.status} · ${player.appeal.text}` : "—"],
["Discord", player.discord || "—"],
["Bio", player.bio || "—"],
@@ -644,39 +723,115 @@
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}`, entry.seen === false && "not seen yet"].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}`]
};
// the player's Jam-a-Grams or wall posts, sent and received
// (lib/chatlog.js): asked with the rest of the extras, and a page more
// with Older. "(not sent)" in front is one the filter stopped.
let mailLines = [];
const loadMail = async older => {
const username = selected;
if (!username) {
return;
}
const before = older && mailLines.length ? mailLines[mailLines.length - 1].id : 0;
const result = await api(`chat?username=${encodeURIComponent(username)}&kind=${$("mail-kind").value}`
+ `&direction=${$("mail-direction").value}&before=${before}`);
if (username !== selected) {
return;
}
const lines = result.ok ? result.data.lines : [];
mailLines = older ? [...mailLines, ...lines] : lines;
$("mail-lines").replaceChildren(...mailLines.map(line => lineNode(line, true)));
$("no-mail").hidden = mailLines.length > 0;
$("mail-older").hidden = !(result.ok && result.data.more);
};
$("mail-kind").addEventListener("change", () => loadMail(false));
$("mail-direction").addEventListener("change", () => loadMail(false));
$("mail-older").addEventListener("click", () => loadMail(true));
// other accounts the same person may have, and what happened to the
// player: asked when a player is opened and after an action, not every
// few seconds (finding alts looks through every account).
const KIND_NAMES = {os: "system id", board: "board", disk: "disk", install: "client id", mac: "network card"};
const TIMELINE_NAMES = {ban: "Ban", staff: "Staff", report: "Report", alert: "Alert"};
const loadExtras = async () => {
const username = selected;
if (!username) {
return;
}
loadMail(false);
const [alts, timeline] = await Promise.all([api(`alts?username=${encodeURIComponent(username)}`), api(`timeline?username=${encodeURIComponent(username)}`)]);
if (username !== selected) {
return;
}
const altList = alts.ok ? alts.data.alts : [];
$("alts").replaceChildren(...altList.map(alt => {
const row = el("tr", undefined, "pick");
const stateCell = el("td");
const tags = stateTags({...alt, silenced: 0, nameRejected: false, moderator: false, banned: alt.banned});
stateCell.append(...(tags.length ? tags.flatMap(tag => [tag, " "]) : ["—"]));
row.append(el("td", alt.username), stateCell,
el("td", alt.devices.length ? `${alt.devices.map(kind => KIND_NAMES[kind] || kind).join(", ")}${alt.weak ? " (weak)" : ""}` : "—"),
el("td", alt.addresses ? String(alt.addresses) : "—", "num"));
row.addEventListener("click", () => openPlayer(alt.username));
return row;
}));
$("no-alts").hidden = altList.length > 0;
const ids = alts.ok ? alts.data.ids : [];
$("device-ids").replaceChildren(...ids.map(entry => {
const row = el("tr", undefined, "pick");
row.title = "Every account that used this id";
row.append(el("td", KIND_NAMES[entry.kind] || entry.kind), el("td", entry.id, "device-id"), el("td", when(entry.first)), el("td", when(entry.last)),
el("td", String(entry.others), "num"), el("td", !entry.banned ? "—" : entry.kind === "mac" ? "Banned (alerts only)" : "Banned"));
row.addEventListener("click", () => searchDevice(entry.id));
return row;
}));
$("no-device-ids").hidden = ids.length > 0;
const events = timeline.ok ? timeline.data.events : [];
$("timeline").replaceChildren(...events.map(entry => el("li", [when(entry.at), TIMELINE_NAMES[entry.kind] || entry.kind, entry.text, entry.by && `by ${entry.by}`]
.filter(Boolean).join(" · "))));
$("no-timeline").hidden = events.length > 0;
};
const select = username => {
selected = username;
hashArg = username || "";
setHash();
setStatus($("detail-status"), "");
for (const id of ["ban-hours", "ban-reason", "silence-hours", "message-text", "warn-note"]) {
$(id).value = "";
}
renderPlayers();
loadDetail();
loadExtras();
};
// from another page: that player's box, whether or not the search shows them.
const openPlayer = username => {
$("player-search").value = username;
$("player-search-by").value = "name";
selected = username;
hashArg = username;
showTab("players");
loadExtras();
};
// every account that used a hardware ID: the player list, searched by it.
const searchDevice = id => {
$("player-search-by").value = "device";
$("player-search").placeholder = "Hardware ID, or the start of one";
$("player-search").value = id;
showTab("players");
refresh();
window.scrollTo(0, 0);
};
const numberFrom = id => ($(id).value.trim() === "" ? NaN : Number($(id).value));
const actionBody = action => {
switch (action) {
case "ban": return {hours: numberFrom("ban-hours"), reason: $("ban-reason").value};
case "banReason": case "banAddress": return {reason: $("ban-reason").value};
case "banReason": case "banAddress": case "banDevices": 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};
@@ -685,6 +840,8 @@
};
const CONFIRM = {
banAddress: name => `Ban the address ${name} last signed in from, for good?`,
banDevices: name => `Hardware ban ${name}? Everyone on their hardware is put out.`,
unbanDevices: name => `Lift the hardware bans on ${name}?`,
rejectName: name => `Reject the username ${name}? They are signed out and must pick another.`,
unwarn: name => `Take back ${name}'s latest warning?`,
};
@@ -707,6 +864,7 @@
$("silence-hours").value = "";
$("message-text").value = "";
refresh();
loadExtras();
}
});
@@ -714,21 +872,37 @@
let searchWait = null;
$("player-search").addEventListener("input", () => {
clearTimeout(searchWait);
searchWait = setTimeout(refresh, $("player-search-by").value === "address" ? 700 : 0);
searchWait = setTimeout(refresh, $("player-search-by").value === "name" ? 250 : 700);
});
// Enter opens the player of exactly that name, when there is one.
$("player-search").addEventListener("keydown", async event => {
if (event.key !== "Enter" || $("player-search-by").value !== "name") {
return;
}
clearTimeout(searchWait);
await refresh();
const wanted = $("player-search").value.trim().toLowerCase();
const exact = players.find(player => player.username.toLowerCase() === wanted);
if (exact && exact.username !== selected) {
select(exact.username);
}
});
$("player-search-by").addEventListener("change", () => {
$("player-search").placeholder = $("player-search-by").value === "address" ? "203.0.113.7, or the start of one" : "Search";
$("player-search").placeholder = {address: "203.0.113.7, or the start of one", device: "Hardware ID, or the start of one"}[$("player-search-by").value] || "Search";
refresh();
});
const chatUrl = before => `chat?username=${encodeURIComponent(chatQuery.username)}&room=${encodeURIComponent(chatQuery.room)}`
+ `&text=${encodeURIComponent(chatQuery.text)}&before=${before}`;
+ `&text=${encodeURIComponent(chatQuery.text)}&kind=${chatQuery.kind || ""}&until=${chatQuery.until || 0}&before=${before}`;
// where a line was said: a room, or who it went to.
const placeOf = line => (line.kind === "whisper" ? `Whisper to ${line.to}` : line.kind === "jamagram" ? `Jam-a-Gram to ${line.to}`
: line.kind === "wall" ? `On ${line.to}'s wall` : line.room);
const lineNode = (line, inContext = false) => {
const item = el("li", undefined, inContext && line.marked ? "this" : "");
const who = button(line.username, () => openPlayer(line.username), "chat-who");
const text = el("span", undefined, "chat-text");
text.append(line.text, el("span", line.whisperTo ? `Whisper to ${line.whisperTo}` : line.room, "chat-room"));
text.append(line.text || "(no words)", el("span", placeOf(line), "chat-room"));
item.append(el("span", when(line.at), "chat-time"), who, text);
if (!inContext) {
item.append(button("Around", () => showContext(line.id), "chat-more"));
@@ -744,7 +918,7 @@
const loadChat = async older => {
if (!chatQuery) {
chatQuery = {username: "", room: "", text: ""};
chatQuery = {username: "", room: "", text: "", kind: "", until: 0};
}
const before = older && chatLines.length ? chatLines[chatLines.length - 1].id : 0;
const result = await api(chatUrl(before));
@@ -764,7 +938,7 @@
return;
}
const {line, lines} = result.data;
$("context-title").textContent = line.whisperTo ? `${line.username} and ${line.whisperTo}` : line.room;
$("context-title").textContent = line.kind === "chat" ? line.room : `${line.username} and ${line.to}`;
$("chat-context").replaceChildren(...lines.map(entry => lineNode({...entry, marked: entry.id === line.id}, true)));
$("context-box").hidden = false;
$("context-box").scrollIntoView({block: "nearest"});
@@ -775,25 +949,41 @@
$("chat-form").addEventListener("submit", event => {
event.preventDefault();
chatQuery = {username: $("chat-player").value.trim(), room: $("chat-room").value.trim(), text: $("chat-text").value.trim()};
const until = $("chat-until").value ? Math.floor(new Date($("chat-until").value).getTime() / 1000) : 0;
chatQuery = {username: $("chat-player").value.trim(), room: $("chat-room").value.trim(), text: $("chat-text").value.trim(), kind: $("chat-kind").value, until};
$("context-box").hidden = true;
loadChat(false);
});
$("chat-older").addEventListener("click", () => loadChat(true));
const openChat = username => {
const openChat = (username, kind = "") => {
$("chat-player").value = username;
$("chat-room").value = "";
$("chat-text").value = "";
chatQuery = {username, room: "", text: ""};
$("chat-kind").value = kind;
$("chat-until").value = "";
chatQuery = {username, room: "", text: "", kind, until: 0};
hashArg = username;
$("context-box").hidden = true;
showTab("chat");
};
$("open-chat").addEventListener("click", () => selected && openChat(selected));
$("open-paintings").addEventListener("click", () => selected && openPaintings(selected));
const renderReports = data => {
// what the reported player said up to the report, once asked for: report id -> lines.
const reportChat = new Map();
let reportsShown = "";
let lastReports = null;
const renderReports = (data, force = false) => {
const handled = $("report-filter").value === "1";
$("report-count").textContent = data.open ? ` (${data.open})` : "";
lastReports = data;
// drawn again only when the list changed.
const shown = `${handled} ${data.reports.map(report => report.id).join(",")}`;
if (shown === reportsShown && !force) {
return;
}
reportsShown = shown;
$("reports").replaceChildren(...data.reports.map(report => {
const box = el("div", undefined, "report");
box.append(el("h3", `${report.target} — ${report.reason}`),
@@ -804,8 +994,24 @@
if (report.context) {
box.append(el("pre", report.context));
}
if (reportChat.has(report.id)) {
const lines = reportChat.get(report.id);
const list = el("ul", undefined, "report-chat");
list.append(...lines.map(line => lineNode(line, true)));
box.append(el("h3", `What ${report.target} said up to the report`), lines.length ? list : el("div", "Nothing kept.", "hint"));
}
const buttons = el("div", undefined, "buttons");
buttons.append(button("Player", () => openPlayer(report.target)), button("Chat history", () => openChat(report.target)));
buttons.append(button("Player", () => openPlayer(report.target)), button("Chat history", () => openChat(report.target)),
button(reportChat.has(report.id) ? "Hide chat" : "Chat at the time", async () => {
if (reportChat.has(report.id)) {
reportChat.delete(report.id);
}
else {
const result = await api(`chat?username=${encodeURIComponent(report.target)}&until=${report.createdAt + 60}&before=0`);
reportChat.set(report.id, result.ok ? result.data.lines.slice(0, 20).reverse() : []);
}
renderReports(lastReports, true);
}));
if (handled) {
box.append(el("div", `Dealt with on ${when(report.handledAt)}`, "hint"));
}
@@ -823,6 +1029,7 @@
};
$("report-filter").addEventListener("change", () => refresh());
const renderRequests = data => {
const handled = $("request-filter").value === "1";
const answer = async body => {
@@ -884,13 +1091,28 @@
$("request-filter").addEventListener("change", () => refresh());
let paintingsShown = "";
// the picture full size, over the page; a click puts it away.
const showPreview = src => {
$("preview-img").src = src;
$("preview").hidden = false;
};
$("preview").addEventListener("click", () => {
$("preview").hidden = true;
});
document.addEventListener("keydown", event => {
if (event.key === "Escape") {
$("preview").hidden = true;
}
});
const renderMasterpieces = data => {
const which = $("masterpiece-filter").value;
const paintings = data[which];
$("masterpiece-count").textContent = data.waiting.length ? ` (${data.waiting.length})` : "";
const marked = (list, status) => list.map(painting => ({...painting, status}));
const paintings = which === "all" ? [...marked(data.waiting, "waiting"), ...marked(data.approved, "approved")] : marked(data[which], which);
$("masterpiece-count").textContent = data.waitingCount ? ` (${data.waitingCount})` : "";
$("no-masterpieces").hidden = paintings.length > 0;
// drawn again only when the list changed, so the pictures do not flicker.
const shown = `${which} ${paintings.map(painting => painting.id).join(" ")}`;
const shown = `${which} ${paintings.map(painting => `${painting.id}:${painting.status}`).join(" ")}`;
if (shown === paintingsShown) {
return;
}
@@ -901,14 +1123,16 @@
picture.src = `/mod/api/masterpiece?id=${encodeURIComponent(painting.id)}`;
picture.alt = `Painting by ${painting.creator}`;
picture.loading = "lazy";
box.append(picture, el("h3", painting.creator), el("div", when(painting.createdAt), "hint"));
picture.addEventListener("click", () => showPreview(picture.src));
box.append(picture, el("h3", painting.creator),
el("div", `${when(painting.createdAt)}${which === "all" ? (painting.status === "waiting" ? " · waiting" : " · on show") : ""}`, "hint"));
const buttons = el("div", undefined, "buttons");
const does = (label, action, className) => button(label, async () => {
const result = await api("masterpiece", {id: painting.id, action});
setStatus($("masterpiece-status"), said(result), !result.ok);
refresh();
}, className);
if (which === "waiting") {
if (painting.status === "waiting") {
buttons.append(does("Approve", "approve", "primary"), does("Reject", "reject", "danger"));
}
else {
@@ -920,6 +1144,18 @@
}));
};
$("masterpiece-filter").addEventListener("change", () => refresh());
let creatorWait = null;
$("masterpiece-creator").addEventListener("input", () => {
clearTimeout(creatorWait);
creatorWait = setTimeout(refresh, 250);
});
// a player's paintings, waiting and on show.
const openPaintings = username => {
$("masterpiece-creator").value = username;
$("masterpiece-filter").value = "all";
hashArg = username;
showTab("masterpieces");
};
const renderBans = data => {
$("bans").replaceChildren(...data.accounts.map(account => {
@@ -954,6 +1190,81 @@
return row;
}));
$("no-addresses").hidden = data.addresses.length > 0;
$("device-bans").replaceChildren(...data.devices.map(ban => {
const row = el("tr");
const buttons = el("td");
buttons.append(button("Unban", async () => {
if (!window.confirm(`Lift the hardware ban made with ${ban.username}?`)) {
return;
}
const result = await api("device", {id: ban.id});
setStatus($("ban-status"), said(result), !result.ok);
refresh();
}), " ", button("Player", () => openPlayer(ban.username)));
row.append(el("td", ban.username || "—"), el("td", ban.reason), el("td", ban.by || "—"), el("td", when(ban.createdAt)),
deviceAccounts(ban.accounts), deviceIds(ban), buttons);
return row;
}));
$("no-device-bans").hidden = data.devices.length > 0;
$("device-alerts").replaceChildren(...data.alerts.map(entry => {
const row = el("tr", undefined, "pick");
const detail = el("td", entry.detail);
detail.style.whiteSpace = "normal";
row.append(el("td", when(entry.at)), el("td", entry.username), el("td", entry.name), detail);
row.addEventListener("click", () => openPlayer(entry.username));
return row;
}));
$("no-device-alerts").hidden = data.alerts.length > 0;
};
// a hardware ban's accounts and ids, each one a link.
const deviceAccounts = names => {
const cell = el("td");
cell.style.whiteSpace = "normal";
cell.append(...(names.length ? names.flatMap((name, index) => {
const link = el("button", name, "link");
link.type = "button";
link.addEventListener("click", () => openPlayer(name));
return index ? [", ", link] : [link];
}) : ["—"]));
return cell;
};
const openBanIds = new Set();
const deviceIds = ban => {
const cell = el("td");
const shown = openBanIds.has(ban.id);
const toggle = el("button", shown ? `Hide ${ban.ids.length}` : `Show ${ban.ids.length}`, "link");
toggle.type = "button";
toggle.addEventListener("click", () => {
if (openBanIds.has(ban.id)) {
openBanIds.delete(ban.id);
}
else {
openBanIds.add(ban.id);
}
refresh();
});
cell.append(toggle);
if (shown) {
for (const entry of ban.ids) {
const link = el("button", `${KIND_NAMES[entry.kind] || entry.kind} ${entry.id}`, "link device-id");
link.type = "button";
link.addEventListener("click", () => searchDevice(entry.id));
cell.append(el("br"), link);
}
}
return cell;
};
const renderFilterHits = list => {
$("filter-hits").replaceChildren(...list.map(entry => {
const row = el("tr");
const buttons = el("td");
buttons.append(button("Lines", () => openChat(entry.username, "notsent")), " ", button("Player", () => openPlayer(entry.username)));
row.append(el("td", entry.username), el("td", String(entry.count), "num"), el("td", when(entry.last)), buttons);
return row;
}));
$("no-filter-hits").hidden = list.length > 0;
};
// ---- items (lib/customitems.js)
@@ -1074,20 +1385,32 @@
$("request-count").textContent = counts.data.requests ? ` (${counts.data.requests})` : "";
$("masterpiece-count").textContent = counts.data.paintings ? ` (${counts.data.paintings})` : "";
$("online-count").textContent = `${counts.data.online} playing`;
// what waits, in the page's title too, for when it is in another tab.
const waiting = counts.data.reports + counts.data.requests + counts.data.paintings;
document.title = waiting ? `(${waiting}) Moderators` : "Moderators";
}
// out of sight, only the counts (for the title); the rest when it is back.
if (document.hidden) {
timer = setTimeout(refresh, REFRESH_MS);
return;
}
if (shown === "players") {
const byAddress = $("player-search-by").value === "address";
const searchBy = $("player-search-by").value;
const byAddress = searchBy !== "name";
const query = $("player-search").value.trim();
$("players-when").textContent = byAddress ? "Last from address" : "Last seen";
$("address-hint").hidden = !byAddress;
$("players-when").textContent = searchBy === "address" ? "Last from address" : searchBy === "device" ? "Last used" : "Last seen";
$("address-hint").hidden = searchBy !== "address";
if (byAddress && query === "") {
players = [];
renderPlayers();
}
else {
const result = await api(`players?q=${encodeURIComponent(query)}${byAddress ? "&by=address" : ""}`);
const result = await api(`players?q=${encodeURIComponent(query)}${byAddress ? `&by=${searchBy}` : ""}`);
players = result.ok ? result.data.players : [];
renderPlayers();
const total = result.ok && result.data.total ? result.data.total : players.length;
$("players-more").hidden = byAddress || total <= players.length;
$("players-more").textContent = `Showing ${players.length} of ${total.toLocaleString()}. Type more of the name to narrow it down.`;
if (!result.ok && byAddress) {
$("no-players").textContent = said(result);
}
@@ -1115,7 +1438,7 @@
}
}
else if (shown === "masterpieces") {
const result = await api("masterpieces");
const result = await api(`masterpieces?creator=${encodeURIComponent($("masterpiece-creator").value.trim())}`);
if (result.ok) {
renderMasterpieces(result.data);
}
@@ -1124,10 +1447,13 @@
await window.statsView.load(api);
}
else if (shown === "bans") {
const result = await api("bans");
const [result, hits] = await Promise.all([api("bans"), api("filterhits")]);
if (result.ok) {
renderBans(result.data);
}
if (hits.ok) {
renderFilterHits(hits.data.players);
}
}
else if (shown === "items") {
const result = await api("items");
@@ -1142,8 +1468,49 @@
}
};
// the page's address follows what is shown ("#players/John",
// "#chat/John"), for links to paste to other staff, and for Back.
let hashArg = "";
let applyingHash = false;
const setHash = () => {
const wanted = `#${tab}${hashArg ? `/${encodeURIComponent(hashArg)}` : ""}`;
if (location.hash !== wanted) {
history[applyingHash ? "replaceState" : "pushState"](null, "", wanted);
}
};
const applyHash = () => {
const [name, arg] = location.hash.slice(1).split("/");
const known = [...document.querySelectorAll("nav button")].some(one => one.dataset.tab === name);
if (!known) {
return false;
}
const value = arg ? decodeURIComponent(arg) : "";
applyingHash = true;
if (name === "players" && value) {
openPlayer(value);
}
else if (name === "chat" && value) {
openChat(value);
}
else if (name === "masterpieces" && value) {
openPaintings(value);
}
else {
hashArg = "";
showTab(name);
}
applyingHash = false;
return true;
};
window.addEventListener("popstate", () => {
if (signedIn) {
applyHash();
}
});
const showTab = name => {
tab = name;
setHash();
for (const one of document.querySelectorAll("nav button")) {
one.setAttribute("aria-selected", String(one.dataset.tab === name));
}
@@ -1153,8 +1520,16 @@
refresh();
};
for (const one of document.querySelectorAll("nav button")) {
one.addEventListener("click", () => showTab(one.dataset.tab));
one.addEventListener("click", () => {
hashArg = "";
showTab(one.dataset.tab);
});
}
document.addEventListener("visibilitychange", () => {
if (!document.hidden) {
refresh();
}
});
// 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.
@@ -1201,7 +1576,11 @@
$("who").textContent = username;
$("gate").hidden = true;
$("panel").hidden = false;
applyPermissions().then(() => showTab(tab));
applyPermissions().then(() => {
if (!applyHash()) {
showTab(tab);
}
});
};
$("gate-form").addEventListener("submit", async event => {
+8 -5
View File
@@ -172,8 +172,9 @@
<tr><td>Username, password (stored only as a salted hash), and the date and version of the terms you accepted</td><td>To give you an account</td></tr>
<tr><td>Your game data: animals, items, dens, pets, buddies, block list, trades, achievements, settings</td><td>To run the game for you</td></tr>
<tr><td>What you choose to write or make: bio, Discord username (optional), Jam-A-Grams, wall posts, paintings, feedback</td><td>To show or deliver it as you asked</td></tr>
<tr><td>Typed chat and whispers, with the room and time</td><td>Moderation: reviewing reports and deciding on bans</td></tr>
<tr><td>Typed chat and whispers, with the room and time, and the words of Jam-A-Grams and wall posts, with who they went to</td><td>Moderation: reviewing reports and deciding on bans</td></tr>
<tr><td>IP address at each sign-in, and sign-in times</td><td>Security: your sign-in history, limiting abuse, address bans, and finding accounts made to get around a ban</td></tr>
<tr><td>Hardware hashes, sent by the Burrow client at each sign-in. The client reads a few identifiers of your device (its system id, hardware serial numbers, network card addresses, and a random id the client makes for itself) and turns each into a one-way hash before sending it; we hash them again with a secret key of our own. The identifiers themselves never leave your device, and the hashes cannot be turned back into them: they do not tell us who you are, what your device is, or anything else about it, and mean nothing outside this server. We also note if the identifiers look missing or altered</td><td>Only to prevent ban evasion: hardware bans, and finding accounts made to get around a ban. They are not used for tracking or advertising and are never shared</td></tr>
<tr><td>When you log in to the game, how long each visit lasts, and your total playtime</td><td>To show you your playtime, and for overall activity figures (how many people play and when) that staff use to run the server</td></tr>
<tr><td>The number of players online, counted every minute</td><td>Overall activity figures. This count is not linked to anyone</td></tr>
<tr><td>Reports, bans and their reasons, appeals, username rejections</td><td>Moderation and preventing ban evasion</td></tr>
@@ -188,7 +189,7 @@
<h2>3. Who can see it</h2>
<ul>
<li><b>Other players</b> see your username, animals, den, bio, Discord username if you add one, badges, when you joined and were last seen, your chat in the room you are in, whether you are currently banned, and your total playtime if you make it public on your account page (it is private unless you choose otherwise).</li>
<li><b>Moderators</b> can also read stored chat and whispers, reports, and ban history, and see your total playtime and the overall activity figures. They cannot see your IP address, sign-in history, password or inventory.</li>
<li><b>Moderators</b> can also read stored chat, whispers, Jam-A-Grams and wall posts, reports, and ban history, see which other accounts used the same device or signed in from the same IP addresses (never the addresses themselves; for devices, only the hashes described in section 2), and see your total playtime and the overall activity figures. They cannot see your IP address, sign-in history, password or inventory.</li>
<li><b>Moderators</b> can look up which accounts signed in from an IP address they already have, only to stop ban evasion: finding new accounts made by someone who is banned. The search shows only account names and when they signed in from that address, never the address itself or any other address. Every search is recorded under the moderator's name and reviewed by the administrator.</li>
<li><b>The administrator</b> can see everything listed in section 2, and can search accounts by IP address for the same purpose.</li>
<li><b>Our hosting provider</b> stores the data on our behalf, in {{hostedIn}}. If that is outside your country, your data is transferred there to provide the service.</li>
@@ -211,7 +212,9 @@
<thead><tr><th>Data</th><th>Kept</th></tr></thead>
<tbody>
<tr><td>Account and game data</td><td>Until you delete your account</td></tr>
<tr><td>Chat and whispers</td><td>30 days</td></tr>
<tr><td>Chat, whispers, and the words of Jam-A-Grams and wall posts</td><td>30 days</td></tr>
<tr><td>Hardware hashes</td><td>Until you delete your account (the latest 60)</td></tr>
<tr><td>Hardware bans (hashes only)</td><td>Until the ban is lifted</td></tr>
<tr><td>Sign-in history with IP addresses</td><td>Your last 40 sign-ins, and none older than 90 days</td></tr>
<tr><td>Error reports and server logs</td><td>Up to 30 days</td></tr>
<tr><td>Handled reports, feedback and username requests</td><td>12 months</td></tr>
@@ -222,7 +225,7 @@
<tr><td>Backups</td><td>14 days</td></tr>
</tbody>
</table></div>
<p style="margin-top:12px">When you delete your account we delete your game data, chat, appeal, feedback, username requests and paintings straight away, and your total playtime. Your past logins stay in the overall activity figures for up to 12 months and are not shown to anyone by name. Your username is held for 30 days so nobody can pass as you, and ban records are kept as shown above. Copies in backups disappear within 14 days.</p>
<p style="margin-top:12px">When you delete your account we delete your game data, chat, hardware hashes, appeal, feedback, username requests and paintings straight away, and your total playtime. Your past logins stay in the overall activity figures for up to 12 months and are not shown to anyone by name. Your username is held for 30 days so nobody can pass as you, and ban records are kept as shown above. Copies in backups disappear within 14 days.</p>
</section>
<section>
@@ -243,7 +246,7 @@
<section>
<h2>8. Cookies and your device</h2>
<p>The website sets only cookies that are needed to keep you signed in: a session cookie on your account page (12 hours) and, if you choose "Trust this device", a 2FA cookie (30 days). The client keeps your saved sign-in on your own computer if you tick "Remember me". Cloudflare may add a security cookie of its own (section 4). There are no advertising or tracking cookies.</p>
<p>The website sets only cookies that are needed to keep you signed in: a session cookie on your account page (12 hours) and, if you choose "Trust this device", a 2FA cookie (30 days). The client keeps your saved sign-in on your own device if you tick "Remember me". Cloudflare may add a security cookie of its own (section 4). There are no advertising or tracking cookies.</p>
</section>
<section>
+2
View File
@@ -5,6 +5,7 @@ require("./lib/log.js"); // first, so everything printed reaches the admin panel
const fs = require("fs");
const accounts = require("./lib/accounts.js");
const bans = require("./lib/bans.js");
const devices = require("./lib/devices.js");
const chatlog = require("./lib/chatlog.js");
const modlog = require("./lib/modlog.js");
const retention = require("./lib/retention.js");
@@ -42,6 +43,7 @@ const main = async () => {
reports.load();
support.load();
bans.load();
devices.load();
chatlog.load();
modlog.load();
masterpieces.load();
+592
View File
@@ -0,0 +1,592 @@
package gui
{
import avatar.Avatar;
import avatar.AvatarManager;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import flash.utils.Dictionary;
import game.ArtStudioKit;
import pet.WorldPet;
// the actions window. an animal has the art for its own set of actions
// only (a land animal's sitting, sleeping, hopping; an ocean animal's
// diving, swirling, posing), so it is shown its own set in any room: a
// land animal underwater still sits and hops. an animal of land and ocean
// both (seal, otter...) has both, and a button above the window swaps the
// set shown ("Swim moves" on land, "Land moves" underwater).
//
// the sets share buttons, and ":dance:" and ":play:" are the same name in
// both (the room picks the animation, AvatarWorldView.setAction): the
// other set's dance and play go by names of their own (OTHER_SET_NAMES).
// the other names (":dive:", ":sitNW:"...) are one set's already.
public class ActionManager
{
private static const OTHER_SET_NAMES:Object = {
"danceAnim_btnCont":[":danceLand:",":danceSwim:"],
"playAnim_btnCont":[":playLand:",":playSwim:"]
};
private static const OTHER_SET_BUTTONS:Object = {
":danceLand:":"danceAnim_btnCont",
":danceSwim:":"danceAnim_btnCont",
":playLand:":"playAnim_btnCont",
":playSwim:":"playAnim_btnCont"
};
private static const SWAP_W:int = 150;
private static const SWAP_H:int = 26;
// the set the window shows: the room's, unless swapped
private var _oceanShown:Boolean;
// action sprites made from a name (matchActionString), and that name
private var _names:Dictionary = new Dictionary(true);
private var _swapBtn:MovieClip;
private const ACTIONWINDOW_DIM_ALPHA:Number = 0.5;
private const ACTIONWINDOW_BRIGHT_ALPHA:Number = 1;
public var actionBtn:MovieClip;
public var actionWindow:MovieClip;
public var emoteBtn:MovieClip;
public var emoteWindow:Sprite;
public var safeChatBtn:MovieClip;
public var safeChatTree:MovieClip;
public var setActionCallback:Function;
public var actionSprites:Array = ["sit1BtnCont","sit2BtnCont","sit3BtnCont","sit4BtnCont","danceAnim_btnCont","sleepAnim_btnCont","hopAnim_btnCont","playAnim_btnCont","pose1BtnCont","pose2BtnCont","diveAnim_btnCont","swirlAnim_btnCont"];
public var actionStrings:Object;
private var _actions:MovieClip;
private var _petActions:MovieClip;
private var _views:Array;
private var _titleBanner:Sprite;
public function ActionManager(param1:Function, param2:MovieClip, param3:MovieClip, param4:MovieClip, param5:Sprite, param6:MovieClip, param7:MovieClip)
{
super();
if(setActionCallback != null)
{
throw new Error("ERROR: Singleton ActionManager did not expect to be created twice!");
}
setActionCallback = param1;
actionBtn = param2;
actionBtn.addEventListener("mouseDown",actionBtnDownHandler,false,0,true);
actionWindow = param3;
addAllActions();
addSwapButton();
actionWindow.addChild(_actions);
actionWindow.addChild(_petActions);
_petActions.visible = false;
actionWindow.poseBtns = _actions.poseBtns;
actionWindow.diveBtn = _actions.diveBtn;
actionWindow.swirlBtn = _actions.swirlBtn;
actionWindow.sitBtns = _actions.sitBtns;
actionWindow.visible = false;
emoteBtn = param4;
emoteWindow = param5;
safeChatBtn = param6;
safeChatTree = param7;
setupTitleBanner();
}
// a room joined: its set is shown, if the animal has it.
public function turnOnOceanActions(param1:Boolean) : void
{
_oceanShown = ownSet(param1);
showSet();
}
// the set to show in a room (true: the ocean's): the room's, unless the
// player's animal has the art of the other only.
private static function ownSet(param1:Boolean) : Boolean
{
var _loc2_:Avatar = AvatarManager.playerAvatar;
if(_loc2_ == null)
{
return param1;
}
var _loc3_:Boolean = Utility.isLand(_loc2_.enviroTypeFlag);
var _loc4_:Boolean = Utility.isOcean(_loc2_.enviroTypeFlag);
return _loc3_ == _loc4_ ? param1 : _loc4_;
}
// whether the player's animal has the art of a set (true: the ocean's)
private static function playerHasSet(param1:Boolean) : Boolean
{
var _loc2_:Avatar = AvatarManager.playerAvatar;
if(_loc2_ == null)
{
return false;
}
return param1 ? Utility.isOcean(_loc2_.enviroTypeFlag) : Utility.isLand(_loc2_.enviroTypeFlag);
}
private function showSet() : void
{
actionWindow.poseBtns.visible = _oceanShown;
actionWindow.diveBtn.visible = _oceanShown;
actionWindow.swirlBtn.visible = _oceanShown;
actionWindow.sitBtns.visible = !_oceanShown;
if(_swapBtn)
{
ArtStudioKit.setLabel(_swapBtn,_oceanShown ? "Land moves" : "Swim moves");
}
}
private function addSwapButton() : void
{
_swapBtn = ArtStudioKit.button(null,null,SWAP_W,SWAP_H,onSwapBtn,"Swim moves");
// the window closes on a press anywhere else
_swapBtn.addEventListener("mouseDown",stopPress,false,0,true);
_swapBtn.visible = false;
_actions.addChild(_swapBtn);
}
private function stopPress(param1:MouseEvent) : void
{
param1.stopPropagation();
}
private function onSwapBtn(param1:MouseEvent) : void
{
_oceanShown = !_oceanShown;
showSet();
}
private static function roomIsOcean() : Boolean
{
return AvatarManager.roomEnviroType == 1;
}
// whether the player's animal has the art of both sets
private static function playerHasBothSets() : Boolean
{
var _loc1_:Avatar = AvatarManager.playerAvatar;
return _loc1_ != null && Utility.isLand(_loc1_.enviroTypeFlag) && Utility.isOcean(_loc1_.enviroTypeFlag);
}
// the swap button, for an animal of both sets, above the window; any
// other is shown its own set (the player may have changed animals
// since the room was joined).
private function updateSwapButton() : void
{
var _loc1_:Boolean = playerHasBothSets();
var _loc2_:Rectangle = null;
if(!_loc1_ && _oceanShown != ownSet(roomIsOcean()))
{
_oceanShown = ownSet(roomIsOcean());
showSet();
}
_swapBtn.visible = _loc1_;
if(_loc1_)
{
_loc2_ = actionWindow.ba.getBounds(actionWindow);
if(_titleBanner && actionWindow.contains(_titleBanner))
{
_loc2_ = _loc2_.union(_titleBanner.getBounds(actionWindow));
}
_swapBtn.x = int(_loc2_.x + (_loc2_.width - SWAP_W) / 2);
_swapBtn.y = int(_loc2_.top - SWAP_H - 4);
}
}
public function turnOnPetActions(param1:Boolean) : void
{
if(param1)
{
_petActions.visible = true;
_actions.visible = false;
}
else
{
_petActions.visible = false;
_actions.visible = true;
}
}
public function reload(param1:MovieClip, param2:MovieClip, param3:MovieClip, param4:Sprite, param5:MovieClip, param6:MovieClip, param7:Function) : void
{
setActionCallback = param7;
if(actionBtn)
{
actionBtn.removeEventListener("mouseDown",actionBtnDownHandler);
}
actionBtn = param1;
actionBtn.addEventListener("mouseDown",actionBtnDownHandler,false,0,true);
while(actionWindow.numChildren > 2)
{
actionWindow.removeChildAt(actionWindow.numChildren - 1);
}
actionWindow = param2;
addAllActions();
addSwapButton();
actionWindow.addChild(_actions);
actionWindow.addChild(_petActions);
_petActions.visible = false;
actionWindow.poseBtns = _actions.poseBtns;
actionWindow.diveBtn = _actions.diveBtn;
actionWindow.swirlBtn = _actions.swirlBtn;
actionWindow.sitBtns = _actions.sitBtns;
actionWindow.visible = false;
emoteBtn = param3;
emoteWindow = param4;
actionWindow = param2;
safeChatBtn = param5;
safeChatTree = param6;
actionBtn.downToUpState();
setupTitleBanner();
}
private function addAllActions() : void
{
var _loc14_:* = 0;
_loc14_ = 10;
var _loc11_:* = 0;
_loc11_ = 25;
var _loc13_:* = 0;
_loc13_ = 40;
var _loc5_:* = 0;
_loc5_ = 91;
var _loc2_:* = 0;
_loc2_ = 2;
var _loc1_:Number = NaN;
_loc1_ = -72;
var _loc4_:Number = NaN;
_loc4_ = -50;
var _loc10_:Number = NaN;
_loc10_ = -88;
var _loc15_:int = 0;
_loc15_ = 4;
var _loc16_:int = 0;
_loc16_ = 2;
var _loc7_:int = 0;
_loc7_ = 8;
var _loc6_:* = 0;
var _loc3_:Sprite = null;
var _loc12_:Sprite = null;
var _loc8_:int = 0;
var _loc9_:int = 0;
_actions = new MovieClip();
_petActions = new MovieClip();
_loc6_ = 0;
while(_loc6_ < actionSprites.length)
{
if(_loc6_ < 8)
{
_loc3_ = GETDEFINITIONBYNAME(_loc6_ < 4 ? "sitBtns" : actionSprites[_loc6_]);
if(_loc6_ == 0)
{
_loc3_.x = actionWindow.ba.width * 0.5 + -72 - 25 - 5;
_loc3_.y = 10 + Math.floor(_loc6_ / 2) * 40 + -50;
_actions.addChild(_loc3_);
_actions.sitBtns = _loc3_;
_loc8_ = 1;
while(_loc8_ <= 4)
{
_loc12_ = _loc3_["sit" + _loc8_ + "Btn"];
_loc12_.buttonMode = true;
_loc12_.useHandCursor = true;
_loc12_.tabEnabled = true;
_loc12_.tabChildren = false;
_loc12_.addEventListener("mouseDown",actionClickHandler,false,0,true);
_loc8_++;
}
}
else if(_loc6_ >= 4)
{
_loc3_.x = 25 + (_loc6_ % 2 * 91 + -72);
_loc3_.y = 10 + Math.floor(_loc6_ / 2) * 40 + -88;
_actions.addChild(_loc3_);
_loc3_.buttonMode = true;
_loc3_.useHandCursor = true;
_loc3_.tabEnabled = true;
_loc3_.tabChildren = false;
_loc3_.addEventListener("mouseDown",actionClickHandler,false,0,true);
}
}
else
{
_loc3_ = GETDEFINITIONBYNAME(_loc6_ == 8 ? "poseBtns" : actionSprites[_loc6_]);
if(_loc6_ == 8)
{
_loc3_.visible = false;
_actions.poseBtns = _loc3_;
_loc3_.x = actionWindow.ba.width * 0.5 + -72 - 25 - 5;
_loc3_.y = 10 + Math.floor((_loc6_ - 8) / 2) * 40 + -50;
_actions.addChild(_loc3_);
_loc9_ = 1;
while(_loc9_ <= 2)
{
_loc12_ = _loc3_["pose" + _loc9_ + "Btn"];
_loc12_.buttonMode = true;
_loc12_.useHandCursor = true;
_loc12_.tabEnabled = true;
_loc12_.tabChildren = false;
_loc12_.addEventListener("mouseDown",actionClickHandler,false,0,true);
_loc9_++;
}
}
else if(_loc6_ >= 8 + 2)
{
_loc3_.visible = false;
if(_loc6_ == actionSprites.length - 1)
{
_actions.diveBtn = _loc3_;
}
else
{
_actions.swirlBtn = _loc3_;
}
_loc3_.x = 25 + ((_loc6_ - 5) % 2 * 91 + -72);
_loc3_.y = 10 + Math.floor((_loc6_ - 5) / 2) * 40 + -88;
_actions.addChild(_loc3_);
_loc3_.buttonMode = true;
_loc3_.useHandCursor = true;
_loc3_.tabEnabled = true;
_loc3_.tabChildren = false;
_loc3_.addEventListener("mouseDown",actionClickHandler,false,0,true);
}
}
_loc6_++;
}
_loc3_ = GETDEFINITIONBYNAME("playPetAnim_btnCont");
_loc3_.y = -31;
_loc3_.buttonMode = true;
_loc3_.useHandCursor = true;
_loc3_.tabEnabled = true;
_loc3_.tabChildren = false;
_loc3_.addEventListener("mouseDown",onPetPlayBtn,false,0,true);
_petActions.addChild(_loc3_);
_loc3_ = GETDEFINITIONBYNAME("dancePetAnim_btnCont");
_petActions.danceBtn = _loc3_;
_loc3_.y = 31;
_loc3_.buttonMode = true;
_loc3_.useHandCursor = true;
_loc3_.tabEnabled = true;
_loc3_.tabChildren = false;
_loc3_.addEventListener("mouseDown",actionClickHandler,false,0,true);
_petActions.addChild(_loc3_);
actionStrings = {};
actionStrings["sit1BtnCont"] = actionStrings["pose1BtnCont"] = [":sitNW:",":poseLeft:"];
actionStrings["sit2BtnCont"] = [":sitNE:"];
actionStrings["sit3BtnCont"] = [":sitSE:"];
actionStrings["sit4BtnCont"] = actionStrings["pose2BtnCont"] = [":sitSW:",":poseRight:"];
actionStrings["danceAnim_btnCont"] = actionStrings["dancePetAnim_btnCont"] = [":dance:"];
actionStrings["sleepAnim_btnCont"] = actionStrings["diveAnim_btnCont"] = [":sleep:",":dive:"];
actionStrings["hopAnim_btnCont"] = actionStrings["swirlAnim_btnCont"] = [":hop:",":swirl:"];
actionStrings["playAnim_btnCont"] = [":play:"];
}
private function setupTitleBanner() : void
{
if(emoteWindow.name.indexOf("Quest") == -1)
{
if(_titleBanner)
{
if(!actionWindow.contains(_titleBanner))
{
actionWindow.addChild(_titleBanner);
}
}
else
{
_titleBanner = GETDEFINITIONBYNAME("AnimsTitleBanner");
_titleBanner.x = -91.75;
_titleBanner.y = -91.25;
actionWindow.addChild(_titleBanner);
}
}
}
public function destroy() : void
{
setActionCallback = null;
actionBtn.removeEventListener("mouseDown",actionBtnDownHandler);
actionBtn = null;
actionWindow.visible = false;
actionWindow = null;
emoteBtn = null;
emoteWindow = null;
safeChatBtn = null;
safeChatTree = null;
}
// the name a button sends: the set shown's, and for dance and play the
// other set's own name when the set shown is not the room's.
private function nameFor(param1:String) : String
{
var _loc2_:Array = actionStrings[param1];
if(!_loc2_)
{
return null;
}
if(OTHER_SET_NAMES[param1] && _oceanShown != roomIsOcean())
{
return OTHER_SET_NAMES[param1][_oceanShown ? 1 : 0];
}
return _loc2_.length > 1 ? _loc2_[_oceanShown ? 1 : 0] : _loc2_[0];
}
public function getActionString(param1:Sprite) : String
{
if(_names[param1] != undefined)
{
return _names[param1];
}
var _loc2_:String = param1["constructor"].toString();
return nameFor(_loc2_.slice(7,_loc2_.length - 1));
}
// the button for an action's name, which it then stands for. `typed`:
// the player's own, typed in chat, which is held to the sets their
// animal has art for; another player's is taken as it came
// (AvatarWorldView.setAction plays what their animal has art for).
public function matchActionString(param1:String, param2:Boolean = false) : Sprite
{
var _loc3_:int = 0;
var _loc4_:String = OTHER_SET_BUTTONS[param1];
var _loc5_:Sprite = null;
if(_loc4_ && param2 && !playerHasSet(param1.indexOf("Swim") != -1))
{
return null;
}
if(!_loc4_)
{
for each(var _loc2_:String in actionSprites)
{
_loc3_ = int(actionStrings[_loc2_].indexOf(param1));
if(_loc3_ != -1)
{
if(actionStrings[_loc2_].length <= 1 || !param2 || playerHasSet(_loc3_ == 1))
{
_loc4_ = _loc2_;
break;
}
}
}
}
if(!_loc4_)
{
return null;
}
_loc5_ = GETDEFINITIONBYNAME(_loc4_);
_names[_loc5_] = param1;
return _loc5_;
}
public function openActions() : void
{
if(!actionWindow.visible)
{
updateSwapButton();
actionWindow.visible = true;
brightenActions();
}
}
public function dimActions() : void
{
if(actionWindow.visible && actionWindow.alpha != 0.5)
{
actionWindow.alpha = 0.5;
}
}
public function brightenActions() : void
{
if(actionWindow.alpha != 1)
{
actionWindow.alpha = 1;
}
}
public function closeActions() : void
{
if(actionWindow.visible)
{
actionWindow.visible = false;
brightenActions();
actionBtn.downToUpState();
}
}
public function grayOutPetDanceBtn(param1:Boolean) : void
{
if(_petActions)
{
_petActions.danceBtn.activateGrayState(param1);
}
}
private function actionBtnDownHandler(param1:MouseEvent) : void
{
param1.stopPropagation();
if(!param1.currentTarget.isGray)
{
if(actionWindow.visible)
{
closeActions();
}
else
{
if(safeChatTree.visible)
{
safeChatBtn.dispatchEvent(param1);
}
if(emoteWindow.visible)
{
emoteBtn.dispatchEvent(param1);
}
openActions();
}
}
}
private function actionClickHandler(param1:MouseEvent) : void
{
param1.stopPropagation();
if(!actionBtn.isGray && !param1.currentTarget.isGray)
{
setActionCallback(new param1.currentTarget.constructor());
actionBtn.dispatchEvent(new MouseEvent("mouseDown"));
param1.currentTarget.downToUpState();
}
}
private function onPetPlayBtn(param1:MouseEvent) : void
{
var _loc2_:WorldPet = null;
param1.stopPropagation();
if(AvatarManager.playerAvatarWorldView)
{
_loc2_ = AvatarManager.playerAvatarWorldView.getActivePet();
if(_loc2_)
{
AvatarManager.playerAvatarWorldView.faceAnim(0,0,false);
_loc2_.onClick(param1);
}
}
actionBtn.dispatchEvent(new MouseEvent("mouseDown"));
param1.currentTarget.downToUpState();
}
}
}
+55 -2
View File
@@ -90,65 +90,106 @@ package avatar
private static const STATE_LAND:int = 6;
// the actions' animations, `land` and `water`. an animal has the art of
// its own set only (land or ocean animals) or of both: an action of a
// set (`set`) plays as that set's when the animal has it, and otherwise
// as the animal's own set's, so a land animal underwater still sits
// (gui.ActionManager). ":dance:" and ":play:" are both sets' and go by
// the room for an animal of both; the other set's dance and play have
// names of their own.
public static var _actionLookup:Array = [{
"name":":dance:",
"land":23,
"water":38,
"flip":false
},{
"name":":danceLand:",
"land":23,
"water":38,
"set":"land",
"flip":false
},{
"name":":danceSwim:",
"land":23,
"water":38,
"set":"water",
"flip":false
},{
"name":":sleep:",
"land":22,
"water":41,
"set":"land",
"flip":false
},{
"name":":dive:",
"land":22,
"water":41,
"set":"water",
"flip":false
},{
"name":":hop:",
"land":17,
"water":33,
"set":"land",
"flip":false
},{
"name":":swirl:",
"land":17,
"water":33,
"set":"water",
"flip":false
},{
"name":":play:",
"land":6,
"water":39,
"flip":false
},{
"name":":playLand:",
"land":6,
"water":39,
"set":"land",
"flip":false
},{
"name":":playSwim:",
"land":6,
"water":39,
"set":"water",
"flip":false
},{
"name":":sitNW:",
"land":2,
"water":40,
"set":"land",
"flip":true
},{
"name":":poseLeft:",
"land":2,
"water":40,
"set":"water",
"flip":true
},{
"name":":sitNE:",
"land":2,
"water":40,
"set":"land",
"flip":false
},{
"name":":sitSE:",
"land":4,
"water":40,
"set":"land",
"flip":true
},{
"name":":poseRight:",
"land":2,
"water":40,
"set":"water",
"flip":false
},{
"name":":sitSW:",
"land":4,
"water":40,
"set":"land",
"flip":false
}];
@@ -1148,11 +1189,22 @@ package avatar
_lastIdleAnim = getBaseIdle();
_lastIdleFlip = false;
var _loc2_:String = _actionMgr.getActionString(param1);
// the sets this animal has art for
var _loc5_:Boolean = _avatar == null || Utility.isLand(_avatar.enviroTypeFlag);
var _loc6_:Boolean = _avatar == null || Utility.isOcean(_avatar.enviroTypeFlag);
var _loc7_:String = null;
for each(var _loc4_:Object in _actionLookup)
{
if(_loc4_.name == _loc2_)
{
_loc3_ = int(_roomType == 0 ? _loc4_.land : _loc4_.water);
// the action's own set, if the animal has it; otherwise its
// only set, or with both (or neither known) the room's
_loc7_ = _loc4_.set;
if(!_loc7_ || (_loc7_ == "water" ? !_loc6_ : !_loc5_))
{
_loc7_ = _loc5_ == _loc6_ ? (_roomType == 0 ? "land" : "water") : (_loc5_ ? "land" : "water");
}
_loc3_ = int(_loc7_ == "water" ? _loc4_.water : _loc4_.land);
if(_loc3_ > 0)
{
_lastIdleAnim = _loc3_;
@@ -1164,7 +1216,8 @@ package avatar
}
if(_pet && _loc2_)
{
_pet.setActionByName(_loc2_);
// pets know ":dance:" and ":play:", not the other set's names
_pet.setActionByName(_loc2_.replace(/(Land|Swim):$/,":"));
}
}
+2 -4
View File
@@ -218,15 +218,13 @@ package gui
"frame":"redeemCode",
"labelTxt":24819,
"btnTxt":24820
/* the game's "World" row (choose a server) is out: there is one
world, this server does not answer the list it asks for (rm),
and the picker then waited behind its spinner for ever.
},{
// the world picker (gui.ServerSelector): the server's worlds,
// config.shards, listed by the server's answer to "rm"
"type":TOGGLE_TYPE_JOIN,
"frame":"world",
"labelTxt":6395,
"btnTxt":6366
*/
},{
"type":TOGGLE_TYPE_TOGGLE_BTN,
"frame":"nameBadge",
+14
View File
@@ -145,6 +145,9 @@ package room
private var _shardId:int;
// whether the worlds' names were asked for (chosenLoginFinished)
private static var _askedWorldNames:Boolean;
public var _gotNewShardId:Boolean;
private var _forceInvisMode:Boolean;
@@ -2603,6 +2606,17 @@ package room
{
if(_mainBackObj == null)
{
// the worlds' names (generic list 16), which the game asked for on
// its world screen at login: this server has none, and without
// them the settings menu's World row and the world picker
// (ServerSelector) have no names, and the picker never opens.
// asked once: with the names in, fillNamesArray asks for the
// world list instead, whose answer needs the picker open.
if(!_askedWorldNames)
{
_askedWorldNames = true;
ServerSelector.fillNamesArray();
}
if(!gMainFrame.userInfo.avtDefsCached)
{
if(ItemXtCommManager.itemDefsHaveLoaded)
+1 -1
View File
@@ -536,7 +536,7 @@ package avatar
}
else
{
_loc5_ = _actionMgr.matchActionString(_loc3_);
_loc5_ = _actionMgr.matchActionString(_loc3_,true);
if(_loc5_)
{
sendAvatarAction(_loc5_);
BIN
View File
Binary file not shown.
Binary file not shown.
+15 -3
View File
@@ -6,6 +6,7 @@
const assert = require("assert");
const {spawn} = require("child_process");
const crypto = require("crypto");
const fs = require("fs");
const net = require("net");
const os = require("os");
@@ -138,10 +139,17 @@ class GameClient {
}
}
// what the client 1.3.0 sends about its computer (lib/devices.js), made up:
// one computer for each username, unless a test gives its own.
const deviceFor = name => {
const hash = kind => crypto.createHash("sha256").update(`test-device:${kind}:${String(name).toLowerCase()}`).digest("hex");
return {v: 1, ids: {os: hash("os"), install: hash("install"), disk: [hash("disk")], mac: [hash("mac")]}, notes: []};
};
const postJson = (url, body) => fetch(url, {
method: "POST",
headers: {"Content-Type": "application/json", "Origin": "null"},
body: JSON.stringify(body),
body: JSON.stringify(/\/authenticate$/.test(url) && body && body.device === undefined ? {...body, device: deviceFor(body.username || "")} : body),
});
// starts a server on the given ports with an empty database, runs `run`
@@ -151,7 +159,11 @@ const postJson = (url, body) => fetch(url, {
const withServer = async (name, httpPort, gamePort, run, {dataDir: keptDir = null} = {}) => {
const dataDir = keptDir || fs.mkdtempSync(path.join(os.tmpdir(), "aj-test-"));
const server = spawn(process.execPath, [path.join(__dirname, "..", "server.js")], {
env: {...process.env, AJ_HTTP_PORT: httpPort, AJ_GAME_PORT: gamePort, AJ_DATA_DIR: dataDir, AJ_QUIET: "1"},
env: {...process.env, AJ_HTTP_PORT: httpPort, AJ_GAME_PORT: gamePort, AJ_DATA_DIR: dataDir, AJ_QUIET: "1",
// everyone arrives in the township, as the tests expect
AJ_SPAWN_ROOMS: process.env.AJ_SPAWN_ROOMS || "jamaa_township.room_main",
// and in the one world
AJ_WORLDS: process.env.AJ_WORLDS || "1"},
stdio: ["ignore", "pipe", "inherit"],
});
let output = "";
@@ -184,4 +196,4 @@ const withServer = async (name, httpPort, gamePort, run, {dataDir: keptDir = nul
}
};
module.exports = {GameClient, postJson, withServer};
module.exports = {deviceFor, GameClient, postJson, withServer};
+1
View File
@@ -33,6 +33,7 @@ set -- \
gui.ReportAPlayer ReportAPlayer.as \
gui.ECardCreation ECardCreation.as \
gui.GuiManager GuiManager.as \
gui.ActionManager ActionManager.as \
gui.PlayerSearch PlayerSearch.as \
avatar.NPCView NPCView.as \
gui.ChatHistory ChatHistory.as \
+55 -1
View File
@@ -178,8 +178,29 @@ def sprout():
return [(stem, False), (small, False), (large, False)]
# id, outline, and the card disc's colours: top, bottom, rim.
def seal_points():
"""A round seal with eight soft scallops, as verified accounts have."""
steps = 96
return [(7.5 * (1 + 0.075 * math.cos(math.radians(8 * angle))) * math.cos(math.radians(angle)),
7.5 * (1 + 0.075 * math.cos(math.radians(8 * angle))) * math.sin(math.radians(angle)))
for angle in (360 * step / steps - 90 for step in range(steps))]
def seal_tick():
return [(x * 0.52, y * 0.52 + 0.3) for x, y in tick()[0][0]]
def verified():
# the seal with the tick cut out of it, so the name tag's colour shows
# the seal and the tag behind shows through the tick.
return [(seal_points(), False), (seal_tick(), True)]
# id, outline, and the card disc's colours: top, bottom, rim. a badge whose
# rim is None has no disc: its outline's solid pieces are shaded instead,
# and its holes are white (the verified seal, blue with a white tick).
BADGES = [
("verified", verified, "#4cb3ff", "#1478e6", None),
("owner", crown, "#ffd95a", "#f0a11c", "#96600a"),
("moderator", shield, "#5cb2ff", "#1f6fd6", "#12458a"),
("contributor", wrench, "#6fd878", "#2f9e3a", "#19621f"),
@@ -262,6 +283,8 @@ def card_pixels(paths, top, bottom, rim):
"""CARD_SIZE square of (r, g, b, a): a disc shaded from `top` to
`bottom` with a `rim`, the outline in white on it. Sixteen samples to a
pixel."""
if rim is None:
return shape_pixels(paths, top, bottom)
paths = fitted(paths, CARD_HALF)
top, bottom, rim = rgb(top), rgb(bottom), rgb(rim)
middle, fill_radius, rim_radius = CARD_SIZE / 2, 20.0, 23.0
@@ -291,6 +314,37 @@ def card_pixels(paths, top, bottom, rim):
return rows
def shape_pixels(paths, top, bottom):
"""CARD_SIZE square of (r, g, b, a): the outline's solid pieces, as big
as the disc, shaded from `top` to `bottom`, and its holes in white."""
paths = fitted(paths, 23.0)
solid = [(points, False) for points, hole in paths if not hole]
holes = [(points, False) for points, hole in paths if hole]
top, bottom = rgb(top), rgb(bottom)
middle = CARD_SIZE / 2
rows = []
for py in range(CARD_SIZE):
row = []
for px in range(CARD_SIZE):
total = [0.0, 0.0, 0.0, 0.0]
for sy in range(4):
for sx in range(4):
x, y = px + (sx + 0.5) / 4 - middle, py + (sy + 0.5) / 4 - middle
if not inside(solid, x, y):
continue
if inside(holes, x, y):
colour = (255, 255, 255)
else:
shade = (y + 23.0) / 46.0
colour = tuple(a + (b - a) * shade for a, b in zip(top, bottom))
for channel in range(3):
total[channel] += colour[channel]
total[3] += 1
row.append(tuple(round(total[c] / total[3]) if total[3] else 0 for c in range(3)) + (round(total[3] / 16 * 255),))
rows.append(row)
return rows
def png(rows):
raw = b"".join(b"\x00" + bytes(value for pixel in row for value in pixel) for row in rows)