Compare commits

..
4 Commits
Author SHA1 Message Date
Snipzil 08780d7e69 Merge branch 'main' of https://github.com/burrow-dev/burrow-server 2026-10-19 10:12:46 -04:00
Snipzil 8babe9cb39 feat(client): add staff tooling and resilient room UI
Deliver the in-game moderation and event overlays, theatre playback bridge, room-effect controls, staff shortcuts, friend-game prompts, and Windows emoji handling fixes.

Improve den editing with explicit front, behind, and natural stacking choices that persist without changing item position. Correct item display layers and custom artwork behavior, and make popup controls reliably closable.

Include performance-mode settings, animation and input safeguards, and rebuild ajclient.swf from the patched sources so the served client exactly matches the feature set.
2026-10-19 10:10:11 -04:00
Snipzil 5c9b2e0066 feat(world): expand events, rewards, and den behavior
Add owner/developer room-effect controls and chat shortcuts, staff movement that bypasses full or locked destinations, in-game moderation entry points, theatre video synchronization, and shared room effects.

Restore game and trade popups, reliably award refreshments and game rewards, support pet play outside parties, correct den placement categories, improve den item persistence, and refresh custom-item and masterpiece behavior.

Harden room, party, pet, minigame, and item state handling with matching feature and restored-system regression coverage.
2026-10-19 10:09:50 -04:00
Snipzil 7dee29010a 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.
2026-10-19 10:09:35 -04:00
58 changed files with 3434 additions and 386 deletions

No files matched your search

