feat(dashboard): unify secure staff administration

Provide a single /dashboard entry point for owner and staff tools, with Discord OAuth sign-in for approved owner accounts and active staff. Add owner-managed dashboard access grants, staff server health and update visibility, filtering, moderation improvements, item controls, and per-animal clothing restrictions.

Replace staff-triggered password and 2FA resets with email-verified account recovery. Persist validated recovery addresses, use short-lived hashed recovery tokens, expose recovery flows in registration and account pages, and keep mail delivery disabled until its webhook configuration is present.

Cover dashboard aliases, recovery restrictions, Discord access, monitoring, item locks, wear rules, and staff behavior with regression tests.
This commit is contained in:
Snipzil committed 2026-10-19 10:09:35 -04:00
1 parent 4997315239
commit 7dee29010a
27 files changed
+2303 -346

No files matched your search

+4
View File
@@ -1,6 +1,10 @@
# Burrow # Burrow
Burrow is a private server for AJ Classic. 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 # 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. 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.
+12 -2
View File
@@ -102,6 +102,13 @@ module.exports = {
turnstile: env.AJ_TURNSTILE_SITE_KEY && env.AJ_TURNSTILE_SECRET turnstile: env.AJ_TURNSTILE_SITE_KEY && env.AJ_TURNSTILE_SECRET
? {siteKey: env.AJ_TURNSTILE_SITE_KEY, secret: env.AJ_TURNSTILE_SECRET} : null, ? {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 // 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. // cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only.
upstreamContent: env.AJ_UPSTREAM || "https://ajcontent.akamaized.net/", upstreamContent: env.AJ_UPSTREAM || "https://ajcontent.akamaized.net/",
@@ -115,8 +122,11 @@ module.exports = {
// before is still kept out). // before is still kept out).
requireDevice: env.AJ_REQUIRE_DEVICE !== "0", requireDevice: env.AJ_REQUIRE_DEVICE !== "0",
// Discord (lib/discord.js): an application's id and secret for linking a // 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 // player's Discord account on the account page and for allowed accounts to
// be <siteUrl>account/discord/callback), and a bot in Burrow's Discord // sign in to /dashboard/admin (OAuth2 redirects:
// <siteUrl>account/discord/callback,
// <siteUrl>dashboard/admin/discord/callback, and
// <siteUrl>dashboard/staff/discord/callback), and a bot in Burrow's Discord
// server for the booster badge. linking is off without the first two, the // server for the booster badge. linking is off without the first two, the
// booster badge left alone without the last two. // booster badge left alone without the last two.
discord: { discord: {
+8
View File
@@ -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). // the whole message left out (see account.filter below).
const DEFAULT_FILTER = {level: 1, mode: 1, words: ""}; const DEFAULT_FILTER = {level: 1, mode: 1, words: ""};
const MAX_PASSWORD_LENGTH = 100; 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 // parts of the game a player can switch off for their own account, each
// enforced where the game asks for it (featureOn below). // enforced where the game asks for it (featureOn below).
// the Early Member badge (lib/badges.js) goes to an account made while // 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). // 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.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.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.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.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 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))) { if (account.discordId !== undefined && !/^\d{5,25}$/.test(String(account.discordId))) {
delete account.discordId; // the linked Discord account's id 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.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 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 // 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, activeAvatar: 1,
// early Member, for an account made while there are no more than a hundred. // early Member, for an account made while there are no more than a hundred.
badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [], 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)})`); console.log(`[accounts] registered "${logText(username)}" (id ${logText(account.id)})`);
return {account}; return {account};
+5 -2
View File
@@ -257,7 +257,10 @@ const handle = async (route, params, body, from) => {
if (device && devices.banOf(device)) { if (device && devices.banOf(device)) {
return {status: 403, body: {error: "device_banned"}}; 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: // the terms and the privacy policy, and old enough to agree to them:
// said by the one signing up, on the page or in the client. // said by the one signing up, on the page or in the client.
if ((body || {}).agreed !== true) { if ((body || {}).agreed !== true) {
@@ -279,7 +282,7 @@ const handle = async (route, params, body, from) => {
if (!STARTER_ANIMALS.includes(avatarType)) { if (!STARTER_ANIMALS.includes(avatarType)) {
return {status: 400, body: {error: "choose_animal"}}; 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) { if (result.account) {
result.account.agreed = {version: config.termsVersion, at: Math.floor(Date.now() / 1000)}; result.account.agreed = {version: config.termsVersion, at: Math.floor(Date.now() / 1000)};
accounts.save(result.account); accounts.save(result.account);
+43 -2
View File
@@ -8,6 +8,7 @@ const config = require("../config.js");
const sales = require("./sales.js"); const sales = require("./sales.js");
const badges = require("./badges.js"); const badges = require("./badges.js");
const extraMusic = require("./extramusic.js"); const extraMusic = require("./extramusic.js");
const wearRules = require("./wearrules.js");
// defPack ids, from loader.DefPacksDefHelper in the client. // defPack ids, from loader.DefPacksDefHelper in the client.
const DEF_ITEM = 1000; const DEF_ITEM = 1000;
@@ -42,6 +43,7 @@ const DEF_PET_TOY = 1063;
const DEF_WORLD_ITEMS = 1064; const DEF_WORLD_ITEMS = 1064;
const DEF_NPC = 1025; const DEF_NPC = 1025;
const DEF_NAMEBAR_BADGE = 1049; const DEF_NAMEBAR_BADGE = 1049;
const DEF_EMOTICON = 1036;
const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items: plain, mannequin const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items: plain, mannequin
const DEN_ITEM_MASTERPIECE = 2725; const DEN_ITEM_MASTERPIECE = 2725;
@@ -70,6 +72,32 @@ const LAYER_EYES = "3";
const TYPE_CLOTHING = "1"; const TYPE_CLOTHING = "1";
const EVERY_AVATAR = "9007199254740991"; // avatarUseFlags with a bit set for each animal type 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 // 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, // build on the CDN still has (lib/cdn.js looks there): the Summer Carnival,
// dropped after build 1828. // dropped after build 1828.
@@ -317,9 +345,9 @@ const alwaysOnSale = (pack, ids) => {
// the rows put back or added (SHARED_CHANGES). // the rows put back or added (SHARED_CHANGES).
const CLIENT_PACKS = new Map([ const CLIENT_PACKS = new Map([
[DEF_ITEM, pack => { [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)) { if (def.type === TYPE_CLOTHING || (def.type === "0" && def.layerId === LAYER_EYES)) {
def.avatarUseFlags = EVERY_AVATAR; pack[key] = clientItemRow(def);
} }
} }
sales.stamp("clothing", pack); sales.stamp("clothing", pack);
@@ -397,6 +425,9 @@ let musicIds = []; // den items that are music tracks
let roomDefsById = new Map(); let roomDefsById = new Map();
let badgeIds = []; // name tag badges, ascending let badgeIds = []; // name tag badges, ascending
let npcDefs = new Map(); // the characters of the adventures, see lib/disguises.js 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 // A pack whose feature can be done without: missing (offline and never
// cached) just leaves that feature empty. // cached) just leaves that feature empty.
@@ -463,6 +494,7 @@ const init = async () => {
petFoodDefs = await loadOptional(DEF_PET_FOOD); petFoodDefs = await loadOptional(DEF_PET_FOOD);
petToyDefs = await loadOptional(DEF_PET_TOY); petToyDefs = await loadOptional(DEF_PET_TOY);
npcDefs = new Map((await loadOptional(DEF_NPC)).map(def => [Number(def.id), def])); 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 => { partyDefs = new Map((await loadOptional(DEF_PARTY)).map(def => {
const room = roomPathsById.get(Number(def.roomDefId)); const room = roomPathsById.get(Number(def.roomDefId));
return [Number(def.id), { return [Number(def.id), {
@@ -544,6 +576,14 @@ module.exports = {
denItemDef: id => denItemDefs.get(Number(id)), denItemDef: id => denItemDefs.get(Number(id)),
denItemIds: () => denItemIds, denItemIds: () => denItemIds,
clientPack, 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]) : ""), string: id => (Object.hasOwn(strings, id) ? String(strings[id]) : ""),
stringId: text => { stringId: text => {
if (!stringIds) { if (!stringIds) {
@@ -558,6 +598,7 @@ module.exports = {
}, },
badgeIds: () => badgeIds, badgeIds: () => badgeIds,
npcDef: id => npcDefs.get(Number(id)), npcDef: id => npcDefs.get(Number(id)),
emoticonMediaId: id => emoticonMediaIds.get(Number(id)) || 0,
oddDenItemIds: () => oddDenItemIds, oddDenItemIds: () => oddDenItemIds,
// den items that exist to be given by id and are in no shop. // den items that exist to be given by id and are in no shop.
unsoldDenItemIds: () => extraMusic.ids, unsoldDenItemIds: () => extraMusic.ids,
+99 -9
View File
@@ -35,27 +35,57 @@ const BOOSTER = "booster";
const linking = () => Boolean(config.discord.clientId && config.discord.clientSecret); const linking = () => Boolean(config.discord.clientId && config.discord.clientSecret);
const boostChecks = () => Boolean(config.discord.botToken && config.discord.guildId); const boostChecks = () => Boolean(config.discord.botToken && config.discord.guildId);
const redirectUri = () => `${config.siteUrl}account/discord/callback`; 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 // a link under way: state (in Discord's address) -> {accountId, nonce (in a
// cookie of the browser that asked), expires}. both must come back. // cookie of the browser that asked), expires}. both must come back.
const states = new Map(); const states = new Map();
const adminStates = new Map();
const staffStates = new Map();
const start = account => { const newState = statesMap => {
for (const [state, entry] of states) { for (const [state, entry] of statesMap) {
if (entry.expires < Date.now()) { if (entry.expires < Date.now()) {
states.delete(state); statesMap.delete(state);
} }
} }
if (states.size >= MAX_STATES) { if (statesMap.size >= MAX_STATES) {
states.delete(states.keys().next().value); statesMap.delete(statesMap.keys().next().value);
} }
const state = crypto.randomBytes(24).toString("hex"); const state = crypto.randomBytes(24).toString("hex");
const nonce = 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); const url = new URL(AUTHORIZE);
url.search = new URLSearchParams({client_id: config.discord.clientId, response_type: "code", scope: "identify", url.search = new URLSearchParams({client_id: config.discord.clientId, response_type: "code", scope: "identify",
redirect_uri: redirectUri(), state, prompt: "consent"}).toString(); redirect_uri: redirect, state, prompt: "consent"}).toString();
return {url: url.href, nonce}; 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 = {}) => { 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. // the link undone, by the player or an admin; the booster badge goes with it.
const unlink = account => { const unlink = account => {
const had = Boolean(account.discordId || account.discord); 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};
+60 -5
View File
@@ -50,6 +50,19 @@ const MIME = {
".otf": "font/otf", ".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 = () => ({ const flashVars = () => ({
content: config.baseUrl, content: config.baseUrl,
// the game's own server to the SWF, whatever its name: it loads the card // 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) // member or not may be chosen on any server (lib/accounts.js)
membershipChoice: true, membershipChoice: true,
smoke_version: config.deployVersion, 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, startupRoom: config.startupRoom,
// "-1" turns the client's stats socket off. // "-1" turns the client's stats socket off.
sbStatTrackerIp: "-1", sbStatTrackerIp: "-1",
@@ -293,7 +306,7 @@ const repeatedError = text => {
const THEMED_ROOM = /^(\d+)\/roomDefs\/theme_(\d+)\/(.+)$/; const THEMED_ROOM = /^(\d+)\/roomDefs\/theme_(\d+)\/(.+)$/;
// the web pages, as against what the game and the client load // 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 // the installers /download offers, those of them config.downloadsDir has
const DOWNLOADS = [ const DOWNLOADS = [
@@ -652,22 +665,54 @@ const handle = async (req, res) => {
return; 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 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: // 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 // 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 // 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. // request ever this machine's own, wherever it came from.
if (!limits.hostAllowed(req)) { if (!limits.hostAllowed(req)) {
if (isAdmin || isAccount || isMod) { if (isDashboard || isAdmin || isAccount || isMod) {
send(res, 421, {error: "wrong_host"}); send(res, 421, {error: "wrong_host"});
return; return;
} }
from.local = false; 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 // 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 // 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). // 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"); send(res, 404, "Not found", "text/plain");
return; 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") { if (url.pathname === "/admin/api/itemart") {
res.setHeader("Cache-Control", "no-store"); res.setHeader("Cache-Control", "no-store");
await itemArtUpload(req, res, url, from, null, panel.signedIn); 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 // and the moderator panel (lib/modpanel.js), which is there for anyone to
// reach: its moderators are players, wherever they are. // 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") { if (isMod && url.pathname === "/mod/api/itemart") {
res.setHeader("Cache-Control", "no-store"); res.setHeader("Cache-Control", "no-store");
await itemArtUpload(req, res, url, from, modpanel.signedInAs); await itemArtUpload(req, res, url, from, modpanel.signedInAs);
+93 -1
View File
@@ -3,6 +3,7 @@
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const customItems = require("./customitems.js"); const customItems = require("./customitems.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const wearRules = require("./wearrules.js");
// what staff who make items (items.create: admins and developers) may do // what staff who make items (items.create: admins and developers) may do
// about who has them: // about who has them:
@@ -83,6 +84,94 @@ const lockedList = () => [...lockSet()].map(entry => {
return {kind, id: Number(id), name: nameOf(kind, id)}; 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 // 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 // list). `world` tells a game playing (lib/world.js itemsTaken). returns how
// many went. // many went.
@@ -135,7 +224,10 @@ const deleteCustom = (kind, id, world) => {
if (lockSet().delete(key(kind, entry.id))) { if (lockSet().delete(key(kind, entry.id))) {
saveLocks(); 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` : ""}.`}; 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};
+72 -1
View File
@@ -22,6 +22,7 @@ const masterpieces = require("./masterpieces.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const support = require("./support.js"); const support = require("./support.js");
const totp = require("./totp.js"); const totp = require("./totp.js");
const recoveryMail = require("./recoverymail.js");
const world = require("./world.js"); const world = require("./world.js");
// the account page at /account: what a player can do about their own // 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 SESSION_HOURS = 12;
const TEN_MINUTES_MS = 600000; const TEN_MINUTES_MS = 600000;
const MAX_NOTE = 120; 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 // wrong passwords before further tries from an address are refused for a
// while, as for the launcher's sign-in (lib/http.js). // 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. // at it and is then signed out.
const WRONG_PASSWORDS_ALLOWED = 5; const WRONG_PASSWORDS_ALLOWED = 5;
const wrongPasswords = limits.limiter(WRONG_PASSWORDS_ALLOWED, TEN_MINUTES_MS); 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). // what may be done from the page of a ban (above).
const BANNED_MAY = ["password", "twoStepStart", "twoStepConfirm", "twoStepOff", "forgetDevices", "delete", "appeal"]; 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 // 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}, appeal: appeal && {createdAt: appeal.createdAt, text: appeal.text, status: appeal.status, reply: appeal.reply, handledAt: appeal.handledAt},
appealLimit: bans.MAX_APPEAL, appealLimit: bans.MAX_APPEAL,
twoStep: twoStepOf(account), 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, banned: null,
locked: account.locked, locked: account.locked,
twoStep: twoStepOf(account), twoStep: twoStepOf(account),
recoveryEmail: account.recoveryEmail ? `${account.recoveryEmail.slice(0, 2)}…${account.recoveryEmail.slice(account.recoveryEmail.lastIndexOf("@"))}` : "",
discord: account.discord, discord: account.discord,
discordLinked: Boolean(account.discordId), discordLinked: Boolean(account.discordId),
discordLinking: discord.linking(), discordLinking: discord.linking(),
@@ -204,7 +210,7 @@ const profile = (account, from) => {
// hash, the 2FA secret, device passes), and what other tables hold of it. // 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 // what others wrote about it (reports, a moderator's notes) is not theirs
// to be handed, and is not here. // 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 => ({ const dataOf = account => ({
exportedAt: new Date().toISOString(), exportedAt: new Date().toISOString(),
server: config.baseUrl, 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"); web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "account.html"))), "text/html; charset=utf-8");
return; 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)) { if (req.method === "POST" && !sameOrigin(req)) {
reply(403, {error: "forbidden"}); reply(403, {error: "forbidden"});
return; return;
@@ -531,6 +541,67 @@ const handle = async (req, res, url, from, web) => {
const body = req.method === "POST" ? await web.readJson(req) : {}; const body = req.method === "POST" ? await web.readJson(req) : {};
switch (route) { 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": { case "POST /account/api/login": {
const key = String(body.username || "").trim().toLowerCase(); const key = String(body.username || "").trim().toLowerCase();
if (!from.local && failuresByAddress.blocked(from.key)) { if (!from.local && failuresByAddress.blocked(from.key)) {
+31 -12
View File
@@ -41,6 +41,7 @@ const SCHEMA = `
status INTEGER NOT NULL, status INTEGER NOT NULL,
frame INTEGER NOT NULL, frame INTEGER NOT NULL,
reviewed_at INTEGER, reviewed_at INTEGER,
reviewed_by TEXT,
likes TEXT NOT NULL, likes TEXT NOT NULL,
image BLOB NOT NULL image BLOB NOT NULL
); );
@@ -81,11 +82,16 @@ const uploadsPerHour = limits.limiter(30, 3600000);
const now = () => Math.floor(Date.now() / 1000); const now = () => Math.floor(Date.now() / 1000);
const db = () => accounts.database(); 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 tokens = new Map(); // upload token -> {account id, expires (ms)}
const load = () => { const load = () => {
db().exec(SCHEMA); 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}); fs.mkdirSync(folder(), {recursive: true});
// pictures still in the table move out into files, once. // 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()) { 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)); fs.writeFileSync(fileOf(row.id), Buffer.from(picture));
db().prepare("UPDATE masterpieces SET image = ? WHERE id = ?").run(NO_IMAGE, row.id); 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()) { 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, likes: JSON.parse(row.likes)}); 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); 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); fs.writeFileSync(fileOf(painting.id), image);
db().prepare("INSERT INTO masterpieces (id, creator_id, created_at, status, frame, likes, image) VALUES (?, ?, ?, ?, ?, '[]', ?)") 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); .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; return painting.id;
}; };
const setStatus = (painting, status) => { // `by`: who approved it, when someone did.
const setStatus = (painting, status, by = null) => {
painting.status = status; painting.status = status;
db().prepare("UPDATE masterpieces SET status = ?, frame = ?, reviewed_at = ? WHERE id = ?") painting.reviewedAt = status === APPROVED ? now() : null;
.run(status, painting.frame, status === APPROVED ? now() : null, painting.id); 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, // 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); 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); const painting = get(id);
if (!painting || painting.status !== PENDING) { if (!painting || painting.status !== PENDING) {
return false; return false;
} }
setStatus(painting, APPROVED); setStatus(painting, APPROVED, by);
return true; return true;
}; };
@@ -318,11 +329,14 @@ const gallery = () => {
return {pool: hung.slice(0, GALLERY_SPOTS), pluspool: hung.slice(GALLERY_SPOTS)}; 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) 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 => { .map(painting => {
const maker = creatorOf(painting.id); 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 // 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))}; 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); const madeBy = account => [...known.values()].filter(painting => painting.creator === account.id).map(painting => painting.id);
// generic lists: (mediaId, name string id) pairs, or null when `listId` is // generic lists: (mediaId, name string id) pairs, or null when `listId` is
@@ -343,7 +362,7 @@ const frameList = listId =>
([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null); ([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null);
module.exports = { module.exports = {
load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, frameList, load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, recentlyApproved, frameList,
needsReview, setNeedsReview, madeBy, needsReview, setNeedsReview, madeBy,
PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES, PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES,
}; };
+225 -9
View File
@@ -1,6 +1,7 @@
"use strict"; "use strict";
const crypto = require("crypto"); const crypto = require("crypto");
const {execFileSync} = require("child_process");
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
@@ -15,6 +16,7 @@ const itemArt = require("./itemart.js");
const playerItems = require("./playeritems.js"); const playerItems = require("./playeritems.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const devices = require("./devices.js"); const devices = require("./devices.js");
const discordLinks = require("./discord.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const manage = require("./manage.js"); const manage = require("./manage.js");
const masterpieces = require("./masterpieces.js"); const masterpieces = require("./masterpieces.js");
@@ -24,6 +26,7 @@ const reports = require("./reports.js");
const roles = require("./roles.js"); const roles = require("./roles.js");
const staff = require("./staff.js"); const staff = require("./staff.js");
const stats = require("./stats.js"); const stats = require("./stats.js");
const sfs = require("./sfs.js");
const support = require("./support.js"); const support = require("./support.js");
const totp = require("./totp.js"); const totp = require("./totp.js");
const world = require("./world.js"); const world = require("./world.js");
@@ -50,11 +53,15 @@ const world = require("./world.js");
// moderator's name, for the admin panel. // moderator's name, for the admin panel.
const COOKIE = "ajc_mod"; const COOKIE = "ajc_mod";
const DISCORD_COOKIE = "ajc_mod_discord";
const SESSION_HOURS = 12; const SESSION_HOURS = 12;
const TEN_MINUTES_MS = 600000; const TEN_MINUTES_MS = 600000;
const MAX_BAN_HOURS = 24 * 365 * 10; const MAX_BAN_HOURS = 24 * 365 * 10;
const MAX_MESSAGE_LENGTH = 200; const MAX_MESSAGE_LENGTH = 200;
const MAX_RECENT_NOTES = 15; 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 failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS);
const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator
@@ -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"); 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 cookieToken = req => {
const match = new RegExp(`(?:^|;\\s*)${COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || ""); const match = new RegExp(`(?:^|;\\s*)${COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "");
return match ? match[1] : null; return match ? match[1] : null;
}; };
const cookieHeader = (token, maxAgeSeconds) => 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)? // may this account use the panel (still)?
const mayModerate = account => Boolean(account && roles.isActiveStaff(account, world.moderation.banRemaining(account) !== 0)); 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)"])); const playing = () => new Map(world.players().map(player => [player.username, player.room || "(between rooms)"]));
// by name (lib/staff.js says in what order). // what the Players page's list can be narrowed to (lib/staff.js `keep`).
const findPlayers = query => { 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 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}; 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"); 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; 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)) { if (req.method === "POST" && !limits.originAllowed(req)) {
reply(403, {error: "forbidden"}); reply(403, {error: "forbidden"});
return; return;
@@ -343,7 +452,7 @@ const handle = async (req, res, url, from, web) => {
switch (route) { switch (route) {
case "GET /mod/api/state": { case "GET /mod/api/state": {
const mod = signedInAs(req); 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; return;
} }
// username, password and a code, all three every time. // 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}); reply(200, {ok: true, username: account.username});
return; 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": { case "POST /mod/api/logout": {
const token = cookieToken(req); const token = cookieToken(req);
if (token) { 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"); reviewRoutes(route.replace(" /mod/api/", " "), body, reply, done, mod.username, "/mod/api/itemart");
return; 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. // custom items (lib/customitems.js), for whoever may make them.
if (url.pathname.startsWith("/mod/api/items")) { if (url.pathname.startsWith("/mod/api/items")) {
if (!roles.can(mod, "items.create")) { if (!roles.can(mod, "items.create")) {
@@ -475,6 +644,32 @@ const handle = async (req, res, url, from, web) => {
}); });
return; 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 // everything else shows players and what they did: not for a role that
// only makes things. // only makes things.
if (!roles.can(mod, "player.view")) { if (!roles.can(mod, "player.view")) {
@@ -488,6 +683,7 @@ const handle = async (req, res, url, from, web) => {
paintings: masterpieces.list(masterpieces.PENDING).length}); paintings: masterpieces.list(masterpieces.PENDING).length});
return; return;
// other accounts the same person may have, and their story (lib/staff.js). // other accounts the same person may have, and their story (lib/staff.js).
case "GET /mod/api/alts": { case "GET /mod/api/alts": {
const account = accounts.byName(url.searchParams.get("username") || ""); const account = accounts.byName(url.searchParams.get("username") || "");
@@ -517,7 +713,7 @@ const handle = async (req, res, url, from, web) => {
return; return;
} }
if (searchBy !== "address") { if (searchBy !== "address") {
reply(200, findPlayers(url.searchParams.get("q"))); reply(200, findPlayers(url.searchParams.get("q"), url.searchParams.get("only")));
return; return;
} }
// by address: only the address typed, which is written down (once // by address: only the address typed, which is written down (once
@@ -670,9 +866,12 @@ const handle = async (req, res, url, from, web) => {
return; 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": 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; return;
case "GET /mod/api/masterpiece": { case "GET /mod/api/masterpiece": {
@@ -700,7 +899,7 @@ const handle = async (req, res, url, from, web) => {
return; return;
} }
const result = body.action === "approve" 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" : 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."}) ? (world.removeMasterpiece(id) ? {ok: "Removed for good. Its maker was told and given a Masterpiece Token."} : {error: "No such painting."})
: {error: "Unknown action."}; : {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. // 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 // 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. // 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} // 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: "update", kind, id, and any of name, cost, members, colors, inShop}
// or {action: "lock" | "unlock", kind, id}: kept out of the item finder // 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. // or {action: "delete", kind, id}: a custom item, out of the game and every inventory.
const itemRoutes = (route, url, body, reply, done, actor) => { const itemRoutes = (route, url, body, reply, done, actor) => {
switch (route) { 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": case "GET items":
reply(200, {items: customItems.list().map(entry => ({...entry, baseName: customItems.baseName(entry), locked: itemControl.isLocked(entry.kind, entry.id), 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)})), artUrl: itemArt.urlOf(entry, actor.artBase)})),
+46 -23
View File
@@ -43,6 +43,7 @@ const {activeAvatar} = require("./player.js");
const PASSWORD_SETTING = "admin_password"; // "salt:hash" const PASSWORD_SETTING = "admin_password"; // "salt:hash"
const COOKIE = "ajc_admin"; const COOKIE = "ajc_admin";
const DISCORD_COOKIE = "ajc_admin_discord";
const SESSION_HOURS = 12; const SESSION_HOURS = 12;
const MIN_PASSWORD_LENGTH = 8; const MIN_PASSWORD_LENGTH = 8;
const MAX_PASSWORD_LENGTH = 200; const MAX_PASSWORD_LENGTH = 200;
@@ -112,7 +113,10 @@ const signedIn = req => {
}; };
const cookieHeader = (token, maxAgeSeconds) => 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 => { const signIn = res => {
for (const [hash, expiry] of sessions) { for (const [hash, expiry] of sessions) {
@@ -144,6 +148,7 @@ const accountRow = (account, playing) => {
locked: account.locked, locked: account.locked,
twoStep: totp.isOn(account), twoStep: totp.isOn(account),
discord: account.discord, discord: account.discord,
adminDashboardAccess: Boolean(account.adminDashboardAccess),
bio: account.bio, bio: account.bio,
badges: account.badges, badges: account.badges,
featuresOff: accounts.FEATURES.filter(name => !accounts.featureOn(account, name)), featuresOff: accounts.FEATURES.filter(name => !accounts.featureOn(account, name)),
@@ -384,32 +389,12 @@ const act = (account, body) => {
const {actions, PERMANENT} = world.moderation; const {actions, PERMANENT} = world.moderation;
const name = account.username; const name = account.username;
switch (body.action) { 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 // the owner locks and unlocks on the account page; this is for when
// they cannot. // they cannot.
case "unlock": case "unlock":
account.locked = false; account.locked = false;
accounts.save(account); accounts.save(account);
return {ok: `${name} is unlocked.`}; 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": { case "rename": {
world.disconnect(account); world.disconnect(account);
manage.forget(account); manage.forget(account);
@@ -549,6 +534,16 @@ const act = (account, body) => {
`+${(account.permGrants || []).join(",") || "none"} -${(account.permDenies || []).join(",") || "none"}`); `+${(account.permGrants || []).join(",") || "none"} -${(account.permDenies || []).join(",") || "none"}`);
return {ok: `${name}'s permissions are saved.`}; 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": case "rejectName":
actions.rejectName(account, BY); actions.rejectName(account, BY);
manage.forget(account); 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"); web.send(res, 200, await stats.withView(await fs.promises.readFile(path.join(config.publicDir, "admin.html"))), "text/html; charset=utf-8");
return; 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)) { if (req.method === "POST" && !sameOrigin(req)) {
reply(403, {error: "forbidden"}); reply(403, {error: "forbidden"});
return; return;
@@ -635,7 +658,7 @@ const handle = async (req, res, url, from, web) => {
switch (route) { switch (route) {
case "GET /admin/api/state": 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; return;
// choosing the first password. whoever is at the server's own machine may; // 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."}; : "New masterpieces are approved as they are made. Ones already waiting still wait."};
} }
else if (body.action === "approve") { 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") { else if (body.action === "reject" || body.action === "remove") {
result = world.removeMasterpiece(id) result = world.removeMasterpiece(id)
+21
View File
@@ -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};
+8 -4
View File
@@ -15,6 +15,7 @@ const totp = require("./totp.js");
// higher up, and for the admin in the end. // higher up, and for the admin in the end.
const PERMISSIONS = { 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)", "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)", "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)", "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", "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", "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.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)", "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 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"]; 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"]; const ADMIN = [...MODERATOR, "items.create", "room.effects"];
// a developer makes things, and moderates nobody. // 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 = { const ROLES = {
developer: {rank: 1, label: "Developer", permissions: DEVELOPER}, developer: {rank: 1, label: "Developer", permissions: DEVELOPER},
+28 -3
View File
@@ -28,6 +28,8 @@ const SIGNUP_LIFETIME_MS = 5 * 60000;
const forLog = message => message.replace(/(<pword><!\[CDATA\[)[\s\S]*?(\]\]>)/, "$1(hidden)$2"); const forLog = message => message.replace(/(<pword><!\[CDATA\[)[\s\S]*?(\]\]>)/, "$1(hidden)$2");
const connections = new Map(); // remote address -> open sockets const connections = new Map(); // remote address -> open sockets
let connectionCount = 0;
const metrics = {accepted: 0, rejected: 0, floodDisconnects: 0, handlerErrors: 0};
let nextUserId = 1; let nextUserId = 1;
@@ -139,13 +141,18 @@ const start = handlers => new Promise((resolve, reject) => {
const onConnection = socket => { const onConnection = socket => {
const address = limits.key(socket.remoteAddress); const address = limits.key(socket.remoteAddress);
const open = connections.get(address) || 0; 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", () => {}); socket.on("error", () => {});
if (open >= config.maxConnectionsPerAddress || total >= config.maxConnections) { if (open >= config.maxConnectionsPerAddress || total >= config.maxConnections) {
metrics.rejected++;
socket.destroy(); socket.destroy();
return; return;
} }
connections.set(address, open + 1); connections.set(address, open + 1);
connectionCount++;
metrics.accepted++;
const session = new Session(socket); const session = new Session(socket);
let buffer = Buffer.alloc(0); let buffer = Buffer.alloc(0);
@@ -179,11 +186,15 @@ const start = handlers => new Promise((resolve, reject) => {
} }
bytesInWindow += chunk.length; bytesInWindow += chunk.length;
if (bytesInWindow > config.maxBytesPerTenSeconds) { if (bytesInWindow > config.maxBytesPerTenSeconds) {
metrics.floodDisconnects++;
console.log(`[game] ${logText(session.name)} disconnected for flooding`); console.log(`[game] ${logText(session.name)} disconnected for flooding`);
socket.destroy(); socket.destroy();
return; 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; let end;
while ((end = buffer.indexOf(0)) !== -1) { while ((end = buffer.indexOf(0)) !== -1) {
if (end > MAX_MESSAGE) { if (end > MAX_MESSAGE) {
@@ -191,6 +202,7 @@ const start = handlers => new Promise((resolve, reject) => {
return; return;
} }
if (++messagesInWindow > config.maxMessagesPerTenSeconds) { if (++messagesInWindow > config.maxMessagesPerTenSeconds) {
metrics.floodDisconnects++;
console.log(`[game] ${logText(session.name)} disconnected for flooding`); console.log(`[game] ${logText(session.name)} disconnected for flooding`);
socket.destroy(); socket.destroy();
return; return;
@@ -201,6 +213,7 @@ const start = handlers => new Promise((resolve, reject) => {
dispatch(session, message); dispatch(session, message);
} }
catch (err) { catch (err) {
metrics.handlerErrors++;
// one line a failure, and an end to them: a client that sends // one line a failure, and an end to them: a client that sends
// nonsense in a loop is not to fill the log. // nonsense in a loop is not to fill the log.
const where = String(err.stack || "").split("\n")[1] || ""; const where = String(err.stack || "").split("\n")[1] || "";
@@ -229,6 +242,7 @@ const start = handlers => new Promise((resolve, reject) => {
else { else {
connections.delete(address); connections.delete(address);
} }
connectionCount = Math.max(0, connectionCount - 1);
console.log(`[game] ${logText(session.name)} disconnected`); console.log(`[game] ${logText(session.name)} disconnected`);
// nothing thrown while a player is seen off may take the server down. // nothing thrown while a player is seen off may take the server down.
try { 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};
+91
View File
@@ -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<clothing def id, Set<avatar type>>
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};
+1 -1
View File
@@ -198,7 +198,7 @@
<div class="row"><button class="primary" type="submit">Sign in</button></div> <div class="row"><button class="primary" type="submit">Sign in</button></div>
</form> </form>
<p class="status" id="gate-status" role="status"></p> <p class="status" id="gate-status" role="status"></p>
<p class="hint" style="margin:10px 0 0">No account yet? <a href="/register">Create one</a></p> <p class="hint" style="margin:10px 0 0">No account yet? <a href="/register">Create one</a> · <a href="/account/recover">Forgot password or 2FA?</a></p>
</div> </div>
<div id="page" hidden> <div id="page" hidden>
+183 -11
View File
@@ -143,6 +143,14 @@
.lock-results .meta { color: var(--muted); font-size: 12px; } .lock-results .meta { color: var(--muted); font-size: 12px; }
.lock-results button { margin-left: auto; } .lock-results button { margin-left: auto; }
.lock-results .is-locked { font-size: 11px; padding: 1px 7px; border: 1px solid var(--text); border-radius: 999px; } .lock-results .is-locked { font-size: 11px; padding: 1px 7px; border: 1px solid var(--text); border-radius: 999px; }
#wear-rule-animals { display: flex; flex-wrap: wrap; gap: 8px 16px; margin-top: 10px; }
#wear-rule-animals label.check { display: inline-flex; align-items: center; gap: 5px; }
#wear-rule-animal { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
#wear-rule-animal button { margin: 0; }
#wear-rule-animal button[aria-pressed="true"] { color: #000; background: var(--text); border-color: var(--text); }
#wear-rule-results li, #wear-rule-active li { display: flex; gap: 10px; align-items: center; }
#wear-rule-results .meta, #wear-rule-active .meta { color: var(--muted); font-size: 12px; }
#wear-rule-results button, #wear-rule-active button { margin-left: auto; }
/* signing in */ /* signing in */
#gate { #gate {
@@ -368,6 +376,8 @@
</div> </div>
<button class="primary" id="gate-button">Sign in</button> <button class="primary" id="gate-button">Sign in</button>
</form> </form>
<button type="button" id="discord-sign-in" hidden>Sign in with Discord</button>
<p class="hint" id="discord-gate-hint" hidden>Only Discord accounts explicitly allowed by the owner can use this.</p>
<p class="status" id="gate-status" role="status"></p> <p class="status" id="gate-status" role="status"></p>
</main> </main>
@@ -375,7 +385,7 @@
<aside id="side"> <aside id="side">
<div class="brand"> <div class="brand">
<img class="mark" src="/logo.png" alt=""> <img class="mark" src="/logo.png" alt="">
<div><h1>Server admin</h1><span class="hint" id="updated"></span></div> <div><h1>Burrow dashboard</h1><span class="hint" id="updated">Owner controls</span></div>
</div> </div>
<nav role="tablist" aria-orientation="vertical"> <nav role="tablist" aria-orientation="vertical">
<button role="tab" data-tab="overview" aria-selected="true"><span class="icon" aria-hidden="true">&#9673;</span>Overview</button> <button role="tab" data-tab="overview" aria-selected="true"><span class="icon" aria-hidden="true">&#9673;</span>Overview</button>
@@ -386,6 +396,7 @@
<button role="tab" data-tab="support" aria-selected="false"><span class="icon" aria-hidden="true">&#9998;</span>Requests<span id="support-count"></span></button> <button role="tab" data-tab="support" aria-selected="false"><span class="icon" aria-hidden="true">&#9998;</span>Requests<span id="support-count"></span></button>
<button role="tab" data-tab="masterpieces" aria-selected="false"><span class="icon" aria-hidden="true">&#9635;</span>Masterpieces<span id="masterpiece-count"></span></button> <button role="tab" data-tab="masterpieces" aria-selected="false"><span class="icon" aria-hidden="true">&#9635;</span>Masterpieces<span id="masterpiece-count"></span></button>
<button role="tab" data-tab="items" aria-selected="false"><span class="icon" aria-hidden="true">&#10070;</span>Items</button> <button role="tab" data-tab="items" aria-selected="false"><span class="icon" aria-hidden="true">&#10070;</span>Items</button>
<button role="tab" data-tab="wear-rules" aria-selected="false"><span class="icon" aria-hidden="true">&#9873;</span>Wear rules</button>
<button role="tab" data-tab="bans" aria-selected="false"><span class="icon" aria-hidden="true">&#8856;</span>Bans</button> <button role="tab" data-tab="bans" aria-selected="false"><span class="icon" aria-hidden="true">&#8856;</span>Bans</button>
<button role="tab" data-tab="moderators" aria-selected="false"><span class="icon" aria-hidden="true">&#9733;</span>Moderators</button> <button role="tab" data-tab="moderators" aria-selected="false"><span class="icon" aria-hidden="true">&#9733;</span>Moderators</button>
<button role="tab" data-tab="messages" aria-selected="false"><span class="icon" aria-hidden="true">&#9993;</span>Messages</button> <button role="tab" data-tab="messages" aria-selected="false"><span class="icon" aria-hidden="true">&#9993;</span>Messages</button>
@@ -474,11 +485,6 @@
<div class="row"><input id="new-name" maxlength="100" placeholder="New username" autocomplete="off" spellcheck="false" aria-label="New username"> <div class="row"><input id="new-name" maxlength="100" placeholder="New username" autocomplete="off" spellcheck="false" aria-label="New username">
<button type="button" data-action="rename">Rename</button></div> <button type="button" data-action="rename">Rename</button></div>
</div> </div>
<div class="action">
<h3>Password</h3>
<div class="row"><input id="new-password" type="password" placeholder="New password" autocomplete="new-password" aria-label="New password">
<button type="button" data-action="password">Set</button></div>
</div>
<div class="action"> <div class="action">
<h3>Adventure level</h3> <h3>Adventure level</h3>
<div class="row"><input id="quest-level" type="number" min="0" max="100" step="1" aria-label="Adventure level of the animal in use"> <div class="row"><input id="quest-level" type="number" min="0" max="100" step="1" aria-label="Adventure level of the animal in use">
@@ -564,7 +570,6 @@
<div class="buttons"> <div class="buttons">
<button type="button" data-action="kick">Disconnect</button> <button type="button" data-action="kick">Disconnect</button>
<button type="button" data-action="unlock">Unlock</button> <button type="button" data-action="unlock">Unlock</button>
<button type="button" data-action="twoStepOff">Turn off 2FA</button>
<button type="button" data-action="rejectName">Reject username</button> <button type="button" data-action="rejectName">Reject username</button>
<button type="button" data-action="acceptName">Take rejection back</button> <button type="button" data-action="acceptName">Take rejection back</button>
<button type="button" data-action="moderator" id="moderator-toggle">Make moderator</button> <button type="button" data-action="moderator" id="moderator-toggle">Make moderator</button>
@@ -617,6 +622,8 @@
<p class="hint">Each one as their role has it, or given or taken for them alone. What they may do now is marked.</p> <p class="hint">Each one as their role has it, or given or taken for them alone. What they may do now is marked.</p>
<div class="perm-list" id="perm-list"></div> <div class="perm-list" id="perm-list"></div>
<div class="row" style="margin-top:10px"><button type="button" class="primary" data-action="permissions">Save permissions</button></div> <div class="row" style="margin-top:10px"><button type="button" class="primary" data-action="permissions">Save permissions</button></div>
<div class="row" style="margin-top:12px"><button type="button" data-action="adminDashboardAccess" id="admin-dashboard-access"></button></div>
<p class="hint" id="admin-dashboard-access-hint"></p>
</div> </div>
<div id="owned"></div> <div id="owned"></div>
</div> </div>
@@ -688,6 +695,30 @@
</section> </section>
</div> </div>
<div data-view="wear-rules" hidden>
<section>
<h2>Animal wear rules</h2>
<p class="hint">Choose an animal below, then control which clothing it may wear. A rule never changes the other animals.</p>
<div id="wear-rule-animal" aria-label="Animal to control"></div>
<div class="toolbar"><input id="wear-rule-q" type="search" placeholder="Clothing name or id" aria-label="Find clothing to restrict" disabled></div>
<ul class="plain lock-results" id="wear-rule-results"></ul>
<p class="hint" id="wear-rule-more" hidden></p>
</section>
<section id="wear-rule-editor" hidden>
<h2 id="wear-rule-title"></h2>
<p class="hint">Tick every animal that must not wear this item. Leaving them all clear lets every animal wear it again.</p>
<div id="wear-rule-animals"></div>
<div class="toolbar" style="margin-top:14px"><button type="button" class="primary" id="wear-rule-save">Save rules</button>
<button type="button" id="wear-rule-close">Close</button></div>
<p class="status" id="wear-rule-status" role="status"></p>
</section>
<section>
<h2>Restricted for this animal</h2>
<ul class="plain lock-results" id="wear-rule-active"></ul>
<div class="empty" id="no-wear-rules">No animal wear rules yet.</div>
</section>
</div>
<div data-view="items" hidden> <div data-view="items" hidden>
<section> <section>
<h2 id="item-form-title">Make an item</h2> <h2 id="item-form-title">Make an item</h2>
@@ -973,7 +1004,7 @@
let timer = null; let timer = null;
const api = async (path, body) => { const api = async (path, body) => {
const response = await fetch(`/admin/api/${path}`, body === undefined ? {} : { const response = await fetch(`/dashboard/api/admin/${path}`, body === undefined ? {} : {
method: "POST", method: "POST",
headers: {"Content-Type": "application/json"}, headers: {"Content-Type": "application/json"},
body: JSON.stringify(body), body: JSON.stringify(body),
@@ -1040,6 +1071,13 @@
$("confirm-field").hidden = !setup; $("confirm-field").hidden = !setup;
$("code-field").hidden = !(setup && state.needsSetupCode); $("code-field").hidden = !(setup && state.needsSetupCode);
$("gate-button").textContent = setup ? "Set password" : "Sign in"; $("gate-button").textContent = setup ? "Set password" : "Sign in";
$("discord-sign-in").hidden = setup;
$("discord-sign-in").disabled = !state.discordLogin;
$("discord-sign-in").textContent = state.discordLogin ? "Sign in with Discord" : "Discord sign-in is not configured";
$("discord-gate-hint").hidden = setup;
$("discord-gate-hint").textContent = state.discordLogin
? "Only Discord accounts explicitly allowed by the owner can use this."
: "Set AJ_DISCORD_CLIENT_ID and AJ_DISCORD_CLIENT_SECRET, then add both admin callback URLs in your Discord application.";
$("password").value = ""; $("password").value = "";
$("confirm").value = ""; $("confirm").value = "";
setStatus($("gate-status"), message || ""); setStatus($("gate-status"), message || "");
@@ -1065,6 +1103,9 @@
state = {needsSetup: false, needsSetupCode: false, signedIn: true}; state = {needsSetup: false, needsSetupCode: false, signedIn: true};
showPanel(); showPanel();
}); });
$("discord-sign-in").addEventListener("click", () => {
location.href = "/dashboard/admin/discord/login";
});
$("sign-out").addEventListener("click", async () => { $("sign-out").addEventListener("click", async () => {
await api("logout", {}); await api("logout", {});
@@ -1443,6 +1484,11 @@
return label; return label;
})); }));
$("discord-name").textContent = current && current.discord ? `Discord: ${current.discord}` : "No Discord linked"; $("discord-name").textContent = current && current.discord ? `Discord: ${current.discord}` : "No Discord linked";
$("admin-dashboard-access").textContent = current && current.adminDashboardAccess ? "Remove Discord dashboard access" : "Allow Discord dashboard access";
$("admin-dashboard-access").disabled = !current || (!current.discord && !current.adminDashboardAccess);
$("admin-dashboard-access-hint").textContent = current && current.discord
? "Lets this linked Discord account open the full owner dashboard without the shared admin password."
: "They must link Discord on their account page first.";
$("bio-text").value = current ? current.bio : ""; $("bio-text").value = current ? current.bio : "";
$("quest-level").value = current ? current.level : ""; $("quest-level").value = current ? current.level : "";
$("ban-reason").value = current ? current.banReason : ""; $("ban-reason").value = current ? current.banReason : "";
@@ -1473,7 +1519,7 @@
selected = username; selected = username;
current = null; current = null;
setStatus($("detail-status"), ""); setStatus($("detail-status"), "");
for (const id of ["new-name", "new-password", "ban-hours", "silence-hours", "message-text", "gems-amount", "gift-value", "gift-text"]) { for (const id of ["new-name", "ban-hours", "silence-hours", "message-text", "gems-amount", "gift-value", "gift-text"]) {
$(id).value = ""; $(id).value = "";
} }
hashArg = username; hashArg = username;
@@ -1618,7 +1664,6 @@
const actionBody = action => { const actionBody = action => {
switch (action) { switch (action) {
case "rename": return {newName: $("new-name").value}; case "rename": return {newName: $("new-name").value};
case "password": return {password: $("new-password").value};
case "lastSeen": return {when: Math.floor(new Date($("last-seen").value).getTime() / 1000)}; case "lastSeen": return {when: Math.floor(new Date($("last-seen").value).getTime() / 1000)};
case "ban": return {hours: numberFrom("ban-hours"), reason: $("ban-reason").value}; case "ban": return {hours: numberFrom("ban-hours"), reason: $("ban-reason").value};
case "banReason": case "banDevices": return {reason: $("ban-reason").value}; case "banReason": case "banDevices": return {reason: $("ban-reason").value};
@@ -1626,6 +1671,7 @@
case "moderator": return {on: !(current || {}).moderator}; case "moderator": return {on: !(current || {}).moderator};
case "role": return {role: $("role-select").value}; case "role": return {role: $("role-select").value};
case "permissions": return permissionChoices(); case "permissions": return permissionChoices();
case "adminDashboardAccess": return {on: !(current || {}).adminDashboardAccess};
case "message": return {text: $("message-text").value}; case "message": return {text: $("message-text").value};
case "gems": return {amount: numberFrom("gems-amount")}; case "gems": return {amount: numberFrom("gems-amount")};
case "gift": return giftBody(); case "gift": return giftBody();
@@ -1678,7 +1724,6 @@
$("new-name").value = ""; $("new-name").value = "";
} }
if (result.ok) { if (result.ok) {
$("new-password").value = "";
await refresh(); await refresh();
fillCard(); fillCard();
loadOwned(); loadOwned();
@@ -2590,6 +2635,130 @@
file.click(); file.click();
}; };
// ---- animal wear rules: the same server-side moderation control the
// moderator dashboard uses (items.restrict in lib/roles.js).
let wearAnimals = [];
let wearRuleEntries = [];
let wearSelected = null;
let wearSelectedTypes = new Set();
let wearAnimal = "";
let wearRuleTimer = null;
let wearRuleAsked = 0;
const wearRuleFor = id => wearRuleEntries.find(rule => rule.id === Number(id));
const wearAnimalName = id => (wearAnimals.find(animal => animal.id === Number(id)) || {name: `Animal ${id}`}).name;
const wearNames = types => types.map(wearAnimalName).join(", ");
const selectedWearAnimal = () => Number(wearAnimal) || 0;
const toggleWearRule = async item => {
const animal = selectedWearAnimal();
if (!animal) return;
const current = item.blockedTypes || (wearRuleFor(item.id) || {}).blockedTypes || [];
const blocked = current.includes(animal) ? current.filter(type => type !== animal) : [...current, animal];
const result = await api("items/wear-rules", {id: item.id, blockedTypes: blocked.sort((one, two) => one - two)});
setStatus($("wear-rule-status"), said(result), !result.ok);
if (result.ok) await loadWearRules();
};
const chooseWearAnimal = animal => {
wearAnimal = String(animal);
wearSelected = null;
$("wear-rule-q").disabled = !selectedWearAnimal();
renderWearRuleEditor();
loadWearRules();
};
const renderWearRuleEditor = () => {
$("wear-rule-editor").hidden = !wearSelected;
if (!wearSelected) {
return;
}
$("wear-rule-title").textContent = `Where ${wearSelected.name || `clothing ${wearSelected.id}`} cannot be worn`;
$("wear-rule-animals").replaceChildren(...wearAnimals.map(animal => {
const box = el("input");
box.type = "checkbox";
box.checked = wearSelectedTypes.has(animal.id);
box.addEventListener("change", () => {
wearSelectedTypes[box.checked ? "add" : "delete"](animal.id);
});
const label = el("label", undefined, "check");
label.append(box, animal.name);
return label;
}));
};
const chooseWearRule = item => {
wearSelected = {id: Number(item.id), name: item.name || `clothing ${item.id}`};
const current = item.blockedTypes || (wearRuleFor(item.id) || {}).blockedTypes || [];
wearSelectedTypes = new Set(current);
setStatus($("wear-rule-status"), "");
renderWearRuleEditor();
};
const renderWearRules = (results, query, total) => {
const animal = selectedWearAnimal();
$("wear-rule-results").replaceChildren(...results.map(item => {
const row = el("li");
const blocked = item.blockedTypes || (wearRuleFor(item.id) || {}).blockedTypes || [];
row.append(el("span", item.name || "(no name)"), el("span", `clothing ${item.id}${item.custom ? ", custom" : ""}${blocked.length ? ` · blocked for ${wearNames(blocked)}` : ""}`, "meta"),
button(animal && blocked.includes(animal) ? `Allow ${wearAnimalName(animal)}` : `Block ${wearAnimalName(animal)}`,
() => toggleWearRule({...item, blockedTypes: blocked}), animal && blocked.includes(animal) ? "" : "primary"));
return row;
}));
$("wear-rule-more").hidden = Boolean(animal && query && results.length > 0 && total <= results.length);
$("wear-rule-more").textContent = !animal ? "Choose an animal, then search for clothing."
: !query ? "Search for clothing to control for this animal."
: results.length === 0 ? "No clothing matches."
: `${total} clothing items match; these are the first ${results.length}. Type more of the name.`;
const active = animal ? wearRuleEntries.filter(rule => rule.blockedTypes.includes(animal)) : [];
$("wear-rule-active").replaceChildren(...active.map(rule => {
const row = el("li");
row.append(el("span", rule.name || "(no name)"), el("span", `clothing ${rule.id} · blocked for ${wearNames(rule.blockedTypes)}`, "meta"),
button("Edit", () => chooseWearRule(rule)));
return row;
}));
$("no-wear-rules").hidden = active.length > 0;
};
const loadWearRules = async () => {
const query = $("wear-rule-q").value.trim();
const asked = ++wearRuleAsked;
const result = await api(`items/wear-rules?q=${encodeURIComponent(query)}`);
if (asked !== wearRuleAsked || !result.ok) {
return;
}
wearAnimals = result.data.animals || [];
$("wear-rule-animal").replaceChildren(...wearAnimals.map(animal => {
const button = el("button", animal.name, selectedWearAnimal() === animal.id ? "primary" : "");
button.type = "button";
button.setAttribute("aria-pressed", String(selectedWearAnimal() === animal.id));
button.addEventListener("click", () => chooseWearAnimal(animal.id));
return button;
}));
wearRuleEntries = result.data.rules || [];
renderWearRules(selectedWearAnimal() && query ? result.data.results || [] : [], query, result.data.total || 0);
renderWearRuleEditor();
};
$("wear-rule-q").addEventListener("input", () => {
clearTimeout(wearRuleTimer);
wearRuleTimer = setTimeout(loadWearRules, 250);
});
$("wear-rule-save").addEventListener("click", async () => {
if (!wearSelected) {
return;
}
const result = await api("items/wear-rules", {id: wearSelected.id, blockedTypes: [...wearSelectedTypes].sort((one, two) => one - two)});
setStatus($("wear-rule-status"), said(result), !result.ok);
if (result.ok) {
await loadWearRules();
}
});
$("wear-rule-close").addEventListener("click", () => {
wearSelected = null;
setStatus($("wear-rule-status"), "");
renderWearRuleEditor();
});
// ---- the overview's item lock: any item by name or id, locked or // ---- the overview's item lock: any item by name or id, locked or
// unlocked where it is found (the Items page lists every locked one). // unlocked where it is found (the Items page lists every locked one).
let quickLockTimer = null; let quickLockTimer = null;
@@ -2717,6 +2886,9 @@
renderSupport(result.data); renderSupport(result.data);
} }
} }
else if (tab === "wear-rules") {
await loadWearRules();
}
else if (tab === "items") { else if (tab === "items") {
result = await api("items"); result = await api("items");
if (result.ok) { if (result.ok) {
+28
View File
@@ -0,0 +1,28 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Burrow dashboard</title>
<link rel="icon" type="image/png" href="/logo-square.png">
<style>
@font-face { font-family: DigitalDelivery; src: url("/fonts/CCDigitalDelivery-Regular.otf") format("opentype"); }
@font-face { font-family: DigitalDelivery; font-weight: 700; src: url("/fonts/CCDigitalDelivery-Bold.otf") format("opentype"); }
:root { color-scheme: dark; } * { box-sizing: border-box; }
body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px; background: #000; color: #fff; font: 16px/1.45 DigitalDelivery, system-ui, sans-serif; }
main { width: min(720px, 100%); padding: clamp(24px, 6vw, 48px); border: 1px solid #333; border-radius: 22px; background: #0d0d0d; }
header { display: flex; align-items: center; gap: 15px; margin-bottom: 28px; } header img { width: 54px; height: 54px; object-fit: contain; } h1 { margin: 0; font-size: 30px; } p { color: #aaa; margin: 5px 0 0; }
.choices { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 14px; } a { display: block; padding: 20px; color: inherit; text-decoration: none; border: 1px solid #3a3a3a; border-radius: 15px; background: #151515; } a:hover, a:focus-visible { background: #222; border-color: #fff; outline: none; } strong { display: block; font-size: 19px; margin-bottom: 5px; } .hint { font-size: 13px; color: #aaa; } footer { margin-top: 24px; font-size: 12px; color: #777; }
</style>
</head>
<body>
<main>
<header><img src="/logo.png" alt=""><div><h1>Burrow dashboard</h1><p>One place for running and moderating your server.</p></div></header>
<div class="choices">
<a href="/dashboard/admin"><strong>Owner dashboard</strong><span class="hint">Server settings, accounts, logs, items, roles, and all administration.</span></a>
<a href="/dashboard/staff"><strong>Staff dashboard</strong><span class="hint">Player care, reports, moderation, review, and server health.</span></a>
</div>
<footer>Access remains role-based. Staff never receive owner controls.</footer>
</main>
</body>
</html>
+1091 -248
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -161,7 +161,7 @@
<section> <section>
<h2>1. Who is responsible</h2> <h2>1. Who is responsible</h2>
<p>The controller of your personal data is the operator of Burrow, {{operator}}. Contact for anything in this policy: {{legalEmail}}. General contact: {{adminEmail}}.</p> <p>The controller of your personal data is the operator of Burrow, {{operator}}. Contact for anything in this policy: {{legalEmail}}. General contact: {{adminEmail}}.</p>
<p>We do not sell data, show ads, track you across sites or send marketing. We do not collect your real name, email address or date of birth. The only statistics we keep are the game's own activity figures in section 2, which are used only to run and plan the server, and the overall traffic figures described in section 4.</p> <p>We do not sell data, show ads, track you across sites or send marketing. We do not collect your real name or date of birth. We keep a recovery email address only to send one-time password and 2FA recovery links. The only statistics we keep are the game's own activity figures in section 2, which are used only to run and plan the server, and the overall traffic figures described in section 4.</p>
</section> </section>
<section> <section>
@@ -170,6 +170,7 @@
<thead><tr><th>Data</th><th>Why</th></tr></thead> <thead><tr><th>Data</th><th>Why</th></tr></thead>
<tbody> <tbody>
<tr><td>Username, password (stored only as a salted hash), and the date and version of the terms you accepted</td><td>To give you an account</td></tr> <tr><td>Username, password (stored only as a salted hash), and the date and version of the terms you accepted</td><td>To give you an account</td></tr>
<tr><td>Recovery email address</td><td>To verify ownership before sending a one-time password or 2FA recovery link</td></tr>
<tr><td>Your game data: animals, items, dens, pets, buddies, block list, trades, achievements, settings</td><td>To run the game for you</td></tr> <tr><td>Your game data: animals, items, dens, pets, buddies, block list, trades, achievements, settings</td><td>To run the game for you</td></tr>
<tr><td>What you choose to write or make: bio, Discord username (optional), Jam-A-Grams, wall posts, paintings, feedback</td><td>To show or deliver it as you asked</td></tr> <tr><td>What you choose to write or make: bio, Discord username (optional), Jam-A-Grams, wall posts, paintings, feedback</td><td>To show or deliver it as you asked</td></tr>
<tr><td>Typed chat and whispers, with the room and time, and the words of Jam-A-Grams and wall posts, with who they went to</td><td>Moderation: reviewing reports and deciding on bans</td></tr> <tr><td>Typed chat and whispers, with the room and time, and the words of Jam-A-Grams and wall posts, with who they went to</td><td>Moderation: reviewing reports and deciding on bans</td></tr>
+8
View File
@@ -0,0 +1,8 @@
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Recover account</title><link rel="icon" type="image/png" href="/logo-square.png">
<style>@font-face{font-family:d;src:url('/fonts/CCDigitalDelivery-Regular.otf')}*{box-sizing:border-box}body{margin:0;padding:48px 16px;background:#000;color:#fff;font:16px/1.45 d,system-ui}main{max-width:420px;margin:auto;padding:28px;background:#0d0d0d;border:1px solid #2e2e2e;border-radius:18px}.logo{height:62px}h1{font-size:25px;margin:10px 0}p,label{color:#aaa}label{display:block;margin:14px 0 5px}input,select,button{width:100%;font:inherit;color:#fff;background:#000;border:1px solid #444;border-radius:12px;padding:10px 12px}button{margin-top:20px;background:#fff;color:#000;font-weight:bold;cursor:pointer}.status{min-height:24px;margin:14px 0 0;color:#aaa}a{color:#fff}</style></head>
<body><main><img class="logo" src="/logo.png" alt=""><h1>Account recovery</h1>
<div id="request"><p>We’ll send a one-time recovery link to the email saved on your account.</p><form id="request-form"><label>Username<input id="username" autocomplete="username" required></label><label>Recovery email<input id="email" type="email" autocomplete="email" required></label><label>What do you need to recover?<select id="kind"><option value="password">Password</option><option value="twoStep">2FA</option></select></label><button>Send recovery link</button></form></div>
<div id="complete" hidden><p id="intro"></p><form id="complete-form"><label id="password-label">New password<input id="password" type="password" autocomplete="new-password" minlength="10"></label><button>Complete recovery</button></form></div><p class="status" id="status" role="status"></p><p><a href="/account">Back to sign in</a></p></main>
<script>"use strict";const $=id=>document.getElementById(id),token=new URLSearchParams(location.search).get('token');const post=async(path,body)=>{const r=await fetch(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});return {ok:r.ok,data:await r.json()}};const status=(text)=>$('status').textContent=text;if(token){post('/account/api/recover/check',{token}).then(r=>{if(!r.ok){status(r.data.error);return}$('request').hidden=true;$('complete').hidden=false;const two=r.data.kind==='twoStep';$('intro').textContent=two?'Confirm that you want to remove 2FA from this account.':'Choose a new password.';$('password-label').hidden=two;$('password').required=!two}).catch(()=>status('The server did not answer.'))}$('request-form').addEventListener('submit',async e=>{e.preventDefault();const r=await post('/account/api/recover/request',{username:$('username').value,email:$('email').value,kind:$('kind').value});status(r.data.ok||'Could not start recovery.')});$('complete-form').addEventListener('submit',async e=>{e.preventDefault();const r=await post('/account/api/recover/complete',{token,password:$('password').value});status(r.data.ok||r.data.error||'Could not complete recovery.')});</script></body></html>
+4 -1
View File
@@ -200,6 +200,8 @@
<input id="password" name="password" type="password" autocomplete="new-password" minlength="10" maxlength="100" required> <input id="password" name="password" type="password" autocomplete="new-password" minlength="10" maxlength="100" required>
<label for="confirm">Password again</label> <label for="confirm">Password again</label>
<input id="confirm" name="confirm" type="password" autocomplete="new-password" required> <input id="confirm" name="confirm" type="password" autocomplete="new-password" required>
<label for="email">Recovery email <span class="hint">Used only to recover your password or 2FA</span></label>
<input id="email" name="email" type="email" autocomplete="email" maxlength="254" required>
<label class="agree"><input id="agreed" name="agreed" type="checkbox" required> <label class="agree"><input id="agreed" name="agreed" type="checkbox" required>
<span>I am 13 or older, and old enough in my country to agree to this myself. I agree to the <a href="/terms" target="_blank" rel="noopener">Terms of Service</a> and the <a href="/privacy" target="_blank" rel="noopener">Privacy Policy</a>.</span></label> <span>I am 13 or older, and old enough in my country to agree to this myself. I agree to the <a href="/terms" target="_blank" rel="noopener">Terms of Service</a> and the <a href="/privacy" target="_blank" rel="noopener">Privacy Policy</a>.</span></label>
<div class="captcha" id="captcha"></div> <div class="captcha" id="captcha"></div>
@@ -242,6 +244,7 @@
captcha_required: "Complete the captcha.", captcha_required: "Complete the captcha.",
captcha_failed: "Captcha failed. Try again.", captcha_failed: "Captcha failed. Try again.",
captcha_unavailable: "Captcha unavailable. Try again later.", captcha_unavailable: "Captcha unavailable. Try again later.",
invalid_email: "Enter a valid recovery email address.",
}; };
const $ = id => document.getElementById(id); const $ = id => document.getElementById(id);
@@ -335,7 +338,7 @@
const response = await fetch("/api/register", { const response = await fetch("/api/register", {
method: "POST", method: "POST",
headers: {"Content-Type": "application/json"}, headers: {"Content-Type": "application/json"},
body: JSON.stringify({username: form.username.value, password: form.password.value, avatarType: chosen[0], agreed: form.agreed.checked, body: JSON.stringify({username: form.username.value, password: form.password.value, email: form.email.value, avatarType: chosen[0], agreed: form.agreed.checked,
captcha: answer}), captcha: answer}),
}); });
check.reset(); check.reset();
+1 -1
View File
@@ -179,7 +179,7 @@
<h2>3. Your account</h2> <h2>3. Your account</h2>
<ul> <ul>
<li>You are responsible for your password and for what is done with your account. Use a password you do not use anywhere else.</li> <li>You are responsible for your password and for what is done with your account. Use a password you do not use anywhere else.</li>
<li>We do not collect an email address, so we cannot send you a password reset. Turn on 2FA and keep your recovery codes.</li> <li>Keep your recovery email current. We use it only to send one-time password or 2FA recovery links.</li>
<li>You can delete your account at any time on <a href="/account">your account page</a>.</li> <li>You can delete your account at any time on <a href="/account">your account page</a>.</li>
</ul> </ul>
</section> </section>
+91 -1
View File
@@ -88,6 +88,28 @@ const pack = async id => Object.values(decode(zlib.inflateRawSync(Buffer.from(aw
const strings = async () => decode(zlib.inflateRawSync(Buffer.from(await (await fetch(`${BASE}/${cdn.hashedPath("defPacks/10230")}`)).arrayBuffer()))); const strings = async () => decode(zlib.inflateRawSync(Buffer.from(await (await fetch(`${BASE}/${cdn.hashedPath("defPacks/10230")}`)).arrayBuffer())));
const byId = (rows, id) => rows.find(row => String(row.id) === String(id)); const byId = (rows, id) => rows.find(row => String(row.id) === String(id));
// Ask for the same full clothing list the item editor does, then find one
// inventory entry in its five-field rows. Keeping this on the real protocol
// lets the rule tests cover both server state and what an open game receives.
const ownInventory = async (client, roomId, username, perUserAvId = 1) => {
client.xt("il", roomId, username, perUserAvId, 1);
for (;;) {
const list = await client.untilXt("il");
if (list[2] === "0" && list[5] === username) {
return list;
}
}
};
const inventoryPiece = (list, defId) => {
for (let index = 0; index < Number(list[8]); index++) {
const at = 9 + index * 5;
if (Number(list[at]) === Number(defId)) {
return {inv: Number(list[at + 1]), equipped: list[at + 3]};
}
}
return null;
};
// "xdi" [.., .., kind, rows as JSON], the next one of `kind`. // "xdi" [.., .., kind, rows as JSON], the next one of `kind`.
const untilDefs = async (client, kind) => { const untilDefs = async (client, kind) => {
for (;;) { for (;;) {
@@ -412,6 +434,56 @@ const first = async () => {
assert.strictEqual(wornAs.mine.find(entry => entry.kind === "clothing" && entry.id === hatEntry.id).artMode, "texture"); assert.strictEqual(wornAs.mine.find(entry => entry.kind === "clothing" && entry.id === hatEntry.id).artMode, "texture");
assert.match((await maker("look", "clothing", hatEntry.id, "melted")).said, /sticker or texture/); assert.match((await maker("look", "clothing", hatEntry.id, "melted")).said, /sticker or texture/);
// --- animal wear rules: a live custom item keeps its xdi-only name and
// picture, existing use is removed, and neither packet nor saved-outfit
// routes may put it back on the animal that staff blocked.
const partyHat = wornAs.mine.find(sameItem);
assert.ok(partyHat && partyHat.art, "the custom clothing to restrict is missing its picture");
const partyPiece = inventoryPiece(await ownInventory(pat.client, pat.roomId, "Pat"), partyHat.id);
assert.ok(partyPiece, "Pat does not own Party Hat");
pat.client.xt("iu", pat.roomId, 1, 0, partyPiece.inv);
assert.strictEqual((await pat.client.untilXt("iu"))[2], "1");
let changedWear = await pat.client.untilXt("il");
assert.deepStrictEqual(changedWear.slice(2), ["3", "1", "1", "Pat", "0", "1", "0", String(partyPiece.inv), String(partyHat.id)]);
say(pat.client, pat.roomId, "!outfit save partyhat");
assert.strictEqual(await nextBox(pat.client), "Outfit partyhat saved (1 items).");
// A no-op item-editor request records what was worn for !outfit undo,
// without taking Party Hat off before the dashboard removes it.
pat.client.xt("iu", pat.roomId, 0, 0);
await pat.client.untilXt("iu");
await pat.client.untilXt("il");
assert.strictEqual(byId(await pack(1000), partyHat.id).avatarUseFlags, "9007199254740991");
assert.strictEqual((await admin("/admin/api/items/wear-rules", {id: partyHat.id, blockedTypes: ["1"]})).status, 400);
assert.strictEqual((await admin("/admin/api/items/wear-rules", {id: bodyPart.id, blockedTypes: [1]})).status, 400);
const partyRule = await admin("/admin/api/items/wear-rules", {id: partyHat.id, blockedTypes: [1]});
assert.match(partyRule.data.ok, /cannot be worn/);
// The owner receives a fresh full list immediately, with the old equipped
// bit actually gone rather than merely hidden in the renderer.
const afterRule = await pat.client.untilXt("il");
assert.strictEqual(afterRule[2], "0");
assert.strictEqual(inventoryPiece(afterRule, partyHat.id).equipped, "0");
const partyUpdate = byId(await untilDefs(pat.client, "clothing"), partyHat.id);
assert.deepStrictEqual([partyUpdate.avatarUseFlags, partyUpdate.name, partyUpdate.art, partyUpdate.artMode],
["9007199254740990", "Party Hat", partyHat.art, "texture"]);
assert.strictEqual(byId(await pack(1000), partyHat.id).avatarUseFlags, "9007199254740990"); // cached pack was invalidated
say(pat.client, pat.roomId, "!outfit undo");
changedWear = await pat.client.untilXt("il");
assert.strictEqual(changedWear[7], "0");
assert.ok(!changedWear.includes(String(partyHat.id)));
assert.match(await nextBox(pat.client), /Back to what you wore before/);
say(pat.client, pat.roomId, "!outfit wear partyhat");
changedWear = await pat.client.untilXt("il");
assert.strictEqual(changedWear[7], "0");
assert.ok(!changedWear.includes(String(partyHat.id)));
assert.match(await nextBox(pat.client), /Wearing partyhat/);
// A crafted/stale editor packet still succeeds as a request but cannot add
// a blocked inventory entry to the response or persisted outfit.
pat.client.xt("iu", pat.roomId, 1, 0, partyPiece.inv);
assert.strictEqual((await pat.client.untilXt("iu"))[2], "1");
changedWear = await pat.client.untilXt("il");
assert.strictEqual(changedWear[7], "0");
assert.ok(!changedWear.includes(String(partyHat.id)));
// deleting: their own only, and gone from everyone // deleting: their own only, and gone from everyone
assert.match((await maker("delete", "clothing", 50001)).said, /not one of your items/); assert.match((await maker("delete", "clothing", 50001)).said, /not one of your items/);
for (const entry of full.mine) { for (const entry of full.mine) {
@@ -420,6 +492,8 @@ const first = async () => {
assert.deepStrictEqual((await maker("info")).mine, []); assert.deepStrictEqual((await maker("info")).mine, []);
assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png`)).status, 404); assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png`)).status, 404);
assert.strictEqual((await dev("/mod/api/items")).data.items.length, 3); assert.strictEqual((await dev("/mod/api/items")).data.items.length, 3);
assert.ok(!(await admin(`/admin/api/items/wear-rules?q=${hatEntry.id}`)).data.rules.some(rule => rule.id === hatEntry.id),
"deleting custom clothing should remove its wear rule");
// --- the admin's switches: what players make waits for a moderator first, // --- the admin's switches: what players make waits for a moderator first,
// out of the game till then; or the Item Maker is off // out of the game till then; or the Item Maker is off
@@ -465,6 +539,20 @@ const first = async () => {
assert.strictEqual((await admin("/admin/api/item-switches", {enabled: true})).status, 200); assert.strictEqual((await admin("/admin/api/item-switches", {enabled: true})).status, 200);
assert.match((await maker("delete", "clothing", waitingHat.id)).said, /^Deleted /); assert.match((await maker("delete", "clothing", waitingHat.id)).said, /^Deleted /);
// A developer can create items but is not silently granted the moderation
// control. Once made a moderator, the existing panel session is checked
// against the new role and can create a rule that survives the restart.
assert.strictEqual((await dev("/mod/api/items/wear-rules")).status, 403);
assert.strictEqual((await dev("/mod/api/items/wear-rules", {id: 50000, blockedTypes: [1]})).status, 403);
assert.match((await admin("/admin/api/account", {username: "Dev", action: "role", role: "moderator"})).data.ok, /moderator/);
const moderatorMe = (await dev("/mod/api/me")).data;
assert.ok(moderatorMe.permissions.includes("items.restrict") && !moderatorMe.permissions.includes("items.create"));
const crownRule = await dev("/mod/api/items/wear-rules", {id: 50000, blockedTypes: [1]});
assert.match(crownRule.data.ok, /cannot be worn/);
const moderatorRules = (await dev("/mod/api/items/wear-rules?q=Gold%20Crown")).data;
assert.deepStrictEqual(moderatorRules.results.find(entry => entry.id === 50000).blockedTypes, [1]);
assert.strictEqual(byId(await pack(1000), 50000).avatarUseFlags, "9007199254740990");
// written down under the maker's name // written down under the maker's name
const log = (await admin("/admin/api/moderators")).data.log.map(entry => `${entry.by} ${entry.action} ${entry.detail}`); const log = (await admin("/admin/api/moderators")).data.log.map(entry => `${entry.by} ${entry.action} ${entry.detail}`);
for (const line of ["Dev item made clothing 50000 Test Crown", "Dev item made den 50000 Test Chair", "Dev item changed clothing 50000 Gold Crown", for (const line of ["Dev item made clothing 50000 Test Crown", "Dev item made den 50000 Test Chair", "Dev item changed clothing 50000 Gold Crown",
@@ -472,7 +560,7 @@ const first = async () => {
"Dev item taken den 50000 x1", "Dev item deleted clothing 50002"]) { "Dev item taken den 50000 x1", "Dev item deleted clothing 50002"]) {
assert.ok(log.includes(line), `missing from the log: ${line}\n${log.join("\n")}`); assert.ok(log.includes(line), `missing from the log: ${line}\n${log.join("\n")}`);
} }
made = {base}; made = {base, restrictedId: 50000};
for (const {client} of [pat, devGame, hal]) { for (const {client} of [pat, devGame, hal]) {
client.socket.destroy(); client.socket.destroy();
} }
@@ -488,6 +576,8 @@ const second = async () => {
assert.deepStrictEqual(atLogin.clothing.map(entry => `${entry.id} ${entry.name}`), ["50000 Gold Crown", "50001 Quick Hat"]); assert.deepStrictEqual(atLogin.clothing.map(entry => `${entry.id} ${entry.name}`), ["50000 Gold Crown", "50001 Quick Hat"]);
assert.deepStrictEqual(atLogin.den.map(entry => entry.name), ["Test Chair"]); assert.deepStrictEqual(atLogin.den.map(entry => entry.name), ["Test Chair"]);
assert.strictEqual(byId(await pack(1000), 50001).layerDefId, made.base.layerDefId); assert.strictEqual(byId(await pack(1000), 50001).layerDefId, made.base.layerDefId);
assert.strictEqual(byId(atLogin.clothing, made.restrictedId).avatarUseFlags, "9007199254740990");
assert.strictEqual(byId(await pack(1000), made.restrictedId).avatarUseFlags, "9007199254740990");
assert.strictEqual((await strings())[9100001], "Quick Hat"); assert.strictEqual((await strings())[9100001], "Quick Hat");
const shop = await shopList(lou.client, lou.roomId, ODD_CLOTHING_SHOP); const shop = await shopList(lou.client, lou.roomId, ODD_CLOTHING_SHOP);
assert.ok(shop.includes("50001") && !shop.includes("50000")); assert.ok(shop.includes("50001") && !shop.includes("50000"));
+19 -8
View File
@@ -464,8 +464,19 @@ const run = async () => {
}); });
return {status: response.status, data: await response.json(), cookie: (response.headers.get("set-cookie") || "").split(";")[0]}; return {status: response.status, data: await response.json(), cookie: (response.headers.get("set-cookie") || "").split(";")[0]};
}; };
assert.match(await (await fetch(`${BASE}/admin`)).text(), /Server admin/); const oldAdmin = await fetch(`${BASE}/admin`, {redirect: "manual"});
assert.deepStrictEqual((await panel("state")).data, {needsSetup: true, needsSetupCode: false, signedIn: false}); assert.strictEqual(oldAdmin.status, 302);
assert.strictEqual(oldAdmin.headers.get("location"), "/dashboard/admin");
const oldMod = await fetch(`${BASE}/mod`, {redirect: "manual"});
assert.strictEqual(oldMod.status, 302);
assert.strictEqual(oldMod.headers.get("location"), "/dashboard/staff");
assert.match(await (await fetch(`${BASE}/dashboard`)).text(), /Burrow dashboard/);
const dashboardSlash = await fetch(`${BASE}/dashboard/`, {redirect: "manual"});
assert.strictEqual(dashboardSlash.status, 302);
assert.strictEqual(dashboardSlash.headers.get("location"), "/dashboard");
assert.match(await (await fetch(`${BASE}/dashboard/admin`)).text(), /Server admin/);
assert.match(await (await fetch(`${BASE}/dashboard/staff`)).text(), /Moderators/);
assert.deepStrictEqual((await panel("state")).data, {needsSetup: true, needsSetupCode: false, signedIn: false, discordLogin: false});
assert.strictEqual((await panel("overview")).status, 401); assert.strictEqual((await panel("overview")).status, 401);
assert.strictEqual((await panel("login", {password: "anything"})).status, 401); assert.strictEqual((await panel("login", {password: "anything"})).status, 401);
assert.strictEqual((await panel("setup", {password: "short"})).status, 400); assert.strictEqual((await panel("setup", {password: "short"})).status, 400);
@@ -544,14 +555,14 @@ const run = async () => {
assert.strictEqual((await panel("account", {username: "Robert", action: "rename", newName: "ROBERT"}, admin)).status, 200); assert.strictEqual((await panel("account", {username: "Robert", action: "rename", newName: "ROBERT"}, admin)).status, 200);
assert.strictEqual((await panel("account", {username: "robert", action: "rename", newName: "Bob"}, admin)).status, 200); assert.strictEqual((await panel("account", {username: "robert", action: "rename", newName: "Bob"}, admin)).status, 200);
// A new password for a player: the old one and old tokens stop working. // Staff cannot take over an account by setting its password; recovery is
// email-only from the account recovery page.
assert.strictEqual((await panel("account", {username: "foo", action: "password", password: "short"}, admin)).status, 400); assert.strictEqual((await panel("account", {username: "foo", action: "password", password: "short"}, admin)).status, 400);
assert.strictEqual((await panel("account", {username: "foo", action: "password", password: "New-password-4"}, admin)).status, 200); assert.strictEqual((await panel("account", {username: "foo", action: "password", password: "New-password-4"}, admin)).status, 400);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "foo", password: "KettlePass04"})).status, 401); assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "foo", password: "KettlePass04"})).status, 200);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {refresh_token: foo.refresh_token})).status, 401); assert.strictEqual((await postJson(`${BASE}/authenticate`, {refresh_token: foo.refresh_token})).status, 200);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "foo", password: "New-password-4"})).status, 200);
assert.strictEqual((await panel("account", {username: "foo", action: "delete"}, admin)).status, 200); assert.strictEqual((await panel("account", {username: "foo", action: "delete"}, admin)).status, 200);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "foo", password: "New-password-4"})).status, 401); assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "foo", password: "KettlePass04"})).status, 401);
// changing the admin password signs every other session out. // changing the admin password signs every other session out.
assert.strictEqual((await panel("password", {current: "nope", password: "admin-password-2"}, admin)).status, 403); assert.strictEqual((await panel("password", {current: "nope", password: "admin-password-2"}, admin)).status, 403);
+29 -1
View File
@@ -82,7 +82,7 @@ const arrive = async (username, password, room, totp, onLogin = async () => {})
await client.untilXt("rp"); await client.untilXt("rp");
} }
client.xt("au", rj[4], 1, 400, 400, 14, 1); client.xt("au", rj[4], 1, 400, 400, 14, 1);
return {client, login, roomId: rj[4], room: rj[3]}; return {client, login, roomId: rj[4], room: rj[3], token: auth.auth_token};
}; };
// the next moderator popup ("fd") of this kind, skipping earlier ones (a // the next moderator popup ("fd") of this kind, skipping earlier ones (a
@@ -240,9 +240,36 @@ const run = async () => {
assert.strictEqual((await halPage("/mod/api/login", {username: "Hal", password: people.Hal, code: codeAt(secrets.Hal, usedStep.Hal)})).status, 200); assert.strictEqual((await halPage("/mod/api/login", {username: "Hal", password: people.Hal, code: codeAt(secrets.Hal, usedStep.Hal)})).status, 200);
const halMe = (await halPage("/mod/api/me")).data; const halMe = (await halPage("/mod/api/me")).data;
assert.strictEqual(halMe.role, "helper"); assert.strictEqual(halMe.role, "helper");
assert.ok(halMe.permissions.includes("server.view"));
assert.ok(!halMe.permissions.includes("player.ban")); assert.ok(!halMe.permissions.includes("player.ban"));
const health = await halPage("/mod/api/server");
assert.strictEqual(health.status, 200);
assert.ok(Number.isInteger(health.data.players));
assert.ok(Number.isInteger(health.data.sockets.openConnections));
assert.strictEqual(typeof health.data.update.needsPublish, "boolean");
assert.ok(Array.isArray(health.data.update.changed));
assert.strictEqual((await halPage("/mod/api/act", {username: "Pip", action: "ban", hours: 1, reason: "x"})).data.error, "Your role cannot do that."); assert.strictEqual((await halPage("/mod/api/act", {username: "Pip", action: "ban", hours: 1, reason: "x"})).data.error, "Your role cannot do that.");
assert.match((await halPage("/mod/api/act", {username: "Mira", action: "silence", hours: 1})).data.error, /your rank or above/); assert.match((await halPage("/mod/api/act", {username: "Mira", action: "silence", hours: 1})).data.error, /your rank or above/);
// the Players page's list, narrowed to who is online, staff, banned or
// silenced (Ann was put out above); an unknown narrowing is everyone
const listed = async only => (await modPage(`/mod/api/players?only=${only}`)).data.players.map(player => player.username).sort();
assert.deepStrictEqual(await listed("staff"), ["Hal", "Mira"]);
const online = await listed("online");
assert.ok(["Hal", "Mira", "Pip"].every(name => online.includes(name)), online.join(", "));
assert.deepStrictEqual(await listed("banned"), []);
assert.deepStrictEqual(await listed("everything"), ["Ann", "Hal", "Mira", "Pip"]);
// the Masterpieces page: those waiting, and the last approved (by anyone,
// or only by this moderator), to take one back from
const paintings = (await modPage("/mod/api/masterpieces?mine=1")).data;
assert.deepStrictEqual([paintings.waiting, paintings.approved, paintings.recent], [[], [], []]);
// signed in through the game (a client the moderator is playing in hands
// over its login token): staff in the game now, from the game's address
const viaGame = webSession();
assert.strictEqual((await viaGame("/mod/api/game-login", {token: mira.token})).status, 200);
assert.strictEqual((await viaGame("/mod/api/me")).data.username, "Mira");
// a player's token, or none that is good, opens nothing
assert.strictEqual((await webSession()("/mod/api/game-login", {token: pip.token})).status, 401);
assert.strictEqual((await webSession()("/mod/api/game-login", {token: "0".repeat(64)})).status, 401);
// searching by address (against ban evasion) is for the roles that ban addresses // searching by address (against ban evasion) is for the roles that ban addresses
assert.strictEqual((await halPage("/mod/api/players?by=address&q=127.0.0.")).status, 403); assert.strictEqual((await halPage("/mod/api/players?by=address&q=127.0.0.")).status, 403);
assert.ok(Array.isArray((await modPage("/mod/api/players?by=address&q=127.0.0.")).data.players)); assert.ok(Array.isArray((await modPage("/mod/api/players?by=address&q=127.0.0.")).data.players));
@@ -305,6 +332,7 @@ const run = async () => {
const annAway = (await modPage("/mod/api/player?username=Ann")).data; const annAway = (await modPage("/mod/api/player?username=Ann")).data;
assert.strictEqual(annAway.warnings, 4); assert.strictEqual(annAway.warnings, 4);
assert.strictEqual(annAway.warningList[0].seen, false); assert.strictEqual(annAway.warningList[0].seen, false);
assert.deepStrictEqual(await listed("silenced"), ["Ann"]);
const annBack = await arrive("Ann", people.Ann, SAREPIA); const annBack = await arrive("Ann", people.Ann, SAREPIA);
assert.deepStrictEqual((await untilPopup(annBack.client, "fw")).slice(2, 4), ["fw", "1"]); // the bullying one assert.deepStrictEqual((await untilPopup(annBack.client, "fw")).slice(2, 4), ["fw", "1"]); // the bullying one
assert.strictEqual((await modPage("/mod/api/player?username=Ann")).data.warningList[0].seen, true); assert.strictEqual((await modPage("/mod/api/player?username=Ann")).data.warningList[0].seen, true);