diff --git a/config.js b/config.js index d344274..68d666b 100644 --- a/config.js +++ b/config.js @@ -98,6 +98,10 @@ module.exports = { // cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only. upstreamContent: env.AJ_UPSTREAM || "https://ajcontent.akamaized.net/", offline: env.AJ_OFFLINE === "1", + // the client's device ids (lib/devices.js): 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", // 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. diff --git a/lib/accounts.js b/lib/accounts.js index 5f045da..210bfcc 100644 --- a/lib/accounts.js +++ b/lib/accounts.js @@ -270,6 +270,8 @@ const normalize = account => { account.totp = account.totp || null; account.totpSetup = account.totpSetup || null; account.devices = Array.isArray(account.devices) ? account.devices : []; + // the computers it signed in from, keyed (lib/devices.js): [{kind, id, first, last}]. + account.hwids = Array.isArray(account.hwids) ? account.hwids : []; account.nextInv = account.nextInv || 2; account.numLogins = account.numLogins || 0; account.uuid = account.uuid || crypto.randomUUID(); diff --git a/lib/admin.js b/lib/admin.js index e61a224..bada434 100644 --- a/lib/admin.js +++ b/lib/admin.js @@ -4,6 +4,7 @@ const accounts = require("./accounts.js"); const bans = require("./bans.js"); const captcha = require("./captcha.js"); const defpacks = require("./defpacks.js"); +const devices = require("./devices.js"); const config = require("../config.js"); const dens = require("./dens.js"); const limits = require("./limits.js"); @@ -204,13 +205,21 @@ const handle = async (route, params, body, from) => { } const ban = world.moderation.banOf(account); const addressBan = ban ? null : bans.addressBan(from.address); + const deviceBan = ban || addressBan ? null : devices.banOfAccount(account); return {status: 200, body: ban ? {banned: "account", banned_seconds: ban.seconds, ban_reason: ban.reason} - : addressBan ? {banned: "address", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason} : {banned: null}}; + : addressBan ? {banned: "address", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason} + : deviceBan ? {banned: "device", banned_seconds: world.moderation.PERMANENT, ban_reason: deviceBan.reason} : {banned: null}}; } case "POST /api/register": { if (bans.addressBan(from.address)) { return {status: 403, body: {error: "address_banned"}}; } + // the client says which computer it is on (lib/devices.js); the sign-up + // page cannot, and an account made there still signs in through the client. + const device = devices.read((body || {}).device); + if (device && devices.banOf(device)) { + return {status: 403, body: {error: "device_banned"}}; + } const {username, password, avatarType} = body || {}; // the terms and the privacy policy, and old enough to agree to them: // said by the one signing up, on the page or in the client. diff --git a/lib/chatlog.js b/lib/chatlog.js index 490fc97..67d781a 100644 --- a/lib/chatlog.js +++ b/lib/chatlog.js @@ -3,7 +3,8 @@ const accounts = require("./accounts.js"); const config = require("../config.js"); -// what players typed: chat in a room, and whispers. kept for the moderator +// what players typed: chat in a room, whispers, Jam-a-Grams and posts on +// each other's Jammer Walls. kept for the moderator // panel (lib/modpanel.js), which is where a moderator reads what was said // before deciding anything; nothing else reads it. lines older than // config.chatLogDays are deleted, and an account's lines go when the @@ -26,6 +27,11 @@ const SCHEMA = ` const CHAT = "chat"; const WHISPER = "whisper"; +const JAMAGRAM = "jamagram"; +const WALL = "wall"; +const KINDS = [CHAT, WHISPER, JAMAGRAM, WALL]; +// what the server's filter kept from being sent is kept with this in front. +const NOT_SENT = "(not sent) "; const DAY_SECONDS = 86400; const MAX_TEXT = 600; const PAGE = 100; @@ -40,28 +46,69 @@ const prune = () => { const load = () => { db().exec(SCHEMA); + // lines the filter stopped are marked, and found by a small index of their own. + if (!db().prepare("PRAGMA table_info(chat_log)").all().some(column => column.name === "stopped")) { + db().exec("ALTER TABLE chat_log ADD COLUMN stopped INTEGER NOT NULL DEFAULT 0"); + db().prepare("UPDATE chat_log SET stopped = 1 WHERE substr(text, 1, ?) = ?").run(NOT_SENT.length, NOT_SENT); + } + db().exec("CREATE INDEX IF NOT EXISTS chat_log_stopped ON chat_log (at) WHERE stopped = 1"); prune(); setInterval(prune, DAY_SECONDS * 1000 / 4).unref(); }; +const stoppedFlag = text => (String(text).startsWith(NOT_SENT) ? 1 : 0); + // A line said in `room` (its name as the world knows it), or with `to` a // whisper to that player. const record = (account, room, text, to = "") => { if (config.chatLogDays <= 0) { return; } - db().prepare("INSERT INTO chat_log (at, account_id, username, room, kind, to_name, text) VALUES (?, ?, ?, ?, ?, ?, ?)") - .run(now(), account.id, account.username, String(room || ""), to ? WHISPER : CHAT, to, String(text).slice(0, MAX_TEXT)); + db().prepare("INSERT INTO chat_log (at, account_id, username, room, kind, to_name, text, stopped) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") + .run(now(), account.id, account.username, String(room || ""), to ? WHISPER : CHAT, to, String(text).slice(0, MAX_TEXT), stoppedFlag(text)); }; -const row = line => ({id: line.id, at: line.at, username: line.username, room: line.room, whisperTo: line.kind === WHISPER ? line.to_name : "", text: line.text}); +// A Jam-a-Gram's words (`kind` JAMAGRAM), or a post on a Jammer Wall +// (WALL): `to` is who it was sent to, or whose wall it is. +const recordTo = (account, kind, to, text) => { + if (config.chatLogDays <= 0 || !KINDS.includes(kind)) { + return; + } + db().prepare("INSERT INTO chat_log (at, account_id, username, room, kind, to_name, text, stopped) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") + .run(now(), account.id, account.username, "", kind, String(to || ""), String(text).slice(0, MAX_TEXT), stoppedFlag(text)); +}; + +const row = line => ({id: line.id, at: line.at, username: line.username, room: line.room, kind: line.kind, to: line.to_name, + whisperTo: line.kind === WHISPER ? line.to_name : "", text: line.text}); // lines newest first, a page at a time: by who said them (or was whispered -// to), by room, by words in them, and `before` an id for the next page. -const search = ({username = "", room = "", text = "", before = 0}) => { +// to, or sent to), by room, by words in them, by kind (one of KINDS, or +// "notsent" for what the filter stopped), from `until` (seconds) back, and +// `before` an id for the next page. `direction` narrows the username to +// what they sent ("sent") or what was sent to them ("received"). +const search = ({username = "", room = "", text = "", kind = "", direction = "", until = 0, before = 0}) => { const where = []; const values = []; - if (username) { + if (KINDS.includes(kind)) { + where.push("kind = ?"); + values.push(kind); + } + else if (kind === "notsent") { + where.push("stopped = 1"); + } + if (until > 0) { + where.push("at <= ?"); + values.push(Math.floor(until)); + } + if (username && direction === "sent") { + where.push("username = ? COLLATE NOCASE"); + values.push(username); + } + else if (username && direction === "received") { + where.push("to_name = ? COLLATE NOCASE"); + values.push(username); + } + else if (username) { where.push("(username = ? COLLATE NOCASE OR to_name = ? COLLATE NOCASE)"); values.push(username, username); } @@ -87,9 +134,9 @@ const around = id => { if (!line) { return null; } - const [same, values] = line.kind === WHISPER - ? ["kind = ? AND ((username = ? AND to_name = ?) OR (username = ? AND to_name = ?))", [WHISPER, line.username, line.to_name, line.to_name, line.username]] - : ["kind = ? AND room = ?", [CHAT, line.room]]; + const [same, values] = line.kind === CHAT + ? ["kind = ? AND room = ?", [CHAT, line.room]] + : ["kind = ? AND ((username = ? AND to_name = ?) OR (username = ? AND to_name = ?))", [line.kind, line.username, line.to_name, line.to_name, line.username]]; const earlier = db().prepare(`SELECT * FROM chat_log WHERE ${same} AND id < ? ORDER BY id DESC LIMIT ?`).all(...values, line.id, AROUND).reverse(); const later = db().prepare(`SELECT * FROM chat_log WHERE ${same} AND id > ? ORDER BY id LIMIT ?`).all(...values, line.id, AROUND); return {line: row(line), lines: [...earlier, line, ...later].map(row)}; @@ -99,9 +146,19 @@ const around = id => { // of their data a player may ask for (lib/manage.js). const saidBy = account => db().prepare("SELECT * FROM chat_log WHERE account_id = ? ORDER BY id").all(account.id).map(row); +// how many of an account's lines the server's filter stopped, in the last +// `days` days. +const notSentCount = (account, days) => db().prepare("SELECT COUNT(*) AS n FROM chat_log WHERE account_id = ? AND at > ? AND stopped = 1") + .get(account.id, now() - days * DAY_SECONDS).n; + +// those the filter stopped most often in the last `days` days: [{username, count, last}]. +const mostStopped = (days, limit) => db().prepare(`SELECT username, COUNT(*) AS count, MAX(at) AS last FROM chat_log + WHERE stopped = 1 AND at > ? GROUP BY account_id ORDER BY count DESC LIMIT ?`) + .all(now() - days * DAY_SECONDS, limit).map(entry => ({username: entry.username, count: entry.count, last: entry.last})); + // an account being deleted: what it said goes with it. const forget = account => { db().prepare("DELETE FROM chat_log WHERE account_id = ?").run(account.id); }; -module.exports = {load, record, search, around, saidBy, forget, PAGE}; +module.exports = {load, record, recordTo, search, around, saidBy, notSentCount, mostStopped, forget, PAGE, JAMAGRAM, WALL, NOT_SENT}; diff --git a/lib/devices.js b/lib/devices.js new file mode 100644 index 0000000..2c51a42 --- /dev/null +++ b/lib/devices.js @@ -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::", 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}; diff --git a/lib/ecards.js b/lib/ecards.js index d24bb20..80b3212 100644 --- a/lib/ecards.js +++ b/lib/ecards.js @@ -5,6 +5,7 @@ const path = require("path"); const accounts = require("./accounts.js"); const achievements = require("./achievements.js"); const chatFilter = require("./chatfilter.js"); +const chatlog = require("./chatlog.js"); const defpacks = require("./defpacks.js"); const dens = require("./dens.js"); const limits = require("./limits.js"); @@ -261,6 +262,7 @@ module.exports = ({findOnline, blocks}) => { if (rule) { chatFilter.warn(session); console.log(`[filter] ${account.username} in a Jam-a-Gram to ${to.username}: "${clean(message || "")}" (${rule})`); + chatlog.recordTo(account, chatlog.JAMAGRAM, to.username, chatlog.NOT_SENT + clean(message || "")); reply(FAILED); return; } @@ -279,6 +281,8 @@ module.exports = ({findOnline, blocks}) => { return; } deliver(to, {from: account.username, fromId: account.id, card: Number(card), stamp: Number(stamp), msg: clean(message || ""), gift}); + // for the panels (lib/chatlog.js), as typed chat is. + chatlog.recordTo(account, chatlog.JAMAGRAM, to.username, clean(message || "") + (gift ? " [with a gift]" : "")); achievements.add(account, achievements.VARS.jamAGramsSent); if (gift) { achievements.add(account, achievements.VARS.giftsSent); diff --git a/lib/erase.js b/lib/erase.js index 11866d5..3782bdd 100644 --- a/lib/erase.js +++ b/lib/erase.js @@ -3,13 +3,15 @@ const accounts = require("./accounts.js"); const bans = require("./bans.js"); const chatlog = require("./chatlog.js"); +const devices = require("./devices.js"); const masterpieces = require("./masterpieces.js"); const support = require("./support.js"); const world = require("./world.js"); // an account deleted for good, by its owner (lib/manage.js) or by the admin // (lib/panel.js), and what was kept about it elsewhere with it: its chat -// lines, its appeal, its feedback and username requests, and the paintings +// lines, its appeal, its feedback and username requests, the computers it +// was used from (lib/devices.js), and the paintings // it made (from whoever holds one by now). what stays is said in the // privacy policy (public/privacy.html): the record of bans and of what // moderators did, under the name it had, until lib/retention.js ends it. @@ -20,6 +22,7 @@ module.exports = account => { } bans.forget(account); chatlog.forget(account); + devices.forget(account); support.forget(account); accounts.remove(account); }; diff --git a/lib/http.js b/lib/http.js index 04d9fea..a1ea651 100644 --- a/lib/http.js +++ b/lib/http.js @@ -11,6 +11,7 @@ const bans = require("./bans.js"); const captcha = require("./captcha.js"); const cdn = require("./cdn.js"); const config = require("../config.js"); +const devices = require("./devices.js"); const defpacks = require("./defpacks.js"); const limits = require("./limits.js"); const manage = require("./manage.js"); @@ -383,6 +384,14 @@ const authenticate = async (req, res, from) => { renameAndSignIn(res, body, from); return; } + // the computer it is on (lib/devices.js): a client that does not say is + // out of date (before 1.3.0) or not ours. 1.2 shows "The server refused + // the login (426)", and still offers its update. + const device = devices.read(body.device); + if (!device && config.requireDevice) { + send(res, 426, {error_code: 101, error: "client_outdated"}); + return; + } const byRefresh = body.refresh_token !== undefined; const accountKey = String(body.username).trim().toLowerCase(); if (!from.local && failuresByAddress.blocked(from.key)) { @@ -430,6 +439,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}); 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 // still nobody gets in. the launcher shows this as a failed sign-in. 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)}); return; } + if (device) { + devices.seen(account, device, other => world.moderation.banRemaining(other) !== 0); + } if (!byRefresh) { accounts.recordLogin(account, "launcher", from.address); - accounts.save(account); } + accounts.save(account); // the custom client's advanced settings; the official launcher sends none. accounts.setLoginChoices(account, body.login_choices); const token = byRefresh ? body.refresh_token : accounts.issueToken(account); diff --git a/lib/masterpieces.js b/lib/masterpieces.js index 7994556..3c502ca 100644 --- a/lib/masterpieces.js +++ b/lib/masterpieces.js @@ -319,6 +319,16 @@ const list = status => [...known.values()].filter(painting => painting.status == return {id: painting.id, creator: maker ? maker.username : "(deleted account)", createdAt: painting.createdAt, frame: painting.frame, likes: painting.likes.length}; }); +// both lists for the panels, narrowed to makers whose names have +// `creator` in them (the one of exactly that name first): {waiting, +// approved}, newest first. +const listsFor = creator => { + const wanted = String(creator || "").trim().toLowerCase().slice(0, 100); + const narrowed = paintings => (wanted ? paintings.filter(painting => painting.creator.toLowerCase().includes(wanted)) + .sort((one, other) => Number(other.creator.toLowerCase() === wanted) - Number(one.creator.toLowerCase() === wanted)) : paintings); + return {waiting: narrowed(list(PENDING)), approved: narrowed(list(APPROVED))}; +}; + const madeBy = account => [...known.values()].filter(painting => painting.creator === account.id).map(painting => painting.id); // generic lists: (mediaId, name string id) pairs, or null when `listId` is @@ -327,7 +337,7 @@ const frameList = listId => ([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null); module.exports = { - load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, frameList, + load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, frameList, needsReview, setNeedsReview, madeBy, PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES, }; diff --git a/lib/modlog.js b/lib/modlog.js index 66f4d32..8ab659b 100644 --- a/lib/modlog.js +++ b/lib/modlog.js @@ -28,4 +28,8 @@ const record = (by, action, target = "", detail = "") => { const recent = () => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log ORDER BY id DESC LIMIT ?").all(SHOWN); -module.exports = {load, record, recent}; +// what staff did to one player, newest first, for their timeline. +const about = username => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log WHERE target = ? COLLATE NOCASE ORDER BY id DESC LIMIT 100") + .all(String(username)); + +module.exports = {load, record, recent, about}; diff --git a/lib/modpanel.js b/lib/modpanel.js index 2ec0741..c924d9e 100644 --- a/lib/modpanel.js +++ b/lib/modpanel.js @@ -8,6 +8,7 @@ const bans = require("./bans.js"); const captcha = require("./captcha.js"); const chatlog = require("./chatlog.js"); const config = require("../config.js"); +const devices = require("./devices.js"); const limits = require("./limits.js"); const manage = require("./manage.js"); const masterpieces = require("./masterpieces.js"); @@ -44,7 +45,6 @@ const SESSION_HOURS = 12; const TEN_MINUTES_MS = 600000; const MAX_BAN_HOURS = 24 * 365 * 10; const MAX_MESSAGE_LENGTH = 200; -const MAX_FOUND = 50; const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS); const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator @@ -99,19 +99,17 @@ const playerRow = (account, playing) => { playtime: account.playtime, bio: account.bio, discord: account.discord, + deviceBanned: devices.bannedId(account) !== 0, }; }; const playing = () => new Map(world.players().map(player => [player.username, player.room || "(between rooms)"])); +// by name (lib/staff.js says in what order). const findPlayers = query => { - const wanted = String(query || "").trim().toLowerCase().slice(0, 100); const online = playing(); - return accounts.all() - .filter(account => account.username.toLowerCase().includes(wanted)) - .sort((a, b) => Number(online.has(b.username)) - Number(online.has(a.username)) || a.username.localeCompare(b.username)) - .slice(0, MAX_FOUND) - .map(account => playerRow(account, online)); + const {found, total} = staff.findAccounts(query); + return {players: found.map(account => playerRow(account, online)), total}; }; // one player: the row, what was done about their bans (without addresses), @@ -121,6 +119,9 @@ const playerDetail = account => ({ history: bans.historyOf(account).map(({at, action, seconds, reason, by}) => ({at, action, seconds, reason, by})), appeal: bans.appealOf(account), 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. @@ -213,6 +214,11 @@ const act = (mod, target, body) => { } 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: return {error: "Unknown action."}; } @@ -339,9 +345,36 @@ const handle = async (req, res, url, from, web) => { paintings: masterpieces.list(masterpieces.PENDING).length}); return; + // other accounts the same person may have, and their story (lib/staff.js). + case "GET /mod/api/alts": { + const account = accounts.byName(url.searchParams.get("username") || ""); + reply(account ? 200 : 404, account ? {alts: staff.altsOf(account), ids: devices.idsFor(account)} : {error: "No such player."}); + return; + } + case "GET /mod/api/timeline": { + const account = accounts.byName(url.searchParams.get("username") || ""); + reply(account ? 200 : 404, account ? {events: staff.timelineOf(account)} : {error: "No such player."}); + return; + } + // who the server's chat filter stopped most this week. + case "GET /mod/api/filterhits": + reply(200, {players: chatlog.mostStopped(7, 50)}); + return; + case "GET /mod/api/players": { - if (url.searchParams.get("by") !== "address") { - reply(200, {players: findPlayers(url.searchParams.get("q"))}); + const searchBy = url.searchParams.get("by"); + if (searchBy === "device") { + const found = staff.byDevice(url.searchParams.get("q")); + if (found.error) { + reply(400, found); + return; + } + const online = playing(); + reply(200, {players: found.players.map(entry => ({...playerRow(accounts.byName(entry.username), online), matchedAt: entry.lastAt}))}); + return; + } + if (searchBy !== "address") { + reply(200, findPlayers(url.searchParams.get("q"))); return; } // by address: only the address typed, which is written down (once @@ -386,7 +419,8 @@ const handle = async (req, res, url, from, web) => { case "GET /mod/api/chat": { const params = url.searchParams; const lines = chatlog.search({username: (params.get("username") || "").trim().slice(0, 100), room: (params.get("room") || "").trim().slice(0, 100), - text: (params.get("text") || "").trim().slice(0, 100), before: Number(params.get("before")) || 0}); + text: (params.get("text") || "").trim().slice(0, 100), kind: params.get("kind") || "", direction: params.get("direction") || "", until: Number(params.get("until")) || 0, + before: Number(params.get("before")) || 0}); reply(200, {lines, more: lines.length === chatlog.PAGE, days: config.chatLogDays}); return; } @@ -426,7 +460,7 @@ const handle = async (req, res, url, from, web) => { } case "GET /mod/api/bans": - reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans().map(maskedAddress)}); + reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans().map(maskedAddress), devices: devices.list(), alerts: devices.alerts()}); return; case "POST /mod/api/address": { @@ -435,9 +469,16 @@ const handle = async (req, res, url, from, web) => { return; } + // A device ban lifted (lib/devices.js). + case "POST /mod/api/device": { + const result = staff.unbanDevices(body.id, mod.username); + done(result, "hardware ban lifted", result.username || ""); + return; + } + // paintings players framed (lib/masterpieces.js). case "GET /mod/api/masterpieces": - reply(200, {waiting: masterpieces.list(masterpieces.PENDING), approved: masterpieces.list(masterpieces.APPROVED)}); + reply(200, {...masterpieces.listsFor(url.searchParams.get("creator")), waitingCount: masterpieces.list(masterpieces.PENDING).length}); return; case "GET /mod/api/masterpiece": { diff --git a/lib/panel.js b/lib/panel.js index 15847e0..a84a873 100644 --- a/lib/panel.js +++ b/lib/panel.js @@ -9,7 +9,9 @@ const adopt = require("./adopt.js"); const badges = require("./badges.js"); const bans = require("./bans.js"); const colours = require("./colours.js"); +const chatlog = require("./chatlog.js"); const config = require("../config.js"); +const devices = require("./devices.js"); const defpacks = require("./defpacks.js"); const limits = require("./limits.js"); const log = require("./log.js"); @@ -47,6 +49,7 @@ const TEN_MINUTES_MS = 600000; const DAY_SECONDS = 86400; const MAX_ANNOUNCEMENT = 300; const MAX_OWNED_LISTED = 300; +const MAX_LISTED = 100; // accounts in one search of the Accounts page // currencies the panel can hand out, as indexes into CURRENCIES. const GIFT_CURRENCIES = {gems: 0, tickets: 1, diamonds: 3}; // who a ban is written down as given by. the panel has one password and so @@ -155,6 +158,10 @@ const accountRow = (account, playing) => { level: activeAvatar(account).questLevel || 0, items: account.items.length + account.denItems.length, gems: account.currency.gems || 0, + deviceBanned: devices.bannedId(account) !== 0, + devicesKnown: devices.knownFor(account).ids, + stoppedThisWeek: chatlog.notSentCount(account, 7), + paintings: masterpieces.madeBy(account).length, }; }; @@ -477,6 +484,11 @@ const act = (account, body) => { return {ok: `${name} is no longer banned.`}; case "kick": return actions.kick(account) ? {ok: `${name} was disconnected.`} : {error: `${name} is not online.`}; + // every computer they signed in from lately (lib/devices.js). + case "banDevices": + return staff.banDevices(account, body.reason, BY); + case "unbanDevices": + return staff.unbanDevicesOf(account, BY); // counted in hours; the game's own notice counts minutes. case "silence": { const hours = wholeNumber(body.hours, 0, MAX_BAN_HOURS); @@ -643,9 +655,24 @@ const handle = async (req, res, url, from, web) => { reply(200, overview()); return; + // a page of accounts by name (lib/staff.js says in what order), never + // all of them: with thousands, sending every one every few seconds + // slowed the page and the game alike. case "GET /admin/api/accounts": { const playing = new Map(world.players().map(player => [player.username, player.room || "(between rooms)"])); - reply(200, {accounts: accounts.all().map(account => accountRow(account, playing)), badges: badges.BADGES}); + const filter = url.searchParams.get("filter"); + const keep = filter === "online" ? (account, online) => online.has(account.username) + : filter === "banned" ? account => world.moderation.banRemaining(account) !== 0 : () => true; + const {found, total} = staff.findAccounts(url.searchParams.get("q"), keep, MAX_LISTED); + reply(200, {accounts: found.map(account => accountRow(account, playing)), total, badges: badges.BADGES}); + return; + } + + // one account's row, for the one that is open whatever the list shows. + case "GET /admin/api/account": { + const account = accounts.byName(url.searchParams.get("username") || ""); + const playing = new Map(world.players().map(player => [player.username, player.room || "(between rooms)"])); + reply(account ? 200 : 404, account ? {account: accountRow(account, playing), badges: badges.BADGES} : {error: "No such account."}); return; } @@ -660,6 +687,28 @@ const handle = async (req, res, url, from, web) => { reply(found.error ? 400 : 200, found); return; } + // who signed in from a computer, by one of its ids or the start of one. + case "GET /admin/api/device-search": { + const found = staff.byDevice(url.searchParams.get("q")); + reply(found.error ? 400 : 200, found.error ? found : {players: found.players.map(entry => ({...entry, + online: Boolean(world.findOnline(entry.username))}))}); + return; + } + + // what players typed, sent and posted (lib/chatlog.js), as the moderators see it. + case "GET /admin/api/chat": { + const params = url.searchParams; + const lines = chatlog.search({username: (params.get("username") || "").trim().slice(0, 100), room: (params.get("room") || "").trim().slice(0, 100), + text: (params.get("text") || "").trim().slice(0, 100), kind: params.get("kind") || "", direction: params.get("direction") || "", until: Number(params.get("until")) || 0, + before: Number(params.get("before")) || 0}); + reply(200, {lines, more: lines.length === chatlog.PAGE, days: config.chatLogDays}); + return; + } + case "GET /admin/api/chat/around": { + const found = chatlog.around(url.searchParams.get("id")); + reply(found ? 200 : 404, found || {error: "No such line."}); + return; + } case "GET /admin/api/logs": { const lines = log.recent(Number(url.searchParams.get("after")) || 0, (url.searchParams.get("filter") || "").slice(0, 100)); @@ -676,6 +725,10 @@ const handle = async (req, res, url, from, web) => { const result = act(account, body); if (result.ok) { console.log(`[admin] ${body.action} on "${account.username}"`); + // in the record beside the moderators', for the player's timeline. + if (!["password", "lastSeen", "level"].includes(body.action)) { + modlog.record(BY, body.action, account.username, result.detail || ""); + } } reply(result.ok ? 200 : 400, result); return; @@ -688,7 +741,39 @@ const handle = async (req, res, url, from, web) => { } case "GET /admin/api/bans": - reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans()}); + reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans(), devices: devices.list(), alerts: devices.alerts()}); + return; + + // A device ban lifted (lib/devices.js). + case "POST /admin/api/device": { + const result = staff.unbanDevices(body.id, BY); + if (result.ok) { + console.log(`[admin] device ban ${Number(body.id)} lifted`); + modlog.record(BY, "hardware ban lifted", result.username || ""); + } + reply(result.ok ? 200 : 400, result); + return; + } + + // other accounts the same person may have, their story, and who the + // chat filter stopped most this week (lib/staff.js, lib/chatlog.js). + case "GET /admin/api/alts": { + const account = accounts.byName(url.searchParams.get("username") || ""); + reply(account ? 200 : 404, account ? {alts: staff.altsOf(account), ids: devices.idsFor(account)} : {error: "No such account."}); + return; + } + case "GET /admin/api/timeline": { + const account = accounts.byName(url.searchParams.get("username") || ""); + reply(account ? 200 : 404, account ? {events: staff.timelineOf(account)} : {error: "No such account."}); + return; + } + case "GET /admin/api/filterhits": + reply(200, {players: chatlog.mostStopped(7, 50)}); + return; + + // what waits, for the tabs and the page's title, on every page. + case "GET /admin/api/counts": + reply(200, {reports: reports.openCount(), support: support.openCount() + bans.openAppeals(), masterpieces: masterpieces.list(masterpieces.PENDING).length}); return; // who may use the moderator panel, and what each did there. @@ -753,8 +838,8 @@ const handle = async (req, res, url, from, web) => { case "GET /admin/api/masterpieces": reply(200, { review: masterpieces.needsReview(), - waiting: masterpieces.list(masterpieces.PENDING), - approved: masterpieces.list(masterpieces.APPROVED), + ...masterpieces.listsFor(url.searchParams.get("creator")), + waitingCount: masterpieces.list(masterpieces.PENDING).length, }); return; diff --git a/lib/reports.js b/lib/reports.js index 7fb523e..64f59aa 100644 --- a/lib/reports.js +++ b/lib/reports.js @@ -94,4 +94,8 @@ const list = (handled = false) => accounts.database() const markHandled = id => accounts.database().prepare("UPDATE reports SET handled_at = ? WHERE id = ? AND handled_at IS NULL").run(now(), id).changes > 0; -module.exports = {load, file, list, markHandled, openCount, MAX_DETAIL}; +// the reports about one player, newest first, for their timeline. +const about = username => accounts.database().prepare("SELECT * FROM reports WHERE target = ? COLLATE NOCASE ORDER BY id DESC LIMIT 100") + .all(String(username)).map(row); + +module.exports = {load, file, list, about, markHandled, openCount, MAX_DETAIL}; diff --git a/lib/staff.js b/lib/staff.js index eec6784..8166135 100644 --- a/lib/staff.js +++ b/lib/staff.js @@ -2,7 +2,11 @@ const accounts = require("./accounts.js"); const bans = require("./bans.js"); +const devices = require("./devices.js"); +const limits = require("./limits.js"); const manage = require("./manage.js"); +const modlog = require("./modlog.js"); +const reports = require("./reports.js"); const support = require("./support.js"); const world = require("./world.js"); @@ -25,6 +29,29 @@ const disciplined = () => accounts.all() .filter(entry => entry.banned !== 0 || entry.silenced !== 0) .sort((a, b) => a.username.localeCompare(b.username)); +// accounts by name, for both panels' search: at most `limit`, those named +// exactly what was typed first, then those whose names start with it, then +// those with it anywhere, online players first within each and then by +// name. so "John" is never lost among John123 and Johnathan. with nothing +// typed: online players, then the ones seen last. `keep` narrows it +// (online, banned...). returns {found, total}: total is how many matched. +const MAX_FOUND = 50; +const findAccounts = (query, keep = () => true, limit = MAX_FOUND) => { + const wanted = String(query || "").trim().toLowerCase().slice(0, 100); + const online = new Set(world.players().map(player => player.username)); + const rank = name => { + const low = name.toLowerCase(); + return low === wanted ? 0 : low.startsWith(wanted) ? 1 : 2; + }; + const matched = accounts.all().filter(account => account.username.toLowerCase().includes(wanted) && keep(account, online)); + const sorted = wanted + ? matched.sort((a, b) => rank(a.username) - rank(b.username) || Number(online.has(b.username)) - Number(online.has(a.username)) + || a.username.localeCompare(b.username)) + : matched.sort((a, b) => Number(online.has(b.username)) - Number(online.has(a.username)) + || (b.lastSeen || b.lastLogin || 0) - (a.lastSeen || a.lastLogin || 0)); + return {found: sorted.slice(0, limit), total: matched.length}; +}; + // the accounts that signed in from an address, or from any address that // starts with what was typed ("203.0.113." for the lot): from the sign-in // histories, which hold the last 90 days (lib/accounts.js). failed tries @@ -67,6 +94,110 @@ const banAddress = (address, reason, by) => { return result.error ? {error: ADDRESS_ERRORS[result.error]} : {ban: result.ban, out: world.disconnectAddress(result.ban.address)}; }; +// bans every computer the account signed in from lately (lib/devices.js), +// and puts out whoever plays from one of them, whichever account. their +// sign-ins stay, as with an address ban: the client asks with one why its +// game stopped, and the account page stays open to them for an appeal; the +// game itself turns them away (lib/world.js). returns {ok, detail} or {error}. +const banDevices = (account, reason, by) => { + const result = devices.banAccount(account, reason, by); + if (result.error) { + return result; + } + const under = devices.accountsUnder(result.ban); + const out = world.disconnectBanned(under); + bans.record({account, action: "device_ban", seconds: -1, reason: result.ban.reason, by}); + const others = under.filter(one => one !== account).map(one => one.username); + return {ok: `${account.username} is hardware banned (${result.ban.ids.length} IDs).${out ? ` ${out} playing from them ${out === 1 ? "was" : "were"} put out.` : ""}` + + `${others.length ? ` Also used by: ${others.slice(0, 10).join(", ")}${others.length > 10 ? "…" : ""}.` : ""}`, detail: result.ban.reason}; +}; + +const unbanDevices = (id, by) => { + const ban = devices.unban(id); + if (!ban) { + return {error: "No such hardware ban."}; + } + bans.record({account: accounts.byId(ban.accountId), action: "device_unban", by}); + return {ok: `The hardware ban made with ${ban.username || "that account"} is lifted.`, username: ban.username}; +}; + +// every computer ban that keeps the account out, or was made with it, lifted. +const unbanDevicesOf = (account, by) => { + const lifted = devices.bansOfAccount(account).map(ban => unbanDevices(ban.id, by)).filter(result => result.ok); + if (!lifted.length) { + return {error: "None of their hardware is banned."}; + } + const names = [...new Set(lifted.map(result => result.username).filter(Boolean))]; + return {ok: `${lifted.length === 1 ? "1 hardware ban was" : `${lifted.length} hardware bans were`} lifted${names.length ? ` (made with ${names.join(", ")})` : ""}.`, + detail: names.join(", ")}; +}; + +// the accounts that used a computer id, or one starting with what was +// typed (lib/devices.js): {error} or {players: [{username, kinds, lastAt}]}. +const byDevice = query => { + const found = devices.search(query); + return found.error ? found : {players: found.players.map(entry => ({username: entry.account.username, kinds: entry.kinds, lastAt: entry.lastAt}))}; +}; + +// other accounts the same person may have: those that used one of its +// computers (lib/devices.js), and those that signed in from one of its +// addresses in the last 90 days. [{username, devices: [kind], weak, +// addresses: count, online, banned}], the likeliest first. the addresses +// themselves are not given: moderators do not see them. +const altsOf = account => { + const found = new Map(); + const entry = username => { + if (!found.has(username)) { + found.set(username, {username, devices: [], weak: false, addresses: 0}); + } + return found.get(username); + }; + for (const alt of devices.alts(account)) { + Object.assign(entry(alt.username), {devices: alt.kinds, weak: alt.weak}); + } + const mine = new Set(account.logins.filter(login => login.ok && login.address && !limits.isLoopback(login.address)).map(login => login.address)); + if (mine.size) { + for (const other of accounts.all()) { + if (other !== account) { + const shared = new Set(other.logins.filter(login => login.ok && mine.has(login.address)).map(login => login.address)); + if (shared.size) { + entry(other.username).addresses = shared.size; + } + } + } + } + return [...found.values()].map(alt => { + const other = accounts.byName(alt.username); + return {...alt, online: Boolean(world.findOnline(alt.username)), banned: other ? world.moderation.banRemaining(other) : 0, + deviceBanned: other ? devices.bannedId(other) !== 0 : false}; + }).sort((one, other) => Number(other.devices.length > 0 && !other.weak) - Number(one.devices.length > 0 && !one.weak) + || other.devices.length - one.devices.length || other.addresses - one.addresses || one.username.localeCompare(other.username)).slice(0, 100); +}; + +// one player's story, newest first: bans given and lifted, what staff did +// to them, the reports about them, and what their computers gave away +// (lib/devices.js). [{at, kind, text, by}]. +const BAN_WORDS = {ban: "Banned", unban: "Ban lifted", reason: "Ban reason changed", appeal: "Appealed", appeal_approved: "Appeal approved", + appeal_denied: "Appeal denied", device_ban: "Hardware banned", device_unban: "Hardware ban lifted"}; +const timelineOf = account => { + const events = []; + for (const entry of bans.historyOf(account)) { + const length = entry.action === "ban" ? (entry.seconds === -1 ? "for good" : `${Math.round(entry.seconds / 3600)} h`) : ""; + events.push({at: entry.at, kind: "ban", text: [BAN_WORDS[entry.action] || entry.action, length, entry.reason].filter(Boolean).join(" · "), by: entry.by}); + } + for (const entry of modlog.about(account.username)) { + events.push({at: entry.at, kind: "staff", text: [entry.action, entry.detail].filter(Boolean).join(" · "), by: entry.by}); + } + for (const report of reports.about(account.username)) { + events.push({at: report.createdAt, kind: "report", text: `Reported: ${report.reason}${report.detail ? ` · ${report.detail}` : ""}${report.handledAt ? "" : " (waiting)"}`, + by: report.reporter}); + } + for (const entry of devices.alertsOf(account)) { + events.push({at: entry.at, kind: "alert", text: `${entry.name} · ${entry.detail}`, by: ""}); + } + return events.sort((one, other) => other.at - one.at).slice(0, 200); +}; + // appeals with what each is against, as it stands now. const appealsFor = handled => bans.appeals(handled).map(appeal => { const account = accounts.byId(appeal.accountId); @@ -122,4 +253,4 @@ const answerNameRequest = (id, approve) => { return {ok: `${oldName} is now called ${account.username}. They log in with the new name and the same password.`, username: account.username}; }; -module.exports = {disciplined, byAddress, banAddress, appealsFor, answerAppeal, answerNameRequest}; +module.exports = {disciplined, findAccounts, byAddress, banAddress, banDevices, unbanDevices, unbanDevicesOf, byDevice, altsOf, timelineOf, appealsFor, answerAppeal, answerNameRequest}; diff --git a/lib/walls.js b/lib/walls.js index 31942b1..ef282f1 100644 --- a/lib/walls.js +++ b/lib/walls.js @@ -5,6 +5,7 @@ const fs = require("fs"); const path = require("path"); const accounts = require("./accounts.js"); const chatFilter = require("./chatfilter.js"); +const chatlog = require("./chatlog.js"); const masterpieces = require("./masterpieces.js"); const limits = require("./limits.js"); const {isUint} = require("./player.js"); @@ -155,6 +156,7 @@ module.exports = ({blocks, findOnline}) => { const rule = message ? chatFilter.broken(message) : null; if (rule) { console.log(`[filter] ${viewer.username} on ${owner.username}'s wall: "${message}" (${rule})`); + chatlog.recordTo(viewer, chatlog.WALL, owner.username, chatlog.NOT_SENT + message); const session = findOnline(viewer.username); if (session) { chatFilter.warn(session); @@ -184,6 +186,8 @@ module.exports = ({blocks, findOnline}) => { if (typeof body.pp === "string" && owner.wall.posts.some(other => other.x === body.pp)) { post.pp = body.pp; // a reply to that post } + // for the panels (lib/chatlog.js), as typed chat is. + chatlog.recordTo(viewer, chatlog.WALL, owner.username, message); owner.wall.posts.push(post); owner.wall.posts = owner.wall.posts.slice(-MAX_POSTS); owner.wall.modified = post.t; diff --git a/lib/world.js b/lib/world.js index b9fb7fc..d38969b 100644 --- a/lib/world.js +++ b/lib/world.js @@ -12,6 +12,7 @@ const defpacks = require("./defpacks.js"); const avatarHandlers = require("./avatars.js"); const badges = require("./badges.js"); const bans = require("./bans.js"); +const devices = require("./devices.js"); const chatlog = require("./chatlog.js"); const chatFilter = require("./chatfilter.js"); const buddyModule = require("./buddies.js"); @@ -261,6 +262,18 @@ const login = (session, msg) => { loginFailed(session, LOGIN_BANNED, "Banned"); return; } + // a banned computer (lib/devices.js), and a game that never said which + // computer it is on: told at /authenticate too, which is the way in. + if (devices.banOfAccount(account)) { + console.log(`[world] login rejected for "${account.username}": hardware banned`); + loginFailed(session, LOGIN_BANNED, "Banned"); + return; + } + if (config.requireDevice && devices.knownFor(account).lastAt < Math.floor(Date.now() / 1000) - 90 * 86400) { + console.log(`[world] login rejected for "${account.username}": no device ids`); + loginFailed(session, 0, "Update the client"); + return; + } // its username was rejected (lib/moderation.js): a new one first, which // the client or the account page asks for. if (account.nameRejected) { @@ -1588,6 +1601,20 @@ module.exports = { } return there.length; }, + // puts out these accounts, if playing, with the game's banned notice: + // their computer was banned (lib/devices.js). returns how many were. + disconnectBanned(list) { + let out = 0; + for (const account of list) { + const session = findOnline(account.username); + if (session) { + session.sendXt("fd", -1, "fb", 1, moderation.PERMANENT); + session.close(); + out++; + } + } + return out; + }, // takes the account out of the world at once (not when its socket gets // round to closing), so the caller can go on to rename or delete it. disconnect(account) { diff --git a/public/admin.html b/public/admin.html index 7b4fd99..e8ddac4 100644 --- a/public/admin.html +++ b/public/admin.html @@ -158,6 +158,8 @@ tbody tr:last-child td { border-bottom: 0; } tbody tr.selected td { background: var(--raised); } tbody tr.pick { cursor: pointer; } + .device-id { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 12px; } + button.link { background: none; border: 0; padding: 0; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; font-weight: 400; } .empty { color: var(--muted); padding: 8px 0; } .toolbar { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; } .toolbar input[type="search"] { flex: 1; min-width: 180px; } @@ -193,11 +195,26 @@ .report .typed { margin: 8px 0; padding: 8px 12px; background: var(--bg); border: 1px solid var(--line); border-radius: 14px; overflow-wrap: anywhere; } .report pre { margin: 8px 0; padding: 8px 12px; background: var(--bg); border: 1px solid var(--line); border-radius: 14px; font: 12px/1.5 ui-monospace, Consolas, monospace; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 180px; overflow: auto; } .report .buttons { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; } + .chat-list { margin: 0; padding: 0; list-style: none; } + .chat-list li { display: flex; gap: 10px; align-items: baseline; padding: 6px 4px; border-bottom: 1px solid var(--line); } + .chat-list li:last-child { border-bottom: 0; } + .chat-list li.this { background: var(--raised); border-radius: 10px; } + .chat-time { flex: none; width: 128px; color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; } + .chat-who { flex: none; max-width: 190px; padding: 0; border: 0; font-weight: 700; text-align: left; overflow: hidden; text-overflow: ellipsis; } + .chat-who:hover { background: none; text-decoration: underline; } + .chat-text { flex: 1; min-width: 0; overflow-wrap: anywhere; } + .chat-room { display: block; color: var(--muted); font-size: 12px; } + .chat-more { flex: none; padding: 2px 10px 3px; font-size: 12px; } + #timeline { margin: 0; padding-left: 18px; font-size: 13px; overflow-wrap: anywhere; } .paintings { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 12px; } .painting { border: 1px solid var(--line); border-radius: 18px; padding: 14px; } .painting img { display: block; width: 100%; height: auto; border-radius: 10px; background: #fff; } .painting h3 { margin: 8px 0 2px; } .painting .buttons { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; } + .painting img { cursor: zoom-in; } + .preview { position: fixed; inset: 0; z-index: 50; display: flex; align-items: center; justify-content: center; padding: 16px; background: rgba(0, 0, 0, 0.85); cursor: zoom-out; } + .preview[hidden] { display: none; } + .preview img { max-width: 100%; max-height: 100%; border-radius: 10px; background: #fff; } textarea { width: 100%; resize: vertical; } .send-row { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; align-items: center; } #owned { margin-top: 16px; } @@ -245,6 +262,7 @@