+4
View File
@@ -1,6 +1,10 @@
# Burrow
Burrow is a private server for AJ Classic.
## Account-recovery email
Set `AJ_RECOVERY_MAIL_URL` and `AJ_RECOVERY_MAIL_TOKEN` to an HTTPS mail-relay or transactional-email webhook. Burrow posts `{to, subject, text}` with a Bearer token. Until both are configured, email recovery intentionally does not issue a usable reset link. New web sign-ups are asked for a recovery email; password and 2FA recovery require the one-time link sent there.
# Security
An independent security audit by a Strawberry Jam contributor, who is not part of the Burrow team, found no malware in the Burrow client or server (client v1.2.0, server as of 17 October 2026). Every file in every installer was checked against its source and against the official Electron, NSIS and Adobe Flash releases. The report also lists the weaknesses found, with fixes, and every check can be repeated by anyone.
+12 -2
View File
@@ -102,6 +102,13 @@ module.exports = {
turnstile: env.AJ_TURNSTILE_SITE_KEY && env.AJ_TURNSTILE_SECRET
? {siteKey: env.AJ_TURNSTILE_SITE_KEY, secret: env.AJ_TURNSTILE_SECRET} : null,
// Account-recovery mail is delivered to this HTTPS webhook. It receives
// {to, subject, text}; point it at the transactional-mail provider or
// small mail relay you use. Recovery is deliberately unavailable until
// both values are set, rather than ever exposing a reset link in a page.
recoveryMail: env.AJ_RECOVERY_MAIL_URL && env.AJ_RECOVERY_MAIL_TOKEN
? {url: env.AJ_RECOVERY_MAIL_URL, token: env.AJ_RECOVERY_MAIL_TOKEN} : null,
// asset mirror: anything not served locally is fetched once from here and
// cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only.
upstreamContent: env.AJ_UPSTREAM || "https://ajcontent.akamaized.net/",
@@ -115,8 +122,11 @@ module.exports = {
// before is still kept out).
requireDevice: env.AJ_REQUIRE_DEVICE !== "0",
// Discord (lib/discord.js): an application's id and secret for linking a
// player's Discord account on the account page (its OAuth2 redirect must
// be <siteUrl>account/discord/callback), and a bot in Burrow's Discord
// player's Discord account on the account page and for allowed accounts to
// sign in to /dashboard/admin (OAuth2 redirects:
// <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
// booster badge left alone without the last two.
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).
const DEFAULT_FILTER = {level: 1, mode: 1, words: ""};
const MAX_PASSWORD_LENGTH = 100;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// parts of the game a player can switch off for their own account, each
// enforced where the game asks for it (featureOn below).
// the Early Member badge (lib/badges.js) goes to an account made while
@@ -216,6 +217,9 @@ const normalize = account => {
// what the player set on the account page (lib/manage.js).
account.features = {...Object.fromEntries(FEATURES.map(name => [name, true])), ...account.features}; // false = switched off
account.locked = account.locked === true; // nobody gets into the game until its owner unlocks it
account.recoveryEmail = typeof account.recoveryEmail === "string" && EMAIL_PATTERN.test(account.recoveryEmail)
? account.recoveryEmail.toLowerCase() : "";
account.recoveryTokens = Array.isArray(account.recoveryTokens) ? account.recoveryTokens.filter(token => token && token.expires > now()) : [];
account.logins = account.logins || []; // {at, via, address, ok}, newest first: lib/accounts.js recordLogin
account.roomThemes = account.roomThemes || {}; // room -> theme, for rooms given a look of their own ("!theme here")
account.randomTheme = account.randomTheme === true; // a theme picked afresh at every login
@@ -249,6 +253,9 @@ const normalize = account => {
if (account.discordId !== undefined && !/^\d{5,25}$/.test(String(account.discordId))) {
delete account.discordId; // the linked Discord account's id
}
// Set only by the owner in /admin. A matching linked Discord identity may
// use this account to open the owner dashboard (lib/discord.js).
account.adminDashboardAccess = account.adminDashboardAccess === true;
account.badges = Array.isArray(account.badges) ? account.badges : []; // badge ids, given in the admin panel
account.bio = typeof account.bio === "string" ? account.bio : ""; // their own words, for the card's Bio tab
// seconds spent in the game in all (lib/world.js counts it), and whether
@@ -717,6 +724,7 @@ const register = (username, password, avatar = {}) => {
activeAvatar: 1,
// early Member, for an account made while there are no more than a hundred.
badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [],
recoveryEmail: typeof avatar.email === "string" && EMAIL_PATTERN.test(avatar.email.trim()) ? avatar.email.trim().toLowerCase() : "",
});
console.log(`[accounts] registered "${logText(username)}" (id ${logText(account.id)})`);
return {account};
+5 -2
View File
@@ -257,7 +257,10 @@ const handle = async (route, params, body, from) => {
if (device && devices.banOf(device)) {
return {status: 403, body: {error: "device_banned"}};
}
const {username, password, avatarType} = body || {};
const {username, password, avatarType, email} = body || {};
if (config.recoveryMail && (typeof email !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim()))) {
return {status: 400, body: {error: "invalid_email"}};
}
// the terms and the privacy policy, and old enough to agree to them:
// said by the one signing up, on the page or in the client.
if ((body || {}).agreed !== true) {
@@ -279,7 +282,7 @@ const handle = async (route, params, body, from) => {
if (!STARTER_ANIMALS.includes(avatarType)) {
return {status: 400, body: {error: "choose_animal"}};
}
const result = accounts.register(username, password, {type: avatarType});
const result = accounts.register(username, password, {type: avatarType, email});
if (result.account) {
result.account.agreed = {version: config.termsVersion, at: Math.floor(Date.now() / 1000)};
accounts.save(result.account);
+104 -1
View File
@@ -4,6 +4,7 @@ const accounts = require("./accounts.js");
const chatlog = require("./chatlog.js");
const customItems = require("./customitems.js");
const itemControl = require("./itemcontrol.js");
const wearRules = require("./wearrules.js");
const modNotes = require("./modnotes.js");
const defpacks = require("./defpacks.js");
const disguises = require("./disguises.js");
@@ -73,7 +74,10 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
const {account} = session;
const avatar = activeAvatar(account);
const before = wornItems(account, avatar);
const wanted = account.items.filter(item => invs.includes(item.inv)).slice(0, MAX_WORN);
// Saved outfits are a second equip route, so they obey the same rule as
// the item editor. A saved id remains in the outfit in case staff later
// remove the rule; it simply cannot be put on while blocked.
const wanted = account.items.filter(item => invs.includes(item.inv) && wearRules.mayWear(item.def, avatar.type)).slice(0, MAX_WORN);
const takenOff = before.filter(item => !wanted.includes(item));
account.outfitUndo = {avInvId: avatar.avInvId, items: before.map(item => item.inv)};
for (const item of takenOff) {
@@ -596,6 +600,59 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
};
const staffCommands = {
// A short-lived room control for owners, admins and developers. It uses
// the avatar protocol rather than persisting any player appearance.
roomfx: {
permission: "room.effects",
run(session, words) {
const room = session.room;
const effect = (words[0] || "").toLowerCase();
if (!room || !["small", "normal", "big", "rainbow", "clear"].includes(effect)) {
tell(session, "Use: !roomfx small, !roomfx normal, !roomfx big, !roomfx rainbow, or !roomfx clear");
return;
}
const send = (type, value) => {
for (const target of room.sessions) {
for (const viewer of room.sessions) {
viewer.sendXt("uc", room.id, target.id, String(value), type);
}
}
};
const stopRainbow = () => {
if (room.roomEffectTimer) {
clearInterval(room.roomEffectTimer);
delete room.roomEffectTimer;
}
};
if (effect === "rainbow") {
stopRainbow();
let hue = 0;
room.roomEffectTimer = setInterval(() => {
if (room.sessions.size === 0) {
stopRainbow();
return;
}
const colour = [0xFF4040, 0xFFB340, 0xF8FF40, 0x50E860, 0x40CFFF, 0x7560FF, 0xDC55FF][hue++ % 7];
send(8, colour);
}, 350);
room.roomEffectTimer.unref();
tell(session, "Rainbow effect started for everyone in this room. !roomfx clear stops it.");
}
else {
stopRainbow();
if (effect === "small" || effect === "big" || effect === "normal") {
send(14, effect === "small" ? 0.7 : effect === "big" ? 1.35 : 1);
tell(session, `Everyone in this room is now ${effect === "normal" ? "normal size" : effect}.`);
}
else {
send(8, 0);
send(14, 1);
tell(session, "Room effects cleared.");
}
}
modlog.record(session.account.username, "room effect (in game)", "", `${effect}: ${roomTitle(room)}`);
},
},
// "!item clothing|den ID NAME": a new item made from the game's item ID
// (lib/customitems.js), free, every colour of the one it is made from;
// everyone has it at once. the moderator panel's Items page does more.
@@ -633,6 +690,38 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
tell(session, on.length ? `Staff online: ${on.join(", ")}` : "No staff online.");
},
},
// Opens the same in-game moderation window as a player's card. This is
// useful when a moderator already knows the name and does not need to
// hunt through search results first.
mod: {
permission: "player.view",
run(session, words) {
const target = words.length ? findOnline(words.join(" ")) : null;
if (!target) {
tell(session, words.length ? `${words.join(" ")} is not online.` : "Use: !mod PLAYER");
return;
}
if (target.account !== session.account && roles.roleOf(target.account) && !roles.outranks(session.account, target.account)) {
tell(session, "Staff of your rank or above are for someone higher up to deal with.");
return;
}
session.sendXt("xui", -1, "moderate", target.account.username);
},
},
// Owners, admins and developers get the room-effects panel from chat.
// `host` is an intuitive alias for event hosts.
event: {
permission: "room.effects",
run(session) {
session.sendXt("xui", -1, "event");
},
},
host: {
permission: "room.effects",
run(session) {
session.sendXt("xui", -1, "event");
},
},
// "!note PLAYER text": a note for the other staff (lib/modnotes.js),
// never shown to the player. "!notes PLAYER": the latest few.
note: {
@@ -681,6 +770,20 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
setInvisible(session, !session.invisible);
},
},
reject: {
permission: "player.names",
run(session, words) {
withTarget(session, words, "Use: !reject PLAYER", true, target => {
if (target.account.nameRejected) {
tell(session, `${target.account.username}'s name is already rejected.`);
return;
}
staffModeration().actions.rejectName(target.account, session.account.username);
tell(session, `${target.account.username} was signed out and must choose a new name.`);
logged(session, "rejected username", target);
});
},
},
// "!lock clothing|den ID", "!unlock clothing|den ID", "!locked": items
// kept out of the item finder for players (lib/itemcontrol.js).
lock: {
+23 -2
View File
@@ -69,19 +69,39 @@ const apply = entry => defpacks.setCustomItem(entry.kind, rowOf(entry), entry.na
// "xdi" [.., .., kind, json]: def rows with their names, as JSON. a field
// may not hold "%" (lib/sfs.js drops it), so a "%" in a name is written as
// JSON's %.
const xtRows = rows => JSON.stringify(rows).replace(/%/g, "\\u0025");
const messages = entries => {
const out = [];
for (const kind of KINDS) {
// a picture waiting for a moderator is not shown yet
const rows = entries.filter(entry => entry.kind === kind && !entry.pending)
.map(entry => ({...rowOf(entry), name: entry.name, art: entry.artPending ? "" : entry.art || "", artMode: entry.artMode || "sticker"}));
.map(entry => ({...(kind === "clothing" ? defpacks.clientItemRow(rowOf(entry)) : rowOf(entry)), name: entry.name,
art: entry.artPending ? "" : entry.art || "", artMode: entry.artMode || "sticker"}));
for (let at = 0; at < rows.length; at += CHUNK) {
out.push([kind, JSON.stringify(rows.slice(at, at + CHUNK)).replace(/%/g, "\\u0025")]);
out.push([kind, xtRows(rows.slice(at, at + CHUNK))]);
}
}
return out;
};
// The patched client accepts ordinary clothing rows through xdi as well as
// newly made ones. That lets a moderation rule take effect in an already
// open editor instead of waiting for its next def-pack download.
const sendClothingDefs = ids => {
const rows = [...new Set(ids.map(Number))].map(id => {
const entry = items.get("clothing").get(id);
// A refreshed custom row must retain the extra xdi-only fields. Omitting
// them makes a live client lose its custom name or picture while its
// avatar-use flag is being updated.
return entry ? {...defpacks.clientItemRow(rowOf(entry)), name: entry.name, art: entry.artPending ? "" : entry.art || "",
artMode: entry.artMode || "sticker"} : defpacks.clientItemDef(id);
}).filter(row => row && row.type === TYPE_CLOTHING);
for (let at = 0; at < rows.length; at += CHUNK) {
broadcast("xdi", "clothing", xtRows(rows.slice(at, at + CHUNK)));
}
};
const announce = entry => {
if (entry.pending) {
return;
@@ -348,6 +368,7 @@ module.exports = {
session.sendXt("xdi", -1, ...params);
}
},
sendClothingDefs,
// lib/world.js says how to reach every game playing.
connect(broadcastXt) {
broadcast = broadcastXt;
+43 -2
View File
@@ -8,6 +8,7 @@ const config = require("../config.js");
const sales = require("./sales.js");
const badges = require("./badges.js");
const extraMusic = require("./extramusic.js");
const wearRules = require("./wearrules.js");
// defPack ids, from loader.DefPacksDefHelper in the client.
const DEF_ITEM = 1000;
@@ -42,6 +43,7 @@ const DEF_PET_TOY = 1063;
const DEF_WORLD_ITEMS = 1064;
const DEF_NPC = 1025;
const DEF_NAMEBAR_BADGE = 1049;
const DEF_EMOTICON = 1036;
const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items: plain, mannequin
const DEN_ITEM_MASTERPIECE = 2725;
@@ -70,6 +72,32 @@ const LAYER_EYES = "3";
const TYPE_CLOTHING = "1";
const EVERY_AVATAR = "9007199254740991"; // avatarUseFlags with a bit set for each animal type
// ItemXtCommManager checks bit (avatar type - 1). BigInt avoids losing a
// bit in JavaScript's 53-bit Number representation while preserving the
// string form the AMF def pack uses.
const clientAvatarUseFlags = itemId => {
let flags = BigInt(EVERY_AVATAR);
for (const type of wearRules.blockedTypes(itemId)) {
if (type <= 53) {
flags &= ~(1n << BigInt(type - 1));
}
}
return String(flags);
};
// One transform is used for fetched packs and for the live `xdi` definition
// updates sent to games that are already running.
const clientItemRow = def => {
const row = {...def};
if (row.type === TYPE_CLOTHING) {
row.avatarUseFlags = clientAvatarUseFlags(row.id);
}
else if (row.type === "0" && row.layerId === LAYER_EYES) {
row.avatarUseFlags = EVERY_AVATAR;
}
return row;
};
// rooms the official room pack no longer lists but whose files an older
// build on the CDN still has (lib/cdn.js looks there): the Summer Carnival,
// dropped after build 1828.
@@ -317,9 +345,9 @@ const alwaysOnSale = (pack, ids) => {
// the rows put back or added (SHARED_CHANGES).
const CLIENT_PACKS = new Map([
[DEF_ITEM, pack => {
for (const def of Object.values(pack)) {
for (const [key, def] of Object.entries(pack)) {
if (def.type === TYPE_CLOTHING || (def.type === "0" && def.layerId === LAYER_EYES)) {
def.avatarUseFlags = EVERY_AVATAR;
pack[key] = clientItemRow(def);
}
}
sales.stamp("clothing", pack);
@@ -397,6 +425,9 @@ let musicIds = []; // den items that are music tracks
let roomDefsById = new Map();
let badgeIds = []; // name tag badges, ascending
let npcDefs = new Map(); // the characters of the adventures, see lib/disguises.js
// An avatar attachment is named by its emoticon definition id on the wire,
// while AvatarWorldView needs the media id stored by that definition.
let emoticonMediaIds = new Map();
// A pack whose feature can be done without: missing (offline and never
// cached) just leaves that feature empty.
@@ -463,6 +494,7 @@ const init = async () => {
petFoodDefs = await loadOptional(DEF_PET_FOOD);
petToyDefs = await loadOptional(DEF_PET_TOY);
npcDefs = new Map((await loadOptional(DEF_NPC)).map(def => [Number(def.id), def]));
emoticonMediaIds = new Map((await loadOptional(DEF_EMOTICON)).map(def => [Number(def.id), Number(def.mediaRef)]));
partyDefs = new Map((await loadOptional(DEF_PARTY)).map(def => {
const room = roomPathsById.get(Number(def.roomDefId));
return [Number(def.id), {
@@ -544,6 +576,14 @@ module.exports = {
denItemDef: id => denItemDefs.get(Number(id)),
denItemIds: () => denItemIds,
clientPack,
// A changing rule must not leave the cached item pack permissive. The next
// client request remakes it, and current games receive an xdi row too.
invalidateClientItemPack: () => clientPackBodies.delete(DEF_ITEM),
clientItemRow,
clientItemDef: id => {
const def = itemDefs.get(Number(id));
return def ? clientItemRow(def) : null;
},
string: id => (Object.hasOwn(strings, id) ? String(strings[id]) : ""),
stringId: text => {
if (!stringIds) {
@@ -558,6 +598,7 @@ module.exports = {
},
badgeIds: () => badgeIds,
npcDef: id => npcDefs.get(Number(id)),
emoticonMediaId: id => emoticonMediaIds.get(Number(id)) || 0,
oddDenItemIds: () => oddDenItemIds,
// den items that exist to be given by id and are in no shop.
unsoldDenItemIds: () => extraMusic.ids,
+18 -5
View File
@@ -5,6 +5,7 @@ const accounts = require("./accounts.js");
const achievements = require("./achievements.js");
const config = require("../config.js");
const defpacks = require("./defpacks.js");
const wearRules = require("./wearrules.js");
const epicDens = require("./epicdens.js");
const masterpieces = require("./masterpieces.js");
const {CURRENCIES, MAX_DEN_ITEMS, hasRoom, activeAvatar, resolvePurchase, isUint} = require("./player.js");
@@ -52,13 +53,21 @@ const LAYER_EYES = "3";
const isMannequin = item => (defpacks.denItemDef(item.def) || {}).specialType === SPECIAL_MANNEQUIN;
const mannequinAvatarType = item => Number((defpacks.denItemDef(item.def) || {}).mannequinAvatarDefId) || 0;
const mannequinOf = item => item.mannequin || {colors: [0, 0, 0], pattern: 0, eyes: 0, worn: [0, 0, 0, 0, 0]};
const mannequinBody = ({colors, pattern, eyes}) => [colors[0], colors[1], pattern, colors[2], eyes];
// the clothing a mannequin of `owner`'s wears, slot by slot (undefined for
// an empty slot or a piece the owner no longer has).
const mannequinClothes = (owner, item) => mannequinOf(item).worn.map(inv => (inv ? owner.items.find(piece => piece.inv === inv) : undefined));
const mannequinClothes = (owner, item) => {
const type = mannequinAvatarType(item);
return mannequinOf(item).worn.map(inv => {
const piece = inv ? owner.items.find(candidate => candidate.inv === inv) : undefined;
return piece && (!type || wearRules.mayWear(piece.def, type)) ? piece : undefined;
});
};
// for the owner's own list (MannequinData.setupDataInvIdsOnly): the body,
// then the five inventory ids.
@@ -74,12 +83,13 @@ const mannequinShownFields = (owner, item) =>
// what the den editor sent for one mannequin, checked: [baseColor,
// patternColor, patternDefId, eyeColor, eyeDefId, tail, leg, back, neck,
// head]. null when any of it is not a whole number in range.
const readMannequin = (account, fields) => {
const readMannequin = (account, item, fields) => {
if (fields.length !== 10 || !fields.every(isUint)) {
return null;
}
const [base, patternColor, pattern, eyeColor, eyes, ...worn] = fields.map(Number);
const bodyPart = (defId, layer) => (defId && (defpacks.itemDef(defId) || {}).layerId === layer ? defId : 0);
const type = mannequinAvatarType(item);
return {
colors: [base, patternColor, eyeColor],
pattern: bodyPart(pattern, LAYER_PATTERN),
@@ -87,7 +97,7 @@ const readMannequin = (account, fields) => {
worn: worn.map((inv, slot) => {
const piece = inv && account.items.find(candidate => candidate.inv === inv);
const def = piece && defpacks.itemDef(piece.def);
return def && MANNEQUIN_SLOT_LAYERS[slot].includes(def.layerId) ? inv : 0;
return def && MANNEQUIN_SLOT_LAYERS[slot].includes(def.layerId) && (!type || wearRules.mayWear(piece.def, type)) ? inv : 0;
}),
};
};
@@ -135,7 +145,10 @@ const sendDenState = (session, room, forceReload = true) => {
session.sendXt("ds", room.id, placed.length, pets.length, forceReload ? 1 : 0,
...placed.flatMap(item => {
const spot = spotOf(item, owner.activeDen);
return [item.inv, item.def, 1, spot.x, spot.y, item.version, spot.flip, "", ...masterpieces.itemFields(item),
// Keep the editor's real placement category. Sending every placed
// object as category 1 made wall/floor items enter the wrong display
// layer when a den was reloaded or another player visited.
return [item.inv, item.def, spot.cat || 1, spot.x, spot.y, item.version, spot.flip, "", ...masterpieces.itemFields(item),
...mannequinShownFields(owner, item), 0];
}),
...pets.flatMap(pet => [pet.inv, pet.lBits, pet.uBits, pet.eBits, PET_CATEGORY, pet.inDen.x, pet.inDen.y, pet.inDen.flip,
@@ -404,7 +417,7 @@ const handlers = ({others, findOnline}) => {
else {
delete item.spots[account.activeDen];
}
const mannequin = isMannequin(item) && readMannequin(account, outfit);
const mannequin = isMannequin(item) && readMannequin(account, item, outfit);
if (mannequin) {
// A piece of clothing is on one mannequin at a time.
for (const other of mannequins) {
+99 -9
View File
@@ -35,27 +35,57 @@ const BOOSTER = "booster";
const linking = () => Boolean(config.discord.clientId && config.discord.clientSecret);
const boostChecks = () => Boolean(config.discord.botToken && config.discord.guildId);
const redirectUri = () => `${config.siteUrl}account/discord/callback`;
const adminRedirectUri = () => `${config.siteUrl}dashboard/admin/discord/callback`;
const staffRedirectUri = () => `${config.siteUrl}dashboard/staff/discord/callback`;
// a link under way: state (in Discord's address) -> {accountId, nonce (in a
// cookie of the browser that asked), expires}. both must come back.
const states = new Map();
const adminStates = new Map();
const staffStates = new Map();
const start = account => {
for (const [state, entry] of states) {
const newState = statesMap => {
for (const [state, entry] of statesMap) {
if (entry.expires < Date.now()) {
states.delete(state);
statesMap.delete(state);
}
}
if (states.size >= MAX_STATES) {
states.delete(states.keys().next().value);
if (statesMap.size >= MAX_STATES) {
statesMap.delete(statesMap.keys().next().value);
}
const state = crypto.randomBytes(24).toString("hex");
const nonce = crypto.randomBytes(24).toString("hex");
states.set(state, {accountId: account.id, nonce, expires: Date.now() + STATE_MINUTES * 60000});
statesMap.set(state, {nonce, expires: Date.now() + STATE_MINUTES * 60000});
return {state, nonce};
};
const authorize = (redirect, state) => {
const url = new URL(AUTHORIZE);
url.search = new URLSearchParams({client_id: config.discord.clientId, response_type: "code", scope: "identify",
redirect_uri: redirectUri(), state, prompt: "consent"}).toString();
return {url: url.href, nonce};
redirect_uri: redirect, state, prompt: "consent"}).toString();
return url.href;
};
const start = account => {
const {state, nonce} = newState(states);
states.get(state).accountId = account.id;
return {url: authorize(redirectUri(), state), nonce};
};
// A separate OAuth state and redirect for the owner dashboard. The Discord
// account must already be linked to a Burrow account explicitly granted
// adminDashboardAccess; knowing a Discord name is never enough.
const startAdmin = () => {
const {state, nonce} = newState(adminStates);
return {url: authorize(adminRedirectUri(), state), nonce};
};
// Staff sign in through a separately scoped state and callback. A Discord
// identity is only useful here after its owner has linked it to their own
// Burrow account; modpanel.js also verifies that account remains active staff.
const startStaff = () => {
const {state, nonce} = newState(staffStates);
return {url: authorize(staffRedirectUri(), state), nonce};
};
const call = async (path, options = {}) => {
@@ -154,6 +184,66 @@ const finish = async (state, nonce, code) => {
}
};
const finishAdmin = async (state, nonce, code) => {
const entry = typeof state === "string" ? adminStates.get(state) : null;
adminStates.delete(state);
const digest = text => crypto.createHash("sha256").update(String(text)).digest();
if (!entry || entry.expires < Date.now() || typeof nonce !== "string" || !crypto.timingSafeEqual(digest(entry.nonce), digest(nonce)) || !code) {
return {error: "expired"};
}
try {
const token = await call("/oauth2/token", {
method: "POST",
headers: {"Content-Type": "application/x-www-form-urlencoded"},
body: new URLSearchParams({client_id: config.discord.clientId, client_secret: config.discord.clientSecret,
grant_type: "authorization_code", code, redirect_uri: adminRedirectUri()}).toString(),
});
if (token.status !== 200 || !token.body.access_token) {
return {error: "discord"};
}
const me = await call("/users/@me", {headers: {Authorization: `Bearer ${token.body.access_token}`}});
if (me.status !== 200 || !/^\d{5,25}$/.test(String(me.body.id))) {
return {error: "discord"};
}
const account = accounts.all().find(candidate => candidate.discordId === String(me.body.id) && candidate.adminDashboardAccess);
return account ? {ok: true, account} : {error: "denied"};
}
catch (err) {
console.log(`[discord] admin sign-in failed: ${logText(err.message)}`);
return {error: "discord"};
}
};
const finishStaff = async (state, nonce, code) => {
const entry = typeof state === "string" ? staffStates.get(state) : null;
staffStates.delete(state);
const digest = text => crypto.createHash("sha256").update(String(text)).digest();
if (!entry || entry.expires < Date.now() || typeof nonce !== "string" || !crypto.timingSafeEqual(digest(entry.nonce), digest(nonce)) || !code) {
return {error: "expired"};
}
try {
const token = await call("/oauth2/token", {
method: "POST",
headers: {"Content-Type": "application/x-www-form-urlencoded"},
body: new URLSearchParams({client_id: config.discord.clientId, client_secret: config.discord.clientSecret,
grant_type: "authorization_code", code, redirect_uri: staffRedirectUri()}).toString(),
});
if (token.status !== 200 || !token.body.access_token) {
return {error: "discord"};
}
const me = await call("/users/@me", {headers: {Authorization: `Bearer ${token.body.access_token}`}});
if (me.status !== 200 || !/^\d{5,25}$/.test(String(me.body.id))) {
return {error: "discord"};
}
const account = accounts.all().find(candidate => candidate.discordId === String(me.body.id));
return account ? {ok: true, account} : {error: "denied"};
}
catch (err) {
console.log(`[discord] staff sign-in failed: ${logText(err.message)}`);
return {error: "discord"};
}
};
// the link undone, by the player or an admin; the booster badge goes with it.
const unlink = account => {
const had = Boolean(account.discordId || account.discord);
@@ -202,4 +292,4 @@ const startup = () => {
}
};
module.exports = {linking, boostChecks, start, finish, unlink, startup};
module.exports = {linking, boostChecks, start, finish, startAdmin, finishAdmin, startStaff, finishStaff, unlink, startup};
+60 -5
View File
@@ -50,6 +50,19 @@ const MIME = {
".otf": "font/otf",
};
// The desktop webview caches the SWF aggressively. Include the local SWF's
// timestamp in its URL so a freshly built client is actually picked up after
// the server restarts, without making an operator remember to bump a config
// value by hand.
const clientRevision = () => {
try {
return Math.floor(fs.statSync(config.clientSwf).mtimeMs).toString(36);
}
catch (_) {
return "unknown";
}
};
const flashVars = () => ({
content: config.baseUrl,
// the game's own server to the SWF, whatever its name: it loads the card
@@ -69,7 +82,7 @@ const flashVars = () => ({
// member or not may be chosen on any server (lib/accounts.js)
membershipChoice: true,
smoke_version: config.deployVersion,
clientURL: `${config.baseUrl}${config.deployVersion}/ajclient.swf?v=${config.buildVersion}`,
clientURL: `${config.baseUrl}${config.deployVersion}/ajclient.swf?v=${config.buildVersion}-${clientRevision()}`,
startupRoom: config.startupRoom,
// "-1" turns the client's stats socket off.
sbStatTrackerIp: "-1",
@@ -293,7 +306,7 @@ const repeatedError = text => {
const THEMED_ROOM = /^(\d+)\/roomDefs\/theme_(\d+)\/(.+)$/;
// the web pages, as against what the game and the client load
const SITE_PAGES = /^\/(?:register|terms|privacy|commands|shop|account|mod|download)?\/?$/;
const SITE_PAGES = /^\/(?:register|terms|privacy|commands|shop|account|mod|admin|dashboard|download)?\/?$/;
// the installers /download offers, those of them config.downloadsDir has
const DOWNLOADS = [
@@ -652,22 +665,54 @@ const handle = async (req, res) => {
return;
}
const isAdmin = url.pathname === "/admin" || url.pathname.startsWith("/admin/");
const dashboardAdmin = url.pathname === "/dashboard/admin" || url.pathname.startsWith("/dashboard/admin/")
|| url.pathname === "/dashboard/api/admin" || url.pathname.startsWith("/dashboard/api/admin/");
const dashboardStaff = url.pathname === "/dashboard/staff" || url.pathname.startsWith("/dashboard/staff/")
|| url.pathname === "/dashboard/api/staff" || url.pathname.startsWith("/dashboard/api/staff/");
const isDashboard = url.pathname === "/dashboard" || dashboardAdmin || dashboardStaff;
const isAdmin = url.pathname === "/admin" || url.pathname.startsWith("/admin/") || dashboardAdmin;
const isAccount = url.pathname === "/account" || url.pathname.startsWith("/account/");
const isMod = url.pathname === "/mod" || url.pathname.startsWith("/mod/");
const isMod = url.pathname === "/mod" || url.pathname.startsWith("/mod/") || dashboardStaff;
// the pages that keep a cookie answer only under this server's own names:
// a request sent here by a page of another name (one whose name was made
// to point at this machine, say) is not theirs to make. nor is such a
// request ever this machine's own, wherever it came from.
if (!limits.hostAllowed(req)) {
if (isAdmin || isAccount || isMod) {
if (isDashboard || isAdmin || isAccount || isMod) {
send(res, 421, {error: "wrong_host"});
return;
}
from.local = false;
}
// One entry point for the owner and staff dashboards. The old addresses
// stay as bookmark-friendly redirects; their APIs remain available for
// installed tools and are not redirected.
if (req.method === "GET" && url.pathname === "/dashboard/") {
res.writeHead(302, {Location: `/dashboard${url.search}`, "Content-Length": 0});
res.end();
return;
}
if (req.method === "GET" && url.pathname === "/dashboard") {
res.setHeader("Cache-Control", "no-store");
res.setHeader("X-Frame-Options", "DENY");
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("Referrer-Policy", "no-referrer");
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "dashboard.html")), "text/html; charset=utf-8");
return;
}
if (req.method === "GET" && url.pathname === "/admin") {
res.writeHead(302, {Location: "/dashboard/admin", "Content-Length": 0});
res.end();
return;
}
if (req.method === "GET" && url.pathname === "/mod") {
res.writeHead(302, {Location: "/dashboard/staff", "Content-Length": 0});
res.end();
return;
}
// the admin panel sets its own, stricter headers: none of the cross-origin
// allowances below apply to it. on a public server it is not there at all
// for anyone but this machine and the addresses named (config.adminAllow).
@@ -676,6 +721,11 @@ const handle = async (req, res) => {
send(res, 404, "Not found", "text/plain");
return;
}
if (dashboardAdmin) {
url.pathname = url.pathname.startsWith("/dashboard/api/admin")
? url.pathname.replace("/dashboard/api/admin", "/admin/api")
: url.pathname.replace("/dashboard/admin", "/admin");
}
if (url.pathname === "/admin/api/itemart") {
res.setHeader("Cache-Control", "no-store");
await itemArtUpload(req, res, url, from, null, panel.signedIn);
@@ -697,6 +747,11 @@ const handle = async (req, res) => {
// and the moderator panel (lib/modpanel.js), which is there for anyone to
// reach: its moderators are players, wherever they are.
if (dashboardStaff) {
url.pathname = url.pathname.startsWith("/dashboard/api/staff")
? url.pathname.replace("/dashboard/api/staff", "/mod/api")
: url.pathname.replace("/dashboard/staff", "/mod");
}
if (isMod && url.pathname === "/mod/api/itemart") {
res.setHeader("Cache-Control", "no-store");
await itemArtUpload(req, res, url, from, modpanel.signedInAs);
+93 -1
View File
@@ -3,6 +3,7 @@
const accounts = require("./accounts.js");
const customItems = require("./customitems.js");
const defpacks = require("./defpacks.js");
const wearRules = require("./wearrules.js");
// what staff who make items (items.create: admins and developers) may do
// about who has them:
@@ -83,6 +84,94 @@ const lockedList = () => [...lockSet()].map(entry => {
return {kind, id: Number(id), name: nameOf(kind, id)};
});
// The animals a moderator can select in the dashboard. Avatar types, rather
// than a hand-written list of species, keep this correct for packs added in
// a later game build.
const wearAnimals = () => defpacks.avatarTypes().sort((one, two) => one - two).map(type => {
const def = defpacks.avatarDef(type) || {};
return {id: Number(type), name: defpacks.string(def.titleStrRef || def.nameStrId) || def.abbrName || `Animal ${type}`};
});
const wearRuleList = () => wearRules.all().flatMap(rule => {
const found = item("clothing", rule.id);
return found.error ? [] : [{id: found.id, name: nameOf(found.kind, found.id), blockedTypes: rule.blocked}];
});
// Remove a new restriction from every possible display of an item. A clothing
// association has an avatar slot; a mannequin keeps the inventory ids in
// five den-item slots. Both must be cleaned or a rule can be bypassed by
// switching animals or visiting a den.
const removeBlockedUses = (account, itemId, blocked) => {
const disallowedAvatarSlots = new Set(account.avatars.filter(avatar => blocked.has(Number(avatar.type))).map(avatar => avatar.avInvId));
const matchingInventory = new Set(account.items.filter(piece => piece.def === itemId).map(piece => piece.inv));
let removed = 0;
let clothingChanged = false;
let mannequinChanged = false;
for (const piece of account.items) {
if (piece.def !== itemId || !Array.isArray(piece.on)) {
continue;
}
const kept = piece.on.filter(avInvId => !disallowedAvatarSlots.has(avInvId));
if (kept.length !== piece.on.length) {
removed += piece.on.length - kept.length;
piece.on = kept;
clothingChanged = true;
}
}
for (const denItem of account.denItems) {
const mannequinType = Number((defpacks.denItemDef(denItem.def) || {}).mannequinAvatarDefId);
if (!blocked.has(mannequinType) || !denItem.mannequin || !Array.isArray(denItem.mannequin.worn)) {
continue;
}
const kept = denItem.mannequin.worn.map(inv => (matchingInventory.has(Number(inv)) ? 0 : inv));
if (kept.some((inv, index) => inv !== denItem.mannequin.worn[index])) {
removed += kept.filter(inv => inv === 0).length - denItem.mannequin.worn.filter(inv => inv === 0).length;
denItem.mannequin.worn = kept;
mannequinChanged = true;
}
}
return {changed: clothingChanged || mannequinChanged, mannequinChanged, removed};
};
// Make a clothing item unavailable to the selected animal types. `world`
// refreshes games and den visitors after the persistent state is cleaned.
const setWearRule = (id, blockedTypes, world) => {
const found = item("clothing", id);
if (found.error) {
return found;
}
const animals = wearAnimals();
const allowed = new Set(animals.map(animal => animal.id));
if (!Array.isArray(blockedTypes) || blockedTypes.length > allowed.size || !blockedTypes.every(Number.isInteger)
|| blockedTypes.some(type => !allowed.has(type))) {
return {error: "Choose only animals from the list."};
}
const blocked = [...new Set(blockedTypes)].sort((one, two) => one - two);
const changedRule = wearRules.setBlockedTypes(found.id, blocked).changed;
let accountsChanged = 0;
let removed = 0;
const blockedSet = new Set(blocked);
for (const account of accounts.all()) {
const cleaned = removeBlockedUses(account, found.id, blockedSet);
if (!cleaned.changed) {
continue;
}
accountsChanged++;
removed += cleaned.removed;
accounts.save(account);
world.wearRulesChanged(account, cleaned.mannequinChanged);
}
// Packs downloaded after this moment, and games already open, use the
// same rule-to-flag transformation. Server checks above remain authority.
defpacks.invalidateClientItemPack();
customItems.sendClothingDefs([found.id]);
const animalNames = blocked.map(type => animals.find(animal => animal.id === type).name);
const subject = describe(found.kind, found.id);
const suffix = blocked.length ? `cannot be worn by ${animalNames.join(", ")}.` : "can be worn by every animal again.";
return {ok: `${subject} ${suffix}${removed ? ` Took it off ${removed} existing use${removed === 1 ? "" : "s"}.` : ""}`,
detail: `clothing ${found.id}; blocked types ${blocked.join(",") || "none"}; ${accountsChanged} account${accountsChanged === 1 ? "" : "s"} changed`, changed: changedRule};
};
// every one of an item an account has, out of its inventory (and its trade
// list). `world` tells a game playing (lib/world.js itemsTaken). returns how
// many went.
@@ -135,7 +224,10 @@ const deleteCustom = (kind, id, world) => {
if (lockSet().delete(key(kind, entry.id))) {
saveLocks();
}
if (kind === "clothing") {
wearRules.forget(entry.id);
}
return {ok: `Deleted ${entry.name} (${kind === "den" ? "den item" : "clothing"} ${entry.id})${count ? `, and took ${count} from players` : ""}.`};
};
module.exports = {isLocked, setLocked, lockedList, take, deleteCustom};
module.exports = {isLocked, setLocked, lockedList, wearAnimals, wearRuleList, setWearRule, take, deleteCustom};
+8
View File
@@ -3,6 +3,7 @@
const accounts = require("./accounts.js");
const achievements = require("./achievements.js");
const defpacks = require("./defpacks.js");
const wearRules = require("./wearrules.js");
const {CURRENCIES, MAX_ITEMS, MAX_WORN, activeAvatar, addClothing, sendClothingAdded, sendClothingRemoved, resolvePurchase} = require("./player.js");
// clothing: buying, wearing and recycling (client side: ItemXtCommManager).
@@ -82,6 +83,13 @@ module.exports = ({others, sendItemList}) => {
}
const item = account.items.find(candidate => candidate.inv === invIdx);
if (item) {
// The client flag only makes the control gray. Never trust it: a
// crafted iu packet or a stale client must not bypass a staff rule.
// Check before changing `on`, so a refused request cannot take off
// an otherwise valid item as a side effect.
if (worn && !wearRules.mayWear(item.def, avatar.type)) {
return null;
}
item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId);
// no more than MAX_WORN on one animal: what is over stays off.
if (worn && account.items.filter(candidate => candidate.on.includes(avatar.avInvId)).length >= MAX_WORN) {
+72 -1
View File
@@ -22,6 +22,7 @@ const masterpieces = require("./masterpieces.js");
const defpacks = require("./defpacks.js");
const support = require("./support.js");
const totp = require("./totp.js");
const recoveryMail = require("./recoverymail.js");
const world = require("./world.js");
// the account page at /account: what a player can do about their own
@@ -50,6 +51,8 @@ const discordCookie = (value, maxAgeSeconds) =>
const SESSION_HOURS = 12;
const TEN_MINUTES_MS = 600000;
const MAX_NOTE = 120;
const RECOVERY_TOKEN_MS = 30 * 60 * 1000;
const recoveryHash = token => crypto.createHash("sha256").update(token).digest("hex");
// wrong passwords before further tries from an address are refused for a
// while, as for the launcher's sign-in (lib/http.js).
@@ -59,6 +62,7 @@ const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_M
// at it and is then signed out.
const WRONG_PASSWORDS_ALLOWED = 5;
const wrongPasswords = limits.limiter(WRONG_PASSWORDS_ALLOWED, TEN_MINUTES_MS);
const recoveryRequests = limits.limiter(5, TEN_MINUTES_MS);
// what may be done from the page of a ban (above).
const BANNED_MAY = ["password", "twoStepStart", "twoStepConfirm", "twoStepOff", "forgetDevices", "delete", "appeal"];
// and from the page of a rejected username: the same, with a new name in
@@ -142,6 +146,7 @@ const bannedProfile = (account, ban) => {
appeal: appeal && {createdAt: appeal.createdAt, text: appeal.text, status: appeal.status, reply: appeal.reply, handledAt: appeal.handledAt},
appealLimit: bans.MAX_APPEAL,
twoStep: twoStepOf(account),
recoveryEmail: account.recoveryEmail ? `${account.recoveryEmail.slice(0, 2)}…${account.recoveryEmail.slice(account.recoveryEmail.lastIndexOf("@"))}` : "",
};
};
@@ -177,6 +182,7 @@ const profile = (account, from) => {
banned: null,
locked: account.locked,
twoStep: twoStepOf(account),
recoveryEmail: account.recoveryEmail ? `${account.recoveryEmail.slice(0, 2)}…${account.recoveryEmail.slice(account.recoveryEmail.lastIndexOf("@"))}` : "",
discord: account.discord,
discordLinked: Boolean(account.discordId),
discordLinking: discord.linking(),
@@ -204,7 +210,7 @@ const profile = (account, from) => {
// hash, the 2FA secret, device passes), and what other tables hold of it.
// what others wrote about it (reports, a moderator's notes) is not theirs
// to be handed, and is not here.
const SECRET_FIELDS = ["salt", "hash", "totp", "totpSetup", "devices", "modNotes"];
const SECRET_FIELDS = ["salt", "hash", "totp", "totpSetup", "devices", "modNotes", "recoveryTokens"];
const dataOf = account => ({
exportedAt: new Date().toISOString(),
server: config.baseUrl,
@@ -524,6 +530,10 @@ const handle = async (req, res, url, from, web) => {
web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "account.html"))), "text/html; charset=utf-8");
return;
}
if (route === "GET /account/recover") {
web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "recover.html"))), "text/html; charset=utf-8");
return;
}
if (req.method === "POST" && !sameOrigin(req)) {
reply(403, {error: "forbidden"});
return;
@@ -531,6 +541,67 @@ const handle = async (req, res, url, from, web) => {
const body = req.method === "POST" ? await web.readJson(req) : {};
switch (route) {
case "POST /account/api/recover/request": {
// Always give the same reply: neither account names nor email addresses
// can be discovered from this endpoint.
if (!from.local && !recoveryRequests.allow(from.key)) {
reply(429, {ok: "If the account and recovery email match, we sent a recovery link."});
return;
}
const account = accounts.byName(String(body.username || ""));
const email = String(body.email || "").trim().toLowerCase();
const kind = body.kind === "twoStep" ? "twoStep" : "password";
if (account && account.recoveryEmail && account.recoveryEmail === email && recoveryMail.available()) {
const token = crypto.randomBytes(32).toString("hex");
account.recoveryTokens = (account.recoveryTokens || []).filter(entry => entry.expires > Date.now());
account.recoveryTokens.push({hash: recoveryHash(token), kind, expires: Date.now() + RECOVERY_TOKEN_MS});
accounts.save(account);
const link = new URL(`/account/recover?token=${token}`, config.siteUrl).href;
const sent = await recoveryMail.send({to: account.recoveryEmail, subject: "Burrow account recovery",
text: `A ${kind === "twoStep" ? "2FA reset" : "password reset"} was requested for ${account.username}. Open this link within 30 minutes:\n${link}\n\nIf this was not you, ignore this email.`});
if (!sent) {
account.recoveryTokens = account.recoveryTokens.filter(entry => entry.hash !== recoveryHash(token));
accounts.save(account);
}
}
reply(200, {ok: "If the account and recovery email match, we sent a recovery link."});
return;
}
case "POST /account/api/recover/check": {
const token = String(body.token || "");
const account = [...accounts.all()].find(candidate => (candidate.recoveryTokens || []).some(entry => entry.hash === recoveryHash(token) && entry.expires > Date.now()));
const entry = account && account.recoveryTokens.find(candidate => candidate.hash === recoveryHash(token) && candidate.expires > Date.now());
reply(entry ? 200 : 400, entry ? {kind: entry.kind} : {error: "This recovery link is invalid or expired."});
return;
}
case "POST /account/api/recover/complete": {
const token = String(body.token || "");
const account = [...accounts.all()].find(candidate => (candidate.recoveryTokens || []).some(entry => entry.hash === recoveryHash(token) && entry.expires > Date.now()));
const entry = account && account.recoveryTokens.find(candidate => candidate.hash === recoveryHash(token) && candidate.expires > Date.now());
if (!entry) {
reply(400, {error: "This recovery link is invalid or expired."});
return;
}
if (entry.kind === "password") {
const problem = accounts.setPassword(account, body.password);
if (problem) {
reply(400, {error: problem === "weak_password" ? "That password is too easy to guess." : "Use 10+ characters with an uppercase letter, lowercase letter and digit."});
return;
}
}
else if (totp.isOn(account)) {
totp.turnOff(account);
accounts.revokeTokens(account);
}
account.recoveryTokens = [];
accounts.save(account);
signOutOthers(account, null);
endStaffSessions(account);
world.moderation.actions.kick(account);
console.log(`[recovery] ${logText(entry.kind)} reset for "${logText(account.username)}" after email verification from ${logText(from.address)}`);
reply(200, {ok: entry.kind === "password" ? "Password reset. You can sign in now." : "2FA reset. You can sign in now."});
return;
}
case "POST /account/api/login": {
const key = String(body.username || "").trim().toLowerCase();
if (!from.local && failuresByAddress.blocked(from.key)) {
+31 -12
View File
@@ -41,6 +41,7 @@ const SCHEMA = `
status INTEGER NOT NULL,
frame INTEGER NOT NULL,
reviewed_at INTEGER,
reviewed_by TEXT,
likes TEXT NOT NULL,
image BLOB NOT NULL
);
@@ -81,11 +82,16 @@ const uploadsPerHour = limits.limiter(30, 3600000);
const now = () => Math.floor(Date.now() / 1000);
const db = () => accounts.database();
const known = new Map(); // id -> {id, creator, createdAt, status, frame, likes: [account ids]}
const known = new Map(); // id -> {id, creator, createdAt, status, frame, reviewedAt, reviewedBy, likes: [account ids]}
const tokens = new Map(); // upload token -> {account id, expires (ms)}
const load = () => {
db().exec(SCHEMA);
// who approved it: a moderator's username, "admin", or null when nobody
// looked (review was off, or it was approved before this was kept).
if (!db().prepare("PRAGMA table_info(masterpieces)").all().some(column => column.name === "reviewed_by")) {
db().exec("ALTER TABLE masterpieces ADD COLUMN reviewed_by TEXT");
}
fs.mkdirSync(folder(), {recursive: true});
// pictures still in the table move out into files, once.
for (const row of db().prepare("SELECT id FROM masterpieces WHERE length(image) > 0").all()) {
@@ -93,8 +99,9 @@ const load = () => {
fs.writeFileSync(fileOf(row.id), Buffer.from(picture));
db().prepare("UPDATE masterpieces SET image = ? WHERE id = ?").run(NO_IMAGE, row.id);
}
for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, likes FROM masterpieces").all()) {
known.set(row.id, {id: row.id, creator: row.creator_id, createdAt: row.created_at, status: row.status, frame: row.frame, likes: JSON.parse(row.likes)});
for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, reviewed_at, reviewed_by, likes FROM masterpieces").all()) {
known.set(row.id, {id: row.id, creator: row.creator_id, createdAt: row.created_at, status: row.status, frame: row.frame,
reviewedAt: row.reviewed_at, reviewedBy: row.reviewed_by, likes: JSON.parse(row.likes)});
}
};
@@ -203,7 +210,7 @@ const upload = async (token, image) => {
forget(painting.id);
}
}
const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, likes: []};
const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, reviewedAt: null, reviewedBy: null, likes: []};
fs.writeFileSync(fileOf(painting.id), image);
db().prepare("INSERT INTO masterpieces (id, creator_id, created_at, status, frame, likes, image) VALUES (?, ?, ?, ?, ?, '[]', ?)")
.run(painting.id, painting.creator, painting.createdAt, painting.status, painting.frame, NO_IMAGE);
@@ -211,10 +218,13 @@ const upload = async (token, image) => {
return painting.id;
};
const setStatus = (painting, status) => {
// `by`: who approved it, when someone did.
const setStatus = (painting, status, by = null) => {
painting.status = status;
db().prepare("UPDATE masterpieces SET status = ?, frame = ?, reviewed_at = ? WHERE id = ?")
.run(status, painting.frame, status === APPROVED ? now() : null, painting.id);
painting.reviewedAt = status === APPROVED ? now() : null;
painting.reviewedBy = status === APPROVED ? by : null;
db().prepare("UPDATE masterpieces SET status = ?, frame = ?, reviewed_at = ?, reviewed_by = ? WHERE id = ?")
.run(status, painting.frame, painting.reviewedAt, painting.reviewedBy, painting.id);
};
// may this account make an item of that painting, in that frame? (Step 3,
@@ -268,12 +278,13 @@ const mayView = (id, address, addressOf) => {
return painting.status === APPROVED || Boolean(maker && addressOf(maker) && addressOf(maker) === address);
};
const approve = id => {
// `by`: the moderator's username, or "admin".
const approve = (id, by) => {
const painting = get(id);
if (!painting || painting.status !== PENDING) {
return false;
}
setStatus(painting, APPROVED);
setStatus(painting, APPROVED, by);
return true;
};
@@ -318,11 +329,14 @@ const gallery = () => {
return {pool: hung.slice(0, GALLERY_SPOTS), pluspool: hung.slice(GALLERY_SPOTS)};
};
// newest first: the waiting ones by when they were made, the approved ones
// by when they were approved, so that one let in by mistake is near the top.
const list = status => [...known.values()].filter(painting => painting.status === status)
.sort((one, other) => other.createdAt - one.createdAt)
.sort((one, other) => (other.reviewedAt || other.createdAt) - (one.reviewedAt || one.createdAt))
.map(painting => {
const maker = creatorOf(painting.id);
return {id: painting.id, creator: maker ? maker.username : "(deleted account)", createdAt: painting.createdAt, frame: painting.frame, likes: painting.likes.length};
return {id: painting.id, creator: maker ? maker.username : "(deleted account)", createdAt: painting.createdAt, frame: painting.frame, likes: painting.likes.length,
approvedAt: painting.reviewedAt, approvedBy: painting.reviewedBy};
});
// both lists for the panels, narrowed to makers whose names have
@@ -335,6 +349,11 @@ const listsFor = creator => {
return {waiting: narrowed(list(PENDING)), approved: narrowed(list(APPROVED))};
};
// the last `count` approved, the latest first, for the moderator panel to
// take one back from: only the ones `by` approved, when given.
const recentlyApproved = (count, by = "") => list(APPROVED)
.filter(painting => !by || String(painting.approvedBy || "").toLowerCase() === by.toLowerCase()).slice(0, count);
const madeBy = account => [...known.values()].filter(painting => painting.creator === account.id).map(painting => painting.id);
// generic lists: (mediaId, name string id) pairs, or null when `listId` is
@@ -343,7 +362,7 @@ const frameList = listId =>
([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null);
module.exports = {
load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, frameList,
load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, recentlyApproved, frameList,
needsReview, setNeedsReview, madeBy,
PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES,
};
+60
View File
@@ -63,6 +63,10 @@ const CARNIVAL_COST = 5; // gems a go
const MAX_TICKETS_PER_GO = 300;
const CURRENCY_TICKETS = 1;
const INVASION_COST = 10; // gems a go, as the machine's own screen says
const SMOOTHIE_COLOURS = new Set(["purple", "orange", "red", "yellow"]);
// The game's attachment state is client-defined (for example, the cocoa
// recipe). It is not an item id and must never become protocol markup.
const attachmentExtra = value => String(value ?? "").replace(/[\r\n%,]/g, "").slice(0, 128);
const awardsPerMinute = limits.limiter(120, 60000);
const invitesPerMinute = limits.limiter(20, 60000);
@@ -204,6 +208,23 @@ module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => {
}
};
// Food-machine games reward a short-lived avatar attachment. Replying
// with "_a" is important: MinigameManager turns it into the same local
// attachment action used by den objects, which then sends the normal
// user-communication packet to the room. Sending that packet ourselves
// skips the local state and leaves the player with nothing visible.
const grantAttachment = (session, game, reply, emoticonDefId, extra = "") => {
if (game.attachmentGranted) {
return;
}
const state = attachmentExtra(extra);
if (!defpacks.emoticonMediaId(emoticonDefId)) {
return;
}
game.attachmentGranted = true;
reply("_a", emoticonDefId, state);
};
// takes the player out of the game they are in, if any, and out of an
// invitation.
const leave = session => {
@@ -450,6 +471,45 @@ module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => {
// what a game asks of the server while it runs, by game class and then by
// the message's first word. `reply` answers the asker as an "mm".
const MESSAGES = {
// These machines do not give an inventory item. They award temporary
// Holdable Icons: popcorn (emoticon 1), smoothies (2), and hot cocoa
// (5). The final field carries the selected visual state.
MicroPopcorn: {
_a(session, game, [kind], reply) {
if (kind === "1") {
grantAttachment(session, game, reply, 1);
}
},
},
MicroSmoothie: {
_a(session, game, [kind, colour], reply) {
const selected = String(colour || "").toLowerCase();
if (kind === "2" && SMOOTHIE_COLOURS.has(selected)) {
grantAttachment(session, game, reply, 2, selected);
}
},
},
MicroHotCocoa: {
_a(session, game, [kind, cocoaInfo], reply) {
if (kind === "5") {
grantAttachment(session, game, reply, 5, cocoaInfo);
}
},
},
CottonCandy: {
_a(session, game, [kind, emoticonInfo], reply) {
if (kind === "30") {
grantAttachment(session, game, reply, 30, emoticonInfo);
}
},
},
BradyChemistrySet: {
_a(session, game, [kind, emoticonInfo], reply) {
if (kind === "6") {
grantAttachment(session, game, reply, 6, emoticonInfo);
}
},
},
// the claw machines: "cp" pays for a go and learns whether the claw
// will hold and what on ([won, isDenItem, defId, ?, version]; anything
// but 1 or 0 for `won` means "not enough gems"); "cd" keeps (1) or
+225 -9
View File
@@ -1,6 +1,7 @@
"use strict";
const crypto = require("crypto");
const {execFileSync} = require("child_process");
const fs = require("fs");
const path = require("path");
const accounts = require("./accounts.js");
@@ -15,6 +16,7 @@ const itemArt = require("./itemart.js");
const playerItems = require("./playeritems.js");
const defpacks = require("./defpacks.js");
const devices = require("./devices.js");
const discordLinks = require("./discord.js");
const limits = require("./limits.js");
const manage = require("./manage.js");
const masterpieces = require("./masterpieces.js");
@@ -24,6 +26,7 @@ const reports = require("./reports.js");
const roles = require("./roles.js");
const staff = require("./staff.js");
const stats = require("./stats.js");
const sfs = require("./sfs.js");
const support = require("./support.js");
const totp = require("./totp.js");
const world = require("./world.js");
@@ -50,11 +53,15 @@ const world = require("./world.js");
// moderator's name, for the admin panel.
const COOKIE = "ajc_mod";
const DISCORD_COOKIE = "ajc_mod_discord";
const SESSION_HOURS = 12;
const TEN_MINUTES_MS = 600000;
const MAX_BAN_HOURS = 24 * 365 * 10;
const MAX_MESSAGE_LENGTH = 200;
const MAX_RECENT_NOTES = 15;
const RECENT_PAINTINGS = 12;
const GIT_STATUS_CACHE_MS = 10000;
const PROJECT_ROOT = path.resolve(__dirname, "..");
const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS);
const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator
@@ -64,13 +71,75 @@ const addressSearched = new Map(); // moderator's account id -> the address they
const sha256 = text => crypto.createHash("sha256").update(text).digest("hex");
// This is read-only and intentionally never fetches, pulls or pushes. It
// gives staff a conspicuous reminder that the running checkout contains work
// which has not made it to its tracked remote yet.
let gitStatusCachedAt = 0;
let gitStatusCached = null;
const gitUpdateState = () => {
if (gitStatusCached && Date.now() - gitStatusCachedAt < GIT_STATUS_CACHE_MS) {
return gitStatusCached;
}
try {
const runGit = args => execFileSync("git", args, {cwd: PROJECT_ROOT, encoding: "utf8", timeout: 1500, maxBuffer: 128 * 1024}).trim();
const raw = runGit(["status", "--porcelain=v1", "-z"]);
const entries = raw ? raw.split("\0").filter(Boolean) : [];
const changed = [];
for (let index = 0; index < entries.length; index++) {
const entry = entries[index];
const status = entry.slice(0, 2);
changed.push({status: status.trim() || "?", path: entry.slice(3)});
// A rename/copy has another NUL-delimited source path. The destination
// is the useful file to show in the warning.
if (status[0] === "R" || status[0] === "C") {
index++;
}
}
let ahead = 0;
let behind = 0;
let remoteKnown = true;
try {
const [behindText, aheadText] = runGit(["rev-list", "--left-right", "--count", "@{upstream}...HEAD"]).split(/\s+/);
behind = Number(behindText) || 0;
ahead = Number(aheadText) || 0;
}
catch (_) {
remoteKnown = false;
}
gitStatusCached = {available: true, changed, ahead, behind, remoteKnown,
needsPublish: changed.length > 0 || ahead > 0};
}
catch (err) {
gitStatusCached = {available: false, changed: [], ahead: 0, behind: 0, remoteKnown: false,
needsPublish: false, error: "Git status could not be read."};
}
gitStatusCachedAt = Date.now();
return gitStatusCached;
};
const cookieToken = req => {
const match = new RegExp(`(?:^|;\\s*)${COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "");
return match ? match[1] : null;
};
const cookieHeader = (token, maxAgeSeconds) =>
`${COOKIE}=${token}; Path=/mod; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
`${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const discordCookie = (value, maxAgeSeconds) =>
`${DISCORD_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const beginSession = (account, res, address, detail = "") => {
accounts.recordLogin(account, "mod", address);
accounts.save(account);
for (const [hash, session] of sessions) {
if (session.expiry < Date.now()) {
sessions.delete(hash);
}
}
const token = crypto.randomBytes(24).toString("hex");
sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000});
res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600));
modlog.record(account.username, "signed in", "", detail);
};
// may this account use the panel (still)?
const mayModerate = account => Boolean(account && roles.isActiveStaff(account, world.moderation.banRemaining(account) !== 0));
@@ -116,10 +185,18 @@ const playerRow = (account, playing) => {
const playing = () => new Map(world.players().map(player => [player.username, player.room || "(between rooms)"]));
// by name (lib/staff.js says in what order).
const findPlayers = query => {
// what the Players page's list can be narrowed to (lib/staff.js `keep`).
const ONLY = {
online: (account, online) => online.has(account.username),
banned: account => world.moderation.banRemaining(account) !== 0 || devices.bannedId(account) !== 0,
silenced: account => world.moderation.silenceRemaining(account) !== 0,
staff: account => Boolean(roles.roleOf(account)),
};
// by name (lib/staff.js says in what order), and `only` one of ONLY's.
const findPlayers = (query, only) => {
const online = playing();
const {found, total} = staff.findAccounts(query);
const {found, total} = staff.findAccounts(query, Object.hasOwn(ONLY, only) ? ONLY[only] : undefined);
return {players: found.map(account => playerRow(account, online)), total};
};
@@ -334,6 +411,38 @@ const handle = async (req, res, url, from, web) => {
web.send(res, 200, captcha.withScriptVersion(await stats.withView(await fs.promises.readFile(path.join(config.publicDir, "mod.html")))), "text/html; charset=utf-8");
return;
}
// The nonce cookie is Lax only for Discord's cross-site return. The normal
// staff-session cookie remains Strict and is issued after the callback.
if (route === "GET /mod/discord/login") {
if (!discordLinks.linking()) {
res.writeHead(302, {Location: "/dashboard/staff?discord=off"});
res.end();
return;
}
const {url: to, nonce} = discordLinks.startStaff();
res.setHeader("Set-Cookie", discordCookie(nonce, 600));
res.writeHead(302, {Location: to});
res.end();
return;
}
if (route === "GET /mod/discord/callback") {
const nonce = (new RegExp(`(?:^|;\\s*)${DISCORD_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1];
const result = url.searchParams.get("error") ? {error: "cancelled"}
: await discordLinks.finishStaff(url.searchParams.get("state"), nonce, url.searchParams.get("code"));
if (result.ok && !mayModerate(result.account)) {
result.ok = false;
result.error = "denied";
}
if (result.ok) {
beginSession(result.account, res, from.address, "through Discord");
console.log(`[mod] ${result.account.username} signed in with Discord from ${from.address}`);
}
const sessionCookie = res.getHeader("Set-Cookie");
res.setHeader("Set-Cookie", sessionCookie ? [sessionCookie, discordCookie("", 0)] : discordCookie("", 0));
res.writeHead(302, {Location: `/dashboard/staff?discord=${result.ok ? "ok" : result.error}`});
res.end();
return;
}
if (req.method === "POST" && !limits.originAllowed(req)) {
reply(403, {error: "forbidden"});
return;
@@ -343,7 +452,7 @@ const handle = async (req, res, url, from, web) => {
switch (route) {
case "GET /mod/api/state": {
const mod = signedInAs(req);
reply(200, {signedIn: Boolean(mod), username: mod ? mod.username : ""});
reply(200, {signedIn: Boolean(mod), username: mod ? mod.username : "", discordLogin: discordLinks.linking()});
return;
}
// username, password and a code, all three every time.
@@ -400,6 +509,50 @@ const handle = async (req, res, url, from, web) => {
reply(200, {ok: true, username: account.username});
return;
}
// signed in through the game instead: a client the moderator is playing
// in hands over the game's login token, so they need not type their
// password and a code again. taken only for active staff with 2FA on
// (so the game's own sign-in took a code), who are in the game now, and
// asking from the address that game connected from: the token alone,
// copied elsewhere, opens nothing.
case "POST /mod/api/game-login": {
if (!from.local && failuresByAddress.blocked(from.key)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
const account = accounts.byToken(body.token);
const session = account ? world.findOnline(account.username) : null;
if (!account || !roles.roleOf(account)) {
failuresByAddress.record(from.key);
reply(401, {error: "Sign in with your password and code."});
return;
}
if (!totp.isOn(account)) {
reply(403, {error: "Turn on 2FA on your account page first."});
return;
}
if (!mayModerate(account)) {
reply(403, {error: "This account cannot sign in here now."});
return;
}
if (!session || limits.key(session.address) !== from.key) {
reply(401, {error: "Be in the game on this computer, or sign in with your password and code."});
return;
}
accounts.recordLogin(account, "mod", from.address);
accounts.save(account);
for (const [hash, kept] of sessions) {
if (kept.expiry < Date.now()) {
sessions.delete(hash);
}
}
const cookie = crypto.randomBytes(24).toString("hex");
sessions.set(sha256(cookie), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000});
res.setHeader("Set-Cookie", cookieHeader(cookie, SESSION_HOURS * 3600));
modlog.record(account.username, "signed in", "", "through the game");
reply(200, {ok: true, username: account.username});
return;
}
case "POST /mod/api/logout": {
const token = cookieToken(req);
if (token) {
@@ -462,6 +615,22 @@ const handle = async (req, res, url, from, web) => {
reviewRoutes(route.replace(" /mod/api/", " "), body, reply, done, mod.username, "/mod/api/itemart");
return;
}
// This deliberately precedes the broad /items branch. Moderators may
// receive the narrow items.restrict permission without also being allowed
// to make, delete, lock or take items.
if (/^\/mod\/api\/items\/wear-rules\/?$/.test(url.pathname)) {
if (!roles.can(mod, "items.restrict")) {
reply(403, {error: "Your role does not allow that."});
return;
}
// Normalize the harmless trailing-slash spelling before dispatching it.
itemRoutes(`${req.method} items/wear-rules`, url, body, reply, done, {
username: mod.username,
artBase: "/mod/api/itemart",
mayTake: () => false,
});
return;
}
// custom items (lib/customitems.js), for whoever may make them.
if (url.pathname.startsWith("/mod/api/items")) {
if (!roles.can(mod, "items.create")) {
@@ -475,6 +644,32 @@ const handle = async (req, res, url, from, web) => {
});
return;
}
// Service health is intentionally separate from player data: every staff
// role may see it, including developers who have no player-view access.
if (route === "GET /mod/api/server") {
if (!roles.can(mod, "server.view")) {
reply(403, {error: "Your role does not allow that."});
return;
}
const memory = process.memoryUsage();
const players = world.players();
const rooms = new Set(players.map(player => player.room).filter(Boolean));
reply(200, {
uptimeSeconds: Math.floor(process.uptime()),
players: players.length,
rooms: rooms.size,
memory: {
rssMb: Math.round(memory.rss / 1048576),
heapUsedMb: Math.round(memory.heapUsed / 1048576),
heapTotalMb: Math.round(memory.heapTotal / 1048576),
},
sockets: sfs.health(),
update: gitUpdateState(),
now: Date.now(),
});
return;
}
// everything else shows players and what they did: not for a role that
// only makes things.
if (!roles.can(mod, "player.view")) {
@@ -488,6 +683,7 @@ const handle = async (req, res, url, from, web) => {
paintings: masterpieces.list(masterpieces.PENDING).length});
return;
// other accounts the same person may have, and their story (lib/staff.js).
case "GET /mod/api/alts": {
const account = accounts.byName(url.searchParams.get("username") || "");
@@ -517,7 +713,7 @@ const handle = async (req, res, url, from, web) => {
return;
}
if (searchBy !== "address") {
reply(200, findPlayers(url.searchParams.get("q")));
reply(200, findPlayers(url.searchParams.get("q"), url.searchParams.get("only")));
return;
}
// by address: only the address typed, which is written down (once
@@ -670,9 +866,12 @@ const handle = async (req, res, url, from, web) => {
return;
}
// paintings players framed (lib/masterpieces.js).
// paintings players framed (lib/masterpieces.js), and the ones approved
// last, to take one back that should not have been (mine=1: only the
// ones this moderator approved).
case "GET /mod/api/masterpieces":
reply(200, {...masterpieces.listsFor(url.searchParams.get("creator")), waitingCount: masterpieces.list(masterpieces.PENDING).length});
reply(200, {...masterpieces.listsFor(url.searchParams.get("creator")), waitingCount: masterpieces.list(masterpieces.PENDING).length,
recent: masterpieces.recentlyApproved(RECENT_PAINTINGS, url.searchParams.get("mine") === "1" ? mod.username : "")});
return;
case "GET /mod/api/masterpiece": {
@@ -700,7 +899,7 @@ const handle = async (req, res, url, from, web) => {
return;
}
const result = body.action === "approve"
? (world.approveMasterpiece(id) ? {ok: "Approved."} : {error: "No such painting waiting."})
? (world.approveMasterpiece(id, mod.username) ? {ok: "Approved."} : {error: "No such painting waiting."})
: body.action === "reject" || body.action === "remove"
? (world.removeMasterpiece(id) ? {ok: "Removed for good. Its maker was told and given a Masterpiece Token."} : {error: "No such painting."})
: {error: "Unknown action."};
@@ -723,6 +922,8 @@ const handle = async (req, res, url, from, web) => {
// whether it is locked out of the finder: for the dashboards' lock.
// GET items/base?kind=clothing|den&id=N: an item of the game's to
// make one from (its name and colours), to check before making it.
// GET items/wear-rules?q=WORDS: clothing search results, animal choices and
// current per-animal wear blocks. POST it with {id, blockedTypes} to set.
// POST items {action: "create", kind, base, name, cost, members, colors}
// or {action: "update", kind, id, and any of name, cost, members, colors, inShop}
// or {action: "lock" | "unlock", kind, id}: kept out of the item finder
@@ -730,6 +931,21 @@ const handle = async (req, res, url, from, web) => {
// or {action: "delete", kind, id}: a custom item, out of the game and every inventory.
const itemRoutes = (route, url, body, reply, done, actor) => {
switch (route) {
case "GET items/wear-rules": {
const search = new URLSearchParams({kind: "clothing", q: url.searchParams.get("q") || ""});
const found = admin.search(search, null, true);
const rules = itemControl.wearRuleList();
const blockedByItem = new Map(rules.map(rule => [rule.id, rule.blockedTypes]));
reply(200, {animals: itemControl.wearAnimals(), rules, total: found.total,
results: found.results.slice(0, 20).map(entry => ({id: entry.id, name: entry.locked ? entry.name.replace(/ \(locked\)$/, "") : entry.name,
custom: entry.id >= customItems.FIRST_ID, blockedTypes: blockedByItem.get(entry.id) || []}))});
return;
}
case "POST items/wear-rules": {
const result = itemControl.setWearRule(body.id, body.blockedTypes, world);
done(result, result.ok ? "item wear rule changed" : "", "", `clothing ${body.id}`);
return;
}
case "GET items":
reply(200, {items: customItems.list().map(entry => ({...entry, baseName: customItems.baseName(entry), locked: itemControl.isLocked(entry.kind, entry.id),
artUrl: itemArt.urlOf(entry, actor.artBase)})),
+46 -23
View File
@@ -43,6 +43,7 @@ const {activeAvatar} = require("./player.js");
const PASSWORD_SETTING = "admin_password"; // "salt:hash"
const COOKIE = "ajc_admin";
const DISCORD_COOKIE = "ajc_admin_discord";
const SESSION_HOURS = 12;
const MIN_PASSWORD_LENGTH = 8;
const MAX_PASSWORD_LENGTH = 200;
@@ -112,7 +113,10 @@ const signedIn = req => {
};
const cookieHeader = (token, maxAgeSeconds) =>
`${COOKIE}=${token}; Path=/admin; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
`${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const discordCookie = (value, maxAgeSeconds) =>
`${DISCORD_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const signIn = res => {
for (const [hash, expiry] of sessions) {
@@ -144,6 +148,7 @@ const accountRow = (account, playing) => {
locked: account.locked,
twoStep: totp.isOn(account),
discord: account.discord,
adminDashboardAccess: Boolean(account.adminDashboardAccess),
bio: account.bio,
badges: account.badges,
featuresOff: accounts.FEATURES.filter(name => !accounts.featureOn(account, name)),
@@ -384,32 +389,12 @@ const act = (account, body) => {
const {actions, PERMANENT} = world.moderation;
const name = account.username;
switch (body.action) {
case "password": {
const passwordProblem = accounts.setPassword(account, body.password);
if (passwordProblem) {
return {error: passwordProblem === "weak_password" ? "That password is too easy to guess: it is a common one, or has your username in it."
: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."};
}
actions.kick(account);
manage.forget(account); // their account page too, whoever has it open
modpanel.forget(account);
return {ok: `${name} has a new password and was signed out.`};
}
// the owner locks and unlocks on the account page; this is for when
// they cannot.
case "unlock":
account.locked = false;
accounts.save(account);
return {ok: `${name} is unlocked.`};
// for a player who lost their phone and their recovery codes: their
// password alone signs them in again.
case "twoStepOff":
if (!totp.isOn(account)) {
return {error: `${name} does not use 2FA.`};
}
totp.turnOff(account);
accounts.save(account);
return {ok: `2FA is off for ${name}.`};
case "rename": {
world.disconnect(account);
manage.forget(account);
@@ -549,6 +534,16 @@ const act = (account, body) => {
`+${(account.permGrants || []).join(",") || "none"} -${(account.permDenies || []).join(",") || "none"}`);
return {ok: `${name}'s permissions are saved.`};
}
case "adminDashboardAccess": {
const on = body.on === true;
if (on && !account.discordId) {
return {error: `${name} must link their Discord account before it can be allowed.`};
}
account.adminDashboardAccess = on;
accounts.save(account);
modlog.record("admin", on ? "admin dashboard access given" : "admin dashboard access removed", account.username, account.discord || "");
return {ok: on ? `${name} may now sign in to this dashboard with their linked Discord account.` : `${name}'s Discord dashboard access was removed.`};
}
case "rejectName":
actions.rejectName(account, BY);
manage.forget(account);
@@ -627,6 +622,34 @@ const handle = async (req, res, url, from, web) => {
web.send(res, 200, await stats.withView(await fs.promises.readFile(path.join(config.publicDir, "admin.html"))), "text/html; charset=utf-8");
return;
}
// Discord redirects do not carry the normal Strict admin cookie, so their
// own short-lived nonce cookie is Lax and scoped to this callback alone.
if (route === "GET /admin/discord/login") {
if (!hasPassword() || !discordLinks.linking()) {
res.writeHead(302, {Location: "/dashboard/admin?discord=off"});
res.end();
return;
}
const {url: to, nonce} = discordLinks.startAdmin();
res.setHeader("Set-Cookie", discordCookie(nonce, 600));
res.writeHead(302, {Location: to});
res.end();
return;
}
if (route === "GET /admin/discord/callback") {
const nonce = (new RegExp(`(?:^|;\\s*)${DISCORD_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1];
const result = url.searchParams.get("error") ? {error: "cancelled"}
: await discordLinks.finishAdmin(url.searchParams.get("state"), nonce, url.searchParams.get("code"));
if (result.ok) {
signIn(res);
console.log(`[admin] ${logText(result.account.username)} signed in with Discord from ${logText(from.address)}`);
}
const adminCookie = res.getHeader("Set-Cookie");
res.setHeader("Set-Cookie", adminCookie ? [adminCookie, discordCookie("", 0)] : discordCookie("", 0));
res.writeHead(302, {Location: `/dashboard/admin?discord=${result.ok ? "ok" : result.error}`});
res.end();
return;
}
if (req.method === "POST" && !sameOrigin(req)) {
reply(403, {error: "forbidden"});
return;
@@ -635,7 +658,7 @@ const handle = async (req, res, url, from, web) => {
switch (route) {
case "GET /admin/api/state":
reply(200, {needsSetup: !hasPassword(), needsSetupCode: !from.local, signedIn: signedIn(req)});
reply(200, {needsSetup: !hasPassword(), needsSetupCode: !from.local, signedIn: signedIn(req), discordLogin: discordLinks.linking()});
return;
// choosing the first password. whoever is at the server's own machine may;
@@ -963,7 +986,7 @@ const handle = async (req, res, url, from, web) => {
: "New masterpieces are approved as they are made. Ones already waiting still wait."};
}
else if (body.action === "approve") {
result = world.approveMasterpiece(id) ? {ok: "Approved. Its maker has been told and can hang it now."} : {error: "No such painting waiting."};
result = world.approveMasterpiece(id, "admin") ? {ok: "Approved. Its maker has been told and can hang it now."} : {error: "No such painting waiting."};
}
else if (body.action === "reject" || body.action === "remove") {
result = world.removeMasterpiece(id)
+3 -1
View File
@@ -117,7 +117,9 @@ module.exports = ({enterRoom, findOnline, blocks}) => {
// PartyManager.customPartyJoinResponse: [success, reason]
const joinHosted = (session, host) => {
const party = host && partyOf(host);
if (!party || blocks.either(host, session.account)) {
// A one-use staff teleport may inspect a hosted party despite a block;
// ordinary party joins retain the host's privacy rule.
if (!party || (!session.staffTravel && blocks.either(host, session.account))) {
session.sendXt("sjp", -1, 0, party ? "BLK" : "NPP");
return;
}
+16
View File
@@ -147,6 +147,14 @@ module.exports = ({others, findOnline, petFields}) => {
return;
}
activeAvatar(account).petInvId = pet ? pet.inv : 0;
if (!pet && session.petPlayerMode) {
session.petPlayerMode = false;
if (session.pos) {
for (const other of [session, ...others(session)]) {
other.sendXt("uc", session.room.id, session.id, "off", "13");
}
}
}
accounts.save(account);
const messageRoom = session.room ? session.room.id : -1;
session.sendXt("ps", messageRoom, 1, session.id, pet ? pet.inv : 0);
@@ -166,6 +174,14 @@ module.exports = ({others, findOnline, petFields}) => {
return;
}
account.pets = account.pets.filter(candidate => candidate !== pet);
if (session.petPlayerMode && activeAvatar(account).petInvId === pet.inv) {
session.petPlayerMode = false;
if (session.pos) {
for (const other of [session, ...others(session)]) {
other.sendXt("uc", session.room.id, session.id, "off", "13");
}
}
}
for (const avatar of account.avatars) {
if (avatar.petInvId === pet.inv) {
avatar.petInvId = 0;
+15 -3
View File
@@ -1,6 +1,7 @@
"use strict";
const defpacks = require("./defpacks.js");
const wearRules = require("./wearrules.js");
// accessors over an account's animals, pets and items (shape: accounts.js).
// SbiConstants.CURRENCY_NAMES; an item's currencyType indexes into this.
@@ -32,13 +33,24 @@ const avatarById = (account, perUserAvId) =>
const activePet = account => account.pets.find(pet => pet.inv === activeAvatar(account).petInvId) || null;
const wornItems = (account, avatar) => account.items.filter(item => item.on.includes(avatar.avInvId));
// The persisted state is also filtered here, not only where a player tries
// to put an item on. That keeps an old/corrupt pairing from reaching player
// cards or other people in a room while a dashboard rule is being applied.
const wornItems = (account, avatar) => account.items.filter(item => item.on.includes(avatar.avInvId)
&& wearRules.mayWear(item.def, avatar.type));
// item.EquippedAvatars: comma-separated 32-bit words, one bit per avInvId of
// an animal wearing the item.
const equippedBits = item => {
// With an account, omit stale pairings that are no longer allowed. The full
// inventory protocol otherwise exposes those bits and a later avatar switch
// can appear to revive a prohibited item.
const equippedBits = (item, account = null) => {
const words = [0];
for (const avInvId of item.on) {
const wornBy = account ? item.on.filter(avInvId => {
const avatar = account.avatars.find(candidate => candidate.avInvId === avInvId);
return avatar && wearRules.mayWear(item.def, avatar.type);
}) : item.on;
for (const avInvId of wornBy) {
const word = avInvId >>> 5;
while (words.length <= word) {
words.push(0);
+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.
const PERMISSIONS = {
"server.view": "see read-only server health in the moderator panel",
"player.view": "see players, chat, reports, requests, bans and paintings in the moderator panel, and keep notes on players (!note, !notes)",
"staff.list": "see which staff are online (!staff)",
"player.warn": "warn a player, take a warning back, send them a message and mark a report dealt with (!warn, !unwarn, !warnings, !message)",
@@ -27,14 +28,17 @@ const PERMISSIONS = {
"player.names": "reject or accept a name, answer requests for a new one, clear a bio, remove a player's Jammer Wall posts",
"address.ban": "ban the address a player last signed in from, or the computers they use, and lift those bans",
"items.approve": "approve or turn away the items and pictures players make, when the admin has asked for that",
"items.restrict": "stop a clothing item from being worn by selected animal types",
"items.create": "make new items from the game's art, change and delete them, lock items out of the item finder and take items from players (!item, !lock, !unlock, !locked, !take)",
"room.effects": "run temporary room-wide size and colour effects (!roomfx)",
"theater.control": "play or stop a YouTube video for everyone in the theatre",
};
const HELPER = ["player.view", "staff.list", "player.warn", "player.goto", "chat.silence"];
const MODERATOR = [...HELPER, "player.kick", "player.summon", "staff.invisible", "player.ban", "player.names", "address.ban", "items.approve"];
const ADMIN = [...MODERATOR, "items.create"];
const HELPER = ["server.view", "player.view", "staff.list", "player.warn", "player.goto", "chat.silence"];
const MODERATOR = [...HELPER, "player.kick", "player.summon", "staff.invisible", "player.ban", "player.names", "address.ban", "items.approve", "items.restrict", "theater.control"];
const ADMIN = [...MODERATOR, "items.create", "room.effects"];
// a developer makes things, and moderates nobody.
const DEVELOPER = ["staff.list", "items.create"];
const DEVELOPER = ["server.view", "staff.list", "items.create", "room.effects", "theater.control"];
const ROLES = {
developer: {rank: 1, label: "Developer", permissions: DEVELOPER},
+28 -3
View File
@@ -31,6 +31,8 @@ const SIGNUP_LIFETIME_MS = 5 * 60000;
const forLog = message => message.replace(/(<pword><!\[CDATA\[)[\s\S]*?(\]\]>)/, "$1(hidden)$2");
const connections = new Map(); // remote address -> open sockets
let connectionCount = 0;
const metrics = {accepted: 0, rejected: 0, floodDisconnects: 0, handlerErrors: 0};
let nextUserId = 1;
@@ -142,13 +144,18 @@ const start = handlers => new Promise((resolve, reject) => {
const onConnection = socket => {
const address = limits.key(socket.remoteAddress);
const open = connections.get(address) || 0;
const total = [...connections.values()].reduce((sum, count) => sum + count, 0);
// Kept as a counter instead of summing every address on every new socket.
// Under a burst of logins the old O(addresses) work delayed everyone else.
const total = connectionCount;
socket.on("error", () => {});
if (open >= config.maxConnectionsPerAddress || total >= config.maxConnections) {
metrics.rejected++;
socket.destroy();
return;
}
connections.set(address, open + 1);
connectionCount++;
metrics.accepted++;
const session = new Session(socket);
let buffer = Buffer.alloc(0);
@@ -182,11 +189,15 @@ const start = handlers => new Promise((resolve, reject) => {
}
bytesInWindow += chunk.length;
if (bytesInWindow > config.maxBytesPerTenSeconds) {
metrics.floodDisconnects++;
console.log(`[game] ${logText(session.name)} disconnected for flooding`);
socket.destroy();
return;
}
buffer = Buffer.concat([buffer, chunk]);
// Node normally gives complete SmartFox packets in one chunk. Avoiding
// Buffer.concat in that common case reduces allocation and GC during
// busy logins; fragments still retain the exact old behaviour.
buffer = buffer.length === 0 ? chunk : Buffer.concat([buffer, chunk]);
let end;
while ((end = buffer.indexOf(0)) !== -1) {
if (end > MAX_MESSAGE) {
@@ -194,6 +205,7 @@ const start = handlers => new Promise((resolve, reject) => {
return;
}
if (++messagesInWindow > config.maxMessagesPerTenSeconds) {
metrics.floodDisconnects++;
console.log(`[game] ${logText(session.name)} disconnected for flooding`);
socket.destroy();
return;
@@ -204,6 +216,7 @@ const start = handlers => new Promise((resolve, reject) => {
dispatch(session, message);
}
catch (err) {
metrics.handlerErrors++;
// one line a failure, and an end to them: a client that sends
// nonsense in a loop is not to fill the log.
const where = String(err.stack || "").split("\n")[1] || "";
@@ -232,6 +245,7 @@ const start = handlers => new Promise((resolve, reject) => {
else {
connections.delete(address);
}
connectionCount = Math.max(0, connectionCount - 1);
console.log(`[game] ${logText(session.name)} disconnected`);
// nothing thrown while a player is seen off may take the server down.
try {
@@ -280,4 +294,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};
+128 -17
View File
@@ -404,7 +404,7 @@ const sendItemList = (to, target, full, perUserAvId) => {
const {account} = target;
const avatar = avatarById(account, perUserAvId);
const items = full
? account.items.flatMap(item => [item.def, item.inv, item.color, equippedBits(item), 0])
? account.items.flatMap(item => [item.def, item.inv, item.color, equippedBits(item, account), 0])
: wornItems(account, avatar).flatMap(item => [item.def, item.inv, item.color]);
const count = full ? account.items.length : wornItems(account, avatar).length;
to.sendXt("il", -1, full ? "0" : "1", 0, avatar.perUserAvId, account.username, avatar.eyes, avatar.pattern, count, ...items);
@@ -464,6 +464,9 @@ const sendAvatarCreate = (to, target) => {
if (target.invisible) {
to.sendXt("xiv", -1, target.id, 1);
}
if (target.petPlayerMode) {
to.sendXt("uc", room.id, target.id, "on", "13");
}
minigames.showBubble(to, target);
};
@@ -538,7 +541,7 @@ const sendUserVars = session => {
};
const findOnline = username => online.get(String(username).toLowerCase());
const STAFF_WINDOW_COMMANDS = ["warn", "unwarn", "message", "silence", "kick", "summon", "goto", "warnings"];
const STAFF_WINDOW_COMMANDS = ["warn", "unwarn", "message", "silence", "kick", "summon", "goto", "warnings", "reject"];
const MAX_STAFF_WINDOW_WORDS = 3; // username, then a reason, hours or the message (each one field)
// a custom colour (lib/colours.js) for these four RGB values, made if it is
@@ -923,6 +926,47 @@ const handlers = {
}
},
// The host/event overlay only sends one of these fixed room effects. Its
// permission check lives here as well, so a forged client packet cannot
// change a room.
xrc(session, roomId, [effect]) {
const choice = String(effect || "").toLowerCase();
if (roles.isActiveStaff(session.account) && roles.can(session.account, "room.effects")
&& ["small", "normal", "big", "rainbow", "clear"].includes(choice)) {
commands.run(session, `!roomfx ${choice}`);
}
},
// The browser host renders the YouTube iframe; the game receives only a
// validated video id and keeps it shared by the people in this theatre.
xtv(session, roomId, [action, value = ""]) {
const {room} = session;
// Some theatre maps report an internal room path which has no "theatre"
// in it (the visible room title does). Staff permission is the boundary;
// restricting by that unreliable path made Play for room silently fail.
if (!roles.isActiveStaff(session.account) || !roles.can(session.account, "theater.control") || !room) {
return;
}
let videoId = "";
if (action === "play") {
const text = String(value).trim();
const match = text.match(/^(?:[A-Za-z0-9_-]{11}|(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([A-Za-z0-9_-]{11})(?:[?&#].*)?)$/i);
videoId = match ? (match[1] || text) : "";
if (!videoId) {
session.sendXt("xtl", -1, "Paste a YouTube watch, share, or embed link.");
return;
}
}
else if (action !== "stop") {
return;
}
room.theatreVideo = videoId;
for (const viewer of room.sessions) {
viewer.sendXt("xtv", room.id, videoId);
}
modlog.record(session.account.username, videoId ? "played theatre video" : "stopped theatre video", "", room.name);
},
// the patched client's chat box: whether its player is typing, for a
// "..." over their animal in everyone else's game (gui.ChatHistory):
// xty [1 | 0], passed on as "xty" [.., .., sfsId, 1 | 0]. a client says
@@ -1138,10 +1182,31 @@ const itemsTaken = (account, kind, invs, worn) => {
}
};
// A dashboard clothing rule can affect several animals and mannequins at
// once. Their persisted references have already been removed by
// itemcontrol.js; refresh both the owner's full inventory and anyone seeing
// their animal or den so an open game cannot keep displaying the old outfit.
const wearRulesChanged = (account, mannequinChanged = false) => {
const session = findOnline(account.username);
if (session) {
sendItemList(session, session, true);
refreshForOthers(session);
if (mannequinChanged) {
dens.sendDenItems(session);
}
}
if (mannequinChanged) {
const den = rooms.get(`den${account.username}`);
for (const visitor of den ? den.sessions : []) {
dens.sendDenState(visitor, den, false);
}
}
};
// staff moving a player: `whoName` to the room `toName` is in (summon is
// the player to the staff member, goto the staff member to the player). both
// online, `toName` in a room. the room's own rules still apply: a full room
// or a locked den keeps them out.
// online, `toName` in a room. This privileged movement deliberately bypasses
// a full room, locked den, or hosted-party block; regular joins do not.
// they land where `toName` stands (the patched client's "xgt": [x, y,
// "1" same room, teleported now | "0" the spot to spawn on in the next
// room], or [] to forget a spot not used). with nobody's spot known yet,
@@ -1165,13 +1230,15 @@ const staffMove = (whoName, toName) => {
who.sendXt("xgt", -1, ...spot, 1);
return {ok: true, room: shown};
}
if (room.sessions.size >= config.maxUsersPerRoom) {
return {error: `${shown} is full.`};
}
if (spot) {
who.sendXt("xgt", -1, ...spot, 0);
}
// staffMove is only reached through permission-checked commands. The flag
// is consumed by enterRoom/joinDen, preserving normal rules for all other
// joins.
who.staffTravel = true;
joinRoom(who, room.name);
delete who.staffTravel;
if (who.room !== room) {
if (spot) {
who.sendXt("xgt", -1);
@@ -1385,11 +1452,13 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
if (room && room === session.room) {
return;
}
// moderators (marked so in the admin panel) are let into a full room, and
// so is a player arriving when every spawn room is full (spawnRoom).
// Moderators, a one-use staff teleport, and a player arriving when every
// spawn room is full (spawnRoom) may enter a full room.
const overflow = session.spawnOverflow;
const staffTravel = session.staffTravel === true;
session.spawnOverflow = false;
if (room && room.sessions.size >= config.maxUsersPerRoom && !roles.isActiveStaff(session.account) && !overflow) {
delete session.staffTravel;
if (room && room.sessions.size >= config.maxUsersPerRoom && !roles.isActiveStaff(session.account) && !staffTravel && !overflow) {
joinFailed(session, "This room is currently full");
return;
}
@@ -1432,6 +1501,9 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
room.customMusicDef,
worldId);
dens.sendRoomProperties(session, roomAsSeenBy(session, room));
if (room.theatreVideo !== undefined) {
session.sendXt("xtv", room.id, room.theatreVideo);
}
for (const other of others(session)) {
if (other.pos && sees(session, other)) {
@@ -1592,7 +1664,7 @@ const joinRoom = (session, requested) => {
let shard = config.shards.find(s => s.id === Number(shardText)) || config.shards.find(s => s.id === session.worldId) || config.shards[0];
// full there: with "Find Open World" on, the same room in a world that
// has space (moderators get into a full room anyway).
if (roomFull(`${base}#${shard.id}`) && !session.account.moderator && findOpenWorld(session.account)) {
if (roomFull(`${base}#${shard.id}`) && !roles.isActiveStaff(session.account) && findOpenWorld(session.account)) {
shard = config.shards.find(other => !roomFull(`${base}#${other.id}`)) || shard;
}
enterRoom(session, `${base}#${shard.id}`, base, roomInfo.name(base), shard.id);
@@ -1614,7 +1686,8 @@ const joinDen = (session, requested) => {
joinFailed(session, `Den "${requested}" does not exist`);
return;
}
if (!dens.canEnter(owner, session.account) || blocks.has(owner, session.account)) {
const staffTravel = session.staffTravel === true;
if ((!dens.canEnter(owner, session.account) || blocks.has(owner, session.account)) && !staffTravel) {
joinFailed(session, "This den is locked");
return;
}
@@ -1661,7 +1734,11 @@ module.exports = {
case "pubMsg": {
// UserCommXtCommManager sends "<text>%<type>[%<extra>]" and reads it
// back in userCommChatResponse as [sfsUserId, text, type, extra].
if (session.room && session.room.id === msg.roomId) {
// An in-room minigame keeps the player in their world room, but its
// embedded SWF labels outgoing user messages with the minigame's
// temporary sub-room id. Accept that id as well so its attachment
// reward can make the normal round trip back to the avatar.
if (session.room && (session.room.id === msg.roomId || (session.game && session.game.roomId === Number(msg.roomId)))) {
// at most text, type and one extra field, and no essays.
const fields = decodeEntities(msg.cdata("txt") || "").split("%").slice(0, 3);
if (fields[0].length > config.maxChatLength || (fields[2] || "").length > MAX_CHAT_EXTRA) {
@@ -1680,10 +1757,42 @@ module.exports = {
minigames.bubble(session, fields[0], fields[2]);
return;
}
// Per-player pet form. It is deliberately a user-communication
// message so every client already in the room updates the same
// avatar, while the normal pet-out state stays unchanged.
if (fields[1] === "13") {
const enabled = fields[0] === "on" && Boolean(activePet(session.account));
session.petPlayerMode = enabled;
for (const other of [session, ...watchers(session)]) {
other.sendXt("uc", session.room.id, session.id, enabled ? "on" : "off", "13");
}
return;
}
// Attachment messages carry an emoticon *definition* id from the
// sender, while the recipient's avatar view needs that definition's
// media id. This is the normal path used by den attachments and
// the food-machine minigames.
if (fields[1] === "4") {
const [defId, ...extra] = fields[0].split(",");
if (defId === "0") {
fields[0] = "0,";
}
else {
const mediaId = defpacks.emoticonMediaId(defId);
if (!mediaId) {
return;
}
fields[0] = `${mediaId},${extra.join(",").replace(/[\r\n%,]/g, "").slice(0, 128)}`;
}
}
// typed chat shows as "..." over the sender until the server sends
// it back (UserCommXtCommManager.sendChatMessage); everything else
// the sender has already shown themselves.
const echo = TYPED_CHAT_TYPES.includes(fields[1]);
// An attachment is only drawn after the server sends it back. The
// local client deliberately does not draw it optimistically, unlike
// typed chat and normal emotes.
const attachmentEcho = fields[1] === "4";
// silenced, or chat switched off on the account page: the line
// goes nowhere.
if (echo && (moderation.isSilenced(session.account) || !accounts.featureOn(session.account, "chat"))) {
@@ -1737,7 +1846,7 @@ module.exports = {
// nobody hears a player they have blocked, and with chat switched
// off nobody's typed lines arrive at all.
// an invisible staff member's emotes and the like reach staff only.
for (const recipient of echo ? session.room.sessions : others(session)) {
for (const recipient of (echo || attachmentEcho) ? session.room.sessions : others(session)) {
if (session.invisible && recipient !== session && !roles.isActiveStaff(recipient.account)) {
continue;
}
@@ -1780,6 +1889,7 @@ module.exports = {
findOnline,
makeColour,
sendItemList,
wearRulesChanged,
setTheme,
// offers left on the account page (lib/trades.js); `refresh` shows a
// playing account its inventories as they are now.
@@ -1880,10 +1990,11 @@ module.exports = {
// the panel's Masterpieces page. A painting waiting for review is an
// item its maker cannot use yet; approving it tells them so, by a
// Jam-A-Gram from Animal Jam HQ and at once if they are playing.
approveMasterpiece(id) {
// Jam-A-Gram from Animal Jam HQ and at once if they are playing. `by`
// is who approved it: a moderator's username, or "admin".
approveMasterpiece(id, by) {
const maker = masterpieces.creatorOf(id);
if (!masterpieces.approve(id)) {
if (!masterpieces.approve(id, by)) {
return false;
}
if (maker) {
+1 -1
View File
@@ -198,7 +198,7 @@
<div class="row"><button class="primary" type="submit">Sign in</button></div>
</form>
<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 id="page" hidden>
+183 -11
View File
@@ -143,6 +143,14 @@
.lock-results .meta { color: var(--muted); font-size: 12px; }
.lock-results button { margin-left: auto; }
.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 */
#gate {
@@ -368,6 +376,8 @@
</div>
<button class="primary" id="gate-button">Sign in</button>
</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>
</main>
@@ -375,7 +385,7 @@
<aside id="side">
<div class="brand">
<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>
<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>
@@ -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="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="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="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>
@@ -474,11 +485,6 @@
<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>
</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">
<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">
@@ -564,7 +570,6 @@
<div class="buttons">
<button type="button" data-action="kick">Disconnect</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="acceptName">Take rejection back</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>
<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:12px"><button type="button" data-action="adminDashboardAccess" id="admin-dashboard-access"></button></div>
<p class="hint" id="admin-dashboard-access-hint"></p>
</div>
<div id="owned"></div>
</div>
@@ -688,6 +695,30 @@
</section>
</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>
<section>
<h2 id="item-form-title">Make an item</h2>
@@ -973,7 +1004,7 @@
let timer = null;
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",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body),
@@ -1040,6 +1071,13 @@
$("confirm-field").hidden = !setup;
$("code-field").hidden = !(setup && state.needsSetupCode);
$("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 = "";
$("confirm").value = "";
setStatus($("gate-status"), message || "");
@@ -1065,6 +1103,9 @@
state = {needsSetup: false, needsSetupCode: false, signedIn: true};
showPanel();
});
$("discord-sign-in").addEventListener("click", () => {
location.href = "/dashboard/admin/discord/login";
});
$("sign-out").addEventListener("click", async () => {
await api("logout", {});
@@ -1443,6 +1484,11 @@
return label;
}));
$("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 : "";
$("quest-level").value = current ? current.level : "";
$("ban-reason").value = current ? current.banReason : "";
@@ -1473,7 +1519,7 @@
selected = username;
current = null;
setStatus($("detail-status"), "");
for (const id of ["new-name", "new-password", "ban-hours", "silence-hours", "message-text", "gems-amount", "gift-value", "gift-text"]) {
for (const id of ["new-name", "ban-hours", "silence-hours", "message-text", "gems-amount", "gift-value", "gift-text"]) {
$(id).value = "";
}
hashArg = username;
@@ -1618,7 +1664,6 @@
const actionBody = action => {
switch (action) {
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 "ban": return {hours: numberFrom("ban-hours"), reason: $("ban-reason").value};
case "banReason": case "banDevices": return {reason: $("ban-reason").value};
@@ -1626,6 +1671,7 @@
case "moderator": return {on: !(current || {}).moderator};
case "role": return {role: $("role-select").value};
case "permissions": return permissionChoices();
case "adminDashboardAccess": return {on: !(current || {}).adminDashboardAccess};
case "message": return {text: $("message-text").value};
case "gems": return {amount: numberFrom("gems-amount")};
case "gift": return giftBody();
@@ -1678,7 +1724,6 @@
$("new-name").value = "";
}
if (result.ok) {
$("new-password").value = "";
await refresh();
fillCard();
loadOwned();
@@ -2590,6 +2635,130 @@
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
// unlocked where it is found (the Items page lists every locked one).
let quickLockTimer = null;
@@ -2717,6 +2886,9 @@
renderSupport(result.data);
}
}
else if (tab === "wear-rules") {
await loadWearRules();
}
else if (tab === "items") {
result = await api("items");
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>
+50 -1
View File
@@ -10,8 +10,28 @@
margin: 0;
overflow: hidden;
}
#flash-content {
position: relative;
z-index: 1;
}
#theatre-video {
position: fixed;
z-index: 2;
display: none;
left: 8.4vw;
top: 6.2vh;
width: 56.8vw;
height: 52.8vh;
border: 0;
background: #000;
pointer-events: auto;
}
#theatre-video.visible {
display: block;
}
</style>
<embed id="flash-content"></embed>
<iframe id="theatre-video" title="Theatre video" allow="autoplay; encrypted-media" referrerpolicy="strict-origin-when-cross-origin"></iframe>
<script>
"use strict";
@@ -19,11 +39,15 @@
// same contract with the launcher (gui/gamePreload.js) and the SWF.
const flashContent = document.getElementById("flash-content");
const theatreVideo = document.getElementById("theatre-video");
// only a SWF from this server may call into this page. with "always"
// any SWF the game came to load, from anywhere, could: and this page
// is handed the player's login token.
flashContent.setAttribute("allowScriptAccess", "sameDomain");
flashContent.setAttribute("wmode", "window");
// The theatre's staff-controlled browser video must be able to appear
// over the SWF screen. "window" puts Flash above every HTML element;
// opaque keeps the normal game drawing while allowing that overlay.
flashContent.setAttribute("wmode", "opaque");
flashContent.style.width = "100vw";
flashContent.style.height = "100vh";
@@ -94,6 +118,31 @@
window.ipc.sendToHost("printImage", imageData);
}
// The server validates the id and decides who in the theatre gets this
// call. The page merely displays it over the theatre's screen area.
function ajTheatreVideo(videoId) {
const id = String(videoId || "");
if (!/^[A-Za-z0-9_-]{11}$/.test(id)) {
theatreVideo.removeAttribute("src");
theatreVideo.classList.remove("visible");
return;
}
theatreVideo.src = `https://www.youtube-nocookie.com/embed/${id}?autoplay=1&rel=0&modestbranding=1`;
theatreVideo.classList.add("visible");
}
// The native theatre sign calls this through ExternalInterface. The
// SWF performs its own permission check before showing the controls.
function ajOpenTheatreControl() {
if (flashContent && typeof flashContent.openTheatreControl === "function") {
try {
flashContent.openTheatreControl();
}
catch (err) {
}
}
}
function reloadSwfOrGetIP(reloadSwf, params) {
window.ipc.sendToHost("reloadGame", reloadSwf, params);
}
+1091 -248
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -161,7 +161,7 @@
<section>
<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>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>
@@ -170,6 +170,7 @@
<thead><tr><th>Data</th><th>Why</th></tr></thead>
<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>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>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>
+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>
<label for="confirm">Password again</label>
<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>
<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>
@@ -242,6 +244,7 @@
captcha_required: "Complete the captcha.",
captcha_failed: "Captcha failed. Try again.",
captcha_unavailable: "Captcha unavailable. Try again later.",
invalid_email: "Enter a valid recovery email address.",
};
const $ = id => document.getElementById(id);
@@ -335,7 +338,7 @@
const response = await fetch("/api/register", {
method: "POST",
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}),
});
check.reset();
+1 -1
View File
@@ -179,7 +179,7 @@
<h2>3. Your account</h2>
<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>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>
</ul>
</section>
+364 -3
View File
@@ -127,6 +127,17 @@ package
private var _moderateButtons:Array;
// Staff-only YouTube control for the theatre. The video itself is a
// browser overlay, called through ExternalInterface below.
private var _theatreButton:Sprite;
private var _theatreControl:Sprite;
private var _theatreInput:TextField;
// Owner/developer room-effect controls, opened by !event or !host.
private var _roomControl:Sprite;
public static var staffRole:String = "";
public static var staffPermissions:Array = [];
@@ -164,6 +175,7 @@ package
if(ExternalInterface.available)
{
ExternalInterface.addCallback("ajHud",setHudShown);
ExternalInterface.addCallback("openTheatreControl",openTheatreControl);
}
}
catch(e:Error)
@@ -327,6 +339,7 @@ package
gMainFrame.stage.addEventListener("keyDown",onFinderKey,true,1000);
gMainFrame.stage.addEventListener("keyDown",onFinderKey,false,1000);
startEmojiButton();
placeTheatreButton();
}
public static function openTool(param1:int) : void
@@ -826,6 +839,278 @@ package
{
staffRole = String(param1[2]);
staffPermissions = String(param1[3]).length > 0 ? String(param1[3]).split(",") : [];
if(_toolsInstance != null)
{
_toolsInstance.placeTheatreButton();
}
}
// "xui": a permission-checked server command asks for a staff panel.
// It is never acted on merely because a browser or another player asks.
public static function onStaffUi(param1:Object) : void
{
if(_toolsInstance == null)
{
return;
}
var _loc1_:String = param1.length > 2 ? String(param1[2]) : "";
if(_loc1_ == "moderate" && param1.length > 3 && canModerate())
{
openModerate(String(param1[3]));
}
else if(_loc1_ == "event" && staffMay("room.effects"))
{
_toolsInstance.openRoomControl();
}
}
// "xtv": a server-authorized YouTube id for this theatre, or empty to
// stop it. The desktop game's web page owns the actual iframe.
public static function onTheatreVideo(param1:Object) : void
{
try
{
if(ExternalInterface.available)
{
ExternalInterface.call("ajTheatreVideo",param1.length > 2 ? String(param1[2]) : "");
}
}
catch(e:Error)
{
}
}
private function placeTheatreButton() : void
{
// Video playback belongs to the theatre's own VIDEOS sign. A HUD
// button existed in every room and den for staff, which was both
// misleading and able to cover other interfaces.
if(_theatreButton != null)
{
_theatreButton.visible = false;
}
}
private function onTheatreButton(param1:MouseEvent) : void
{
param1.stopPropagation();
if(_theatreControl == null)
{
buildTheatreControl();
}
_theatreControl.visible = !_theatreControl.visible;
if(_theatreControl.visible)
{
setChildIndex(_theatreControl,numChildren - 1);
gMainFrame.stage.focus = _theatreInput;
}
}
// Called by the theatre's VIDEOS sign through game.html. This needs to
// remain public for ExternalInterface, but permission is still derived
// from the signed-in server role, never from the browser call.
public function openTheatreControl() : void
{
if(!staffMay("theater.control"))
{
return;
}
if(_theatreControl == null)
{
buildTheatreControl();
}
_theatreControl.visible = true;
setChildIndex(_theatreControl,numChildren - 1);
gMainFrame.stage.focus = _theatreInput;
}
private function buildTheatreControl() : void
{
_theatreControl = new Sprite();
_theatreControl.graphics.beginFill(0,0.55);
_theatreControl.graphics.drawRect(0,0,900,550);
_theatreControl.graphics.endFill();
var _loc1_:Sprite = new Sprite();
_loc1_.x = 225;
_loc1_.y = 170;
_loc1_.graphics.lineStyle(2,0x7B4D24);
_loc1_.graphics.beginFill(0x27221D);
_loc1_.graphics.drawRoundRect(0,0,450,210,22,22);
_loc1_.graphics.endFill();
_theatreControl.addChild(_loc1_);
theatreCloseButton(_loc1_);
var _loc2_:TextField = modText("THEATRE VIDEO",22,0xFFFFFF);
_loc2_.x = 24;
_loc2_.y = 22;
_loc1_.addChild(_loc2_);
var _loc3_:TextField = modText("Paste a YouTube link. Everyone in this theatre will see it.",12,0xD5C5AE,false);
_loc3_.x = 24;
_loc3_.y = 58;
_loc1_.addChild(_loc3_);
var _loc4_:Sprite = new Sprite();
_loc4_.x = 24;
_loc4_.y = 94;
_loc4_.graphics.lineStyle(1,0x7B4D24);
_loc4_.graphics.beginFill(0x111111);
_loc4_.graphics.drawRoundRect(0,0,402,34,10,10);
_loc4_.graphics.endFill();
_loc1_.addChild(_loc4_);
_theatreInput = new TextField();
_theatreInput.type = "input";
_theatreInput.embedFonts = hasGameFont();
_theatreInput.defaultTextFormat = new TextFormat("CCDigitalDelivery",13,0xFFFFFF,false);
_theatreInput.maxChars = 200;
_theatreInput.x = 10;
_theatreInput.y = 7;
_theatreInput.width = 382;
_theatreInput.height = 22;
_loc4_.addChild(_theatreInput);
theatreControlButton(_loc1_,"play","Play for room",24,150,186,0x357A45);
theatreControlButton(_loc1_,"stop","Stop video",240,150,186,0x8E3D3D);
_theatreControl.addEventListener("mouseDown",onFinderMouse);
_theatreControl.addEventListener("mouseUp",onFinderMouse);
_theatreControl.addEventListener("click",onFinderMouse);
_theatreControl.visible = false;
addChild(_theatreControl);
}
private function theatreControlButton(param1:Sprite, param2:String, param3:String, param4:Number, param5:Number, param6:Number, param7:uint) : void
{
var _loc1_:Sprite = new Sprite();
_loc1_.name = param2;
_loc1_.x = param4;
_loc1_.y = param5;
_loc1_.buttonMode = true;
_loc1_.mouseChildren = false;
paintFlatButton(_loc1_,param6,param7);
var _loc2_:TextField = modText(param3,14,0xFFFFFF);
_loc2_.name = "label";
_loc1_.addChild(_loc2_);
paintFlatButton(_loc1_,param6,param7);
_loc1_.addEventListener("mouseDown",onTheatreControl,false,0,true);
param1.addChild(_loc1_);
}
private function onTheatreControl(param1:MouseEvent) : void
{
param1.stopPropagation();
var _loc1_:String = Sprite(param1.currentTarget).name;
if(_loc1 == "play" && _theatreInput.text.replace(/^\s+|\s+$/g,"").length == 0)
{
gMainFrame.stage.focus = _theatreInput;
return;
}
gMainFrame.server.setXtObject_Str("xtv",[_loc1,_loc1 == "play" ? _theatreInput.text.split("%").join("") : ""]);
_theatreControl.visible = false;
gMainFrame.stage.focus = null;
}
private function openRoomControl() : void
{
if(!staffMay("room.effects"))
{
return;
}
if(_roomControl == null)
{
buildRoomControl();
}
_roomControl.visible = true;
setChildIndex(_roomControl,numChildren - 1);
}
private function buildRoomControl() : void
{
_roomControl = new Sprite();
_roomControl.graphics.beginFill(0,0.55);
_roomControl.graphics.drawRect(0,0,900,550);
_roomControl.graphics.endFill();
var _loc1_:Sprite = new Sprite();
_loc1_.x = 225;
_loc1_.y = 150;
_loc1_.graphics.lineStyle(2,0x7B4D24);
_loc1_.graphics.beginFill(0x27221D);
_loc1_.graphics.drawRoundRect(0,0,450,250,22,22);
_loc1_.graphics.endFill();
_roomControl.addChild(_loc1_);
theatreCloseButton(_loc1_);
var _loc2_:TextField = modText("HOST / EVENT CONTROLS",22,0xFFFFFF);
_loc2_.x = 24;
_loc2_.y = 22;
_loc1_.addChild(_loc2_);
var _loc3_:TextField = modText("Change the whole room. Clear resets size and colour.",12,0xD5C5AE,false);
_loc3_.x = 24;
_loc3_.y = 58;
_loc1_.addChild(_loc3_);
roomControlButton(_loc1_,"small","Make everyone small",24,98,126,0x357A45);
roomControlButton(_loc1_,"normal","Normal size",162,98,126,0x496B91);
roomControlButton(_loc1_,"big","Make everyone big",300,98,126,0x7A5FBD);
roomControlButton(_loc1_,"rainbow","Rainbow room",24,150,196,0xA54E96);
roomControlButton(_loc1_,"clear","Clear effects",230,150,196,0x8E3D3D);
_roomControl.addEventListener("mouseDown",onFinderMouse);
_roomControl.addEventListener("mouseUp",onFinderMouse);
_roomControl.addEventListener("click",onFinderMouse);
_roomControl.visible = false;
addChild(_roomControl);
}
private function roomControlButton(param1:Sprite, param2:String, param3:String, param4:Number, param5:Number, param6:Number, param7:uint) : void
{
var _loc1_:Sprite = new Sprite();
_loc1_.name = param2;
_loc1_.x = param4;
_loc1_.y = param5;
_loc1_.buttonMode = true;
_loc1_.useHandCursor = true;
_loc1_.mouseChildren = false;
var _loc2_:TextField = modText(param3,12,0xFFFFFF);
_loc2_.name = "label";
_loc1_.addChild(_loc2_);
paintFlatButton(_loc1_,param6,param7);
_loc1_.addEventListener("mouseDown",onRoomControl,false,0,true);
param1.addChild(_loc1_);
}
private function onRoomControl(param1:MouseEvent) : void
{
param1.stopPropagation();
gMainFrame.server.setXtObject_Str("xrc",[Sprite(param1.currentTarget).name]);
_roomControl.visible = false;
}
// A visible close control is reliable even while an input field owns
// keyboard focus, unlike relying only on Escape.
private function theatreCloseButton(param1:Sprite) : void
{
var _loc1_:Sprite = new Sprite();
_loc1_.buttonMode = true;
_loc1_.useHandCursor = true;
_loc1_.graphics.beginFill(MOD_GREY);
_loc1_.graphics.drawCircle(0,0,13);
_loc1_.graphics.endFill();
_loc1_.graphics.lineStyle(2,0xFFFFFF);
_loc1_.graphics.moveTo(-4,-4);
_loc1_.graphics.lineTo(4,4);
_loc1_.graphics.moveTo(4,-4);
_loc1_.graphics.lineTo(-4,4);
_loc1_.x = 422;
_loc1_.y = 25;
_loc1_.addEventListener("mouseDown",onTheatreClose,false,0,true);
param1.addChild(_loc1_);
}
private function onTheatreClose(param1:MouseEvent) : void
{
param1.stopPropagation();
if(_theatreControl != null)
{
_theatreControl.visible = false;
}
if(_roomControl != null)
{
_roomControl.visible = false;
}
gMainFrame.stage.focus = null;
}
public static function staffMay(param1:String) : Boolean
@@ -1254,6 +1539,9 @@ package
// the 120 and 144 this once offered came to the same).
// 9005 Camera: 1 Smooth (room.RoomManagerWorld.easeCamera), else the
// game's own.
// 9007 Performance profile: 1 Low-end, 2 High, unset Balanced. A
// profile changes only optional rendering work, never the
// game's native 24 FPS (which would slow its animations).
private static var _smoothTimer:Timer;
@@ -1277,12 +1565,45 @@ package
public static function smoothOn() : Boolean
{
if(performanceProfile() == 1)
{
return false;
}
if(performanceProfile() == 2)
{
return true;
}
return settingOf(9003) != 1;
}
// 0 Balanced, 1 Low-end, 2 High. It is persisted with the other client
// settings, so the preference follows the player to another computer.
public static function performanceProfile() : int
{
var _loc1_:int = settingOf(9007);
return _loc1_ == 1 || _loc1_ == 2 ? _loc1_ : 0;
}
public static function performanceProfileLabel() : String
{
switch(performanceProfile())
{
case 1:
return "Low-end";
case 2:
return "High";
default:
return "Balanced";
}
}
// pictures a second asked for, or 0 for no limit.
public static function frameRate() : int
{
if(performanceProfile() == 2)
{
return 0;
}
return settingOf(9004) == 1 ? 60 : 0;
}
@@ -1330,7 +1651,9 @@ package
}
try
{
_loc2_ = !_smoothBroken && MainFrame.isInitialized() && gMainFrame.userInfo != null && gMainFrame.userInfo.userVarCache != null && AvatarManager.playerAvatarWorldView != null && !MinigameManager.inMinigame() && smoothOn();
// Extra interpolation cannot be seen below a modal. The world map
// is a modal without DarkenManager, so include it here too.
_loc2_ = !_smoothBroken && MainFrame.isInitialized() && gMainFrame.userInfo != null && gMainFrame.userInfo.userVarCache != null && AvatarManager.playerAvatarWorldView != null && !MinigameManager.inMinigame() && !GuiManager.isModal() && smoothOn();
}
catch(e:Error)
{
@@ -1370,6 +1693,20 @@ package
gMainFrame.stage.quality = gMainFrame.currStageQuality != null ? gMainFrame.currStageQuality : "medium";
}
}
// Low-end uses Flash's lower-quality renderer but keeps the original
// game framerate, so movement and frame-based animations do not run
// in slow motion. Restore the game's normal renderer on exit.
if(performanceProfile() == 1)
{
if(gMainFrame.stage.quality != "LOW")
{
gMainFrame.stage.quality = "low";
}
}
else if(!_smoothQuality && gMainFrame.stage.quality == "LOW")
{
gMainFrame.stage.quality = gMainFrame.currStageQuality != null ? gMainFrame.currStageQuality : "medium";
}
}
// between two frames: every animal that is walking goes on by the
@@ -2426,7 +2763,7 @@ package
// the window's look: flat, dark, rounded, in the game's font.
private static const MOD_W:int = 560;
private static const MOD_H:int = 432;
private static const MOD_H:int = 486;
private static const MOD_PAD:int = 24;
@@ -2624,6 +2961,8 @@ package
modButton("warnings","Warnings",_loc2_[0],372,_loc1_,MOD_GREY,"player.warn");
modButton("unwarn","Undo warning",_loc2_[1],372,_loc1_,MOD_GREY,"player.warn");
modButton("invisible","Go invisible",_loc2_[2],372,_loc1_,MOD_GREY,"staff.invisible");
modSection("Name",422);
modButton("reject","Reject username",_loc2_[0],440,_loc1_,MOD_RED,"player.names");
_moderate.addEventListener("mouseDown",onFinderMouse);
_moderate.addEventListener("mouseUp",onFinderMouse);
_moderate.addEventListener("click",onFinderMouse);
@@ -3437,7 +3776,10 @@ package
_emojiButton.addEventListener("mouseDown",onEmojiButton);
addChild(_emojiButton);
}
var _loc5_:Boolean = shownOnStage(_loc2_) && _loc2_.type == "input";
// The chat field remains technically visible under darkened game
// windows (inventory, trading, shops, etc.). Do not leave the
// emoji button or its grid sitting above those interfaces.
var _loc5_:Boolean = shownOnStage(_loc2_) && _loc2_.type == "input" && !DarkenManager.isDarkened && !GuiManager.isModal();
_emojiButton.visible = _loc5_;
if(!_loc5_)
{
@@ -4227,6 +4569,25 @@ package
param1.stopImmediatePropagation();
return;
}
if(_theatreControl != null && _theatreControl.visible)
{
if(param1.keyCode == 27)
{
_theatreControl.visible = false;
gMainFrame.stage.focus = null;
}
param1.stopImmediatePropagation();
return;
}
if(_roomControl != null && _roomControl.visible)
{
if(param1.keyCode == 27)
{
_roomControl.visible = false;
}
param1.stopImmediatePropagation();
return;
}
// the rules: Esc closes them as their X does
if(_rulesWin != null && _rulesWin.visible)
{
+14
View File
@@ -2,6 +2,7 @@ package gui
{
import avatar.Avatar;
import avatar.AvatarManager;
import avatar.UserCommXtCommManager;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.MouseEvent;
@@ -699,6 +700,19 @@ package gui
{
var _loc2_:WorldPet = null;
param1.stopPropagation();
// Outside a play-as-your-pet event this button is the personal
// pet-form switch. The server echoes the change to everybody in
// the room, so this is not merely a local visual effect.
if(!GuiManager.isBeYourPetRoom())
{
if(AvatarManager.playerAvatarWorldView && AvatarManager.playerAvatarWorldView.getActivePet())
{
UserCommXtCommManager.sendPetPlayerMode(!GuiManager.isPlayingAsPet());
}
actionBtn.dispatchEvent(new MouseEvent("mouseDown"));
param1.currentTarget.downToUpState();
return;
}
if(AvatarManager.playerAvatarWorldView)
{
_loc2_ = AvatarManager.playerAvatarWorldView.getActivePet();
+30 -1
View File
@@ -605,7 +605,7 @@ package avatar
_hudViewHolder.mouse.gotoAndStop(offScreenDefaultMouseFrameLabel());
}
}
_shouldShowPetOnly = GuiManager.isBeYourPetRoom();
_shouldShowPetOnly = GuiManager.isBeYourPetRoom() || userId == AvatarManager.playerSfsUserId && GuiManager.isPlayingAsPet();
if(_shouldShowPetOnly)
{
_layerAnim.alpha = 0;
@@ -2079,6 +2079,7 @@ package avatar
if(param2 != 0 && PetManager.canCurrAvatarUsePet(_avatar.enviroTypeFlag,PetManager.getPetDef(param2 & 0xFF),param1))
{
_pet = new WorldPet(this,param1,param2,param3,param4,param6,param8,param7,param9);
_currPetName = LocalizationManager.translatePetName(param5);
}
if(_shouldShowPetOnly)
{
@@ -2095,6 +2096,34 @@ package avatar
}
}
}
// Called from the type-13 user communication message. Unlike the
// party/quest form this belongs to one avatar, so each view keeps its
// own state instead of asking the room-wide GuiManager predicate.
public function setPetPlayerMode(param1:Boolean) : void
{
var _loc2_:Boolean = param1 && _pet != null;
_shouldShowPetOnly = _loc2_ || GuiManager.isBeYourPetRoom();
_layerAnim.alpha = _shouldShowPetOnly ? 0 : 1;
_layerAnim.avatarEnabled = !_shouldShowPetOnly;
if(_shouldShowPetOnly && _pet)
{
if(!isActivePetGroundPet())
{
_splash.showShadow(false);
}
_namebar.setAvName(_currPetName);
}
else
{
_splash.showShadow(true);
_namebar.setAvName(_avatar.avName);
}
if(userId == AvatarManager.playerSfsUserId)
{
GuiManager.setPersonalPetMode(_loc2_);
}
}
public function getActivePet() : WorldPet
{
+3 -1
View File
@@ -71,7 +71,9 @@ package gui
// emoji panel, say), which the game's font has none of: each is drawn
// as a picture of it, from the server (/emoji/<code points>.png,
// Twemoji's). each is {at, clip}: where its gap starts in the text shown.
private static const INLINE_GAP:String = " ";
// Three spaces fit the line-height-sized emoji without the noticeably
// wide hole four spaces left between neighbouring words or emoji.
private static const INLINE_GAP:String = " ";
private static const LONGEST_EMOTE_CODE:int = 16;
+6 -1
View File
@@ -870,7 +870,12 @@ package gui
{
_inputFormat = chatMsgText.defaultTextFormat;
_inputEmbedded = chatMsgText.embedFonts;
_loc4_ = new TextFormat("Segoe UI Emoji",_inputFormat.size,_inputFormat.color,_inputFormat.bold);
// Keep ordinary letters and spaces in their normal Windows face;
// it falls back to Segoe UI Emoji only for the emoji glyphs.
// The emoji-only face widened mixed text and made spacing uneven.
_loc4_ = new TextFormat("Segoe UI",_inputFormat.size,_inputFormat.color,_inputFormat.bold);
_loc4_.letterSpacing = _inputFormat.letterSpacing;
_loc4_.leading = _inputFormat.leading;
chatMsgText.embedFonts = false;
chatMsgText.defaultTextFormat = _loc4_;
chatMsgText.setTextFormat(_loc4_);
+77
View File
@@ -15,10 +15,13 @@ package gui
import den.DenStateItem;
import den.DenXtCommManager;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.geom.Point;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.Timer;
import gui.itemWindows.ItemWindowOriginal;
import localization.LocalizationManager;
@@ -139,6 +142,8 @@ package gui
private var _privacyId:int;
private var _itemSetEvent:DenItemHolderEvent;
private var _layerControls:Sprite;
public function DenEditor()
{
@@ -157,6 +162,7 @@ package gui
_roomMgr = RoomManagerWorld.instance;
_denItemHolder = _roomMgr.denItemHolder;
_guiLayer.addChild(_denEditor);
createLayerControls();
initAssetVisibility();
setupPlayerItems();
DenXtCommManager.denEditorDIResponseCallback = diResponseCallback;
@@ -170,6 +176,7 @@ package gui
_denItemHolder.removeEventListener("OnItemRemoved",onDenItemRemoved);
_denItemHolder.removeEventListener("OnSaveState",onDenSaveState);
removeListeners();
destroyLayerControls();
_guiLayer.removeChild(_denEditor);
if(_denLockPopup)
{
@@ -1195,6 +1202,76 @@ package gui
var _loc3_:DenStateItem = new DenStateItem(param1.defId,param1.invIdx,param1.defId << 16 | _loc2_,0,0,param1.version,param1.version2,param1.version3,0,_loc2_,param1.refId,param1.sortId,param1.minigameDefId,param1.layerId,param1.enviroType,param1.strmName,0,"",param1.specialType,param1.listId,param1.uniqueImageId,param1.uniqueImageCreator,param1.uniqueImageCreatorDbId,param1.uniqueImageCreatorUUID,false,null,0,0,param1.petItem,param1.mannequinData,param1.ecoConsumerStateId);
_roomMgr.spawnNewDenItem(_loc3_);
}
// Small controls added at runtime so every den item can be stacked
// deliberately, instead of relying solely on where its feet land.
private function createLayerControls() : void
{
_layerControls = new Sprite();
_layerControls.x = _denEditor.width - 258;
_layerControls.y = 12;
_layerControls.addChild(makeLayerLabel("Selected item layer",0,0,230,22,13,16774041));
addLayerButton("Send behind",0,onSendBehind);
addLayerButton("Bring on top",116,onBringOnTop);
addLayerButton("Use natural depth",0,onResetLayer,62,230,30);
_denEditor.addChild(_layerControls);
}
private function addLayerButton(param1:String, param2:Number, param3:Function, param4:Number = 26, param5:Number = 110, param6:Number = 30) : void
{
var _loc6_:Sprite = new Sprite();
_loc6_.x = param2;
_loc6_.y = param4;
_loc6_.buttonMode = true;
_loc6_.mouseChildren = false;
_loc6_.graphics.beginFill(5986842,0.96);
_loc6_.graphics.drawRoundRect(0,0,param5,param6,8,8);
_loc6_.graphics.endFill();
_loc6_.addChild(makeLayerLabel(param1,0,5,param5,param6 - 5,12,16777215));
_loc6_.addEventListener("mouseDown",param3,false,0,true);
_layerControls.addChild(_loc6_);
}
private function makeLayerLabel(param1:String, param2:Number, param3:Number, param4:Number, param5:Number, param6:int, param7:uint) : TextField
{
var _loc8_:TextField = new TextField();
_loc8_.x = param2;
_loc8_.y = param3;
_loc8_.width = param4;
_loc8_.height = param5;
_loc8_.selectable = false;
_loc8_.mouseEnabled = false;
_loc8_.defaultTextFormat = new TextFormat("Arial",param6,param7,true,null,null,null,null,"center");
_loc8_.text = param1;
return _loc8_;
}
private function onSendBehind(param1:MouseEvent) : void
{
param1.stopImmediatePropagation();
_denItemHolder.sendSelectedBehind();
}
private function onBringOnTop(param1:MouseEvent) : void
{
param1.stopImmediatePropagation();
_denItemHolder.bringSelectedToFront();
}
private function onResetLayer(param1:MouseEvent) : void
{
param1.stopImmediatePropagation();
_denItemHolder.resetSelectedStacking();
}
private function destroyLayerControls() : void
{
if(_layerControls && _layerControls.parent)
{
_layerControls.parent.removeChild(_layerControls);
}
_layerControls = null;
}
private function onClose(param1:MouseEvent) : void
{
+16
View File
@@ -96,6 +96,22 @@ package loader
public function get sortOffset() : int
{
// The low two flip bits are used by the original client. Den editing
// also uses bits 2-3 as an explicit stacking choice: 1 = behind and
// 2 = in front. A very large offset lets that choice win over the
// normal y-position depth sort without visibly moving the item.
if(_denStateItem != null)
{
var _loc1_:int = _denStateItem.flipped >> 2 & 3;
if(_loc1_ == 1)
{
return _sortOffset + 1000000;
}
if(_loc1_ == 2)
{
return _sortOffset - 1000000;
}
}
return _sortOffset;
}
+6 -1
View File
@@ -690,6 +690,7 @@ package gui
var _loc5_:String = null;
var _loc4_:Array = null;
var _loc3_:Object = null;
var _loc9_:Object = null;
var _loc6_:ECard = _inbox[_currCardIdx];
if(_loc6_)
{
@@ -709,8 +710,12 @@ package gui
});
break;
}
// A card records the historical layer id. Prefer the
// attached item's current accId when it is available,
// so items with shared or changed layers draw correctly.
_loc9_ = ItemXtCommManager.getItemDef(giftItemDefId(_loc6_));
_clothingIconHelper = new SimpleIcon();
_clothingIconHelper.init(_loc6_.giftColor,_loc6_.giftId,1,true,false,clothingIconReceived);
_clothingIconHelper.init(_loc6_.giftColor,_loc9_ ? _loc9_.accId : _loc6_.giftId,1,true,false,clothingIconReceived);
break;
case 3:
case 99:
+22
View File
@@ -180,6 +180,10 @@ package gui
private static var _imageDisplayPopup:ImageDisplayPopup;
private static var _petInventory:PetInventory;
// A player's voluntary pet form. Party and quest pet forms remain
// room-wide and are still reported by isBeYourPetRoom().
private static var _personalPetMode:Boolean = false;
private static var _joeyPopup:MovieClip;
@@ -2906,6 +2910,24 @@ package gui
{
return QuestManager.isBeYourPetQuest() || PartyManager.isBeYourPetParty();
}
public static function isPlayingAsPet() : Boolean
{
return _personalPetMode || isBeYourPetRoom();
}
public static function setPersonalPetMode(param1:Boolean) : void
{
if(_personalPetMode == param1)
{
return;
}
_personalPetMode = param1;
if(mainHud)
{
showHudAvt();
}
}
public static function addQuestXP(param1:Number) : void
{
+18
View File
@@ -191,6 +191,9 @@ package gui.itemWindows
case "wasd":
showWasd();
break;
case "performance":
showPerformance();
break;
case "graphics":
showGraphics();
break;
@@ -416,6 +419,18 @@ package gui.itemWindows
{
showChoice("Graphics",AJClient.smoothOn() ? "Smooth" : "Default");
}
private function showPerformance() : void
{
showChoice("Performance",AJClient.performanceProfileLabel());
}
private function nextPerformance() : void
{
var _loc1_:int = AJClient.performanceProfile();
setChoice(9007,_loc1_ == 0 ? 1 : (_loc1_ == 1 ? 2 : 0));
showPerformance();
}
private function showFrameRate() : void
{
@@ -715,6 +730,9 @@ package gui.itemWindows
case "wasd":
setWasd(!AJClient.wasdOn());
break;
case "performance":
nextPerformance();
break;
case "graphics":
setChoice(9003,AJClient.smoothOn() ? 1 : 2);
showGraphics();
+4
View File
@@ -204,6 +204,10 @@ package gui
"type":TOGGLE_TYPE_JOIN,
"frame":"wasd",
"iconFrame":"world"
},{
"type":TOGGLE_TYPE_JOIN,
"frame":"performance",
"iconFrame":"world"
},{
"type":TOGGLE_TYPE_JOIN,
"frame":"graphics",
+36
View File
@@ -151,6 +151,7 @@ package room
gMainFrame.stage.removeEventListener("deactivate",onDeactivate);
gMainFrame.stage.removeEventListener("keyDown",onKeyDownEvt);
gMainFrame.stage.removeEventListener("keyUp",onKeyUpEvt);
removeAndClearMiniMap();
}
override public function exitRoom(param1:Boolean = false) : void
@@ -380,6 +381,11 @@ package room
public function removeAndClearMiniMap() : void
{
var _loc1_:MovieClip = null;
for each(_loc1_ in _miniMaps)
{
disposeMiniMap(_loc1_);
}
if(_miniMap && _miniMap.parent)
{
_miniMap.parent.removeChild(_miniMap);
@@ -387,6 +393,36 @@ package room
_miniMap = null;
_miniMaps = new Dictionary();
}
// The minimap grid and trail are BitmapData made for this room. Flash
// may keep their native allocations after the display clips are dropped,
// particularly after visiting many rooms, so release only those buffers
// when the cache is intentionally cleared.
private function disposeMiniMap(param1:MovieClip) : void
{
var _loc1_:Bitmap = null;
try
{
if(param1 != null && param1.numChildren > 1)
{
_loc1_ = param1.getChildAt(1) as Bitmap;
if(_loc1_ != null && _loc1_.bitmapData != null)
{
_loc1_.bitmapData.dispose();
_loc1_.bitmapData = null;
}
}
_loc1_ = param1 != null && param1.overlay is Bitmap ? Bitmap(param1.overlay) : null;
if(_loc1_ != null && _loc1_.bitmapData != null)
{
_loc1_.bitmapData.dispose();
_loc1_.bitmapData = null;
}
}
catch(e:Error)
{
}
}
public function removeMiniMap() : void
{
+20 -1
View File
@@ -2526,7 +2526,26 @@ package room
}
_theaterLayer = _scene.getLayer("movie_player_streaming");
}
GenericListGuiManager.genericListVolumeClicked(_loc5_.typeDefId,_loc9_);
// The stock theatre asks the server for a legacy FLV
// playlist, which this server intentionally does not
// fabricate for arbitrary web URLs. Let the VIDEOS
// sign open the staff YouTube control instead; its SWF
// callback verifies the staff permission.
if(_loc4_.typeId == 1037 && ExternalInterface.available)
{
try
{
ExternalInterface.call("ajOpenTheatreControl");
}
catch(e:Error)
{
GenericListGuiManager.genericListVolumeClicked(_loc5_.typeDefId,_loc9_);
}
}
else
{
GenericListGuiManager.genericListVolumeClicked(_loc5_.typeDefId,_loc9_);
}
}
break;
case 13:
+5 -1
View File
@@ -1103,7 +1103,11 @@ package gui
var _loc4_:int = int(param1[2]);
if(_loc4_ == 0)
{
if(isCurrentlyTrading || gMainFrame.clientInfo.extCallsActive)
// The desktop client keeps extCallsActive set while its host is
// available. It is not an indication that this player has a
// modal dialog open; treating it as one made every incoming
// trade request look like a busy response.
if(isCurrentlyTrading)
{
TradeXtCommManager.sendTradeItemAcceptOrReject(2);
}
+25
View File
@@ -523,6 +523,13 @@ package avatar
_customPVPPassback = param4;
gMainFrame.server.sendMessage((param1 ? "on" : "off") + RAW_STR + 12 + RAW_STR + param2);
}
// A per-player counterpart to the party's room-wide pet form. The
// server relays this as a normal user-communication message (type 13).
public static function sendPetPlayerMode(param1:Boolean) : void
{
gMainFrame.server.sendMessage((param1 ? "on" : "off") + RAW_STR + 13);
}
public static function onSendMessage(param1:MouseEvent, param2:String = "") : void
{
@@ -714,6 +721,13 @@ package avatar
_customPVPMessageCallback = null;
}
}
else if(_loc20_ == 13)
{
if(AvatarManager.avatarViewList[_loc19_])
{
AvatarManager.avatarViewList[_loc19_].setPetPlayerMode(_loc2_ == "on");
}
}
else
{
_loc2_ = param1[3];
@@ -786,6 +800,17 @@ package avatar
case 10:
AvatarManager._setAvatarAlphaLevel(_loc19_,uint(param1[3]));
return;
// Server room effects: a temporary display-only scale.
// Kept here (rather than in avatar state) so it never
// becomes part of an animal's saved appearance.
case 14:
_loc3_ = Math.max(0.5,Math.min(1.5,Number(param1[3])));
if(AvatarManager.avatarViewList[_loc19_])
{
AvatarManager.avatarViewList[_loc19_].scaleX = _loc3_;
AvatarManager.avatarViewList[_loc19_].scaleY = _loc3_;
}
return;
default:
_loc14_ = true;
}
+10
View File
@@ -89,6 +89,16 @@ package
AJClient.onStaff(param1.obj);
return;
}
if(param1.obj[0] == "xtv")
{
AJClient.onTheatreVideo(param1.obj);
return;
}
if(param1.obj[0] == "xui")
{
AJClient.onStaffUi(param1.obj);
return;
}
if(param1.obj[0] == "xdi")
{
AJClient.onItemDefs(param1.obj);
BIN
View File
Binary file not shown.
+8
View File
@@ -172,6 +172,14 @@ const run = async () => {
a.xt("mg", subRoom[4], 1, 2, 3); // not signed: no gems
await a.nextXt("mg");
assert.ok(nextSerial > 0);
// food machine wins award a temporary avatar attachment rather than an
// inventory entry.
a.xt("mm", subRoom[4], 15, "_a", 1);
assert.deepStrictEqual((await a.nextXt("mm")).slice(2), ["_a", "1", ""]);
// Attachment packets must also return to their sender: that echoed media
// id is what makes the local avatar draw the held item.
a.send(`<msg t='sys'><body action='pubMsg' r='${subRoom[4]}'><txt><![CDATA[1,%4]]></txt></body></msg>`);
assert.deepStrictEqual((await a.nextXt("uc")).slice(2), [String(annLogin.params.userId), "35,", "4"]);
a.xt("rl", subRoom[4], subRoom[4]);
a.xt("mj", roomId, 4, 0, 0, -1); // gem Ball takes the room's place
const gameRoom = await a.nextXt("rj");
+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 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`.
const untilDefs = async (client, kind) => {
for (;;) {
@@ -412,6 +434,56 @@ const first = async () => {
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/);
// --- 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
assert.match((await maker("delete", "clothing", 50001)).said, /not one of your items/);
for (const entry of full.mine) {
@@ -420,6 +492,8 @@ const first = async () => {
assert.deepStrictEqual((await maker("info")).mine, []);
assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png`)).status, 404);
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,
// 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.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
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",
@@ -472,7 +560,7 @@ const first = async () => {
"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")}`);
}
made = {base};
made = {base, restrictedId: 50000};
for (const {client} of [pat, devGame, hal]) {
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.den.map(entry => entry.name), ["Test Chair"]);
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");
const shop = await shopList(lou.client, lou.roomId, ODD_CLOTHING_SHOP);
assert.ok(shop.includes("50001") && !shop.includes("50000"));
+6
View File
@@ -274,6 +274,10 @@ const run = async () => {
assert.strictEqual((await panel(`masterpiece?id=${posted.uuid}`)).status, 401);
assert.strictEqual((await panel("masterpiece", {id: posted.uuid, action: "approve"}, admin)).status, 200);
assert.match((await a.untilXt("ep"))[7], /approved/);
// on show, with who approved it and when: the last approved first
const onShow = (await panel("masterpieces", undefined, admin)).data.approved;
assert.deepStrictEqual(onShow.map(entry => [entry.id, entry.approvedBy]), [[posted.uuid, "admin"]]);
assert.ok(Math.abs(onShow[0].approvedAt - Date.now() / 1000) < 60);
const approved = await a.nextXt("di");
assert.strictEqual(approved[approved.indexOf(painting, 5) + 4], "true");
// hung, once Ann is home from the easel: a visitor is told which painting and whose.
@@ -316,6 +320,8 @@ const run = async () => {
assert.strictEqual((await a.untilXt("db"))[2], "1");
const last = await a.nextXt("di");
assert.ok(!last.includes("2947") && last[last.indexOf(second.uuid) - 1] === "true");
// approved by nobody, that one
assert.deepStrictEqual((await panel("masterpieces", undefined, admin)).data.approved.map(entry => [entry.id, entry.approvedBy]), [[second.uuid, null]]);
a.socket.destroy();
b.socket.destroy();
+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]};
};
assert.match(await (await fetch(`${BASE}/admin`)).text(), /Server admin/);
assert.deepStrictEqual((await panel("state")).data, {needsSetup: true, needsSetupCode: false, signedIn: false});
const oldAdmin = await fetch(`${BASE}/admin`, {redirect: "manual"});
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("login", {password: "anything"})).status, 401);
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: "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: "New-password-4"}, admin)).status, 200);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "foo", password: "KettlePass04"})).status, 401);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {refresh_token: foo.refresh_token})).status, 401);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "foo", password: "New-password-4"})).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, 200);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {refresh_token: foo.refresh_token})).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.
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");
}
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
@@ -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);
const halMe = (await halPage("/mod/api/me")).data;
assert.strictEqual(halMe.role, "helper");
assert.ok(halMe.permissions.includes("server.view"));
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.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
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));
@@ -305,6 +332,7 @@ const run = async () => {
const annAway = (await modPage("/mod/api/player?username=Ann")).data;
assert.strictEqual(annAway.warnings, 4);
assert.strictEqual(annAway.warningList[0].seen, false);
assert.deepStrictEqual(await listed("silenced"), ["Ann"]);
const annBack = await arrive("Ann", people.Ann, SAREPIA);
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);
+2 -1
View File
@@ -92,7 +92,8 @@ set -- \
gui.SitForwardAction SitForwardAction.as \
avatar.AvatarUtility AvatarUtility.as \
item.Item Item.as \
loader.DenItemHelper DenItemHelper.as
loader.DenItemHelper DenItemHelper.as \
room.DenItemHolder ../tools/decompiled/room/DenItemHolder.as
# not in the game: added before the replace (game.ArtStudioKit is Strawberry
# Jam's, shared by its two art studio painters; gui.SitForwardAction is the
# action of sitting facing forward)
+34
View File
@@ -148,6 +148,40 @@ package room
{
return _dragItem != null;
}
// The original editor only sorted furniture from its y position. These
// helpers give the replacement editor an explicit, persisted choice.
// Bits 2-3 of `flipped` are unused by the game's flip code, so the
// normal horizontal/vertical flip bits remain intact in bits 0-1.
public function sendSelectedBehind() : Boolean
{
return setSelectedStacking(1);
}
public function bringSelectedToFront() : Boolean
{
return setSelectedStacking(2);
}
public function resetSelectedStacking() : Boolean
{
return setSelectedStacking(0);
}
private function setSelectedStacking(param1:int) : Boolean
{
if(_dragItem == null || _dragItem.layerId == 1 || isTheme(_dragItem.sortCatId) || _dragItem.sortCatId == 4)
{
return false;
}
_dragItem.flipped = _dragItem.flipped & -13 | param1 << 2;
if(_dragItem.denItemHelper && _dragItem.denItemHelper.displayObject)
{
_dragItem.denItemHelper.displayObject.name = String(_dragItem.denItemHelper.sortOffset);
}
saveState(_dragItem.invIdx);
return true;
}
public function get lastSelectedItem() : DenStateItem
{