feat: hardware bans, panel search and logs, jam-a-gram and wall post logs

- the client (1.3.0) sends one-way hashes of the device's ids at
  sign-in; the server keys them again with a secret of its own
  (data/device-key) and keeps them per account (lib/devices.js). a
  sign-in without them is refused with 426 (AJ_REQUIRE_DEVICE=0 lets it
  in), so 1.2 clients cannot sign in.
- hardware bans: every device an account used in the last 90 days.
  any id but a network card blocks sign-in, sign-up and the game, on
  any account. a network card match, ids that look altered, or a device
  shared with a banned player raise hardware alerts instead.
- both panels: hardware ban and lift, the account's hardware ids,
  search by hardware id, other accounts by device or address, a
  timeline (bans, staff actions, reports, alerts), and hardware bans
  and alerts in the bans tab.
- jam-a-grams and wall posts go into the chat log, the filtered ones
  marked not sent. chat search filters by kind, by what the filter
  stopped, and from a time back; each player's page lists their
  jam-a-grams and wall posts, sent and received.
- account search runs on the server and ranks exact names first, then
  names starting with the search; the admin panel no longer downloads
  every account. hidden tabs only refresh the waiting counts in the
  title. masterpieces can be searched by maker, approved ones too.
  reports can show the reported player's chat at the time. links follow
  the open tab and player.
- admin actions on accounts go into the moderator log.
- privacy policy covers hardware hashes and the new logs.
This commit is contained in:
Burrowdev committed 2026-10-17 23:54:46 +03:00
1 parent 0e86592d40
commit cf729d52dc
21 files changed
+1898 -131

No files matched your search

