mirror of
https://github.com/burrow-dev/burrow-server.git
synced 2026-11-18 17:27:50 -05:00
feat(server): staff tools, player-made items, picture safety, chat, multiplayer games
Staff and moderation
- Invisible staff (!invisible, "xiv"): hidden from players, half see-through
to other staff, cannot chat while hidden. New permission staff.invisible.
- Summon and goto land on the player's exact spot ("xgt" before the move).
- Custom warnings (!warn PLAYER custom TEXT), shown in the warning popup.
- Mod notes (!note, !notes; lib/modnotes.js), on the player page and the
dashboard.
- Granular permissions: per-role overrides (setting rolePermissions) and
per-account grants and denies, applied live to staff who are playing
(refreshStaff re-sends "xsp").
- Item control (lib/itemcontrol.js): lock items out of the item finder
(!lock, !unlock, !locked), take an item from a player (!take), delete a
custom item from the game and every inventory.
- GET items/find: search any item by name or id, marked locked, for the
dashboards' quick lock.
Player-made items (lib/playeritems.js, "xcm")
- The Item Maker: make, rename, set the worn look, delete. 5 a day, 20 in all;
names go through the name filter.
- Admin switches: Item Maker on/off, new items wait for approval, and a
separate switch (on by default) that holds every player-uploaded picture
for a moderator. Review queue for items.approve (moderator and up).
- Pictures (lib/itemart.js): PNG, JPEG and GIF cleaned of metadata, BMP
converted to PNG; 512px and 300KB at most once cleaned.
- Worn as the maker chooses: a sticker (the picture) or a texture (the
item's shape painted with the picture).
Picture safety
- A picture waiting for approval is never served publicly: /itemart/ 404s it,
and it is only shown through /account|/mod|/admin/api/itemart to its maker
and to staff who review or make items.
- A picture turned away or taken off is remembered by SHA-256 and cannot be
uploaded again.
- Three strikes: three pictures turned away stops a player's uploads until a
moderator lets them again. Staff can stop or allow uploads by hand.
- Accounts under 24 hours old cannot upload pictures (AJ_ITEM_ART_MIN_HOURS);
uploads capped at 10 a day.
- Optional Google Cloud Vision SafeSearch (lib/image-moderation.js) for item
pictures and Art Studio paintings when AJ_GOOGLE_VISION_API_KEY is set;
fails closed when the scanner is unreachable.
Chat
- Emoji: Twemoji pictures served at /emoji/<codepoints>.png and cached in
data/emoji (lib/emoji.js).
- Smart spam filtering before the word filter (lib/chatspam.js): long runs of
one character, repeated words and lines, huge words and emoji floods are
tidied, and repeats within 20 seconds are dropped.
- Typing indicator: "xty" is passed on to everyone in the room who can see
the player, at most every 2 seconds.
Games (lib/minigames.js)
- Room games can be played together: a MULTIPLAYER table gives a game a
waiting list (Single Player / Multiplayer). Players in the same room are
matched, taken into the game together, and each one's moves are relayed to
the others. Gem Breaker is the first: two players, "pos", "shoot" and
"playerLost" relayed.
- Gem Breaker's start message now lists each player's id. Without it no
player counted as local, so even single player could not aim.
Other
- Players stay connected through the client's new 75-minute AFK limit
(idleTimeoutMs 80 minutes).
- Jam-a-Grams carry custom items and colours; Jammer Wall avatar photos are
validated (walls.js photoParam).
- Weak passwords refused (common words, or containing the username).
- Code-scanning fixes: every logged value goes through logText
(lib/logtext.js) against log injection, HSTS, path-only error logs, a
single file read in lib/names.js.
Tests: items (pictures, approval, strikes, re-upload refusal, the hidden
waiting picture, the dashboard search), staff (invisibility, goto and summon
spots, custom warnings, notes), buddygames (two-player Gem Breaker, the
typing relay), and updates for main's verified badge and spawn rooms.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
da7eb9af58
commit
e05565787f
50 files changed
+2904
-277
No files matched your search
@@ -3,6 +3,7 @@
|
||||
const path = require("path");
|
||||
|
||||
const env = process.env;
|
||||
const googleVisionApiKey = env.AJ_GOOGLE_VISION_API_KEY;
|
||||
const LOOPBACK_NAMES = ["127.0.0.1", "::1", "localhost"];
|
||||
const bindAddress = env.AJ_BIND || "127.0.0.1";
|
||||
const httpPort = Number(env.AJ_HTTP_PORT || 8080);
|
||||
@@ -84,6 +85,13 @@ module.exports = {
|
||||
// cookies are only sent back over an encrypted connection when players
|
||||
// have one, whoever does the encrypting.
|
||||
secureCookies: baseUrl.startsWith("https:"),
|
||||
// Google Cloud Vision SafeSearch, used for player-uploaded custom item art
|
||||
// and masterpieces. Off when no key is configured (useful for local work).
|
||||
// When on, a Google outage rejects uploads rather than letting unscanned
|
||||
// images through.
|
||||
googleVision: googleVisionApiKey ? {
|
||||
endpoint: `https://vision.googleapis.com/v1/images:annotate?key=${encodeURIComponent(googleVisionApiKey)}`,
|
||||
} : null,
|
||||
// the admin panel answers this machine alone on a public server (reach it
|
||||
// through an SSH tunnel), plus the addresses listed in AJ_ADMIN_ALLOW,
|
||||
// separated by commas. on a local server it answers whoever can reach it.
|
||||
@@ -97,6 +105,8 @@ module.exports = {
|
||||
// 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/",
|
||||
// emoji pictures for chat (lib/emoji.js): Twemoji's, at one version
|
||||
emojiUpstream: env.AJ_EMOJI_UPSTREAM || "https://cdn.jsdelivr.net/gh/jdecked/[email protected]/assets/72x72/",
|
||||
offline: env.AJ_OFFLINE === "1",
|
||||
// the client's device ids (lib/devices.js): with AJ_REQUIRE_DEVICE=1, a
|
||||
// sign-in without them (a client from before 1.3.0, the official
|
||||
@@ -263,9 +273,11 @@ module.exports = {
|
||||
// can switch in the settings menu (gui.ServerSelector). the game names
|
||||
// world N after the Nth name of its own list (551 Aldan, 552 Congo...,
|
||||
// generic list 16), so the names here are only for the panels and logs.
|
||||
// AJ_WORLDS: how many (the tests' is one).
|
||||
// AJ_WORLDS: how many. A local server starts with one shared world so two
|
||||
// players in the same land can always see one another; set AJ_WORLDS=2 or
|
||||
// more to opt into separate copies of every land.
|
||||
shards: ["Aldan", "Congo", "Draa", "Grande", "Kama", "Nile", "Pecos", "Ramu", "Tigris", "Zambezi"]
|
||||
.slice(0, Math.min(10, Math.max(1, Number(env.AJ_WORLDS) || 2))).map((name, i) => ({id: i + 1, name})),
|
||||
.slice(0, Math.min(10, Math.max(1, Number(env.AJ_WORLDS) || 1))).map((name, i) => ({id: i + 1, name})),
|
||||
maxUsersPerRoom: 40,
|
||||
// everything in every shop for nothing (AJ_FREE_SHOPS=1). off unless
|
||||
// asked for: what the game's shops make of a price of 0 has not been seen.
|
||||
@@ -301,9 +313,18 @@ module.exports = {
|
||||
tlsHandshakeTimeoutMs: 10000,
|
||||
maxMessagesPerTenSeconds: 400, // per game socket; walking sends a few a second
|
||||
loginTimeoutMs: 30000, // a game socket must log in within this
|
||||
idleTimeoutMs: 15 * 60000, // the client sends a keep-alive far more often
|
||||
// a client sends nothing while its player is away, and signs itself out
|
||||
// after 75 minutes of that (com.sbi.client.KeepAlive): the socket waits longer.
|
||||
idleTimeoutMs: 80 * 60000,
|
||||
tokenLifetimeDays: 30, // login tokens kept by the launcher's "remember me"
|
||||
maxChatLength: 300,
|
||||
// a line as sent: the client's chat box takes 200 (gui.ChatHistory), and
|
||||
// each emoji goes as a tag of 8 or more ("\{1f600}"). lib/chatspam.js
|
||||
// cuts down what is long for no good reason.
|
||||
maxChatLength: 600,
|
||||
// how old an account must be before it may give its items pictures
|
||||
// (lib/playeritems.js), so a picture turned away is not simply sent again
|
||||
// from a new account. not for this machine's own requests (AJ_ITEM_ART_MIN_HOURS).
|
||||
itemArtMinAccountHours: Number(env.AJ_ITEM_ART_MIN_HOURS || 24),
|
||||
// warnings (lib/moderation.js warn): the Nth one within `days` also
|
||||
// silences the player for that many minutes, [[N, minutes], ...]. a
|
||||
// longer silence already on them stays. steps [] turns it off.
|
||||
|
||||
+32
-13
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
@@ -348,7 +349,7 @@ const importLegacyFile = () => {
|
||||
}
|
||||
db.exec("COMMIT");
|
||||
fs.renameSync(file, `${file}.imported`);
|
||||
console.log(`[accounts] imported ${byKey.size} accounts from accounts.json`);
|
||||
console.log(`[accounts] imported ${logText(byKey.size)} accounts from accounts.json`);
|
||||
};
|
||||
|
||||
const load = () => {
|
||||
@@ -391,7 +392,7 @@ const load = () => {
|
||||
// runs the server is told which, to rename by hand if they see fit.
|
||||
const unusual = [...byId.values()].filter(account => names.refused(account.username)).map(account => account.username);
|
||||
if (unusual.length) {
|
||||
console.log(`[accounts] usernames that could not be chosen today: ${unusual.slice(0, 50).join(", ")}${unusual.length > 50 ? ", ..." : ""}`);
|
||||
console.log(`[accounts] usernames that could not be chosen today: ${logText(unusual.slice(0, 50).join(", "))}${logText(unusual.length > 50 ? ", ..." : "")}`);
|
||||
}
|
||||
// once: the Early Member badge for the accounts that were there before
|
||||
// it existed, the oldest hundred of them.
|
||||
@@ -414,7 +415,7 @@ const load = () => {
|
||||
for (const row of db.prepare("SELECT token, account_id, created_at FROM tokens").all()) {
|
||||
tokens.set(row.token, {id: row.account_id, createdAt: row.created_at});
|
||||
}
|
||||
console.log(`[accounts] ${byKey.size} accounts in ${path.join(config.dataDir, "game.sqlite")}`);
|
||||
console.log(`[accounts] ${logText(byKey.size)} accounts in ${logText(path.join(config.dataDir, "game.sqlite"))}`);
|
||||
};
|
||||
|
||||
// Which accounts a save looks at. turning an account into JSON to see
|
||||
@@ -638,7 +639,7 @@ const backup = async () => {
|
||||
for (const name of old) {
|
||||
fs.unlinkSync(path.join(folder, name));
|
||||
}
|
||||
console.log(`[accounts] backup written: ${file}`);
|
||||
console.log(`[accounts] backup written: ${logText(file)}`);
|
||||
};
|
||||
const startBackups = () => {
|
||||
const attempt = () => {
|
||||
@@ -671,9 +672,26 @@ const retire = key => {
|
||||
// A new password: ten characters or more, with a capital letter, a small
|
||||
// one and a digit among them. passwords chosen before this rule still sign
|
||||
// in; it is asked of the next one.
|
||||
const passwordProblem = password =>
|
||||
(typeof password !== "string" || password.length < MIN_PASSWORD_LENGTH || password.length > MAX_PASSWORD_LENGTH
|
||||
|| !/[A-Z]/.test(password) || !/[a-z]/.test(password) || !/[0-9]/.test(password) ? "invalid_password" : null);
|
||||
// the words most often under a password that meets the rules ("Password123",
|
||||
// "Sunshine2024"): with its digits and signs taken off, a password that is
|
||||
// one of these is refused, as is one with the username in it.
|
||||
const COMMON_PASSWORD_WORDS = new Set(["password", "passw", "pass", "qwerty", "qwertyuiop", "asdfgh", "asdfghjkl", "zxcvbn", "abcdef", "abcdefg",
|
||||
"abcdefgh", "abcdefghij", "welcome", "letmein", "iloveyou", "admin", "administrator", "monkey", "dragon", "football", "baseball", "soccer",
|
||||
"sunshine", "princess", "starwars", "superman", "batman", "master", "shadow", "michael", "jennifer", "charlie", "freedom", "whatever",
|
||||
"trustno", "hello", "secret", "login", "changeme", "animaljam", "animal", "jamaa", "jammer", "wildworks", "burrow", "summer", "winter",
|
||||
"spring", "autumn", "january", "minecraft", "roblox", "fortnite", "pokemon", "computer", "internet", "cookie", "chocolate", "butterfly"]);
|
||||
const passwordProblem = (password, username = "") => {
|
||||
if (typeof password !== "string" || password.length < MIN_PASSWORD_LENGTH || password.length > MAX_PASSWORD_LENGTH
|
||||
|| !/[A-Z]/.test(password) || !/[a-z]/.test(password) || !/[0-9]/.test(password)) {
|
||||
return "invalid_password";
|
||||
}
|
||||
const lower = password.toLowerCase();
|
||||
const name = String(username || "").toLowerCase().replace(/[^a-z0-9]/g, "");
|
||||
if (COMMON_PASSWORD_WORDS.has(lower.replace(/[^a-z]/g, "")) || (name.length >= 3 && lower.replace(/[^a-z0-9]/g, "").includes(name))) {
|
||||
return "weak_password";
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// creates an account. `avatar` gives the first animal's {type, name}; the
|
||||
// name may be left out, and is then the player's. there is no default
|
||||
@@ -682,7 +700,7 @@ const passwordProblem = password =>
|
||||
// "invalid_password" | "choose_animal"}.
|
||||
const register = (username, password, avatar = {}) => {
|
||||
username = typeof username === "string" ? username.trim() : username;
|
||||
const error = usernameProblem(username) || passwordProblem(password) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal");
|
||||
const error = usernameProblem(username) || passwordProblem(password, username) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal");
|
||||
if (error) {
|
||||
return {error};
|
||||
}
|
||||
@@ -694,7 +712,7 @@ const register = (username, password, avatar = {}) => {
|
||||
// early Member, for an account made while there are no more than a hundred.
|
||||
badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [],
|
||||
});
|
||||
console.log(`[accounts] registered "${username}" (id ${account.id})`);
|
||||
console.log(`[accounts] registered "${logText(username)}" (id ${logText(account.id)})`);
|
||||
return {account};
|
||||
};
|
||||
|
||||
@@ -740,9 +758,10 @@ const authenticateAsync = async (username, password) => {
|
||||
};
|
||||
|
||||
// gives the account a new password and signs it out everywhere. returns
|
||||
// "invalid_password" when the password is not acceptable, else null.
|
||||
// "invalid_password" (the rules) or "weak_password" (a common one, or the
|
||||
// username in it) when the password is not acceptable, else null.
|
||||
const setPassword = (account, password) => {
|
||||
const problem = passwordProblem(password);
|
||||
const problem = passwordProblem(password, account.username);
|
||||
if (problem) {
|
||||
return problem;
|
||||
}
|
||||
@@ -791,7 +810,7 @@ const rename = (account, username, anyName = false) => {
|
||||
db.prepare("DELETE FROM retired_names WHERE name_key = ?").run(newKey);
|
||||
}
|
||||
db.prepare("UPDATE accounts SET username = ?, username_key = ? WHERE id = ?").run(username, newKey, account.id);
|
||||
console.log(`[accounts] renamed "${account.username}" to "${username}" (id ${account.id})`);
|
||||
console.log(`[accounts] renamed "${logText(account.username)}" to "${logText(username)}" (id ${logText(account.id)})`);
|
||||
byKey.delete(oldKey);
|
||||
account.username = username;
|
||||
byKey.set(newKey, account);
|
||||
@@ -850,7 +869,7 @@ const remove = account => {
|
||||
}
|
||||
}
|
||||
save(...named);
|
||||
console.log(`[accounts] deleted "${account.username}" (id ${account.id})`);
|
||||
console.log(`[accounts] deleted "${logText(account.username)}" (id ${logText(account.id)})`);
|
||||
};
|
||||
|
||||
// small server-wide values kept in the database (the admin panel's password).
|
||||
|
||||
+35
-8
@@ -6,7 +6,10 @@ const captcha = require("./captcha.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const devices = require("./devices.js");
|
||||
const config = require("../config.js");
|
||||
const roles = require("./roles.js");
|
||||
const dens = require("./dens.js");
|
||||
const itemControl = require("./itemcontrol.js");
|
||||
const customItems = require("./customitems.js");
|
||||
const limits = require("./limits.js");
|
||||
const world = require("./world.js");
|
||||
const {addClothing, sendClothingAdded, isUint} = require("./player.js");
|
||||
@@ -37,8 +40,12 @@ const buildCatalog = () => [
|
||||
|
||||
// `favourites` is an account's finderGiven, or null: with nothing typed, the
|
||||
// items that account took most often come first, the latest first among
|
||||
// equals. (The in-game finder says whose search it is.)
|
||||
const search = (params, favourites = null) => {
|
||||
// equals. (The in-game finder says whose search it is.) items locked out of
|
||||
// the finder (lib/itemcontrol.js) are left out, unless `seesLocked`: then
|
||||
// they are marked. an item a player made (lib/playeritems.js) is found by
|
||||
// its maker only (`askerId`), and by those who see locked ones. with
|
||||
// "base=1", only the game's own items that can be made into a new one.
|
||||
const search = (params, favourites = null, seesLocked = false, askerId = null) => {
|
||||
if (!catalog || catalogVersion !== defpacks.customVersion()) {
|
||||
catalog = buildCatalog();
|
||||
catalogVersion = defpacks.customVersion();
|
||||
@@ -46,7 +53,10 @@ const search = (params, favourites = null) => {
|
||||
const kind = params.get("kind") || "all";
|
||||
const words = (params.get("q") || "").toLowerCase().split(/\s+/).filter(Boolean);
|
||||
const matches = catalog.filter(entry => (kind === "all" || entry.kind === kind)
|
||||
&& words.every(word => entry.search.includes(word) || String(entry.id) === word));
|
||||
&& words.every(word => entry.search.includes(word) || String(entry.id) === word)
|
||||
&& (seesLocked || !itemControl.isLocked(entry.kind, entry.id))
|
||||
&& (seesLocked || [null, askerId].includes(customItems.ownerOf(entry.kind, entry.id)))
|
||||
&& (params.get("base") !== "1" || customItems.copyable(entry.kind, entry.id)));
|
||||
matches.sort((a, b) => words.includes(String(b.id)) - words.includes(String(a.id)));
|
||||
if (words.length === 0 && favourites) {
|
||||
const taken = entry => favourites[`${entry.kind}:${entry.id}`] || {count: 0, at: 0};
|
||||
@@ -54,7 +64,10 @@ const search = (params, favourites = null) => {
|
||||
}
|
||||
return {
|
||||
total: matches.length,
|
||||
results: matches.slice(0, MAX_RESULTS).map(({kind: entryKind, id, name, cost, colors}) => ({kind: entryKind, id, name, cost, colors})),
|
||||
results: matches.slice(0, MAX_RESULTS).map(({kind: entryKind, id, name, cost, colors}) => {
|
||||
const locked = seesLocked && itemControl.isLocked(entryKind, id);
|
||||
return {kind: entryKind, id, name: locked ? `${name} (locked)` : name, cost, colors, ...(locked ? {locked} : {})};
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -62,11 +75,19 @@ const search = (params, favourites = null) => {
|
||||
// digits alone are a colour id
|
||||
const HEX_COLOURS = /^#[0-9a-f]{6}([\s,]+#[0-9a-f]{6}){0,3}$/i;
|
||||
|
||||
const give = body => {
|
||||
// `seesLocked`: who asks may take items locked out of the finder.
|
||||
const give = (body, seesLocked = false) => {
|
||||
const account = accounts.byName(body.username);
|
||||
if (!account) {
|
||||
return {status: 404, body: {error: "No such account"}};
|
||||
}
|
||||
const maker = customItems.ownerOf(body.kind, body.id);
|
||||
if (!seesLocked && maker !== null && maker !== account.id) {
|
||||
return {status: 403, body: {error: "That item is another player's own."}};
|
||||
}
|
||||
if (!seesLocked && itemControl.isLocked(body.kind, body.id)) {
|
||||
return {status: 403, body: {error: "That item is locked out of the item finder."}};
|
||||
}
|
||||
const session = world.findOnline(account.username);
|
||||
if (body.kind === "clothing") {
|
||||
const def = defpacks.itemDef(body.id);
|
||||
@@ -130,6 +151,11 @@ const give = body => {
|
||||
|
||||
const FORBIDDEN = {status: 403, body: {error: "forbidden"}};
|
||||
|
||||
// may whoever asks see and take items locked out of the finder? staff who
|
||||
// may lock them (admins and developers) do; so does the owner, on this
|
||||
// machine, asking with no account's token (the /shop page).
|
||||
const seesLocked = (account, from) => (account ? roles.can(account, "items.create") : from.local);
|
||||
|
||||
// the account a login token is for, while it may play. A ban leaves the
|
||||
// token alone (so that the client can ask about the ban with it, below),
|
||||
// and it is good for nothing else until the ban is over.
|
||||
@@ -147,7 +173,8 @@ const handle = async (route, params, body, from) => {
|
||||
case "GET /api/search": {
|
||||
const asking = accounts.byName(params.get("username") || "");
|
||||
const known = asking && (from.local || holderOf(params.get("token")) === asking);
|
||||
return {status: 200, body: search(params, known ? asking.finderGiven : null)};
|
||||
return {status: 200, body: search(params, known ? asking.finderGiven : null, seesLocked(params.get("token") ? holderOf(params.get("token")) : null, from),
|
||||
known ? asking.id : null)};
|
||||
}
|
||||
case "GET /api/accounts":
|
||||
if (!from.local) {
|
||||
@@ -162,7 +189,7 @@ const handle = async (route, params, body, from) => {
|
||||
if (!from.local && !givesPerMinute.allow(owner.id)) {
|
||||
return {status: 429, body: {error: "Too many at once. Try again in a minute."}};
|
||||
}
|
||||
return give(body || {});
|
||||
return give(body || {}, seesLocked((body || {}).token ? owner : null, from));
|
||||
}
|
||||
case "POST /api/theme": {
|
||||
const account = accounts.byName((body || {}).username);
|
||||
@@ -260,4 +287,4 @@ const handle = async (route, params, body, from) => {
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {handle};
|
||||
module.exports = {handle, search};
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
// adventures. the engine is in the client (quest/QuestManager): it places
|
||||
// the actors named in the room file and plays them. what happens when was
|
||||
// decided by scripts on the official server, which no file holds, so each
|
||||
@@ -145,7 +146,7 @@ module.exports = ({enterRoom, joinRoom, tell}) => {
|
||||
family[1](tools(session, quest), key, ...args);
|
||||
}
|
||||
else if (key !== null && kind !== "pickedUp") {
|
||||
console.log(`[adventure] ${quest.script.title}: nothing written for "${kind} ${key}"`);
|
||||
console.log(`[adventure] ${logText(quest.script.title)}: nothing written for "${logText(kind)} ${logText(key)}"`);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const accounts = require("./accounts.js");
|
||||
const limits = require("./limits.js");
|
||||
const net = require("net");
|
||||
@@ -158,7 +159,7 @@ const appeal = (account, text, addressKey = "") => {
|
||||
}
|
||||
db().prepare("INSERT INTO appeals (account_id, created_at, username, text, address_key) VALUES (?, ?, ?, ?, ?)").run(account.id, now(), account.username, body, addressKey);
|
||||
record({account, address: addressKey, action: "appeal"});
|
||||
console.log(`[bans] "${account.username}" appealed`);
|
||||
console.log(`[bans] "${logText(account.username)}" appealed`);
|
||||
return {appeal: appealOf(account)};
|
||||
};
|
||||
|
||||
|
||||
+7
-3
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
@@ -79,7 +80,7 @@ const verify = async (answer, from, action) => {
|
||||
result = await response.json();
|
||||
}
|
||||
catch (err) {
|
||||
console.log(`[captcha] cloudflare did not answer: ${err.message}`);
|
||||
console.log(`[captcha] cloudflare did not answer: ${logText(err.message)}`);
|
||||
return "captcha_unavailable";
|
||||
}
|
||||
// an answer made for another form is no answer for this one. cloudflare's
|
||||
@@ -103,8 +104,11 @@ const check = async (body, from, action, account) => {
|
||||
return verify(body.captcha, from, action);
|
||||
};
|
||||
|
||||
// a page's security policy, letting the widget in when it is on.
|
||||
const policy = csp => (on ? `${csp.replace("script-src ", `script-src 'self' ${ORIGIN} `)}; frame-src ${ORIGIN}` : csp);
|
||||
// a page's security policy: public/captcha.js always (the page calls it even
|
||||
// when off), and the widget too when it is on.
|
||||
const policy = csp => (on
|
||||
? `${csp.replace("script-src ", `script-src 'self' ${ORIGIN} `)}; frame-src ${ORIGIN}`
|
||||
: csp.replace("script-src ", "script-src 'self' "));
|
||||
|
||||
// a page with public/captcha.js asked for under a name that changes with the
|
||||
// script and the key: cloudflare keeps .js files for hours, whatever the
|
||||
|
||||
+6
-5
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
@@ -69,7 +70,7 @@ const measure = async folder => {
|
||||
};
|
||||
measure(config.cacheDir).then(() => {
|
||||
if (cacheBytes > config.maxCacheBytes) {
|
||||
console.log(`[cdn] the cache holds ${Math.round(cacheBytes / 1048576)} MB, over its limit: new files are served but not kept (AJ_MAX_CACHE_MB)`);
|
||||
console.log(`[cdn] the cache holds ${logText(Math.round(cacheBytes / 1048576))} MB, over its limit: new files are served but not kept (AJ_MAX_CACHE_MB)`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -84,7 +85,7 @@ const download = async (relPath, file) => {
|
||||
}
|
||||
missing.add(relPath);
|
||||
}
|
||||
console.log(`[cdn] ${res.status} ${relPath}`);
|
||||
console.log(`[cdn] ${logText(res.status)} ${logText(relPath)}`);
|
||||
return null;
|
||||
}
|
||||
const body = Buffer.from(await res.arrayBuffer());
|
||||
@@ -99,10 +100,10 @@ const download = async (relPath, file) => {
|
||||
const tmp = `${file}.${process.pid}.tmp`;
|
||||
await fs.promises.writeFile(tmp, body);
|
||||
await fs.promises.rename(tmp, file);
|
||||
console.log(`[cdn] cached ${relPath} (${body.length} bytes)`);
|
||||
console.log(`[cdn] cached ${logText(relPath)} (${logText(body.length)} bytes)`);
|
||||
}
|
||||
catch (err) {
|
||||
console.log(`[cdn] could not cache ${relPath}: ${err.message}`);
|
||||
console.log(`[cdn] could not cache ${logText(relPath)}: ${logText(err.message)}`);
|
||||
}
|
||||
return body;
|
||||
};
|
||||
@@ -134,7 +135,7 @@ const getExact = async (asked, mayFetch = () => true) => {
|
||||
// A download that fails (the CDN not answering in time) is "not there"
|
||||
// for now, and is tried again the next time the file is asked for.
|
||||
inFlight.set(relPath, download(relPath, file).catch(err => {
|
||||
console.log(`[cdn] could not fetch ${relPath}: ${err.message}`);
|
||||
console.log(`[cdn] could not fetch ${logText(relPath)}: ${logText(err.message)}`);
|
||||
return null;
|
||||
}).finally(() => inFlight.delete(relPath)));
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
@@ -142,11 +143,11 @@ const rules = () => {
|
||||
parsed.push({line, clauses});
|
||||
}
|
||||
else {
|
||||
console.log(`[filter] lib/chat-filter.txt: a rule that could not be read was left out: ${line}`);
|
||||
console.log(`[filter] lib/chat-filter.txt: a rule that could not be read was left out: ${logText(line)}`);
|
||||
}
|
||||
}
|
||||
kept = {mtime, rules: parsed};
|
||||
console.log(`[filter] ${parsed.length} rules`);
|
||||
console.log(`[filter] ${logText(parsed.length)} rules`);
|
||||
}
|
||||
return kept.rules;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"use strict";
|
||||
|
||||
// typed chat made fit to read before anyone sees it (lib/world.js, pubMsg):
|
||||
// not a filter of what is said (that is lib/chatfilter.js) but of how much
|
||||
// of it there is. a key held down ("aaaaaaaaaa..."), a word said over and
|
||||
// over, one long run of letters with no space, a line all in capitals, a
|
||||
// wall of emoji: each is cut down, and the line still goes. the same line
|
||||
// said again and again in a short while does not.
|
||||
|
||||
const MAX_RUN = 5; // the same character this many times at most ("nooooo")
|
||||
const MAX_REPEAT = 4; // the same word or emoji this many times in a row
|
||||
const MAX_WORD = 32; // letters with no space between
|
||||
const MAX_EMOJI = 12; // emoji in a line ("\{1f600}", as the client sends them)
|
||||
const SHOUT_LENGTH = 12; // a line this long or more ...
|
||||
const SHOUT_SHARE = 0.7; // ... with this share of its letters capitals is lowered
|
||||
const REPEAT_LINES = 3; // the last few lines a player said ...
|
||||
const REPEAT_MS = 20000; // ... within this long: one of those again is not sent
|
||||
|
||||
const EMOJI = /\\\{[0-9a-f]{2,6}(?:-[0-9a-f]{2,6}){0,9}\}/g;
|
||||
|
||||
// the line made tidy. emoji tags count as one character each here.
|
||||
const tidy = text => {
|
||||
// every emoji as one character for now (a private-use one), so that the
|
||||
// rules below see it as one: put back at the end
|
||||
const emoji = [];
|
||||
let line = String(text).replace(EMOJI, tag => {
|
||||
emoji.push(tag);
|
||||
return String.fromCharCode(0xE000);
|
||||
});
|
||||
// a character held down (not a digit: "1000000" is a number)
|
||||
line = line.replace(new RegExp(`(.)\\1{${MAX_RUN},}`, "gu"), (run, char) => (/\d/.test(char) ? run : char.repeat(MAX_RUN)));
|
||||
// one long run with no space
|
||||
line = line.split(" ").map(word => (word.length > MAX_WORD ? word.slice(0, MAX_WORD) : word)).join(" ");
|
||||
// the same word (or emoji) over and over: in a row, with or without spaces
|
||||
line = line.replace(new RegExp(`((?:\\S+?)\\s*)\\1{${MAX_REPEAT},}`, "giu"), (run, once) => (/\d/.test(once) ? run : once.repeat(MAX_REPEAT)));
|
||||
// shouting
|
||||
const letters = line.replace(/[^A-Za-z]/g, "");
|
||||
if (letters.length >= SHOUT_LENGTH && letters.replace(/[^A-Z]/g, "").length / letters.length >= SHOUT_SHARE) {
|
||||
line = line.toLowerCase();
|
||||
}
|
||||
// the emoji back, no more than MAX_EMOJI of them
|
||||
let kept = 0;
|
||||
let at = 0;
|
||||
line = line.replace(new RegExp(String.fromCharCode(0xE000), "g"), () => {
|
||||
const tag = emoji[at++];
|
||||
return kept++ < MAX_EMOJI ? tag : "";
|
||||
});
|
||||
return line.replace(/\s{2,}/g, " ").trim();
|
||||
};
|
||||
|
||||
// was this line said by them just now (one of their last few, a short while
|
||||
// ago)? kept on the session, as recentChat is.
|
||||
const repeated = (session, line) => {
|
||||
const now = Date.now();
|
||||
const said = (session.saidLately || []).filter(entry => now - entry.at < REPEAT_MS);
|
||||
const again = said.some(entry => entry.line.toLowerCase() === line.toLowerCase());
|
||||
session.saidLately = [...said, {line, at: now}].slice(-REPEAT_LINES);
|
||||
return again;
|
||||
};
|
||||
|
||||
module.exports = {tidy, repeated};
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const accounts = require("./accounts.js");
|
||||
|
||||
// custom colours. the game stores a colour as four palette indexes packed in
|
||||
@@ -29,7 +30,7 @@ const load = () => {
|
||||
entries.set(row.id, row.rgb.split(",").map(Number));
|
||||
nextId = Math.max(nextId, row.id + 1);
|
||||
}
|
||||
console.log(`[colours] ${entries.size} custom colours`);
|
||||
console.log(`[colours] ${logText(entries.size)} custom colours`);
|
||||
};
|
||||
|
||||
const valid = rgbs => rgbs.length === 4 && rgbs.every(value => Number.isInteger(value) && value >= 0 && value <= MAX_RGB);
|
||||
|
||||
+137
-2
@@ -3,6 +3,8 @@
|
||||
const accounts = require("./accounts.js");
|
||||
const chatlog = require("./chatlog.js");
|
||||
const customItems = require("./customitems.js");
|
||||
const itemControl = require("./itemcontrol.js");
|
||||
const modNotes = require("./modnotes.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const disguises = require("./disguises.js");
|
||||
const dens = require("./dens.js");
|
||||
@@ -50,7 +52,7 @@ const MAX_AGAIN = 100;
|
||||
// A hosted party's own name is three string ids, no use outside the game.
|
||||
const roomTitle = room => (room.partyHost ? `${room.partyHost.username}'s party` : room.displayName);
|
||||
|
||||
module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideBlocked, refreshForOthers, travel, reloadRoom, buyAgain, ask, staffMove, staffModeration}) => {
|
||||
module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideBlocked, refreshForOthers, travel, reloadRoom, buyAgain, ask, staffMove, setInvisible, staffModeration}) => {
|
||||
// A plain message box with an OK button.
|
||||
const tell = (session, text) => session.sendXt("xtl", -1, String(text).replace(/%/g, " percent"));
|
||||
|
||||
@@ -511,6 +513,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
|
||||
const MAX_WARNING = 200;
|
||||
const MAX_WARNINGS_SHOWN = 5;
|
||||
const MAX_ITEMS_LISTED = 8;
|
||||
const MAX_NOTES_SHOWN = 5; // "!notes": the latest, in one message box
|
||||
|
||||
const staffMay = (session, permission) => {
|
||||
const moderation = staffModeration();
|
||||
@@ -564,6 +567,34 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
|
||||
const logged = (session, action, target, detail = "") =>
|
||||
modlog.record(session.account.username, `${action} (in game)`, target.account.username, detail);
|
||||
|
||||
// what lib/itemcontrol.js tells about items taken.
|
||||
const worldForItems = {itemsTaken: (...args) => require("./world.js").itemsTaken(...args)};
|
||||
|
||||
const lockCommand = (session, words, locked) => {
|
||||
const [kind, id] = [(words[0] || "").toLowerCase(), words[1]];
|
||||
if (words.length !== 2) {
|
||||
tell(session, `Use: !${locked ? "lock" : "unlock"} clothing|den ID`);
|
||||
return;
|
||||
}
|
||||
const result = itemControl.setLocked(kind, id, locked);
|
||||
tell(session, result.error || result.ok);
|
||||
if (result.ok) {
|
||||
modlog.record(session.account.username, locked ? "item locked (in game)" : "item unlocked (in game)", "", `${kind} ${id}`);
|
||||
}
|
||||
};
|
||||
|
||||
// an account named by the first words (a name may have spaces: the longest
|
||||
// that is one), and the words after it.
|
||||
const accountAndRest = words => {
|
||||
for (let count = words.length; count > 0; count--) {
|
||||
const account = accounts.byName(words.slice(0, count).join(" "));
|
||||
if (account) {
|
||||
return {account, rest: words.slice(count)};
|
||||
}
|
||||
}
|
||||
return {account: null, rest: words};
|
||||
};
|
||||
|
||||
const staffCommands = {
|
||||
// "!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;
|
||||
@@ -602,6 +633,104 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
|
||||
tell(session, on.length ? `Staff online: ${on.join(", ")}` : "No staff online.");
|
||||
},
|
||||
},
|
||||
// "!note PLAYER text": a note for the other staff (lib/modnotes.js),
|
||||
// never shown to the player. "!notes PLAYER": the latest few.
|
||||
note: {
|
||||
permission: "player.view",
|
||||
run(session, words) {
|
||||
const {account, rest} = accountAndRest(words);
|
||||
if (!account || !rest.length) {
|
||||
tell(session, account || !words.length ? "Use: !note PLAYER text" : `No player called ${words[0]}.`);
|
||||
return;
|
||||
}
|
||||
if (account === session.account) {
|
||||
tell(session, "That is you.");
|
||||
return;
|
||||
}
|
||||
if (roles.roleOf(account) && !roles.outranks(session.account, account)) {
|
||||
tell(session, "Staff of your rank or above are for someone higher up to deal with.");
|
||||
return;
|
||||
}
|
||||
const result = modNotes.add(account, session.account.username, rest.join(" "));
|
||||
if (result.error) {
|
||||
tell(session, result.error);
|
||||
return;
|
||||
}
|
||||
tell(session, `Note on ${account.username} added.`);
|
||||
modlog.record(session.account.username, "note (in game)", account.username, result.note.text);
|
||||
},
|
||||
},
|
||||
notes: {
|
||||
permission: "player.view",
|
||||
run(session, words) {
|
||||
const account = words.length ? accounts.byName(words.join(" ")) : null;
|
||||
if (!account) {
|
||||
tell(session, words.length ? `No player called ${words.join(" ")}.` : "Use: !notes PLAYER");
|
||||
return;
|
||||
}
|
||||
const latest = modNotes.list(account).slice(0, MAX_NOTES_SHOWN)
|
||||
.map(note => `${new Date(note.at * 1000).toISOString().slice(0, 10)} ${note.by}: ${note.text}`);
|
||||
tell(session, latest.length ? `Notes on ${account.username}: ${latest.join(" | ")}` : `No notes on ${account.username}.`);
|
||||
},
|
||||
},
|
||||
// "!invisible": unseen by players in every room until said again (staff
|
||||
// still see them), as the game's own moderators could be.
|
||||
invisible: {
|
||||
permission: "staff.invisible",
|
||||
run(session) {
|
||||
setInvisible(session, !session.invisible);
|
||||
},
|
||||
},
|
||||
// "!lock clothing|den ID", "!unlock clothing|den ID", "!locked": items
|
||||
// kept out of the item finder for players (lib/itemcontrol.js).
|
||||
lock: {
|
||||
permission: "items.create",
|
||||
run(session, words) {
|
||||
lockCommand(session, words, true);
|
||||
},
|
||||
},
|
||||
unlock: {
|
||||
permission: "items.create",
|
||||
run(session, words) {
|
||||
lockCommand(session, words, false);
|
||||
},
|
||||
},
|
||||
locked: {
|
||||
permission: "items.create",
|
||||
run(session) {
|
||||
const list = itemControl.lockedList().slice(0, MAX_ITEMS_LISTED)
|
||||
.map(entry => `${entry.kind} ${entry.id} ${entry.name || "(no name)"}`);
|
||||
tell(session, list.length ? `Locked out of the item finder: ${list.join("; ")}` : "Nothing is locked out of the item finder.");
|
||||
},
|
||||
},
|
||||
// "!take PLAYER clothing|den ID": every one of that item, out of their
|
||||
// inventory, online or not.
|
||||
take: {
|
||||
permission: "items.create",
|
||||
run(session, words) {
|
||||
const usage = "Use: !take PLAYER clothing|den ID";
|
||||
// the name may have spaces: the kind and the id are the last two words.
|
||||
const [kind, id] = words.slice(-2).map(word => word.toLowerCase());
|
||||
const account = words.length >= 3 ? accounts.byName(words.slice(0, -2).join(" ")) : null;
|
||||
if (words.length < 3 || !/^\d+$/.test(id)) {
|
||||
tell(session, usage);
|
||||
return;
|
||||
}
|
||||
if (!account) {
|
||||
tell(session, `No player called ${words.slice(0, -2).join(" ")}.`);
|
||||
return;
|
||||
}
|
||||
if (account !== session.account && !roles.outranks(session.account, account) && roles.roleOf(account)) {
|
||||
tell(session, "Staff of your rank or above are for someone higher up to deal with.");
|
||||
return;
|
||||
}
|
||||
const result = itemControl.take(account.username, kind, id, worldForItems);
|
||||
tell(session, result.error || result.ok);
|
||||
if (result.ok) {
|
||||
modlog.record(session.account.username, "item taken (in game)", account.username, `${kind} ${id} x${result.count}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
summon: {
|
||||
permission: "player.summon",
|
||||
run(session, words) {
|
||||
@@ -672,15 +801,21 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
|
||||
// "!warn PLAYER [REASON] [note]": a warning, kept on the account and
|
||||
// shown with the game's own warning popup. REASON is behavior (the
|
||||
// default), bullying, personal or scamming; the note is for staff.
|
||||
// "!warn PLAYER custom TEXT": a warning in the staff member's own
|
||||
// words, which is what the player is shown.
|
||||
warn: {
|
||||
permission: "player.warn",
|
||||
run(session, words) {
|
||||
const usage = `Use: !warn PLAYER [${staffModeration().WARNINGS.join("|")}] [note]`;
|
||||
const usage = `Use: !warn PLAYER [${staffModeration().WARNINGS.join("|")}] [note], or !warn PLAYER custom TEXT`;
|
||||
withTarget(session, words, usage, true, (target, rest) => {
|
||||
const {WARNINGS, actions} = staffModeration();
|
||||
const asked = (rest[0] || "").toLowerCase();
|
||||
const reason = WARNINGS.includes(asked) ? asked : "behavior";
|
||||
const note = (WARNINGS.includes(asked) ? rest.slice(1) : rest).join(" ").trim().slice(0, MAX_WARNING);
|
||||
if (reason === "custom" && !note) {
|
||||
tell(session, "Use: !warn PLAYER custom TEXT (the text is what they are shown)");
|
||||
return;
|
||||
}
|
||||
const result = actions.warn(target.account, reason, session.account.username, note);
|
||||
tell(session, `${target.account.username} warned (${reason}): warning ${result.count}.`
|
||||
+ (result.silencedMinutes ? ` Silenced for ${result.silencedMinutes} minutes, for that many warnings.` : ""));
|
||||
|
||||
+139
-13
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const accounts = require("./accounts.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
|
||||
@@ -11,8 +12,8 @@ const defpacks = require("./defpacks.js");
|
||||
// ("xdi", which the patched client adds to its tables), and so is every game
|
||||
// at login, in case it was started before the item was made.
|
||||
//
|
||||
// an item is never removed, since players may have it: it can be taken out
|
||||
// of the shop, renamed and repriced.
|
||||
// an item can be taken out of the shop, renamed and repriced, or deleted:
|
||||
// then it goes from every inventory too (lib/itemcontrol.js).
|
||||
|
||||
// ids far above the game's own (clothing to about 4,600, den items to about
|
||||
// 6,000), one range per pack; names go under localization ids above the
|
||||
@@ -71,7 +72,9 @@ const apply = entry => defpacks.setCustomItem(entry.kind, rowOf(entry), entry.na
|
||||
const messages = entries => {
|
||||
const out = [];
|
||||
for (const kind of KINDS) {
|
||||
const rows = entries.filter(entry => entry.kind === kind).map(entry => ({...rowOf(entry), name: entry.name}));
|
||||
// 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"}));
|
||||
for (let at = 0; at < rows.length; at += CHUNK) {
|
||||
out.push([kind, JSON.stringify(rows.slice(at, at + CHUNK)).replace(/%/g, "\\u0025")]);
|
||||
}
|
||||
@@ -80,6 +83,9 @@ const messages = entries => {
|
||||
};
|
||||
|
||||
const announce = entry => {
|
||||
if (entry.pending) {
|
||||
return;
|
||||
}
|
||||
for (const params of messages([entry])) {
|
||||
broadcast("xdi", ...params);
|
||||
}
|
||||
@@ -88,20 +94,52 @@ const announce = entry => {
|
||||
const fromRow = row => ({
|
||||
kind: row.kind, id: row.id, base: row.base, name: row.name, cost: row.cost, members: row.members === 1,
|
||||
colors: row.colors ? row.colors.split(",").map(Number) : [], inShop: row.in_shop === 1, createdBy: row.created_by, createdAt: row.created_at,
|
||||
ownerId: row.owner_id ?? null,
|
||||
art: row.art || null,
|
||||
artMode: LOOKS.includes(row.art_mode) ? row.art_mode : "sticker",
|
||||
pending: row.pending === 1,
|
||||
artPending: row.art_pending === 1,
|
||||
});
|
||||
|
||||
// a player-made item (lib/playeritems.js) has the maker's account id;
|
||||
// staff-made ones none. an item with a picture of its own (lib/itemart.js)
|
||||
// has its version. the columns came later than the table.
|
||||
const addOwnerColumn = () => {
|
||||
const columns = db().prepare("PRAGMA table_info(custom_items)").all().map(column => column.name);
|
||||
if (!columns.includes("owner_id")) {
|
||||
db().exec("ALTER TABLE custom_items ADD COLUMN owner_id INTEGER");
|
||||
}
|
||||
if (!columns.includes("art")) {
|
||||
db().exec("ALTER TABLE custom_items ADD COLUMN art TEXT");
|
||||
}
|
||||
if (!columns.includes("art_mode")) {
|
||||
db().exec("ALTER TABLE custom_items ADD COLUMN art_mode TEXT");
|
||||
}
|
||||
// waiting for a moderator (lib/playeritems.js, when the admin asks for it):
|
||||
// the item itself, or only its newest picture
|
||||
if (!columns.includes("pending")) {
|
||||
db().exec("ALTER TABLE custom_items ADD COLUMN pending INTEGER");
|
||||
}
|
||||
if (!columns.includes("art_pending")) {
|
||||
db().exec("ALTER TABLE custom_items ADD COLUMN art_pending INTEGER");
|
||||
}
|
||||
};
|
||||
|
||||
const load = () => {
|
||||
db().exec(SCHEMA);
|
||||
addOwnerColumn();
|
||||
for (const row of db().prepare("SELECT * FROM custom_items ORDER BY rowid").all()) {
|
||||
const entry = {...fromRow(row), seq: made++};
|
||||
if (!baseDef(entry.kind, entry.base)) {
|
||||
console.log(`[custom items] ${entry.kind} ${entry.id} is made from ${entry.base}, which is not in the packs; left out`);
|
||||
console.log(`[custom items] ${logText(entry.kind)} ${logText(entry.id)} is made from ${logText(entry.base)}, which is not in the packs; left out`);
|
||||
continue;
|
||||
}
|
||||
items.get(entry.kind).set(entry.id, entry);
|
||||
apply(entry);
|
||||
if (!entry.pending) {
|
||||
apply(entry);
|
||||
}
|
||||
}
|
||||
console.log(`[custom items] ${items.get("clothing").size} clothing, ${items.get("den").size} den items`);
|
||||
console.log(`[custom items] ${logText(items.get("clothing").size)} clothing, ${logText(items.get("den").size)} den items`);
|
||||
};
|
||||
|
||||
// checks what staff typed. returns {error} or the cleaned values.
|
||||
@@ -149,8 +187,10 @@ const clean = (kind, fields, current = null) => {
|
||||
};
|
||||
|
||||
// makes an item from `base`, an existing clothing piece or den item.
|
||||
// `ownerId`: the player who made it (lib/playeritems.js), or null for staff.
|
||||
// `pending`: it waits for a moderator (approve), out of the game till then.
|
||||
// returns {item} or {error}.
|
||||
const create = (kind, fields, by) => {
|
||||
const create = (kind, fields, by, ownerId = null, pending = false) => {
|
||||
if (!KINDS.includes(kind)) {
|
||||
return {error: "The kind is clothing or den."};
|
||||
}
|
||||
@@ -173,12 +213,15 @@ const create = (kind, fields, by) => {
|
||||
return values;
|
||||
}
|
||||
const id = Math.max(FIRST_ID - 1, ...items.get(kind).keys()) + 1;
|
||||
const entry = {kind, id, base: baseId, colors: [], ...values, createdBy: String(by), createdAt: now(), seq: made++};
|
||||
db().prepare("INSERT INTO custom_items (kind, id, base, name, cost, members, colors, in_shop, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
|
||||
.run(kind, id, baseId, entry.name, entry.cost, entry.members ? 1 : 0, entry.colors.join(","), entry.inShop ? 1 : 0, entry.createdBy, entry.createdAt);
|
||||
const entry = {kind, id, base: baseId, colors: [], ...values, createdBy: String(by), createdAt: now(), ownerId, artMode: "sticker", pending, artPending: false,
|
||||
seq: made++};
|
||||
db().prepare("INSERT INTO custom_items (kind, id, base, name, cost, members, colors, in_shop, created_by, created_at, owner_id, pending) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
|
||||
.run(kind, id, baseId, entry.name, entry.cost, entry.members ? 1 : 0, entry.colors.join(","), entry.inShop ? 1 : 0, entry.createdBy, entry.createdAt, ownerId, pending ? 1 : 0);
|
||||
items.get(kind).set(id, entry);
|
||||
apply(entry);
|
||||
announce(entry);
|
||||
if (!pending) {
|
||||
apply(entry);
|
||||
announce(entry);
|
||||
}
|
||||
return {item: entry};
|
||||
};
|
||||
|
||||
@@ -195,8 +238,72 @@ const update = (kind, id, fields) => {
|
||||
Object.assign(entry, values);
|
||||
db().prepare("UPDATE custom_items SET name = ?, cost = ?, members = ?, colors = ?, in_shop = ? WHERE kind = ? AND id = ?")
|
||||
.run(entry.name, entry.cost, entry.members ? 1 : 0, entry.colors.join(","), entry.inShop ? 1 : 0, kind, entry.id);
|
||||
if (!entry.pending) {
|
||||
apply(entry);
|
||||
announce(entry);
|
||||
}
|
||||
return {item: entry};
|
||||
};
|
||||
|
||||
// how a clothing item with a picture of its own is worn: "sticker" (the
|
||||
// picture where the item would be) or "texture" (the item's shape, painted
|
||||
// with the picture). the patched client draws it (LayerBitmap.paintLayer).
|
||||
const LOOKS = ["sticker", "texture"];
|
||||
|
||||
// returns {item} or {error}; every game is told.
|
||||
const setArtMode = (kind, id, mode) => {
|
||||
const entry = items.has(kind) && items.get(kind).get(Number(id));
|
||||
if (!entry) {
|
||||
return {error: "No such custom item."};
|
||||
}
|
||||
if (!LOOKS.includes(mode)) {
|
||||
return {error: "The look is sticker or texture."};
|
||||
}
|
||||
entry.artMode = mode;
|
||||
db().prepare("UPDATE custom_items SET art_mode = ? WHERE kind = ? AND id = ?").run(mode, kind, entry.id);
|
||||
announce(entry);
|
||||
return {item: entry};
|
||||
};
|
||||
|
||||
// its picture's version (lib/itemart.js), or null for none; every game is told.
|
||||
// `pending`: the picture waits for a moderator, and is not shown till then.
|
||||
const setArt = (kind, id, art, pending = false) => {
|
||||
const entry = items.has(kind) && items.get(kind).get(Number(id));
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
entry.art = art || null;
|
||||
entry.artPending = Boolean(art && pending);
|
||||
db().prepare("UPDATE custom_items SET art = ?, art_pending = ? WHERE kind = ? AND id = ?").run(entry.art, entry.artPending ? 1 : 0, kind, entry.id);
|
||||
announce(entry);
|
||||
};
|
||||
|
||||
// a moderator lets an item, or its picture, in (lib/playeritems.js approve).
|
||||
// returns the entry, or null when there was nothing waiting.
|
||||
const approve = (kind, id) => {
|
||||
const entry = items.has(kind) && items.get(kind).get(Number(id));
|
||||
if (!entry || (!entry.pending && !entry.artPending)) {
|
||||
return null;
|
||||
}
|
||||
entry.pending = false;
|
||||
entry.artPending = false;
|
||||
db().prepare("UPDATE custom_items SET pending = 0, art_pending = 0 WHERE kind = ? AND id = ?").run(kind, entry.id);
|
||||
apply(entry);
|
||||
announce(entry);
|
||||
return entry;
|
||||
};
|
||||
|
||||
// deletes it from the tables (games playing keep its def row, which nothing
|
||||
// uses now). taking it from the players who have it is the caller's.
|
||||
// returns {item} or {error}.
|
||||
const remove = (kind, id) => {
|
||||
const entry = items.has(kind) && items.get(kind).get(Number(id));
|
||||
if (!entry) {
|
||||
return {error: "No such custom item."};
|
||||
}
|
||||
db().prepare("DELETE FROM custom_items WHERE kind = ? AND id = ?").run(kind, entry.id);
|
||||
items.get(kind).delete(entry.id);
|
||||
defpacks.unsetCustomItem(kind, entry.id);
|
||||
return {item: entry};
|
||||
};
|
||||
|
||||
@@ -209,8 +316,27 @@ module.exports = {
|
||||
load,
|
||||
create,
|
||||
update,
|
||||
remove,
|
||||
setArt,
|
||||
setArtMode,
|
||||
approve,
|
||||
// what waits for a moderator: items, and pictures, the oldest first
|
||||
waiting: () => list().filter(entry => entry.pending || entry.artPending).reverse(),
|
||||
LOOKS,
|
||||
list,
|
||||
get: (kind, id) => (items.has(kind) && items.get(kind).get(Number(id))) || null,
|
||||
// the account id of the player who made an item, or null (staff's, or
|
||||
// one of the game's own).
|
||||
ownerOf: (kind, id) => {
|
||||
const entry = items.has(kind) && items.get(kind).get(Number(id));
|
||||
return entry ? entry.ownerId : null;
|
||||
},
|
||||
// can this base be made into an item? (the checks of create, for a list
|
||||
// to offer only those.)
|
||||
copyable: (kind, id) => {
|
||||
const def = baseDef(kind, id);
|
||||
return Boolean(def) && Number(id) < FIRST_ID && (kind === "clothing" ? def.type === TYPE_CLOTHING : OFFERED_SPECIAL_TYPES.includes(def.specialType));
|
||||
},
|
||||
// the base an item's art is from, for a list showing what each is.
|
||||
baseName: entry => {
|
||||
const def = baseDef(entry.kind, entry.base);
|
||||
@@ -218,7 +344,7 @@ module.exports = {
|
||||
},
|
||||
// every custom item, for a game logging in.
|
||||
sendAll(session) {
|
||||
for (const params of messages(list().reverse())) {
|
||||
for (const params of messages(list().reverse().filter(entry => !entry.pending))) {
|
||||
session.sendXt("xdi", -1, ...params);
|
||||
}
|
||||
},
|
||||
|
||||
+26
-2
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const zlib = require("zlib");
|
||||
const amf3 = require("./amf3.js");
|
||||
const cdn = require("./cdn.js");
|
||||
@@ -401,7 +402,7 @@ const loadOptional = async id => {
|
||||
return await load(id);
|
||||
}
|
||||
catch (err) {
|
||||
console.log(`[defs] ${err.message}; the feature that uses it is off`);
|
||||
console.log(`[defs] ${logText(err.message)}; the feature that uses it is off`);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
@@ -471,7 +472,7 @@ const init = async () => {
|
||||
isGame: def.isGame === "1",
|
||||
}];
|
||||
}));
|
||||
console.log(`[defs] ${avatarDefs.size} avatars, ${roomDefsByPath.size} rooms, ${clothingIds.length} clothing items, ${denItemIds.length} den items, ${petIds.length} pets`);
|
||||
console.log(`[defs] ${logText(avatarDefs.size)} avatars, ${logText(roomDefsByPath.size)} rooms, ${logText(clothingIds.length)} clothing items, ${logText(denItemIds.length)} den items, ${logText(petIds.length)} pets`);
|
||||
};
|
||||
|
||||
// puts a custom item (lib/customitems.js) in, or changes one already in:
|
||||
@@ -504,9 +505,32 @@ const setCustomItem = (kind, row, name, inShop = true) => {
|
||||
customVersion++;
|
||||
};
|
||||
|
||||
// a custom item deleted (lib/customitems.js): out of the tables and the
|
||||
// packs new games fetch. its name stays under its string id, unused.
|
||||
const unsetCustomItem = (kind, id) => {
|
||||
const pack = kind === "den" ? DEF_DEN_ITEM : DEF_ITEM;
|
||||
const number = Number(id);
|
||||
customRows.get(pack).delete(number);
|
||||
if (packs.has(pack)) {
|
||||
packs.set(pack, packs.get(pack).filter(def => Number(def.id) !== number));
|
||||
}
|
||||
if (kind === "den") {
|
||||
denItemDefs.delete(number);
|
||||
denItemIds = denItemIds.filter(one => one !== number);
|
||||
}
|
||||
else {
|
||||
itemDefs.delete(number);
|
||||
clothingIds = clothingIds.filter(one => one !== number);
|
||||
}
|
||||
customInShop[kind].delete(number);
|
||||
clientPackBodies.delete(pack);
|
||||
customVersion++;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
init,
|
||||
setCustomItem,
|
||||
unsetCustomItem,
|
||||
// the custom items on sale, the newest first.
|
||||
customShopIds: kind => [...customInShop[kind]].reverse(),
|
||||
customVersion: () => customVersion,
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const accounts = require("./accounts.js");
|
||||
const achievements = require("./achievements.js");
|
||||
const config = require("../config.js");
|
||||
@@ -260,7 +261,7 @@ const handlers = ({others, findOnline}) => {
|
||||
const item = giveDenItem(account, masterpieces.DEN_ITEM, frame);
|
||||
item.image = String(paintingId);
|
||||
accounts.save(account);
|
||||
console.log(`[world] ${account.username} made masterpiece ${item.image}${masterpieces.itemApproved(item) ? "" : " (waiting for review in the admin panel)"}`);
|
||||
console.log(`[world] ${logText(account.username)} made masterpiece ${logText(item.image)}${logText(masterpieces.itemApproved(item) ? "" : " (waiting for review in the admin panel)")}`);
|
||||
session.sendXt("db", -1, 1, account.currency.diamonds || 0, 0, CURRENCY_DIAMONDS, item.inv);
|
||||
sendDenItems(session);
|
||||
};
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
@@ -188,7 +189,7 @@ const alert = (account, kind, detail) => {
|
||||
return;
|
||||
}
|
||||
db().prepare("INSERT INTO device_alerts (at, account_id, username, kind, detail) VALUES (?, ?, ?, ?, ?)").run(now(), account.id, account.username, kind, detail);
|
||||
console.log(`[devices] ${account.username}: ${kind} (${detail})`);
|
||||
console.log(`[devices] ${logText(account.username)}: ${logText(kind)} (${logText(detail)})`);
|
||||
};
|
||||
|
||||
// an account signed in from this computer: its ids are kept, and what looks
|
||||
|
||||
+7
-2
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const accounts = require("./accounts.js");
|
||||
@@ -97,7 +98,11 @@ module.exports = ({findOnline, blocks}) => {
|
||||
0, // secondary type
|
||||
senderType,
|
||||
USERNAME_SHOWN,
|
||||
"", // additional gift data
|
||||
// additional gift data: for clothing, "item|<def id>", so that the
|
||||
// patched client (ECardInbox) can show a custom item as itself (its
|
||||
// own picture and name) and not as the art it was made from. (the
|
||||
// "|" keeps the game from taking it for an HQ gift's own message.)
|
||||
card.gift && card.gift.type === TYPE_CLOTHING ? `item|${card.gift.def}` : "",
|
||||
card.secret ? SECRET_VALENTINE : 0,
|
||||
];
|
||||
};
|
||||
@@ -261,7 +266,7 @@ module.exports = ({findOnline, blocks}) => {
|
||||
const rule = chatFilter.broken(clean(message || ""));
|
||||
if (rule) {
|
||||
chatFilter.warn(session);
|
||||
console.log(`[filter] ${account.username} in a Jam-a-Gram to ${to.username}: "${clean(message || "")}" (${rule})`);
|
||||
console.log(`[filter] ${logText(account.username)} in a Jam-a-Gram to ${logText(to.username)}: "${logText(clean(message || ""))}" (${logText(rule)})`);
|
||||
chatlog.recordTo(account, chatlog.JAMAGRAM, to.username, chatlog.NOT_SENT + clean(message || ""));
|
||||
reply(FAILED);
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const config = require("../config.js");
|
||||
const {logText} = require("./logtext.js");
|
||||
|
||||
// pictures of emoji, for the patched client's chat bubbles (gui.ChatBalloon):
|
||||
// the game's font has none, so an emoji typed in chat (with Windows' emoji
|
||||
// panel, say) is drawn as one of these. they are Twemoji's (CC-BY 4.0,
|
||||
// https://github.com/jdecked/twemoji), asked of config.emojiUpstream once
|
||||
// each and kept in data/emoji. a name is the emoji's code points in hex,
|
||||
// joined by "-", as Twemoji names its files ("1f600", "1f468-200d-1f469").
|
||||
|
||||
const NAME = /^[0-9a-f]{2,6}(?:-[0-9a-f]{2,6}){0,9}$/;
|
||||
const MAX_BYTES = 64 * 1024;
|
||||
const MAX_MISSING = 5000;
|
||||
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
|
||||
const DIR = path.join(config.dataDir, "emoji");
|
||||
|
||||
const missing = new Set(); // names the upstream does not have
|
||||
const pending = new Map(); // name -> promise, so that one is asked for once
|
||||
|
||||
const isName = name => typeof name === "string" && NAME.test(name);
|
||||
|
||||
const fileOf = name => path.join(DIR, `${name}.png`);
|
||||
|
||||
const fetchUpstream = async name => {
|
||||
const res = await fetch(`${config.emojiUpstream}${name}.png`, {signal: AbortSignal.timeout(config.upstreamTimeoutMs)});
|
||||
if (!res.ok) {
|
||||
if (res.status === 404 || res.status === 403) {
|
||||
if (missing.size >= MAX_MISSING) {
|
||||
missing.clear();
|
||||
}
|
||||
missing.add(name);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const body = Buffer.from(await res.arrayBuffer());
|
||||
// a PNG, and a small one, or nothing is kept
|
||||
if (body.length > MAX_BYTES || !body.subarray(0, 8).equals(PNG_SIGNATURE)) {
|
||||
console.log(`[emoji] not a picture: ${logText(name)}`);
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
fs.mkdirSync(DIR, {recursive: true});
|
||||
const tmp = `${fileOf(name)}.${process.pid}.tmp`;
|
||||
fs.writeFileSync(tmp, body);
|
||||
fs.renameSync(tmp, fileOf(name));
|
||||
}
|
||||
catch (err) {
|
||||
console.log(`[emoji] could not keep ${logText(name)}: ${logText(err.message)}`);
|
||||
}
|
||||
return body;
|
||||
};
|
||||
|
||||
// the picture for `name`: a Buffer, or null. `mayFetch()`: whether one not
|
||||
// kept yet may be asked of the upstream for this request (asked only then).
|
||||
const get = async (name, mayFetch) => {
|
||||
if (!isName(name) || missing.has(name)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return await fs.promises.readFile(fileOf(name));
|
||||
}
|
||||
catch (err) {
|
||||
if (err.code !== "ENOENT") {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (!mayFetch()) {
|
||||
return null;
|
||||
}
|
||||
if (!pending.has(name)) {
|
||||
pending.set(name, fetchUpstream(name).catch(() => null).finally(() => pending.delete(name)));
|
||||
}
|
||||
return pending.get(name);
|
||||
};
|
||||
|
||||
module.exports = {get, isName};
|
||||
+191
-23
@@ -1,11 +1,17 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const http = require("http");
|
||||
const https = require("https");
|
||||
const path = require("path");
|
||||
const accounts = require("./accounts.js");
|
||||
const customItems = require("./customitems.js");
|
||||
const itemArt = require("./itemart.js");
|
||||
const emoji = require("./emoji.js");
|
||||
const modlog = require("./modlog.js");
|
||||
const roles = require("./roles.js");
|
||||
const admin = require("./admin.js");
|
||||
const bans = require("./bans.js");
|
||||
const captcha = require("./captcha.js");
|
||||
@@ -139,6 +145,92 @@ const formParts = (contentType, body) => {
|
||||
return parts;
|
||||
};
|
||||
|
||||
// a custom item's picture set or taken away (?kind=&id=[&remove=1], the
|
||||
// picture as the body): by its maker, or by staff who make items. who asks
|
||||
// is the holder of a game's token (/api/itemart?token=, the client's Item
|
||||
// Maker), or `signedIn` (req) -> account: the account page's or the
|
||||
// moderator panel's session, whose cookies only go to their own paths
|
||||
// (/account/api/itemart, /mod/api/itemart), from this server's own pages.
|
||||
// every answer is 200, with {ok} or {error}: the game's Flash cannot read
|
||||
// the body of any other.
|
||||
// `adminSignedIn` (req) -> boolean: the admin panel's session, which acts as
|
||||
// staff who make items, and is written down as "admin".
|
||||
const itemArtUpload = async (req, res, url, from, signedIn = null, adminSignedIn = null) => {
|
||||
if ((req.method === "GET" || req.method === "HEAD") && (signedIn || adminSignedIn)) {
|
||||
itemArtView(req, res, url, signedIn, adminSignedIn);
|
||||
return;
|
||||
}
|
||||
if (req.method !== "POST" || !limits.originAllowed(req)) {
|
||||
send(res, 200, {error: "forbidden"});
|
||||
return;
|
||||
}
|
||||
const token = url.searchParams.get("token");
|
||||
const holder = token ? accounts.byToken(token) : null;
|
||||
const asAdmin = Boolean(adminSignedIn && adminSignedIn(req));
|
||||
const account = asAdmin ? null : signedIn ? signedIn(req) : holder && world.moderation.banRemaining(holder) === 0 ? holder : null;
|
||||
if (!account && !asAdmin) {
|
||||
send(res, 200, {error: "Sign in first."});
|
||||
return;
|
||||
}
|
||||
const kind = url.searchParams.get("kind");
|
||||
const entry = customItems.get(kind, url.searchParams.get("id"));
|
||||
if (!entry) {
|
||||
send(res, 200, {error: "No such custom item."});
|
||||
return;
|
||||
}
|
||||
const staffMay = asAdmin || roles.can(account, "items.create");
|
||||
if (!staffMay && entry.ownerId !== account.id) {
|
||||
send(res, 200, {error: "That is not one of your items."});
|
||||
return;
|
||||
}
|
||||
const playerItems = require("./playeritems.js");
|
||||
const refusal = staffMay || url.searchParams.get("remove") === "1" ? null : playerItems.uploadRefusal(account, from.local);
|
||||
if (refusal) {
|
||||
send(res, 200, refusal);
|
||||
return;
|
||||
}
|
||||
if (!from.local && !asAdmin && !artUploads.allow(account.id)) {
|
||||
send(res, 200, {error: "Too many pictures today. Try again tomorrow."});
|
||||
return;
|
||||
}
|
||||
let result;
|
||||
if (url.searchParams.get("remove") === "1") {
|
||||
result = itemArt.remove(kind, entry.id);
|
||||
}
|
||||
else {
|
||||
const data = await readBody(req, itemArt.MAX_UPLOAD + 1).catch(() => null);
|
||||
// a player's own picture waits for a moderator unless the admin says not;
|
||||
// one turned away before may not come back.
|
||||
const waits = !staffMay && playerItems.pictureWaits();
|
||||
result = data ? await itemArt.set(kind, entry.id, data, waits, staffMay ? null : playerItems.pictureRefused)
|
||||
: {error: `That picture is too big: ${Math.round(itemArt.MAX_UPLOAD / 1024 / 1024)} MB at most.`};
|
||||
}
|
||||
if (result.ok) {
|
||||
const owner = entry.ownerId === null ? null : accounts.byId(entry.ownerId);
|
||||
modlog.record(asAdmin ? "admin" : account.username, url.searchParams.get("remove") === "1" ? "item picture removed" : "item picture set",
|
||||
owner && owner !== account ? owner.username : "", `${kind} ${entry.id} ${entry.name}`);
|
||||
}
|
||||
send(res, 200, result);
|
||||
};
|
||||
|
||||
// a picture still waiting for a moderator, which /itemart/ does not serve:
|
||||
// to its maker (the account page) and to staff who review or make items.
|
||||
const itemArtView = (req, res, url, signedIn, adminSignedIn) => {
|
||||
res.setHeader("Cache-Control", "private, no-store");
|
||||
const asAdmin = Boolean(adminSignedIn && adminSignedIn(req));
|
||||
const account = asAdmin ? null : signedIn ? signedIn(req) : null;
|
||||
const entry = customItems.get(url.searchParams.get("kind"), url.searchParams.get("id"));
|
||||
const allowed = entry && (asAdmin || (account && (entry.ownerId === account.id || roles.can(account, "items.approve") || roles.can(account, "items.create"))));
|
||||
const picture = allowed ? itemArt.file(entry.kind, entry.id, true) : null;
|
||||
if (!picture) {
|
||||
send(res, 404, "Not found", "text/plain");
|
||||
return;
|
||||
}
|
||||
res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox");
|
||||
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||
send(res, 200, picture.data, `image/${picture.type}`);
|
||||
};
|
||||
|
||||
const send = (res, status, body, type = "application/json") => {
|
||||
const data = Buffer.isBuffer(body) ? body : Buffer.from(typeof body === "string" ? body : JSON.stringify(body));
|
||||
res.writeHead(status, {"Content-Type": type, "Content-Length": data.length});
|
||||
@@ -156,6 +248,8 @@ const MISSING_ASSET_SECONDS = 600; // how long a client may keep the CDN's "no s
|
||||
const cacheMisses = limits.limiter(config.cacheMissesPerTenMinutes, TEN_MINUTES_MS); // files fetched from the official CDN for one address
|
||||
const errorReports = limits.limiter(config.errorReportsPerMinute, 60000);
|
||||
const paintingPosts = limits.limiter(60, TEN_MINUTES_MS); // per address; each also needs a token from the game
|
||||
const artUploads = limits.limiter(10, 24 * 3600000); // custom items' pictures, per account a day
|
||||
const emojiFetches = limits.limiter(600, TEN_MINUTES_MS); // emoji pictures not kept yet, asked of the upstream, per address
|
||||
const PAINTING_PATH = /^\/masterpieces\/([0-9a-f-]{36})$/;
|
||||
|
||||
// where clients ask for the HUD artwork; ours is a changed copy.
|
||||
@@ -372,7 +466,7 @@ const renameAndSignIn = (res, body, from) => {
|
||||
manage.forget(account);
|
||||
accounts.recordLogin(account, "launcher", from.address);
|
||||
accounts.save(account);
|
||||
console.log(`[accounts] a rejected username was replaced by "${account.username}"`);
|
||||
console.log(`[accounts] a rejected username was replaced by "${logText(account.username)}"`);
|
||||
accounts.setLoginChoices(account, body.login_choices);
|
||||
const token = accounts.issueToken(account);
|
||||
send(res, 200, {auth_token: token, refresh_token: token, device_token: entry.deviceToken});
|
||||
@@ -392,36 +486,57 @@ const authenticate = async (req, res, from) => {
|
||||
send(res, 426, {error_code: 101, error: "client_outdated"});
|
||||
return;
|
||||
}
|
||||
const byRefresh = body.refresh_token !== undefined;
|
||||
const accountKey = String(body.username).trim().toLowerCase();
|
||||
if (!from.local && failuresByAddress.blocked(from.key)) {
|
||||
send(res, 429, {error_code: 429, error: "too_many_attempts"});
|
||||
return;
|
||||
}
|
||||
// A saved sign-in ("remember me"): the account its token is good for,
|
||||
// which is what the rest goes by. a token is only ever given after a
|
||||
// whole sign-in (password, captcha and 2FA code), so one that is good
|
||||
// stands in for them; one that is not is refused here, whatever else
|
||||
// the request says. (Whether the request offers a token is not what
|
||||
// decides: only the server's own answer for it.)
|
||||
if (body.refresh_token !== undefined) {
|
||||
const saved = accounts.byToken(body.refresh_token);
|
||||
if (!saved) {
|
||||
failuresByAddress.record(from.key);
|
||||
// error_code 100 = expired refresh token
|
||||
send(res, 401, {error_code: 100});
|
||||
return;
|
||||
}
|
||||
await signInChecked(res, body, from, saved, true, device);
|
||||
return;
|
||||
}
|
||||
// a password is not looked at before the captcha. the custom client
|
||||
// knows these errors; the official launcher shows them as a wrong password.
|
||||
const captchaProblem = byRefresh ? null : await captcha.check(body, from, "login", accounts.byName(accountKey));
|
||||
const captchaProblem = await captcha.check(body, from, "login", accounts.byName(accountKey));
|
||||
if (captchaProblem) {
|
||||
send(res, captchaProblem === "captcha_unavailable" ? 503 : 401, {error_code: 101, error: captchaProblem});
|
||||
return;
|
||||
}
|
||||
const account = byRefresh
|
||||
? accounts.byToken(body.refresh_token)
|
||||
: await accounts.authenticateAsync(body.username, body.password);
|
||||
const account = await accounts.authenticateAsync(body.username, body.password);
|
||||
if (!account) {
|
||||
failuresByAddress.record(from.key);
|
||||
if (!byRefresh) {
|
||||
// A wrong password shows in the account's own login history.
|
||||
const tried = accounts.byName(accountKey);
|
||||
if (tried) {
|
||||
accounts.recordLogin(tried, "launcher", from.address, false);
|
||||
accounts.save(tried);
|
||||
}
|
||||
// A wrong password shows in the account's own login history.
|
||||
const tried = accounts.byName(accountKey);
|
||||
if (tried) {
|
||||
accounts.recordLogin(tried, "launcher", from.address, false);
|
||||
accounts.save(tried);
|
||||
}
|
||||
// error_code 100 = expired refresh token, 101 = wrong credentials
|
||||
send(res, 401, {error_code: byRefresh ? 100 : 101});
|
||||
// error_code 101 = wrong credentials
|
||||
send(res, 401, {error_code: 101});
|
||||
return;
|
||||
}
|
||||
await signInChecked(res, body, from, account, false, device);
|
||||
};
|
||||
|
||||
// the rest of a sign-in, for an account whose password was right (`saved`
|
||||
// false) or whose saved sign-in's token was good (`saved` true; then it is
|
||||
// not asked for a 2FA code again, and the token it has is the one it keeps).
|
||||
// `device`: the computer it is on (lib/devices.js), or null for a client that does not say.
|
||||
const signInChecked = async (res, body, from, account, saved, device) => {
|
||||
const byRefresh = saved === true;
|
||||
// banned: said here, with how long is left (-1 for good), where a client
|
||||
// can show it. the game itself would only be refused at its socket with
|
||||
// the one line it has for that, which says neither. the password (or the
|
||||
@@ -444,7 +559,7 @@ const authenticate = async (req, res, from) => {
|
||||
// account was seen on.
|
||||
const deviceBan = device ? devices.banOf(device) : devices.banOfAccount(account);
|
||||
if (deviceBan) {
|
||||
console.log(`[devices] "${account.username}" refused: hardware banned (ban ${deviceBan.id})`);
|
||||
console.log(`[devices] "${logText(account.username)}" refused: hardware banned (ban ${logText(deviceBan.id)})`);
|
||||
send(res, 401, {error_code: 101, error: "device_banned", banned_seconds: world.moderation.PERMANENT, ban_reason: deviceBan.reason});
|
||||
return;
|
||||
}
|
||||
@@ -514,6 +629,10 @@ const player = (req, res) => {
|
||||
};
|
||||
|
||||
const handle = async (req, res) => {
|
||||
// over https, browsers are told to keep to it (a year)
|
||||
if (config.secureCookies) {
|
||||
res.setHeader("Strict-Transport-Security", "max-age=31536000");
|
||||
}
|
||||
const url = new URL(req.url, config.baseUrl);
|
||||
const route = `${req.method} ${url.pathname}`;
|
||||
|
||||
@@ -553,10 +672,20 @@ const handle = async (req, res) => {
|
||||
send(res, 404, "Not found", "text/plain");
|
||||
return;
|
||||
}
|
||||
if (url.pathname === "/admin/api/itemart") {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
await itemArtUpload(req, res, url, from, null, panel.signedIn);
|
||||
return;
|
||||
}
|
||||
await panel.handle(req, res, url, from, {send, readJson});
|
||||
return;
|
||||
}
|
||||
|
||||
if (isAccount && url.pathname === "/account/api/itemart") {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
await itemArtUpload(req, res, url, from, manage.signedInAs);
|
||||
return;
|
||||
}
|
||||
if (isAccount) {
|
||||
await manage.handle(req, res, url, from, {send, readJson});
|
||||
return;
|
||||
@@ -564,6 +693,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 (isMod && url.pathname === "/mod/api/itemart") {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
await itemArtUpload(req, res, url, from, modpanel.signedInAs);
|
||||
return;
|
||||
}
|
||||
if (isMod) {
|
||||
await modpanel.handle(req, res, url, from, {send, readJson});
|
||||
return;
|
||||
@@ -589,6 +723,39 @@ const handle = async (req, res) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// custom items' own pictures (lib/itemart.js): served as the picture
|
||||
// they are and nothing else.
|
||||
const artPath = /^\/itemart\/(clothing|den)\/(\d{1,9})\.png$/.exec(url.pathname);
|
||||
if (artPath && (req.method === "GET" || req.method === "HEAD")) {
|
||||
const picture = itemArt.file(artPath[1], artPath[2]);
|
||||
if (!picture) {
|
||||
send(res, 404, "Not found", "text/plain");
|
||||
return;
|
||||
}
|
||||
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
||||
res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox");
|
||||
res.setHeader("Content-Disposition", "inline");
|
||||
send(res, 200, picture.data, `image/${picture.type}`);
|
||||
return;
|
||||
}
|
||||
// emoji pictures for chat bubbles (lib/emoji.js)
|
||||
const emojiPath = /^\/emoji\/([0-9a-f-]{2,80})\.png$/.exec(url.pathname);
|
||||
if (emojiPath && (req.method === "GET" || req.method === "HEAD")) {
|
||||
const picture = await emoji.get(emojiPath[1], () => from.local || emojiFetches.allow(from.key));
|
||||
if (!picture) {
|
||||
send(res, 404, "Not found", "text/plain");
|
||||
return;
|
||||
}
|
||||
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
||||
res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox");
|
||||
send(res, 200, picture, "image/png");
|
||||
return;
|
||||
}
|
||||
if (url.pathname === "/api/itemart") {
|
||||
await itemArtUpload(req, res, url, from);
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith("/api/")) {
|
||||
// the item finder's API changes accounts, so other sites open in a
|
||||
// browser on this machine must not be able to call it.
|
||||
@@ -732,7 +899,7 @@ const handle = async (req, res) => {
|
||||
if (trace ? config.logPackets : from.local || errorReports.allow(from.key)) {
|
||||
const again = trace ? "" : repeatedError(`${section} ${message}`);
|
||||
if (again !== null) {
|
||||
console.log(`[${trace ? "client-trace" : "client-error"}] (${section}) ${message}${again}`);
|
||||
console.log(`[${logText(trace ? "client-trace" : "client-error")}] (${logText(section)}) ${logText(message)}${logText(again)}`);
|
||||
if (!trace) {
|
||||
keepClientError(`${new Date().toISOString()} (${section}) ${message}${again}\n`);
|
||||
}
|
||||
@@ -755,7 +922,7 @@ const handle = async (req, res) => {
|
||||
return;
|
||||
}
|
||||
const parts = formParts(req.headers["content-type"], await readBody(req, masterpieces.MAX_IMAGE_BYTES + 16 * 1024));
|
||||
const uuid = masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image"));
|
||||
const uuid = await masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image"));
|
||||
send(res, 200, uuid ? {success: true, uuid} : {success: false});
|
||||
return;
|
||||
}
|
||||
@@ -771,13 +938,13 @@ const handle = async (req, res) => {
|
||||
}
|
||||
|
||||
if (req.method !== "GET" && req.method !== "HEAD") {
|
||||
console.log(`[http] unhandled ${route}`);
|
||||
console.log(`[http] unhandled ${logText(route)}`);
|
||||
send(res, 404, {error: "not_found"});
|
||||
return;
|
||||
}
|
||||
|
||||
if (config.logPackets) {
|
||||
console.log(`[http] GET ${url.pathname}`);
|
||||
console.log(`[http] GET ${logText(url.pathname)}`);
|
||||
}
|
||||
|
||||
// asset SWFs import their fonts from this fixed path next to the game page;
|
||||
@@ -843,7 +1010,7 @@ const handle = async (req, res) => {
|
||||
res.setHeader("Cache-Control", `public, max-age=${MISSING_ASSET_SECONDS}`);
|
||||
}
|
||||
else {
|
||||
console.log(`[http] 404 ${url.pathname}`);
|
||||
console.log(`[http] 404 ${logText(url.pathname)}`);
|
||||
}
|
||||
send(res, 404, "Not found", "text/plain");
|
||||
return;
|
||||
@@ -855,7 +1022,8 @@ const handle = async (req, res) => {
|
||||
const start = () => new Promise((resolve, reject) => {
|
||||
const onRequest = (req, res) => {
|
||||
handle(req, res).catch(err => {
|
||||
console.log(`[http] ${req.method} ${req.url} failed: ${err.message}`);
|
||||
// the path only: a query may hold a login token (the item finder's, the Item Maker's)
|
||||
console.log(`[http] ${logText(req.method)} ${logText(String(req.url).split("?")[0])} failed: ${logText(err.message)}`);
|
||||
if (!res.headersSent) {
|
||||
send(res, 500, {error: "server_error"});
|
||||
}
|
||||
@@ -904,7 +1072,7 @@ const start = () => new Promise((resolve, reject) => {
|
||||
});
|
||||
server.once("error", reject);
|
||||
server.listen(config.httpPort, config.bindAddress, () => {
|
||||
console.log(`[http] listening on ${config.bindAddress}:${config.httpPort}${config.webTls ? " (TLS)" : ""}`);
|
||||
console.log(`[http] listening on ${logText(config.bindAddress)}:${logText(config.httpPort)}${logText(config.webTls ? " (TLS)" : "")}`);
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"use strict";
|
||||
|
||||
const config = require("../config.js");
|
||||
|
||||
// Google Cloud Vision SafeSearch detects adult and racy material. We keep
|
||||
// this dependency-free and use its REST API so deploying the server needs no
|
||||
// service-account files or Google SDK in node_modules.
|
||||
const UNSAFE = new Set(["LIKELY", "VERY_LIKELY"]);
|
||||
const TIMEOUT_MS = 10000;
|
||||
|
||||
// {blocked, error}; `error` deliberately fails closed when the scanner is
|
||||
// enabled: accepting an image while the safety service is unavailable would
|
||||
// make this protection easy to bypass.
|
||||
const scan = async image => {
|
||||
if (!config.googleVision) {
|
||||
return {blocked: false};
|
||||
}
|
||||
if (!Buffer.isBuffer(image) || image.length === 0) {
|
||||
return {blocked: true, error: "That picture could not be checked for safety."};
|
||||
}
|
||||
const abort = new AbortController();
|
||||
const timer = setTimeout(() => abort.abort(), TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetch(config.googleVision.endpoint, {
|
||||
method: "POST",
|
||||
headers: {"Content-Type": "application/json"},
|
||||
signal: abort.signal,
|
||||
body: JSON.stringify({
|
||||
requests: [{image: {content: image.toString("base64")}, features: [{type: "SAFE_SEARCH_DETECTION"}]}],
|
||||
}),
|
||||
});
|
||||
const result = await response.json().catch(() => null);
|
||||
const safeSearch = result && result.responses && result.responses[0] && result.responses[0].safeSearchAnnotation;
|
||||
if (!response.ok || !safeSearch) {
|
||||
console.error(`[image-moderation] Google Vision request failed (${response.status})`);
|
||||
return {blocked: true, error: "Picture safety checking is temporarily unavailable. Please try again."};
|
||||
}
|
||||
if (UNSAFE.has(safeSearch.adult) || UNSAFE.has(safeSearch.racy)) {
|
||||
return {blocked: true, error: "That picture was blocked because it may contain nudity or other NSFW content."};
|
||||
}
|
||||
return {blocked: false};
|
||||
}
|
||||
catch (err) {
|
||||
console.error(`[image-moderation] Google Vision request failed: ${err.message}`);
|
||||
return {blocked: true, error: "Picture safety checking is temporarily unavailable. Please try again."};
|
||||
}
|
||||
finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {scan};
|
||||
+403
@@ -0,0 +1,403 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const zlib = require("zlib");
|
||||
const config = require("../config.js");
|
||||
const customItems = require("./customitems.js");
|
||||
const imageModeration = require("./image-moderation.js");
|
||||
|
||||
// custom items' own pictures: uploaded by the item's maker (or staff), shown
|
||||
// by the patched client in place of the item's icon, and for a den item in
|
||||
// place of the item standing in a den (AJClient.customArtUrl). worn
|
||||
// clothing keeps the art it was made from: that is drawn for every animal
|
||||
// and pose, which one picture cannot be.
|
||||
//
|
||||
// a picture is checked before it is kept: a PNG, a JPEG or a GIF by its own
|
||||
// bytes (whatever it is called), of a sensible size, and kept without what
|
||||
// else such files carry (a photo's EXIF, with where it was taken; PNG text;
|
||||
// GIF comments). a BMP is made a PNG. (the pages and the game turn other
|
||||
// kinds, and pictures too big, into a PNG before they send them.)
|
||||
// kept as data/itemart/<kind>-<id>.<png|jpg|gif>; its version, a hash, is on
|
||||
// the item (customItems.setArt), so a new picture is a new address.
|
||||
|
||||
const MAX_BYTES = 300 * 1024; // a picture kept
|
||||
const MAX_UPLOAD = 2 * 1024 * 1024; // one sent (a BMP is bigger than the PNG it becomes)
|
||||
const MAX_SIDE = 512;
|
||||
const MIN_SIDE = 8;
|
||||
const DIR = path.join(config.dataDir, "itemart");
|
||||
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
|
||||
// the PNG chunks a picture needs; text, times, EXIF and the like are dropped
|
||||
const PNG_KEPT = new Set(["IHDR", "PLTE", "IDAT", "IEND", "tRNS", "gAMA", "cHRM", "sRGB", "iCCP", "sBIT", "pHYs"]);
|
||||
|
||||
const TYPES = ["png", "jpeg", "gif"];
|
||||
const EXTENSION = {png: "png", jpeg: "jpg", gif: "gif"};
|
||||
const VERSION_MARK = {png: "p", jpeg: "j", gif: "g"};
|
||||
|
||||
const fileOf = (kind, id, type) => path.join(DIR, `${kind}-${Number(id)}.${EXTENSION[type]}`);
|
||||
|
||||
// a GIF's blocks, without comments, plain text and any application block but
|
||||
// the one that says it loops; null when it is not a whole GIF. kept animated.
|
||||
const cleanGif = data => {
|
||||
const head = data.toString("latin1", 0, 6);
|
||||
if (data.length < 14 || (head !== "GIF87a" && head !== "GIF89a")) {
|
||||
return null;
|
||||
}
|
||||
const width = data.readUInt16LE(6);
|
||||
const height = data.readUInt16LE(8);
|
||||
const packed = data[10];
|
||||
let at = 13 + (packed & 0x80 ? 3 * (2 << (packed & 7)) : 0);
|
||||
if (at > data.length) {
|
||||
return null;
|
||||
}
|
||||
const kept = [data.subarray(0, at)];
|
||||
// sub-blocks from `from`: where they end (after the 0 that ends them)
|
||||
const subBlocksEnd = from => {
|
||||
let i = from;
|
||||
while (i < data.length && data[i] !== 0) {
|
||||
i += data[i] + 1;
|
||||
}
|
||||
return i < data.length ? i + 1 : -1;
|
||||
};
|
||||
let images = 0;
|
||||
while (at < data.length) {
|
||||
const block = data[at];
|
||||
if (block === 0x3B) {
|
||||
kept.push(data.subarray(at, at + 1));
|
||||
return images ? {data: Buffer.concat(kept), width, height, type: "gif"} : null;
|
||||
}
|
||||
if (block === 0x2C) {
|
||||
if (at + 10 > data.length) {
|
||||
return null;
|
||||
}
|
||||
const local = data[at + 9];
|
||||
const start = at;
|
||||
at += 10 + (local & 0x80 ? 3 * (2 << (local & 7)) : 0) + 1; // the descriptor, its colours, the LZW code size
|
||||
const end = subBlocksEnd(at);
|
||||
if (end === -1) {
|
||||
return null;
|
||||
}
|
||||
kept.push(data.subarray(start, end));
|
||||
at = end;
|
||||
images++;
|
||||
continue;
|
||||
}
|
||||
if (block === 0x21 && at + 2 <= data.length) {
|
||||
const label = data[at + 1];
|
||||
const end = subBlocksEnd(at + 2);
|
||||
if (end === -1) {
|
||||
return null;
|
||||
}
|
||||
const loops = label === 0xFF && data.toString("latin1", at + 3, at + 14) === "NETSCAPE2.0";
|
||||
if (label === 0xF9 || loops) {
|
||||
kept.push(data.subarray(at, end));
|
||||
}
|
||||
at = end;
|
||||
continue;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// a PNG of RGBA pixels (`pixels`, width * height * 4 bytes, rows top down).
|
||||
const CRC_TABLE = Array.from({length: 256}, (unused, n) => {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) {
|
||||
c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1;
|
||||
}
|
||||
return c >>> 0;
|
||||
});
|
||||
const crc32 = buffer => {
|
||||
let c = 0xFFFFFFFF;
|
||||
for (const byte of buffer) {
|
||||
c = CRC_TABLE[(c ^ byte) & 0xFF] ^ (c >>> 8);
|
||||
}
|
||||
return (c ^ 0xFFFFFFFF) >>> 0;
|
||||
};
|
||||
const pngChunk = (type, body) => {
|
||||
const length = Buffer.alloc(4);
|
||||
length.writeUInt32BE(body.length);
|
||||
const typed = Buffer.concat([Buffer.from(type, "latin1"), body]);
|
||||
const crc = Buffer.alloc(4);
|
||||
crc.writeUInt32BE(crc32(typed));
|
||||
return Buffer.concat([length, typed, crc]);
|
||||
};
|
||||
const encodePng = (width, height, pixels) => {
|
||||
const header = Buffer.alloc(13);
|
||||
header.writeUInt32BE(width, 0);
|
||||
header.writeUInt32BE(height, 4);
|
||||
header[8] = 8; // bits a channel
|
||||
header[9] = 6; // RGBA
|
||||
const rows = Buffer.alloc((width * 4 + 1) * height);
|
||||
for (let y = 0; y < height; y++) {
|
||||
pixels.copy(rows, y * (width * 4 + 1) + 1, y * width * 4, (y + 1) * width * 4);
|
||||
}
|
||||
return Buffer.concat([PNG_SIGNATURE, pngChunk("IHDR", header), pngChunk("IDAT", zlib.deflateSync(rows)), pngChunk("IEND", Buffer.alloc(0))]);
|
||||
};
|
||||
|
||||
// RGBA pixels shrunk to fit `side` (each new pixel the mean of those it covers).
|
||||
const shrink = (width, height, pixels, side) => {
|
||||
const scale = Math.min(1, side / width, side / height);
|
||||
if (scale === 1) {
|
||||
return {width, height, pixels};
|
||||
}
|
||||
const w = Math.max(1, Math.round(width * scale));
|
||||
const h = Math.max(1, Math.round(height * scale));
|
||||
const out = Buffer.alloc(w * h * 4);
|
||||
for (let y = 0; y < h; y++) {
|
||||
const y0 = Math.floor(y / scale);
|
||||
const y1 = Math.min(height, Math.max(y0 + 1, Math.floor((y + 1) / scale)));
|
||||
for (let x = 0; x < w; x++) {
|
||||
const x0 = Math.floor(x / scale);
|
||||
const x1 = Math.min(width, Math.max(x0 + 1, Math.floor((x + 1) / scale)));
|
||||
const sum = [0, 0, 0, 0];
|
||||
for (let sy = y0; sy < y1; sy++) {
|
||||
for (let sx = x0; sx < x1; sx++) {
|
||||
for (let c = 0; c < 4; c++) {
|
||||
sum[c] += pixels[(sy * width + sx) * 4 + c];
|
||||
}
|
||||
}
|
||||
}
|
||||
const count = (y1 - y0) * (x1 - x0);
|
||||
for (let c = 0; c < 4; c++) {
|
||||
out[(y * w + x) * 4 + c] = Math.round(sum[c] / count);
|
||||
}
|
||||
}
|
||||
}
|
||||
return {width: w, height: h, pixels: out};
|
||||
};
|
||||
|
||||
// a BMP (uncompressed, or bit fields: 1, 4, 8, 24 or 32 bits a pixel) as a
|
||||
// PNG, shrunk to fit; null when it is not one this can read.
|
||||
const MAX_BMP_SIDE = 4096;
|
||||
const bmpToPng = data => {
|
||||
if (data.length < 54 || data.toString("latin1", 0, 2) !== "BM") {
|
||||
return null;
|
||||
}
|
||||
const offset = data.readUInt32LE(10);
|
||||
const headerSize = data.readUInt32LE(14);
|
||||
if (headerSize < 40) {
|
||||
return null;
|
||||
}
|
||||
const width = data.readInt32LE(18);
|
||||
const rawHeight = data.readInt32LE(22);
|
||||
const height = Math.abs(rawHeight);
|
||||
const bits = data.readUInt16LE(28);
|
||||
const compression = data.readUInt32LE(30);
|
||||
if (width < 1 || height < 1 || width > MAX_BMP_SIDE || height > MAX_BMP_SIDE || ![1, 4, 8, 24, 32].includes(bits) || ![0, 3].includes(compression)) {
|
||||
return null;
|
||||
}
|
||||
const stride = Math.ceil(width * bits / 32) * 4;
|
||||
if (offset + stride * height > data.length) {
|
||||
return null;
|
||||
}
|
||||
const paletteAt = 14 + headerSize;
|
||||
const pixels = Buffer.alloc(width * height * 4);
|
||||
const hasAlpha = bits === 32 && (headerSize >= 56 || compression === 3);
|
||||
for (let y = 0; y < height; y++) {
|
||||
const row = offset + (rawHeight > 0 ? height - 1 - y : y) * stride;
|
||||
for (let x = 0; x < width; x++) {
|
||||
const o = (y * width + x) * 4;
|
||||
let b;
|
||||
let g;
|
||||
let r;
|
||||
let a = 255;
|
||||
if (bits >= 24) {
|
||||
const p = row + x * (bits / 8);
|
||||
[b, g, r] = [data[p], data[p + 1], data[p + 2]];
|
||||
if (hasAlpha) {
|
||||
a = data[p + 3];
|
||||
}
|
||||
}
|
||||
else {
|
||||
const perByte = 8 / bits;
|
||||
const byte = data[row + Math.floor(x / perByte)];
|
||||
const index = (byte >> ((perByte - 1 - (x % perByte)) * bits)) & ((1 << bits) - 1);
|
||||
const entry = paletteAt + index * 4;
|
||||
if (entry + 3 > data.length) {
|
||||
return null;
|
||||
}
|
||||
[b, g, r] = [data[entry], data[entry + 1], data[entry + 2]];
|
||||
}
|
||||
pixels[o] = r;
|
||||
pixels[o + 1] = g;
|
||||
pixels[o + 2] = b;
|
||||
pixels[o + 3] = a;
|
||||
}
|
||||
}
|
||||
const small = shrink(width, height, pixels, MAX_SIDE);
|
||||
return {data: encodePng(small.width, small.height, small.pixels), width: small.width, height: small.height, type: "png"};
|
||||
};
|
||||
|
||||
// a PNG's chunks, without the ones not kept; null when it is not a whole PNG.
|
||||
const cleanPng = data => {
|
||||
if (data.length < 33 || !data.subarray(0, 8).equals(PNG_SIGNATURE)) {
|
||||
return null;
|
||||
}
|
||||
const kept = [PNG_SIGNATURE];
|
||||
let at = 8;
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
let ended = false;
|
||||
while (at + 12 <= data.length) {
|
||||
const length = data.readUInt32BE(at);
|
||||
const type = data.toString("latin1", at + 4, at + 8);
|
||||
if (at + 12 + length > data.length) {
|
||||
return null;
|
||||
}
|
||||
if (type === "IHDR") {
|
||||
width = data.readUInt32BE(at + 8);
|
||||
height = data.readUInt32BE(at + 12);
|
||||
}
|
||||
if (PNG_KEPT.has(type)) {
|
||||
kept.push(data.subarray(at, at + 12 + length));
|
||||
}
|
||||
at += 12 + length;
|
||||
if (type === "IEND") {
|
||||
ended = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return ended && width && height ? {data: Buffer.concat(kept), width, height, type: "png"} : null;
|
||||
};
|
||||
|
||||
// a JPEG without its APP1..APP15 (EXIF, XMP, ...) and comment segments;
|
||||
// null when it is not one. its size is read from the frame header.
|
||||
const cleanJpeg = data => {
|
||||
if (data.length < 4 || data[0] !== 0xFF || data[1] !== 0xD8) {
|
||||
return null;
|
||||
}
|
||||
const kept = [data.subarray(0, 2)];
|
||||
let at = 2;
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
while (at + 4 <= data.length) {
|
||||
if (data[at] !== 0xFF) {
|
||||
return null;
|
||||
}
|
||||
const marker = data[at + 1];
|
||||
if (marker === 0xD9) {
|
||||
kept.push(data.subarray(at, at + 2));
|
||||
break;
|
||||
}
|
||||
const length = data.readUInt16BE(at + 2);
|
||||
if (length < 2 || at + 2 + length > data.length) {
|
||||
return null;
|
||||
}
|
||||
const segment = data.subarray(at, at + 2 + length);
|
||||
// start of frame (not DHT, JPG or DAC): the size
|
||||
if (marker >= 0xC0 && marker <= 0xCF && ![0xC4, 0xC8, 0xCC].includes(marker)) {
|
||||
height = data.readUInt16BE(at + 5);
|
||||
width = data.readUInt16BE(at + 7);
|
||||
}
|
||||
const dropped = (marker >= 0xE1 && marker <= 0xEF) || marker === 0xFE;
|
||||
if (!dropped) {
|
||||
kept.push(segment);
|
||||
}
|
||||
at += 2 + length;
|
||||
// start of scan: the compressed data runs to the end
|
||||
if (marker === 0xDA) {
|
||||
kept.push(data.subarray(at));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return width && height ? {data: Buffer.concat(kept), width, height, type: "jpeg"} : null;
|
||||
};
|
||||
|
||||
// checks and cleans an upload: {data, type} or {error}.
|
||||
const check = data => {
|
||||
if (!Buffer.isBuffer(data) || data.length === 0) {
|
||||
return {error: "Choose a picture first."};
|
||||
}
|
||||
if (data.length > MAX_UPLOAD) {
|
||||
return {error: `That picture is too big: ${Math.round(MAX_UPLOAD / 1024 / 1024)} MB at most.`};
|
||||
}
|
||||
const image = cleanPng(data) || cleanJpeg(data) || cleanGif(data) || bmpToPng(data);
|
||||
if (!image) {
|
||||
return {error: "That is not a PNG, JPEG, GIF or BMP picture."};
|
||||
}
|
||||
if (image.data.length > MAX_BYTES) {
|
||||
return {error: `That picture is too big: ${Math.round(MAX_BYTES / 1024)} KB at most once cleaned. A smaller one, please.`};
|
||||
}
|
||||
if (image.width > MAX_SIDE || image.height > MAX_SIDE || image.width < MIN_SIDE || image.height < MIN_SIDE) {
|
||||
return {error: `A picture from ${MIN_SIDE} to ${MAX_SIDE} pixels on each side, please.`};
|
||||
}
|
||||
return image;
|
||||
};
|
||||
|
||||
const digest = data => crypto.createHash("sha256").update(data).digest("hex");
|
||||
|
||||
// sets an item's picture. resolves to {ok, art} or {error}.
|
||||
// `pending`: it waits for a moderator before anyone is shown it (lib/playeritems.js).
|
||||
// `refused(hash)`: whether a picture of that SHA-256 (once cleaned) was
|
||||
// turned away before, and may not be sent again.
|
||||
const set = async (kind, id, data, pending = false, refused = null) => {
|
||||
const entry = customItems.get(kind, id);
|
||||
if (!entry) {
|
||||
return {error: "No such custom item."};
|
||||
}
|
||||
const image = check(data);
|
||||
if (image.error) {
|
||||
return image;
|
||||
}
|
||||
if (refused && refused(digest(image.data))) {
|
||||
return {error: "A moderator turned that picture away before. Choose another one."};
|
||||
}
|
||||
const safety = await imageModeration.scan(image.data);
|
||||
if (safety.blocked) {
|
||||
return {error: safety.error};
|
||||
}
|
||||
fs.mkdirSync(DIR, {recursive: true});
|
||||
for (const type of TYPES) {
|
||||
fs.rmSync(fileOf(kind, entry.id, type), {force: true});
|
||||
}
|
||||
fs.writeFileSync(fileOf(kind, entry.id, image.type), image.data);
|
||||
const art = `${VERSION_MARK[image.type]}${crypto.createHash("sha256").update(image.data).digest("hex").slice(0, 12)}`;
|
||||
customItems.setArt(kind, entry.id, art, pending);
|
||||
return {ok: pending ? `${entry.name}'s new picture is waiting for a moderator to approve it.` : `${entry.name} has a new picture.`, art};
|
||||
};
|
||||
|
||||
// takes an item's picture away (its maker's choice, or staff's).
|
||||
const remove = (kind, id) => {
|
||||
const entry = customItems.get(kind, id);
|
||||
if (!entry || !entry.art) {
|
||||
return {error: "That item has no picture of its own."};
|
||||
}
|
||||
for (const type of TYPES) {
|
||||
fs.rmSync(fileOf(kind, entry.id, type), {force: true});
|
||||
}
|
||||
customItems.setArt(kind, entry.id, null);
|
||||
return {ok: `${entry.name}'s picture was taken away.`};
|
||||
};
|
||||
|
||||
// the picture to serve: {data, type} or null. one waiting for a moderator
|
||||
// only `withPending`: for the maker and the moderators (lib/http.js).
|
||||
const file = (kind, id, withPending = false) => {
|
||||
const entry = customItems.get(kind, id);
|
||||
if (!entry || !entry.art || (entry.artPending && !withPending)) {
|
||||
return null;
|
||||
}
|
||||
const type = TYPES.find(one => entry.art.startsWith(VERSION_MARK[one])) || "png";
|
||||
try {
|
||||
return {data: fs.readFileSync(fileOf(kind, entry.id, type)), type};
|
||||
}
|
||||
catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// the SHA-256 of an item's picture as kept, waiting or not: null for none.
|
||||
const digestOf = (kind, id) => {
|
||||
const picture = file(kind, id, true);
|
||||
return picture ? digest(picture.data) : null;
|
||||
};
|
||||
|
||||
// where a page shows an item's picture: the public address once anyone may
|
||||
// see it; while it waits, `base` (the page's own /…/api/itemart, which asks
|
||||
// who it is first).
|
||||
const urlOf = (entry, base) => (!entry.art ? null : entry.artPending
|
||||
? `${base}?kind=${entry.kind}&id=${entry.id}&v=${entry.art}` : `/itemart/${entry.kind}/${entry.id}.png?v=${entry.art}`);
|
||||
|
||||
module.exports = {set, remove, file, check, digestOf, urlOf, MAX_BYTES, MAX_UPLOAD};
|
||||
@@ -0,0 +1,141 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const customItems = require("./customitems.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
|
||||
// what staff who make items (items.create: admins and developers) may do
|
||||
// about who has them:
|
||||
//
|
||||
// - lock an item out of the item finder (lib/admin.js): players no longer
|
||||
// find it there or take it from it. staff who may lock still do, with the
|
||||
// item marked locked. it stays wherever else it is (a shop, a trade).
|
||||
// - take an item from one player: every one of it they have.
|
||||
// - delete a custom item (lib/customitems.js): out of the game, and out of
|
||||
// every inventory.
|
||||
|
||||
const LOCKS_SETTING = "finderLocks";
|
||||
const KINDS = ["clothing", "den"];
|
||||
|
||||
let locks = null; // Set of "kind:id"
|
||||
|
||||
const key = (kind, id) => `${kind}:${Number(id)}`;
|
||||
|
||||
const lockSet = () => {
|
||||
if (!locks) {
|
||||
let saved = [];
|
||||
try {
|
||||
saved = JSON.parse(accounts.setting(LOCKS_SETTING) || "[]");
|
||||
}
|
||||
catch {
|
||||
saved = [];
|
||||
}
|
||||
locks = new Set(Array.isArray(saved) ? saved.map(String) : []);
|
||||
}
|
||||
return locks;
|
||||
};
|
||||
|
||||
const saveLocks = () => accounts.setSetting(LOCKS_SETTING, JSON.stringify([...lockSet()]));
|
||||
|
||||
const defOf = (kind, id) => (kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id));
|
||||
|
||||
const nameOf = (kind, id) => {
|
||||
const def = defOf(kind, id);
|
||||
if (!def) {
|
||||
return "";
|
||||
}
|
||||
return kind === "den" ? defpacks.string(def.nameStrId) || def.abbrName || "" : defpacks.string(def.titleStrId);
|
||||
};
|
||||
|
||||
const describe = (kind, id) => `${nameOf(kind, id) || "(no name)"} (${kind === "den" ? "den item" : "clothing"} ${Number(id)})`;
|
||||
|
||||
// checks a kind and id typed by staff: {kind, id} of an item that exists, or {error}.
|
||||
const item = (kind, id) => {
|
||||
const number = Number(id);
|
||||
if (!KINDS.includes(kind)) {
|
||||
return {error: "The kind is clothing or den."};
|
||||
}
|
||||
if (!Number.isInteger(number) || !defOf(kind, number) || (kind === "clothing" && !defpacks.clothingIds().includes(number))) {
|
||||
return {error: `No ${kind === "den" ? "den item" : "clothing"} with the id ${id}.`};
|
||||
}
|
||||
return {kind, id: number};
|
||||
};
|
||||
|
||||
const isLocked = (kind, id) => lockSet().has(key(kind, id));
|
||||
|
||||
// returns {ok} or {error}.
|
||||
const setLocked = (kind, id, locked) => {
|
||||
const found = item(kind, id);
|
||||
if (found.error) {
|
||||
return found;
|
||||
}
|
||||
const was = isLocked(found.kind, found.id);
|
||||
if (was === locked) {
|
||||
return {error: `${describe(found.kind, found.id)} is ${locked ? "already" : "not"} locked.`};
|
||||
}
|
||||
lockSet()[locked ? "add" : "delete"](key(found.kind, found.id));
|
||||
saveLocks();
|
||||
return {ok: `${describe(found.kind, found.id)} is ${locked ? "locked out of" : "back in"} the item finder.`};
|
||||
};
|
||||
|
||||
const lockedList = () => [...lockSet()].map(entry => {
|
||||
const [kind, id] = entry.split(":");
|
||||
return {kind, id: Number(id), name: nameOf(kind, id)};
|
||||
});
|
||||
|
||||
// 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.
|
||||
const takeFromAccount = (account, kind, id, world) => {
|
||||
const number = Number(id);
|
||||
const collection = kind === "den" ? "denItems" : "items";
|
||||
const gone = account[collection].filter(entry => entry.def === number);
|
||||
if (!gone.length) {
|
||||
return 0;
|
||||
}
|
||||
const invs = new Set(gone.map(entry => entry.inv));
|
||||
account[collection] = account[collection].filter(entry => !invs.has(entry.inv));
|
||||
account.tradeList = account.tradeList.filter(entry => !invs.has(entry.inv));
|
||||
accounts.save();
|
||||
world.itemsTaken(account, kind, [...invs], kind === "clothing" && gone.some(entry => entry.on.length > 0));
|
||||
return gone.length;
|
||||
};
|
||||
|
||||
// from one player, by username. returns {ok, count} or {error}.
|
||||
const take = (username, kind, id, world) => {
|
||||
const account = accounts.byName(username);
|
||||
if (!account) {
|
||||
return {error: `No player called ${username}.`};
|
||||
}
|
||||
// a deleted custom item can be gone from the tables and still be owned:
|
||||
// the id is taken as it is then.
|
||||
const found = item(kind, id);
|
||||
if (found.error && !(KINDS.includes(kind) && Number.isInteger(Number(id)))) {
|
||||
return found;
|
||||
}
|
||||
const count = takeFromAccount(account, kind, id, world);
|
||||
return count ? {ok: `Took ${count} of ${describe(kind, id)} from ${account.username}.`, count}
|
||||
: {error: `${account.username} has no ${describe(kind, id)}.`};
|
||||
};
|
||||
|
||||
// a custom item out of the game, and out of everyone's inventory. returns {ok} or {error}.
|
||||
const deleteCustom = (kind, id, world) => {
|
||||
const entry = customItems.get(kind, id);
|
||||
if (!entry) {
|
||||
return {error: "No such custom item."};
|
||||
}
|
||||
let count = 0;
|
||||
for (const account of accounts.all()) {
|
||||
count += takeFromAccount(account, kind, entry.id, world);
|
||||
}
|
||||
if (entry.art) {
|
||||
require("./itemart.js").remove(kind, entry.id);
|
||||
}
|
||||
customItems.remove(kind, entry.id);
|
||||
if (lockSet().delete(key(kind, entry.id))) {
|
||||
saveLocks();
|
||||
}
|
||||
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};
|
||||
@@ -0,0 +1,14 @@
|
||||
"use strict";
|
||||
|
||||
// a value from outside (a username, an address, what a client sent) as it
|
||||
// may go into a line of the server's log: on one line, and with no control
|
||||
// characters, so that it cannot pass for a line of the server's own (a name
|
||||
// with a line break in it, "...\n[admin] signed in") or move the terminal's
|
||||
// cursor about. (U+2028 and U+2029, which end a line too, are in the second.)
|
||||
const OTHER_BREAKS_AND_CONTROLS = new RegExp("[\x00-\x1f\x7f-\x9f\u2028\u2029]", "g");
|
||||
|
||||
const logText = value => String(value)
|
||||
.replace(/[\r\n]+/g, " ")
|
||||
.replace(OTHER_BREAKS_AND_CONTROLS, "?");
|
||||
|
||||
module.exports = {logText};
|
||||
+38
-12
@@ -1,5 +1,9 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const customItems = require("./customitems.js");
|
||||
const itemControl = require("./itemcontrol.js");
|
||||
const playerItems = require("./playeritems.js");
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
@@ -149,6 +153,11 @@ const profile = (account, from) => {
|
||||
animalType: avatar ? avatar.type : null,
|
||||
items: account.items.length,
|
||||
denItems: account.denItems.length,
|
||||
// what they made in the game's Item Maker (lib/playeritems.js)
|
||||
customItems: playerItems.madeBy(account).map(entry => ({kind: entry.kind, id: entry.id, name: entry.name,
|
||||
art: require("./itemart.js").urlOf(entry, "/account/api/itemart"), artWaiting: Boolean(entry.artPending), look: entry.artMode || "sticker"})),
|
||||
picturesStopped: Boolean(account.artBlocked),
|
||||
customItemLimits: {perDay: playerItems.PER_DAY, inAll: playerItems.IN_ALL},
|
||||
pets: account.pets.length,
|
||||
buddies: account.buddies.length,
|
||||
banned: null,
|
||||
@@ -179,7 +188,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"];
|
||||
const SECRET_FIELDS = ["salt", "hash", "totp", "totpSetup", "devices", "modNotes"];
|
||||
const dataOf = account => ({
|
||||
exportedAt: new Date().toISOString(),
|
||||
server: config.baseUrl,
|
||||
@@ -250,7 +259,7 @@ const act = (account, body, req, from, res) => {
|
||||
}
|
||||
delete account.nameRejected;
|
||||
accounts.save(account);
|
||||
console.log(`[account] a rejected username was replaced by "${account.username}" from ${from.address}`);
|
||||
console.log(`[account] a rejected username was replaced by "${logText(account.username)}" from ${logText(from.address)}`);
|
||||
return {ok: "Saved."};
|
||||
}
|
||||
// one for each account, ever: an answer that wants a follow-up says
|
||||
@@ -267,12 +276,14 @@ const act = (account, body, req, from, res) => {
|
||||
if (!passwordAgain(account, body.current)) {
|
||||
return {error: "Wrong password."};
|
||||
}
|
||||
if (accounts.setPassword(account, body.password)) {
|
||||
return {error: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."};
|
||||
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."};
|
||||
}
|
||||
world.moderation.actions.kick(account);
|
||||
signOutOthers(account, req);
|
||||
console.log(`[account] "${account.username}" changed their password from ${from.address}`);
|
||||
console.log(`[account] "${logText(account.username)}" changed their password from ${logText(from.address)}`);
|
||||
return {ok: "Password changed."};
|
||||
}
|
||||
case "requestName": {
|
||||
@@ -293,7 +304,7 @@ const act = (account, body, req, from, res) => {
|
||||
world.moderation.actions.kick(account);
|
||||
}
|
||||
accounts.save(account);
|
||||
console.log(`[account] "${account.username}" ${account.locked ? "locked" : "unlocked"} from ${from.address}`);
|
||||
console.log(`[account] "${logText(account.username)}" ${logText(account.locked ? "locked" : "unlocked")} from ${logText(from.address)}`);
|
||||
return {ok: account.locked ? "Locked." : "Unlocked."};
|
||||
}
|
||||
case "feature": {
|
||||
@@ -322,11 +333,12 @@ const act = (account, body, req, from, res) => {
|
||||
const recovery = totp.confirm(account, body.code);
|
||||
if (!recovery) {
|
||||
accounts.save(account);
|
||||
return {error: "Wrong code."};
|
||||
// confirm() drops a setup older than 15 minutes: no code can match it now.
|
||||
return {error: account.totpSetup ? "Wrong code." : "Setup timed out. Turn 2FA on again and scan the new QR code."};
|
||||
}
|
||||
accounts.revokeTokens(account);
|
||||
accounts.save(account);
|
||||
console.log(`[account] "${account.username}" turned two-step sign-in on from ${from.address}`);
|
||||
console.log(`[account] "${logText(account.username)}" turned two-step sign-in on from ${logText(from.address)}`);
|
||||
return {ok: "2FA is on.", recovery};
|
||||
}
|
||||
// turning it off: the password and a code (or a recovery code).
|
||||
@@ -344,7 +356,7 @@ const act = (account, body, req, from, res) => {
|
||||
totp.turnOff(account);
|
||||
accounts.save(account);
|
||||
res.setHeader("Set-Cookie", cookieHeader("", 0, DEVICE_COOKIE));
|
||||
console.log(`[account] "${account.username}" turned two-step sign-in off from ${from.address}`);
|
||||
console.log(`[account] "${logText(account.username)}" turned two-step sign-in off from ${logText(from.address)}`);
|
||||
return {ok: "2FA is off."};
|
||||
}
|
||||
case "forgetDevices":
|
||||
@@ -352,6 +364,20 @@ const act = (account, body, req, from, res) => {
|
||||
accounts.save(account);
|
||||
return {ok: "Trusted devices forgotten."};
|
||||
// their bio, for the Bio tab of their card in the game. empty takes it off.
|
||||
// their own custom items: a new name, or gone (from everyone who has
|
||||
// one). a picture is sent to /api/itemart.
|
||||
case "itemLook":
|
||||
return playerItems.setLook(account, String(body.kind), body.id, String(body.look));
|
||||
case "itemRename":
|
||||
return playerItems.rename(account, String(body.kind), body.id, body.name);
|
||||
case "itemDelete": {
|
||||
const entry = customItems.get(String(body.kind), body.id);
|
||||
if (!entry || entry.ownerId !== account.id) {
|
||||
return {error: "That is not one of your items."};
|
||||
}
|
||||
const result = itemControl.deleteCustom(entry.kind, entry.id, world);
|
||||
return result.error ? result : {ok: `Deleted ${entry.name}.`};
|
||||
}
|
||||
case "bio": {
|
||||
// typed words others read: not while they cannot chat.
|
||||
if (world.moderation.isSilenced(account)) {
|
||||
@@ -365,7 +391,7 @@ const act = (account, body, req, from, res) => {
|
||||
// each other (lib/chat-filter.txt).
|
||||
const rule = chatFilter.broken(bio);
|
||||
if (rule) {
|
||||
console.log(`[filter] "${account.username}" bio not saved (${rule}): ${JSON.stringify(bio)}`);
|
||||
console.log(`[filter] "${logText(account.username)}" bio not saved (${logText(rule)}): ${logText(JSON.stringify(bio))}`);
|
||||
return {error: "Your bio has words that are not allowed here."};
|
||||
}
|
||||
account.bio = bio;
|
||||
@@ -446,7 +472,7 @@ const act = (account, body, req, from, res) => {
|
||||
world.disconnect(account);
|
||||
signOutOthers(account, null);
|
||||
erase(account);
|
||||
console.log(`[account] "${name}" deleted their account from ${from.address}`);
|
||||
console.log(`[account] "${logText(name)}" deleted their account from ${logText(from.address)}`);
|
||||
return {ok: "Account deleted.", deleted: true};
|
||||
}
|
||||
default:
|
||||
@@ -601,4 +627,4 @@ const handle = async (req, res, url, from, web) => {
|
||||
// called when an account's name changes or it is deleted: its page sessions end.
|
||||
const forget = account => signOutOthers(account, null);
|
||||
|
||||
module.exports = {handle, forget};
|
||||
module.exports = {handle, forget, signedInAs};
|
||||
+8
-2
@@ -6,6 +6,7 @@ const path = require("path");
|
||||
const config = require("../config.js");
|
||||
const accounts = require("./accounts.js");
|
||||
const limits = require("./limits.js");
|
||||
const imageModeration = require("./image-moderation.js");
|
||||
|
||||
// masterpieces: paintings from the Art Studio, framed and hung in a den
|
||||
// (client side: game.artStudioPainting.ArtStudioPainting, the same in
|
||||
@@ -181,16 +182,21 @@ const looksLikeJpeg = image => {
|
||||
return false;
|
||||
};
|
||||
|
||||
// step 2. returns the new painting's id, or null when the token is not
|
||||
// step 2. resolves to the new painting's id, or null when the token is not
|
||||
// good, the picture is not a JPEG of a sane size, or the account has posted
|
||||
// too many.
|
||||
const upload = (token, image) => {
|
||||
const upload = async (token, image) => {
|
||||
const entry = typeof token === "string" ? tokens.get(token) : null;
|
||||
tokens.delete(token);
|
||||
if (!entry || entry.expires < Date.now() || !Buffer.isBuffer(image) || image.length > MAX_IMAGE_BYTES || !looksLikeJpeg(image)
|
||||
|| !uploadsPerHour.allow(entry.account)) {
|
||||
return null;
|
||||
}
|
||||
const safety = await imageModeration.scan(image);
|
||||
if (safety.blocked) {
|
||||
console.log(`[masterpieces] rejected unsafe upload from account ${entry.account}`);
|
||||
return null;
|
||||
}
|
||||
// one painting at a time is between the easel and the frame.
|
||||
for (const painting of [...known.values()]) {
|
||||
if (painting.creator === entry.account && painting.status === UPLOADED) {
|
||||
|
||||
+92
-3
@@ -75,9 +75,27 @@ const messagesPerMinute = limits.limiter(900, 60000);
|
||||
// the "start" message a game waits for once it has said it is ready.
|
||||
const START = {
|
||||
seed: () => [serial()],
|
||||
seedAndPlayers: game => [serial(), game.players.length],
|
||||
// then each player's sfs id and a field the game skips: a game knows
|
||||
// which player is its own by the id (GemBreakerPlayer.init), and only
|
||||
// that one aims and shoots.
|
||||
seedAndPlayers: game => [serial(), game.players.length, ...game.players.flatMap(player => [player.id, 0])],
|
||||
};
|
||||
|
||||
// the room games several players play together: "Multiplayer" on the
|
||||
// game's waiting list (MinigameManager.setupWaitListPopup), for players in
|
||||
// the same room. each client plays the same game from the same start, and
|
||||
// the server passes each player's moves on to the others: `relay` names
|
||||
// the messages passed on, true for those that go with the sender's sfs id
|
||||
// first. a full list starts the game.
|
||||
const MULTIPLAYER = {
|
||||
// GemBreaker.message: "pos" [sfsUserId, cannon angle], "shoot" [the shot's
|
||||
// nine numbers], "playerLost" [the next round's seed]. two players, a
|
||||
// field each, first to win two rounds.
|
||||
GemBreaker: {max: 2, relay: {pos: true, shoot: false, playerLost: false}},
|
||||
};
|
||||
const MAX_RELAYED_FIELDS = 12;
|
||||
const RELAYED_FIELD = /^[-0-9a-zA-Z.]{1,32}$/;
|
||||
|
||||
// serial numbers the client mixes into its award messages; any number will do.
|
||||
function serial() {
|
||||
return 1 + Math.floor(Math.random() * 1000000);
|
||||
@@ -93,7 +111,10 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
||||
defpacks.stringId(game.title) || defpacks.stringId(FALLBACK_TITLE),
|
||||
game.swf, // extName
|
||||
game.swf, // swfName
|
||||
game.buddy ? 2 : 1, game.buddy ? 2 : 1, // min and max players
|
||||
// min and max players: more than one gives the game a waiting list
|
||||
// with "Single Player" and "Multiplayer" (lib/minigames.js MULTIPLAYER).
|
||||
game.buddy ? 2 : MULTIPLAYER[game.swf] ? MULTIPLAYER[game.swf].max : 1,
|
||||
game.buddy ? 2 : MULTIPLAYER[game.swf] ? MULTIPLAYER[game.swf].max : 1,
|
||||
0, // max spectators
|
||||
game.type,
|
||||
// the game card: the title picture on the "play" popup (not known), and
|
||||
@@ -134,6 +155,13 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
||||
}
|
||||
session.game = null;
|
||||
game.players = game.players.filter(player => player !== session);
|
||||
if (game.lobby) {
|
||||
if (game.players.length === 0) {
|
||||
lobbies.delete(game.lobby);
|
||||
}
|
||||
tellLobby(game);
|
||||
return;
|
||||
}
|
||||
// the games' own "player left": [sfsUserId]. A buddy game takes it for
|
||||
// a win, so the one still looking at the result of a game that has been
|
||||
// decided is not told. three of them only the clients know the end of
|
||||
@@ -191,6 +219,59 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
||||
session.sendXt("mj", game.roomId, ...game.players.map(player => player.id));
|
||||
};
|
||||
|
||||
// the waiting lists of multiplayer room games: "<gameDefId> <room>" -> a
|
||||
// game not started yet. one is answered "mj" from the room the players
|
||||
// wait in, with who waits: the client draws them from that room, so they
|
||||
// stay in it till the list is full.
|
||||
const lobbies = new Map();
|
||||
const tellLobby = game => {
|
||||
for (const player of game.players) {
|
||||
player.sendXt("mj", game.waitRoom.id, ...game.players.map(other => other.id));
|
||||
}
|
||||
};
|
||||
const joinLobby = (session, def, multi) => {
|
||||
const key = `${def.id} ${session.room.name}`;
|
||||
let game = lobbies.get(key);
|
||||
if (game && game.players.some(player => blocks.either(player.account, session.account))) {
|
||||
session.sendXt("mj", -1, "as", 0);
|
||||
tell(session, "Someone already waiting for that game is not someone you play with. Try again later.");
|
||||
return;
|
||||
}
|
||||
if (!game) {
|
||||
game = {roomId: nextGameRoomId++, def, multi, players: [], started: false, ready: new Set(), lobby: key, waitRoom: session.room};
|
||||
lobbies.set(key, game);
|
||||
}
|
||||
game.players.push(session);
|
||||
session.game = game;
|
||||
tellLobby(game);
|
||||
if (game.players.length >= multi.max) {
|
||||
lobbies.delete(key);
|
||||
game.lobby = null;
|
||||
for (const player of game.players) {
|
||||
const music = player.room ? player.room.customMusicDef : 0;
|
||||
if (def.type !== IN_ROOM) {
|
||||
leaveRoom(player);
|
||||
}
|
||||
seat(player, game, music);
|
||||
}
|
||||
start(game);
|
||||
}
|
||||
};
|
||||
|
||||
// a move in a multiplayer room game, passed on to the other players.
|
||||
const relay = (session, game, word, params) => {
|
||||
const withId = game.multi.relay[word];
|
||||
if (!game.started || params.length > MAX_RELAYED_FIELDS || !params.every(field => RELAYED_FIELD.test(String(field)))
|
||||
|| !messagesPerMinute.allow(session.account.id)) {
|
||||
return;
|
||||
}
|
||||
for (const other of game.players) {
|
||||
if (other !== session) {
|
||||
other.sendXt("mm", game.roomId, word, ...(withId ? [session.id] : []), ...params);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// starts a buddy game between two players (lib/buddygames.js says what
|
||||
// `match` is). it runs in a window over whatever room each is in.
|
||||
const startMatch = (def, sender, target) => {
|
||||
@@ -451,7 +532,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
||||
},
|
||||
|
||||
// MinigameManager.launchGame: [gameDefId, multiplayer, proModeId, ?].
|
||||
mj(session, roomId, [gameDefId]) {
|
||||
mj(session, roomId, [gameDefId, multiplayer]) {
|
||||
leave(session); // a game left without a word, if any
|
||||
const def = games.get(Number(gameDefId));
|
||||
if (!def || def.ready === false || def.buddy || !session.room) {
|
||||
@@ -461,6 +542,10 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
||||
tell(session, "That game is not ready on this server yet.");
|
||||
return;
|
||||
}
|
||||
if (multiplayer === "1" && Object.hasOwn(MULTIPLAYER, def.swf)) {
|
||||
joinLobby(session, def, MULTIPLAYER[def.swf]);
|
||||
return;
|
||||
}
|
||||
const game = {roomId: nextGameRoomId++, def, players: [session], started: false, ready: new Set()};
|
||||
const music = session.room.customMusicDef; // the client takes this from every room join
|
||||
if (def.type !== IN_ROOM) {
|
||||
@@ -490,6 +575,10 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
||||
matchMessage(session, game, String(word), params);
|
||||
return;
|
||||
}
|
||||
if (game.multi && Object.hasOwn(game.multi.relay, String(word))) {
|
||||
relay(session, game, String(word), params);
|
||||
return;
|
||||
}
|
||||
const reply = (...fields) => session.sendXt("mm", game.roomId, ...fields);
|
||||
const own = game.def.tickets ? carnival : MESSAGES[game.def.swf];
|
||||
if (own && Object.hasOwn(own, word)) {
|
||||
|
||||
+21
-6
@@ -27,7 +27,11 @@ const WARNINGS = {
|
||||
bullying: 1, // "Bullying"
|
||||
personal: 3, // "Personal Information"
|
||||
scamming: 9, // "Scamming"
|
||||
// in the staff member's own words: its note is what the player is shown,
|
||||
// in a message box (there is no popup for it), and it cannot be left out.
|
||||
custom: null,
|
||||
};
|
||||
const CUSTOM_WARNING = "custom";
|
||||
const MAX_WARNINGS_KEPT = 100;
|
||||
const MAX_WARNING_NOTE = 200;
|
||||
const SECONDS_PER_DAY = 86400;
|
||||
@@ -81,6 +85,16 @@ module.exports = ({findOnline}) => {
|
||||
|
||||
// A "message from moderator" popup; also used to answer chat commands.
|
||||
const notify = (session, text) => discipline(session, "fp", text, 0);
|
||||
// a warning as the player sees it: the game's popup for its reason, or a
|
||||
// custom one's words.
|
||||
const showWarning = (session, entry) => {
|
||||
if (entry.reason === CUSTOM_WARNING && entry.note) {
|
||||
notify(session, `Warning: ${entry.note}`);
|
||||
}
|
||||
else {
|
||||
discipline(session, "fw", WARNINGS[entry.reason] ?? WARNINGS.behavior);
|
||||
}
|
||||
};
|
||||
|
||||
const actions = {
|
||||
kick(target) {
|
||||
@@ -207,18 +221,19 @@ module.exports = ({findOnline}) => {
|
||||
// config.warningSilence.days may also silence them for a while; a
|
||||
// longer silence already on them is left alone.
|
||||
// returns {count, online, silencedMinutes}, or null for a reason that
|
||||
// is not one.
|
||||
// is not one (or a custom warning with nothing to say).
|
||||
warn(target, reason, by, note = "") {
|
||||
if (!Object.hasOwn(WARNINGS, reason)) {
|
||||
const text = String(note).trim().slice(0, MAX_WARNING_NOTE);
|
||||
if (!Object.hasOwn(WARNINGS, reason) || (reason === CUSTOM_WARNING && !text)) {
|
||||
return null;
|
||||
}
|
||||
const session = findOnline(target.username);
|
||||
const seen = Boolean(session && session.greeted);
|
||||
target.warnings = [...(target.warnings || []), {at: now(), by, reason, note: String(note).slice(0, MAX_WARNING_NOTE), seen}]
|
||||
.slice(-MAX_WARNINGS_KEPT);
|
||||
const entry = {at: now(), by, reason, note: text, seen};
|
||||
target.warnings = [...(target.warnings || []), entry].slice(-MAX_WARNINGS_KEPT);
|
||||
accounts.save();
|
||||
if (seen) {
|
||||
discipline(session, "fw", WARNINGS[reason]);
|
||||
showWarning(session, entry);
|
||||
}
|
||||
let silencedMinutes = silenceForWarning(recentWarnings(target));
|
||||
const left = silenceRemaining(target);
|
||||
@@ -261,7 +276,7 @@ module.exports = ({findOnline}) => {
|
||||
}
|
||||
unseen.forEach(entry => { entry.seen = true; });
|
||||
accounts.save();
|
||||
discipline(session, "fw", WARNINGS[unseen[unseen.length - 1].reason] ?? WARNINGS.behavior);
|
||||
showWarning(session, unseen[unseen.length - 1]);
|
||||
};
|
||||
|
||||
return {handlers, actions, greet, banRemaining, banOf, isSilenced, silenceRemaining, PERMANENT, WARNINGS: Object.keys(WARNINGS)};
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const accounts = require("./accounts.js");
|
||||
|
||||
// what each moderator did in the moderator panel (lib/modpanel.js), for
|
||||
@@ -23,7 +24,7 @@ const load = () => accounts.database().exec(SCHEMA);
|
||||
const record = (by, action, target = "", detail = "") => {
|
||||
accounts.database().prepare("INSERT INTO mod_log (at, by, action, target, detail) VALUES (?, ?, ?, ?, ?)")
|
||||
.run(Math.floor(Date.now() / 1000), by, action, String(target), String(detail).slice(0, MAX_DETAIL));
|
||||
console.log(`[mod] ${by}: ${action}${target ? ` "${target}"` : ""}`);
|
||||
console.log(`[mod] ${logText(by)}: ${logText(action)}${logText(target ? ` "${target}"` : "")}`);
|
||||
};
|
||||
|
||||
const recent = () => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log ORDER BY id DESC LIMIT ?").all(SHOWN);
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const accounts = require("./accounts.js");
|
||||
|
||||
// moderators' notes on a player: what staff want one another to know about
|
||||
// them ("talked to them about trading, seemed fine"), on the player's page
|
||||
// of the moderator panel and with "!notes" in the game. the player is never
|
||||
// shown them (lib/manage.js leaves them out of their data).
|
||||
//
|
||||
// on an account: modNotes [{id, at, by, text}], the oldest first.
|
||||
|
||||
const MAX_NOTES = 100;
|
||||
const MAX_TEXT = 500;
|
||||
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
|
||||
const list = account => [...(account.modNotes || [])].reverse();
|
||||
|
||||
// returns {note} or {error}.
|
||||
const add = (account, by, text) => {
|
||||
const clean = String(text || "").replace(/\s+/g, " ").trim().slice(0, MAX_TEXT);
|
||||
if (!clean) {
|
||||
return {error: "Write the note first."};
|
||||
}
|
||||
const note = {id: crypto.randomBytes(6).toString("hex"), at: now(), by: String(by), text: clean};
|
||||
account.modNotes = [...(account.modNotes || []), note].slice(-MAX_NOTES);
|
||||
accounts.save();
|
||||
return {note};
|
||||
};
|
||||
|
||||
// a note taken away by whoever wrote it, or by someone who may remove anyone's
|
||||
// (`anyone`). returns {note} or {error}.
|
||||
const remove = (account, id, by, anyone) => {
|
||||
const note = (account.modNotes || []).find(entry => entry.id === String(id));
|
||||
if (!note) {
|
||||
return {error: "No such note."};
|
||||
}
|
||||
if (!anyone && note.by.toLowerCase() !== String(by).toLowerCase()) {
|
||||
return {error: "Only whoever wrote a note, or an admin, can remove it."};
|
||||
}
|
||||
account.modNotes = account.modNotes.filter(entry => entry !== note);
|
||||
accounts.save();
|
||||
return {note};
|
||||
};
|
||||
|
||||
// the newest notes on anybody, with whom they are about.
|
||||
const recent = count => accounts.all()
|
||||
.flatMap(account => (account.modNotes || []).map(note => ({...note, about: account.username})))
|
||||
.sort((one, other) => other.at - one.at)
|
||||
.slice(0, count);
|
||||
|
||||
module.exports = {list, add, remove, recent, MAX_TEXT};
|
||||
+152
-13
@@ -4,17 +4,22 @@ const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const accounts = require("./accounts.js");
|
||||
const admin = require("./admin.js");
|
||||
const bans = require("./bans.js");
|
||||
const captcha = require("./captcha.js");
|
||||
const chatlog = require("./chatlog.js");
|
||||
const config = require("../config.js");
|
||||
const customItems = require("./customitems.js");
|
||||
const itemControl = require("./itemcontrol.js");
|
||||
const itemArt = require("./itemart.js");
|
||||
const playerItems = require("./playeritems.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const devices = require("./devices.js");
|
||||
const limits = require("./limits.js");
|
||||
const manage = require("./manage.js");
|
||||
const masterpieces = require("./masterpieces.js");
|
||||
const modlog = require("./modlog.js");
|
||||
const modNotes = require("./modnotes.js");
|
||||
const reports = require("./reports.js");
|
||||
const roles = require("./roles.js");
|
||||
const staff = require("./staff.js");
|
||||
@@ -49,6 +54,7 @@ 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 failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS);
|
||||
const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator
|
||||
@@ -124,10 +130,16 @@ const playerDetail = account => ({
|
||||
history: bans.historyOf(account).map(({at, action, seconds, reason, by}) => ({at, action, seconds, reason, by})),
|
||||
appeal: bans.appealOf(account),
|
||||
warningList: (account.warnings || []).slice(-20).reverse(),
|
||||
notes: modNotes.list(account),
|
||||
openReports: reports.list(false).filter(report => report.target.toLowerCase() === account.username.toLowerCase()).length,
|
||||
devicesKnown: devices.knownFor(account).ids,
|
||||
stoppedThisWeek: chatlog.notSentCount(account, 7),
|
||||
paintings: masterpieces.madeBy(account).length,
|
||||
// what they made in the Item Maker, with its pictures, for a report about one
|
||||
madeItems: playerItems.madeBy(account).map(entry => ({kind: entry.kind, id: entry.id, name: entry.name,
|
||||
artUrl: itemArt.urlOf(entry, "/mod/api/itemart"), artWaiting: Boolean(entry.artPending)})),
|
||||
picturesStopped: Boolean(account.artBlocked),
|
||||
pictureStrikes: account.artRefusals || 0,
|
||||
});
|
||||
|
||||
// an address with its end left out, and a name to lift its ban by.
|
||||
@@ -149,6 +161,7 @@ const ACTION_PERMISSIONS = {
|
||||
rejectName: "player.names", acceptName: "player.names", clearBio: "player.names",
|
||||
banAddress: "address.ban",
|
||||
summon: "player.summon", goto: "player.goto",
|
||||
note: "player.view", deleteNote: "player.view",
|
||||
};
|
||||
|
||||
// minutes as a person would say them: "1 hour", "1 day", "90 minutes".
|
||||
@@ -214,7 +227,8 @@ const act = (mod, target, body) => {
|
||||
const reason = String(body.reason || "behavior");
|
||||
const result = actions.warn(target, reason, by, body.note);
|
||||
if (!result) {
|
||||
return {error: `A warning's reason: ${world.moderation.WARNINGS.join(", ")}.`};
|
||||
return {error: reason === "custom" ? "A custom warning needs its words in the note: they are what the player is shown."
|
||||
: `A warning's reason: ${world.moderation.WARNINGS.join(", ")}.`};
|
||||
}
|
||||
return {ok: `${name} warned (${reason}): warning ${result.count}.${result.online ? "" : " They are offline: they will see it when they next play."}`
|
||||
+ (result.silencedMinutes ? ` That many warnings also silenced them for ${silenceText(result.silencedMinutes)}.` : ""),
|
||||
@@ -242,6 +256,15 @@ const act = (mod, target, body) => {
|
||||
target.bio = "";
|
||||
accounts.save(target);
|
||||
return {ok: "Bio cleared."};
|
||||
// a note for the other staff (lib/modnotes.js); the player never sees it.
|
||||
case "note": {
|
||||
const result = modNotes.add(target, by, body.text);
|
||||
return result.error ? result : {ok: "Note added.", detail: result.note.text};
|
||||
}
|
||||
case "deleteNote": {
|
||||
const result = modNotes.remove(target, body.id, by, roles.roleOf(mod) === "admin");
|
||||
return result.error ? result : {ok: "Note removed.", detail: `${result.note.by}: ${result.note.text}`};
|
||||
}
|
||||
// the address they last signed in from, for good. which address that
|
||||
// is, the moderator is not told.
|
||||
case "banAddress": {
|
||||
@@ -398,13 +421,26 @@ const handle = async (req, res, url, from, web) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// what players made that waits for approval (lib/playeritems.js)
|
||||
if (url.pathname === "/mod/api/review") {
|
||||
if (!roles.can(mod, "items.approve")) {
|
||||
reply(403, {error: "Your role does not allow that."});
|
||||
return;
|
||||
}
|
||||
reviewRoutes(route.replace(" /mod/api/", " "), body, reply, done, mod.username, "/mod/api/itemart");
|
||||
return;
|
||||
}
|
||||
// custom items (lib/customitems.js), for whoever may make them.
|
||||
if (url.pathname.startsWith("/mod/api/items")) {
|
||||
if (!roles.can(mod, "items.create")) {
|
||||
reply(403, {error: "Your role does not allow that."});
|
||||
return;
|
||||
}
|
||||
itemRoutes(route, url, body, reply, done, mod);
|
||||
itemRoutes(route.replace(" /mod/api/", " "), url, body, reply, done, {
|
||||
username: mod.username,
|
||||
artBase: "/mod/api/itemart",
|
||||
mayTake: target => target === mod || !roles.roleOf(target) || roles.outranks(mod, target),
|
||||
});
|
||||
return;
|
||||
}
|
||||
// everything else shows players and what they did: not for a role that
|
||||
@@ -474,6 +510,11 @@ const handle = async (req, res, url, from, web) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// the latest mod notes on anybody (lib/modnotes.js), for the dashboard.
|
||||
case "GET /mod/api/notes":
|
||||
reply(200, {notes: modNotes.recent(MAX_RECENT_NOTES)});
|
||||
return;
|
||||
|
||||
case "GET /mod/api/stats":
|
||||
reply(200, stats.report(Number(url.searchParams.get("days")), Number(url.searchParams.get("offset"))));
|
||||
return;
|
||||
@@ -593,17 +634,39 @@ const handle = async (req, res, url, from, web) => {
|
||||
}
|
||||
};
|
||||
|
||||
// GET /mod/api/items: the custom items, the newest first.
|
||||
// GET /mod/api/items/base?kind=clothing|den&id=N: an item of the game's to
|
||||
// the custom items' pages, for the moderator panel (/mod/api/...) and the
|
||||
// admin panel (/admin/api/..., lib/panel.js): `route` is without that
|
||||
// ("GET items"), and `actor` is {username, mayTake(account)}: who it is
|
||||
// written down as, and whether they may take items from that player.
|
||||
// GET items: the custom items, the newest first.
|
||||
// GET items/find?q=WORDS&kind=all|clothing|den: any item (the game's or a
|
||||
// custom one), by name or id, as the item finder finds it, each marked
|
||||
// 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.
|
||||
// POST /mod/api/items {action: "create", kind, base, name, cost, members, colors}
|
||||
// or {action: "update", kind, id, and any of name, cost, members, colors, inShop}.
|
||||
const itemRoutes = (route, url, body, reply, done, mod) => {
|
||||
// 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
|
||||
// or {action: "take", username, kind, id}: every one of it, from one player
|
||||
// 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 /mod/api/items":
|
||||
reply(200, {items: customItems.list().map(entry => ({...entry, baseName: customItems.baseName(entry)})), firstId: customItems.FIRST_ID});
|
||||
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)})),
|
||||
firstId: customItems.FIRST_ID, locked: itemControl.lockedList()});
|
||||
return;
|
||||
case "GET /mod/api/items/base": {
|
||||
case "GET items/find": {
|
||||
const found = admin.search(url.searchParams, null, true);
|
||||
reply(200, {total: found.total, results: found.results.slice(0, 20).map(entry => ({
|
||||
kind: entry.kind, id: entry.id, cost: entry.cost,
|
||||
name: entry.locked ? entry.name.replace(/ \(locked\)$/, "") : entry.name,
|
||||
locked: Boolean(entry.locked),
|
||||
custom: entry.id >= customItems.FIRST_ID,
|
||||
})), lockedCount: itemControl.lockedList().length});
|
||||
return;
|
||||
}
|
||||
case "GET items/base": {
|
||||
const kind = url.searchParams.get("kind") === "den" ? "den" : "clothing";
|
||||
const id = Number(url.searchParams.get("id"));
|
||||
const def = kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id);
|
||||
@@ -616,11 +679,37 @@ const itemRoutes = (route, url, body, reply, done, mod) => {
|
||||
: {kind, id, name: defpacks.string(def.titleStrId), art: Number(def.layerDefId), cost: Number(def.value), colors: String(def.colors).split(",").map(Number)});
|
||||
return;
|
||||
}
|
||||
case "POST /mod/api/items": {
|
||||
case "POST items": {
|
||||
const kind = String(body.kind || "");
|
||||
if (body.action === "lock" || body.action === "unlock") {
|
||||
const result = itemControl.setLocked(kind, body.id, body.action === "lock");
|
||||
done(result, result.ok ? `item ${body.action}ed` : "", "", `${kind} ${body.id}`);
|
||||
return;
|
||||
}
|
||||
if (body.action === "take") {
|
||||
const target = accounts.byName(String(body.username || "").trim());
|
||||
if (target && !actor.mayTake(target)) {
|
||||
done({error: "Staff of your rank or above are for someone higher up to deal with."});
|
||||
return;
|
||||
}
|
||||
const result = itemControl.take(String(body.username || "").trim(), kind, body.id, world);
|
||||
done(result, result.ok ? "item taken" : "", target ? target.username : "", `${kind} ${body.id}${result.count ? ` x${result.count}` : ""}`);
|
||||
return;
|
||||
}
|
||||
if (body.action === "look") {
|
||||
const result = customItems.setArtMode(kind, body.id, String(body.look));
|
||||
done(result.error ? result : {ok: `${result.item.name} is worn as ${body.look === "texture" ? "a texture" : "a sticker"}.`},
|
||||
"item look changed", "", `${kind} ${body.id} ${body.look}`);
|
||||
return;
|
||||
}
|
||||
if (body.action === "delete") {
|
||||
const result = itemControl.deleteCustom(kind, body.id, world);
|
||||
done(result, result.ok ? "item deleted" : "", "", `${kind} ${body.id}`);
|
||||
return;
|
||||
}
|
||||
const result = body.action === "update"
|
||||
? customItems.update(kind, body.id, body)
|
||||
: body.action === "create" ? customItems.create(kind, body, mod.username) : {error: "Unknown action."};
|
||||
: body.action === "create" ? customItems.create(kind, body, actor.username) : {error: "Unknown action."};
|
||||
if (result.error) {
|
||||
done(result);
|
||||
return;
|
||||
@@ -635,8 +724,58 @@ const itemRoutes = (route, url, body, reply, done, mod) => {
|
||||
}
|
||||
};
|
||||
|
||||
// GET review: what waits, the oldest first; POST review {kind, id, approve: true | false}.
|
||||
// for the moderator panel and the admin panel (lib/panel.js) alike.
|
||||
// POST review {action: "takePicture", kind, id}: a picture off an item,
|
||||
// counted against its maker; {action: "uploads", username, blocked}:
|
||||
// stops, or lets again, one player's picture uploads.
|
||||
// `artBase`: the panel's /…/api/itemart, where pictures that wait are shown.
|
||||
const reviewRoutes = (route, body, reply, done, by, artBase) => {
|
||||
if (route === "GET review") {
|
||||
reply(200, {
|
||||
waiting: customItems.waiting().map(entry => {
|
||||
const maker = entry.ownerId === null ? null : accounts.byId(entry.ownerId);
|
||||
return {kind: entry.kind, id: entry.id, name: entry.name, baseName: customItems.baseName(entry), base: entry.base, maker: maker ? maker.username : entry.createdBy,
|
||||
createdAt: entry.createdAt, waiting: entry.pending ? "item" : "picture", artUrl: itemArt.urlOf(entry, artBase),
|
||||
makerStrikes: maker ? maker.artRefusals || 0 : 0};
|
||||
}),
|
||||
enabled: playerItems.enabled(),
|
||||
approval: playerItems.approvalOn(),
|
||||
artApproval: playerItems.artApprovalOn(),
|
||||
strikes: playerItems.ART_STRIKES,
|
||||
stopped: accounts.all().filter(account => account.artBlocked).map(account => account.username).sort(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (route === "POST review" && body.action === "takePicture") {
|
||||
const kind = String(body.kind || "");
|
||||
const entry = customItems.get(kind, body.id);
|
||||
const maker = entry && entry.ownerId !== null ? accounts.byId(entry.ownerId) : null;
|
||||
const result = playerItems.takePicture(kind, body.id);
|
||||
done(result, result.ok ? "item picture taken off" : "", maker ? maker.username : "", `${kind} ${body.id}`);
|
||||
return;
|
||||
}
|
||||
if (route === "POST review" && body.action === "uploads") {
|
||||
const target = accounts.byName(String(body.username || "").trim());
|
||||
if (!target) {
|
||||
done({error: "No such player."});
|
||||
return;
|
||||
}
|
||||
const result = playerItems.setUploadsBlocked(target, body.blocked === true);
|
||||
done(result, body.blocked === true ? "picture uploads stopped" : "picture uploads allowed", target.username);
|
||||
return;
|
||||
}
|
||||
if (route === "POST review") {
|
||||
const kind = String(body.kind || "");
|
||||
const result = playerItems.review(kind, body.id, body.approve === true, by, world);
|
||||
done(result, result.ok ? (body.approve === true ? "item approved" : "item turned away") : "", "", `${kind} ${body.id}`);
|
||||
return;
|
||||
}
|
||||
reply(404, {error: "not_found"});
|
||||
};
|
||||
|
||||
const moderators = () => accounts.all().filter(account => roles.roleOf(account))
|
||||
.map(account => ({username: account.username, role: roles.roleOf(account), twoStep: totp.isOn(account), lastSeen: account.lastSeen || null}))
|
||||
.sort((a, b) => a.username.localeCompare(b.username));
|
||||
|
||||
module.exports = {handle, forget, moderators};
|
||||
module.exports = {handle, forget, moderators, signedInAs, itemRoutes, reviewRoutes};
|
||||
+18
-10
@@ -35,23 +35,31 @@ const stretched = word => /(.)\1\1/.test(word);
|
||||
// above. "word" is for a line marked "=": in lib/sexual-names.txt the rest
|
||||
// are matched anywhere in a name.
|
||||
const lists = new Map(); // file -> {mtime, entries}
|
||||
// the file is opened once, and its time and its words are both of what was
|
||||
// opened: a list changed in between cannot be read under the old one's time.
|
||||
const read = file => {
|
||||
let mtime = 0;
|
||||
let fd;
|
||||
try {
|
||||
mtime = fs.statSync(file).mtimeMs;
|
||||
fd = fs.openSync(file, "r");
|
||||
}
|
||||
catch (err) {
|
||||
return [];
|
||||
}
|
||||
const kept = lists.get(file);
|
||||
if (kept && kept.mtime === mtime) {
|
||||
return kept.entries;
|
||||
try {
|
||||
const mtime = fs.fstatSync(fd).mtimeMs;
|
||||
const kept = lists.get(file);
|
||||
if (kept && kept.mtime === mtime) {
|
||||
return kept.entries;
|
||||
}
|
||||
const entries = fs.readFileSync(fd, "utf8").split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith("#"))
|
||||
.map(line => ({text: line.replace(/^=/, "").replace(/\*$/, "").split(/\s+/).map(plain).join(""), prefix: line.endsWith("*"), word: line.startsWith("=")}))
|
||||
.filter(entry => entry.text.length >= 2);
|
||||
lists.set(file, {mtime, entries});
|
||||
return entries;
|
||||
}
|
||||
finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
const entries = fs.readFileSync(file, "utf8").split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith("#"))
|
||||
.map(line => ({text: line.replace(/^=/, "").replace(/\*$/, "").split(/\s+/).map(plain).join(""), prefix: line.endsWith("*"), word: line.startsWith("=")}))
|
||||
.filter(entry => entry.text.length >= 2);
|
||||
lists.set(file, {mtime, entries});
|
||||
return entries;
|
||||
};
|
||||
|
||||
let epicDens = null;
|
||||
|
||||
+87
-16
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
@@ -18,6 +19,7 @@ const log = require("./log.js");
|
||||
const masterpieces = require("./masterpieces.js");
|
||||
const modlog = require("./modlog.js");
|
||||
const modpanel = require("./modpanel.js");
|
||||
const playerItems = require("./playeritems.js");
|
||||
const erase = require("./erase.js");
|
||||
const reports = require("./reports.js");
|
||||
const roles = require("./roles.js");
|
||||
@@ -89,7 +91,7 @@ const passwordAcceptable = password =>
|
||||
const load = () => {
|
||||
if (!hasPassword()) {
|
||||
setupCode = crypto.randomBytes(5).toString("hex");
|
||||
console.log(`[admin] no admin password yet: open ${config.baseUrl}admin to choose one`
|
||||
console.log(`[admin] no admin password yet: open ${logText(config.baseUrl)}admin to choose one`
|
||||
+ ` (from another machine it will ask for this setup code: ${setupCode})`);
|
||||
}
|
||||
};
|
||||
@@ -154,6 +156,10 @@ const accountRow = (account, playing) => {
|
||||
banReason: ban === 0 ? "" : account.banReason || bans.NO_REASON,
|
||||
moderator: Boolean(roles.roleOf(account)),
|
||||
role: roles.roleOf(account),
|
||||
// what they may do (their role's, with their own grants and denies)
|
||||
permissions: roles.permissionsOf(account),
|
||||
permGrants: account.permGrants || [],
|
||||
permDenies: account.permDenies || [],
|
||||
nameRejected: Boolean(account.nameRejected),
|
||||
silenced: world.moderation.isSilenced(account),
|
||||
animals: account.avatars.length,
|
||||
@@ -378,8 +384,10 @@ const act = (account, body) => {
|
||||
const name = account.username;
|
||||
switch (body.action) {
|
||||
case "password": {
|
||||
if (accounts.setPassword(account, body.password)) {
|
||||
return {error: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."};
|
||||
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
|
||||
@@ -523,12 +531,26 @@ const act = (account, body) => {
|
||||
modpanel.forget(account);
|
||||
}
|
||||
accounts.save();
|
||||
world.refreshStaff(account);
|
||||
if (role === null) {
|
||||
return {ok: `${name} has no staff role.`};
|
||||
}
|
||||
const label = roles.ROLES[role].label.toLowerCase();
|
||||
return {ok: `${name} is now ${/^[aeiou]/.test(label) ? "an" : "a"} ${label}.${totp.isOn(account) ? "" : " They have no 2FA yet, so their role does nothing until they turn it on."}`};
|
||||
}
|
||||
// one staff member's own permissions, beyond their role's or taken from
|
||||
// it ({grants: [...], denies: [...]}).
|
||||
case "permissions": {
|
||||
if (!roles.roleOf(account)) {
|
||||
return {error: `${name} has no staff role: give them one first.`};
|
||||
}
|
||||
roles.setAccountPermissions(account, body.grants, body.denies);
|
||||
accounts.save();
|
||||
world.refreshStaff(account);
|
||||
modlog.record("admin", "permissions changed", account.username,
|
||||
`+${(account.permGrants || []).join(",") || "none"} -${(account.permDenies || []).join(",") || "none"}`);
|
||||
return {ok: `${name}'s permissions are saved.`};
|
||||
}
|
||||
case "rejectName":
|
||||
actions.rejectName(account, BY);
|
||||
manage.forget(account);
|
||||
@@ -633,7 +655,7 @@ const handle = async (req, res, url, from, web) => {
|
||||
}
|
||||
storePassword(body.password);
|
||||
setupCode = null;
|
||||
console.log(`[admin] admin password chosen from ${from.address}`);
|
||||
console.log(`[admin] admin password chosen from ${logText(from.address)}`);
|
||||
signIn(res);
|
||||
reply(200, {ok: true});
|
||||
return;
|
||||
@@ -646,11 +668,11 @@ const handle = async (req, res, url, from, web) => {
|
||||
}
|
||||
if (!hasPassword() || !passwordMatches(body.password)) {
|
||||
recordFailure(from.key);
|
||||
console.log(`[admin] failed sign-in from ${from.address}`);
|
||||
console.log(`[admin] failed sign-in from ${logText(from.address)}`);
|
||||
reply(401, {error: "Wrong password."});
|
||||
return;
|
||||
}
|
||||
console.log(`[admin] signed in from ${from.address}`);
|
||||
console.log(`[admin] signed in from ${logText(from.address)}`);
|
||||
signIn(res);
|
||||
reply(200, {ok: true});
|
||||
return;
|
||||
@@ -667,6 +689,39 @@ const handle = async (req, res, url, from, web) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// what players made that waits (the moderator panel's Review), and the
|
||||
// admin's switches for the Item Maker: {enabled, approval}.
|
||||
if (url.pathname === "/admin/api/review" || url.pathname === "/admin/api/item-switches") {
|
||||
const done = (result, action, target = "", detail = "") => {
|
||||
if (result.ok) {
|
||||
modlog.record("admin", action, target, result.detail || detail);
|
||||
}
|
||||
reply(result.ok ? 200 : 400, result.ok ? {ok: result.ok} : {error: result.error});
|
||||
};
|
||||
if (route === "POST /admin/api/item-switches") {
|
||||
const flag = value => (value === undefined ? undefined : value === true);
|
||||
playerItems.setSwitches({enabled: flag(body.enabled), approval: flag(body.approval), artApproval: flag(body.artApproval)});
|
||||
const pictures = playerItems.pictureWaits() ? "pictures wait for a moderator" : "pictures are shown at once";
|
||||
done({ok: `The Item Maker is ${playerItems.enabled() ? "on" : "off"}; new items ${playerItems.approvalOn() ? "wait for a moderator first" : "are in the game at once"}; ${pictures}.`},
|
||||
"item maker settings", "", `${playerItems.enabled() ? "on" : "off"}, approval ${playerItems.approvalOn() ? "on" : "off"}, pictures ${playerItems.pictureWaits() ? "wait" : "at once"}`);
|
||||
return;
|
||||
}
|
||||
modpanel.reviewRoutes(route.replace(" /admin/api/", " "), body, reply, done, "admin", "/admin/api/itemart");
|
||||
return;
|
||||
}
|
||||
// custom items (lib/customitems.js): the moderator panel's pages, the
|
||||
// admin written down as "admin", and free to take from anyone.
|
||||
if (url.pathname.startsWith("/admin/api/items")) {
|
||||
const done = (result, action, target = "", detail = "") => {
|
||||
if (result.ok) {
|
||||
modlog.record("admin", action, target, result.detail || detail);
|
||||
}
|
||||
reply(result.ok ? 200 : 400, result.ok ? {ok: result.ok} : {error: result.error});
|
||||
};
|
||||
modpanel.itemRoutes(route.replace(" /admin/api/", " "), url, body, reply, done, {username: "admin", artBase: "/admin/api/itemart", mayTake: () => true});
|
||||
return;
|
||||
}
|
||||
|
||||
switch (route) {
|
||||
case "GET /admin/api/overview":
|
||||
reply(200, overview());
|
||||
@@ -741,7 +796,7 @@ const handle = async (req, res, url, from, web) => {
|
||||
}
|
||||
const result = act(account, body);
|
||||
if (result.ok) {
|
||||
console.log(`[admin] ${body.action} on "${account.username}"`);
|
||||
console.log(`[admin] ${logText(body.action)} on "${logText(account.username)}"`);
|
||||
// in the record beside the moderators', for the player's timeline.
|
||||
if (!["password", "lastSeen", "level"].includes(body.action)) {
|
||||
modlog.record(BY, body.action, account.username, result.detail || "");
|
||||
@@ -765,7 +820,7 @@ const handle = async (req, res, url, from, web) => {
|
||||
case "POST /admin/api/device": {
|
||||
const result = staff.unbanDevices(body.id, BY);
|
||||
if (result.ok) {
|
||||
console.log(`[admin] device ban ${Number(body.id)} lifted`);
|
||||
console.log(`[admin] device ban ${logText(Number(body.id))} lifted`);
|
||||
modlog.record(BY, "hardware ban lifted", result.username || "");
|
||||
}
|
||||
reply(result.ok ? 200 : 400, result);
|
||||
@@ -796,9 +851,25 @@ const handle = async (req, res, url, from, web) => {
|
||||
// who may use the moderator panel, and what each did there.
|
||||
// the staff roles and what each may do.
|
||||
case "GET /admin/api/roles":
|
||||
reply(200, {roles: Object.entries(roles.ROLES).map(([id, role]) => ({id, label: role.label, rank: role.rank, permissions: role.permissions})),
|
||||
permissions: roles.PERMISSIONS});
|
||||
reply(200, {roles: Object.entries(roles.ROLES).map(([id, role]) => ({id, label: role.label, rank: role.rank, permissions: roles.rolePermissions(id),
|
||||
defaults: role.permissions, changed: roles.roleChanged(id)})), permissions: roles.PERMISSIONS});
|
||||
return;
|
||||
// a role's permissions changed ({role, permissions: [...]}), or back to
|
||||
// its defaults ({role, reset: true}). its staff who are playing are told.
|
||||
case "POST /admin/api/roles": {
|
||||
const role = String(body.role || "");
|
||||
if (!roles.setRolePermissions(role, body.reset === true ? null : Array.isArray(body.permissions) ? body.permissions : [])) {
|
||||
reply(400, {error: "No such role."});
|
||||
return;
|
||||
}
|
||||
for (const player of accounts.all().filter(account => roles.roleOf(account) === role)) {
|
||||
world.refreshStaff(player);
|
||||
}
|
||||
console.log(`[admin] permissions of the ${logText(role)} role ${logText(body.reset === true ? "reset" : "changed")}`);
|
||||
modlog.record("admin", body.reset === true ? "role permissions reset" : "role permissions changed", "", `${role}: ${roles.rolePermissions(role).join(", ")}`);
|
||||
reply(200, {ok: `${roles.ROLES[role].label}: ${body.reset === true ? "back to its defaults" : "saved"}.`});
|
||||
return;
|
||||
}
|
||||
case "GET /admin/api/moderators":
|
||||
reply(200, {moderators: modpanel.moderators(), log: modlog.recent()});
|
||||
return;
|
||||
@@ -812,7 +883,7 @@ const handle = async (req, res, url, from, web) => {
|
||||
case "POST /admin/api/address": {
|
||||
const result = addressAct(body);
|
||||
if (result.ok) {
|
||||
console.log(`[admin] address ${body.action}: ${limits.key(body.address)}`);
|
||||
console.log(`[admin] address ${logText(body.action)}: ${logText(limits.key(body.address))}`);
|
||||
}
|
||||
reply(result.ok ? 200 : 400, result);
|
||||
return;
|
||||
@@ -829,7 +900,7 @@ const handle = async (req, res, url, from, web) => {
|
||||
case "POST /admin/api/debug": {
|
||||
const result = debugAct(body);
|
||||
if (result.ok) {
|
||||
console.log(`[admin] debug: ${body.action} ${body.action === "teleport" ? `${body.username} -> ${body.room}` : body.on === true}`);
|
||||
console.log(`[admin] debug: ${logText(body.action)} ${logText(body.action === "teleport" ? `${body.username} -> ${body.room}` : body.on === true)}`);
|
||||
}
|
||||
reply(result.ok ? 200 : 400, result);
|
||||
return;
|
||||
@@ -850,7 +921,7 @@ const handle = async (req, res, url, from, web) => {
|
||||
return;
|
||||
}
|
||||
const reached = world.announce(text, body.room ? String(body.room) : null);
|
||||
console.log(`[admin] announcement to ${body.room ? `room ${body.room}` : "everyone"} (${reached} players)`);
|
||||
console.log(`[admin] announcement to ${logText(body.room ? `room ${body.room}` : "everyone")} (${logText(reached)} players)`);
|
||||
reply(200, {ok: reached === 1 ? "Shown to 1 player." : `Shown to ${reached} players.`});
|
||||
return;
|
||||
}
|
||||
@@ -895,7 +966,7 @@ const handle = async (req, res, url, from, web) => {
|
||||
result = {error: "Unknown action."};
|
||||
}
|
||||
if (result.ok) {
|
||||
console.log(`[admin] masterpiece ${body.action} ${id || body.on === true}`);
|
||||
console.log(`[admin] masterpiece ${logText(body.action)} ${logText(id || body.on === true)}`);
|
||||
}
|
||||
reply(result.ok ? 200 : 400, result);
|
||||
return;
|
||||
@@ -937,7 +1008,7 @@ const handle = async (req, res, url, from, web) => {
|
||||
result = {error: "Unknown action."};
|
||||
}
|
||||
if (result.ok) {
|
||||
console.log(`[admin] support: ${body.action} ${Number(body.id)}`);
|
||||
console.log(`[admin] support: ${logText(body.action)} ${logText(Number(body.id))}`);
|
||||
}
|
||||
reply(result.ok ? 200 : 400, result);
|
||||
return;
|
||||
@@ -965,4 +1036,4 @@ const handle = async (req, res, url, from, web) => {
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {load, handle, PASSWORD_SETTING};
|
||||
module.exports = {load, handle, signedIn, PASSWORD_SETTING};
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const accounts = require("./accounts.js");
|
||||
const config = require("../config.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
@@ -190,7 +191,7 @@ module.exports = ({enterRoom, findOnline, blocks}) => {
|
||||
accounts.save(account);
|
||||
const party = {host: account, defId: def.id, name: `${name1}|${name2}|${name3}`, music: Number(music), endsAt: now() + config.partyMinutes * 60};
|
||||
hosted.set(account.username.toLowerCase(), party);
|
||||
console.log(`[world] ${account.username} is hosting a party (def ${def.id})`);
|
||||
console.log(`[world] ${logText(account.username)} is hosting a party (def ${logText(def.id)})`);
|
||||
session.sendXt("cu", -1, CURRENCY_DIAMONDS, account.currency.diamonds, 0);
|
||||
session.sendXt("scp", -1, 1, 1, party.endsAt - now());
|
||||
joinHosted(session, account);
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const config = require("../config.js");
|
||||
const customItems = require("./customitems.js");
|
||||
const dens = require("./dens.js");
|
||||
const itemControl = require("./itemcontrol.js");
|
||||
const modlog = require("./modlog.js");
|
||||
const names = require("./names.js");
|
||||
const {addClothing, sendClothingAdded} = require("./player.js");
|
||||
|
||||
// items players make for themselves (the patched client's Item Maker, in the
|
||||
// settings menu): one of the game's clothing pieces or den items under a
|
||||
// name of their own, as staff make them (lib/customitems.js), but free, never
|
||||
// in a shop, and in the item finder for its maker only. the maker is given
|
||||
// one at once; it can be worn, placed and traded like any other. a maker
|
||||
// may delete their own; staff may delete anyone's (the moderator panel).
|
||||
//
|
||||
// "xcm" from the client: ["info"], ["make", kind, baseId, name],
|
||||
// ["rename", kind, id, name], ["look", kind, id, "sticker" | "texture"]
|
||||
// (how one with a picture is worn) or ["delete", kind, id]. its picture is
|
||||
// uploaded over HTTP (lib/itemart.js, POST /api/itemart). the answer is always "xcm" [ok 1 | 0, what to say,
|
||||
// left today, left in all, the maker's items as JSON]
|
||||
|
||||
// the admin's two switches (the admin panel's Items page): whether players
|
||||
// may make items at all, and whether what they make (an item, or a new
|
||||
// picture for one) waits for a moderator first (items.approve: the
|
||||
// moderator panel's Review page), out of the game till then.
|
||||
const ENABLED_SETTING = "playerItems";
|
||||
const APPROVAL_SETTING = "playerItemApproval";
|
||||
const enabled = () => accounts.setting(ENABLED_SETTING) !== "off";
|
||||
const approvalOn = () => accounts.setting(APPROVAL_SETTING) === "on";
|
||||
// pictures are seen by everyone who meets the item, so a player's waits for
|
||||
// a moderator even when items do not: unless the admin turns this off too.
|
||||
const ART_APPROVAL_SETTING = "playerArtApproval";
|
||||
const artApprovalOn = () => accounts.setting(ART_APPROVAL_SETTING) !== "off";
|
||||
const pictureWaits = () => approvalOn() || artApprovalOn();
|
||||
const setSwitches = ({enabled: on, approval, artApproval}) => {
|
||||
if (on !== undefined) {
|
||||
accounts.setSetting(ENABLED_SETTING, on ? "on" : "off");
|
||||
}
|
||||
if (approval !== undefined) {
|
||||
accounts.setSetting(APPROVAL_SETTING, approval ? "on" : "off");
|
||||
}
|
||||
if (artApproval !== undefined) {
|
||||
accounts.setSetting(ART_APPROVAL_SETTING, artApproval ? "on" : "off");
|
||||
}
|
||||
};
|
||||
|
||||
// ---- what keeps pictures players upload decent
|
||||
//
|
||||
// - a picture turned away (or taken off by a moderator) is remembered by
|
||||
// its SHA-256, and the same picture cannot be sent again;
|
||||
// - each counts against its maker: at ART_STRIKES their uploads stop,
|
||||
// till a moderator lets them again (account.artBlocked);
|
||||
// - an account younger than config.itemArtMinAccountHours may not upload.
|
||||
const ART_STRIKES = 3;
|
||||
const REFUSED_SETTING = "refusedArt";
|
||||
const MAX_REFUSED = 5000;
|
||||
let refused = null; // Set of SHA-256 hex
|
||||
|
||||
const refusedSet = () => {
|
||||
if (!refused) {
|
||||
let saved = [];
|
||||
try {
|
||||
saved = JSON.parse(accounts.setting(REFUSED_SETTING) || "[]");
|
||||
}
|
||||
catch {
|
||||
saved = [];
|
||||
}
|
||||
refused = new Set(Array.isArray(saved) ? saved.map(String) : []);
|
||||
}
|
||||
return refused;
|
||||
};
|
||||
const pictureRefused = hash => refusedSet().has(hash);
|
||||
|
||||
// {error} when `account` may not upload a picture now, else null. `local`:
|
||||
// the request is from this machine (no wait for a new account).
|
||||
const uploadRefusal = (account, local = false) => {
|
||||
if (account.artBlocked) {
|
||||
return {error: "A moderator has turned off picture uploads for your account."};
|
||||
}
|
||||
const hours = config.itemArtMinAccountHours;
|
||||
if (!local && hours > 0 && Math.floor(Date.now() / 1000) - (account.createdAt || 0) < hours * 3600) {
|
||||
return {error: `New accounts can add pictures after ${hours} hours. Try again later.`};
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// stops or lets again one player's uploads; letting them again clears the
|
||||
// pictures counted against them.
|
||||
const setUploadsBlocked = (account, blocked) => {
|
||||
account.artBlocked = Boolean(blocked);
|
||||
if (!blocked) {
|
||||
account.artRefusals = 0;
|
||||
}
|
||||
accounts.save(account);
|
||||
return {ok: blocked ? `${account.username} can no longer upload pictures.` : `${account.username} can upload pictures again.`};
|
||||
};
|
||||
|
||||
// a picture turned away or taken off: never again, and counted against its
|
||||
// maker (not against staff, whose items have no maker). before it is removed.
|
||||
// returns what to add to what the moderator is told.
|
||||
const strike = entry => {
|
||||
const hash = require("./itemart.js").digestOf(entry.kind, entry.id);
|
||||
if (hash) {
|
||||
const set = refusedSet();
|
||||
set.add(hash);
|
||||
const kept = [...set].slice(-MAX_REFUSED);
|
||||
refused = new Set(kept);
|
||||
accounts.setSetting(REFUSED_SETTING, JSON.stringify(kept));
|
||||
}
|
||||
const maker = entry.ownerId === null ? null : accounts.byId(entry.ownerId);
|
||||
if (!maker) {
|
||||
return "";
|
||||
}
|
||||
maker.artRefusals = (maker.artRefusals || 0) + 1;
|
||||
if (maker.artRefusals >= ART_STRIKES && !maker.artBlocked) {
|
||||
maker.artBlocked = true;
|
||||
accounts.save(maker);
|
||||
modlog.record("system", "picture uploads stopped", maker.username, `${maker.artRefusals} pictures turned away`);
|
||||
return ` That is ${maker.artRefusals} for ${maker.username}: their picture uploads are stopped.`;
|
||||
}
|
||||
accounts.save(maker);
|
||||
return ` ${maker.username} has had ${maker.artRefusals} of ${ART_STRIKES} pictures turned away.`;
|
||||
};
|
||||
|
||||
// a moderator takes an item's picture off, shown or waiting (after a report).
|
||||
const takePicture = (kind, id) => {
|
||||
const entry = customItems.get(kind, id);
|
||||
if (!entry || !entry.art) {
|
||||
return {error: "That item has no picture of its own."};
|
||||
}
|
||||
const said = strike(entry);
|
||||
const result = require("./itemart.js").remove(kind, entry.id);
|
||||
return result.error ? result : {ok: `${result.ok}${said}`};
|
||||
};
|
||||
|
||||
const PER_DAY = 5;
|
||||
const IN_ALL = 20;
|
||||
const DAY = 86400;
|
||||
|
||||
const RENAMES_PER_HOUR = 10;
|
||||
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
const renames = require("./limits.js").limiter(RENAMES_PER_HOUR, 3600000); // per account: each is sent to every game
|
||||
|
||||
const madeBy = account => customItems.list().filter(entry => entry.ownerId === account.id);
|
||||
|
||||
const left = account => {
|
||||
const mine = madeBy(account);
|
||||
const today = mine.filter(entry => entry.createdAt > now() - DAY).length;
|
||||
return {today: Math.max(0, Math.min(PER_DAY - today, IN_ALL - mine.length)), inAll: Math.max(0, IN_ALL - mine.length)};
|
||||
};
|
||||
|
||||
// returns {ok} or {error}.
|
||||
const make = (session, kind, baseId, name) => {
|
||||
const {account} = session;
|
||||
if (!enabled()) {
|
||||
return {error: "The Item Maker is turned off on this server for now."};
|
||||
}
|
||||
if (!customItems.KINDS.includes(kind) || !/^\d+$/.test(String(baseId))) {
|
||||
return {error: "Choose an item to make yours from."};
|
||||
}
|
||||
if (!customItems.copyable(kind, Number(baseId))) {
|
||||
return {error: "That item cannot be made into one of your own. Choose another."};
|
||||
}
|
||||
const room = left(account);
|
||||
if (room.inAll === 0) {
|
||||
return {error: `You have made ${IN_ALL} items, as many as there can be. Delete one to make another.`};
|
||||
}
|
||||
if (room.today === 0) {
|
||||
return {error: `You have made ${PER_DAY} items today. Try again tomorrow.`};
|
||||
}
|
||||
const clean = String(name || "").trim().replace(/\s+/g, " ");
|
||||
if (clean && names.refused(clean)) {
|
||||
return {error: "That name is not allowed."};
|
||||
}
|
||||
const waits = approvalOn();
|
||||
const result = customItems.create(kind, {base: Number(baseId), name: clean, cost: 0, members: false, inShop: false}, account.username, account.id, waits);
|
||||
if (result.error) {
|
||||
return result;
|
||||
}
|
||||
const {item} = result;
|
||||
if (waits) {
|
||||
modlog.record(account.username, "item made by a player, waiting for approval", "", `${kind} ${item.id} ${item.name}`);
|
||||
return {ok: `${item.name} is waiting for a moderator to approve it. It is yours as soon as they do.`};
|
||||
}
|
||||
giveTo(account, item, session);
|
||||
modlog.record(account.username, "item made by a player", "", `${kind} ${item.id} ${item.name}`);
|
||||
return {ok: `Made ${item.name}. It is in your ${kind === "den" ? "den items" : "clothing"} now.`};
|
||||
};
|
||||
|
||||
// one of the item, to its maker: now in their game if `session` is it
|
||||
const giveTo = (account, item, session) => {
|
||||
if (item.kind === "den") {
|
||||
if (dens.giveDenItem(account, item.id) && session) {
|
||||
dens.sendDenItems(session);
|
||||
}
|
||||
}
|
||||
else {
|
||||
const given = addClothing(account, item.id, item.colors[0]);
|
||||
accounts.save(account);
|
||||
if (session) {
|
||||
sendClothingAdded(session, given);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// a moderator's answer about what waits (lib/modpanel.js, lib/panel.js): an
|
||||
// item let in is given to its maker; one turned away is deleted, or only
|
||||
// its picture taken away. `world` finds whether its maker is playing, and
|
||||
// tells games about items taken. returns {ok} or {error}.
|
||||
const review = (kind, id, approve, by, world) => {
|
||||
const entry = customItems.get(kind, id);
|
||||
if (!entry || (!entry.pending && !entry.artPending)) {
|
||||
return {error: "That is not waiting for approval."};
|
||||
}
|
||||
const maker = entry.ownerId === null ? null : accounts.byId(entry.ownerId);
|
||||
const wasNew = entry.pending;
|
||||
if (approve) {
|
||||
customItems.approve(kind, entry.id);
|
||||
if (wasNew && maker) {
|
||||
giveTo(maker, entry, world.findOnline(maker.username));
|
||||
}
|
||||
return {ok: wasNew ? `${entry.name} is in the game, and ${maker ? maker.username : "its maker"} has one.` : `${entry.name}'s picture is shown now.`};
|
||||
}
|
||||
if (wasNew) {
|
||||
itemControl.deleteCustom(kind, entry.id, world);
|
||||
return {ok: `${entry.name} was turned away and deleted.`};
|
||||
}
|
||||
const said = strike(entry);
|
||||
require("./itemart.js").remove(kind, entry.id);
|
||||
return {ok: `${entry.name}'s new picture was turned away.${said}`};
|
||||
};
|
||||
|
||||
// a new name for one of their own (every game is told: customItems.update).
|
||||
const rename = (account, kind, id, name) => {
|
||||
const entry = customItems.get(kind, id);
|
||||
if (!entry || entry.ownerId !== account.id) {
|
||||
return {error: "That is not one of your items."};
|
||||
}
|
||||
if (!renames.allow(account.id)) {
|
||||
return {error: "Too many renames. Try again in an hour."};
|
||||
}
|
||||
const clean = String(name || "").trim().replace(/\s+/g, " ");
|
||||
if (clean && names.refused(clean)) {
|
||||
return {error: "That name is not allowed."};
|
||||
}
|
||||
const result = customItems.update(kind, entry.id, {name: clean});
|
||||
return result.error ? result : {ok: `Renamed it ${result.item.name}.`};
|
||||
};
|
||||
|
||||
// how one of their own is worn ("sticker" or "texture")
|
||||
const setLook = (account, kind, id, mode) => {
|
||||
const entry = customItems.get(kind, id);
|
||||
if (!entry || entry.ownerId !== account.id) {
|
||||
return {error: "That is not one of your items."};
|
||||
}
|
||||
const result = customItems.setArtMode(kind, entry.id, String(mode));
|
||||
return result.error ? result : {ok: `${entry.name} is worn as ${mode === "texture" ? "its shape, with your picture in it" : "your picture"}.`};
|
||||
};
|
||||
|
||||
const remove = (session, kind, id, world) => {
|
||||
const entry = customItems.get(kind, id);
|
||||
if (!entry || entry.ownerId !== session.account.id) {
|
||||
return {error: "That is not one of your items."};
|
||||
}
|
||||
const result = itemControl.deleteCustom(kind, entry.id, world);
|
||||
return result.error ? result : {ok: `Deleted ${entry.name}.`};
|
||||
};
|
||||
|
||||
const reply = (session, result) => {
|
||||
const room = left(session.account);
|
||||
const mine = madeBy(session.account).map(entry => ({kind: entry.kind, id: entry.id, name: entry.name, base: entry.base, art: entry.artPending ? "" : entry.art || "",
|
||||
artMode: entry.artMode || "sticker", waiting: entry.pending ? "item" : entry.artPending ? "picture" : ""}));
|
||||
session.sendXt("xcm", -1, result.error ? 0 : 1, String(result.error || result.ok || "").replace(/%/g, " percent"), room.today, room.inAll,
|
||||
JSON.stringify(mine).replace(/%/g, "\\u0025"));
|
||||
};
|
||||
|
||||
// `world` tells games about items taken (lib/world.js itemsTaken).
|
||||
const handlers = world => ({
|
||||
xcm(session, roomId, [action, kind, id, ...words]) {
|
||||
if (action === "make") {
|
||||
reply(session, make(session, kind, id, words.join(" ")));
|
||||
}
|
||||
else if (action === "look") {
|
||||
reply(session, setLook(session.account, kind, id, words[0]));
|
||||
}
|
||||
else if (action === "rename") {
|
||||
reply(session, rename(session.account, kind, id, words.join(" ")));
|
||||
}
|
||||
else if (action === "delete") {
|
||||
reply(session, remove(session, kind, id, world));
|
||||
}
|
||||
else {
|
||||
reply(session, enabled() ? {ok: ""} : {error: "The Item Maker is turned off on this server for now."});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
module.exports = {handlers, madeBy, rename, setLook, review, enabled, approvalOn, artApprovalOn, pictureWaits, setSwitches,
|
||||
pictureRefused, uploadRefusal, setUploadsBlocked, takePicture, ART_STRIKES, PER_DAY, IN_ALL};
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const accounts = require("./accounts.js");
|
||||
const limits = require("./limits.js");
|
||||
|
||||
@@ -69,7 +70,7 @@ const file = ({reporter, target, reason, detail = "", context = "", room = ""})
|
||||
}
|
||||
db.prepare("INSERT INTO reports (created_at, reporter, target, reason, detail, context, room) VALUES (?, ?, ?, ?, ?, ?, ?)")
|
||||
.run(now(), reporter, target, Number.isInteger(reason) ? reason : 0, clean(detail, MAX_DETAIL), clean(context, MAX_CONTEXT), clean(room, 100));
|
||||
console.log(`[world] ${reporter} reported "${target}" (${REASONS[reason] || `reason ${reason}`})`);
|
||||
console.log(`[world] ${logText(reporter)} reported "${logText(target)}" (${logText(REASONS[reason] || `reason ${reason}`)})`);
|
||||
return true;
|
||||
};
|
||||
|
||||
|
||||
+79
-6
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const totp = require("./totp.js");
|
||||
|
||||
// staff roles, and what each may do. an account holds at most one role
|
||||
@@ -14,21 +15,23 @@ const totp = require("./totp.js");
|
||||
// higher up, and for the admin in the end.
|
||||
|
||||
const PERMISSIONS = {
|
||||
"player.view": "see players, chat, reports, requests, bans and paintings 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 and send them a message (!warn, !unwarn, !warnings, !message)",
|
||||
"player.goto": "go to the room a player is in (!goto)",
|
||||
"chat.silence": "silence and unsilence a player (!silence)",
|
||||
"player.kick": "disconnect a player (!kick)",
|
||||
"player.summon": "bring a player to the room you are in (!summon)",
|
||||
"staff.invisible": "go unseen in rooms, as the game's moderators could (!invisible)",
|
||||
"player.ban": "ban, unban and change a ban's reason",
|
||||
"player.names": "reject or accept a name, clear a bio",
|
||||
"address.ban": "ban the address a player last signed in from",
|
||||
"items.create": "make new items from the game's art, and change them (!item)",
|
||||
"items.approve": "approve or turn away the items and pictures players make, when the admin has asked for that",
|
||||
"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)",
|
||||
};
|
||||
|
||||
const HELPER = ["player.view", "staff.list", "player.warn", "player.goto", "chat.silence"];
|
||||
const MODERATOR = [...HELPER, "player.kick", "player.summon", "player.ban", "player.names", "address.ban"];
|
||||
const MODERATOR = [...HELPER, "player.kick", "player.summon", "staff.invisible", "player.ban", "player.names", "address.ban", "items.approve"];
|
||||
const ADMIN = [...MODERATOR, "items.create"];
|
||||
// a developer makes things, and moderates nobody.
|
||||
const DEVELOPER = ["staff.list", "items.create"];
|
||||
@@ -63,13 +66,82 @@ const rankOf = account => {
|
||||
const isActiveStaff = (account, banned = false) =>
|
||||
Boolean(roleOf(account) && totp.isOn(account) && !account.locked && !banned);
|
||||
|
||||
// what each role may do can be changed by the admin (the admin panel's
|
||||
// Moderators page): kept as a setting, {role: [permission, ...]}, a role
|
||||
// not in it holding its defaults above. one staff member can be given more
|
||||
// than their role, or less (`permGrants`, `permDenies` on the account, from
|
||||
// their page in the admin panel). a role and 2FA are still what makes
|
||||
// someone staff at all (isActiveStaff).
|
||||
const ROLE_SETTING = "rolePermissions";
|
||||
let roleOverrides = null;
|
||||
|
||||
const overrides = () => {
|
||||
if (!roleOverrides) {
|
||||
try {
|
||||
const saved = JSON.parse(accounts.setting(ROLE_SETTING) || "{}");
|
||||
roleOverrides = saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
|
||||
}
|
||||
catch {
|
||||
roleOverrides = {};
|
||||
}
|
||||
}
|
||||
return roleOverrides;
|
||||
};
|
||||
|
||||
// the permissions in a list that are ones, each once
|
||||
const known = list => [...new Set(Array.isArray(list) ? list.map(String) : [])].filter(permission => Object.hasOwn(PERMISSIONS, permission));
|
||||
|
||||
const rolePermissions = role => (Object.hasOwn(overrides(), role) ? known(overrides()[role]) : [...ROLES[role].permissions]);
|
||||
|
||||
const roleChanged = role => Object.hasOwn(overrides(), role);
|
||||
|
||||
// a role's permissions, or its defaults again (`list` null). false for no such role.
|
||||
const setRolePermissions = (role, list) => {
|
||||
if (!Object.hasOwn(ROLES, role)) {
|
||||
return false;
|
||||
}
|
||||
const changed = {...overrides()};
|
||||
if (list === null) {
|
||||
delete changed[role];
|
||||
}
|
||||
else {
|
||||
changed[role] = known(list);
|
||||
}
|
||||
accounts.setSetting(ROLE_SETTING, JSON.stringify(changed));
|
||||
roleOverrides = changed;
|
||||
return true;
|
||||
};
|
||||
|
||||
const permissionsOf = account => {
|
||||
const role = roleOf(account);
|
||||
return role ? [...ROLES[role].permissions] : [];
|
||||
if (!role) {
|
||||
return [];
|
||||
}
|
||||
const denied = new Set(known(account.permDenies));
|
||||
return [...new Set([...rolePermissions(role), ...known(account.permGrants)])].filter(permission => !denied.has(permission));
|
||||
};
|
||||
|
||||
// one staff member's own: given beyond their role, and taken from it. a
|
||||
// permission in both is given. the caller saves the account.
|
||||
const setAccountPermissions = (account, grants, denies) => {
|
||||
const given = known(grants);
|
||||
const taken = known(denies).filter(permission => !given.includes(permission));
|
||||
if (given.length) {
|
||||
account.permGrants = given;
|
||||
}
|
||||
else {
|
||||
delete account.permGrants;
|
||||
}
|
||||
if (taken.length) {
|
||||
account.permDenies = taken;
|
||||
}
|
||||
else {
|
||||
delete account.permDenies;
|
||||
}
|
||||
};
|
||||
|
||||
const can = (account, permission, banned = false) =>
|
||||
isActiveStaff(account, banned) && ROLES[roleOf(account)].permissions.includes(permission);
|
||||
isActiveStaff(account, banned) && permissionsOf(account).includes(permission);
|
||||
|
||||
// may `actor` act on `target`? never on themselves, nor on staff of their
|
||||
// own rank or above.
|
||||
@@ -91,4 +163,5 @@ const setRole = (account, role) => {
|
||||
return true;
|
||||
};
|
||||
|
||||
module.exports = {PERMISSIONS, ROLES, roleOf, rankOf, isActiveStaff, permissionsOf, can, outranks, setRole};
|
||||
module.exports = {PERMISSIONS, ROLES, roleOf, rankOf, isActiveStaff, permissionsOf, rolePermissions, roleChanged, setRolePermissions,
|
||||
setAccountPermissions, can, outranks, setRole};
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const zlib = require("zlib");
|
||||
const amf3 = require("./amf3.js");
|
||||
const cdn = require("./cdn.js");
|
||||
@@ -71,7 +72,7 @@ const preload = async () => {
|
||||
remember(base, body);
|
||||
}
|
||||
}
|
||||
console.log(`[rooms] names of ${rooms.size} rooms read from the cache`);
|
||||
console.log(`[rooms] names of ${logText(rooms.size)} rooms read from the cache`);
|
||||
};
|
||||
|
||||
// A name made from the path, for a room not read yet or left unnamed:
|
||||
|
||||
+11
-10
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const net = require("net");
|
||||
@@ -49,7 +50,7 @@ class Session {
|
||||
write(message) {
|
||||
if (this.socket.writable) {
|
||||
if (config.logPackets) {
|
||||
console.log(`[game] -> ${this.name} ${message}`);
|
||||
console.log(`[game] -> ${logText(this.name)} ${logText(message)}`);
|
||||
}
|
||||
this.socket.write(message + "\0");
|
||||
// A client that stopped reading must not pile up messages here forever.
|
||||
@@ -96,7 +97,7 @@ const parseSys = message => {
|
||||
const start = handlers => new Promise((resolve, reject) => {
|
||||
const dispatch = (session, message) => {
|
||||
if (config.logPackets) {
|
||||
console.log(`[game] <- ${session.name} ${forLog(message)}`);
|
||||
console.log(`[game] <- ${logText(session.name)} ${logText(forLog(message))}`);
|
||||
}
|
||||
if (message.startsWith("<policy-file-request")) {
|
||||
session.socket.end(POLICY + "\0");
|
||||
@@ -153,7 +154,7 @@ const start = handlers => new Promise((resolve, reject) => {
|
||||
let bytesInWindow = 0;
|
||||
let errorsInWindow = 0;
|
||||
socket.setNoDelay(true);
|
||||
console.log(`[game] ${session.remote} connected as #${session.id}`);
|
||||
console.log(`[game] ${logText(session.remote)} connected as #${logText(session.id)}`);
|
||||
|
||||
// whoever connects has to log in (or start signing up) promptly, and
|
||||
// nobody may sit silent for long: the client sends keep-alives.
|
||||
@@ -178,7 +179,7 @@ const start = handlers => new Promise((resolve, reject) => {
|
||||
}
|
||||
bytesInWindow += chunk.length;
|
||||
if (bytesInWindow > config.maxBytesPerTenSeconds) {
|
||||
console.log(`[game] ${session.name} disconnected for flooding`);
|
||||
console.log(`[game] ${logText(session.name)} disconnected for flooding`);
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
@@ -190,7 +191,7 @@ const start = handlers => new Promise((resolve, reject) => {
|
||||
return;
|
||||
}
|
||||
if (++messagesInWindow > config.maxMessagesPerTenSeconds) {
|
||||
console.log(`[game] ${session.name} disconnected for flooding`);
|
||||
console.log(`[game] ${logText(session.name)} disconnected for flooding`);
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
@@ -203,9 +204,9 @@ const start = handlers => new Promise((resolve, reject) => {
|
||||
// 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] || "";
|
||||
console.log(`[game] error handling message from ${session.name}: ${err.message}${where ? ` (${where.trim()})` : ""}`);
|
||||
console.log(`[game] error handling message from ${logText(session.name)}: ${logText(err.message)}${logText(where ? ` (${where.trim()})` : "")}`);
|
||||
if (++errorsInWindow > MAX_ERRORS_PER_WINDOW) {
|
||||
console.log(`[game] ${session.name} disconnected: too many messages that could not be handled`);
|
||||
console.log(`[game] ${logText(session.name)} disconnected: too many messages that could not be handled`);
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
@@ -228,13 +229,13 @@ const start = handlers => new Promise((resolve, reject) => {
|
||||
else {
|
||||
connections.delete(address);
|
||||
}
|
||||
console.log(`[game] ${session.name} disconnected`);
|
||||
console.log(`[game] ${logText(session.name)} disconnected`);
|
||||
// nothing thrown while a player is seen off may take the server down.
|
||||
try {
|
||||
handlers.close(session);
|
||||
}
|
||||
catch (err) {
|
||||
console.log(`[game] error while ${session.name} left: ${err.stack}`);
|
||||
console.log(`[game] error while ${logText(session.name)} left: ${logText(err.stack)}`);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -271,7 +272,7 @@ const start = handlers => new Promise((resolve, reject) => {
|
||||
}
|
||||
server.once("error", reject);
|
||||
server.listen(config.gamePort, config.gameBindAddress, () => {
|
||||
console.log(`[game] listening on ${config.gameBindAddress}:${config.gamePort}${config.tls ? " (TLS)" : ""}`);
|
||||
console.log(`[game] listening on ${logText(config.gameBindAddress)}:${logText(config.gamePort)}${logText(config.tls ? " (TLS)" : "")}`);
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
|
||||
+3
-1
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const crypto = require("crypto");
|
||||
const accounts = require("./accounts.js");
|
||||
const bans = require("./bans.js");
|
||||
@@ -24,6 +25,7 @@ const STATUS = {
|
||||
username_taken: USERNAME_TAKEN,
|
||||
invalid_username: USERNAME_INVALID,
|
||||
invalid_password: PASSWORD_INVALID,
|
||||
weak_password: PASSWORD_INVALID, // the game's screens have one word for both
|
||||
name_not_allowed: USERNAME_INVALID,
|
||||
};
|
||||
// names asked about on one guest connection: the screens ask once or twice.
|
||||
@@ -88,7 +90,7 @@ const handlers = {
|
||||
return;
|
||||
}
|
||||
if (!limits.registrationAllowed(session.address, limits.isTrustedLocal(session.address))) {
|
||||
console.log(`[signup] too many sign-ups from ${session.address}`);
|
||||
console.log(`[signup] too many sign-ups from ${logText(session.address)}`);
|
||||
session.sendXt("lc", -1, FAILED, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const accounts = require("./accounts.js");
|
||||
|
||||
// what players send from the account page (/account, lib/manage.js) for
|
||||
@@ -79,7 +80,7 @@ const requestName = (account, newName, reason) => {
|
||||
db().prepare("UPDATE name_requests SET status = ?, handled_at = ? WHERE account_id = ? AND status = ?").run(WITHDRAWN, now(), account.id, WAITING);
|
||||
db().prepare("INSERT INTO name_requests (created_at, account_id, old_name, new_name, reason) VALUES (?, ?, ?, ?, ?)")
|
||||
.run(now(), account.id, account.username, newName, clean(reason, MAX_REASON));
|
||||
console.log(`[support] "${account.username}" asked to be called "${newName}"`);
|
||||
console.log(`[support] "${logText(account.username)}" asked to be called "${logText(newName)}"`);
|
||||
return {request: waitingNameRequest(account)};
|
||||
};
|
||||
|
||||
@@ -127,7 +128,7 @@ const sendFeedback = (account, kind, text) => {
|
||||
return {error: "too_many"};
|
||||
}
|
||||
db().prepare("INSERT INTO feedback (created_at, account_id, username, kind, text) VALUES (?, ?, ?, ?, ?)").run(now(), account.id, account.username, kind, body);
|
||||
console.log(`[support] ${kind === "bug" ? "bug report" : "feedback"} from "${account.username}"`);
|
||||
console.log(`[support] ${logText(kind === "bug" ? "bug report" : "feedback")} from "${logText(account.username)}"`);
|
||||
return {ok: true};
|
||||
};
|
||||
|
||||
|
||||
+11
-2
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
@@ -73,6 +74,14 @@ const flat = value => scalar(value) || (typeof value === "object" && !Array.isAr
|
||||
&& Object.keys(value).length <= 12 && Object.values(value).every(scalar));
|
||||
const plainParam = value => flat(value) || (Array.isArray(value) && value.length <= MAX_PARAM_ENTRIES && value.every(flat));
|
||||
const whole = value => (Number.isInteger(Number(value)) ? Number(value) : 0);
|
||||
// the photo booth picture ("pb", PlayerWallGui): one level deeper than the
|
||||
// rest, {avatar: {id, color1.., eyes, pattern}, bgid, pet: {ts, lbits, ..} |
|
||||
// null, items: [{id, color}, ..]}. it was turned away as too deep, and the
|
||||
// owner's whole change with it: the photo never stayed.
|
||||
const MAX_PHOTO_ITEMS = 30;
|
||||
const photoParam = value => value === null || (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length <= 6
|
||||
&& Object.entries(value).every(([key, part]) => (key === "items" ? Array.isArray(part) && part.length <= MAX_PHOTO_ITEMS && part.every(flat)
|
||||
: key === "avatar" || key === "pet" ? part === null || flat(part) : scalar(part))));
|
||||
|
||||
module.exports = ({blocks, findOnline}) => {
|
||||
const tokens = new Map(); // token -> {viewer: account id, owner: account id, expires}
|
||||
@@ -155,7 +164,7 @@ module.exports = ({blocks, findOnline}) => {
|
||||
// the server's filter (lib/chatfilter.js) too.
|
||||
const rule = message ? chatFilter.broken(message) : null;
|
||||
if (rule) {
|
||||
console.log(`[filter] ${viewer.username} on ${owner.username}'s wall: "${message}" (${rule})`);
|
||||
console.log(`[filter] ${logText(viewer.username)} on ${logText(owner.username)}'s wall: "${logText(message)}" (${logText(rule)})`);
|
||||
chatlog.recordTo(viewer, chatlog.WALL, owner.username, chatlog.NOT_SENT + message);
|
||||
const session = findOnline(viewer.username);
|
||||
if (session) {
|
||||
@@ -325,7 +334,7 @@ module.exports = ({blocks, findOnline}) => {
|
||||
const merged = changes && typeof changes === "object" && !Array.isArray(changes) ? {...wall.params} : null;
|
||||
for (const key of merged ? OWNER_PARAMS : []) {
|
||||
if (changes[key] !== undefined) {
|
||||
if (!plainParam(changes[key])) {
|
||||
if (!(key === "pb" ? photoParam(changes[key]) : plainParam(changes[key]))) {
|
||||
session.sendXt("wps", -1, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
+170
-24
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const {logText} = require("./logtext.js");
|
||||
const accounts = require("./accounts.js");
|
||||
const achievements = require("./achievements.js");
|
||||
const adopt = require("./adopt.js");
|
||||
@@ -7,6 +8,8 @@ const config = require("../config.js");
|
||||
const colours = require("./colours.js");
|
||||
const customItems = require("./customitems.js");
|
||||
const roles = require("./roles.js");
|
||||
const modlog = require("./modlog.js");
|
||||
const playerItems = require("./playeritems.js");
|
||||
const commandModule = require("./commands.js");
|
||||
const limits = require("./limits.js");
|
||||
const masterpieces = require("./masterpieces.js");
|
||||
@@ -17,6 +20,7 @@ const bans = require("./bans.js");
|
||||
const devices = require("./devices.js");
|
||||
const chatlog = require("./chatlog.js");
|
||||
const chatFilter = require("./chatfilter.js");
|
||||
const chatSpam = require("./chatspam.js");
|
||||
const buddyModule = require("./buddies.js");
|
||||
const dens = require("./dens.js");
|
||||
const disguises = require("./disguises.js");
|
||||
@@ -37,7 +41,7 @@ const stubHandlers = require("./stubs.js");
|
||||
const wallModule = require("./walls.js");
|
||||
const worldItems = require("./worlditems.js");
|
||||
const stats = require("./stats.js");
|
||||
const {CURRENCIES, DIAMOND_TYPES, activeAvatar, avatarById, activePet, equippedBits, wornItems, lastSeenField} = require("./player.js");
|
||||
const {CURRENCIES, DIAMOND_TYPES, activeAvatar, avatarById, activePet, equippedBits, wornItems, lastSeenField, sendClothingRemoved} = require("./player.js");
|
||||
|
||||
// game logic behind the socket. field orders below mirror the client's
|
||||
// parsers; the class that reads each message is named next to it.
|
||||
@@ -172,9 +176,12 @@ const blocks = {
|
||||
has: (blocker, target) => blocker.blocked.includes(nameKey(target)),
|
||||
either: (a, b) => a.blocked.includes(nameKey(b)) || b.blocked.includes(nameKey(a)),
|
||||
};
|
||||
const sees = (viewer, subject) => !(viewer.account.hideBlocked && blocks.has(viewer.account, subject.account));
|
||||
// staff gone invisible (setInvisible, below) are drawn for staff only.
|
||||
const sees = (viewer, subject) => (!subject.invisible || roles.isActiveStaff(viewer.account))
|
||||
&& !(viewer.account.hideBlocked && blocks.has(viewer.account, subject.account));
|
||||
// everyone else in the room who should hear about this player's animal.
|
||||
const watchers = session => others(session).filter(other => sees(other, session));
|
||||
const TYPING_EVERY_MS = 2000; // "typing" passed on at most this often per player (xty)
|
||||
|
||||
const decodeEntities = text => text
|
||||
.replace(/</g, "<")
|
||||
@@ -274,44 +281,44 @@ const login = (session, msg) => {
|
||||
const username = (msg.cdata("nick") || "").split("%")[0];
|
||||
const account = accounts.byToken(msg.cdata("pword"));
|
||||
if (!account || account.username.toLowerCase() !== username.toLowerCase()) {
|
||||
console.log(`[world] login rejected for "${username}"`);
|
||||
console.log(`[world] login rejected for "${logText(username)}"`);
|
||||
loginFailed(session, 0, "Invalid login");
|
||||
return;
|
||||
}
|
||||
if (moderation.banRemaining(account) !== 0) {
|
||||
console.log(`[world] login rejected for banned account "${account.username}"`);
|
||||
console.log(`[world] login rejected for banned account "${logText(account.username)}"`);
|
||||
loginFailed(session, LOGIN_BANNED, "Banned");
|
||||
return;
|
||||
}
|
||||
// A banned address (lib/bans.js). the client is told at /authenticate,
|
||||
// with the reason; this is for a game that got here another way.
|
||||
if (bans.addressBan(session.address)) {
|
||||
console.log(`[world] login rejected for "${account.username}" from a banned address`);
|
||||
console.log(`[world] login rejected for "${logText(account.username)}" from a banned address`);
|
||||
loginFailed(session, LOGIN_BANNED, "Banned");
|
||||
return;
|
||||
}
|
||||
// a banned computer (lib/devices.js), and a game that never said which
|
||||
// computer it is on: told at /authenticate too, which is the way in.
|
||||
if (devices.banOfAccount(account)) {
|
||||
console.log(`[world] login rejected for "${account.username}": hardware banned`);
|
||||
console.log(`[world] login rejected for "${logText(account.username)}": hardware banned`);
|
||||
loginFailed(session, LOGIN_BANNED, "Banned");
|
||||
return;
|
||||
}
|
||||
if (config.requireDevice && devices.knownFor(account).lastAt < Math.floor(Date.now() / 1000) - 90 * 86400) {
|
||||
console.log(`[world] login rejected for "${account.username}": no device ids`);
|
||||
console.log(`[world] login rejected for "${logText(account.username)}": no device ids`);
|
||||
loginFailed(session, 0, "Update the client");
|
||||
return;
|
||||
}
|
||||
// its username was rejected (lib/moderation.js): a new one first, which
|
||||
// the client or the account page asks for.
|
||||
if (account.nameRejected) {
|
||||
console.log(`[world] login rejected for "${account.username}": the name was rejected`);
|
||||
console.log(`[world] login rejected for "${logText(account.username)}": the name was rejected`);
|
||||
loginFailed(session, 0, "Username rejected");
|
||||
return;
|
||||
}
|
||||
// locked by its owner on the account page (lib/manage.js).
|
||||
if (account.locked) {
|
||||
console.log(`[world] login rejected for locked account "${account.username}"`);
|
||||
console.log(`[world] login rejected for locked account "${logText(account.username)}"`);
|
||||
loginFailed(session, 0, "Account locked");
|
||||
return;
|
||||
}
|
||||
@@ -343,7 +350,7 @@ const login = (session, msg) => {
|
||||
achievements.refresh(account);
|
||||
accounts.save(account);
|
||||
online.set(key, session);
|
||||
console.log(`[world] ${account.username} logged in as sfs user ${session.id}`);
|
||||
console.log(`[world] ${logText(account.username)} logged in as sfs user ${logText(session.id)}`);
|
||||
session.sendXtJson(-1, {_cmd: "login", status: "1", params: loginParams(session)});
|
||||
// every custom colour, before anything that might be drawn with one
|
||||
// (XtReplyDemuxer -> PaletteHelper.handleCustomColors in the patched SWF).
|
||||
@@ -426,6 +433,9 @@ const sendAvatarCreate = (to, target) => {
|
||||
...(pet ? petFields(pet) : []));
|
||||
sendItemList(to, target, false);
|
||||
disguises.show(to, target);
|
||||
if (target.invisible) {
|
||||
to.sendXt("xiv", -1, target.id, 1);
|
||||
}
|
||||
};
|
||||
|
||||
// redraws `session`'s animal for everyone else in the room, for changes the
|
||||
@@ -646,8 +656,12 @@ const handlers = {
|
||||
}
|
||||
}
|
||||
if (firstUpdate) {
|
||||
// the player's own animal is on their screen now: its disguise, if any.
|
||||
// the player's own animal is on their screen now: its disguise, if any,
|
||||
// and see-through if they are invisible.
|
||||
disguises.show(session, session);
|
||||
if (session.invisible) {
|
||||
session.sendXt("xiv", -1, session.id, 1);
|
||||
}
|
||||
}
|
||||
for (const other of watchers(session)) {
|
||||
if (firstUpdate) {
|
||||
@@ -655,7 +669,6 @@ const handlers = {
|
||||
sendAvatarCreate(other, session);
|
||||
}
|
||||
else {
|
||||
// AvatarManager.avatarUpdateResponse
|
||||
other.sendXt("au", session.room.id, 1, session.id, count, ...coords, teleport);
|
||||
}
|
||||
}
|
||||
@@ -881,6 +894,30 @@ const handlers = {
|
||||
}
|
||||
},
|
||||
|
||||
// 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
|
||||
// it again every few seconds while typing; more often is not passed on.
|
||||
xty(session, roomId, [on]) {
|
||||
const typing = on === "1";
|
||||
const now = Date.now();
|
||||
if (!session.room || session.invisible || (typing && session.typingAt && now - session.typingAt < TYPING_EVERY_MS)
|
||||
|| (!typing && !session.typingAt)) {
|
||||
return;
|
||||
}
|
||||
session.typingAt = typing ? now : 0;
|
||||
for (const other of watchers(session)) {
|
||||
other.sendXt("xty", -1, session.id, typing ? 1 : 0);
|
||||
}
|
||||
},
|
||||
|
||||
// the patched client's staff window: going invisible, or being seen again.
|
||||
xiv(session) {
|
||||
if (session.invisible || roles.can(session.account, "staff.invisible")) {
|
||||
setInvisible(session, !session.invisible);
|
||||
}
|
||||
},
|
||||
|
||||
// the patched report window (gui.ReportAPlayer), just before its "fr" or
|
||||
// "fra": [username, reasonId, what the reporter typed].
|
||||
xrd(session, roomId, [username, reason, ...text]) {
|
||||
@@ -987,10 +1024,83 @@ const fileReport = (session, username, reason, detail = "", about = "") => {
|
||||
|
||||
// what the modules below may use of this one. `others` here is everyone who
|
||||
// should see the player's animal change; dens get everyone in the room.
|
||||
// invisible staff (the "staff.invisible" permission): their animal is drawn
|
||||
// for staff only, half see-through ("xiv" [.., .., sfsId, 1 | 0], for the
|
||||
// patched client), on their own screen too. the game's own invisible mode
|
||||
// ("fi") is not used: with it the client stops sending where it walks, and
|
||||
// staff could not see them move. they say nothing while invisible (pubMsg).
|
||||
const setInvisible = (session, invisible) => {
|
||||
if (Boolean(session.invisible) === invisible) {
|
||||
return;
|
||||
}
|
||||
const {room} = session;
|
||||
const shown = Boolean(room && session.pos);
|
||||
const before = shown ? watchers(session) : [];
|
||||
session.invisible = invisible;
|
||||
const after = shown ? watchers(session) : [];
|
||||
for (const other of before.filter(other => !after.includes(other))) {
|
||||
other.sendXt("ar", room.id, session.id);
|
||||
}
|
||||
for (const other of after) {
|
||||
if (before.includes(other)) {
|
||||
other.sendXt("xiv", -1, session.id, invisible ? 1 : 0);
|
||||
}
|
||||
else {
|
||||
sendAvatarCreate(other, session);
|
||||
}
|
||||
}
|
||||
if (shown) {
|
||||
session.sendXt("xiv", -1, session.id, invisible ? 1 : 0);
|
||||
}
|
||||
// the patched client's message box, as the staff commands answer in
|
||||
session.sendXt("xtl", -1, invisible ? "You are invisible: only staff see you, and you cannot chat. Say !invisible again to be seen."
|
||||
: "You can be seen again.");
|
||||
modlog.record(session.account.username, invisible ? "went invisible (in game)" : "became visible (in game)", "", room ? room.name : "");
|
||||
};
|
||||
|
||||
// what an account's game knows of its staff role ("xsp", AJClient.onStaff),
|
||||
// sent again when the admin changed it: nothing for one no longer staff.
|
||||
// one that may no longer go invisible is seen again.
|
||||
const refreshStaff = account => {
|
||||
const session = findOnline(account.username);
|
||||
if (!session) {
|
||||
return;
|
||||
}
|
||||
const active = roles.isActiveStaff(account);
|
||||
session.sendXt("xsp", -1, active ? roles.roleOf(account) : "", active ? roles.permissionsOf(account).join(",") : "");
|
||||
if (session.invisible && !roles.can(account, "staff.invisible")) {
|
||||
setInvisible(session, false);
|
||||
}
|
||||
};
|
||||
|
||||
// items taken from an account (lib/itemcontrol.js): its game, if playing,
|
||||
// and anybody in its den are told. `worn`: clothing it had on went too.
|
||||
const itemsTaken = (account, kind, invs, worn) => {
|
||||
const session = findOnline(account.username);
|
||||
if (session && kind === "den") {
|
||||
dens.sendDenItems(session);
|
||||
}
|
||||
else if (session) {
|
||||
sendClothingRemoved(session, invs);
|
||||
if (worn) {
|
||||
sendItemList(session, session, false);
|
||||
refreshForOthers(session);
|
||||
}
|
||||
}
|
||||
const den = kind === "den" ? rooms.get(`den${account.username}`) : null;
|
||||
for (const other of den ? den.sessions : []) {
|
||||
dens.sendDenState(other, 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.
|
||||
// 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,
|
||||
// it is the room's usual spawn.
|
||||
const staffMove = (whoName, toName) => {
|
||||
const who = findOnline(whoName);
|
||||
const to = findOnline(toName);
|
||||
@@ -1002,14 +1112,28 @@ const staffMove = (whoName, toName) => {
|
||||
}
|
||||
const room = to.room;
|
||||
const shown = room.displayName || room.name;
|
||||
const spot = to.pos ? [to.pos.x, to.pos.y] : null;
|
||||
if (who.room === room) {
|
||||
return {error: "Already in the same room."};
|
||||
if (!spot) {
|
||||
return {error: "Already in the same room."};
|
||||
}
|
||||
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);
|
||||
}
|
||||
joinRoom(who, room.name);
|
||||
return who.room === room ? {ok: true, room: shown} : {error: `Could not get into ${shown}.`};
|
||||
if (who.room !== room) {
|
||||
if (spot) {
|
||||
who.sendXt("xgt", -1);
|
||||
}
|
||||
return {error: `Could not get into ${shown}.`};
|
||||
}
|
||||
return {ok: true, room: shown};
|
||||
};
|
||||
|
||||
const context = {
|
||||
@@ -1036,6 +1160,7 @@ const context = {
|
||||
worldName,
|
||||
joinRoom: (...args) => joinRoom(...args),
|
||||
staffMove: (...args) => staffMove(...args),
|
||||
setInvisible: (...args) => setInvisible(...args),
|
||||
// the moderation module, made after this context (lib/commands.js uses it)
|
||||
staffModeration: () => moderation,
|
||||
reloadRoom: session => reloadRoom(session),
|
||||
@@ -1054,7 +1179,8 @@ const trades = tradeHandlers(context);
|
||||
achievements.setFinder(findOnline);
|
||||
Object.assign(handlers, avatarHandlers(context), itemHandlers(context), pets.handlers, dens.handlers({...context, others}),
|
||||
buddies.handlers, moderation.handlers, trades.handlers, achievements.handlers, adopt.handlers, worldItems.handlers,
|
||||
parties.handlers, ecards.handlers, walls.handlers, minigames.handlers, adventures.handlers, stubHandlers);
|
||||
parties.handlers, ecards.handlers, walls.handlers, minigames.handlers, adventures.handlers, stubHandlers,
|
||||
playerItems.handlers({itemsTaken: (...args) => itemsTaken(...args)}));
|
||||
|
||||
const leaveRoom = session => {
|
||||
const {room} = session;
|
||||
@@ -1189,7 +1315,7 @@ const setTheme = (account, theme) => {
|
||||
|
||||
// RoomXtCommManager.roomJoinResponse failure branch
|
||||
const joinFailed = (session, reason) => {
|
||||
console.log(`[world] ${session.name} could not join: ${reason}`);
|
||||
console.log(`[world] ${logText(session.name)} could not join: ${logText(reason)}`);
|
||||
session.sendXt("rj", -1, 0, reason);
|
||||
};
|
||||
|
||||
@@ -1462,7 +1588,7 @@ const unhandled = (cmd, params) => {
|
||||
const key = cmd === "gl" ? `gl ${params[0]}` : cmd;
|
||||
if (!seenUnhandled.has(key) && seenUnhandled.size < 500) {
|
||||
seenUnhandled.add(key);
|
||||
console.log(`[world] no handler for xt "${key}" (params: ${JSON.stringify(params).slice(0, 200)}) - the client gets no reply`);
|
||||
console.log(`[world] no handler for xt "${logText(key)}" (params: ${logText(JSON.stringify(params).slice(0, 200))}) - the client gets no reply`);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1527,25 +1653,43 @@ module.exports = {
|
||||
session.sendXt("uc", session.room.id, session.id, ...fields);
|
||||
return;
|
||||
}
|
||||
fields[0] = said;
|
||||
// invisible staff give commands and say nothing: the bubble
|
||||
// waiting goes, as for a silenced player.
|
||||
if (session.invisible) {
|
||||
session.sendXt("uc", session.room.id, session.id, -1, 5);
|
||||
return;
|
||||
}
|
||||
// how much there is of it (lib/chatspam.js): a key held down, a
|
||||
// word over and over, shouting, a wall of emoji are cut down; the
|
||||
// same line again and again is not sent.
|
||||
const line = chatSpam.tidy(said);
|
||||
if (!line || chatSpam.repeated(session, line)) {
|
||||
session.sendXt("uc", session.room.id, session.id, -1, 5);
|
||||
return;
|
||||
}
|
||||
fields[0] = line;
|
||||
// the server's filter (lib/chatfilter.js): the line reaches
|
||||
// nobody, the sender sees the game's warning screen, and it is
|
||||
// kept in the chat log for the moderators, marked as not sent.
|
||||
const rule = chatFilter.broken(said);
|
||||
const rule = chatFilter.broken(line);
|
||||
if (rule) {
|
||||
session.sendXt("uc", session.room.id, session.id, -1, 5);
|
||||
chatFilter.warn(session);
|
||||
chatlog.record(session.account, session.room.name, `(not sent) ${said}`);
|
||||
console.log(`[filter] ${session.name} in ${session.room.name}: "${said}" (${rule})`);
|
||||
chatlog.record(session.account, session.room.name, `(not sent) ${line}`);
|
||||
console.log(`[filter] ${logText(session.name)} in ${logText(session.room.name)}: "${logText(line)}" (${logText(rule)})`);
|
||||
return;
|
||||
}
|
||||
session.recentChat.push(`${new Date().toISOString().slice(11, 19)} ${said}`);
|
||||
session.recentChat.push(`${new Date().toISOString().slice(11, 19)} ${line}`);
|
||||
session.recentChat = session.recentChat.slice(-RECENT_CHAT_LINES);
|
||||
chatlog.record(session.account, session.room.name, said);
|
||||
chatlog.record(session.account, session.room.name, line);
|
||||
}
|
||||
// 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)) {
|
||||
if (session.invisible && recipient !== session && !roles.isActiveStaff(recipient.account)) {
|
||||
continue;
|
||||
}
|
||||
if (recipient === session || (!blocks.has(recipient.account, session.account) && (!echo || accounts.featureOn(recipient.account, "chat")))) {
|
||||
recipient.sendXt("uc", session.room.id, session.id, ...fields);
|
||||
}
|
||||
@@ -1557,7 +1701,7 @@ module.exports = {
|
||||
session.close();
|
||||
return;
|
||||
default:
|
||||
console.log(`[world] unhandled sys "${msg.action}" from ${session.name}`);
|
||||
console.log(`[world] unhandled sys "${logText(msg.action)}" from ${logText(session.name)}`);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1624,6 +1768,8 @@ module.exports = {
|
||||
},
|
||||
moderation,
|
||||
staffMove,
|
||||
itemsTaken,
|
||||
refreshStaff,
|
||||
walls,
|
||||
ecards,
|
||||
// called when the admin changed an account's badges: a name tag showing
|
||||
|
||||
+22
-22
@@ -44,7 +44,7 @@ const panel = page("admin");
|
||||
|
||||
const run = async () => {
|
||||
const register = (username, avatarType) => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify({username, password: "Password01", avatarType, agreed: true})});
|
||||
body: JSON.stringify({username, password: "KettlePass01", avatarType, agreed: true})});
|
||||
assert.strictEqual((await register("Ann", 4)).status, 200);
|
||||
assert.strictEqual((await register("Ben", 24)).status, 200);
|
||||
// what a client shows beside its login form.
|
||||
@@ -55,8 +55,8 @@ const run = async () => {
|
||||
assert.match(await (await fetch(`${BASE}/account`)).text(), /Your account/);
|
||||
assert.strictEqual((await mine("me")).status, 401);
|
||||
assert.strictEqual((await mine("login", {username: "Ann", password: "wrong"})).status, 401);
|
||||
assert.strictEqual((await mine("login", {username: "Nobody", password: "Password01"})).status, 401);
|
||||
const signedIn = await mine("login", {username: "ann", password: "Password01"});
|
||||
assert.strictEqual((await mine("login", {username: "Nobody", password: "KettlePass01"})).status, 401);
|
||||
const signedIn = await mine("login", {username: "ann", password: "KettlePass01"});
|
||||
assert.strictEqual(signedIn.status, 200);
|
||||
assert.match(signedIn.cookie, /^ajc_account=[0-9a-f]{48}$/);
|
||||
const ann = signedIn.cookie;
|
||||
@@ -67,8 +67,8 @@ const run = async () => {
|
||||
assert.deepStrictEqual(me.history.map(login => [login.via, login.ok]), [["web", true], ["web", false]]);
|
||||
|
||||
// --- parts of the game switched off
|
||||
const {client: a, roomId} = await arrive("Ann", "Password01");
|
||||
const {client: b} = await arrive("Ben", "Password01");
|
||||
const {client: a, roomId} = await arrive("Ann", "KettlePass01");
|
||||
const {client: b} = await arrive("Ben", "KettlePass01");
|
||||
await a.untilXt("ac");
|
||||
const set = async (feature, on) => assert.strictEqual((await mine("act", {action: "feature", feature, on}, ann)).status, 200);
|
||||
assert.strictEqual((await mine("act", {action: "feature", feature: "flying", on: false}, ann)).status, 400);
|
||||
@@ -144,7 +144,7 @@ const run = async () => {
|
||||
}
|
||||
b.xt("ts", roomId, 0, 1, 0, benHas[9]); // ben puts his scarf up for trade, in the game
|
||||
await b.untilXt("tl");
|
||||
const benPageCookie = (await mine("login", {username: "Ben", password: "Password01"})).cookie;
|
||||
const benPageCookie = (await mine("login", {username: "Ben", password: "KettlePass01"})).cookie;
|
||||
const tradable = (await mine("tradable?of=ben", undefined, ann)).data;
|
||||
assert.deepStrictEqual([tradable.found, tradable.theirs.map(item => item.name), tradable.mine.map(item => item.name)], [true, [scarfName], [hatName]]);
|
||||
assert.strictEqual((await mine("act", {action: "offer", to: "Ben", wanted: tradable.theirs[0], offered: []}, ann)).status, 400);
|
||||
@@ -182,27 +182,27 @@ const run = async () => {
|
||||
assert.strictEqual((await panel("support", {action: "approve", id: waiting.names[0].id}, admin)).status, 200);
|
||||
assert.strictEqual((await panel("support", {action: "approve", id: waiting.names[0].id}, admin)).status, 400); // only once
|
||||
assert.strictEqual((await mine("me", undefined, ann)).status, 401); // renamed: sign in again, with the new name
|
||||
assert.strictEqual((await authenticate("Ann", "Password01")).status, 401);
|
||||
const annabel = (await mine("login", {username: "Annabel", password: "Password01"})).cookie;
|
||||
assert.strictEqual((await authenticate("Ann", "KettlePass01")).status, 401);
|
||||
const annabel = (await mine("login", {username: "Annabel", password: "KettlePass01"})).cookie;
|
||||
me = (await mine("me", undefined, annabel)).data;
|
||||
assert.deepStrictEqual([me.username, me.nameRequests[0].status, me.feedback[0].handledAt > 0], ["Annabel", "approved", true]);
|
||||
|
||||
// --- the lock: out of the game, and no way back in until it is undone
|
||||
const {token} = await arrive("Annabel", "Password01");
|
||||
const {token} = await arrive("Annabel", "KettlePass01");
|
||||
assert.strictEqual((await mine("act", {action: "lock", locked: true}, annabel)).status, 200);
|
||||
assert.strictEqual((await authenticate("Annabel", "Password01")).status, 401);
|
||||
assert.strictEqual((await authenticate("Annabel", "KettlePass01")).status, 401);
|
||||
assert.strictEqual((await postJson(`${BASE}/authenticate`, {refresh_token: token})).status, 401); // the saved sign-in is gone
|
||||
assert.strictEqual((await panel("accounts", undefined, admin)).data.accounts.find(account => account.username === "Annabel").locked, true);
|
||||
assert.strictEqual((await mine("login", {username: "Annabel", password: "Password01"})).status, 200); // the page still lets her in
|
||||
assert.strictEqual((await mine("login", {username: "Annabel", password: "KettlePass01"})).status, 200); // the page still lets her in
|
||||
assert.strictEqual((await mine("act", {action: "lock", locked: false}, annabel)).status, 200);
|
||||
assert.strictEqual((await authenticate("Annabel", "Password01")).status, 200);
|
||||
assert.strictEqual((await authenticate("Annabel", "KettlePass01")).status, 200);
|
||||
|
||||
// --- the password: the old one is asked for, and stops working
|
||||
assert.strictEqual((await mine("act", {action: "password", current: "wrong", password: "Password02"}, annabel)).status, 400);
|
||||
assert.strictEqual((await mine("act", {action: "password", current: "Password01", password: "short"}, annabel)).status, 400);
|
||||
assert.strictEqual((await mine("act", {action: "password", current: "Password01", password: "Password02"}, annabel)).status, 200);
|
||||
assert.strictEqual((await authenticate("Annabel", "Password01")).status, 401);
|
||||
assert.strictEqual((await authenticate("Annabel", "Password02")).status, 200);
|
||||
assert.strictEqual((await mine("act", {action: "password", current: "wrong", password: "KettlePass02"}, annabel)).status, 400);
|
||||
assert.strictEqual((await mine("act", {action: "password", current: "KettlePass01", password: "short"}, annabel)).status, 400);
|
||||
assert.strictEqual((await mine("act", {action: "password", current: "KettlePass01", password: "KettlePass02"}, annabel)).status, 200);
|
||||
assert.strictEqual((await authenticate("Annabel", "KettlePass01")).status, 401);
|
||||
assert.strictEqual((await authenticate("Annabel", "KettlePass02")).status, 200);
|
||||
me = (await mine("me", undefined, annabel)).data;
|
||||
assert.ok(me.history.some(login => login.via === "launcher" && !login.ok) && me.history.some(login => login.via === "game" && login.ok));
|
||||
|
||||
@@ -210,14 +210,14 @@ const run = async () => {
|
||||
assert.strictEqual((await mine("me", undefined, annabel)).status, 401);
|
||||
|
||||
// --- deleting one's own account: the password and the name, then it is gone
|
||||
const {client: b2} = await arrive("Ben", "Password01");
|
||||
const ben = (await mine("login", {username: "Ben", password: "Password01"})).cookie;
|
||||
const {client: b2} = await arrive("Ben", "KettlePass01");
|
||||
const ben = (await mine("login", {username: "Ben", password: "KettlePass01"})).cookie;
|
||||
assert.strictEqual((await mine("act", {action: "delete", current: "wrong", confirm: "Ben"}, ben)).status, 400);
|
||||
assert.strictEqual((await mine("act", {action: "delete", current: "Password01", confirm: "Annabel"}, ben)).status, 400);
|
||||
const gone = await mine("act", {action: "delete", current: "Password01", confirm: "ben"}, ben);
|
||||
assert.strictEqual((await mine("act", {action: "delete", current: "KettlePass01", confirm: "Annabel"}, ben)).status, 400);
|
||||
const gone = await mine("act", {action: "delete", current: "KettlePass01", confirm: "ben"}, ben);
|
||||
assert.deepStrictEqual([gone.status, gone.data.deleted, gone.data.account], [200, true, undefined]);
|
||||
assert.strictEqual((await mine("me", undefined, ben)).status, 401);
|
||||
assert.strictEqual((await authenticate("Ben", "Password01")).status, 401);
|
||||
assert.strictEqual((await authenticate("Ben", "KettlePass01")).status, 401);
|
||||
assert.ok(!(await panel("accounts", undefined, admin)).data.accounts.some(account => account.username === "Ben"));
|
||||
// the name is held for a while (lib/accounts.js, NAME_HELD_DAYS): the
|
||||
// players Ben met still know him by it.
|
||||
|
||||
+52
-2
@@ -14,7 +14,7 @@ const {postJson} = harness;
|
||||
const GAMES = {ticTacToe: 89, fourGems: 90, rockPaperScissors: 91, shellGame: 92, pairs: 93, scooped: 95, bowling: 98, marbles: 101};
|
||||
|
||||
const arrive = async username => {
|
||||
const auth = await (await postJson(`${BASE}/authenticate`, {username, password: "Password01"})).json();
|
||||
const auth = await (await postJson(`${BASE}/authenticate`, {username, password: "KettlePass01"})).json();
|
||||
const client = new harness.GameClient(GAME_PORT);
|
||||
await client.connect();
|
||||
const login = await client.logIn(username, auth.auth_token);
|
||||
@@ -28,7 +28,7 @@ const arrive = async username => {
|
||||
|
||||
const run = async () => {
|
||||
for (const username of ["Ann", "Ben", "Cat"]) {
|
||||
const response = await fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({username, password: "Password01", avatarType: 1, agreed: true})});
|
||||
const response = await fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({username, password: "KettlePass01", avatarType: 1, agreed: true})});
|
||||
assert.strictEqual(response.status, 200);
|
||||
}
|
||||
const ann = await arrive("Ann");
|
||||
@@ -301,6 +301,56 @@ const run = async () => {
|
||||
a.socket.destroy();
|
||||
assert.deepStrictEqual((await b.untilXt("mp")).slice(2), ["101", "1"]);
|
||||
|
||||
// --- a room game played together (lib/minigames.js MULTIPLAYER): Gem
|
||||
// Breaker offers its waiting list, Ben waits in the room, Cat joins, both
|
||||
// are taken in, and each one's moves reach the other
|
||||
// (and first, typing: Cat's "..." reaches Ben, said again too soon is not
|
||||
// passed on, and stopping is)
|
||||
c.xt("xty", cat.roomId, 1);
|
||||
assert.deepStrictEqual((await b.untilXt("xty")).slice(2), [cat.id, "1"]);
|
||||
c.xt("xty", cat.roomId, 1);
|
||||
c.xt("xty", cat.roomId, 0);
|
||||
assert.deepStrictEqual((await b.nextXt("xty")).slice(2), [cat.id, "0"]);
|
||||
|
||||
const GEM_BREAKER = 30;
|
||||
b.xt("mi", ben.roomId, GEM_BREAKER);
|
||||
const gemInfo = (await b.untilXt("mi")).slice(3);
|
||||
assert.deepStrictEqual([gemInfo[0], gemInfo[4], gemInfo[5]], ["30", "2", "2"]);
|
||||
b.xt("mj", ben.roomId, GEM_BREAKER, 1, 0, -1);
|
||||
assert.deepStrictEqual((await b.untilXt("mj")).slice(1), [ben.roomId, ben.id]);
|
||||
c.xt("mj", cat.roomId, GEM_BREAKER, 1, 0, -1);
|
||||
for (const client of [b, c]) {
|
||||
assert.deepStrictEqual((await client.untilXt("mj")).slice(1), [ben.roomId, ben.id, cat.id]);
|
||||
}
|
||||
const gemRoom = (await b.untilXt("rj"))[4];
|
||||
for (const client of [b, c]) {
|
||||
assert.deepStrictEqual((await client.untilXt("mj")).slice(1), [gemRoom, ben.id, cat.id]);
|
||||
assert.deepStrictEqual((await client.untilXt("ms")).slice(2, 5), ["2", ben.id, cat.id]);
|
||||
}
|
||||
b.xt("mm", gemRoom, GEM_BREAKER, "ready");
|
||||
c.xt("mm", gemRoom, GEM_BREAKER, "ready");
|
||||
for (const client of [b, c]) {
|
||||
const go = await client.untilXt("mm");
|
||||
assert.deepStrictEqual([go[2], ...go.slice(4)], ["start", "2", ben.id, "0", cat.id, "0"]);
|
||||
}
|
||||
b.xt("mm", gemRoom, GEM_BREAKER, "pos", "-45");
|
||||
assert.deepStrictEqual((await c.nextXt("mm")).slice(2), ["pos", ben.id, "-45"]);
|
||||
c.xt("mm", gemRoom, GEM_BREAKER, "shoot", "0.5", "-0.8", "210", "40", "3", "1", "300", "0", "5");
|
||||
assert.deepStrictEqual((await b.nextXt("mm")).slice(2), ["shoot", "0.5", "-0.8", "210", "40", "3", "1", "300", "0", "5"]);
|
||||
c.xt("mm", gemRoom, GEM_BREAKER, "pos", "<b>");
|
||||
c.xt("mm", gemRoom, GEM_BREAKER, "playerLost", "12345");
|
||||
assert.deepStrictEqual((await b.nextXt("mm")).slice(2), ["playerLost", "12345"]); // and not the one with markup
|
||||
// one leaving: the other is told, as the game expects
|
||||
c.xt("ml", gemRoom);
|
||||
assert.deepStrictEqual((await b.untilXt("ml")).slice(1), [gemRoom, cat.id]);
|
||||
// alone, the start names its one player, whose cannon it is
|
||||
b.xt("rj", gemRoom, TOWNSHIP, 1, 0, 0);
|
||||
const back = (await b.untilXt("rj"))[4];
|
||||
b.xt("mj", back, GEM_BREAKER, 0, 0, -1);
|
||||
const soloRoom = (await b.untilXt("mj"))[1];
|
||||
b.xt("mm", soloRoom, GEM_BREAKER, "ready");
|
||||
assert.deepStrictEqual((await b.untilXt("mm")).slice(4), ["1", ben.id, "0"]);
|
||||
|
||||
b.socket.destroy();
|
||||
c.socket.destroy();
|
||||
};
|
||||
|
||||
+16
-17
@@ -46,7 +46,7 @@ const wall = async body => (await postJson(`${BASE}/wall`, body)).json();
|
||||
const run = async () => {
|
||||
const registerJson = body => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({avatarType: 1, agreed: true, ...body})});
|
||||
for (const username of ["Ann", "Ben", "Cat", "Scout"]) {
|
||||
assert.strictEqual((await registerJson({username, password: "Password01"})).status, 200);
|
||||
assert.strictEqual((await registerJson({username, password: "KettlePass01"})).status, 200);
|
||||
}
|
||||
|
||||
// --- the admin panel's message of the day reaches a player once their first room has loaded
|
||||
@@ -62,7 +62,7 @@ const run = async () => {
|
||||
assert.strictEqual((await panel("motd", {text: "Welcome to the test server"}, admin)).status, 200);
|
||||
assert.strictEqual((await panel("messages", undefined, admin)).data.motd, "Welcome to the test server");
|
||||
|
||||
const {client: a, login: annLogin, roomId} = await arrive("Ann", "Password01");
|
||||
const {client: a, login: annLogin, roomId} = await arrive("Ann", "KettlePass01");
|
||||
// "ua": the text sits where a room id usually does, then 1 = system message.
|
||||
assert.deepStrictEqual((await a.untilXt("ua")).slice(1), ["Welcome to the test server", "1"]);
|
||||
assert.strictEqual((await panel("motd", {text: ""}, admin)).status, 200);
|
||||
@@ -81,7 +81,7 @@ const run = async () => {
|
||||
a.xt("pad", roomId, "Ann");
|
||||
assert.deepStrictEqual((await a.nextXt("pad")).slice(2), ["1", "1", String(annLogin.params.usableAdoptAPetDefs[0].defId), String(annLogin.params.usableAdoptAPetDefs[0].invId)]);
|
||||
|
||||
const {client: b, login: benLogin} = await arrive("Ben", "Password01");
|
||||
const {client: b, login: benLogin} = await arrive("Ben", "KettlePass01");
|
||||
await a.untilXt("ac");
|
||||
await a.nextXt("il");
|
||||
|
||||
@@ -90,7 +90,7 @@ const run = async () => {
|
||||
// path. a scout goes in first and comes back until the file has been read,
|
||||
// so that what follows does not depend on what an earlier run left in the
|
||||
// cache. (the scout never enters the township, so a and b see nothing.)
|
||||
const scoutAuth = await (await postJson(`${BASE}/authenticate`, {username: "Scout", password: "Password01"})).json();
|
||||
const scoutAuth = await (await postJson(`${BASE}/authenticate`, {username: "Scout", password: "KettlePass01"})).json();
|
||||
const scout = new harness.GameClient(GAME_PORT);
|
||||
await scout.connect();
|
||||
assert.strictEqual((await scout.logIn("Scout", scoutAuth.auth_token)).status, "1");
|
||||
@@ -200,7 +200,7 @@ const run = async () => {
|
||||
// --- name tags: the colour and badge go with a colour change, reach the room, and stay
|
||||
a.xt("gl", roomId, 110);
|
||||
const badges = await a.nextXt("gl");
|
||||
assert.deepStrictEqual([badges[3], badges[8], badges[9], badges[70]], ["1049", "75", "1", "62"]); // every badge, in id order: the game's 62 and the thirteen the admin gives
|
||||
assert.deepStrictEqual([badges[3], badges[8], badges[9], badges[70]], ["1049", "76", "1", "62"]); // every badge, in id order: the game's 62 and the fourteen the admin gives (verified among them)
|
||||
const tag = 6 | 11 << 8; // colour 6, the twelfth badge
|
||||
a.xt("ap", roomId, 1, 2, 3, tag);
|
||||
assert.deepStrictEqual((await a.nextXt("ap")).slice(2), ["1"]);
|
||||
@@ -435,18 +435,9 @@ const run = async () => {
|
||||
b.xt("ei", own[4], 0);
|
||||
await b.nextXt("ei");
|
||||
|
||||
// A secret valentine: the receiver is not told who sent it, the server knows.
|
||||
// secret valentines are off (lib/ecards.js): one asked for is refused
|
||||
a.xt("es", own[4], "Ben", cards[9], stamps[9], 2, "GUESS WHO", 0, 0, 1);
|
||||
assert.deepStrictEqual((await a.nextXt("es")).slice(2), ["1"]);
|
||||
const valentine = await b.nextXt("ep");
|
||||
assert.deepStrictEqual([valentine[3], valentine[7], valentine[18]], ["", "GUESS WHO", "1"]); // no name; special type 1
|
||||
b.xt("fr", own[4], "Secret Valentine", 14); // reported under the name the game shows
|
||||
assert.deepStrictEqual((await b.nextXt("fr")).slice(2), ["1"]);
|
||||
const aboutValentine = (await panel("reports", undefined, admin)).data.reports;
|
||||
assert.deepStrictEqual([aboutValentine[0].reporter, aboutValentine[0].target, aboutValentine[0].reason], ["Ben", "Ann", "Inappropriate Jam-A-Gram"]);
|
||||
await panel("report", {id: aboutValentine[0].id}, admin);
|
||||
b.xt("ed", own[4], valentine[2]);
|
||||
await b.nextXt("ed");
|
||||
assert.deepStrictEqual((await a.nextXt("es")).slice(2), ["0"]);
|
||||
|
||||
// --- Jammer Walls: the wallpapers a wall cannot be drawn without, and their buttons
|
||||
a.xt("gl", own[4], 314);
|
||||
@@ -488,6 +479,14 @@ const run = async () => {
|
||||
assert.deepStrictEqual((await b.nextXt("wps")).slice(2), ["1"]);
|
||||
const mine = await wall({cmd: "GET", t: ownToken});
|
||||
assert.deepStrictEqual([mine.p.bg, mine.p.tag, mine.p.visits, mine.r.length], ["7", "hello there", 1, 1]); // visits are not the owner's to set
|
||||
// the photo booth picture: its animal, its pet and what it wears, kept
|
||||
const photo = {avatar: {id: 4, color1: 1463028479, color2: 603979776, color3: 83885823, eyes: 4, pattern: 25}, bgid: 3,
|
||||
pet: {ts: 1792133948, lbits: 25, uBits: 0, eBits: 0}, items: [{id: 101, color: 1463028479}, {id: 202, color: 0}]};
|
||||
b.xt("wps", own[4], JSON.stringify({pb: photo}));
|
||||
assert.deepStrictEqual((await b.nextXt("wps")).slice(2), ["1"]);
|
||||
assert.deepStrictEqual((await wall({cmd: "GET", t: ownToken})).p.pb, photo);
|
||||
b.xt("wps", own[4], JSON.stringify({pb: {avatar: {deep: {deeper: 1}}}})); // but no deeper than that
|
||||
assert.deepStrictEqual((await b.nextXt("wps")).slice(2), ["0"]);
|
||||
assert.deepStrictEqual(await wall({cmd: "CLW", t: token[3]}), {s: false}); // only the owner clears a wall
|
||||
assert.deepStrictEqual(await wall({cmd: "DEL", t: ownToken, x: put.x}), {s: true});
|
||||
assert.strictEqual((await wall({cmd: "GET", t: ownToken})).r.length, 0);
|
||||
@@ -515,7 +514,7 @@ const run = async () => {
|
||||
assert.strictEqual((await panel("overview", undefined, admin)).data.stats.reports, 1);
|
||||
assert.strictEqual((await panel("report", {id: waiting.reports[0].id}, admin)).status, 200);
|
||||
assert.strictEqual((await panel("reports", undefined, admin)).data.open, 0);
|
||||
assert.strictEqual((await panel("reports?handled=1", undefined, admin)).data.reports.length, 2); // this one and the valentine
|
||||
assert.strictEqual((await panel("reports?handled=1", undefined, admin)).data.reports.length, 1); // this one (secret valentines, reported before, are off)
|
||||
|
||||
// --- blocking: no chat from them, out of my party and my den, and out of sight if I say so
|
||||
a.xt("bb", own[4], "Ben");
|
||||
|
||||
+240
-3
@@ -80,7 +80,7 @@ const arrive = async (username, password, totp, onLogin = async () => {}) => {
|
||||
client.xt("rj", 1, TOWNSHIP, 1, 0, 0);
|
||||
const rj = await client.untilXt("rj");
|
||||
await client.untilXt("rp");
|
||||
return {client, roomId: rj[4]};
|
||||
return {client, roomId: rj[4], token: auth.auth_token};
|
||||
};
|
||||
|
||||
// a pack as the clients get it.
|
||||
@@ -103,7 +103,7 @@ const shopList = async (client, roomId, shop) => {
|
||||
return (await client.untilXt("gl")).slice(9);
|
||||
};
|
||||
|
||||
const people = {Dev: "Password21", Hal: "Password22", Pat: "Password23", Lou: "Password24"};
|
||||
const people = {Dev: "KettlePass21", Hal: "KettlePass22", Pat: "KettlePass23", Lou: "KettlePass24"};
|
||||
const secret = {};
|
||||
let usedStep = 0;
|
||||
let made = {};
|
||||
@@ -229,10 +229,247 @@ const first = async () => {
|
||||
}
|
||||
assert.strictEqual((await dev("/mod/api/items")).data.items.length, 3);
|
||||
|
||||
// --- locked out of the item finder (lib/itemcontrol.js): players do not
|
||||
// find it or take it; the owner here, and staff who may lock, still do
|
||||
const searchAs = async (q, who) => (await (await fetch(`${BASE}/api/search?kind=clothing&q=${q}${who ? `&username=${who.name}&token=${who.token}` : ""}`)).json()).results;
|
||||
// (as the item finder page and the client send it: no Origin of another site)
|
||||
const giveAs = (body, token) => fetch(`${BASE}/api/give`, {method: "POST", headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify({...body, ...(token ? {token} : {})})});
|
||||
const patAs = {name: "Pat", token: pat.token};
|
||||
assert.ok((await searchAs(50001, patAs)).some(entry => entry.id === 50001));
|
||||
assert.match((await dev("/mod/api/items", {action: "lock", kind: "clothing", id: 50001})).data.ok, /^Quick Hat \(clothing 50001\) is locked out of the item finder\.$/);
|
||||
assert.match((await dev("/mod/api/items", {action: "lock", kind: "clothing", id: 50001})).data.error, /already locked/);
|
||||
assert.ok(!(await searchAs(50001, patAs)).some(entry => entry.id === 50001));
|
||||
const refused = await giveAs({username: "Pat", kind: "clothing", id: 50001}, pat.token);
|
||||
assert.deepStrictEqual([refused.status, (await refused.json()).error], [403, "That item is locked out of the item finder."]);
|
||||
assert.deepStrictEqual((await searchAs(50001)).filter(entry => entry.id === 50001).map(entry => [entry.name, entry.locked]), [["Quick Hat (locked)", true]]);
|
||||
assert.strictEqual((await searchAs(50001, {name: "Dev", token: devGame.token})).find(entry => entry.id === 50001).name, "Quick Hat (locked)");
|
||||
assert.deepStrictEqual((await dev("/mod/api/items")).data.locked, [{kind: "clothing", id: 50001, name: "Quick Hat"}]);
|
||||
// the dashboards' lock finds it by name, marked locked, with the count
|
||||
const findLock = (await dev("/mod/api/items/find?q=quick%20hat&kind=clothing")).data;
|
||||
assert.deepStrictEqual([findLock.lockedCount, findLock.results.find(entry => entry.id === 50001)],
|
||||
[1, {kind: "clothing", id: 50001, cost: findLock.results.find(entry => entry.id === 50001).cost, name: "Quick Hat", locked: true, custom: true}]);
|
||||
say(devGame.client, devGame.roomId, "!locked");
|
||||
assert.strictEqual(await nextBox(devGame.client), "Locked out of the item finder: clothing 50001 Quick Hat");
|
||||
|
||||
// --- taken from a player: every one of it, their game told
|
||||
assert.strictEqual((await giveAs({username: "Pat", kind: "clothing", id: 50001, colorIndex: 0})).status, 200); // the owner, here
|
||||
assert.strictEqual((await giveAs({username: "Pat", kind: "clothing", id: 50001, colorIndex: 0})).status, 200);
|
||||
say(devGame.client, devGame.roomId, "!take Pat clothing 50001");
|
||||
assert.strictEqual(await nextBox(devGame.client), "Took 2 of Quick Hat (clothing 50001) from Pat.");
|
||||
for (;;) {
|
||||
const changed = await pat.client.untilXt("il");
|
||||
if (changed[2] === "2" && changed[8] === "2") { // two removed
|
||||
break;
|
||||
}
|
||||
}
|
||||
say(devGame.client, devGame.roomId, "!take Pat clothing 50001");
|
||||
assert.strictEqual(await nextBox(devGame.client), "Pat has no Quick Hat (clothing 50001).");
|
||||
assert.strictEqual((await giveAs({username: "Pat", kind: "den", id: 50000})).status, 200);
|
||||
assert.match((await dev("/mod/api/items", {action: "take", username: "Pat", kind: "den", id: 50000})).data.ok, /^Took 1 of Test Chair \(den item 50000\) from Pat\.$/);
|
||||
assert.match((await dev("/mod/api/items", {action: "unlock", kind: "clothing", id: 50001})).data.ok, /back in the item finder/);
|
||||
assert.ok((await searchAs(50001, patAs)).some(entry => entry.id === 50001));
|
||||
|
||||
// --- a custom item deleted: out of the game and every inventory
|
||||
say(devGame.client, devGame.roomId, `!item clothing ${base.id} Doomed Hat`);
|
||||
assert.strictEqual(await nextBox(devGame.client), "Made Doomed Hat, clothing 50002. It is in the item finder now.");
|
||||
assert.strictEqual((await giveAs({username: "Pat", kind: "clothing", id: 50002, colorIndex: 0})).status, 200);
|
||||
assert.match((await dev("/mod/api/items", {action: "delete", kind: "clothing", id: 50002})).data.ok, /^Deleted Doomed Hat \(clothing 50002\), and took 1 from players\.$/);
|
||||
assert.ok(!(await searchAs(50002)).some(entry => entry.id === 50002));
|
||||
assert.strictEqual((await giveAs({username: "Pat", kind: "clothing", id: 50002, colorIndex: 0})).status, 400);
|
||||
assert.ok(!byId(await pack(1000), 50002));
|
||||
assert.strictEqual((await dev("/mod/api/items")).data.items.length, 3);
|
||||
|
||||
// --- a player's own items (lib/playeritems.js, the client's Item Maker):
|
||||
// free, given to them, found by them only, at most five a day
|
||||
const maker = async (...params) => {
|
||||
pat.client.xt("xcm", pat.roomId, ...params);
|
||||
const answer = await pat.client.untilXt("xcm");
|
||||
return {ok: answer[2] === "1", said: answer[3], today: Number(answer[4]), inAll: Number(answer[5]), mine: JSON.parse(answer[6])};
|
||||
};
|
||||
assert.deepStrictEqual(await maker("info"), {ok: true, said: "", today: 5, inAll: 20, mine: []});
|
||||
const own = await maker("make", "clothing", base.id, "Pat Hat");
|
||||
assert.deepStrictEqual([own.ok, own.said, own.today, own.inAll], [true, "Made Pat Hat. It is in your clothing now.", 4, 19]);
|
||||
const patHat = own.mine[0];
|
||||
assert.deepStrictEqual([patHat.kind, patHat.name, patHat.base], ["clothing", "Pat Hat", Number(base.id)]);
|
||||
assert.ok((await searchAs(patHat.id, patAs)).some(entry => entry.id === patHat.id));
|
||||
const halAs = {name: "Hal", token: hal.token};
|
||||
assert.ok(!(await searchAs(patHat.id, halAs)).some(entry => entry.id === patHat.id));
|
||||
assert.strictEqual((await giveAs({username: "Hal", kind: "clothing", id: patHat.id, colorIndex: 0}, hal.token)).status, 403);
|
||||
assert.ok((await searchAs(patHat.id, {name: "Dev", token: devGame.token})).some(entry => entry.id === patHat.id)); // staff who make items
|
||||
assert.match((await maker("make", "clothing", base.id, "Admin Hat")).said, /not allowed/);
|
||||
assert.match((await maker("make", "clothing", bodyPart.id, "Body")).said, /cannot be made into one of your own/);
|
||||
// the base list offers only what can be copied
|
||||
assert.ok(!(await (await fetch(`${BASE}/api/search?base=1&kind=clothing&q=${bodyPart.id}`)).json()).results.some(entry => entry.id === bodyPart.id));
|
||||
for (let count = 2; count <= 5; count++) {
|
||||
assert.ok((await maker("make", "den", 1, `Pat Chair ${count}`)).ok);
|
||||
}
|
||||
const full = await maker("make", "den", 1, "One Too Many");
|
||||
assert.deepStrictEqual([full.ok, full.today], [false, 0]);
|
||||
assert.match(full.said, /made 5 items today/);
|
||||
// --- its own picture (lib/itemart.js): checked and cleaned, served, and
|
||||
// every game told; only by its maker or staff who make items
|
||||
const crc32 = buf => {
|
||||
let c = ~0;
|
||||
for (const byte of buf) {
|
||||
c ^= byte;
|
||||
for (let k = 0; k < 8; k++) {
|
||||
c = (c >>> 1) ^ (0xEDB88320 & -(c & 1));
|
||||
}
|
||||
}
|
||||
return (~c) >>> 0;
|
||||
};
|
||||
const chunk = (type, data) => {
|
||||
const head = Buffer.alloc(8);
|
||||
head.writeUInt32BE(data.length);
|
||||
head.write(type, 4, "latin1");
|
||||
const crc = Buffer.alloc(4);
|
||||
crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data])));
|
||||
return Buffer.concat([head, data, crc]);
|
||||
};
|
||||
const png = (side, extra = []) => {
|
||||
const ihdr = Buffer.alloc(13);
|
||||
ihdr.writeUInt32BE(side, 0);
|
||||
ihdr.writeUInt32BE(side, 4);
|
||||
ihdr[8] = 8;
|
||||
ihdr[9] = 2;
|
||||
const raw = Buffer.alloc((side * 3 + 1) * side, 0x7F);
|
||||
return Buffer.concat([Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]), chunk("IHDR", ihdr), ...extra,
|
||||
chunk("IDAT", zlib.deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);
|
||||
};
|
||||
const upload = (who, entry, body, extra = "") => fetch(`${BASE}/api/itemart?kind=${entry.kind}&id=${entry.id}&token=${who.token}${extra}`,
|
||||
{method: "POST", headers: {"Content-Type": "application/octet-stream"}, body}).then(response => response.json());
|
||||
const hatEntry = (await maker("info")).mine.find(entry => entry.name === "Pat Hat");
|
||||
// by default a player's picture waits for a moderator, even with items
|
||||
// let in at once: nobody else is shown it, not even by its address
|
||||
assert.match((await upload(pat, hatEntry, png(30))).ok, /waiting for a moderator/);
|
||||
assert.strictEqual((await maker("info")).mine.find(entry => entry.kind === hatEntry.kind && entry.id === hatEntry.id).art, "");
|
||||
assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png`)).status, 404);
|
||||
const pendingUrl = (await admin("/admin/api/review")).data.waiting.find(entry => entry.id === hatEntry.id).artUrl;
|
||||
assert.match(pendingUrl, /^\/admin\/api\/itemart\?kind=clothing&id=\d+&v=p[0-9a-f]{12}$/);
|
||||
assert.strictEqual((await admin(pendingUrl)).status, 200);
|
||||
assert.strictEqual((await fetch(`${BASE}${pendingUrl}`)).status, 404); // signed in to nothing
|
||||
assert.match((await admin("/admin/api/review", {kind: "clothing", id: hatEntry.id, approve: true})).data.ok, /picture is shown now/);
|
||||
assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png`)).status, 200);
|
||||
while (!(await untilDefs(pat.client, "clothing")).some(row => row.art)) {
|
||||
// every game is told of it waiting (no picture), then of it shown
|
||||
}
|
||||
// the rest of these, shown at once (the admin's switch)
|
||||
assert.strictEqual((await admin("/admin/api/item-switches", {artApproval: false})).status, 200);
|
||||
assert.strictEqual((await admin("/admin/api/review")).data.artApproval, false);
|
||||
assert.match((await upload(pat, hatEntry, png(32, [chunk("tEXt", Buffer.from("Author\x00Pat at home"))]))).ok, /new picture/);
|
||||
const told = (await untilDefs(pat.client, "clothing")).map(row => [row.id, row.art]);
|
||||
const sameItem = entry => entry.kind === hatEntry.kind && entry.id === hatEntry.id;
|
||||
const withArt = (await maker("info")).mine.find(sameItem);
|
||||
assert.match(withArt.art, /^p[0-9a-f]{12}$/);
|
||||
assert.deepStrictEqual(told, [[String(hatEntry.id), withArt.art]]);
|
||||
const served = await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png?v=${withArt.art}`);
|
||||
assert.deepStrictEqual([served.status, served.headers.get("content-type"), served.headers.get("x-content-type-options")], [200, "image/png", "nosniff"]);
|
||||
const bytes = Buffer.from(await served.arrayBuffer());
|
||||
assert.ok(!bytes.includes(Buffer.from("tEXt")) && !bytes.includes(Buffer.from("Pat at home")), "the text chunk was left in");
|
||||
assert.match((await upload(pat, hatEntry, Buffer.from("<html><script>alert(1)</script></html>"))).error, /not a PNG, JPEG, GIF or BMP/);
|
||||
// a GIF is kept a GIF (without its comment); a BMP is made a PNG
|
||||
const gif = Buffer.concat([Buffer.from("GIF89a"), Buffer.from([16, 0, 16, 0, 0x80, 0, 0]), Buffer.alloc(6, 0x55),
|
||||
Buffer.from([0x21, 0xFE, 4]), Buffer.from("Bob!"), Buffer.from([0]), Buffer.from([0x2C, 0, 0, 0, 0, 16, 0, 16, 0, 0, 2, 3, 1, 2, 3, 0, 0x3B])]);
|
||||
assert.match((await upload(pat, hatEntry, gif)).ok, /new picture/);
|
||||
const gifArt = (await maker("info")).mine.find(entry => entry.kind === hatEntry.kind && entry.id === hatEntry.id).art;
|
||||
const gifServed = await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png?v=${gifArt}`);
|
||||
assert.strictEqual(gifServed.headers.get("content-type"), "image/gif");
|
||||
assert.ok(!Buffer.from(await gifServed.arrayBuffer()).includes(Buffer.from("Bob!")), "the GIF comment was left in");
|
||||
const bmp = Buffer.alloc(54 + 32 * 3 * 32);
|
||||
bmp.write("BM");
|
||||
bmp.writeUInt32LE(bmp.length, 2);
|
||||
bmp.writeUInt32LE(54, 10);
|
||||
bmp.writeUInt32LE(40, 14);
|
||||
bmp.writeInt32LE(32, 18);
|
||||
bmp.writeInt32LE(32, 22);
|
||||
bmp.writeUInt16LE(1, 26);
|
||||
bmp.writeUInt16LE(24, 28);
|
||||
assert.match((await upload(pat, hatEntry, bmp)).ok, /new picture/);
|
||||
const bmpArt = (await maker("info")).mine.find(entry => entry.kind === hatEntry.kind && entry.id === hatEntry.id).art;
|
||||
assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png?v=${bmpArt}`)).headers.get("content-type"), "image/png");
|
||||
assert.match((await upload(pat, hatEntry, png(600))).error, /512 pixels/);
|
||||
assert.match((await upload(hal, hatEntry, png(16))).error, /not one of your items/);
|
||||
assert.match((await fetch(`${BASE}/api/itemart?kind=clothing&id=${hatEntry.id}`, {method: "POST", body: png(16)}).then(r => r.json())).error, /Sign in/);
|
||||
// a JPEG keeps its picture and loses its EXIF (where a photo was taken)
|
||||
const segment = (marker, data) => Buffer.concat([Buffer.from([0xFF, marker, (data.length + 2) >> 8, (data.length + 2) & 0xFF]), data]);
|
||||
const jpeg = Buffer.concat([Buffer.from([0xFF, 0xD8]), segment(0xE0, Buffer.from("JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00", "latin1")),
|
||||
segment(0xE1, Buffer.from("Exif\x00\x00GPS 51.5N 0.12W", "latin1")), segment(0xC0, Buffer.from([8, 0, 20, 0, 30, 1, 1, 0x11, 0])),
|
||||
segment(0xDA, Buffer.from([1, 1, 0, 0, 0x3F, 0])), Buffer.from([0x12, 0x34, 0xFF, 0xD9])]);
|
||||
assert.match((await upload(pat, hatEntry, jpeg)).ok, /new picture/);
|
||||
const jpegArt = (await maker("info")).mine.find(sameItem).art;
|
||||
const jpegBytes = Buffer.from(await (await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png?v=${jpegArt}`)).arrayBuffer());
|
||||
assert.ok(jpegBytes.includes(Buffer.from("JFIF")) && !jpegBytes.includes(Buffer.from("GPS")), "the EXIF was left in");
|
||||
assert.match((await upload(pat, hatEntry, Buffer.alloc(0), "&remove=1")).ok, /taken away/);
|
||||
assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png`)).status, 404);
|
||||
assert.match((await upload(pat, hatEntry, png(24))).ok, /new picture/); // deleted with the item, below
|
||||
assert.match((await maker("rename", "clothing", hatEntry.id, "Party Hat")).said, /^Renamed it Party Hat\.$/);
|
||||
// how it is worn: a sticker by default, a texture when its maker says so, every game told
|
||||
pat.client.xt("xcm", pat.roomId, "look", "clothing", hatEntry.id, "texture");
|
||||
assert.strictEqual((await untilDefs(pat.client, "clothing"))[0].artMode, "texture");
|
||||
assert.strictEqual((await pat.client.untilXt("xcm"))[2], "1"); // its own answer, after every game was told
|
||||
const wornAs = await maker("info");
|
||||
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/);
|
||||
|
||||
// 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) {
|
||||
assert.match((await maker("delete", entry.kind, entry.id)).said, /^Deleted /);
|
||||
}
|
||||
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);
|
||||
|
||||
// --- the admin's switches: what players make waits for a moderator first,
|
||||
// out of the game till then; or the Item Maker is off
|
||||
assert.strictEqual((await admin("/admin/api/item-switches", {enabled: true, approval: true})).status, 200);
|
||||
const asked = await maker("make", "clothing", base.id, "Waiting Hat");
|
||||
assert.match(asked.said, /waiting for a moderator/);
|
||||
const waitingHat = asked.mine.find(entry => entry.name === "Waiting Hat");
|
||||
assert.strictEqual(waitingHat.waiting, "item");
|
||||
assert.ok(!(await searchAs(waitingHat.id)).some(entry => entry.id === waitingHat.id)); // not in the game yet
|
||||
const queue = (await admin("/admin/api/review")).data;
|
||||
assert.deepStrictEqual([queue.enabled, queue.approval, queue.waiting.map(entry => `${entry.name} ${entry.waiting} ${entry.maker}`)],
|
||||
[true, true, ["Waiting Hat item Pat"]]);
|
||||
assert.strictEqual((await dev("/mod/api/review")).status, 403); // a developer approves nothing
|
||||
assert.match((await admin("/admin/api/review", {kind: "clothing", id: waitingHat.id, approve: true})).data.ok, /in the game, and Pat has one/);
|
||||
for (;;) {
|
||||
const changed = await pat.client.untilXt("il");
|
||||
if (changed[2] === "2" && changed[10] === String(waitingHat.id)) { // given to Pat
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert.ok((await searchAs(waitingHat.id, patAs)).some(entry => entry.id === waitingHat.id));
|
||||
// a new picture waits too, and is not shown till then
|
||||
assert.match((await upload(pat, waitingHat, png(20))).ok, /waiting for a moderator/);
|
||||
assert.strictEqual((await maker("info")).mine.find(entry => entry.id === waitingHat.id && entry.kind === "clothing").waiting, "picture");
|
||||
assert.match((await admin("/admin/api/review", {kind: "clothing", id: waitingHat.id, approve: false})).data.ok,
|
||||
/picture was turned away\. Pat has had 1 of 3 pictures turned away\.$/);
|
||||
assert.strictEqual((await admin("/admin/api/review")).data.waiting.length, 0);
|
||||
// the same picture cannot come back; after three turned away, uploads stop
|
||||
assert.match((await upload(pat, waitingHat, png(20))).error, /turned that picture away before/);
|
||||
assert.match((await upload(pat, waitingHat, png(21))).ok, /waiting/);
|
||||
assert.match((await admin("/admin/api/review", {kind: "clothing", id: waitingHat.id, approve: false})).data.ok, /2 of 3/);
|
||||
assert.match((await upload(pat, waitingHat, png(22))).ok, /waiting/);
|
||||
assert.match((await admin("/admin/api/review", {action: "takePicture", kind: "clothing", id: waitingHat.id})).data.ok,
|
||||
/taken away\. That is 3 for Pat: their picture uploads are stopped\.$/);
|
||||
assert.match((await upload(pat, waitingHat, png(23))).error, /turned off picture uploads/);
|
||||
assert.deepStrictEqual((await admin("/admin/api/review")).data.stopped, ["Pat"]);
|
||||
assert.match((await admin("/admin/api/review", {action: "uploads", username: "Pat", blocked: false})).data.ok, /Pat can upload pictures again/);
|
||||
assert.match((await upload(pat, waitingHat, png(23))).ok, /waiting/);
|
||||
assert.match((await admin("/admin/api/review", {kind: "clothing", id: waitingHat.id, approve: true})).data.ok, /shown now/);
|
||||
// off: nothing is made
|
||||
assert.strictEqual((await admin("/admin/api/item-switches", {enabled: false, approval: false})).status, 200);
|
||||
assert.match((await maker("make", "clothing", base.id, "No Hat")).said, /turned off/);
|
||||
assert.strictEqual((await admin("/admin/api/item-switches", {enabled: true})).status, 200);
|
||||
assert.match((await maker("delete", "clothing", waitingHat.id)).said, /^Deleted /);
|
||||
|
||||
// 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",
|
||||
"Dev item made (in game) clothing 50001 Quick Hat"]) {
|
||||
"Dev item made (in game) clothing 50001 Quick Hat", "Dev item locked clothing 50001", "Dev item taken (in game) clothing 50001 x2",
|
||||
"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};
|
||||
|
||||
+3
-3
@@ -21,7 +21,7 @@ const told = async client => (await client.untilXt("xtl"))[2];
|
||||
// logs in and asks for the township, as the game always does first.
|
||||
// returns where the server put them.
|
||||
const arrive = async username => {
|
||||
const auth = await (await postJson(`${BASE}/authenticate`, {username, password: "Password01"})).json();
|
||||
const auth = await (await postJson(`${BASE}/authenticate`, {username, password: "KettlePass01"})).json();
|
||||
const client = new harness.GameClient(GAME_PORT);
|
||||
await client.connect();
|
||||
const login = await client.logIn(username, auth.auth_token);
|
||||
@@ -36,7 +36,7 @@ const arrive = async username => {
|
||||
const run = async () => {
|
||||
for (const username of ["Ann", "Ben"]) {
|
||||
const response = await fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify({username, password: "Password01", avatarType: 1, agreed: true})});
|
||||
body: JSON.stringify({username, password: "KettlePass01", avatarType: 1, agreed: true})});
|
||||
assert.strictEqual(response.status, 200);
|
||||
}
|
||||
let {client: a, login, roomId, room} = await arrive("Ann");
|
||||
@@ -190,7 +190,7 @@ const run = async () => {
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
|
||||
// --- "start in your own den" (asked for at sign-in): the game asks for the township and is put in the den
|
||||
const denAuth = await (await postJson(`${BASE}/authenticate`, {username: "Ann", password: "Password01", login_choices: {startInDen: true}})).json();
|
||||
const denAuth = await (await postJson(`${BASE}/authenticate`, {username: "Ann", password: "KettlePass01", login_choices: {startInDen: true}})).json();
|
||||
const home = new harness.GameClient(GAME_PORT);
|
||||
await home.connect();
|
||||
await home.logIn("Ann", denAuth.auth_token);
|
||||
|
||||
+6
-6
@@ -38,9 +38,9 @@ const byId = (rows, id) => rows.find(row => String(row.id) === String(id));
|
||||
const run = async () => {
|
||||
const registerJson = body => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({avatarType: 1, agreed: true, ...body})});
|
||||
for (const username of ["Ann", "Ben"]) {
|
||||
assert.strictEqual((await registerJson({username, password: "Password01"})).status, 200);
|
||||
assert.strictEqual((await registerJson({username, password: "KettlePass01"})).status, 200);
|
||||
}
|
||||
const {client: a, roomId} = await arrive("Ann", "Password01");
|
||||
const {client: a, roomId} = await arrive("Ann", "KettlePass01");
|
||||
|
||||
// --- Epic Dens: twenty names; asking for the den of one leads into its room
|
||||
a.xt("dh", roomId);
|
||||
@@ -147,7 +147,7 @@ const run = async () => {
|
||||
a.xt("di", den);
|
||||
assert.deepStrictEqual((await a.nextXt("di")).slice(13, 24), ["111", "222", "0", "333", "0", "0", "0", "0", "0", hat, "0"]);
|
||||
// A visitor is told what the hat is: its def and colour, then its id.
|
||||
const {client: b, roomId: benRoom} = await arrive("Ben", "Password01");
|
||||
const {client: b, roomId: benRoom} = await arrive("Ben", "KettlePass01");
|
||||
b.xt("dj", benRoom, "denAnn", 1, -1);
|
||||
const seen = await b.untilXt("ds");
|
||||
assert.deepStrictEqual(seen.slice(5), [mannequin, "3433", "1", "300", "400", "0", "0", "", "", "-1", "",
|
||||
@@ -177,8 +177,8 @@ const run = async () => {
|
||||
assert.strictEqual((await a.nextXt("di"))[22], "0");
|
||||
|
||||
// --- a player who is not in the game: their card still shows who they are
|
||||
assert.strictEqual((await registerJson({username: "Cat", password: "Password01"})).status, 200);
|
||||
const {client: c, roomId: catRoom} = await arrive("Cat", "Password01");
|
||||
assert.strictEqual((await registerJson({username: "Cat", password: "KettlePass01"})).status, 200);
|
||||
const {client: c, roomId: catRoom} = await arrive("Cat", "KettlePass01");
|
||||
c.xt("pc", catRoom, 312, 1, 0, 0, 15386, 15428, 0); // a pet, so there is one to list
|
||||
await c.untilXt("pc");
|
||||
c.socket.destroy();
|
||||
@@ -204,7 +204,7 @@ const run = async () => {
|
||||
const stamps = (await b.nextXt("gl")).slice(9);
|
||||
b.xt("es", benRoom, "Cat", cards[0], stamps[0], 0, "see you soon", 0, 0, 0);
|
||||
assert.strictEqual((await b.untilXt("es"))[2], "1");
|
||||
const {client: c2, login: catLogin, roomId: catRoom2} = await arrive("Cat", "Password01");
|
||||
const {client: c2, login: catLogin, roomId: catRoom2} = await arrive("Cat", "KettlePass01");
|
||||
assert.strictEqual(catLogin.params.numUnreadECards, 1);
|
||||
assert.deepStrictEqual((await c2.untilXt("ba")).slice(2), ["0", "Ben", "1"]); // asked, now that Cat is here
|
||||
c2.xt("bc", catRoom2, "Ben", 1);
|
||||
|
||||
+28
-24
@@ -28,29 +28,29 @@ const run = async () => {
|
||||
// --- registration: the web form's API, and no accounts made by logging in
|
||||
assert.match(await (await fetch(`${BASE}/register`)).text(), /Create an account/);
|
||||
const registerJson = body => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({avatarType: 1, agreed: true, ...body})});
|
||||
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Alice", password: "Password01"})).status, 401);
|
||||
assert.strictEqual((await registerJson({username: "Alice", password: "Password01"})).status, 200);
|
||||
assert.deepStrictEqual(await (await registerJson({username: "alice", password: "Password01"})).json(), {error: "username_taken"});
|
||||
assert.deepStrictEqual(await (await registerJson({username: "a!", password: "Password01"})).json(), {error: "invalid_username"});
|
||||
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Alice", password: "KettlePass01"})).status, 401);
|
||||
assert.strictEqual((await registerJson({username: "Alice", password: "KettlePass01"})).status, 200);
|
||||
assert.deepStrictEqual(await (await registerJson({username: "alice", password: "KettlePass01"})).json(), {error: "username_taken"});
|
||||
assert.deepStrictEqual(await (await registerJson({username: "a!", password: "KettlePass01"})).json(), {error: "invalid_username"});
|
||||
assert.deepStrictEqual(await (await registerJson({username: "Shorty", password: "pw"})).json(), {error: "invalid_password"});
|
||||
// no default animal: whoever signs up picks one of the nine on the page.
|
||||
assert.deepStrictEqual(await (await registerJson({username: "Noanimal", password: "Password01", avatarType: undefined})).json(), {error: "choose_animal"});
|
||||
assert.deepStrictEqual(await (await registerJson({username: "Noanimal", password: "Password01", avatarType: 2})).json(), {error: "choose_animal"});
|
||||
assert.deepStrictEqual(await (await registerJson({username: "Noanimal", password: "KettlePass01", avatarType: undefined})).json(), {error: "choose_animal"});
|
||||
assert.deepStrictEqual(await (await registerJson({username: "Noanimal", password: "KettlePass01", avatarType: 2})).json(), {error: "choose_animal"});
|
||||
assert.match(await (await fetch(`${BASE}/register`)).text(), /Choose an animal/);
|
||||
assert.strictEqual((await fetch(`${BASE}/signup/thumb_wolf.svg`)).headers.get("content-type"), "image/svg+xml");
|
||||
assert.strictEqual((await fetch(`${BASE}/signup/..%2Faccount.html`)).status, 404);
|
||||
for (const [username, password] of [["Bob", "Password02"], ["Carol", "Password03"], ["foo", "Password04"]]) {
|
||||
for (const [username, password] of [["Bob", "KettlePass02"], ["Carol", "KettlePass03"], ["foo", "KettlePass04"]]) {
|
||||
assert.strictEqual((await registerJson({username, password})).status, 200);
|
||||
}
|
||||
|
||||
let res = await postJson(`${BASE}/authenticate`, {username: "Alice", password: "Password01", domain: "flash", df: "x"});
|
||||
let res = await postJson(`${BASE}/authenticate`, {username: "Alice", password: "KettlePass01", domain: "flash", df: "x"});
|
||||
assert.strictEqual(res.status, 200);
|
||||
assert.strictEqual(res.headers.get("access-control-allow-origin"), "null");
|
||||
const alice = await res.json();
|
||||
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "alice", password: "wrong"})).status, 401);
|
||||
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "constructor", password: "Password01"})).status, 401);
|
||||
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "constructor", password: "KettlePass01"})).status, 401);
|
||||
assert.strictEqual((await postJson(`${BASE}/authenticate`, {refresh_token: alice.refresh_token})).status, 200);
|
||||
const bob = await (await postJson(`${BASE}/authenticate`, {username: "Bob", password: "Password02"})).json();
|
||||
const bob = await (await postJson(`${BASE}/authenticate`, {username: "Bob", password: "KettlePass02"})).json();
|
||||
|
||||
res = await fetch(`${BASE}/player?domain=flash&client_version=1830`, {headers: {Authorization: `Bearer ${alice.auth_token}`}});
|
||||
assert.strictEqual((await res.json()).screen_name, "Alice");
|
||||
@@ -83,11 +83,11 @@ const run = async () => {
|
||||
assert.deepStrictEqual((await guest.nextXt("la")).slice(2), ["1"]);
|
||||
const iv = crypto.randomBytes(16);
|
||||
const cipher = crypto.createCipheriv("aes-256-cbc", crypto.createHash("sha256").update(guestKey).digest(), iv);
|
||||
const encrypted = Buffer.concat([iv, cipher.update("DavePass01"), cipher.final()]).toString("base64");
|
||||
const encrypted = Buffer.concat([iv, cipher.update("TulipKettle01"), cipher.final()]).toString("base64");
|
||||
guest.xt("lc", 1, "Dave", encrypted, "2000-01-01", 0, "", 15136, 15224, 15299, 4, 0, "US", 1830);
|
||||
assert.deepStrictEqual((await guest.nextXt("lc")).slice(2, 3), ["1"]);
|
||||
guest.socket.destroy();
|
||||
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Dave", password: "DavePass01"})).status, 200);
|
||||
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Dave", password: "TulipKettle01"})).status, 200);
|
||||
|
||||
// --- first player: login and world entry
|
||||
const a = new GameClient();
|
||||
@@ -158,6 +158,10 @@ const run = async () => {
|
||||
assert.deepStrictEqual((await b.nextXt("uc")).slice(1), [roomId, String(bobId), "hi & bye", "0"]);
|
||||
b.send(`<msg t='sys'><body action='pubMsg' r='${roomId}'><txt><![CDATA[7%2]]></txt></body></msg>`); // emote: not echoed
|
||||
assert.deepStrictEqual((await a.nextXt("uc")).slice(3), ["7", "2"]);
|
||||
// Actions are sent to every other player in the room. The sender has
|
||||
// already applied the action locally, so it is not echoed back to them.
|
||||
b.send(`<msg t='sys'><body action='pubMsg' r='${roomId}'><txt><![CDATA[:sitS:%3%m1]]></txt></body></msg>`);
|
||||
assert.deepStrictEqual((await a.nextXt("uc")).slice(3), [":sitS:", "3", "m1"]);
|
||||
|
||||
// --- player cards
|
||||
a.xt("ag", roomId, "bob", 1);
|
||||
@@ -234,7 +238,7 @@ const run = async () => {
|
||||
assert.deepStrictEqual((await a.nextXt("ds")).slice(2), ["0", "0", "1"]);
|
||||
|
||||
// --- shops, clothing, animals and pets (Carol watches from the same den)
|
||||
const carol = await (await postJson(`${BASE}/authenticate`, {username: "Carol", password: "Password03"})).json();
|
||||
const carol = await (await postJson(`${BASE}/authenticate`, {username: "Carol", password: "KettlePass03"})).json();
|
||||
const c = new GameClient();
|
||||
await c.connect();
|
||||
await c.logIn("Carol", carol.auth_token);
|
||||
@@ -394,7 +398,7 @@ const run = async () => {
|
||||
{
|
||||
const stranger = new GameClient();
|
||||
await stranger.connect();
|
||||
await stranger.logIn("Dave", (await (await postJson(`${BASE}/authenticate`, {username: "Dave", password: "DavePass01"})).json()).auth_token);
|
||||
await stranger.logIn("Dave", (await (await postJson(`${BASE}/authenticate`, {username: "Dave", password: "TulipKettle01"})).json()).auth_token);
|
||||
stranger.xt("dj", 1, "denAlice", 1, -1);
|
||||
assert.strictEqual((await stranger.nextXt("rj"))[2], "0");
|
||||
stranger.socket.destroy();
|
||||
@@ -429,7 +433,7 @@ const run = async () => {
|
||||
assert.deepStrictEqual((await a.nextXt("di")).slice(3, 4), ["1"]);
|
||||
|
||||
// --- no game account has admin powers: "foo" is an ordinary player now
|
||||
const foo = await (await postJson(`${BASE}/authenticate`, {username: "foo", password: "Password04"})).json();
|
||||
const foo = await (await postJson(`${BASE}/authenticate`, {username: "foo", password: "KettlePass04"})).json();
|
||||
const f = new GameClient();
|
||||
await f.connect();
|
||||
const fooLogin = await f.logIn("foo", foo.auth_token);
|
||||
@@ -521,14 +525,14 @@ const run = async () => {
|
||||
// names sign-up would refuse are fine from the panel, and can log in.
|
||||
for (const odd of ["x", "~*Bob*~ <3", "Ünïcødé 名前", "a name well past twenty characters"]) {
|
||||
assert.strictEqual((await panel("account", {username: "Bob", action: "rename", newName: odd}, admin)).status, 200);
|
||||
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: odd, password: "Password02"})).status, 200);
|
||||
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: odd, password: "KettlePass02"})).status, 200);
|
||||
assert.strictEqual((await panel("account", {username: odd, action: "rename", newName: "Bob"}, admin)).status, 200);
|
||||
}
|
||||
assert.strictEqual((await registerJson({username: "x", password: "Password09"})).status, 400); // sign-up rules unchanged
|
||||
assert.strictEqual((await registerJson({username: "x", password: "KettlePass09"})).status, 400); // sign-up rules unchanged
|
||||
const renamed = await panel("account", {username: "Bob", action: "rename", newName: "Robert"}, admin);
|
||||
assert.deepStrictEqual([renamed.status, renamed.data.username], [200, "Robert"]);
|
||||
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Bob", password: "Password02"})).status, 401);
|
||||
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "robert", password: "Password02"})).status, 200);
|
||||
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Bob", password: "KettlePass02"})).status, 401);
|
||||
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "robert", password: "KettlePass02"})).status, 200);
|
||||
assert.ok(!(await panel("accounts", undefined, admin)).data.accounts.some(account => account.username === "Bob"));
|
||||
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);
|
||||
@@ -536,7 +540,7 @@ const run = async () => {
|
||||
// A new password for a player: the old one and old tokens stop working.
|
||||
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: "Password04"})).status, 401);
|
||||
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: "delete"}, admin)).status, 200);
|
||||
@@ -624,13 +628,13 @@ const run = async () => {
|
||||
assert.strictEqual((await (await fetch(`${BASE}/flashvars`)).json()).loginChoices, true);
|
||||
// (a fresh account: Carol is banned by now, and a banned account's
|
||||
// sign-in is refused with "account_banned", so it gets no token.)
|
||||
assert.strictEqual((await registerJson({username: "Erin", password: "Password05"})).status, 200);
|
||||
const chosen = await (await postJson(`${BASE}/authenticate`, {username: "Erin", password: "Password05",
|
||||
assert.strictEqual((await registerJson({username: "Erin", password: "KettlePass05"})).status, 200);
|
||||
const chosen = await (await postJson(`${BASE}/authenticate`, {username: "Erin", password: "KettlePass05",
|
||||
login_choices: {accountType: 0, isGuide: true, membershipDays: 12, isModerator: "yes"}})).json();
|
||||
assert.strictEqual((await (await fetch(`${BASE}/player`, {headers: {Authorization: `Bearer ${chosen.auth_token}`}})).json()).game_account_type, 0);
|
||||
a.xt("ag", denId, "Erin", 0);
|
||||
assert.deepStrictEqual((await a.untilXt("ag")).slice(5, 7), ["0", "1"]); // account type, guide
|
||||
await postJson(`${BASE}/authenticate`, {username: "Erin", password: "Password05"}); // and back to normal
|
||||
await postJson(`${BASE}/authenticate`, {username: "Erin", password: "KettlePass05"}); // and back to normal
|
||||
a.xt("ag", denId, "Erin", 0);
|
||||
assert.deepStrictEqual((await a.untilXt("ag")).slice(5, 7), ["2", "0"]);
|
||||
|
||||
@@ -645,7 +649,7 @@ const run = async () => {
|
||||
assert.strictEqual((await a.untilXt("ap"))[2], "1");
|
||||
const late = new GameClient();
|
||||
await late.connect();
|
||||
const dev = await (await postJson(`${BASE}/authenticate`, {username: "Alice", password: "Password01", login_choices: {accountType: 4, membershipDays: 7}})).json();
|
||||
const dev = await (await postJson(`${BASE}/authenticate`, {username: "Alice", password: "KettlePass01", login_choices: {accountType: 4, membershipDays: 7}})).json();
|
||||
const devLogin = await late.logIn("Alice", dev.auth_token);
|
||||
assert.deepStrictEqual([devLogin.params.accountType, devLogin.params.numDaysLeftOnSubscription, devLogin.params.isGuide, devLogin.params.isModerator], [4, 7, false, false]);
|
||||
assert.deepStrictEqual((await late.untilXt("xcc")).slice(2, 4), ["1", String(0xFD000000)]); // the table at login
|
||||
|
||||
+87
-3
@@ -73,8 +73,14 @@ const arrive = async (username, password, room, totp, onLogin = async () => {})
|
||||
assert.strictEqual(login.status, "1");
|
||||
await onLogin(client);
|
||||
client.xt("rj", 1, room, 1, 0, 0);
|
||||
const rj = await client.untilXt("rj");
|
||||
let rj = await client.untilXt("rj");
|
||||
await client.untilXt("rp");
|
||||
// a session's first room is always a spawn room (lib/world.js joinRoom)
|
||||
if (rj[3] !== room) {
|
||||
client.xt("rj", rj[4], room, 1, 0, 0);
|
||||
rj = await client.untilXt("rj");
|
||||
await client.untilXt("rp");
|
||||
}
|
||||
client.xt("au", rj[4], 1, 400, 400, 14, 1);
|
||||
return {client, login, roomId: rj[4], room: rj[3]};
|
||||
};
|
||||
@@ -106,7 +112,7 @@ const untilChat = async (client, text) => {
|
||||
|
||||
const run = async () => {
|
||||
const registerJson = body => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({avatarType: 1, agreed: true, ...body})});
|
||||
const people = {Mira: "Password11", Hal: "Password12", Pip: "Password13", Ann: "Password14"};
|
||||
const people = {Mira: "KettlePass11", Hal: "KettlePass12", Pip: "KettlePass13", Ann: "KettlePass14"};
|
||||
for (const [username, password] of Object.entries(people)) {
|
||||
assert.strictEqual((await registerJson({username, password})).status, 200);
|
||||
}
|
||||
@@ -163,6 +169,8 @@ const run = async () => {
|
||||
|
||||
// summon: Pip is brought from Sarepia to Mira in the township
|
||||
say(mira.client, mira.roomId, "!summon Pip");
|
||||
// ... onto the spot where Mira stands, when the room has loaded ("xgt")
|
||||
assert.deepStrictEqual((await pip.client.untilXt("xgt")).slice(2), ["400", "400", "0"]);
|
||||
assert.strictEqual((await pip.client.untilXt("rj"))[3], TOWNSHIP);
|
||||
assert.strictEqual(await nextBox(mira.client), "Pip was brought here.");
|
||||
|
||||
@@ -179,7 +187,11 @@ const run = async () => {
|
||||
|
||||
// goto: Mira goes to Ann in Sarepia
|
||||
say(mira.client, mira.roomId, "!goto Ann");
|
||||
assert.deepStrictEqual((await mira.client.untilXt("xgt")).slice(2), ["400", "400", "0"]);
|
||||
assert.strictEqual((await mira.client.untilXt("rj"))[3], SAREPIA);
|
||||
// in the same room already: straight onto her
|
||||
say(mira.client, ann.roomId, "!goto Ann");
|
||||
assert.deepStrictEqual((await mira.client.untilXt("xgt")).slice(2), ["400", "400", "1"]);
|
||||
|
||||
// a warning: the game's own popup for the reason ("fw", 1 = bullying),
|
||||
// kept on the account; a message box; the count; then kick disconnects
|
||||
@@ -243,6 +255,22 @@ const run = async () => {
|
||||
assert.deepStrictEqual([pipPage.warningList[0].reason, pipPage.warningList[0].note, pipPage.warningList[0].by], ["scamming", "fake trade", "Mira"]);
|
||||
assert.strictEqual(pipPage.warningList[0].seen, true);
|
||||
|
||||
// mod notes: for staff, never the player; removed by their writer or an admin
|
||||
assert.strictEqual((await modPage("/mod/api/act", {username: "Pip", action: "note", text: " talked about trading, seemed fine "})).data.ok, "Note added.");
|
||||
assert.match((await modPage("/mod/api/act", {username: "Pip", action: "note", text: " "})).data.error, /Write the note first/);
|
||||
assert.strictEqual((await halPage("/mod/api/act", {username: "Pip", action: "note", text: "keeps asking for free items"})).data.ok, "Note added.");
|
||||
const notes = (await modPage("/mod/api/player?username=Pip")).data.notes;
|
||||
assert.deepStrictEqual(notes.map(note => `${note.by}: ${note.text}`), ["Hal: keeps asking for free items", "Mira: talked about trading, seemed fine"]);
|
||||
assert.match((await modPage("/mod/api/act", {username: "Pip", action: "deleteNote", id: notes[0].id})).data.error, /Only whoever wrote a note/);
|
||||
assert.strictEqual((await halPage("/mod/api/act", {username: "Pip", action: "deleteNote", id: notes[0].id})).data.ok, "Note removed.");
|
||||
assert.match((await halPage("/mod/api/act", {username: "Mira", action: "note", text: "x"})).data.error, /your rank or above/);
|
||||
say(mira.client, ann.roomId, "!note Pip asked about the rules");
|
||||
assert.strictEqual(await nextBox(mira.client), "Note on Pip added.");
|
||||
say(mira.client, ann.roomId, "!notes Pip");
|
||||
assert.match(await nextBox(mira.client), /^Notes on Pip: \S+ Mira: asked about the rules \| \S+ Mira: talked about trading, seemed fine$/);
|
||||
say(mira.client, ann.roomId, "!notes Nobody");
|
||||
assert.strictEqual(await nextBox(mira.client), "No player called Nobody.");
|
||||
|
||||
// warnings while away (Ann was disconnected): kept for her next visit;
|
||||
// the fifth in 30 days silences for a day; one is taken back
|
||||
assert.match((await modPage("/mod/api/act", {username: "Ann", action: "warn", reason: "bullying"})).data.ok,
|
||||
@@ -265,11 +293,67 @@ const run = async () => {
|
||||
assert.match((await modPage("/mod/api/act", {username: "Pip", action: "summon"})).data.ok || "", /^Pip was brought to /);
|
||||
assert.strictEqual((await pip.client.untilXt("rj"))[3], SAREPIA);
|
||||
|
||||
// a custom warning: the staff member's words are what the player sees
|
||||
mira.client.xt("xmd", ann.roomId, "warn", "Pip", "custom", "no spamming please");
|
||||
assert.deepStrictEqual((await untilPopup(pip.client, "fp")).slice(2, 4), ["fp", "Warning: no spamming please"]);
|
||||
assert.strictEqual(await nextBox(mira.client), "Pip warned (custom): warning 2.");
|
||||
say(mira.client, ann.roomId, "!warn Pip custom");
|
||||
assert.match(await nextBox(mira.client), /^Use: !warn PLAYER custom TEXT/);
|
||||
assert.match((await modPage("/mod/api/act", {username: "Pip", action: "warn", reason: "custom", note: " "})).data.error, /custom warning needs its words/);
|
||||
|
||||
// invisible: gone from players' screens, still seen by staff (half
|
||||
// see-through: "xiv"), and seen moving by them; not for a helper
|
||||
// ("ac": [.., room, id, x, y, anim, username, ...]; others' may be waiting)
|
||||
const untilDrawn = async (client, username, x) => {
|
||||
for (;;) {
|
||||
const fields = await client.untilXt("ac");
|
||||
if (fields[6] === username && fields[3] === x) {
|
||||
return fields;
|
||||
}
|
||||
}
|
||||
};
|
||||
const untilRemoved = async (client, id) => {
|
||||
for (;;) {
|
||||
if ((await client.untilXt("ar"))[2] === id) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
mira.client.xt("au", ann.roomId, 1, 300, 300, 14, 1);
|
||||
const miraId = (await untilDrawn(pip.client, "Mira", "300"))[2];
|
||||
hal.client.xt("rj", 1, SAREPIA, 1, 0, 0);
|
||||
const halRj = await hal.client.untilXt("rj");
|
||||
await hal.client.untilXt("rp");
|
||||
hal.client.xt("au", halRj[4], 1, 410, 410, 14, 1);
|
||||
await untilDrawn(hal.client, "Mira", "300");
|
||||
say(mira.client, ann.roomId, "!invisible");
|
||||
await untilRemoved(pip.client, miraId);
|
||||
assert.deepStrictEqual((await hal.client.untilXt("xiv")).slice(2), [miraId, "1"]);
|
||||
assert.deepStrictEqual((await mira.client.untilXt("xiv")).slice(2), [miraId, "1"]);
|
||||
assert.match(await nextBox(mira.client), /^You are invisible: only staff see you/);
|
||||
mira.client.xt("au", ann.roomId, 1, 350, 350, 14, 0);
|
||||
for (;;) {
|
||||
const moved = await hal.client.untilXt("au");
|
||||
if (moved[3] === miraId) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// a helper may not: the window's request does nothing, the command is chat
|
||||
hal.client.xt("xiv", halRj[4]);
|
||||
say(hal.client, halRj[4], "!invisible");
|
||||
await untilChat(pip.client, "!invisible");
|
||||
// back again, where she walked to
|
||||
mira.client.xt("xiv", ann.roomId);
|
||||
assert.deepStrictEqual((await untilDrawn(pip.client, "Mira", "350")).slice(2, 5), [miraId, "350", "350"]);
|
||||
assert.deepStrictEqual((await hal.client.untilXt("xiv")).slice(2), [miraId, "0"]);
|
||||
assert.strictEqual(await nextBox(mira.client), "You can be seen again.");
|
||||
|
||||
// everything above is in the moderators' log, the in-game ones marked so
|
||||
const log = (await admin("/admin/api/moderators")).data.log.map(entry => `${entry.by} ${entry.action} ${entry.target}`);
|
||||
for (const line of ["Mira summon (in game) Pip", "Hal silence (in game) Pip", "Mira goto (in game) Ann", "Mira warn (in game) Ann",
|
||||
"Mira message (in game) Ann", "Mira kick (in game) Ann", "Mira warn Pip", "Mira summon Pip", "Mira warn Ann", "Mira unwarn Ann",
|
||||
"Mira unwarn (in game) Ann"]) {
|
||||
"Mira unwarn (in game) Ann", "Mira went invisible (in game) ", "Mira became visible (in game) ", "Mira note Pip", "Hal deleteNote Pip",
|
||||
"Mira note (in game) Pip"]) {
|
||||
assert.ok(log.includes(line), `missing from the log: ${line}\n${log.join("\n")}`);
|
||||
}
|
||||
|
||||
|
||||
+24
-4
@@ -59,7 +59,16 @@ const day = time => new Date(time).toISOString().slice(0, 10);
|
||||
fs.mkdirSync(filesDir, {recursive: true});
|
||||
|
||||
// {builds: {build: newest sale start}, rooms: {room: {build: hash of its file}}}
|
||||
let index = fs.existsSync(indexFile) ? JSON.parse(fs.readFileSync(indexFile)) : null;
|
||||
// read if it is there: no separate look first, which the file could change after
|
||||
let index = null;
|
||||
try {
|
||||
index = JSON.parse(fs.readFileSync(indexFile));
|
||||
}
|
||||
catch (err) {
|
||||
if (err.code !== "ENOENT") {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
if (!index) {
|
||||
index = {builds: {}, rooms: {}};
|
||||
const jobs = [];
|
||||
@@ -83,14 +92,25 @@ const day = time => new Date(time).toISOString().slice(0, 10);
|
||||
const [build, room] = jobs.pop();
|
||||
const body = await download(build, `roomDefs/${room}.xroom`);
|
||||
const hash = body ? crypto.createHash("sha1").update(body).digest("hex").slice(0, 12) : null;
|
||||
if (body && !fs.existsSync(path.join(filesDir, hash))) {
|
||||
fs.writeFileSync(path.join(filesDir, hash), body);
|
||||
// named by its own hash, so one already there is this same file: "wx"
|
||||
// writes only a new one, in the one step.
|
||||
if (body) {
|
||||
try {
|
||||
fs.writeFileSync(path.join(filesDir, hash), body, {flag: "wx"});
|
||||
}
|
||||
catch (err) {
|
||||
if (err.code !== "EEXIST") {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
(index.rooms[room] = index.rooms[room] || {})[build] = hash;
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({length: WORKERS}, worker));
|
||||
fs.writeFileSync(indexFile, JSON.stringify(index));
|
||||
// written whole under another name, then put in its place
|
||||
fs.writeFileSync(`${indexFile}.tmp`, JSON.stringify(index));
|
||||
fs.renameSync(`${indexFile}.tmp`, indexFile);
|
||||
}
|
||||
|
||||
console.log("Builds, by the newest sale start in each:");
|
||||
|
||||
Reference in new issue
Block a user