mirror of
https://github.com/burrow-dev/burrow-server.git
synced 2026-11-18 17:27:50 -05:00
Custom items made while the server runs, and a Developer role
Staff with the new items.create permission (admins, and the new Developer role) make clothing and den items from the game's own art: an existing item under a new id (50000 on), name, price, members-only flag and choice of its colours. No restart of the server or of anyone's game: - lib/customitems.js keeps them (custom_items table) and puts them into the server's tables and the packs new games fetch (defpacks.setCustomItem) - games already playing get the def rows in "xdi"; so does every game at login. The client adds them (ItemXtCommManager.addItemDefs, DenXtCommManager.addDenItemDefs, both now in swf-src; rebuild with tools/build-client.sh) - they are sold first in the two shops of oddities and found by the item finder; an item can be renamed, repriced, recoloured and taken off sale, never deleted (players may own it) - the moderator panel has an Items page; in game, "!item clothing|den ID NAME" and "!item list" - the Developer role holds only staff.list and items.create. The panel's pages that show players (players, chat, reports, requests, bans, paintings) now need player.view, which helpers and up have test/items.js covers it end to end, including a restart (withServer can keep its database for that). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
2fba9f1612
commit
6563d5de99
18 files changed
+3853
-23
No files matched your search
+5
-1
@@ -21,6 +21,7 @@ const MAX_FAVOURITES = 200; // finder items remembered per account
|
||||
const STARTER_ANIMALS = [1, 4, 5, 6, 7, 8, 13, 18, 24];
|
||||
|
||||
let catalog = null;
|
||||
let catalogVersion = -1; // defpacks.customVersion() it was built at: staff add items as the server runs
|
||||
|
||||
const buildCatalog = () => [
|
||||
...defpacks.clothingIds().map(id => {
|
||||
@@ -37,7 +38,10 @@ const buildCatalog = () => [
|
||||
// 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) => {
|
||||
catalog = catalog || buildCatalog();
|
||||
if (!catalog || catalogVersion !== defpacks.customVersion()) {
|
||||
catalog = buildCatalog();
|
||||
catalogVersion = defpacks.customVersion();
|
||||
}
|
||||
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)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const chatlog = require("./chatlog.js");
|
||||
const customItems = require("./customitems.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const disguises = require("./disguises.js");
|
||||
const dens = require("./dens.js");
|
||||
@@ -509,6 +510,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
|
||||
const MAX_STAFF_HOURS = 24 * 365 * 10;
|
||||
const MAX_WARNING = 200;
|
||||
const MAX_WARNINGS_SHOWN = 5;
|
||||
const MAX_ITEMS_LISTED = 8;
|
||||
|
||||
const staffMay = (session, permission) => {
|
||||
const moderation = staffModeration();
|
||||
@@ -563,6 +565,35 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
|
||||
modlog.record(session.account.username, `${action} (in game)`, target.account.username, detail);
|
||||
|
||||
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;
|
||||
// everyone has it at once. the moderator panel's Items page does more.
|
||||
// "!item list": the latest made.
|
||||
item: {
|
||||
permission: "items.create",
|
||||
run(session, words) {
|
||||
const usage = "Use: !item clothing|den ID NAME, or !item list";
|
||||
if ((words[0] || "").toLowerCase() === "list") {
|
||||
const latest = customItems.list().slice(0, MAX_ITEMS_LISTED)
|
||||
.map(entry => `${entry.id} ${entry.name} (${entry.kind === "den" ? "den" : "clothing"}${entry.inShop ? "" : ", off sale"})`);
|
||||
tell(session, latest.length ? `Latest items made: ${latest.join("; ")}` : "No items made yet.");
|
||||
return;
|
||||
}
|
||||
const kind = (words[0] || "").toLowerCase();
|
||||
if (!customItems.KINDS.includes(kind) || !/^\d+$/.test(words[1] || "") || words.length < 3) {
|
||||
tell(session, usage);
|
||||
return;
|
||||
}
|
||||
const result = customItems.create(kind, {base: words[1], name: words.slice(2).join(" ")}, session.account.username);
|
||||
if (result.error) {
|
||||
tell(session, result.error);
|
||||
return;
|
||||
}
|
||||
const {item} = result;
|
||||
tell(session, `Made ${item.name}, ${kind === "den" ? "den item" : "clothing"} ${item.id}. It is in the item finder now.`);
|
||||
modlog.record(session.account.username, "item made (in game)", "", `${kind} ${item.id} ${item.name}`);
|
||||
},
|
||||
},
|
||||
staff: {
|
||||
permission: "staff.list",
|
||||
run(session) {
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
|
||||
// items the staff make while the server runs, with no restart of the server
|
||||
// or of anybody's game. each is an existing item's art (the clothing piece
|
||||
// or den item it is made from) under an id, name, price and colours of its
|
||||
// own. the server's tables and the packs new games fetch have it at once
|
||||
// (defpacks.setCustomItem); games already playing are sent its def row
|
||||
// ("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.
|
||||
|
||||
// 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
|
||||
// server's other added strings (lib/defpacks.js ADDED_STRINGS, 9000001 on).
|
||||
const FIRST_ID = 50000;
|
||||
const STRING_BASE = {clothing: 9100000, den: 9200000};
|
||||
const KINDS = ["clothing", "den"];
|
||||
const MAX_NAME = 40;
|
||||
const MAX_COST = 1000000;
|
||||
const MAX_COLOURS = 16;
|
||||
const MAX_ITEMS = 5000; // per kind
|
||||
const CHUNK = 40; // def rows per "xdi" message
|
||||
const TYPE_CLOTHING = "1";
|
||||
const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items that can be copied: plain, mannequin
|
||||
const CURRENCY_GEMS = "0";
|
||||
|
||||
const SCHEMA = `CREATE TABLE IF NOT EXISTS custom_items (
|
||||
kind TEXT NOT NULL, id INTEGER NOT NULL, base INTEGER NOT NULL, name TEXT NOT NULL,
|
||||
cost INTEGER NOT NULL, members INTEGER NOT NULL, colors TEXT NOT NULL, in_shop INTEGER NOT NULL,
|
||||
created_by TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (kind, id))`;
|
||||
|
||||
const items = new Map(KINDS.map(kind => [kind, new Map()])); // kind -> id -> entry
|
||||
let made = 0; // entries in the order they were made (`seq`), for lists
|
||||
let broadcast = () => {}; // (cmd, ...params) to every game playing; set by lib/world.js
|
||||
|
||||
const db = () => accounts.database();
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
|
||||
const baseDef = (kind, id) => (kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id));
|
||||
|
||||
// the def row of an entry: its base's row with its own id, name, price and
|
||||
// colours, always on sale and marked new.
|
||||
const rowOf = entry => {
|
||||
const base = baseDef(entry.kind, entry.base);
|
||||
const own = {
|
||||
id: String(entry.id),
|
||||
membersOnly: entry.members ? "1" : "0",
|
||||
itemStatus: "1",
|
||||
availabilityStartTime: "0",
|
||||
availabilityEndTime: "0",
|
||||
currencyType: CURRENCY_GEMS,
|
||||
recycleValue: "0",
|
||||
combinedCost: "",
|
||||
};
|
||||
if (entry.kind === "den") {
|
||||
return {...base, ...own, nameStrId: String(STRING_BASE.den + entry.id - FIRST_ID), cost: String(entry.cost)};
|
||||
}
|
||||
return {...base, ...own, titleStrId: String(STRING_BASE.clothing + entry.id - FIRST_ID), value: String(entry.cost), colors: entry.colors.join(","), isGiftable: "1"};
|
||||
};
|
||||
|
||||
const apply = entry => defpacks.setCustomItem(entry.kind, rowOf(entry), entry.name, entry.inShop);
|
||||
|
||||
// "xdi" [.., .., kind, json]: def rows with their names, as JSON. a field
|
||||
// may not hold "%" (lib/sfs.js drops it), so a "%" in a name is written as
|
||||
// JSON's %.
|
||||
const messages = entries => {
|
||||
const out = [];
|
||||
for (const kind of KINDS) {
|
||||
const rows = entries.filter(entry => entry.kind === kind).map(entry => ({...rowOf(entry), name: entry.name}));
|
||||
for (let at = 0; at < rows.length; at += CHUNK) {
|
||||
out.push([kind, JSON.stringify(rows.slice(at, at + CHUNK)).replace(/%/g, "\\u0025")]);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const announce = entry => {
|
||||
for (const params of messages([entry])) {
|
||||
broadcast("xdi", ...params);
|
||||
}
|
||||
};
|
||||
|
||||
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,
|
||||
});
|
||||
|
||||
const load = () => {
|
||||
db().exec(SCHEMA);
|
||||
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`);
|
||||
continue;
|
||||
}
|
||||
items.get(entry.kind).set(entry.id, entry);
|
||||
apply(entry);
|
||||
}
|
||||
console.log(`[custom items] ${items.get("clothing").size} clothing, ${items.get("den").size} den items`);
|
||||
};
|
||||
|
||||
// checks what staff typed. returns {error} or the cleaned values.
|
||||
const NAME_PATTERN = /^[\p{L}\p{N} '&!?.,:()#+\-]+$/u;
|
||||
const clean = (kind, fields, current = null) => {
|
||||
const out = {};
|
||||
if (fields.name !== undefined || !current) {
|
||||
const name = String(fields.name || "").trim().replace(/\s+/g, " ");
|
||||
if (!name || name.length > MAX_NAME || !NAME_PATTERN.test(name)) {
|
||||
return {error: `A name of 1 to ${MAX_NAME} letters, numbers, spaces and simple punctuation, please.`};
|
||||
}
|
||||
out.name = name;
|
||||
}
|
||||
if (fields.cost !== undefined || !current) {
|
||||
const cost = Number(fields.cost === undefined || fields.cost === "" ? 0 : fields.cost);
|
||||
if (!Number.isInteger(cost) || cost < 0 || cost > MAX_COST) {
|
||||
return {error: `A price from 0 to ${MAX_COST} gems, please.`};
|
||||
}
|
||||
out.cost = cost;
|
||||
}
|
||||
if (fields.members !== undefined || !current) {
|
||||
out.members = fields.members === true || fields.members === "1" || fields.members === 1;
|
||||
}
|
||||
if (fields.inShop !== undefined || !current) {
|
||||
out.inShop = fields.inShop === undefined ? true : fields.inShop === true || fields.inShop === "1" || fields.inShop === 1;
|
||||
}
|
||||
if (kind === "clothing" && (fields.colors !== undefined || !current)) {
|
||||
const base = baseDef(kind, current ? current.base : fields.base);
|
||||
const baseColours = String(base.colors).split(",").map(Number);
|
||||
let colors = fields.colors;
|
||||
if (colors === undefined || colors === null || colors === "") {
|
||||
colors = baseColours;
|
||||
}
|
||||
else {
|
||||
colors = (Array.isArray(colors) ? colors : String(colors).split(",")).map(value => Number(String(value).trim()));
|
||||
}
|
||||
// a colour is a packed palette number, as in the packs (or a custom colour
|
||||
// id, lib/colours.js).
|
||||
if (colors.length === 0 || colors.length > MAX_COLOURS || !colors.every(value => Number.isInteger(value) && value >= 0 && value <= 0xFFFFFFFF)) {
|
||||
return {error: `1 to ${MAX_COLOURS} colours, each a number as the packs have them.`};
|
||||
}
|
||||
out.colors = colors;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
// makes an item from `base`, an existing clothing piece or den item.
|
||||
// returns {item} or {error}.
|
||||
const create = (kind, fields, by) => {
|
||||
if (!KINDS.includes(kind)) {
|
||||
return {error: "The kind is clothing or den."};
|
||||
}
|
||||
const baseId = Number(fields.base);
|
||||
const base = Number.isInteger(baseId) ? baseDef(kind, baseId) : null;
|
||||
if (!base || baseId >= FIRST_ID) {
|
||||
return {error: `No ${kind === "den" ? "den item" : "clothing"} with the id ${fields.base} to make it from (it must be one of the game's own).`};
|
||||
}
|
||||
if (kind === "clothing" && base.type !== TYPE_CLOTHING) {
|
||||
return {error: `${baseId} is a body part, not clothing.`};
|
||||
}
|
||||
if (kind === "den" && !OFFERED_SPECIAL_TYPES.includes(base.specialType)) {
|
||||
return {error: `Den item ${baseId} does something of its own (a portal, a game, ...) and cannot be copied.`};
|
||||
}
|
||||
if (items.get(kind).size >= MAX_ITEMS) {
|
||||
return {error: "There are as many custom items of that kind as there can be."};
|
||||
}
|
||||
const values = clean(kind, {...fields, base: baseId});
|
||||
if (values.error) {
|
||||
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);
|
||||
items.get(kind).set(id, entry);
|
||||
apply(entry);
|
||||
announce(entry);
|
||||
return {item: entry};
|
||||
};
|
||||
|
||||
// changes the name, price, members-only, colours or whether it is on sale.
|
||||
const update = (kind, id, fields) => {
|
||||
const entry = items.has(kind) && items.get(kind).get(Number(id));
|
||||
if (!entry) {
|
||||
return {error: "No such custom item."};
|
||||
}
|
||||
const values = clean(kind, fields, entry);
|
||||
if (values.error) {
|
||||
return values;
|
||||
}
|
||||
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);
|
||||
apply(entry);
|
||||
announce(entry);
|
||||
return {item: entry};
|
||||
};
|
||||
|
||||
const list = () => KINDS.flatMap(kind => [...items.get(kind).values()])
|
||||
.sort((one, other) => other.seq - one.seq);
|
||||
|
||||
module.exports = {
|
||||
KINDS,
|
||||
FIRST_ID,
|
||||
load,
|
||||
create,
|
||||
update,
|
||||
list,
|
||||
get: (kind, id) => (items.has(kind) && items.get(kind).get(Number(id))) || null,
|
||||
// the base an item's art is from, for a list showing what each is.
|
||||
baseName: entry => {
|
||||
const def = baseDef(entry.kind, entry.base);
|
||||
return def ? defpacks.string(entry.kind === "den" ? def.nameStrId : def.titleStrId) || String(def.abbrName || entry.base) : String(entry.base);
|
||||
},
|
||||
// every custom item, for a game logging in.
|
||||
sendAll(session) {
|
||||
for (const params of messages(list().reverse())) {
|
||||
session.sendXt("xdi", -1, ...params);
|
||||
}
|
||||
},
|
||||
// lib/world.js says how to reach every game playing.
|
||||
connect(broadcastXt) {
|
||||
broadcast = broadcastXt;
|
||||
},
|
||||
};
|
||||
+56
-3
@@ -188,7 +188,26 @@ const withLineBreaks = pack => {
|
||||
return pack;
|
||||
};
|
||||
|
||||
const withAddedStrings = pack => withLineBreaks(withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings())));
|
||||
// items the staff make while the server runs (lib/customitems.js): an
|
||||
// existing item's art under a new id, name and price. their rows and names
|
||||
// are kept here, and go into the packs like the rows above, after the
|
||||
// renaming (a name staff chose is left as they wrote it).
|
||||
const customRows = new Map([[DEF_ITEM, new Map()], [DEF_DEN_ITEM, new Map()]]); // pack -> id -> row
|
||||
const customStrings = {}; // localization id -> name
|
||||
const customInShop = {clothing: new Set(), den: new Set()}; // ids on sale
|
||||
let customVersion = 0; // goes up with every change, for anything that keeps a list of items
|
||||
|
||||
const withCustomRows = id => pack => {
|
||||
const at = new Map(Object.entries(pack).map(([key, def]) => [String(def.id), key]));
|
||||
let next = Math.max(-1, ...Object.keys(pack).map(Number).filter(Number.isInteger)) + 1;
|
||||
for (const row of customRows.get(id).values()) {
|
||||
// a changed row replaces the one the pack was made with.
|
||||
pack[at.has(row.id) ? at.get(row.id) : next++] = {...row};
|
||||
}
|
||||
return pack;
|
||||
};
|
||||
|
||||
const withAddedStrings = pack => Object.assign(withLineBreaks(withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings()))), customStrings);
|
||||
|
||||
// the extra music tracks (lib/extramusic.js), as den items like the
|
||||
// official tracks.
|
||||
@@ -249,8 +268,8 @@ const SHARED_CHANGES = new Map([
|
||||
[DEF_ROOM, withRestoredRooms],
|
||||
[DEF_PARTY, withRestoredParties],
|
||||
[DEF_DEN_ROOM, withoutPrices(DEF_DEN_ROOM, withAddedDens)],
|
||||
[DEF_DEN_ITEM, withoutPrices(DEF_DEN_ITEM, withExtraMusic)],
|
||||
[DEF_ITEM, withoutPrices(DEF_ITEM)],
|
||||
[DEF_DEN_ITEM, withoutPrices(DEF_DEN_ITEM, pack => withCustomRows(DEF_DEN_ITEM)(withExtraMusic(pack)))],
|
||||
[DEF_ITEM, withoutPrices(DEF_ITEM, withCustomRows(DEF_ITEM))],
|
||||
[DEF_DIAMOND, withoutPrices(DEF_DIAMOND)],
|
||||
[DEF_PET, withoutPrices(DEF_PET)],
|
||||
[DEF_LOCALIZATION_EN, withAddedStrings],
|
||||
@@ -455,8 +474,42 @@ const init = async () => {
|
||||
console.log(`[defs] ${avatarDefs.size} avatars, ${roomDefsByPath.size} rooms, ${clothingIds.length} clothing items, ${denItemIds.length} den items, ${petIds.length} pets`);
|
||||
};
|
||||
|
||||
// puts a custom item (lib/customitems.js) in, or changes one already in:
|
||||
// `kind` "clothing" or "den", `row` its full def row (strings, as in the
|
||||
// packs), `name` its English name under the row's string id. the server's
|
||||
// tables have it at once, and the packs clients fetch are made again.
|
||||
// `inShop` false takes it out of the shop (the ones players have still draw).
|
||||
const setCustomItem = (kind, row, name, inShop = true) => {
|
||||
const pack = kind === "den" ? DEF_DEN_ITEM : DEF_ITEM;
|
||||
const id = Number(row.id);
|
||||
const stringId = kind === "den" ? row.nameStrId : row.titleStrId;
|
||||
customRows.get(pack).set(id, row);
|
||||
customStrings[stringId] = name;
|
||||
strings[stringId] = name;
|
||||
stringIds = null;
|
||||
if (packs.has(pack)) {
|
||||
packs.set(pack, [...packs.get(pack).filter(def => Number(def.id) !== id), row]);
|
||||
}
|
||||
if (kind === "den") {
|
||||
denItemDefs.set(id, row);
|
||||
denItemIds = denItemIds.includes(id) ? denItemIds : [...denItemIds, id];
|
||||
}
|
||||
else {
|
||||
itemDefs.set(id, row);
|
||||
clothingIds = clothingIds.includes(id) ? clothingIds : [...clothingIds, id];
|
||||
}
|
||||
customInShop[kind][inShop ? "add" : "delete"](id);
|
||||
clientPackBodies.delete(pack);
|
||||
clientPackBodies.delete(DEF_LOCALIZATION_EN);
|
||||
customVersion++;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
init,
|
||||
setCustomItem,
|
||||
// the custom items on sale, the newest first.
|
||||
customShopIds: kind => [...customInShop[kind]].reverse(),
|
||||
customVersion: () => customVersion,
|
||||
load,
|
||||
itemDef: id => itemDefs.get(Number(id)),
|
||||
clothingIds: () => clothingIds,
|
||||
|
||||
@@ -8,6 +8,8 @@ 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 defpacks = require("./defpacks.js");
|
||||
const limits = require("./limits.js");
|
||||
const manage = require("./manage.js");
|
||||
const masterpieces = require("./masterpieces.js");
|
||||
@@ -376,7 +378,25 @@ const handle = async (req, res, url, from, web) => {
|
||||
case "GET /mod/api/me":
|
||||
reply(200, {username: mod.username, role: roles.roleOf(mod), permissions: roles.permissionsOf(mod)});
|
||||
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);
|
||||
return;
|
||||
}
|
||||
// everything else shows players and what they did: not for a role that
|
||||
// only makes things.
|
||||
if (!roles.can(mod, "player.view")) {
|
||||
reply(403, {error: "Your role does not allow that."});
|
||||
return;
|
||||
}
|
||||
|
||||
switch (route) {
|
||||
case "GET /mod/api/overview":
|
||||
reply(200, {online: world.players().length, reports: reports.openCount(), requests: support.nameRequests(false).length + bans.openAppeals(),
|
||||
paintings: masterpieces.list(masterpieces.PENDING).length});
|
||||
@@ -511,6 +531,48 @@ 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
|
||||
// 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) => {
|
||||
switch (route) {
|
||||
case "GET /mod/api/items":
|
||||
reply(200, {items: customItems.list().map(entry => ({...entry, baseName: customItems.baseName(entry)})), firstId: customItems.FIRST_ID});
|
||||
return;
|
||||
case "GET /mod/api/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);
|
||||
if (!def || id >= customItems.FIRST_ID || (kind === "clothing" && def.type !== "1")) {
|
||||
reply(404, {error: `No ${kind === "den" ? "den item" : "clothing"} with that id.`});
|
||||
return;
|
||||
}
|
||||
reply(200, kind === "den"
|
||||
? {kind, id, name: defpacks.string(def.nameStrId) || def.abbrName, art: def.abbrName, cost: Number(def.cost)}
|
||||
: {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": {
|
||||
const kind = String(body.kind || "");
|
||||
const result = body.action === "update"
|
||||
? customItems.update(kind, body.id, body)
|
||||
: body.action === "create" ? customItems.create(kind, body, mod.username) : {error: "Unknown action."};
|
||||
if (result.error) {
|
||||
done(result);
|
||||
return;
|
||||
}
|
||||
const {item} = result;
|
||||
done({ok: `${item.name} (${item.kind === "den" ? "den item" : "clothing"} ${item.id}) ${body.action === "update" ? "changed" : "made"}.`},
|
||||
body.action === "update" ? "item changed" : "item made", "", `${item.kind} ${item.id} ${item.name}`);
|
||||
return;
|
||||
}
|
||||
default:
|
||||
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));
|
||||
|
||||
+7
-2
@@ -14,6 +14,7 @@ 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",
|
||||
"staff.list": "see which staff are online (!staff)",
|
||||
"player.warn": "warn a player and send them a message (!warn, !warnings, !message)",
|
||||
"player.goto": "go to the room a player is in (!goto)",
|
||||
@@ -23,13 +24,17 @@ const PERMISSIONS = {
|
||||
"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)",
|
||||
};
|
||||
|
||||
const HELPER = ["staff.list", "player.warn", "player.goto", "chat.silence"];
|
||||
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 ADMIN = [...MODERATOR];
|
||||
const ADMIN = [...MODERATOR, "items.create"];
|
||||
// a developer makes things, and moderates nobody.
|
||||
const DEVELOPER = ["staff.list", "items.create"];
|
||||
|
||||
const ROLES = {
|
||||
developer: {rank: 1, label: "Developer", permissions: DEVELOPER},
|
||||
helper: {rank: 1, label: "Helper", permissions: HELPER},
|
||||
moderator: {rank: 2, label: "Moderator", permissions: MODERATOR},
|
||||
admin: {rank: 3, label: "Admin", permissions: ADMIN},
|
||||
|
||||
+14
-1
@@ -5,6 +5,7 @@ const achievements = require("./achievements.js");
|
||||
const adopt = require("./adopt.js");
|
||||
const config = require("../config.js");
|
||||
const colours = require("./colours.js");
|
||||
const customItems = require("./customitems.js");
|
||||
const roles = require("./roles.js");
|
||||
const commandModule = require("./commands.js");
|
||||
const limits = require("./limits.js");
|
||||
@@ -314,6 +315,9 @@ const login = (session, msg) => {
|
||||
for (const chunk of colours.chunks()) {
|
||||
session.sendXt("xcc", -1, chunk.length, ...chunk.flat());
|
||||
}
|
||||
// and the items staff have made (lib/customitems.js), for a game started
|
||||
// before they were.
|
||||
customItems.sendAll(session);
|
||||
sendFilter(session);
|
||||
buddies.announce(account);
|
||||
};
|
||||
@@ -423,6 +427,8 @@ const sortStock = () => {
|
||||
// has the den items, the one in the Zios archives the clothing. see
|
||||
// oddDenItemIds in lib/defpacks.js.
|
||||
const ODDITY_SHOPS = new Map([[396, () => defpacks.oddDenItemIds()], [666, () => defpacks.oddClothingIds()]]);
|
||||
// the items staff have made (lib/customitems.js) are sold there too, first.
|
||||
const CUSTOM_ITEM_SHOPS = new Map([[396, "den"], [666, "clothing"]]);
|
||||
const ticketStock = kind => sortStock()[kind];
|
||||
// the den shops of the lands (Coral Canyons, Deep Blue) and the one inside
|
||||
// a den: lists that mix kinds, selling den rooms.
|
||||
@@ -475,6 +481,13 @@ const makeColour = (account, rgbs, asker = null) => {
|
||||
return entry;
|
||||
};
|
||||
|
||||
// a message for every game playing (custom items, lib/customitems.js).
|
||||
customItems.connect((cmd, ...params) => {
|
||||
for (const session of online.values()) {
|
||||
session.sendXt(cmd, -1, ...params);
|
||||
}
|
||||
});
|
||||
|
||||
// the account's chat filter, for its game to apply: [chosen, level, mode, own words].
|
||||
const sendFilter = session => {
|
||||
const {filter} = session.account;
|
||||
@@ -688,7 +701,7 @@ const handlers = {
|
||||
else if (ODDITY_SHOPS.has(Number(listId))) {
|
||||
// what the shop really sold comes first.
|
||||
const real = shopStock.list(listId, type);
|
||||
entries = [...new Set([...(real ? real.entries : []), ...ODDITY_SHOPS.get(Number(listId))()])];
|
||||
entries = [...new Set([...defpacks.customShopIds(CUSTOM_ITEM_SHOPS.get(Number(listId))), ...(real ? real.entries : []), ...ODDITY_SHOPS.get(Number(listId))()])];
|
||||
}
|
||||
else if (Number(listId) === DIAMOND_DEN_LIST) {
|
||||
entries = defpacks.diamondIds().filter(id => {
|
||||
|
||||
+2
-1
@@ -401,6 +401,7 @@
|
||||
<button type="button" data-action="moderator" id="moderator-toggle">Make moderator</button>
|
||||
<select id="role-select" aria-label="Staff role">
|
||||
<option value="none">No staff role</option>
|
||||
<option value="developer">Developer</option>
|
||||
<option value="helper">Helper</option>
|
||||
<option value="moderator">Moderator</option>
|
||||
<option value="admin">Admin</option>
|
||||
@@ -754,7 +755,7 @@
|
||||
tags.push(el("span", "Name rejected", "tag bad"));
|
||||
}
|
||||
if (account.moderator) {
|
||||
const label = {helper: "Helper", moderator: "Moderator", admin: "Admin"}[account.role] || "Moderator";
|
||||
const label = {developer: "Developer", helper: "Helper", moderator: "Moderator", admin: "Admin"}[account.role] || "Moderator";
|
||||
tags.push(el("span", label, "tag good"));
|
||||
}
|
||||
if (account.twoStep) {
|
||||
|
||||
+174
-10
@@ -119,6 +119,8 @@
|
||||
@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
|
||||
input, select, textarea { background: var(--bg); }
|
||||
label.check { margin: 0; color: var(--text); font-size: 14px; cursor: pointer; }
|
||||
#item-colours { display: flex; gap: 6px 14px; flex-wrap: wrap; margin-top: 8px; }
|
||||
#item-colours label.check { display: inline-flex; gap: 5px; align-items: center; }
|
||||
|
||||
#gate {
|
||||
max-width: 380px;
|
||||
@@ -255,13 +257,14 @@
|
||||
<button id="sign-out" type="button">Sign out</button>
|
||||
</header>
|
||||
<nav role="tablist">
|
||||
<button role="tab" data-tab="players" aria-selected="true">Players</button>
|
||||
<button role="tab" data-tab="chat" aria-selected="false">Chat</button>
|
||||
<button role="tab" data-tab="reports" aria-selected="false">Reports<span id="report-count"></span></button>
|
||||
<button role="tab" data-tab="requests" aria-selected="false">Requests<span id="request-count"></span></button>
|
||||
<button role="tab" data-tab="masterpieces" aria-selected="false">Masterpieces<span id="masterpiece-count"></span></button>
|
||||
<button role="tab" data-tab="bans" aria-selected="false">Bans</button>
|
||||
<button role="tab" data-tab="stats" aria-selected="false">Stats</button>
|
||||
<button role="tab" data-tab="players" data-needs="player.view" aria-selected="true">Players</button>
|
||||
<button role="tab" data-tab="chat" data-needs="player.view" aria-selected="false">Chat</button>
|
||||
<button role="tab" data-tab="reports" data-needs="player.view" aria-selected="false">Reports<span id="report-count"></span></button>
|
||||
<button role="tab" data-tab="requests" data-needs="player.view" aria-selected="false">Requests<span id="request-count"></span></button>
|
||||
<button role="tab" data-tab="masterpieces" data-needs="player.view" aria-selected="false">Masterpieces<span id="masterpiece-count"></span></button>
|
||||
<button role="tab" data-tab="bans" data-needs="player.view" aria-selected="false">Bans</button>
|
||||
<button role="tab" data-tab="stats" data-needs="player.view" aria-selected="false">Stats</button>
|
||||
<button role="tab" data-tab="items" data-needs="items.create" aria-selected="false" hidden>Items</button>
|
||||
</nav>
|
||||
|
||||
<div data-view="players">
|
||||
@@ -410,6 +413,45 @@
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div data-view="items" hidden>
|
||||
<section>
|
||||
<h2 id="item-form-title">Make an item</h2>
|
||||
<p class="hint">One of the game's items under a new name, price and colours. Players have it at once, with no restart: in the item finder, and first in the hidden shops of oddities.</p>
|
||||
<div class="actions">
|
||||
<div class="action">
|
||||
<h3>Made from</h3>
|
||||
<div class="row">
|
||||
<select id="item-kind" aria-label="Kind">
|
||||
<option value="clothing">Clothing</option>
|
||||
<option value="den">Den item</option>
|
||||
</select>
|
||||
<input id="item-base" type="number" min="1" placeholder="Id of the game's item" aria-label="Id of the item to copy">
|
||||
<button type="button" id="item-look">Look up</button></div>
|
||||
<p class="hint" id="item-base-name"></p>
|
||||
</div>
|
||||
<div class="action">
|
||||
<h3>The new item</h3>
|
||||
<div class="row"><input id="item-name" maxlength="40" placeholder="Name" aria-label="Name"></div>
|
||||
<div class="row" style="margin-top:8px"><input id="item-cost" type="number" min="0" placeholder="Price in gems" aria-label="Price in gems">
|
||||
<label class="check"><input type="checkbox" id="item-members"> Members only</label></div>
|
||||
<div id="item-colours" aria-label="Colours offered"></div>
|
||||
<div class="row" style="margin-top:12px">
|
||||
<button type="button" class="primary" id="item-save">Make it</button>
|
||||
<button type="button" id="item-cancel" hidden>Cancel</button></div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="status" id="item-status" role="status"></p>
|
||||
</section>
|
||||
<section>
|
||||
<h2>Items made</h2>
|
||||
<div class="table-wrap"><table>
|
||||
<thead><tr><th class="num">Id</th><th>Name</th><th>Made from</th><th class="num">Price</th><th>By</th><th></th></tr></thead>
|
||||
<tbody id="items"></tbody>
|
||||
</table></div>
|
||||
<div class="empty" id="no-items" hidden>None yet.</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div data-view="bans" hidden>
|
||||
<section>
|
||||
<h2>Banned and silenced</h2>
|
||||
@@ -912,13 +954,119 @@
|
||||
$("no-addresses").hidden = data.addresses.length > 0;
|
||||
};
|
||||
|
||||
// ---- items (lib/customitems.js)
|
||||
let items = [];
|
||||
let editing = null; // the item the form is changing, or null to make one
|
||||
let baseColours = []; // the colours of the item looked up
|
||||
|
||||
const showColours = (colours, chosen) => {
|
||||
$("item-colours").replaceChildren(...colours.map((colour, index) => {
|
||||
const box = el("input");
|
||||
box.type = "checkbox";
|
||||
box.value = String(colour);
|
||||
box.checked = !chosen || chosen.includes(colour);
|
||||
const label = el("label", undefined, "check");
|
||||
label.append(box, ` Colour ${index + 1}`);
|
||||
return label;
|
||||
}));
|
||||
};
|
||||
|
||||
const lookUp = async () => {
|
||||
const result = await api(`items/base?kind=${$("item-kind").value}&id=${encodeURIComponent($("item-base").value.trim())}`);
|
||||
baseColours = result.ok && result.data.colors ? result.data.colors : [];
|
||||
if (!result.ok) {
|
||||
$("item-base-name").textContent = said(result);
|
||||
showColours([]);
|
||||
return null;
|
||||
}
|
||||
if (!editing) {
|
||||
$("item-base-name").textContent = `${result.data.name || "(no name)"}: ${result.data.cost} gems in the game.`;
|
||||
if (!$("item-name").value.trim()) {
|
||||
$("item-name").value = result.data.name || "";
|
||||
}
|
||||
showColours(baseColours);
|
||||
}
|
||||
return result.data;
|
||||
};
|
||||
$("item-look").addEventListener("click", lookUp);
|
||||
$("item-kind").addEventListener("change", () => {
|
||||
$("item-base-name").textContent = "";
|
||||
showColours([]);
|
||||
});
|
||||
|
||||
const itemForm = item => {
|
||||
editing = item;
|
||||
$("item-form-title").textContent = item ? `Change ${item.name}` : "Make an item";
|
||||
$("item-save").textContent = item ? "Save" : "Make it";
|
||||
$("item-cancel").hidden = !item;
|
||||
for (const field of ["item-kind", "item-base", "item-look"]) {
|
||||
$(field).disabled = Boolean(item);
|
||||
}
|
||||
if (item) {
|
||||
$("item-kind").value = item.kind;
|
||||
}
|
||||
$("item-base").value = item ? item.base : "";
|
||||
$("item-name").value = item ? item.name : "";
|
||||
$("item-cost").value = item ? item.cost : "";
|
||||
$("item-members").checked = Boolean(item && item.members);
|
||||
$("item-base-name").textContent = item ? `${item.baseName} (${item.kind === "den" ? "den item" : "clothing"} ${item.base})` : "";
|
||||
showColours([]);
|
||||
if (item && item.kind === "clothing") {
|
||||
// the base's colours, and any of the item's own that are not among them
|
||||
lookUp().then(() => showColours([...new Set([...baseColours, ...item.colors])], item.colors));
|
||||
}
|
||||
};
|
||||
$("item-cancel").addEventListener("click", () => itemForm(null));
|
||||
|
||||
$("item-save").addEventListener("click", async () => {
|
||||
const fields = {name: $("item-name").value, cost: $("item-cost").value, members: $("item-members").checked};
|
||||
const boxes = [...$("item-colours").querySelectorAll("input")];
|
||||
if (boxes.length) {
|
||||
fields.colors = boxes.filter(box => box.checked).map(box => Number(box.value));
|
||||
if (!fields.colors.length) {
|
||||
setStatus($("item-status"), "Leave at least one colour.", true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
$("item-save").disabled = true;
|
||||
const result = await api("items", editing
|
||||
? {action: "update", kind: editing.kind, id: editing.id, ...fields}
|
||||
: {action: "create", kind: $("item-kind").value, base: $("item-base").value.trim(), ...fields});
|
||||
$("item-save").disabled = false;
|
||||
setStatus($("item-status"), said(result), !result.ok);
|
||||
if (result.ok) {
|
||||
itemForm(null);
|
||||
refresh();
|
||||
}
|
||||
});
|
||||
|
||||
const renderItems = () => {
|
||||
$("items").replaceChildren(...items.map(item => {
|
||||
const row = el("tr");
|
||||
const buttons = el("td");
|
||||
buttons.append(button("Change", () => itemForm(item)), " ",
|
||||
button(item.inShop ? "Take off sale" : "Put on sale", async () => {
|
||||
const result = await api("items", {action: "update", kind: item.kind, id: item.id, inShop: !item.inShop});
|
||||
setStatus($("item-status"), said(result), !result.ok);
|
||||
await refresh();
|
||||
}));
|
||||
row.append(el("td", String(item.id), "num"), el("td", `${item.name}${item.members ? " (members)" : ""}${item.inShop ? "" : " (off sale)"}`),
|
||||
el("td", `${item.baseName} (${item.kind === "den" ? "den item" : "clothing"} ${item.base})`), el("td", String(item.cost), "num"),
|
||||
el("td", item.createdBy), buttons);
|
||||
return row;
|
||||
}));
|
||||
$("no-items").hidden = items.length > 0;
|
||||
};
|
||||
|
||||
let permissions = new Set(); // what the signed-in role may do (GET /mod/api/me)
|
||||
|
||||
const refresh = async () => {
|
||||
clearTimeout(timer);
|
||||
if (!signedIn) {
|
||||
return;
|
||||
}
|
||||
const shown = tab;
|
||||
const counts = await api("overview");
|
||||
const counts = permissions.has("player.view") ? await api("overview") : {ok: false};
|
||||
if (counts.ok) {
|
||||
$("report-count").textContent = counts.data.reports ? ` (${counts.data.reports})` : "";
|
||||
$("request-count").textContent = counts.data.requests ? ` (${counts.data.requests})` : "";
|
||||
@@ -979,6 +1127,13 @@
|
||||
renderBans(result.data);
|
||||
}
|
||||
}
|
||||
else if (shown === "items") {
|
||||
const result = await api("items");
|
||||
if (result.ok) {
|
||||
items = result.data.items;
|
||||
renderItems();
|
||||
}
|
||||
}
|
||||
if (signedIn) {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(refresh, REFRESH_MS);
|
||||
@@ -1014,10 +1169,20 @@
|
||||
return;
|
||||
}
|
||||
const allowed = new Set(result.data.permissions || []);
|
||||
permissions = allowed;
|
||||
for (const pressed of document.querySelectorAll("button[data-action]")) {
|
||||
const needed = ACTION_PERMISSIONS[pressed.dataset.action];
|
||||
pressed.hidden = Boolean(needed) && !allowed.has(needed);
|
||||
}
|
||||
// the pages the role may see; the first of them when the one open is not.
|
||||
const pages = [...document.querySelectorAll("nav button")];
|
||||
for (const page of pages) {
|
||||
page.hidden = !allowed.has(page.dataset.needs);
|
||||
}
|
||||
const open = pages.find(page => page.dataset.tab === tab && !page.hidden) || pages.find(page => !page.hidden);
|
||||
if (open) {
|
||||
tab = open.dataset.tab;
|
||||
}
|
||||
if (result.data.role) {
|
||||
$("who").textContent = `${result.data.username} (${result.data.role})`;
|
||||
}
|
||||
@@ -1028,8 +1193,7 @@
|
||||
$("who").textContent = username;
|
||||
$("gate").hidden = true;
|
||||
$("panel").hidden = false;
|
||||
showTab(tab);
|
||||
applyPermissions();
|
||||
applyPermissions().then(() => showTab(tab));
|
||||
};
|
||||
|
||||
$("gate-form").addEventListener("submit", async event => {
|
||||
|
||||
@@ -9,6 +9,7 @@ const chatlog = require("./lib/chatlog.js");
|
||||
const modlog = require("./lib/modlog.js");
|
||||
const retention = require("./lib/retention.js");
|
||||
const colours = require("./lib/colours.js");
|
||||
const customItems = require("./lib/customitems.js");
|
||||
const config = require("./config.js");
|
||||
const defpacks = require("./lib/defpacks.js");
|
||||
const http = require("./lib/http.js");
|
||||
@@ -37,6 +38,7 @@ const main = async () => {
|
||||
fs.chmodSync(config.dataDir, 0o700);
|
||||
accounts.startBackups();
|
||||
colours.load();
|
||||
customItems.load();
|
||||
reports.load();
|
||||
support.load();
|
||||
bans.load();
|
||||
|
||||
@@ -7,7 +7,9 @@ package
|
||||
import den.DenXtCommManager;
|
||||
import item.ItemXtCommManager;
|
||||
import den.DenItem;
|
||||
import den.DenXtCommManager;
|
||||
import item.Item;
|
||||
import item.ItemXtCommManager;
|
||||
import com.sbi.loader.ResourceStack;
|
||||
import com.sbi.popup.SBOkPopup;
|
||||
import com.sbi.popup.SBStandardPopup;
|
||||
@@ -491,6 +493,29 @@ package
|
||||
return _loc6_;
|
||||
}
|
||||
|
||||
// "xdi": [.., .., kind, rows as JSON]. items the staff made while the
|
||||
// game runs (the server's lib/customitems.js): "clothing" or "den" def
|
||||
// rows, as in the item packs, each with its name.
|
||||
public static function onItemDefs(param1:Object) : void
|
||||
{
|
||||
try
|
||||
{
|
||||
var _loc2_:Array = JSON.parse(String(param1[3])) as Array;
|
||||
if(String(param1[2]) == "den")
|
||||
{
|
||||
DenXtCommManager.addDenItemDefs(_loc2_);
|
||||
}
|
||||
else
|
||||
{
|
||||
ItemXtCommManager.addItemDefs(_loc2_);
|
||||
}
|
||||
}
|
||||
catch(e:Error)
|
||||
{
|
||||
GlobalErrorCatch.reportToServer("item defs: " + e + "\n" + e.getStackTrace());
|
||||
}
|
||||
}
|
||||
|
||||
// "xtl": [.., .., text]. A plain message box; what a chat command says.
|
||||
public static function showMessage(param1:Object) : void
|
||||
{
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -84,6 +84,11 @@ package
|
||||
PaletteHelper.handleCustomColors(param1.obj);
|
||||
return;
|
||||
}
|
||||
if(param1.obj[0] == "xdi")
|
||||
{
|
||||
AJClient.onItemDefs(param1.obj);
|
||||
return;
|
||||
}
|
||||
if(param1.obj[0] == "xtl")
|
||||
{
|
||||
AJClient.showMessage(param1.obj);
|
||||
|
||||
+7
-3
@@ -145,8 +145,10 @@ const postJson = (url, body) => fetch(url, {
|
||||
|
||||
// starts a server on the given ports with an empty database, runs `run`
|
||||
// against it, and prints `name` passed or the server's output on failure.
|
||||
const withServer = async (name, httpPort, gamePort, run) => {
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "aj-test-"));
|
||||
// with `dataDir` it uses that database instead, and leaves it there (for a
|
||||
// test of what is still there after a restart).
|
||||
const withServer = async (name, httpPort, gamePort, run, {dataDir: keptDir = null} = {}) => {
|
||||
const dataDir = keptDir || fs.mkdtempSync(path.join(os.tmpdir(), "aj-test-"));
|
||||
const server = spawn(process.execPath, [path.join(__dirname, "..", "server.js")], {
|
||||
env: {...process.env, AJ_HTTP_PORT: httpPort, AJ_GAME_PORT: gamePort, AJ_DATA_DIR: dataDir, AJ_QUIET: "1"},
|
||||
stdio: ["ignore", "pipe", "inherit"],
|
||||
@@ -175,7 +177,9 @@ const withServer = async (name, httpPort, gamePort, run) => {
|
||||
const exited = server.exitCode !== null ? Promise.resolve() : new Promise(resolve => server.once("exit", resolve));
|
||||
server.kill();
|
||||
await exited;
|
||||
fs.rmSync(dataDir, {recursive: true, force: true, maxRetries: 10, retryDelay: 200});
|
||||
if (!keptDir) {
|
||||
fs.rmSync(dataDir, {recursive: true, force: true, maxRetries: 10, retryDelay: 200});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
"use strict";
|
||||
|
||||
// end to end: items the staff make while the server runs
|
||||
// (lib/customitems.js), from the moderator panel and in the game: games
|
||||
// already playing are sent them, the packs have them, the shop sells them,
|
||||
// and they are still there after a restart.
|
||||
|
||||
const assert = require("assert");
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const os = require("os");
|
||||
const path = require("path");
|
||||
const zlib = require("zlib");
|
||||
const harness = require("./harness.js");
|
||||
const {decode} = require("../lib/amf3.js");
|
||||
const cdn = require("../lib/cdn.js");
|
||||
|
||||
const HTTP_PORT = 18093;
|
||||
const GAME_PORT = 19352;
|
||||
const BASE = `http://127.0.0.1:${HTTP_PORT}`;
|
||||
const TOWNSHIP = "jamaa_township.room_main#1";
|
||||
const ODD_CLOTHING_SHOP = 666;
|
||||
const ODD_DEN_SHOP = 396;
|
||||
const {postJson} = harness;
|
||||
|
||||
// the authenticator app's side of 2FA (lib/totp.js), as in test/staff.js.
|
||||
const STEP = 30;
|
||||
const base32Decode = text => {
|
||||
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||
const bits = text.replace(/=+$/, "").toUpperCase().split("").map(c => alphabet.indexOf(c).toString(2).padStart(5, "0")).join("");
|
||||
const bytes = [];
|
||||
for (let i = 0; i + 8 <= bits.length; i += 8) {
|
||||
bytes.push(parseInt(bits.slice(i, i + 8), 2));
|
||||
}
|
||||
return Buffer.from(bytes);
|
||||
};
|
||||
const codeAt = (secret, step) => {
|
||||
const counter = Buffer.alloc(8);
|
||||
counter.writeBigUInt64BE(BigInt(step));
|
||||
const mac = crypto.createHmac("sha1", base32Decode(secret)).update(counter).digest();
|
||||
const offset = mac[mac.length - 1] & 0x0F;
|
||||
return String((mac.readUInt32BE(offset) & 0x7FFFFFFF) % 1000000).padStart(6, "0");
|
||||
};
|
||||
const stepNow = () => Math.floor(Date.now() / 1000 / STEP);
|
||||
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
const waitForStep = async step => {
|
||||
while (stepNow() < step) {
|
||||
await sleep(250);
|
||||
}
|
||||
};
|
||||
|
||||
const webSession = () => {
|
||||
let cookie = "";
|
||||
return async (urlPath, body) => {
|
||||
const headers = {cookie};
|
||||
const options = body === undefined ? {headers} : {method: "POST", headers: {...headers, "Content-Type": "application/json"}, body: JSON.stringify(body)};
|
||||
const res = await fetch(`${BASE}${urlPath}`, options);
|
||||
const set = res.headers.get("set-cookie");
|
||||
if (set) {
|
||||
cookie = set.split(";")[0];
|
||||
}
|
||||
return {status: res.status, data: await res.json().catch(() => ({}))};
|
||||
};
|
||||
};
|
||||
|
||||
const say = (client, roomId, text) =>
|
||||
client.send(`<msg t='sys'><body action='pubMsg' r='${roomId}'><txt><![CDATA[${text}%0]]></txt></body></msg>`);
|
||||
|
||||
// `onLogin(client)` runs before the room is joined, for what the server
|
||||
// sends with the login (joining skips everything else on the way).
|
||||
const arrive = async (username, password, totp, onLogin = async () => {}) => {
|
||||
const res = await postJson(`${BASE}/authenticate`, {username, password, ...(totp ? {totp} : {})});
|
||||
const auth = await res.json();
|
||||
assert.strictEqual(res.status, 200, `${username} could not sign in: ${JSON.stringify(auth)}`);
|
||||
const client = new harness.GameClient(GAME_PORT);
|
||||
await client.connect();
|
||||
const login = await client.logIn(username, auth.auth_token);
|
||||
assert.strictEqual(login.status, "1");
|
||||
await onLogin(client);
|
||||
client.xt("rj", 1, TOWNSHIP, 1, 0, 0);
|
||||
const rj = await client.untilXt("rj");
|
||||
await client.untilXt("rp");
|
||||
return {client, roomId: rj[4]};
|
||||
};
|
||||
|
||||
// a pack as the clients get it.
|
||||
const pack = async id => Object.values(decode(zlib.inflateRawSync(Buffer.from(await (await fetch(`${BASE}/${cdn.hashedPath(`defPacks/${id}`)}`)).arrayBuffer()))));
|
||||
const strings = async () => decode(zlib.inflateRawSync(Buffer.from(await (await fetch(`${BASE}/${cdn.hashedPath("defPacks/10230")}`)).arrayBuffer())));
|
||||
const byId = (rows, id) => rows.find(row => String(row.id) === String(id));
|
||||
|
||||
// "xdi" [.., .., kind, rows as JSON], the next one of `kind`.
|
||||
const untilDefs = async (client, kind) => {
|
||||
for (;;) {
|
||||
const fields = await client.untilXt("xdi");
|
||||
if (fields[2] === kind) {
|
||||
return JSON.parse(fields[3]);
|
||||
}
|
||||
}
|
||||
};
|
||||
const nextBox = async client => (await client.untilXt("xtl"))[2];
|
||||
const shopList = async (client, roomId, shop) => {
|
||||
client.xt("gl", roomId, shop);
|
||||
return (await client.untilXt("gl")).slice(9);
|
||||
};
|
||||
|
||||
const people = {Dev: "Password21", Hal: "Password22", Pat: "Password23", Lou: "Password24"};
|
||||
const secret = {};
|
||||
let usedStep = 0;
|
||||
let made = {};
|
||||
|
||||
const first = 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, password] of Object.entries(people)) {
|
||||
assert.strictEqual((await registerJson({username, password})).status, 200);
|
||||
}
|
||||
const admin = webSession();
|
||||
assert.strictEqual((await admin("/admin/api/setup", {password: "AdminPass99!"})).status, 200);
|
||||
assert.strictEqual((await admin("/admin/api/login", {password: "AdminPass99!"})).status, 200);
|
||||
for (const username of ["Dev", "Hal"]) {
|
||||
const page = webSession();
|
||||
assert.strictEqual((await page("/account/api/login", {username, password: people[username]})).status, 200);
|
||||
secret[username] = (await page("/account/api/act", {action: "twoStepStart", current: people[username]})).data.setup.secret;
|
||||
usedStep = Math.max(usedStep, stepNow());
|
||||
assert.ok((await page("/account/api/act", {action: "twoStepConfirm", code: codeAt(secret[username], stepNow())})).data.ok);
|
||||
}
|
||||
assert.match((await admin("/admin/api/account", {username: "Dev", action: "role", role: "developer"})).data.ok, /developer/);
|
||||
assert.match((await admin("/admin/api/account", {username: "Hal", action: "role", role: "helper"})).data.ok, /helper/);
|
||||
|
||||
// a game started before anything is made
|
||||
const pat = await arrive("Pat", people.Pat);
|
||||
|
||||
// --- the panel: a developer makes items, and sees no players
|
||||
usedStep++;
|
||||
await waitForStep(usedStep);
|
||||
const dev = webSession();
|
||||
assert.strictEqual((await dev("/mod/api/login", {username: "Dev", password: people.Dev, code: codeAt(secret.Dev, usedStep)})).status, 200);
|
||||
const me = (await dev("/mod/api/me")).data;
|
||||
assert.strictEqual(me.role, "developer");
|
||||
assert.ok(me.permissions.includes("items.create") && !me.permissions.includes("player.view"));
|
||||
for (const page of ["/mod/api/players", "/mod/api/chat", "/mod/api/reports", "/mod/api/overview"]) {
|
||||
assert.strictEqual((await dev(page)).status, 403, page);
|
||||
}
|
||||
assert.deepStrictEqual((await dev("/mod/api/items")).data.items, []);
|
||||
|
||||
// something to make them from: a clothing piece with several colours, and the bean bag chair
|
||||
const clothing = await pack(1000);
|
||||
const base = clothing.find(row => row.type === "1" && String(row.colors).split(",").length >= 3);
|
||||
const looked = (await dev(`/mod/api/items/base?kind=clothing&id=${base.id}`)).data;
|
||||
assert.strictEqual(looked.art, Number(base.layerDefId));
|
||||
assert.strictEqual(looked.colors.length, String(base.colors).split(",").length);
|
||||
const bodyPart = clothing.find(row => row.type === "0");
|
||||
assert.strictEqual((await dev(`/mod/api/items/base?kind=clothing&id=${bodyPart.id}`)).status, 404);
|
||||
|
||||
// bad requests
|
||||
const make = fields => dev("/mod/api/items", {action: "create", kind: "clothing", base: base.id, name: "Test Crown", cost: 25, ...fields});
|
||||
assert.match((await make({name: ""})).data.error, /name/);
|
||||
assert.match((await make({name: "<b>hi</b>"})).data.error, /name/);
|
||||
assert.match((await make({cost: -1})).data.error, /price/);
|
||||
assert.match((await make({base: bodyPart.id})).data.error, /body part/);
|
||||
assert.match((await make({base: 999999})).data.error, /No clothing/);
|
||||
assert.match((await make({colors: []})).data.error, /colours/);
|
||||
|
||||
// made: Pat's game is told at once
|
||||
const colours = looked.colors.slice(0, 2);
|
||||
const crown = await make({colors: colours});
|
||||
assert.match(crown.data.ok, /^Test Crown \(clothing 50000\) made\.$/);
|
||||
const [row] = await untilDefs(pat.client, "clothing");
|
||||
assert.deepStrictEqual([row.id, row.name, row.layerDefId, row.layerId, row.colors, row.titleStrId],
|
||||
["50000", "Test Crown", base.layerDefId, base.layerId, colours.join(","), "9100000"]);
|
||||
|
||||
// the packs a new game fetches have it, and its name
|
||||
const crownRow = byId(await pack(1000), 50000);
|
||||
assert.strictEqual(crownRow.layerDefId, base.layerDefId);
|
||||
assert.strictEqual(crownRow.avatarUseFlags, "9007199254740991"); // any animal, like all clothing here
|
||||
assert.strictEqual((await strings())[9100000], "Test Crown");
|
||||
|
||||
// first in the shop of oddities, and Pat can buy it in a colour it has
|
||||
assert.strictEqual((await shopList(pat.client, pat.roomId, ODD_CLOTHING_SHOP))[0], "50000");
|
||||
pat.client.xt("ib", pat.roomId, ODD_CLOTHING_SHOP, 1, 50000, 2, 0);
|
||||
assert.strictEqual((await pat.client.untilXt("ib"))[2], "0"); // a third colour it was not given
|
||||
pat.client.xt("ib", pat.roomId, ODD_CLOTHING_SHOP, 1, 50000, 1, 0);
|
||||
const bought = await pat.client.untilXt("il");
|
||||
assert.ok(bought.includes("50000"));
|
||||
assert.strictEqual((await pat.client.untilXt("ib"))[2], "1");
|
||||
|
||||
// a den item, from the bean bag chair
|
||||
const chair = await dev("/mod/api/items", {action: "create", kind: "den", base: 1, name: "Test Chair", cost: 10});
|
||||
assert.match(chair.data.ok, /^Test Chair \(den item 50000\) made\.$/);
|
||||
const [chairRow] = await untilDefs(pat.client, "den");
|
||||
assert.deepStrictEqual([chairRow.id, chairRow.abbrName, chairRow.name, chairRow.nameStrId], ["50000", "BeanBagChair", "Test Chair", "9200000"]);
|
||||
assert.strictEqual((await shopList(pat.client, pat.roomId, ODD_DEN_SHOP))[0], "50000");
|
||||
assert.strictEqual(byId(await pack(1030), 50000).abbrName, "BeanBagChair");
|
||||
|
||||
// the item finder has them
|
||||
const found = await (await fetch(`${BASE}/api/search?kind=all&q=50000`)).json();
|
||||
assert.deepStrictEqual(found.results.filter(entry => entry.id === 50000).map(entry => `${entry.kind} ${entry.name}`).sort(), ["clothing Test Crown", "den Test Chair"]);
|
||||
|
||||
// changed: renamed and taken off sale, and Pat is told the new name
|
||||
assert.match((await dev("/mod/api/items", {action: "update", kind: "clothing", id: 50000, name: "Gold Crown", inShop: false})).data.ok, /Gold Crown .* changed/);
|
||||
assert.strictEqual((await untilDefs(pat.client, "clothing"))[0].name, "Gold Crown");
|
||||
assert.ok(!(await shopList(pat.client, pat.roomId, ODD_CLOTHING_SHOP)).includes("50000"));
|
||||
assert.strictEqual((await strings())[9100000], "Gold Crown");
|
||||
|
||||
// --- in the game: !item, for whoever may make items
|
||||
usedStep++;
|
||||
await waitForStep(usedStep);
|
||||
// a game logging in is sent every item made so far
|
||||
let atLogin = null;
|
||||
const devGame = await arrive("Dev", people.Dev, codeAt(secret.Dev, usedStep), async client => {
|
||||
atLogin = await untilDefs(client, "clothing");
|
||||
});
|
||||
assert.deepStrictEqual(atLogin.map(entry => entry.name), ["Gold Crown"]);
|
||||
say(devGame.client, devGame.roomId, `!item clothing ${base.id} Quick Hat`);
|
||||
assert.strictEqual(await nextBox(devGame.client), "Made Quick Hat, clothing 50001. It is in the item finder now.");
|
||||
assert.strictEqual((await untilDefs(pat.client, "clothing"))[0].name, "Quick Hat");
|
||||
say(devGame.client, devGame.roomId, "!item list");
|
||||
assert.match(await nextBox(devGame.client), /^Latest items made: 50001 Quick Hat \(clothing\); 50000 Test Chair \(den\); 50000 Gold Crown \(clothing, off sale\)$/);
|
||||
say(devGame.client, devGame.roomId, "!item hat 12 x");
|
||||
assert.match(await nextBox(devGame.client), /^Use: !item/);
|
||||
|
||||
// a helper may not: it is chat (another account: the same step will do)
|
||||
const hal = await arrive("Hal", people.Hal, codeAt(secret.Hal, usedStep));
|
||||
say(hal.client, hal.roomId, `!item clothing ${base.id} Nope`);
|
||||
for (;;) {
|
||||
const line = await pat.client.untilXt("uc");
|
||||
if (line[3] === `!item clothing ${base.id} Nope`) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert.strictEqual((await dev("/mod/api/items")).data.items.length, 3);
|
||||
|
||||
// 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"]) {
|
||||
assert.ok(log.includes(line), `missing from the log: ${line}\n${log.join("\n")}`);
|
||||
}
|
||||
made = {base};
|
||||
for (const {client} of [pat, devGame, hal]) {
|
||||
client.socket.destroy();
|
||||
}
|
||||
};
|
||||
|
||||
// the same database, a new server: everything is still there.
|
||||
const second = async () => {
|
||||
const atLogin = {};
|
||||
const lou = await arrive("Lou", people.Lou, null, async client => {
|
||||
atLogin.clothing = await untilDefs(client, "clothing");
|
||||
atLogin.den = await untilDefs(client, "den");
|
||||
});
|
||||
assert.deepStrictEqual(atLogin.clothing.map(entry => `${entry.id} ${entry.name}`), ["50000 Gold Crown", "50001 Quick Hat"]);
|
||||
assert.deepStrictEqual(atLogin.den.map(entry => entry.name), ["Test Chair"]);
|
||||
assert.strictEqual(byId(await pack(1000), 50001).layerDefId, made.base.layerDefId);
|
||||
assert.strictEqual((await strings())[9100001], "Quick Hat");
|
||||
const shop = await shopList(lou.client, lou.roomId, ODD_CLOTHING_SHOP);
|
||||
assert.ok(shop.includes("50001") && !shop.includes("50000"));
|
||||
lou.client.socket.destroy();
|
||||
};
|
||||
|
||||
(async () => {
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "aj-test-"));
|
||||
try {
|
||||
await harness.withServer("items test", HTTP_PORT, GAME_PORT, first, {dataDir});
|
||||
await harness.withServer("items test (after a restart)", HTTP_PORT, GAME_PORT, second, {dataDir});
|
||||
}
|
||||
finally {
|
||||
fs.rmSync(dataDir, {recursive: true, force: true, maxRetries: 10, retryDelay: 200});
|
||||
}
|
||||
})().catch(err => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
+1
-1
@@ -114,7 +114,7 @@ const run = async () => {
|
||||
assert.strictEqual((await admin("/admin/api/setup", {password: "AdminPass99!"})).status, 200);
|
||||
assert.strictEqual((await admin("/admin/api/login", {password: "AdminPass99!"})).status, 200);
|
||||
const roleList = await admin("/admin/api/roles");
|
||||
assert.deepStrictEqual(roleList.data.roles.map(role => role.id), ["helper", "moderator", "admin"]);
|
||||
assert.deepStrictEqual(roleList.data.roles.map(role => role.id), ["developer", "helper", "moderator", "admin"]);
|
||||
assert.match((await admin("/admin/api/account", {username: "Mira", action: "role", role: "boss"})).data.error, /No such role/);
|
||||
|
||||
// staff need 2FA: turned on from the account page.
|
||||
|
||||
@@ -74,7 +74,9 @@ set -- \
|
||||
ecard.ECard ECard.as \
|
||||
game.ArtStudioKit ArtStudioKit.as \
|
||||
game.artStudioPainting.ArtStudioPainting ArtStudioPainting.as \
|
||||
game.artStudioGridDrawing.ArtStudioGridDrawing ArtStudioGridDrawing.as
|
||||
game.artStudioGridDrawing.ArtStudioGridDrawing ArtStudioGridDrawing.as \
|
||||
item.ItemXtCommManager ItemXtCommManager.as \
|
||||
den.DenXtCommManager DenXtCommManager.as
|
||||
# not in the game: added before the replace (game.ArtStudioKit is Strawberry
|
||||
# Jam's, shared by its two art studio painters)
|
||||
NEW_CLASSES="game.ArtStudioKit"
|
||||
|
||||
Reference in new issue
Block a user