+4
View File
@@ -98,6 +98,10 @@ module.exports = {
// cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only. // cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only.
upstreamContent: env.AJ_UPSTREAM || "https://ajcontent.akamaized.net/", upstreamContent: env.AJ_UPSTREAM || "https://ajcontent.akamaized.net/",
offline: env.AJ_OFFLINE === "1", offline: env.AJ_OFFLINE === "1",
// the client's device ids (lib/devices.js): a sign-in without them (a
// client from before 1.3.0, the official launcher, or one that left them
// out) is refused. AJ_REQUIRE_DEVICE=0 lets them in, unknown.
requireDevice: env.AJ_REQUIRE_DEVICE !== "0",
deployVersion: env.AJ_DEPLOY_VERSION || "1830", deployVersion: env.AJ_DEPLOY_VERSION || "1830",
// older builds the CDN still serves, asked in turn for a room file the // 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. // current build has dropped. 1828 is the last with the Summer Carnival.
+2
View File
@@ -270,6 +270,8 @@ const normalize = account => {
account.totp = account.totp || null; account.totp = account.totp || null;
account.totpSetup = account.totpSetup || null; account.totpSetup = account.totpSetup || null;
account.devices = Array.isArray(account.devices) ? account.devices : []; 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.nextInv = account.nextInv || 2;
account.numLogins = account.numLogins || 0; account.numLogins = account.numLogins || 0;
account.uuid = account.uuid || crypto.randomUUID(); 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 bans = require("./bans.js");
const captcha = require("./captcha.js"); const captcha = require("./captcha.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const devices = require("./devices.js");
const config = require("../config.js"); const config = require("../config.js");
const dens = require("./dens.js"); const dens = require("./dens.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
@@ -204,13 +205,21 @@ const handle = async (route, params, body, from) => {
} }
const ban = world.moderation.banOf(account); const ban = world.moderation.banOf(account);
const addressBan = ban ? null : bans.addressBan(from.address); 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} 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": { case "POST /api/register": {
if (bans.addressBan(from.address)) { if (bans.addressBan(from.address)) {
return {status: 403, body: {error: "address_banned"}}; 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 || {}; const {username, password, avatarType} = body || {};
// the terms and the privacy policy, and old enough to agree to them: // 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. // said by the one signing up, on the page or in the client.
+68 -11
View File
@@ -3,7 +3,8 @@
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const config = require("../config.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 // panel (lib/modpanel.js), which is where a moderator reads what was said
// before deciding anything; nothing else reads it. lines older than // before deciding anything; nothing else reads it. lines older than
// config.chatLogDays are deleted, and an account's lines go when the // config.chatLogDays are deleted, and an account's lines go when the
@@ -26,6 +27,11 @@ const SCHEMA = `
const CHAT = "chat"; const CHAT = "chat";
const WHISPER = "whisper"; 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 DAY_SECONDS = 86400;
const MAX_TEXT = 600; const MAX_TEXT = 600;
const PAGE = 100; const PAGE = 100;
@@ -40,28 +46,69 @@ const prune = () => {
const load = () => { const load = () => {
db().exec(SCHEMA); 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(); prune();
setInterval(prune, DAY_SECONDS * 1000 / 4).unref(); 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 // A line said in `room` (its name as the world knows it), or with `to` a
// whisper to that player. // whisper to that player.
const record = (account, room, text, to = "") => { const record = (account, room, text, to = "") => {
if (config.chatLogDays <= 0) { if (config.chatLogDays <= 0) {
return; return;
} }
db().prepare("INSERT INTO chat_log (at, account_id, username, room, kind, to_name, text) VALUES (?, ?, ?, ?, ?, ?, ?)") 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)); .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 // 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. // to, or sent to), by room, by words in them, by kind (one of KINDS, or
const search = ({username = "", room = "", text = "", before = 0}) => { // "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 where = [];
const values = []; 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)"); where.push("(username = ? COLLATE NOCASE OR to_name = ? COLLATE NOCASE)");
values.push(username, username); values.push(username, username);
} }
@@ -87,9 +134,9 @@ const around = id => {
if (!line) { if (!line) {
return null; return null;
} }
const [same, values] = line.kind === WHISPER const [same, values] = line.kind === CHAT
? ["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]]
: ["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 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); 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)}; 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). // 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); 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. // an account being deleted: what it said goes with it.
const forget = account => { const forget = account => {
db().prepare("DELETE FROM chat_log WHERE account_id = ?").run(account.id); 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 accounts = require("./accounts.js");
const achievements = require("./achievements.js"); const achievements = require("./achievements.js");
const chatFilter = require("./chatfilter.js"); const chatFilter = require("./chatfilter.js");
const chatlog = require("./chatlog.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const dens = require("./dens.js"); const dens = require("./dens.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
@@ -261,6 +262,7 @@ module.exports = ({findOnline, blocks}) => {
if (rule) { if (rule) {
chatFilter.warn(session); chatFilter.warn(session);
console.log(`[filter] ${account.username} in a Jam-a-Gram to ${to.username}: "${clean(message || "")}" (${rule})`); 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); reply(FAILED);
return; return;
} }
@@ -279,6 +281,8 @@ module.exports = ({findOnline, blocks}) => {
return; return;
} }
deliver(to, {from: account.username, fromId: account.id, card: Number(card), stamp: Number(stamp), msg: clean(message || ""), gift}); 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); achievements.add(account, achievements.VARS.jamAGramsSent);
if (gift) { if (gift) {
achievements.add(account, achievements.VARS.giftsSent); achievements.add(account, achievements.VARS.giftsSent);
+4 -1
View File
@@ -3,13 +3,15 @@
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const bans = require("./bans.js"); const bans = require("./bans.js");
const chatlog = require("./chatlog.js"); const chatlog = require("./chatlog.js");
const devices = require("./devices.js");
const masterpieces = require("./masterpieces.js"); const masterpieces = require("./masterpieces.js");
const support = require("./support.js"); const support = require("./support.js");
const world = require("./world.js"); const world = require("./world.js");
// an account deleted for good, by its owner (lib/manage.js) or by the admin // 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 // (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 // 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 // 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. // moderators did, under the name it had, until lib/retention.js ends it.
@@ -20,6 +22,7 @@ module.exports = account => {
} }
bans.forget(account); bans.forget(account);
chatlog.forget(account); chatlog.forget(account);
devices.forget(account);
support.forget(account); support.forget(account);
accounts.remove(account); accounts.remove(account);
}; };
+20 -1
View File
@@ -11,6 +11,7 @@ const bans = require("./bans.js");
const captcha = require("./captcha.js"); const captcha = require("./captcha.js");
const cdn = require("./cdn.js"); const cdn = require("./cdn.js");
const config = require("../config.js"); const config = require("../config.js");
const devices = require("./devices.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const manage = require("./manage.js"); const manage = require("./manage.js");
@@ -383,6 +384,14 @@ const authenticate = async (req, res, from) => {
renameAndSignIn(res, body, from); renameAndSignIn(res, body, from);
return; 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 byRefresh = body.refresh_token !== undefined;
const accountKey = String(body.username).trim().toLowerCase(); const accountKey = String(body.username).trim().toLowerCase();
if (!from.local && failuresByAddress.blocked(from.key)) { if (!from.local && failuresByAddress.blocked(from.key)) {
@@ -430,6 +439,13 @@ const authenticate = async (req, res, from) => {
send(res, 401, {error_code: 101, error: "address_banned", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason}); send(res, 401, {error_code: 101, error: "address_banned", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason});
return; return;
} }
// A banned computer (lib/devices.js): for good, whichever account.
const deviceBan = device && devices.banOf(device);
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 // 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. // still nobody gets in. the launcher shows this as a failed sign-in.
if (account.locked) { if (account.locked) {
@@ -466,10 +482,13 @@ const authenticate = async (req, res, from) => {
send(res, 401, {error_code: 101, error: "name_rejected", rename_ticket: renameTicket(account, deviceToken)}); send(res, 401, {error_code: 101, error: "name_rejected", rename_ticket: renameTicket(account, deviceToken)});
return; return;
} }
if (device) {
devices.seen(account, device, other => world.moderation.banRemaining(other) !== 0);
}
if (!byRefresh) { if (!byRefresh) {
accounts.recordLogin(account, "launcher", from.address); accounts.recordLogin(account, "launcher", from.address);
accounts.save(account);
} }
accounts.save(account);
// the custom client's advanced settings; the official launcher sends none. // the custom client's advanced settings; the official launcher sends none.
accounts.setLoginChoices(account, body.login_choices); accounts.setLoginChoices(account, body.login_choices);
const token = byRefresh ? body.refresh_token : accounts.issueToken(account); 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}; 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); 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 // 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); ([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null);
module.exports = { 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, needsReview, setNeedsReview, madeBy,
PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES, 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); 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
@@ -8,6 +8,7 @@ const bans = require("./bans.js");
const captcha = require("./captcha.js"); const captcha = require("./captcha.js");
const chatlog = require("./chatlog.js"); const chatlog = require("./chatlog.js");
const config = require("../config.js"); const config = require("../config.js");
const devices = require("./devices.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const manage = require("./manage.js"); const manage = require("./manage.js");
const masterpieces = require("./masterpieces.js"); const masterpieces = require("./masterpieces.js");
@@ -44,7 +45,6 @@ const SESSION_HOURS = 12;
const TEN_MINUTES_MS = 600000; const TEN_MINUTES_MS = 600000;
const MAX_BAN_HOURS = 24 * 365 * 10; const MAX_BAN_HOURS = 24 * 365 * 10;
const MAX_MESSAGE_LENGTH = 200; const MAX_MESSAGE_LENGTH = 200;
const MAX_FOUND = 50;
const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS); const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS);
const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator
@@ -99,19 +99,17 @@ const playerRow = (account, playing) => {
playtime: account.playtime, playtime: account.playtime,
bio: account.bio, bio: account.bio,
discord: account.discord, discord: account.discord,
deviceBanned: devices.bannedId(account) !== 0,
}; };
}; };
const playing = () => new Map(world.players().map(player => [player.username, player.room || "(between rooms)"])); 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 findPlayers = query => {
const wanted = String(query || "").trim().toLowerCase().slice(0, 100);
const online = playing(); const online = playing();
return accounts.all() const {found, total} = staff.findAccounts(query);
.filter(account => account.username.toLowerCase().includes(wanted)) return {players: found.map(account => playerRow(account, online)), total};
.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));
}; };
// one player: the row, what was done about their bans (without addresses), // one player: the row, what was done about their bans (without addresses),
@@ -121,6 +119,9 @@ const playerDetail = account => ({
history: bans.historyOf(account).map(({at, action, seconds, reason, by}) => ({at, action, seconds, reason, by})), history: bans.historyOf(account).map(({at, action, seconds, reason, by}) => ({at, action, seconds, reason, by})),
appeal: bans.appealOf(account), appeal: bans.appealOf(account),
openReports: reports.list(false).filter(report => report.target.toLowerCase() === account.username.toLowerCase()).length, 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. // an address with its end left out, and a name to lift its ban by.
@@ -213,6 +214,11 @@ const act = (mod, target, body) => {
} }
return {ok: "Their address is banned.", detail: result.ban.reason}; return {ok: "Their address is banned.", detail: result.ban.reason};
} }
// 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: default:
return {error: "Unknown action."}; return {error: "Unknown action."};
} }
@@ -339,9 +345,36 @@ const handle = async (req, res, url, from, web) => {
paintings: masterpieces.list(masterpieces.PENDING).length}); paintings: masterpieces.list(masterpieces.PENDING).length});
return; 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": { case "GET /mod/api/players": {
if (url.searchParams.get("by") !== "address") { const searchBy = url.searchParams.get("by");
reply(200, {players: findPlayers(url.searchParams.get("q"))}); 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; return;
} }
// by address: only the address typed, which is written down (once // by address: only the address typed, which is written down (once
@@ -386,7 +419,8 @@ const handle = async (req, res, url, from, web) => {
case "GET /mod/api/chat": { case "GET /mod/api/chat": {
const params = url.searchParams; const params = url.searchParams;
const lines = chatlog.search({username: (params.get("username") || "").trim().slice(0, 100), room: (params.get("room") || "").trim().slice(0, 100), 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}); reply(200, {lines, more: lines.length === chatlog.PAGE, days: config.chatLogDays});
return; return;
} }
@@ -426,7 +460,7 @@ const handle = async (req, res, url, from, web) => {
} }
case "GET /mod/api/bans": 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; return;
case "POST /mod/api/address": { case "POST /mod/api/address": {
@@ -435,9 +469,16 @@ const handle = async (req, res, url, from, web) => {
return; 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). // paintings players framed (lib/masterpieces.js).
case "GET /mod/api/masterpieces": 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; return;
case "GET /mod/api/masterpiece": { case "GET /mod/api/masterpiece": {
+89 -4
View File
@@ -9,7 +9,9 @@ const adopt = require("./adopt.js");
const badges = require("./badges.js"); const badges = require("./badges.js");
const bans = require("./bans.js"); const bans = require("./bans.js");
const colours = require("./colours.js"); const colours = require("./colours.js");
const chatlog = require("./chatlog.js");
const config = require("../config.js"); const config = require("../config.js");
const devices = require("./devices.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const log = require("./log.js"); const log = require("./log.js");
@@ -47,6 +49,7 @@ const TEN_MINUTES_MS = 600000;
const DAY_SECONDS = 86400; const DAY_SECONDS = 86400;
const MAX_ANNOUNCEMENT = 300; const MAX_ANNOUNCEMENT = 300;
const MAX_OWNED_LISTED = 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. // currencies the panel can hand out, as indexes into CURRENCIES.
const GIFT_CURRENCIES = {gems: 0, tickets: 1, diamonds: 3}; 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 // who a ban is written down as given by. the panel has one password and so
@@ -155,6 +158,10 @@ const accountRow = (account, playing) => {
level: activeAvatar(account).questLevel || 0, level: activeAvatar(account).questLevel || 0,
items: account.items.length + account.denItems.length, items: account.items.length + account.denItems.length,
gems: account.currency.gems || 0, 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,
}; };
}; };
@@ -477,6 +484,11 @@ const act = (account, body) => {
return {ok: `${name} is no longer banned.`}; return {ok: `${name} is no longer banned.`};
case "kick": case "kick":
return actions.kick(account) ? {ok: `${name} was disconnected.`} : {error: `${name} is not online.`}; 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. // counted in hours; the game's own notice counts minutes.
case "silence": { case "silence": {
const hours = wholeNumber(body.hours, 0, MAX_BAN_HOURS); const hours = wholeNumber(body.hours, 0, MAX_BAN_HOURS);
@@ -643,9 +655,24 @@ const handle = async (req, res, url, from, web) => {
reply(200, overview()); reply(200, overview());
return; 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": { case "GET /admin/api/accounts": {
const playing = new Map(world.players().map(player => [player.username, player.room || "(between rooms)"])); 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; return;
} }
@@ -660,6 +687,28 @@ const handle = async (req, res, url, from, web) => {
reply(found.error ? 400 : 200, found); reply(found.error ? 400 : 200, found);
return; 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": { case "GET /admin/api/logs": {
const lines = log.recent(Number(url.searchParams.get("after")) || 0, (url.searchParams.get("filter") || "").slice(0, 100)); const lines = log.recent(Number(url.searchParams.get("after")) || 0, (url.searchParams.get("filter") || "").slice(0, 100));
@@ -676,6 +725,10 @@ const handle = async (req, res, url, from, web) => {
const result = act(account, body); const result = act(account, body);
if (result.ok) { if (result.ok) {
console.log(`[admin] ${body.action} on "${account.username}"`); 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); reply(result.ok ? 200 : 400, result);
return; return;
@@ -688,7 +741,39 @@ const handle = async (req, res, url, from, web) => {
} }
case "GET /admin/api/bans": 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; return;
// who may use the moderator panel, and what each did there. // who may use the moderator panel, and what each did there.
@@ -753,8 +838,8 @@ const handle = async (req, res, url, from, web) => {
case "GET /admin/api/masterpieces": case "GET /admin/api/masterpieces":
reply(200, { reply(200, {
review: masterpieces.needsReview(), review: masterpieces.needsReview(),
waiting: masterpieces.list(masterpieces.PENDING), ...masterpieces.listsFor(url.searchParams.get("creator")),
approved: masterpieces.list(masterpieces.APPROVED), waitingCount: masterpieces.list(masterpieces.PENDING).length,
}); });
return; 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; 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 accounts = require("./accounts.js");
const bans = require("./bans.js"); const bans = require("./bans.js");
const devices = require("./devices.js");
const limits = require("./limits.js");
const manage = require("./manage.js"); const manage = require("./manage.js");
const modlog = require("./modlog.js");
const reports = require("./reports.js");
const support = require("./support.js"); const support = require("./support.js");
const world = require("./world.js"); const world = require("./world.js");
@@ -25,6 +29,29 @@ const disciplined = () => accounts.all()
.filter(entry => entry.banned !== 0 || entry.silenced !== 0) .filter(entry => entry.banned !== 0 || entry.silenced !== 0)
.sort((a, b) => a.username.localeCompare(b.username)); .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 // 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 // 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 // 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)}; 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. // appeals with what each is against, as it stands now.
const appealsFor = handled => bans.appeals(handled).map(appeal => { const appealsFor = handled => bans.appeals(handled).map(appeal => {
const account = accounts.byId(appeal.accountId); 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}; 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 path = require("path");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const chatFilter = require("./chatfilter.js"); const chatFilter = require("./chatfilter.js");
const chatlog = require("./chatlog.js");
const masterpieces = require("./masterpieces.js"); const masterpieces = require("./masterpieces.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const {isUint} = require("./player.js"); const {isUint} = require("./player.js");
@@ -155,6 +156,7 @@ module.exports = ({blocks, findOnline}) => {
const rule = message ? chatFilter.broken(message) : null; const rule = message ? chatFilter.broken(message) : null;
if (rule) { if (rule) {
console.log(`[filter] ${viewer.username} on ${owner.username}'s wall: "${message}" (${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); const session = findOnline(viewer.username);
if (session) { if (session) {
chatFilter.warn(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)) { if (typeof body.pp === "string" && owner.wall.posts.some(other => other.x === body.pp)) {
post.pp = body.pp; // a reply to that post 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.push(post);
owner.wall.posts = owner.wall.posts.slice(-MAX_POSTS); owner.wall.posts = owner.wall.posts.slice(-MAX_POSTS);
owner.wall.modified = post.t; owner.wall.modified = post.t;
+27
View File
@@ -12,6 +12,7 @@ const defpacks = require("./defpacks.js");
const avatarHandlers = require("./avatars.js"); const avatarHandlers = require("./avatars.js");
const badges = require("./badges.js"); const badges = require("./badges.js");
const bans = require("./bans.js"); const bans = require("./bans.js");
const devices = require("./devices.js");
const chatlog = require("./chatlog.js"); const chatlog = require("./chatlog.js");
const chatFilter = require("./chatfilter.js"); const chatFilter = require("./chatfilter.js");
const buddyModule = require("./buddies.js"); const buddyModule = require("./buddies.js");
@@ -261,6 +262,18 @@ const login = (session, msg) => {
loginFailed(session, LOGIN_BANNED, "Banned"); loginFailed(session, LOGIN_BANNED, "Banned");
return; 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 // its username was rejected (lib/moderation.js): a new one first, which
// the client or the account page asks for. // the client or the account page asks for.
if (account.nameRejected) { if (account.nameRejected) {
@@ -1588,6 +1601,20 @@ module.exports = {
} }
return there.length; 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 // 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. // round to closing), so the caller can go on to rename or delete it.
disconnect(account) { disconnect(account) {
+621 -53
View File
@@ -158,6 +158,8 @@
tbody tr:last-child td { border-bottom: 0; } tbody tr:last-child td { border-bottom: 0; }
tbody tr.selected td { background: var(--raised); } tbody tr.selected td { background: var(--raised); }
tbody tr.pick { cursor: pointer; } 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; } .empty { color: var(--muted); padding: 8px 0; }
.toolbar { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; } .toolbar { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; }
.toolbar input[type="search"] { flex: 1; min-width: 180px; } .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 .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 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; } .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; } .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 { border: 1px solid var(--line); border-radius: 18px; padding: 14px; }
.painting img { display: block; width: 100%; height: auto; border-radius: 10px; background: #fff; } .painting img { display: block; width: 100%; height: auto; border-radius: 10px; background: #fff; }
.painting h3 { margin: 8px 0 2px; } .painting h3 { margin: 8px 0 2px; }
.painting .buttons { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; } .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; } textarea { width: 100%; resize: vertical; }
.send-row { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; align-items: center; } .send-row { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; align-items: center; }
#owned { margin-top: 16px; } #owned { margin-top: 16px; }
@@ -245,6 +262,7 @@
<nav role="tablist"> <nav role="tablist">
<button role="tab" data-tab="overview" aria-selected="true">Overview</button> <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="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="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="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> <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"> <select id="account-search-by" aria-label="Search by">
<option value="name">By name</option> <option value="name">By name</option>
<option value="address">By IP address</option> <option value="address">By IP address</option>
<option value="device">By hardware ID</option>
</select> </select>
<input id="account-search" type="search" placeholder="Search" aria-label="Search accounts"> <input id="account-search" type="search" placeholder="Search" aria-label="Search accounts">
<select id="account-filter" aria-label="Which accounts"> <select id="account-filter" aria-label="Which accounts">
@@ -294,10 +313,9 @@
</select> </select>
</div> </div>
<div id="address-view" hidden> <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> <p class="status" id="address-status" role="status"></p>
<div class="table-wrap"><table> <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> <tbody id="address-results"></tbody>
</table></div> </table></div>
</div> </div>
@@ -306,6 +324,7 @@
<tbody id="accounts"></tbody> <tbody id="accounts"></tbody>
</table></div> </table></div>
<div class="empty" id="no-accounts" hidden>No accounts match.</div> <div class="empty" id="no-accounts" hidden>No accounts match.</div>
<p class="hint" id="account-more" hidden></p>
<div id="detail" hidden> <div id="detail" hidden>
<h2 id="detail-name"></h2> <h2 id="detail-name"></h2>
@@ -355,7 +374,9 @@
<div class="row" style="margin-top:8px"> <div class="row" style="margin-top:8px">
<button type="button" data-action="ban" class="danger">Ban</button> <button type="button" data-action="ban" class="danger">Ban</button>
<button type="button" data-action="banReason">Save reason</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 id="ban-record"></div>
</div> </div>
<div class="action"> <div class="action">
@@ -369,6 +390,14 @@
<div class="row"><input id="message-text" maxlength="200" placeholder="Text" aria-label="Message"> <div class="row"><input id="message-text" maxlength="200" placeholder="Text" aria-label="Message">
<button type="button" data-action="message">Send</button></div> <button type="button" data-action="message">Send</button></div>
</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"> <div class="action">
<h3>Gems</h3> <h3>Gems</h3>
<div class="row"><input id="gems-amount" type="number" placeholder="Amount" aria-label="Gems to add"> <div class="row"><input id="gems-amount" type="number" placeholder="Amount" aria-label="Gems to add">
@@ -404,11 +433,69 @@
</div> </div>
</div> </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 id="owned"></div>
</div> </div>
</section> </section>
</div> </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> <div data-view="reports" hidden>
<section> <section>
<div class="toolbar"> <div class="toolbar">
@@ -490,6 +577,31 @@
</table></div> </table></div>
<div class="empty" id="no-addresses" hidden>No address is banned.</div> <div class="empty" id="no-addresses" hidden>No address is banned.</div>
</section> </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>
<div data-view="messages" hidden> <div data-view="messages" hidden>
@@ -519,12 +631,15 @@
<select id="masterpiece-filter" aria-label="Which masterpieces"> <select id="masterpiece-filter" aria-label="Which masterpieces">
<option value="waiting">Waiting</option> <option value="waiting">Waiting</option>
<option value="approved">Approved</option> <option value="approved">Approved</option>
<option value="all">All</option>
</select> </select>
<input id="masterpiece-creator" type="search" maxlength="100" placeholder="Maker's username" autocomplete="off" spellcheck="false" aria-label="Maker's username">
</div> </div>
<label class="check"><input id="masterpiece-review" type="checkbox"> Review new masterpieces</label> <label class="check"><input id="masterpiece-review" type="checkbox"> Review new masterpieces</label>
<p class="status" id="masterpiece-status" role="status"></p> <p class="status" id="masterpiece-status" role="status"></p>
<div class="paintings" id="masterpieces"></div> <div class="paintings" id="masterpieces"></div>
<div class="empty" id="no-masterpieces" hidden>Nothing here.</div> <div class="empty" id="no-masterpieces" hidden>Nothing here.</div>
<div class="preview" id="preview" hidden><img id="preview-img" alt=""></div>
</section> </section>
</div> </div>
@@ -592,7 +707,9 @@
const MAX_LOG_LINES = 2000; const MAX_LOG_LINES = 2000;
let state = null; // {needsSetup, needsSetupCode, signedIn} 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 badges = []; // {id, label}: the badges an account's card can show
let selected = null; // username whose actions are shown let selected = null; // username whose actions are shown
let tab = "overview"; let tab = "overview";
@@ -631,6 +748,18 @@
}; };
const when = seconds => (seconds ? new Date(seconds * 1000).toLocaleString([], {dateStyle: "medium", timeStyle: "short"}) : "never"); 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 duration = seconds => {
const units = [[86400, "day"], [3600, "hour"], [60, "minute"]]; const units = [[86400, "day"], [3600, "hour"], [60, "minute"]];
@@ -740,6 +869,9 @@
if (account.silenced) { if (account.silenced) {
tags.push(el("span", "Silenced", "tag bad")); tags.push(el("span", "Silenced", "tag bad"));
} }
if (account.deviceBanned) {
tags.push(el("span", "Hardware banned", "tag bad"));
}
if (account.locked) { if (account.locked) {
tags.push(el("span", "Locked", "tag bad")); tags.push(el("span", "Locked", "tag bad"));
} }
@@ -769,9 +901,10 @@
return days > 0 ? `${days.toLocaleString()}d ${hours}h` : hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`; 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. // by IP address (the sign-in histories) or hardware ID (lib/devices.js).
let addressFound = null; // {query, players} or null let addressFound = null; // {query, by, players} or null
const searchByAddress = async () => { const searchByAddress = async () => {
const by = $("account-search-by").value;
const query = $("account-search").value.trim(); const query = $("account-search").value.trim();
if (query === "") { if (query === "") {
addressFound = null; addressFound = null;
@@ -779,11 +912,11 @@
renderAccounts(); renderAccounts();
return; return;
} }
const result = await api(`address-search?q=${encodeURIComponent(query)}`); const result = await api(`${by}-search?q=${encodeURIComponent(query)}`);
if (query !== $("account-search").value.trim()) { if (query !== $("account-search").value.trim() || by !== $("account-search-by").value) {
return; // typed on meanwhile 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); setStatus($("address-status"), result.ok ? (result.data.players.length ? "" : "Nobody signed in from there.") : result.data.error || "That did not work.", !result.ok);
renderAccounts(); renderAccounts();
}; };
@@ -802,25 +935,30 @@
stateCell.append(...accountState(account).flatMap(tag => [tag, " "])); stateCell.append(...accountState(account).flatMap(tag => [tag, " "]));
} }
row.addEventListener("click", () => select(entry.username)); 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; return row;
})); }));
}; };
const renderAccounts = () => { const renderAccounts = () => {
const byAddress = $("account-search-by").value === "address"; const searchBy = $("account-search-by").value;
const byAddress = searchBy !== "name";
$("address-view").hidden = !byAddress; $("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; $("account-list").hidden = byAddress;
if (byAddress) { if (byAddress) {
renderAddressResults(); renderAddressResults();
$("no-accounts").hidden = true; $("no-accounts").hidden = true;
} }
const query = byAddress ? "" : $("account-search").value.trim().toLowerCase(); // found and put in order by the server (exact name first).
const filter = $("account-filter").value; const shown = byAddress ? [] : accounts;
const shown = accounts $("account-more").hidden = byAddress || accountTotal <= shown.length;
.filter(account => account.username.toLowerCase().includes(query)) $("account-more").textContent = `Showing ${shown.length} of ${accountTotal.toLocaleString()}. Type more of the name to narrow it down.`;
.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));
$("accounts").replaceChildren(...shown.map(account => { $("accounts").replaceChildren(...shown.map(account => {
const row = el("tr", undefined, account.username === selected ? "pick selected" : "pick"); const row = el("tr", undefined, account.username === selected ? "pick selected" : "pick");
const stateCell = el("td"); const stateCell = el("td");
@@ -842,10 +980,11 @@
if (!byAddress) { if (!byAddress) {
$("no-accounts").hidden = shown.length > 0; $("no-accounts").hidden = shown.length > 0;
} }
const current = accounts.find(account => account.username === selected);
$("detail").hidden = !current; $("detail").hidden = !current;
if (current) { if (current) {
$("detail-name").textContent = `${current.username} · ${current.gems.toLocaleString()} gems · played ${played(current.playtime || 0)}${current.playtimePublic ? " (public)" : ""}`; $("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}`;
} }
}; };
@@ -944,7 +1083,6 @@
}; };
const fillCard = () => { const fillCard = () => {
const current = accounts.find(account => account.username === selected);
$("badge-boxes").replaceChildren(...badges.map(badge => { $("badge-boxes").replaceChildren(...badges.map(badge => {
const label = el("label", undefined, "check"); const label = el("label", undefined, "check");
const box = el("input"); const box = el("input");
@@ -961,16 +1099,151 @@
$("moderator-toggle").textContent = current && current.moderator ? "Remove moderator" : "Make moderator"; $("moderator-toggle").textContent = current && current.moderator ? "Remove moderator" : "Make moderator";
}; };
const select = username => { // the open account's own row, whatever the search shows.
selected = selected === username ? null : username; 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"), ""); setStatus($("detail-status"), "");
for (const id of ["new-name", "new-password", "ban-hours", "silence-hours", "message-text", "gems-amount", "gift-value", "gift-text"]) { for (const id of ["new-name", "new-password", "ban-hours", "silence-hours", "message-text", "gems-amount", "gift-value", "gift-text"]) {
$(id).value = ""; $(id).value = "";
} }
hashArg = username;
setHash();
await loadCurrent();
renderAccounts(); renderAccounts();
fillCard(); fillCard();
loadOwned(); loadOwned();
loadBanRecord(); 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", const GIFT_PLACEHOLDERS = {gems: "Amount", diamonds: "Amount", tickets: "Amount", clothing: "Item id", den: "Item id",
@@ -997,9 +1270,9 @@
case "password": return {password: $("new-password").value}; case "password": return {password: $("new-password").value};
case "lastSeen": return {when: Math.floor(new Date($("last-seen").value).getTime() / 1000)}; 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 "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 "silence": return {hours: numberFrom("silence-hours")};
case "moderator": return {on: !(accounts.find(account => account.username === selected) || {}).moderator}; case "moderator": return {on: !(current || {}).moderator};
case "message": return {text: $("message-text").value}; case "message": return {text: $("message-text").value};
case "gems": return {amount: numberFrom("gems-amount")}; case "gems": return {amount: numberFrom("gems-amount")};
case "gift": return giftBody(); case "gift": return giftBody();
@@ -1031,6 +1304,12 @@
if (action === "delete" && !window.confirm(`Delete ${selected} and everything they own? This cannot be undone.`)) { if (action === "delete" && !window.confirm(`Delete ${selected} and everything they own? This cannot be undone.`)) {
return; 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; button.disabled = true;
const result = await api("account", {username: selected, action, ...actionBody(action)}); const result = await api("account", {username: selected, action, ...actionBody(action)});
button.disabled = false; button.disabled = false;
@@ -1048,30 +1327,40 @@
fillCard(); fillCard();
loadOwned(); loadOwned();
loadBanRecord(); loadBanRecord();
loadExtras();
} }
}); });
// the server searches, once typing stops for a moment.
let addressWait = null; let addressWait = null;
$("account-search").addEventListener("input", () => { $("account-search").addEventListener("input", () => {
if ($("account-search-by").value === "address") { clearTimeout(addressWait);
clearTimeout(addressWait); addressWait = setTimeout($("account-search-by").value !== "name" ? searchByAddress : refresh, $("account-search-by").value !== "name" ? 400 : 250);
addressWait = setTimeout(searchByAddress, 400); });
// 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 { clearTimeout(addressWait);
renderAccounts(); 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", () => { $("account-search-by").addEventListener("change", () => {
const byAddress = $("account-search-by").value === "address"; const byAddress = $("account-search-by").value !== "name";
$("account-search").placeholder = byAddress ? "203.0.113.7, or the start of one" : "Search"; $("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) { if (byAddress) {
searchByAddress(); searchByAddress();
} }
else { else {
renderAccounts(); refresh();
} }
}); });
$("account-filter").addEventListener("change", renderAccounts); $("account-filter").addEventListener("change", () => refresh());
const act = async (username, action, extra, statusElement) => { const act = async (username, action, extra, statusElement) => {
const result = await api("account", {username, action, ...extra}); const result = await api("account", {username, action, ...extra});
@@ -1079,9 +1368,91 @@
return result.ok; 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"; const handled = $("report-filter").value === "1";
$("report-count").textContent = data.open ? ` (${data.open})` : ""; $("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 => { $("reports").replaceChildren(...data.reports.map(report => {
const box = el("div", undefined, "report"); const box = el("div", undefined, "report");
box.append(el("h3", `${report.target} — ${report.reason}`), box.append(el("h3", `${report.target} — ${report.reason}`),
@@ -1092,6 +1463,22 @@
if (report.context) { if (report.context) {
box.append(el("pre", 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) { if (!handled) {
const buttons = el("div", undefined, "buttons"); const buttons = el("div", undefined, "buttons");
const button = (label, run, className) => { const button = (label, run, className) => {
@@ -1112,15 +1499,18 @@
}, "primary"), }, "primary"),
button("Silence 1 hour", () => act(report.target, "silence", {hours: 1}, $("report-status"))), 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"), 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 () => { button("Open account", async () => {
selected = report.target; openAccountTab(report.target);
showTab("accounts");
loadOwned();
})); }));
box.append(buttons); box.append(buttons);
} }
else { else {
box.append(el("div", `Dealt with on ${when(report.handledAt)}`, "hint")); 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; return box;
})); }));
@@ -1220,14 +1610,29 @@
$("support-filter").addEventListener("change", () => refresh()); $("support-filter").addEventListener("change", () => refresh());
let paintingsShown = ""; 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 renderMasterpieces = data => {
const which = $("masterpiece-filter").value; const which = $("masterpiece-filter").value;
const paintings = data[which]; const marked = (list, status) => list.map(painting => ({...painting, status}));
$("masterpiece-count").textContent = data.waiting.length ? ` (${data.waiting.length})` : ""; 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; $("masterpiece-review").checked = data.review;
$("no-masterpieces").hidden = paintings.length > 0; $("no-masterpieces").hidden = paintings.length > 0;
// drawn again only when the list changed, so the pictures do not flicker. // 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) { if (shown === paintingsShown) {
return; return;
} }
@@ -1238,8 +1643,10 @@
picture.src = `/admin/api/masterpiece?id=${encodeURIComponent(painting.id)}`; picture.src = `/admin/api/masterpiece?id=${encodeURIComponent(painting.id)}`;
picture.alt = `Painting by ${painting.creator}`; picture.alt = `Painting by ${painting.creator}`;
picture.loading = "lazy"; picture.loading = "lazy";
picture.addEventListener("click", () => showPreview(picture.src));
box.append(picture, el("h3", painting.creator), 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 buttons = el("div", undefined, "buttons");
const button = (label, action, className) => { const button = (label, action, className) => {
const node = el("button", label, className); const node = el("button", label, className);
@@ -1252,7 +1659,7 @@
}); });
return node; return node;
}; };
if (which === "waiting") { if (painting.status === "waiting") {
buttons.append(button("Approve", "approve", "primary"), button("Reject", "reject", "danger")); buttons.append(button("Approve", "approve", "primary"), button("Reject", "reject", "danger"));
} }
else { else {
@@ -1261,9 +1668,7 @@
const open = el("button", "Open account"); const open = el("button", "Open account");
open.type = "button"; open.type = "button";
open.addEventListener("click", () => { open.addEventListener("click", () => {
selected = painting.creator; openAccountTab(painting.creator);
showTab("accounts");
loadOwned();
}); });
buttons.append(open); buttons.append(open);
box.append(buttons); box.append(buttons);
@@ -1272,11 +1677,62 @@
}; };
$("masterpiece-filter").addEventListener("change", () => refresh()); $("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 () => { $("masterpiece-review").addEventListener("change", async () => {
const result = await api("masterpiece", {action: "review", on: $("masterpiece-review").checked}); 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); 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 renderBans = data => {
const left = seconds => (seconds === -1 ? "Until lifted" : seconds ? `${duration(seconds)} left` : "—"); const left = seconds => (seconds === -1 ? "Until lifted" : seconds ? `${duration(seconds)} left` : "—");
$("bans").replaceChildren(...data.accounts.map(account => { $("bans").replaceChildren(...data.accounts.map(account => {
@@ -1319,6 +1775,42 @@
return row; return row;
})); }));
$("no-addresses").hidden = data.addresses.length > 0; $("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 => { $("address-form").addEventListener("submit", async event => {
@@ -1454,6 +1946,21 @@
if (!state || !state.signedIn) { if (!state || !state.signedIn) {
return; 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; let result = null;
if (tab === "overview") { if (tab === "overview") {
result = await api("overview"); result = await api("overview");
@@ -1462,10 +1969,13 @@
} }
} }
else if (tab === "accounts") { 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) { if (result.ok) {
accounts = result.data.accounts; accounts = result.data.accounts;
accountTotal = result.data.total;
badges = result.data.badges || []; badges = result.data.badges || [];
await loadCurrent();
renderAccounts(); renderAccounts();
} }
} }
@@ -1485,7 +1995,7 @@
} }
} }
else if (tab === "masterpieces") { else if (tab === "masterpieces") {
result = await api("masterpieces"); result = await api(`masterpieces?creator=${encodeURIComponent($("masterpiece-creator").value.trim())}`);
if (result.ok) { if (result.ok) {
renderMasterpieces(result.data); renderMasterpieces(result.data);
} }
@@ -1498,11 +2008,7 @@
const open = el("button", "Open account"); const open = el("button", "Open account");
open.type = "button"; open.type = "button";
open.addEventListener("click", () => { open.addEventListener("click", () => {
selected = mod.username; openAccountTab(mod.username);
showTab("accounts");
fillCard();
loadOwned();
loadBanRecord();
}); });
const cell = el("td"); const cell = el("td");
cell.append(open); cell.append(open);
@@ -1521,10 +2027,22 @@
} }
} }
else if (tab === "bans") { else if (tab === "bans") {
const hits = api("filterhits");
result = await api("bans"); result = await api("bans");
if (result.ok) { if (result.ok) {
renderBans(result.data); 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") { else if (tab === "messages") {
result = await api("messages"); result = await api("messages");
@@ -1552,8 +2070,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 => { const showTab = name => {
tab = name; tab = name;
setHash();
for (const button of document.querySelectorAll("nav button")) { for (const button of document.querySelectorAll("nav button")) {
button.setAttribute("aria-selected", String(button.dataset.tab === name)); button.setAttribute("aria-selected", String(button.dataset.tab === name));
} }
@@ -1564,13 +2122,23 @@
}; };
for (const button of document.querySelectorAll("nav button")) { 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 = () => { const showPanel = () => {
$("gate").hidden = true; $("gate").hidden = true;
$("panel").hidden = false; $("panel").hidden = false;
showTab(tab); if (!applyHash()) {
showTab(tab);
}
}; };
const start = async () => { const start = async () => {
+420 -37
View File
@@ -160,6 +160,8 @@
tbody tr:last-child td { border-bottom: 0; } tbody tr:last-child td { border-bottom: 0; }
tbody tr.selected td { background: var(--raised); } tbody tr.selected td { background: var(--raised); }
tbody tr.pick { cursor: pointer; } 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; } .empty { color: var(--muted); padding: 8px 0; }
.toolbar { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; } .toolbar { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; }
.toolbar input[type="search"] { flex: 1; min-width: 180px; } .toolbar input[type="search"] { flex: 1; min-width: 180px; }
@@ -200,6 +202,10 @@
.painting img { display: block; width: 100%; height: auto; border-radius: 10px; background: #fff; } .painting img { display: block; width: 100%; height: auto; border-radius: 10px; background: #fff; }
.painting h3 { margin: 8px 0 2px; } .painting h3 { margin: 8px 0 2px; }
.painting .buttons { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; } .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; } textarea { width: 100%; resize: vertical; }
.send-row { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; align-items: center; } .send-row { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; align-items: center; }
#owned { margin-top: 16px; } #owned { margin-top: 16px; }
@@ -215,7 +221,8 @@
.logo { display: block; height: 72px; margin: 0 0 12px; } .logo { display: block; height: 72px; margin: 0 0 12px; }
.mark { height: 34px; flex: none; } .mark { height: 34px; flex: none; }
#chat-lines { margin: 0; padding: 0; list-style: 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-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-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 { flex: none; max-width: 190px; padding: 0; border: 0; font-weight: 700; text-align: left; overflow: hidden; text-overflow: ellipsis; }
@@ -226,7 +233,7 @@
#chat-context { margin: 0; padding: 0; list-style: none; } #chat-context { margin: 0; padding: 0; list-style: none; }
#chat-context li.this { background: var(--raised); border-radius: 10px; } #chat-context li.this { background: var(--raised); border-radius: 10px; }
#player-facts { margin-bottom: 14px; } #player-facts { margin-bottom: 14px; }
#player-history { 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; } .actions { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 12px; }
</style> </style>
</head> </head>
@@ -270,6 +277,7 @@
<select id="player-search-by" aria-label="Search by"> <select id="player-search-by" aria-label="Search by">
<option value="name">By name</option> <option value="name">By name</option>
<option value="address">By IP address</option> <option value="address">By IP address</option>
<option value="device">By hardware ID</option>
</select> </select>
<input id="player-search" type="search" placeholder="Search" aria-label="Search players"> <input id="player-search" type="search" placeholder="Search" aria-label="Search players">
<span class="hint" id="online-count"></span> <span class="hint" id="online-count"></span>
@@ -279,7 +287,8 @@
<tbody id="players"></tbody> <tbody id="players"></tbody>
</table></div> </table></div>
<div class="empty" id="no-players" hidden>No players match.</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>
<section id="detail" hidden> <section id="detail" hidden>
<h2 id="detail-name"></h2> <h2 id="detail-name"></h2>
@@ -294,14 +303,17 @@
<button type="button" data-action="ban" class="danger">Ban</button> <button type="button" data-action="ban" class="danger">Ban</button>
<button type="button" data-action="banReason">Save reason</button> <button type="button" data-action="banReason">Save reason</button>
<button type="button" data-action="unban">Lift</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>
<div class="action"> <div class="action">
<h3>Chat</h3> <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"> <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="silence">Silence</button>
<button type="button" data-action="unsilence">Lift</button></div> <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>
<div class="action"> <div class="action">
<h3>Message</h3> <h3>Message</h3>
@@ -317,8 +329,36 @@
<button type="button" data-action="clearBio">Clear bio</button></div> <button type="button" data-action="clearBio">Clear bio</button></div>
</div> </div>
</div> </div>
<h3 style="margin:16px 0 4px" id="history-title" hidden>Ban history</h3> <h3 style="margin:16px 0 4px">Other accounts</h3>
<ul id="player-history"></ul> <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> </section>
</div> </div>
@@ -332,6 +372,15 @@
<input id="chat-player" maxlength="100" placeholder="Player" autocomplete="off" spellcheck="false" aria-label="Player"> <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-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"> <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> <button class="primary" type="submit">Search</button>
</form> </form>
<p class="status" id="chat-status" role="status"></p> <p class="status" id="chat-status" role="status"></p>
@@ -386,11 +435,14 @@
<select id="masterpiece-filter" aria-label="Which masterpieces"> <select id="masterpiece-filter" aria-label="Which masterpieces">
<option value="waiting">Waiting</option> <option value="waiting">Waiting</option>
<option value="approved">On show</option> <option value="approved">On show</option>
<option value="all">All</option>
</select> </select>
<input id="masterpiece-creator" type="search" maxlength="100" placeholder="Maker's username" autocomplete="off" spellcheck="false" aria-label="Maker's username">
</div> </div>
<p class="status" id="masterpiece-status" role="status"></p> <p class="status" id="masterpiece-status" role="status"></p>
<div class="paintings" id="masterpieces"></div> <div class="paintings" id="masterpieces"></div>
<div class="empty" id="no-masterpieces" hidden>Nothing here.</div> <div class="empty" id="no-masterpieces" hidden>Nothing here.</div>
<div class="preview" id="preview" hidden><img id="preview-img" alt=""></div>
</section> </section>
</div> </div>
@@ -412,6 +464,30 @@
</table></div> </table></div>
<div class="empty" id="no-addresses" hidden>No address is banned.</div> <div class="empty" id="no-addresses" hidden>No address is banned.</div>
</section> </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>
</div> </div>
@@ -518,6 +594,9 @@
if (player.silenced !== 0) { if (player.silenced !== 0) {
tags.push(el("span", "Silenced", "tag bad")); tags.push(el("span", "Silenced", "tag bad"));
} }
if (player.deviceBanned) {
tags.push(el("span", "Hardware banned", "tag bad"));
}
if (player.nameRejected) { if (player.nameRejected) {
tags.push(el("span", "Name rejected", "tag bad")); tags.push(el("span", "Name rejected", "tag bad"));
} }
@@ -541,8 +620,6 @@
$("no-players").hidden = players.length > 0; $("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 () => { const loadDetail = async () => {
$("detail").hidden = !selected; $("detail").hidden = !selected;
if (!selected) { if (!selected) {
@@ -569,6 +646,9 @@
["Ban", player.banned === 0 ? "—" : `${left(player.banned)} · ${player.banReason}`], ["Ban", player.banned === 0 ? "—" : `${left(player.banned)} · ${player.banReason}`],
["Chat", player.silenced === 0 ? "—" : `Silenced: ${left(player.silenced).toLowerCase()}`], ["Chat", player.silenced === 0 ? "—" : `Silenced: ${left(player.silenced).toLowerCase()}`],
["Reports waiting", String(player.openReports)], ["Reports waiting", String(player.openReports)],
["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}` : "—"], ["Appeal", player.appeal ? `${player.appeal.status} · ${player.appeal.text}` : "—"],
["Discord", player.discord || "—"], ["Discord", player.discord || "—"],
["Bio", player.bio || "—"], ["Bio", player.bio || "—"],
@@ -584,34 +664,115 @@
if (document.activeElement !== $("ban-reason")) { if (document.activeElement !== $("ban-reason")) {
$("ban-reason").value = player.banned === 0 ? "" : player.banReason; $("ban-reason").value = player.banned === 0 ? "" : player.banReason;
} }
$("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(" · ")))); .filter(Boolean).join(" · "))));
$("no-timeline").hidden = events.length > 0;
}; };
const select = username => { const select = username => {
selected = username; selected = username;
hashArg = username || "";
setHash();
setStatus($("detail-status"), ""); setStatus($("detail-status"), "");
for (const id of ["ban-hours", "ban-reason", "silence-hours", "message-text"]) { for (const id of ["ban-hours", "ban-reason", "silence-hours", "message-text"]) {
$(id).value = ""; $(id).value = "";
} }
renderPlayers(); renderPlayers();
loadDetail(); loadDetail();
loadExtras();
}; };
// from another page: that player's box, whether or not the search shows them. // from another page: that player's box, whether or not the search shows them.
const openPlayer = username => { const openPlayer = username => {
$("player-search").value = username; $("player-search").value = username;
$("player-search-by").value = "name";
selected = username; selected = username;
hashArg = username;
showTab("players"); 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 numberFrom = id => ($(id).value.trim() === "" ? NaN : Number($(id).value));
const actionBody = action => { const actionBody = action => {
switch (action) { switch (action) {
case "ban": return {hours: numberFrom("ban-hours"), reason: $("ban-reason").value}; 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 "silence": return {hours: numberFrom("silence-hours")};
case "message": return {text: $("message-text").value}; case "message": return {text: $("message-text").value};
default: return {}; default: return {};
@@ -619,6 +780,8 @@
}; };
const CONFIRM = { const CONFIRM = {
banAddress: name => `Ban the address ${name} last signed in from, for good?`, 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.`, rejectName: name => `Reject the username ${name}? They are signed out and must pick another.`,
}; };
@@ -640,6 +803,7 @@
$("silence-hours").value = ""; $("silence-hours").value = "";
$("message-text").value = ""; $("message-text").value = "";
refresh(); refresh();
loadExtras();
} }
}); });
@@ -647,21 +811,37 @@
let searchWait = null; let searchWait = null;
$("player-search").addEventListener("input", () => { $("player-search").addEventListener("input", () => {
clearTimeout(searchWait); 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-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(); refresh();
}); });
const chatUrl = before => `chat?username=${encodeURIComponent(chatQuery.username)}&room=${encodeURIComponent(chatQuery.room)}` 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 lineNode = (line, inContext = false) => {
const item = el("li", undefined, inContext && line.marked ? "this" : ""); const item = el("li", undefined, inContext && line.marked ? "this" : "");
const who = button(line.username, () => openPlayer(line.username), "chat-who"); const who = button(line.username, () => openPlayer(line.username), "chat-who");
const text = el("span", undefined, "chat-text"); 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); item.append(el("span", when(line.at), "chat-time"), who, text);
if (!inContext) { if (!inContext) {
item.append(button("Around", () => showContext(line.id), "chat-more")); item.append(button("Around", () => showContext(line.id), "chat-more"));
@@ -677,7 +857,7 @@
const loadChat = async older => { const loadChat = async older => {
if (!chatQuery) { 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 before = older && chatLines.length ? chatLines[chatLines.length - 1].id : 0;
const result = await api(chatUrl(before)); const result = await api(chatUrl(before));
@@ -697,7 +877,7 @@
return; return;
} }
const {line, lines} = result.data; 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))); $("chat-context").replaceChildren(...lines.map(entry => lineNode({...entry, marked: entry.id === line.id}, true)));
$("context-box").hidden = false; $("context-box").hidden = false;
$("context-box").scrollIntoView({block: "nearest"}); $("context-box").scrollIntoView({block: "nearest"});
@@ -708,25 +888,41 @@
$("chat-form").addEventListener("submit", event => { $("chat-form").addEventListener("submit", event => {
event.preventDefault(); 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; $("context-box").hidden = true;
loadChat(false); loadChat(false);
}); });
$("chat-older").addEventListener("click", () => loadChat(true)); $("chat-older").addEventListener("click", () => loadChat(true));
const openChat = username => { const openChat = (username, kind = "") => {
$("chat-player").value = username; $("chat-player").value = username;
$("chat-room").value = ""; $("chat-room").value = "";
$("chat-text").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; $("context-box").hidden = true;
showTab("chat"); showTab("chat");
}; };
$("open-chat").addEventListener("click", () => selected && openChat(selected)); $("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"; const handled = $("report-filter").value === "1";
$("report-count").textContent = data.open ? ` (${data.open})` : ""; $("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 => { $("reports").replaceChildren(...data.reports.map(report => {
const box = el("div", undefined, "report"); const box = el("div", undefined, "report");
box.append(el("h3", `${report.target} — ${report.reason}`), box.append(el("h3", `${report.target} — ${report.reason}`),
@@ -737,8 +933,24 @@
if (report.context) { if (report.context) {
box.append(el("pre", 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"); 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) { if (handled) {
box.append(el("div", `Dealt with on ${when(report.handledAt)}`, "hint")); box.append(el("div", `Dealt with on ${when(report.handledAt)}`, "hint"));
} }
@@ -756,6 +968,7 @@
}; };
$("report-filter").addEventListener("change", () => refresh()); $("report-filter").addEventListener("change", () => refresh());
const renderRequests = data => { const renderRequests = data => {
const handled = $("request-filter").value === "1"; const handled = $("request-filter").value === "1";
const answer = async body => { const answer = async body => {
@@ -817,13 +1030,28 @@
$("request-filter").addEventListener("change", () => refresh()); $("request-filter").addEventListener("change", () => refresh());
let paintingsShown = ""; 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 renderMasterpieces = data => {
const which = $("masterpiece-filter").value; const which = $("masterpiece-filter").value;
const paintings = data[which]; const marked = (list, status) => list.map(painting => ({...painting, status}));
$("masterpiece-count").textContent = data.waiting.length ? ` (${data.waiting.length})` : ""; 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; $("no-masterpieces").hidden = paintings.length > 0;
// drawn again only when the list changed, so the pictures do not flicker. // 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) { if (shown === paintingsShown) {
return; return;
} }
@@ -834,14 +1062,16 @@
picture.src = `/mod/api/masterpiece?id=${encodeURIComponent(painting.id)}`; picture.src = `/mod/api/masterpiece?id=${encodeURIComponent(painting.id)}`;
picture.alt = `Painting by ${painting.creator}`; picture.alt = `Painting by ${painting.creator}`;
picture.loading = "lazy"; 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 buttons = el("div", undefined, "buttons");
const does = (label, action, className) => button(label, async () => { const does = (label, action, className) => button(label, async () => {
const result = await api("masterpiece", {id: painting.id, action}); const result = await api("masterpiece", {id: painting.id, action});
setStatus($("masterpiece-status"), said(result), !result.ok); setStatus($("masterpiece-status"), said(result), !result.ok);
refresh(); refresh();
}, className); }, className);
if (which === "waiting") { if (painting.status === "waiting") {
buttons.append(does("Approve", "approve", "primary"), does("Reject", "reject", "danger")); buttons.append(does("Approve", "approve", "primary"), does("Reject", "reject", "danger"));
} }
else { else {
@@ -853,6 +1083,18 @@
})); }));
}; };
$("masterpiece-filter").addEventListener("change", () => refresh()); $("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 => { const renderBans = data => {
$("bans").replaceChildren(...data.accounts.map(account => { $("bans").replaceChildren(...data.accounts.map(account => {
@@ -887,6 +1129,81 @@
return row; return row;
})); }));
$("no-addresses").hidden = data.addresses.length > 0; $("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;
}; };
const refresh = async () => { const refresh = async () => {
@@ -901,20 +1218,32 @@
$("request-count").textContent = counts.data.requests ? ` (${counts.data.requests})` : ""; $("request-count").textContent = counts.data.requests ? ` (${counts.data.requests})` : "";
$("masterpiece-count").textContent = counts.data.paintings ? ` (${counts.data.paintings})` : ""; $("masterpiece-count").textContent = counts.data.paintings ? ` (${counts.data.paintings})` : "";
$("online-count").textContent = `${counts.data.online} playing`; $("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") { 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(); const query = $("player-search").value.trim();
$("players-when").textContent = byAddress ? "Last from address" : "Last seen"; $("players-when").textContent = searchBy === "address" ? "Last from address" : searchBy === "device" ? "Last used" : "Last seen";
$("address-hint").hidden = !byAddress; $("address-hint").hidden = searchBy !== "address";
if (byAddress && query === "") { if (byAddress && query === "") {
players = []; players = [];
renderPlayers(); renderPlayers();
} }
else { 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 : []; players = result.ok ? result.data.players : [];
renderPlayers(); 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) { if (!result.ok && byAddress) {
$("no-players").textContent = said(result); $("no-players").textContent = said(result);
} }
@@ -942,7 +1271,7 @@
} }
} }
else if (shown === "masterpieces") { else if (shown === "masterpieces") {
const result = await api("masterpieces"); const result = await api(`masterpieces?creator=${encodeURIComponent($("masterpiece-creator").value.trim())}`);
if (result.ok) { if (result.ok) {
renderMasterpieces(result.data); renderMasterpieces(result.data);
} }
@@ -951,10 +1280,13 @@
await window.statsView.load(api); await window.statsView.load(api);
} }
else if (shown === "bans") { else if (shown === "bans") {
const result = await api("bans"); const [result, hits] = await Promise.all([api("bans"), api("filterhits")]);
if (result.ok) { if (result.ok) {
renderBans(result.data); renderBans(result.data);
} }
if (hits.ok) {
renderFilterHits(hits.data.players);
}
} }
if (signedIn) { if (signedIn) {
clearTimeout(timer); clearTimeout(timer);
@@ -962,8 +1294,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 => { const showTab = name => {
tab = name; tab = name;
setHash();
for (const one of document.querySelectorAll("nav button")) { for (const one of document.querySelectorAll("nav button")) {
one.setAttribute("aria-selected", String(one.dataset.tab === name)); one.setAttribute("aria-selected", String(one.dataset.tab === name));
} }
@@ -973,15 +1346,25 @@
refresh(); refresh();
}; };
for (const one of document.querySelectorAll("nav button")) { 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();
}
});
const showPanel = username => { const showPanel = username => {
signedIn = true; signedIn = true;
$("who").textContent = username; $("who").textContent = username;
$("gate").hidden = true; $("gate").hidden = true;
$("panel").hidden = false; $("panel").hidden = false;
showTab(tab); if (!applyHash()) {
showTab(tab);
}
}; };
$("gate-form").addEventListener("submit", async event => { $("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>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>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>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>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. The client cannot sign in without them</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>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>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> <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> <h2>3. Who can see it</h2>
<ul> <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>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>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>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> <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> <thead><tr><th>Data</th><th>Kept</th></tr></thead>
<tbody> <tbody>
<tr><td>Account and game data</td><td>Until you delete your account</td></tr> <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>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>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> <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> <tr><td>Backups</td><td>14 days</td></tr>
</tbody> </tbody>
</table></div> </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>
<section> <section>
@@ -243,7 +246,7 @@
<section> <section>
<h2>8. Cookies and your device</h2> <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>
<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 fs = require("fs");
const accounts = require("./lib/accounts.js"); const accounts = require("./lib/accounts.js");
const bans = require("./lib/bans.js"); const bans = require("./lib/bans.js");
const devices = require("./lib/devices.js");
const chatlog = require("./lib/chatlog.js"); const chatlog = require("./lib/chatlog.js");
const modlog = require("./lib/modlog.js"); const modlog = require("./lib/modlog.js");
const retention = require("./lib/retention.js"); const retention = require("./lib/retention.js");
@@ -40,6 +41,7 @@ const main = async () => {
reports.load(); reports.load();
support.load(); support.load();
bans.load(); bans.load();
devices.load();
chatlog.load(); chatlog.load();
modlog.load(); modlog.load();
masterpieces.load(); masterpieces.load();
+10 -2
View File
@@ -6,6 +6,7 @@
const assert = require("assert"); const assert = require("assert");
const {spawn} = require("child_process"); const {spawn} = require("child_process");
const crypto = require("crypto");
const fs = require("fs"); const fs = require("fs");
const net = require("net"); const net = require("net");
const os = require("os"); const os = require("os");
@@ -132,10 +133,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, { const postJson = (url, body) => fetch(url, {
method: "POST", method: "POST",
headers: {"Content-Type": "application/json", "Origin": "null"}, 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` // starts a server on the given ports with an empty database, runs `run`
@@ -170,4 +178,4 @@ const withServer = async (name, httpPort, gamePort, run) => {
} }
}; };
module.exports = {GameClient, postJson, withServer}; module.exports = {deviceFor, GameClient, postJson, withServer};