diff --git a/README.md b/README.md index db685fe..93f003c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,10 @@ # Burrow Burrow is a private server for AJ Classic. +## Account-recovery email + +Set `AJ_RECOVERY_MAIL_URL` and `AJ_RECOVERY_MAIL_TOKEN` to an HTTPS mail-relay or transactional-email webhook. Burrow posts `{to, subject, text}` with a Bearer token. Until both are configured, email recovery intentionally does not issue a usable reset link. New web sign-ups are asked for a recovery email; password and 2FA recovery require the one-time link sent there. + # Security An independent security audit by a Strawberry Jam contributor, who is not part of the Burrow team, found no malware in the Burrow client or server (client v1.2.0, server as of 17 October 2026). Every file in every installer was checked against its source and against the official Electron, NSIS and Adobe Flash releases. The report also lists the weaknesses found, with fixes, and every check can be repeated by anyone. diff --git a/config.js b/config.js index 2ee6633..882f37b 100644 --- a/config.js +++ b/config.js @@ -102,6 +102,13 @@ module.exports = { turnstile: env.AJ_TURNSTILE_SITE_KEY && env.AJ_TURNSTILE_SECRET ? {siteKey: env.AJ_TURNSTILE_SITE_KEY, secret: env.AJ_TURNSTILE_SECRET} : null, + // Account-recovery mail is delivered to this HTTPS webhook. It receives + // {to, subject, text}; point it at the transactional-mail provider or + // small mail relay you use. Recovery is deliberately unavailable until + // both values are set, rather than ever exposing a reset link in a page. + recoveryMail: env.AJ_RECOVERY_MAIL_URL && env.AJ_RECOVERY_MAIL_TOKEN + ? {url: env.AJ_RECOVERY_MAIL_URL, token: env.AJ_RECOVERY_MAIL_TOKEN} : null, + // asset mirror: anything not served locally is fetched once from here and // cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only. upstreamContent: env.AJ_UPSTREAM || "https://ajcontent.akamaized.net/", @@ -115,8 +122,11 @@ module.exports = { // before is still kept out). requireDevice: env.AJ_REQUIRE_DEVICE !== "0", // Discord (lib/discord.js): an application's id and secret for linking a - // player's Discord account on the account page (its OAuth2 redirect must - // be account/discord/callback), and a bot in Burrow's Discord + // player's Discord account on the account page and for allowed accounts to + // sign in to /dashboard/admin (OAuth2 redirects: + // account/discord/callback, + // dashboard/admin/discord/callback, and + // dashboard/staff/discord/callback), and a bot in Burrow's Discord // server for the booster badge. linking is off without the first two, the // booster badge left alone without the last two. discord: { diff --git a/lib/accounts.js b/lib/accounts.js index 9a08ea6..b65fae5 100644 --- a/lib/accounts.js +++ b/lib/accounts.js @@ -62,6 +62,7 @@ const USER_VAR_SETTINGS = 363; // the settings menu's switches, a bit each (gui. // the whole message left out (see account.filter below). const DEFAULT_FILTER = {level: 1, mode: 1, words: ""}; const MAX_PASSWORD_LENGTH = 100; +const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // parts of the game a player can switch off for their own account, each // enforced where the game asks for it (featureOn below). // the Early Member badge (lib/badges.js) goes to an account made while @@ -216,6 +217,9 @@ const normalize = account => { // what the player set on the account page (lib/manage.js). account.features = {...Object.fromEntries(FEATURES.map(name => [name, true])), ...account.features}; // false = switched off account.locked = account.locked === true; // nobody gets into the game until its owner unlocks it + account.recoveryEmail = typeof account.recoveryEmail === "string" && EMAIL_PATTERN.test(account.recoveryEmail) + ? account.recoveryEmail.toLowerCase() : ""; + account.recoveryTokens = Array.isArray(account.recoveryTokens) ? account.recoveryTokens.filter(token => token && token.expires > now()) : []; account.logins = account.logins || []; // {at, via, address, ok}, newest first: lib/accounts.js recordLogin account.roomThemes = account.roomThemes || {}; // room -> theme, for rooms given a look of their own ("!theme here") account.randomTheme = account.randomTheme === true; // a theme picked afresh at every login @@ -249,6 +253,9 @@ const normalize = account => { if (account.discordId !== undefined && !/^\d{5,25}$/.test(String(account.discordId))) { delete account.discordId; // the linked Discord account's id } + // Set only by the owner in /admin. A matching linked Discord identity may + // use this account to open the owner dashboard (lib/discord.js). + account.adminDashboardAccess = account.adminDashboardAccess === true; account.badges = Array.isArray(account.badges) ? account.badges : []; // badge ids, given in the admin panel account.bio = typeof account.bio === "string" ? account.bio : ""; // their own words, for the card's Bio tab // seconds spent in the game in all (lib/world.js counts it), and whether @@ -714,6 +721,7 @@ const register = (username, password, avatar = {}) => { activeAvatar: 1, // early Member, for an account made while there are no more than a hundred. badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [], + recoveryEmail: typeof avatar.email === "string" && EMAIL_PATTERN.test(avatar.email.trim()) ? avatar.email.trim().toLowerCase() : "", }); console.log(`[accounts] registered "${logText(username)}" (id ${logText(account.id)})`); return {account}; diff --git a/lib/admin.js b/lib/admin.js index 0a4d479..2b1487c 100644 --- a/lib/admin.js +++ b/lib/admin.js @@ -257,7 +257,10 @@ const handle = async (route, params, body, from) => { if (device && devices.banOf(device)) { return {status: 403, body: {error: "device_banned"}}; } - const {username, password, avatarType} = body || {}; + const {username, password, avatarType, email} = body || {}; + if (config.recoveryMail && (typeof email !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim()))) { + return {status: 400, body: {error: "invalid_email"}}; + } // 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. if ((body || {}).agreed !== true) { @@ -279,7 +282,7 @@ const handle = async (route, params, body, from) => { if (!STARTER_ANIMALS.includes(avatarType)) { return {status: 400, body: {error: "choose_animal"}}; } - const result = accounts.register(username, password, {type: avatarType}); + const result = accounts.register(username, password, {type: avatarType, email}); if (result.account) { result.account.agreed = {version: config.termsVersion, at: Math.floor(Date.now() / 1000)}; accounts.save(result.account); diff --git a/lib/defpacks.js b/lib/defpacks.js index 2376fc3..7107186 100644 --- a/lib/defpacks.js +++ b/lib/defpacks.js @@ -8,6 +8,7 @@ const config = require("../config.js"); const sales = require("./sales.js"); const badges = require("./badges.js"); const extraMusic = require("./extramusic.js"); +const wearRules = require("./wearrules.js"); // defPack ids, from loader.DefPacksDefHelper in the client. const DEF_ITEM = 1000; @@ -42,6 +43,7 @@ const DEF_PET_TOY = 1063; const DEF_WORLD_ITEMS = 1064; const DEF_NPC = 1025; const DEF_NAMEBAR_BADGE = 1049; +const DEF_EMOTICON = 1036; const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items: plain, mannequin const DEN_ITEM_MASTERPIECE = 2725; @@ -70,6 +72,32 @@ const LAYER_EYES = "3"; const TYPE_CLOTHING = "1"; const EVERY_AVATAR = "9007199254740991"; // avatarUseFlags with a bit set for each animal type +// ItemXtCommManager checks bit (avatar type - 1). BigInt avoids losing a +// bit in JavaScript's 53-bit Number representation while preserving the +// string form the AMF def pack uses. +const clientAvatarUseFlags = itemId => { + let flags = BigInt(EVERY_AVATAR); + for (const type of wearRules.blockedTypes(itemId)) { + if (type <= 53) { + flags &= ~(1n << BigInt(type - 1)); + } + } + return String(flags); +}; + +// One transform is used for fetched packs and for the live `xdi` definition +// updates sent to games that are already running. +const clientItemRow = def => { + const row = {...def}; + if (row.type === TYPE_CLOTHING) { + row.avatarUseFlags = clientAvatarUseFlags(row.id); + } + else if (row.type === "0" && row.layerId === LAYER_EYES) { + row.avatarUseFlags = EVERY_AVATAR; + } + return row; +}; + // rooms the official room pack no longer lists but whose files an older // build on the CDN still has (lib/cdn.js looks there): the Summer Carnival, // dropped after build 1828. @@ -317,9 +345,9 @@ const alwaysOnSale = (pack, ids) => { // the rows put back or added (SHARED_CHANGES). const CLIENT_PACKS = new Map([ [DEF_ITEM, pack => { - for (const def of Object.values(pack)) { + for (const [key, def] of Object.entries(pack)) { if (def.type === TYPE_CLOTHING || (def.type === "0" && def.layerId === LAYER_EYES)) { - def.avatarUseFlags = EVERY_AVATAR; + pack[key] = clientItemRow(def); } } sales.stamp("clothing", pack); @@ -397,6 +425,9 @@ let musicIds = []; // den items that are music tracks let roomDefsById = new Map(); let badgeIds = []; // name tag badges, ascending let npcDefs = new Map(); // the characters of the adventures, see lib/disguises.js +// An avatar attachment is named by its emoticon definition id on the wire, +// while AvatarWorldView needs the media id stored by that definition. +let emoticonMediaIds = new Map(); // A pack whose feature can be done without: missing (offline and never // cached) just leaves that feature empty. @@ -463,6 +494,7 @@ const init = async () => { petFoodDefs = await loadOptional(DEF_PET_FOOD); petToyDefs = await loadOptional(DEF_PET_TOY); npcDefs = new Map((await loadOptional(DEF_NPC)).map(def => [Number(def.id), def])); + emoticonMediaIds = new Map((await loadOptional(DEF_EMOTICON)).map(def => [Number(def.id), Number(def.mediaRef)])); partyDefs = new Map((await loadOptional(DEF_PARTY)).map(def => { const room = roomPathsById.get(Number(def.roomDefId)); return [Number(def.id), { @@ -544,6 +576,14 @@ module.exports = { denItemDef: id => denItemDefs.get(Number(id)), denItemIds: () => denItemIds, clientPack, + // A changing rule must not leave the cached item pack permissive. The next + // client request remakes it, and current games receive an xdi row too. + invalidateClientItemPack: () => clientPackBodies.delete(DEF_ITEM), + clientItemRow, + clientItemDef: id => { + const def = itemDefs.get(Number(id)); + return def ? clientItemRow(def) : null; + }, string: id => (Object.hasOwn(strings, id) ? String(strings[id]) : ""), stringId: text => { if (!stringIds) { @@ -558,6 +598,7 @@ module.exports = { }, badgeIds: () => badgeIds, npcDef: id => npcDefs.get(Number(id)), + emoticonMediaId: id => emoticonMediaIds.get(Number(id)) || 0, oddDenItemIds: () => oddDenItemIds, // den items that exist to be given by id and are in no shop. unsoldDenItemIds: () => extraMusic.ids, diff --git a/lib/discord.js b/lib/discord.js index 579a0b3..4ed7d93 100644 --- a/lib/discord.js +++ b/lib/discord.js @@ -35,27 +35,57 @@ const BOOSTER = "booster"; const linking = () => Boolean(config.discord.clientId && config.discord.clientSecret); const boostChecks = () => Boolean(config.discord.botToken && config.discord.guildId); const redirectUri = () => `${config.siteUrl}account/discord/callback`; +const adminRedirectUri = () => `${config.siteUrl}dashboard/admin/discord/callback`; +const staffRedirectUri = () => `${config.siteUrl}dashboard/staff/discord/callback`; // a link under way: state (in Discord's address) -> {accountId, nonce (in a // cookie of the browser that asked), expires}. both must come back. const states = new Map(); +const adminStates = new Map(); +const staffStates = new Map(); -const start = account => { - for (const [state, entry] of states) { +const newState = statesMap => { + for (const [state, entry] of statesMap) { if (entry.expires < Date.now()) { - states.delete(state); + statesMap.delete(state); } } - if (states.size >= MAX_STATES) { - states.delete(states.keys().next().value); + if (statesMap.size >= MAX_STATES) { + statesMap.delete(statesMap.keys().next().value); } const state = crypto.randomBytes(24).toString("hex"); const nonce = crypto.randomBytes(24).toString("hex"); - states.set(state, {accountId: account.id, nonce, expires: Date.now() + STATE_MINUTES * 60000}); + statesMap.set(state, {nonce, expires: Date.now() + STATE_MINUTES * 60000}); + return {state, nonce}; +}; + +const authorize = (redirect, state) => { const url = new URL(AUTHORIZE); url.search = new URLSearchParams({client_id: config.discord.clientId, response_type: "code", scope: "identify", - redirect_uri: redirectUri(), state, prompt: "consent"}).toString(); - return {url: url.href, nonce}; + redirect_uri: redirect, state, prompt: "consent"}).toString(); + return url.href; +}; + +const start = account => { + const {state, nonce} = newState(states); + states.get(state).accountId = account.id; + return {url: authorize(redirectUri(), state), nonce}; +}; + +// A separate OAuth state and redirect for the owner dashboard. The Discord +// account must already be linked to a Burrow account explicitly granted +// adminDashboardAccess; knowing a Discord name is never enough. +const startAdmin = () => { + const {state, nonce} = newState(adminStates); + return {url: authorize(adminRedirectUri(), state), nonce}; +}; + +// Staff sign in through a separately scoped state and callback. A Discord +// identity is only useful here after its owner has linked it to their own +// Burrow account; modpanel.js also verifies that account remains active staff. +const startStaff = () => { + const {state, nonce} = newState(staffStates); + return {url: authorize(staffRedirectUri(), state), nonce}; }; const call = async (path, options = {}) => { @@ -154,6 +184,66 @@ const finish = async (state, nonce, code) => { } }; +const finishAdmin = async (state, nonce, code) => { + const entry = typeof state === "string" ? adminStates.get(state) : null; + adminStates.delete(state); + const digest = text => crypto.createHash("sha256").update(String(text)).digest(); + if (!entry || entry.expires < Date.now() || typeof nonce !== "string" || !crypto.timingSafeEqual(digest(entry.nonce), digest(nonce)) || !code) { + return {error: "expired"}; + } + try { + const token = await call("/oauth2/token", { + method: "POST", + headers: {"Content-Type": "application/x-www-form-urlencoded"}, + body: new URLSearchParams({client_id: config.discord.clientId, client_secret: config.discord.clientSecret, + grant_type: "authorization_code", code, redirect_uri: adminRedirectUri()}).toString(), + }); + if (token.status !== 200 || !token.body.access_token) { + return {error: "discord"}; + } + const me = await call("/users/@me", {headers: {Authorization: `Bearer ${token.body.access_token}`}}); + if (me.status !== 200 || !/^\d{5,25}$/.test(String(me.body.id))) { + return {error: "discord"}; + } + const account = accounts.all().find(candidate => candidate.discordId === String(me.body.id) && candidate.adminDashboardAccess); + return account ? {ok: true, account} : {error: "denied"}; + } + catch (err) { + console.log(`[discord] admin sign-in failed: ${logText(err.message)}`); + return {error: "discord"}; + } +}; + +const finishStaff = async (state, nonce, code) => { + const entry = typeof state === "string" ? staffStates.get(state) : null; + staffStates.delete(state); + const digest = text => crypto.createHash("sha256").update(String(text)).digest(); + if (!entry || entry.expires < Date.now() || typeof nonce !== "string" || !crypto.timingSafeEqual(digest(entry.nonce), digest(nonce)) || !code) { + return {error: "expired"}; + } + try { + const token = await call("/oauth2/token", { + method: "POST", + headers: {"Content-Type": "application/x-www-form-urlencoded"}, + body: new URLSearchParams({client_id: config.discord.clientId, client_secret: config.discord.clientSecret, + grant_type: "authorization_code", code, redirect_uri: staffRedirectUri()}).toString(), + }); + if (token.status !== 200 || !token.body.access_token) { + return {error: "discord"}; + } + const me = await call("/users/@me", {headers: {Authorization: `Bearer ${token.body.access_token}`}}); + if (me.status !== 200 || !/^\d{5,25}$/.test(String(me.body.id))) { + return {error: "discord"}; + } + const account = accounts.all().find(candidate => candidate.discordId === String(me.body.id)); + return account ? {ok: true, account} : {error: "denied"}; + } + catch (err) { + console.log(`[discord] staff sign-in failed: ${logText(err.message)}`); + return {error: "discord"}; + } +}; + // the link undone, by the player or an admin; the booster badge goes with it. const unlink = account => { const had = Boolean(account.discordId || account.discord); @@ -202,4 +292,4 @@ const startup = () => { } }; -module.exports = {linking, boostChecks, start, finish, unlink, startup}; +module.exports = {linking, boostChecks, start, finish, startAdmin, finishAdmin, startStaff, finishStaff, unlink, startup}; diff --git a/lib/http.js b/lib/http.js index a23218e..b9a983c 100644 --- a/lib/http.js +++ b/lib/http.js @@ -50,6 +50,19 @@ const MIME = { ".otf": "font/otf", }; +// The desktop webview caches the SWF aggressively. Include the local SWF's +// timestamp in its URL so a freshly built client is actually picked up after +// the server restarts, without making an operator remember to bump a config +// value by hand. +const clientRevision = () => { + try { + return Math.floor(fs.statSync(config.clientSwf).mtimeMs).toString(36); + } + catch (_) { + return "unknown"; + } +}; + const flashVars = () => ({ content: config.baseUrl, // the game's own server to the SWF, whatever its name: it loads the card @@ -69,7 +82,7 @@ const flashVars = () => ({ // member or not may be chosen on any server (lib/accounts.js) membershipChoice: true, smoke_version: config.deployVersion, - clientURL: `${config.baseUrl}${config.deployVersion}/ajclient.swf?v=${config.buildVersion}`, + clientURL: `${config.baseUrl}${config.deployVersion}/ajclient.swf?v=${config.buildVersion}-${clientRevision()}`, startupRoom: config.startupRoom, // "-1" turns the client's stats socket off. sbStatTrackerIp: "-1", @@ -293,7 +306,7 @@ const repeatedError = text => { const THEMED_ROOM = /^(\d+)\/roomDefs\/theme_(\d+)\/(.+)$/; // the web pages, as against what the game and the client load -const SITE_PAGES = /^\/(?:register|terms|privacy|commands|shop|account|mod|download)?\/?$/; +const SITE_PAGES = /^\/(?:register|terms|privacy|commands|shop|account|mod|admin|dashboard|download)?\/?$/; // the installers /download offers, those of them config.downloadsDir has const DOWNLOADS = [ @@ -652,22 +665,54 @@ const handle = async (req, res) => { return; } - const isAdmin = url.pathname === "/admin" || url.pathname.startsWith("/admin/"); + const dashboardAdmin = url.pathname === "/dashboard/admin" || url.pathname.startsWith("/dashboard/admin/") + || url.pathname === "/dashboard/api/admin" || url.pathname.startsWith("/dashboard/api/admin/"); + const dashboardStaff = url.pathname === "/dashboard/staff" || url.pathname.startsWith("/dashboard/staff/") + || url.pathname === "/dashboard/api/staff" || url.pathname.startsWith("/dashboard/api/staff/"); + const isDashboard = url.pathname === "/dashboard" || dashboardAdmin || dashboardStaff; + const isAdmin = url.pathname === "/admin" || url.pathname.startsWith("/admin/") || dashboardAdmin; const isAccount = url.pathname === "/account" || url.pathname.startsWith("/account/"); - const isMod = url.pathname === "/mod" || url.pathname.startsWith("/mod/"); + const isMod = url.pathname === "/mod" || url.pathname.startsWith("/mod/") || dashboardStaff; // the pages that keep a cookie answer only under this server's own names: // a request sent here by a page of another name (one whose name was made // to point at this machine, say) is not theirs to make. nor is such a // request ever this machine's own, wherever it came from. if (!limits.hostAllowed(req)) { - if (isAdmin || isAccount || isMod) { + if (isDashboard || isAdmin || isAccount || isMod) { send(res, 421, {error: "wrong_host"}); return; } from.local = false; } + // One entry point for the owner and staff dashboards. The old addresses + // stay as bookmark-friendly redirects; their APIs remain available for + // installed tools and are not redirected. + if (req.method === "GET" && url.pathname === "/dashboard/") { + res.writeHead(302, {Location: `/dashboard${url.search}`, "Content-Length": 0}); + res.end(); + return; + } + if (req.method === "GET" && url.pathname === "/dashboard") { + res.setHeader("Cache-Control", "no-store"); + res.setHeader("X-Frame-Options", "DENY"); + res.setHeader("X-Content-Type-Options", "nosniff"); + res.setHeader("Referrer-Policy", "no-referrer"); + send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "dashboard.html")), "text/html; charset=utf-8"); + return; + } + if (req.method === "GET" && url.pathname === "/admin") { + res.writeHead(302, {Location: "/dashboard/admin", "Content-Length": 0}); + res.end(); + return; + } + if (req.method === "GET" && url.pathname === "/mod") { + res.writeHead(302, {Location: "/dashboard/staff", "Content-Length": 0}); + res.end(); + return; + } + // the admin panel sets its own, stricter headers: none of the cross-origin // allowances below apply to it. on a public server it is not there at all // for anyone but this machine and the addresses named (config.adminAllow). @@ -676,6 +721,11 @@ const handle = async (req, res) => { send(res, 404, "Not found", "text/plain"); return; } + if (dashboardAdmin) { + url.pathname = url.pathname.startsWith("/dashboard/api/admin") + ? url.pathname.replace("/dashboard/api/admin", "/admin/api") + : url.pathname.replace("/dashboard/admin", "/admin"); + } if (url.pathname === "/admin/api/itemart") { res.setHeader("Cache-Control", "no-store"); await itemArtUpload(req, res, url, from, null, panel.signedIn); @@ -697,6 +747,11 @@ const handle = async (req, res) => { // and the moderator panel (lib/modpanel.js), which is there for anyone to // reach: its moderators are players, wherever they are. + if (dashboardStaff) { + url.pathname = url.pathname.startsWith("/dashboard/api/staff") + ? url.pathname.replace("/dashboard/api/staff", "/mod/api") + : url.pathname.replace("/dashboard/staff", "/mod"); + } if (isMod && url.pathname === "/mod/api/itemart") { res.setHeader("Cache-Control", "no-store"); await itemArtUpload(req, res, url, from, modpanel.signedInAs); diff --git a/lib/itemcontrol.js b/lib/itemcontrol.js index 9fe77c6..00b9fe4 100644 --- a/lib/itemcontrol.js +++ b/lib/itemcontrol.js @@ -3,6 +3,7 @@ const accounts = require("./accounts.js"); const customItems = require("./customitems.js"); const defpacks = require("./defpacks.js"); +const wearRules = require("./wearrules.js"); // what staff who make items (items.create: admins and developers) may do // about who has them: @@ -83,6 +84,94 @@ const lockedList = () => [...lockSet()].map(entry => { return {kind, id: Number(id), name: nameOf(kind, id)}; }); +// The animals a moderator can select in the dashboard. Avatar types, rather +// than a hand-written list of species, keep this correct for packs added in +// a later game build. +const wearAnimals = () => defpacks.avatarTypes().sort((one, two) => one - two).map(type => { + const def = defpacks.avatarDef(type) || {}; + return {id: Number(type), name: defpacks.string(def.titleStrRef || def.nameStrId) || def.abbrName || `Animal ${type}`}; +}); + +const wearRuleList = () => wearRules.all().flatMap(rule => { + const found = item("clothing", rule.id); + return found.error ? [] : [{id: found.id, name: nameOf(found.kind, found.id), blockedTypes: rule.blocked}]; +}); + +// Remove a new restriction from every possible display of an item. A clothing +// association has an avatar slot; a mannequin keeps the inventory ids in +// five den-item slots. Both must be cleaned or a rule can be bypassed by +// switching animals or visiting a den. +const removeBlockedUses = (account, itemId, blocked) => { + const disallowedAvatarSlots = new Set(account.avatars.filter(avatar => blocked.has(Number(avatar.type))).map(avatar => avatar.avInvId)); + const matchingInventory = new Set(account.items.filter(piece => piece.def === itemId).map(piece => piece.inv)); + let removed = 0; + let clothingChanged = false; + let mannequinChanged = false; + for (const piece of account.items) { + if (piece.def !== itemId || !Array.isArray(piece.on)) { + continue; + } + const kept = piece.on.filter(avInvId => !disallowedAvatarSlots.has(avInvId)); + if (kept.length !== piece.on.length) { + removed += piece.on.length - kept.length; + piece.on = kept; + clothingChanged = true; + } + } + for (const denItem of account.denItems) { + const mannequinType = Number((defpacks.denItemDef(denItem.def) || {}).mannequinAvatarDefId); + if (!blocked.has(mannequinType) || !denItem.mannequin || !Array.isArray(denItem.mannequin.worn)) { + continue; + } + const kept = denItem.mannequin.worn.map(inv => (matchingInventory.has(Number(inv)) ? 0 : inv)); + if (kept.some((inv, index) => inv !== denItem.mannequin.worn[index])) { + removed += kept.filter(inv => inv === 0).length - denItem.mannequin.worn.filter(inv => inv === 0).length; + denItem.mannequin.worn = kept; + mannequinChanged = true; + } + } + return {changed: clothingChanged || mannequinChanged, mannequinChanged, removed}; +}; + +// Make a clothing item unavailable to the selected animal types. `world` +// refreshes games and den visitors after the persistent state is cleaned. +const setWearRule = (id, blockedTypes, world) => { + const found = item("clothing", id); + if (found.error) { + return found; + } + const animals = wearAnimals(); + const allowed = new Set(animals.map(animal => animal.id)); + if (!Array.isArray(blockedTypes) || blockedTypes.length > allowed.size || !blockedTypes.every(Number.isInteger) + || blockedTypes.some(type => !allowed.has(type))) { + return {error: "Choose only animals from the list."}; + } + const blocked = [...new Set(blockedTypes)].sort((one, two) => one - two); + const changedRule = wearRules.setBlockedTypes(found.id, blocked).changed; + let accountsChanged = 0; + let removed = 0; + const blockedSet = new Set(blocked); + for (const account of accounts.all()) { + const cleaned = removeBlockedUses(account, found.id, blockedSet); + if (!cleaned.changed) { + continue; + } + accountsChanged++; + removed += cleaned.removed; + accounts.save(account); + world.wearRulesChanged(account, cleaned.mannequinChanged); + } + // Packs downloaded after this moment, and games already open, use the + // same rule-to-flag transformation. Server checks above remain authority. + defpacks.invalidateClientItemPack(); + customItems.sendClothingDefs([found.id]); + const animalNames = blocked.map(type => animals.find(animal => animal.id === type).name); + const subject = describe(found.kind, found.id); + const suffix = blocked.length ? `cannot be worn by ${animalNames.join(", ")}.` : "can be worn by every animal again."; + return {ok: `${subject} ${suffix}${removed ? ` Took it off ${removed} existing use${removed === 1 ? "" : "s"}.` : ""}`, + detail: `clothing ${found.id}; blocked types ${blocked.join(",") || "none"}; ${accountsChanged} account${accountsChanged === 1 ? "" : "s"} changed`, changed: changedRule}; +}; + // every one of an item an account has, out of its inventory (and its trade // list). `world` tells a game playing (lib/world.js itemsTaken). returns how // many went. @@ -135,7 +224,10 @@ const deleteCustom = (kind, id, world) => { if (lockSet().delete(key(kind, entry.id))) { saveLocks(); } + if (kind === "clothing") { + wearRules.forget(entry.id); + } return {ok: `Deleted ${entry.name} (${kind === "den" ? "den item" : "clothing"} ${entry.id})${count ? `, and took ${count} from players` : ""}.`}; }; -module.exports = {isLocked, setLocked, lockedList, take, deleteCustom}; +module.exports = {isLocked, setLocked, lockedList, wearAnimals, wearRuleList, setWearRule, take, deleteCustom}; diff --git a/lib/manage.js b/lib/manage.js index 32eef7c..79655ce 100644 --- a/lib/manage.js +++ b/lib/manage.js @@ -22,6 +22,7 @@ const masterpieces = require("./masterpieces.js"); const defpacks = require("./defpacks.js"); const support = require("./support.js"); const totp = require("./totp.js"); +const recoveryMail = require("./recoverymail.js"); const world = require("./world.js"); // the account page at /account: what a player can do about their own @@ -50,6 +51,8 @@ const discordCookie = (value, maxAgeSeconds) => const SESSION_HOURS = 12; const TEN_MINUTES_MS = 600000; const MAX_NOTE = 120; +const RECOVERY_TOKEN_MS = 30 * 60 * 1000; +const recoveryHash = token => crypto.createHash("sha256").update(token).digest("hex"); // wrong passwords before further tries from an address are refused for a // while, as for the launcher's sign-in (lib/http.js). @@ -59,6 +62,7 @@ const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_M // at it and is then signed out. const WRONG_PASSWORDS_ALLOWED = 5; const wrongPasswords = limits.limiter(WRONG_PASSWORDS_ALLOWED, TEN_MINUTES_MS); +const recoveryRequests = limits.limiter(5, TEN_MINUTES_MS); // what may be done from the page of a ban (above). const BANNED_MAY = ["password", "twoStepStart", "twoStepConfirm", "twoStepOff", "forgetDevices", "delete", "appeal"]; // and from the page of a rejected username: the same, with a new name in @@ -142,6 +146,7 @@ const bannedProfile = (account, ban) => { appeal: appeal && {createdAt: appeal.createdAt, text: appeal.text, status: appeal.status, reply: appeal.reply, handledAt: appeal.handledAt}, appealLimit: bans.MAX_APPEAL, twoStep: twoStepOf(account), + recoveryEmail: account.recoveryEmail ? `${account.recoveryEmail.slice(0, 2)}…${account.recoveryEmail.slice(account.recoveryEmail.lastIndexOf("@"))}` : "", }; }; @@ -177,6 +182,7 @@ const profile = (account, from) => { banned: null, locked: account.locked, twoStep: twoStepOf(account), + recoveryEmail: account.recoveryEmail ? `${account.recoveryEmail.slice(0, 2)}…${account.recoveryEmail.slice(account.recoveryEmail.lastIndexOf("@"))}` : "", discord: account.discord, discordLinked: Boolean(account.discordId), discordLinking: discord.linking(), @@ -204,7 +210,7 @@ const profile = (account, from) => { // hash, the 2FA secret, device passes), and what other tables hold of it. // what others wrote about it (reports, a moderator's notes) is not theirs // to be handed, and is not here. -const SECRET_FIELDS = ["salt", "hash", "totp", "totpSetup", "devices", "modNotes"]; +const SECRET_FIELDS = ["salt", "hash", "totp", "totpSetup", "devices", "modNotes", "recoveryTokens"]; const dataOf = account => ({ exportedAt: new Date().toISOString(), server: config.baseUrl, @@ -524,6 +530,10 @@ const handle = async (req, res, url, from, web) => { web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "account.html"))), "text/html; charset=utf-8"); return; } + if (route === "GET /account/recover") { + web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "recover.html"))), "text/html; charset=utf-8"); + return; + } if (req.method === "POST" && !sameOrigin(req)) { reply(403, {error: "forbidden"}); return; @@ -531,6 +541,67 @@ const handle = async (req, res, url, from, web) => { const body = req.method === "POST" ? await web.readJson(req) : {}; switch (route) { + case "POST /account/api/recover/request": { + // Always give the same reply: neither account names nor email addresses + // can be discovered from this endpoint. + if (!from.local && !recoveryRequests.allow(from.key)) { + reply(429, {ok: "If the account and recovery email match, we sent a recovery link."}); + return; + } + const account = accounts.byName(String(body.username || "")); + const email = String(body.email || "").trim().toLowerCase(); + const kind = body.kind === "twoStep" ? "twoStep" : "password"; + if (account && account.recoveryEmail && account.recoveryEmail === email && recoveryMail.available()) { + const token = crypto.randomBytes(32).toString("hex"); + account.recoveryTokens = (account.recoveryTokens || []).filter(entry => entry.expires > Date.now()); + account.recoveryTokens.push({hash: recoveryHash(token), kind, expires: Date.now() + RECOVERY_TOKEN_MS}); + accounts.save(account); + const link = new URL(`/account/recover?token=${token}`, config.siteUrl).href; + const sent = await recoveryMail.send({to: account.recoveryEmail, subject: "Burrow account recovery", + text: `A ${kind === "twoStep" ? "2FA reset" : "password reset"} was requested for ${account.username}. Open this link within 30 minutes:\n${link}\n\nIf this was not you, ignore this email.`}); + if (!sent) { + account.recoveryTokens = account.recoveryTokens.filter(entry => entry.hash !== recoveryHash(token)); + accounts.save(account); + } + } + reply(200, {ok: "If the account and recovery email match, we sent a recovery link."}); + return; + } + case "POST /account/api/recover/check": { + const token = String(body.token || ""); + const account = [...accounts.all()].find(candidate => (candidate.recoveryTokens || []).some(entry => entry.hash === recoveryHash(token) && entry.expires > Date.now())); + const entry = account && account.recoveryTokens.find(candidate => candidate.hash === recoveryHash(token) && candidate.expires > Date.now()); + reply(entry ? 200 : 400, entry ? {kind: entry.kind} : {error: "This recovery link is invalid or expired."}); + return; + } + case "POST /account/api/recover/complete": { + const token = String(body.token || ""); + const account = [...accounts.all()].find(candidate => (candidate.recoveryTokens || []).some(entry => entry.hash === recoveryHash(token) && entry.expires > Date.now())); + const entry = account && account.recoveryTokens.find(candidate => candidate.hash === recoveryHash(token) && candidate.expires > Date.now()); + if (!entry) { + reply(400, {error: "This recovery link is invalid or expired."}); + return; + } + if (entry.kind === "password") { + const problem = accounts.setPassword(account, body.password); + if (problem) { + reply(400, {error: problem === "weak_password" ? "That password is too easy to guess." : "Use 10+ characters with an uppercase letter, lowercase letter and digit."}); + return; + } + } + else if (totp.isOn(account)) { + totp.turnOff(account); + accounts.revokeTokens(account); + } + account.recoveryTokens = []; + accounts.save(account); + signOutOthers(account, null); + endStaffSessions(account); + world.moderation.actions.kick(account); + console.log(`[recovery] ${logText(entry.kind)} reset for "${logText(account.username)}" after email verification from ${logText(from.address)}`); + reply(200, {ok: entry.kind === "password" ? "Password reset. You can sign in now." : "2FA reset. You can sign in now."}); + return; + } case "POST /account/api/login": { const key = String(body.username || "").trim().toLowerCase(); if (!from.local && failuresByAddress.blocked(from.key)) { diff --git a/lib/masterpieces.js b/lib/masterpieces.js index 09cede5..1ad1a03 100644 --- a/lib/masterpieces.js +++ b/lib/masterpieces.js @@ -41,6 +41,7 @@ const SCHEMA = ` status INTEGER NOT NULL, frame INTEGER NOT NULL, reviewed_at INTEGER, + reviewed_by TEXT, likes TEXT NOT NULL, image BLOB NOT NULL ); @@ -81,11 +82,16 @@ const uploadsPerHour = limits.limiter(30, 3600000); const now = () => Math.floor(Date.now() / 1000); const db = () => accounts.database(); -const known = new Map(); // id -> {id, creator, createdAt, status, frame, likes: [account ids]} +const known = new Map(); // id -> {id, creator, createdAt, status, frame, reviewedAt, reviewedBy, likes: [account ids]} const tokens = new Map(); // upload token -> {account id, expires (ms)} const load = () => { db().exec(SCHEMA); + // who approved it: a moderator's username, "admin", or null when nobody + // looked (review was off, or it was approved before this was kept). + if (!db().prepare("PRAGMA table_info(masterpieces)").all().some(column => column.name === "reviewed_by")) { + db().exec("ALTER TABLE masterpieces ADD COLUMN reviewed_by TEXT"); + } fs.mkdirSync(folder(), {recursive: true}); // pictures still in the table move out into files, once. for (const row of db().prepare("SELECT id FROM masterpieces WHERE length(image) > 0").all()) { @@ -93,8 +99,9 @@ const load = () => { fs.writeFileSync(fileOf(row.id), Buffer.from(picture)); db().prepare("UPDATE masterpieces SET image = ? WHERE id = ?").run(NO_IMAGE, row.id); } - for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, likes FROM masterpieces").all()) { - known.set(row.id, {id: row.id, creator: row.creator_id, createdAt: row.created_at, status: row.status, frame: row.frame, likes: JSON.parse(row.likes)}); + for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, reviewed_at, reviewed_by, likes FROM masterpieces").all()) { + known.set(row.id, {id: row.id, creator: row.creator_id, createdAt: row.created_at, status: row.status, frame: row.frame, + reviewedAt: row.reviewed_at, reviewedBy: row.reviewed_by, likes: JSON.parse(row.likes)}); } }; @@ -203,7 +210,7 @@ const upload = async (token, image) => { forget(painting.id); } } - const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, likes: []}; + const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, reviewedAt: null, reviewedBy: null, likes: []}; fs.writeFileSync(fileOf(painting.id), image); db().prepare("INSERT INTO masterpieces (id, creator_id, created_at, status, frame, likes, image) VALUES (?, ?, ?, ?, ?, '[]', ?)") .run(painting.id, painting.creator, painting.createdAt, painting.status, painting.frame, NO_IMAGE); @@ -211,10 +218,13 @@ const upload = async (token, image) => { return painting.id; }; -const setStatus = (painting, status) => { +// `by`: who approved it, when someone did. +const setStatus = (painting, status, by = null) => { painting.status = status; - db().prepare("UPDATE masterpieces SET status = ?, frame = ?, reviewed_at = ? WHERE id = ?") - .run(status, painting.frame, status === APPROVED ? now() : null, painting.id); + painting.reviewedAt = status === APPROVED ? now() : null; + painting.reviewedBy = status === APPROVED ? by : null; + db().prepare("UPDATE masterpieces SET status = ?, frame = ?, reviewed_at = ?, reviewed_by = ? WHERE id = ?") + .run(status, painting.frame, painting.reviewedAt, painting.reviewedBy, painting.id); }; // may this account make an item of that painting, in that frame? (Step 3, @@ -268,12 +278,13 @@ const mayView = (id, address, addressOf) => { return painting.status === APPROVED || Boolean(maker && addressOf(maker) && addressOf(maker) === address); }; -const approve = id => { +// `by`: the moderator's username, or "admin". +const approve = (id, by) => { const painting = get(id); if (!painting || painting.status !== PENDING) { return false; } - setStatus(painting, APPROVED); + setStatus(painting, APPROVED, by); return true; }; @@ -318,11 +329,14 @@ const gallery = () => { return {pool: hung.slice(0, GALLERY_SPOTS), pluspool: hung.slice(GALLERY_SPOTS)}; }; +// newest first: the waiting ones by when they were made, the approved ones +// by when they were approved, so that one let in by mistake is near the top. const list = status => [...known.values()].filter(painting => painting.status === status) - .sort((one, other) => other.createdAt - one.createdAt) + .sort((one, other) => (other.reviewedAt || other.createdAt) - (one.reviewedAt || one.createdAt)) .map(painting => { const maker = creatorOf(painting.id); - 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, + approvedAt: painting.reviewedAt, approvedBy: painting.reviewedBy}; }); // both lists for the panels, narrowed to makers whose names have @@ -335,6 +349,11 @@ const listsFor = creator => { return {waiting: narrowed(list(PENDING)), approved: narrowed(list(APPROVED))}; }; +// the last `count` approved, the latest first, for the moderator panel to +// take one back from: only the ones `by` approved, when given. +const recentlyApproved = (count, by = "") => list(APPROVED) + .filter(painting => !by || String(painting.approvedBy || "").toLowerCase() === by.toLowerCase()).slice(0, count); + 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 @@ -343,7 +362,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, listsFor, frameList, + load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, recentlyApproved, frameList, needsReview, setNeedsReview, madeBy, PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES, }; diff --git a/lib/modpanel.js b/lib/modpanel.js index cee7603..04d46d7 100644 --- a/lib/modpanel.js +++ b/lib/modpanel.js @@ -1,6 +1,7 @@ "use strict"; const crypto = require("crypto"); +const {execFileSync} = require("child_process"); const fs = require("fs"); const path = require("path"); const accounts = require("./accounts.js"); @@ -15,6 +16,7 @@ const itemArt = require("./itemart.js"); const playerItems = require("./playeritems.js"); const defpacks = require("./defpacks.js"); const devices = require("./devices.js"); +const discordLinks = require("./discord.js"); const limits = require("./limits.js"); const manage = require("./manage.js"); const masterpieces = require("./masterpieces.js"); @@ -24,6 +26,7 @@ const reports = require("./reports.js"); const roles = require("./roles.js"); const staff = require("./staff.js"); const stats = require("./stats.js"); +const sfs = require("./sfs.js"); const support = require("./support.js"); const totp = require("./totp.js"); const world = require("./world.js"); @@ -50,11 +53,15 @@ const world = require("./world.js"); // moderator's name, for the admin panel. const COOKIE = "ajc_mod"; +const DISCORD_COOKIE = "ajc_mod_discord"; const SESSION_HOURS = 12; const TEN_MINUTES_MS = 600000; const MAX_BAN_HOURS = 24 * 365 * 10; const MAX_MESSAGE_LENGTH = 200; const MAX_RECENT_NOTES = 15; +const RECENT_PAINTINGS = 12; +const GIT_STATUS_CACHE_MS = 10000; +const PROJECT_ROOT = path.resolve(__dirname, ".."); const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS); const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator @@ -64,13 +71,75 @@ const addressSearched = new Map(); // moderator's account id -> the address they const sha256 = text => crypto.createHash("sha256").update(text).digest("hex"); +// This is read-only and intentionally never fetches, pulls or pushes. It +// gives staff a conspicuous reminder that the running checkout contains work +// which has not made it to its tracked remote yet. +let gitStatusCachedAt = 0; +let gitStatusCached = null; +const gitUpdateState = () => { + if (gitStatusCached && Date.now() - gitStatusCachedAt < GIT_STATUS_CACHE_MS) { + return gitStatusCached; + } + try { + const runGit = args => execFileSync("git", args, {cwd: PROJECT_ROOT, encoding: "utf8", timeout: 1500, maxBuffer: 128 * 1024}).trim(); + const raw = runGit(["status", "--porcelain=v1", "-z"]); + const entries = raw ? raw.split("\0").filter(Boolean) : []; + const changed = []; + for (let index = 0; index < entries.length; index++) { + const entry = entries[index]; + const status = entry.slice(0, 2); + changed.push({status: status.trim() || "?", path: entry.slice(3)}); + // A rename/copy has another NUL-delimited source path. The destination + // is the useful file to show in the warning. + if (status[0] === "R" || status[0] === "C") { + index++; + } + } + let ahead = 0; + let behind = 0; + let remoteKnown = true; + try { + const [behindText, aheadText] = runGit(["rev-list", "--left-right", "--count", "@{upstream}...HEAD"]).split(/\s+/); + behind = Number(behindText) || 0; + ahead = Number(aheadText) || 0; + } + catch (_) { + remoteKnown = false; + } + gitStatusCached = {available: true, changed, ahead, behind, remoteKnown, + needsPublish: changed.length > 0 || ahead > 0}; + } + catch (err) { + gitStatusCached = {available: false, changed: [], ahead: 0, behind: 0, remoteKnown: false, + needsPublish: false, error: "Git status could not be read."}; + } + gitStatusCachedAt = Date.now(); + return gitStatusCached; +}; + const cookieToken = req => { const match = new RegExp(`(?:^|;\\s*)${COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || ""); return match ? match[1] : null; }; const cookieHeader = (token, maxAgeSeconds) => - `${COOKIE}=${token}; Path=/mod; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`; + `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`; +const discordCookie = (value, maxAgeSeconds) => + `${DISCORD_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`; + +const beginSession = (account, res, address, detail = "") => { + accounts.recordLogin(account, "mod", address); + accounts.save(account); + for (const [hash, session] of sessions) { + if (session.expiry < Date.now()) { + sessions.delete(hash); + } + } + const token = crypto.randomBytes(24).toString("hex"); + sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000}); + res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600)); + modlog.record(account.username, "signed in", "", detail); +}; // may this account use the panel (still)? const mayModerate = account => Boolean(account && roles.isActiveStaff(account, world.moderation.banRemaining(account) !== 0)); @@ -116,10 +185,18 @@ const playerRow = (account, playing) => { 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 => { +// what the Players page's list can be narrowed to (lib/staff.js `keep`). +const ONLY = { + online: (account, online) => online.has(account.username), + banned: account => world.moderation.banRemaining(account) !== 0 || devices.bannedId(account) !== 0, + silenced: account => world.moderation.silenceRemaining(account) !== 0, + staff: account => Boolean(roles.roleOf(account)), +}; + +// by name (lib/staff.js says in what order), and `only` one of ONLY's. +const findPlayers = (query, only) => { const online = playing(); - const {found, total} = staff.findAccounts(query); + const {found, total} = staff.findAccounts(query, Object.hasOwn(ONLY, only) ? ONLY[only] : undefined); return {players: found.map(account => playerRow(account, online)), total}; }; @@ -334,6 +411,38 @@ const handle = async (req, res, url, from, web) => { web.send(res, 200, captcha.withScriptVersion(await stats.withView(await fs.promises.readFile(path.join(config.publicDir, "mod.html")))), "text/html; charset=utf-8"); return; } + // The nonce cookie is Lax only for Discord's cross-site return. The normal + // staff-session cookie remains Strict and is issued after the callback. + if (route === "GET /mod/discord/login") { + if (!discordLinks.linking()) { + res.writeHead(302, {Location: "/dashboard/staff?discord=off"}); + res.end(); + return; + } + const {url: to, nonce} = discordLinks.startStaff(); + res.setHeader("Set-Cookie", discordCookie(nonce, 600)); + res.writeHead(302, {Location: to}); + res.end(); + return; + } + if (route === "GET /mod/discord/callback") { + const nonce = (new RegExp(`(?:^|;\\s*)${DISCORD_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1]; + const result = url.searchParams.get("error") ? {error: "cancelled"} + : await discordLinks.finishStaff(url.searchParams.get("state"), nonce, url.searchParams.get("code")); + if (result.ok && !mayModerate(result.account)) { + result.ok = false; + result.error = "denied"; + } + if (result.ok) { + beginSession(result.account, res, from.address, "through Discord"); + console.log(`[mod] ${result.account.username} signed in with Discord from ${from.address}`); + } + const sessionCookie = res.getHeader("Set-Cookie"); + res.setHeader("Set-Cookie", sessionCookie ? [sessionCookie, discordCookie("", 0)] : discordCookie("", 0)); + res.writeHead(302, {Location: `/dashboard/staff?discord=${result.ok ? "ok" : result.error}`}); + res.end(); + return; + } if (req.method === "POST" && !limits.originAllowed(req)) { reply(403, {error: "forbidden"}); return; @@ -343,7 +452,7 @@ const handle = async (req, res, url, from, web) => { switch (route) { case "GET /mod/api/state": { const mod = signedInAs(req); - reply(200, {signedIn: Boolean(mod), username: mod ? mod.username : ""}); + reply(200, {signedIn: Boolean(mod), username: mod ? mod.username : "", discordLogin: discordLinks.linking()}); return; } // username, password and a code, all three every time. @@ -400,6 +509,50 @@ const handle = async (req, res, url, from, web) => { reply(200, {ok: true, username: account.username}); return; } + // signed in through the game instead: a client the moderator is playing + // in hands over the game's login token, so they need not type their + // password and a code again. taken only for active staff with 2FA on + // (so the game's own sign-in took a code), who are in the game now, and + // asking from the address that game connected from: the token alone, + // copied elsewhere, opens nothing. + case "POST /mod/api/game-login": { + if (!from.local && failuresByAddress.blocked(from.key)) { + reply(429, {error: "Too many attempts. Try later."}); + return; + } + const account = accounts.byToken(body.token); + const session = account ? world.findOnline(account.username) : null; + if (!account || !roles.roleOf(account)) { + failuresByAddress.record(from.key); + reply(401, {error: "Sign in with your password and code."}); + return; + } + if (!totp.isOn(account)) { + reply(403, {error: "Turn on 2FA on your account page first."}); + return; + } + if (!mayModerate(account)) { + reply(403, {error: "This account cannot sign in here now."}); + return; + } + if (!session || limits.key(session.address) !== from.key) { + reply(401, {error: "Be in the game on this computer, or sign in with your password and code."}); + return; + } + accounts.recordLogin(account, "mod", from.address); + accounts.save(account); + for (const [hash, kept] of sessions) { + if (kept.expiry < Date.now()) { + sessions.delete(hash); + } + } + const cookie = crypto.randomBytes(24).toString("hex"); + sessions.set(sha256(cookie), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000}); + res.setHeader("Set-Cookie", cookieHeader(cookie, SESSION_HOURS * 3600)); + modlog.record(account.username, "signed in", "", "through the game"); + reply(200, {ok: true, username: account.username}); + return; + } case "POST /mod/api/logout": { const token = cookieToken(req); if (token) { @@ -462,6 +615,22 @@ const handle = async (req, res, url, from, web) => { reviewRoutes(route.replace(" /mod/api/", " "), body, reply, done, mod.username, "/mod/api/itemart"); return; } + // This deliberately precedes the broad /items branch. Moderators may + // receive the narrow items.restrict permission without also being allowed + // to make, delete, lock or take items. + if (/^\/mod\/api\/items\/wear-rules\/?$/.test(url.pathname)) { + if (!roles.can(mod, "items.restrict")) { + reply(403, {error: "Your role does not allow that."}); + return; + } + // Normalize the harmless trailing-slash spelling before dispatching it. + itemRoutes(`${req.method} items/wear-rules`, url, body, reply, done, { + username: mod.username, + artBase: "/mod/api/itemart", + mayTake: () => false, + }); + return; + } // custom items (lib/customitems.js), for whoever may make them. if (url.pathname.startsWith("/mod/api/items")) { if (!roles.can(mod, "items.create")) { @@ -475,6 +644,32 @@ const handle = async (req, res, url, from, web) => { }); return; } + // Service health is intentionally separate from player data: every staff + // role may see it, including developers who have no player-view access. + if (route === "GET /mod/api/server") { + if (!roles.can(mod, "server.view")) { + reply(403, {error: "Your role does not allow that."}); + return; + } + const memory = process.memoryUsage(); + const players = world.players(); + const rooms = new Set(players.map(player => player.room).filter(Boolean)); + reply(200, { + uptimeSeconds: Math.floor(process.uptime()), + players: players.length, + rooms: rooms.size, + memory: { + rssMb: Math.round(memory.rss / 1048576), + heapUsedMb: Math.round(memory.heapUsed / 1048576), + heapTotalMb: Math.round(memory.heapTotal / 1048576), + }, + sockets: sfs.health(), + update: gitUpdateState(), + now: Date.now(), + }); + return; + } + // everything else shows players and what they did: not for a role that // only makes things. if (!roles.can(mod, "player.view")) { @@ -488,6 +683,7 @@ 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") || ""); @@ -517,7 +713,7 @@ const handle = async (req, res, url, from, web) => { return; } if (searchBy !== "address") { - reply(200, findPlayers(url.searchParams.get("q"))); + reply(200, findPlayers(url.searchParams.get("q"), url.searchParams.get("only"))); return; } // by address: only the address typed, which is written down (once @@ -670,9 +866,12 @@ const handle = async (req, res, url, from, web) => { return; } - // paintings players framed (lib/masterpieces.js). + // paintings players framed (lib/masterpieces.js), and the ones approved + // last, to take one back that should not have been (mine=1: only the + // ones this moderator approved). case "GET /mod/api/masterpieces": - reply(200, {...masterpieces.listsFor(url.searchParams.get("creator")), waitingCount: masterpieces.list(masterpieces.PENDING).length}); + reply(200, {...masterpieces.listsFor(url.searchParams.get("creator")), waitingCount: masterpieces.list(masterpieces.PENDING).length, + recent: masterpieces.recentlyApproved(RECENT_PAINTINGS, url.searchParams.get("mine") === "1" ? mod.username : "")}); return; case "GET /mod/api/masterpiece": { @@ -700,7 +899,7 @@ const handle = async (req, res, url, from, web) => { return; } const result = body.action === "approve" - ? (world.approveMasterpiece(id) ? {ok: "Approved."} : {error: "No such painting waiting."}) + ? (world.approveMasterpiece(id, mod.username) ? {ok: "Approved."} : {error: "No such painting waiting."}) : body.action === "reject" || body.action === "remove" ? (world.removeMasterpiece(id) ? {ok: "Removed for good. Its maker was told and given a Masterpiece Token."} : {error: "No such painting."}) : {error: "Unknown action."}; @@ -723,6 +922,8 @@ const handle = async (req, res, url, from, web) => { // whether it is locked out of the finder: for the dashboards' lock. // GET items/base?kind=clothing|den&id=N: an item of the game's to // make one from (its name and colours), to check before making it. +// GET items/wear-rules?q=WORDS: clothing search results, animal choices and +// current per-animal wear blocks. POST it with {id, blockedTypes} to set. // POST items {action: "create", kind, base, name, cost, members, colors} // or {action: "update", kind, id, and any of name, cost, members, colors, inShop} // or {action: "lock" | "unlock", kind, id}: kept out of the item finder @@ -730,6 +931,21 @@ const handle = async (req, res, url, from, web) => { // or {action: "delete", kind, id}: a custom item, out of the game and every inventory. const itemRoutes = (route, url, body, reply, done, actor) => { switch (route) { + case "GET items/wear-rules": { + const search = new URLSearchParams({kind: "clothing", q: url.searchParams.get("q") || ""}); + const found = admin.search(search, null, true); + const rules = itemControl.wearRuleList(); + const blockedByItem = new Map(rules.map(rule => [rule.id, rule.blockedTypes])); + reply(200, {animals: itemControl.wearAnimals(), rules, total: found.total, + results: found.results.slice(0, 20).map(entry => ({id: entry.id, name: entry.locked ? entry.name.replace(/ \(locked\)$/, "") : entry.name, + custom: entry.id >= customItems.FIRST_ID, blockedTypes: blockedByItem.get(entry.id) || []}))}); + return; + } + case "POST items/wear-rules": { + const result = itemControl.setWearRule(body.id, body.blockedTypes, world); + done(result, result.ok ? "item wear rule changed" : "", "", `clothing ${body.id}`); + return; + } case "GET items": reply(200, {items: customItems.list().map(entry => ({...entry, baseName: customItems.baseName(entry), locked: itemControl.isLocked(entry.kind, entry.id), artUrl: itemArt.urlOf(entry, actor.artBase)})), diff --git a/lib/panel.js b/lib/panel.js index ec9dbf8..21a783f 100644 --- a/lib/panel.js +++ b/lib/panel.js @@ -43,6 +43,7 @@ const {activeAvatar} = require("./player.js"); const PASSWORD_SETTING = "admin_password"; // "salt:hash" const COOKIE = "ajc_admin"; +const DISCORD_COOKIE = "ajc_admin_discord"; const SESSION_HOURS = 12; const MIN_PASSWORD_LENGTH = 8; const MAX_PASSWORD_LENGTH = 200; @@ -112,7 +113,10 @@ const signedIn = req => { }; const cookieHeader = (token, maxAgeSeconds) => - `${COOKIE}=${token}; Path=/admin; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`; + `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`; + +const discordCookie = (value, maxAgeSeconds) => + `${DISCORD_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`; const signIn = res => { for (const [hash, expiry] of sessions) { @@ -144,6 +148,7 @@ const accountRow = (account, playing) => { locked: account.locked, twoStep: totp.isOn(account), discord: account.discord, + adminDashboardAccess: Boolean(account.adminDashboardAccess), bio: account.bio, badges: account.badges, featuresOff: accounts.FEATURES.filter(name => !accounts.featureOn(account, name)), @@ -384,32 +389,12 @@ const act = (account, body) => { const {actions, PERMANENT} = world.moderation; const name = account.username; switch (body.action) { - case "password": { - const passwordProblem = accounts.setPassword(account, body.password); - if (passwordProblem) { - return {error: passwordProblem === "weak_password" ? "That password is too easy to guess: it is a common one, or has your username in it." - : "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."}; - } - actions.kick(account); - manage.forget(account); // their account page too, whoever has it open - modpanel.forget(account); - return {ok: `${name} has a new password and was signed out.`}; - } // the owner locks and unlocks on the account page; this is for when // they cannot. case "unlock": account.locked = false; accounts.save(account); return {ok: `${name} is unlocked.`}; - // for a player who lost their phone and their recovery codes: their - // password alone signs them in again. - case "twoStepOff": - if (!totp.isOn(account)) { - return {error: `${name} does not use 2FA.`}; - } - totp.turnOff(account); - accounts.save(account); - return {ok: `2FA is off for ${name}.`}; case "rename": { world.disconnect(account); manage.forget(account); @@ -549,6 +534,16 @@ const act = (account, body) => { `+${(account.permGrants || []).join(",") || "none"} -${(account.permDenies || []).join(",") || "none"}`); return {ok: `${name}'s permissions are saved.`}; } + case "adminDashboardAccess": { + const on = body.on === true; + if (on && !account.discordId) { + return {error: `${name} must link their Discord account before it can be allowed.`}; + } + account.adminDashboardAccess = on; + accounts.save(account); + modlog.record("admin", on ? "admin dashboard access given" : "admin dashboard access removed", account.username, account.discord || ""); + return {ok: on ? `${name} may now sign in to this dashboard with their linked Discord account.` : `${name}'s Discord dashboard access was removed.`}; + } case "rejectName": actions.rejectName(account, BY); manage.forget(account); @@ -627,6 +622,34 @@ const handle = async (req, res, url, from, web) => { web.send(res, 200, await stats.withView(await fs.promises.readFile(path.join(config.publicDir, "admin.html"))), "text/html; charset=utf-8"); return; } + // Discord redirects do not carry the normal Strict admin cookie, so their + // own short-lived nonce cookie is Lax and scoped to this callback alone. + if (route === "GET /admin/discord/login") { + if (!hasPassword() || !discordLinks.linking()) { + res.writeHead(302, {Location: "/dashboard/admin?discord=off"}); + res.end(); + return; + } + const {url: to, nonce} = discordLinks.startAdmin(); + res.setHeader("Set-Cookie", discordCookie(nonce, 600)); + res.writeHead(302, {Location: to}); + res.end(); + return; + } + if (route === "GET /admin/discord/callback") { + const nonce = (new RegExp(`(?:^|;\\s*)${DISCORD_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1]; + const result = url.searchParams.get("error") ? {error: "cancelled"} + : await discordLinks.finishAdmin(url.searchParams.get("state"), nonce, url.searchParams.get("code")); + if (result.ok) { + signIn(res); + console.log(`[admin] ${logText(result.account.username)} signed in with Discord from ${logText(from.address)}`); + } + const adminCookie = res.getHeader("Set-Cookie"); + res.setHeader("Set-Cookie", adminCookie ? [adminCookie, discordCookie("", 0)] : discordCookie("", 0)); + res.writeHead(302, {Location: `/dashboard/admin?discord=${result.ok ? "ok" : result.error}`}); + res.end(); + return; + } if (req.method === "POST" && !sameOrigin(req)) { reply(403, {error: "forbidden"}); return; @@ -635,7 +658,7 @@ const handle = async (req, res, url, from, web) => { switch (route) { case "GET /admin/api/state": - reply(200, {needsSetup: !hasPassword(), needsSetupCode: !from.local, signedIn: signedIn(req)}); + reply(200, {needsSetup: !hasPassword(), needsSetupCode: !from.local, signedIn: signedIn(req), discordLogin: discordLinks.linking()}); return; // choosing the first password. whoever is at the server's own machine may; @@ -963,7 +986,7 @@ const handle = async (req, res, url, from, web) => { : "New masterpieces are approved as they are made. Ones already waiting still wait."}; } else if (body.action === "approve") { - result = world.approveMasterpiece(id) ? {ok: "Approved. Its maker has been told and can hang it now."} : {error: "No such painting waiting."}; + result = world.approveMasterpiece(id, "admin") ? {ok: "Approved. Its maker has been told and can hang it now."} : {error: "No such painting waiting."}; } else if (body.action === "reject" || body.action === "remove") { result = world.removeMasterpiece(id) diff --git a/lib/recoverymail.js b/lib/recoverymail.js new file mode 100644 index 0000000..8a4abae --- /dev/null +++ b/lib/recoverymail.js @@ -0,0 +1,21 @@ +"use strict"; + +const config = require("../config.js"); + +const send = async ({to, subject, text}) => { + if (!config.recoveryMail) { + return false; + } + try { + const response = await fetch(config.recoveryMail.url, {method: "POST", headers: { + "Content-Type": "application/json", "Authorization": `Bearer ${config.recoveryMail.token}`, + }, body: JSON.stringify({to, subject, text})}); + return response.ok; + } + catch (err) { + console.error("[recovery] email delivery failed"); + return false; + } +}; + +module.exports = {available: () => Boolean(config.recoveryMail), send}; diff --git a/lib/roles.js b/lib/roles.js index e621b94..74b37a7 100644 --- a/lib/roles.js +++ b/lib/roles.js @@ -15,6 +15,7 @@ const totp = require("./totp.js"); // higher up, and for the admin in the end. const PERMISSIONS = { + "server.view": "see read-only server health in the moderator panel", "player.view": "see players, chat, reports, requests, bans and paintings in the moderator panel, and keep notes on players (!note, !notes)", "staff.list": "see which staff are online (!staff)", "player.warn": "warn a player, take a warning back, send them a message and mark a report dealt with (!warn, !unwarn, !warnings, !message)", @@ -27,14 +28,17 @@ const PERMISSIONS = { "player.names": "reject or accept a name, answer requests for a new one, clear a bio, remove a player's Jammer Wall posts", "address.ban": "ban the address a player last signed in from, or the computers they use, and lift those bans", "items.approve": "approve or turn away the items and pictures players make, when the admin has asked for that", + "items.restrict": "stop a clothing item from being worn by selected animal types", "items.create": "make new items from the game's art, change and delete them, lock items out of the item finder and take items from players (!item, !lock, !unlock, !locked, !take)", + "room.effects": "run temporary room-wide size and colour effects (!roomfx)", + "theater.control": "play or stop a YouTube video for everyone in the theatre", }; -const HELPER = ["player.view", "staff.list", "player.warn", "player.goto", "chat.silence"]; -const MODERATOR = [...HELPER, "player.kick", "player.summon", "staff.invisible", "player.ban", "player.names", "address.ban", "items.approve"]; -const ADMIN = [...MODERATOR, "items.create"]; +const HELPER = ["server.view", "player.view", "staff.list", "player.warn", "player.goto", "chat.silence"]; +const MODERATOR = [...HELPER, "player.kick", "player.summon", "staff.invisible", "player.ban", "player.names", "address.ban", "items.approve", "items.restrict", "theater.control"]; +const ADMIN = [...MODERATOR, "items.create", "room.effects"]; // a developer makes things, and moderates nobody. -const DEVELOPER = ["staff.list", "items.create"]; +const DEVELOPER = ["server.view", "staff.list", "items.create", "room.effects", "theater.control"]; const ROLES = { developer: {rank: 1, label: "Developer", permissions: DEVELOPER}, diff --git a/lib/sfs.js b/lib/sfs.js index ab37fe9..9dc0d73 100644 --- a/lib/sfs.js +++ b/lib/sfs.js @@ -28,6 +28,8 @@ const SIGNUP_LIFETIME_MS = 5 * 60000; const forLog = message => message.replace(/()/, "$1(hidden)$2"); const connections = new Map(); // remote address -> open sockets +let connectionCount = 0; +const metrics = {accepted: 0, rejected: 0, floodDisconnects: 0, handlerErrors: 0}; let nextUserId = 1; @@ -139,13 +141,18 @@ const start = handlers => new Promise((resolve, reject) => { const onConnection = socket => { const address = limits.key(socket.remoteAddress); const open = connections.get(address) || 0; - const total = [...connections.values()].reduce((sum, count) => sum + count, 0); + // Kept as a counter instead of summing every address on every new socket. + // Under a burst of logins the old O(addresses) work delayed everyone else. + const total = connectionCount; socket.on("error", () => {}); if (open >= config.maxConnectionsPerAddress || total >= config.maxConnections) { + metrics.rejected++; socket.destroy(); return; } connections.set(address, open + 1); + connectionCount++; + metrics.accepted++; const session = new Session(socket); let buffer = Buffer.alloc(0); @@ -179,11 +186,15 @@ const start = handlers => new Promise((resolve, reject) => { } bytesInWindow += chunk.length; if (bytesInWindow > config.maxBytesPerTenSeconds) { + metrics.floodDisconnects++; console.log(`[game] ${logText(session.name)} disconnected for flooding`); socket.destroy(); return; } - buffer = Buffer.concat([buffer, chunk]); + // Node normally gives complete SmartFox packets in one chunk. Avoiding + // Buffer.concat in that common case reduces allocation and GC during + // busy logins; fragments still retain the exact old behaviour. + buffer = buffer.length === 0 ? chunk : Buffer.concat([buffer, chunk]); let end; while ((end = buffer.indexOf(0)) !== -1) { if (end > MAX_MESSAGE) { @@ -191,6 +202,7 @@ const start = handlers => new Promise((resolve, reject) => { return; } if (++messagesInWindow > config.maxMessagesPerTenSeconds) { + metrics.floodDisconnects++; console.log(`[game] ${logText(session.name)} disconnected for flooding`); socket.destroy(); return; @@ -201,6 +213,7 @@ const start = handlers => new Promise((resolve, reject) => { dispatch(session, message); } catch (err) { + metrics.handlerErrors++; // one line a failure, and an end to them: a client that sends // nonsense in a loop is not to fill the log. const where = String(err.stack || "").split("\n")[1] || ""; @@ -229,6 +242,7 @@ const start = handlers => new Promise((resolve, reject) => { else { connections.delete(address); } + connectionCount = Math.max(0, connectionCount - 1); console.log(`[game] ${logText(session.name)} disconnected`); // nothing thrown while a player is seen off may take the server down. try { @@ -277,4 +291,15 @@ const start = handlers => new Promise((resolve, reject) => { }); }); -module.exports = {start}; +// This intentionally exposes counts only: staff can see whether the service +// is healthy without receiving player addresses or packet contents. +const health = () => ({ + openConnections: connectionCount, + connectedAddresses: connections.size, + accepted: metrics.accepted, + rejected: metrics.rejected, + floodDisconnects: metrics.floodDisconnects, + handlerErrors: metrics.handlerErrors, +}); + +module.exports = {start, health}; diff --git a/lib/wearrules.js b/lib/wearrules.js new file mode 100644 index 0000000..84ea255 --- /dev/null +++ b/lib/wearrules.js @@ -0,0 +1,91 @@ +"use strict"; + +// Loaded only when a rule is read or saved. defpacks.js is imported while +// accounts.js is still defining its exports, so a top-level require here +// would retain that partial `{}` forever. +const accounts = () => require("./accounts.js"); + +// Clothing that staff have said must not be worn by certain animal types. +// This is deliberately its own small module: game code, def packs and the +// dashboards all ask the same source of truth, while itemcontrol.js owns +// validating dashboard input and removing existing uses. + +const SETTING = "clothingWearRules"; + +let rules = null; // Map> + +const positiveInteger = value => Number.isSafeInteger(value) && value > 0; + +const ruleMap = () => { + if (rules) { + return rules; + } + let saved = {}; + try { + const parsed = JSON.parse(accounts().setting(SETTING) || "{}"); + saved = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; + } + catch { + saved = {}; + } + rules = new Map(); + for (const [id, types] of Object.entries(saved)) { + const itemId = Number(id); + if (!positiveInteger(itemId) || !Array.isArray(types)) { + continue; + } + const blocked = new Set(types.map(Number).filter(positiveInteger)); + if (blocked.size) { + rules.set(itemId, blocked); + } + } + return rules; +}; + +const save = () => { + const stored = {}; + for (const [id, types] of [...ruleMap()].sort(([one], [two]) => one - two)) { + stored[id] = [...types].sort((one, two) => one - two); + } + accounts().setSetting(SETTING, JSON.stringify(stored)); +}; + +const blockedTypes = itemId => [...(ruleMap().get(Number(itemId)) || [])].sort((one, two) => one - two); + +const all = () => [...ruleMap()].map(([id]) => ({id, blocked: blockedTypes(id)})).sort((one, two) => one.id - two.id); + +const mayWear = (itemId, avatarType) => !ruleMap().get(Number(itemId))?.has(Number(avatarType)); + +// `types` has already been checked against the avatar definitions by +// itemcontrol.js. Keeping this module generic lets it also be used while a +// def pack is being made, without a defpacks <-> wearrules dependency cycle. +const setBlockedTypes = (itemId, types) => { + const id = Number(itemId); + if (!positiveInteger(id)) { + return {changed: false, blocked: []}; + } + const next = new Set((Array.isArray(types) ? types : []).map(Number).filter(positiveInteger)); + const before = blockedTypes(id); + if (next.size) { + ruleMap().set(id, next); + } + else { + ruleMap().delete(id); + } + const after = blockedTypes(id); + const changed = before.length !== after.length || before.some((type, index) => type !== after[index]); + if (changed) { + save(); + } + return {changed, blocked: after}; +}; + +// Custom clothing ids are never reused, but clearing their rule at deletion +// keeps the setting accurate and avoids showing a stale dashboard entry. +const forget = itemId => { + if (ruleMap().delete(Number(itemId))) { + save(); + } +}; + +module.exports = {blockedTypes, all, mayWear, setBlockedTypes, forget}; diff --git a/public/account.html b/public/account.html index 57c9e10..65bfe24 100644 --- a/public/account.html +++ b/public/account.html @@ -198,7 +198,7 @@

-

No account yet? Create one

+

No account yet? Create one · Forgot password or 2FA?

+ +

@@ -375,7 +385,7 @@