Brought up to date with the private repository (a06d3c5)
No files matched your search
@@ -0,0 +1,29 @@
|
||||
# Accounts, login tokens and logs
|
||||
data/
|
||||
|
||||
# Assets mirrored from the official CDN; re-downloaded on demand
|
||||
cache/
|
||||
|
||||
# Third-party decompiler and its output; see HANDOFF.md for how to restore them
|
||||
tools/ffdec/
|
||||
tools/decompiled/
|
||||
tools/hud/hud.xml
|
||||
tools/hud/hud.pickle
|
||||
tools/hud/__pycache__/
|
||||
|
||||
node_modules/
|
||||
*.log
|
||||
tools/recorder.js
|
||||
SITE.md
|
||||
|
||||
# python leaves these beside the tools
|
||||
__pycache__/
|
||||
|
||||
# kept in the private repository, never here
|
||||
*.md
|
||||
/swf
|
||||
/swf-src
|
||||
/client-updates
|
||||
/HANDOFF.md
|
||||
/DISCOVERIES.md
|
||||
/GOING-PUBLIC.md
|
||||
@@ -0,0 +1,307 @@
|
||||
"use strict";
|
||||
|
||||
const path = require("path");
|
||||
|
||||
const env = process.env;
|
||||
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);
|
||||
const gamePort = Number(env.AJ_GAME_PORT || 9339);
|
||||
// with a certificate both ports speak TLS. the launcher follows suit when its
|
||||
// own config.js uses an https:// address.
|
||||
const tls = env.AJ_TLS_CERT && env.AJ_TLS_KEY ? {certFile: env.AJ_TLS_CERT, keyFile: env.AJ_TLS_KEY} : null;
|
||||
// AJ_PUBLIC_URL: the address players reach this server at
|
||||
// ("https://play.burrow.moe", with a port if it is not the usual one). it
|
||||
// is the one switch for a server strangers can reach, whether this process
|
||||
// listens on a public address itself or sits behind a reverse proxy or a
|
||||
// tunnel: with it set the server knows it is public, tells the game that
|
||||
// address, marks its cookies Secure when it is an https:// one, and trusts
|
||||
// no request for coming from this machine (behind a proxy they all do).
|
||||
const publicUrl = env.AJ_PUBLIC_URL ? new URL(env.AJ_PUBLIC_URL) : null;
|
||||
const host = env.AJ_HOST || (publicUrl ? publicUrl.hostname : "127.0.0.1");
|
||||
// AJ_SITE_URL: where the web pages are (the home page, sign-up, the account
|
||||
// page, the moderator panel, the terms), when that is another name than the
|
||||
// game server's ("https://burrow.moe" beside AJ_PUBLIC_URL's
|
||||
// "https://play.burrow.moe"). the server answers to both; a web page asked
|
||||
// for under the game server's name is sent on to this one.
|
||||
const siteUrl = env.AJ_SITE_URL ? new URL(env.AJ_SITE_URL) : null;
|
||||
// reachable from other machines? several defaults get stricter when it is.
|
||||
const isPublic = Boolean(publicUrl) || !LOOPBACK_NAMES.includes(bindAddress) || !LOOPBACK_NAMES.includes(env.AJ_GAME_BIND || bindAddress);
|
||||
// AJ_TRUSTED_PROXY=1: a reverse proxy on this machine is the only thing that
|
||||
// reaches the web port, and the visitor's address is the last one in the
|
||||
// X-Forwarded-For header it sets. without it every visitor behind a proxy
|
||||
// has the proxy's address, and the per-address limits see one address.
|
||||
const trustedProxy = env.AJ_TRUSTED_PROXY === "1";
|
||||
// the game port can listen wider than the web port: a proxy (cloudflare, say)
|
||||
// carries web pages but not the game's own protocol
|
||||
const gameBindAddress = env.AJ_GAME_BIND || bindAddress;
|
||||
const baseUrl = publicUrl ? `${publicUrl.origin}/` : `${tls ? "https" : "http"}://${host}:${httpPort}/`;
|
||||
// settings that contradict each other are refused at start (server.js)
|
||||
// rather than left to be found out.
|
||||
const problems = [];
|
||||
if (publicUrl && env.AJ_TRUST_LOCAL === "1") {
|
||||
problems.push("AJ_PUBLIC_URL and AJ_TRUST_LOCAL=1 cannot both be set: behind a proxy every request looks local");
|
||||
}
|
||||
if (trustedProxy && !LOOPBACK_NAMES.includes(bindAddress)) {
|
||||
problems.push("AJ_TRUSTED_PROXY=1 needs AJ_BIND to be 127.0.0.1: anyone who reaches the port directly could name any address as theirs");
|
||||
}
|
||||
if ((publicUrl || !LOOPBACK_NAMES.includes(bindAddress)) && env.AJ_REGISTER === "1") {
|
||||
problems.push("AJ_REGISTER=1 cannot be used on a public server: an account made that way has agreed to nothing");
|
||||
}
|
||||
if (Boolean(env.AJ_TURNSTILE_SITE_KEY) !== Boolean(env.AJ_TURNSTILE_SECRET)) {
|
||||
problems.push("AJ_TURNSTILE_SITE_KEY and AJ_TURNSTILE_SECRET go together: set both or neither");
|
||||
}
|
||||
if (siteUrl && (!publicUrl || !/^https?:$/.test(siteUrl.protocol))) {
|
||||
problems.push("AJ_SITE_URL needs AJ_PUBLIC_URL, and must be an http:// or https:// address");
|
||||
}
|
||||
if (publicUrl && !/^https?:$/.test(publicUrl.protocol)) {
|
||||
problems.push("AJ_PUBLIC_URL must be an http:// or https:// address");
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
// address the client is told to use. the patched ajclient.swf always opens
|
||||
// its game socket to 127.0.0.1, so only change this together with the SWF.
|
||||
host,
|
||||
bindAddress,
|
||||
gameBindAddress,
|
||||
isPublic,
|
||||
publicUrl,
|
||||
trustedProxy,
|
||||
problems,
|
||||
tls,
|
||||
// behind a trusted proxy the proxy encrypts the web port; the certificate is the game port's
|
||||
webTls: trustedProxy ? null : tls,
|
||||
// requests from this machine may use the item finder for any account and
|
||||
// list accounts. never with AJ_PUBLIC_URL set; AJ_TRUST_LOCAL=0 turns it
|
||||
// off otherwise. (A request that came through a proxy is never taken for
|
||||
// local, whatever is set: lib/limits.js.)
|
||||
trustLocalRequests: !publicUrl && env.AJ_TRUST_LOCAL !== "0",
|
||||
httpPort,
|
||||
gamePort,
|
||||
baseUrl,
|
||||
// the web pages' address: baseUrl unless AJ_SITE_URL names another
|
||||
siteUrl: siteUrl ? `${siteUrl.origin}/` : baseUrl,
|
||||
// cookies are only sent back over an encrypted connection when players
|
||||
// have one, whoever does the encrypting.
|
||||
secureCookies: baseUrl.startsWith("https:"),
|
||||
// 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.
|
||||
adminAllow: (env.AJ_ADMIN_ALLOW || "").split(",").map(address => address.trim()).filter(Boolean),
|
||||
|
||||
// cloudflare turnstile (lib/captcha.js): a captcha wherever a password is
|
||||
// tried or an account is made, with both set. off without them.
|
||||
turnstile: env.AJ_TURNSTILE_SITE_KEY && env.AJ_TURNSTILE_SECRET
|
||||
? {siteKey: env.AJ_TURNSTILE_SITE_KEY, secret: env.AJ_TURNSTILE_SECRET} : null,
|
||||
|
||||
// asset mirror: anything not served locally is fetched once from here and
|
||||
// cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only.
|
||||
upstreamContent: env.AJ_UPSTREAM || "https://ajcontent.akamaized.net/",
|
||||
offline: env.AJ_OFFLINE === "1",
|
||||
deployVersion: env.AJ_DEPLOY_VERSION || "1830",
|
||||
// older builds the CDN still serves, asked in turn for a room file the
|
||||
// current build has dropped. 1828 is the last with the Summer Carnival.
|
||||
olderBuilds: ["1828"],
|
||||
// the client adds this to every asset address, so raising it makes every
|
||||
// client fetch everything afresh. raise it whenever the server starts
|
||||
// serving an asset differently (4: item defs with all eyes for all animals;
|
||||
// 5: re-dated item packs, the room pack, HUD artwork with the 2014 name tag;
|
||||
// 6: the party pack; 14 and 15: more rows in the Theme list; 16: clothing
|
||||
// for every animal, and last-seen times on player cards; 17 and 18: the
|
||||
// banned label on player cards).
|
||||
// 19 to 25: the comforts of 2026-10-11, see HANDOFF.md.
|
||||
// 39: chat drawn as text and never as markup, the chat filter, and the
|
||||
// game no longer open to SWFs from other addresses.
|
||||
// 40: the chat filter's window laid out again.
|
||||
// 41: the game's text says "Burrow" where it said Animal Jam.
|
||||
buildVersion: env.AJ_BUILD_VERSION || "41",
|
||||
// what the official CDN is asked for; not ours to change.
|
||||
upstreamBuildVersion: "3",
|
||||
|
||||
// the patched game client and the font file its assets import, both in
|
||||
// swf/ (ajclient.before-finder.swf there is the base the client is rebuilt
|
||||
// from, see the README).
|
||||
clientSwf: env.AJ_CLIENT_SWF || path.join(__dirname, "swf", "ajclient.swf"),
|
||||
sharedFontsSwf: path.join(__dirname, "swf", "sharedFonts.swf"),
|
||||
// the HUD artwork (assets/HUDAssets.swf on the CDN), served from here
|
||||
// because it is changed: see "Rebuild" in the README.
|
||||
hudAssetsSwf: path.join(__dirname, "swf", "HUDAssets.swf"),
|
||||
dataDir: env.AJ_DATA_DIR || path.join(__dirname, "data"),
|
||||
cacheDir: path.join(__dirname, "cache"),
|
||||
// updates for installed clients, served at /client/ (the client's
|
||||
// tools/make-update.js writes them here; they are in the repository)
|
||||
clientUpdatesDir: env.AJ_CLIENT_UPDATES_DIR || path.join(__dirname, "client-updates"),
|
||||
publicDir: path.join(__dirname, "public"),
|
||||
|
||||
// accounts are made through the client's Create Account screens or the
|
||||
// /register page. set AJ_REGISTER=1 to also create one whenever an unknown
|
||||
// username logs in (handy for throwaway test accounts).
|
||||
registerOnLogin: env.AJ_REGISTER === "1",
|
||||
|
||||
// the terms of service and the privacy policy (public/terms.html,
|
||||
// public/privacy.html). A sign-up records the version agreed to: change
|
||||
// it when either text changes in a way that matters. the values under it
|
||||
// are written into both pages. the emails and the host's country are
|
||||
// placeholders until set; the operator is, at the owner's word, said to
|
||||
// be in the EU without a name or a country.
|
||||
termsVersion: "2026-10-13",
|
||||
legalEmail: env.AJ_LEGAL_EMAIL || "[email protected]",
|
||||
adminEmail: env.AJ_ADMIN_EMAIL || "[email protected]",
|
||||
operator: env.AJ_OPERATOR || "an individual based in the European Union",
|
||||
hostedIn: env.AJ_HOSTED_IN || "[country of the hosting provider]",
|
||||
|
||||
// links on the home page; an empty download reads "Soon"
|
||||
downloadUrl: env.AJ_DOWNLOAD_URL || "",
|
||||
githubUrl: env.AJ_GITHUB_URL || "",
|
||||
discordUrl: env.AJ_DISCORD_URL || "",
|
||||
|
||||
// 2+ is a member. 4 and 5 unlock the client's developer debug overlays.
|
||||
// no account type gives powers over other players; running the server is
|
||||
// done from the admin panel at /admin (lib/panel.js).
|
||||
defaultAccountType: 2,
|
||||
// looks of the lands players can pick with the Theme list. the official CDN
|
||||
// keeps past builds (35 of them, November 2022 to today), each with that
|
||||
// month's version of every land, so a theme is first of all the build to
|
||||
// take room files from. `rooms` then names rooms shown as another room
|
||||
// file: the room list still carries seasonal copies of some lands that the
|
||||
// official game stopped using years ago, and those are older than any
|
||||
// build. `label` is for people; the list the game shows is in
|
||||
// swf-src/MySettings.as, in the same order.
|
||||
//
|
||||
// the first eight are the latest year's seasons. the rest is every other
|
||||
// season and year there is (DISCOVERIES.md, "Older designs of the lands",
|
||||
// says what was looked through and how each was dated): one row for each
|
||||
// season of each year the builds cover, then one for each year's worth
|
||||
// of leftover seasonal room files. most differ from today's version of
|
||||
// their season by a handful of decorations; the ones that show more:
|
||||
// - 1636 and 1637: the Township's painting before it was redone in 2023
|
||||
// and Club Geoz was built.
|
||||
// - 1691 and earlier: the Flag Shop in Sarepia, before it became the
|
||||
// Hall of Animals.
|
||||
// - friendship2018: the Township on its winter 2017 painting with the
|
||||
// old arcade front, and Mt. shiveer before the bridge to Balloosh.
|
||||
// - freedom2021: Freedom Day's fireworks, which today's July build no
|
||||
// longer has.
|
||||
themes: {
|
||||
halloween: {label: "Halloween", build: 1830},
|
||||
fall: {label: "Fall", build: 1829},
|
||||
jamaalidays: {label: "Jamaalidays", build: 1810},
|
||||
winter: {label: "Winter", build: 1811},
|
||||
friendship: {label: "Friendship", build: 1815},
|
||||
lucky: {label: "Lucky Day", build: 1817},
|
||||
spring: {label: "Spring", build: 1820},
|
||||
summer: {label: "Summer", build: 1828},
|
||||
halloween2025: {label: "Halloween 2025", build: 1803},
|
||||
fall2025: {label: "Fall 2025", build: 1807},
|
||||
summer2025: {label: "Summer 2025", build: 1731},
|
||||
lucky2025: {label: "Lucky Day 2025", build: 1711},
|
||||
summer2024: {label: "Summer 2024", build: 1691},
|
||||
spring2024: {label: "Spring 2024", build: 1678},
|
||||
lucky2024: {label: "Lucky Day 2024", build: 1676},
|
||||
jamaalidays2022: {label: "Jamaalidays 2022", build: 1637},
|
||||
fall2022: {label: "Fall 2022", build: 1636},
|
||||
freedom2021: {label: "Freedom Day 2021", build: 1824, rooms: {"sarepia.room_main": "sarepia.room_main_freedom"}},
|
||||
jamaalidays2020: {label: "Jamaalidays 2020", build: 1810, rooms: {"sarepia.room_main": "sarepia.room_main_jamaalidays"}},
|
||||
spring2020: {label: "Spring 2020", build: 1820, rooms: {"canyon_path.room_main": "canyon_path.room_main_main"}},
|
||||
jamaalidays2018: {
|
||||
label: "Jamaalidays 2018",
|
||||
build: 1810,
|
||||
rooms: {
|
||||
"lost_temple_of_zios.room_main": "lost_temple_of_zios.room_main_jamaalidays",
|
||||
"balloosh.room_main": "balloosh.room_main_jamaalidays",
|
||||
},
|
||||
},
|
||||
summer2018: {label: "Summer 2018", build: 1828, rooms: {"sarepia.room_main": "sarepia.room_main_summer"}},
|
||||
lucky2018: {label: "Lucky Day 2018", build: 1817, rooms: {"mountains_of_shivveer.room_main": "mountains_of_shivveer.room_main_lucky"}},
|
||||
friendship2018: {
|
||||
label: "Friendship 2018",
|
||||
build: 1815,
|
||||
rooms: {
|
||||
"jamaa_township.room_main": "jamaa_township.room_main_friendship",
|
||||
"mountains_of_shivveer.room_main": "mountains_of_shivveer.room_main_friendship",
|
||||
"crystal_sands.room_main": "crystal_sands.room_main_friendship",
|
||||
"lost_temple_of_zios.room_main": "lost_temple_of_zios.room_main_friendship",
|
||||
},
|
||||
},
|
||||
// the Phantom Vortex rooms as saved in 2011 and 2013: no shop, no fog.
|
||||
halloween2013: {
|
||||
label: "Halloween 2013",
|
||||
build: 1830,
|
||||
rooms: Object.fromEntries([1, 2, 3, 4, 5].map(n => [`holidays_and_celebrations.room_jamaa_halloween${n}`, `rholidays_and_celebrations.room_jamaa_halloween${n}`])),
|
||||
},
|
||||
},
|
||||
// rooms shown as another version of themselves in some months (1-12).
|
||||
// both are versions the official game put up for a while and no door
|
||||
// leads to today; when it did so is not recorded, so the months are ours:
|
||||
// the Canyons Pathway with the plushie scavenger hunt's stand in spring,
|
||||
// and the Conservation Museum with its "Antlers and Tusks" exhibit in
|
||||
// place of the savannah one every other month.
|
||||
roomSwaps: [
|
||||
{room: "canyon_path.room_main", shown: "canyon_path.room_main_main", months: [3, 4]},
|
||||
{room: "appondale.room_museum", shown: "appondale.room_museum_ant", months: [2, 4, 6, 8, 10, 12]},
|
||||
],
|
||||
startupRoom: "jamaa_township.room_main",
|
||||
shards: [{id: 1, name: "Aldan"}],
|
||||
maxUsersPerRoom: 80,
|
||||
// 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.
|
||||
freeShops: env.AJ_FREE_SHOPS === "1",
|
||||
// smooth movement in the client (AJClient.smoothOn in the SWF) for players
|
||||
// who never chose: on, or with AJ_SMOOTH=0 off for everyone who has not
|
||||
// chosen "Graphics: Smooth" themselves. the way back if it misbehaves.
|
||||
smooth: env.AJ_SMOOTH !== "0",
|
||||
partyMinutes: 120,
|
||||
// row of the den-room defPack every player's den uses (1 = the small free den).
|
||||
denDefId: 1,
|
||||
// every currency of every account is raised to at least this at each login,
|
||||
// so nobody runs dry while testing.
|
||||
minimumCurrency: 10000000,
|
||||
|
||||
// limits on what strangers can do. requests from the server's own machine
|
||||
// are exempt from the per-address ones (see trustLocalRequests).
|
||||
registrationsPerHour: 5, // per address
|
||||
failedLoginsPerTenMinutes: 10, // per address, and 3x this per account
|
||||
errorReportsPerMinute: 30, // per address
|
||||
maxConnectionsPerAddress: 10, // game sockets
|
||||
// the asset mirror (lib/cdn.js): files asked for that are not in the
|
||||
// cache yet, per address; how long the official CDN is waited for; and
|
||||
// how big the cache may grow (files are still fetched and served past
|
||||
// that, only not kept).
|
||||
cacheMissesPerTenMinutes: 1500, // a first visit with an empty cache fetches several hundred files
|
||||
upstreamTimeoutMs: 20000,
|
||||
maxCacheBytes: Number(env.AJ_MAX_CACHE_MB || 8192) * 1024 * 1024,
|
||||
maxConnections: 2000,
|
||||
maxHttpConnections: 2000, // open at once, in all
|
||||
maxHttpConnectionsPerAddress: 40, // the game opens a good many at once while it loads
|
||||
httpSocketTimeoutMs: 60000, // a connection nothing moves on is closed
|
||||
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
|
||||
tokenLifetimeDays: 30, // login tokens kept by the launcher's "remember me"
|
||||
maxChatLength: 300,
|
||||
// days typed chat and whispers are kept for the moderator panel's chat
|
||||
// history (lib/chatlog.js); 0 keeps none.
|
||||
chatLogDays: env.AJ_CHAT_LOG_DAYS === undefined ? 30 : Math.max(0, Number(env.AJ_CHAT_LOG_DAYS) || 0),
|
||||
chatLinesPerWindow: 5, // typed chat lines one player may send ...
|
||||
chatWindowMs: 3000, // ... in this long
|
||||
maxBytesPerTenSeconds: 512 * 1024, // per game socket; saving a full den is about 40 KB
|
||||
// custom colours (lib/colours.js). every one ever made is sent to every
|
||||
// player at every login and is never taken out again, so there is an end
|
||||
// to how many one account may add in a day and to the table as a whole.
|
||||
customColoursPerDay: 30,
|
||||
maxCustomColours: 20000,
|
||||
|
||||
// may a client pick, when it logs in, how the game should treat the
|
||||
// account for that session: member or not, guide, moderator, membership
|
||||
// days left (the custom client's "advanced" settings)? it changes what that
|
||||
// player's own game shows and the badge others see, never what the server
|
||||
// lets them do. on by default only for a local server;
|
||||
// AJ_LOGIN_CHOICES=1 / 0 forces it.
|
||||
loginChoices: env.AJ_LOGIN_CHOICES === undefined ? !isPublic : env.AJ_LOGIN_CHOICES === "1",
|
||||
|
||||
// log every game packet in both directions (login tokens are masked), plus
|
||||
// the client's media-load traces. on by default only for a local server;
|
||||
// AJ_QUIET=1 / AJ_QUIET=0 forces it off / on.
|
||||
logPackets: env.AJ_QUIET === undefined ? !isPublic : env.AJ_QUIET !== "1",
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
[Unit]
|
||||
Description=Update the Burrow server from GitHub
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/bin/bash /home/aj/ajc-private-server/deploy/update.sh
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=Look for a new Burrow server every two minutes
|
||||
|
||||
[Timer]
|
||||
OnBootSec=2min
|
||||
OnUnitActiveSec=2min
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env bash
|
||||
# brings the server to origin's main and restarts it when the change needs it.
|
||||
# run as root by burrow-update.timer; git itself runs as the server's user.
|
||||
set -euo pipefail
|
||||
|
||||
dir=${BURROW_DIR:-/home/aj/ajc-private-server}
|
||||
user=${BURROW_USER:-aj}
|
||||
service=${BURROW_SERVICE:-burrow}
|
||||
branch=${BURROW_BRANCH:-main}
|
||||
|
||||
git() { runuser -u "$user" -- git -C "$dir" "$@"; }
|
||||
|
||||
git fetch --quiet origin "$branch"
|
||||
old=$(git rev-parse HEAD)
|
||||
new=$(git rev-parse "origin/$branch")
|
||||
[ "$old" != "$new" ] || exit 0
|
||||
|
||||
# only a fast-forward: a server that was edited by hand is left for a person
|
||||
git merge --quiet --ff-only "origin/$branch"
|
||||
|
||||
# a file that does not parse would take the game down on restart
|
||||
for file in $(git diff --name-only "$old" "$new" -- '*.js'); do
|
||||
if [ -f "$dir/$file" ] && ! runuser -u "$user" -- node --check "$dir/$file"; then
|
||||
git reset --quiet --hard "$old"
|
||||
echo "update to $new refused: $file does not parse; staying on $old" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
# public/ is read from disk on every request; the rest is loaded once, at start
|
||||
if git diff --name-only "$old" "$new" | grep -qvE '^(public/|client-updates/|test/|tools/|deploy/|[^/]+\.md$|\.gitignore$)'; then
|
||||
systemctl restart "$service"
|
||||
echo "updated $old -> $new, restarted $service"
|
||||
else
|
||||
echo "updated $old -> $new, no restart needed"
|
||||
fi
|
||||
@@ -0,0 +1,694 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const {DatabaseSync} = require("node:sqlite");
|
||||
const config = require("../config.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const names = require("./names.js");
|
||||
|
||||
// accounts live in a SQLite database. identity and credentials are columns;
|
||||
// everything a player owns (animals, items, pets, den, buddies, ...) is one
|
||||
// JSON document per account in `state`.
|
||||
//
|
||||
// every account is held in memory while the server runs. game code changes
|
||||
// those objects directly and then calls save(), which has every account
|
||||
// whose state changed written back, a moment later: however many times it
|
||||
// is called in that moment, the accounts are gone through once (flush).
|
||||
|
||||
const SCHEMA = `
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT NOT NULL,
|
||||
username_key TEXT NOT NULL UNIQUE,
|
||||
password_salt TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
state TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS retired_names (
|
||||
name_key TEXT PRIMARY KEY,
|
||||
until INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS tokens (
|
||||
token TEXT PRIMARY KEY,
|
||||
account_id INTEGER NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
`;
|
||||
|
||||
// fields stored in their own columns rather than in `state`.
|
||||
const COLUMN_FIELDS = ["id", "username", "salt", "hash", "createdAt"];
|
||||
// how the game treats the account this session; set again at every login.
|
||||
const SESSION_FIELDS = ["accountType", "isGuide", "isModerator", "membershipDays", "startInDen", "startRoom"];
|
||||
const DEFAULT_MEMBERSHIP_DAYS = 9999;
|
||||
const MAX_ACCOUNT_TYPE = 5;
|
||||
const MAX_MEMBERSHIP_DAYS = 99999;
|
||||
|
||||
const USERNAME_PATTERN = /^[A-Za-z0-9 .-]{3,20}$/;
|
||||
const MIN_LETTERS = 3; // the client's own rule (SbiConstants.USERNAME_REGEX)
|
||||
const MIN_PASSWORD_LENGTH = 10;
|
||||
const MAX_DEN_SLOTS = 200; // DenSwitch.nextFreeSlotIdx
|
||||
const DEN_OPEN = 2; // den privacy: 0 locked, 1 buddies only, 2 everyone
|
||||
const MAX_PASSWORD_LENGTH = 100;
|
||||
// parts of the game a player can switch off for their own account, each
|
||||
// enforced where the game asks for it (featureOn below).
|
||||
// the Early Member badge (lib/badges.js) goes to an account made while
|
||||
// there are no more than this many.
|
||||
const EARLY_MEMBERS = 100;
|
||||
const EARLY_BADGE = "early";
|
||||
const EARLY_SETTING = "earlyMembersGiven";
|
||||
|
||||
const FEATURES = ["chat", "buddies", "trading", "jamagrams", "gameInvites", "wall"];
|
||||
const MAX_LOGINS_KEPT = 40;
|
||||
const LOGIN_DAYS_KEPT = 90; // and none older than this: they hold addresses
|
||||
|
||||
let db = null;
|
||||
const byKey = new Map(); // lowercased username -> account
|
||||
const byId = new Map();
|
||||
const savedState = new Map(); // account id -> state JSON as last written
|
||||
// A name somebody gave up (a rename, a deleted account) is nobody's to take
|
||||
// for a while: whoever had it is still known by it to the players they met.
|
||||
const NAME_HELD_DAYS = 30;
|
||||
const retired = new Map(); // lowercased username -> until (seconds)
|
||||
const tokens = new Map(); // SHA-256 of a login token -> {id, createdAt}
|
||||
|
||||
// tokens are as good as passwords, so only their hashes are stored.
|
||||
const TOKEN_HEX_LENGTH = 48;
|
||||
const MAX_TOKENS_PER_ACCOUNT = 10;
|
||||
const tokenHash = token => crypto.createHash("sha256").update(token).digest("hex");
|
||||
const tokenExpired = createdAt => now() - createdAt > config.tokenLifetimeDays * 86400;
|
||||
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
|
||||
const hashPassword = (password, salt) => crypto.scryptSync(password, salt, 32).toString("hex");
|
||||
// the same off the main thread, for the sign-ins strangers can repeat: a
|
||||
// password check takes long enough that a row of them would hold the game up.
|
||||
const hashPasswordAsync = (password, salt) => new Promise((resolve, reject) => {
|
||||
crypto.scrypt(password, salt, 32, (err, hash) => (err ? reject(err) : resolve(hash.toString("hex"))));
|
||||
});
|
||||
// checked against when the name is nobody's, so that a wrong name takes as
|
||||
// long to refuse as a wrong password.
|
||||
const NOBODY_SALT = crypto.randomBytes(16).toString("hex");
|
||||
|
||||
// eyes and pattern an animal type starts with. custom ("special") animals
|
||||
// carry their own pattern.
|
||||
const newAvatar = (ids, name, type, customAvId) => {
|
||||
const def = defpacks.avatarDef(type);
|
||||
const custom = defpacks.customAvatarDef(customAvId);
|
||||
return {
|
||||
...ids,
|
||||
name,
|
||||
type: Number(type),
|
||||
customAvId: custom ? Number(customAvId) : -1,
|
||||
colors: [def.colorLayer1, Number(custom && custom.overrideColorLayer2) || def.colorLayer2, def.colorLayer3].map(Number),
|
||||
eyes: Number(def.baseEyesId) || 0,
|
||||
pattern: Number(custom ? custom.patternRefId : def.basePatternId) || 0,
|
||||
petInvId: 0,
|
||||
};
|
||||
};
|
||||
|
||||
// an animal's inventory id is a bit's place in what the client keeps for
|
||||
// every piece of clothing, "which of my animals wear this"
|
||||
// (item.EquippedAvatars): 32 words of 32 bits and no more, and a bit past
|
||||
// them is an error that ends the login. so it is a slot, 1 to 1000, and
|
||||
// never a number from the item counter.
|
||||
const MAX_AVATAR_SLOT = 1000;
|
||||
const freeAvatarSlot = account => {
|
||||
const taken = new Set(account.avatars.map(avatar => avatar.avInvId));
|
||||
let slot = 1;
|
||||
while (taken.has(slot)) {
|
||||
slot++;
|
||||
}
|
||||
return slot;
|
||||
};
|
||||
|
||||
// brings accounts saved by older versions up to the current shape.
|
||||
const normalize = account => {
|
||||
if (!account.avatars) {
|
||||
const old = account.avatar;
|
||||
account.avatars = [{...newAvatar({perUserAvId: old.perUserAvId, avInvId: old.avInvId}, old.name, old.type, old.customAvId), colors: old.colors}];
|
||||
account.activeAvatar = old.perUserAvId;
|
||||
delete account.avatar;
|
||||
}
|
||||
account.currency = account.currency || {};
|
||||
account.items = account.items || []; // {inv, def, color, on: [avInvId, ...]}
|
||||
// animals made before their inventory ids were slots (above) have ids
|
||||
// from the item counter: they move into free slots, and what their
|
||||
// clothes say about who wears them follows.
|
||||
for (const avatar of account.avatars.filter(candidate => !(candidate.avInvId >= 1 && candidate.avInvId <= MAX_AVATAR_SLOT))) {
|
||||
const old = avatar.avInvId;
|
||||
avatar.avInvId = 0; // out of the way while a slot is looked for
|
||||
avatar.avInvId = freeAvatarSlot(account);
|
||||
for (const item of account.items) {
|
||||
item.on = (item.on || []).map(avInvId => (avInvId === old ? avatar.avInvId : avInvId));
|
||||
}
|
||||
if (account.outfitUndo && account.outfitUndo.avInvId === old) {
|
||||
account.outfitUndo.avInvId = avatar.avInvId;
|
||||
}
|
||||
}
|
||||
account.pets = account.pets || []; // {inv, lBits, uBits, eBits, name, createdAt}
|
||||
account.dens = account.dens || [{inv: 0, def: config.denDefId}]; // den rooms owned
|
||||
account.activeDen = account.activeDen || 0; // inv of the den in use
|
||||
// A den's id is its slot on the den switcher, 0 to 199 (lib/dens.js). dens
|
||||
// bought before that was known have ids from the item counter: they move
|
||||
// into the first free slots, and what points at them follows.
|
||||
if (account.dens.some(den => den.inv >= MAX_DEN_SLOTS)) {
|
||||
const taken = new Set(account.dens.map(den => den.inv).filter(inv => inv < MAX_DEN_SLOTS));
|
||||
const moved = new Map();
|
||||
for (const den of account.dens.filter(candidate => candidate.inv >= MAX_DEN_SLOTS)) {
|
||||
let slot = 0;
|
||||
while (taken.has(slot)) {
|
||||
slot++;
|
||||
}
|
||||
taken.add(slot);
|
||||
moved.set(den.inv, slot);
|
||||
den.inv = slot;
|
||||
}
|
||||
account.activeDen = moved.has(account.activeDen) ? moved.get(account.activeDen) : account.activeDen;
|
||||
for (const item of account.denItems || []) {
|
||||
item.den = moved.has(item.den) ? moved.get(item.den) : item.den;
|
||||
}
|
||||
}
|
||||
account.denPrivacy = account.denPrivacy === undefined ? DEN_OPEN : account.denPrivacy;
|
||||
account.denItems = account.denItems || []; // {inv, def, version, placed, den, x, y, flip, mannequin?, image?}: lib/dens.js
|
||||
for (const item of account.denItems) {
|
||||
item.den = item.den === undefined ? account.activeDen : item.den; // which den it is placed in
|
||||
}
|
||||
account.userVars = account.userVars || {};
|
||||
account.theme = account.theme || ""; // seasonal look of the lands, see themes in config.js
|
||||
account.lastSeen = account.lastSeen || 0; // when they last left the game, in seconds; 0 = never recorded
|
||||
// what the player set on the account page (lib/manage.js).
|
||||
account.features = {...Object.fromEntries(FEATURES.map(name => [name, true])), ...account.features}; // false = switched off
|
||||
account.locked = account.locked === true; // nobody gets into the game until its owner unlocks it
|
||||
account.logins = account.logins || []; // {at, via, address, ok}, newest first: lib/accounts.js recordLogin
|
||||
account.roomThemes = account.roomThemes || {}; // room -> theme, for rooms given a look of their own ("!theme here")
|
||||
account.randomTheme = account.randomTheme === true; // a theme picked afresh at every login
|
||||
account.denVisits = account.denVisits || []; // {at, name}, newest first: who came into their den
|
||||
account.buddyNotes = account.buddyNotes || {}; // lowercased username -> the player's own note about that buddy
|
||||
account.tradeHistory = account.tradeHistory || []; // {at, with, got: [names], gave: [names]}, newest first
|
||||
account.outfitUndo = account.outfitUndo || null; // {avInvId, items: [inv]}: what an animal wore before its last change
|
||||
account.denNames = account.denNames || {}; // den inv -> a name of the player's own ("!den name")
|
||||
account.finderGiven = account.finderGiven || {}; // "kind:id" -> {count, at}: what they took from the item finder
|
||||
account.tradeOffers = account.tradeOffers || []; // offers left for this account while its owner was away: lib/trades.js
|
||||
account.denUndo = account.denUndo || null; // the den as it stood before it was last cleared: {den, items}
|
||||
account.buddies = account.buddies || []; // lowercased usernames
|
||||
account.blocked = account.blocked || [];
|
||||
account.buddyRequests = account.buddyRequests || []; // lowercased usernames of who asked, see lib/buddies.js
|
||||
account.tradeList = account.tradeList || []; // {type, inv}; types as in TradeItem
|
||||
account.achievements = account.achievements || []; // {inv, def}, see lib/achievements.js
|
||||
account.adoptAPets = account.adoptAPets || []; // {inv, def, ts, seen}, see lib/adopt.js
|
||||
account.ecards = account.ecards || []; // the Jam-A-Gram inbox, see lib/ecards.js
|
||||
account.ecardPrivacy = account.ecardPrivacy || 0; // 0 everyone, 1 buddies only, 2 nobody
|
||||
// the Jammer Wall, see lib/walls.js. privacy: 0 nobody, 1 buddies only, 2 everyone.
|
||||
account.wall = account.wall || {privacy: DEN_OPEN, posts: [], params: {bg: "19"}, visits: 0, hidden: [], modified: 0, readAt: 0};
|
||||
account.outfits = account.outfits || []; // {name, items: [inv, ...]}, see lib/commands.js
|
||||
account.denLayouts = account.denLayouts || []; // {name, den, items: [{def, version, x, y, flip}]}
|
||||
account.hideBlocked = account.hideBlocked === true; // do not show me players I blocked
|
||||
// the name tag: colour in the low byte, badge above it, bit 16 hides the
|
||||
// adventure level shape (avatar.NameBar.setColorAndBadge).
|
||||
account.nameBarData = Number.isInteger(account.nameBarData) ? account.nameBarData : 0;
|
||||
account.disguise = Number.isInteger(account.disguise) ? account.disguise : 0; // NPC id, see lib/disguises.js
|
||||
// shown on the player's card: lib/badges.js.
|
||||
account.discord = typeof account.discord === "string" ? account.discord : ""; // their Discord username, as they gave it
|
||||
account.badges = Array.isArray(account.badges) ? account.badges : []; // badge ids, given in the admin panel
|
||||
account.bio = typeof account.bio === "string" ? account.bio : ""; // their own words, for the card's Bio tab
|
||||
// the chat filter, which the player's own game applies (AJClient in the
|
||||
// patched SWF; "xfl" in lib/world.js): {level: 1 slurs and threats, 2
|
||||
// swearing too, 0 off; mode: 0 stars over the words, 1 the message left
|
||||
// out; words: their own, commas between; chosen: have they been asked}.
|
||||
// an account that has not chosen has no filter: that is the start.
|
||||
account.filter = account.filter && typeof account.filter === "object" && account.filter.chosen ? account.filter : {level: 0, mode: 0, words: "", chosen: false};
|
||||
// two-step sign-in: lib/totp.js.
|
||||
account.totp = account.totp || null;
|
||||
account.totpSetup = account.totpSetup || null;
|
||||
account.devices = Array.isArray(account.devices) ? account.devices : [];
|
||||
account.nextInv = account.nextInv || 2;
|
||||
account.numLogins = account.numLogins || 0;
|
||||
account.uuid = account.uuid || crypto.randomUUID();
|
||||
setLoginChoices(account, null);
|
||||
return account;
|
||||
};
|
||||
|
||||
// sets how the game treats the account for the coming session. `choices` is
|
||||
// what the client asked for at login ({accountType, isGuide, isModerator,
|
||||
// membershipDays}, each optional); anything missing, invalid or not allowed
|
||||
// by config.loginChoices gets the usual value.
|
||||
const MAX_START_ROOM = 80;
|
||||
|
||||
function setLoginChoices(account, choices) {
|
||||
const asked = config.loginChoices && choices && typeof choices === "object" ? choices : {};
|
||||
const whole = (value, max) => Number.isInteger(value) && value >= 0 && value <= max;
|
||||
account.accountType = whole(asked.accountType, MAX_ACCOUNT_TYPE) ? asked.accountType : config.defaultAccountType;
|
||||
account.isGuide = asked.isGuide === true;
|
||||
account.isModerator = asked.isModerator === true;
|
||||
account.membershipDays = whole(asked.membershipDays, MAX_MEMBERSHIP_DAYS) ? asked.membershipDays : DEFAULT_MEMBERSHIP_DAYS;
|
||||
// where to start is the player's to say on any server: their own den in
|
||||
// place of the township (the custom client's "Start in your own den").
|
||||
account.startInDen = Boolean(choices && typeof choices === "object" && choices.startInDen === true);
|
||||
// ... or a room or den by name ("denf", "jamaa_township.room_main");
|
||||
// lib/world.js checks that there is such a place.
|
||||
const room = choices && typeof choices === "object" ? choices.startRoom : null;
|
||||
account.startRoom = typeof room === "string" && room.length <= MAX_START_ROOM && !room.includes("%") ? room.trim() : "";
|
||||
}
|
||||
|
||||
const stateJson = account => JSON.stringify(Object.fromEntries(Object.entries(account)
|
||||
.filter(([field]) => !COLUMN_FIELDS.includes(field) && !SESSION_FIELDS.includes(field))));
|
||||
|
||||
const remember = account => {
|
||||
byKey.set(account.username.toLowerCase(), account);
|
||||
byId.set(account.id, account);
|
||||
};
|
||||
|
||||
const insert = (username, salt, hash, createdAt, state) => {
|
||||
const account = normalize({username, salt, hash, createdAt, ...state});
|
||||
const json = stateJson(account);
|
||||
const result = db.prepare("INSERT INTO accounts (username, username_key, password_salt, password_hash, created_at, state) VALUES (?, ?, ?, ?, ?, ?)")
|
||||
.run(username, username.toLowerCase(), salt, hash, createdAt, json);
|
||||
account.id = Number(result.lastInsertRowid);
|
||||
savedState.set(account.id, json);
|
||||
remember(account);
|
||||
return account;
|
||||
};
|
||||
|
||||
// one-time import of the accounts.json file earlier versions kept.
|
||||
const importLegacyFile = () => {
|
||||
const file = path.join(config.dataDir, "accounts.json");
|
||||
if (!fs.existsSync(file) || db.prepare("SELECT COUNT(*) AS count FROM accounts").get().count > 0) {
|
||||
return;
|
||||
}
|
||||
const legacy = JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
db.exec("BEGIN");
|
||||
for (const old of Object.values(legacy.accounts)) {
|
||||
const {id, username, salt, hash, createdAt, ...state} = old;
|
||||
if (!byKey.has(username.trim().toLowerCase())) {
|
||||
insert(username.trim(), salt, hash, createdAt || now(), state);
|
||||
}
|
||||
}
|
||||
for (const [token, usernameKey] of Object.entries(legacy.tokens || {})) {
|
||||
const account = byKey.get(usernameKey.trim());
|
||||
if (account) {
|
||||
db.prepare("INSERT INTO tokens (token, account_id, created_at) VALUES (?, ?, ?)").run(token, account.id, now());
|
||||
}
|
||||
}
|
||||
db.exec("COMMIT");
|
||||
fs.renameSync(file, `${file}.imported`);
|
||||
console.log(`[accounts] imported ${byKey.size} accounts from accounts.json`);
|
||||
};
|
||||
|
||||
const load = () => {
|
||||
fs.mkdirSync(config.dataDir, {recursive: true});
|
||||
db = new DatabaseSync(path.join(config.dataDir, "game.sqlite"));
|
||||
// busy_timeout: something else writing to the file for a moment (a tool,
|
||||
// a copy being made) is waited for, not an error.
|
||||
db.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;");
|
||||
db.exec(SCHEMA);
|
||||
for (const row of db.prepare("SELECT * FROM accounts").all()) {
|
||||
const account = normalize({
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
salt: row.password_salt,
|
||||
hash: row.password_hash,
|
||||
createdAt: row.created_at,
|
||||
...JSON.parse(row.state),
|
||||
});
|
||||
savedState.set(account.id, row.state);
|
||||
remember(account);
|
||||
}
|
||||
importLegacyFile();
|
||||
db.prepare("DELETE FROM retired_names WHERE until < ?").run(now());
|
||||
for (const row of db.prepare("SELECT name_key, until FROM retired_names").all()) {
|
||||
retired.set(row.name_key, row.until);
|
||||
}
|
||||
// trade offers left on an account name who made them by account id
|
||||
// (lib/trades.js). ones from before that named a username: the id is
|
||||
// filled in, and an offer by nobody still here is dropped.
|
||||
for (const account of byId.values()) {
|
||||
for (const offer of account.tradeOffers) {
|
||||
if (offer.fromId === undefined) {
|
||||
const maker = byKey.get(String(offer.from));
|
||||
offer.fromId = maker ? maker.id : 0;
|
||||
}
|
||||
}
|
||||
account.tradeOffers = account.tradeOffers.filter(offer => byId.has(offer.fromId));
|
||||
}
|
||||
// accounts made before some names were set aside keep theirs; whoever
|
||||
// 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 ? ", ..." : ""}`);
|
||||
}
|
||||
// once: the Early Member badge for the accounts that were there before
|
||||
// it existed, the oldest hundred of them.
|
||||
if (!setting(EARLY_SETTING)) {
|
||||
const oldest = [...byId.values()].sort((one, other) => one.createdAt - other.createdAt || one.id - other.id).slice(0, EARLY_MEMBERS);
|
||||
for (const account of oldest) {
|
||||
if (!account.badges.includes(EARLY_BADGE)) {
|
||||
account.badges.push(EARLY_BADGE);
|
||||
}
|
||||
}
|
||||
flush();
|
||||
setSetting(EARLY_SETTING, "1");
|
||||
}
|
||||
// tokens stored as issued by earlier versions are replaced by their hashes.
|
||||
const rehash = db.prepare("UPDATE tokens SET token = ? WHERE token = ?");
|
||||
for (const row of db.prepare("SELECT token FROM tokens WHERE length(token) = ?").all(TOKEN_HEX_LENGTH)) {
|
||||
rehash.run(tokenHash(row.token), row.token);
|
||||
}
|
||||
db.prepare("DELETE FROM tokens WHERE created_at < ?").run(now() - config.tokenLifetimeDays * 86400);
|
||||
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")}`);
|
||||
};
|
||||
|
||||
// writes every account whose state changed since it was last written, in
|
||||
// one transaction.
|
||||
const flush = () => {
|
||||
clearTimeout(saveTimer);
|
||||
saveTimer = null;
|
||||
if (!db) {
|
||||
return;
|
||||
}
|
||||
const changed = [];
|
||||
for (const account of byId.values()) {
|
||||
const json = stateJson(account);
|
||||
if (savedState.get(account.id) !== json) {
|
||||
changed.push([account.id, json]);
|
||||
}
|
||||
}
|
||||
if (changed.length === 0) {
|
||||
return;
|
||||
}
|
||||
const update = db.prepare("UPDATE accounts SET state = ? WHERE id = ?");
|
||||
db.exec("BEGIN");
|
||||
try {
|
||||
for (const [id, json] of changed) {
|
||||
update.run(json, id);
|
||||
}
|
||||
db.exec("COMMIT");
|
||||
}
|
||||
catch (err) {
|
||||
db.exec("ROLLBACK");
|
||||
throw err;
|
||||
}
|
||||
for (const [id, json] of changed) {
|
||||
savedState.set(id, json);
|
||||
}
|
||||
};
|
||||
|
||||
// "Something changed": the accounts are written within SAVE_DELAY_MS. going
|
||||
// through every account costs more the more there are, and game code calls
|
||||
// this after nearly every message (and some of it a hundred times in a
|
||||
// row), so the going-through is done once for all the calls of a moment.
|
||||
// what a crash can lose is that moment; a stop of the server writes first
|
||||
// (server.js).
|
||||
const SAVE_DELAY_MS = 1000;
|
||||
let saveTimer = null;
|
||||
const save = () => {
|
||||
if (saveTimer === null) {
|
||||
saveTimer = setTimeout(() => {
|
||||
try {
|
||||
flush();
|
||||
}
|
||||
catch (err) {
|
||||
console.error(`[accounts] could not save: ${err.message}`);
|
||||
save(); // tried again in a moment: nothing is lost while the server runs
|
||||
}
|
||||
}, SAVE_DELAY_MS);
|
||||
}
|
||||
};
|
||||
|
||||
// A copy of the whole database, made once a day into data/backups/ and the
|
||||
// latest BACKUPS_KEPT kept. it is a whole file of its own (VACUUM INTO), to
|
||||
// be copied somewhere else by whoever runs the server: a copy on the same
|
||||
// disk is no help when the disk goes.
|
||||
const BACKUPS_KEPT = 14;
|
||||
const backup = () => {
|
||||
const folder = path.join(config.dataDir, "backups");
|
||||
const file = path.join(folder, `game-${new Date().toISOString().slice(0, 10)}.sqlite`);
|
||||
if (fs.existsSync(file)) {
|
||||
return;
|
||||
}
|
||||
fs.mkdirSync(folder, {recursive: true, mode: 0o700});
|
||||
flush();
|
||||
db.prepare("VACUUM INTO ?").run(file);
|
||||
fs.chmodSync(file, 0o600);
|
||||
const old = fs.readdirSync(folder).filter(name => /^game-\d{4}-\d{2}-\d{2}\.sqlite$/.test(name)).sort().slice(0, -BACKUPS_KEPT);
|
||||
for (const name of old) {
|
||||
fs.unlinkSync(path.join(folder, name));
|
||||
}
|
||||
console.log(`[accounts] backup written: ${file}`);
|
||||
};
|
||||
const startBackups = () => {
|
||||
const attempt = () => {
|
||||
try {
|
||||
backup();
|
||||
}
|
||||
catch (err) {
|
||||
console.error(`[accounts] backup failed: ${err.message}`);
|
||||
}
|
||||
};
|
||||
attempt();
|
||||
setInterval(attempt, 3600000).unref();
|
||||
};
|
||||
|
||||
const usernameProblem = username => {
|
||||
if (typeof username !== "string" || !USERNAME_PATTERN.test(username) || username !== username.trim() || /\s{2,}/.test(username)
|
||||
|| (username.match(/[A-Za-z]/g) || []).length < MIN_LETTERS) {
|
||||
return "invalid_username";
|
||||
}
|
||||
if (byKey.has(username.toLowerCase()) || (retired.get(username.toLowerCase()) || 0) > now()) {
|
||||
return "username_taken";
|
||||
}
|
||||
// staff-like names and slurs (lib/names.js).
|
||||
return names.refused(username) ? "name_not_allowed" : null;
|
||||
};
|
||||
|
||||
const retire = key => {
|
||||
const until = now() + NAME_HELD_DAYS * 86400;
|
||||
retired.set(key, until);
|
||||
db.prepare("INSERT INTO retired_names (name_key, until) VALUES (?, ?) ON CONFLICT(name_key) DO UPDATE SET until = excluded.until").run(key, until);
|
||||
};
|
||||
|
||||
// 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);
|
||||
|
||||
// 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
|
||||
// animal: whoever signs up picks one.
|
||||
// returns {account} or {error: "invalid_username" | "username_taken" |
|
||||
// "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");
|
||||
if (error) {
|
||||
return {error};
|
||||
}
|
||||
const type = Number(avatar.type);
|
||||
const salt = crypto.randomBytes(16).toString("hex");
|
||||
const account = insert(username, salt, hashPassword(password, salt), now(), {
|
||||
avatars: [newAvatar({perUserAvId: 1, avInvId: 1}, avatar.name || username, type, -1)],
|
||||
activeAvatar: 1,
|
||||
// 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})`);
|
||||
return {account};
|
||||
};
|
||||
|
||||
const authenticate = (username, password) => {
|
||||
// "name" and "name " are the same account.
|
||||
const account = typeof username === "string" ? byKey.get(username.trim().toLowerCase()) : null;
|
||||
if (typeof password !== "string" || !password) {
|
||||
return null;
|
||||
}
|
||||
if (password.length > MAX_PASSWORD_LENGTH) {
|
||||
return null;
|
||||
}
|
||||
if (!account) {
|
||||
// throwaway test accounts (AJ_REGISTER=1) are the one sign-up with no
|
||||
// choice of animal to make.
|
||||
if (config.registerOnLogin) {
|
||||
return register(username, password, {type: defpacks.defaultAvatarType()}).account || null;
|
||||
}
|
||||
hashPassword(password, NOBODY_SALT);
|
||||
return null;
|
||||
}
|
||||
const hash = Buffer.from(hashPassword(password, account.salt), "hex");
|
||||
return crypto.timingSafeEqual(hash, Buffer.from(account.hash, "hex")) ? account : null;
|
||||
};
|
||||
|
||||
// the same, with the password worked out off the main thread (above).
|
||||
const authenticateAsync = async (username, password) => {
|
||||
const account = typeof username === "string" ? byKey.get(username.trim().toLowerCase()) : null;
|
||||
if (typeof password !== "string" || !password || password.length > MAX_PASSWORD_LENGTH) {
|
||||
return null;
|
||||
}
|
||||
if (!account) {
|
||||
if (config.registerOnLogin) {
|
||||
return register(username, password, {type: defpacks.defaultAvatarType()}).account || null;
|
||||
}
|
||||
await hashPasswordAsync(password, NOBODY_SALT);
|
||||
return null;
|
||||
}
|
||||
const {salt, hash: stored} = account;
|
||||
const hash = Buffer.from(await hashPasswordAsync(password, salt), "hex");
|
||||
// the account may have gone, or got a new password, in the meantime.
|
||||
return byId.get(account.id) === account && account.hash === stored && crypto.timingSafeEqual(hash, Buffer.from(stored, "hex")) ? account : null;
|
||||
};
|
||||
|
||||
// gives the account a new password and signs it out everywhere. returns
|
||||
// "invalid_password" when the password is not acceptable, else null.
|
||||
const setPassword = (account, password) => {
|
||||
const problem = passwordProblem(password);
|
||||
if (problem) {
|
||||
return problem;
|
||||
}
|
||||
account.salt = crypto.randomBytes(16).toString("hex");
|
||||
account.hash = hashPassword(password, account.salt);
|
||||
db.prepare("UPDATE accounts SET password_salt = ?, password_hash = ? WHERE id = ?").run(account.salt, account.hash, account.id);
|
||||
revokeTokens(account);
|
||||
account.devices = []; // every device gives its two-step code again (lib/totp.js)
|
||||
flush();
|
||||
return null;
|
||||
};
|
||||
|
||||
// the only limits on a username the admin sets by hand: it has to be storable
|
||||
// and able to reach the game at all. the database needs some text and a name
|
||||
// nobody else has; "%" and control characters cannot travel through the game
|
||||
// protocol ("%" separates its fields), so such a name could never log in.
|
||||
// MAX_STORED_USERNAME is a sanity cap, not a rule of the game.
|
||||
const MAX_STORED_USERNAME = 100;
|
||||
const storableUsernameProblem = username => {
|
||||
if (typeof username !== "string" || username.length === 0 || username.length > MAX_STORED_USERNAME
|
||||
|| /[%\u0000-\u001f\u007f]/.test(username) || username.includes("]]>")) {
|
||||
return "invalid_username";
|
||||
}
|
||||
return byKey.has(username.toLowerCase()) ? "username_taken" : null;
|
||||
};
|
||||
|
||||
// gives the account a new username, and carries it into everyone's buddy and
|
||||
// block lists. returns "invalid_username" or "username_taken", else null.
|
||||
// the player must not be online: the game knows them by the old name.
|
||||
// with `anyName` (the admin panel) the sign-up rules about length and
|
||||
// characters do not apply; see storableUsernameProblem.
|
||||
const rename = (account, username, anyName = false) => {
|
||||
// spaces around a name are dropped: logging in drops them too.
|
||||
username = typeof username === "string" ? username.trim() : username;
|
||||
const oldKey = account.username.toLowerCase();
|
||||
// only changing the capitals of one's own name is not "taken".
|
||||
const problem = typeof username === "string" && username.toLowerCase() === oldKey && username !== account.username
|
||||
? null : (anyName ? storableUsernameProblem : usernameProblem)(username);
|
||||
if (problem) {
|
||||
return problem;
|
||||
}
|
||||
const newKey = username.toLowerCase();
|
||||
if (newKey !== oldKey) {
|
||||
retire(oldKey);
|
||||
retired.delete(newKey); // the admin gave out a held name
|
||||
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})`);
|
||||
byKey.delete(oldKey);
|
||||
account.username = username;
|
||||
byKey.set(newKey, account);
|
||||
for (const other of byId.values()) {
|
||||
other.buddies = other.buddies.map(name => (name === oldKey ? newKey : name));
|
||||
other.blocked = other.blocked.map(name => (name === oldKey ? newKey : name));
|
||||
other.buddyRequests = other.buddyRequests.map(name => (name === oldKey ? newKey : name));
|
||||
}
|
||||
save();
|
||||
return null;
|
||||
};
|
||||
|
||||
// is this part of the game switched on for the account (FEATURES)?
|
||||
const featureOn = (account, name) => account.features[name] !== false;
|
||||
|
||||
// notes a sign-in, or a wrong password, in the account's own history.
|
||||
// `via` is "game" (the game itself connecting), "launcher" (signing in to
|
||||
// play) or "web" (the account page). the caller saves.
|
||||
const recordLogin = (account, via, address, ok = true) => {
|
||||
account.logins.unshift({at: now(), via, address: String(address || "").replace(/^::ffff:/, "").slice(0, 60), ok});
|
||||
account.logins = account.logins.filter(login => login.at > now() - LOGIN_DAYS_KEPT * 86400).slice(0, MAX_LOGINS_KEPT);
|
||||
};
|
||||
|
||||
const revokeTokens = account => {
|
||||
db.prepare("DELETE FROM tokens WHERE account_id = ?").run(account.id);
|
||||
for (const [hash, entry] of tokens) {
|
||||
if (entry.id === account.id) {
|
||||
tokens.delete(hash);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// deletes the account for good, and its name from everyone's buddy and
|
||||
// block lists.
|
||||
const remove = account => {
|
||||
const key = account.username.toLowerCase();
|
||||
revokeTokens(account);
|
||||
db.prepare("DELETE FROM accounts WHERE id = ?").run(account.id);
|
||||
byKey.delete(key);
|
||||
byId.delete(account.id);
|
||||
savedState.delete(account.id);
|
||||
retire(key);
|
||||
for (const other of byId.values()) {
|
||||
other.tradeOffers = other.tradeOffers.filter(offer => offer.fromId !== account.id);
|
||||
other.buddies = other.buddies.filter(name => name !== key);
|
||||
other.blocked = other.blocked.filter(name => name !== key);
|
||||
other.buddyRequests = other.buddyRequests.filter(name => name !== key);
|
||||
}
|
||||
save();
|
||||
console.log(`[accounts] deleted "${account.username}" (id ${account.id})`);
|
||||
};
|
||||
|
||||
// small server-wide values kept in the database (the admin panel's password).
|
||||
const setting = key => {
|
||||
const row = db.prepare("SELECT value FROM settings WHERE key = ?").get(key);
|
||||
return row ? row.value : null;
|
||||
};
|
||||
|
||||
const setSetting = (key, value) => {
|
||||
db.prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(key, value);
|
||||
};
|
||||
|
||||
// one token serves as both auth_token and refresh_token. it stops working
|
||||
// after config.tokenLifetimeDays, and each account keeps only its newest few.
|
||||
const issueToken = account => {
|
||||
const token = crypto.randomBytes(TOKEN_HEX_LENGTH / 2).toString("hex");
|
||||
const hash = tokenHash(token);
|
||||
const createdAt = now();
|
||||
db.prepare("INSERT INTO tokens (token, account_id, created_at) VALUES (?, ?, ?)").run(hash, account.id, createdAt);
|
||||
tokens.set(hash, {id: account.id, createdAt});
|
||||
const mine = [...tokens].filter(([, entry]) => entry.id === account.id).sort((a, b) => b[1].createdAt - a[1].createdAt);
|
||||
for (const [oldHash] of mine.slice(MAX_TOKENS_PER_ACCOUNT)) {
|
||||
db.prepare("DELETE FROM tokens WHERE token = ?").run(oldHash);
|
||||
tokens.delete(oldHash);
|
||||
}
|
||||
return token;
|
||||
};
|
||||
|
||||
const byToken = token => {
|
||||
const entry = typeof token === "string" && token.length === TOKEN_HEX_LENGTH ? tokens.get(tokenHash(token)) : null;
|
||||
return entry && !tokenExpired(entry.createdAt) ? byId.get(entry.id) || null : null;
|
||||
};
|
||||
|
||||
const byName = username => byKey.get(String(username).toLowerCase()) || null;
|
||||
|
||||
const accountById = id => byId.get(Number(id)) || null;
|
||||
|
||||
const all = () => [...byId.values()];
|
||||
|
||||
const database = () => db;
|
||||
|
||||
module.exports = {FEATURES, featureOn, recordLogin, revokeTokens, load, save, flush, startBackups, database, setLoginChoices, setPassword, rename, remove, setting, setSetting, hashPassword, register, usernameProblem, authenticate, authenticateAsync, issueToken, byToken, byName, byId: accountById, newAvatar, freeAvatarSlot, all};
|
||||
@@ -0,0 +1,167 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
|
||||
// achievements (client side: AchievementManager, AchievementXtCommManager).
|
||||
// an achievement def names a user var and the value it has to reach. most
|
||||
// user vars are counters the official servers kept ("gems earned", "buddies
|
||||
// added"); the ones this server can count itself are kept here, and the rest
|
||||
// are whatever the client last set them to (see "zs" in world.js).
|
||||
//
|
||||
// A player's achievements are {inv, def} pairs in account.achievements. the
|
||||
// client learns about a new one from the reply to a user var change.
|
||||
|
||||
// counters only the server changes; a client's own "zs" for one is ignored.
|
||||
const VARS = {
|
||||
gemsEarned: 1,
|
||||
gemsSpent: 2,
|
||||
denItemsBought: 3,
|
||||
clothesBought: 4,
|
||||
jamAGramsSent: 38,
|
||||
giftsSent: 39,
|
||||
buddiesAdded: 40,
|
||||
animals: 51,
|
||||
pets: 212,
|
||||
adoptAPets: 426,
|
||||
worldItemsTaken: 439, // one bit per gift found in the lands (lib/worlditems.js)
|
||||
};
|
||||
const SERVER_VARS = new Set(Object.values(VARS));
|
||||
const CURRENCY_GEMS = "gems";
|
||||
|
||||
let findOnline = () => null;
|
||||
|
||||
let byVar = null;
|
||||
const defsFor = varId => {
|
||||
if (!byVar) {
|
||||
byVar = new Map();
|
||||
for (const def of defpacks.achievementDefs()) {
|
||||
byVar.set(def.userVarRef, [...(byVar.get(def.userVarRef) || []), def]);
|
||||
}
|
||||
}
|
||||
return byVar.get(Number(varId)) || [];
|
||||
};
|
||||
|
||||
// gives the account every achievement its value of `varId` has earned and
|
||||
// returns the new ones. the caller saves.
|
||||
const award = (account, varId) => {
|
||||
const value = Number(account.userVars[varId]) || 0;
|
||||
const earned = [];
|
||||
for (const def of defsFor(varId)) {
|
||||
if (value >= def.triggerAmount && !account.achievements.some(have => have.def === def.id)) {
|
||||
const achievement = {inv: account.nextInv++, def: def.id};
|
||||
account.achievements.push(achievement);
|
||||
earned.push(achievement);
|
||||
}
|
||||
}
|
||||
return earned;
|
||||
};
|
||||
|
||||
// AchievementXtCommManager.setUserVarResponse: [varId, value, newCount,
|
||||
// (invId, defId)...]. sent unasked it still updates the client's copy of the
|
||||
// var and pops up the new achievements.
|
||||
const sendVar = (session, varId, earned = []) => {
|
||||
session.sendXt("zs", -1, varId, session.account.userVars[varId], earned.length,
|
||||
...earned.flatMap(achievement => [achievement.inv, achievement.def]));
|
||||
};
|
||||
|
||||
// sets a user var, hands out what that earns and tells the player if they
|
||||
// are online. the caller saves.
|
||||
const set = (account, varId, value) => {
|
||||
if (account.userVars[varId] === value) {
|
||||
return;
|
||||
}
|
||||
account.userVars[varId] = value;
|
||||
const earned = award(account, varId);
|
||||
const session = findOnline(account.username);
|
||||
if (session) {
|
||||
sendVar(session, varId, earned);
|
||||
}
|
||||
};
|
||||
|
||||
const add = (account, varId, amount = 1) => set(account, varId, (Number(account.userVars[varId]) || 0) + amount);
|
||||
|
||||
// counts a change of some currency towards "gems earned" / "gems spent".
|
||||
const currencyChanged = (account, currencyName, delta) => {
|
||||
if (currencyName === CURRENCY_GEMS && delta !== 0) {
|
||||
add(account, delta > 0 ? VARS.gemsEarned : VARS.gemsSpent, Math.abs(delta));
|
||||
}
|
||||
};
|
||||
|
||||
// brings the counters that mirror what an account owns up to date (accounts
|
||||
// from before achievements existed, gifts from the admin panel, ...).
|
||||
const refresh = account => {
|
||||
set(account, VARS.animals, Math.max(Number(account.userVars[VARS.animals]) || 0, account.avatars.length));
|
||||
set(account, VARS.pets, Math.max(Number(account.userVars[VARS.pets]) || 0, account.pets.length));
|
||||
set(account, VARS.buddiesAdded, Math.max(Number(account.userVars[VARS.buddiesAdded]) || 0, account.buddies.length));
|
||||
set(account, VARS.adoptAPets, account.adoptAPets.length);
|
||||
};
|
||||
|
||||
// gives one achievement outright (the admin panel). false if unknown or owned.
|
||||
const grant = (account, defId) => {
|
||||
const def = defpacks.achievementDefs().find(candidate => candidate.id === Number(defId));
|
||||
if (!def || account.achievements.some(have => have.def === def.id)) {
|
||||
return false;
|
||||
}
|
||||
const achievement = {inv: account.nextInv++, def: def.id};
|
||||
account.achievements.push(achievement);
|
||||
accounts.save();
|
||||
const session = findOnline(account.username);
|
||||
if (session) {
|
||||
if (account.userVars[def.userVarRef] === undefined) {
|
||||
account.userVars[def.userVarRef] = 0;
|
||||
}
|
||||
sendVar(session, def.userVarRef, [achievement]);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
// for the account page: how many achievements the account has, and for
|
||||
// each thing the game counts, how far along it is. the defs carry no
|
||||
// readable title, only an internal name like "2_Gems_10000_Gems_Earned".
|
||||
const label = def => String(def.name).split("_").filter(word => word && !/^\d+$/.test(word))
|
||||
.filter((word, index, words) => word !== words[index - 1]).join(" ");
|
||||
const progress = account => {
|
||||
const all = defpacks.achievementDefs();
|
||||
const have = new Set(account.achievements.map(achievement => achievement.def));
|
||||
const groups = new Map();
|
||||
for (const def of all) {
|
||||
groups.set(def.userVarRef, [...(groups.get(def.userVarRef) || []), def]);
|
||||
}
|
||||
const counted = [...groups].map(([varId, defs]) => {
|
||||
const steps = defs.map(def => def.triggerAmount).sort((one, other) => one - other);
|
||||
const value = Number(account.userVars[varId]) || 0;
|
||||
const next = steps.find(step => step > value);
|
||||
return {name: label(defs[defs.length - 1]), value, next: next === undefined ? null : next, earned: defs.filter(def => have.has(def.id)).length, of: defs.length};
|
||||
});
|
||||
return {earned: have.size, of: all.length, counted: counted.sort((one, other) => one.name.localeCompare(other.name))};
|
||||
};
|
||||
|
||||
const handlers = {
|
||||
// AchievementXtCommManager.getAchievementsResponse: [username, count,
|
||||
// (invId, defId)...]; a count of -1 says "nothing new since you last asked".
|
||||
za(session, roomId, [username]) {
|
||||
const account = accounts.byName(username);
|
||||
const list = account ? account.achievements : [];
|
||||
session.sendXt("za", -1, account ? account.username : username, list.length, ...list.flatMap(achievement => [achievement.inv, achievement.def]));
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
// is this a user var some achievement watches, and not one of the server's own?
|
||||
counts: varId => !SERVER_VARS.has(Number(varId)) && defsFor(varId).length > 0,
|
||||
VARS,
|
||||
SERVER_VARS,
|
||||
handlers,
|
||||
award,
|
||||
sendVar,
|
||||
set,
|
||||
add,
|
||||
currencyChanged,
|
||||
refresh,
|
||||
grant,
|
||||
progress,
|
||||
setFinder(finder) {
|
||||
findOnline = finder;
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,231 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const bans = require("./bans.js");
|
||||
const captcha = require("./captcha.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const config = require("../config.js");
|
||||
const dens = require("./dens.js");
|
||||
const limits = require("./limits.js");
|
||||
const world = require("./world.js");
|
||||
const {addClothing, sendClothingAdded, isUint} = require("./player.js");
|
||||
|
||||
// backs the item finder page (/shop): look any item up by id or name and put
|
||||
// it straight into an account, since in-game shops only stock a slice each.
|
||||
|
||||
const MAX_RESULTS = 60;
|
||||
const givesPerMinute = limits.limiter(120, 60000); // per account, from anywhere but this machine
|
||||
const MAX_FAVOURITES = 200; // finder items remembered per account
|
||||
// the nine animals the official sign-up page offers (public/register.html
|
||||
// has their pictures): tiger, wolf, koala, panda, monkey, bunny, rhino, seal, penguin.
|
||||
const STARTER_ANIMALS = [1, 4, 5, 6, 7, 8, 13, 18, 24];
|
||||
|
||||
let catalog = null;
|
||||
|
||||
const buildCatalog = () => [
|
||||
...defpacks.clothingIds().map(id => {
|
||||
const def = defpacks.itemDef(id);
|
||||
return {kind: "clothing", id, name: defpacks.string(def.titleStrId), cost: Number(def.value), colors: String(def.colors).split(",").length};
|
||||
}),
|
||||
...defpacks.denItemIds().map(id => {
|
||||
const def = defpacks.denItemDef(id);
|
||||
return {kind: "den", id, name: defpacks.string(def.nameStrId) || def.abbrName, cost: Number(def.cost), colors: 1};
|
||||
}),
|
||||
].map(entry => ({...entry, search: entry.name.toLowerCase()}));
|
||||
|
||||
// `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) => {
|
||||
catalog = catalog || buildCatalog();
|
||||
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));
|
||||
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};
|
||||
matches.sort((a, b) => taken(b).count - taken(a).count || taken(b).at - taken(a).at);
|
||||
}
|
||||
return {
|
||||
total: matches.length,
|
||||
results: matches.slice(0, MAX_RESULTS).map(({kind: entryKind, id, name, cost, colors}) => ({kind: entryKind, id, name, cost, colors})),
|
||||
};
|
||||
};
|
||||
|
||||
const give = body => {
|
||||
const account = accounts.byName(body.username);
|
||||
if (!account) {
|
||||
return {status: 404, body: {error: "No such account"}};
|
||||
}
|
||||
const session = world.findOnline(account.username);
|
||||
if (body.kind === "clothing") {
|
||||
const def = defpacks.itemDef(body.id);
|
||||
const colors = def ? String(def.colors).split(",") : [];
|
||||
// `color` is a raw colour id of the caller's choosing; otherwise one of
|
||||
// the item's own colours is picked by `colorIndex`.
|
||||
const custom = body.color !== undefined && body.color !== "";
|
||||
if (custom && !isUint(String(body.color))) {
|
||||
return {status: 400, body: {error: "The colour id must be a whole number from 0 to 4294967295"}};
|
||||
}
|
||||
const color = custom ? String(body.color) : colors[Number(body.colorIndex) || 0];
|
||||
if (!def || !defpacks.clothingIds().includes(Number(def.id)) || color === undefined) {
|
||||
return {status: 400, body: {error: "No such clothing item or colour"}};
|
||||
}
|
||||
const item = addClothing(account, def.id, color);
|
||||
if (!item) {
|
||||
return {status: 409, body: {error: "That inventory is full"}};
|
||||
}
|
||||
accounts.save();
|
||||
if (session) {
|
||||
sendClothingAdded(session, item);
|
||||
}
|
||||
}
|
||||
else if (body.kind === "den") {
|
||||
if (!defpacks.denItemIds().includes(Number(body.id))) {
|
||||
return {status: 400, body: {error: "No such den item"}};
|
||||
}
|
||||
if (!dens.giveDenItem(account, body.id)) {
|
||||
return {status: 409, body: {error: "That inventory is full"}};
|
||||
}
|
||||
if (session) {
|
||||
dens.sendDenItems(session);
|
||||
}
|
||||
}
|
||||
else {
|
||||
return {status: 400, body: {error: "Unknown item kind"}};
|
||||
}
|
||||
// what this account takes from the finder, for its favourites.
|
||||
const key = `${body.kind}:${Number(body.id)}`;
|
||||
account.finderGiven[key] = {count: ((account.finderGiven[key] || {}).count || 0) + 1, at: Math.floor(Date.now() / 1000)};
|
||||
const kept = Object.entries(account.finderGiven).sort((one, other) => other[1].at - one[1].at).slice(0, MAX_FAVOURITES);
|
||||
account.finderGiven = Object.fromEntries(kept);
|
||||
accounts.save();
|
||||
return {status: 200, body: {ok: true, online: Boolean(session)}};
|
||||
};
|
||||
|
||||
const FORBIDDEN = {status: 403, body: {error: "forbidden"}};
|
||||
|
||||
// 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.
|
||||
const holderOf = token => {
|
||||
const account = accounts.byToken(token);
|
||||
return account && world.moderation.banRemaining(account) === 0 ? account : null;
|
||||
};
|
||||
|
||||
// `from.local` marks a request made on the server's own machine: the owner,
|
||||
// who may use the finder for any account. everyone else can only give items
|
||||
// to the account whose login token they hold, which is how the in-game
|
||||
// finder calls it.
|
||||
const handle = async (route, params, body, from) => {
|
||||
switch (route) {
|
||||
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)};
|
||||
}
|
||||
case "GET /api/accounts":
|
||||
if (!from.local) {
|
||||
return FORBIDDEN;
|
||||
}
|
||||
return {status: 200, body: accounts.all().map(account => ({username: account.username, online: Boolean(world.findOnline(account.username))}))};
|
||||
case "POST /api/give": {
|
||||
const owner = holderOf((body || {}).token);
|
||||
if (!from.local && (!owner || owner !== accounts.byName((body || {}).username))) {
|
||||
return FORBIDDEN;
|
||||
}
|
||||
if (!from.local && !givesPerMinute.allow(owner.id)) {
|
||||
return {status: 429, body: {error: "Too many at once. Try again in a minute."}};
|
||||
}
|
||||
return give(body || {});
|
||||
}
|
||||
case "POST /api/theme": {
|
||||
const account = accounts.byName((body || {}).username);
|
||||
if (!account || (!from.local && holderOf((body || {}).token) !== account)) {
|
||||
return FORBIDDEN;
|
||||
}
|
||||
return world.setTheme(account, String((body || {}).theme))
|
||||
? {status: 200, body: {ok: true, theme: account.theme}}
|
||||
: {status: 400, body: {error: "Unknown theme"}};
|
||||
}
|
||||
// for the settings menu's Outfits and Den layouts lists (gui.MySettings
|
||||
// in the patched client): the names saved, and a way to run the chat
|
||||
// commands that save, wear and load them.
|
||||
case "GET /api/saved": {
|
||||
const account = accounts.byName(params.get("username"));
|
||||
if (!account || (!from.local && holderOf(params.get("token")) !== account)) {
|
||||
return FORBIDDEN;
|
||||
}
|
||||
return {status: 200, body: {outfits: account.outfits.map(entry => entry.name), layouts: account.denLayouts.map(entry => entry.name)}};
|
||||
}
|
||||
case "POST /api/command": {
|
||||
const account = accounts.byName((body || {}).username);
|
||||
if (!account || (!from.local && holderOf((body || {}).token) !== account)) {
|
||||
return FORBIDDEN;
|
||||
}
|
||||
const text = String((body || {}).text || "");
|
||||
if (!/^!(outfit|den) (wear|load|savenew|off|undo)( [a-z0-9]{1,20})?$/.test(text)) {
|
||||
return {status: 400, body: {error: "Unknown command"}};
|
||||
}
|
||||
return world.runCommand(account, text) ? {status: 200, body: {ok: true}} : {status: 409, body: {error: "Not in the game"}};
|
||||
}
|
||||
// what a client shows beside its login form and in the game's top bar:
|
||||
// how many are playing (the world map says as much), and since when the
|
||||
// server has been up.
|
||||
case "GET /api/status":
|
||||
return {status: 200, body: {online: world.players().length, uptimeSeconds: Math.floor(process.uptime())}};
|
||||
// is the holder of this login token banned, or the address they ask
|
||||
// from? the client asks when its game stops, to say why. the reason is
|
||||
// for the banned player, and the token says that is who asks.
|
||||
case "POST /api/ban": {
|
||||
const account = accounts.byToken((body || {}).token);
|
||||
if (!account) {
|
||||
return FORBIDDEN;
|
||||
}
|
||||
const ban = world.moderation.banOf(account);
|
||||
const addressBan = ban ? null : bans.addressBan(from.address);
|
||||
return {status: 200, body: ban ? {banned: "account", banned_seconds: ban.seconds, ban_reason: ban.reason}
|
||||
: addressBan ? {banned: "address", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason} : {banned: null}};
|
||||
}
|
||||
case "POST /api/register": {
|
||||
if (bans.addressBan(from.address)) {
|
||||
return {status: 403, body: {error: "address_banned"}};
|
||||
}
|
||||
const {username, password, avatarType} = body || {};
|
||||
// the terms and the privacy policy, and old enough to agree to them:
|
||||
// said by the one signing up, on the page or in the client.
|
||||
if ((body || {}).agreed !== true) {
|
||||
return {status: 400, body: {error: "agree_first"}};
|
||||
}
|
||||
const captchaProblem = await captcha.check(body, from, "signup");
|
||||
if (captchaProblem) {
|
||||
return {status: captchaProblem === "captcha_unavailable" ? 503 : 400, body: {error: captchaProblem}};
|
||||
}
|
||||
const problem = accounts.usernameProblem(typeof username === "string" ? username.trim() : username);
|
||||
if (problem) {
|
||||
return {status: 400, body: {error: problem}};
|
||||
}
|
||||
if (!limits.registrationAllowed(from.address, from.local)) {
|
||||
return {status: 429, body: {error: "too_many_registrations"}};
|
||||
}
|
||||
// the animals the sign-up page offers; the game's own Create Account
|
||||
// screens (lib/signup.js) offer theirs.
|
||||
if (!STARTER_ANIMALS.includes(avatarType)) {
|
||||
return {status: 400, body: {error: "choose_animal"}};
|
||||
}
|
||||
const result = accounts.register(username, password, {type: avatarType});
|
||||
if (result.account) {
|
||||
result.account.agreed = {version: config.termsVersion, at: Math.floor(Date.now() / 1000)};
|
||||
accounts.save();
|
||||
}
|
||||
// the client signs in straight after, and is not asked again.
|
||||
return result.error ? {status: 400, body: {error: result.error}}
|
||||
: {status: 200, body: {username: result.account.username, captcha_pass: captcha.issuePass(result.account, from)}};
|
||||
}
|
||||
default:
|
||||
return {status: 404, body: {error: "not_found"}};
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {handle};
|
||||
@@ -0,0 +1,66 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const achievements = require("./achievements.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
|
||||
// the Adopt-A-Pet checklist (client side: AdoptAPetManager, CheckListPopup):
|
||||
// the collectable toy pets a player has "found". the real game handed them
|
||||
// out through codes packed with the toys. here every day's first login finds
|
||||
// one the player does not have yet, and the admin panel can give any.
|
||||
//
|
||||
// account.adoptAPets holds {inv, def, ts, seen}.
|
||||
|
||||
const jamaaDate = () => Math.floor(Date.now() / 86400000);
|
||||
|
||||
// adds one to the account's checklist; null if unknown or already there.
|
||||
// the caller saves.
|
||||
const give = (account, defId) => {
|
||||
if (!defpacks.adoptAPetDef(defId) || account.adoptAPets.some(have => have.def === Number(defId))) {
|
||||
return null;
|
||||
}
|
||||
const found = {inv: account.nextInv++, def: Number(defId), ts: Math.floor(Date.now() / 1000), seen: false};
|
||||
account.adoptAPets.push(found);
|
||||
achievements.set(account, achievements.VARS.adoptAPets, account.adoptAPets.length);
|
||||
return found;
|
||||
};
|
||||
|
||||
// the day's find, at login. the caller saves.
|
||||
const dailyFind = account => {
|
||||
if (account.adoptAPetDay === jamaaDate()) {
|
||||
return null;
|
||||
}
|
||||
account.adoptAPetDay = jamaaDate();
|
||||
const missing = defpacks.adoptAPetIds().filter(id =>
|
||||
defpacks.adoptAPetDef(id).hidden !== "1" && !account.adoptAPets.some(have => have.def === id));
|
||||
return missing.length ? give(account, missing[Math.floor(Math.random() * missing.length)]) : null;
|
||||
};
|
||||
|
||||
// GamePlay.onWorldLogIn -> AdoptAPetData: what the login message lists.
|
||||
const loginList = account => account.adoptAPets.map(found => ({invId: found.inv, defId: found.def, ts: found.ts, hasSeen: found.seen}));
|
||||
|
||||
const handlers = {
|
||||
// CheckListPopup.onOtherUserUsableAdoptAPetData: [success, count, (defId, invId)...]
|
||||
pad(session, roomId, [username]) {
|
||||
const account = accounts.byName(username);
|
||||
const list = account ? account.adoptAPets : [];
|
||||
session.sendXt("pad", -1, account ? 1 : 0, list.length, ...list.flatMap(found => [found.def, found.inv]));
|
||||
},
|
||||
|
||||
// BuddyCard.onAdoptAPetCount: how many that player has (0 hides the button).
|
||||
padc(session, roomId, [username]) {
|
||||
const account = accounts.byName(username);
|
||||
session.sendXt("padc", -1, account ? account.adoptAPets.length : 0);
|
||||
},
|
||||
|
||||
// CheckListPopup: the ones the player has now looked at, [defId, ...].
|
||||
pads(session, roomId, defIds) {
|
||||
const seen = new Set(defIds.map(Number));
|
||||
for (const found of session.account.adoptAPets) {
|
||||
found.seen = found.seen || seen.has(found.def);
|
||||
}
|
||||
accounts.save();
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = {handlers, give, dailyFind, loginList};
|
||||
@@ -0,0 +1,356 @@
|
||||
"use strict";
|
||||
|
||||
// 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
|
||||
// adventure here is a script written by hand from a recording of the
|
||||
// official game (tools/recorder.js): lib/adventures/<name>.js says what to
|
||||
// send when the player triggers an actor, answers one, and so on.
|
||||
//
|
||||
// one player to an adventure, each in rooms of their own.
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const achievements = require("./achievements.js");
|
||||
const config = require("../config.js");
|
||||
const dens = require("./dens.js");
|
||||
const {activeAvatar} = require("./player.js");
|
||||
|
||||
const scripts = new Map([
|
||||
require("./adventures/training-grounds.js"),
|
||||
require("./adventures/return-of-the-phantoms.js"),
|
||||
].map(script => [script.defId, script]));
|
||||
|
||||
const LIST_ADVENTURES = 201; // the adventure list's rows: script def ids
|
||||
const ROOM_TYPE_QUEST = 7;
|
||||
const CURRENCY_GEMS = 0;
|
||||
const MAX_LEVEL = 100;
|
||||
|
||||
const HEARTS = 6; // a player's health, and what a phantom's zap takes of it
|
||||
const ZAP = 2;
|
||||
const GIFT_DEN_ITEM = 1;
|
||||
const GIFT_GEMS = 3;
|
||||
|
||||
// the XP a level starts at. the recordings show three levels: 50 XP to
|
||||
// level 1, 200 more to level 2, and about 450 more to level 3 (5 XP into
|
||||
// level 2 shown as 1%, 55 as 12%). that is 50 times the level squared, and
|
||||
// the levels after are taken to go on so.
|
||||
const levelXp = level => 50 * level * (level + 1) * (2 * level + 1) / 6;
|
||||
const levelFor = xp => {
|
||||
let level = 0;
|
||||
while (level < MAX_LEVEL && xp >= levelXp(level + 1)) {
|
||||
level++;
|
||||
}
|
||||
return level;
|
||||
};
|
||||
const xpOf = avatar => Math.max(avatar.questXp || 0, levelXp(avatar.questLevel || 0));
|
||||
// how far through its level, in percent (QuestManager.handleXpUpdate).
|
||||
const percent = xp => {
|
||||
const level = levelFor(xp);
|
||||
return Math.round((xp - levelXp(level)) * 100 / (levelXp(level + 1) - levelXp(level)));
|
||||
};
|
||||
|
||||
module.exports = ({enterRoom, joinRoom, tell}) => {
|
||||
const playing = session => (session.quest && session.room === session.quest.room ? session.quest : null);
|
||||
|
||||
const tools = (session, quest) => {
|
||||
const q = {
|
||||
me: session.id,
|
||||
vars: quest.vars,
|
||||
send(cmd, ...fields) {
|
||||
if (playing(session) === quest) {
|
||||
session.sendXt(cmd, -1, ...fields);
|
||||
}
|
||||
},
|
||||
after(ms, action) {
|
||||
setTimeout(() => {
|
||||
try {
|
||||
if (playing(session) === quest) {
|
||||
action();
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
console.error(`[adventure] ${quest.script.title}: a timed step failed: ${err.stack}`);
|
||||
}
|
||||
}, ms).unref();
|
||||
},
|
||||
// QuestManager.handleXpUpdate: [earned, total, level before, level
|
||||
// now, percent, the actor the number floats over].
|
||||
xp(amount, actor = "") {
|
||||
const avatar = activeAvatar(session.account);
|
||||
const before = xpOf(avatar);
|
||||
const level = levelFor(before);
|
||||
avatar.questXp = before + amount;
|
||||
avatar.questLevel = levelFor(avatar.questXp);
|
||||
if (amount > 0) {
|
||||
accounts.save();
|
||||
}
|
||||
q.send("quxp", amount, avatar.questXp, level, avatar.questLevel, percent(avatar.questXp), actor);
|
||||
if (avatar.questLevel > level) {
|
||||
// A new level: full health, the animal's numbers, then the level.
|
||||
quest.hearts = HEARTS;
|
||||
q.send("quhp", session.id, 100, HEARTS, HEARTS, HEARTS);
|
||||
q.send("qusu", 10, 200, 1, 200);
|
||||
q.send("qulu", session.id, avatar.questLevel);
|
||||
}
|
||||
},
|
||||
// what the player carries (an actor's name), and using it up:
|
||||
// command 7 takes it out of their hands.
|
||||
held: () => quest.held,
|
||||
use() {
|
||||
quest.held = null;
|
||||
q.send("qcmd", 7);
|
||||
},
|
||||
// goes to another of the adventure's rooms, to stand at `spawn`.
|
||||
room(key, spawn) {
|
||||
const place = quest.script.rooms[key];
|
||||
q.send("qcmd", 14, 0, spawn);
|
||||
const room = enter(session, quest.script, place);
|
||||
if (room) {
|
||||
quest.room = room;
|
||||
q.send("qmusic", place.music);
|
||||
}
|
||||
},
|
||||
// the prizes to choose from at the end: [GIFT_DEN_ITEM, def id, 0]
|
||||
// or [GIFT_GEMS, amount, amount] each (QuestManager.handlePickGift).
|
||||
offer(gifts) {
|
||||
quest.gifts = gifts;
|
||||
q.send("qpgift", gifts.length, 0, ...gifts.flat());
|
||||
},
|
||||
level: () => levelFor(xpOf(activeAvatar(session.account))),
|
||||
gems(amount) {
|
||||
const {account} = session;
|
||||
account.currency.gems = (account.currency.gems || 0) + amount;
|
||||
achievements.currencyChanged(account, "gems", amount);
|
||||
accounts.save();
|
||||
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
|
||||
},
|
||||
};
|
||||
return q;
|
||||
};
|
||||
|
||||
const run = (session, kind, key, ...args) => {
|
||||
const quest = playing(session);
|
||||
if (!quest) {
|
||||
return;
|
||||
}
|
||||
const table = quest.script.on[kind];
|
||||
// A script may answer a whole family of actors: [pattern, handler] in
|
||||
// "<kind>Like", the handler given the actor's name.
|
||||
const family = key === null ? null : (quest.script.on[`${kind}Like`] || []).find(([pattern]) => pattern.test(key));
|
||||
const handler = key === null ? table : (table || {})[key];
|
||||
if (handler) {
|
||||
handler(tools(session, quest), ...args);
|
||||
}
|
||||
else if (family) {
|
||||
family[1](tools(session, quest), key, ...args);
|
||||
}
|
||||
else if (key !== null && kind !== "pickedUp") {
|
||||
console.log(`[adventure] ${quest.script.title}: nothing written for "${kind} ${key}"`);
|
||||
}
|
||||
};
|
||||
|
||||
// QuestXtCommManager.questStartResponse: [script def, players, actor
|
||||
// count, when the script was written, then for each actor its name,
|
||||
// type, def id (a name for type 16), state, visible, needs a click, path,
|
||||
// and the state of its artwork]. the room join follows it.
|
||||
const enter = (session, script, place) => enterRoom(session, `quest_${session.id}_${script.defId}_${Date.now()}__${place.room}`,
|
||||
place.room, place.name, config.shards[0].id, {roomType: ROOM_TYPE_QUEST, secondaryDefId: script.defId, nameStringId: place.nameStringId,
|
||||
joinFlags: [0, 1, 0, 1, 0]}); // a game room, and temporary
|
||||
|
||||
const start = (session, script) => {
|
||||
const returnTo = session.room.name;
|
||||
session.questLobby = null;
|
||||
session.sendXt("qs", session.room.id, script.defId, 1, script.actors.length, script.written, ...script.actors.flat());
|
||||
session.sendXt("qcmd", -1, 38, script.objective);
|
||||
session.sendXt("qmusic", -1, script.rooms.start.music);
|
||||
const room = enter(session, script, script.rooms.start);
|
||||
if (!room) {
|
||||
return;
|
||||
}
|
||||
session.quest = {script, room, returnTo, vars: {}, loaded: false, held: null, hearts: HEARTS, gifts: null, gift: null};
|
||||
tools(session, session.quest).xp(0);
|
||||
};
|
||||
|
||||
const handlers = {
|
||||
// QuestXtCommManager.sendQuestCreateJoinPublic: [room, script def,
|
||||
// difficulty, 0]. A refusal is [0, reason]; "NV" is "Failed to join!".
|
||||
qj(session, roomId, [, defId]) {
|
||||
const script = scripts.get(Number(defId));
|
||||
if (!script || !session.room || playing(session)) {
|
||||
session.sendXt("qj", -1, 0, "NV");
|
||||
if (!script) {
|
||||
tell(session, "That adventure is not on this server yet.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!script.lobby) {
|
||||
start(session, script);
|
||||
return;
|
||||
}
|
||||
// an adventure for several waits for its players: [1, 1, script
|
||||
// def, 0], then who is waiting ("qw"). the player's own Start
|
||||
// button, or the client by itself, then asks to begin ("qs").
|
||||
session.questLobby = script;
|
||||
session.sendXt("qj", session.room.id, 1, 1, script.defId, 0);
|
||||
session.sendXt("qw", session.room.id, session.id);
|
||||
},
|
||||
// QuestXtCommManager.sendQuestStartRequest: [room]
|
||||
qs(session) {
|
||||
if (session.questLobby && session.room && !playing(session)) {
|
||||
start(session, session.questLobby);
|
||||
}
|
||||
},
|
||||
// ... and leaving the wait
|
||||
qjx(session) {
|
||||
session.questLobby = null;
|
||||
session.sendXt("qjx", -1, 1);
|
||||
},
|
||||
// the private lobby asks the same way: [room, script def, difficulty].
|
||||
qjc(session, roomId, params) {
|
||||
handlers.qj(session, roomId, params);
|
||||
},
|
||||
|
||||
// "What was moved?", once the room is up: nothing is answered, and it
|
||||
// is where a script begins.
|
||||
qmi(session) {
|
||||
const quest = playing(session);
|
||||
if (quest && !quest.loaded) {
|
||||
quest.loaded = true;
|
||||
run(session, "loaded", null);
|
||||
}
|
||||
},
|
||||
|
||||
// [actor, 0]: walked into, or clicked
|
||||
qat(session, roomId, [actor]) {
|
||||
run(session, "trigger", String(actor));
|
||||
},
|
||||
// [actor, ?, answer]: a talk read to its end
|
||||
qaskr(session, roomId, [actor]) {
|
||||
run(session, "answer", String(actor));
|
||||
},
|
||||
// [actor, state]: an actor's own change of mind (a phantom noticing the
|
||||
// player, giving up), which the server only passes round:
|
||||
// QuestManager.handleQuestActorRequestSeekResponse [actor, state, who].
|
||||
qas(session, roomId, [actor, state]) {
|
||||
if (playing(session) && /^-?\d+$/.test(state)) {
|
||||
session.sendXt("qas", -1, String(actor), Number(state), session.id);
|
||||
}
|
||||
},
|
||||
// QuestXtCommManager.questPickUpItem: [actor, who]. answered [1, actor,
|
||||
// who] (QuestManager.handlePickUpItem); with something in hand already
|
||||
// it is [0, actor], which has the client ask whether to drop that.
|
||||
qpup(session, roomId, [actor]) {
|
||||
const quest = playing(session);
|
||||
const name = String(actor);
|
||||
if (!quest || !quest.script.actors.some(row => row[0] === name)) {
|
||||
return;
|
||||
}
|
||||
const refill = quest.script.refills;
|
||||
if (quest.held && !(refill && refill.test(quest.held) && refill.test(name))) {
|
||||
session.sendXt("qpup", -1, 0, name, "null");
|
||||
return;
|
||||
}
|
||||
quest.held = name;
|
||||
session.sendXt("qpup", -1, 1, name, session.id);
|
||||
run(session, "pickedUp", name);
|
||||
},
|
||||
// "Yes, drop it": [x, y, the actor wanted, who]. what was held is put
|
||||
// down there ([4, actor, who, x, y, 0, 150, who, the one wanted]) and
|
||||
// the other picked up.
|
||||
qdroppup(session, roomId, [x, y, actor]) {
|
||||
const quest = playing(session);
|
||||
const name = String(actor);
|
||||
if (!quest || !quest.held || ![x, y].every(value => /^-?\d+$/.test(value)) || !quest.script.actors.some(row => row[0] === name)) {
|
||||
return;
|
||||
}
|
||||
session.sendXt("qpup", -1, 4, quest.held, session.id, Number(x), Number(y), 0, 150, session.id, name);
|
||||
quest.held = name;
|
||||
session.sendXt("qpup", -1, 1, name, session.id);
|
||||
run(session, "pickedUp", name);
|
||||
},
|
||||
|
||||
// A phantom has zapped the player: [phantom, who, x, y], which goes
|
||||
// back after the player's health, [who, percent, change, hearts, of]
|
||||
// (QuestManager.handleHealthUpdate). at none the player is down ("qpd").
|
||||
qpzap(session, roomId, [phantom, , x, y]) {
|
||||
const quest = playing(session);
|
||||
if (!quest || quest.hearts <= 0 || ![x, y].every(value => /^-?\d+$/.test(value))) {
|
||||
return;
|
||||
}
|
||||
quest.hearts = Math.max(0, quest.hearts - ZAP);
|
||||
session.sendXt("quhp", -1, session.id, Math.floor(quest.hearts * 100 / HEARTS), -ZAP, quest.hearts, HEARTS);
|
||||
if (quest.hearts === 0) {
|
||||
session.sendXt("qpd", -1, session.id);
|
||||
}
|
||||
session.sendXt("qpzap", -1, String(phantom), session.id, Number(x), Number(y));
|
||||
},
|
||||
// ... and asks to get up again: [0, x, y], a place of the client's
|
||||
// choosing. [who, percent, hearts three times, x, y], then "qprr" 6.
|
||||
qprr(session, roomId, [, x, y]) {
|
||||
const quest = playing(session);
|
||||
if (!quest || quest.hearts > 0 || ![x, y].every(value => /^-?\d+$/.test(value))) {
|
||||
return;
|
||||
}
|
||||
quest.hearts = HEARTS;
|
||||
session.sendXt("qrspn", -1, session.id, 100, HEARTS, HEARTS, HEARTS, Number(x), Number(y));
|
||||
session.sendXt("qprr", -1, HEARTS);
|
||||
},
|
||||
|
||||
// the prize picked from those offered: [which, ?, ?], then "done".
|
||||
qpgift(session, roomId, [index]) {
|
||||
const quest = playing(session);
|
||||
if (quest && quest.gifts && quest.gift === null && /^\d+$/.test(index) && Number(index) < quest.gifts.length) {
|
||||
quest.gift = quest.gifts[Number(index)];
|
||||
}
|
||||
},
|
||||
qpgiftdone(session) {
|
||||
const quest = playing(session);
|
||||
if (!quest || !quest.gift) {
|
||||
return;
|
||||
}
|
||||
const [kind, value] = quest.gift;
|
||||
quest.gifts = quest.gift = null;
|
||||
if (kind === GIFT_DEN_ITEM) {
|
||||
dens.giveDenItem(session.account, value);
|
||||
dens.sendDenItems(session);
|
||||
}
|
||||
else if (kind === GIFT_GEMS) {
|
||||
tools(session, quest).gems(value);
|
||||
}
|
||||
run(session, "gifted", null);
|
||||
},
|
||||
|
||||
// [plant, phantom]: a chomper plant has caught one. nothing comes back.
|
||||
qpa() {},
|
||||
// [plant, phantom, x, y]: ... and eaten it
|
||||
qep(session, roomId, [plant, phantom, x, y]) {
|
||||
if (playing(session) && [x, y].every(value => /^-?\d+$/.test(value))) {
|
||||
run(session, "eaten", null, String(plant), String(phantom), Number(x), Number(y));
|
||||
}
|
||||
},
|
||||
// [actor, 0] is answered by the script when the chest is triggered
|
||||
// ("qat"); [actor, 1] is the chest opened.
|
||||
qatt(session, roomId, [actor, opened]) {
|
||||
if (opened === "1") {
|
||||
run(session, "opened", String(actor));
|
||||
}
|
||||
},
|
||||
|
||||
// QuestXtCommManager.sendQuestExit. the official game goes to the
|
||||
// Adventure Base Camp; here it is back to where the player came from.
|
||||
qx(session) {
|
||||
const quest = playing(session);
|
||||
if (quest) {
|
||||
session.quest = null;
|
||||
joinRoom(session, quest.returnTo);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
handlers,
|
||||
list: listId => (Number(listId) === LIST_ADVENTURES ? [...scripts.keys()] : null),
|
||||
};
|
||||
};
|
||||
|
||||
Object.assign(module.exports, {levelXp, MAX_LEVEL});
|
||||
@@ -0,0 +1,688 @@
|
||||
"use strict";
|
||||
|
||||
// return of the Phantoms (script def 14), normal mode, written from a
|
||||
// recording of the official game of 2026-10-12: one player, who plugged
|
||||
// the four pipes, watered the eight plants, fetched the key from the
|
||||
// burrow, freed the four bunnies and took a prize; was zapped down once,
|
||||
// fed four phantoms to the plants and opened two chests. what was sent
|
||||
// there is sent here. marked "guessed" below is what that run did not do.
|
||||
//
|
||||
// commands ("qcmd"): 1 sets an actor's [state, visible, needs a click],
|
||||
// and state 99 takes it out of the adventure (all that belongs to hard
|
||||
// mode goes that way at the start); 2 has an actor say a string; 3 has it
|
||||
// talk and wait for an answer; 7 takes what the player carries; 14 puts
|
||||
// the player at a spawn point; 38 is the line under the top of the
|
||||
// screen; 19 ends the adventure. "qcmdVT" sets a counter or a timer,
|
||||
// "qsp" a phantom's path.
|
||||
|
||||
// kinds of prize (QuestManager.handlePickGift).
|
||||
const GIFT_DEN_ITEM = 1;
|
||||
const GIFT_GEMS = 3;
|
||||
|
||||
const set = (q, name, state, visible, click) => q.send("qcmd", 1, name, state, visible, click);
|
||||
const counter = (q, name, value) => q.send("qcmdVT", 1, name, value, 0, 0);
|
||||
const say = (q, name, text) => q.send("qcmd", 2, name, text, 1);
|
||||
const goal = (q, text) => q.send("qcmd", 38, text);
|
||||
// the official game counts its page views this way; the client is told.
|
||||
const page = (q, flag, name) => {
|
||||
counter(q, flag, 1);
|
||||
q.send("qposturi", `/adventure1-returnofthephantoms/#${name}/#0#001`);
|
||||
counter(q, flag, 99);
|
||||
};
|
||||
const lizaAppears = (q, name) => {
|
||||
q.send("qswfs", name, "facesw");
|
||||
q.send("qswfs", name, "appear");
|
||||
set(q, name, 1, 1, 1);
|
||||
};
|
||||
const phantoms = (q, list) => {
|
||||
for (const [name, path] of list) {
|
||||
if (path) {
|
||||
q.send("qsp", name, path);
|
||||
}
|
||||
set(q, name, 1, 1, 1);
|
||||
}
|
||||
};
|
||||
const pick = letters => letters[Math.floor(Math.random() * letters.length)];
|
||||
|
||||
const NORMAL_FLOWERS = [1, 2, 3, 4, 9, 10, 11, 12];
|
||||
const flowerTrigger = number => (number < 10 ? `flowertrig_${number}` : `flowertrig${number}`);
|
||||
// everything of hard mode, taken out when a normal adventure begins.
|
||||
const HARD_ONLY = ["hard", "phan_door_h", "phan_block_h", "phan_trig_h", "blocker_e", "pipe_5", "pipe_6", "sludge_5", "sludge_6",
|
||||
"flowers_5", "flowers_6", "flowers_7", "flowers_8", "well_1h", "checkpoint2", "spawn_2"];
|
||||
const PIPE_GOALS = {5: 3546, 6: 3547}; // "Find 2 more CORKS...", "Find the last CORK..."
|
||||
// chests the recording opened; the others are guessed at 50.
|
||||
const CHEST_GEMS = {treasure_3: 100, treasure_4: 50};
|
||||
const GUESSED_CHEST_GEMS = 50;
|
||||
const PRIZES = [[GIFT_DEN_ITEM, 1288, 0], [GIFT_DEN_ITEM, 1289, 0], [GIFT_DEN_ITEM, 1290, 0], [GIFT_GEMS, 500, 500], [GIFT_DEN_ITEM, 1291, 0]];
|
||||
|
||||
const pipePlugged = (q, pipe) => {
|
||||
const number = pipe.slice("pipetrig_".length);
|
||||
// guessed: without a cork in hand the pipe says a cork fits in it.
|
||||
if (!/^cork_/.test(q.held() || "")) {
|
||||
say(q, pipe, 3468);
|
||||
return;
|
||||
}
|
||||
if (q.vars.plugged.has(pipe)) {
|
||||
return;
|
||||
}
|
||||
q.vars.plugged.add(pipe);
|
||||
q.use();
|
||||
set(q, `pipe_${number}`, 1, 1, 0);
|
||||
set(q, `sludge_${number}`, 1, 0, 0);
|
||||
set(q, pipe, 2, 0, 0);
|
||||
if (q.vars.plugged.size === 1) {
|
||||
// the first, with the bunny's cork: phantoms come, and the other three
|
||||
// pipes can be plugged.
|
||||
counter(q, "watervar", 1);
|
||||
phantoms(q, [["phantom_2", "path_2"], ["phantom_3", "path_3"], ["phantom_4", null]]);
|
||||
q.xp(5, pipe);
|
||||
q.after(650, () => {
|
||||
set(q, "bunny_2", 1, 1, 1);
|
||||
say(q, "bunny_2", 3467);
|
||||
set(q, "bunny_2", 2, 1, 0);
|
||||
counter(q, "watervar", 4);
|
||||
goal(q, 3472);
|
||||
for (const other of ["pipetrig_2", "pipetrig_3", "pipetrig_4"]) {
|
||||
set(q, other, 1, 1, 1);
|
||||
}
|
||||
q.after(2000, () => {
|
||||
set(q, "vineblock_2", 1, 0, 0);
|
||||
set(q, "vine_2", 1, 1, 0);
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
const water = 3 + q.vars.plugged.size; // 5, 6, then 7 for the last
|
||||
counter(q, "watervar", water);
|
||||
if (water < 7) {
|
||||
goal(q, PIPE_GOALS[water]);
|
||||
q.xp(5, pipe);
|
||||
return;
|
||||
}
|
||||
// the water runs clean: pails at the well, and eight plants to revive.
|
||||
set(q, "sludgewall", 1, 0, 0);
|
||||
set(q, "waterfall", 1, 1, 0);
|
||||
set(q, "water_1", 0, 1, 0);
|
||||
set(q, "well_1", 0, 1, 0);
|
||||
set(q, "pail_1", 1, 1, 0);
|
||||
set(q, "pail_2", 1, 1, 0);
|
||||
goal(q, 14989);
|
||||
counter(q, "flower_count", 4);
|
||||
goal(q, 3478);
|
||||
set(q, "watervol_1", 1, 0, 0);
|
||||
for (const number of NORMAL_FLOWERS) {
|
||||
set(q, flowerTrigger(number), 1, 1, 1);
|
||||
}
|
||||
set(q, "bunny_2", 3, 1, 1);
|
||||
set(q, "bunny_1", 2, 1, 1);
|
||||
q.xp(15, "waterdone");
|
||||
page(q, "10_uri", "10-plugthepipes");
|
||||
q.xp(5, pipe);
|
||||
q.after(2560, () => q.send("qsnd", "ajq_riverclear"));
|
||||
};
|
||||
|
||||
const flowerWatered = (q, trigger) => {
|
||||
const number = trigger.replace(/\D/g, "");
|
||||
if (!/^pail_/.test(q.held() || "") || q.vars.watered.has(trigger)) {
|
||||
return;
|
||||
}
|
||||
q.vars.watered.add(trigger);
|
||||
q.use();
|
||||
set(q, `flowers_${number}`, 0, 1, 0);
|
||||
set(q, trigger, 2, 0, 0);
|
||||
const count = 4 + q.vars.watered.size; // the counter starts at 4 and ends at 12
|
||||
counter(q, "flower_count", count);
|
||||
goal(q, 3474 + count); // 3479 "... 7 more PLANTS" to 3486
|
||||
if (count === 12) {
|
||||
// the burrow opens.
|
||||
set(q, "trig_1a", 1, 1, 1);
|
||||
set(q, "nobody_home", 1, 0, 0);
|
||||
set(q, "bunnyblocker", 1, 0, 0);
|
||||
set(q, "burrow_door", 1, 1, 0);
|
||||
for (const pail of ["pail_1", "pail_2", "pail_3"]) {
|
||||
set(q, pail, 2, 0, 0);
|
||||
}
|
||||
q.xp(15, "flower_count");
|
||||
set(q, "bunny_12", 1, 1, 0);
|
||||
page(q, "20_uri", "20-revivetheplants");
|
||||
}
|
||||
q.xp(5, trigger);
|
||||
};
|
||||
|
||||
const bunnyFreed = (q, bunny) => {
|
||||
const number = Number(bunny.slice("bunny_".length));
|
||||
if (!/^bunny_key_/.test(q.held() || "") || q.vars.freed.has(bunny)) {
|
||||
return;
|
||||
}
|
||||
q.vars.freed.add(bunny);
|
||||
q.use();
|
||||
q.xp(10, bunny);
|
||||
set(q, `cage${number}_f`, 1, 1, 0);
|
||||
set(q, `cage${number}_b`, 1, 1, 0);
|
||||
q.send("qswfs", bunny, "dance");
|
||||
set(q, bunny, 1, 1, 0);
|
||||
const count = q.vars.freed.size;
|
||||
counter(q, "trap_count", count);
|
||||
goal(q, 3572 + count); // "Find 3 KEYS..." down to "Adventure COMPLETE!"
|
||||
if (count === 4) {
|
||||
q.xp(25, "trap_count");
|
||||
lizaAppears(q, "liza_2");
|
||||
page(q, "30_uri", "30-rescuethebunnies");
|
||||
}
|
||||
say(q, bunny, 3561 + number); // bunny_7 says 3568, ... bunny_10 3571
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
defId: 14,
|
||||
title: "Return of the Phantoms",
|
||||
lobby: true,
|
||||
rooms: {
|
||||
start: {room: "adventures.room_adventure_1x", name: "On An Adventure", nameStringId: 18324, music: "ajq_musquest"},
|
||||
burrow: {room: "adventures.room_adventure_1a", name: "On an Adventure", nameStringId: 18324, music: "ajq_musbunnyburrow"},
|
||||
},
|
||||
written: "2017-10-30 22:02:01",
|
||||
objective: 3465, // "TALK to Liza."
|
||||
refills: /^pail_/, // a pail in hand is filled again at the well
|
||||
|
||||
// name, type, def, state, visible, needs a click, path, artwork state
|
||||
actors: [
|
||||
["queststart", 18, 0, 0, 1, 1, "", ""],
|
||||
["questready", 7, 0, 0, 1, 1, "", ""],
|
||||
["checkpoint2", 27, 0, 0, 1, 1, "", ""],
|
||||
["checkpoint4", 27, 0, 0, 1, 1, "", ""],
|
||||
["start_init", 8, 0, 0, 0, 1, "", ""],
|
||||
["water_time", 8, 0, 0, 0, 1, "", ""],
|
||||
["bunnytimer_1", 8, 0, 0, 0, 1, "", ""],
|
||||
["bunnytimer_2", 8, 0, 0, 0, 1, "", ""],
|
||||
["bunnytimer_3", 8, 0, 0, 0, 1, "", ""],
|
||||
["bunnytimer_4", 8, 0, 0, 0, 1, "", ""],
|
||||
["blocktimer_1", 8, 0, 0, 0, 1, "", ""],
|
||||
["phan_timer_1", 8, 0, 0, 0, 1, "", ""],
|
||||
["gifttimer", 8, 0, 0, 0, 1, "", ""],
|
||||
["players", 7, 0, 0, 1, 1, "", ""],
|
||||
["waterdone", 7, 0, 0, 1, 1, "", ""],
|
||||
["watervar", 7, 0, 0, 0, 1, "", ""],
|
||||
["flower_count", 7, 0, 0, 0, 1, "", ""],
|
||||
["trap_count", 7, 0, 0, 0, 1, "", ""],
|
||||
["spawn_1_a", 9, 1, 0, 1, 1, "", ""],
|
||||
["trig_1_a", 3, 0, 0, 1, 1, "", ""],
|
||||
["spawn_1a", 9, 0, 0, 1, 1, "", ""],
|
||||
["trig_1a", 3, 0, 0, 0, 1, "", ""],
|
||||
["spawn_1_b", 9, 2, 0, 1, 1, "", ""],
|
||||
["trig_1_b", 3, 0, 0, 1, 1, "", ""],
|
||||
["spawn_1b", 9, 0, 0, 1, 1, "", ""],
|
||||
["trig_1b", 3, 0, 0, 1, 1, "", ""],
|
||||
["liza_1", 1, 21, 0, 0, 1, "", ""],
|
||||
["liza_2", 1, 21, 0, 0, 1, "", ""],
|
||||
["bunny_1", 1, 88, 0, 1, 1, "", "facesw"],
|
||||
["bunny_2", 1, 89, 0, 1, 1, "", ""],
|
||||
["bunny_3", 1, 90, 0, 1, 1, "", "facesw"],
|
||||
["bunnytrig_3", 3, 0, 0, 1, 1, "", ""],
|
||||
["bunny_4", 1, 91, 0, 1, 1, "", "facesw"],
|
||||
["bunny_5", 1, 92, 0, 1, 1, "", ""],
|
||||
["bunny_6", 1, 93, 0, 1, 1, "", ""],
|
||||
["bunny_7", 1, 94, 0, 1, 1, "", ""],
|
||||
["bunny_8", 1, 95, 0, 1, 1, "", ""],
|
||||
["bunny_9", 1, 96, 0, 1, 1, "", "facesw"],
|
||||
["bunny_10", 1, 97, 0, 1, 1, "", "facesw"],
|
||||
["bunny_11", 1, 98, 0, 1, 1, "", ""],
|
||||
["bunny_12", 1, 101, 0, 1, 1, "", "facesw"],
|
||||
["nobody_home", 1, 44, 0, 1, 1, "", ""],
|
||||
["pipeinfo_1", 1, 116, 0, 0, 1, "", ""],
|
||||
["pipeinfo_2", 1, 116, 0, 0, 1, "", ""],
|
||||
["pipeinfo_3", 1, 116, 0, 0, 1, "", ""],
|
||||
["pipeinfo_4", 1, 116, 0, 0, 1, "", ""],
|
||||
["pipeinfo_5", 1, 116, 0, 0, 1, "", ""],
|
||||
["pipeinfo_6", 1, 116, 0, 0, 1, "", ""],
|
||||
["pipetrig_1", 1, 69, 0, 0, 1, "", ""],
|
||||
["pipetrig_2", 1, 69, 0, 0, 1, "", ""],
|
||||
["pipetrig_3", 1, 69, 0, 0, 1, "", ""],
|
||||
["pipetrig_4", 1, 69, 0, 0, 1, "", ""],
|
||||
["pipetrig_5", 1, 69, 0, 0, 1, "", ""],
|
||||
["pipetrig_6", 1, 69, 0, 0, 1, "", ""],
|
||||
["flowerinfo_1", 1, 116, 0, 0, 1, "", ""],
|
||||
["flowerinfo_2", 1, 116, 0, 0, 1, "", ""],
|
||||
["flowerinfo_3", 1, 116, 0, 0, 1, "", ""],
|
||||
["flowerinfo_4", 1, 116, 0, 0, 1, "", ""],
|
||||
["flowerinfo_5", 1, 116, 0, 0, 1, "", ""],
|
||||
["flowerinfo_6", 1, 116, 0, 0, 1, "", ""],
|
||||
["flowerinfo_7", 1, 116, 0, 0, 1, "", ""],
|
||||
["flowerinfo_8", 1, 116, 0, 0, 1, "", ""],
|
||||
["flowerinfo_9", 1, 116, 0, 0, 1, "", ""],
|
||||
["flowerinfo10", 1, 116, 0, 0, 1, "", ""],
|
||||
["flowerinfo11", 1, 116, 0, 0, 1, "", ""],
|
||||
["flowerinfo12", 1, 116, 0, 0, 1, "", ""],
|
||||
["flowertrig_1", 1, 67, 0, 0, 1, "", ""],
|
||||
["flowertrig_2", 1, 67, 0, 0, 1, "", ""],
|
||||
["flowertrig_3", 1, 67, 0, 0, 1, "", ""],
|
||||
["flowertrig_4", 1, 67, 0, 0, 1, "", ""],
|
||||
["flowertrig_5", 1, 67, 0, 0, 1, "", ""],
|
||||
["flowertrig_6", 1, 67, 0, 0, 1, "", ""],
|
||||
["flowertrig_7", 1, 67, 0, 0, 1, "", ""],
|
||||
["flowertrig_8", 1, 67, 0, 0, 1, "", ""],
|
||||
["flowertrig_9", 1, 67, 0, 0, 1, "", ""],
|
||||
["flowertrig10", 1, 67, 0, 0, 1, "", ""],
|
||||
["flowertrig11", 1, 67, 0, 0, 1, "", ""],
|
||||
["flowertrig12", 1, 67, 0, 0, 1, "", ""],
|
||||
["plant_1", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_2", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_3", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_4", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_5", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_6", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_7", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_8", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_9", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_10", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_11", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_12", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_13", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_14", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_15", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_16", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_17", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_18", 21, 100, 0, 1, 1, "", ""],
|
||||
["path_1", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_2", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_2_h", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_3", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_3_h", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_5", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_5_h", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_6", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_7", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_8a", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_8b", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_9", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_9_h", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_11", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_11_h", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_12", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_12_h", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_13_h", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_14_h", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_15_h", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_17_h", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_18_h", 20, 0, 0, 0, 1, "", ""],
|
||||
["path_19_h", 20, 0, 0, 0, 1, "", ""],
|
||||
["pail_1", 17, 1955, 0, 0, 1, "", ""],
|
||||
["pail_2", 17, 1955, 0, 0, 1, "", ""],
|
||||
["pail_3", 17, 1955, 0, 0, 1, "", ""],
|
||||
["cork_1", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_2a", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_2a_h", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_2b", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_2b_h", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_2c", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_2c_h", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_3a", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_3a_h", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_3b", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_3b_h", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_3c", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_3c_h", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_4a", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_4a_h", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_4b", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_4b_h", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_4c", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_4c_h", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_5a_h", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_5b_h", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_5c_h", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_6a_h", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_6b_h", 15, 1937, 0, 0, 1, "", ""],
|
||||
["cork_6c_h", 15, 1937, 0, 0, 1, "", ""],
|
||||
["spawn_1", 16, "ajq_spawnpointlp", 0, 1, 1, "", ""],
|
||||
["spawn_2", 16, "ajq_spawnpointlp", 0, 1, 1, "", ""],
|
||||
["spawn_3", 16, "ajq_spawnpointlp", 0, 1, 1, "", ""],
|
||||
["spawn_4", 16, "ajq_spawnpointlp", 0, 1, 1, "", ""],
|
||||
["waterfall", 16, "ajq_waterfall_lp", 0, 0, 1, "", ""],
|
||||
["sludgewall", 16, "ajq_sludge_lp", 0, 1, 1, "", ""],
|
||||
["sludge_1", 16, "ajq_sludge_lp", 0, 1, 1, "", ""],
|
||||
["sludge_2", 16, "ajq_sludge_lp", 0, 1, 1, "", ""],
|
||||
["sludge_3", 16, "ajq_sludge_lp", 0, 1, 1, "", ""],
|
||||
["sludge_4", 16, "ajq_sludge_lp", 0, 1, 1, "", ""],
|
||||
["sludge_5", 16, "ajq_sludge_lp", 0, 1, 1, "", ""],
|
||||
["sludge_6", 16, "ajq_sludge_lp", 0, 1, 1, "", ""],
|
||||
["portal", 16, "ajq_portalgatelp", 0, 0, 1, "", ""],
|
||||
["diffvol_1", 5, 0, 0, 1, 1, "", ""],
|
||||
["diffvol_2", 5, 0, 0, 1, 1, "", ""],
|
||||
["diffvol_3", 5, 0, 0, 1, 1, "", ""],
|
||||
["bunnyblocker", 5, 0, 0, 1, 1, "", ""],
|
||||
["phan_block_e", 5, 0, 0, 1, 1, "", ""],
|
||||
["phan_block_h", 5, 0, 0, 1, 1, "", ""],
|
||||
["watervol_1", 5, 0, 0, 1, 1, "", ""],
|
||||
["vineblock_1", 5, 0, 0, 1, 1, "", ""],
|
||||
["vineblock_2", 5, 0, 0, 1, 1, "", ""],
|
||||
["blocker_h", 5, 0, 0, 1, 1, "", ""],
|
||||
["blocker_e", 5, 0, 0, 1, 1, "", ""],
|
||||
["exit_block", 5, 0, 0, 1, 1, "", ""],
|
||||
["bunnyvol_1", 5, 0, 0, 1, 1, "", ""],
|
||||
["bunnytrig_1", 1, 45, 0, 1, 1, "", ""],
|
||||
["cheatchq", 3, 0, 0, 1, 1, "", ""],
|
||||
["phan_trig_e", 1, 44, 0, 1, 1, "", ""],
|
||||
["phan_trig_h", 1, 44, 0, 1, 1, "", ""],
|
||||
["phan_key_1", 15, 1912, 0, 0, 1, "", ""],
|
||||
["cage10_f", 2, 0, 0, 1, 1, "", ""],
|
||||
["cage10_b", 2, 0, 0, 1, 1, "", ""],
|
||||
["cage9_f", 2, 0, 0, 1, 1, "", ""],
|
||||
["cage9_b", 2, 0, 0, 1, 1, "", ""],
|
||||
["cage8_f", 2, 0, 0, 1, 1, "", ""],
|
||||
["cage8_b", 2, 0, 0, 1, 1, "", ""],
|
||||
["cage7_f", 2, 0, 0, 1, 1, "", ""],
|
||||
["cage7_b", 2, 0, 0, 1, 1, "", ""],
|
||||
["burrow_door", 2, 0, 0, 1, 1, "", ""],
|
||||
["bunnytile_1", 2, 0, 0, 1, 1, "", ""],
|
||||
["bunnyblock_1", 2, 0, 0, 1, 1, "", ""],
|
||||
["phan_door_e", 2, 0, 0, 1, 1, "", ""],
|
||||
["phan_door_h", 2, 0, 0, 1, 1, "", ""],
|
||||
["vine_1", 2, 0, 0, 1, 1, "", ""],
|
||||
["vine_2", 2, 0, 0, 1, 1, "", ""],
|
||||
["well_1", 2, 0, 0, 1, 1, "", ""],
|
||||
["well_1h", 2, 0, 0, 1, 1, "", ""],
|
||||
["water_1", 2, 0, 0, 1, 1, "", ""],
|
||||
["easy", 2, 0, 0, 1, 1, "", ""],
|
||||
["hard", 2, 0, 0, 1, 1, "", ""],
|
||||
["pipe_1", 2, 0, 0, 1, 1, "", ""],
|
||||
["pipe_2", 2, 0, 0, 1, 1, "", ""],
|
||||
["pipe_3", 2, 0, 0, 1, 1, "", ""],
|
||||
["pipe_4", 2, 0, 0, 1, 1, "", ""],
|
||||
["pipe_5", 2, 0, 0, 1, 1, "", ""],
|
||||
["pipe_6", 2, 0, 0, 1, 1, "", ""],
|
||||
["flowers_1", 2, 0, 0, 1, 1, "", ""],
|
||||
["flowers_2", 2, 0, 0, 1, 1, "", ""],
|
||||
["flowers_3", 2, 0, 0, 1, 1, "", ""],
|
||||
["flowers_4", 2, 0, 0, 1, 1, "", ""],
|
||||
["flowers_5", 2, 0, 0, 1, 1, "", ""],
|
||||
["flowers_6", 2, 0, 0, 1, 1, "", ""],
|
||||
["flowers_7", 2, 0, 0, 1, 1, "", ""],
|
||||
["flowers_8", 2, 0, 0, 1, 1, "", ""],
|
||||
["flowers_9", 2, 0, 0, 1, 1, "", ""],
|
||||
["flowers_10", 2, 0, 0, 1, 1, "", ""],
|
||||
["flowers_11", 2, 0, 0, 1, 1, "", ""],
|
||||
["flowers_12", 2, 0, 0, 1, 1, "", ""],
|
||||
["exit_port", 2, 0, 0, 1, 1, "", ""],
|
||||
["phantom_1", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_2", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_2_h", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_3", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_3_h", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_4", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_5__a", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_5__b", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_5__c", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_5_h", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_6", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_7", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_8__a", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_8__b", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_9", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_9a_h", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_9b_h", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_9c_h", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_10", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_11", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_11_h", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_12", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_12_h", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_13", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_13_h", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_14", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_14_h", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_15", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_15_h", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_16_h", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_17_h", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_18_h", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantom_19_h", 11, 2, 0, 0, 1, "", ""],
|
||||
["phantoff1", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff2", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff2h", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff3", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff3h", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff4", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff5a", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff5b", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff5c", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff5h", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff6", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff7", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff8a", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff8b", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff9", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff9a", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff9b", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff9c", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff10", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff11", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff11h", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff12", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff12h", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff13", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff13h", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff14", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff14h", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff15", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff15h", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff16h", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff17h", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff18h", 8, 0, 0, 0, 1, "", ""],
|
||||
["phantoff19h", 8, 0, 0, 0, 1, "", ""],
|
||||
["treasure_1", 13, 39, 0, 1, 1, "", ""],
|
||||
["treasure_2", 13, 39, 0, 1, 1, "", ""],
|
||||
["treasure_3", 13, 39, 0, 1, 1, "", ""],
|
||||
["treasure_4", 13, 39, 0, 1, 1, "", ""],
|
||||
["treasure_5", 13, 39, 0, 1, 1, "", ""],
|
||||
["treasure_6", 13, 39, 0, 1, 1, "", ""],
|
||||
["treasure_7", 13, 39, 0, 1, 1, "", ""],
|
||||
["bunny_key_1a", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_1b", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_1c", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_1d", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_1e", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_1f", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_2a", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_2b", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_2c", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_2d", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_2e", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_2f", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_3a", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_3b", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_3c", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_3d", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_3e", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_3f", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_4a", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_4b", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_4c", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_4d", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_4e", 15, 1912, 0, 0, 1, "", ""],
|
||||
["bunny_key_4f", 15, 1912, 0, 0, 1, "", ""],
|
||||
["exit_vol", 3, 0, 0, 1, 1, "", ""],
|
||||
["secret_1", 3, 0, 0, 1, 1, "", ""],
|
||||
["secret_2", 3, 0, 0, 1, 1, "", ""],
|
||||
["00_uri", 7, 0, 0, 0, 1, "", ""],
|
||||
["10_uri", 7, 0, 0, 0, 1, "", ""],
|
||||
["20_uri", 7, 0, 0, 0, 1, "", ""],
|
||||
["30_uri", 7, 0, 0, 0, 1, "", ""],
|
||||
["40_uri", 7, 0, 0, 0, 1, "", ""],
|
||||
["diff_level", 7, 0, 0, 1, 1, "", ""],
|
||||
["live_players", 7, 0, 1, 0, 1, "", ""],
|
||||
["playermember", 7, 0, 0, 1, 1, "", ""], ],
|
||||
|
||||
on: {
|
||||
trigger: {
|
||||
// sent by the client each time one of the rooms is up.
|
||||
questready(q) {
|
||||
if (q.vars.begun) {
|
||||
return;
|
||||
}
|
||||
Object.assign(q.vars, {begun: true, plugged: new Set(), watered: new Set(), freed: new Set(), eaten: new Set(), opened: new Set()});
|
||||
counter(q, "start_init", 1);
|
||||
q.after(270, () => {
|
||||
lizaAppears(q, "liza_1");
|
||||
set(q, "well_1", 1, 1, 0);
|
||||
set(q, "water_1", 1, 1, 0);
|
||||
for (const number of NORMAL_FLOWERS) {
|
||||
set(q, `flowers_${number}`, 1, 1, 0);
|
||||
}
|
||||
for (const name of HARD_ONLY) {
|
||||
set(q, name, 99, 0, 0);
|
||||
}
|
||||
// each cork and key has several places it may lie in; the
|
||||
// recording had corks 2a, 3a, 4a and keys 1c to 4c. guessed:
|
||||
// that the place is drawn by lot.
|
||||
for (const number of [2, 3, 4]) {
|
||||
set(q, `cork_${number}${pick("abc")}`, 1, 1, 0);
|
||||
}
|
||||
for (const number of [1, 2, 3, 4]) {
|
||||
set(q, `bunny_key_${number}${pick("abcdef")}`, 1, 1, 0);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
liza_1: q => q.send("qcmd", 3, 0, "liza_1", 1, 3461),
|
||||
liza_2: q => q.send("qcmd", 3, 0, "liza_2", 1, 3495),
|
||||
bunny_1: q => say(q, "bunny_1", 3462),
|
||||
bunny_2(q) {
|
||||
if (q.vars.corkGiven) {
|
||||
return;
|
||||
}
|
||||
q.vars.corkGiven = true;
|
||||
say(q, "bunny_2", 3463);
|
||||
set(q, "bunny_2", 2, 1, 0);
|
||||
set(q, "cork_1", 1, 1, 0);
|
||||
q.after(47, () => set(q, "pipetrig_1", 1, 1, 1));
|
||||
},
|
||||
bunnytrig_3: q => say(q, "bunny_3", 3469),
|
||||
bunny_6(q) {
|
||||
say(q, "bunny_6", 3488);
|
||||
set(q, "bunny_6", 1, 1, 0);
|
||||
if (!q.vars.keyShown) {
|
||||
q.vars.keyShown = true;
|
||||
set(q, "phan_key_1", 1, 1, 0);
|
||||
}
|
||||
},
|
||||
|
||||
// the burrow's door and back. the second pair was not walked through
|
||||
// in the recording and is guessed from the first.
|
||||
trig_1a: q => q.room("burrow", "spawn_1_a"),
|
||||
trig_1_a: q => q.room("start", "spawn_1a"),
|
||||
trig_1b: q => q.room("burrow", "spawn_1_b"),
|
||||
trig_1_b: q => q.room("start", "spawn_1b"),
|
||||
|
||||
// the phantoms' door, with the burrow's key.
|
||||
phan_trig_e(q) {
|
||||
if (q.held() !== "phan_key_1" || q.vars.doorOpen) {
|
||||
return;
|
||||
}
|
||||
q.vars.doorOpen = true;
|
||||
q.use();
|
||||
set(q, "phan_door_e", 1, 1, 0);
|
||||
set(q, "phan_trig_e", 1, 0, 0);
|
||||
q.xp(15, "phan_trig_e");
|
||||
goal(q, 3490);
|
||||
phantoms(q, [["phantom_1", "path_1"], ["phantom_6", "path_6"], ["phantom_7", "path_7"], ["phantom_10", null],
|
||||
["phantom_11", "path_1"], ["phantom_12", "path_12"], ["phantom_13", null], ["phantom_14", null], ["phantom_15", null]]);
|
||||
q.after(2964, () => set(q, "phan_block_e", 1, 0, 0));
|
||||
},
|
||||
|
||||
exit_vol: q => q.send("qcmd", 19),
|
||||
},
|
||||
|
||||
triggerLike: [
|
||||
[/^pipetrig_[1-4]$/, pipePlugged],
|
||||
[/^flowertrig_?\d+$/, flowerWatered],
|
||||
[/^bunny_(7|8|9|10)$/, bunnyFreed],
|
||||
// QuestActor.handleTriggerTreasure: [actor, 3, gems, 0, 1]
|
||||
[/^treasure_\d+$/, (q, chest) => {
|
||||
if (!q.vars.opened.has(chest)) {
|
||||
q.send("qatt", chest, 3, CHEST_GEMS[chest] || GUESSED_CHEST_GEMS, 0, 1);
|
||||
}
|
||||
}],
|
||||
// the gem an eaten phantom leaves, walked into.
|
||||
[/^phantom_\w+__give_gem$/, (q, gem) => {
|
||||
const phantom = gem.slice(0, -"__give_gem".length);
|
||||
if (q.vars.eaten.has(phantom) && !q.vars.opened.has(gem)) {
|
||||
q.vars.opened.add(gem);
|
||||
q.gems(25);
|
||||
q.send("qad", gem, 0, "null");
|
||||
}
|
||||
}],
|
||||
],
|
||||
|
||||
// a talk read to its end
|
||||
answer: {
|
||||
liza_1(q) {
|
||||
counter(q, "00_uri", 1);
|
||||
counter(q, "players", 1);
|
||||
q.send("qposturi", "/adventure1-returnofthephantoms/#00-start/#0#001");
|
||||
counter(q, "00_uri", 99);
|
||||
set(q, "vineblock_1", 1, 0, 0);
|
||||
set(q, "vine_1", 1, 1, 0);
|
||||
q.send("qswfs", "liza_1", "disappear");
|
||||
set(q, "liza_1", 2, 1, 1);
|
||||
set(q, "liza_1", 3, 1, 0);
|
||||
goal(q, 3466);
|
||||
},
|
||||
liza_2(q) {
|
||||
if (q.vars.thanked) {
|
||||
return;
|
||||
}
|
||||
q.vars.thanked = true;
|
||||
set(q, "liza_2", 2, 1, 1);
|
||||
set(q, "exit_port", 1, 1, 0);
|
||||
set(q, "portal", 1, 1, 0);
|
||||
q.xp(50, "liza_2");
|
||||
set(q, "liza_2", 3, 1, 0);
|
||||
q.after(565, () => {
|
||||
page(q, "40_uri", "40-exit");
|
||||
q.offer(PRIZES);
|
||||
});
|
||||
},
|
||||
},
|
||||
|
||||
pickedUp: {
|
||||
// the bunnies outside hear of the key.
|
||||
phan_key_1(q) {
|
||||
q.after(47, () => {
|
||||
set(q, "bunny_1", 3, 1, 1);
|
||||
set(q, "bunny_2", 4, 1, 1);
|
||||
set(q, "bunny_4", 2, 1, 1);
|
||||
});
|
||||
},
|
||||
},
|
||||
|
||||
// A plant ate a phantom ([actor, 50, 1, x, y, ""] has it die there),
|
||||
// which leaves a gem worth 25 behind.
|
||||
eaten(q, plant, phantom, x, y) {
|
||||
if (!/^phantom_\w+$/.test(phantom) || q.vars.eaten.has(phantom)) {
|
||||
return;
|
||||
}
|
||||
q.vars.eaten.add(phantom);
|
||||
q.send("qad", phantom, 50, 1, x, y, "");
|
||||
q.send("qspn", phantom, `${phantom}__give_gem`, 200, 42, 3, 25, "null", "null", "null");
|
||||
q.xp(5, phantom);
|
||||
set(q, phantom, 3, 1, 0);
|
||||
q.after(1500, () => set(q, phantom, 99, 0, 0));
|
||||
},
|
||||
|
||||
// a chest, opened
|
||||
openedLike: [
|
||||
[/^treasure_\d+$/, (q, chest) => {
|
||||
if (!q.vars.opened.has(chest)) {
|
||||
q.vars.opened.add(chest);
|
||||
q.gems(CHEST_GEMS[chest] || GUESSED_CHEST_GEMS);
|
||||
q.xp(5, chest);
|
||||
}
|
||||
}],
|
||||
],
|
||||
|
||||
// the prize taken
|
||||
gifted(q) {
|
||||
q.after(960, () => set(q, "exit_block", 1, 0, 0));
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,198 @@
|
||||
"use strict";
|
||||
|
||||
// the Training Grounds ("Adventure Tutorial", script def 15), written from
|
||||
// a recording of the official game of 2026-10-12: one player, who talked
|
||||
// to Liza four times, fed the four phantoms to the plants, crept past the
|
||||
// rest unseen and opened the chest. everything sent here was seen sent
|
||||
// there, in this order. not in the recording, so not here: being caught by
|
||||
// a phantom.
|
||||
//
|
||||
// commands ("qcmd"): 1 sets an actor's [state, visible, needs a click];
|
||||
// 3 has it talk (a string id); 38 is the line under the screen's top; 19
|
||||
// ends the adventure. "qswfs" plays a state of an actor's artwork.
|
||||
|
||||
const liza = (q, name, ...artwork) => {
|
||||
for (const state of artwork) {
|
||||
q.send("qswfs", name, state);
|
||||
}
|
||||
q.send("qcmd", 1, name, 1, 1, 1);
|
||||
};
|
||||
const TALKS = {liza_1: 3149, liza_2: 3150, liza_3: 3155, liza_4: 3151};
|
||||
const talk = name => q => q.send("qcmd", 3, 0, name, 1, TALKS[name]);
|
||||
// Liza leaves in two steps and is put away a little later.
|
||||
const leaves = (q, name, between, gone) => {
|
||||
q.send("qswfs", name, "disappear");
|
||||
q.send("qcmd", 1, name, 2, 1, 1);
|
||||
between();
|
||||
q.send("qcmd", 1, name, 3, 1, 0);
|
||||
q.after(gone, () => q.send("qcmd", 1, name, 4, 0, 0));
|
||||
};
|
||||
const TRAPPED_LINES = [3539, 3540, 3541];
|
||||
|
||||
module.exports = {
|
||||
defId: 15,
|
||||
title: "Training Grounds",
|
||||
rooms: {start: {room: "adventures.room_adventure_tutorial", name: "Adventure Tutorial", nameStringId: 18326, music: "ajq_mustutorial"}},
|
||||
written: "2018-03-14 22:04:55",
|
||||
objective: 3152, // "TALK to Liza."
|
||||
|
||||
// name, type, def, state, visible, needs a click, path, artwork state
|
||||
actors: [
|
||||
["queststart", 18, 0, 0, 1, 1, "", ""],
|
||||
["checkpoint", 16, "ajq_spawnpointlp", 0, 1, 1, "", ""],
|
||||
["portal", 16, "ajq_portalgatelp", 0, 0, 1, "", ""],
|
||||
["lizatimer_1", 8, 0, 0, 0, 1, "", ""],
|
||||
["liza_1", 1, 21, 0, 0, 1, "", ""],
|
||||
["liza_2", 1, 21, 0, 0, 1, "", ""],
|
||||
["lizatimer_2", 8, 0, 0, 0, 1, "", ""],
|
||||
["lizatimer_3", 8, 0, 0, 0, 1, "", ""],
|
||||
["lizatrig_1", 3, 0, 0, 1, 1, "", ""],
|
||||
["blockvol_1", 5, 0, 0, 1, 1, "", ""],
|
||||
["blockvol_2", 5, 0, 0, 1, 1, "", ""],
|
||||
["blockvol_3", 5, 0, 0, 1, 1, "", ""],
|
||||
["block_1", 2, 0, 0, 1, 1, "", ""],
|
||||
["block_2", 2, 0, 0, 1, 1, "", ""],
|
||||
["block_3", 2, 0, 0, 1, 1, "", ""],
|
||||
["phantom_1", 11, 2, 0, 1, 1, "", ""],
|
||||
["phantom_2", 11, 2, 0, 1, 1, "", ""],
|
||||
["phantom_3", 11, 2, 0, 1, 1, "", ""],
|
||||
["phantom_4__a", 11, 2, 0, 1, 1, "", ""],
|
||||
["phantom_4__b", 11, 2, 0, 1, 1, "", ""],
|
||||
["plant_0", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_1", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_2", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_3", 21, 100, 0, 1, 1, "", ""],
|
||||
["plant_4", 21, 100, 0, 1, 1, "", ""],
|
||||
["phantom_5", 11, 2, 0, 1, 1, "path_5", ""],
|
||||
["phantom_6", 11, 2, 0, 1, 1, "path_6", ""],
|
||||
["phantom_7", 11, 2, 0, 1, 1, "path_7", ""],
|
||||
["phantom_8", 11, 2, 0, 1, 1, "path_8", ""],
|
||||
["phantom_9", 11, 2, 0, 1, 1, "path_9", ""],
|
||||
["phantom_10", 11, 2, 0, 1, 1, "path_10", ""],
|
||||
["phantom_11", 11, 2, 0, 1, 1, "path_11", ""],
|
||||
["phantom_12", 11, 2, 0, 1, 1, "path_12", ""],
|
||||
["phantom_13", 11, 2, 0, 1, 1, "path_13", ""],
|
||||
["phantom_14", 11, 2, 0, 1, 1, "path_14", ""],
|
||||
["treasure_1", 13, 39, 0, 0, 1, "", ""],
|
||||
["exitblock", 5, 0, 0, 1, 1, "", ""],
|
||||
["exit", 2, 0, 0, 1, 1, "", ""],
|
||||
["exitvol", 3, 0, 0, 1, 1, "", ""],
|
||||
["liza_3", 1, 21, 0, 0, 1, "", ""],
|
||||
["lizatimer_4", 8, 0, 0, 0, 1, "", ""],
|
||||
["lizatrig_3", 3, 0, 0, 1, 1, "", ""],
|
||||
["liza_4", 1, 21, 0, 0, 1, "", ""],
|
||||
["lizatimer_5", 8, 0, 0, 0, 1, "", ""],
|
||||
["trap_count", 7, 0, 0, 0, 1, "", ""],
|
||||
["traptimer", 8, 0, 0, 0, 1, "", ""],
|
||||
["path_5", 20, 0, 0, 1, 1, "", ""],
|
||||
["path_6", 20, 0, 0, 1, 1, "", ""],
|
||||
["path_7", 20, 0, 0, 1, 1, "", ""],
|
||||
["path_8", 20, 0, 0, 1, 1, "", ""],
|
||||
["path_9", 20, 0, 0, 1, 1, "", ""],
|
||||
["path_10", 20, 0, 0, 1, 1, "", ""],
|
||||
["path_11", 20, 0, 0, 1, 1, "", ""],
|
||||
["path_12", 20, 0, 0, 1, 1, "", ""],
|
||||
["path_13", 20, 0, 0, 1, 1, "", ""],
|
||||
["path_14", 20, 0, 0, 1, 1, "", ""],
|
||||
["diff_level", 7, 0, 0, 1, 1, "", ""],
|
||||
["live_players", 7, 0, 1, 0, 1, "", ""], ],
|
||||
|
||||
on: {
|
||||
loaded(q) {
|
||||
q.vars.trapped = 0;
|
||||
q.after(1700, () => liza(q, "liza_1", "facesw", "appear"));
|
||||
},
|
||||
|
||||
// walked into, or clicked
|
||||
trigger: {
|
||||
liza_1: talk("liza_1"),
|
||||
liza_2: talk("liza_2"),
|
||||
liza_3: talk("liza_3"),
|
||||
liza_4: talk("liza_4"),
|
||||
lizatrig_1(q) {
|
||||
liza(q, "liza_2", "facesw", "appear");
|
||||
q.send("qcmd", 1, "lizatrig_1", 1, 0, 0);
|
||||
},
|
||||
lizatrig_3(q) {
|
||||
liza(q, "liza_4", "appear");
|
||||
q.send("qposturi", "/adventure0-tutorial/#20-sneakpastthephantoms/#0#001");
|
||||
q.send("qcmd", 1, "lizatrig_3", 1, 0, 0);
|
||||
},
|
||||
// QuestActor.handleTriggerTreasure: [actor, 3, gems, 0, 1]
|
||||
treasure_1(q) {
|
||||
q.send("qatt", "treasure_1", 3, 250, 0, 1);
|
||||
q.send("qposturi", "/adventure0-tutorial/#30-exit/#0#001");
|
||||
},
|
||||
exitvol(q) {
|
||||
q.send("qcmd", 19);
|
||||
},
|
||||
},
|
||||
|
||||
// a talk read to its end
|
||||
answer: {
|
||||
liza_1(q) {
|
||||
q.send("qposturi", "/adventure0-tutorial/#00-start/#0#001");
|
||||
q.send("qcmd", 1, "block_1", 1, 1, 0);
|
||||
q.send("qcmd", 1, "blockvol_1", 1, 0, 0);
|
||||
q.send("qcmd", 38, 3157);
|
||||
leaves(q, "liza_1", () => {}, 2200);
|
||||
},
|
||||
liza_2(q) {
|
||||
q.send("qcmd", 1, "blockvol_2", 1, 0, 0);
|
||||
q.send("qcmd", 1, "block_2", 1, 1, 0);
|
||||
leaves(q, "liza_2", () => {}, 2950);
|
||||
q.send("qcmd", 38, 3538);
|
||||
},
|
||||
liza_3(q) {
|
||||
q.send("qcmd", 1, "block_3", 1, 1, 0);
|
||||
q.send("qcmd", 1, "blockvol_3", 1, 0, 0);
|
||||
q.send("qcmd", 38, 3542);
|
||||
leaves(q, "liza_3", () => {}, 2580);
|
||||
},
|
||||
liza_4(q) {
|
||||
q.send("qcmd", 1, "treasure_1", 1, 1, 1);
|
||||
leaves(q, "liza_4", () => q.send("qcmd", 38, 3543), 2700);
|
||||
// the recording's animal was level 0 and got 50 XP here, which made
|
||||
// it level 1. guessed: that this is for a first time only.
|
||||
if (q.level() === 0) {
|
||||
q.after(690, () => q.xp(50, "lizatimer_5"));
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
// A plant ate a phantom: [actor, 50, 1, x, y, ""] has it die there.
|
||||
eaten(q, plant, phantom, x, y) {
|
||||
if (!/^phantom_\w+$/.test(phantom) || q.vars.trapped >= 4) {
|
||||
return;
|
||||
}
|
||||
q.vars.trapped++;
|
||||
q.send("qad", phantom, 50, 1, x, y, "");
|
||||
q.send("qcmdVT", 1, "trap_count", q.vars.trapped, 0, 0);
|
||||
if (q.vars.trapped < 4) {
|
||||
q.send("qcmd", 38, TRAPPED_LINES[q.vars.trapped - 1]);
|
||||
}
|
||||
else {
|
||||
q.send("qposturi", "/adventure0-tutorial/#10-trapthephantoms/#0#001");
|
||||
q.send("qcmd", 38, 3152);
|
||||
q.after(500, () => liza(q, "liza_3", "facesw", "appear"));
|
||||
}
|
||||
q.xp(1, phantom);
|
||||
},
|
||||
|
||||
// the chest, opened
|
||||
opened: {
|
||||
treasure_1(q) {
|
||||
if (q.vars.opened) {
|
||||
return;
|
||||
}
|
||||
q.vars.opened = true;
|
||||
q.gems(250);
|
||||
q.xp(1, "treasure_1");
|
||||
q.send("qcmd", 1, "exitblock", 1, 0, 0);
|
||||
q.send("qcmd", 1, "exit", 1, 1, 0);
|
||||
q.send("qcmd", 1, "portal", 1, 1, 0);
|
||||
q.send("qposturi", "/adventure0-tutorial/#30-exit/#0#001");
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,278 @@
|
||||
"use strict";
|
||||
|
||||
// minimal AMF3 reader, enough for the game's defPacks (objects, arrays,
|
||||
// strings and numbers).
|
||||
|
||||
class Amf3Reader {
|
||||
constructor(buf) {
|
||||
this.buf = buf;
|
||||
this.pos = 0;
|
||||
this.strings = [];
|
||||
this.objects = [];
|
||||
this.traits = [];
|
||||
}
|
||||
|
||||
u29() {
|
||||
let value = 0;
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const b = this.buf[this.pos++];
|
||||
if (i === 3) {
|
||||
return (value << 8) | b;
|
||||
}
|
||||
value = (value << 7) | (b & 0x7f);
|
||||
if (!(b & 0x80)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
string() {
|
||||
const ref = this.u29();
|
||||
if (!(ref & 1)) {
|
||||
return this.strings[ref >> 1];
|
||||
}
|
||||
const len = ref >> 1;
|
||||
if (len === 0) {
|
||||
return "";
|
||||
}
|
||||
const str = this.buf.toString("utf8", this.pos, this.pos + len);
|
||||
this.pos += len;
|
||||
this.strings.push(str);
|
||||
return str;
|
||||
}
|
||||
|
||||
value() {
|
||||
const type = this.buf[this.pos++];
|
||||
switch (type) {
|
||||
case 0x00: return undefined;
|
||||
case 0x01: return null;
|
||||
case 0x02: return false;
|
||||
case 0x03: return true;
|
||||
case 0x04: {
|
||||
const n = this.u29();
|
||||
return n & 0x10000000 ? n - 0x20000000 : n;
|
||||
}
|
||||
case 0x05: {
|
||||
const n = this.buf.readDoubleBE(this.pos);
|
||||
this.pos += 8;
|
||||
return n;
|
||||
}
|
||||
case 0x06: return this.string();
|
||||
case 0x08: {
|
||||
const ref = this.u29();
|
||||
if (!(ref & 1)) {
|
||||
return this.objects[ref >> 1];
|
||||
}
|
||||
const date = new Date(this.buf.readDoubleBE(this.pos));
|
||||
this.pos += 8;
|
||||
this.objects.push(date);
|
||||
return date;
|
||||
}
|
||||
case 0x09: return this.array();
|
||||
case 0x0a: return this.object();
|
||||
case 0x0c: {
|
||||
const ref = this.u29();
|
||||
if (!(ref & 1)) {
|
||||
return this.objects[ref >> 1];
|
||||
}
|
||||
const bytes = this.buf.subarray(this.pos, this.pos + (ref >> 1));
|
||||
this.pos += ref >> 1;
|
||||
this.objects.push(bytes);
|
||||
return bytes;
|
||||
}
|
||||
// Vector.<int>, Vector.<uint>, Vector.<Number>, Vector.<Object>
|
||||
case 0x0d:
|
||||
case 0x0e:
|
||||
case 0x0f:
|
||||
case 0x10: {
|
||||
const ref = this.u29();
|
||||
if (!(ref & 1)) {
|
||||
return this.objects[ref >> 1];
|
||||
}
|
||||
const out = [];
|
||||
this.objects.push(out);
|
||||
this.pos += 1; // fixed-length flag
|
||||
if (type === 0x10) {
|
||||
this.string(); // element class name
|
||||
}
|
||||
for (let i = 0; i < ref >> 1; i++) {
|
||||
if (type === 0x10) {
|
||||
out.push(this.value());
|
||||
}
|
||||
else if (type === 0x0f) {
|
||||
out.push(this.buf.readDoubleBE(this.pos));
|
||||
this.pos += 8;
|
||||
}
|
||||
else {
|
||||
out.push(type === 0x0d ? this.buf.readInt32BE(this.pos) : this.buf.readUInt32BE(this.pos));
|
||||
this.pos += 4;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
default:
|
||||
throw new Error(`Unsupported AMF3 type 0x${type.toString(16)} at ${this.pos - 1}`);
|
||||
}
|
||||
}
|
||||
|
||||
array() {
|
||||
const ref = this.u29();
|
||||
if (!(ref & 1)) {
|
||||
return this.objects[ref >> 1];
|
||||
}
|
||||
const dense = ref >> 1;
|
||||
const assoc = {};
|
||||
let hasAssoc = false;
|
||||
const out = [];
|
||||
this.objects.push(out);
|
||||
for (let key = this.string(); key !== ""; key = this.string()) {
|
||||
assoc[key] = this.value();
|
||||
hasAssoc = true;
|
||||
}
|
||||
for (let i = 0; i < dense; i++) {
|
||||
out.push(this.value());
|
||||
}
|
||||
if (hasAssoc) {
|
||||
Object.assign(out, assoc);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
object() {
|
||||
const ref = this.u29();
|
||||
if (!(ref & 1)) {
|
||||
return this.objects[ref >> 1];
|
||||
}
|
||||
let traits;
|
||||
if (!(ref & 2)) {
|
||||
traits = this.traits[ref >> 2];
|
||||
}
|
||||
else {
|
||||
if (ref & 4) {
|
||||
throw new Error("Externalizable AMF3 objects are not supported");
|
||||
}
|
||||
traits = {dynamic: Boolean(ref & 8), names: []};
|
||||
const count = ref >> 4;
|
||||
this.string(); // class name
|
||||
for (let i = 0; i < count; i++) {
|
||||
traits.names.push(this.string());
|
||||
}
|
||||
this.traits.push(traits);
|
||||
}
|
||||
const out = {};
|
||||
this.objects.push(out);
|
||||
for (const name of traits.names) {
|
||||
out[name] = this.value();
|
||||
}
|
||||
if (traits.dynamic) {
|
||||
for (let key = this.string(); key !== ""; key = this.string()) {
|
||||
out[key] = this.value();
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
// writer for what the reader above produces from a defPack: plain objects,
|
||||
// arrays (with or without string keys), strings, numbers, booleans and null.
|
||||
// nothing is written as a reference except repeated strings.
|
||||
class Amf3Writer {
|
||||
constructor() {
|
||||
this.parts = [];
|
||||
this.strings = new Map();
|
||||
}
|
||||
|
||||
u29(value) {
|
||||
if (value < 0x80) {
|
||||
this.parts.push(Buffer.from([value]));
|
||||
}
|
||||
else if (value < 0x4000) {
|
||||
this.parts.push(Buffer.from([(value >> 7) | 0x80, value & 0x7f]));
|
||||
}
|
||||
else if (value < 0x200000) {
|
||||
this.parts.push(Buffer.from([(value >> 14) | 0x80, ((value >> 7) & 0x7f) | 0x80, value & 0x7f]));
|
||||
}
|
||||
else {
|
||||
this.parts.push(Buffer.from([(value >> 22) | 0x80, ((value >> 15) & 0x7f) | 0x80, ((value >> 8) & 0x7f) | 0x80, value & 0xff]));
|
||||
}
|
||||
}
|
||||
|
||||
string(text) {
|
||||
if (text === "") {
|
||||
this.u29(1);
|
||||
}
|
||||
else if (this.strings.has(text)) {
|
||||
this.u29(this.strings.get(text) << 1);
|
||||
}
|
||||
else {
|
||||
this.strings.set(text, this.strings.size);
|
||||
const bytes = Buffer.from(text, "utf8");
|
||||
this.u29((bytes.length << 1) | 1);
|
||||
this.parts.push(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
pairs(entries) {
|
||||
for (const [key, value] of entries) {
|
||||
this.string(key);
|
||||
this.value(value);
|
||||
}
|
||||
this.string("");
|
||||
}
|
||||
|
||||
value(value) {
|
||||
if (value === undefined) {
|
||||
this.parts.push(Buffer.from([0x00]));
|
||||
}
|
||||
else if (value === null) {
|
||||
this.parts.push(Buffer.from([0x01]));
|
||||
}
|
||||
else if (typeof value === "boolean") {
|
||||
this.parts.push(Buffer.from([value ? 0x03 : 0x02]));
|
||||
}
|
||||
else if (typeof value === "number") {
|
||||
if (Number.isInteger(value) && value >= -0x10000000 && value < 0x10000000) {
|
||||
this.parts.push(Buffer.from([0x04]));
|
||||
this.u29(value & 0x1fffffff);
|
||||
}
|
||||
else {
|
||||
const bytes = Buffer.alloc(9);
|
||||
bytes[0] = 0x05;
|
||||
bytes.writeDoubleBE(value, 1);
|
||||
this.parts.push(bytes);
|
||||
}
|
||||
}
|
||||
else if (typeof value === "string") {
|
||||
this.parts.push(Buffer.from([0x06]));
|
||||
this.string(value);
|
||||
}
|
||||
else if (Array.isArray(value)) {
|
||||
this.parts.push(Buffer.from([0x09]));
|
||||
this.u29((value.length << 1) | 1);
|
||||
// string keys set on the array beside its numbered elements.
|
||||
this.pairs(Object.entries(value).filter(([key]) => !/^\d+$/.test(key)));
|
||||
for (const element of value) {
|
||||
this.value(element);
|
||||
}
|
||||
}
|
||||
else if (typeof value === "object" && !Buffer.isBuffer(value)) {
|
||||
// A dynamic object of no class, with its traits written in place.
|
||||
this.parts.push(Buffer.from([0x0a, 0x0b]));
|
||||
this.string("");
|
||||
this.pairs(Object.entries(value));
|
||||
}
|
||||
else {
|
||||
throw new Error("Cannot write this value as AMF3");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
decode: buf => new Amf3Reader(buf).value(),
|
||||
encode: value => {
|
||||
const writer = new Amf3Writer();
|
||||
writer.value(value);
|
||||
return Buffer.concat(writer.parts);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,148 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const colours = require("./colours.js");
|
||||
const badges = require("./badges.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const {activeAvatar, activePet, wornItems, lastSeenField, isUint} = require("./player.js");
|
||||
|
||||
// owning several animals (client side: AvatarSwitch, AvatarXtCommManager).
|
||||
// new animals are free.
|
||||
|
||||
const MAX_AVATARS = 1000; // where the client's animal switcher stops counting
|
||||
|
||||
// AvatarXtCommManager.avatarGetResponse status
|
||||
const PLAYER_OFFLINE = 0;
|
||||
const PLAYER_ONLINE = 1;
|
||||
const PLAYER_UNKNOWN = 3;
|
||||
|
||||
// avatar.NameBar: colour ids 0-10, a badge by its place in the badge list,
|
||||
// and one bit for "hide my adventure level".
|
||||
const NAME_BAR_COLORS = 10;
|
||||
const validNameBarData = (value, account) => Number.isInteger(value) && value >= 0
|
||||
&& (value & 0xFF) <= NAME_BAR_COLORS
|
||||
&& (value >> 8 & 0xFF) < defpacks.badgeIds().length
|
||||
&& badges.mayWear(account, defpacks.badgeIds()[value >> 8 & 0xFF]) // the ones the admin gives: lib/badges.js
|
||||
&& (value >> 16) <= 1;
|
||||
|
||||
module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}) => {
|
||||
// A player's card: who they are, the animal they are using and what it
|
||||
// wears. AvatarXtCommManager.avatarGetResponse reads [username, uuid,
|
||||
// status, accountType, isGuide, daysSinceLogin, perUserAvId, avInvId,
|
||||
// nameBarData, avatarType, customAvatarId, 3 colours, avatarName, eyesDefId,
|
||||
// patternDefId, questLevel, clothingCount, sfsUserId, moderatedFlag, pet
|
||||
// lBits/uBits/eBits/name, (itemDefId, colour)...].
|
||||
const sendPlayerCard = (session, account, requestedName) => {
|
||||
if (!account) {
|
||||
session.sendXt("ag", -1, requestedName, "", PLAYER_UNKNOWN);
|
||||
return;
|
||||
}
|
||||
const targetSession = findOnline(account.username);
|
||||
const avatar = activeAvatar(account);
|
||||
const worn = wornItems(account, avatar);
|
||||
session.sendXt("ag", -1, account.username, account.uuid, targetSession ? PLAYER_ONLINE : PLAYER_OFFLINE,
|
||||
account.accountType, account.isGuide ? 1 : 0, lastSeenField(account, Boolean(targetSession)),
|
||||
avatar.perUserAvId, avatar.avInvId, account.nameBarData, avatar.type, avatar.customAvId, ...avatar.colors, avatar.name,
|
||||
avatar.eyes, avatar.pattern, avatar.questLevel || 0, worn.length, targetSession ? targetSession.id : -1, 1,
|
||||
...petFields(activePet(account)).slice(0, 4),
|
||||
...worn.flatMap(item => [item.def, item.color]));
|
||||
};
|
||||
|
||||
return {
|
||||
// [username, ?]
|
||||
ag(session, roomId, [username]) {
|
||||
sendPlayerCard(session, accounts.byName(username), username);
|
||||
},
|
||||
|
||||
// [sfsUserId, ?]: the same, for a player met in a room
|
||||
ags(session, roomId, [sfsUserId]) {
|
||||
const target = findBySfsId(Number(sfsUserId));
|
||||
if (target) {
|
||||
sendPlayerCard(session, target.account, target.account.username);
|
||||
}
|
||||
},
|
||||
|
||||
// AvatarSwitch.addNewWorldAvatar: [nameId1, nameId2, nameId3, avatarType,
|
||||
// customAvatarId, diamondDefId, shopId]. the name is kept as its three
|
||||
// localization ids, which is what LocalizationManager.translateAvatarName reads.
|
||||
aa(session, roomId, [name1, name2, name3, type, customAvId]) {
|
||||
const {account} = session;
|
||||
const custom = defpacks.customAvatarDef(customAvId);
|
||||
if (![name1, name2, name3].every(isUint) || !defpacks.avatarDef(type) || account.avatars.length >= MAX_AVATARS
|
||||
|| (custom && Number(custom.avatarRef) !== Number(type))) {
|
||||
// AvatarSwitch.addAvatarResponse: [status, perUserAvId, avInvId]
|
||||
session.sendXt("aa", -1, 0, 0, 0);
|
||||
return;
|
||||
}
|
||||
// the inventory id is a slot: the client cannot count past 1,023 there
|
||||
// (accounts.freeAvatarSlot).
|
||||
const avatar = accounts.newAvatar({perUserAvId: account.nextInv++, avInvId: accounts.freeAvatarSlot(account)}, `${name1}|${name2}|${name3}`, type, customAvId);
|
||||
account.avatars.push(avatar);
|
||||
accounts.save();
|
||||
session.sendXt("aa", -1, 1, avatar.perUserAvId, avatar.avInvId);
|
||||
},
|
||||
|
||||
// AvatarSwitch.switchAvatars: [perUserAvId]. everyone in the room gets the
|
||||
// reply (AvatarSwitch.avatarSwitchResponse / transformEnterFrameHandler);
|
||||
// it ends differently for the player who switched.
|
||||
as(session, roomId, [perUserAvId]) {
|
||||
const {account} = session;
|
||||
const avatar = account.avatars.find(candidate => candidate.perUserAvId === Number(perUserAvId));
|
||||
if (!avatar) {
|
||||
session.sendXt("as", -1, 0);
|
||||
return;
|
||||
}
|
||||
account.activeAvatar = avatar.perUserAvId;
|
||||
accounts.save();
|
||||
const messageRoom = session.room ? session.room.id : -1;
|
||||
const common = [1, session.id, avatar.perUserAvId, avatar.avInvId, avatar.customAvId, avatar.type, ...avatar.colors, avatar.name];
|
||||
session.sendXt("as", messageRoom, ...common, avatar.petInvId, avatar.questLevel || 0);
|
||||
if (session.pos) {
|
||||
for (const other of others(session)) {
|
||||
other.sendXt("as", messageRoom, ...common, ...petFields(activePet(account)), avatar.questLevel || 0);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// AvatarSwitch.avatarKillResponse: [success, ?]
|
||||
ak(session, roomId, [perUserAvId]) {
|
||||
const {account} = session;
|
||||
const avatar = account.avatars.find(candidate => candidate.perUserAvId === Number(perUserAvId));
|
||||
if (!avatar || avatar === activeAvatar(account) || account.avatars.length < 2) {
|
||||
session.sendXt("ak", -1, 0, 0);
|
||||
return;
|
||||
}
|
||||
account.avatars = account.avatars.filter(candidate => candidate !== avatar);
|
||||
for (const item of account.items) {
|
||||
item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId);
|
||||
}
|
||||
accounts.save();
|
||||
session.sendXt("ak", -1, 1, 0);
|
||||
},
|
||||
|
||||
// AvatarXtCommManager.requestColorChange: [color1, color2, color3, nameBarData]
|
||||
ap(session, roomId, colors) {
|
||||
if (!colors.slice(0, 3).every(isUint) || colors.length < 3 || !colors.slice(0, 3).every(color => colours.known(Number(color)))) {
|
||||
session.sendXt("ap", -1, 0);
|
||||
return;
|
||||
}
|
||||
activeAvatar(session.account).colors = colors.slice(0, 3).map(Number);
|
||||
// the name tag is the account's, not the animal's. the client only
|
||||
// sends it along here, changed or not.
|
||||
const nameBarData = Number(colors[3]);
|
||||
const tagChanged = colors.length > 3 && validNameBarData(nameBarData, session.account) && nameBarData !== session.account.nameBarData;
|
||||
if (tagChanged) {
|
||||
session.account.nameBarData = nameBarData;
|
||||
}
|
||||
accounts.save();
|
||||
session.sendXt("ap", -1, 1);
|
||||
refreshForOthers(session);
|
||||
if (tagChanged) {
|
||||
// AvatarXtCommManager "an": [sfsUserId, nameBarData]
|
||||
for (const other of others(session)) {
|
||||
other.sendXt("an", session.room.id, session.id, nameBarData);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,129 @@
|
||||
"use strict";
|
||||
|
||||
const path = require("path");
|
||||
const cdn = require("./cdn.js");
|
||||
|
||||
// what a player's card shows about the account beyond the game's own:
|
||||
// marks the admin gives in the panel, the player's Discord username and
|
||||
// their bio, both of which they set themselves on the account page. all of
|
||||
// it is for show: a badge gives no power over anything or anyone.
|
||||
//
|
||||
// every badge is drawn on the player's card, after the username in the
|
||||
// name bar (buddy.BuddyCard in the SWF), as public/badges/<id>.png; the
|
||||
// card is told its id and label. the Discord username is drawn there too,
|
||||
// last. ids and labels must stay free of "," "|" and "%", which separate
|
||||
// them on the way to the client.
|
||||
//
|
||||
// A badge with `tag` is a name tag badge as well: one more of the icons a
|
||||
// player picks for their name tag in the animal editor, beside the game's
|
||||
// own 62. it is a row added to the badge pack (defPack 1049) that clients get, with
|
||||
// a picture of ours (swf/badges/<id>.swf, served as media `tag.media`) and
|
||||
// an unlock flag: the editor only offers a badge whose `pendingFlagsBit` is
|
||||
// set in the flags the login message carries (gui.AvatarEditor
|
||||
// .onNamebarBadgeIdsLoaded), so it is offered to the accounts that hold it
|
||||
// and to nobody else, from their next login. the server refuses a name tag
|
||||
// that names one the account does not hold (lib/avatars.js). the def ids
|
||||
// must follow the game's own without a gap: a name tag names its badge by
|
||||
// its place in the list, and the editor takes that to be the def id less
|
||||
// one. so a badge added later goes on the end and none is ever taken out.
|
||||
//
|
||||
// tools/make-badges.py draws both pictures of a badge from one outline.
|
||||
//
|
||||
// early Member is given by the server itself, to an account made while
|
||||
// there are no more than a hundred (lib/accounts.js); the admin may give
|
||||
// it and take it away like any other.
|
||||
|
||||
// in the order they are listed and drawn.
|
||||
const BADGES = [
|
||||
{id: "owner", label: "Owner", tag: {def: 63, media: 20001, bit: 8}},
|
||||
{id: "moderator", label: "Moderator", tag: {def: 64, media: 20002, bit: 9}},
|
||||
{id: "contributor", label: "Contributor", tag: {def: 65, media: 20003, bit: 10}},
|
||||
{id: "developer", label: "Developer", tag: {def: 66, media: 20004, bit: 11}},
|
||||
{id: "artist", label: "Artist", tag: {def: 67, media: 20005, bit: 12}},
|
||||
{id: "helper", label: "Helper", tag: {def: 68, media: 20006, bit: 13}},
|
||||
{id: "bughunter", label: "Bug Hunter", tag: {def: 69, media: 20007, bit: 14}},
|
||||
{id: "eventwinner", label: "Event Winner", tag: {def: 70, media: 20008, bit: 15}},
|
||||
{id: "tester", label: "Tester", tag: {def: 71, media: 20009, bit: 16}},
|
||||
{id: "friend", label: "Friend", tag: {def: 72, media: 20010, bit: 17}},
|
||||
{id: "supporter", label: "Supporter", tag: {def: 73, media: 20011, bit: 18}},
|
||||
{id: "partner", label: "Partner", tag: {def: 74, media: 20012, bit: 19}},
|
||||
{id: "early", label: "Early Member", tag: {def: 75, media: 20013, bit: 20}},
|
||||
{id: "booster", label: "Discord Server Booster"}, // on the card only
|
||||
];
|
||||
const TAG_BADGES = BADGES.filter(badge => badge.tag);
|
||||
|
||||
const known = id => BADGES.some(badge => badge.id === id);
|
||||
|
||||
const of = account => BADGES.filter(badge => account.badges.includes(badge.id));
|
||||
|
||||
const set = (account, ids) => {
|
||||
account.badges = BADGES.map(badge => badge.id).filter(id => Array.isArray(ids) && ids.includes(id));
|
||||
};
|
||||
|
||||
// A Discord username as Discord has them now: 2 to 32 of a-z, 0-9, "_" and
|
||||
// ".", with no two dots in a row. nobody checks that it is theirs.
|
||||
const DISCORD_NAME = /^(?!.*\.\.)[a-z0-9_.]{2,32}$/;
|
||||
|
||||
// returns the username as it will be kept ("" for none), or null when it
|
||||
// cannot be one. A leading "@" and capitals are forgiven.
|
||||
const discordName = text => {
|
||||
const name = String(text === undefined || text === null ? "" : text).trim().replace(/^@/, "").toLowerCase();
|
||||
return name === "" || DISCORD_NAME.test(name) ? name : null;
|
||||
};
|
||||
|
||||
// A bio, the player's own words on the Bio tab of their card: up to
|
||||
// MAX_BIO characters on at most MAX_BIO_LINES lines. returns it as it will
|
||||
// be kept ("" for none), or null when it is too long. "%" cannot travel in
|
||||
// the game's messages and is left out.
|
||||
const MAX_BIO = 200;
|
||||
const MAX_BIO_LINES = 8;
|
||||
const bioText = text => {
|
||||
const bio = String(text === undefined || text === null ? "" : text)
|
||||
.replace(/\r\n?/g, "\n")
|
||||
.replace(/[\u0000-\u0009\u000b-\u001f\u007f%]/g, "")
|
||||
.split("\n").map(line => line.trim()).join("\n")
|
||||
.replace(/\n{3,}/g, "\n\n")
|
||||
.trim();
|
||||
return [...bio].length <= MAX_BIO && bio.split("\n").length <= MAX_BIO_LINES ? bio : null;
|
||||
};
|
||||
|
||||
// for the card: "id|label,id|label".
|
||||
const cardField = account => of(account).map(badge => `${badge.id}|${badge.label}`).join(",");
|
||||
|
||||
// adds the name tag badges' rows to the badge pack, which is keyed by def
|
||||
// id and has rows of {id, mediaRefId, pendingFlagsBit}, all strings.
|
||||
const addTagDefs = pack => {
|
||||
for (const {tag} of TAG_BADGES) {
|
||||
const row = [];
|
||||
row.id = String(tag.def);
|
||||
row.mediaRefId = String(tag.media);
|
||||
row.pendingFlagsBit = String(tag.bit);
|
||||
pack[tag.def] = row;
|
||||
}
|
||||
return pack;
|
||||
};
|
||||
|
||||
// the bits to add to an account's login flags: one for each name tag badge
|
||||
// it holds.
|
||||
const loginFlags = account => of(account).reduce((flags, badge) => (badge.tag ? flags | 1 << badge.tag.bit : flags), 0);
|
||||
|
||||
// may the account's name tag show the badge with this def id? any of the
|
||||
// game's own, and those of ours it holds.
|
||||
const mayWear = (account, defId) => {
|
||||
const badge = TAG_BADGES.find(candidate => candidate.tag.def === Number(defId));
|
||||
return !badge || account.badges.includes(badge.id);
|
||||
};
|
||||
|
||||
// the file behind a request for one of the name tag badges' pictures
|
||||
// ("<build>/media/<hashed id>"), or null when `relPath` is not one.
|
||||
const mediaFiles = new Map(TAG_BADGES.map(badge =>
|
||||
[cdn.hashedPath(`media/${badge.tag.media}`), path.join(__dirname, "..", "swf", "badges", `${badge.id}.swf`)]));
|
||||
const mediaFile = relPath => mediaFiles.get(relPath) || null;
|
||||
|
||||
// the Bio tab's artwork (swf/biotab.swf, made by tools/make-bio-tab.py),
|
||||
// which the card asks for as media BIO_TAB_MEDIA, or null.
|
||||
const BIO_TAB_MEDIA = 20100;
|
||||
const bioTabPath = cdn.hashedPath(`media/${BIO_TAB_MEDIA}`);
|
||||
const cardMedia = relPath => (relPath === bioTabPath ? path.join(__dirname, "..", "swf", "biotab.swf") : null);
|
||||
|
||||
module.exports = {BADGES, MAX_BIO, MAX_BIO_LINES, known, of, set, discordName, bioText, cardField, cardMedia, addTagDefs, loginFlags, mayWear, mediaFile};
|
||||
@@ -0,0 +1,199 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const limits = require("./limits.js");
|
||||
const net = require("net");
|
||||
|
||||
// what bans keep beside the account's own `bannedUntil`: banned addresses,
|
||||
// each account's one appeal, and a record of every ban given and lifted.
|
||||
//
|
||||
// an address ban is for good, and is of the address alone: the accounts
|
||||
// that were used from it are not banned with it (a VPN's address is many
|
||||
// people's). it keeps that address out of the game and out of signing up;
|
||||
// the account page still opens there, where a player can ask about it or
|
||||
// delete their account. this machine's own address cannot be banned, which
|
||||
// is also the address of everyone when a proxy or a tunnel stands in front
|
||||
// and the server has not been told (AJ_TRUSTED_PROXY).
|
||||
|
||||
const SCHEMA = `
|
||||
CREATE TABLE IF NOT EXISTS ban_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
at INTEGER NOT NULL,
|
||||
account_id INTEGER,
|
||||
username TEXT NOT NULL DEFAULT '',
|
||||
address TEXT NOT NULL DEFAULT '',
|
||||
action TEXT NOT NULL,
|
||||
seconds INTEGER NOT NULL DEFAULT 0,
|
||||
reason TEXT NOT NULL DEFAULT '',
|
||||
by TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS address_bans (
|
||||
address_key TEXT PRIMARY KEY,
|
||||
address TEXT NOT NULL,
|
||||
reason TEXT NOT NULL,
|
||||
by TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS appeals (
|
||||
account_id INTEGER PRIMARY KEY,
|
||||
created_at INTEGER NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
address_key TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT 'waiting',
|
||||
reply TEXT NOT NULL DEFAULT '',
|
||||
handled_at INTEGER
|
||||
);
|
||||
`;
|
||||
|
||||
const WAITING = "waiting";
|
||||
const APPROVED = "approved";
|
||||
const DENIED = "denied";
|
||||
const MAX_REASON = 300;
|
||||
const MAX_APPEAL = 1000;
|
||||
const MAX_REPLY = 500;
|
||||
const MAX_ADDRESS_BANS = 10000;
|
||||
const HISTORY_SHOWN = 50;
|
||||
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
const db = () => accounts.database();
|
||||
// A line break is kept; the other control characters are not.
|
||||
const clean = (text, max) => String(text === undefined || text === null ? "" : text).replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g, " ").trim().slice(0, max);
|
||||
|
||||
// A ban's reason as it is kept and shown: something is always said.
|
||||
const NO_REASON = "Not provided";
|
||||
const reasonText = text => clean(text, MAX_REASON) || NO_REASON;
|
||||
|
||||
const banned = new Map(); // address as limits count it -> {key, address, reason, by, createdAt}
|
||||
|
||||
const addressRow = row => ({key: row.address_key, address: row.address, reason: row.reason, by: row.by, createdAt: row.created_at});
|
||||
|
||||
const load = () => {
|
||||
db().exec(SCHEMA);
|
||||
for (const row of db().prepare("SELECT * FROM address_bans").all()) {
|
||||
banned.set(row.address_key, addressRow(row));
|
||||
}
|
||||
};
|
||||
|
||||
// `entry`: {account, address, action, seconds, reason, by}. actions: "ban",
|
||||
// "unban", "reason", "address_ban", "address_unban", "appeal",
|
||||
// "appeal_approved", "appeal_denied". A ban that runs out leaves no line.
|
||||
const record = entry => {
|
||||
db().prepare("INSERT INTO ban_log (at, account_id, username, address, action, seconds, reason, by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
|
||||
.run(now(), entry.account ? entry.account.id : null, entry.account ? entry.account.username : "", entry.address || "",
|
||||
entry.action, entry.seconds || 0, entry.reason || "", entry.by || "");
|
||||
};
|
||||
|
||||
const logRow = row => ({at: row.at, username: row.username, address: row.address, action: row.action, seconds: row.seconds, reason: row.reason, by: row.by});
|
||||
|
||||
const historyOf = account =>
|
||||
db().prepare("SELECT * FROM ban_log WHERE account_id = ? ORDER BY id DESC LIMIT ?").all(account.id, HISTORY_SHOWN).map(logRow);
|
||||
|
||||
const addressBan = address => banned.get(limits.key(address)) || null;
|
||||
|
||||
// returns {ban} or {error: "not_an_address" | "own_address" | "already" | "too_many"}.
|
||||
const banAddress = (address, reason, by) => {
|
||||
const text = String(address || "").trim().replace(/^::ffff:(?=\d+\.\d+\.\d+\.\d+$)/i, "");
|
||||
if (!net.isIP(text)) {
|
||||
return {error: "not_an_address"};
|
||||
}
|
||||
// this machine: the owner at home, and with a proxy or a tunnel in front
|
||||
// everybody else as well.
|
||||
if (limits.isLoopback(text) || /^(0\.0\.0\.0|::|0:0:0:0:0:0:0:[01])$/.test(text)) {
|
||||
return {error: "own_address"};
|
||||
}
|
||||
const key = limits.key(text);
|
||||
if (banned.has(key)) {
|
||||
return {error: "already"};
|
||||
}
|
||||
if (banned.size >= MAX_ADDRESS_BANS) {
|
||||
return {error: "too_many"};
|
||||
}
|
||||
const ban = {key, address: text, reason: reasonText(reason), by, createdAt: now()};
|
||||
db().prepare("INSERT INTO address_bans (address_key, address, reason, by, created_at) VALUES (?, ?, ?, ?, ?)").run(key, ban.address, ban.reason, by, ban.createdAt);
|
||||
banned.set(key, ban);
|
||||
record({address: key, action: "address_ban", seconds: -1, reason: ban.reason, by});
|
||||
return {ban};
|
||||
};
|
||||
|
||||
// `key` as a listing gave it, or any address the ban covers.
|
||||
const unbanAddress = (key, by) => {
|
||||
const ban = banned.get(String(key)) || addressBan(key);
|
||||
if (!ban) {
|
||||
return false;
|
||||
}
|
||||
db().prepare("DELETE FROM address_bans WHERE address_key = ?").run(ban.key);
|
||||
banned.delete(ban.key);
|
||||
record({address: ban.key, action: "address_unban", by});
|
||||
return true;
|
||||
};
|
||||
|
||||
const addressBans = () => [...banned.values()].sort((one, other) => other.createdAt - one.createdAt);
|
||||
|
||||
const appealRow = row => ({
|
||||
accountId: row.account_id,
|
||||
createdAt: row.created_at,
|
||||
username: row.username,
|
||||
text: row.text,
|
||||
addressKey: row.address_key,
|
||||
status: row.status,
|
||||
reply: row.reply,
|
||||
handledAt: row.handled_at,
|
||||
});
|
||||
|
||||
const appealOf = account => {
|
||||
const row = db().prepare("SELECT * FROM appeals WHERE account_id = ?").get(account.id);
|
||||
return row ? appealRow(row) : null;
|
||||
};
|
||||
|
||||
// `addressKey` when it is (also) about the address they wrote from.
|
||||
// returns {appeal} or {error: "empty" | "already"}.
|
||||
const appeal = (account, text, addressKey = "") => {
|
||||
const body = clean(text, MAX_APPEAL);
|
||||
if (!body) {
|
||||
return {error: "empty"};
|
||||
}
|
||||
if (appealOf(account)) {
|
||||
return {error: "already"};
|
||||
}
|
||||
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`);
|
||||
return {appeal: appealOf(account)};
|
||||
};
|
||||
|
||||
// appeals waiting, oldest first; or with `handled`, the latest answered.
|
||||
const appeals = (handled = false) => db()
|
||||
.prepare(handled
|
||||
? "SELECT * FROM appeals WHERE status <> ? ORDER BY handled_at DESC LIMIT 200"
|
||||
: "SELECT * FROM appeals WHERE status = ? ORDER BY created_at LIMIT 500")
|
||||
.all(WAITING).map(appealRow);
|
||||
|
||||
const waitingAppeal = accountId => {
|
||||
const row = db().prepare("SELECT * FROM appeals WHERE account_id = ? AND status = ?").get(Number(accountId), WAITING);
|
||||
return row ? appealRow(row) : null;
|
||||
};
|
||||
|
||||
// the caller lifts the bans when it approves.
|
||||
const answerAppeal = (accountId, approved, reply, by) => {
|
||||
const answered = db().prepare("UPDATE appeals SET status = ?, reply = ?, handled_at = ? WHERE account_id = ? AND status = ?")
|
||||
.run(approved ? APPROVED : DENIED, clean(reply, MAX_REPLY), now(), Number(accountId), WAITING).changes > 0;
|
||||
if (answered) {
|
||||
const account = accounts.byId(Number(accountId));
|
||||
record({account, action: approved ? "appeal_approved" : "appeal_denied", reason: clean(reply, MAX_REPLY), by});
|
||||
}
|
||||
return answered;
|
||||
};
|
||||
|
||||
const openAppeals = () => db().prepare("SELECT COUNT(*) AS count FROM appeals WHERE status = ?").get(WAITING).count;
|
||||
|
||||
// an account being deleted: what it wrote goes with it. the record of what
|
||||
// was done about it stays, under the name it had.
|
||||
const forget = account => {
|
||||
db().prepare("DELETE FROM appeals WHERE account_id = ?").run(account.id);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
load, record, historyOf, addressBan, banAddress, unbanAddress, addressBans, appealOf, appeal, appeals, waitingAppeal, answerAppeal,
|
||||
openAppeals, forget, clean, reasonText, NO_REASON, MAX_REASON, MAX_APPEAL, MAX_REPLY,
|
||||
};
|
||||
@@ -0,0 +1,224 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const achievements = require("./achievements.js");
|
||||
const limits = require("./limits.js");
|
||||
const {activeAvatar} = require("./player.js");
|
||||
|
||||
// buddy lists and blocking (client side: BuddyXtCommManager, BuddyManager).
|
||||
// buddies are mutual and stored on both accounts as lowercased usernames.
|
||||
|
||||
const MAX_BUDDIES = 1337;
|
||||
const MAX_BLOCKED = 1000; // as on the account page (lib/world.js)
|
||||
|
||||
// BuddyManager.buddyAddRequestResponseHandler status codes
|
||||
const REQUEST_INCOMING = 0;
|
||||
const REQUEST_SENT = 1;
|
||||
const REQUEST_TARGET_FULL = 2;
|
||||
const REQUEST_NOT_ACCEPTING = 3;
|
||||
const REQUEST_OWN_LIST_FULL = 4;
|
||||
const REQUEST_UNBLOCK_FIRST = 5;
|
||||
|
||||
// BuddyManager.buddyStatusResponseHandler buddyFlag values
|
||||
const STATUS_UPDATE = 0;
|
||||
const STATUS_ACCEPTED_YOUR_REQUEST = 1;
|
||||
|
||||
const USERNAME_SHOWN = 1; // userNameModeratedFlag: > 0 shows the real name
|
||||
|
||||
// requests waiting for an answer are kept on the asked account, as
|
||||
// `buddyRequests`: lowercased usernames of who asked. someone not in the
|
||||
// game is shown theirs when they next arrive.
|
||||
const MAX_WAITING_REQUESTS = 50;
|
||||
|
||||
const key = account => account.username.toLowerCase();
|
||||
// requests one account may send: enough for anyone making friends, too few
|
||||
// to fill other players' waiting lists with.
|
||||
const requestsPerTenMinutes = limits.limiter(20, 600000);
|
||||
|
||||
// BuddyCard.buddyRoomResponseHandler shows this on the buddy's card: the
|
||||
// name the room goes by on screen. it tells a den by the word "Den" in it,
|
||||
// and reads a hosted party's name as three string ids.
|
||||
const roomTitle = room => room.displayName;
|
||||
|
||||
module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
|
||||
// BuddyXtCommManager.buddyStatusResponse: [1, username, uuid, moderatedFlag,
|
||||
// online, accountType, buddyFlag, avatarName, perUserAvId, partyTimeLeft]
|
||||
const sendStatus = (to, account, buddyFlag) => {
|
||||
const avatar = activeAvatar(account);
|
||||
to.sendXt("bs", -1, 1, account.username, account.uuid, USERNAME_SHOWN, findOnline(account.username) ? 1 : 0,
|
||||
account.accountType, buddyFlag, avatar.name, avatar.perUserAvId, partyTimeLeft(account));
|
||||
};
|
||||
|
||||
const announce = account => {
|
||||
for (const name of account.buddies) {
|
||||
const buddy = findOnline(name);
|
||||
if (buddy) {
|
||||
sendStatus(buddy, account, STATUS_UPDATE);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const hasOnlineBuddies = account => account.buddies.some(name => Boolean(findOnline(name)));
|
||||
|
||||
const handlers = {
|
||||
// BuddyManager.buddyListResponseHandler: [0, onlineCount, (username, uuid,
|
||||
// moderatedFlag, accountType, partyTimeLeft)..., offlineCount, (username,
|
||||
// uuid, moderatedFlag, accountType)...], then blockedListResponseHandler:
|
||||
// [1, count, username...]
|
||||
bl(session) {
|
||||
const buddies = session.account.buddies.map(accounts.byName).filter(Boolean);
|
||||
const online = buddies.filter(buddy => findOnline(buddy.username));
|
||||
const offline = buddies.filter(buddy => !findOnline(buddy.username));
|
||||
session.sendXt("bl", -1, 0,
|
||||
online.length, ...online.flatMap(buddy => [buddy.username, buddy.uuid, USERNAME_SHOWN, buddy.accountType, partyTimeLeft(buddy)]),
|
||||
offline.length, ...offline.flatMap(buddy => [buddy.username, buddy.uuid, USERNAME_SHOWN, buddy.accountType]));
|
||||
session.sendXt("bl", -1, 1, session.account.blocked.length, ...session.account.blocked);
|
||||
// for the patched buddy list (gui.itemWindows.ItemWindowBuddyList):
|
||||
// when each offline buddy was last seen, as [count, (username, seconds)...].
|
||||
session.sendXt("xls", -1, offline.length, ...offline.flatMap(buddy => [buddy.username, buddy.lastSeen || buddy.lastLogin || 0]));
|
||||
},
|
||||
|
||||
// [username]: ask someone to be a buddy. the requester and the target each
|
||||
// get a "ba" (buddyAddRequestResponse: [status, username, moderatedFlag]).
|
||||
ba(session, roomId, [username]) {
|
||||
const {account} = session;
|
||||
const target = accounts.byName(username);
|
||||
const targetSession = target && findOnline(target.username);
|
||||
const reply = status => session.sendXt("ba", -1, status, target ? target.username : username, USERNAME_SHOWN);
|
||||
if (!target || target === account || target.blocked.includes(key(account))
|
||||
|| !accounts.featureOn(account, "buddies") || !accounts.featureOn(target, "buddies")
|
||||
|| (!target.buddyRequests.includes(key(account)) && target.buddyRequests.length >= MAX_WAITING_REQUESTS)) {
|
||||
reply(REQUEST_NOT_ACCEPTING);
|
||||
}
|
||||
else if (account.blocked.includes(key(target))) {
|
||||
reply(REQUEST_UNBLOCK_FIRST);
|
||||
}
|
||||
else if (account.buddies.length >= MAX_BUDDIES) {
|
||||
reply(REQUEST_OWN_LIST_FULL);
|
||||
}
|
||||
else if (target.buddies.length >= MAX_BUDDIES) {
|
||||
reply(REQUEST_TARGET_FULL);
|
||||
}
|
||||
else if (!account.buddies.includes(key(target)) && !target.buddyRequests.includes(key(account)) && !requestsPerTenMinutes.allow(account.id)) {
|
||||
reply(REQUEST_NOT_ACCEPTING);
|
||||
}
|
||||
else if (!account.buddies.includes(key(target))) {
|
||||
if (!target.buddyRequests.includes(key(account))) {
|
||||
target.buddyRequests.push(key(account));
|
||||
accounts.save();
|
||||
}
|
||||
if (targetSession) {
|
||||
targetSession.sendXt("ba", -1, REQUEST_INCOMING, account.username, USERNAME_SHOWN);
|
||||
}
|
||||
reply(REQUEST_SENT);
|
||||
}
|
||||
},
|
||||
|
||||
// [username, "1" accept | "0" decline]: answer a pending request.
|
||||
bc(session, roomId, [username, accept]) {
|
||||
const {account} = session;
|
||||
const requester = accounts.byName(username);
|
||||
if (!requester || !account.buddyRequests.includes(key(requester))) {
|
||||
return;
|
||||
}
|
||||
account.buddyRequests = account.buddyRequests.filter(name => name !== key(requester));
|
||||
accounts.save();
|
||||
const requesterSession = findOnline(requester.username);
|
||||
if (accept !== "1" || account.buddies.includes(key(requester))
|
||||
|| account.buddies.length >= MAX_BUDDIES || requester.buddies.length >= MAX_BUDDIES) {
|
||||
if (requesterSession) {
|
||||
requesterSession.sendXt("ba", -1, REQUEST_NOT_ACCEPTING, account.username, USERNAME_SHOWN);
|
||||
}
|
||||
return;
|
||||
}
|
||||
account.buddies.push(key(requester));
|
||||
requester.buddies.push(key(account));
|
||||
achievements.add(account, achievements.VARS.buddiesAdded);
|
||||
achievements.add(requester, achievements.VARS.buddiesAdded);
|
||||
accounts.save();
|
||||
sendStatus(session, requester, STATUS_UPDATE);
|
||||
if (requesterSession) {
|
||||
sendStatus(requesterSession, account, STATUS_ACCEPTED_YOUR_REQUEST);
|
||||
}
|
||||
},
|
||||
|
||||
// [username]: end a buddyship. both sides get a "bd" naming the other.
|
||||
bd(session, roomId, [username]) {
|
||||
const {account} = session;
|
||||
const other = accounts.byName(username);
|
||||
if (other) {
|
||||
account.buddies = account.buddies.filter(name => name !== key(other));
|
||||
other.buddies = other.buddies.filter(name => name !== key(account));
|
||||
accounts.save();
|
||||
const otherSession = findOnline(other.username);
|
||||
if (otherSession) {
|
||||
otherSession.sendXt("bd", -1, account.username);
|
||||
}
|
||||
}
|
||||
session.sendXt("bd", -1, other ? other.username : username);
|
||||
},
|
||||
|
||||
// BuddyManager.buddyBlockResponseHandler: [username, success]
|
||||
bb(session, roomId, [username]) {
|
||||
const {account} = session;
|
||||
const other = accounts.byName(username);
|
||||
const added = other && other !== account && !account.blocked.includes(key(other)) && account.blocked.length < MAX_BLOCKED;
|
||||
if (added) {
|
||||
account.blocked.push(key(other));
|
||||
accounts.save();
|
||||
}
|
||||
session.sendXt("bb", -1, username, other && other !== account && account.blocked.includes(key(other)) ? 1 : 0);
|
||||
if (added) {
|
||||
onBlocked(session, other);
|
||||
}
|
||||
},
|
||||
|
||||
bu(session, roomId, [username]) {
|
||||
const {account} = session;
|
||||
const other = accounts.byName(username);
|
||||
const removed = other && account.blocked.includes(key(other));
|
||||
account.blocked = account.blocked.filter(name => name !== String(username).toLowerCase());
|
||||
accounts.save();
|
||||
session.sendXt("bu", -1, username, 1);
|
||||
if (removed) {
|
||||
onUnblocked(session, other);
|
||||
}
|
||||
},
|
||||
|
||||
// [username]: is that player blocking me?
|
||||
bi(session, roomId, [username]) {
|
||||
const other = accounts.byName(username);
|
||||
session.sendXt("bi", -1, username, other && other.blocked.includes(key(session.account)) ? 1 : 0);
|
||||
},
|
||||
|
||||
// [username]: where is that player? BuddyCard.buddyRoomResponseHandler
|
||||
// gets [roomName, displayName, displayNameStringId, cannotGoThere]; an
|
||||
// empty room means offline. the last field greys out the card's "go to"
|
||||
// button (BuddyCard.checkBuddyRoomAgainstMine), so it is 0: every room
|
||||
// here can be walked into. someone who blocked the asker looks offline.
|
||||
br(session, roomId, [username]) {
|
||||
const target = findOnline(username);
|
||||
if (target && target.room && !target.account.blocked.includes(key(session.account))) {
|
||||
session.sendXt("br", -1, target.room.name, roomTitle(target.room), 0, 0);
|
||||
}
|
||||
else {
|
||||
session.sendXt("br", -1, "", "", 0, 0);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// shows a player who has just arrived the requests made while they were
|
||||
// away. they stay on the account until answered, so one the player did
|
||||
// not get to is asked again next time.
|
||||
const greet = session => {
|
||||
const {account} = session;
|
||||
const waiting = account.buddyRequests.map(accounts.byName)
|
||||
.filter(requester => requester && !account.buddies.includes(key(requester)) && !account.blocked.includes(key(requester)));
|
||||
account.buddyRequests = waiting.map(key);
|
||||
for (const requester of waiting) {
|
||||
session.sendXt("ba", -1, REQUEST_INCOMING, requester.username, USERNAME_SHOWN);
|
||||
}
|
||||
};
|
||||
|
||||
return {handlers, announce, hasOnlineBuddies, greet};
|
||||
};
|
||||
@@ -0,0 +1,369 @@
|
||||
"use strict";
|
||||
|
||||
// the eight games two buddies play against each other from a player's card
|
||||
// (client side: game.pVP_*). each has a protocol of its own, which the
|
||||
// official server spoke and nothing else records; what is here was read off
|
||||
// each game's `message` method and the code inside its scene file (the
|
||||
// "theGame" layer of roomDefs/pvp_*/room_main).
|
||||
//
|
||||
// half of them the server referees, since the clients only draw what they
|
||||
// are told: Tic Tac Toe, Four Gems, Rock Paper Scissors, the Shell Game and
|
||||
// Pairs. the other half run on both clients at once, each simulating the
|
||||
// same thing from the same inputs, and the server only passes the inputs
|
||||
// across and says when both are ready to go on: Bowling, Marbles, Scooped.
|
||||
//
|
||||
// A game here is given `match`: {ids: [sfsUserId, sfsUserId] in the order
|
||||
// of the start message, send(player, ...fields), broadcast(...fields),
|
||||
// over()} and keeps what it likes on `match.state`. `player` is 0 or 1.
|
||||
// every handler is entered with words that came from a client, so each
|
||||
// checks what it is given; a message that makes no sense is dropped.
|
||||
|
||||
const other = player => 1 - player;
|
||||
const coin = () => (Math.random() < 0.5 ? 0 : 1);
|
||||
const whole = (text, min, max) => {
|
||||
const value = /^-?\d{1,9}$/.test(String(text)) ? Number(text) : NaN;
|
||||
return Number.isInteger(value) && value >= min && value <= max ? value : null;
|
||||
};
|
||||
const number = text => {
|
||||
const value = /^-?\d{1,7}(\.\d{1,20})?(e-?\d{1,3})?$/i.test(String(text)) ? Number(text) : NaN;
|
||||
return Number.isFinite(value) ? value : null;
|
||||
};
|
||||
const ROUNDS_TO_WIN = 2; // Rock Paper Scissors and the Shell Game: first to win two rounds
|
||||
|
||||
// is there a run of `length` of `player`'s marks through (x, y)? `at(x, y)`
|
||||
// gives who holds a cell, undefined off the board.
|
||||
const DIRECTIONS = [[1, 0], [0, 1], [1, 1], [1, -1]];
|
||||
const hasLine = (at, x, y, player, length) => DIRECTIONS.some(([dx, dy]) => {
|
||||
let run = 1;
|
||||
for (const sign of [1, -1]) {
|
||||
for (let step = 1; at(x + sign * step * dx, y + sign * step * dy) === player; step++) {
|
||||
run++;
|
||||
}
|
||||
}
|
||||
return run >= length;
|
||||
});
|
||||
|
||||
// tic Tac Toe and Four Gems share their messages: "round" [whose turn, the
|
||||
// two players] opens, a "mark" is answered to both with [who, where..., won,
|
||||
// tied, whose turn next], and "invalid" [whose turn] hands the turn on
|
||||
// after a move that cannot be made or a turn that ran out of time. the
|
||||
// first player of the start message plays X.
|
||||
const boardGame = ({width, height, connect, cellOf}) => ({
|
||||
ready(match) {
|
||||
match.state = {cells: new Map(), turn: coin()};
|
||||
match.broadcast("round", match.state.turn, ...match.ids);
|
||||
},
|
||||
messages: {
|
||||
mark(match, player, params) {
|
||||
const {state} = match;
|
||||
const at = (x, y) => state.cells.get(`${x},${y}`);
|
||||
const cell = state && player === state.turn ? cellOf(params, at) : null;
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
if (!cell || cell.x < 0 || cell.x >= width || cell.y < 0 || cell.y >= height || at(cell.x, cell.y) !== undefined) {
|
||||
match.send(player, "invalid", state.turn);
|
||||
return;
|
||||
}
|
||||
state.cells.set(`${cell.x},${cell.y}`, player);
|
||||
const won = hasLine(at, cell.x, cell.y, player, connect);
|
||||
const tied = !won && state.cells.size === width * height;
|
||||
state.turn = won || tied ? state.turn : other(player);
|
||||
match.broadcast("mark", player, ...cell.sent, won ? 1 : 0, tied ? 1 : 0, state.turn);
|
||||
if (won || tied) {
|
||||
match.over();
|
||||
}
|
||||
},
|
||||
time(match, player) {
|
||||
const {state} = match;
|
||||
if (state && player === state.turn) {
|
||||
state.turn = other(player);
|
||||
match.broadcast("invalid", state.turn);
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const ticTacToe = boardGame({
|
||||
width: 3, height: 3, connect: 3,
|
||||
// [x, y], each 0 to 2 (the scene's cells are p<x>_<y>)
|
||||
cellOf([x, y]) {
|
||||
const cell = {x: whole(x, 0, 2), y: whole(y, 0, 2)};
|
||||
return cell.x === null || cell.y === null ? null : {...cell, sent: [cell.x, cell.y]};
|
||||
},
|
||||
});
|
||||
|
||||
const fourGems = boardGame({
|
||||
width: 7, height: 6, connect: 4,
|
||||
// [column], 0 to 6; the gem drops to the lowest free row
|
||||
cellOf([column], at) {
|
||||
const x = whole(column, 0, 6);
|
||||
if (x === null) {
|
||||
return null;
|
||||
}
|
||||
let y = 0;
|
||||
while (y < 6 && at(x, y) !== undefined) {
|
||||
y++;
|
||||
}
|
||||
return {x, y, sent: [x]};
|
||||
},
|
||||
});
|
||||
|
||||
// Rock Paper Scissors and the Shell Game: no turns. "round" starts the
|
||||
// clock on both clients; when it runs out each says "time" with what its
|
||||
// player picked, and both are told "mark" [first player's pick, second
|
||||
// player's pick, then "1", winner when the game is over, or "0", "1",
|
||||
// winner when only the round is won, or "0", "0" for a round nobody won].
|
||||
// both clients ask for the next round by saying "ready" again.
|
||||
const pickGame = ({startRound, read, roundWinner}) => ({
|
||||
ready(match) {
|
||||
match.state = match.state || {wins: [0, 0]};
|
||||
match.state.picks = [undefined, undefined];
|
||||
match.state.round = startRound();
|
||||
match.broadcast("round", ...match.ids, ...match.state.round.sent);
|
||||
},
|
||||
messages: {
|
||||
time(match, player, params) {
|
||||
const {state} = match;
|
||||
if (!state || state.picks[player] !== undefined) {
|
||||
return;
|
||||
}
|
||||
state.picks[player] = read(params[0]);
|
||||
if (state.picks[other(player)] === undefined) {
|
||||
return;
|
||||
}
|
||||
const winner = roundWinner(state.picks, state.round);
|
||||
if (winner === null) {
|
||||
match.broadcast("mark", ...state.picks, 0, 0);
|
||||
return;
|
||||
}
|
||||
state.wins[winner]++;
|
||||
if (state.wins[winner] >= ROUNDS_TO_WIN) {
|
||||
match.broadcast("mark", ...state.picks, 1, winner);
|
||||
match.over();
|
||||
}
|
||||
else {
|
||||
match.broadcast("mark", ...state.picks, 0, 1, winner);
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const HANDS = ["rock", "paper", "scissors"]; // each beats the one before it
|
||||
const NO_HAND = "off"; // nothing picked in time
|
||||
const rockPaperScissors = pickGame({
|
||||
startRound: () => ({sent: []}),
|
||||
read: hand => (HANDS.includes(hand) ? hand : NO_HAND),
|
||||
roundWinner([first, second]) {
|
||||
if (first === second) {
|
||||
return null;
|
||||
}
|
||||
if (first === NO_HAND || second === NO_HAND) {
|
||||
return first === NO_HAND ? 1 : 0;
|
||||
}
|
||||
return (HANDS.indexOf(first) - HANDS.indexOf(second) + 3) % 3 === 1 ? 0 : 1;
|
||||
},
|
||||
});
|
||||
|
||||
// the round opens with which of the three shells hides the gem; a pick is
|
||||
// 1 to 3, 0 for none. whoever is right when the other is wrong wins the round.
|
||||
const SHELLS = 3;
|
||||
const shellGame = pickGame({
|
||||
startRound() {
|
||||
const shell = 1 + Math.floor(Math.random() * SHELLS);
|
||||
return {shell, sent: [shell]};
|
||||
},
|
||||
read: pick => whole(pick, 1, SHELLS) || 0,
|
||||
roundWinner([first, second], {shell}) {
|
||||
return (first === shell) === (second === shell) ? null : first === shell ? 0 : 1;
|
||||
},
|
||||
});
|
||||
|
||||
// pairs: sixteen cards, four to a row, numbered 0 to 15 along the rows. A
|
||||
// card's picture is its number in the list of 1 to 16, two of which make a
|
||||
// pair when they differ by 8 (the scene folds 9-16 onto 1-8). "round" names
|
||||
// the player who starts first, then the other, then the cards. the player
|
||||
// whose turn it is turns up two ("c1", "c2", which the other is shown), both
|
||||
// are told "results" [0, matched] and say "rp" when they have watched it,
|
||||
// and "nextround" lets the game go on: the same player again after a match,
|
||||
// the other after a miss or a "time". the last pair brings "results" [1,
|
||||
// winner's id, 0 for a draw].
|
||||
const CARDS = 16;
|
||||
const pairs = {
|
||||
ready(match) {
|
||||
const cards = Array.from({length: CARDS}, (_, index) => index + 1);
|
||||
for (let index = cards.length - 1; index > 0; index--) {
|
||||
const swap = Math.floor(Math.random() * (index + 1));
|
||||
[cards[index], cards[swap]] = [cards[swap], cards[index]];
|
||||
}
|
||||
match.state = {cards, gone: new Set(), turn: coin(), first: null, found: [0, 0], watched: new Set(), showing: false};
|
||||
match.broadcast("round", match.ids[match.state.turn], match.ids[other(match.state.turn)], CARDS, ...cards);
|
||||
},
|
||||
messages: {
|
||||
c1(match, player, [card]) {
|
||||
const {state} = match;
|
||||
const index = whole(card, 0, CARDS - 1);
|
||||
if (state && !state.showing && player === state.turn && state.first === null && index !== null && !state.gone.has(index)) {
|
||||
state.first = index;
|
||||
match.send(other(player), "c1", index);
|
||||
}
|
||||
},
|
||||
c2(match, player, [card]) {
|
||||
const {state} = match;
|
||||
const index = whole(card, 0, CARDS - 1);
|
||||
if (!state || state.showing || player !== state.turn || state.first === null || index === null || index === state.first || state.gone.has(index)) {
|
||||
return;
|
||||
}
|
||||
match.send(other(player), "c2", index);
|
||||
const matched = (state.cards[index] - state.cards[state.first]) % (CARDS / 2) === 0;
|
||||
if (matched) {
|
||||
state.gone.add(index).add(state.first);
|
||||
state.found[player]++;
|
||||
}
|
||||
else {
|
||||
state.turn = other(player);
|
||||
}
|
||||
state.first = null;
|
||||
if (state.gone.size === CARDS) {
|
||||
const [mine, theirs] = [state.found[player], state.found[other(player)]];
|
||||
match.broadcast("results", 1, mine === theirs ? 0 : match.ids[mine > theirs ? player : other(player)]);
|
||||
match.over();
|
||||
return;
|
||||
}
|
||||
state.showing = true;
|
||||
state.watched.clear();
|
||||
match.broadcast("results", 0, matched ? 1 : 0);
|
||||
},
|
||||
time(match, player) {
|
||||
const {state} = match;
|
||||
if (state && !state.showing && player === state.turn) {
|
||||
state.turn = other(player);
|
||||
state.first = null;
|
||||
state.showing = true;
|
||||
state.watched.clear();
|
||||
match.broadcast("time");
|
||||
}
|
||||
},
|
||||
rp(match, player) {
|
||||
const {state} = match;
|
||||
if (state && state.showing && state.watched.add(player).size === 2) {
|
||||
state.showing = false;
|
||||
match.broadcast("nextround");
|
||||
}
|
||||
},
|
||||
emote: relayEmote,
|
||||
},
|
||||
};
|
||||
|
||||
// the little faces Pairs and Bowling let players pull at each other.
|
||||
function relayEmote(match, player, [emote]) {
|
||||
const face = whole(emote, 0, 1000);
|
||||
if (face !== null) {
|
||||
match.send(other(player), "emote", face);
|
||||
}
|
||||
}
|
||||
|
||||
// Scooped: a race to build the same ice creams, the order of which both
|
||||
// clients work out from the start message. each scoop is shown to the
|
||||
// other player ("sc_click" and the name of the button pressed); whoever
|
||||
// says "sc_done" first has won, and both are told who.
|
||||
const scooped = {
|
||||
ready(match) {
|
||||
match.state = {done: false};
|
||||
match.broadcast("start");
|
||||
},
|
||||
messages: {
|
||||
sc_click(match, player, [button]) {
|
||||
if (match.state && !match.state.done && /^[A-Za-z]\w{0,30}$/.test(String(button))) {
|
||||
match.send(other(player), "sc_click", button);
|
||||
}
|
||||
},
|
||||
sc_done(match, player) {
|
||||
if (match.state && !match.state.done) {
|
||||
match.state.done = true;
|
||||
match.broadcast("sc_done", player);
|
||||
match.over();
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Bowling: both clients roll every ball through the same simulation, the
|
||||
// thrower's own and the other from the "ball" [angle, x, y] passed across.
|
||||
// "round" names who bowls first. after each ball both say "rp" and are let
|
||||
// on with "nextround"; a thrower who ran out of time says "time", which
|
||||
// both are told. they keep the score and end the game themselves.
|
||||
const bowling = {
|
||||
ready(match) {
|
||||
const first = coin();
|
||||
match.state = {watched: new Set()};
|
||||
match.broadcast("round", match.ids[first], match.ids[other(first)]);
|
||||
},
|
||||
messages: {
|
||||
ball(match, player, params) {
|
||||
const shot = params.slice(0, 3).map(number);
|
||||
if (match.state && shot.length === 3 && !shot.includes(null)) {
|
||||
match.send(other(player), "ball", ...shot);
|
||||
}
|
||||
},
|
||||
time(match) {
|
||||
if (match.state) {
|
||||
match.broadcast("time");
|
||||
}
|
||||
},
|
||||
rp(match, player) {
|
||||
if (match.state && match.state.watched.add(player).size === 2) {
|
||||
match.state.watched.clear();
|
||||
match.broadcast("nextround");
|
||||
}
|
||||
},
|
||||
emote: relayEmote,
|
||||
},
|
||||
};
|
||||
|
||||
// marbles: the same arrangement. the start message picks one of the
|
||||
// fourteen ways the marbles are laid out; "start" says who shoots first
|
||||
// (as a place in the start message's list of players); the shooter's aim
|
||||
// ("pos") and shot ("shoot" [from x, from y, force x, force y]) are passed
|
||||
// to the other; and when both have said "endTurn", their marbles at rest,
|
||||
// both are told so and change turns.
|
||||
const MARBLE_PATTERNS = 14;
|
||||
const marbles = {
|
||||
startData: () => [1 + Math.floor(Math.random() * MARBLE_PATTERNS)],
|
||||
ready(match) {
|
||||
match.state = {rested: new Set()};
|
||||
match.broadcast("start", coin());
|
||||
},
|
||||
messages: {
|
||||
pos(match, player, params) {
|
||||
const spot = params.slice(0, 2).map(value => whole(value, -10000, 10000));
|
||||
if (match.state && spot.length === 2 && !spot.includes(null)) {
|
||||
match.send(other(player), "pos", ...spot);
|
||||
}
|
||||
},
|
||||
shoot(match, player, params) {
|
||||
const shot = params.slice(0, 4).map(number);
|
||||
if (match.state && shot.length === 4 && !shot.includes(null)) {
|
||||
match.send(other(player), "shoot", ...shot);
|
||||
}
|
||||
},
|
||||
endTurn(match, player) {
|
||||
if (match.state && match.state.rested.add(player).size === 2) {
|
||||
match.state.rested.clear();
|
||||
match.broadcast("endTurn");
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// by the game's key in game.IncludeMinigames (`swf` in lib/games.json).
|
||||
module.exports = {
|
||||
PVP_TicTacToe: ticTacToe,
|
||||
PVP_ConnectFour: fourGems,
|
||||
PVP_RockPaperScissor: rockPaperScissors,
|
||||
PVP_ShellGame: shellGame,
|
||||
PVP_Memory: pairs,
|
||||
PVP_Scooped: scooped,
|
||||
PVP_Bowling: bowling,
|
||||
PVP_Marbles: marbles,
|
||||
};
|
||||
@@ -0,0 +1,120 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const config = require("../config.js");
|
||||
const limits = require("./limits.js");
|
||||
|
||||
// cloudflare turnstile, with AJ_TURNSTILE_SITE_KEY and AJ_TURNSTILE_SECRET
|
||||
// set: a captcha before every password tried (the client's login, the
|
||||
// account page, the moderator panel) and every account made (the sign-up
|
||||
// page, the client). a saved sign-in is not asked. the page shows the
|
||||
// widget (public/captcha.js) and sends its answer as `captcha`; the answer
|
||||
// is checked here with cloudflare, and is good for one request.
|
||||
//
|
||||
// a sign-in that passed the captcha and then wants a 2FA code, and a
|
||||
// sign-up the client signs in with straight after, get a pass: good for
|
||||
// that account from that address for a few minutes, so the second request
|
||||
// is not asked again.
|
||||
|
||||
const ORIGIN = "https://challenges.cloudflare.com";
|
||||
const VERIFY_URL = `${ORIGIN}/turnstile/v0/siteverify`;
|
||||
const VERIFY_TIMEOUT_MS = 10000;
|
||||
const MAX_ANSWER_LENGTH = 2048;
|
||||
const PASS_MS = 600000;
|
||||
const PASS_USES = 5;
|
||||
const MAX_PASSES = 10000;
|
||||
|
||||
const on = Boolean(config.turnstile);
|
||||
const passes = new Map(); // SHA-256 of a pass -> {id: account id, key: address key, expiry, uses}
|
||||
const sha256 = text => crypto.createHash("sha256").update(String(text)).digest("hex");
|
||||
|
||||
// for the pages: what each answer means
|
||||
const MESSAGES = {
|
||||
captcha_required: "Complete the captcha.",
|
||||
captcha_failed: "Captcha failed. Try again.",
|
||||
captcha_unavailable: "Captcha unavailable. Try again later.",
|
||||
};
|
||||
|
||||
const issuePass = (account, from) => {
|
||||
if (!on || !account) {
|
||||
return undefined;
|
||||
}
|
||||
for (const [hash, entry] of passes) {
|
||||
if (entry.expiry < Date.now() || passes.size >= MAX_PASSES) {
|
||||
passes.delete(hash);
|
||||
}
|
||||
}
|
||||
const pass = crypto.randomBytes(24).toString("hex");
|
||||
passes.set(sha256(pass), {id: account.id, key: from.key, expiry: Date.now() + PASS_MS, uses: 0});
|
||||
return pass;
|
||||
};
|
||||
|
||||
const passHolds = (pass, account, from) => {
|
||||
if (typeof pass !== "string" || !account) {
|
||||
return false;
|
||||
}
|
||||
const hash = sha256(pass);
|
||||
const entry = passes.get(hash);
|
||||
if (!entry || entry.expiry < Date.now() || entry.id !== account.id || entry.key !== from.key || ++entry.uses > PASS_USES) {
|
||||
passes.delete(hash);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
// asks cloudflare about one answer of the widget. null when it was a person.
|
||||
const verify = async (answer, from, action) => {
|
||||
if (typeof answer !== "string" || !answer || answer.length > MAX_ANSWER_LENGTH) {
|
||||
return "captcha_required";
|
||||
}
|
||||
const form = new URLSearchParams({secret: config.turnstile.secret, response: answer});
|
||||
if (!limits.isLoopback(from.address)) {
|
||||
form.set("remoteip", from.address);
|
||||
}
|
||||
let result;
|
||||
try {
|
||||
const response = await fetch(VERIFY_URL, {method: "POST", body: form, signal: AbortSignal.timeout(VERIFY_TIMEOUT_MS)});
|
||||
result = await response.json();
|
||||
}
|
||||
catch (err) {
|
||||
console.log(`[captcha] cloudflare did not answer: ${err.message}`);
|
||||
return "captcha_unavailable";
|
||||
}
|
||||
// an answer made for another form is no answer for this one. cloudflare's
|
||||
// test keys give none.
|
||||
if (!result || result.success !== true || (result.action && result.action !== action)) {
|
||||
return "captcha_failed";
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// null when the request may go on, or why not (a key of MESSAGES).
|
||||
// `account`, when known, is who a pass would have to be for. requests from
|
||||
// the server's own machine are not asked, as with the other limits.
|
||||
const check = async (body, from, action, account) => {
|
||||
if (!on || from.local) {
|
||||
return null;
|
||||
}
|
||||
if (passHolds(body.captcha_pass, account, from)) {
|
||||
return null;
|
||||
}
|
||||
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 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
|
||||
// server says, and a browser would go on with an old one.
|
||||
const withScriptVersion = html => {
|
||||
const version = sha256(fs.readFileSync(path.join(config.publicDir, "captcha.js")) + (on ? config.turnstile.siteKey : "")).slice(0, 12);
|
||||
return Buffer.from(String(html).replace("src=\"/captcha.js\"", `src="/captcha.js?v=${version}"`));
|
||||
};
|
||||
|
||||
// public/captcha.js with the site key in it ("" when off).
|
||||
const script = text => text.replace("\"{{siteKey}}\"", JSON.stringify(on ? config.turnstile.siteKey : ""));
|
||||
|
||||
module.exports = {on, check, issuePass, policy, script, withScriptVersion, MESSAGES};
|
||||
@@ -0,0 +1,174 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const config = require("../config.js");
|
||||
|
||||
// mirrors LoaderCache.hashItV2 in the client: the last path component of every
|
||||
// versioned asset is obfuscated this way before it is requested.
|
||||
const hashName = name => {
|
||||
const salted = "W3 7r4Ck h4X0r3rs" + name;
|
||||
let out = "";
|
||||
for (let i = 0; i < salted.length; i++) {
|
||||
out = i % 2 === 0 ? out + salted[i] : salted[i] + out;
|
||||
}
|
||||
return crypto.createHash("md5").update(out).digest("hex");
|
||||
};
|
||||
|
||||
// "defPacks/1003" -> "1830/defPacks/<hash>"
|
||||
const hashedPath = assetPath => {
|
||||
const parts = assetPath.split("/");
|
||||
parts.push(hashName(parts.pop()));
|
||||
return `${config.deployVersion}/${parts.join("/")}`;
|
||||
};
|
||||
|
||||
const missing = new Set();
|
||||
const inFlight = new Map();
|
||||
|
||||
// asset paths are short and plain; anything else is not worth asking the
|
||||
// upstream CDN about on a stranger's behalf.
|
||||
const ASSET_PATH = /^[A-Za-z0-9_.\-\/]{1,200}$/;
|
||||
const MAX_MISSING = 20000;
|
||||
const MAX_DOWNLOADS = 64; // at once
|
||||
|
||||
// the builds this server has any use for: the one the game runs on, the
|
||||
// older ones room files are taken from, and the themes' (config.js). the
|
||||
// official CDN holds a good deal more under other names (every other build,
|
||||
// and two folders of players' own data); none of that is fetched, kept or
|
||||
// handed on for anyone.
|
||||
const BUILDS = new Set([config.deployVersion, ...config.olderBuilds, ...Object.values(config.themes).map(theme => theme.build)].map(String));
|
||||
|
||||
// the path as it is kept and asked for: "a/./b" and "a//b" are "a/b", and
|
||||
// nothing climbs out of its build. null for a path that is not an asset's.
|
||||
const clean = relPath => {
|
||||
if (typeof relPath !== "string" || !ASSET_PATH.test(relPath)) {
|
||||
return null;
|
||||
}
|
||||
const parts = relPath.split("/").filter(part => part !== "" && part !== ".");
|
||||
return parts.length >= 2 && !parts.includes("..") && BUILDS.has(parts[0]) ? parts.join("/") : null;
|
||||
};
|
||||
|
||||
const cacheFile = relPath => {
|
||||
const file = path.join(config.cacheDir, relPath);
|
||||
return file.startsWith(config.cacheDir + path.sep) ? file : null;
|
||||
};
|
||||
|
||||
// how much the cache holds: counted once at start (in the background), then
|
||||
// kept up as files are added.
|
||||
let cacheBytes = 0;
|
||||
const measure = async folder => {
|
||||
for (const entry of await fs.promises.readdir(folder, {withFileTypes: true}).catch(() => [])) {
|
||||
if (entry.isDirectory()) {
|
||||
await measure(path.join(folder, entry.name));
|
||||
}
|
||||
else {
|
||||
cacheBytes += (await fs.promises.stat(path.join(folder, entry.name)).catch(() => ({size: 0}))).size;
|
||||
}
|
||||
}
|
||||
};
|
||||
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)`);
|
||||
}
|
||||
});
|
||||
|
||||
const download = async (relPath, file) => {
|
||||
const url = new URL(relPath, config.upstreamContent);
|
||||
url.searchParams.set("v", config.upstreamBuildVersion);
|
||||
const res = await fetch(url, {headers: {"User-Agent": "Mozilla/5.0"}, signal: AbortSignal.timeout(config.upstreamTimeoutMs)});
|
||||
if (!res.ok) {
|
||||
if (res.status === 404 || res.status === 403) {
|
||||
if (missing.size >= MAX_MISSING) {
|
||||
missing.clear();
|
||||
}
|
||||
missing.add(relPath);
|
||||
}
|
||||
console.log(`[cdn] ${res.status} ${relPath}`);
|
||||
return null;
|
||||
}
|
||||
const body = Buffer.from(await res.arrayBuffer());
|
||||
// A cache that cannot be written to (wrong owner, full disk) costs a
|
||||
// download each time; it must not cost the player the file.
|
||||
try {
|
||||
if (cacheBytes + body.length > config.maxCacheBytes) {
|
||||
return body;
|
||||
}
|
||||
cacheBytes += body.length;
|
||||
await fs.promises.mkdir(path.dirname(file), {recursive: true});
|
||||
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)`);
|
||||
}
|
||||
catch (err) {
|
||||
console.log(`[cdn] could not cache ${relPath}: ${err.message}`);
|
||||
}
|
||||
return body;
|
||||
};
|
||||
|
||||
// `mayFetch`: may a file that is not in the cache be asked of the official
|
||||
// CDN for this request? (Whoever asks for too many is given only what is
|
||||
// there already: lib/http.js.)
|
||||
const getExact = async (asked, mayFetch = () => true) => {
|
||||
const relPath = clean(asked);
|
||||
const file = relPath && cacheFile(relPath);
|
||||
if (!file) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return await fs.promises.readFile(file);
|
||||
}
|
||||
catch (err) {
|
||||
if (err.code !== "ENOENT" && err.code !== "EISDIR" && err.code !== "ENOTDIR") {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
if (config.offline || missing.has(relPath)) {
|
||||
return null;
|
||||
}
|
||||
if (!inFlight.has(relPath) && (inFlight.size >= MAX_DOWNLOADS || !mayFetch())) {
|
||||
return null;
|
||||
}
|
||||
if (!inFlight.has(relPath)) {
|
||||
// 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}`);
|
||||
return null;
|
||||
}).finally(() => inFlight.delete(relPath)));
|
||||
}
|
||||
return inFlight.get(relPath);
|
||||
};
|
||||
|
||||
// returns the asset's bytes, or null when it does not exist. A room file the
|
||||
// current build no longer has is looked for in the older builds named in
|
||||
// config.olderBuilds (the client asks for everything under the current one).
|
||||
const CURRENT_ROOM_FILE = new RegExp(`^${config.deployVersion}/(roomDefs/.+)$`);
|
||||
const get = async (relPath, mayFetch) => {
|
||||
const body = await getExact(relPath, mayFetch);
|
||||
const room = body ? null : CURRENT_ROOM_FILE.exec(clean(relPath) || "");
|
||||
if (room) {
|
||||
for (const build of config.olderBuilds) {
|
||||
const older = await getExact(`${build}/${room[1]}`, mayFetch);
|
||||
if (older) {
|
||||
return older;
|
||||
}
|
||||
}
|
||||
}
|
||||
return body;
|
||||
};
|
||||
|
||||
// the asset's bytes if it is already in the cache, else null; never downloads.
|
||||
const cached = async asked => {
|
||||
const relPath = clean(asked);
|
||||
const file = relPath && cacheFile(relPath);
|
||||
try {
|
||||
return file ? await fs.promises.readFile(file) : null;
|
||||
}
|
||||
catch (err) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {get, cached, hashName, hashedPath};
|
||||
@@ -0,0 +1,107 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const config = require("../config.js");
|
||||
|
||||
// what players typed: chat in a room, and whispers. kept for the moderator
|
||||
// panel (lib/modpanel.js), which is where a moderator reads what was said
|
||||
// before deciding anything; nothing else reads it. lines older than
|
||||
// config.chatLogDays are deleted, and an account's lines go when the
|
||||
// account is deleted. with chatLogDays 0 nothing is kept at all.
|
||||
|
||||
const SCHEMA = `
|
||||
CREATE TABLE IF NOT EXISTS chat_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
at INTEGER NOT NULL,
|
||||
account_id INTEGER NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
room TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
to_name TEXT NOT NULL DEFAULT '',
|
||||
text TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS chat_log_account ON chat_log (account_id, id);
|
||||
CREATE INDEX IF NOT EXISTS chat_log_room ON chat_log (room, id);
|
||||
`;
|
||||
|
||||
const CHAT = "chat";
|
||||
const WHISPER = "whisper";
|
||||
const DAY_SECONDS = 86400;
|
||||
const MAX_TEXT = 600;
|
||||
const PAGE = 100;
|
||||
const AROUND = 25; // lines before and after the one asked about
|
||||
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
const db = () => accounts.database();
|
||||
|
||||
const prune = () => {
|
||||
db().prepare("DELETE FROM chat_log WHERE at < ?").run(now() - config.chatLogDays * DAY_SECONDS);
|
||||
};
|
||||
|
||||
const load = () => {
|
||||
db().exec(SCHEMA);
|
||||
prune();
|
||||
setInterval(prune, DAY_SECONDS * 1000 / 4).unref();
|
||||
};
|
||||
|
||||
// A line said in `room` (its name as the world knows it), or with `to` a
|
||||
// whisper to that player.
|
||||
const record = (account, room, text, to = "") => {
|
||||
if (config.chatLogDays <= 0) {
|
||||
return;
|
||||
}
|
||||
db().prepare("INSERT INTO chat_log (at, account_id, username, room, kind, to_name, text) VALUES (?, ?, ?, ?, ?, ?, ?)")
|
||||
.run(now(), account.id, account.username, String(room || ""), to ? WHISPER : CHAT, to, String(text).slice(0, MAX_TEXT));
|
||||
};
|
||||
|
||||
const row = line => ({id: line.id, at: line.at, username: line.username, room: line.room, whisperTo: line.kind === WHISPER ? line.to_name : "", text: line.text});
|
||||
|
||||
// lines newest first, a page at a time: by who said them (or was whispered
|
||||
// to), by room, by words in them, and `before` an id for the next page.
|
||||
const search = ({username = "", room = "", text = "", before = 0}) => {
|
||||
const where = [];
|
||||
const values = [];
|
||||
if (username) {
|
||||
where.push("(username = ? COLLATE NOCASE OR to_name = ? COLLATE NOCASE)");
|
||||
values.push(username, username);
|
||||
}
|
||||
if (room) {
|
||||
where.push("room LIKE ? ESCAPE '\\'");
|
||||
values.push(`%${room.replace(/[\\%_]/g, "\\$&")}%`);
|
||||
}
|
||||
if (text) {
|
||||
where.push("text LIKE ? ESCAPE '\\'");
|
||||
values.push(`%${text.replace(/[\\%_]/g, "\\$&")}%`);
|
||||
}
|
||||
if (before > 0) {
|
||||
where.push("id < ?");
|
||||
values.push(before);
|
||||
}
|
||||
return db().prepare(`SELECT * FROM chat_log ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY id DESC LIMIT ?`).all(...values, PAGE).map(row);
|
||||
};
|
||||
|
||||
// what was said around one line, oldest first: in its room, or for a
|
||||
// whisper between its two players.
|
||||
const around = id => {
|
||||
const line = db().prepare("SELECT * FROM chat_log WHERE id = ?").get(Number(id));
|
||||
if (!line) {
|
||||
return null;
|
||||
}
|
||||
const [same, values] = line.kind === WHISPER
|
||||
? ["kind = ? AND ((username = ? AND to_name = ?) OR (username = ? AND to_name = ?))", [WHISPER, line.username, line.to_name, line.to_name, line.username]]
|
||||
: ["kind = ? AND room = ?", [CHAT, line.room]];
|
||||
const earlier = db().prepare(`SELECT * FROM chat_log WHERE ${same} AND id < ? ORDER BY id DESC LIMIT ?`).all(...values, line.id, AROUND).reverse();
|
||||
const later = db().prepare(`SELECT * FROM chat_log WHERE ${same} AND id > ? ORDER BY id LIMIT ?`).all(...values, line.id, AROUND);
|
||||
return {line: row(line), lines: [...earlier, line, ...later].map(row)};
|
||||
};
|
||||
|
||||
// everything an account said that is still kept, oldest first, for the copy
|
||||
// of their data a player may ask for (lib/manage.js).
|
||||
const saidBy = account => db().prepare("SELECT * FROM chat_log WHERE account_id = ? ORDER BY id").all(account.id).map(row);
|
||||
|
||||
// an account being deleted: what it said goes with it.
|
||||
const forget = account => {
|
||||
db().prepare("DELETE FROM chat_log WHERE account_id = ?").run(account.id);
|
||||
};
|
||||
|
||||
module.exports = {load, record, search, around, saidBy, forget, PAGE};
|
||||
@@ -0,0 +1,73 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
|
||||
// custom colours. the game stores a colour as four palette indexes packed in
|
||||
// one number, which leaves no room for "any hex colour". so a number in a
|
||||
// range no real colour uses (CUSTOM_BASE and up) is instead the id of an
|
||||
// entry here: the four RGB values that layer is drawn with. the patched
|
||||
// client keeps the same table (PaletteHelper.customColors); the server sends
|
||||
// it at login and announces every new entry to everyone before anybody can
|
||||
// receive a colour that uses it.
|
||||
|
||||
const CUSTOM_BASE = 0xFD000000; // top byte 0xFD: unused by every item and animal def
|
||||
const config = require("../config.js");
|
||||
const MAX_ID = 0xFDFFFFFF; // the last id with the top byte 0xFD
|
||||
const MAX_RGB = 0xFFFFFF;
|
||||
|
||||
const SCHEMA = "CREATE TABLE IF NOT EXISTS custom_colours (id INTEGER PRIMARY KEY, rgb TEXT NOT NULL UNIQUE)";
|
||||
|
||||
const byKey = new Map(); // "r1,r2,r3,r4" -> id
|
||||
const entries = new Map(); // id -> [r1, r2, r3, r4]
|
||||
let nextId = CUSTOM_BASE; // one past the highest id ever given: ids are never used twice
|
||||
|
||||
const load = () => {
|
||||
const db = accounts.database();
|
||||
db.exec(SCHEMA);
|
||||
for (const row of db.prepare("SELECT id, rgb FROM custom_colours").all()) {
|
||||
byKey.set(row.rgb, row.id);
|
||||
entries.set(row.id, row.rgb.split(",").map(Number));
|
||||
nextId = Math.max(nextId, row.id + 1);
|
||||
}
|
||||
console.log(`[colours] ${entries.size} custom colours`);
|
||||
};
|
||||
|
||||
const valid = rgbs => rgbs.length === 4 && rgbs.every(value => Number.isInteger(value) && value >= 0 && value <= MAX_RGB);
|
||||
|
||||
// the id for these four RGB values, making the entry if it is new and
|
||||
// `mayCreate` is not false. returns {id, rgbs, created}; null when the
|
||||
// values are bad, and {full: true} when a new entry would be needed and may
|
||||
// not be made (the table is full, or the asker has made enough today).
|
||||
const allocate = (rgbs, mayCreate = true) => {
|
||||
if (!valid(rgbs)) {
|
||||
return null;
|
||||
}
|
||||
const key = rgbs.join(",");
|
||||
if (byKey.has(key)) {
|
||||
return {id: byKey.get(key), rgbs, created: false};
|
||||
}
|
||||
if (!mayCreate || entries.size >= config.maxCustomColours || nextId > MAX_ID) {
|
||||
return {full: true};
|
||||
}
|
||||
const id = nextId++;
|
||||
accounts.database().prepare("INSERT INTO custom_colours (id, rgb) VALUES (?, ?)").run(id, key);
|
||||
byKey.set(key, id);
|
||||
entries.set(id, rgbs);
|
||||
return {id, rgbs, created: true};
|
||||
};
|
||||
|
||||
// [id, r1, r2, r3, r4] for every entry, in groups small enough for one message.
|
||||
const chunks = (size = 200) => {
|
||||
const all = [...entries].map(([id, rgbs]) => [id, ...rgbs]);
|
||||
const out = [];
|
||||
for (let i = 0; i < all.length; i += size) {
|
||||
out.push(all.slice(i, i + size));
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
// is this number a colour the game can draw: one of its own (anything below
|
||||
// the custom range), or an entry of the table?
|
||||
const known = id => id < CUSTOM_BASE || id > MAX_ID || entries.has(id);
|
||||
|
||||
module.exports = {load, allocate, chunks, known, count: () => entries.size};
|
||||
@@ -0,0 +1,527 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const chatlog = require("./chatlog.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const disguises = require("./disguises.js");
|
||||
const dens = require("./dens.js");
|
||||
const {isSilenced} = require("./moderation.js");
|
||||
const {MAX_DEN_ITEMS, MAX_WORN, activeAvatar, wornItems} = require("./player.js");
|
||||
|
||||
// things players can do by typing "!something" in the chat box, for what
|
||||
// the game has no window for. none of them touches another player: they
|
||||
// look things up, or change the typist's own outfit, den or settings.
|
||||
// what a command has to say comes up in a plain message box of the game's
|
||||
// ("xtl", shown by the patched client), not as a note from Animal Jam HQ.
|
||||
//
|
||||
// the chat box only lets through letters, digits, spaces and !'.,():?-
|
||||
// so that is all a command or a name given to one can be made of.
|
||||
|
||||
const PREFIX = "!";
|
||||
const MAX_OUTFITS = 30;
|
||||
const MAX_LAYOUTS = 20;
|
||||
const MAX_NAME = 20;
|
||||
const MAX_LISTED = 40;
|
||||
const NAME_PATTERN = /^[a-z0-9]{1,20}$/;
|
||||
|
||||
// what each command does is listed for players at /commands
|
||||
// (public/commands.html): too much to read in a popup in the game.
|
||||
|
||||
// short names for "!go". any room of the room list also goes by its own
|
||||
// name, with dots ("sarepia.flag_shop").
|
||||
const PLACES = {
|
||||
township: "jamaa_township.room_main", jamaa: "jamaa_township.room_main",
|
||||
sarepia: "sarepia.room_main", crystal: "crystal_sands.room_main", sands: "crystal_sands.room_main",
|
||||
coral: "coral_canyons.room_main", canyons: "coral_canyons.room_main", shiveer: "mountains_of_shivveer.room_main",
|
||||
appondale: "appondale.room_main", zios: "lost_temple_of_zios.room_main", temple: "lost_temple_of_zios.room_main",
|
||||
kimbara: "aussie.room_main", outback: "aussie.room_main", balloosh: "balloosh.room_main",
|
||||
bahari: "oceans.bahari_bay", reef: "oceans.crystal_reef", deep: "oceans.deep_sea", kani: "pirate_ship.room_main",
|
||||
arcade: "jamaa_township.room_arcade", diamonds: "jamaa_township.room_diamonds", alphas: "jamaa_township.room_alphahq",
|
||||
museum: "appondale.room_museum", chamber: "lost_temple_of_zios.chamber_of_knowledge", aquarium: "crystal_sands.room_tierney",
|
||||
path: "canyon_path.room_main", carnival: "party.venue_carnival",
|
||||
};
|
||||
const PLAIN_NAME = /^[A-Za-z0-9][A-Za-z0-9 '.-]{0,19}$/; // a typed animal or pet name
|
||||
const MAX_WHISPER = 200;
|
||||
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}) => {
|
||||
// A plain message box with an OK button.
|
||||
const tell = (session, text) => session.sendXt("xtl", -1, String(text).replace(/%/g, " percent"));
|
||||
|
||||
const named = (list, name) => list.find(entry => entry.name === name);
|
||||
|
||||
const validName = (session, name) => {
|
||||
if (!NAME_PATTERN.test(name || "")) {
|
||||
tell(session, `Give it a name of letters and digits, up to ${MAX_NAME} long.`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
// has the animal in use wear exactly the clothes with these inventory
|
||||
// ids, and remembers what it wore before for "!outfit undo". returns the
|
||||
// items now worn.
|
||||
const dress = (session, invs) => {
|
||||
const {account} = session;
|
||||
const avatar = activeAvatar(account);
|
||||
const before = wornItems(account, avatar);
|
||||
const wanted = account.items.filter(item => invs.includes(item.inv)).slice(0, MAX_WORN);
|
||||
const takenOff = before.filter(item => !wanted.includes(item));
|
||||
account.outfitUndo = {avInvId: avatar.avInvId, items: before.map(item => item.inv)};
|
||||
for (const item of takenOff) {
|
||||
item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId);
|
||||
}
|
||||
for (const item of wanted) {
|
||||
if (!item.on.includes(avatar.avInvId)) {
|
||||
item.on.push(avatar.avInvId);
|
||||
}
|
||||
}
|
||||
accounts.save();
|
||||
// ItemXtCommManager.itemsChangedListResponse, "3" = what is worn
|
||||
// changed: [3, inUse, perUserAvId, username, colour, onCount,
|
||||
// offCount, (invIdx, defId)..., offInvIdx...]
|
||||
session.sendXt("il", -1, 3, 1, avatar.perUserAvId, account.username, 0, wanted.length, takenOff.length,
|
||||
...wanted.flatMap(item => [item.inv, item.def]), ...takenOff.map(item => item.inv));
|
||||
for (const other of watchers(session)) {
|
||||
sendItemList(other, session, false);
|
||||
}
|
||||
return wanted;
|
||||
};
|
||||
|
||||
const outfit = (session, [action, name]) => {
|
||||
const {account} = session;
|
||||
const avatar = activeAvatar(account);
|
||||
switch (action) {
|
||||
case "off":
|
||||
dress(session, []);
|
||||
tell(session, "Everything is off. !outfit undo puts it back on.");
|
||||
return;
|
||||
// what this animal wore before the last change made here or in the
|
||||
// animal editor (lib/items.js keeps it).
|
||||
case "undo": {
|
||||
const undo = account.outfitUndo;
|
||||
if (!undo || undo.avInvId !== avatar.avInvId) {
|
||||
tell(session, "There is nothing to put back for this animal.");
|
||||
return;
|
||||
}
|
||||
dress(session, undo.items);
|
||||
tell(session, "Back to what you wore before. !outfit undo again swaps back.");
|
||||
return;
|
||||
}
|
||||
// the next free "outfit N" (the settings menu's "Save what I wear").
|
||||
case "savenew": {
|
||||
let number = 1;
|
||||
while (named(account.outfits, `outfit${number}`)) {
|
||||
number++;
|
||||
}
|
||||
outfit(session, ["save", `outfit${number}`]);
|
||||
return;
|
||||
}
|
||||
case "save": {
|
||||
if (!validName(session, name)) {
|
||||
return;
|
||||
}
|
||||
const existing = named(account.outfits, name);
|
||||
if (!existing && account.outfits.length >= MAX_OUTFITS) {
|
||||
tell(session, `You already have ${MAX_OUTFITS} outfits. Delete one first.`);
|
||||
return;
|
||||
}
|
||||
const items = wornItems(account, avatar).map(item => item.inv);
|
||||
account.outfits = [...account.outfits.filter(entry => entry !== existing), {name, items}];
|
||||
accounts.save();
|
||||
tell(session, `Outfit ${name} saved (${items.length} items).`);
|
||||
return;
|
||||
}
|
||||
case "wear": {
|
||||
const saved = named(account.outfits, name);
|
||||
if (!saved) {
|
||||
tell(session, `You have no outfit called ${name}. Try !outfit list.`);
|
||||
return;
|
||||
}
|
||||
const wanted = dress(session, saved.items);
|
||||
const missing = saved.items.length - wanted.length;
|
||||
tell(session, missing ? `Wearing ${name}. ${missing} of its items are no longer yours.` : `Wearing ${name}.`);
|
||||
return;
|
||||
}
|
||||
case "delete":
|
||||
if (!named(account.outfits, name)) {
|
||||
tell(session, `You have no outfit called ${name}.`);
|
||||
return;
|
||||
}
|
||||
account.outfits = account.outfits.filter(entry => entry.name !== name);
|
||||
accounts.save();
|
||||
tell(session, `Outfit ${name} deleted.`);
|
||||
return;
|
||||
case "list":
|
||||
tell(session, account.outfits.length ? `Your outfits: ${account.outfits.map(entry => entry.name).join(", ")}` : "You have no saved outfits yet.");
|
||||
return;
|
||||
default:
|
||||
tell(session, "Use: !outfit save NAME, !outfit wear NAME, !outfit list, !outfit delete NAME, !outfit off, !outfit undo");
|
||||
}
|
||||
};
|
||||
|
||||
const activeDenDef = account => (account.dens.find(den => den.inv === account.activeDen) || account.dens[0]).def;
|
||||
|
||||
const layoutOf = owner => owner.denItems
|
||||
.filter(item => item.placed && item.den === owner.activeDen)
|
||||
.map(item => ({def: item.def, version: item.version, x: item.x, y: item.y, flip: item.flip}));
|
||||
|
||||
// lays the account's den in use out as `layout` says, with its own items.
|
||||
// with `giveMissing`, items it lacks are added to its inventory first.
|
||||
// returns how many of the layout's items could not be placed.
|
||||
const applyLayout = (session, layout, giveMissing) => {
|
||||
const {account} = session;
|
||||
for (const item of account.denItems.filter(candidate => candidate.den === account.activeDen)) {
|
||||
item.placed = false;
|
||||
item.x = item.y = item.flip = 0;
|
||||
}
|
||||
const used = new Set();
|
||||
let missing = 0;
|
||||
for (const spot of layout) {
|
||||
let item = account.denItems.find(candidate => !used.has(candidate) && !candidate.placed
|
||||
&& candidate.def === spot.def && candidate.version === spot.version);
|
||||
if (!item && giveMissing && account.denItems.length < MAX_DEN_ITEMS && defpacks.denItemIds().includes(spot.def)) {
|
||||
item = dens.giveDenItem(account, spot.def, spot.version);
|
||||
}
|
||||
if (!item) {
|
||||
missing++;
|
||||
continue;
|
||||
}
|
||||
used.add(item);
|
||||
Object.assign(item, {placed: true, den: account.activeDen, x: spot.x, y: spot.y, flip: spot.flip});
|
||||
}
|
||||
accounts.save();
|
||||
dens.sendDenItems(session);
|
||||
const room = session.room && session.room.denOwner === account ? session.room : null;
|
||||
for (const occupant of room ? room.sessions : []) {
|
||||
dens.sendDenState(occupant, room, false);
|
||||
}
|
||||
return missing;
|
||||
};
|
||||
|
||||
const den = (session, [action, name]) => {
|
||||
const {account} = session;
|
||||
switch (action) {
|
||||
case "save": {
|
||||
if (!validName(session, name)) {
|
||||
return;
|
||||
}
|
||||
const existing = named(account.denLayouts, name);
|
||||
if (!existing && account.denLayouts.length >= MAX_LAYOUTS) {
|
||||
tell(session, `You already have ${MAX_LAYOUTS} den layouts. Delete one first.`);
|
||||
return;
|
||||
}
|
||||
const items = layoutOf(account);
|
||||
account.denLayouts = [...account.denLayouts.filter(entry => entry !== existing), {name, den: activeDenDef(account), items}];
|
||||
accounts.save();
|
||||
tell(session, `Den layout ${name} saved (${items.length} items).`);
|
||||
return;
|
||||
}
|
||||
case "load": {
|
||||
const saved = named(account.denLayouts, name);
|
||||
if (!saved) {
|
||||
tell(session, `You have no den layout called ${name}. Try !den list.`);
|
||||
return;
|
||||
}
|
||||
if (saved.den !== activeDenDef(account)) {
|
||||
tell(session, `Layout ${name} was made in another kind of den. Switch to that den first.`);
|
||||
return;
|
||||
}
|
||||
const missing = applyLayout(session, saved.items, false);
|
||||
tell(session, missing ? `Den layout ${name} loaded. ${missing} of its items are no longer yours.` : `Den layout ${name} loaded.`);
|
||||
return;
|
||||
}
|
||||
case "copy": {
|
||||
const owner = session.room && session.room.denOwner;
|
||||
if (!owner || owner === account) {
|
||||
tell(session, "Stand in the den you want to copy, then type !den copy.");
|
||||
return;
|
||||
}
|
||||
if (activeDenDef(owner) !== activeDenDef(account)) {
|
||||
tell(session, "Your den in use is a different kind of den. Switch to the same kind first.");
|
||||
return;
|
||||
}
|
||||
const missing = applyLayout(session, layoutOf(owner), true);
|
||||
tell(session, missing ? `Your den now looks like this one, apart from ${missing} items.` : "Your den now looks like this one.");
|
||||
return;
|
||||
}
|
||||
case "savenew": {
|
||||
let number = 1;
|
||||
while (named(account.denLayouts, `layout${number}`)) {
|
||||
number++;
|
||||
}
|
||||
den(session, ["save", `layout${number}`]);
|
||||
return;
|
||||
}
|
||||
// what the den's "clear" button took away (lib/dens.js clearDen keeps it).
|
||||
case "undo": {
|
||||
const undo = account.denUndo;
|
||||
if (!undo || undo.den !== account.activeDen) {
|
||||
tell(session, undo ? "That was another den. Switch to it first." : "There is nothing to put back.");
|
||||
return;
|
||||
}
|
||||
const missing = applyLayout(session, undo.items, false);
|
||||
account.denUndo = null;
|
||||
accounts.save();
|
||||
tell(session, missing ? `Your den is back as it was, apart from ${missing} items that are no longer yours.` : "Your den is back as it was.");
|
||||
return;
|
||||
}
|
||||
case "delete":
|
||||
if (!named(account.denLayouts, name)) {
|
||||
tell(session, `You have no den layout called ${name}.`);
|
||||
return;
|
||||
}
|
||||
account.denLayouts = account.denLayouts.filter(entry => entry.name !== name);
|
||||
accounts.save();
|
||||
tell(session, `Den layout ${name} deleted.`);
|
||||
return;
|
||||
case "list":
|
||||
tell(session, account.denLayouts.length ? `Your den layouts: ${account.denLayouts.map(entry => entry.name).join(", ")}` : "You have no saved den layouts yet.");
|
||||
return;
|
||||
default:
|
||||
tell(session, "Use: !den save NAME, !den load NAME, !den list, !den delete NAME, !den copy, !den undo");
|
||||
}
|
||||
};
|
||||
|
||||
const commands = {
|
||||
online(session) {
|
||||
const names = players().filter(other => !blocks.either(other.account, session.account)).map(other => other.account.username);
|
||||
const shown = names.slice(0, MAX_LISTED).join(", ");
|
||||
tell(session, `${names.length} playing: ${shown}${names.length > MAX_LISTED ? ", ..." : ""}`);
|
||||
},
|
||||
|
||||
// only for buddies, as with the buddy list's own "go to".
|
||||
where(session, words) {
|
||||
const name = words.join(" ");
|
||||
const target = findOnline(name);
|
||||
if (!name) {
|
||||
tell(session, "Use: !where NAME");
|
||||
}
|
||||
else if (!session.account.buddies.includes(name.toLowerCase())) {
|
||||
tell(session, `${name} is not one of your buddies.`);
|
||||
}
|
||||
else if (!target || !target.room) {
|
||||
tell(session, `${name} is not online.`);
|
||||
}
|
||||
else {
|
||||
tell(session, `${target.account.username} is in ${roomTitle(target.room)}.`);
|
||||
}
|
||||
},
|
||||
|
||||
time(session) {
|
||||
tell(session, `It is ${new Date().toUTCString()}.`);
|
||||
},
|
||||
|
||||
outfit,
|
||||
den,
|
||||
|
||||
// lib/disguises.js
|
||||
become(session, [choice]) {
|
||||
if (!choice || choice === "list") {
|
||||
tell(session, `You can become: ${disguises.names().join(", ")}, or any character by its number. !become off to be yourself.`);
|
||||
return;
|
||||
}
|
||||
if (choice === "off") {
|
||||
disguises.set(session, 0, refreshForOthers);
|
||||
tell(session, "You are yourself again.");
|
||||
return;
|
||||
}
|
||||
const id = disguises.find(choice);
|
||||
if (!id) {
|
||||
tell(session, `There is no character called ${choice}. Try !become list.`);
|
||||
return;
|
||||
}
|
||||
const changing = disguises.of(session.account) !== 0;
|
||||
disguises.set(session, id, refreshForOthers);
|
||||
tell(session, changing ? "Done. It shows when you next walk into a room." : "Done. !become off to be yourself again.");
|
||||
},
|
||||
|
||||
again(session, [choice]) {
|
||||
const times = choice === undefined ? 1 : Number(choice);
|
||||
if (!session.lastPurchase || !Number.isInteger(times) || times < 1 || times > MAX_AGAIN) {
|
||||
tell(session, session.lastPurchase ? `Use: !again N, with N from 1 to ${MAX_AGAIN}` : "Buy something in a shop first; !again then buys more of it.");
|
||||
return;
|
||||
}
|
||||
ask(session, times === 1 ? "Buy one more of the last thing you bought?" : `Buy ${times} more of the last thing you bought?`, () => {
|
||||
for (let count = 0; count < times; count++) {
|
||||
buyAgain(session);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
go(session, [place]) {
|
||||
if (!place || place === "list") {
|
||||
tell(session, `Places: ${Object.keys(PLACES).join(", ")}. Any room also goes by its own name, like sarepia.flag_shop.`);
|
||||
return;
|
||||
}
|
||||
const base = Object.hasOwn(PLACES, place) ? PLACES[place] : place;
|
||||
if (!defpacks.roomDef(base) || /^(player_den|epic_dens)\./.test(base)) {
|
||||
tell(session, `There is no place called ${place}. Try !go list.`);
|
||||
return;
|
||||
}
|
||||
travel(session, base);
|
||||
},
|
||||
|
||||
// A look for the room they stand in, a look picked afresh at every
|
||||
// login, or the list of looks (config.themes).
|
||||
theme(session, [action, choice]) {
|
||||
const {account} = session;
|
||||
const themes = require("../config.js").themes;
|
||||
if (action === "random" && (choice === "on" || choice === "off")) {
|
||||
account.randomTheme = choice === "on";
|
||||
accounts.save();
|
||||
tell(session, account.randomTheme ? "The lands get a look picked at random each time you log in." : "The lands keep the look you choose.");
|
||||
}
|
||||
else if (action === "here" && session.room && !session.room.denOwner && (choice === "off" || Object.hasOwn(themes, choice))) {
|
||||
if (choice === "off") {
|
||||
delete account.roomThemes[session.room.base];
|
||||
}
|
||||
else {
|
||||
account.roomThemes[session.room.base] = choice;
|
||||
}
|
||||
accounts.save();
|
||||
reloadRoom(session);
|
||||
}
|
||||
else if (action === "list") {
|
||||
tell(session, `Looks: ${Object.keys(themes).join(", ")}`);
|
||||
}
|
||||
else {
|
||||
tell(session, "Use: !theme list, !theme here NAME, !theme here off, !theme random on, !theme random off");
|
||||
}
|
||||
},
|
||||
|
||||
// deletes the Jam-A-Grams already read; ones with a gift not yet taken stay.
|
||||
mail(session, [action]) {
|
||||
const {account} = session;
|
||||
if (action !== "clear") {
|
||||
tell(session, "Use: !mail clear");
|
||||
return;
|
||||
}
|
||||
const before = account.ecards.length;
|
||||
account.ecards = account.ecards.filter(card => !card.read || card.gift);
|
||||
accounts.save();
|
||||
tell(session, `${before - account.ecards.length} read Jam-A-Grams deleted. Open your mail again to see.`);
|
||||
},
|
||||
|
||||
// every music track, the official ones and this server's extras, as den
|
||||
// items of theirs: what the den's music list offers is what they own.
|
||||
music(session, [action]) {
|
||||
const {account} = session;
|
||||
if (action !== "all") {
|
||||
tell(session, "Use: !music all");
|
||||
return;
|
||||
}
|
||||
const owned = new Set(account.denItems.map(item => item.def));
|
||||
const wanted = [...defpacks.musicIds(), ...defpacks.extraMusicIds()].filter(id => !owned.has(id));
|
||||
const given = wanted.filter(id => dens.giveDenItem(account, id)).length;
|
||||
dens.sendDenItems(session);
|
||||
tell(session, given < wanted.length ? `${given} music tracks added. Your den items are full: recycle some for the rest.`
|
||||
: wanted.length ? `${wanted.length} music tracks added. They are in your den's music list.` : "You have every music track already.");
|
||||
},
|
||||
|
||||
hideblocked(session, [choice]) {
|
||||
if (choice !== "on" && choice !== "off") {
|
||||
tell(session, `Blocked players are ${session.account.hideBlocked ? "hidden" : "shown"}. Use: !hideblocked on, or !hideblocked off`);
|
||||
return;
|
||||
}
|
||||
setHideBlocked(session, choice === "on");
|
||||
tell(session, choice === "on" ? "Players you have blocked are now hidden from you." : "Players you have blocked are shown again.");
|
||||
},
|
||||
};
|
||||
|
||||
// commands whose words matter as they were typed, capitals and all.
|
||||
const asTyped = {
|
||||
// A whisper: only that buddy sees it, wherever they are. standing in
|
||||
// the same room it is a chat bubble for the two of them; otherwise a
|
||||
// message box, the one way the game has to show text from afar.
|
||||
w(session, [name, ...words]) {
|
||||
const {account} = session;
|
||||
const said = words.join(" ").slice(0, MAX_WHISPER);
|
||||
const target = name ? findOnline(name) : null;
|
||||
if (!name || !said) {
|
||||
tell(session, "Use: !w BUDDY message");
|
||||
}
|
||||
else if (!account.buddies.includes(name.toLowerCase())) {
|
||||
tell(session, `${name} is not one of your buddies.`);
|
||||
}
|
||||
else if (!target || !target.room || blocks.either(target.account, account)
|
||||
|| !accounts.featureOn(target.account, "chat") || !accounts.featureOn(account, "chat")) {
|
||||
tell(session, `${name} cannot be whispered to right now.`);
|
||||
}
|
||||
else if (target.room === session.room) {
|
||||
// "xw" makes the next chat bubble the reader's game draws a
|
||||
// light green one (gui.ChatBalloon in the patched client).
|
||||
for (const reader of [session, target]) {
|
||||
reader.sendXt("xw", -1, 1);
|
||||
reader.sendXt("uc", session.room.id, session.id, said, 0);
|
||||
}
|
||||
chatlog.record(account, session.room.name, said, target.account.username);
|
||||
}
|
||||
else {
|
||||
// from afar there is no bubble to draw: a message box, in the same green.
|
||||
target.sendXt("xw", -1, 0, account.username, said.replace(/%/g, " percent"));
|
||||
tell(session, `Whispered to ${target.account.username}.`);
|
||||
chatlog.record(account, session.room ? session.room.name : "", said, target.account.username);
|
||||
}
|
||||
},
|
||||
whisper(session, words) {
|
||||
asTyped.w(session, words);
|
||||
},
|
||||
|
||||
// "!den name NEW NAME": what the den in use is called on the screen of
|
||||
// whoever walks in. anything else after "!den" is the usual command.
|
||||
den(session, [action, ...words]) {
|
||||
const {account} = session;
|
||||
const wanted = words.join(" ");
|
||||
if (action.toLowerCase() !== "name") {
|
||||
commands.den(session, [action, ...words].map(word => word.toLowerCase()));
|
||||
}
|
||||
else if (wanted.toLowerCase() === "off") {
|
||||
delete account.denNames[account.activeDen];
|
||||
accounts.save();
|
||||
tell(session, "This den has its usual name again.");
|
||||
}
|
||||
else if (isSilenced(account)) {
|
||||
tell(session, "You cannot name a den while silenced.");
|
||||
}
|
||||
else if (!PLAIN_NAME.test(wanted)) {
|
||||
tell(session, "Use: !den name NEW NAME (letters, digits and spaces, up to 20), or !den name off");
|
||||
}
|
||||
else {
|
||||
account.denNames[account.activeDen] = wanted;
|
||||
accounts.save();
|
||||
tell(session, `This den is now called ${wanted}. It shows the next time someone walks in.`);
|
||||
}
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
return {
|
||||
// runs `text` if it is a command. returns what to do with the chat line:
|
||||
// null to swallow it, or the text everyone should see in its place.
|
||||
run(session, text) {
|
||||
if (!text.startsWith(PREFIX)) {
|
||||
return text;
|
||||
}
|
||||
const typed = text.slice(PREFIX.length).trim().split(/\s+/);
|
||||
const [name, ...words] = typed.map(word => word.toLowerCase());
|
||||
if (Object.hasOwn(asTyped, name) && (name !== "den" || typed.length > 1)) {
|
||||
asTyped[name](session, typed.slice(1));
|
||||
return null;
|
||||
}
|
||||
if (name === "roll") {
|
||||
// said out loud, so the room can see it was not made up.
|
||||
return `(rolls a dice: ${1 + Math.floor(Math.random() * 6)})`;
|
||||
}
|
||||
if (!Object.hasOwn(commands, name)) {
|
||||
return text; // "!!!" and the like are just chat
|
||||
}
|
||||
commands[name](session, words);
|
||||
return null;
|
||||
},
|
||||
roomTitle,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,503 @@
|
||||
"use strict";
|
||||
|
||||
const zlib = require("zlib");
|
||||
const amf3 = require("./amf3.js");
|
||||
const cdn = require("./cdn.js");
|
||||
const config = require("../config.js");
|
||||
const sales = require("./sales.js");
|
||||
const badges = require("./badges.js");
|
||||
const extraMusic = require("./extramusic.js");
|
||||
|
||||
// defPack ids, from loader.DefPacksDefHelper in the client.
|
||||
const DEF_ITEM = 1000;
|
||||
const DEF_AVATAR = 1003;
|
||||
const DEF_ROOM = 1011;
|
||||
const DEF_LOCALIZATION_EN = 10230;
|
||||
const DEF_DEN_ITEM = 1030;
|
||||
const DEF_GENERIC_LIST_TYPE = 1038;
|
||||
const DEF_DEN_ROOM = 1040;
|
||||
const DEF_DIAMOND = 1054;
|
||||
const DEF_PET = 1046;
|
||||
const DEF_AVATAR_CUSTOM = 1057;
|
||||
const DEF_ACHIEVEMENTS = 1042;
|
||||
const DEF_PARTY = 1047;
|
||||
const DEF_CURRENCY_EXCHANGE = 1051;
|
||||
const DEF_ADOPT_A_PET = 1061;
|
||||
const DEF_PET_FOOD = 1062;
|
||||
const DEF_PET_TOY = 1063;
|
||||
const DEF_WORLD_ITEMS = 1064;
|
||||
const DEF_NPC = 1025;
|
||||
const DEF_NAMEBAR_BADGE = 1049;
|
||||
|
||||
const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items: plain, mannequin
|
||||
const DEN_ITEM_MASTERPIECE = 2725;
|
||||
|
||||
const packs = new Map();
|
||||
|
||||
// A defPack is a raw-deflated AMF3 object.
|
||||
const loadRaw = async id => {
|
||||
const raw = await cdn.get(cdn.hashedPath(`defPacks/${id}`));
|
||||
if (!raw) {
|
||||
throw new Error(`defPack ${id} is not available (offline and not cached?)`);
|
||||
}
|
||||
return amf3.decode(zlib.inflateRawSync(raw));
|
||||
};
|
||||
|
||||
// the pack with this server's rows in it (SHARED_CHANGES, further down).
|
||||
const loadChanged = async id => {
|
||||
const pack = await loadRaw(id);
|
||||
if (SHARED_CHANGES.has(id)) {
|
||||
SHARED_CHANGES.get(id)(pack);
|
||||
}
|
||||
return pack;
|
||||
};
|
||||
|
||||
const LAYER_EYES = "3";
|
||||
const TYPE_CLOTHING = "1";
|
||||
const EVERY_AVATAR = "9007199254740991"; // avatarUseFlags with a bit set for each animal type
|
||||
|
||||
// rooms the official room pack no longer lists but whose files an older
|
||||
// build on the CDN still has (lib/cdn.js looks there): the Summer Carnival,
|
||||
// dropped after build 1828.
|
||||
const RESTORED_ROOMS = [
|
||||
{id: "273", pathName: "party/venue_carnival", type: "0", isPlatformer: "0"},
|
||||
];
|
||||
|
||||
const withRestoredRooms = pack => {
|
||||
const paths = new Set(Object.values(pack).map(def => def.pathName));
|
||||
let next = Math.max(-1, ...Object.keys(pack).map(Number).filter(Number.isInteger)) + 1;
|
||||
for (const room of RESTORED_ROOMS) {
|
||||
if (!paths.has(room.pathName)) {
|
||||
pack[next++] = {...room};
|
||||
}
|
||||
}
|
||||
return pack;
|
||||
};
|
||||
|
||||
// parties. five party defs point at rooms that are in no build's room list
|
||||
// and whose files are nowhere to be found (the 2012 New Year's party, an
|
||||
// older Jamaaliday Jam, the Trading Party, a leap-year room, one hostable
|
||||
// venue), and seven party rooms on the CDN have no party def pointing at
|
||||
// them. put together here:
|
||||
// - the Trading Party is held in the trading barn (the unused twin of the
|
||||
// barn players can host in), since its own room is gone;
|
||||
// - the restaurant and the dance club among the unused rooms become
|
||||
// parties of their own, with a title and list picture borrowed from
|
||||
// what is nearest.
|
||||
// - the other four unused rooms are earlier copies of venues players can
|
||||
// host in (cake, vet, bakery, medieval castle). they become parties too,
|
||||
// under the names the game has for those venues and with their pictures.
|
||||
// - party 36 is the "AJHQ" button of the world map's Epic Dens window. it
|
||||
// led to whichever showcase den was on that month; lib/epicdens.js picks
|
||||
// the room, so here it only gets a title that fits them all.
|
||||
const PARTY_STAND_IN_ROOMS = new Map([["6", "515"]]); // party def id -> room def id
|
||||
const ADDED_PARTIES = [
|
||||
// "Restaurant", the Dinner Party's picture, party/venue_p_diner
|
||||
{id: "52", titleStrId: "703", mediaRefId: "1234", roomDefId: "472"},
|
||||
// "Dance Party", the hostable dance club's picture, party/venue_pl_dance_club
|
||||
{id: "53", titleStrId: "24279", mediaRefId: "4424", roomDefId: "519"},
|
||||
// "Birthday Party", "Science Party", "Bakery Party", "Medieval Party":
|
||||
// party/venue_pl_birthday_cake, _vet_science, _res_bakery, _castle_medieval
|
||||
{id: "54", titleStrId: "24271", mediaRefId: "4422", roomDefId: "514"},
|
||||
{id: "55", titleStrId: "24277", mediaRefId: "4425", roomDefId: "517"},
|
||||
{id: "56", titleStrId: "24275", mediaRefId: "4421", roomDefId: "518"},
|
||||
{id: "57", titleStrId: "24273", mediaRefId: "4423", roomDefId: "520"},
|
||||
];
|
||||
const PARTY_EPIC_DENS = "36";
|
||||
const STRING_EPIC_DENS = "8700";
|
||||
const PARTY_DEFAULTS = {iconMediaRefId: "0", avatarDefId: "0", restrictions: "0", avatarDefFlags: "0", petDefScalableFlags: "0", isGame: "0", isCustom: "0"};
|
||||
|
||||
const withRestoredParties = pack => {
|
||||
const ids = new Set();
|
||||
for (const def of Object.values(pack)) {
|
||||
ids.add(String(def.id));
|
||||
if (PARTY_STAND_IN_ROOMS.has(String(def.id))) {
|
||||
def.roomDefId = PARTY_STAND_IN_ROOMS.get(String(def.id));
|
||||
}
|
||||
if (String(def.id) === PARTY_EPIC_DENS) {
|
||||
def.titleStrId = STRING_EPIC_DENS;
|
||||
}
|
||||
}
|
||||
let next = Math.max(-1, ...Object.keys(pack).map(Number).filter(Number.isInteger)) + 1;
|
||||
for (const party of ADDED_PARTIES) {
|
||||
if (!ids.has(party.id)) {
|
||||
pack[next++] = {...PARTY_DEFAULTS, ...party};
|
||||
}
|
||||
}
|
||||
return pack;
|
||||
};
|
||||
|
||||
// text of our own, for things the game has no string for. added to the
|
||||
// English localization pack under ids far above the game's (about 41,000).
|
||||
const ADDED_STRINGS = {
|
||||
9000001: "Castle (2010 draft)",
|
||||
9000002: "Water Park (three slides)",
|
||||
9000003: "Water Park (five slides)",
|
||||
9000004: "Crystal Palace (concept)",
|
||||
// the buddy game the client's files call "fourGem"; no string says so.
|
||||
9000005: "Four Gems",
|
||||
};
|
||||
|
||||
// the game under this server's name. its text says "Animal Jam", "Animal
|
||||
// Jam Classic", "AJ Classic" and "AJ" in some six hundred places (shop and
|
||||
// item names, phrases of the chat menus, popups, "AJHQ"); here they all say
|
||||
// "Burrow", in capitals where the game shouted. web addresses are left as
|
||||
// they are: "animaljam.com" is a place, not a name.
|
||||
const NAME = "Burrow";
|
||||
const renamed = text => text
|
||||
.replace(/Animal Jam Classic|AJ Classic|Animal Jam(?!\.com)|\bAJ(?=HQ\b)|\bAJ\b/gi, (found, at) => {
|
||||
// "aj" in small letters is somebody's word, not the game's name.
|
||||
if (/^aj$/i.test(found) && found !== "AJ") {
|
||||
return found;
|
||||
}
|
||||
const shouted = found === found.toUpperCase() && !/^AJ/.test(found);
|
||||
return (shouted ? NAME.toUpperCase() : NAME) + (text.slice(at + found.length, at + found.length + 2) === "HQ" ? " " : "");
|
||||
});
|
||||
const withOurName = pack => {
|
||||
for (const [id, text] of Object.entries(pack)) {
|
||||
if (typeof text === "string" && /Animal Jam|AJ/i.test(text)) {
|
||||
pack[id] = renamed(text);
|
||||
}
|
||||
}
|
||||
return pack;
|
||||
};
|
||||
|
||||
const withAddedStrings = pack => withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings()));
|
||||
|
||||
// the extra music tracks (lib/extramusic.js), as den items like the
|
||||
// official tracks.
|
||||
const withExtraMusic = pack => {
|
||||
const rows = Object.values(pack);
|
||||
const template = rows.find(def => Number(def.id) === extraMusic.TEMPLATE);
|
||||
const present = new Set(rows.map(def => String(def.id)));
|
||||
let next = Math.max(-1, ...Object.keys(pack).map(Number).filter(Number.isInteger)) + 1;
|
||||
for (const def of template ? extraMusic.defs(template) : []) {
|
||||
if (!present.has(def.id)) {
|
||||
pack[next++] = def;
|
||||
}
|
||||
}
|
||||
return pack;
|
||||
};
|
||||
|
||||
// den rooms on the CDN that no den def sells: four early drafts, each one
|
||||
// drawing where the finished den has many parts. they are sold like any
|
||||
// den, with the picture of the den they turned into.
|
||||
const ADDED_DENS = [
|
||||
{id: "62", titleStrRef: "9000001", mediaRef: "83", iconMediaRef: "84", roomDefId: "130"}, // player_den/room_castle_lrg
|
||||
{id: "63", titleStrRef: "9000002", mediaRef: "425", iconMediaRef: "1026", roomDefId: "187"}, // room_main_waterpark3
|
||||
{id: "64", titleStrRef: "9000003", mediaRef: "425", iconMediaRef: "1026", roomDefId: "186"}, // room_main_waterpark4
|
||||
{id: "65", titleStrRef: "9000004", mediaRef: "2777", iconMediaRef: "2776", roomDefId: "441"}, // room_main_epicpalace
|
||||
];
|
||||
const DEN_DEFAULTS = {cost: "5000", enviroType: "0", storeStatus: "0", membersOnly: "0", availabilityStartTime: null, availabilityEndTime: null};
|
||||
|
||||
const withAddedDens = pack => {
|
||||
const ids = new Set(Object.values(pack).map(def => String(def.id)));
|
||||
let next = Math.max(-1, ...Object.keys(pack).map(Number).filter(Number.isInteger)) + 1;
|
||||
for (const den of ADDED_DENS) {
|
||||
if (!ids.has(den.id)) {
|
||||
pack[next++] = {...DEN_DEFAULTS, ...den};
|
||||
}
|
||||
}
|
||||
return pack;
|
||||
};
|
||||
|
||||
// with config.freeShops everything in every shop costs nothing: every
|
||||
// account has ten million of each currency anyway (config.minimumCurrency),
|
||||
// so a price is only a number to read past. the field a price is in differs
|
||||
// by pack.
|
||||
const PRICE_FIELDS = new Map([[DEF_ITEM, "value"], [DEF_DEN_ITEM, "cost"], [DEF_DIAMOND, "cost"], [DEF_PET, "cost"], [DEF_DEN_ROOM, "cost"]]);
|
||||
const withoutPrices = (id, change = pack => pack) => pack => {
|
||||
change(pack);
|
||||
if (config.freeShops && PRICE_FIELDS.has(id)) {
|
||||
for (const def of Object.values(pack)) {
|
||||
if (def && def[PRICE_FIELDS.get(id)] !== undefined) {
|
||||
def[PRICE_FIELDS.get(id)] = "0";
|
||||
}
|
||||
}
|
||||
}
|
||||
return pack;
|
||||
};
|
||||
|
||||
// what both the server and the clients get changed: rows put back or added.
|
||||
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_DIAMOND, withoutPrices(DEF_DIAMOND)],
|
||||
[DEF_PET, withoutPrices(DEF_PET)],
|
||||
[DEF_LOCALIZATION_EN, withAddedStrings],
|
||||
[DEF_NAMEBAR_BADGE, badges.addTagDefs], // the name tag badges the admin gives: lib/badges.js
|
||||
]);
|
||||
|
||||
// den items and clothing that are in the tables and were never, or not for
|
||||
// years, in a shop: the Beta set, items named for testing, and items with
|
||||
// no name. they get a shop each (ODDITY_SHOPS in lib/world.js) and are on
|
||||
// sale there whatever their dates say. worked out in init().
|
||||
const TEST_DEN_ITEMS = [584, 1517, 1518, 2196, 2199, 2200, 3118, 3123];
|
||||
const FOUNDERS_HAT = 215;
|
||||
let oddDenItemIds = [];
|
||||
let oddClothingIds = [];
|
||||
|
||||
const alwaysOnSale = (pack, ids) => {
|
||||
const wanted = new Set(ids.map(String));
|
||||
for (const def of Object.values(pack)) {
|
||||
if (wanted.has(String(def.id))) {
|
||||
def.availabilityStartTime = "0";
|
||||
def.availabilityEndTime = "0";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// the packs clients get in a form of their own, each made by changing the
|
||||
// official one:
|
||||
// items every eye type usable by every animal. the official pack
|
||||
// keeps the two ocean eyes to the animals that have art for
|
||||
// them; on any other animal they are simply not drawn, which
|
||||
// is wanted here as a way to have no eyes.
|
||||
// (ItemXtCommManager.canUseItem is the check.) Clothing
|
||||
// likewise: the official pack keeps each item to the animals
|
||||
// it was drawn for (no beret on a penguin). and sale dates.
|
||||
// den items, the diamond shop
|
||||
// sale dates (lib/sales.js), which is why these are made
|
||||
// again each day.
|
||||
// animals, pets, dens
|
||||
// no sale dates at all.
|
||||
// rooms, parties, dens, strings, name tag badges
|
||||
// the rows put back or added (SHARED_CHANGES).
|
||||
const CLIENT_PACKS = new Map([
|
||||
[DEF_ITEM, pack => {
|
||||
for (const def of Object.values(pack)) {
|
||||
if (def.type === TYPE_CLOTHING || (def.type === "0" && def.layerId === LAYER_EYES)) {
|
||||
def.avatarUseFlags = EVERY_AVATAR;
|
||||
}
|
||||
}
|
||||
sales.stamp("clothing", pack);
|
||||
alwaysOnSale(pack, oddClothingIds);
|
||||
}],
|
||||
[DEF_DEN_ITEM, pack => {
|
||||
sales.stamp("denItems", pack);
|
||||
alwaysOnSale(pack, oddDenItemIds);
|
||||
}],
|
||||
[DEF_DIAMOND, pack => sales.stamp("diamond", pack)],
|
||||
// animals, pets and dens are never out of season here. the official pack
|
||||
// dates the "travelling" animals and a few pets and dens, and the client
|
||||
// will not offer what its dates do not cover.
|
||||
[DEF_AVATAR, sales.always],
|
||||
[DEF_PET, sales.always],
|
||||
[DEF_DEN_ROOM, sales.always],
|
||||
[DEF_ROOM, () => {}],
|
||||
[DEF_PARTY, () => {}],
|
||||
[DEF_LOCALIZATION_EN, () => {}],
|
||||
[DEF_NAMEBAR_BADGE, () => {}],
|
||||
]);
|
||||
const clientPackPaths = new Map([...CLIENT_PACKS.keys()].map(id => [cdn.hashedPath(`defPacks/${id}`), id]));
|
||||
const clientPackBodies = new Map(); // id -> {day, allOnSale, body}
|
||||
|
||||
// the pack at `relPath` as clients should get it, or null when it is not
|
||||
// one of the above (and comes straight from the CDN).
|
||||
const clientPack = async relPath => {
|
||||
const id = clientPackPaths.get(relPath);
|
||||
if (id === undefined) {
|
||||
return null;
|
||||
}
|
||||
const made = clientPackBodies.get(id);
|
||||
if (made && made.day === sales.today() && made.allOnSale === sales.everythingOnSale()) {
|
||||
return made.body;
|
||||
}
|
||||
const pack = await loadChanged(id);
|
||||
CLIENT_PACKS.get(id)(pack);
|
||||
const body = zlib.deflateRawSync(amf3.encode(pack));
|
||||
clientPackBodies.set(id, {day: sales.today(), allOnSale: sales.everythingOnSale(), body});
|
||||
return body;
|
||||
};
|
||||
|
||||
// most packs are tables: an object of rows keyed by row index.
|
||||
const load = async id => {
|
||||
if (!packs.has(id)) {
|
||||
packs.set(id, Object.values(await loadChanged(id)));
|
||||
}
|
||||
return packs.get(id);
|
||||
};
|
||||
|
||||
let avatarDefs = new Map();
|
||||
let roomDefsByPath = new Map();
|
||||
let itemDefs = new Map();
|
||||
let clothingIds = [];
|
||||
let petIds = [];
|
||||
let customAvatarDefs = new Map();
|
||||
let denItemDefs = new Map();
|
||||
let denItemIds = [];
|
||||
let petDefs = new Map();
|
||||
let strings = {}; // localization id -> English text
|
||||
let stringIds = null; // English text -> localization id, built when first asked
|
||||
let denRoomPaths = new Map();
|
||||
let diamondDefs = new Map(); // diamond def id -> {id, type, refId, cost}
|
||||
let denRoomDefs = new Map(); // den room def id -> "player_den/..." room path
|
||||
let listTypes = new Map(); // generic list id -> defPack type of its entries
|
||||
let patternLists = new Map(); // generic list id -> pattern item ids of a custom avatar
|
||||
let achievementDefs = []; // {id, userVarRef, triggerAmount}
|
||||
let exchangeDefs = new Map(); // id -> {cost, costType, result, resultType}
|
||||
let adoptAPetDefs = new Map();
|
||||
let partyDefs = new Map(); // id -> {id, room ("party.venue_x"), restrictions, avatarDefFlags, isCustom, isGame}
|
||||
let worldItemDefs = new Map();
|
||||
let petFoodDefs = [];
|
||||
let petToyDefs = [];
|
||||
let musicIds = []; // den items that are music tracks
|
||||
let roomDefsById = new Map();
|
||||
let badgeIds = []; // name tag badges, ascending
|
||||
let npcDefs = new Map(); // the characters of the adventures, see lib/disguises.js
|
||||
|
||||
// A pack whose feature can be done without: missing (offline and never
|
||||
// cached) just leaves that feature empty.
|
||||
const loadOptional = async id => {
|
||||
try {
|
||||
return await load(id);
|
||||
}
|
||||
catch (err) {
|
||||
console.log(`[defs] ${err.message}; the feature that uses it is off`);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const init = async () => {
|
||||
avatarDefs = new Map((await load(DEF_AVATAR)).map(def => [Number(def.id), def]));
|
||||
roomDefsByPath = new Map((await load(DEF_ROOM)).map(def => [String(def.pathName).toLowerCase(), def]));
|
||||
const roomPathsById = new Map((await load(DEF_ROOM)).map(def => [Number(def.id), String(def.pathName)]));
|
||||
denRoomDefs = new Map((await load(DEF_DEN_ROOM)).map(def => [Number(def.id), def]));
|
||||
denRoomPaths = new Map((await load(DEF_DEN_ROOM)).map(def => [Number(def.id), roomPathsById.get(Number(def.roomDefId))]));
|
||||
diamondDefs = new Map((await load(DEF_DIAMOND)).map(def => [Number(def.id), def]));
|
||||
badgeIds = (await loadOptional(DEF_NAMEBAR_BADGE)).map(def => Number(def.id)).sort((one, other) => one - other);
|
||||
listTypes = new Map((await load(DEF_GENERIC_LIST_TYPE)).map(def => [Number(def.id), Number(def.typeId)]));
|
||||
itemDefs = new Map((await load(DEF_ITEM)).map(def => [Number(def.id), def]));
|
||||
// type 1 = clothing and accessories; type 0 = body parts, eyes and patterns
|
||||
clothingIds = [...itemDefs].filter(([, def]) => def.type === "1").map(([id]) => id);
|
||||
petDefs = new Map((await load(DEF_PET)).map(def => [Number(def.id), def]));
|
||||
petIds = [...petDefs.keys()];
|
||||
denItemDefs = new Map((await load(DEF_DEN_ITEM)).map(def => [Number(def.id), def]));
|
||||
// special types carry extra state (a den portal's destination, a shop's
|
||||
// stock, ...). of those only mannequins (4) are modelled, in lib/dens.js,
|
||||
// so plain den items and mannequins are what is offered.
|
||||
// the Masterpiece item is a painting's frame, made in the Art Studio and
|
||||
// nowhere else (lib/masterpieces.js).
|
||||
denItemIds = [...denItemDefs].filter(([id, def]) => OFFERED_SPECIAL_TYPES.includes(def.specialType) && id !== DEN_ITEM_MASTERPIECE).map(([id]) => id);
|
||||
strings = await loadChanged(DEF_LOCALIZATION_EN);
|
||||
// the Beta set first, then the test items, then the nameless ones (some
|
||||
// 260, many of them one item in several colours): a shop shows its list
|
||||
// in the order given.
|
||||
const isBeta = id => /beta/i.test(denItemDefs.get(id).abbrName);
|
||||
const isTest = id => TEST_DEN_ITEMS.includes(id);
|
||||
const isNameless = id => !strings[denItemDefs.get(id).nameStrId];
|
||||
oddDenItemIds = [
|
||||
...denItemIds.filter(isBeta),
|
||||
...denItemIds.filter(id => isTest(id) && !isBeta(id)),
|
||||
...denItemIds.filter(id => isNameless(id) && !isBeta(id) && !isTest(id)),
|
||||
];
|
||||
oddClothingIds = [FOUNDERS_HAT, ...clothingIds.filter(id => id !== FOUNDERS_HAT && !strings[itemDefs.get(id).titleStrId])];
|
||||
customAvatarDefs = new Map((await load(DEF_AVATAR_CUSTOM)).map(def => [Number(def.id), def]));
|
||||
for (const def of await load(DEF_AVATAR_CUSTOM)) {
|
||||
const listId = Number(def.patternListRefId);
|
||||
patternLists.set(listId, [...(patternLists.get(listId) || []), Number(def.patternRefId)]);
|
||||
}
|
||||
roomDefsById = new Map((await load(DEF_ROOM)).map(def => [Number(def.id), def]));
|
||||
// typeCat 4 is music (the jukebox tracks; also what a hosted party plays)
|
||||
musicIds = [...denItemDefs].filter(([id, def]) => def.typeCat === "4" && def.specialType === "0" && !extraMusic.ids.includes(id)).map(([id]) => id);
|
||||
achievementDefs = (await loadOptional(DEF_ACHIEVEMENTS))
|
||||
.map(def => ({id: Number(def.id), userVarRef: Number(def.userVarRef), triggerAmount: Number(def.triggerAmount), name: String(def.name)}))
|
||||
.filter(def => def.userVarRef > 0 && !/REUSE/.test(def.name));
|
||||
exchangeDefs = new Map((await loadOptional(DEF_CURRENCY_EXCHANGE)).map(def => [Number(def.id),
|
||||
{id: Number(def.id), cost: Number(def.cost), costType: Number(def.costType), result: Number(def.result), resultType: Number(def.resultType)}]));
|
||||
adoptAPetDefs = new Map((await loadOptional(DEF_ADOPT_A_PET)).map(def => [Number(def.id), def]));
|
||||
worldItemDefs = new Map((await loadOptional(DEF_WORLD_ITEMS)).map(def => [Number(def.id), def]));
|
||||
petFoodDefs = await loadOptional(DEF_PET_FOOD);
|
||||
petToyDefs = await loadOptional(DEF_PET_TOY);
|
||||
npcDefs = new Map((await loadOptional(DEF_NPC)).map(def => [Number(def.id), def]));
|
||||
partyDefs = new Map((await loadOptional(DEF_PARTY)).map(def => {
|
||||
const room = roomPathsById.get(Number(def.roomDefId));
|
||||
return [Number(def.id), {
|
||||
id: Number(def.id),
|
||||
room: room && room.replace(/\//g, ".").toLowerCase(),
|
||||
titleStrId: Number(def.titleStrId),
|
||||
restrictions: Number(def.restrictions),
|
||||
avatarDefFlags: String(def.avatarDefFlags),
|
||||
isCustom: def.isCustom === "1",
|
||||
isGame: def.isGame === "1",
|
||||
}];
|
||||
}));
|
||||
console.log(`[defs] ${avatarDefs.size} avatars, ${roomDefsByPath.size} rooms, ${clothingIds.length} clothing items, ${denItemIds.length} den items, ${petIds.length} pets`);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
init,
|
||||
load,
|
||||
itemDef: id => itemDefs.get(Number(id)),
|
||||
clothingIds: () => clothingIds,
|
||||
petIds: () => petIds,
|
||||
denItemDef: id => denItemDefs.get(Number(id)),
|
||||
denItemIds: () => denItemIds,
|
||||
clientPack,
|
||||
string: id => (Object.hasOwn(strings, id) ? String(strings[id]) : ""),
|
||||
stringId: text => {
|
||||
if (!stringIds) {
|
||||
stringIds = new Map();
|
||||
for (const [id, value] of Object.entries(strings)) {
|
||||
if (typeof value === "string" && !stringIds.has(value)) {
|
||||
stringIds.set(value, Number(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
return stringIds.get(text) || 0;
|
||||
},
|
||||
badgeIds: () => badgeIds,
|
||||
npcDef: id => npcDefs.get(Number(id)),
|
||||
oddDenItemIds: () => oddDenItemIds,
|
||||
// den items that exist to be given by id and are in no shop.
|
||||
unsoldDenItemIds: () => extraMusic.ids,
|
||||
oddClothingIds: () => oddClothingIds,
|
||||
roomPaths: () => [...roomDefsByPath.keys()],
|
||||
customAvatarDef: id => customAvatarDefs.get(Number(id)),
|
||||
avatarDef: type => avatarDefs.get(Number(type)),
|
||||
denRoomName: denDefId => {
|
||||
const pathName = denRoomPaths.get(Number(denDefId));
|
||||
return pathName && pathName.replace(/\//g, ".");
|
||||
},
|
||||
denRoomDef: id => denRoomDefs.get(Number(id)),
|
||||
denRoomIds: () => [...denRoomDefs.keys()],
|
||||
// what a diamond-priced thing is sold as: `type` says what `refId` is the
|
||||
// def id of (see DIAMOND_TYPES), `cost` is in diamonds.
|
||||
diamondDef: id => diamondDefs.get(Number(id)),
|
||||
diamondIds: () => [...diamondDefs.keys()],
|
||||
listType: listId => listTypes.get(Number(listId)),
|
||||
// every generic list id whose entries are of this defPack type, ascending.
|
||||
listsOfType: type => [...listTypes].filter(([, listType]) => listType === type).map(([id]) => id).sort((a, b) => a - b),
|
||||
achievementDefs: () => achievementDefs,
|
||||
exchangeDef: id => exchangeDefs.get(Number(id)),
|
||||
exchangeDefs: () => [...exchangeDefs.values()],
|
||||
adoptAPetDef: id => adoptAPetDefs.get(Number(id)),
|
||||
adoptAPetIds: () => [...adoptAPetDefs.keys()],
|
||||
partyDef: id => partyDefs.get(Number(id)),
|
||||
partyDefs: () => [...partyDefs.values()],
|
||||
worldItemDef: id => worldItemDefs.get(Number(id)),
|
||||
worldItemIds: () => [...worldItemDefs.keys()],
|
||||
petDef: id => petDefs.get(Number(id)),
|
||||
petFoodDefs: () => petFoodDefs,
|
||||
petToyDefs: () => petToyDefs,
|
||||
musicIds: () => musicIds,
|
||||
extraMusicIds: () => extraMusic.ids,
|
||||
roomDefById: id => roomDefsById.get(Number(id)),
|
||||
patternList: listId => patternLists.get(Number(listId)),
|
||||
avatarTypes: () => [...avatarDefs.keys()],
|
||||
// first non-member land animal, falling back to whatever the pack lists
|
||||
// first.
|
||||
defaultAvatarType: () => {
|
||||
for (const [id, def] of avatarDefs) {
|
||||
if (def.membersOnly !== "1" && (Number(def.enviroTypeFlags) & 1)) {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
return avatarDefs.keys().next().value;
|
||||
},
|
||||
// "jamaa_township.room_main" -> row of the room defPack
|
||||
roomDef: roomName => roomDefsByPath.get(roomName.replace(/\./g, "/").toLowerCase()),
|
||||
};
|
||||
@@ -0,0 +1,434 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const achievements = require("./achievements.js");
|
||||
const config = require("../config.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const epicDens = require("./epicdens.js");
|
||||
const masterpieces = require("./masterpieces.js");
|
||||
const {CURRENCIES, MAX_DEN_ITEMS, hasRoom, activeAvatar, resolvePurchase, isUint} = require("./player.js");
|
||||
|
||||
// den items: owning, placing and recycling furniture (client side:
|
||||
// DenXtCommManager, DenItemHolder, DenEditor).
|
||||
|
||||
const MAX_DENS = 200;
|
||||
const MAX_SAVED_AT_ONCE = 1000; // den items in one save: as many as a den holds (gui.DenEditor)
|
||||
const MAX_RECYCLED_AT_ONCE = 500;
|
||||
const DEF_DEN_ROOM = 1040;
|
||||
|
||||
// den privacy (BuddyCard.onDenPrivacyResponse)
|
||||
const DEN_LOCKED = 0;
|
||||
const DEN_BUDDIES_ONLY = 1;
|
||||
const DEN_OPEN = 2;
|
||||
|
||||
// loadRoom's roomType for a den (DenXtCommManager.denChangeResponse)
|
||||
const ROOM_TYPE_DEN = 2;
|
||||
|
||||
const activeDen = account => account.dens.find(den => den.inv === account.activeDen) || account.dens[0];
|
||||
|
||||
const canEnter = (owner, visitor) => owner === visitor || owner.denPrivacy === DEN_OPEN
|
||||
|| (owner.denPrivacy === DEN_BUDDIES_ONLY && owner.buddies.includes(visitor.username.toLowerCase()));
|
||||
const RECYCLE_FRACTION = 0.3; // matches recyclePercentage sent at login
|
||||
const FIELDS_PER_SAVED_ITEM = 17;
|
||||
const REF_DEN_ITEM = "0"; // "1" would be a pet placed in the den
|
||||
const CURRENCY_DIAMONDS = 3;
|
||||
|
||||
// mannequins: den items (special type 4) that stand as an animal in clothes
|
||||
// of the owner's. what one wears is kept on the den item as `mannequin`:
|
||||
// {colors: [base, pattern, eyes], pattern, eyes, worn: [tail, leg, back,
|
||||
// neck, head]}, the five being inventory ids of clothing, 0 for none. A 0
|
||||
// colour or def means the animal type's own (MannequinData.setupBodMods).
|
||||
// the clothes stay in the owner's inventory and may leave it; a mannequin
|
||||
// simply stops wearing what is no longer there.
|
||||
const SPECIAL_MANNEQUIN = "4";
|
||||
// which clothing layers go in which of the five places (MannequinData.updateLayer).
|
||||
const MANNEQUIN_SLOT_LAYERS = [["4"], ["5"], ["6"], ["7"], ["8", "9", "10"]];
|
||||
const LAYER_PATTERN = "2";
|
||||
const LAYER_EYES = "3";
|
||||
|
||||
const isMannequin = item => (defpacks.denItemDef(item.def) || {}).specialType === SPECIAL_MANNEQUIN;
|
||||
|
||||
const mannequinOf = item => item.mannequin || {colors: [0, 0, 0], pattern: 0, eyes: 0, worn: [0, 0, 0, 0, 0]};
|
||||
|
||||
const mannequinBody = ({colors, pattern, eyes}) => [colors[0], colors[1], pattern, colors[2], eyes];
|
||||
|
||||
// the clothing a mannequin of `owner`'s wears, slot by slot (undefined for
|
||||
// an empty slot or a piece the owner no longer has).
|
||||
const mannequinClothes = (owner, item) => mannequinOf(item).worn.map(inv => (inv ? owner.items.find(piece => piece.inv === inv) : undefined));
|
||||
|
||||
// for the owner's own list (MannequinData.setupDataInvIdsOnly): the body,
|
||||
// then the five inventory ids.
|
||||
const mannequinOwnFields = (owner, item) =>
|
||||
(isMannequin(item) ? [...mannequinBody(mannequinOf(item)), ...mannequinClothes(owner, item).map(piece => (piece ? piece.inv : 0))] : []);
|
||||
|
||||
// for whoever looks at the den (setupDataFull): the body, then for each
|
||||
// slot the clothing's def id and, when there is one, its colour and
|
||||
// inventory id.
|
||||
const mannequinShownFields = (owner, item) =>
|
||||
(isMannequin(item) ? [...mannequinBody(mannequinOf(item)), ...mannequinClothes(owner, item).flatMap(piece => (piece ? [piece.def, piece.color, piece.inv] : [0]))] : []);
|
||||
|
||||
// what the den editor sent for one mannequin, checked: [baseColor,
|
||||
// patternColor, patternDefId, eyeColor, eyeDefId, tail, leg, back, neck,
|
||||
// head]. null when any of it is not a whole number in range.
|
||||
const readMannequin = (account, fields) => {
|
||||
if (fields.length !== 10 || !fields.every(isUint)) {
|
||||
return null;
|
||||
}
|
||||
const [base, patternColor, pattern, eyeColor, eyes, ...worn] = fields.map(Number);
|
||||
const bodyPart = (defId, layer) => (defId && (defpacks.itemDef(defId) || {}).layerId === layer ? defId : 0);
|
||||
return {
|
||||
colors: [base, patternColor, eyeColor],
|
||||
pattern: bodyPart(pattern, LAYER_PATTERN),
|
||||
eyes: bodyPart(eyes, LAYER_EYES),
|
||||
worn: worn.map((inv, slot) => {
|
||||
const piece = inv && account.items.find(candidate => candidate.inv === inv);
|
||||
const def = piece && defpacks.itemDef(piece.def);
|
||||
return def && MANNEQUIN_SLOT_LAYERS[slot].includes(def.layerId) ? inv : 0;
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
// DenXtCommManager.denItemsResponse: [activeDenIdx, count, ?, (invIdx, defId,
|
||||
// placed, version, approved, imageId, creatorDbId, creatorUuid, [mannequin],
|
||||
// denStoreInvId)...]. the three after "approved" are a masterpiece's
|
||||
// (lib/masterpieces.js); one not approved yet the client keeps out of dens,
|
||||
// trades and the recycler.
|
||||
const sendDenItems = session => {
|
||||
const {account} = session;
|
||||
const {denItems} = account;
|
||||
session.sendXt("di", -1, account.activeDen, denItems.length, 0,
|
||||
...denItems.flatMap(item => [item.inv, item.def, item.placed ? 1 : 0, item.version, masterpieces.itemApproved(item), ...masterpieces.itemFields(item),
|
||||
...mannequinOwnFields(account, item), 0]));
|
||||
};
|
||||
|
||||
// DenXtCommManager.denStateResponse: [itemCount, petCount, forceReload,
|
||||
// (invIdx, defId, placed, x, y, version, flipped, userNameLink, imageId,
|
||||
// creatorDbId, creatorUuid, [mannequin], ?)...]. forceReload makes the client finish a
|
||||
// pending room change, so it is set when the den has just been entered.
|
||||
const sendDenState = (session, room, forceReload = true) => {
|
||||
const placed = room.denOwner.denItems.filter(item => item.placed && item.den === room.denOwner.activeDen && masterpieces.itemApproved(item));
|
||||
session.sendXt("ds", room.id, placed.length, 0, forceReload ? 1 : 0,
|
||||
...placed.flatMap(item => [item.inv, item.def, 1, item.x, item.y, item.version, item.flip, "", ...masterpieces.itemFields(item),
|
||||
...mannequinShownFields(room.denOwner, item), 0]));
|
||||
};
|
||||
|
||||
// adds a den item to an account; used by purchases, prizes and the item
|
||||
// finder. null when the inventory is full.
|
||||
const giveDenItem = (account, defId, version = 0) => {
|
||||
if (!hasRoom(account, "denItems")) {
|
||||
return null;
|
||||
}
|
||||
const item = {inv: account.nextInv++, def: Number(defId), version: Number(version) || 0, placed: false, den: account.activeDen, x: 0, y: 0, flip: 0};
|
||||
account.denItems.push(item);
|
||||
accounts.save();
|
||||
return item;
|
||||
};
|
||||
|
||||
// puts every placed item back in the owner's inventory and empties the den
|
||||
// on the screens of everyone inside it (DenXtCommManager.denEmptyResponse).
|
||||
const clearDen = (owner, findOnline) => {
|
||||
// kept so that "!den undo" can put it back (lib/commands.js).
|
||||
const placed = owner.denItems.filter(item => item.placed && item.den === owner.activeDen);
|
||||
if (placed.length) {
|
||||
owner.denUndo = {den: owner.activeDen, items: placed.map(item => ({def: item.def, version: item.version, x: item.x, y: item.y, flip: item.flip}))};
|
||||
}
|
||||
for (const item of owner.denItems.filter(candidate => candidate.den === owner.activeDen)) {
|
||||
item.placed = false;
|
||||
item.x = item.y = item.flip = 0;
|
||||
}
|
||||
accounts.save();
|
||||
const ownerSession = findOnline(owner.username);
|
||||
const room = ownerSession && ownerSession.room && ownerSession.room.denOwner === owner ? ownerSession.room : null;
|
||||
for (const session of room ? room.sessions : []) {
|
||||
session.sendXt("de", room.id);
|
||||
}
|
||||
if (ownerSession) {
|
||||
sendDenItems(ownerSession);
|
||||
}
|
||||
};
|
||||
|
||||
// the room a player's den in use is: {base, defId, enviroType, roomType, secondaryDefId}.
|
||||
const denRoom = owner => {
|
||||
const den = activeDen(owner);
|
||||
const base = defpacks.denRoomName(den.def) || defpacks.denRoomName(config.denDefId);
|
||||
const def = defpacks.roomDef(base);
|
||||
return {base, defId: Number(def.id), enviroType: Number(def.type), roomType: ROOM_TYPE_DEN, secondaryDefId: den.def};
|
||||
};
|
||||
|
||||
// RoomXtCommManager.roomPropertiesResponse -> RoomManagerWorld.loadRoom
|
||||
// (path, enviroType, roomType, secondaryDefId, zoom, roomDefId, customData)
|
||||
const sendRoomProperties = (session, room) => {
|
||||
// customData is JSON the room is made with; made when asked for, so that
|
||||
// it is current (a function on the room, or nothing).
|
||||
const customData = room.customData ? JSON.stringify(room.customData()) : "";
|
||||
session.sendXt("rp", room.id, room.base, room.enviroType, room.roomType, room.secondaryDefId, 100, room.defId, customData);
|
||||
};
|
||||
|
||||
const handlers = ({others, findOnline}) => {
|
||||
const inOwnDen = session => session.room && session.room.denOwner === session.account;
|
||||
|
||||
// DenXtCommManager.denListResponse: [count, (invId, denDefId)...]
|
||||
const sendDenList = session => {
|
||||
const {dens} = session.account;
|
||||
session.sendXt("dl", -1, dens.length, ...dens.flatMap(den => [den.inv, den.def]));
|
||||
};
|
||||
|
||||
// A den room from a den shop, paid for in gems. the client asks for the
|
||||
// den list again by itself once the purchase is confirmed.
|
||||
// A den's inventory id is the slot it sits in on the den switcher (0 to
|
||||
// 199): the client asks for the slot it wants filled, keeps its den list
|
||||
// by that number and looks the new den up there when the purchase is
|
||||
// confirmed (DenSwitcher.purchasedDenRoomCallback).
|
||||
const freeSlot = (account, wanted) => {
|
||||
const taken = new Set(account.dens.map(den => den.inv));
|
||||
if (Number.isInteger(wanted) && wanted >= 0 && wanted < MAX_DENS && !taken.has(wanted)) {
|
||||
return wanted;
|
||||
}
|
||||
return Array.from({length: MAX_DENS}, (_, slot) => slot).find(slot => !taken.has(slot));
|
||||
};
|
||||
|
||||
const buyDen = (session, defId, isDiamond, slot) => {
|
||||
const {account} = session;
|
||||
// den rooms priced in gems have no currency field of their own.
|
||||
const purchase = resolvePurchase(defId, isDiamond, "denRoom", id => ({cost: Number((defpacks.denRoomDef(id) || {}).cost) || 0, currencyType: 0}));
|
||||
const currency = purchase && CURRENCIES[purchase.currencyType];
|
||||
if (!purchase || !defpacks.denRoomDef(purchase.defId) || !defpacks.denRoomName(purchase.defId) || account.dens.length >= MAX_DENS
|
||||
|| (account.currency[currency] || 0) < purchase.cost) {
|
||||
session.sendXt("db", -1, 0, "", 0, 0, 0);
|
||||
return;
|
||||
}
|
||||
account.currency[currency] -= purchase.cost;
|
||||
achievements.currencyChanged(account, currency, -purchase.cost);
|
||||
account.dens.push({inv: freeSlot(account, /^\d{1,3}$/.test(String(slot)) ? Number(slot) : NaN), def: purchase.defId});
|
||||
accounts.save();
|
||||
session.sendXt("db", -1, 1, account.currency[currency], 0, purchase.currencyType, 0);
|
||||
sendDenList(session);
|
||||
};
|
||||
|
||||
// A painting framed: the Art Studio's purchase (lib/masterpieces.js, step
|
||||
// 3), paid with two diamonds or with a Masterpiece Token from the
|
||||
// inventory. the reply's last field is the new item's inventory id.
|
||||
const buyMasterpiece = (session, defId, frame, withToken, paintingId) => {
|
||||
const {account} = session;
|
||||
const diamond = defpacks.diamondDef(defId);
|
||||
const cost = diamond ? Number(diamond.cost) : 0;
|
||||
const token = account.denItems.find(item => item.def === masterpieces.TOKEN_DEN_ITEM);
|
||||
if (defId !== masterpieces.DIAMOND_DEF || !diamond || !masterpieces.claimable(account, paintingId, frame)
|
||||
|| account.denItems.length >= MAX_DEN_ITEMS || (withToken ? !token : (account.currency.diamonds || 0) < cost)) {
|
||||
session.sendXt("db", -1, 0, "", 0, 0, 0);
|
||||
return;
|
||||
}
|
||||
if (withToken) {
|
||||
account.denItems.splice(account.denItems.indexOf(token), 1);
|
||||
}
|
||||
else {
|
||||
account.currency.diamonds -= cost;
|
||||
achievements.currencyChanged(account, "diamonds", -cost);
|
||||
}
|
||||
masterpieces.claim(paintingId, frame);
|
||||
const item = giveDenItem(account, masterpieces.DEN_ITEM, frame);
|
||||
item.image = String(paintingId);
|
||||
accounts.save();
|
||||
console.log(`[world] ${account.username} made masterpiece ${item.image}${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);
|
||||
};
|
||||
|
||||
return {
|
||||
di(session) {
|
||||
sendDenItems(session);
|
||||
},
|
||||
|
||||
// PlayerWallGui.setupMasterpieces and the like: [username] -> the
|
||||
// approved masterpieces that player has (denMasterpieceInventoryResponse:
|
||||
// [count, (defId, invIdx, version, approved, imageId, creatorDbId,
|
||||
// creatorUuid)...]).
|
||||
dmi(session, roomId, [username]) {
|
||||
const owner = accounts.byName(username);
|
||||
const hung = owner ? owner.denItems.filter(item => item.image && masterpieces.itemApproved(item)) : [];
|
||||
session.sendXt("dmi", -1, hung.length, ...hung.flatMap(item => [item.def, item.inv, item.version, "true", ...masterpieces.itemFields(item)]));
|
||||
},
|
||||
|
||||
// MasterpiecePreview: [ownerName, paintingId] -> [who painted it]
|
||||
dmc(session, roomId, [, paintingId]) {
|
||||
const maker = masterpieces.creatorOf(paintingId);
|
||||
session.sendXt("dmc", -1, maker ? maker.username : "");
|
||||
},
|
||||
|
||||
// DenXtCommManager.requestBuy: ["0" item | "-1" den room, shopId, defId,
|
||||
// version (items) or den slot (rooms), isDiamondItem, ...]. for something
|
||||
// priced in diamonds defId is its diamond def's id. the reply
|
||||
// (denBuyResponse) is [status, newAmount, ?, currencyType, ?].
|
||||
db(session, roomId, [kind, shopId, defId, version, isDiamondItem, isMasterpiece, withToken, paintingId]) {
|
||||
const {account} = session;
|
||||
if (kind === "-1") {
|
||||
buyDen(session, defId, isDiamondItem === "1", version);
|
||||
return;
|
||||
}
|
||||
if (kind === "0" && isMasterpiece === "1") {
|
||||
buyMasterpiece(session, Number(defId), Number(version), withToken === "1", paintingId);
|
||||
return;
|
||||
}
|
||||
const purchase = resolvePurchase(defId, isDiamondItem === "1", "denItem", id => {
|
||||
const own = defpacks.denItemDef(id);
|
||||
return {cost: own ? Number(own.cost) : 0, currencyType: own ? Number(own.currencyType) : -1};
|
||||
});
|
||||
const def = purchase && defpacks.denItemDef(purchase.defId);
|
||||
const currency = purchase && CURRENCIES[purchase.currencyType];
|
||||
// combined costs and special item types other than mannequins are refused.
|
||||
if (kind !== "0" || !def || !defpacks.denItemIds().includes(purchase.defId) || !currency
|
||||
|| account.denItems.length >= MAX_DEN_ITEMS || (account.currency[currency] || 0) < purchase.cost) {
|
||||
session.sendXt("db", -1, 0, "", 0, 0, 0);
|
||||
return;
|
||||
}
|
||||
account.currency[currency] -= purchase.cost;
|
||||
achievements.currencyChanged(account, currency, -purchase.cost);
|
||||
achievements.add(account, achievements.VARS.denItemsBought);
|
||||
giveDenItem(account, purchase.defId, version);
|
||||
session.sendXt("db", -1, 1, account.currency[currency], 0, purchase.currencyType, 0);
|
||||
sendDenItems(session);
|
||||
},
|
||||
|
||||
// DenXtCommManager.requestDenStateChange: [count, (refType, invIdx, placed,
|
||||
// x, y, flipped, userNameLink, 10 mannequin fields)...]. the reply
|
||||
// (DenEditor.onDenSaveSet) lists the inventory ids that were applied.
|
||||
ds(session, roomId, params) {
|
||||
const {account} = session;
|
||||
const count = Number(params[0]);
|
||||
if (!Number.isInteger(count) || count < 0 || count > MAX_SAVED_AT_ONCE || params.length !== 1 + count * FIELDS_PER_SAVED_ITEM) {
|
||||
session.sendXt("dss", -1);
|
||||
return;
|
||||
}
|
||||
const applied = [];
|
||||
const byInv = new Map(account.denItems.map(candidate => [candidate.inv, candidate]));
|
||||
const mannequins = account.denItems.filter(candidate => candidate.mannequin);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const [refType, invIdx, placed, x, y, flip, , ...outfit] = params.slice(1 + i * FIELDS_PER_SAVED_ITEM, 1 + (i + 1) * FIELDS_PER_SAVED_ITEM);
|
||||
const item = byInv.get(Number(invIdx));
|
||||
if (refType !== REF_DEN_ITEM || !item || ![x, y, flip].every(value => Number.isInteger(Number(value)))
|
||||
|| (placed === "1" && !masterpieces.itemApproved(item))) {
|
||||
continue;
|
||||
}
|
||||
item.placed = placed === "1";
|
||||
item.den = account.activeDen;
|
||||
item.x = item.placed ? Number(x) : 0;
|
||||
item.y = item.placed ? Number(y) : 0;
|
||||
item.flip = item.placed ? Number(flip) : 0;
|
||||
const mannequin = isMannequin(item) && readMannequin(account, outfit);
|
||||
if (mannequin) {
|
||||
// A piece of clothing is on one mannequin at a time.
|
||||
for (const other of mannequins) {
|
||||
if (other !== item && other.mannequin) {
|
||||
other.mannequin.worn = other.mannequin.worn.map(inv => (mannequin.worn.includes(inv) ? 0 : inv));
|
||||
}
|
||||
}
|
||||
if (!item.mannequin) {
|
||||
mannequins.push(item);
|
||||
}
|
||||
item.mannequin = mannequin;
|
||||
}
|
||||
applied.push(item.inv);
|
||||
}
|
||||
accounts.save();
|
||||
session.sendXt("dss", -1, ...applied);
|
||||
if (inOwnDen(session)) {
|
||||
for (const other of others(session)) {
|
||||
sendDenState(other, session.room, false);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// DenXtCommManager.requestRecycle: ["0" items | "-1" den rooms, "inv,inv,..."].
|
||||
// the reply (denRecycleResponse) is [count, newGemTotal, ...recycledInvIdx],
|
||||
// and the recycling window then waits for a den item list (its
|
||||
// recycleDiCallback) before it lets go of its spinner.
|
||||
dr(session, roomId, [kind, invList]) {
|
||||
const {account} = session;
|
||||
const recycled = [];
|
||||
for (const invIdx of kind === "0" ? new Set(String(invList).split(",", MAX_RECYCLED_AT_ONCE).map(Number)) : []) {
|
||||
const index = account.denItems.findIndex(item => item.inv === invIdx);
|
||||
if (index === -1 || !masterpieces.itemApproved(account.denItems[index])) {
|
||||
continue;
|
||||
}
|
||||
const def = defpacks.denItemDef(account.denItems[index].def);
|
||||
if (def && def.currencyType === "0") {
|
||||
const refund = Number(def.recycleValue) || Math.floor(Number(def.cost) * RECYCLE_FRACTION);
|
||||
account.currency.gems += refund;
|
||||
achievements.currencyChanged(account, "gems", refund);
|
||||
}
|
||||
account.denItems.splice(index, 1);
|
||||
recycled.push(invIdx);
|
||||
}
|
||||
accounts.save();
|
||||
session.sendXt("dr", -1, recycled.length, account.currency.gems, ...recycled);
|
||||
if (recycled.length) {
|
||||
sendDenItems(session);
|
||||
}
|
||||
if (recycled.length && inOwnDen(session)) {
|
||||
for (const other of others(session)) {
|
||||
sendDenState(other, session.room, false);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// DenXtCommManager.requestEmptyDen: the owner's own "clear den" button.
|
||||
de(session) {
|
||||
clearDen(session.account, findOnline);
|
||||
if (!inOwnDen(session)) {
|
||||
session.sendXt("de", -1);
|
||||
}
|
||||
},
|
||||
|
||||
dl(session) {
|
||||
sendDenList(session);
|
||||
},
|
||||
|
||||
// DenXtCommManager.requestDenChange: [denInvIdx]. the reply
|
||||
// (denChangeResponse: [denDefId, perUserAvId, petInvId]) makes the owner's
|
||||
// client load the new den; visitors are sent the new room as well.
|
||||
dc(session, roomId, [invIdx]) {
|
||||
const {account} = session;
|
||||
const den = account.dens.find(candidate => candidate.inv === Number(invIdx));
|
||||
if (!den) {
|
||||
return;
|
||||
}
|
||||
account.activeDen = den.inv;
|
||||
accounts.save();
|
||||
const avatar = activeAvatar(account);
|
||||
session.sendXt("dc", -1, den.def, avatar.perUserAvId, avatar.petInvId);
|
||||
if (inOwnDen(session)) {
|
||||
const {room} = session;
|
||||
Object.assign(room, denRoom(account));
|
||||
for (const other of others(session)) {
|
||||
sendRoomProperties(other, room);
|
||||
}
|
||||
for (const occupant of room.sessions) {
|
||||
sendDenState(occupant, room);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// the "Epic Dens" list on the world map (denHighestResponse: [count,
|
||||
// name...]): today's showcase dens, see lib/epicdens.js.
|
||||
dh(session) {
|
||||
const names = epicDens.list();
|
||||
session.sendXt("dh", -1, names.length, ...names);
|
||||
},
|
||||
|
||||
// ["1", username]: who may enter that player's den?
|
||||
// (BuddyManager.onDenPrivacyResponse: [username, setting])
|
||||
// ["0", setting]: change one's own setting.
|
||||
dp(session, roomId, [mode, value]) {
|
||||
if (mode === "1") {
|
||||
const owner = accounts.byName(value);
|
||||
session.sendXt("dp", -1, value, owner ? owner.denPrivacy : DEN_LOCKED);
|
||||
}
|
||||
else if ([DEN_LOCKED, DEN_BUDDIES_ONLY, DEN_OPEN].includes(Number(value))) {
|
||||
session.account.denPrivacy = Number(value);
|
||||
accounts.save();
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = {handlers, sendDenState, sendDenItems, sendRoomProperties, giveDenItem, clearDen, denRoom, canEnter, DEF_DEN_ROOM};
|
||||
@@ -0,0 +1,74 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
|
||||
// playing as one of the game's characters ("!become liza").
|
||||
//
|
||||
// the alphas were animals players could not be: in 2013 they were animal
|
||||
// types of their own (2, 3, 9 to 12, since given to the eagle, deer, hyena,
|
||||
// otter, polar bear and owl), and that artwork is gone. what is left of
|
||||
// them is in the NPC table (defPack 1025): the clips the adventures put on
|
||||
// the map, each a drawing that can stand, face left or right, talk, cast
|
||||
// and so on, but not walk.
|
||||
//
|
||||
// the client has one way to draw a player as something from that table:
|
||||
// the Phantomizer den item, which swaps a player's animal for NPC 2, a
|
||||
// phantom, that then follows it about (DenXtCommManager.denPhantomResponse,
|
||||
// "dph": [ok, sfsUserId, on]). the patched client takes the NPC's id from
|
||||
// one more field of that message (XtReplyDemuxer, avatar.NPCView in
|
||||
// swf-src/). so a disguise is a "dph" that follows a player's animal
|
||||
// wherever the client is told of the animal.
|
||||
//
|
||||
// what does not work, by the nature of it: the clip glides, as it has no
|
||||
// walk; the animal under it still does everything, unseen (sit, dance,
|
||||
// clothes); and a client keeps the first disguise it drew for an animal
|
||||
// until that animal is drawn afresh, so changing from one to another shows
|
||||
// when the player next changes rooms.
|
||||
|
||||
const NPC_PHANTOM = 2; // what the client draws when no id is given
|
||||
const TYPE_CLIP = "0";
|
||||
const TYPE_ANIMAL = "1"; // an ordinary animal in an outfit: the villagers of the adventures
|
||||
|
||||
// the names "!become" takes, with the NPC each is.
|
||||
const NAMED = new Map([
|
||||
["peck", 20], ["liza", 21], ["greely", 22], ["graham", 23], ["gilbert", 24], ["cosmo", 25], ["tavie", 219],
|
||||
["phantom", NPC_PHANTOM],
|
||||
]);
|
||||
|
||||
// is this NPC one a player can be drawn as? clips with no artwork (two
|
||||
// rows have none) would leave them invisible.
|
||||
const usable = id => {
|
||||
const def = defpacks.npcDef(id);
|
||||
return Boolean(def) && (def.type === TYPE_ANIMAL || (def.type === TYPE_CLIP && Number(def.mediaRefId) > 0));
|
||||
};
|
||||
|
||||
// the NPC id for what a player typed (a name above or a number), or null.
|
||||
const find = text => {
|
||||
const word = String(text).toLowerCase();
|
||||
const id = NAMED.has(word) ? NAMED.get(word) : /^\d{1,4}$/.test(word) ? Number(word) : NaN;
|
||||
return usable(id) ? id : null;
|
||||
};
|
||||
|
||||
const of = account => (usable(account.disguise) ? account.disguise : 0);
|
||||
|
||||
// tells `to` how `subject` (a session whose animal `to` has just been told
|
||||
// of, or has on screen) is disguised, if at all.
|
||||
const show = (to, subject) => {
|
||||
const id = of(subject.account);
|
||||
if (id) {
|
||||
to.sendXt("dph", -1, 1, subject.id, 1, id);
|
||||
}
|
||||
};
|
||||
|
||||
// puts a disguise on (an NPC id) or takes it off (0). the player's own
|
||||
// client is told here; `redraw` puts their animal on everyone else's screen
|
||||
// afresh, which brings the disguise with it (`show`).
|
||||
const set = (session, id, redraw) => {
|
||||
session.account.disguise = id;
|
||||
accounts.save();
|
||||
session.sendXt("dph", -1, 1, session.id, id ? 1 : 0, id || NPC_PHANTOM);
|
||||
redraw(session);
|
||||
};
|
||||
|
||||
module.exports = {find, of, show, set, names: () => [...NAMED.keys()]};
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"cards": [1,2,3,4,5,7,8,86,118,119,124,128,152,154,155,201,283,284,329,346,355,356,361,380,382,384,385,387,388,389,390,391,1188,1206,1211,1222,1228,1242,1249,1250,1251,1354,1426,1520,1627,1768,1933,2235,2649,2697,2700,2702,2703,2704,2705,2706,2707,2708,2709,2711,2712,2713,2714,2715,2716,2717,2720,2723,2762,2763,2805,2806,2807,2808,2809,2810,2811,2812,2813,2814,2815,2816,2817,2818,2819,2820,2821,2822,2823,2824,2825,2826,2827,2828,3749,4393,4410,4411,4434,4435,4451,4452,4453,4454,4455,4457,4460,4461,4462,4464,4465,4466,4467,4468,4469,4470,4477,4478,4479,4538,4539,4540,4541,4542,4543,4544,4545,4546,4547,4548,4549,4777,4778,4779,4780,4855,4856,4946,5023,5024,5026,5066,5067,5068,5069,5070,5071,5073,5074,5075,5076,5077,5078,5079,5080,5081,5082,5083,5084,5085,5086,5087,5088,5089,5090,5091,5092,5093,5094,5095,5099,5100,5738,5980,5981,6130,6138,9013,9014,9015,9016,9017,9167,9170,9172,9174,9175,9326,9327,9328,9329,9330,9331,9332],
|
||||
"stamps": [10,11,12,13,15,16,17,18,19,20,21,22,23]
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const accounts = require("./accounts.js");
|
||||
const achievements = require("./achievements.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const dens = require("./dens.js");
|
||||
const limits = require("./limits.js");
|
||||
const {isSilenced} = require("./moderation.js");
|
||||
const {CURRENCIES, hasRoom, addClothing, sendClothingAdded, sendClothingRemoved} = require("./player.js");
|
||||
|
||||
// Jam-A-Grams (client side: ECardManager, ECardInbox, ECardCreation,
|
||||
// ECardXtCommManager): a card, a stamp, a short message and perhaps a gift,
|
||||
// kept in the receiver's inbox (account.ecards) until they delete it.
|
||||
//
|
||||
// which cards and stamps exist was a list on the official servers. the ones
|
||||
// offered here were found by looking through the CDN's media files for card
|
||||
// artwork (tools/find-art.py found what is in lib/ecard-art.json).
|
||||
|
||||
// ECard.type: what, if anything, comes with the card
|
||||
const TYPE_PLAIN = 0;
|
||||
const TYPE_CLOTHING = 1;
|
||||
const TYPE_DEN_ITEM = 3;
|
||||
const TYPE_GEMS = 4;
|
||||
const TYPE_DIAMONDS = 9;
|
||||
const CURRENCY_OF = {[TYPE_GEMS]: 0, [TYPE_DIAMONDS]: 3};
|
||||
|
||||
// ECard senderType
|
||||
const FROM_PLAYER = 0;
|
||||
// "The voice": Animal Jam HQ. the sender's name is then the id of a
|
||||
// localization string, the inbox shows the AJ badge in place of a stamp and
|
||||
// the gift comes in the HQ gift popup (ECardInbox.setupGiftPopup).
|
||||
const FROM_HQ = 1;
|
||||
// A card the client never lists: it opens as a gift popup by itself, at
|
||||
// login or when told to look (StartupPopups.redemptionCardsRequest). the
|
||||
// inbox cannot open gems or diamonds, so those come this way.
|
||||
const FROM_REDEMPTION = 2;
|
||||
const HQ_NAME_STRING = 15964; // "Animal Jam HQ" in the game's text, "Burrow HQ" as this server sends it (lib/defpacks.js)
|
||||
const HQ_NAME = "Burrow HQ";
|
||||
const MEMBER = 2; // account type the client draws a full name bar for
|
||||
// ECard specialType: the receiver is shown "Secret Valentine" as the sender.
|
||||
const SECRET_VALENTINE = 1;
|
||||
|
||||
// ECardCreation.onSentResponseCallback
|
||||
const SENT = 1;
|
||||
const INBOX_FULL = -1;
|
||||
const NOT_ACCEPTING = -2;
|
||||
const FAILED = 0;
|
||||
|
||||
// who may send to a player (ECardInbox's settings popup).
|
||||
const FROM_EVERYONE = 0;
|
||||
const FROM_BUDDIES = 1;
|
||||
const FROM_NOBODY = 2;
|
||||
|
||||
const LIST_CARDS = 10;
|
||||
const LIST_STAMPS = 44;
|
||||
const MAX_INBOX = 500;
|
||||
const MAX_MESSAGE = 200;
|
||||
const USERNAME_SHOWN = 1;
|
||||
|
||||
const art = JSON.parse(fs.readFileSync(path.join(__dirname, "ecard-art.json"), "utf8"));
|
||||
const sendsPerTenMinutes = limits.limiter(40, 600000);
|
||||
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
const clean = text => String(text).replace(/[\u0000-\u001f\u007f%]/g, " ").trim().slice(0, MAX_MESSAGE);
|
||||
|
||||
module.exports = ({findOnline, blocks}) => {
|
||||
// A card from the server carrying gems or diamonds: one of the popups.
|
||||
const isRedemption = card => Boolean(card.hq && card.gift && Object.hasOwn(CURRENCY_OF, card.gift.type));
|
||||
|
||||
// who sent a card: by account id, and for cards from before ids were
|
||||
// kept by the name on them.
|
||||
const senderOf = card => (card.fromId ? accounts.byId(card.fromId) : accounts.byName(card.from));
|
||||
|
||||
// the 17 fields ECard.init takes, for one card. A secret valentine's
|
||||
// sender is known here (reports about it reach them) but not sent.
|
||||
const fields = card => {
|
||||
const sender = card.hq ? null : senderOf(card);
|
||||
const senderType = isRedemption(card) ? FROM_REDEMPTION : card.hq ? FROM_HQ : FROM_PLAYER;
|
||||
const name = card.secret ? "" : senderType === FROM_HQ ? HQ_NAME_STRING : card.hq ? HQ_NAME : card.from;
|
||||
return [
|
||||
card.id, name, card.card, card.stamp, card.read ? 1 : 0, card.msg, card.gift ? card.gift.type : TYPE_PLAIN,
|
||||
card.gift ? card.gift.def : 0, card.gift ? card.gift.color : 0, card.gift ? card.gift.name : 0,
|
||||
card.hq || card.secret ? MEMBER : sender ? sender.accountType : 0,
|
||||
0, // name bar data
|
||||
0, // secondary type
|
||||
senderType,
|
||||
USERNAME_SHOWN,
|
||||
"", // additional gift data
|
||||
card.secret ? SECRET_VALENTINE : 0,
|
||||
];
|
||||
};
|
||||
|
||||
const inInbox = account => account.ecards.filter(card => !isRedemption(card));
|
||||
const unread = account => inInbox(account).filter(card => !card.read).length;
|
||||
// gift popups waiting for the player: numRedemptionCards in the login message.
|
||||
const redemptions = account => account.ecards.filter(isRedemption).length;
|
||||
|
||||
// puts a card in an inbox and, if its owner is playing, on their screen
|
||||
// (ECardXtCommManager.eCardPushHandler). the caller saves.
|
||||
const deliver = (to, card) => {
|
||||
const stored = {id: to.nextInv++, read: false, ts: now(), ...card};
|
||||
to.ecards.push(stored);
|
||||
const session = findOnline(to.username);
|
||||
if (session && isRedemption(stored)) {
|
||||
// GameRedemptionXtCommManager.handleRedeemCodeResponse: "a code was
|
||||
// redeemed", which has the client fetch its cards and open the popups.
|
||||
session.sendXt("grc", -1, 1, "", 0);
|
||||
}
|
||||
else if (session) {
|
||||
session.sendXt("ep", -1, ...fields(stored));
|
||||
}
|
||||
return stored;
|
||||
};
|
||||
|
||||
// A gift from the server itself (the admin panel), as a Jam-A-Gram from
|
||||
// Animal Jam HQ. `gift` is {kind: "clothing" | "den", id, color} for an
|
||||
// item, which waits in the inbox, or {kind: "gems" | "diamonds", amount},
|
||||
// which pops up by itself. returns null, or why it could not be sent.
|
||||
const sendFromHq = (to, text, gift) => {
|
||||
if (to.ecards.length >= MAX_INBOX) {
|
||||
return "Their Jam-A-Gram inbox is full";
|
||||
}
|
||||
let attached;
|
||||
if (gift.kind === "clothing") {
|
||||
const def = defpacks.itemDef(gift.id);
|
||||
const colors = def ? String(def.colors).split(",") : [];
|
||||
if (!def || !defpacks.clothingIds().includes(Number(def.id))) {
|
||||
return "No such clothing item";
|
||||
}
|
||||
attached = {type: TYPE_CLOTHING, def: Number(def.id), color: Number(gift.color === undefined ? colors[0] : gift.color), name: Number(def.titleStrId)};
|
||||
}
|
||||
else if (gift.kind === "den") {
|
||||
const def = defpacks.denItemIds().includes(Number(gift.id)) && defpacks.denItemDef(gift.id);
|
||||
if (!def) {
|
||||
return "No such den item";
|
||||
}
|
||||
attached = {type: TYPE_DEN_ITEM, def: Number(def.id), color: 0, name: Number(def.nameStrId), version: 0};
|
||||
}
|
||||
else {
|
||||
// for these the card's "gift id" and "gift name" are both the amount.
|
||||
attached = {type: gift.kind === "gems" ? TYPE_GEMS : TYPE_DIAMONDS, def: gift.amount, color: 0, name: gift.amount};
|
||||
}
|
||||
// the gift popup takes a message that starts with a number for the id of
|
||||
// a localization string (StartupPopups.setupGiftPopup).
|
||||
const message = clean(text).replace(/^(?=[\s+-]*\d)/, "Gift: ");
|
||||
deliver(to, {from: HQ_NAME, hq: true, card: art.cards[0], stamp: 0, msg: message, gift: attached});
|
||||
accounts.save();
|
||||
return null;
|
||||
};
|
||||
|
||||
// A card from Animal Jam HQ with words and nothing else, for news the
|
||||
// server has for one player. false when their inbox is full.
|
||||
const noteFromHq = (to, text) => {
|
||||
if (to.ecards.length >= MAX_INBOX) {
|
||||
return false;
|
||||
}
|
||||
deliver(to, {from: HQ_NAME, hq: true, card: art.cards[0], stamp: 0, msg: clean(text).replace(/^(?=[\s+-]*\d)/, "Note: "), gift: null});
|
||||
accounts.save();
|
||||
return true;
|
||||
};
|
||||
|
||||
// the gift a sender attached: one of their own items, taken out of their
|
||||
// inventory until the receiver accepts or throws the card away.
|
||||
const takeGift = (session, type, invIdx) => {
|
||||
const {account} = session;
|
||||
if (type === TYPE_CLOTHING) {
|
||||
const item = account.items.find(candidate => candidate.inv === invIdx);
|
||||
const def = item && defpacks.itemDef(item.def);
|
||||
if (!def) {
|
||||
return null;
|
||||
}
|
||||
account.items.splice(account.items.indexOf(item), 1);
|
||||
account.tradeList = account.tradeList.filter(listed => !(listed.type === 0 && listed.inv === item.inv));
|
||||
sendClothingRemoved(session, item.inv);
|
||||
return {type, def: item.def, color: item.color, name: Number(def.titleStrId)};
|
||||
}
|
||||
if (type === TYPE_DEN_ITEM) {
|
||||
const item = account.denItems.find(candidate => candidate.inv === invIdx);
|
||||
const def = item && defpacks.denItemDef(item.def);
|
||||
// mannequins and the like stay home, and so do paintings: a card has
|
||||
// no way to say which painting it carries.
|
||||
if (!def || def.specialType !== "0" || item.image) {
|
||||
return null;
|
||||
}
|
||||
account.denItems.splice(account.denItems.indexOf(item), 1);
|
||||
account.tradeList = account.tradeList.filter(listed => !(listed.type === 1 && listed.inv === item.inv));
|
||||
dens.sendDenItems(session);
|
||||
return {type, def: item.def, color: 0, name: Number(def.nameStrId), version: item.version};
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const giveGift = (session, gift) => {
|
||||
const {account} = session;
|
||||
if (gift.type === TYPE_CLOTHING) {
|
||||
sendClothingAdded(session, addClothing(account, gift.def, gift.color));
|
||||
}
|
||||
else if (gift.type === TYPE_DEN_ITEM) {
|
||||
dens.giveDenItem(account, gift.def, gift.version);
|
||||
dens.sendDenItems(session);
|
||||
}
|
||||
else if (Object.hasOwn(CURRENCY_OF, gift.type)) {
|
||||
const currency = CURRENCIES[CURRENCY_OF[gift.type]];
|
||||
account.currency[currency] = (account.currency[currency] || 0) + gift.def;
|
||||
achievements.currencyChanged(account, currency, gift.def);
|
||||
// ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason]
|
||||
session.sendXt("cu", -1, CURRENCY_OF[gift.type], account.currency[currency], 0);
|
||||
}
|
||||
};
|
||||
|
||||
const mayReceiveFrom = (to, from) => {
|
||||
if (blocks.either(to, from) || to.ecardPrivacy === FROM_NOBODY || !accounts.featureOn(to, "jamagrams")) {
|
||||
return false;
|
||||
}
|
||||
return to.ecardPrivacy !== FROM_BUDDIES || to.buddies.includes(from.username.toLowerCase());
|
||||
};
|
||||
|
||||
const handlers = {
|
||||
// ECardXtCommManager.eCardListResponse: [count, 17 fields per card...].
|
||||
// the client reverses what it is sent, to show the newest first.
|
||||
// [forPopups]: "1" when it is looking for gift popups to open rather
|
||||
// than filling the inbox; only then are those cards in the list.
|
||||
el(session, roomId, [forPopups]) {
|
||||
const cards = forPopups === "1" ? session.account.ecards : inInbox(session.account);
|
||||
session.sendXt("el", -1, cards.length, ...cards.flatMap(fields));
|
||||
},
|
||||
|
||||
// ECardCreation.sendECard: [to, cardMediaId, stampMediaId, messageType,
|
||||
// message, giftType, giftInvIdx, isValentine]
|
||||
es(session, roomId, [toName, card, stamp, , message, giftType, giftInvIdx, isValentine]) {
|
||||
const {account} = session;
|
||||
const to = accounts.byName(toName);
|
||||
const reply = status => session.sendXt("es", -1, status);
|
||||
// silenced: no words of their own reach anyone, in a card either.
|
||||
if (!to || to === account || !art.cards.includes(Number(card)) || !art.stamps.includes(Number(stamp))
|
||||
|| !accounts.featureOn(account, "jamagrams") || (isSilenced(account) && clean(message || "") !== "")
|
||||
|| !sendsPerTenMinutes.allow(account.id)) {
|
||||
reply(FAILED);
|
||||
return;
|
||||
}
|
||||
if (!mayReceiveFrom(to, account)) {
|
||||
reply(NOT_ACCEPTING);
|
||||
return;
|
||||
}
|
||||
if (to.ecards.length >= MAX_INBOX) {
|
||||
reply(INBOX_FULL);
|
||||
return;
|
||||
}
|
||||
const wantsGift = [TYPE_CLOTHING, TYPE_DEN_ITEM].includes(Number(giftType));
|
||||
const gift = wantsGift ? takeGift(session, Number(giftType), Number(giftInvIdx)) : null;
|
||||
if (wantsGift && !gift) {
|
||||
reply(FAILED);
|
||||
return;
|
||||
}
|
||||
deliver(to, {from: account.username, fromId: account.id, card: Number(card), stamp: Number(stamp), msg: clean(message || ""), gift,
|
||||
...(isValentine === "1" ? {secret: true} : {})});
|
||||
achievements.add(account, achievements.VARS.jamAGramsSent);
|
||||
if (gift) {
|
||||
achievements.add(account, achievements.VARS.giftsSent);
|
||||
}
|
||||
accounts.save();
|
||||
reply(SENT);
|
||||
},
|
||||
|
||||
// [msgId] -> eCardReadResponse: [msgId, success]
|
||||
er(session, roomId, [msgId]) {
|
||||
const card = session.account.ecards.find(candidate => candidate.id === Number(msgId));
|
||||
if (card) {
|
||||
card.read = true;
|
||||
accounts.save();
|
||||
}
|
||||
session.sendXt("er", -1, msgId, card ? 1 : 0);
|
||||
},
|
||||
|
||||
// [msgId] -> eCardDeleteResponse: [success, count, msgId...]. A gift
|
||||
// still in the card goes with it.
|
||||
ed(session, roomId, [msgId]) {
|
||||
const {account} = session;
|
||||
const before = account.ecards.length;
|
||||
account.ecards = account.ecards.filter(card => card.id !== Number(msgId));
|
||||
accounts.save();
|
||||
session.sendXt("ed", -1, 1, before - account.ecards.length, ...(before === account.ecards.length ? [] : [msgId]));
|
||||
},
|
||||
|
||||
// [msgId, "1" keep | "0" discard] -> eCardGiftResponse: [msgId, success]
|
||||
eg(session, roomId, [msgId, accept]) {
|
||||
const card = session.account.ecards.find(candidate => candidate.id === Number(msgId));
|
||||
if (!card || !card.gift) {
|
||||
session.sendXt("eg", -1, msgId, 0);
|
||||
return;
|
||||
}
|
||||
const {gift} = card;
|
||||
// no room for it: it stays in the card until there is.
|
||||
if (accept === "1" && ((gift.type === TYPE_CLOTHING && !hasRoom(session.account, "items"))
|
||||
|| (gift.type === TYPE_DEN_ITEM && !hasRoom(session.account, "denItems")))) {
|
||||
session.sendXt("eg", -1, msgId, 0);
|
||||
return;
|
||||
}
|
||||
if (isRedemption(card)) {
|
||||
// A popup's card is gone once answered, as the client assumes.
|
||||
session.account.ecards = session.account.ecards.filter(candidate => candidate !== card);
|
||||
}
|
||||
card.gift = null;
|
||||
if (accept === "1") {
|
||||
giveGift(session, gift);
|
||||
}
|
||||
accounts.save();
|
||||
session.sendXt("eg", -1, msgId, 1);
|
||||
},
|
||||
|
||||
// [setting] -> eCardIsolationHandler: [success]
|
||||
ei(session, roomId, [setting]) {
|
||||
const value = Number(setting);
|
||||
const valid = [FROM_EVERYONE, FROM_BUDDIES, FROM_NOBODY].includes(value);
|
||||
if (valid) {
|
||||
session.account.ecardPrivacy = value;
|
||||
accounts.save();
|
||||
}
|
||||
session.sendXt("ei", -1, valid ? 1 : 0);
|
||||
},
|
||||
|
||||
// answering a buddy request that came as a card; requests here do not.
|
||||
eb() {},
|
||||
// "I closed the inbox after deleting something": nothing is cached here.
|
||||
ec() {},
|
||||
};
|
||||
|
||||
// GenericListXtCommManager.handleMediaResponse: (mediaId, name) pairs; null
|
||||
// when `listId` is neither the cards' nor the stamps' list.
|
||||
const list = listId => {
|
||||
const ids = {[LIST_CARDS]: art.cards, [LIST_STAMPS]: art.stamps}[Number(listId)];
|
||||
return ids ? ids.flatMap(id => [id, 0]) : null;
|
||||
};
|
||||
|
||||
// who sent the newest secret valentine in this inbox: the game reports
|
||||
// such a card as being from "Secret Valentine".
|
||||
const secretSender = account => {
|
||||
const card = [...account.ecards].reverse().find(candidate => candidate.secret);
|
||||
return card ? senderOf(card) : null;
|
||||
};
|
||||
|
||||
return {handlers, list, unread, redemptions, sendFromHq, noteFromHq, secretSender, SECRET_NAME: "Secret Valentine"};
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
"use strict";
|
||||
|
||||
const defpacks = require("./defpacks.js");
|
||||
|
||||
// Epic Dens: the world map's list of dens worth a visit (client side:
|
||||
// VolumeSelector, DenXtCommManager.requestDenHighest).
|
||||
//
|
||||
// the official list named players, and its "AJHQ" button led to a showcase
|
||||
// den Animal Jam HQ had furnished, a new one every so often, held as party
|
||||
// 36. those showcase dens are still on the CDN, 53 of them, each a whole
|
||||
// room with its furniture in the file. here the list is the showcase dens:
|
||||
// the client shows a name per row and asks to enter "den<that name>", which
|
||||
// the server answers by putting the player in the room. the client draws
|
||||
// twenty rows at most, so the list is a different twenty each day, and the
|
||||
// AJHQ button goes to one more.
|
||||
//
|
||||
// the files do not say what the dens were called. each is named after the
|
||||
// den type it was built in, going by its file name.
|
||||
const KINDS = new Map([
|
||||
["skyden", "Sky Kingdom"], ["ginger", "Gingerbread House"], ["winterp", "Winter Palace"], ["lcastle", "Lucky Castle"],
|
||||
["beach", "Beach House"], ["crystal_", "Crystal Palace"], ["sprgctg", "Spring Cottage"], ["peck", "Peck's Den"],
|
||||
["pixel", "Pixel Place"], ["greely", "Greely's Hideout"], ["gilbert", "Gilbert's Palace"], ["haunted", "Haunted Manor"],
|
||||
["snofort", "Snow Fort"], ["cottage", "Friendship Cottage"], ["liza", "Liza's Garden"], ["barn", "Ol' Barn"],
|
||||
["solarcade", "Sol Arcade"], ["graham", "Graham's Observatory"], ["bounce", "Bounce House"], ["cosmotree", "Cosmo's Tree House"],
|
||||
["waterpark", "Water Park"], ["greelyhalloween", "Haunted Hideout"], ["fallfree", "Autumn House"],
|
||||
["friendshipfortress", "Friendship Fortress"], ["epicbetaden", "Epic Beta Den"],
|
||||
]);
|
||||
const FOLDER = "epic_dens/room_";
|
||||
const ROWS_SHOWN = 20; // VolumeSelector.createDenWindows
|
||||
|
||||
let dens = null; // [{name, base}], in room id order
|
||||
|
||||
const all = () => {
|
||||
if (!dens) {
|
||||
const count = new Map();
|
||||
dens = defpacks.roomPaths().filter(path => path.startsWith(FOLDER)).map(path => {
|
||||
const base = path.replace(/\//g, ".");
|
||||
const kind = path.slice(FOLDER.length).replace(/\d*$/, "");
|
||||
return {title: KINDS.get(kind) || kind, base, id: Number(defpacks.roomDef(base).id)};
|
||||
}).sort((one, other) => one.id - other.id);
|
||||
// "Sky Kingdom 2" where there are several of a kind.
|
||||
for (const den of dens) {
|
||||
count.set(den.title, (count.get(den.title) || 0) + 1);
|
||||
den.number = count.get(den.title);
|
||||
}
|
||||
for (const den of dens) {
|
||||
den.name = count.get(den.title) > 1 ? `${den.title} ${den.number}` : den.title;
|
||||
}
|
||||
}
|
||||
return dens;
|
||||
};
|
||||
|
||||
const today = () => Math.floor(Date.now() / 86400000);
|
||||
|
||||
// the names in today's list.
|
||||
const fromToday = (day, offset) => all()[(day * ROWS_SHOWN + offset) % all().length];
|
||||
const list = (day = today()) => Array.from({length: Math.min(ROWS_SHOWN, all().length)}, (_, i) => fromToday(day, i).name);
|
||||
|
||||
const byName = name => all().find(den => den.name.toLowerCase() === String(name).toLowerCase());
|
||||
|
||||
// the den behind the AJHQ button today: the one after today's list.
|
||||
const featured = (day = today()) => fromToday(day, ROWS_SHOWN);
|
||||
|
||||
module.exports = {all, list, byName, featured};
|
||||
@@ -0,0 +1,25 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const bans = require("./bans.js");
|
||||
const chatlog = require("./chatlog.js");
|
||||
const masterpieces = require("./masterpieces.js");
|
||||
const support = require("./support.js");
|
||||
const world = require("./world.js");
|
||||
|
||||
// an account deleted for good, by its owner (lib/manage.js) or by the admin
|
||||
// (lib/panel.js), and what was kept about it elsewhere with it: its chat
|
||||
// lines, its appeal, its feedback and username requests, and the paintings
|
||||
// it made (from whoever holds one by now). what stays is said in the
|
||||
// privacy policy (public/privacy.html): the record of bans and of what
|
||||
// moderators did, under the name it had, until lib/retention.js ends it.
|
||||
// the caller has taken the account out of the world and its pages.
|
||||
module.exports = account => {
|
||||
for (const id of masterpieces.madeBy(account)) {
|
||||
world.removeMasterpiece(id);
|
||||
}
|
||||
bans.forget(account);
|
||||
chatlog.forget(account);
|
||||
support.forget(account);
|
||||
accounts.remove(account);
|
||||
};
|
||||
@@ -0,0 +1,123 @@
|
||||
"use strict";
|
||||
|
||||
const zlib = require("zlib");
|
||||
const amf3 = require("./amf3.js");
|
||||
const cdn = require("./cdn.js");
|
||||
|
||||
// extra den music: sounds found in the game's files that nothing plays, or
|
||||
// that only one room plays, made into music den items (see "Odd audio" in
|
||||
// DISCOVERIES.md). they are not in any shop; the item finder and the admin
|
||||
// panel's gifts give them by id.
|
||||
//
|
||||
// A music den item plays "audio/<its abbrName>.mp3" from the content server
|
||||
// (DenItemHolder), and the CDN has no such files for these. each one's
|
||||
// sound sits inside a media file or a room file as an MP3 (a DefineSound
|
||||
// tag of a zlib-compressed SWF), so the file is cut out of there when a
|
||||
// client first asks for it. nothing of it is kept in this repository.
|
||||
|
||||
const FIRST_ID = 6001; // the official den items end at 5925
|
||||
const STRING_BASE = 9000100;
|
||||
const VOLUME = "40"; // the def's `flag`, as the official tracks have it
|
||||
const TEMPLATE = 614; // "Jam On": each new row starts as a copy of this track's
|
||||
|
||||
// {file, title, sound: the sound's exported name ("" for the only, unnamed
|
||||
// one), and where it is: a media id, or a room file and the asset in it}
|
||||
const TRACKS = [
|
||||
{file: "XtraNarration", title: "Narration", media: 1904, sound: "Narration"},
|
||||
{file: "XtraUnnamed", title: "Unnamed Sound", media: 46, sound: ""},
|
||||
{file: "XtraPhantomKings", title: "Phantom Kings", media: 2680, sound: "ajq_q7phntmKings.wav"},
|
||||
{file: "XtraYearBook", title: "TV Yearbook", media: 5828, sound: "ajq_tvYearBook"},
|
||||
{file: "XtraUSBKey", title: "Phantom USB Key", media: 5828, sound: "ajq_phntmUSBkey"},
|
||||
{file: "XtraNightingale", title: "Nightingale", media: 2365, sound: "ajq_nightingaleFull"},
|
||||
{file: "XtraVolcano", title: "Volcano", media: 2507, sound: "aj_musVolcanoFull"},
|
||||
...[1, 2, 3, 4].map(layer => ({file: `XtraConcert${layer}`, title: `Concert Layer ${layer}`,
|
||||
room: "party/venue_concert", asset: "Concert\\Concert_Party_Front_Lights.swf", sound: `layer${layer}`})),
|
||||
].map((track, index) => ({...track, id: FIRST_ID + index, stringId: STRING_BASE + index}));
|
||||
|
||||
const ids = TRACKS.map(track => track.id);
|
||||
|
||||
// rows for the den item pack, each a copy of an official track's row.
|
||||
const defs = template => TRACKS.map(track => ({
|
||||
...template, id: String(track.id), nameStrId: String(track.stringId), abbrName: track.file, cost: "0", membersOnly: "0",
|
||||
flag: VOLUME, availabilityStartTime: null, availabilityEndTime: null,
|
||||
}));
|
||||
|
||||
const strings = () => Object.fromEntries(TRACKS.map(track => [track.stringId, track.title]));
|
||||
|
||||
const TAG_DEFINE_SOUND = 14;
|
||||
const TAG_EXPORT = 56;
|
||||
const TAG_SYMBOL_CLASS = 76;
|
||||
const FORMAT_MP3 = 2;
|
||||
|
||||
const soundIn = (swf, name) => {
|
||||
if (swf.toString("latin1", 0, 3) !== "CWS") {
|
||||
return null;
|
||||
}
|
||||
const body = zlib.inflateSync(swf.subarray(8));
|
||||
const sounds = new Map(); // character id -> MP3 data
|
||||
const names = new Map(); // character id -> exported name
|
||||
let at = Math.ceil((5 + 4 * (body[0] >> 3)) / 8) + 4; // past the frame size, rate and count
|
||||
while (at + 2 <= body.length) {
|
||||
const head = body.readUInt16LE(at);
|
||||
at += 2;
|
||||
let length = head & 0x3F;
|
||||
if (length === 0x3F) {
|
||||
length = body.readUInt32LE(at);
|
||||
at += 4;
|
||||
}
|
||||
const tag = body.subarray(at, at + length);
|
||||
at += length;
|
||||
if (head >> 6 === TAG_DEFINE_SOUND && tag.length > 9 && tag[2] >> 4 === FORMAT_MP3) {
|
||||
sounds.set(tag.readUInt16LE(0), tag.subarray(9)); // id, flags, sample count, seek samples, then the frames
|
||||
}
|
||||
else if (head >> 6 === TAG_SYMBOL_CLASS || head >> 6 === TAG_EXPORT) {
|
||||
let pos = 2;
|
||||
for (let left = tag.readUInt16LE(0); left > 0 && pos + 2 < tag.length; left--) {
|
||||
const end = tag.indexOf(0, pos + 2);
|
||||
names.set(tag.readUInt16LE(pos), tag.toString("utf8", pos + 2, end));
|
||||
pos = end + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [id, data] of sounds) {
|
||||
if ((names.get(id) || "") === name) {
|
||||
return Buffer.from(data);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const extract = async track => {
|
||||
if (track.media) {
|
||||
const swf = await cdn.get(cdn.hashedPath(`media/${track.media}`));
|
||||
return swf ? soundIn(swf, track.sound) : null;
|
||||
}
|
||||
const room = await cdn.get(cdn.hashedPath(`roomDefs/${track.room}.xroom`));
|
||||
const asset = room && amf3.decode(zlib.inflateSync(room)).assets
|
||||
.find(candidate => String(candidate.name).toLowerCase() === track.asset.toLowerCase());
|
||||
return asset && Buffer.isBuffer(asset.ba) ? soundIn(asset.ba, track.sound) : null;
|
||||
};
|
||||
|
||||
const audioPaths = new Map(TRACKS.map(track => [cdn.hashedPath(`audio/${track.file}.mp3`), track]));
|
||||
const made = new Map(); // track -> promise of its MP3
|
||||
|
||||
// what to answer a content request with when it is for one of these
|
||||
// tracks' audio: {body, type}; undefined when it is not, and {body: null}
|
||||
// when the source could not be read. (Music items have no picture: the
|
||||
// den's music list shows their names.)
|
||||
const asset = async relPath => {
|
||||
const track = audioPaths.get(relPath);
|
||||
if (!track) {
|
||||
return undefined;
|
||||
}
|
||||
if (!made.has(track)) {
|
||||
made.set(track, extract(track).catch(() => null));
|
||||
}
|
||||
const body = await made.get(track);
|
||||
if (!body) {
|
||||
made.delete(track); // offline, perhaps: try again next time
|
||||
}
|
||||
return {body, type: "audio/mpeg"};
|
||||
};
|
||||
|
||||
module.exports = {TRACKS, ids, defs, strings, asset, TEMPLATE};
|
||||
@@ -0,0 +1,118 @@
|
||||
[
|
||||
{"id": 4, "swf": "Pachinko", "title": "Gem Ball", "type": 1, "vars": [16, 17, 0], "icon": 4295},
|
||||
{"id": 5, "swf": "MiniGame_Memory", "title": "Double Up", "type": 1, "vars": [6, 7, 83], "icon": 4291},
|
||||
{"id": 6, "swf": "MoatMadness", "title": "Overflow", "type": 1, "vars": [8, 9, 80], "icon": 4300},
|
||||
{"id": 10, "swf": "ParachuteGlider", "title": "Wind Rider", "type": 1, "vars": [12, 13, 79], "start": "seed", "icon": 4311},
|
||||
{"id": 11, "swf": "Trivia", "title": "Temple of Trivia", "type": 1, "vars": [10, 11, 0], "ready": false, "icon": 4309},
|
||||
{"id": 12, "swf": "RiverRace", "title": "River Race", "type": 1, "vars": [22, 23, 0], "start": "seed"},
|
||||
{"id": 13, "swf": "PhantomFighter", "title": "Phantom Fighter", "type": 1, "vars": [14, 15, 84], "icon": 4312},
|
||||
{"id": 14, "swf": "SpiderShooter", "title": "Spider Zapper", "type": 1, "vars": [18, 19, 82], "start": "seed", "icon": 4305},
|
||||
{"id": 15, "swf": "MicroPopcorn", "title": "Popcorn Machine", "type": 0},
|
||||
{"id": 16, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 17, "swf": "MicroSmoothie", "title": "Smoothie Machine", "type": 0},
|
||||
{"id": 19, "swf": "WindRider", "title": "Sky High", "type": 1, "vars": [26, 27, 0], "icon": 4304},
|
||||
{"id": 20, "swf": "Twister", "title": "Twister", "type": 1, "vars": [24, 25, 81], "icon": 4310},
|
||||
{"id": 22, "swf": "DistanceChallenge", "title": "Long Shot", "type": 1, "vars": [20, 21, 0], "icon": 4298},
|
||||
{"id": 23, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1},
|
||||
{"id": 26, "swf": "ArtStudioPottery", "title": "Pottery", "type": 1},
|
||||
{"id": 27, "swf": "MicroPhantom", "title": "Phantom Vortex", "type": 0},
|
||||
{"id": 28, "swf": "TowerDefense", "title": "Pest Control", "type": 1, "vars": [130, 131, 132], "icon": 4301},
|
||||
{"id": 30, "swf": "GemBreaker", "title": "Gem Breaker", "type": 1, "vars": [91, 93, 92], "start": "seedAndPlayers", "icon": 4313},
|
||||
{"id": 34, "swf": "MicroMiraSays", "title": "Mira Says", "type": 1, "vars": [77, 76, 0], "icon": 4299},
|
||||
{"id": 35, "swf": "FortSmasher", "title": "Fruit Slinger", "type": 1, "vars": [143, 144, 145], "ready": false, "icon": 4294},
|
||||
{"id": 36, "swf": "MicroHotCocoa", "title": "Hot Cocoa Machine", "type": 0},
|
||||
{"id": 37, "swf": "SuperSort", "title": "Super Sort", "type": 1, "vars": [31, 32, 37], "icon": 4307},
|
||||
{"id": 39, "swf": "PillBugs", "title": "Pill Bugs", "type": 1, "vars": [277, 278, 279], "icon": 4303},
|
||||
{"id": 40, "swf": "BradyExpeditions", "title": "Brady Expeditions", "type": 1},
|
||||
{"id": 41, "swf": "PhantomsTreasure", "title": "Phantom's Treasure", "type": 1, "vars": [281, 283, 282], "icon": 4302},
|
||||
{"id": 42, "swf": "FeedingFrenzy", "title": "Eat 'Em Up", "type": 1, "vars": [284, 285, 0], "icon": 4292},
|
||||
{"id": 43, "swf": "MicroPetWash", "title": "Pet Wash", "type": 0},
|
||||
{"id": 48, "swf": "FashionShow", "title": "Best Dressed", "type": 1, "vars": [292, 293, 294], "ready": false, "icon": 4288},
|
||||
{"id": 51, "swf": "ArtStudioPainting", "title": "Painting", "type": 1},
|
||||
{"id": 52, "swf": "MicroPetSalon", "title": "Pet Stop", "type": 0},
|
||||
{"id": 55, "swf": "MicroGameInvasion", "title": "Phantom Invasion", "type": 0},
|
||||
{"id": 57, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 59, "swf": "MicroCrane", "title": "The Claw", "type": 0, "icon": 4290},
|
||||
{"id": 60, "swf": "TouchPool", "title": "Touch Pool", "type": 1, "vars": [310, 308, 309], "icon": 5229},
|
||||
{"id": 61, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 62, "swf": "HorseRace", "title": "Jamaa Derby", "type": 1, "vars": [327, 328, 330], "ready": false, "icon": 4297},
|
||||
{"id": 63, "swf": "MicroPuppy", "title": "Disc Toss", "type": 0, "vars": [313, 314, 315], "pet": 4},
|
||||
{"id": 64, "swf": "MicroDucky", "title": "Ducky Dash", "type": 0, "vars": [316, 317, 318], "pet": 3},
|
||||
{"id": 65, "swf": "MicroSnake", "title": "Sssssnake", "type": 0, "vars": [321, 322, 323], "pet": 11},
|
||||
{"id": 66, "swf": "FashionShow", "title": "Best Dressed", "type": 1, "vars": [292, 293, 294], "ready": false, "icon": 4289},
|
||||
{"id": 68, "swf": "Skeeball", "title": "Phantom Ball", "type": 1, "tickets": 10},
|
||||
{"id": 69, "swf": "WhackPhantom", "title": "Whack-A-Phantom", "type": 1, "tickets": 10},
|
||||
{"id": 70, "swf": "CandyCatcher", "title": "Candy Catch", "type": 1, "tickets": 10},
|
||||
{"id": 71, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 72, "swf": "MicroGameInvasion", "title": "Phantom Invasion", "type": 0},
|
||||
{"id": 73, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 1},
|
||||
{"id": 74, "swf": "CottonCandy", "title": "Cotton Candy Machine", "type": 0},
|
||||
{"id": 75, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 76, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1},
|
||||
{"id": 77, "swf": "FallingPhantoms", "title": "Falling Phantoms", "type": 1, "vars": [344, 345, 346], "ready": false, "icon": 4293},
|
||||
{"id": 78, "swf": "DolphinRace", "title": "Splash and Dash", "type": 1, "vars": [357, 358, 360], "ready": false, "icon": 4306},
|
||||
{"id": 80, "swf": "ShootingGallery", "title": "Carnival Darts", "type": 1, "tickets": 100},
|
||||
{"id": 81, "swf": "MicroPetSalon", "title": "Pet Stop", "type": 0},
|
||||
{"id": 82, "swf": "FastFoodies", "title": "Fast Foodies", "type": 1, "vars": [445, 444, 446], "icon": 5727},
|
||||
{"id": 83, "swf": "HedgeHog", "title": "Hedge Hog", "type": 1, "vars": [349, 350, 351], "icon": 4296},
|
||||
{"id": 85, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 86, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1},
|
||||
{"id": 87, "swf": "BradyChemistrySet", "title": "Brady's Lab", "type": 0},
|
||||
{"id": 88, "swf": "SafetyQuiz", "title": "Safety Quiz", "type": 0},
|
||||
{"id": 94, "swf": "EagleFlap", "title": "Swoopy Eagle", "type": 1, "vars": [378, 377, 0], "icon": 4308},
|
||||
{"id": 96, "swf": "DunkAPhantom", "title": "Dunk-A-Phantom", "type": 1, "tickets": 10},
|
||||
{"id": 97, "swf": "SpotOn", "title": "Spot On", "type": 1, "vars": [386, 387, 388], "icon": 4321},
|
||||
{"id": 99, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 100, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 102, "swf": "TrueFalse", "title": "Best Guess", "type": 1, "vars": [403, 405, 0], "ready": false},
|
||||
{"id": 103, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 104, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 105, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 106, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 107, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 109, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 110, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 116, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 117, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 118, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 119, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 120, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 121, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 123, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 125, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 126, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 127, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 128, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 129, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 130, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 131, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 132, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 133, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 134, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 136, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1},
|
||||
{"id": 138, "swf": "FastFoodies", "title": "Fast Foodies", "type": 1, "vars": [445, 444, 446]},
|
||||
{"id": 139, "swf": "ArtStudioGridDrawing", "title": "Pixel Painting", "type": 1},
|
||||
{"id": 140, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 141, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 142, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 143, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 144, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 145, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 146, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 147, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 148, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 149, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 150, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 153, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 154, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 155, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 156, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||
{"id": 89, "swf": "PVP_TicTacToe", "title": "Tic Tac Toe", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5063},
|
||||
{"id": 90, "swf": "PVP_ConnectFour", "title": "Four Gems", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5057},
|
||||
{"id": 91, "swf": "PVP_RockPaperScissor", "title": "Rock Paper Scissors", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5060},
|
||||
{"id": 92, "swf": "PVP_ShellGame", "title": "Shell Game", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5062},
|
||||
{"id": 93, "swf": "PVP_Memory", "title": "Pairs", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5059},
|
||||
{"id": 95, "swf": "PVP_Scooped", "title": "Scooped", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5061},
|
||||
{"id": 98, "swf": "PVP_Bowling", "title": "Bowling", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5056},
|
||||
{"id": 101, "swf": "PVP_Marbles", "title": "Marbles", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5058}
|
||||
]
|
||||
@@ -0,0 +1,755 @@
|
||||
"use strict";
|
||||
|
||||
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 admin = require("./admin.js");
|
||||
const bans = require("./bans.js");
|
||||
const captcha = require("./captcha.js");
|
||||
const cdn = require("./cdn.js");
|
||||
const config = require("../config.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const limits = require("./limits.js");
|
||||
const manage = require("./manage.js");
|
||||
const modpanel = require("./modpanel.js");
|
||||
const badges = require("./badges.js");
|
||||
const extraMusic = require("./extramusic.js");
|
||||
const masterpieces = require("./masterpieces.js");
|
||||
const panel = require("./panel.js");
|
||||
const totp = require("./totp.js");
|
||||
const world = require("./world.js");
|
||||
|
||||
// stands in for every web service the launcher and the SWF talk to:
|
||||
// www (flashvars), authenticator, player-session-data, ajelectronapi, the
|
||||
// game host page and the content CDN.
|
||||
|
||||
const CROSS_DOMAIN = '<?xml version="1.0"?><cross-domain-policy><site-control permitted-cross-domain-policies="all"/>'
|
||||
+ '<allow-access-from domain="*" to-ports="*"/><allow-http-request-headers-from domain="*" headers="*"/></cross-domain-policy>';
|
||||
|
||||
const MIME = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".js": "text/javascript",
|
||||
".json": "application/json",
|
||||
".xml": "text/xml",
|
||||
".swf": "application/x-shockwave-flash",
|
||||
".png": "image/png",
|
||||
".svg": "image/svg+xml",
|
||||
".jpg": "image/jpeg",
|
||||
".mp3": "audio/mpeg",
|
||||
".txt": "text/plain",
|
||||
".otf": "font/otf",
|
||||
};
|
||||
|
||||
const flashVars = () => ({
|
||||
content: config.baseUrl,
|
||||
// the game's own server to the SWF, whatever its name: it loads the card
|
||||
// badges, the bio and ban icons and the chat filter's lists from here,
|
||||
// and calls /api here. the client lets the game load from no other name.
|
||||
website: config.baseUrl,
|
||||
mdUrl: `${config.baseUrl}game/`,
|
||||
playerWallHost: `${config.baseUrl}wall`,
|
||||
smartfoxServer: config.host,
|
||||
blueboxServer: config.host,
|
||||
smartfoxPort: String(config.gamePort),
|
||||
blueboxPort: String(config.httpPort),
|
||||
build_version: config.buildVersion,
|
||||
deploy_version: config.deployVersion,
|
||||
// for the custom client: are its advanced login settings honoured here?
|
||||
loginChoices: config.loginChoices,
|
||||
smoke_version: config.deployVersion,
|
||||
clientURL: `${config.baseUrl}${config.deployVersion}/ajclient.swf?v=${config.buildVersion}`,
|
||||
startupRoom: config.startupRoom,
|
||||
// "-1" turns the client's stats socket off.
|
||||
sbStatTrackerIp: "-1",
|
||||
sbStatModulator: "0",
|
||||
currentTimestamp: Math.floor(Date.now() / 1000),
|
||||
country: "US",
|
||||
locale: "en",
|
||||
});
|
||||
|
||||
const readJson = req => new Promise((resolve, reject) => {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
req.on("data", chunk => {
|
||||
size += chunk.length;
|
||||
if (size > 64 * 1024) {
|
||||
reject(new Error("body too large"));
|
||||
req.destroy();
|
||||
}
|
||||
else {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
});
|
||||
req.on("end", () => {
|
||||
try {
|
||||
resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString()) : {});
|
||||
}
|
||||
catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
req.on("error", reject);
|
||||
});
|
||||
|
||||
const readBody = (req, maxBytes) => new Promise((resolve, reject) => {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
req.on("data", chunk => {
|
||||
size += chunk.length;
|
||||
if (size > maxBytes) {
|
||||
reject(new Error("body too large"));
|
||||
req.destroy();
|
||||
}
|
||||
else {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
});
|
||||
req.on("end", () => resolve(Buffer.concat(chunks)));
|
||||
req.on("error", reject);
|
||||
});
|
||||
|
||||
// the parts of a multipart/form-data body, as a Map of field name ->
|
||||
// Buffer. empty when the body is not one.
|
||||
const formParts = (contentType, body) => {
|
||||
const parts = new Map();
|
||||
const boundary = /boundary=("?)([^";]{1,200})\1/.exec(contentType || "");
|
||||
if (!boundary) {
|
||||
return parts;
|
||||
}
|
||||
const mark = Buffer.from(`--${boundary[2]}`);
|
||||
let at = body.indexOf(mark);
|
||||
while (at !== -1) {
|
||||
const next = body.indexOf(mark, at + mark.length);
|
||||
const headEnd = body.indexOf("\r\n\r\n", at);
|
||||
if (next === -1 || headEnd === -1 || headEnd > next) {
|
||||
break;
|
||||
}
|
||||
const name = /name="([^"]{1,100})"/.exec(body.toString("latin1", at + mark.length, headEnd));
|
||||
if (name) {
|
||||
parts.set(name[1], body.subarray(headEnd + 4, next - 2)); // without the line break before the mark
|
||||
}
|
||||
at = next;
|
||||
}
|
||||
return parts;
|
||||
};
|
||||
|
||||
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});
|
||||
res.end(res.req && res.req.method === "HEAD" ? undefined : data);
|
||||
};
|
||||
|
||||
// wrong passwords allowed per address before further tries from it are
|
||||
// refused for a while. the address is what is blocked, never the account:
|
||||
// blocking an account would let anybody keep its owner out by guessing at
|
||||
// it, and guessing from many addresses is what makes it dear.
|
||||
const TEN_MINUTES_MS = 600000;
|
||||
const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS);
|
||||
const searches = limits.limiter(120, 60000); // item finder searches, per address
|
||||
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 PAINTING_PATH = /^\/masterpieces\/([0-9a-f-]{36})$/;
|
||||
|
||||
// where clients ask for the HUD artwork; ours is a changed copy.
|
||||
const HUD_ASSETS_PATH = cdn.hashedPath("assets/HUDAssets.swf");
|
||||
const MAX_REPORT_LENGTH = 4000;
|
||||
|
||||
// client errors are also kept in a file of their own, so they outlive a
|
||||
// server whose output only went to a terminal.
|
||||
const CLIENT_ERROR_FILE = path.join(config.dataDir, "client-errors.log");
|
||||
const MAX_CLIENT_ERROR_FILE = 5 * 1024 * 1024;
|
||||
const keepClientError = text => {
|
||||
fs.promises.stat(CLIENT_ERROR_FILE).then(stat => stat.size, () => 0)
|
||||
.then(size => (size < MAX_CLIENT_ERROR_FILE ? fs.promises.appendFile(CLIENT_ERROR_FILE, text) : null))
|
||||
.catch(() => {});
|
||||
};
|
||||
const THEMED_ROOM = /^(\d+)\/roomDefs\/theme_(\d+)\/(.+)$/;
|
||||
|
||||
// the web pages, as against what the game and the client load
|
||||
const SITE_PAGES = /^\/(?:register|terms|privacy|commands|shop|account|mod)?\/?$/;
|
||||
|
||||
// origins a client's own page has: a file, as browsers name it.
|
||||
const CLIENT_ORIGINS = ["null", "file://"];
|
||||
|
||||
// one of this server's plain pages (sign-up, the commands, the item finder),
|
||||
// with the headers the account page and the panel have: nothing loaded from
|
||||
// elsewhere, nothing sent elsewhere, no frame.
|
||||
const PAGE_HEADERS = {
|
||||
"X-Frame-Options": "DENY",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
"Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; "
|
||||
+ "form-action 'none'; frame-ancestors 'none'; base-uri 'none'",
|
||||
};
|
||||
// the same, for the pages that show the captcha (lib/captcha.js)
|
||||
const CAPTCHA_PAGE_HEADERS = {...PAGE_HEADERS, "Content-Security-Policy": captcha.policy(PAGE_HEADERS["Content-Security-Policy"])};
|
||||
// the terms and the privacy policy carry who runs this server and where to
|
||||
// write, from config.js.
|
||||
const LEGAL_VALUES = {legalEmail: config.legalEmail, adminEmail: config.adminEmail, operator: config.operator, hostedIn: config.hostedIn,
|
||||
version: config.termsVersion, site: new URL(config.siteUrl).host};
|
||||
const escapeHtml = text => String(text).replace(/[&<>"]/g, sign => ({"&": "&", "<": "<", ">": ">", "\"": """})[sign]);
|
||||
const sendLegalPage = async (res, file) => {
|
||||
for (const [name, value] of Object.entries(PAGE_HEADERS)) {
|
||||
res.setHeader(name, value);
|
||||
}
|
||||
const page = (await fs.promises.readFile(path.join(config.publicDir, file), "utf8"))
|
||||
.replace(/\{\{(\w+)\}\}/g, (whole, name) => (Object.hasOwn(LEGAL_VALUES, name) ? escapeHtml(LEGAL_VALUES[name]) : whole));
|
||||
send(res, 200, page, MIME[".html"]);
|
||||
};
|
||||
// a web address or a path on this server; anything else is dropped
|
||||
const pageLink = text => (/^https?:\/\/[^\s"<>]+$/.test(text) || /^\/[^/\s"<>][^\s"<>]*$/.test(text) ? text : "");
|
||||
const HOME_VALUES = {downloadUrl: pageLink(config.downloadUrl), githubUrl: pageLink(config.githubUrl), discordUrl: pageLink(config.discordUrl)};
|
||||
const sendHomePage = async res => {
|
||||
for (const [name, value] of Object.entries(PAGE_HEADERS)) {
|
||||
res.setHeader(name, value);
|
||||
}
|
||||
const page = (await fs.promises.readFile(path.join(config.publicDir, "home.html"), "utf8"))
|
||||
.replace(/\{\{(\w+)\}\}/g, (whole, name) => (Object.hasOwn(HOME_VALUES, name) ? escapeHtml(HOME_VALUES[name]) : whole));
|
||||
send(res, 200, page, MIME[".html"]);
|
||||
};
|
||||
const sendPage = async (res, file, headers = PAGE_HEADERS) => {
|
||||
for (const [name, value] of Object.entries(headers)) {
|
||||
res.setHeader(name, value);
|
||||
}
|
||||
send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, file))), MIME[".html"]);
|
||||
};
|
||||
|
||||
// A username that was rejected (lib/moderation.js) is replaced as part of
|
||||
// signing in: the sign-in that proved who it is gets a ticket in place of a
|
||||
// login token, and the ticket with a new name finishes the sign-in. A ticket
|
||||
// is good for a few minutes and a few tries.
|
||||
const RENAME_TICKET_MS = 600000;
|
||||
const RENAME_TRIES = 20;
|
||||
const renameTickets = new Map(); // SHA-256 of a ticket -> {id, expiry, tries, deviceToken}
|
||||
const ticketHash = ticket => crypto.createHash("sha256").update(String(ticket)).digest("hex");
|
||||
|
||||
const renameTicket = (account, deviceToken) => {
|
||||
for (const [hash, entry] of renameTickets) {
|
||||
if (entry.expiry < Date.now() || entry.id === account.id) {
|
||||
renameTickets.delete(hash);
|
||||
}
|
||||
}
|
||||
const ticket = crypto.randomBytes(24).toString("hex");
|
||||
renameTickets.set(ticketHash(ticket), {id: account.id, expiry: Date.now() + RENAME_TICKET_MS, tries: 0, deviceToken});
|
||||
return ticket;
|
||||
};
|
||||
|
||||
// the second half of such a sign-in: {rename_ticket, new_username}.
|
||||
const renameAndSignIn = (res, body, from) => {
|
||||
const hash = ticketHash(body.rename_ticket);
|
||||
const entry = renameTickets.get(hash);
|
||||
const account = entry && entry.expiry > Date.now() ? accounts.byId(entry.id) : null;
|
||||
if (!account || !account.nameRejected || account.locked || world.moderation.banRemaining(account) !== 0 || bans.addressBan(from.address)
|
||||
|| ++entry.tries > RENAME_TRIES) {
|
||||
renameTickets.delete(hash);
|
||||
send(res, 401, {error_code: 101, error: "rename_expired"});
|
||||
return;
|
||||
}
|
||||
const wanted = typeof body.new_username === "string" ? body.new_username.trim() : "";
|
||||
world.disconnect(account);
|
||||
const problem = wanted.toLowerCase() === account.username.toLowerCase() ? "same_name" : accounts.rename(account, wanted);
|
||||
if (problem) {
|
||||
send(res, 401, {error_code: 101, error: "name_rejected", rename_ticket: body.rename_ticket, name_error: problem});
|
||||
return;
|
||||
}
|
||||
renameTickets.delete(hash);
|
||||
delete account.nameRejected;
|
||||
manage.forget(account);
|
||||
accounts.recordLogin(account, "launcher", from.address);
|
||||
accounts.save();
|
||||
console.log(`[accounts] a rejected username was replaced by "${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});
|
||||
};
|
||||
|
||||
const authenticate = async (req, res, from) => {
|
||||
const body = await readJson(req);
|
||||
if (body.rename_ticket !== undefined) {
|
||||
renameAndSignIn(res, body, from);
|
||||
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 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));
|
||||
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);
|
||||
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();
|
||||
}
|
||||
}
|
||||
// error_code 100 = expired refresh token, 101 = wrong credentials
|
||||
send(res, 401, {error_code: byRefresh ? 100 : 101});
|
||||
return;
|
||||
}
|
||||
// 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
|
||||
// saved sign-in) was right, so this tells nobody anything a player's card
|
||||
// does not.
|
||||
// the reason goes with it: whoever got this far is the banned player.
|
||||
const ban = world.moderation.banOf(account);
|
||||
if (ban) {
|
||||
send(res, 401, {error_code: 101, error: "account_banned", banned_seconds: ban.seconds, ban_reason: ban.reason});
|
||||
return;
|
||||
}
|
||||
// A banned address (lib/bans.js): for good, whoever signs in from it.
|
||||
const addressBan = bans.addressBan(from.address);
|
||||
if (addressBan) {
|
||||
send(res, 401, {error_code: 101, error: "address_banned", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason});
|
||||
return;
|
||||
}
|
||||
// locked by its owner on the account page: the password is right, and
|
||||
// still nobody gets in. the launcher shows this as a failed sign-in.
|
||||
if (account.locked) {
|
||||
send(res, 401, {error_code: 101, error: "account_locked"});
|
||||
return;
|
||||
}
|
||||
// two-step sign-in (lib/totp.js): after the password, a code from the
|
||||
// player's authenticator app, unless this device gave one in the last 30
|
||||
// days and kept the token it got for it. A saved sign-in is not asked:
|
||||
// it was given after a code, and lasts no longer than such a token. the
|
||||
// custom client knows these errors; the official launcher shows them as a
|
||||
// wrong password, and cannot give a code.
|
||||
let deviceToken;
|
||||
if (!byRefresh && totp.isOn(account) && !totp.deviceTrusted(account, body.device_token)) {
|
||||
if (body.totp === undefined || body.totp === "") {
|
||||
send(res, 401, {error_code: 101, error: "totp_required", captcha_pass: captcha.issuePass(account, from)});
|
||||
return;
|
||||
}
|
||||
if (!totp.verify(account, String(body.totp))) {
|
||||
failuresByAddress.record(from.key);
|
||||
accounts.recordLogin(account, "launcher", from.address, false);
|
||||
accounts.save();
|
||||
send(res, 401, {error_code: 101, error: "totp_wrong", captcha_pass: captcha.issuePass(account, from)});
|
||||
return;
|
||||
}
|
||||
if (body.remember_device === true) {
|
||||
deviceToken = totp.trustDevice(account, "launcher");
|
||||
}
|
||||
}
|
||||
// its username was rejected: a new one first (above). the official
|
||||
// launcher shows this as a wrong password; the account page asks too.
|
||||
if (account.nameRejected) {
|
||||
accounts.save(); // a two-step code just used stays used
|
||||
send(res, 401, {error_code: 101, error: "name_rejected", rename_ticket: renameTicket(account, deviceToken)});
|
||||
return;
|
||||
}
|
||||
if (!byRefresh) {
|
||||
accounts.recordLogin(account, "launcher", from.address);
|
||||
accounts.save();
|
||||
}
|
||||
// the custom client's advanced settings; the official launcher sends none.
|
||||
accounts.setLoginChoices(account, body.login_choices);
|
||||
const token = byRefresh ? body.refresh_token : accounts.issueToken(account);
|
||||
send(res, 200, {auth_token: token, refresh_token: token, device_token: deviceToken});
|
||||
};
|
||||
|
||||
const player = (req, res) => {
|
||||
const match = /^Bearer (.+)$/.exec(req.headers.authorization || "");
|
||||
const account = match && accounts.byToken(match[1]);
|
||||
if (!account) {
|
||||
send(res, 401, {error: "invalid_token"});
|
||||
return;
|
||||
}
|
||||
send(res, 200, {
|
||||
id: account.id,
|
||||
screen_name: account.username,
|
||||
game_account_type: account.accountType,
|
||||
language: "en",
|
||||
game_server: config.host,
|
||||
});
|
||||
};
|
||||
|
||||
const handle = async (req, res) => {
|
||||
const url = new URL(req.url, config.baseUrl);
|
||||
const route = `${req.method} ${url.pathname}`;
|
||||
|
||||
const from = limits.clientOf(req);
|
||||
|
||||
// the web pages live under the site's name (config.siteUrl): one asked
|
||||
// for under the game server's name is sent there. what the game and the
|
||||
// client load stays here, the client's captcha page among it.
|
||||
if ((req.method === "GET" || req.method === "HEAD") && config.siteUrl !== config.baseUrl
|
||||
&& String(req.headers.host || "").toLowerCase() === new URL(config.baseUrl).host && SITE_PAGES.test(url.pathname)) {
|
||||
res.writeHead(301, {Location: new URL(url.pathname + url.search, config.siteUrl).href, "Content-Length": 0});
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const isAdmin = url.pathname === "/admin" || url.pathname.startsWith("/admin/");
|
||||
const isAccount = url.pathname === "/account" || url.pathname.startsWith("/account/");
|
||||
const isMod = url.pathname === "/mod" || url.pathname.startsWith("/mod/");
|
||||
|
||||
// the pages that keep a cookie answer only under this server's own names:
|
||||
// a request sent here by a page of another name (one whose name was made
|
||||
// to point at this machine, say) is not theirs to make. nor is such a
|
||||
// request ever this machine's own, wherever it came from.
|
||||
if (!limits.hostAllowed(req)) {
|
||||
if (isAdmin || isAccount || isMod) {
|
||||
send(res, 421, {error: "wrong_host"});
|
||||
return;
|
||||
}
|
||||
from.local = false;
|
||||
}
|
||||
|
||||
// the admin panel sets its own, stricter headers: none of the cross-origin
|
||||
// allowances below apply to it. on a public server it is not there at all
|
||||
// for anyone but this machine and the addresses named (config.adminAllow).
|
||||
if (isAdmin) {
|
||||
if (config.isPublic && !from.direct && !config.adminAllow.includes(from.address)) {
|
||||
send(res, 404, "Not found", "text/plain");
|
||||
return;
|
||||
}
|
||||
await panel.handle(req, res, url, from, {send, readJson});
|
||||
return;
|
||||
}
|
||||
|
||||
if (isAccount) {
|
||||
await manage.handle(req, res, url, from, {send, readJson});
|
||||
return;
|
||||
}
|
||||
|
||||
// and the moderator panel (lib/modpanel.js), which is there for anyone to
|
||||
// reach: its moderators are players, wherever they are.
|
||||
if (isMod) {
|
||||
await modpanel.handle(req, res, url, from, {send, readJson});
|
||||
return;
|
||||
}
|
||||
|
||||
// the clients' own pages are files, which browsers call the origin "null":
|
||||
// those and this server's pages may read what the rest answers. no cookie
|
||||
// is used outside /account and /admin.
|
||||
const {origin} = req.headers;
|
||||
if (origin && (CLIENT_ORIGINS.includes(origin) || limits.originAllowed(req))) {
|
||||
res.setHeader("Access-Control-Allow-Origin", origin);
|
||||
res.setHeader("Access-Control-Allow-Credentials", "true");
|
||||
res.setHeader("Vary", "Origin");
|
||||
}
|
||||
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
|
||||
res.setHeader("Cache-Control", "no-cache");
|
||||
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||
|
||||
if (req.method === "OPTIONS") {
|
||||
res.writeHead(204);
|
||||
res.end();
|
||||
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.
|
||||
if (!limits.originAllowed(req)) {
|
||||
send(res, 403, {error: "forbidden"});
|
||||
return;
|
||||
}
|
||||
if (url.pathname === "/api/search" && !from.local && !searches.allow(from.key)) {
|
||||
send(res, 429, {error: "too_many_requests"});
|
||||
return;
|
||||
}
|
||||
const result = await admin.handle(route, url.searchParams, req.method === "POST" ? await readJson(req) : null, from);
|
||||
send(res, result.status, result.body);
|
||||
return;
|
||||
}
|
||||
|
||||
const signupArt = req.method === "GET" && /^\/signup\/((?:thumb|hero)_[a-z]+\.svg)$/.exec(url.pathname);
|
||||
if (signupArt) {
|
||||
const art = await fs.promises.readFile(path.join(config.publicDir, "signup", signupArt[1])).catch(() => null);
|
||||
res.setHeader("Cache-Control", "public, max-age=86400");
|
||||
send(res, art ? 200 : 404, art || "Not found", art ? MIME[".svg"] : "text/plain");
|
||||
return;
|
||||
}
|
||||
|
||||
// the font of the web pages, which is the game's own text font and the
|
||||
// client's (public/fonts/).
|
||||
const font = req.method === "GET" && /^\/fonts\/(CCDigitalDelivery-(?:Regular|Bold)\.otf)$/.exec(url.pathname);
|
||||
if (font) {
|
||||
res.setHeader("Cache-Control", "public, max-age=604800");
|
||||
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "fonts", font[1])), MIME[".otf"]);
|
||||
return;
|
||||
}
|
||||
|
||||
// the chat filter's two word lists (public/filter/), which each player's
|
||||
// game fetches and applies itself. read from disk each time, so that a
|
||||
// change to a list is there for the next player to start the game.
|
||||
const wordList = req.method === "GET" && /^\/filter\/(level[12]\.txt)$/.exec(url.pathname);
|
||||
if (wordList) {
|
||||
const list = await fs.promises.readFile(path.join(config.publicDir, "filter", wordList[1])).catch(() => null);
|
||||
send(res, list ? 200 : 404, list || "Not found", "text/plain; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
|
||||
// updates for the installed clients (config.clientUpdatesDir). each is
|
||||
// signed, and the clients check that themselves; the bundle's name
|
||||
// carries its version, so it never changes once published.
|
||||
const clientUpdate = req.method === "GET" && /^\/client\/(latest\.json|app-\d+\.\d+\.\d+\.burrow)$/.exec(url.pathname);
|
||||
if (clientUpdate) {
|
||||
const file = await fs.promises.readFile(path.join(config.clientUpdatesDir, clientUpdate[1])).catch(() => null);
|
||||
const manifest = clientUpdate[1] === "latest.json";
|
||||
res.setHeader("Cache-Control", manifest ? "no-cache" : "public, max-age=31536000, immutable");
|
||||
send(res, file ? 200 : 404, file || "Not found", file ? (manifest ? MIME[".json"] : "application/octet-stream") : "text/plain");
|
||||
return;
|
||||
}
|
||||
|
||||
// the badges and the Discord mark on player cards (public/badges/, lib/badges.js).
|
||||
const badgeArt = req.method === "GET" && /^\/badges\/([a-z0-9]{1,30}\.png)$/.exec(url.pathname);
|
||||
if (badgeArt) {
|
||||
const art = await fs.promises.readFile(path.join(config.publicDir, "badges", badgeArt[1])).catch(() => null);
|
||||
res.setHeader("Cache-Control", "public, max-age=3600");
|
||||
send(res, art ? 200 : 404, art || "Not found", art ? MIME[".png"] : "text/plain");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (route) {
|
||||
case "GET /register":
|
||||
await sendPage(res, "register.html", CAPTCHA_PAGE_HEADERS);
|
||||
return;
|
||||
// the captcha on its own, for the client, whose login page is a file
|
||||
// that cloudflare's widget does not run in.
|
||||
case "GET /captcha":
|
||||
await sendPage(res, "captcha.html", CAPTCHA_PAGE_HEADERS);
|
||||
return;
|
||||
case "GET /captcha.js": {
|
||||
const text = await fs.promises.readFile(path.join(config.publicDir, "captcha.js"), "utf8");
|
||||
send(res, 200, captcha.script(text), "text/javascript; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
case "GET /terms":
|
||||
await sendLegalPage(res, "terms.html");
|
||||
return;
|
||||
case "GET /privacy":
|
||||
await sendLegalPage(res, "privacy.html");
|
||||
return;
|
||||
case "GET /":
|
||||
await sendHomePage(res);
|
||||
return;
|
||||
case "GET /logo.png":
|
||||
case "GET /logo-square.png":
|
||||
case "GET /favicon.ico":
|
||||
res.setHeader("Cache-Control", "public, max-age=86400");
|
||||
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, url.pathname === "/logo.png" ? "logo.png" : "logo-square.png")), MIME[".png"]);
|
||||
return;
|
||||
case "GET /ban-icon.png": // the banned label on player cards (swf-src/BuddyCard.as)
|
||||
res.setHeader("Cache-Control", "public, max-age=86400");
|
||||
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "ban-icon.png")), MIME[".png"]);
|
||||
return;
|
||||
case "GET /bio-icon.png": // the button of the card's Bio tab
|
||||
res.setHeader("Cache-Control", "public, max-age=86400");
|
||||
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "bio-icon.png")), MIME[".png"]);
|
||||
return;
|
||||
case "GET /commands":
|
||||
await sendPage(res, "commands.html");
|
||||
return;
|
||||
case "GET /shop":
|
||||
await sendPage(res, "shop.html");
|
||||
return;
|
||||
case "GET /flashvars":
|
||||
send(res, 200, flashVars());
|
||||
return;
|
||||
case "POST /authenticate":
|
||||
await authenticate(req, res, from);
|
||||
return;
|
||||
case "GET /player":
|
||||
player(req, res);
|
||||
return;
|
||||
case "POST /v1/login":
|
||||
await readJson(req);
|
||||
send(res, 200, {});
|
||||
return;
|
||||
case "POST /v1/reportError": {
|
||||
// the launcher and the SWF both report crashes here; they are the best
|
||||
// clue for what the server got wrong. the patched SWF also sends
|
||||
// progress traces for media loads this way, which are only worth
|
||||
// having while debugging locally.
|
||||
const report = await readJson(req);
|
||||
// later lines are indented so a report cannot pass off its own text as
|
||||
// one of the server's log lines.
|
||||
const message = String(report.message).slice(0, MAX_REPORT_LENGTH).replace(/[^\x20-\x7e\n\t]/g, "?").replace(/\n\s*/g, "\n\t");
|
||||
const section = String(report.section).slice(0, 20).replace(/[^\w-]/g, "?");
|
||||
const trace = message.startsWith("media ");
|
||||
if (trace ? config.logPackets : from.local || errorReports.allow(from.key)) {
|
||||
console.log(`[${trace ? "client-trace" : "client-error"}] (${section}) ${message}`);
|
||||
if (!trace) {
|
||||
keepClientError(`${new Date().toISOString()} (${section}) ${message}\n`);
|
||||
}
|
||||
}
|
||||
send(res, 200, {});
|
||||
return;
|
||||
}
|
||||
// the Jammer Wall service (playerWallHost in the flashvars); every
|
||||
// command carries a token the game socket handed out, see lib/walls.js.
|
||||
case "POST /wall":
|
||||
send(res, 200, world.walls.http(await readJson(req)));
|
||||
return;
|
||||
// the Art Studio posts a painting to be made a masterpiece of (the
|
||||
// mdUrl flashvar + "mp"): a form with the token the game socket handed
|
||||
// out and the picture. ArtStudioPainting.onSendComplete reads the reply.
|
||||
case "POST /game/mp": {
|
||||
if (!from.local && !paintingPosts.allow(from.key)) {
|
||||
send(res, 429, {success: false});
|
||||
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"));
|
||||
send(res, 200, uuid ? {success: true, uuid} : {success: false});
|
||||
return;
|
||||
}
|
||||
case "GET /crossdomain.xml":
|
||||
send(res, 200, CROSS_DOMAIN, "text/xml");
|
||||
return;
|
||||
case "GET /gameClient/game/index.html":
|
||||
// not to be put in a frame of anyone's; the client shows it in a view of its own.
|
||||
res.setHeader("X-Frame-Options", "DENY");
|
||||
res.setHeader("Referrer-Policy", "no-referrer");
|
||||
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "game.html")), MIME[".html"]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method !== "GET" && req.method !== "HEAD") {
|
||||
console.log(`[http] unhandled ${route}`);
|
||||
send(res, 404, {error: "not_found"});
|
||||
return;
|
||||
}
|
||||
|
||||
if (config.logPackets) {
|
||||
console.log(`[http] GET ${url.pathname}`);
|
||||
}
|
||||
|
||||
// asset SWFs import their fonts from this fixed path next to the game page;
|
||||
// the launcher ships its own copy.
|
||||
if (url.pathname === "/gameClient/sharedFonts.swf") {
|
||||
send(res, 200, await fs.promises.readFile(config.sharedFontsSwf), MIME[".swf"]);
|
||||
return;
|
||||
}
|
||||
|
||||
// the patched client is served in place of the CDN's own copy.
|
||||
if (url.pathname.endsWith("/ajclient.swf")) {
|
||||
send(res, 200, await fs.promises.readFile(config.clientSwf), MIME[".swf"]);
|
||||
return;
|
||||
}
|
||||
|
||||
// A painting, by its id (MasterpieceFileServer).
|
||||
const painting = PAINTING_PATH.exec(url.pathname);
|
||||
if (painting) {
|
||||
const playingFrom = account => {
|
||||
const session = world.findOnline(account.username);
|
||||
return session ? limits.key(session.address) : null;
|
||||
};
|
||||
const picture = masterpieces.mayView(painting[1], from.key, playingFrom) || from.local ? masterpieces.image(painting[1]) : null;
|
||||
send(res, picture ? 200 : 404, picture || "Not found", picture ? MIME[".jpg"] : "text/plain");
|
||||
return;
|
||||
}
|
||||
|
||||
const relPath = decodeURIComponent(url.pathname).replace(/^\/+/, "");
|
||||
if (relPath === HUD_ASSETS_PATH) {
|
||||
send(res, 200, await fs.promises.readFile(config.hudAssetsSwf), MIME[".swf"]);
|
||||
return;
|
||||
}
|
||||
// the name tag badges of ours and the card's Bio tab, which the CDN has no file for.
|
||||
const badgeMedia = badges.mediaFile(relPath) || badges.cardMedia(relPath);
|
||||
if (badgeMedia) {
|
||||
const body = await fs.promises.readFile(badgeMedia).catch(() => null);
|
||||
send(res, body ? 200 : 404, body || "Not found", body ? MIME[".swf"] : "text/plain");
|
||||
return;
|
||||
}
|
||||
// the extra den music tracks, which the CDN does not have as files.
|
||||
const extra = await extraMusic.asset(relPath);
|
||||
if (extra) {
|
||||
send(res, extra.body ? 200 : 404, extra.body || "Not found", extra.body ? extra.type : "text/plain");
|
||||
return;
|
||||
}
|
||||
const clientPack = await defpacks.clientPack(relPath);
|
||||
if (clientPack) {
|
||||
send(res, 200, clientPack, "application/octet-stream");
|
||||
return;
|
||||
}
|
||||
// A room file in a seasonal theme ("<build>/roomDefs/theme_<other
|
||||
// build>/...", see roomAsSeenBy in world.js) comes from that other build,
|
||||
// or from the current one when the room did not exist yet back then.
|
||||
const themed = THEMED_ROOM.exec(relPath);
|
||||
const mayFetch = () => from.local || cacheMisses.allow(from.key);
|
||||
const body = (themed && Object.values(config.themes).some(theme => theme.build === Number(themed[2])) && await cdn.get(`${themed[2]}/roomDefs/${themed[3]}`, mayFetch))
|
||||
|| await cdn.get(themed ? `${themed[1]}/roomDefs/${themed[3]}` : relPath, mayFetch);
|
||||
if (!body) {
|
||||
console.log(`[http] 404 ${url.pathname}`);
|
||||
send(res, 404, "Not found", "text/plain");
|
||||
return;
|
||||
}
|
||||
res.setHeader("Cache-Control", "public, max-age=86400");
|
||||
send(res, 200, body, MIME[path.extname(relPath).toLowerCase()] || "application/octet-stream");
|
||||
};
|
||||
|
||||
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}`);
|
||||
if (!res.headersSent) {
|
||||
send(res, 500, {error: "server_error"});
|
||||
}
|
||||
else {
|
||||
res.destroy();
|
||||
}
|
||||
});
|
||||
};
|
||||
const server = config.webTls
|
||||
? https.createServer({cert: fs.readFileSync(config.webTls.certFile), key: fs.readFileSync(config.webTls.keyFile)}, onRequest)
|
||||
: http.createServer(onRequest);
|
||||
// nobody gets to hold a request open by trickling it in, nor a reply by
|
||||
// never reading it; and there is an end to how many connections there
|
||||
// may be, in all and from one address.
|
||||
server.requestTimeout = 30000;
|
||||
server.headersTimeout = 15000;
|
||||
server.timeout = config.httpSocketTimeoutMs;
|
||||
server.maxConnections = config.maxHttpConnections;
|
||||
const open = new Map(); // address, as limits count it -> connections
|
||||
server.on("connection", socket => {
|
||||
const address = limits.key(socket.remoteAddress);
|
||||
// behind a proxy every connection is the proxy's own.
|
||||
if (limits.isLoopback(socket.remoteAddress)) {
|
||||
return;
|
||||
}
|
||||
const count = (open.get(address) || 0) + 1;
|
||||
if (count > config.maxHttpConnectionsPerAddress) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
open.set(address, count);
|
||||
socket.once("close", () => {
|
||||
const left = open.get(address) - 1;
|
||||
if (left > 0) {
|
||||
open.set(address, left);
|
||||
}
|
||||
else {
|
||||
open.delete(address);
|
||||
}
|
||||
});
|
||||
});
|
||||
server.once("error", reject);
|
||||
server.listen(config.httpPort, config.bindAddress, () => {
|
||||
console.log(`[http] listening on ${config.bindAddress}:${config.httpPort}${config.webTls ? " (TLS)" : ""}`);
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = {start};
|
||||
@@ -0,0 +1,167 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const achievements = require("./achievements.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const {CURRENCIES, MAX_ITEMS, MAX_WORN, activeAvatar, addClothing, sendClothingAdded, sendClothingRemoved, resolvePurchase} = require("./player.js");
|
||||
|
||||
// clothing: buying, wearing and recycling (client side: ItemXtCommManager).
|
||||
|
||||
const DEF_ITEM = 1000;
|
||||
const DEF_DIAMOND = 1054;
|
||||
const DEF_COMBINED_LIST = 1060;
|
||||
const DEF_CURRENCY_EXCHANGE = 1051;
|
||||
const SHOP_TYPES = [DEF_ITEM, DEF_DIAMOND, DEF_COMBINED_LIST]; // kinds of shop that sell clothing
|
||||
const TYPE_CLOTHING = "1";
|
||||
const LAYER_PATTERN = "2";
|
||||
const LAYER_EYES = "3";
|
||||
const MAX_RECYCLED_AT_ONCE = 500;
|
||||
const MAX_USED_AT_ONCE = 200; // pieces put on or taken off in one message
|
||||
const RECYCLE_FRACTION = 0.3; // matches recyclePercentage sent at login
|
||||
|
||||
module.exports = ({others, sendItemList}) => {
|
||||
// ItemXtCommManager.itemBuyResponse: [status, shopId, newAmount, currencyType]
|
||||
const buyFailed = (session, shopId) => session.sendXt("ib", -1, 0, shopId, "", 0);
|
||||
|
||||
return {
|
||||
// shop.requestItemBuy: [shopId, 1, defId, colorIndex, isDiamondItem,
|
||||
// denItemInvIdx, username]. for an item priced in diamonds defId is its
|
||||
// diamond def's id.
|
||||
ib(session, roomId, [shopId, , defId, colorIndex, isDiamondItem]) {
|
||||
const {account} = session;
|
||||
const purchase = resolvePurchase(defId, isDiamondItem === "1", "clothing", id => {
|
||||
const own = defpacks.itemDef(id);
|
||||
return {cost: own ? Number(own.value) : 0, currencyType: own ? Number(own.currencyType) : -1};
|
||||
});
|
||||
const def = purchase && defpacks.itemDef(purchase.defId);
|
||||
const colors = def ? String(def.colors).split(",") : [];
|
||||
const currency = purchase && CURRENCIES[purchase.currencyType];
|
||||
// only clothing bought with a single currency is supported; combined
|
||||
// costs are refused.
|
||||
if (!SHOP_TYPES.includes(defpacks.listType(shopId)) || !def || def.type !== TYPE_CLOTHING
|
||||
|| !currency || !/^\d{1,3}$/.test(colorIndex) || colors[colorIndex] === undefined || account.items.length >= MAX_ITEMS
|
||||
|| (account.currency[currency] || 0) < purchase.cost) {
|
||||
buyFailed(session, shopId);
|
||||
return;
|
||||
}
|
||||
account.currency[currency] -= purchase.cost;
|
||||
achievements.currencyChanged(account, currency, -purchase.cost);
|
||||
achievements.add(account, achievements.VARS.clothesBought);
|
||||
const item = addClothing(account, def.id, colors[colorIndex]);
|
||||
accounts.save();
|
||||
sendClothingAdded(session, item);
|
||||
session.sendXt("ib", -1, 1, shopId, account.currency[currency], purchase.currencyType);
|
||||
},
|
||||
|
||||
// ItemXtCommManager.requestItemUse: [onCount, offCount, ...invIdxOn, ...invIdxOff]
|
||||
// for the animal in use. eyes and patterns are sent as minus their def id.
|
||||
iu(session, roomId, params) {
|
||||
const {account} = session;
|
||||
const onCount = Number(params[0]);
|
||||
const offCount = Number(params[1]);
|
||||
const ids = params.slice(2).map(Number);
|
||||
if (!Number.isInteger(onCount) || !Number.isInteger(offCount) || onCount < 0 || offCount < 0
|
||||
|| ids.length !== onCount + offCount || ids.length > MAX_USED_AT_ONCE || !ids.every(Number.isInteger)) {
|
||||
session.sendXt("iu", -1, 0);
|
||||
return;
|
||||
}
|
||||
const avatar = activeAvatar(account);
|
||||
// for "!outfit undo" (lib/commands.js).
|
||||
account.outfitUndo = {avInvId: avatar.avInvId, items: account.items.filter(item => item.on.includes(avatar.avInvId)).map(item => item.inv)};
|
||||
// returns the item's def id when the change was one this player can make.
|
||||
const setWorn = (invIdx, worn) => {
|
||||
if (invIdx < 0) {
|
||||
const def = defpacks.itemDef(-invIdx);
|
||||
if (def && def.layerId === LAYER_EYES && worn) {
|
||||
avatar.eyes = -invIdx;
|
||||
}
|
||||
else if (def && def.layerId === LAYER_PATTERN && (worn || avatar.pattern === -invIdx)) {
|
||||
avatar.pattern = worn ? -invIdx : 0;
|
||||
}
|
||||
return def ? -invIdx : null;
|
||||
}
|
||||
const item = account.items.find(candidate => candidate.inv === invIdx);
|
||||
if (item) {
|
||||
item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId);
|
||||
// no more than MAX_WORN on one animal: what is over stays off.
|
||||
if (worn && account.items.filter(candidate => candidate.on.includes(avatar.avInvId)).length >= MAX_WORN) {
|
||||
return null;
|
||||
}
|
||||
if (worn) {
|
||||
item.on.push(avatar.avInvId);
|
||||
}
|
||||
}
|
||||
return item ? item.def : null;
|
||||
};
|
||||
const off = ids.slice(onCount).filter(invIdx => setWorn(invIdx, false) !== null);
|
||||
const on = ids.slice(0, onCount).map(invIdx => [invIdx, setWorn(invIdx, true)]).filter(([, def]) => def !== null);
|
||||
accounts.save();
|
||||
// ItemXtCommManager.itemUseResponse
|
||||
session.sendXt("iu", -1, 1);
|
||||
// the reply only closes the editor. the animal in the room is redrawn
|
||||
// from this: itemsChangedListResponse, "3" = what is worn changed,
|
||||
// [3, inUse, perUserAvId, username, colour, onCount, offCount,
|
||||
// (invIdx, defId)..., offInvIdx...]. without it the player goes on
|
||||
// seeing the old outfit until the next room.
|
||||
session.sendXt("il", -1, 3, 1, avatar.perUserAvId, account.username, 0, on.length, off.length, ...on.flat(), ...off);
|
||||
for (const other of others(session)) {
|
||||
sendItemList(other, session, false);
|
||||
}
|
||||
},
|
||||
|
||||
// shop.requestCurrencyExchange: [shopId, exchangeDefId], one of the deals
|
||||
// in the currency exchange defPack (gems for tickets, diamonds for gems).
|
||||
// the reply (currencyExchangeResponse -> Shop.confirmPurchase) is
|
||||
// [status, new amount of the currency paid with]; the currency received
|
||||
// gets its own update.
|
||||
ce(session, roomId, [shopId, defId]) {
|
||||
const {account} = session;
|
||||
const def = defpacks.exchangeDef(defId);
|
||||
const paid = def && CURRENCIES[def.costType];
|
||||
const received = def && CURRENCIES[def.resultType];
|
||||
if (defpacks.listType(shopId) !== DEF_CURRENCY_EXCHANGE || !paid || !received || (account.currency[paid] || 0) < def.cost) {
|
||||
session.sendXt("ce", -1, 0, 0);
|
||||
return;
|
||||
}
|
||||
account.currency[paid] -= def.cost;
|
||||
account.currency[received] = (account.currency[received] || 0) + def.result;
|
||||
achievements.currencyChanged(account, paid, -def.cost);
|
||||
achievements.currencyChanged(account, received, def.result);
|
||||
accounts.save();
|
||||
// ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason]
|
||||
session.sendXt("cu", -1, def.resultType, account.currency[received], 0);
|
||||
session.sendXt("ce", -1, 1, account.currency[paid]);
|
||||
},
|
||||
|
||||
// ItemXtCommManager.requestItemRecycle: [invIdx, ...]. the reply
|
||||
// (itemRecycleResponse) is [count, newGemTotal, ...recycledInvIdx], and
|
||||
// the recycling window then waits, behind its spinner, for the item
|
||||
// list to change (ItemXtCommManager.checkIlCallbacks).
|
||||
ir(session, roomId, params) {
|
||||
const {account} = session;
|
||||
const recycled = [];
|
||||
for (const invIdx of new Set(params.slice(0, MAX_RECYCLED_AT_ONCE).map(Number))) {
|
||||
const index = account.items.findIndex(item => item.inv === invIdx);
|
||||
if (index === -1) {
|
||||
continue;
|
||||
}
|
||||
const def = defpacks.itemDef(account.items[index].def);
|
||||
const refund = def ? Number(def.recycleValue) || Math.floor(Number(def.value) * RECYCLE_FRACTION) : 0;
|
||||
if (def && def.currencyType === "0") {
|
||||
account.currency.gems = (account.currency.gems || 0) + refund;
|
||||
achievements.currencyChanged(account, "gems", refund);
|
||||
}
|
||||
account.items.splice(index, 1);
|
||||
recycled.push(invIdx);
|
||||
}
|
||||
accounts.save();
|
||||
session.sendXt("ir", -1, recycled.length, account.currency.gems || 0, ...recycled);
|
||||
if (recycled.length) {
|
||||
sendClothingRemoved(session, recycled);
|
||||
for (const other of others(session)) {
|
||||
sendItemList(other, session, false);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,137 @@
|
||||
"use strict";
|
||||
|
||||
const config = require("../config.js");
|
||||
|
||||
// small in-memory rate limits for the parts of the server that strangers can
|
||||
// reach: logins, sign-ups, error reports and the game socket; and who a web
|
||||
// request is from.
|
||||
|
||||
const LOOPBACK = ["127.0.0.1", "::1"];
|
||||
const MAX_KEYS = 100000;
|
||||
const MAX_KEY_LENGTH = 64;
|
||||
|
||||
// an address as limits count it. an IPv4 address is itself (also when it
|
||||
// arrives written as an IPv6 one, "::ffff:1.2.3.4"). an IPv6 address is its
|
||||
// first four groups, the /64: that is what one customer is given, and all
|
||||
// 2^64 addresses in it are theirs to use.
|
||||
const key = address => {
|
||||
const text = String(address || "").replace(/^::ffff:(?=\d+\.\d+\.\d+\.\d+$)/i, "").toLowerCase();
|
||||
if (!text.includes(":")) {
|
||||
return text.slice(0, MAX_KEY_LENGTH);
|
||||
}
|
||||
const [head, tail = ""] = text.split("%")[0].split("::");
|
||||
const front = head ? head.split(":") : [];
|
||||
const back = tail ? tail.split(":") : [];
|
||||
const groups = text.includes("::") ? [...front, ...Array(Math.max(0, 8 - front.length - back.length)).fill("0"), ...back] : front;
|
||||
return groups.slice(0, 4).map(group => group.replace(/^0+(?=.)/, "")).join(":").slice(0, MAX_KEY_LENGTH);
|
||||
};
|
||||
|
||||
const isLoopback = address => LOOPBACK.includes(String(address || "").replace(/^::ffff:/i, ""));
|
||||
|
||||
// is this address the server's own machine, and does that count for
|
||||
// anything here? (It must not when a local reverse proxy forwards everyone.)
|
||||
const isTrustedLocal = address => config.trustLocalRequests && isLoopback(address);
|
||||
|
||||
// who a web request is from: {address, key, local, direct}.
|
||||
// address the visitor's, for showing (the last hop a trusted proxy
|
||||
// reports, else the connection's own)
|
||||
// key the same as limits count it (above)
|
||||
// direct it came from this machine and through no proxy: somebody at
|
||||
// the server itself, or an SSH tunnel to it
|
||||
// local direct, and requests from this machine are trusted (config)
|
||||
// A request that carries a forwarding header came through a proxy or a
|
||||
// tunnel, whatever else is set, and is never taken for this machine's own.
|
||||
const clientOf = req => {
|
||||
const own = String(req.socket.remoteAddress || "").replace(/^::ffff:/i, "");
|
||||
const forwarded = req.headers["x-forwarded-for"] || req.headers.forwarded || req.headers["cf-connecting-ip"] || req.headers["x-real-ip"];
|
||||
const hops = String(req.headers["x-forwarded-for"] || "").split(",").map(hop => hop.trim()).filter(Boolean);
|
||||
const address = config.trustedProxy && isLoopback(own) && hops.length ? hops[hops.length - 1].replace(/^::ffff:/i, "").slice(0, 60) : own;
|
||||
const direct = isLoopback(own) && !forwarded;
|
||||
return {address, key: key(address), direct, local: direct && config.trustLocalRequests};
|
||||
};
|
||||
|
||||
// the names this server answers to: what a Host header, or the Origin of a
|
||||
// request that changes something, may say. A page from anywhere else that
|
||||
// got a browser to send a request here (DNS rebinding, a cross-site form)
|
||||
// names another.
|
||||
const ownHosts = (() => {
|
||||
const base = new URL(config.baseUrl);
|
||||
const site = new URL(config.siteUrl);
|
||||
const names = new Set([base.host, base.hostname, site.host, site.hostname]);
|
||||
for (const name of ["127.0.0.1", "localhost", "[::1]", config.bindAddress, config.host]) {
|
||||
names.add(`${name}:${config.httpPort}`);
|
||||
}
|
||||
return names;
|
||||
})();
|
||||
// an SSH tunnel to the server (`ssh -L <port>:127.0.0.1:8080`) arrives on
|
||||
// this machine's loopback with no forwarding header, under a loopback name
|
||||
// and whatever port its far end chose: that is the server's own too.
|
||||
const TUNNEL_HOST = /^(?:127\.0\.0\.1|localhost|\[::1\]):\d{1,5}$/;
|
||||
const throughTunnel = req => TUNNEL_HOST.test(String(req.headers.host || "").toLowerCase()) && clientOf(req).direct;
|
||||
const hostAllowed = req => ownHosts.has(String(req.headers.host || "").toLowerCase()) || throughTunnel(req);
|
||||
// A request that changes something must come from this server's own pages.
|
||||
// one with no Origin is not a browser's cross-site request.
|
||||
const originAllowed = req => {
|
||||
const {origin} = req.headers;
|
||||
if (!origin) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
const from = new URL(origin).host;
|
||||
// through a tunnel only the page of that very address: another page on
|
||||
// this computer's loopback, on another port, is another site.
|
||||
return ownHosts.has(from) || (throughTunnel(req) && from === String(req.headers.host).toLowerCase());
|
||||
}
|
||||
catch (err) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// allows `max` events per `windowMs` for each key.
|
||||
const limiter = (max, windowMs) => {
|
||||
const events = new Map(); // key -> timestamps inside the window
|
||||
const named = name => String(name).slice(0, MAX_KEY_LENGTH);
|
||||
const recent = name => (events.get(named(name)) || []).filter(time => time > Date.now() - windowMs);
|
||||
const timer = setInterval(() => {
|
||||
for (const name of events.keys()) {
|
||||
if (recent(name).length === 0) {
|
||||
events.delete(name);
|
||||
}
|
||||
}
|
||||
}, Math.max(windowMs, 10000));
|
||||
timer.unref();
|
||||
return {
|
||||
blocked: name => recent(name).length >= max,
|
||||
record(name) {
|
||||
const times = [...recent(name), Date.now()];
|
||||
// full: the keys longest in the table make room, a few at a time.
|
||||
// (Emptying it would let whoever filled it start afresh.)
|
||||
if (!events.has(named(name)) && events.size >= MAX_KEYS) {
|
||||
let dropped = 0;
|
||||
for (const oldest of events.keys()) {
|
||||
events.delete(oldest);
|
||||
if (++dropped >= 100) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
events.delete(named(name)); // so that it counts as the newest
|
||||
events.set(named(name), times.slice(-max));
|
||||
},
|
||||
allow(name) {
|
||||
if (this.blocked(name)) {
|
||||
return false;
|
||||
}
|
||||
this.record(name);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
// sign-ups from one address, shared by the /register page and the client's
|
||||
// Create Account screens. `trusted` is for a request already known to be
|
||||
// this machine's own.
|
||||
const registrations = limiter(config.registrationsPerHour, 3600000);
|
||||
const registrationAllowed = (address, trusted = false) => trusted || registrations.allow(key(address));
|
||||
|
||||
module.exports = {limiter, key, isLoopback, isTrustedLocal, clientOf, hostAllowed, originAllowed, registrationAllowed};
|
||||
@@ -0,0 +1,33 @@
|
||||
"use strict";
|
||||
|
||||
// keeps the most recent lines the server printed, for the admin panel's log
|
||||
// view. requiring this module is what starts the capture.
|
||||
|
||||
const MAX_LINES = 5000;
|
||||
const MAX_LINE_LENGTH = 2000;
|
||||
|
||||
const lines = []; // {id, time, text}
|
||||
let nextId = 1;
|
||||
|
||||
const capture = original => (...args) => {
|
||||
original(...args);
|
||||
const text = args.map(arg => (typeof arg === "string" ? arg : String(arg && arg.stack ? arg.stack : JSON.stringify(arg)))).join(" ");
|
||||
for (const line of text.split("\n")) {
|
||||
lines.push({id: nextId++, time: Date.now(), text: line.slice(0, MAX_LINE_LENGTH)});
|
||||
}
|
||||
if (lines.length > MAX_LINES) {
|
||||
lines.splice(0, lines.length - MAX_LINES);
|
||||
}
|
||||
};
|
||||
|
||||
console.log = capture(console.log.bind(console));
|
||||
console.error = capture(console.error.bind(console));
|
||||
|
||||
// lines newer than id `after` whose text contains `filter` (any case), newest
|
||||
// `limit` of them, oldest first.
|
||||
const recent = (after = 0, filter = "", limit = 500) => {
|
||||
const wanted = filter.toLowerCase();
|
||||
return lines.filter(line => line.id > after && (!wanted || line.text.toLowerCase().includes(wanted))).slice(-limit);
|
||||
};
|
||||
|
||||
module.exports = {recent, count: () => nextId - 1};
|
||||
@@ -0,0 +1,589 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const accounts = require("./accounts.js");
|
||||
const config = require("../config.js");
|
||||
const limits = require("./limits.js");
|
||||
const achievements = require("./achievements.js");
|
||||
const badges = require("./badges.js");
|
||||
const bans = require("./bans.js");
|
||||
const captcha = require("./captcha.js");
|
||||
const chatlog = require("./chatlog.js");
|
||||
const erase = require("./erase.js");
|
||||
const masterpieces = require("./masterpieces.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const support = require("./support.js");
|
||||
const totp = require("./totp.js");
|
||||
const world = require("./world.js");
|
||||
|
||||
// the account page at /account: what a player can do about their own
|
||||
// account from a browser. they sign in with the game's username and
|
||||
// password; that sets a cookie only this page's requests send back
|
||||
// (HttpOnly, SameSite=Strict, Path=/account). sessions live in memory, so
|
||||
// restarting the server signs everyone out of the page (not out of the game).
|
||||
//
|
||||
// A locked account can still sign in here: this is where it is unlocked.
|
||||
//
|
||||
// A banned account, or anyone signing in from a banned address, gets another
|
||||
// page altogether: what the ban is and why, one appeal, and the way out
|
||||
// (signing out, or deleting the account). the password and two-step sign-in
|
||||
// stay within reach, in case the account is in other hands. nothing else of
|
||||
// the account is sent or may be changed until the ban is over.
|
||||
|
||||
const COOKIE = "ajc_account";
|
||||
// A device that gave its two-step code keeps this for 30 days (lib/totp.js).
|
||||
const DEVICE_COOKIE = "ajc_device";
|
||||
const SESSION_HOURS = 12;
|
||||
const TEN_MINUTES_MS = 600000;
|
||||
const MAX_NOTE = 120;
|
||||
|
||||
// wrong passwords before further tries from an address are refused for a
|
||||
// while, as for the launcher's sign-in (lib/http.js).
|
||||
const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS);
|
||||
// the password is asked for again before the changes that matter. A page
|
||||
// left open, or one that fell into other hands, gets this many wrong tries
|
||||
// at it and is then signed out.
|
||||
const WRONG_PASSWORDS_ALLOWED = 5;
|
||||
const wrongPasswords = limits.limiter(WRONG_PASSWORDS_ALLOWED, TEN_MINUTES_MS);
|
||||
// what may be done from the page of a ban (above).
|
||||
const BANNED_MAY = ["password", "twoStepStart", "twoStepConfirm", "twoStepOff", "forgetDevices", "delete", "appeal"];
|
||||
// and from the page of a rejected username: the same, with a new name in
|
||||
// place of an appeal.
|
||||
const RENAMING_MAY = ["password", "twoStepStart", "twoStepConfirm", "twoStepOff", "forgetDevices", "delete", "newName"];
|
||||
// things that write to the database, per account.
|
||||
const writesPerTenMinutes = limits.limiter(60, TEN_MINUTES_MS);
|
||||
|
||||
const sessions = new Map(); // SHA-256 of a session token -> {id: account id, expiry: ms}
|
||||
|
||||
const sha256 = text => crypto.createHash("sha256").update(text).digest("hex");
|
||||
|
||||
const cookieToken = req => {
|
||||
const match = new RegExp(`(?:^|;\\s*)${COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "");
|
||||
return match ? match[1] : null;
|
||||
};
|
||||
|
||||
const cookieHeader = (token, maxAgeSeconds, name = COOKIE) =>
|
||||
`${name}=${token}; Path=/account; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
|
||||
|
||||
const deviceCookie = req => {
|
||||
const match = new RegExp(`(?:^|;\\s*)${DEVICE_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "");
|
||||
return match ? match[1] : null;
|
||||
};
|
||||
|
||||
const signedInAs = req => {
|
||||
const token = cookieToken(req);
|
||||
const session = token && sessions.get(sha256(token));
|
||||
return session && session.expiry > Date.now() ? accounts.byId(session.id) : null;
|
||||
};
|
||||
|
||||
const signIn = (res, account, otherCookies = []) => {
|
||||
for (const [hash, session] of sessions) {
|
||||
if (session.expiry < Date.now()) {
|
||||
sessions.delete(hash);
|
||||
}
|
||||
}
|
||||
const token = crypto.randomBytes(24).toString("hex");
|
||||
sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000});
|
||||
res.setHeader("Set-Cookie", [cookieHeader(token, SESSION_HOURS * 3600), ...otherCookies]);
|
||||
};
|
||||
|
||||
// ends the account's sessions on this page, all but the one making `req`.
|
||||
const signOutOthers = (account, req) => {
|
||||
const keep = req && cookieToken(req) ? sha256(cookieToken(req)) : null;
|
||||
for (const [hash, session] of sessions) {
|
||||
if (session.id === account.id && hash !== keep) {
|
||||
sessions.delete(hash);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const twoStepOf = account => ({on: totp.isOn(account), since: account.totp ? account.totp.since : null,
|
||||
recoveryLeft: account.totp ? account.totp.recovery.length : 0, devices: totp.freshDevices(account).length, deviceDays: totp.DEVICE_DAYS});
|
||||
|
||||
// the ban in the way of this account from where it is asked about: its own,
|
||||
// or else the one on that address. {kind, permanent, seconds, reason,
|
||||
// since, addressKey}, or null.
|
||||
const banFor = (account, from) => {
|
||||
const own = world.moderation.banOf(account);
|
||||
if (own) {
|
||||
return {kind: "account", permanent: own.seconds === world.moderation.PERMANENT, seconds: own.seconds, reason: own.reason, since: own.since, addressKey: ""};
|
||||
}
|
||||
const address = bans.addressBan(from.address);
|
||||
return address ? {kind: "address", permanent: true, seconds: world.moderation.PERMANENT, reason: address.reason, since: address.createdAt, addressKey: address.key} : null;
|
||||
};
|
||||
|
||||
// all the page of a ban is given.
|
||||
const bannedProfile = (account, ban) => {
|
||||
const appeal = bans.appealOf(account);
|
||||
return {
|
||||
username: account.username,
|
||||
banned: {kind: ban.kind, permanent: ban.permanent, seconds: ban.seconds, reason: ban.reason, since: ban.since},
|
||||
appeal: appeal && {createdAt: appeal.createdAt, text: appeal.text, status: appeal.status, reply: appeal.reply, handledAt: appeal.handledAt},
|
||||
appealLimit: bans.MAX_APPEAL,
|
||||
twoStep: twoStepOf(account),
|
||||
};
|
||||
};
|
||||
|
||||
const profile = (account, from) => {
|
||||
const ban = banFor(account, from);
|
||||
if (ban) {
|
||||
return bannedProfile(account, ban);
|
||||
}
|
||||
// A rejected username (lib/moderation.js): a new one before anything else.
|
||||
if (account.nameRejected) {
|
||||
return {username: account.username, banned: null, nameRejected: true, twoStep: twoStepOf(account)};
|
||||
}
|
||||
const avatar = account.avatars.find(candidate => candidate.perUserAvId === account.activeAvatar) || account.avatars[0];
|
||||
return {
|
||||
username: account.username,
|
||||
createdAt: account.createdAt,
|
||||
lastSeen: account.lastSeen || account.lastLogin || null,
|
||||
online: Boolean(world.findOnline(account.username)),
|
||||
logins: account.numLogins || 0,
|
||||
animals: account.avatars.length,
|
||||
animalType: avatar ? avatar.type : null,
|
||||
items: account.items.length,
|
||||
denItems: account.denItems.length,
|
||||
pets: account.pets.length,
|
||||
buddies: account.buddies.length,
|
||||
banned: null,
|
||||
locked: account.locked,
|
||||
twoStep: twoStepOf(account),
|
||||
discord: account.discord,
|
||||
bio: account.bio,
|
||||
bioLimit: badges.MAX_BIO,
|
||||
badges: badges.of(account).map(badge => badge.label),
|
||||
features: Object.fromEntries(accounts.FEATURES.map(name => [name, accounts.featureOn(account, name)])),
|
||||
history: account.logins,
|
||||
denVisits: account.denVisits,
|
||||
trades: account.tradeHistory,
|
||||
buddyList: account.buddies.map(key => {
|
||||
const buddy = accounts.byName(key);
|
||||
return {name: buddy ? buddy.username : key, online: Boolean(buddy && world.findOnline(buddy.username)), note: account.buddyNotes[key] || ""};
|
||||
}).sort((one, other) => one.name.localeCompare(other.name)),
|
||||
blocked: account.blocked.map(key => (accounts.byName(key) || {username: key}).username).sort(),
|
||||
achievements: achievements.progress(account),
|
||||
offers: {incoming: world.tradeOffers.incoming(account), outgoing: world.tradeOffers.outgoing(account)},
|
||||
nameRequests: support.nameRequestsOf(account),
|
||||
feedback: support.feedbackOf(account),
|
||||
};
|
||||
};
|
||||
|
||||
// everything kept about the account, for its owner to take away: the
|
||||
// account as it is stored, without what would let someone in (the password's
|
||||
// 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 dataOf = account => ({
|
||||
exportedAt: new Date().toISOString(),
|
||||
server: config.baseUrl,
|
||||
account: {...Object.fromEntries(Object.entries(account).filter(([field]) => !SECRET_FIELDS.includes(field))), twoStepOn: totp.isOn(account)},
|
||||
chat: chatlog.saidBy(account),
|
||||
banRecord: bans.historyOf(account),
|
||||
appeal: bans.appealOf(account),
|
||||
usernameRequests: support.nameRequestsOf(account),
|
||||
feedback: support.feedbackOf(account),
|
||||
paintings: masterpieces.madeBy(account),
|
||||
});
|
||||
|
||||
const NAME_ERRORS = {
|
||||
invalid_username: "3 to 20 letters, digits, spaces, dots or dashes, with at least three letters.",
|
||||
username_taken: "Username taken.",
|
||||
name_not_allowed: "That name is not allowed.",
|
||||
same_name: "That is already your username.",
|
||||
};
|
||||
const OFFER_ERRORS = {
|
||||
unavailable: "You cannot trade with them.",
|
||||
not_listed: "No longer on their trade list.",
|
||||
nothing: "Pick something to give.",
|
||||
not_yours: "You no longer have one of those.",
|
||||
too_many: "Too many offers waiting.",
|
||||
};
|
||||
const FEEDBACK_ERRORS = {
|
||||
empty: "Write something first.",
|
||||
unknown_kind: "Pick feedback or a bug report.",
|
||||
too_many: "Too many today. Try tomorrow.",
|
||||
};
|
||||
|
||||
// is `password` the account's own? A wrong one counts, and after a few the
|
||||
// page is signed out (the caller of `act` sees to that).
|
||||
const passwordAgain = (account, password) => {
|
||||
if (wrongPasswords.blocked(account.id)) {
|
||||
return false;
|
||||
}
|
||||
const right = accounts.authenticate(account.username, password) === account;
|
||||
if (!right) {
|
||||
wrongPasswords.record(account.id);
|
||||
}
|
||||
return right;
|
||||
};
|
||||
|
||||
// one change to the signed-in account. returns {ok: text} or {error: text}.
|
||||
const act = (account, body, req, from, res) => {
|
||||
const ban = banFor(account, from);
|
||||
if (ban && !BANNED_MAY.includes(body.action)) {
|
||||
return {error: "Not while banned."};
|
||||
}
|
||||
if (!ban && account.nameRejected && !RENAMING_MAY.includes(body.action)) {
|
||||
return {error: "Choose a new username first."};
|
||||
}
|
||||
switch (body.action) {
|
||||
// in place of a rejected username, at once and under the sign-up rules.
|
||||
case "newName": {
|
||||
if (!account.nameRejected || ban) {
|
||||
return {error: "Your username was not rejected."};
|
||||
}
|
||||
const wanted = typeof body.newName === "string" ? body.newName.trim() : "";
|
||||
if (wanted.toLowerCase() === account.username.toLowerCase()) {
|
||||
return {error: NAME_ERRORS.same_name};
|
||||
}
|
||||
world.disconnect(account);
|
||||
const problem = accounts.rename(account, wanted);
|
||||
if (problem) {
|
||||
return {error: NAME_ERRORS[problem] || NAME_ERRORS.invalid_username};
|
||||
}
|
||||
delete account.nameRejected;
|
||||
accounts.save();
|
||||
console.log(`[account] a rejected username was replaced by "${account.username}" from ${from.address}`);
|
||||
return {ok: "Saved."};
|
||||
}
|
||||
// one for each account, ever: an answer that wants a follow-up says
|
||||
// where to go with it.
|
||||
case "appeal": {
|
||||
if (!ban) {
|
||||
return {error: "You are not banned."};
|
||||
}
|
||||
const result = bans.appeal(account, body.text, ban.addressKey);
|
||||
return result.error ? {error: result.error === "empty" ? "Write something first." : "Already appealed."} : {ok: "Sent."};
|
||||
}
|
||||
case "password": {
|
||||
// asked for again: a page left open is not enough to take an account over.
|
||||
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."};
|
||||
}
|
||||
world.moderation.actions.kick(account);
|
||||
signOutOthers(account, req);
|
||||
console.log(`[account] "${account.username}" changed their password from ${from.address}`);
|
||||
return {ok: "Password changed."};
|
||||
}
|
||||
case "requestName": {
|
||||
const result = support.requestName(account, body.newName, body.reason);
|
||||
return result.error ? {error: NAME_ERRORS[result.error]} : {ok: `Requested "${result.request.newName}".`};
|
||||
}
|
||||
case "withdrawName":
|
||||
return support.withdrawNameRequest(account) ? {ok: "Withdrawn."} : {error: "No request waiting."};
|
||||
case "feedback": {
|
||||
const result = support.sendFeedback(account, String(body.kind), body.text);
|
||||
return result.error ? {error: FEEDBACK_ERRORS[result.error]} : {ok: body.kind === "bug" ? "Bug report sent." : "Feedback sent."};
|
||||
}
|
||||
case "lock": {
|
||||
account.locked = body.locked === true;
|
||||
if (account.locked) {
|
||||
// out of the game now, and no saved sign-in gets back in.
|
||||
accounts.revokeTokens(account);
|
||||
world.moderation.actions.kick(account);
|
||||
}
|
||||
accounts.save();
|
||||
console.log(`[account] "${account.username}" ${account.locked ? "locked" : "unlocked"} from ${from.address}`);
|
||||
return {ok: account.locked ? "Locked." : "Unlocked."};
|
||||
}
|
||||
case "feature": {
|
||||
if (!accounts.FEATURES.includes(body.feature) || typeof body.on !== "boolean") {
|
||||
return {error: "Unknown setting."};
|
||||
}
|
||||
account.features[body.feature] = body.on;
|
||||
accounts.save();
|
||||
return {ok: "Saved."};
|
||||
}
|
||||
// two-step sign-in (lib/totp.js). turning it on: the password again,
|
||||
// then a secret for their authenticator app, then a code from the app
|
||||
// to show it took. saved sign-ins end, so every device passes it once.
|
||||
case "twoStepStart": {
|
||||
if (totp.isOn(account)) {
|
||||
return {error: "2FA is already on."};
|
||||
}
|
||||
if (!passwordAgain(account, body.current)) {
|
||||
return {error: "Wrong password."};
|
||||
}
|
||||
const setup = totp.begin(account);
|
||||
accounts.save();
|
||||
return {ok: "Scan the code.", setup};
|
||||
}
|
||||
case "twoStepConfirm": {
|
||||
const recovery = totp.confirm(account, body.code);
|
||||
if (!recovery) {
|
||||
accounts.save();
|
||||
return {error: "Wrong code."};
|
||||
}
|
||||
accounts.revokeTokens(account);
|
||||
accounts.save();
|
||||
console.log(`[account] "${account.username}" turned two-step sign-in on from ${from.address}`);
|
||||
return {ok: "2FA is on.", recovery};
|
||||
}
|
||||
// turning it off: the password and a code (or a recovery code).
|
||||
case "twoStepOff": {
|
||||
if (!totp.isOn(account)) {
|
||||
return {error: "2FA is not on."};
|
||||
}
|
||||
if (!passwordAgain(account, body.current)) {
|
||||
return {error: "Wrong password."};
|
||||
}
|
||||
if (!totp.verify(account, String(body.code || ""))) {
|
||||
accounts.save();
|
||||
return {error: "Wrong code."};
|
||||
}
|
||||
totp.turnOff(account);
|
||||
accounts.save();
|
||||
res.setHeader("Set-Cookie", cookieHeader("", 0, DEVICE_COOKIE));
|
||||
console.log(`[account] "${account.username}" turned two-step sign-in off from ${from.address}`);
|
||||
return {ok: "2FA is off."};
|
||||
}
|
||||
case "forgetDevices":
|
||||
totp.forgetDevices(account);
|
||||
accounts.save();
|
||||
return {ok: "Trusted devices forgotten."};
|
||||
// their bio, for the Bio tab of their card in the game. empty takes it off.
|
||||
case "bio": {
|
||||
// typed words others read: not while they cannot chat.
|
||||
if (world.moderation.isSilenced(account)) {
|
||||
return {error: "You cannot change your bio while silenced."};
|
||||
}
|
||||
const bio = badges.bioText(body.text);
|
||||
if (bio === null) {
|
||||
return {error: `At most ${badges.MAX_BIO} characters on ${badges.MAX_BIO_LINES} lines.`};
|
||||
}
|
||||
account.bio = bio;
|
||||
accounts.save();
|
||||
return {ok: bio ? "Saved." : "Removed."};
|
||||
}
|
||||
// their Discord username, for their card in the game. empty takes it off.
|
||||
case "discord": {
|
||||
const name = badges.discordName(body.name);
|
||||
if (name === null) {
|
||||
return {error: "Not a Discord username."};
|
||||
}
|
||||
account.discord = name;
|
||||
accounts.save();
|
||||
return {ok: name ? "Saved." : "Removed."};
|
||||
}
|
||||
// the player's own words about a buddy; only they see them.
|
||||
case "buddyNote": {
|
||||
const key = String(body.name || "").toLowerCase();
|
||||
if (!account.buddies.includes(key)) {
|
||||
return {error: "Not a buddy."};
|
||||
}
|
||||
const note = String(body.note || "").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_NOTE);
|
||||
if (note) {
|
||||
account.buddyNotes[key] = note;
|
||||
}
|
||||
else {
|
||||
delete account.buddyNotes[key];
|
||||
}
|
||||
accounts.save();
|
||||
return {ok: "Saved."};
|
||||
}
|
||||
// blocking and unblocking, as the game's own buttons do it.
|
||||
case "block":
|
||||
case "unblock": {
|
||||
const target = accounts.byName(String(body.name || "").trim());
|
||||
if (!target || target === account) {
|
||||
return {error: "No such player."};
|
||||
}
|
||||
return world.setBlocked(account, target, body.action === "block")
|
||||
? {ok: body.action === "block" ? "Blocked." : "Unblocked."}
|
||||
: {error: body.action === "block" ? "Already blocked, or your list is full." : "Not blocked."};
|
||||
}
|
||||
// an offer for something on another player's trade list, left for them
|
||||
// to answer on their own page.
|
||||
case "offer": {
|
||||
const problem = world.tradeOffers.make(account, accounts.byName(String(body.to || "").trim()), body.wanted, body.offered);
|
||||
return problem ? {error: OFFER_ERRORS[problem]} : {ok: "Offer sent."};
|
||||
}
|
||||
case "answerOffer": {
|
||||
const problem = world.tradeOffers.answer(account, body.id, body.accept === true, world.refreshInventories);
|
||||
return problem ? {error: problem === "gone" ? "That offer is no longer possible." : "No such offer."}
|
||||
: {ok: body.accept === true ? "Traded." : "Declined."};
|
||||
}
|
||||
case "withdrawOffer":
|
||||
return world.tradeOffers.withdraw(account, String(body.to || ""), body.id) ? {ok: "Withdrawn."} : {error: "No such offer."};
|
||||
case "signOutEverywhere":
|
||||
accounts.revokeTokens(account);
|
||||
totp.forgetDevices(account);
|
||||
accounts.save();
|
||||
world.moderation.actions.kick(account);
|
||||
signOutOthers(account, req);
|
||||
return {ok: "Signed out everywhere."};
|
||||
// for good: the password again, and the username typed out.
|
||||
case "delete": {
|
||||
if (!passwordAgain(account, body.current)) {
|
||||
return {error: "Wrong password."};
|
||||
}
|
||||
if (String(body.confirm || "").trim().toLowerCase() !== account.username.toLowerCase()) {
|
||||
return {error: "Username does not match."};
|
||||
}
|
||||
const name = account.username;
|
||||
world.disconnect(account);
|
||||
signOutOthers(account, null);
|
||||
erase(account);
|
||||
console.log(`[account] "${name}" deleted their account from ${from.address}`);
|
||||
return {ok: "Account deleted.", deleted: true};
|
||||
}
|
||||
default:
|
||||
return {error: "Unknown action."};
|
||||
}
|
||||
};
|
||||
|
||||
const PAGE_HEADERS = {
|
||||
"Cache-Control": "no-store",
|
||||
"X-Frame-Options": "DENY",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
"Content-Security-Policy": captcha.policy("default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; "
|
||||
+ "form-action 'none'; frame-ancestors 'none'; base-uri 'none'"),
|
||||
};
|
||||
|
||||
// A request that changes something must come from this server's own page.
|
||||
const sameOrigin = limits.originAllowed;
|
||||
|
||||
// `from` is {address, local}; `web` is {send, readJson} from lib/http.js.
|
||||
const handle = async (req, res, url, from, web) => {
|
||||
for (const [name, value] of Object.entries(PAGE_HEADERS)) {
|
||||
res.setHeader(name, value);
|
||||
}
|
||||
const reply = (status, body) => web.send(res, status, body);
|
||||
const route = `${req.method} ${url.pathname.replace(/\/$/, "") || "/account"}`;
|
||||
|
||||
if (route === "GET /account") {
|
||||
web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "account.html"))), "text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (req.method === "POST" && !sameOrigin(req)) {
|
||||
reply(403, {error: "forbidden"});
|
||||
return;
|
||||
}
|
||||
const body = req.method === "POST" ? await web.readJson(req) : {};
|
||||
|
||||
switch (route) {
|
||||
case "POST /account/api/login": {
|
||||
const key = String(body.username || "").trim().toLowerCase();
|
||||
if (!from.local && failuresByAddress.blocked(from.key)) {
|
||||
reply(429, {error: "Too many attempts. Try later."});
|
||||
return;
|
||||
}
|
||||
// looked up first: with AJ_REGISTER=1 authenticate() would make the account.
|
||||
const known = accounts.byName(key);
|
||||
const captchaProblem = await captcha.check({captcha: body.captcha, captcha_pass: body.captchaPass}, from, "login", known);
|
||||
if (captchaProblem) {
|
||||
reply(captchaProblem === "captcha_unavailable" ? 503 : 401, {error: captcha.MESSAGES[captchaProblem], captcha: true});
|
||||
return;
|
||||
}
|
||||
const account = known && await accounts.authenticateAsync(known.username, body.password) === known ? known : null;
|
||||
if (!account) {
|
||||
failuresByAddress.record(from.key);
|
||||
if (known) {
|
||||
accounts.recordLogin(known, "web", from.address, false);
|
||||
accounts.save();
|
||||
}
|
||||
reply(401, {error: "Wrong username or password."});
|
||||
return;
|
||||
}
|
||||
// two-step sign-in: a code after the password, unless this browser
|
||||
// gave one in the last 30 days (lib/totp.js).
|
||||
const cookies = [];
|
||||
if (totp.isOn(account) && !totp.deviceTrusted(account, deviceCookie(req))) {
|
||||
if (!body.code) {
|
||||
reply(401, {error: "Enter your 2FA code.", twoStep: true, captchaPass: captcha.issuePass(account, from)});
|
||||
return;
|
||||
}
|
||||
if (!totp.verify(account, String(body.code))) {
|
||||
failuresByAddress.record(from.key);
|
||||
accounts.recordLogin(account, "web", from.address, false);
|
||||
accounts.save();
|
||||
reply(401, {error: "Wrong code.", twoStep: true, captchaPass: captcha.issuePass(account, from)});
|
||||
return;
|
||||
}
|
||||
if (body.rememberDevice === true) {
|
||||
cookies.push(cookieHeader(totp.trustDevice(account, "web"), totp.DEVICE_DAYS * 86400, DEVICE_COOKIE));
|
||||
}
|
||||
}
|
||||
accounts.recordLogin(account, "web", from.address);
|
||||
accounts.save();
|
||||
signIn(res, account, cookies);
|
||||
reply(200, {ok: true});
|
||||
return;
|
||||
}
|
||||
case "POST /account/api/logout": {
|
||||
const token = cookieToken(req);
|
||||
if (token) {
|
||||
sessions.delete(sha256(token));
|
||||
}
|
||||
res.setHeader("Set-Cookie", cookieHeader("", 0));
|
||||
reply(200, {ok: true});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const account = signedInAs(req);
|
||||
if (!account) {
|
||||
reply(401, {error: "Sign in first."});
|
||||
return;
|
||||
}
|
||||
switch (route) {
|
||||
// A copy of their data, as a file. also from the page of a ban.
|
||||
case "GET /account/api/export":
|
||||
if (!writesPerTenMinutes.allow(account.id)) {
|
||||
reply(429, {error: "Too many. Try later."});
|
||||
return;
|
||||
}
|
||||
res.setHeader("Content-Disposition", `attachment; filename="burrow-data-${account.id}.json"`);
|
||||
web.send(res, 200, JSON.stringify(dataOf(account), null, 2));
|
||||
return;
|
||||
case "GET /account/api/me":
|
||||
reply(200, profile(account, from));
|
||||
return;
|
||||
// for the trade offer form: what the player could give, and what
|
||||
// another player has up for trade.
|
||||
case "GET /account/api/tradable": {
|
||||
if (banFor(account, from) || account.nameRejected) {
|
||||
reply(403, {error: "Not now."});
|
||||
return;
|
||||
}
|
||||
const other = accounts.byName(url.searchParams.get("of") || "");
|
||||
reply(200, {mine: world.tradeOffers.owned(account), theirs: other && other !== account ? world.tradeOffers.listed(other) : [],
|
||||
found: Boolean(other && other !== account)});
|
||||
return;
|
||||
}
|
||||
case "POST /account/api/act": {
|
||||
if (!writesPerTenMinutes.allow(account.id)) {
|
||||
reply(429, {error: "Too many changes. Try later."});
|
||||
return;
|
||||
}
|
||||
const result = act(account, body, req, from, res);
|
||||
// too many wrong passwords on this page: it is signed out.
|
||||
if (!result.deleted && wrongPasswords.blocked(account.id)) {
|
||||
signOutOthers(account, null);
|
||||
res.setHeader("Set-Cookie", cookieHeader("", 0));
|
||||
reply(401, {error: "Too many wrong passwords. Sign in again."});
|
||||
return;
|
||||
}
|
||||
if (result.deleted) {
|
||||
res.setHeader("Set-Cookie", cookieHeader("", 0));
|
||||
}
|
||||
reply(result.ok ? 200 : 400, result.ok && !result.deleted ? {...result, account: profile(account, from)} : result);
|
||||
return;
|
||||
}
|
||||
default:
|
||||
reply(404, {error: "not_found"});
|
||||
}
|
||||
};
|
||||
|
||||
// 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};
|
||||
@@ -0,0 +1,333 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const config = require("../config.js");
|
||||
const accounts = require("./accounts.js");
|
||||
const limits = require("./limits.js");
|
||||
|
||||
// masterpieces: paintings from the Art Studio, framed and hung in a den
|
||||
// (client side: game.artStudioPainting.ArtStudioPainting, the same in
|
||||
// ArtStudioGridDrawing, masterpiece.MasterpieceDisplayItem,
|
||||
// gui.MasterpiecePreview).
|
||||
//
|
||||
// how one comes about, in the client's order:
|
||||
// 1. the game asks for an upload token over the game socket ("gmtkn").
|
||||
// 2. it posts the painting, a JPEG, with that token to the web server
|
||||
// (the mdUrl flashvar + "mp") and is told the painting's id.
|
||||
// 3. it buys the Masterpiece den item (diamond def 221) naming that id
|
||||
// and the frame picked, for two diamonds or a Masterpiece Token.
|
||||
// 4. the item is in the inventory but "not approved": the client will
|
||||
// not place, trade or recycle it. whoever runs the server looks at it
|
||||
// in the admin panel and approves or rejects it. (That review can be
|
||||
// switched off there; paintings are then approved as they are bought.)
|
||||
// Everyone's client fetches a painting from "masterpieces/<id>" on the
|
||||
// content server when it has to draw it.
|
||||
//
|
||||
// A painting lives here, in a table of its own: who made it and where it
|
||||
// stands. the picture is a file, data/masterpieces/<id>.jpg (the table's
|
||||
// `image` column held it once, and is left empty now: pictures made the
|
||||
// one file with every account in it many times its size). the den item made from it carries the painting's id
|
||||
// (`image` on the den item, see lib/dens.js) and can change hands; the
|
||||
// painting's maker stays who it was.
|
||||
|
||||
const SCHEMA = `
|
||||
CREATE TABLE IF NOT EXISTS masterpieces (
|
||||
id TEXT PRIMARY KEY,
|
||||
creator_id INTEGER NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
status INTEGER NOT NULL,
|
||||
frame INTEGER NOT NULL,
|
||||
reviewed_at INTEGER,
|
||||
likes TEXT NOT NULL,
|
||||
image BLOB NOT NULL
|
||||
);
|
||||
`;
|
||||
|
||||
const UPLOADED = 0; // posted, not made into an item yet
|
||||
const PENDING = 1; // an item, waiting to be looked at
|
||||
const APPROVED = 2;
|
||||
|
||||
const DEN_ITEM = 2725; // "Masterpiece" (DenItem.isCustom)
|
||||
const TOKEN_DEN_ITEM = 2947; // "Masterpiece Token": pays for one in place of diamonds
|
||||
const DIAMOND_DEF = 221; // what the Art Studio buys
|
||||
// the frames, in the order the client numbers them (generic list 424; a
|
||||
// masterpiece's den item "version" is an index into it), with each one's
|
||||
// name string. they are media files; the order is ours, since the game's
|
||||
// own list is gone, and must not change once masterpieces exist.
|
||||
const FRAMES = [
|
||||
[4813, 25174], [4816, 25175], [4814, 25177], [4815, 25176], [4851, 25308], [4888, 25306], [4892, 25307], [4941, 25305],
|
||||
[5688, 28858], [5733, 29009], [5780, 29304], [5948, 29967], [5949, 29968], [6075, 30265], [6077, 30266], [6170, 30375],
|
||||
[6921, 31954], [7139, 32409], [7164, 32479], [7186, 32594], [7232, 32663], [7254, 32753], [7277, 32754], [7324, 32755],
|
||||
];
|
||||
const LIST_FRAMES_OFFERED = 416;
|
||||
const LIST_FRAMES_IN_ORDER = 424;
|
||||
|
||||
const REVIEW_SETTING = "masterpiece_review"; // "0" = approve as they are bought
|
||||
const MAX_IMAGE_BYTES = 2 * 1024 * 1024;
|
||||
const TOKEN_MINUTES = 15;
|
||||
const UNCLAIMED_MINUTES = 60;
|
||||
const MAX_WAITING_PER_ACCOUNT = 30; // waiting to be looked at
|
||||
const MAX_APPROVED_PER_ACCOUNT = 300; // on show, of one maker's
|
||||
const MAX_SIDE = 4096; // pixels, either way
|
||||
const NO_IMAGE = Buffer.alloc(0);
|
||||
const folder = () => path.join(config.dataDir, "masterpieces");
|
||||
const fileOf = id => path.join(folder(), `${id}.jpg`);
|
||||
const GALLERY_SPOTS = 12; // PartyManager.setupMasterpiecesInRoom
|
||||
|
||||
const uploadsPerHour = limits.limiter(30, 3600000);
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
const db = () => accounts.database();
|
||||
|
||||
const known = new Map(); // id -> {id, creator, createdAt, status, frame, likes: [account ids]}
|
||||
const tokens = new Map(); // upload token -> {account id, expires (ms)}
|
||||
|
||||
const load = () => {
|
||||
db().exec(SCHEMA);
|
||||
fs.mkdirSync(folder(), {recursive: true});
|
||||
// pictures still in the table move out into files, once.
|
||||
for (const row of db().prepare("SELECT id FROM masterpieces WHERE length(image) > 0").all()) {
|
||||
const {image: picture} = db().prepare("SELECT image FROM masterpieces WHERE id = ?").get(row.id);
|
||||
fs.writeFileSync(fileOf(row.id), Buffer.from(picture));
|
||||
db().prepare("UPDATE masterpieces SET image = ? WHERE id = ?").run(NO_IMAGE, row.id);
|
||||
}
|
||||
for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, likes FROM masterpieces").all()) {
|
||||
known.set(row.id, {id: row.id, creator: row.creator_id, createdAt: row.created_at, status: row.status, frame: row.frame, likes: JSON.parse(row.likes)});
|
||||
}
|
||||
};
|
||||
|
||||
const needsReview = () => accounts.setting(REVIEW_SETTING) !== "0";
|
||||
const setNeedsReview = on => accounts.setSetting(REVIEW_SETTING, on ? "1" : "0");
|
||||
|
||||
const forget = id => {
|
||||
known.delete(id);
|
||||
db().prepare("DELETE FROM masterpieces WHERE id = ?").run(id);
|
||||
fs.rmSync(fileOf(id), {force: true});
|
||||
};
|
||||
|
||||
// paintings posted and never framed are thrown away after a while.
|
||||
const sweep = () => {
|
||||
for (const [token, entry] of tokens) {
|
||||
if (entry.expires < Date.now()) {
|
||||
tokens.delete(token);
|
||||
}
|
||||
}
|
||||
for (const painting of [...known.values()]) {
|
||||
if (painting.status === UPLOADED && painting.createdAt < now() - UNCLAIMED_MINUTES * 60) {
|
||||
forget(painting.id);
|
||||
}
|
||||
}
|
||||
};
|
||||
setInterval(() => {
|
||||
try {
|
||||
sweep();
|
||||
}
|
||||
catch (err) {
|
||||
console.error(`[masterpieces] sweep failed: ${err.message}`);
|
||||
}
|
||||
}, 600000).unref();
|
||||
|
||||
// A token for one upload by this account (step 1).
|
||||
const issueToken = account => {
|
||||
for (const [token, entry] of tokens) {
|
||||
if (entry.account === account.id) {
|
||||
tokens.delete(token);
|
||||
}
|
||||
}
|
||||
const token = crypto.randomBytes(16).toString("hex");
|
||||
tokens.set(token, {account: account.id, expires: Date.now() + TOKEN_MINUTES * 60000});
|
||||
return token;
|
||||
};
|
||||
|
||||
// is this a JPEG picture, whole and of a sane size? every viewer's game
|
||||
// decodes it, so it is read through here first: the start mark, then one
|
||||
// well-formed segment after another up to the picture data, among them a
|
||||
// frame header saying how big it is, and the end mark last.
|
||||
const looksLikeJpeg = image => {
|
||||
if (image.length < 100 || image[0] !== 0xFF || image[1] !== 0xD8 || image[image.length - 2] !== 0xFF || image[image.length - 1] !== 0xD9) {
|
||||
return false;
|
||||
}
|
||||
let at = 2;
|
||||
let sized = false;
|
||||
while (at + 4 <= image.length) {
|
||||
if (image[at] !== 0xFF) {
|
||||
return false;
|
||||
}
|
||||
const marker = image[at + 1];
|
||||
if (marker === 0xFF) {
|
||||
at++; // padding between segments
|
||||
continue;
|
||||
}
|
||||
const length = image.readUInt16BE(at + 2);
|
||||
if (length < 2 || at + 2 + length > image.length) {
|
||||
return false;
|
||||
}
|
||||
// start of frame: baseline, extended or progressive. [precision, height, width, ...]
|
||||
if (marker >= 0xC0 && marker <= 0xC2) {
|
||||
const height = image.readUInt16BE(at + 5);
|
||||
const width = image.readUInt16BE(at + 7);
|
||||
if (length < 8 || height < 1 || width < 1 || height > MAX_SIDE || width > MAX_SIDE) {
|
||||
return false;
|
||||
}
|
||||
sized = true;
|
||||
}
|
||||
// start of scan: the picture data follows, to the end mark.
|
||||
if (marker === 0xDA) {
|
||||
return sized;
|
||||
}
|
||||
at += 2 + length;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
// step 2. returns 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 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;
|
||||
}
|
||||
// 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) {
|
||||
forget(painting.id);
|
||||
}
|
||||
}
|
||||
const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, likes: []};
|
||||
fs.writeFileSync(fileOf(painting.id), image);
|
||||
db().prepare("INSERT INTO masterpieces (id, creator_id, created_at, status, frame, likes, image) VALUES (?, ?, ?, ?, ?, '[]', ?)")
|
||||
.run(painting.id, painting.creator, painting.createdAt, painting.status, painting.frame, NO_IMAGE);
|
||||
known.set(painting.id, painting);
|
||||
return painting.id;
|
||||
};
|
||||
|
||||
const setStatus = (painting, status) => {
|
||||
painting.status = status;
|
||||
db().prepare("UPDATE masterpieces SET status = ?, frame = ?, reviewed_at = ? WHERE id = ?")
|
||||
.run(status, painting.frame, status === APPROVED ? now() : null, painting.id);
|
||||
};
|
||||
|
||||
// may this account make an item of that painting, in that frame? (Step 3,
|
||||
// before anything is paid.)
|
||||
const claimable = (account, id, frame) => {
|
||||
const painting = known.get(String(id));
|
||||
const mine = [...known.values()].filter(other => other.creator === account.id);
|
||||
const waiting = mine.filter(other => other.status === PENDING).length;
|
||||
const shown = mine.filter(other => other.status === APPROVED).length;
|
||||
return Boolean(painting) && painting.creator === account.id && painting.status === UPLOADED
|
||||
&& Number.isInteger(frame) && frame >= 0 && frame < FRAMES.length && waiting < MAX_WAITING_PER_ACCOUNT && shown < MAX_APPROVED_PER_ACCOUNT;
|
||||
};
|
||||
|
||||
// step 3, paid for: the painting is an item now. true when it is approved
|
||||
// on the spot.
|
||||
const claim = (id, frame) => {
|
||||
const painting = known.get(String(id));
|
||||
painting.frame = frame;
|
||||
setStatus(painting, needsReview() ? PENDING : APPROVED);
|
||||
return painting.status === APPROVED;
|
||||
};
|
||||
|
||||
const get = id => known.get(String(id)) || null;
|
||||
|
||||
// the picture itself, or null. (Ids are the ones made here, so the file's
|
||||
// name is never a visitor's to choose.)
|
||||
const image = id => {
|
||||
if (!known.has(String(id))) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return fs.readFileSync(fileOf(String(id)));
|
||||
}
|
||||
catch (err) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// may the picture be handed to whoever asks at this address (as limits
|
||||
// count addresses)? once approved, to anyone: every game that draws it asks
|
||||
// for it. before that only to its maker, known by the address their game is
|
||||
// connected from: a picture nobody has looked at is not something this
|
||||
// server puts on show for the world at a link. `addressOf` gives the
|
||||
// address an account is playing from, or null.
|
||||
const mayView = (id, address, addressOf) => {
|
||||
const painting = known.get(String(id));
|
||||
if (!painting) {
|
||||
return false;
|
||||
}
|
||||
const maker = accounts.byId(painting.creator);
|
||||
return painting.status === APPROVED || Boolean(maker && addressOf(maker) && addressOf(maker) === address);
|
||||
};
|
||||
|
||||
const approve = id => {
|
||||
const painting = get(id);
|
||||
if (!painting || painting.status !== PENDING) {
|
||||
return false;
|
||||
}
|
||||
setStatus(painting, APPROVED);
|
||||
return true;
|
||||
};
|
||||
|
||||
// is a den item fit to be shown, traded and recycled? anything that is not
|
||||
// a painting is.
|
||||
const itemApproved = item => !item.image || (known.has(item.image) && known.get(item.image).status === APPROVED);
|
||||
|
||||
const creatorOf = id => {
|
||||
const painting = get(id);
|
||||
return painting ? accounts.byId(painting.creator) : null;
|
||||
};
|
||||
|
||||
// the three fields that follow a den item wherever the client is told of
|
||||
// one: the painting's id, and its maker's database id and uuid.
|
||||
const itemFields = item => {
|
||||
const maker = item.image ? creatorOf(item.image) : null;
|
||||
return [item.image || "", maker ? maker.id : -1, maker ? maker.uuid : ""];
|
||||
};
|
||||
|
||||
// the like button of the preview window: one like an account.
|
||||
const like = (id, account) => {
|
||||
const painting = get(id);
|
||||
if (!painting || painting.status !== APPROVED || painting.creator === account.id || painting.likes.includes(account.id)) {
|
||||
return false;
|
||||
}
|
||||
painting.likes.push(account.id);
|
||||
db().prepare("UPDATE masterpieces SET likes = ? WHERE id = ?").run(JSON.stringify(painting.likes), painting.id);
|
||||
return true;
|
||||
};
|
||||
|
||||
// what hangs in the Masterpiece Gallery party and on Jammer Central's
|
||||
// board: approved paintings, the most liked first and the newest among
|
||||
// equals ({pool, pluspool} of MasterpieceDisplayItem.initFromPool objects).
|
||||
const gallery = () => {
|
||||
const hung = [...known.values()].filter(painting => painting.status === APPROVED && creatorOf(painting.id))
|
||||
.sort((one, other) => other.likes.length - one.likes.length || other.createdAt - one.createdAt)
|
||||
.slice(0, GALLERY_SPOTS * 2)
|
||||
.map(painting => {
|
||||
const maker = creatorOf(painting.id);
|
||||
return {frameId: painting.frame, resourceId: painting.id, userName: maker.username, creatorDBId: maker.id, creatorId: maker.uuid};
|
||||
});
|
||||
return {pool: hung.slice(0, GALLERY_SPOTS), pluspool: hung.slice(GALLERY_SPOTS)};
|
||||
};
|
||||
|
||||
const list = status => [...known.values()].filter(painting => painting.status === status)
|
||||
.sort((one, other) => other.createdAt - one.createdAt)
|
||||
.map(painting => {
|
||||
const maker = creatorOf(painting.id);
|
||||
return {id: painting.id, creator: maker ? maker.username : "(deleted account)", createdAt: painting.createdAt, frame: painting.frame, likes: painting.likes.length};
|
||||
});
|
||||
|
||||
const madeBy = account => [...known.values()].filter(painting => painting.creator === account.id).map(painting => painting.id);
|
||||
|
||||
// generic lists: (mediaId, name string id) pairs, or null when `listId` is
|
||||
// not one of the frame lists (GenericListXtCommManager.handleMediaResponse).
|
||||
const frameList = listId =>
|
||||
([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null);
|
||||
|
||||
module.exports = {
|
||||
load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, frameList,
|
||||
needsReview, setNeedsReview, madeBy,
|
||||
PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES,
|
||||
};
|
||||
@@ -0,0 +1,622 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const achievements = require("./achievements.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const buddyGames = require("./buddygames.js");
|
||||
const masterpieces = require("./masterpieces.js");
|
||||
const dens = require("./dens.js");
|
||||
const limits = require("./limits.js");
|
||||
const {activeAvatar, addClothing, sendClothingAdded} = require("./player.js");
|
||||
|
||||
// minigames (client side: MinigameManager, MinigameXtCommManager and the
|
||||
// game.* classes). the games themselves are compiled into the client; what
|
||||
// the official server kept was the table saying which game def id is which
|
||||
// game (the "game" defPack is gone from the CDN) and the session around a
|
||||
// game: the room it runs in, the start signal, gem awards, and for some
|
||||
// games a few messages of their own.
|
||||
//
|
||||
// lib/games.json is that table, put back together from what still names the
|
||||
// ids: arcade-machine den items (gameDefId and a name), the room files (which
|
||||
// id stands where), the names GameCardPopup has for each game class, and the
|
||||
// achievement defs (which user vars a game counts in). entries:
|
||||
// id game def id
|
||||
// swf the game's key in game.IncludeMinigames
|
||||
// title its name; sent as the id of the localization string that says so
|
||||
// type 0 runs in a window over the room ("in-room"), 1 replaces the room
|
||||
// vars user vars: games played, and two the game uses as it likes
|
||||
// pet pet species the player must have out (the pet games)
|
||||
// start what the game waits for after it says "ready": see START
|
||||
// ready false: needs more from the server than is here yet; not playable
|
||||
// tickets a carnival game: how many points of its score make one ticket
|
||||
// icon media id of its picture in the HUD's Games window; the games with
|
||||
// one are the ones that window lists
|
||||
// buddy true: one of the eight games two players play from a player's
|
||||
// card (lib/buddygames.js). their ids are ours: nothing in the
|
||||
// client names them, and the official table is gone.
|
||||
// card a buddy game's picture, on the card's game tab and in the
|
||||
// invitation
|
||||
//
|
||||
// every other game is played alone (minPlayers = maxPlayers = 1): the
|
||||
// multiplayer ones each have a protocol of their own between the players.
|
||||
|
||||
const games = new Map(require("./games.json").map(game => [game.id, game]));
|
||||
|
||||
const IN_ROOM = 0;
|
||||
const MAX_GEMS_PER_AWARD = 5000;
|
||||
const MAX_MASTERY_PER_AWARD = 100;
|
||||
const MASTERY_FULL = 100;
|
||||
const CURRENCY_GEMS = 0;
|
||||
const CLAW_COST = 5; // gems a go
|
||||
const CLAW_WIN_CHANCE = 0.4;
|
||||
const SKY_HIGH_PRIZE_CHANCE = 0.5;
|
||||
const SAFETY_QUIZ_PRIZE = 1179; // den item, SafetyQuiz.init
|
||||
const TOUCH_POOL_PRIZES = [867, 869, 872, 868, 870, 871]; // den items, TouchPool.init
|
||||
const LANG_ENG = 0;
|
||||
const FALLBACK_TITLE = "Games";
|
||||
const MAX_INFO_REQUEST = 100;
|
||||
// A game id the table does not have: it still gets its sign, and says
|
||||
// "not ready" when clicked.
|
||||
const UNKNOWN_GAME = {swf: "", title: FALLBACK_TITLE, type: 0, ready: false};
|
||||
const INVASION_WIN = 11; // MicroGameInvasion.keptItem
|
||||
const CARNIVAL_COST = 5; // gems a go
|
||||
const MAX_TICKETS_PER_GO = 300;
|
||||
const CURRENCY_TICKETS = 1;
|
||||
const INVASION_COST = 10; // gems a go, as the machine's own screen says
|
||||
|
||||
const awardsPerMinute = limits.limiter(120, 60000);
|
||||
const invitesPerMinute = limits.limiter(20, 60000);
|
||||
const LEFT_NOTICE_DELAY_MS = 2500;
|
||||
const GAME_PAINTING = 51;
|
||||
const GAME_PIXEL_PAINTING = 139;
|
||||
// marbles sends the shooter's aim four times a second; nothing needs more.
|
||||
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],
|
||||
};
|
||||
|
||||
// serial numbers the client mixes into its award messages; any number will do.
|
||||
function serial() {
|
||||
return 1 + Math.floor(Math.random() * 1000000);
|
||||
}
|
||||
|
||||
let nextGameRoomId = 500000; // well clear of the world's room ids
|
||||
|
||||
module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
||||
// MinigameInfo.init, the 19 fields the "mi" reply carries for a game.
|
||||
const info = game => [
|
||||
game.id,
|
||||
// never 0: the client throws on a string it cannot find.
|
||||
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
|
||||
0, // max spectators
|
||||
game.type,
|
||||
// the game card: the title picture on the "play" popup (not known), and
|
||||
// for a buddy game the picture in the invitation.
|
||||
game.card || 0,
|
||||
...(game.vars || [0, 0, 0]),
|
||||
game.buddy ? 1 : 0, // ready for player-versus-player: listed on players' cards
|
||||
1, // gem multiplier
|
||||
game.pet || 0,
|
||||
0, // pro mode user var
|
||||
0, // leaderboard user var
|
||||
game.icon || game.card || 0, // its picture in the Games window or on a card's game tab
|
||||
0, // required avatar type
|
||||
];
|
||||
|
||||
// an invitation to a buddy game that has not been answered: both players
|
||||
// have {def, sender, target} as `invite`. dropping it tells the other
|
||||
// side "no" (MinigameManager.pvpResponse: [gameDefId, 1]).
|
||||
const dropInvite = (session, tellOther = true) => {
|
||||
const {invite} = session;
|
||||
if (!invite) {
|
||||
return;
|
||||
}
|
||||
invite.sender.invite = invite.target.invite = null;
|
||||
const other = invite.sender === session ? invite.target : invite.sender;
|
||||
if (tellOther) {
|
||||
other.sendXt("mp", -1, invite.def.id, 1);
|
||||
}
|
||||
};
|
||||
|
||||
// takes the player out of the game they are in, if any, and out of an
|
||||
// invitation.
|
||||
const leave = session => {
|
||||
dropInvite(session);
|
||||
const {game} = session;
|
||||
if (!game) {
|
||||
return;
|
||||
}
|
||||
session.game = null;
|
||||
game.players = game.players.filter(player => player !== session);
|
||||
// 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
|
||||
// (lib/buddygames.js), and at their end both players leave within a
|
||||
// moment of each other: there the news waits a little, and reaches
|
||||
// only a player who is still in the game by then.
|
||||
const tellOthers = () => {
|
||||
for (const other of game.players.filter(player => player.game === game)) {
|
||||
other.sendXt("ml", game.roomId, session.id);
|
||||
}
|
||||
};
|
||||
if (!game.match) {
|
||||
tellOthers();
|
||||
}
|
||||
else if (!game.match.finished) {
|
||||
setTimeout(() => {
|
||||
try {
|
||||
tellOthers();
|
||||
}
|
||||
catch (err) {
|
||||
console.error(`[minigames] could not tell of a player leaving: ${err.message}`);
|
||||
}
|
||||
}, LEFT_NOTICE_DELAY_MS).unref();
|
||||
}
|
||||
};
|
||||
|
||||
// MinigameManager.startGame: [playerCount, sfsUserId..., then for each
|
||||
// player an id and their username, then whatever the game adds], which
|
||||
// the game reads as "ms". the id is the animal's (perUserAvId): the games
|
||||
// that draw their players ask for that animal by it.
|
||||
const start = game => {
|
||||
game.started = true;
|
||||
for (const player of game.players) {
|
||||
player.sendXt("ms", game.roomId, game.players.length, ...game.players.map(other => other.id),
|
||||
...game.players.flatMap(other => [activeAvatar(other.account).perUserAvId, other.account.username]),
|
||||
...(game.startData || []));
|
||||
}
|
||||
};
|
||||
|
||||
// RoomXtCommManager.roomJoinResponse for a game's own room: a temporary
|
||||
// game room, which for a game that runs in a window is a "sub room"
|
||||
// beside the room the player stays in. then the serial numbers the game's
|
||||
// first awards are to be signed with (MinigameManager.minigameGems,
|
||||
// minigamePetMastery) and who is in the game (joinGameResponse).
|
||||
const seat = (session, game, music) => {
|
||||
const avatar = activeAvatar(session.account);
|
||||
session.game = game;
|
||||
session.sendXt("rj", -1, 1, `game${game.def.id}_${game.roomId}`, game.roomId, game.players.length, game.players.length, 0, 0,
|
||||
0, 1, 0, 1, game.def.type === IN_ROOM ? 1 : 0, // isPrivate, isGame, isLimbo, isTemp, isSubRoom
|
||||
"", 0, avatar.perUserAvId, avatar.petInvId, LANG_ENG, music, 1);
|
||||
session.gemSerial = serial();
|
||||
session.masterySerial = serial();
|
||||
session.sendXt("mg", game.roomId, session.gemSerial, 1);
|
||||
session.sendXt("ma", game.roomId, session.masterySerial, 0);
|
||||
session.sendXt("mj", game.roomId, ...game.players.map(player => player.id));
|
||||
};
|
||||
|
||||
// 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) => {
|
||||
const referee = buddyGames[def.swf];
|
||||
const game = {roomId: nextGameRoomId++, def, players: [sender, target], started: false, ready: new Set(),
|
||||
startData: referee.startData ? referee.startData() : []};
|
||||
const seats = [sender, target];
|
||||
game.match = {
|
||||
ids: seats.map(session => session.id),
|
||||
state: null,
|
||||
finished: false,
|
||||
ready: new Set(),
|
||||
send: (player, ...fields) => seats[player].sendXt("mm", game.roomId, ...fields),
|
||||
broadcast: (...fields) => seats.forEach(session => session.sendXt("mm", game.roomId, ...fields)),
|
||||
over() {
|
||||
game.match.finished = true;
|
||||
},
|
||||
seatOf: session => seats.indexOf(session),
|
||||
};
|
||||
for (const session of seats) {
|
||||
seat(session, game, session.room ? session.room.customMusicDef : 0);
|
||||
}
|
||||
start(game);
|
||||
};
|
||||
|
||||
const matchMessage = (session, game, word, params) => {
|
||||
const {match} = game;
|
||||
const referee = buddyGames[game.def.swf];
|
||||
const player = match.seatOf(session);
|
||||
// nothing more is refereed once the game is decided or a player has gone.
|
||||
if (player === -1 || match.finished || game.players.length < 2 || !messagesPerMinute.allow(session.account.id)) {
|
||||
return;
|
||||
}
|
||||
if (word === "ready") {
|
||||
// both say so before the first round, and again before each further one.
|
||||
if (match.ready.add(player).size === 2) {
|
||||
match.ready.clear();
|
||||
referee.ready(match);
|
||||
}
|
||||
}
|
||||
else if (Object.hasOwn(referee.messages, word)) {
|
||||
referee.messages[word](match, player, params);
|
||||
}
|
||||
};
|
||||
|
||||
// den items a claw machine can drop: the plushies, of the machine's own
|
||||
// animal when it is named for one ("The Wolf Claw").
|
||||
let plushies = null;
|
||||
const clawPrizes = game => {
|
||||
plushies = plushies || defpacks.denItemIds().filter(id => /plush/i.test(defpacks.denItemDef(id).abbrName));
|
||||
const item = defpacks.denItemIds().map(id => defpacks.denItemDef(id)).find(def => Number(def.gameDefId) === game.id);
|
||||
const animal = item ? /^ArcCraneGame(.+)$/.exec(item.abbrName) : null;
|
||||
const own = animal ? plushies.filter(id => defpacks.denItemDef(id).abbrName.toLowerCase().includes(animal[1].toLowerCase())) : [];
|
||||
return own.length ? own : plushies;
|
||||
};
|
||||
|
||||
// what Phantom Invasion gives: den items named for phantoms, the arcade
|
||||
// machines aside.
|
||||
let phantomItems = null;
|
||||
const invasionPrizes = () => {
|
||||
phantomItems = phantomItems || defpacks.denItemIds().filter(id => /phantom/i.test(defpacks.denItemDef(id).abbrName)
|
||||
&& !/^Arc/.test(defpacks.denItemDef(id).abbrName) && defpacks.string(defpacks.denItemDef(id).nameStrId));
|
||||
return phantomItems.length ? phantomItems : defpacks.denItemIds().slice(0, 1);
|
||||
};
|
||||
|
||||
// the Summer Carnival's games (Skeeball and the rest share one protocol):
|
||||
// the server opens with "pz" and a serial number, "pg" pays for a go and
|
||||
// brings a second one, and "gr" reports the score, signed with both, and
|
||||
// is answered with the tickets it earned. how many points make a ticket
|
||||
// was the official server's to know; games.json has a guess per game.
|
||||
const hideSerial = sn => (sn + 5) * 3 - 7; // undone by the games as (x + 7) / 3 - 5
|
||||
const carnival = {
|
||||
pg(session, game, params, reply) {
|
||||
const {account} = session;
|
||||
if ((account.currency.gems || 0) < CARNIVAL_COST) {
|
||||
reply("pg", "0");
|
||||
return;
|
||||
}
|
||||
account.currency.gems -= CARNIVAL_COST;
|
||||
achievements.currencyChanged(account, "gems", -CARNIVAL_COST);
|
||||
accounts.save();
|
||||
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
|
||||
game.serial2 = serial();
|
||||
reply("pg", "1", hideSerial(game.serial2));
|
||||
},
|
||||
gr(session, game, [a, b, c], reply) {
|
||||
const {account} = session;
|
||||
const score = (Number(a) - (game.serial1 + 49) * 5) / 7 - 29;
|
||||
const valid = game.serial2 !== undefined && Number.isInteger(score) && score >= 0
|
||||
&& Number(b) === (score + 49) * 3 + (game.serial2 + 83) * 5
|
||||
&& Number(c) === (game.serial1 + score) * 3 + score * 3
|
||||
&& awardsPerMinute.allow(account.id);
|
||||
game.serial2 = undefined; // one score a go
|
||||
const tickets = valid ? Math.min(MAX_TICKETS_PER_GO, Math.ceil(score / game.def.tickets)) : 0;
|
||||
if (tickets > 0) {
|
||||
account.currency.tickets = (account.currency.tickets || 0) + tickets;
|
||||
achievements.currencyChanged(account, "tickets", tickets);
|
||||
accounts.save();
|
||||
session.sendXt("cu", -1, CURRENCY_TICKETS, account.currency.tickets, 0);
|
||||
}
|
||||
reply("gr", tickets);
|
||||
},
|
||||
};
|
||||
|
||||
const uploadToken = (session, game, [, purpose], reply) => {
|
||||
reply("tkn", 1, 0, masterpieces.issueToken(session.account), 0, purpose === undefined ? 1 : Number(purpose) || 1);
|
||||
};
|
||||
|
||||
// what a game asks of the server while it runs, by game class and then by
|
||||
// the message's first word. `reply` answers the asker as an "mm".
|
||||
const MESSAGES = {
|
||||
// the claw machines: "cp" pays for a go and learns whether the claw
|
||||
// will hold and what on ([won, isDenItem, defId, ?, version]; anything
|
||||
// but 1 or 0 for `won` means "not enough gems"); "cd" keeps (1) or
|
||||
// leaves (0) what came out.
|
||||
MicroCrane: {
|
||||
cp(session, game, params, reply) {
|
||||
const {account} = session;
|
||||
if ((account.currency.gems || 0) < CLAW_COST) {
|
||||
reply("cp", "2");
|
||||
return;
|
||||
}
|
||||
account.currency.gems -= CLAW_COST;
|
||||
achievements.currencyChanged(account, "gems", -CLAW_COST);
|
||||
accounts.save();
|
||||
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
|
||||
const prizes = clawPrizes(game.def);
|
||||
const won = prizes.length > 0 && Math.random() < CLAW_WIN_CHANCE;
|
||||
session.clawPrize = won ? prizes[Math.floor(Math.random() * prizes.length)] : null;
|
||||
reply("cp", won ? "1" : "0", "1", session.clawPrize || 0, 0, 0);
|
||||
},
|
||||
cd(session, game, [keep]) {
|
||||
if (keep === "1" && session.clawPrize) {
|
||||
dens.giveDenItem(session.account, session.clawPrize);
|
||||
dens.sendDenItems(session);
|
||||
}
|
||||
session.clawPrize = null;
|
||||
},
|
||||
},
|
||||
// sky High: "gw" on reaching the top -> [won, clothingDefId, ?, colour];
|
||||
// "gd" keeps (1) or leaves (0) the prize.
|
||||
WindRider: {
|
||||
go() {},
|
||||
gw(session, game, params, reply) {
|
||||
const ids = defpacks.clothingIds();
|
||||
const def = Math.random() < SKY_HIGH_PRIZE_CHANCE ? defpacks.itemDef(ids[Math.floor(Math.random() * ids.length)]) : null;
|
||||
session.gamePrize = def ? {def: Number(def.id), color: Number(String(def.colors).split(",")[0])} : null;
|
||||
reply("gw", def ? "1" : "0", def ? def.id : 0, 0, def ? session.gamePrize.color : 0);
|
||||
},
|
||||
gd(session, game, [keep]) {
|
||||
if (keep === "1" && session.gamePrize) {
|
||||
sendClothingAdded(session, addClothing(session.account, session.gamePrize.def, session.gamePrize.color));
|
||||
accounts.save();
|
||||
}
|
||||
session.gamePrize = null;
|
||||
},
|
||||
},
|
||||
// the safety quiz: "hs" asks for a serial number, and "hp", signed with
|
||||
// it, claims the quiz's one prize.
|
||||
SafetyQuiz: {
|
||||
hs(session, game, params, reply) {
|
||||
session.prizeSerial = serial();
|
||||
reply("hs", session.prizeSerial);
|
||||
},
|
||||
hp(session, game, [, check]) {
|
||||
if (session.prizeSerial !== undefined && Number(check) === (session.prizeSerial + session.id) * 3) {
|
||||
dens.giveDenItem(session.account, SAFETY_QUIZ_PRIZE);
|
||||
dens.sendDenItems(session);
|
||||
}
|
||||
session.prizeSerial = undefined;
|
||||
},
|
||||
},
|
||||
// brady Barr's expeditions ask for the same serial; their prizes hang on
|
||||
// the theatre's films and are not given.
|
||||
BradyExpeditions: {
|
||||
hs(session, game, params, reply) {
|
||||
reply("hs", serial());
|
||||
},
|
||||
hp() {},
|
||||
},
|
||||
// the touch pool: the same again, with six prizes; which one is in the
|
||||
// first number.
|
||||
TouchPool: {
|
||||
ts(session, game, params, reply) {
|
||||
session.prizeSerial = serial();
|
||||
reply("ts", session.prizeSerial);
|
||||
},
|
||||
tp(session, game, [signed, check]) {
|
||||
const sn = session.prizeSerial;
|
||||
const prize = sn === undefined ? -1 : (Number(signed) - (session.id + 99) * 3 - (sn + 49) * 5) / 5;
|
||||
if (TOUCH_POOL_PRIZES[prize] !== undefined && Number(check) === (sn + session.id + prize) * 3 + prize * 3) {
|
||||
dens.giveDenItem(session.account, TOUCH_POOL_PRIZES[prize]);
|
||||
dens.sendDenItems(session);
|
||||
}
|
||||
session.prizeSerial = undefined; // one prize a serial number
|
||||
},
|
||||
},
|
||||
// phantom Invasion: "cp" pays for a go and names the prize a win will
|
||||
// bring, [ok, serial, isDenItem, defId, ?, version]; the game itself
|
||||
// decides whether it was won. "cd", signed with the serial, keeps it;
|
||||
// "cd 2" leaves it and "cd 0" is a lost round.
|
||||
MicroGameInvasion: {
|
||||
cp(session, game, params, reply) {
|
||||
const {account} = session;
|
||||
if ((account.currency.gems || 0) < INVASION_COST) {
|
||||
reply("cp", "2");
|
||||
return;
|
||||
}
|
||||
account.currency.gems -= INVASION_COST;
|
||||
achievements.currencyChanged(account, "gems", -INVASION_COST);
|
||||
accounts.save();
|
||||
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
|
||||
const prizes = invasionPrizes();
|
||||
session.prizeSerial = serial();
|
||||
session.gamePrize = prizes[Math.floor(Math.random() * prizes.length)];
|
||||
reply("cp", "1", session.prizeSerial, "1", session.gamePrize, 0, 0);
|
||||
},
|
||||
cd(session, game, [signed, check]) {
|
||||
const sn = session.prizeSerial;
|
||||
const won = sn !== undefined && session.gamePrize
|
||||
&& Number(signed) === INVASION_WIN * 5 + (session.id + 99) * 3 + (sn + 49) * 5
|
||||
&& Number(check) === (sn + session.id + INVASION_WIN) * 3 + INVASION_WIN * 3;
|
||||
if (won) {
|
||||
dens.giveDenItem(session.account, session.gamePrize);
|
||||
dens.sendDenItems(session);
|
||||
}
|
||||
session.prizeSerial = undefined;
|
||||
session.gamePrize = null;
|
||||
},
|
||||
},
|
||||
// the Art Studio's two easels: "gmtkn" asks for a token to post a
|
||||
// painting with (lib/masterpieces.js). the game reads [word, ok, ?,
|
||||
// token, ?, what the token is for], the last as it was sent.
|
||||
ArtStudioPainting: {gmtkn: uploadToken},
|
||||
ArtStudioGridDrawing: {gmtkn: uploadToken},
|
||||
// the Phantom Vortex's prize machine: anything but "0" is "no prize".
|
||||
MicroPhantom: {
|
||||
pi(session, game, params, reply) {
|
||||
reply("cp", "1");
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const handlers = {
|
||||
// MinigameXtCommManager.handleMinigameInfo: [count, 19 fields a game...].
|
||||
// RoomManagerWorld asks for every game standing in a room at once and
|
||||
// draws none of their signs unless it hears about all of them.
|
||||
mi(session, roomId, ids) {
|
||||
const asked = ids.slice(0, MAX_INFO_REQUEST).map(Number).filter(id => Number.isInteger(id) && id > 0);
|
||||
// the easel's "play" popup offers both painting games and reads the
|
||||
// second one's description without having asked for it
|
||||
// (GameCardPopup, for game 51): it goes along.
|
||||
if (asked.includes(GAME_PAINTING) && !asked.includes(GAME_PIXEL_PAINTING)) {
|
||||
asked.push(GAME_PIXEL_PAINTING);
|
||||
}
|
||||
const known = asked.map(id => games.get(id) || {...UNKNOWN_GAME, id});
|
||||
session.sendXt("mi", -1, known.length, ...known.flatMap(info));
|
||||
},
|
||||
|
||||
// MinigameManager.launchGame: [gameDefId, multiplayer, proModeId, ?].
|
||||
mj(session, roomId, [gameDefId]) {
|
||||
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) {
|
||||
// "as": the one refusal that puts the client back as it was. it
|
||||
// comes with a popup about switching animals, hence one of our own.
|
||||
session.sendXt("mj", -1, "as", 0);
|
||||
tell(session, "That game is not ready on this server yet.");
|
||||
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) {
|
||||
// the game takes the room's place: the player is gone from the
|
||||
// world until they come back with an ordinary room join.
|
||||
game.returnTo = session.room.name;
|
||||
leaveRoom(session);
|
||||
}
|
||||
seat(session, game, music);
|
||||
start(game);
|
||||
if (def.tickets) {
|
||||
game.serial1 = serial();
|
||||
session.sendXt("mm", game.roomId, "pz", hideSerial(game.serial1));
|
||||
}
|
||||
},
|
||||
|
||||
// "Start now", from a waiting list; nobody waits here.
|
||||
ms() {},
|
||||
|
||||
// MinigameManager.msg: [gameDefId, word, ...]. the game's own protocol.
|
||||
mm(session, roomId, [gameDefId, word, ...params]) {
|
||||
const {game} = session;
|
||||
if (!game || game.def.id !== Number(gameDefId)) {
|
||||
return;
|
||||
}
|
||||
if (game.match) {
|
||||
matchMessage(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)) {
|
||||
own[word](session, game, params, reply);
|
||||
}
|
||||
else if (word === "ready" && game.def.start && Object.hasOwn(START, game.def.start)) {
|
||||
game.ready.add(session);
|
||||
if (game.ready.size === game.players.length) {
|
||||
for (const player of game.players) {
|
||||
player.sendXt("mm", game.roomId, "start", ...START[game.def.start](game));
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// leaving an in-room game: [subRoomId]. (A game that took the room's
|
||||
// place is left by joining a room again.)
|
||||
rl(session) {
|
||||
leave(session);
|
||||
},
|
||||
ml(session) {
|
||||
leave(session);
|
||||
},
|
||||
|
||||
// MinigameManager.sendGemAward: three numbers made of the amount, the
|
||||
// game, the player's sfs id and the serial number last handed out (the
|
||||
// second, which names the game, is not checked: not every game says
|
||||
// which it is). the reply is the next serial number.
|
||||
mg(session, roomId, [a, , c]) {
|
||||
const {account, game} = session;
|
||||
const sn = session.gemSerial;
|
||||
const amount = (Number(a) - (session.id + 99) * 3 - (sn + 49) * 5) / 7 - 29;
|
||||
const valid = game && sn !== undefined && Number.isInteger(amount) && amount > 0 && amount <= MAX_GEMS_PER_AWARD
|
||||
&& Number(c) === (sn + session.id + amount) * 3 + amount * 3
|
||||
&& awardsPerMinute.allow(account.id);
|
||||
if (valid) {
|
||||
account.currency.gems = (account.currency.gems || 0) + amount;
|
||||
achievements.currencyChanged(account, "gems", amount);
|
||||
accounts.save();
|
||||
}
|
||||
session.gemSerial = serial();
|
||||
session.sendXt("mg", -1, session.gemSerial, 0);
|
||||
},
|
||||
|
||||
// MinigameManager.sendMasteryPoints, the same for the pet's mastery. the
|
||||
// second field of the reply says its mastery is now full.
|
||||
ma(session, roomId, [a, b, c]) {
|
||||
const {account, game} = session;
|
||||
const sn = session.masterySerial;
|
||||
const amount = (Number(a) - (session.id + 99) * 3 - (sn + 49) * 5) / 7 - 29;
|
||||
const pet = account.pets.find(candidate => candidate.inv === activeAvatar(account).petInvId);
|
||||
const valid = game && pet && sn !== undefined && Number.isInteger(amount) && amount > 0 && amount <= MAX_MASTERY_PER_AWARD
|
||||
&& Number(c) === (sn + session.id + amount) * 3 + amount * 3 && Number(b) === (game.def.id + 49) * 3 + (sn + 83) * 5;
|
||||
let nowFull = false;
|
||||
if (valid && (pet.mastery || 0) < MASTERY_FULL) {
|
||||
pet.mastery = Math.min(MASTERY_FULL, (pet.mastery || 0) + amount);
|
||||
nowFull = pet.mastery === MASTERY_FULL;
|
||||
accounts.save();
|
||||
}
|
||||
session.masterySerial = serial();
|
||||
session.sendXt("ma", -1, session.masterySerial, nowFull ? 1 : 0);
|
||||
},
|
||||
|
||||
// high scores for the leaderboards, which are not kept.
|
||||
msv() {},
|
||||
// MinigameManager.leaderBoardResponse: [gameDefId, count, ...]
|
||||
mlb(session, roomId, [gameDefId]) {
|
||||
session.sendXt("mlb", -1, gameDefId, 0);
|
||||
},
|
||||
// the buddy games (MinigameXtCommManager.sendMinigamePvpMsg): [gameDefId,
|
||||
// 0, username] invites that player; [gameDefId, 0] from the invited
|
||||
// player says yes, and [gameDefId, 1] from either says no or never mind.
|
||||
// MinigameManager.pvpResponse reads [gameDefId, 0, who is asking, their
|
||||
// name may be shown] and [gameDefId, 1] for "no".
|
||||
mp(session, roomId, [gameDefId, status, username]) {
|
||||
const def = games.get(Number(gameDefId));
|
||||
if (status !== "0") {
|
||||
dropInvite(session);
|
||||
return;
|
||||
}
|
||||
if (username === undefined || username === "") {
|
||||
const {invite} = session;
|
||||
if (invite && invite.target === session && invite.def === def && !invite.sender.game && !session.game) {
|
||||
dropInvite(session, false);
|
||||
startMatch(def, invite.sender, session);
|
||||
}
|
||||
else {
|
||||
dropInvite(session);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const target = findOnline(username);
|
||||
const free = other => other && other.room && !other.game && !other.invite;
|
||||
if (!def || !def.buddy || !free(session) || !free(target) || target === session
|
||||
|| blocks.either(session.account, target.account) || !invitesPerMinute.allow(session.account.id)
|
||||
|| !accounts.featureOn(session.account, "gameInvites") || !accounts.featureOn(target.account, "gameInvites")) {
|
||||
// "They said no" is all the client has for an invitation that cannot be made.
|
||||
dropInvite(session);
|
||||
session.sendXt("mp", -1, def ? def.id : Number(gameDefId) || 0, 1);
|
||||
return;
|
||||
}
|
||||
session.invite = target.invite = {def, sender: session, target};
|
||||
target.sendXt("mp", -1, def.id, 0, session.account.username, 1);
|
||||
},
|
||||
// an open challenge to whoever walks up (UserCommXtCommManager.sendCustomPVPMessage); not offered.
|
||||
mcp() {},
|
||||
};
|
||||
|
||||
// the HUD's Games window (GameJoinPopup, generic list 341): the playable
|
||||
// games that have a picture for it, by name.
|
||||
const library = [...games.values()].filter(game => game.icon && game.ready !== false)
|
||||
.sort((one, other) => one.title.localeCompare(other.title)).map(game => game.id);
|
||||
|
||||
// the buddy games' descriptions, sent unasked when a player arrives: a
|
||||
// player's card lists whichever games the client has heard are ready to
|
||||
// be played against another player (MinigameInfoCache.getAllReadyForPvpGameDefs).
|
||||
const greet = session => {
|
||||
const buddy = [...games.values()].filter(game => game.buddy && Object.hasOwn(buddyGames, game.swf));
|
||||
session.sendXt("mi", -1, buddy.length, ...buddy.flatMap(info));
|
||||
};
|
||||
|
||||
return {
|
||||
handlers,
|
||||
leave,
|
||||
greet,
|
||||
library: () => library,
|
||||
// the room a player in a room-replacing game came from, for the panel.
|
||||
playing: session => (session.game ? session.game.def.title : null),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,184 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const achievements = require("./achievements.js");
|
||||
const bans = require("./bans.js");
|
||||
const dens = require("./dens.js");
|
||||
const {CURRENCIES} = require("./player.js");
|
||||
|
||||
// moderation: kick, ban, silence, clear a den, grant gems, message a player.
|
||||
// these are done from the admin panel (lib/panel.js). no game account has
|
||||
// them: the client's own moderator requests (FacilitatorXtCommManager) are
|
||||
// always refused.
|
||||
|
||||
const PERMANENT = -1;
|
||||
const SECONDS_PER_MINUTE = 60;
|
||||
const CURRENCY_GEMS = 0;
|
||||
// ItemXtCommManager.currencyUpdateResponse: with this as the reason the
|
||||
// client says "You earned N ..." in a popup when the amount went up.
|
||||
const REASON_ANNOUNCE = 3;
|
||||
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
|
||||
// seconds of ban left, PERMANENT, or 0 when not banned.
|
||||
const banRemaining = account => {
|
||||
if (account.bannedUntil === PERMANENT) {
|
||||
return PERMANENT;
|
||||
}
|
||||
return Math.max(0, (account.bannedUntil || 0) - now());
|
||||
};
|
||||
|
||||
// the ban an account is under, for whoever may know why (the banned player,
|
||||
// and whoever runs the server): {seconds, reason, by, since}, or null.
|
||||
const banOf = account => {
|
||||
const seconds = banRemaining(account);
|
||||
return seconds === 0 ? null : {seconds, reason: account.banReason || bans.NO_REASON, by: account.bannedBy || "", since: account.bannedAt || null};
|
||||
};
|
||||
|
||||
const isSilenced = account => account.silencedUntil === PERMANENT || (account.silencedUntil || 0) > now();
|
||||
|
||||
// seconds of silence left, PERMANENT, or 0 when the account may chat.
|
||||
const silenceRemaining = account => {
|
||||
if (account.silencedUntil === PERMANENT) {
|
||||
return PERMANENT;
|
||||
}
|
||||
return Math.max(0, (account.silencedUntil || 0) - now());
|
||||
};
|
||||
|
||||
module.exports = ({findOnline}) => {
|
||||
// FacilitatorXtCommManager.facilitatorDisciplineResponse: what the affected
|
||||
// player's client is told.
|
||||
const discipline = (session, ...fields) => session.sendXt("fd", -1, ...fields);
|
||||
|
||||
// A "message from moderator" popup; also used to answer chat commands.
|
||||
const notify = (session, text) => discipline(session, "fp", text, 0);
|
||||
|
||||
const actions = {
|
||||
kick(target) {
|
||||
const session = findOnline(target.username);
|
||||
if (!session) {
|
||||
return false;
|
||||
}
|
||||
discipline(session, "fk", 0);
|
||||
session.close();
|
||||
return true;
|
||||
},
|
||||
|
||||
// duration in seconds, or PERMANENT. the reason is for the banned
|
||||
// player and whoever runs the server, nobody else; `by` is who gave it.
|
||||
ban(target, duration, reason = "", by = "") {
|
||||
target.bannedUntil = duration === PERMANENT ? PERMANENT : now() + duration;
|
||||
target.banReason = bans.reasonText(reason);
|
||||
target.bannedBy = by;
|
||||
target.bannedAt = now();
|
||||
accounts.save();
|
||||
bans.record({account: target, action: "ban", seconds: duration, reason: target.banReason, by});
|
||||
const session = findOnline(target.username);
|
||||
if (session) {
|
||||
discipline(session, "fb", 1, duration);
|
||||
session.close();
|
||||
}
|
||||
return true;
|
||||
},
|
||||
|
||||
unban(target, by = "") {
|
||||
const was = banRemaining(target) !== 0;
|
||||
delete target.bannedUntil;
|
||||
delete target.banReason;
|
||||
delete target.bannedBy;
|
||||
delete target.bannedAt;
|
||||
accounts.save();
|
||||
if (was) {
|
||||
bans.record({account: target, action: "unban", by});
|
||||
}
|
||||
return true;
|
||||
},
|
||||
|
||||
// another reason for the ban they are under; its length stays.
|
||||
banReason(target, reason, by = "") {
|
||||
if (banRemaining(target) === 0) {
|
||||
return false;
|
||||
}
|
||||
target.banReason = bans.reasonText(reason);
|
||||
accounts.save();
|
||||
bans.record({account: target, action: "reason", reason: target.banReason, by});
|
||||
return true;
|
||||
},
|
||||
|
||||
// duration in seconds, PERMANENT, or 0 to lift
|
||||
silence(target, duration) {
|
||||
target.silencedUntil = duration === PERMANENT ? PERMANENT : (duration > 0 ? now() + duration : 0);
|
||||
accounts.save();
|
||||
const session = findOnline(target.username);
|
||||
if (session) {
|
||||
// minutes, negative for "until further notice", 0 for "you may type again"
|
||||
discipline(session, "fs", duration === PERMANENT ? PERMANENT : Math.ceil(duration / SECONDS_PER_MINUTE));
|
||||
}
|
||||
return true;
|
||||
},
|
||||
|
||||
// their username will not do: they are put out, every saved sign-in
|
||||
// ends, and the next sign-in asks for another name before it lets them
|
||||
// in (lib/http.js, lib/manage.js). the name itself stays until then.
|
||||
rejectName(target, by = "") {
|
||||
target.nameRejected = {by, at: now()};
|
||||
accounts.revokeTokens(target);
|
||||
accounts.save();
|
||||
actions.kick(target);
|
||||
return true;
|
||||
},
|
||||
|
||||
// taken back: the name will do after all.
|
||||
acceptName(target) {
|
||||
delete target.nameRejected;
|
||||
accounts.save();
|
||||
return true;
|
||||
},
|
||||
|
||||
clearDen(target) {
|
||||
dens.clearDen(target, findOnline);
|
||||
return true;
|
||||
},
|
||||
|
||||
grantGems(target, amount) {
|
||||
return actions.grantCurrency(target, CURRENCY_GEMS, amount, false);
|
||||
},
|
||||
|
||||
// adds to (or with a negative amount takes from) one of a player's
|
||||
// currencies: an index into CURRENCIES. `announce` has their game say so.
|
||||
grantCurrency(target, currencyType, amount, announce = true) {
|
||||
const name = CURRENCIES[currencyType];
|
||||
if (!name) {
|
||||
return false;
|
||||
}
|
||||
const before = target.currency[name] || 0;
|
||||
target.currency[name] = Math.max(0, before + amount);
|
||||
achievements.currencyChanged(target, name, target.currency[name] - before);
|
||||
accounts.save();
|
||||
const session = findOnline(target.username);
|
||||
if (session) {
|
||||
// ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason]
|
||||
session.sendXt("cu", -1, currencyType, target.currency[name], announce ? REASON_ANNOUNCE : 0);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
|
||||
message(target, text) {
|
||||
const session = findOnline(target.username);
|
||||
if (!session) {
|
||||
return false;
|
||||
}
|
||||
notify(session, text);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
// the client's moderator requests, refused whoever sends them. each
|
||||
// expects [0] for failure; "fc" (clear den) has no reply at all.
|
||||
const refuse = reply => session => session.sendXt(reply, -1, 0);
|
||||
const handlers = {fk: refuse("fk"), fb: refuse("fb"), fs: refuse("fs"), fm: refuse("fm"), fg: refuse("fg"), fp: refuse("fp"), fc() {}};
|
||||
|
||||
return {handlers, actions, banRemaining, banOf, isSilenced, silenceRemaining, PERMANENT};
|
||||
};
|
||||
|
||||
Object.assign(module.exports, {isSilenced, banRemaining, banOf});
|
||||
@@ -0,0 +1,31 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
|
||||
// what each moderator did in the moderator panel (lib/modpanel.js), for
|
||||
// whoever runs the server to read in the admin panel. never pruned.
|
||||
|
||||
const SCHEMA = `
|
||||
CREATE TABLE IF NOT EXISTS mod_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
at INTEGER NOT NULL,
|
||||
by TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
target TEXT NOT NULL DEFAULT '',
|
||||
detail TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
`;
|
||||
const MAX_DETAIL = 400;
|
||||
const SHOWN = 300;
|
||||
|
||||
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}"` : ""}`);
|
||||
};
|
||||
|
||||
const recent = () => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log ORDER BY id DESC LIMIT ?").all(SHOWN);
|
||||
|
||||
module.exports = {load, record, recent};
|
||||
@@ -0,0 +1,447 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const accounts = require("./accounts.js");
|
||||
const bans = require("./bans.js");
|
||||
const captcha = require("./captcha.js");
|
||||
const chatlog = require("./chatlog.js");
|
||||
const config = require("../config.js");
|
||||
const limits = require("./limits.js");
|
||||
const manage = require("./manage.js");
|
||||
const masterpieces = require("./masterpieces.js");
|
||||
const modlog = require("./modlog.js");
|
||||
const reports = require("./reports.js");
|
||||
const staff = require("./staff.js");
|
||||
const support = require("./support.js");
|
||||
const totp = require("./totp.js");
|
||||
const world = require("./world.js");
|
||||
|
||||
// the moderator panel at /mod: what a moderator needs to look after the
|
||||
// players, and no more. it is apart from the admin panel (lib/panel.js),
|
||||
// which stays whoever runs the server's alone.
|
||||
//
|
||||
// A moderator is a game account the admin marked as one (`moderator` on the
|
||||
// account). they sign in here with that account's username and password and
|
||||
// a code from their authenticator app, every time: an account without 2FA
|
||||
// cannot sign in at all, and a trusted device is not taken for a code.
|
||||
// being a moderator gives the account nothing in the game itself.
|
||||
//
|
||||
// what it does not give: addresses, sign-in histories, the server's log,
|
||||
// what an account owns, passwords, renaming, deleting, gifts. an address
|
||||
// can be banned through its player (the one they last signed in from) and
|
||||
// shows here with its end left out. another moderator cannot be acted on.
|
||||
// everything done here is written down (lib/modlog.js) under the
|
||||
// moderator's name, for the admin panel.
|
||||
|
||||
const COOKIE = "ajc_mod";
|
||||
const SESSION_HOURS = 12;
|
||||
const TEN_MINUTES_MS = 600000;
|
||||
const MAX_BAN_HOURS = 24 * 365 * 10;
|
||||
const MAX_MESSAGE_LENGTH = 200;
|
||||
const MAX_FOUND = 50;
|
||||
|
||||
const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS);
|
||||
const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator
|
||||
|
||||
const sessions = new Map(); // SHA-256 of a session token -> {id: account id, expiry: ms}
|
||||
|
||||
const sha256 = text => crypto.createHash("sha256").update(text).digest("hex");
|
||||
|
||||
const cookieToken = req => {
|
||||
const match = new RegExp(`(?:^|;\\s*)${COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "");
|
||||
return match ? match[1] : null;
|
||||
};
|
||||
|
||||
const cookieHeader = (token, maxAgeSeconds) =>
|
||||
`${COOKIE}=${token}; Path=/mod; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
|
||||
|
||||
// may this account use the panel (still)?
|
||||
const mayModerate = account => Boolean(account && account.moderator && totp.isOn(account) && !account.locked
|
||||
&& world.moderation.banRemaining(account) === 0);
|
||||
|
||||
const signedInAs = req => {
|
||||
const token = cookieToken(req);
|
||||
const session = token && sessions.get(sha256(token));
|
||||
const account = session && session.expiry > Date.now() ? accounts.byId(session.id) : null;
|
||||
return mayModerate(account) ? account : null;
|
||||
};
|
||||
|
||||
// ends the account's sessions here: it is no longer a moderator, or its
|
||||
// password or name changed.
|
||||
const forget = account => {
|
||||
for (const [hash, session] of sessions) {
|
||||
if (session.id === account.id) {
|
||||
sessions.delete(hash);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const playerRow = (account, playing) => {
|
||||
const ban = world.moderation.banOf(account);
|
||||
return {
|
||||
username: account.username,
|
||||
createdAt: account.createdAt,
|
||||
lastSeen: account.lastSeen || account.lastLogin || null,
|
||||
online: playing.has(account.username),
|
||||
room: playing.get(account.username) || null,
|
||||
banned: ban ? ban.seconds : 0,
|
||||
banReason: ban ? ban.reason : "",
|
||||
silenced: world.moderation.silenceRemaining(account),
|
||||
nameRejected: Boolean(account.nameRejected),
|
||||
moderator: Boolean(account.moderator),
|
||||
bio: account.bio,
|
||||
discord: account.discord,
|
||||
};
|
||||
};
|
||||
|
||||
const playing = () => new Map(world.players().map(player => [player.username, player.room || "(between rooms)"]));
|
||||
|
||||
const findPlayers = query => {
|
||||
const wanted = String(query || "").trim().toLowerCase().slice(0, 100);
|
||||
const online = playing();
|
||||
return accounts.all()
|
||||
.filter(account => account.username.toLowerCase().includes(wanted))
|
||||
.sort((a, b) => Number(online.has(b.username)) - Number(online.has(a.username)) || a.username.localeCompare(b.username))
|
||||
.slice(0, MAX_FOUND)
|
||||
.map(account => playerRow(account, online));
|
||||
};
|
||||
|
||||
// one player: the row, what was done about their bans (without addresses),
|
||||
// their appeal, and the reports about them still waiting.
|
||||
const playerDetail = account => ({
|
||||
...playerRow(account, playing()),
|
||||
history: bans.historyOf(account).map(({at, action, seconds, reason, by}) => ({at, action, seconds, reason, by})),
|
||||
appeal: bans.appealOf(account),
|
||||
openReports: reports.list(false).filter(report => report.target.toLowerCase() === account.username.toLowerCase()).length,
|
||||
});
|
||||
|
||||
// an address with its end left out, and a name to lift its ban by.
|
||||
const maskedAddress = ban => ({
|
||||
id: sha256(ban.key).slice(0, 16),
|
||||
address: ban.key.includes(":") ? `${ban.key.split(":").slice(0, 2).join(":")}:…` : `${ban.key.split(".").slice(0, 2).join(".")}.…`,
|
||||
reason: ban.reason,
|
||||
by: ban.by,
|
||||
createdAt: ban.createdAt,
|
||||
});
|
||||
|
||||
const wholeNumber = (value, min, max) => (Number.isInteger(value) && value >= min && value <= max ? value : null);
|
||||
|
||||
const act = (mod, target, body) => {
|
||||
const {actions, PERMANENT} = world.moderation;
|
||||
const name = target.username;
|
||||
const by = mod.username;
|
||||
if (target === mod) {
|
||||
return {error: "That is you."};
|
||||
}
|
||||
if (target.moderator) {
|
||||
return {error: "Another moderator is the admin's to deal with."};
|
||||
}
|
||||
switch (body.action) {
|
||||
case "ban": {
|
||||
const hours = wholeNumber(body.hours, 0, MAX_BAN_HOURS);
|
||||
if (hours === null) {
|
||||
return {error: "Hours as a whole number, or 0 for permanent."};
|
||||
}
|
||||
actions.ban(target, hours === 0 ? PERMANENT : hours * 3600, body.reason, by);
|
||||
manage.forget(target);
|
||||
return {ok: hours === 0 ? `${name} is banned permanently.` : `${name} is banned for ${hours} hours.`, detail: `${hours || "permanent"} · ${target.banReason}`};
|
||||
}
|
||||
case "banReason":
|
||||
return actions.banReason(target, body.reason, by) ? {ok: "Reason saved.", detail: target.banReason} : {error: `${name} is not banned.`};
|
||||
case "unban":
|
||||
if (world.moderation.banRemaining(target) === 0) {
|
||||
return {error: `${name} is not banned.`};
|
||||
}
|
||||
actions.unban(target, by);
|
||||
return {ok: `${name} is no longer banned.`};
|
||||
// counted in hours here; the game's own notice counts minutes.
|
||||
case "silence": {
|
||||
const hours = wholeNumber(body.hours, 0, MAX_BAN_HOURS);
|
||||
if (hours === null) {
|
||||
return {error: "Hours as a whole number, or 0 for until lifted."};
|
||||
}
|
||||
actions.silence(target, hours === 0 ? PERMANENT : hours * 3600);
|
||||
return {ok: hours === 0 ? `${name} cannot chat until it is lifted.` : `${name} cannot chat for ${hours} hours.`, detail: String(hours || "until lifted")};
|
||||
}
|
||||
case "unsilence":
|
||||
actions.silence(target, 0);
|
||||
return {ok: `${name} can chat again.`};
|
||||
case "kick":
|
||||
return actions.kick(target) ? {ok: `${name} was disconnected.`} : {error: `${name} is not online.`};
|
||||
case "message": {
|
||||
const text = String(body.text || "").trim().slice(0, MAX_MESSAGE_LENGTH);
|
||||
if (!text) {
|
||||
return {error: "The message is empty."};
|
||||
}
|
||||
return actions.message(target, text) ? {ok: `Shown to ${name}.`, detail: text} : {error: `${name} is not online.`};
|
||||
}
|
||||
case "rejectName":
|
||||
if (target.nameRejected) {
|
||||
return {error: "Already rejected."};
|
||||
}
|
||||
actions.rejectName(target, by);
|
||||
manage.forget(target);
|
||||
return {ok: `${name} is signed out and picks a new name at the next sign-in.`};
|
||||
case "acceptName":
|
||||
if (!target.nameRejected) {
|
||||
return {error: "Not rejected."};
|
||||
}
|
||||
actions.acceptName(target);
|
||||
return {ok: `${name} keeps the name.`};
|
||||
case "clearBio":
|
||||
target.bio = "";
|
||||
accounts.save();
|
||||
return {ok: "Bio cleared."};
|
||||
// the address they last signed in from, for good. which address that
|
||||
// is, the moderator is not told.
|
||||
case "banAddress": {
|
||||
const last = target.logins.find(login => login.ok && login.address);
|
||||
if (!last) {
|
||||
return {error: "No address is known for them."};
|
||||
}
|
||||
const result = staff.banAddress(last.address, body.reason, by);
|
||||
if (result.error) {
|
||||
return {error: result.error.startsWith("That is this machine") ? "Their address cannot be banned." : result.error};
|
||||
}
|
||||
return {ok: "Their address is banned.", detail: result.ban.reason};
|
||||
}
|
||||
default:
|
||||
return {error: "Unknown action."};
|
||||
}
|
||||
};
|
||||
|
||||
const PAGE_HEADERS = {
|
||||
"Cache-Control": "no-store",
|
||||
"X-Frame-Options": "DENY",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
"Content-Security-Policy": captcha.policy("default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; "
|
||||
+ "form-action 'none'; frame-ancestors 'none'; base-uri 'none'"),
|
||||
};
|
||||
|
||||
// `from` is {address, key, local}; `web` is {send, readJson} from lib/http.js.
|
||||
const handle = async (req, res, url, from, web) => {
|
||||
for (const [name, value] of Object.entries(PAGE_HEADERS)) {
|
||||
res.setHeader(name, value);
|
||||
}
|
||||
const reply = (status, body) => web.send(res, status, body);
|
||||
const route = `${req.method} ${url.pathname.replace(/\/$/, "") || "/mod"}`;
|
||||
|
||||
if (route === "GET /mod") {
|
||||
web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "mod.html"))), "text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (req.method === "POST" && !limits.originAllowed(req)) {
|
||||
reply(403, {error: "forbidden"});
|
||||
return;
|
||||
}
|
||||
const body = req.method === "POST" ? await web.readJson(req) : {};
|
||||
|
||||
switch (route) {
|
||||
case "GET /mod/api/state": {
|
||||
const mod = signedInAs(req);
|
||||
reply(200, {signedIn: Boolean(mod), username: mod ? mod.username : ""});
|
||||
return;
|
||||
}
|
||||
// username, password and a code, all three every time.
|
||||
case "POST /mod/api/login": {
|
||||
if (!from.local && failuresByAddress.blocked(from.key)) {
|
||||
reply(429, {error: "Too many attempts. Try later."});
|
||||
return;
|
||||
}
|
||||
const captchaProblem = await captcha.check({captcha: body.captcha}, from, "login");
|
||||
if (captchaProblem) {
|
||||
reply(captchaProblem === "captcha_unavailable" ? 503 : 401, {error: captcha.MESSAGES[captchaProblem]});
|
||||
return;
|
||||
}
|
||||
// looked up first: with AJ_REGISTER=1 authenticate() would make the account.
|
||||
const known = accounts.byName(String(body.username || "").trim());
|
||||
const account = known && await accounts.authenticateAsync(known.username, body.password) === known ? known : null;
|
||||
// one answer for a wrong password and for an account that is no
|
||||
// moderator: who the moderators are is nobody's to find out here.
|
||||
if (!account || !account.moderator) {
|
||||
failuresByAddress.record(from.key);
|
||||
if (known && !account) {
|
||||
accounts.recordLogin(known, "mod", from.address, false);
|
||||
accounts.save();
|
||||
}
|
||||
reply(401, {error: "Wrong username or password."});
|
||||
return;
|
||||
}
|
||||
if (!totp.isOn(account)) {
|
||||
reply(403, {error: "Turn on 2FA on your account page first."});
|
||||
return;
|
||||
}
|
||||
if (!mayModerate(account)) {
|
||||
reply(403, {error: "This account cannot sign in here now."});
|
||||
return;
|
||||
}
|
||||
if (!totp.verify(account, String(body.code || ""))) {
|
||||
failuresByAddress.record(from.key);
|
||||
accounts.recordLogin(account, "mod", from.address, false);
|
||||
accounts.save();
|
||||
reply(401, {error: "Wrong code."});
|
||||
return;
|
||||
}
|
||||
accounts.recordLogin(account, "mod", from.address);
|
||||
accounts.save();
|
||||
for (const [hash, session] of sessions) {
|
||||
if (session.expiry < Date.now()) {
|
||||
sessions.delete(hash);
|
||||
}
|
||||
}
|
||||
const token = crypto.randomBytes(24).toString("hex");
|
||||
sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000});
|
||||
res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600));
|
||||
modlog.record(account.username, "signed in");
|
||||
reply(200, {ok: true, username: account.username});
|
||||
return;
|
||||
}
|
||||
case "POST /mod/api/logout": {
|
||||
const token = cookieToken(req);
|
||||
if (token) {
|
||||
sessions.delete(sha256(token));
|
||||
}
|
||||
res.setHeader("Set-Cookie", cookieHeader("", 0));
|
||||
reply(200, {ok: true});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const mod = signedInAs(req);
|
||||
if (!mod) {
|
||||
reply(401, {error: "Sign in first."});
|
||||
return;
|
||||
}
|
||||
if (req.method === "POST" && !actionsPerTenMinutes.allow(mod.id)) {
|
||||
reply(429, {error: "Too many at once. Try later."});
|
||||
return;
|
||||
}
|
||||
// what was done, under the moderator's name; then the answer.
|
||||
const done = (result, action, target = "", detail = "") => {
|
||||
if (result.ok) {
|
||||
modlog.record(mod.username, action, target, result.detail || detail);
|
||||
}
|
||||
reply(result.ok ? 200 : 400, result.ok ? {ok: result.ok} : {error: result.error});
|
||||
};
|
||||
|
||||
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});
|
||||
return;
|
||||
|
||||
case "GET /mod/api/players":
|
||||
reply(200, {players: findPlayers(url.searchParams.get("q"))});
|
||||
return;
|
||||
|
||||
case "GET /mod/api/player": {
|
||||
const account = accounts.byName(url.searchParams.get("username") || "");
|
||||
reply(account ? 200 : 404, account ? playerDetail(account) : {error: "No such player."});
|
||||
return;
|
||||
}
|
||||
|
||||
case "POST /mod/api/act": {
|
||||
const target = accounts.byName(String(body.username || ""));
|
||||
if (!target) {
|
||||
reply(404, {error: "No such player."});
|
||||
return;
|
||||
}
|
||||
done(act(mod, target, body), String(body.action), target.username);
|
||||
return;
|
||||
}
|
||||
|
||||
// what players typed (lib/chatlog.js): a page of lines, or the lines
|
||||
// around one of them.
|
||||
case "GET /mod/api/chat": {
|
||||
const params = url.searchParams;
|
||||
const lines = chatlog.search({username: (params.get("username") || "").trim().slice(0, 100), room: (params.get("room") || "").trim().slice(0, 100),
|
||||
text: (params.get("text") || "").trim().slice(0, 100), before: Number(params.get("before")) || 0});
|
||||
reply(200, {lines, more: lines.length === chatlog.PAGE, days: config.chatLogDays});
|
||||
return;
|
||||
}
|
||||
case "GET /mod/api/chat/around": {
|
||||
const found = chatlog.around(url.searchParams.get("id"));
|
||||
reply(found ? 200 : 404, found || {error: "No such line."});
|
||||
return;
|
||||
}
|
||||
|
||||
case "GET /mod/api/reports":
|
||||
reply(200, {reports: reports.list(url.searchParams.get("handled") === "1"), open: reports.openCount()});
|
||||
return;
|
||||
|
||||
case "POST /mod/api/report":
|
||||
done(reports.markHandled(Number(body.id)) ? {ok: "Marked as dealt with."} : {error: "No such report waiting."}, "report dealt with", "", `#${Number(body.id)}`);
|
||||
return;
|
||||
|
||||
// requests for another username, and ban appeals.
|
||||
case "GET /mod/api/requests": {
|
||||
const handled = url.searchParams.get("handled") === "1";
|
||||
reply(200, {names: support.nameRequests(handled), appeals: staff.appealsFor(handled).map(({addressKey, address, ...appeal}) => ({...appeal, ofAddress: Boolean(address)}))});
|
||||
return;
|
||||
}
|
||||
case "POST /mod/api/request": {
|
||||
if (body.action === "appealApprove" || body.action === "appealDeny") {
|
||||
const result = staff.answerAppeal(body.id, body.action === "appealApprove", body.reply, mod.username);
|
||||
done(result, body.action === "appealApprove" ? "appeal approved" : "appeal denied", result.username, bans.clean(body.reply, bans.MAX_REPLY));
|
||||
}
|
||||
else if (body.action === "approve" || body.action === "deny") {
|
||||
const result = staff.answerNameRequest(body.id, body.action === "approve");
|
||||
done(result, body.action === "approve" ? "name request approved" : "name request denied", result.username);
|
||||
}
|
||||
else {
|
||||
reply(400, {error: "Unknown action."});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
case "GET /mod/api/bans":
|
||||
reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans().map(maskedAddress)});
|
||||
return;
|
||||
|
||||
case "POST /mod/api/address": {
|
||||
const ban = bans.addressBans().find(entry => sha256(entry.key).slice(0, 16) === String(body.id));
|
||||
done(ban && bans.unbanAddress(ban.key, mod.username) ? {ok: "No longer banned."} : {error: "Not banned."}, "address unbanned", "", ban ? ban.reason : "");
|
||||
return;
|
||||
}
|
||||
|
||||
// paintings players framed (lib/masterpieces.js).
|
||||
case "GET /mod/api/masterpieces":
|
||||
reply(200, {waiting: masterpieces.list(masterpieces.PENDING), approved: masterpieces.list(masterpieces.APPROVED)});
|
||||
return;
|
||||
|
||||
case "GET /mod/api/masterpiece": {
|
||||
const picture = masterpieces.image(url.searchParams.get("id") || "");
|
||||
if (!picture) {
|
||||
reply(404, {error: "No such painting."});
|
||||
return;
|
||||
}
|
||||
res.setHeader("Cache-Control", "private, max-age=3600");
|
||||
web.send(res, 200, picture, "image/jpeg");
|
||||
return;
|
||||
}
|
||||
|
||||
case "POST /mod/api/masterpiece": {
|
||||
const id = String(body.id || "");
|
||||
const maker = masterpieces.creatorOf(id);
|
||||
const result = body.action === "approve"
|
||||
? (world.approveMasterpiece(id) ? {ok: "Approved."} : {error: "No such painting waiting."})
|
||||
: body.action === "reject" || body.action === "remove"
|
||||
? (world.removeMasterpiece(id) ? {ok: "Removed for good. Its maker was told and given a Masterpiece Token."} : {error: "No such painting."})
|
||||
: {error: "Unknown action."};
|
||||
done(result, `painting ${body.action === "approve" ? "approved" : "removed"}`, maker ? maker.username : "", id);
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
reply(404, {error: "not_found"});
|
||||
}
|
||||
};
|
||||
|
||||
const moderators = () => accounts.all().filter(account => account.moderator)
|
||||
.map(account => ({username: account.username, twoStep: totp.isOn(account), lastSeen: account.lastSeen || null}))
|
||||
.sort((a, b) => a.username.localeCompare(b.username));
|
||||
|
||||
module.exports = {handle, forget, moderators};
|
||||
@@ -0,0 +1,77 @@
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const config = require("../config.js");
|
||||
|
||||
// which usernames a player may not choose (sign-up, and a request for a new
|
||||
// name): the ones that would pass for whoever runs the game, and slurs.
|
||||
// deliberately loose. A name is refused for BEING such a word, or having
|
||||
// one as one of its words; a name that merely contains one is let through,
|
||||
// and whoever runs the server deals with the odd one by hand (rename, in
|
||||
// the admin panel). the lists are files, read again when they change:
|
||||
// lib/reserved-names.txt staff-like names
|
||||
// public/filter/level1.txt the chat filter's first level: slurs, threats
|
||||
// and the names of the Epic Dens, which are how a showcase den is asked for.
|
||||
|
||||
const RESERVED_FILE = path.join(__dirname, "reserved-names.txt");
|
||||
const SLURS_FILE = path.join(config.publicDir, "filter", "level1.txt");
|
||||
const DIGITS = {0: "o", 1: "i", 3: "e", 4: "a", 5: "s", 7: "t"};
|
||||
|
||||
// A word as it is compared: small letters, digits at either end dropped
|
||||
// ("mod123"), digits inside read as the letters they stand in for. this and
|
||||
// the matching below are the chat filter's own rules (AJClient.filterText
|
||||
// in the patched client), since the slurs are its first list.
|
||||
const plain = word => word.toLowerCase().replace(/^\d+|\d+$/g, "").replace(/\d/g, digit => DIGITS[digit] || "").replace(/[^a-z]/g, "");
|
||||
// A letter drawn out ("mooood") is undone, but only for a word that has one
|
||||
// drawn out three times or more: "coon" must not be the same word as "con".
|
||||
const squash = word => word.replace(/(.)\1+/g, "$1");
|
||||
const stretched = word => /(.)\1\1/.test(word);
|
||||
|
||||
// the entries of a list file: [{text, prefix}], text made plain as above.
|
||||
const lists = new Map(); // file -> {mtime, entries}
|
||||
const read = file => {
|
||||
let mtime = 0;
|
||||
try {
|
||||
mtime = fs.statSync(file).mtimeMs;
|
||||
}
|
||||
catch (err) {
|
||||
return [];
|
||||
}
|
||||
const kept = lists.get(file);
|
||||
if (kept && kept.mtime === mtime) {
|
||||
return kept.entries;
|
||||
}
|
||||
const entries = fs.readFileSync(file, "utf8").split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith("#"))
|
||||
.map(line => ({text: line.replace(/\*$/, "").split(/\s+/).map(plain).join(""), prefix: line.endsWith("*")})).filter(entry => entry.text.length >= 2);
|
||||
lists.set(file, {mtime, entries});
|
||||
return entries;
|
||||
};
|
||||
|
||||
let epicDens = null;
|
||||
const denNames = () => {
|
||||
if (!epicDens) {
|
||||
try {
|
||||
const names = require("./epicdens.js").all().map(den => plain(den.name));
|
||||
if (names.length === 0) {
|
||||
return names; // the game's data is not loaded yet
|
||||
}
|
||||
epicDens = names;
|
||||
}
|
||||
catch (err) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
return epicDens;
|
||||
};
|
||||
|
||||
const refused = username => {
|
||||
const words = String(username).split(/[ .-]+/).map(plain).filter(Boolean);
|
||||
const whole = plain(String(username));
|
||||
const same = (word, entry) => word === entry.text || (entry.prefix && word.startsWith(entry.text))
|
||||
|| (stretched(word) && (squash(word) === squash(entry.text) || (entry.prefix && squash(word).startsWith(squash(entry.text)))));
|
||||
const hit = entry => same(whole, entry) || words.some(word => same(word, entry));
|
||||
return read(RESERVED_FILE).some(hit) || read(SLURS_FILE).some(hit) || denNames().includes(whole);
|
||||
};
|
||||
|
||||
module.exports = {refused, plain};
|
||||
@@ -0,0 +1,846 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const accounts = require("./accounts.js");
|
||||
const achievements = require("./achievements.js");
|
||||
const adopt = require("./adopt.js");
|
||||
const badges = require("./badges.js");
|
||||
const bans = require("./bans.js");
|
||||
const colours = require("./colours.js");
|
||||
const config = require("../config.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const limits = require("./limits.js");
|
||||
const log = require("./log.js");
|
||||
const masterpieces = require("./masterpieces.js");
|
||||
const modlog = require("./modlog.js");
|
||||
const modpanel = require("./modpanel.js");
|
||||
const erase = require("./erase.js");
|
||||
const reports = require("./reports.js");
|
||||
const sales = require("./sales.js");
|
||||
const staff = require("./staff.js");
|
||||
const support = require("./support.js");
|
||||
const totp = require("./totp.js");
|
||||
const manage = require("./manage.js");
|
||||
const world = require("./world.js");
|
||||
const {activeAvatar} = require("./player.js");
|
||||
|
||||
// the admin panel at /admin: the only place the server is administered from.
|
||||
// it has one password, chosen the first time the panel is opened and kept as
|
||||
// a salted scrypt hash in the database. no game account has admin powers.
|
||||
//
|
||||
// signing in sets a cookie that only this panel's pages send back (HttpOnly,
|
||||
// SameSite=Strict, Path=/admin); sessions live in memory, so restarting the
|
||||
// server signs everyone out.
|
||||
|
||||
const PASSWORD_SETTING = "admin_password"; // "salt:hash"
|
||||
const COOKIE = "ajc_admin";
|
||||
const SESSION_HOURS = 12;
|
||||
const MIN_PASSWORD_LENGTH = 8;
|
||||
const MAX_PASSWORD_LENGTH = 200;
|
||||
const MAX_MESSAGE_LENGTH = 200;
|
||||
const MAX_BAN_HOURS = 24 * 365 * 10;
|
||||
const MAX_GEMS = 1000000000;
|
||||
const TEN_MINUTES_MS = 600000;
|
||||
const DAY_SECONDS = 86400;
|
||||
const MAX_ANNOUNCEMENT = 300;
|
||||
const MAX_OWNED_LISTED = 300;
|
||||
// currencies the panel can hand out, as indexes into CURRENCIES.
|
||||
const GIFT_CURRENCIES = {gems: 0, tickets: 1, diamonds: 3};
|
||||
// who a ban is written down as given by. the panel has one password and so
|
||||
// one name; moderators with sign-ins of their own will each have theirs.
|
||||
const BY = "admin";
|
||||
|
||||
// wrong passwords (and wrong setup codes) allowed per address before further
|
||||
// tries from it are refused for a while. there is deliberately no overall
|
||||
// limit: it would let a stranger lock the real admin out.
|
||||
const failuresByAddress = limits.limiter(8, TEN_MINUTES_MS);
|
||||
|
||||
const sessions = new Map(); // SHA-256 of a session token -> expiry (ms)
|
||||
let setupCode = null; // needed to choose the first password from another machine
|
||||
|
||||
const sha256 = text => crypto.createHash("sha256").update(text).digest("hex");
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
|
||||
const hasPassword = () => accounts.setting(PASSWORD_SETTING) !== null;
|
||||
|
||||
const storePassword = password => {
|
||||
const salt = crypto.randomBytes(16).toString("hex");
|
||||
accounts.setSetting(PASSWORD_SETTING, `${salt}:${accounts.hashPassword(password, salt)}`);
|
||||
};
|
||||
|
||||
const passwordMatches = password => {
|
||||
const [salt, hash] = (accounts.setting(PASSWORD_SETTING) || ":").split(":");
|
||||
if (typeof password !== "string" || !salt || password.length > MAX_PASSWORD_LENGTH) {
|
||||
return false;
|
||||
}
|
||||
return crypto.timingSafeEqual(Buffer.from(accounts.hashPassword(password, salt), "hex"), Buffer.from(hash, "hex"));
|
||||
};
|
||||
|
||||
const passwordAcceptable = password =>
|
||||
typeof password === "string" && password.length >= MIN_PASSWORD_LENGTH && password.length <= MAX_PASSWORD_LENGTH;
|
||||
|
||||
const load = () => {
|
||||
if (!hasPassword()) {
|
||||
setupCode = crypto.randomBytes(5).toString("hex");
|
||||
console.log(`[admin] no admin password yet: open ${config.baseUrl}admin to choose one`
|
||||
+ ` (from another machine it will ask for this setup code: ${setupCode})`);
|
||||
}
|
||||
};
|
||||
|
||||
const cookieToken = req => {
|
||||
const match = new RegExp(`(?:^|;\\s*)${COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "");
|
||||
return match ? match[1] : null;
|
||||
};
|
||||
|
||||
const signedIn = req => {
|
||||
const token = cookieToken(req);
|
||||
const expiry = token && sessions.get(sha256(token));
|
||||
if (!expiry || expiry < Date.now()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const cookieHeader = (token, maxAgeSeconds) =>
|
||||
`${COOKIE}=${token}; Path=/admin; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
|
||||
|
||||
const signIn = res => {
|
||||
for (const [hash, expiry] of sessions) {
|
||||
if (expiry < Date.now()) {
|
||||
sessions.delete(hash);
|
||||
}
|
||||
}
|
||||
const token = crypto.randomBytes(24).toString("hex");
|
||||
sessions.set(sha256(token), Date.now() + SESSION_HOURS * 3600000);
|
||||
res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600));
|
||||
};
|
||||
|
||||
const signOut = (req, res) => {
|
||||
const token = cookieToken(req);
|
||||
if (token) {
|
||||
sessions.delete(sha256(token));
|
||||
}
|
||||
res.setHeader("Set-Cookie", cookieHeader("", 0));
|
||||
};
|
||||
|
||||
const accountRow = (account, playing) => {
|
||||
const ban = world.moderation.banRemaining(account);
|
||||
return {
|
||||
id: account.id,
|
||||
username: account.username,
|
||||
createdAt: account.createdAt,
|
||||
lastLogin: account.lastLogin || null,
|
||||
lastSeen: account.lastSeen || null,
|
||||
locked: account.locked,
|
||||
twoStep: totp.isOn(account),
|
||||
discord: account.discord,
|
||||
bio: account.bio,
|
||||
badges: account.badges,
|
||||
featuresOff: accounts.FEATURES.filter(name => !accounts.featureOn(account, name)),
|
||||
logins: account.numLogins,
|
||||
online: playing.has(account.username),
|
||||
room: playing.get(account.username) || null,
|
||||
// seconds left, -1 for permanent, 0 for not banned
|
||||
banned: ban,
|
||||
banReason: ban === 0 ? "" : account.banReason || bans.NO_REASON,
|
||||
moderator: Boolean(account.moderator),
|
||||
nameRejected: Boolean(account.nameRejected),
|
||||
silenced: world.moderation.isSilenced(account),
|
||||
animals: account.avatars.length,
|
||||
level: activeAvatar(account).questLevel || 0,
|
||||
items: account.items.length + account.denItems.length,
|
||||
gems: account.currency.gems || 0,
|
||||
};
|
||||
};
|
||||
|
||||
const overview = () => {
|
||||
const players = world.players();
|
||||
const all = accounts.all();
|
||||
const rooms = new Map();
|
||||
for (const player of players) {
|
||||
const room = player.room || "(between rooms)";
|
||||
rooms.set(room, (rooms.get(room) || 0) + 1);
|
||||
}
|
||||
return {
|
||||
stats: {
|
||||
online: players.length,
|
||||
accounts: all.length,
|
||||
newToday: all.filter(account => account.createdAt > now() - DAY_SECONDS).length,
|
||||
activeToday: all.filter(account => (account.lastLogin || 0) > now() - DAY_SECONDS).length,
|
||||
banned: all.filter(account => world.moderation.banRemaining(account) !== 0).length,
|
||||
clientErrors: log.recent(0, "[client-error]", Infinity).length,
|
||||
reports: reports.openCount(),
|
||||
support: support.openCount() + bans.openAppeals(),
|
||||
masterpieces: masterpieces.list(masterpieces.PENDING).length,
|
||||
},
|
||||
server: {
|
||||
address: config.baseUrl,
|
||||
uptimeSeconds: Math.floor(process.uptime()),
|
||||
memoryMb: Math.round(process.memoryUsage().rss / 1048576),
|
||||
node: process.version,
|
||||
reachableFromOtherMachines: config.isPublic,
|
||||
encrypted: config.secureCookies,
|
||||
packetLog: config.logPackets,
|
||||
customColours: colours.count(),
|
||||
},
|
||||
players,
|
||||
rooms: [...rooms].map(([name, count]) => ({name, count})).sort((a, b) => b.count - a.count),
|
||||
};
|
||||
};
|
||||
|
||||
const ownedBy = account => {
|
||||
const counted = (entries, nameOf) => {
|
||||
const counts = new Map();
|
||||
for (const entry of entries) {
|
||||
counts.set(entry.def, (counts.get(entry.def) || 0) + 1);
|
||||
}
|
||||
return [...counts].map(([def, count]) => ({id: def, name: nameOf(def) || `#${def}`, count}))
|
||||
.sort((a, b) => a.name.localeCompare(b.name)).slice(0, MAX_OWNED_LISTED);
|
||||
};
|
||||
const clothingName = def => defpacks.string((defpacks.itemDef(def) || {}).titleStrId);
|
||||
const denItemName = def => {
|
||||
const item = defpacks.denItemDef(def) || {};
|
||||
return defpacks.string(item.nameStrId) || item.abbrName;
|
||||
};
|
||||
return {
|
||||
username: account.username,
|
||||
currency: Object.fromEntries(Object.keys(GIFT_CURRENCIES).map(name => [name, account.currency[name] || 0])),
|
||||
animals: account.avatars.map(avatar => defpacks.string((defpacks.avatarDef(avatar.type) || {}).titleStrId) || `Animal type ${avatar.type}`),
|
||||
pets: account.pets.map(pet => defpacks.string((defpacks.petDef(pet.lBits & 0xFF) || {}).titleStrId) || `Pet type ${pet.lBits & 0xFF}`),
|
||||
dens: account.dens.length,
|
||||
clothing: counted(account.items, clothingName),
|
||||
clothingTotal: account.items.length,
|
||||
denItems: counted(account.denItems, denItemName),
|
||||
denItemsTotal: account.denItems.length,
|
||||
buddies: account.buddies,
|
||||
blocked: account.blocked,
|
||||
achievements: account.achievements.length,
|
||||
adoptAPets: account.adoptAPets.length,
|
||||
jamAGrams: account.ecards.length,
|
||||
wallPosts: account.wall.posts.length,
|
||||
outfits: account.outfits.map(outfit => outfit.name),
|
||||
denLayouts: account.denLayouts.map(layout => layout.name),
|
||||
hidesBlockedPlayers: account.hideBlocked,
|
||||
};
|
||||
};
|
||||
|
||||
// ---- the Debug page: getting into rooms nothing leads to, and seeing what
|
||||
// sale dates hide. for whoever runs the server to look around with; it gives
|
||||
// a player nothing they keep.
|
||||
|
||||
// rooms found to be unused, unfinished or otherwise out of reach (see
|
||||
// DISCOVERIES.md), with what they are.
|
||||
const ROOM_NOTES = {
|
||||
"lost_temple_of_zios/room_chamberbase": "reached from a hidden spot on the world map (bottom left, under Appondale); its shop sells the odd den items",
|
||||
"appondale/room_museum_ant": "the museum with its Antlers and Tusks exhibit; shown in place of the usual one in even months",
|
||||
"first_five/room_firstfive": "the new-player tutorial room",
|
||||
"canyon_path/room_main_main": "the Canyons Pathway with the plushie hunt's stand; shown in March and April",
|
||||
"activitygeography/room_main": "scene of a geography activity",
|
||||
"world_map/room_main": "the world map, as a room",
|
||||
"reuseplayer_den/content/pd_burrow/pd_burrow": "a stray copy of the burrow den",
|
||||
"holidays_and_celebrations/halloween/room_main": "Halloween room no portal leads to",
|
||||
"party/venue_pl_birthday_cake": "earlier copy of a hostable venue; now the Birthday Party",
|
||||
"party/venue_pl_vet_science": "earlier copy of a hostable venue; now the Science Party",
|
||||
"party/venue_pl_res_bakery": "earlier copy of a hostable venue; now the Bakery Party",
|
||||
"party/venue_pl_castle_medieval": "earlier copy of a hostable venue; now the Medieval Party",
|
||||
"player_den/room_castle_lrg": "a draft den; sold in the den shops now",
|
||||
"player_den/room_main_waterpark3": "a draft den; sold in the den shops now",
|
||||
"player_den/room_main_waterpark4": "a draft den; sold in the den shops now",
|
||||
"player_den/room_main_epicpalace": "a draft den; sold in the den shops now",
|
||||
"riverraceassets/room_main_new": "a newer River Race scene",
|
||||
"prototypehorserace/room_main": "prototype of Jamaa Derby",
|
||||
};
|
||||
const ROOM_GROUP_NOTES = {
|
||||
epic_dens: "the Epic Dens showcase; twenty a day are in the world map's Epic Dens list",
|
||||
holidays_and_celebrations: "Halloween rooms: copies of the Phantom Vortex room the lands lead to in October",
|
||||
rholidays_and_celebrations: "Halloween rooms, older set",
|
||||
adventures: "adventure maps; nothing in them moves",
|
||||
};
|
||||
|
||||
const debugState = () => ({
|
||||
players: world.players().map(player => player.username).sort((a, b) => a.localeCompare(b)),
|
||||
rooms: defpacks.roomPaths().map(roomPath => {
|
||||
const group = roomPath.split("/")[0];
|
||||
return {path: roomPath, group, note: ROOM_NOTES[roomPath] || ROOM_GROUP_NOTES[group] || ""};
|
||||
}).sort((a, b) => a.path.localeCompare(b.path)),
|
||||
everythingOnSale: sales.everythingOnSale(),
|
||||
});
|
||||
|
||||
const debugAct = body => {
|
||||
if (body.action === "teleport") {
|
||||
const account = accounts.byName(String(body.username || ""));
|
||||
if (!account) {
|
||||
return {error: "No such account."};
|
||||
}
|
||||
const problem = world.teleport(account, String(body.room || ""));
|
||||
return problem ? {error: `${problem}.`} : {ok: `${account.username} is on the way to ${body.room}.`};
|
||||
}
|
||||
if (body.action === "everythingOnSale") {
|
||||
sales.setEverythingOnSale(body.on === true);
|
||||
return {ok: body.on === true
|
||||
? "Sale dates are off: every item shows, for players who start the game from now on."
|
||||
: "Sale dates are back on, for players who start the game from now on."};
|
||||
}
|
||||
return {error: "Unknown debug action."};
|
||||
};
|
||||
|
||||
// what was done about an account's bans, its appeal, and the addresses it
|
||||
// signed in from (newest first, each once), for banning one of them.
|
||||
const banRecord = account => {
|
||||
const seen = new Map();
|
||||
for (const login of account.logins) {
|
||||
if (login.address && !seen.has(login.address)) {
|
||||
seen.set(login.address, {address: login.address, at: login.at, banned: Boolean(bans.addressBan(login.address)),
|
||||
own: limits.isLoopback(login.address)});
|
||||
}
|
||||
}
|
||||
return {history: bans.historyOf(account), appeal: bans.appealOf(account), addresses: [...seen.values()]};
|
||||
};
|
||||
|
||||
// bans an address for good, or lifts that. returns {ok: text} or {error: text}.
|
||||
const addressAct = body => {
|
||||
if (body.action === "ban") {
|
||||
const result = staff.banAddress(body.address, body.reason, BY);
|
||||
if (result.error) {
|
||||
return result;
|
||||
}
|
||||
const {out} = result;
|
||||
return {ok: `${result.ban.key} is banned.${out ? ` ${out} playing from it ${out === 1 ? "was" : "were"} disconnected.` : ""}`};
|
||||
}
|
||||
if (body.action === "unban") {
|
||||
return bans.unbanAddress(String(body.address || ""), BY) ? {ok: "No longer banned."} : {error: "Not banned."};
|
||||
}
|
||||
return {error: "Unknown action."};
|
||||
};
|
||||
|
||||
// A gift from the panel. gems, diamonds and items arrive as a Jam-A-Gram
|
||||
// from Animal Jam HQ, whether or not the player is online: an item waits in
|
||||
// their inbox, gems and diamonds open as a gift popup (lib/ecards.js). the
|
||||
// rest has no such card and goes straight into the account.
|
||||
const gift = (account, body) => {
|
||||
const name = account.username;
|
||||
const text = String(body.text || "").trim().slice(0, MAX_MESSAGE_LENGTH) || "A gift for you!";
|
||||
if (Object.hasOwn(GIFT_CURRENCIES, body.kind)) {
|
||||
const amount = wholeNumber(body.amount, 1, MAX_GEMS);
|
||||
if (amount === null) {
|
||||
return {error: "Give a whole number above zero."};
|
||||
}
|
||||
if (body.kind === "tickets") {
|
||||
world.moderation.actions.grantCurrency(account, GIFT_CURRENCIES.tickets, amount);
|
||||
return {ok: `${name} was given ${amount.toLocaleString()} tickets.`};
|
||||
}
|
||||
const problem = world.ecards.sendFromHq(account, text, {kind: body.kind, amount});
|
||||
return problem ? {error: `${problem}.`} : {ok: `A Jam-A-Gram with ${amount.toLocaleString()} ${body.kind} is on its way to ${name}.`};
|
||||
}
|
||||
if (body.kind === "clothing" || body.kind === "den") {
|
||||
const color = body.color === undefined || body.color === "" ? undefined : wholeNumber(Number(body.color), 0, 0xFFFFFFFF);
|
||||
if (color === null) {
|
||||
return {error: "The colour id must be a whole number from 0 to 4294967295."};
|
||||
}
|
||||
const problem = world.ecards.sendFromHq(account, text, {kind: body.kind, id: body.id, color});
|
||||
return problem ? {error: `${problem}.`} : {ok: `A Jam-A-Gram with that item is in ${name}'s inbox.`};
|
||||
}
|
||||
if (body.kind === "adopt") {
|
||||
const ids = body.id === "all" ? defpacks.adoptAPetIds() : [body.id];
|
||||
const given = ids.filter(id => adopt.give(account, id)).length;
|
||||
accounts.save();
|
||||
return given ? {ok: `${name} has ${given} more on their Adopt-A-Pet checklist (it shows after their next login).`}
|
||||
: {error: "No such Adopt-A-Pet, or they already have it."};
|
||||
}
|
||||
if (body.kind === "achievement") {
|
||||
return achievements.grant(account, body.id) ? {ok: `${name} has that achievement now.`}
|
||||
: {error: "No such achievement, or they already have it."};
|
||||
}
|
||||
return {error: "Unknown kind of gift."};
|
||||
};
|
||||
|
||||
const MAX_QUEST_LEVEL = 100;
|
||||
|
||||
const wholeNumber = (value, min, max) => (Number.isInteger(value) && value >= min && value <= max ? value : null);
|
||||
|
||||
// returns {ok: text} or {error: text}.
|
||||
const act = (account, body) => {
|
||||
const {actions, PERMANENT} = world.moderation;
|
||||
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."};
|
||||
}
|
||||
actions.kick(account);
|
||||
manage.forget(account); // their account page too, whoever has it open
|
||||
modpanel.forget(account);
|
||||
return {ok: `${name} has a new password and was signed out.`};
|
||||
}
|
||||
// the owner locks and unlocks on the account page; this is for when
|
||||
// they cannot.
|
||||
case "unlock":
|
||||
account.locked = false;
|
||||
accounts.save();
|
||||
return {ok: `${name} is unlocked.`};
|
||||
// for a player who lost their phone and their recovery codes: their
|
||||
// password alone signs them in again.
|
||||
case "twoStepOff":
|
||||
if (!totp.isOn(account)) {
|
||||
return {error: `${name} does not use 2FA.`};
|
||||
}
|
||||
totp.turnOff(account);
|
||||
accounts.save();
|
||||
return {ok: `2FA is off for ${name}.`};
|
||||
case "rename": {
|
||||
world.disconnect(account);
|
||||
manage.forget(account);
|
||||
modpanel.forget(account);
|
||||
// the admin may pick any name the server can store and the game can carry.
|
||||
const problem = accounts.rename(account, body.newName, true);
|
||||
if (problem) {
|
||||
return {error: problem === "username_taken" ? "That username is taken."
|
||||
: "That name cannot be used: it must not be empty, be over 100 characters, or contain % or control characters."};
|
||||
}
|
||||
return {ok: `${name} is now called ${account.username}. They log in with the new name and the same password.`, username: account.username};
|
||||
}
|
||||
// for trying out what a player's card says about when they were last
|
||||
// seen: any time in the past, in seconds. it is overwritten the next
|
||||
// time they leave the game.
|
||||
case "lastSeen": {
|
||||
const when = wholeNumber(body.when, 1, Math.floor(Date.now() / 1000));
|
||||
if (when === null) {
|
||||
return {error: "Pick a date and time in the past."};
|
||||
}
|
||||
account.lastSeen = when;
|
||||
accounts.save();
|
||||
return {ok: `${name} was last seen ${new Date(when * 1000).toISOString().replace("T", " ").slice(0, 16)} UTC, as far as the game knows.`};
|
||||
}
|
||||
// the adventure level of the animal they are using.
|
||||
case "level": {
|
||||
const level = wholeNumber(body.level, 0, MAX_QUEST_LEVEL);
|
||||
if (level === null) {
|
||||
return {error: `0 to ${MAX_QUEST_LEVEL}.`};
|
||||
}
|
||||
world.setQuestLevel(account, level);
|
||||
return {ok: `${name}'s animal is level ${level}.`};
|
||||
}
|
||||
// their badges (lib/badges.js): the whole set at once.
|
||||
case "badges": {
|
||||
if (!Array.isArray(body.badges) || !body.badges.every(badges.known)) {
|
||||
return {error: "Unknown badge."};
|
||||
}
|
||||
badges.set(account, body.badges);
|
||||
accounts.save();
|
||||
world.checkNameTag(account);
|
||||
return {ok: account.badges.length ? `${name} has: ${badges.of(account).map(badge => badge.label).join(", ")}.` : `${name} has no badges.`};
|
||||
}
|
||||
// their Discord username, which they otherwise set on the account
|
||||
// page; empty takes it off.
|
||||
case "discord": {
|
||||
const discord = badges.discordName(body.name);
|
||||
if (discord === null) {
|
||||
return {error: "Not a Discord username."};
|
||||
}
|
||||
account.discord = discord;
|
||||
accounts.save();
|
||||
return {ok: discord ? `Discord set to "${discord}".` : "Discord cleared."};
|
||||
}
|
||||
// their bio, which they otherwise write on the account page; empty
|
||||
// takes it off.
|
||||
case "bio": {
|
||||
const bio = badges.bioText(body.text);
|
||||
if (bio === null) {
|
||||
return {error: `At most ${badges.MAX_BIO} characters on ${badges.MAX_BIO_LINES} lines.`};
|
||||
}
|
||||
account.bio = bio;
|
||||
accounts.save();
|
||||
return {ok: bio ? "Bio set." : "Bio cleared."};
|
||||
}
|
||||
case "ban": {
|
||||
const hours = wholeNumber(body.hours, 0, MAX_BAN_HOURS);
|
||||
if (hours === null) {
|
||||
return {error: "Give the ban a whole number of hours, or 0 for permanent."};
|
||||
}
|
||||
actions.ban(account, hours === 0 ? PERMANENT : hours * 3600, body.reason, BY);
|
||||
// out of the account page as well. (They may sign in to it again: it
|
||||
// shows them the ban and little else, lib/manage.js.) Saved sign-ins
|
||||
// are left: nothing takes one while the ban lasts but the client's
|
||||
// question about the ban itself (lib/admin.js).
|
||||
manage.forget(account);
|
||||
return {ok: hours === 0 ? `${name} is banned permanently.` : `${name} is banned for ${hours} hours.`};
|
||||
}
|
||||
case "banReason":
|
||||
return actions.banReason(account, body.reason, BY) ? {ok: "Reason saved."} : {error: `${name} is not banned.`};
|
||||
case "unban":
|
||||
actions.unban(account, BY);
|
||||
return {ok: `${name} is no longer banned.`};
|
||||
case "kick":
|
||||
return actions.kick(account) ? {ok: `${name} was disconnected.`} : {error: `${name} is not online.`};
|
||||
// counted in hours; the game's own notice counts minutes.
|
||||
case "silence": {
|
||||
const hours = wholeNumber(body.hours, 0, MAX_BAN_HOURS);
|
||||
if (hours === null) {
|
||||
return {error: "Give a whole number of hours, or 0 for until lifted."};
|
||||
}
|
||||
actions.silence(account, hours === 0 ? PERMANENT : hours * 3600);
|
||||
return {ok: hours === 0 ? `${name} cannot chat until you lift it.` : `${name} cannot chat for ${hours} hours.`};
|
||||
}
|
||||
// A moderator may use the moderator panel (lib/modpanel.js), with this
|
||||
// account's password and its 2FA, which it has to have.
|
||||
case "moderator":
|
||||
if (body.on === true) {
|
||||
account.moderator = true;
|
||||
}
|
||||
else {
|
||||
delete account.moderator;
|
||||
modpanel.forget(account);
|
||||
}
|
||||
accounts.save();
|
||||
return {ok: body.on === true
|
||||
? `${name} is a moderator.${totp.isOn(account) ? "" : " They have no 2FA yet and cannot sign in to the moderator panel until they turn it on."}`
|
||||
: `${name} is no longer a moderator.`};
|
||||
case "rejectName":
|
||||
actions.rejectName(account, BY);
|
||||
manage.forget(account);
|
||||
modpanel.forget(account);
|
||||
return {ok: `${name} is signed out and picks a new name at the next sign-in.`};
|
||||
case "acceptName":
|
||||
actions.acceptName(account);
|
||||
return {ok: `${name} keeps the name.`};
|
||||
case "unsilence":
|
||||
actions.silence(account, 0);
|
||||
return {ok: `${name} can chat again.`};
|
||||
case "message": {
|
||||
const text = String(body.text || "").trim().slice(0, MAX_MESSAGE_LENGTH);
|
||||
if (!text) {
|
||||
return {error: "The message is empty."};
|
||||
}
|
||||
return actions.message(account, text) ? {ok: `Message shown to ${name}.`} : {error: `${name} is not online.`};
|
||||
}
|
||||
case "clearDen":
|
||||
actions.clearDen(account);
|
||||
return {ok: `Everything in ${name}'s den went back to their inventory.`};
|
||||
case "gems": {
|
||||
const amount = wholeNumber(body.amount, -MAX_GEMS, MAX_GEMS);
|
||||
if (amount === null) {
|
||||
return {error: "Give a whole number of gems (negative to take away)."};
|
||||
}
|
||||
actions.grantGems(account, amount);
|
||||
return {ok: `${name} now has ${account.currency.gems} gems.`};
|
||||
}
|
||||
case "gift":
|
||||
return gift(account, body);
|
||||
case "delete":
|
||||
world.disconnect(account);
|
||||
manage.forget(account);
|
||||
modpanel.forget(account);
|
||||
erase(account);
|
||||
return {ok: `${name} was deleted.`};
|
||||
default:
|
||||
return {error: "Unknown action."};
|
||||
}
|
||||
};
|
||||
|
||||
const PAGE_HEADERS = {
|
||||
"Cache-Control": "no-store",
|
||||
"X-Frame-Options": "DENY",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
"Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; "
|
||||
+ "form-action 'none'; frame-ancestors 'none'; base-uri 'none'",
|
||||
};
|
||||
|
||||
// A request that changes something must come from the panel's own page.
|
||||
const sameOrigin = limits.originAllowed;
|
||||
|
||||
const tooManyFailures = address => failuresByAddress.blocked(address);
|
||||
const recordFailure = address => failuresByAddress.record(address);
|
||||
|
||||
// `from` is {address, local}; `web` is {send, readJson} from lib/http.js.
|
||||
const handle = async (req, res, url, from, web) => {
|
||||
for (const [name, value] of Object.entries(PAGE_HEADERS)) {
|
||||
res.setHeader(name, value);
|
||||
}
|
||||
const reply = (status, body) => web.send(res, status, body);
|
||||
const route = `${req.method} ${url.pathname.replace(/\/$/, "") || "/admin"}`;
|
||||
|
||||
if (route === "GET /admin") {
|
||||
web.send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "admin.html")), "text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (req.method === "POST" && !sameOrigin(req)) {
|
||||
reply(403, {error: "forbidden"});
|
||||
return;
|
||||
}
|
||||
const body = req.method === "POST" ? await web.readJson(req) : {};
|
||||
|
||||
switch (route) {
|
||||
case "GET /admin/api/state":
|
||||
reply(200, {needsSetup: !hasPassword(), needsSetupCode: !from.local, signedIn: signedIn(req)});
|
||||
return;
|
||||
|
||||
// choosing the first password. whoever is at the server's own machine may;
|
||||
// anyone else must give the code the server printed when it started.
|
||||
case "POST /admin/api/setup": {
|
||||
if (hasPassword()) {
|
||||
reply(409, {error: "The admin password has already been chosen."});
|
||||
return;
|
||||
}
|
||||
if (tooManyFailures(from.key)) {
|
||||
reply(429, {error: "Too many attempts. Try again in a few minutes."});
|
||||
return;
|
||||
}
|
||||
setupCode = setupCode || crypto.randomBytes(5).toString("hex");
|
||||
const code = String(body.code || "").trim().toLowerCase();
|
||||
if (!from.local && (code.length !== setupCode.length || !crypto.timingSafeEqual(Buffer.from(code), Buffer.from(setupCode)))) {
|
||||
recordFailure(from.key);
|
||||
reply(403, {error: "That is not the setup code. It is in the server's output, on the line starting [admin]."});
|
||||
return;
|
||||
}
|
||||
if (!passwordAcceptable(body.password)) {
|
||||
reply(400, {error: `Choose a password of at least ${MIN_PASSWORD_LENGTH} characters.`});
|
||||
return;
|
||||
}
|
||||
storePassword(body.password);
|
||||
setupCode = null;
|
||||
console.log(`[admin] admin password chosen from ${from.address}`);
|
||||
signIn(res);
|
||||
reply(200, {ok: true});
|
||||
return;
|
||||
}
|
||||
|
||||
case "POST /admin/api/login": {
|
||||
if (tooManyFailures(from.key)) {
|
||||
reply(429, {error: "Too many attempts. Try again in a few minutes."});
|
||||
return;
|
||||
}
|
||||
if (!hasPassword() || !passwordMatches(body.password)) {
|
||||
recordFailure(from.key);
|
||||
console.log(`[admin] failed sign-in from ${from.address}`);
|
||||
reply(401, {error: "Wrong password."});
|
||||
return;
|
||||
}
|
||||
console.log(`[admin] signed in from ${from.address}`);
|
||||
signIn(res);
|
||||
reply(200, {ok: true});
|
||||
return;
|
||||
}
|
||||
|
||||
case "POST /admin/api/logout":
|
||||
signOut(req, res);
|
||||
reply(200, {ok: true});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!signedIn(req)) {
|
||||
reply(401, {error: "Sign in first."});
|
||||
return;
|
||||
}
|
||||
|
||||
switch (route) {
|
||||
case "GET /admin/api/overview":
|
||||
reply(200, overview());
|
||||
return;
|
||||
|
||||
case "GET /admin/api/accounts": {
|
||||
const playing = new Map(world.players().map(player => [player.username, player.room || "(between rooms)"]));
|
||||
reply(200, {accounts: accounts.all().map(account => accountRow(account, playing)), badges: badges.BADGES});
|
||||
return;
|
||||
}
|
||||
|
||||
case "GET /admin/api/logs": {
|
||||
const lines = log.recent(Number(url.searchParams.get("after")) || 0, (url.searchParams.get("filter") || "").slice(0, 100));
|
||||
reply(200, {lines, newest: log.count()});
|
||||
return;
|
||||
}
|
||||
|
||||
case "POST /admin/api/account": {
|
||||
const account = accounts.byName(String(body.username || ""));
|
||||
if (!account) {
|
||||
reply(404, {error: "No such account."});
|
||||
return;
|
||||
}
|
||||
const result = act(account, body);
|
||||
if (result.ok) {
|
||||
console.log(`[admin] ${body.action} on "${account.username}"`);
|
||||
}
|
||||
reply(result.ok ? 200 : 400, result);
|
||||
return;
|
||||
}
|
||||
|
||||
case "GET /admin/api/owned": {
|
||||
const account = accounts.byName(url.searchParams.get("username") || "");
|
||||
reply(account ? 200 : 404, account ? ownedBy(account) : {error: "No such account."});
|
||||
return;
|
||||
}
|
||||
|
||||
case "GET /admin/api/bans":
|
||||
reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans()});
|
||||
return;
|
||||
|
||||
// who may use the moderator panel, and what each did there.
|
||||
case "GET /admin/api/moderators":
|
||||
reply(200, {moderators: modpanel.moderators(), log: modlog.recent()});
|
||||
return;
|
||||
|
||||
case "GET /admin/api/banrecord": {
|
||||
const account = accounts.byName(url.searchParams.get("username") || "");
|
||||
reply(account ? 200 : 404, account ? banRecord(account) : {error: "No such account."});
|
||||
return;
|
||||
}
|
||||
|
||||
case "POST /admin/api/address": {
|
||||
const result = addressAct(body);
|
||||
if (result.ok) {
|
||||
console.log(`[admin] address ${body.action}: ${limits.key(body.address)}`);
|
||||
}
|
||||
reply(result.ok ? 200 : 400, result);
|
||||
return;
|
||||
}
|
||||
|
||||
case "GET /admin/api/messages":
|
||||
reply(200, {motd: world.motd(), rooms: world.rooms()});
|
||||
return;
|
||||
|
||||
case "GET /admin/api/debug":
|
||||
reply(200, debugState());
|
||||
return;
|
||||
|
||||
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}`);
|
||||
}
|
||||
reply(result.ok ? 200 : 400, result);
|
||||
return;
|
||||
}
|
||||
|
||||
// the message everyone is shown when they arrive; empty for none.
|
||||
case "POST /admin/api/motd":
|
||||
world.setMotd(String(body.text || ""));
|
||||
console.log("[admin] message of the day changed");
|
||||
reply(200, {ok: world.motd() ? "Players will see this when they arrive." : "There is no message of the day now.", motd: world.motd()});
|
||||
return;
|
||||
|
||||
// A message for everyone playing, or everyone in one room.
|
||||
case "POST /admin/api/announce": {
|
||||
const text = String(body.text || "").trim().slice(0, MAX_ANNOUNCEMENT);
|
||||
if (!text) {
|
||||
reply(400, {error: "The message is empty."});
|
||||
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)`);
|
||||
reply(200, {ok: reached === 1 ? "Shown to 1 player." : `Shown to ${reached} players.`});
|
||||
return;
|
||||
}
|
||||
|
||||
// paintings players made masterpieces of (lib/masterpieces.js): the
|
||||
// ones waiting to be looked at, and the ones on show.
|
||||
case "GET /admin/api/masterpieces":
|
||||
reply(200, {
|
||||
review: masterpieces.needsReview(),
|
||||
waiting: masterpieces.list(masterpieces.PENDING),
|
||||
approved: masterpieces.list(masterpieces.APPROVED),
|
||||
});
|
||||
return;
|
||||
|
||||
case "GET /admin/api/masterpiece": {
|
||||
const picture = masterpieces.image(url.searchParams.get("id") || "");
|
||||
if (!picture) {
|
||||
reply(404, {error: "No such painting."});
|
||||
return;
|
||||
}
|
||||
res.setHeader("Cache-Control", "private, max-age=3600");
|
||||
web.send(res, 200, picture, "image/jpeg");
|
||||
return;
|
||||
}
|
||||
|
||||
case "POST /admin/api/masterpiece": {
|
||||
const id = String(body.id || "");
|
||||
let result;
|
||||
if (body.action === "review") {
|
||||
masterpieces.setNeedsReview(body.on === true);
|
||||
result = {ok: body.on === true ? "New masterpieces wait here until you approve them."
|
||||
: "New masterpieces are approved as they are made. Ones already waiting still wait."};
|
||||
}
|
||||
else if (body.action === "approve") {
|
||||
result = world.approveMasterpiece(id) ? {ok: "Approved. Its maker has been told and can hang it now."} : {error: "No such painting waiting."};
|
||||
}
|
||||
else if (body.action === "reject" || body.action === "remove") {
|
||||
result = world.removeMasterpiece(id)
|
||||
? {ok: "Removed for good. Its maker has been told and given a Masterpiece Token."} : {error: "No such painting."};
|
||||
}
|
||||
else {
|
||||
result = {error: "Unknown action."};
|
||||
}
|
||||
if (result.ok) {
|
||||
console.log(`[admin] masterpiece ${body.action} ${id || body.on === true}`);
|
||||
}
|
||||
reply(result.ok ? 200 : 400, result);
|
||||
return;
|
||||
}
|
||||
|
||||
case "GET /admin/api/reports":
|
||||
reply(200, {reports: reports.list(url.searchParams.get("handled") === "1"), open: reports.openCount()});
|
||||
return;
|
||||
|
||||
case "POST /admin/api/report":
|
||||
if (!reports.markHandled(Number(body.id))) {
|
||||
reply(404, {error: "No such report waiting."});
|
||||
return;
|
||||
}
|
||||
reply(200, {ok: "Marked as dealt with."});
|
||||
return;
|
||||
|
||||
// what players sent from the account page: requests for a new username,
|
||||
// and feedback and bug reports (lib/support.js).
|
||||
case "GET /admin/api/support": {
|
||||
const handled = url.searchParams.get("handled") === "1";
|
||||
reply(200, {names: support.nameRequests(handled), feedback: support.feedback(handled), appeals: staff.appealsFor(handled),
|
||||
open: support.openCount() + bans.openAppeals()});
|
||||
return;
|
||||
}
|
||||
|
||||
case "POST /admin/api/support": {
|
||||
let result;
|
||||
if (body.action === "appealApprove" || body.action === "appealDeny") {
|
||||
result = staff.answerAppeal(body.id, body.action === "appealApprove", body.reply, BY);
|
||||
}
|
||||
else if (body.action === "read") {
|
||||
result = support.markFeedbackRead(body.id) ? {ok: "Marked as read."} : {error: "No such message waiting."};
|
||||
}
|
||||
else if (body.action === "approve" || body.action === "deny") {
|
||||
result = staff.answerNameRequest(body.id, body.action === "approve");
|
||||
}
|
||||
else {
|
||||
result = {error: "Unknown action."};
|
||||
}
|
||||
if (result.ok) {
|
||||
console.log(`[admin] support: ${body.action} ${Number(body.id)}`);
|
||||
}
|
||||
reply(result.ok ? 200 : 400, result);
|
||||
return;
|
||||
}
|
||||
|
||||
case "POST /admin/api/password": {
|
||||
if (!passwordMatches(body.current)) {
|
||||
reply(403, {error: "The current password is wrong."});
|
||||
return;
|
||||
}
|
||||
if (!passwordAcceptable(body.password)) {
|
||||
reply(400, {error: `Choose a password of at least ${MIN_PASSWORD_LENGTH} characters.`});
|
||||
return;
|
||||
}
|
||||
storePassword(body.password);
|
||||
sessions.clear();
|
||||
signIn(res);
|
||||
console.log("[admin] admin password changed");
|
||||
reply(200, {ok: true});
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
reply(404, {error: "not_found"});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {load, handle, PASSWORD_SETTING};
|
||||
@@ -0,0 +1,276 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const config = require("../config.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const epicDens = require("./epicdens.js");
|
||||
const masterpieces = require("./masterpieces.js");
|
||||
const {activeAvatar, isUint} = require("./player.js");
|
||||
|
||||
// parties (client side: PartyManager, PartyPopup, CustomPartyCreatePopup).
|
||||
//
|
||||
// "AJ parties" are the game's own party rooms. the real game opened a few
|
||||
// at a time on a timetable; here every one whose room exists is open all
|
||||
// the time. A party room is called "party<defId>".
|
||||
//
|
||||
// "Jammer parties" are hosted by players: pick one of the party rooms made
|
||||
// for it, a three-word name and the music, pay a diamond, and the party is
|
||||
// listed for everyone until it ends. its room is "pparty<host username>",
|
||||
// which is how the client tells whose party it is in.
|
||||
|
||||
const ROOM_TYPE_PARTY = 5; // RoomManagerWorld: clientInfo.roomType in a party
|
||||
const CURRENCY_DIAMONDS = 3;
|
||||
const HOST_COST = 1; // diamonds; CustomPartyCreatePopup shows this price
|
||||
const NOT_HOSTING = -1;
|
||||
const ALWAYS_OPEN_SECONDS = 86400;
|
||||
// the world map's "AJHQ" button asks for this party: today's showcase den.
|
||||
const PARTY_EPIC_DEN = 36;
|
||||
const PARTY_GALLERY = 47; // PartyManager.PARTY_DEF_MASTERPIECE
|
||||
|
||||
// PartyManager restrictions
|
||||
const RESTRICT_AVATAR = 1;
|
||||
const RESTRICT_PET = 4;
|
||||
const RESTRICT_PET_ONLY = 8;
|
||||
|
||||
// generic lists the party windows ask for.
|
||||
const LIST_CUSTOM_PARTY_DEFS = 370;
|
||||
const LIST_PARTY_MUSIC = 401;
|
||||
// the three name wheels of CustomPartyCreatePopup, as ranges of ids in the
|
||||
// localization defPack ("Epic" ... "Trading", "Birthday" ... "Animal",
|
||||
// "Den" ... "Alliance"). 24138 sits in the first range but is a den item's name.
|
||||
const NAME_LISTS = new Map([
|
||||
[386, [24135, 24161]],
|
||||
[387, [24162, 24185]],
|
||||
[388, [24186, 24210]],
|
||||
]);
|
||||
const NOT_A_NAME = 24138;
|
||||
const MAX_PARTIES = 200;
|
||||
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
|
||||
module.exports = ({enterRoom, findOnline, blocks}) => {
|
||||
// parties being hosted: lowercased host username -> {host, defId, name, music, endsAt}
|
||||
const hosted = new Map();
|
||||
|
||||
const joinable = def => def && def.room && defpacks.roomDef(def.room) && !def.isGame;
|
||||
const ajParties = () => defpacks.partyDefs().filter(def => joinable(def) && !def.isCustom);
|
||||
const customDefs = () => defpacks.partyDefs().filter(def => joinable(def) && def.isCustom);
|
||||
|
||||
const nameList = listId => {
|
||||
const [first, last] = NAME_LISTS.get(Number(listId));
|
||||
return Array.from({length: last - first + 1}, (_, i) => first + i).filter(id => id !== NOT_A_NAME);
|
||||
};
|
||||
const validName = (listId, id) => isUint(id) && nameList(listId).includes(Number(id));
|
||||
|
||||
const partyOf = account => {
|
||||
const party = hosted.get(account.username.toLowerCase());
|
||||
if (party && party.endsAt <= now()) {
|
||||
hosted.delete(account.username.toLowerCase());
|
||||
return null;
|
||||
}
|
||||
return party || null;
|
||||
};
|
||||
|
||||
// seconds the account's own party has left; NOT_HOSTING without one.
|
||||
const timeLeft = account => {
|
||||
const party = partyOf(account);
|
||||
return party ? party.endsAt - now() : NOT_HOSTING;
|
||||
};
|
||||
|
||||
const liveParties = () => [...hosted.values()].filter(party => partyOf(party.host));
|
||||
|
||||
// PartyManager.roomSoireeResponse: [0, reason, ...]; "NA" wrong animal,
|
||||
// "NP" no pet, each with the party def the barrier popup is about.
|
||||
const refuse = (session, reason, defId) => session.sendXt("sj", -1, 0, reason, defId);
|
||||
|
||||
const joinAjParty = (session, defId) => {
|
||||
const def = defpacks.partyDef(defId);
|
||||
if (!joinable(def) || def.isCustom) {
|
||||
refuse(session, "NM", defId);
|
||||
return;
|
||||
}
|
||||
const avatar = activeAvatar(session.account);
|
||||
if (def.restrictions === RESTRICT_AVATAR && !((BigInt(def.avatarDefFlags) >> BigInt(avatar.type - 1)) & 1n)) {
|
||||
refuse(session, "NA", def.id);
|
||||
return;
|
||||
}
|
||||
if ([RESTRICT_PET, RESTRICT_PET_ONLY].includes(def.restrictions) && !avatar.petInvId) {
|
||||
refuse(session, "NP", def.id);
|
||||
return;
|
||||
}
|
||||
const shard = config.shards[0];
|
||||
if (def.id === PARTY_EPIC_DEN) {
|
||||
// A room to each showcase den, so that whoever is inside when the day
|
||||
// turns stays where they are.
|
||||
const den = epicDens.featured();
|
||||
enterRoom(session, `party${def.id}_${den.id}`, den.base, den.name, shard.id, {roomType: ROOM_TYPE_PARTY, secondaryDefId: def.id});
|
||||
return;
|
||||
}
|
||||
// the Masterpiece Gallery hangs players' paintings on its walls: the
|
||||
// room is told which with its properties (PartyManager.setupMasterpiecesInRoom,
|
||||
// which also has to be given the two lists when there are none).
|
||||
enterRoom(session, `party${def.id}`, def.room, defpacks.string(def.titleStrId) || "Party", shard.id,
|
||||
{roomType: ROOM_TYPE_PARTY, secondaryDefId: def.id, ...(def.id === PARTY_GALLERY ? {customData: masterpieces.gallery} : {})});
|
||||
};
|
||||
|
||||
// PartyManager.customPartyJoinResponse: [success, reason]
|
||||
const joinHosted = (session, host) => {
|
||||
const party = host && partyOf(host);
|
||||
if (!party || blocks.either(host, session.account)) {
|
||||
session.sendXt("sjp", -1, 0, party ? "BLK" : "NPP");
|
||||
return;
|
||||
}
|
||||
const def = defpacks.partyDef(party.defId);
|
||||
const room = enterRoom(session, `pparty${host.username}`, def.room, party.name, config.shards[0].id,
|
||||
{roomType: ROOM_TYPE_PARTY, secondaryDefId: def.id, customMusicDef: party.music, partyHost: host});
|
||||
if (room) {
|
||||
session.sendXt("sjp", -1, 1);
|
||||
}
|
||||
};
|
||||
|
||||
// ends a party: everyone in it goes back to the starting room.
|
||||
const end = (party, sendHome) => {
|
||||
hosted.delete(party.host.username.toLowerCase());
|
||||
const hostSession = findOnline(party.host.username);
|
||||
if (hostSession) {
|
||||
// PartyManager.customPartyKillResponse: [diamonds refunded]
|
||||
hostSession.sendXt("spk", -1, 0);
|
||||
}
|
||||
sendHome(`pparty${party.host.username}`);
|
||||
};
|
||||
|
||||
const handlers = {
|
||||
// PartyPopup.partyListResponse: [?, count, (partyDefId, secondsToStart,
|
||||
// secondsToEnd)...]
|
||||
sl(session) {
|
||||
const list = ajParties();
|
||||
session.sendXt("sl", -1, 0, list.length, ...list.flatMap(def => [def.id, 0, ALWAYS_OPEN_SECONDS]));
|
||||
},
|
||||
|
||||
// [partyDefId]
|
||||
sj(session, roomId, [defId]) {
|
||||
joinAjParty(session, defId);
|
||||
},
|
||||
|
||||
// PartyPopup.customPartyListResponse: [success, total, first, pageSize,
|
||||
// count, (hostUuid, "nameId|nameId|nameId", server node, partyDefId,
|
||||
// secondsLeft)...]. the node has to be this server's own address
|
||||
// (SFClient.serverIp) or the client tries to change servers.
|
||||
slp(session) {
|
||||
const list = liveParties().filter(party => !blocks.either(party.host, session.account));
|
||||
session.sendXt("slp", -1, 1, list.length, 0, list.length, list.length,
|
||||
...list.flatMap(party => [party.host.uuid, party.name, config.host, party.defId, party.endsAt - now()]));
|
||||
},
|
||||
|
||||
// CustomPartyCreatePopup: [partyDefId, nameId1, nameId2, nameId3,
|
||||
// musicDenItemId]. PartyManager.customPartyCreateResponse reads
|
||||
// [1, isHost, secondsLeft] or [0, reason].
|
||||
scp(session, roomId, [defId, name1, name2, name3, music]) {
|
||||
const {account} = session;
|
||||
const def = defpacks.partyDef(defId);
|
||||
const fail = reason => session.sendXt("scp", -1, 0, reason);
|
||||
if (!joinable(def) || !def.isCustom || !validName(386, name1) || !validName(387, name2) || !validName(388, name3)
|
||||
|| !defpacks.musicIds().includes(Number(music))) {
|
||||
fail("INV");
|
||||
return;
|
||||
}
|
||||
if (partyOf(account)) {
|
||||
fail("EXISTS");
|
||||
return;
|
||||
}
|
||||
if ((account.currency.diamonds || 0) < HOST_COST) {
|
||||
fail("ND");
|
||||
return;
|
||||
}
|
||||
if (liveParties().length >= MAX_PARTIES) {
|
||||
fail("DIS");
|
||||
return;
|
||||
}
|
||||
account.currency.diamonds -= HOST_COST;
|
||||
accounts.save();
|
||||
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})`);
|
||||
session.sendXt("cu", -1, CURRENCY_DIAMONDS, account.currency.diamonds, 0);
|
||||
session.sendXt("scp", -1, 1, 1, party.endsAt - now());
|
||||
joinHosted(session, account);
|
||||
},
|
||||
|
||||
// PartyManager.customPartyIsHostingResponse: [hostUuid] -> seconds left
|
||||
// of that player's party, -1 when there is none.
|
||||
sphp(session, roomId, [uuid]) {
|
||||
const party = liveParties().find(candidate => candidate.host.uuid === uuid);
|
||||
session.sendXt("sphp", -1, party ? party.endsAt - now() : NOT_HOSTING);
|
||||
},
|
||||
|
||||
// PartyManager.onGetPartyNodeId: [hostUuid] -> [success, hostUuid, node]
|
||||
spn(session, roomId, [uuid]) {
|
||||
const party = liveParties().find(candidate => candidate.host.uuid === uuid);
|
||||
session.sendXt("spn", -1, party ? 1 : 0, uuid, config.host);
|
||||
},
|
||||
|
||||
// [hostUuid]
|
||||
sjp(session, roomId, [uuid]) {
|
||||
const party = liveParties().find(candidate => candidate.host.uuid === uuid);
|
||||
joinHosted(session, party ? party.host : null);
|
||||
},
|
||||
|
||||
// PartyXtCommManager.sendPartyMasterpiece: the paintings on show, as
|
||||
// JSON (BulletinBoard.onMasterpiecesLoaded reads pool[0]); empty for none.
|
||||
sm(session) {
|
||||
const gallery = masterpieces.gallery();
|
||||
session.sendXt("sm", -1, gallery.pool.length ? JSON.stringify(gallery) : "");
|
||||
},
|
||||
};
|
||||
|
||||
// "party12" / "ppartyAlice", from a buddy's "go to": joins it. false when
|
||||
// the name is not a party room's.
|
||||
const joinByRoomName = (session, name) => {
|
||||
const aj = /^party(\d+)(?:_\d+)?$/.exec(name);
|
||||
if (aj) {
|
||||
joinAjParty(session, aj[1]);
|
||||
return true;
|
||||
}
|
||||
if (/^pparty/i.test(name)) {
|
||||
joinHosted(session, accounts.byName(name.slice(6)));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
// parties whose time is up, checked once a minute.
|
||||
const expire = sendHome => {
|
||||
for (const party of [...hosted.values()]) {
|
||||
if (party.endsAt <= now()) {
|
||||
end(party, sendHome);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// generic lists: null when `listId` is not one of the party windows'.
|
||||
const list = listId => {
|
||||
if (Number(listId) === LIST_CUSTOM_PARTY_DEFS) {
|
||||
return customDefs().map(def => def.id);
|
||||
}
|
||||
if (Number(listId) === LIST_PARTY_MUSIC) {
|
||||
return defpacks.musicIds();
|
||||
}
|
||||
return NAME_LISTS.has(Number(listId)) ? nameList(listId) : null;
|
||||
};
|
||||
|
||||
return {
|
||||
handlers,
|
||||
timeLeft,
|
||||
joinByRoomName,
|
||||
expire,
|
||||
list,
|
||||
// the host left the game or was removed: the party goes with them.
|
||||
forget(account, sendHome) {
|
||||
const party = hosted.get(account.username.toLowerCase());
|
||||
if (party) {
|
||||
end(party, sendHome);
|
||||
}
|
||||
},
|
||||
partyOf,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,238 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const achievements = require("./achievements.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const {activeAvatar, isUint} = require("./player.js");
|
||||
|
||||
// pets (client side: PetManager, PetXtCommManager). A pet's species and look
|
||||
// are packed into three integers by PetManager.packPetBits; the species is
|
||||
// the low byte of the first. pets are free.
|
||||
|
||||
const MAX_PETS = 1000;
|
||||
const DEF_PET_FOOD = 1062;
|
||||
const DEF_PET_TOY = 1063;
|
||||
// generic list 432: the personalities a pet can have, as the ids of their
|
||||
// names in the localization defPack ("Adventurous" ... "Zany").
|
||||
const PERSONALITY_LIST = 432;
|
||||
const PERSONALITIES = [25865, 25932];
|
||||
// A pet has ten foods and ten toys it might favour (its def's foodListId and
|
||||
// toyListId). which ten is not in any file: only the lists' ids and all the
|
||||
// foods and toys are. both packs run in the order the lists were made, ten
|
||||
// to a list, so a list is taken to be the ten at its place in that order.
|
||||
// the newest pet's two lists (437, 438) have the lowest ids but come last.
|
||||
const PER_LIST = 10;
|
||||
const LATE_LISTS = [437, 438];
|
||||
// mastery (PetInventory: at 100 the pet may wear its mastery item). it grew
|
||||
// from playing minigames with the pet; here it grows as the pet is walked
|
||||
// from room to room.
|
||||
const MASTERY_FULL = 100;
|
||||
const MASTERY_PER_ROOM = 5;
|
||||
const MASTERY_BITS = 0xF00; // the part of uBits PetInventory writes
|
||||
const SECONDS_TO_HATCH = 259200; // PetManager.hasHatched
|
||||
|
||||
const random = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
|
||||
|
||||
const listOrder = type => {
|
||||
const ids = defpacks.listsOfType(type);
|
||||
return [...ids.filter(id => !LATE_LISTS.includes(id)), ...ids.filter(id => LATE_LISTS.includes(id))];
|
||||
};
|
||||
|
||||
// the foods (DEF_PET_FOOD) or toys (DEF_PET_TOY) of one list, as defs.
|
||||
const favourites = (type, listId) => {
|
||||
const index = listOrder(type).indexOf(Number(listId));
|
||||
const defs = type === DEF_PET_FOOD ? defpacks.petFoodDefs() : defpacks.petToyDefs();
|
||||
return index === -1 ? [] : defs.slice(index * PER_LIST, (index + 1) * PER_LIST);
|
||||
};
|
||||
|
||||
// GenericListXtCommManager.handleMediaResponse: (defId, name string id) pairs.
|
||||
const favouritesList = (type, listId) => favourites(type, listId).flatMap(def => [def.id, def.titleStrId]);
|
||||
|
||||
const personalityList = () => Array.from({length: PERSONALITIES[1] - PERSONALITIES[0] + 1}, (_, i) => PERSONALITIES[0] + i);
|
||||
|
||||
const pick = list => (list.length ? Number(list[random(0, list.length - 1)].id) : 0);
|
||||
|
||||
// what PetCertificatePopup shows: a personality, a favourite toy and food.
|
||||
const giveCharacter = pet => {
|
||||
const def = defpacks.petDef(pet.lBits & 0xFF) || {};
|
||||
// eggs hatch at once here; one bought when they took three days has its
|
||||
// wait ended.
|
||||
if (def.isEgg === "1") {
|
||||
pet.createdAt = Math.min(pet.createdAt, Math.floor(Date.now() / 1000) - SECONDS_TO_HATCH);
|
||||
}
|
||||
pet.personality = pet.personality || random(...PERSONALITIES);
|
||||
pet.toy = pet.toy || pick(favourites(DEF_PET_TOY, def.toyListId));
|
||||
pet.food = pet.food || pick(favourites(DEF_PET_FOOD, def.foodListId));
|
||||
};
|
||||
|
||||
// called when a player walks into a room with a pet out.
|
||||
const walked = account => {
|
||||
const pet = account.pets.find(candidate => candidate.inv === activeAvatar(account).petInvId);
|
||||
if (pet && (pet.mastery || 0) < MASTERY_FULL) {
|
||||
pet.mastery = Math.min(MASTERY_FULL, (pet.mastery || 0) + MASTERY_PER_ROOM);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = ({others, findOnline, petFields}) => {
|
||||
// PetManager.onPetCreateResponse: [success, newAmount, currencyType, invIdx,
|
||||
// lBits, uBits, eBits, name, createdTs, personality, toy, food, ?]
|
||||
const create = (session, [lBits, uBits, eBits, name1, name2]) => {
|
||||
const {account} = session;
|
||||
if (![lBits, uBits, eBits, name1, name2].every(isUint) || !defpacks.petIds().includes(Number(lBits) & 0xFF)
|
||||
|| account.pets.length >= MAX_PETS) {
|
||||
session.sendXt("pc", -1, 0);
|
||||
return;
|
||||
}
|
||||
const isEgg = (defpacks.petDef(Number(lBits) & 0xFF) || {}).isEgg === "1";
|
||||
const pet = {
|
||||
inv: account.nextInv++,
|
||||
lBits: Number(lBits),
|
||||
uBits: Number(uBits),
|
||||
eBits: Number(eBits),
|
||||
// two localization ids, read by LocalizationManager.translatePetName.
|
||||
// an egg is named when it has hatched (EggPetHatchedPopup, "pn").
|
||||
name: isEgg ? "" : `${name1}|${name2}`,
|
||||
// an egg hatches three days after this (PetManager.hasHatched), so
|
||||
// an egg is made that much in the past: it hatches at once.
|
||||
createdAt: Math.floor(Date.now() / 1000) - (isEgg ? SECONDS_TO_HATCH : 0),
|
||||
mastery: 0,
|
||||
};
|
||||
giveCharacter(pet);
|
||||
account.pets.push(pet);
|
||||
achievements.set(account, achievements.VARS.pets, Math.max(Number(account.userVars[achievements.VARS.pets]) || 0, account.pets.length));
|
||||
accounts.save();
|
||||
session.sendXt("pc", -1, 1, account.currency.gems || 0, 0, pet.inv, ...petFields(pet), 0);
|
||||
};
|
||||
|
||||
const ownPet = (account, invIdx) => account.pets.find(candidate => candidate.inv === Number(invIdx));
|
||||
|
||||
const handlers = {
|
||||
// PetManager.onPetListResponse: [found, username, count, (invIdx,
|
||||
// createdTs, name, lBits, uBits, eBits, mastery, personality, toy, food,
|
||||
// denStoreInvId)...]
|
||||
pl(session, roomId, [username]) {
|
||||
// anybody's, playing or not: a player's card shows their pets.
|
||||
const owner = accounts.byName(username);
|
||||
const target = findOnline(username);
|
||||
const pets = owner ? owner.pets : [];
|
||||
session.sendXt("pl", -1, 1, username, pets.length,
|
||||
...pets.flatMap(pet => [pet.inv, pet.createdAt, pet.name, pet.lBits, pet.uBits, pet.eBits,
|
||||
pet.mastery || 0, pet.personality || 0, pet.toy || 0, pet.food || 0, 0]));
|
||||
if (target === session) {
|
||||
// PetManager.unlockedPets: a bit per pet species (bit = id - 1). the
|
||||
// pet picker dereferences this, so it must arrive before the picker
|
||||
// opens; every species is unlocked.
|
||||
const words = Math.ceil(Math.max(...defpacks.petIds()) / 32);
|
||||
session.sendXt("pu", -1, Array(words).fill(4294967295).join(","));
|
||||
}
|
||||
},
|
||||
|
||||
// PetCreator: [shopId, lBits, uBits, eBits, nameId1, nameId2, fromRedemption]
|
||||
pc(session, roomId, params) {
|
||||
create(session, params.slice(1));
|
||||
},
|
||||
|
||||
// same, for diamond-shop pets: [shopId, diamondDefId, lBits, uBits, eBits, nameId1, nameId2, fromRedemption]
|
||||
pb(session, roomId, params) {
|
||||
create(session, params.slice(2));
|
||||
},
|
||||
|
||||
// [petInvIdx], 0 = walk without a pet. PetManager.onPetSwitchResponse reads
|
||||
// the pet's inventory id for its owner and the pet's look for everyone else.
|
||||
ps(session, roomId, [invIdx]) {
|
||||
const {account} = session;
|
||||
const pet = account.pets.find(candidate => candidate.inv === Number(invIdx)) || null;
|
||||
if (!pet && invIdx !== "0") {
|
||||
session.sendXt("ps", -1, 0);
|
||||
return;
|
||||
}
|
||||
activeAvatar(account).petInvId = pet ? pet.inv : 0;
|
||||
accounts.save();
|
||||
const messageRoom = session.room ? session.room.id : -1;
|
||||
session.sendXt("ps", messageRoom, 1, session.id, pet ? pet.inv : 0);
|
||||
if (session.pos) {
|
||||
for (const other of others(session)) {
|
||||
other.sendXt("ps", messageRoom, 1, session.id, ...petFields(pet));
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// PetManager.onPetDismissResponse: [success, invIdx]
|
||||
pd(session, roomId, [invIdx]) {
|
||||
const {account} = session;
|
||||
const pet = account.pets.find(candidate => candidate.inv === Number(invIdx));
|
||||
if (!pet) {
|
||||
session.sendXt("pd", -1, 0, invIdx);
|
||||
return;
|
||||
}
|
||||
account.pets = account.pets.filter(candidate => candidate !== pet);
|
||||
for (const avatar of account.avatars) {
|
||||
if (avatar.petInvId === pet.inv) {
|
||||
avatar.petInvId = 0;
|
||||
}
|
||||
}
|
||||
accounts.save();
|
||||
session.sendXt("pd", -1, 1, pet.inv);
|
||||
},
|
||||
|
||||
// PetInventory: [masteryItem, petInvIdx] puts the pet's mastery item on
|
||||
// or off, once its mastery is full. the reply (onPetMasteryResponse) is
|
||||
// [success, invIdx, lBits, uBits, eBits].
|
||||
pm(session, roomId, [masteryItem, invIdx]) {
|
||||
const {account} = session;
|
||||
const pet = ownPet(account, invIdx);
|
||||
const item = Number(masteryItem);
|
||||
if (!pet || !Number.isInteger(item) || item < 0 || item > 15 || (pet.mastery || 0) < MASTERY_FULL) {
|
||||
session.sendXt("pm", -1, 0);
|
||||
return;
|
||||
}
|
||||
pet.uBits = ((pet.uBits & ~MASTERY_BITS) | (item << 8)) >>> 0;
|
||||
accounts.save();
|
||||
session.sendXt("pm", -1, 1, pet.inv, pet.lBits, pet.uBits, pet.eBits);
|
||||
if (pet.inv === activeAvatar(account).petInvId && session.pos) {
|
||||
for (const other of others(session)) {
|
||||
other.sendXt("ps", session.room.id, 1, session.id, ...petFields(pet));
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// EggPetHatchedPopup: [petInvIdx, nameId1, nameId2] names a pet hatched
|
||||
// from an egg. PetManager.onPetEggNameResponse: [success, invIdx, name].
|
||||
pn(session, roomId, [invIdx, name1, name2]) {
|
||||
const pet = ownPet(session.account, invIdx);
|
||||
const def = pet && defpacks.petDef(pet.lBits & 0xFF);
|
||||
if (!pet || ![name1, name2].every(isUint) || pet.name || !def || def.isEgg !== "1"
|
||||
|| pet.createdAt + SECONDS_TO_HATCH > Math.floor(Date.now() / 1000)) {
|
||||
session.sendXt("pn", -1, 0, invIdx, pet ? pet.name : "");
|
||||
return;
|
||||
}
|
||||
pet.name = `${name1}|${name2}`;
|
||||
accounts.save();
|
||||
session.sendXt("pn", -1, 1, pet.inv, pet.name);
|
||||
},
|
||||
|
||||
// the pet salon minigame (MicroPetSalon via MinigameManager.sendPetItemRequest):
|
||||
// [a, b, c, enviroType], the pet in use's three accessories, which
|
||||
// PetManager.packPetBits keeps in bits 12 to 23 of uBits. the reply
|
||||
// (PetManager.onPetItemsResponse) is [success, gems, invIdx, lBits, uBits, eBits].
|
||||
pi(session, roomId, [a, b, c]) {
|
||||
const {account} = session;
|
||||
const pet = ownPet(account, activeAvatar(account).petInvId);
|
||||
const parts = [a, b, c].map(Number);
|
||||
if (!pet || !parts.every(part => Number.isInteger(part) && part >= 0 && part <= 15)) {
|
||||
session.sendXt("pi", -1, 0);
|
||||
return;
|
||||
}
|
||||
pet.uBits = ((pet.uBits & 0xFFF) | (parts[0] << 12) | (parts[1] << 16) | (parts[2] << 20)) >>> 0;
|
||||
accounts.save();
|
||||
session.sendXt("pi", -1, 1, account.currency.gems || 0, pet.inv, pet.lBits, pet.uBits, pet.eBits);
|
||||
if (session.pos) {
|
||||
for (const other of others(session)) {
|
||||
other.sendXt("ps", session.room.id, 1, session.id, ...petFields(pet));
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
return {handlers, walked, giveCharacter, favouritesList, personalityList, PERSONALITY_LIST};
|
||||
};
|
||||
@@ -0,0 +1,100 @@
|
||||
"use strict";
|
||||
|
||||
const defpacks = require("./defpacks.js");
|
||||
// accessors over an account's animals, pets and items (shape: accounts.js).
|
||||
|
||||
// SbiConstants.CURRENCY_NAMES; an item's currencyType indexes into this.
|
||||
const CURRENCIES = ["gems", "tickets", "orbs", "diamonds", "straw", "bamboo", "wood", "stone", "silver", "gold", "gemstone", "ecoCredits"];
|
||||
const CURRENCY_DIAMONDS = 3;
|
||||
|
||||
// what a diamond def's refId points at (DiamondItem.isAccessory and friends).
|
||||
const DIAMOND_TYPES = {clothing: "0", denItem: "1", pet: "2", avatar: "3", denRoom: "4", customAvatar: "5"};
|
||||
|
||||
// shops send a diamond def id instead of the item's own def id when the item
|
||||
// is priced in diamonds. resolves either form to {defId, cost, currencyType},
|
||||
// with `ownPrice(defId)` giving {cost, currencyType} for an ordinary item; null
|
||||
// when the diamond def does not exist or is not of the expected kind.
|
||||
const resolvePurchase = (defId, isDiamond, kind, ownPrice) => {
|
||||
if (!isDiamond) {
|
||||
return {defId: Number(defId), ...ownPrice(defId)};
|
||||
}
|
||||
const diamond = defpacks.diamondDef(defId);
|
||||
return diamond && diamond.type === DIAMOND_TYPES[kind]
|
||||
? {defId: Number(diamond.refId), cost: Number(diamond.cost), currencyType: CURRENCY_DIAMONDS}
|
||||
: null;
|
||||
};
|
||||
|
||||
const activeAvatar = account => account.avatars.find(avatar => avatar.perUserAvId === account.activeAvatar) || account.avatars[0];
|
||||
|
||||
// the requested animal, or the one in use when the id is unknown.
|
||||
const avatarById = (account, perUserAvId) =>
|
||||
account.avatars.find(avatar => avatar.perUserAvId === Number(perUserAvId)) || activeAvatar(account);
|
||||
|
||||
const activePet = account => account.pets.find(pet => pet.inv === activeAvatar(account).petInvId) || null;
|
||||
|
||||
const wornItems = (account, avatar) => account.items.filter(item => item.on.includes(avatar.avInvId));
|
||||
|
||||
// item.EquippedAvatars: comma-separated 32-bit words, one bit per avInvId of
|
||||
// an animal wearing the item.
|
||||
const equippedBits = item => {
|
||||
const words = [0];
|
||||
for (const avInvId of item.on) {
|
||||
const word = avInvId >>> 5;
|
||||
while (words.length <= word) {
|
||||
words.push(0);
|
||||
}
|
||||
words[word] = (words[word] | (1 << (avInvId & 31))) >>> 0;
|
||||
}
|
||||
return words.join(",");
|
||||
};
|
||||
|
||||
// how much an account may hold, as the patched client counts
|
||||
// (shop.ShopManager), and how many pieces one animal may wear at once: the
|
||||
// seven places clothes go, three to a place, and a few to spare. everyone in
|
||||
// a room is sent what each animal there wears.
|
||||
const MAX_ITEMS = 5000;
|
||||
const MAX_DEN_ITEMS = 5000;
|
||||
const MAX_WORN = 24;
|
||||
// has the account room for `count` more? `kind` is "items" (clothing) or "denItems".
|
||||
const hasRoom = (account, kind, count = 1) => account[kind].length + count <= (kind === "items" ? MAX_ITEMS : MAX_DEN_ITEMS);
|
||||
|
||||
// adds a clothing item to an account's inventory (the caller saves); null
|
||||
// when the inventory is full.
|
||||
const addClothing = (account, defId, color) => {
|
||||
if (!hasRoom(account, "items")) {
|
||||
return null;
|
||||
}
|
||||
const item = {inv: account.nextInv++, def: Number(defId), color: Number(color), on: []};
|
||||
account.items.push(item);
|
||||
return item;
|
||||
};
|
||||
|
||||
// ItemXtCommManager.itemsChangedListResponse ("2" = inventory changed): tells
|
||||
// a connected player about a new item. [type, inUse, perUserAvId, username,
|
||||
// color, addedCount, removedCount, (invIdx, defId)..., removedInvIdx...]
|
||||
const sendClothingAdded = (session, item) => {
|
||||
if (!item) {
|
||||
return; // the inventory was full
|
||||
}
|
||||
session.sendXt("il", -1, 2, 0, activeAvatar(session.account).perUserAvId, session.account.username, item.color, 1, 0, item.inv, item.def);
|
||||
};
|
||||
|
||||
// the same message, for items that left the inventory (one inventory id or
|
||||
// a list of them).
|
||||
const sendClothingRemoved = (session, inv) => {
|
||||
const gone = [].concat(inv);
|
||||
session.sendXt("il", -1, 2, 0, activeAvatar(session.account).perUserAvId, session.account.username, 0, 0, gone.length, ...gone);
|
||||
};
|
||||
|
||||
// what goes in the "days since last login" field of a player's card. the
|
||||
// patched client (swf-src/BuddyCard.as) takes it as the time the player was
|
||||
// last seen, in seconds, to show as a time of day and a date; -2 is "online
|
||||
// now" and -1 "unknown", which the official client showed as "More than 30
|
||||
// Days".
|
||||
const LAST_SEEN_ONLINE = -2;
|
||||
const LAST_SEEN_UNKNOWN = -1;
|
||||
const lastSeenField = (account, isOnline) => (isOnline ? LAST_SEEN_ONLINE : account.lastSeen || account.lastLogin || LAST_SEEN_UNKNOWN);
|
||||
|
||||
const isUint = text => /^\d{1,10}$/.test(text) && Number(text) <= 0xFFFFFFFF;
|
||||
|
||||
module.exports = {MAX_ITEMS, MAX_DEN_ITEMS, MAX_WORN, hasRoom, CURRENCIES, DIAMOND_TYPES, resolvePurchase, activeAvatar, avatarById, activePet, wornItems, equippedBits, addClothing, sendClothingAdded, sendClothingRemoved, lastSeenField, isUint};
|
||||
@@ -0,0 +1,97 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const limits = require("./limits.js");
|
||||
|
||||
// player reports (client side: ReportAPlayer, FacilitatorXtCommManager). A
|
||||
// report is who, about whom, one of the game's fixed reasons, and what the
|
||||
// reporter typed about it (the patched report window has a text box; the
|
||||
// game's own had none). they wait in the admin panel's Reports page.
|
||||
|
||||
const SCHEMA = `
|
||||
CREATE TABLE IF NOT EXISTS reports (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
created_at INTEGER NOT NULL,
|
||||
reporter TEXT NOT NULL,
|
||||
target TEXT NOT NULL,
|
||||
reason INTEGER NOT NULL,
|
||||
detail TEXT NOT NULL,
|
||||
context TEXT NOT NULL,
|
||||
room TEXT NOT NULL,
|
||||
handled_at INTEGER
|
||||
);
|
||||
`;
|
||||
|
||||
// ReportAPlayer.reasonIdForReason, in the game's own words.
|
||||
const REASONS = {
|
||||
1: "Being a bully",
|
||||
2: "Bad words",
|
||||
3: "Personal info",
|
||||
4: "Safety",
|
||||
5: "Inappropriate den",
|
||||
6: "Scamming",
|
||||
7: "Inappropriate behavior",
|
||||
13: "Inappropriate username",
|
||||
14: "Inappropriate Jam-A-Gram",
|
||||
15: "Inappropriate Jammer Wall post",
|
||||
16: "Inappropriate Masterpiece",
|
||||
};
|
||||
const MAX_DETAIL = 200;
|
||||
const MAX_CONTEXT = 4000;
|
||||
const MAX_OPEN = 5000; // reports waiting; further ones are dropped
|
||||
const MERGE_SECONDS = 10;
|
||||
|
||||
const perTenMinutes = limits.limiter(10, 600000);
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
const clean = (text, max) => String(text === undefined ? "" : text).replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, " ").trim().slice(0, max);
|
||||
|
||||
const load = () => accounts.database().exec(SCHEMA);
|
||||
|
||||
const openCount = () => accounts.database().prepare("SELECT COUNT(*) AS count FROM reports WHERE handled_at IS NULL").get().count;
|
||||
|
||||
// files a report. the patched client sends what was typed in a message of
|
||||
// its own just before the game's usual report message, so a second report
|
||||
// by the same player about the same player within a few seconds is the
|
||||
// same one: its typed text is kept and nothing new is filed.
|
||||
// returns false when the reporter has sent too many.
|
||||
const file = ({reporter, target, reason, detail = "", context = "", room = ""}) => {
|
||||
const db = accounts.database();
|
||||
const recent = db.prepare("SELECT id, detail FROM reports WHERE reporter = ? AND target = ? AND created_at >= ? ORDER BY id DESC LIMIT 1")
|
||||
.get(reporter, target, now() - MERGE_SECONDS);
|
||||
if (recent) {
|
||||
if (!recent.detail && detail) {
|
||||
db.prepare("UPDATE reports SET detail = ? WHERE id = ?").run(clean(detail, MAX_DETAIL), recent.id);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (!perTenMinutes.allow(reporter.toLowerCase()) || openCount() >= MAX_OPEN) {
|
||||
return false;
|
||||
}
|
||||
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}`})`);
|
||||
return true;
|
||||
};
|
||||
|
||||
const row = report => ({
|
||||
id: report.id,
|
||||
createdAt: report.created_at,
|
||||
reporter: report.reporter,
|
||||
target: report.target,
|
||||
reason: REASONS[report.reason] || `Reason ${report.reason}`,
|
||||
detail: report.detail,
|
||||
context: report.context,
|
||||
room: report.room,
|
||||
handledAt: report.handled_at,
|
||||
});
|
||||
|
||||
// reports waiting, oldest first; or with `handled`, the latest dealt with.
|
||||
const list = (handled = false) => accounts.database()
|
||||
.prepare(handled
|
||||
? "SELECT * FROM reports WHERE handled_at IS NOT NULL ORDER BY handled_at DESC LIMIT 200"
|
||||
: "SELECT * FROM reports WHERE handled_at IS NULL ORDER BY id LIMIT 500")
|
||||
.all().map(row);
|
||||
|
||||
const markHandled = id => accounts.database().prepare("UPDATE reports SET handled_at = ? WHERE id = ? AND handled_at IS NULL").run(now(), id).changes > 0;
|
||||
|
||||
module.exports = {load, file, list, markHandled, openCount, MAX_DETAIL};
|
||||
@@ -0,0 +1,27 @@
|
||||
# Names nobody may sign up with: the ones that would pass for whoever runs
|
||||
# the game. One to a line; capitals, spaces, dots and dashes do not matter.
|
||||
#
|
||||
# A username is refused when it is one of these, or when one of its words is
|
||||
# ("Admin Bob", "AJHQ-Liza"): never for merely containing one ("Badminton"
|
||||
# is fine). The names of the Epic Dens are refused too (they are how a den
|
||||
# is asked for), and so is anything in public/filter/level1.txt. Read again
|
||||
# whenever it changes. The admin panel's own rename is not held to this.
|
||||
|
||||
ajhq
|
||||
aj hq
|
||||
animal jam hq
|
||||
animaljam
|
||||
animal jam
|
||||
wildworks
|
||||
wild works
|
||||
moderator
|
||||
mod
|
||||
mods
|
||||
admin
|
||||
admins
|
||||
administrator
|
||||
staff
|
||||
owner
|
||||
developer
|
||||
support
|
||||
official
|
||||
@@ -0,0 +1,52 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const config = require("../config.js");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
// how long the records about players are kept, as the privacy policy says
|
||||
// (public/privacy.html): change one and change the other. run at start and
|
||||
// once a day. chat has its own, shorter time (lib/chatlog.js), and sign-in
|
||||
// histories are trimmed as they are written (lib/accounts.js).
|
||||
|
||||
const DAY_SECONDS = 86400;
|
||||
const YEAR_DAYS = 365;
|
||||
// the game clients' error reports (data/client-errors.log, lib/http.js) are
|
||||
// emptied this often, so nothing in the file is older.
|
||||
const ERROR_REPORT_DAYS = 30;
|
||||
const ERRORS_CLEARED = "client_errors_cleared";
|
||||
|
||||
const sweep = () => {
|
||||
const db = accounts.database();
|
||||
const before = Math.floor(Date.now() / 1000) - YEAR_DAYS * DAY_SECONDS;
|
||||
// reports, feedback and username requests, a year after they were dealt with.
|
||||
db.prepare("DELETE FROM reports WHERE handled_at IS NOT NULL AND handled_at < ?").run(before);
|
||||
db.prepare("DELETE FROM feedback WHERE handled_at IS NOT NULL AND handled_at < ?").run(before);
|
||||
db.prepare("DELETE FROM name_requests WHERE handled_at IS NOT NULL AND handled_at < ?").run(before);
|
||||
// what moderators did, after a year.
|
||||
db.prepare("DELETE FROM mod_log WHERE at < ?").run(before);
|
||||
// the record of bans: while the account exists, and a year past it (or
|
||||
// for a line about an address, a year).
|
||||
db.prepare("DELETE FROM ban_log WHERE at < ? AND (account_id IS NULL OR account_id NOT IN (SELECT id FROM accounts))").run(before);
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const cleared = Number(accounts.setting(ERRORS_CLEARED)) || 0;
|
||||
if (cleared === 0) {
|
||||
accounts.setSetting(ERRORS_CLEARED, String(now));
|
||||
}
|
||||
else if (now - cleared > ERROR_REPORT_DAYS * DAY_SECONDS) {
|
||||
try {
|
||||
fs.truncateSync(path.join(config.dataDir, "client-errors.log"));
|
||||
}
|
||||
catch (err) {
|
||||
}
|
||||
accounts.setSetting(ERRORS_CLEARED, String(now));
|
||||
}
|
||||
};
|
||||
|
||||
const load = () => {
|
||||
sweep();
|
||||
setInterval(sweep, DAY_SECONDS * 1000).unref();
|
||||
};
|
||||
|
||||
module.exports = {load, sweep, YEAR_DAYS};
|
||||
@@ -0,0 +1,101 @@
|
||||
"use strict";
|
||||
|
||||
const zlib = require("zlib");
|
||||
const amf3 = require("./amf3.js");
|
||||
const cdn = require("./cdn.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
|
||||
// what a room's own file says about it: its name ("Jam Mart Clothing"),
|
||||
// which the client shows in the corner of the screen, and which shops stand
|
||||
// in it. the room defPack has neither, and a shop's title is not in any
|
||||
// defPack at all: the official server sent both along. the file is the
|
||||
// same one the client loads to draw the room (roomDefs/<path>.xroom: zlib,
|
||||
// then AMF3), so reading it here costs no extra download once anyone has
|
||||
// been in the room.
|
||||
|
||||
// what the room editor left in files nobody named.
|
||||
const UNNAMED = "Display Name";
|
||||
// rooms whose file has no name and whose path does not spell it either.
|
||||
const NAMES = new Map([
|
||||
["jamaa_township.room_diamonds", "Diamond Shop"],
|
||||
["jamaa_township.room_alphahq", "Alpha Headquarters"],
|
||||
["oceans.deep_sea", "Deep Blue"],
|
||||
["aussie.room_main", "Kimbara Outback"],
|
||||
["aussie.room_aushop", "Outback Imports"],
|
||||
["aussie.room_hos", "Medical Center"],
|
||||
]);
|
||||
const VOLUME_SHOP = 12; // ActorVolume.type: clicking it opens generic list `typeDefId`
|
||||
|
||||
const rooms = new Map(); // "jamaa_township.clothes_shop" -> {name, shops: Set of list ids}
|
||||
const loading = new Map();
|
||||
|
||||
const filePath = base => cdn.hashedPath(`roomDefs/${base.replace(/\./g, "/")}.xroom`);
|
||||
|
||||
const parse = body => {
|
||||
const room = amf3.decode(zlib.inflateSync(body));
|
||||
const settings = (room.actors.ActorSettings || [])[0] || {};
|
||||
const volumes = room.actors.ActorVolume || [];
|
||||
return {
|
||||
name: typeof settings.name === "string" && settings.name.trim() !== UNNAMED ? settings.name.trim() : "",
|
||||
shops: new Set(volumes.filter(volume => Number(volume.type) === VOLUME_SHOP).map(volume => Number(volume.typeDefId))),
|
||||
};
|
||||
};
|
||||
|
||||
const remember = (base, body) => {
|
||||
try {
|
||||
rooms.set(base, body ? parse(body) : {name: "", shops: new Set()});
|
||||
}
|
||||
catch (err) {
|
||||
rooms.set(base, {name: "", shops: new Set()});
|
||||
}
|
||||
};
|
||||
|
||||
// reads the room's file, downloading it if nobody has been there yet.
|
||||
// nothing waits on this: the first player ever to enter a room gets the
|
||||
// fallback name below, everyone after them the real one.
|
||||
const ensure = base => {
|
||||
if (rooms.has(base) || loading.has(base)) {
|
||||
return;
|
||||
}
|
||||
loading.set(base, cdn.get(filePath(base))
|
||||
.then(body => remember(base, body), () => {})
|
||||
.finally(() => loading.delete(base)));
|
||||
};
|
||||
|
||||
// at start: every room whose file is already in the cache.
|
||||
const preload = async () => {
|
||||
for (const path of defpacks.roomPaths()) {
|
||||
const base = path.replace(/\//g, ".");
|
||||
const body = await cdn.cached(filePath(base));
|
||||
if (body) {
|
||||
remember(base, body);
|
||||
}
|
||||
}
|
||||
console.log(`[rooms] names of ${rooms.size} rooms read from the cache`);
|
||||
};
|
||||
|
||||
// A name made from the path, for a room not read yet or left unnamed:
|
||||
// "jamaa_township.room_main" -> "Jamaa Township", "oceans.crystal_reef" ->
|
||||
// "Crystal Reef". the seasonal versions of a land ("room_main_summer") are
|
||||
// that land.
|
||||
const titleCase = text => text.split("_").filter(Boolean).map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
|
||||
const fallbackName = base => {
|
||||
const [folder, room = ""] = base.split(".");
|
||||
return NAMES.get(base) || (/^room_main|^main_room|^$/.test(room) ? titleCase(folder) : titleCase(room.replace(/^room_/, "")));
|
||||
};
|
||||
|
||||
const name = base => (rooms.get(base) || {}).name || fallbackName(base);
|
||||
|
||||
// the title of a shop opened in this room, as the id of a localization
|
||||
// string (Shop.gotItemListCallback), or "" to leave the shop window's own.
|
||||
// A shop's title was its room's name ("Jam Mart Clothing", "Epic Wonders");
|
||||
// a shop standing in a land's main room has no name of its own to be found.
|
||||
const shopTitle = (base, listId) => {
|
||||
const room = rooms.get(base);
|
||||
if (!room || !room.shops.has(Number(listId)) || /\.room_main/.test(base)) {
|
||||
return "";
|
||||
}
|
||||
return defpacks.stringId(name(base)) || "";
|
||||
};
|
||||
|
||||
module.exports = {ensure, preload, name, shopTitle};
|
||||
@@ -0,0 +1,103 @@
|
||||
"use strict";
|
||||
|
||||
const history = require("./sale-dates.json");
|
||||
|
||||
// when shop items are on sale. the client decides that by itself: a shop
|
||||
// drops whatever its def's availabilityStartTime..availabilityEndTime does
|
||||
// not cover today (GenericListXtCommManager.filterIitems), tags what
|
||||
// started in the last ten days as new and counts down to the end. so the
|
||||
// defs are what to change, and they are re-stamped here before a client
|
||||
// gets them.
|
||||
//
|
||||
// the official game rewrote an item's window each time the item came back,
|
||||
// and lib/sale-dates.json has every window found in the builds the CDN
|
||||
// still serves (tools/sale-history.js). here each window comes round again
|
||||
// every year on the same dates: an item whose window, moved to this year,
|
||||
// covers today is stamped with it; any other gets the next one coming, and
|
||||
// stays hidden until then. items with no window in the file are left as
|
||||
// their def has them.
|
||||
|
||||
const DAY = 86400;
|
||||
// sold for most of a year at a stretch: not seasonal, so always in stock.
|
||||
const ALWAYS_DAYS = 330;
|
||||
|
||||
// [start, end] in seconds for the def to carry at `now`, or null to leave it.
|
||||
const windowFor = (windows, now) => {
|
||||
if (!windows || windows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (windows.some(([startDay, endDay]) => endDay - startDay >= ALWAYS_DAYS)) {
|
||||
return [0, 0];
|
||||
}
|
||||
const year = new Date(now * 1000).getUTCFullYear();
|
||||
let current = null;
|
||||
let next = null;
|
||||
for (const [startDay, endDay] of windows) {
|
||||
const first = new Date(startDay * DAY * 1000);
|
||||
for (const candidate of [year - 1, year, year + 1]) {
|
||||
const start = Date.UTC(candidate, first.getUTCMonth(), first.getUTCDate()) / 1000;
|
||||
const end = start + (endDay - startDay) * DAY;
|
||||
if (start <= now && now <= end) {
|
||||
current = !current || end > current[1] ? [start, end] : current;
|
||||
}
|
||||
else if (start > now) {
|
||||
next = !next || start < next[0] ? [start, end] : next;
|
||||
}
|
||||
}
|
||||
}
|
||||
return current || next;
|
||||
};
|
||||
|
||||
// A testing switch (the admin panel's Debug page): with it on, nothing has
|
||||
// sale dates at all, so every item shows wherever it is listed. kept in memory; a restart turns it off.
|
||||
let everythingOnSale = false;
|
||||
|
||||
// whether a seasonal item is in its season at `now`: it has sale dates, none
|
||||
// of them makes it a year-round one, and one of them, moved to this year,
|
||||
// covers today. (With the switch above on, any seasonal item is.)
|
||||
const inSeason = (kind, id, now = Date.now() / 1000) => {
|
||||
const windows = (history[kind] || {})[String(id)];
|
||||
if (!windows || windows.length === 0 || windows.some(([startDay, endDay]) => endDay - startDay >= ALWAYS_DAYS)) {
|
||||
return false;
|
||||
}
|
||||
const [start, end] = windowFor(windows, now);
|
||||
return everythingOnSale || (start <= now && now <= end);
|
||||
};
|
||||
|
||||
// re-stamps the rows of a defPack (`kind`: clothing, denItems or diamond) in
|
||||
// place. returns how many are on sale at `now` thanks to it.
|
||||
const stamp = (kind, pack, now = Date.now() / 1000) => {
|
||||
const windows = history[kind] || {};
|
||||
let onSale = 0;
|
||||
for (const def of Object.values(pack)) {
|
||||
const window = everythingOnSale ? [0, 0] : windowFor(windows[String(def.id)], now);
|
||||
if (window) {
|
||||
def.availabilityStartTime = String(window[0]);
|
||||
def.availabilityEndTime = String(window[1]);
|
||||
onSale += window[0] <= now && (window[1] === 0 || now <= window[1]) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
return onSale;
|
||||
};
|
||||
|
||||
const always = pack => {
|
||||
for (const def of Object.values(pack)) {
|
||||
def.availabilityStartTime = "0";
|
||||
def.availabilityEndTime = "0";
|
||||
}
|
||||
};
|
||||
|
||||
// the day the stamps were made for; a new day needs new ones.
|
||||
const today = (now = Date.now() / 1000) => Math.floor(now / DAY);
|
||||
|
||||
module.exports = {
|
||||
stamp,
|
||||
always,
|
||||
today,
|
||||
windowFor,
|
||||
inSeason,
|
||||
everythingOnSale: () => everythingOnSale,
|
||||
setEverythingOnSale(on) {
|
||||
everythingOnSale = on === true;
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,279 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const net = require("net");
|
||||
const tls = require("tls");
|
||||
const config = require("../config.js");
|
||||
const limits = require("./limits.js");
|
||||
|
||||
// SmartFoxServer 1.x wire protocol as spoken by the client's SmartFoxClient:
|
||||
// messages are UTF-8, terminated by a NUL byte, and come in three flavours
|
||||
// told apart by their first character:
|
||||
// <msg t='sys'><body action='..' r='roomId'>..</body></msg> system (XML)
|
||||
// %xt%<ext>%<cmd>%<roomId>%<param>%...% extension (raw)
|
||||
// {"t":"xt","b":{...}} extension (JSON)
|
||||
|
||||
const POLICY = '<cross-domain-policy><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>';
|
||||
const MAX_MESSAGE = 64 * 1024;
|
||||
const RATE_WINDOW_MS = 10000;
|
||||
const MAX_BACKLOG = 4 * 1024 * 1024;
|
||||
const MAX_ERRORS_PER_WINDOW = 20;
|
||||
// the Create Account screens are done in a few minutes; a guest connection
|
||||
// does not get to stay for as long as it keeps sending something.
|
||||
const SIGNUP_LIFETIME_MS = 5 * 60000;
|
||||
|
||||
// the login message carries the account's login token; keep it out of the log.
|
||||
const forLog = message => message.replace(/(<pword><!\[CDATA\[)[\s\S]*?(\]\]>)/, "$1(hidden)$2");
|
||||
|
||||
const connections = new Map(); // remote address -> open sockets
|
||||
|
||||
let nextUserId = 1;
|
||||
|
||||
class Session {
|
||||
constructor(socket) {
|
||||
this.socket = socket;
|
||||
this.id = nextUserId++;
|
||||
this.key = null;
|
||||
this.account = null;
|
||||
this.room = null;
|
||||
this.pos = null;
|
||||
this.address = socket.remoteAddress || "";
|
||||
this.remote = `${this.address}:${socket.remotePort}`;
|
||||
}
|
||||
|
||||
get name() {
|
||||
return this.account ? this.account.username : `#${this.id}`;
|
||||
}
|
||||
|
||||
write(message) {
|
||||
if (this.socket.writable) {
|
||||
if (config.logPackets) {
|
||||
console.log(`[game] -> ${this.name} ${message}`);
|
||||
}
|
||||
this.socket.write(message + "\0");
|
||||
// A client that stopped reading must not pile up messages here forever.
|
||||
if (this.socket.writableLength > MAX_BACKLOG) {
|
||||
this.socket.destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sendSys(action, roomId, body = "") {
|
||||
this.write(`<msg t='sys'><body action='${action}' r='${roomId}'>${body}</body></msg>`);
|
||||
}
|
||||
|
||||
// raw extension message. the client reads params starting at index 2 of
|
||||
// [cmd, roomId, ...params].
|
||||
// "%" separates fields and NUL ends the message, so neither may appear
|
||||
// inside one: a player-chosen string could otherwise forge fields.
|
||||
sendXt(cmd, roomId, ...params) {
|
||||
this.write(`%xt%${[cmd, roomId, ...params].map(param => String(param).replace(/[%\0]/g, "")).join("%")}%`);
|
||||
}
|
||||
|
||||
sendXtJson(roomId, obj) {
|
||||
this.write(JSON.stringify({t: "xt", b: {r: roomId, o: obj}}));
|
||||
}
|
||||
|
||||
close() {
|
||||
this.socket.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
const parseSys = message => {
|
||||
const body = /<body action='([^']*)' r='(-?\d+)'>([\s\S]*)<\/body>/.exec(message);
|
||||
if (!body) {
|
||||
return null;
|
||||
}
|
||||
const cdata = tag => {
|
||||
const match = new RegExp(`<${tag}><!\\[CDATA\\[([\\s\\S]*?)\\]\\]></${tag}>`).exec(body[3]);
|
||||
return match ? match[1] : null;
|
||||
};
|
||||
return {action: body[1], roomId: Number(body[2]), raw: body[3], cdata};
|
||||
};
|
||||
|
||||
// handlers: {sys(session, msg), xt(session, cmd, roomId, params), close(session)}
|
||||
const start = handlers => new Promise((resolve, reject) => {
|
||||
const dispatch = (session, message) => {
|
||||
if (config.logPackets) {
|
||||
console.log(`[game] <- ${session.name} ${forLog(message)}`);
|
||||
}
|
||||
if (message.startsWith("<policy-file-request")) {
|
||||
session.socket.end(POLICY + "\0");
|
||||
return;
|
||||
}
|
||||
if (message[0] === "<") {
|
||||
const msg = parseSys(message);
|
||||
if (!msg) {
|
||||
return;
|
||||
}
|
||||
switch (msg.action) {
|
||||
case "verChk":
|
||||
session.sendSys("apiOK", 0);
|
||||
return;
|
||||
case "rndK":
|
||||
session.key = crypto.randomBytes(16).toString("hex");
|
||||
session.sendSys("rndK", -1, `<k>${session.key}</k>`);
|
||||
return;
|
||||
default:
|
||||
handlers.sys(session, msg);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (message[0] === "%") {
|
||||
// %xt%o%rj%1%a%b% -> ["", "xt", "o", "rj", "1", "a", "b", ""]
|
||||
const parts = message.split("%");
|
||||
if (parts[1] === "xt" && parts.length >= 6) {
|
||||
handlers.xt(session, parts[3], Number(parts[4]), parts.slice(5, -1));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (message[0] === "{") {
|
||||
const body = JSON.parse(message).b || {};
|
||||
const params = Array.isArray(body.p) ? body.p : Object.values(Object(body.p));
|
||||
handlers.xt(session, String(body.c), Number(body.r), params.map(String));
|
||||
}
|
||||
};
|
||||
|
||||
const onConnection = socket => {
|
||||
const address = limits.key(socket.remoteAddress);
|
||||
const open = connections.get(address) || 0;
|
||||
const total = [...connections.values()].reduce((sum, count) => sum + count, 0);
|
||||
socket.on("error", () => {});
|
||||
if (open >= config.maxConnectionsPerAddress || total >= config.maxConnections) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
connections.set(address, open + 1);
|
||||
|
||||
const session = new Session(socket);
|
||||
let buffer = Buffer.alloc(0);
|
||||
let windowStart = Date.now();
|
||||
let messagesInWindow = 0;
|
||||
let bytesInWindow = 0;
|
||||
let errorsInWindow = 0;
|
||||
socket.setNoDelay(true);
|
||||
console.log(`[game] ${session.remote} connected as #${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.
|
||||
const loginTimer = setTimeout(() => {
|
||||
if (!session.account && !session.signingUp) {
|
||||
socket.destroy();
|
||||
}
|
||||
}, config.loginTimeoutMs);
|
||||
const signupTimer = setTimeout(() => {
|
||||
if (!session.account) {
|
||||
socket.destroy();
|
||||
}
|
||||
}, SIGNUP_LIFETIME_MS);
|
||||
socket.setTimeout(config.idleTimeoutMs, () => socket.destroy());
|
||||
|
||||
socket.on("data", chunk => {
|
||||
if (Date.now() - windowStart > RATE_WINDOW_MS) {
|
||||
windowStart = Date.now();
|
||||
messagesInWindow = 0;
|
||||
bytesInWindow = 0;
|
||||
errorsInWindow = 0;
|
||||
}
|
||||
bytesInWindow += chunk.length;
|
||||
if (bytesInWindow > config.maxBytesPerTenSeconds) {
|
||||
console.log(`[game] ${session.name} disconnected for flooding`);
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
buffer = Buffer.concat([buffer, chunk]);
|
||||
let end;
|
||||
while ((end = buffer.indexOf(0)) !== -1) {
|
||||
if (end > MAX_MESSAGE) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
if (++messagesInWindow > config.maxMessagesPerTenSeconds) {
|
||||
console.log(`[game] ${session.name} disconnected for flooding`);
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
const message = buffer.toString("utf8", 0, end);
|
||||
buffer = buffer.subarray(end + 1);
|
||||
try {
|
||||
dispatch(session, message);
|
||||
}
|
||||
catch (err) {
|
||||
// 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()})` : ""}`);
|
||||
if (++errorsInWindow > MAX_ERRORS_PER_WINDOW) {
|
||||
console.log(`[game] ${session.name} disconnected: too many messages that could not be handled`);
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (socket.destroyed) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (buffer.length > MAX_MESSAGE) {
|
||||
socket.destroy();
|
||||
}
|
||||
});
|
||||
socket.on("close", () => {
|
||||
clearTimeout(loginTimer);
|
||||
clearTimeout(signupTimer);
|
||||
const left = connections.get(address) - 1;
|
||||
if (left > 0) {
|
||||
connections.set(address, left);
|
||||
}
|
||||
else {
|
||||
connections.delete(address);
|
||||
}
|
||||
console.log(`[game] ${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}`);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const server = config.tls
|
||||
? tls.createServer({cert: fs.readFileSync(config.tls.certFile), key: fs.readFileSync(config.tls.keyFile),
|
||||
handshakeTimeout: config.tlsHandshakeTimeoutMs}, onConnection)
|
||||
: net.createServer(onConnection);
|
||||
server.on("tlsClientError", () => {});
|
||||
server.maxConnections = config.maxConnections * 2;
|
||||
if (config.tls) {
|
||||
// connections that have not finished their TLS greeting are counted
|
||||
// too: the limit above is only reached once they have.
|
||||
const greeting = new Map(); // address -> connections not yet through it
|
||||
server.on("connection", raw => {
|
||||
const address = limits.key(raw.remoteAddress);
|
||||
const count = (greeting.get(address) || 0) + 1;
|
||||
if (count > config.maxConnectionsPerAddress * 2) {
|
||||
raw.destroy();
|
||||
return;
|
||||
}
|
||||
greeting.set(address, count);
|
||||
const done = () => {
|
||||
const left = greeting.get(address) - 1;
|
||||
if (left > 0) {
|
||||
greeting.set(address, left);
|
||||
}
|
||||
else {
|
||||
greeting.delete(address);
|
||||
}
|
||||
};
|
||||
raw.once("close", done);
|
||||
});
|
||||
}
|
||||
server.once("error", reject);
|
||||
server.listen(config.gamePort, config.gameBindAddress, () => {
|
||||
console.log(`[game] listening on ${config.gameBindAddress}:${config.gamePort}${config.tls ? " (TLS)" : ""}`);
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = {start};
|
||||
@@ -0,0 +1,111 @@
|
||||
{"source":"AJ Classic Wiki (animaljam.fandom.com), read by tools/shop-stock.py","lists":{
|
||||
"5":{"shop":"Shiveer Shoppe","now":{"clothing":[828,345,156,1110,1761,1762,1763,1091,274,709,1111,1100,356],"den":[]},"former":{"clothing":[233,142,152,135,251,1273,263,1378,1113,1431,1433,1271,154,838,1750,714,1682,892,543,1350,718,1318,1065,528,527,1970,1064,1325,269,703,1292,3827,140,713,1377,234,232,780,3111,2120,478,3631,3770,3304,4295,1323,3756,3754,3873,1767,1985,3277,536,4511,4147,3364,3426,1776,2760,231,3907,2010,3215,3182,1911,3808,4231,881,64,2500,2147,489,490,1759,237,4150,4130,4084,4197,3376,2040,3124,392,4026,3826,3852,3463,3444,2734,3196,3027,2133,2746,1937,4267,479,2629,4484,1059,4416,3689,217,2169,3144,1733,534,1082,2646,3128,3292,3094,3351,3517,4293,3478,3519,2810,3236,3198,3600,3254,2897,3004,3561,2975,3953,4048,1864,4594,4508,3618,2631,572,2717,533,236,4244,225,871,219,221,220,1099,1055,1092,1671,707,250,1272,4273,1977,333,334,228,245,1291,876],"den":[]}},
|
||||
"9":{"shop":"Mystery Emporium","now":{"clothing":[],"den":[1065,621,442,970,445,443,480,1201,441,809,479,447,538,1360,444,750,1587,1591,1593]},"former":{"clothing":[],"den":[391,717,64,708,392,56,60,403,440,89,645,755,50,91,742,389,397,59,400,528,390,358,164,628,484,1086]}},
|
||||
"11":{"shop":"Jam Mart Clothing","now":{"clothing":[1296,706,142,1578,468,1262,560,559,1264,1045,134,944,1226,932,153,1154,937,738,906,141,260,265,154,1577,834,936,278,157,982,418,159,1249,621,1227,1000,145,830,935,1430,586,632,811,151,573,144,809,1086,137,240,796,1297,1307,1673,268,661,578,577,58,1557,931,765,163,126,1261,164,1037,1558,1129,810,133,792,469,1252,1508,758,999,829,1250,147,125,253,519,1533,60,587,779,1579,1237,1534,417,1251,122,136,165,629,708,1240,743,1540,812,754,22,753,662,1228],"den":[]},"former":{"clothing":[1286,149,233,152,135,981,287,426,4271,1929,828,251,238,1287,652,59,1003,1004,1248,1005,3011,425,925,63,1650,837,759,1273,670,1044,127,289,435,766,822,692,790,1614,128,3016,1446,123,1168,2220,2211,2219,2217,2218,2216,2215,2213,2214,2209,2210,2212,1155,1115,262,264,912,263,1376,1378,1128,729,911,1113,470,1667,546,224,719,905,702,701,500,3877,3911,2032,2035,2029,2036,2033,2037,2034,2027,2030,2031,2038,2028,552,1431,1432,1433,821,820,150,160,169,690,266,663,664,653,835,1271,486,760,1672,1683,1690,684,1493,601,1052,823,838,1247,4272,620,313,1440,1535,1263,1443,598,215,3008,482,612,212,213,441,613,209,214,974,614,3258,783,210,3259,211,1098,1750,1748,1749,1752,1751,1316,714,473,1728,1730,1729,3014,847,1288,647,1181,1494,3009,491,1939,1938,249,259,242,243,357,257,892,889,256,543,1097,255,1106,258,718,4247,1104,1096,1105,1285,488,1061,1967,161,329,1036,1326,1318,1085,852,930,3013,1317,1065,246,1958,1686,1083,528,872,1062,1968,1681,1063,1680,1957,1060,1725,1724,1687,1688,1678,527,1970,1064,1325,1084,1679,3015,849,870,247,267,456,453,269,1292,3912,800,1241,547,162,1298,720,65,261,725,3012,129,1764,2390,2391,2393,2392,2388,2394,2398,2399,2389,2395,2396,2397,2400,2401,2387,983,2475,2474,2472,2471,2473,2457,50,146,481,1509,131,495,836,402,487,3010,1726,130,156,140,998,1001,877,132,1219,1220,1218,713,762,395,1289,2452,2448,235,2447,2449,398,628,2450,2451,2446,2445,1127,254,241,869,1669,1760,139,1377,1114,1393,646,234,232,2077,1438,1923,1256,2119,592,1612,522,475,476,1245,1343,611,545,3110,644,626,1791,624,625,2278,521,1268,848,825,1896,1556,2252,585,745,1654,1235,2072,2071,3029,4487,723,636,1613,1023,1919,2251,1990,1555,445,1464,699,1897,575,1165,1210,1080,1321,1425,1356,3771,3755,1424,1294,2808,1975,3872,1986,1374,497,1768,918,2193,1125,1373,826,908,633,986,540,2274,561,832,716,864,239,1491,2275,1024,1236,971,1567,2761,1586,3214,1225,763,593,756,1054,447,2553,2554,797,231,695,2555,2287,2277,2285,3692,3632,2284,2106,2628,2286,2266,2267,2268,2265,3906,928,539,1830,1445,775,1721,1792,544,727,1922,1774,804,1576,4335,412,1215,571,1833,1950,1414,4292,929,138,226,2241,2240,2025,2424,2425,4024,979,776,777,3956,2901,2183,2188,2331,2330,715,2329,2731,3796,1568,1777,2295,1314,711,379,2222,2238,2221,1677,64,1391,4047,2499,2497,2501,2498,1492,2811,2972,1239,3112,3363,4148,875,907,909,883,1349,1758,1982,904,1348,1984,903,1980,400,1357,2189,2187,1026,1742,1157,1046,237,2296,3127,460,919,1133,955,1415,1978,1734,4083,4085,1811,1664,2645,867,3377,1322,2298,4199,1676,696,697,2149,2167,1306,1238,471,542,541,535,844,1108,843,746,1936,704,467,910,1988,557,1050,4232,2340,3853,2745,4246,3464,2339,2747,2338,3465,728,2144,1025,2117,405,406,327,508,1267,1039,1610,1335,764,227,1184,637,1973,1722,556,682,1775,1731,2105,2103,2104,1049,1538,833,2132,1611,1290,1392,399,1053,1337,3238,882,3183,752,422,1283,1653,3289,650,1081,2191,2192,1153,673,1047,1879,1180,531,446,1095,3199,1526,1444,924,645,1259,1840,778,1663,218,3690,217,675,674,1918,4131,1527,1585,1126,741,956,1908,1437,651,2297,1341,2170,694,1675,2718,509,1814,1089,1109,1094,705,700,230,393,786,4133,2276,3031,3096,3306,3349,841,2009,3477,2200,2348,2350,2332,2224,2405,2341,2347,3856,1989,3518,1134,2198,1998,2404,2402,2197,2001,1997,2194,2403,2196,2195,2762,3480,2199,2351,2423,2349,3197,2422,1012,1862,413,551,498,722,1831,1912,3620,2239,2453,2039,2456,2480,2261,2259,2260,2481,2455,3275,2257,3253,2256,3001,3954,2026,2250,3237,2479,2478,2454,2249,1340,799,755,1909,1794,996,1147,386,380,951,2182,855,4510,1652,846,1813,934,1426,2011,681,1284,23,941,1575,222,3291,3616,933,2299,2317,2315,532,2318,2316,3145,229,236,387,4417,770,950,942,1013,4269,3442,3824,1971,1058,225,1510,627,248,871,721,840,946,891,62,945,943,433,219,221,1649,216,220,3005,724,3007,671,648,831,24,166,1091,1055,1092,710,850,707,873,1668,874,250,1670,774,2427,2426,789,757,744,501,665,1033,597,1781,1765,1818,1796,1810,1817,939,938,1439,1429,1778,1441,3876,1808,1809,1779,3219,1797,1816,4270,3218,1795,1780,290,252,1272,693,401,520,3369,1793,761,529,1270,1112,1648,21,1442,842,244,1308,574,143,223,3006,1974,484,4058,4053,4051,4064,4050,4055,4054,4066,4067,4052,4057,4056,4059,4060,4065,4061,4063,4062,1665,333,334,1666,485,502,228,148,767,245,1291,499,839],"den":[]}},
|
||||
"12":{"shop":"Jam Mart Furniture","music":false,"now":{"clothing":[],"den":[424,4995,1547,3427,1624,1213,542,1538,3191,1,1232,1471,4071,4988,118,338,372,2846,637,4114,4624,2362,382,2356,3100,2781,1549,4532,4535,4534,4539,4544,4545,4542,4533,4536,4537,4543,949,4997,3098,1212,1044,373,4656,1048,1043,1046,1047,4996,348,4991,1172,2352,3342,4986,2785,1437,330,381,2782,4998,773,641,1234,3104,1523,2834,4994,4993,547,4999,2361,3101,612,499,3194,4992,189,4622,131,1857,1853,1854,1990,1864,1956,1954,1963,1861,1973,1970,1953,1617,2349,2682,2683,2679,2678,2681,1100,1101,4623,4957,4620,295,367,1595,36,418,369,771,4958,2783,383,4990,1235,4987,776,3103,1139,1536,2192,4119,4118,363,3102,416,415,398,2847,3172,1616,371,2505,2789,1557,152,158,1615,2348,2600,2553,3099,1169,3560,439,423,3189,775,4090,3171,3197,2363,357,1602,2,1590,1592,1594,365]},"former":{"clothing":[],"den":[2484,4648,2427,2422,2421,2424,2431,2430,2426,2420,2423,2428,2429,2425,2865,1135,4694,4696,4695,4771,1575,1768,1770,1769,1760,391,4616,3203,3602,3605,1307,611,4952,4951,8,1821,3894,2412,3431,3434,2719,13,4646,4066,717,16,1103,3225,4182,4724,4590,4686,399,2801,402,15,4091,4104,565,4098,4097,2677,2296,1402,19,3886,3740,292,362,366,24,435,4709,3970,3969,3968,3972,3971,4522,1734,4086,4836,2471,3879,345,2298,1766,3599,1533,2739,2742,2747,2744,2741,2745,2749,2746,2748,2750,2743,2740,380,489,733,411,2455,3946,3945,2452,2434,3949,715,1938,3948,1362,3944,3947,3952,1368,4084,430,3324,2339,394,4117,4115,1303,436,1528,4538,4644,4645,2398,2397,2399,1442,1443,846,1441,848,1447,1985,847,4940,4945,4942,4941,4939,4938,4783,1015,346,2480,181,527,526,1237,4657,1556,1539,3629,2494,1497,1948,1677,4691,2774,37,3694,3689,3684,3685,3688,3692,3686,3683,3687,3693,3691,3690,736,4844,4839,4838,4837,2552,3749,2117,1532,3748,2551,2116,3450,1306,1765,1749,4948,488,812,4563,4561,4560,4564,4559,1483,52,478,1792,4067,4651,4653,4650,903,4652,4083,485,4586,2358,1230,3063,3186,3185,3061,3062,4907,3592,1689,1718,1719,1643,1691,1685,1686,1648,531,732,1788,392,4469,3311,3883,4281,4714,2866,4723,1584,4316,51,3739,3733,3731,3730,3729,3735,3737,3728,3727,3736,3732,3734,3889,3624,3623,3675,3669,3666,3674,3672,3670,3673,3676,3665,3667,3671,3668,56,559,2837,494,935,3745,2702,360,2602,349,1525,1229,1095,2717,4594,355,3232,3236,4593,3234,3233,3231,3235,1057,3007,3990,3006,2998,4832,2396,739,902,842,3507,1901,3504,819,2418,1486,405,4183,4184,3741,3747,1236,3742,3746,388,387,934,403,3887,3437,1524,4069,1312,427,3328,3327,4464,4113,4466,1045,2512,4592,1843,4845,4775,4465,1708,1605,4383,3325,4584,1836,4647,404,4726,4039,2921,4867,4110,1411,2044,3174,428,3463,3464,3460,2593,1837,738,3461,3459,1699,1480,2278,2272,2275,2269,2274,2277,2281,2273,2282,2271,2280,2283,65,1173,1764,1640,3521,1540,3627,2489,1499,1495,4712,1541,3631,2493,1501,4710,419,463,1577,2780,2773,562,395,4585,737,4180,4591,2821,2736,425,1083,2772,1566,4690,3835,3836,3841,3840,4688,3870,3834,2232,2229,793,794,2465,434,68,3511,3513,2470,3508,1962,1416,1606,3008,1940,790,3004,1417,1415,1423,1418,2469,3509,563,1438,1413,2909,2295,4774,586,1729,904,1713,4103,1709,1707,1714,1706,1711,3600,1700,1710,817,4108,820,1404,1826,4107,2461,4105,3935,2676,3885,4275,4280,1450,1365,1840,2453,4736,4732,5243,3451,3452,1935,429,1161,5245,1839,2887,5244,1937,1818,4735,4733,1841,2911,350,4587,1280,3146,1529,2345,1527,3454,2411,3428,1152,2401,3429,3453,3962,2820,2819,1446,4835,1531,432,433,431,1939,1542,3626,2488,1496,4312,4311,4776,4309,4310,1227,4386,4384,4387,4385,4389,4388,3032,4458,4456,4457,4459,4001,454,3996,3034,3518,3517,4858,3033,3998,4004,3035,4454,4451,4449,4452,4450,4455,3031,2510,3999,4000,1789,1791,1790,440,3880,83,3744,1058,4460,3890,2417,3376,1153,2867,2864,1810,3300,3295,3305,3304,3301,3302,3296,3297,3294,3299,3298,3303,4291,2786,2787,486,4649,2915,1091,3127,3129,3133,3128,2456,4687,1484,361,4643,1537,2680,4960,4950,4954,4955,4953,1580,1731,2344,753,2354,2404,1481,1596,354,130,2733,2732,2734,2737,2735,2738,2462,4617,4618,3750,1904,1914,1916,1911,1905,1906,3523,1923,1924,1925,3714,3716,3708,3710,1907,3712,3709,3715,3717,3713,1928,3718,3707,1910,3711,4181,3226,3223,3218,3224,3220,1687,4596,744,1932,456,646,1543,3628,2491,1500,1134,3961,3963,3965,3967,3964,4864,4093,1429,4138,1412,2886,4655,1834,1349,818,2779,1520,695,1809,4041,4043,2047,4040,4042,2049,2045,4038,2048,2046,1445,493,1314,4467,2730,2720,2728,2721,2723,2724,2727,2722,2731,2729,2726,2479,4367,841,4065,50,39,370,364,1233,91,2776,2778,4589,2525,2545,2529,2408,2410,2546,2532,2530,2547,2548,2597,2527,2409,2528,2526,2531,1727,1738,1739,1726,1728,1735,1733,1730,1736,413,335,4613,4614,1474,2912,1936,4812,4808,4810,4813,4809,1601,1934,1488,422,455,4877,4085,845,97,1763,464,412,1614,1613,3895,2850,1870,4727,4728,3456,2402,1579,1238,1468,1645,3772,1545,1650,1276,1190,1277,1226,3610,3608,3616,3611,3614,1224,55,1225,3130,3132,3124,3131,114,629,462,4731,751,2910,4671,4672,4670,115,417,351,4063,1431,1960,734,1801,731,1081,1082,1761,4392,4734,1696,1214,1693,1694,1690,1692,1720,1717,1688,1695,1697,1929,1865Line truncated
|
||||
"50":{"shop":"Bahari Bargains","now":{"clothing":[296,305,1593,302,293,454,303,299,588,295,329,335,438,298,361,432,464,947,304,291,311,404,423,424,465,672,431,308,301,455,292,1617,347,403,437,306,583,312,309],"den":[]},"former":{"clothing":[505,340,339,377,381,378,382,504,4525,310,1221,1223,1222,337,328,359,358,901,483,3957,331,336,294,360,300,494,503,288,297,307,324,550,4371,4266,325,2014,461,3619,712,2008,680,972,4229,3424,4025,1983,2190,330,3521,615,1841,362,1863,1483,2171,791,326,927,448,3598,1265,771,3910,1834,472,845,562,824,466,2089,2088,576,2223,3560,1021,1547,3823,352,363,346,321,322,496,351,1815,323],"den":[]}},
|
||||
"51":{"shop":"Sunken Treasures","now":{"clothing":[],"den":[680,756,705,682,683,880,940,879,745,891,877,727,876,1014,1897,757,878,760,1013,905,1460,892,687,688,1608,1609,741,893,689,1287,1197,3209,3212,3208,3211,3215,1061,1055,1112,890,1873,926,874,873,686,1477,1175,1174,1004,849,828,1869,703,1503,1505,1507,1502,1506,1535,1504,1604,690,711,1461,1482,709,1286,1508,1198,1603]},"former":{"clothing":[],"den":[726,875,681,1056,844,684,827,1146,740,1144,1903,710,685,923,924,790,1060,1147,1142,791,691,925,1143,712,759,938,939,1159,752,1479,941,920]}},
|
||||
"56":{"shop":"Music Shop","music":true,"now":{"clothing":[],"den":[697,698,805,699,865,614,1246,914,702,2577,701,648,829,700,5563]},"former":{"clothing":[],"den":[615,616,693]}},
|
||||
"59":{"shop":"Epic Wonders","now":{"clothing":[1735,803,1135,1542,462,3344,1002,414,463,350,507,353,795,663,664,760,477,1299,768,623,397,348,428,537,530,349,449,1543,415,1832,4512,1560,827,683,677,678,679,427,622,1043,631,630,649,574],"den":[1177,956,728,1473,795,1157,1150,1170,2051,2041,2040,2054,2066,2052,1463,2067,1151,2276,850,1041,735,5607,3561,3293,851,4179,843,2315,2316,1217,1313,2193,730,921,1476]},"former":{"clothing":[1286,4234,4279,837,4251,4250,4248,4252,4249,1375,905,355,784,4280,785,354,821,4296,726,1930,819,1969,1672,1736,492,1035,1034,4233,4029,2545,2525,2549,2534,2532,506,2540,2542,2546,2550,2535,2541,2530,2523,2547,2528,2526,2529,2522,450,2533,2544,2543,2527,2548,4275,890,1320,1319,573,1087,878,1723,1324,2079,4274,1673,481,1001,4336,4421,493,2078,2077,2080,2075,2076,2082,2074,2081,538,1315,3772,3216,4049,4370,4419,4418,2145,2012,1185,1743,3427,3425,1505,3855,3305,1101,1158,3217,1812,3113,2973,1880,2148,1102,1949,1506,1921,616,2720,3181,3146,4509,3809,2007,880,1996,2748,2898,2899,4245,742,4294,4149,3126,3125,698,2630,3599,4198,3375,3378,2168,1972,3825,3184,2118,3520,1539,3634,3278,4134,1164,4485,4486,3256,3293,3688,3352,2647,1979,1732,2552,1920,2763,4268,3875,2733,3366,3002,3290,2146,1305,1090,3617,1910,4230,3443,4201,1293,396,4372,4488,1615,676,831,1651,873,874,529,1270,1269,1228,1166,474],"den":[1178,1207,2792,1040,725,1576,3951,4116,4689,2477,4100,4282,1084,1264,1085,1222,1223,1263,1243,1242,1087,4089,2922,1208,922,3591,1209,4778,1522,2209,2270,5659,3455,2554,3505,4101,1176,4464,4466,4006,4842,4465,3960,4081,2447,1156,2448,1097,3876,3514,4841,852,803,1158,4211,4292,4106,3997,2030,2788,2675,1455,1457,1458,1435,1459,1456,2718,4112,1210,1215,1008,1132,3884,1009,5658,5660,1098,3184,4811,4817,802,4213,4212,4210,4333,5291,5761,5056,5467,731,1211,3635,3633,1216,5661,2353,804,2805,936,4777,1819,3936,2449,1845,729,4283,1137,4058,4053,4886,2359,1218,3933,1219,3992,2191,3503,4780]}},
|
||||
"61":{"shop":"Jamaaliday Shop","music":false,"now":{"clothing":[1690,1062,1681,1725,1724,1678,1956,1084,1679],"den":[717,733,1350,739,3954,2460,2433,1836,428,3463,3464,1837,737,2435,1348,3956,3957,3955,2909,3935,2885,2883,429,1364,1366,744,751,734,3934,1933,3953,754,1367]},"former":{"clothing":[1312,851,692,1067,1052,1328,1329,1330,1327,1331,872,1063,1957,527,247,1959,693,2408,2409,2411,2406,2407,2410,245,1960],"den":[3801,2434,1362,736,4751,3799,427,3960,3800,3959,3958,4744,3462,738,3461,425,1365,4745,2437,3807,2438,3768,3767,1935,432,431,3806,2770,3798,1349,1934,3805,3802,3804,4746,4753,3803,4754,426,1363]}},
|
||||
"63":{"shop":"Sol Arcade Shop","now":{"clothing":[],"den":[832,708,831,1088,777,561,543,1133,1059,613,560,645,743,491,789,755,528,492,1155,544,713,628,529]},"former":{"clothing":[],"den":[742]}},
|
||||
"67":{"shop":"Dinner Shop","now":{"clothing":[],"den":[781,780,489,488,490,487,2745,2747,2749,2741,2746,2750,2748,2740,2744,2743,2742,2739]},"former":{"clothing":[],"den":[]}},
|
||||
"68":{"shop":"Friendship Shop","now":{"clothing":[],"den":[4847,3513,3511,4839,4844,4838,4837,4846,4848,4849,4390,4394,4393,3516,3515,434,68,435,2467,374,364]},"former":{"clothing":[],"den":[]}},
|
||||
"70":{"shop":"Heatwave Shop","now":{"clothing":[],"den":[564,563,562,15,530,565]},"former":{"clothing":[],"den":[]}},
|
||||
"71":{"shop":"Leap Year Accessories","now":{"clothing":[3445,3446,3447,3448,3449,3450],"den":[]},"former":{"clothing":[],"den":[]}},
|
||||
"72":{"shop":"Leap Year Den Items","now":{"clothing":[],"den":[5299,5298,5297,5296,5295,5294,5293,5292]},"former":{"clothing":[],"den":[]}},
|
||||
"74":{"shop":"Lucky Shop","now":{"clothing":[],"den":[4873,4871,4875,4872,3519,3522,3036,848,1442,454,847,846,866]},"former":{"clothing":[],"den":[]}},
|
||||
"81":{"shop":"Wolves Only Shop","now":{"clothing":[],"den":[882,883,884,881,885,886]},"former":{"clothing":[],"den":[]}},
|
||||
"82":{"shop":"April Fools' Shop","now":{"clothing":[1427,922,1156,740,923,1428,921,920],"den":[4893,4892,4891,4889,4887,4894,4888,4890,4878,4865,4863,4866,4471,4470,4482,4461,4463,3595,3600,3597,3598,2031,2038,2033,2035,2039,3596,912,909,907,910,908,911]},"former":{"clothing":[],"den":[]}},
|
||||
"83":{"shop":"Horses Only Shop","now":{"clothing":[384,383,385,143,149,160],"den":[901,900,899,898,897,896,919]},"former":{"clothing":[],"den":[]}},
|
||||
"84":{"shop":"Horses Only Shop","music":false,"now":{"clothing":[384,383,385,143,149,160],"den":[901,900,899,898,897,896,919]},"former":{"clothing":[],"den":[]}},
|
||||
"85":{"shop":"Pet Den Item Shop","now":{"clothing":[],"den":[582,917,581,918,916,631,943,942,2355,955,1494,4095,4094,952,950]},"former":{"clothing":[],"den":[946,945,944,953,610,712,954,951]}},
|
||||
"87":{"shop":"Atlantis Shop","now":{"clothing":[388,389,391,390],"den":[930,931,929,928,927,932]},"former":{"clothing":[],"den":[]}},
|
||||
"88":{"shop":"Atlantis Shop","now":{"clothing":[388,389,391,390],"den":[930,931,929,928,927,932]},"former":{"clothing":[],"den":[]}},
|
||||
"90":{"shop":"Horses Only Shop","music":true,"now":{"clothing":[384,383,385,143,149,160],"den":[901,900,899,898,897,896,919]},"former":{"clothing":[],"den":[]}},
|
||||
"92":{"shop":"Spooky Shop","now":{"clothing":[1031,1030,1029,1038,1027,251],"den":[3877,3337,3341,2853,2855,3887,3883,401,402,2351,1141,394,395,3839,693]},"former":{"clothing":[],"den":[]}},
|
||||
"93":{"shop":"Spooky Shop","music":false,"now":{"clothing":[1031,1030,1029,1038,1027,251],"den":[3877,3337,3341,2853,2855,3887,3883,401,402,2351,1141,394,395,3839,693]},"former":{"clothing":[],"den":[]}},
|
||||
"94":{"shop":"Spooky Shop","music":true,"now":{"clothing":[1031,1030,1029,1038,1027,251],"den":[3877,3337,3341,2853,2855,3887,3883,401,402,2351,1141,394,395,3839,693]},"former":{"clothing":[],"den":[]}},
|
||||
"95":{"shop":"Cruise Ship Shop","now":{"clothing":[],"den":[4882,4881,4880,4879,965,963,966,964,962,961,960]},"former":{"clothing":[],"den":[]}},
|
||||
"96":{"shop":"Cruise Ship Shop","now":{"clothing":[],"den":[4882,4881,4880,4879,965,963,966,964,962,961,960]},"former":{"clothing":[],"den":[]}},
|
||||
"99":{"shop":"Bunnies Only Shop","music":false,"now":{"clothing":[],"den":[975,976,977,978,979,980,1005]},"former":{"clothing":[],"den":[]}},
|
||||
"100":{"shop":"Bunnies Only Shop","music":true,"now":{"clothing":[],"den":[975,976,977,978,979,980,1005]},"former":{"clothing":[],"den":[]}},
|
||||
"104":{"shop":"Penguins Only Shop","music":false,"now":{"clothing":[],"den":[1016,1017,1018,1019,1020,1021,1039]},"former":{"clothing":[],"den":[]}},
|
||||
"106":{"shop":"Penguins Only Shop","music":true,"now":{"clothing":[],"den":[1016,1017,1018,1019,1020,1021,1039]},"former":{"clothing":[],"den":[]}},
|
||||
"107":{"shop":"Freedom Shop","now":{"clothing":[1530,978,976,1528,977,973,1529,1531,975,1217,1216,1532],"den":[2175,1052,5585,2186,3237,2176,2179,2181,1051,3238,2183,2178,2182]},"former":{"clothing":[612,439,441,440,613,781,974,614,783,444,443,442,782],"den":[1054,1049,2180,2185,1050,2177,2184,1053]}},
|
||||
"108":{"shop":"Freedom Shop","now":{"clothing":[1530,978,976,1528,977,973,1529,1531,975,1217,1216,1532],"den":[2175,1052,5585,2186,3237,2176,2179,2181,1051,3238,2183,2178,2182]},"former":{"clothing":[612,439,441,440,613,781,974,614,783,444,443,442,782],"den":[1054,1049,2180,2185,1050,2177,2184,1053]}},
|
||||
"111":{"shop":"Pets Only Shop","music":false,"now":{"clothing":[],"den":[580,579,630,1078,955,952,950,942,943,631,916,918,917,582,581,1090,946,945,944,953,610,954,951]},"former":{"clothing":[],"den":[]}},
|
||||
"112":{"shop":"Pets Only Shop","music":true,"now":{"clothing":[],"den":[580,579,630,1078,955,952,950,942,943,631,916,918,917,582,581,1090,946,945,944,953,610,954,951]},"former":{"clothing":[],"den":[]}},
|
||||
"113":{"shop":"Treetop Gardens","now":{"clothing":[],"den":[1552,13,1636,2309,1578,2305,9,2310,2115,1525,2311,1509,1510,2321,2322,2306,1551,1131,1553,2096,5608,2308,27,3562]},"former":{"clothing":[],"den":[2302,391,2303,2284,2285,5662,5663,2412,5665,5664,2304,16,1583,5434,1582,4086,250,1893,1894,436,2325,2324,2090,1447,5673,5674,5676,1145,1912,1913,2095,1154,392,4314,4845,2194,2195,2435,5671,5672,5675,5669,5670,1415,460,481,2170,2171,3454,2411,1630,3430,3428,1152,2555,2401,3429,3453,4835,2018,2020,432,433,431,1130,4386,4384,4387,4385,4389,4388,3525,5435,2326,2328,5666,5668,5508,2529,2530,2597,2528,482,2912,1488,845,97,1908,1909,1870,2402,2042,2043,2074,1960,5432,389,2019,5430,5429,3064,5506,1546,2089,774,390,1992,1994,5431,5433,86,5507,1102,1512,1519,1602,5538,5428,5667]}},
|
||||
"116":{"shop":"Monkeys Only Shop","music":false,"now":{"clothing":[],"den":[1107,1099,1108,1105,1104,1106,1111]},"former":{"clothing":[],"den":[]}},
|
||||
"117":{"shop":"Monkeys Only Shop","music":true,"now":{"clothing":[],"den":[1107,1099,1108,1105,1104,1106,1111]},"former":{"clothing":[],"den":[]}},
|
||||
"118":{"shop":"AJ Birthday Shop","music":false,"now":{"clothing":[1020,1019,1018,1017,1016,1015],"den":[3358,3357,3089,3079,3020,3018,3022,2707,2633,2626,2623,2336,2158,2004,1816,1758,1753,1755,1754,1301,1752,1759,1756,1757,1302,1114,1115,3354,1116,1117,3353,3356,3355,1118,1119,1120,1121,1122,1123,1124,1125,1127,1126,3875,3874,5001,5177,5392,5616,5893,2827,2825,2826,2823,2822,2824,1128]},"former":{"clothing":[],"den":[]}},
|
||||
"119":{"shop":"AJ Birthday Shop","music":true,"now":{"clothing":[1020,1019,1018,1017,1016,1015],"den":[3358,3357,3089,3079,3020,3018,3022,2707,2633,2626,2623,2336,2158,2004,1816,1758,1753,1755,1754,1301,1752,1759,1756,1757,1302,1114,1115,3354,1116,1117,3353,3356,3355,1118,1119,1120,1121,1122,1123,1124,1125,1127,1126,3875,3874,5001,5177,5392,5616,5893,2827,2825,2826,2823,2822,2824,1128]},"former":{"clothing":[],"den":[]}},
|
||||
"122":{"shop":"Haunted Forest Shop","now":{"clothing":[1042,1028,1041,1040,500,499],"den":[3344,3338,2854,2342,2338,399,400,2346,1570,693]},"former":{"clothing":[],"den":[]}},
|
||||
"123":{"shop":"Haunted Forest Shop","music":false,"now":{"clothing":[1042,1028,1041,1040,500,499],"den":[3344,3338,2854,2342,2338,399,400,2346,1570,693]},"former":{"clothing":[],"den":[]}},
|
||||
"124":{"shop":"Haunted Forest Shop","music":true,"now":{"clothing":[1042,1028,1041,1040,500,499],"den":[3344,3338,2854,2342,2338,399,400,2346,1570,693]},"former":{"clothing":[],"den":[]}},
|
||||
"138":{"shop":"Jamaaliday Shop","music":true,"now":{"clothing":[1690,1062,1681,1725,1724,1678,1956,1084,1679],"den":[717,733,1350,739,3954,2460,2433,1836,428,3463,3464,1837,737,2435,1348,3956,3957,3955,2909,3935,2885,2883,429,1364,1366,744,751,734,3934,1933,3953,754,1367]},"former":{"clothing":[1312,851,692,1067,1052,1328,1329,1330,1327,1331,872,1063,1957,527,247,1959,693,2408,2409,2411,2406,2407,2410,245,1960],"den":[3801,2434,1362,736,4751,3799,427,3960,3800,3959,3958,4744,3462,738,3461,425,1365,4745,2437,3807,2438,3768,3767,1935,432,431,3806,2770,3798,1349,1934,3805,3802,3804,4746,4753,3803,4754,426,1363]}},
|
||||
"143":{"shop":"New Year's Shop","now":{"clothing":[4202,4203,4204,4205,4206,4207,4208,4209,879,1727,482,401,257,290,254],"den":[5710,2478,2481,2482,3490,5035,3489,3488,615,616,754,693]},"former":{"clothing":[],"den":[]}},
|
||||
"144":{"shop":"New Year's Shop","music":false,"now":{"clothing":[4202,4203,4204,4205,4206,4207,4208,4209,879,1727,482,401,257,290,254],"den":[5710,2478,2481,2482,3490,5035,3489,3488,615,616,754,693]},"former":{"clothing":[],"den":[]}},
|
||||
"145":{"shop":"New Year's Shop","music":true,"now":{"clothing":[4202,4203,4204,4205,4206,4207,4208,4209,879,1727,482,401,257,290,254],"den":[5710,2478,2481,2482,3490,5035,3489,3488,615,616,754,693]},"former":{"clothing":[],"den":[]}},
|
||||
"150":{"shop":"Paradise Shop","now":{"clothing":[],"den":[1199,1191,1192,1194,1196,1193,1195]},"former":{"clothing":[],"den":[]}},
|
||||
"161":{"shop":"Jam Session Shop","now":{"clothing":[590,591,589,579,582,580],"den":[2658,2657,2655,2653,2648,2647,2646,1266,1265,1260,1257,1258,1259,1246]},"former":{"clothing":[],"den":[]}},
|
||||
"163":{"shop":"Jam Session Shop","music":true,"now":{"clothing":[590,591,589,579,582,580],"den":[2658,2657,2655,2653,2648,2647,2646,1266,1265,1260,1257,1258,1259,1246]},"former":{"clothing":[],"den":[]}},
|
||||
"164":{"shop":"Jam Session Shop","music":false,"now":{"clothing":[590,591,589,579,582,580],"den":[2658,2657,2655,2653,2648,2647,2646,1266,1265,1260,1257,1258,1259,1246]},"former":{"clothing":[],"den":[]}},
|
||||
"167":{"shop":"Diamond Shop","music":false,"now":{"clothing":[],"den":[3485,3613,1279,2576,649,5561,2565,5562,4423,4403,4404,4405,4406,4511,4509,3400,4499,4487,4505,4508,4498,4488,4504,4489,4502,4493,4496,4483,4491,4486,4503,4501,4490,4495,4500,4497,4494,4506,4485,4507,4484,4492,3159,3153,4407,4408,4409,4410,4411,4412,4413,4476,4480,4481,4478,4479,4477,5593,5594,4422,4420,4421,4418,4414,4415,4416,4417,4419,895,3140,2947,66,2279,3993,1278,3042,5654,5655,1673,4159,4512,4510,3620,948,3409,3370,3360,3366,3364,3359,3363,3365,3361,742,4425,4431,4429,4427,4426,4430,4428,4441,4442,4443,4438,4437,4439,4440,4151,1610,5301,4150,4432,4435,4436,4433,4424,4154,4156,1478,2610,2247,1683,2250,3659,3060,3662,1921,2224,2645,1679,2641,3661,2863,1919,2225,2611,1346,2851,1680,2442,2245,2226,3051,2246,2443,2441,1681,2445,2249,1682,1917,3053,2444,1918,3660,1922,1920,3059,3058,2248,1684,3052,1623,650,4157,4153,4152,4473,4472,4474,4475]},"former":{"clothing":[],"den":[4603,4608,4606,4607,4206,5075,4636,3314,4265,2839,2842,2841,2840,3407,3408,2843,3271,4947,4946,4949,3788,3783,3790,3787,3784,4360,2514,3764,5656,5124,5113,5122,4641,4369,4632,5552,3830,4574,4582,4576,3794,3782,5078,4827,4822,4823,4834,4833,4830,4829,4824,4828,4825,4831,4826,5405,4226,4197,4194,4195,4186,4188,4189,4190,4185,4193,4187,4191,5883,5879,5885,5877,5881,5878,5880,5886,5882,4680,4675,4674,4676,4685,4677,4684,4683,4682,4679,4681,4678,4376,3792,3740,5328,704,4896,3822,3820,3821,3819,3227,5376,5789,5781,5785,5790,5784,5787,5780,5782,5786,5788,5783,4232,1070,5072,3229,3288,4239,3930,4137,3041,2110,2118,3040,2120,3329,5119,5120,5409,5174,3848,5331,5337,5558,2606,4601,4572,3849,2812,3319,4148,4149,3813,5140,3629,5556,5559,5555,4217,3169,1872,4270,3694,3689,3684,3685,3688,3692,3313,3686,3683,3687,3693,3691,3690,5540,5543,5546,5545,5547,5544,5541,5542,4372,4128,3749,3748,4131,5184,5179,5180,5181,5182,5183,5199,5201,5210,5202,5203,5205,5204,5200,5206,5207,5208,5209,5211,5212,4379,5058,5059,5062,5063,5057,5066,5067,5065,5064,5061,5060,4166,4165,4167,4639,4640,4935,3121,4233,4579,4637,5085,3844,4578,4299,4271,4269,3763,3816,5068,3811,5135,4267,4171,4172,4170,4168,4164,3845,3165,3167,3818,4301,4302,4300,4303,3739,3733,3731,3730,3729,3735,3737,3728,3727,3736,3732,3734,5101,3281,3624,3623,3675,3669,3666,3674,3672,3670,3673,3676,3665,3667,3671,3668,2312,2314,2313,5229,5230,5220,4224,4263,4264,4266,3745,4331,4136,5114,5553,5310,5551,4219,3282,4050,4044,4075,4048,4078,4077,4076,4045,4079,4080,4047,3268,2790,2791,5307,5175,3541,5315,4018,4008,4013,4024,4012,4015,4007,4009,4014,4017,4011,3544,3540,3542,3543,5103,4334,2871,2872,2873,4333,2870,5407,5125,5126,5127,5128,5129,5130,5131,5132,5133,5134,4237,4236,4235,5311,5312,5305,3741,3747,5306,3742,5309,3746,3352,3347,3350,3348,3346,3351,3349,4658,2616,1273,3809,5136,4192,3326,1249,3726,3094,3379,1359,4638,5408,1773,2629,3385,4049,3927,2619,1641,1300,3028,1268,2161,2343,3650,5843,3823,1747,2002,3796,2713,1811,5410,4906,4897,3725,4642,5406,3797,3085,3077,1274,3107,3030,3828,4298,3923,3929,3925,3921,3924,3926,3920,1160,3922,3847,3861,3867,3858,3864,3863,3860,3868,3857,3865,3859,3869,5487,5489,5488,5486,5485,5492,5490,5491,4268,3627,3309,3310,3308,5564,5565,3631,4577,3931,3125,3779,3269,3862,866,3619,3835,3836,3841,3840,3870,3834,2475,5316,5317,4231,2651,2649,2650,3778,3647,3652,3646,3648,3649,5335,4339,4335,4338,4337,4330,5069,4934,5144,5143,4926,4929,5142,4933,4598,4602,4597,3176,4631,1449,5381,3312,5219,1915,3766,3846,4133,3721,5145,5146,5147,5148,5149,5150,5151,5152,5153,5154,5155,5156,5030,5019,5008,5032,5023,5016,5013,5014,5026,5021,5025,5004,5002,5033,5006,5015,5010,5028,5022,5018,5020,5017,5012,5007,5027,5034,5003,5005,5024,5011,5009,5029,5031,4209,4208,4207,4203,4200,4205,4201,4202,4204,5343,5341,5342,5338,5344,5347,5340,5339,5345,5346,3166,3780,4635,3318,3977,3988,3982,3979,3981,3987,3983,3985,3978,3986,3976,3980,4373,4370,4368,4708,4707,5326,3287,4218,4223,3817,4581,4604,4381,4229,4228,5100,2500,2499,2495,4580,1270,5185,5187,5196,5188,5189,5191,5190,5186,5192,5193,5194,5195,5197,5198,4132,5550,3626,4936,5117,3793,3795,3317,4850,2083,4852,4854,4856,4859,4851,4862,4861,4857,4860,4853,4855,4032,4026,4029,4030,4028,4037,4031,4027,4035,4033,4034,4036,4382,4135,3744,4134,5118,3932,5592,5591,5587,5589,5590,5588,4216,4222,4221,4220,2786,2787,2788,5350,5352,5353,5354,3789,4759,4768,4764,4760,4763,4767,4762,4769,4761,4765,4766,4770,5844,5845,5846,5847,5848,5849,5850,5851,5852,5853,4937,3170,3785,3786,4633,3316,5384,3190,3781,4073,4088,4074,4019,4087,3722,3278,4199,63,5833,5834,5835,5836,5837,5838,5839,5840,5841,5842,3720,3719,4214,4296,4295,4294,4125,5557,3750,3714,3716,3708,3710,2718,3712,3709,3715,3717,3713,3718,3707,3711,3221,3219,3217,5089,5083,5086,5084,5091,5092,5090,5082,5093,5087,5081,5088,5116,3628,5123,3164,5377,4548,4605,3814,5137,5643,5638,5639,3106,3618,5077,5640,5642,3114,1534,5637,5641,5076,3228,3290,4169,3284,3184,5573,5574,5575,5577,5580,5570,5579,5572,5578,5576,5571,5569,4262,5169,5170,5171,3761,2415,2414,2416,2413,3Line truncated
|
||||
"168":{"shop":"Diamond Shop","now":{"clothing":[1352,1353,1354,1351,1355,1573,735,734,736,733,737,608,607,606,609,610,772,567,584,568,773,569],"den":[]},"former":{"clothing":[2968,2969,2970,2967,2971,1875,2722,2723,2724,3280,3281,3279,3283,3285,3286,3287,3284,3288,3353,3355,3023,3024,3025,3022,3026,2325,2324,2322,4081,3628,3626,2918,2919,2920,2917,2921,4013,4011,4014,2769,2770,2771,2874,2875,2872,4408,3933,4385,3931,3932,4378,4330,4329,3834,4239,4240,4241,4238,4242,1333,1067,2844,2842,2843,1370,1371,1368,1372,3246,3244,3506,3359,3360,3361,3358,3362,4095,2923,2924,2925,2922,2926,2963,2964,2965,2962,2966,2302,2303,2304,1893,815,816,817,814,818,2794,2795,2796,2793,2797,376,3523,3525,3526,3153,3155,3178,3180,2958,2959,2960,2957,2961,3763,2639,2641,2642,2562,2563,2564,2561,2565,1395,1396,1397,1394,1398,1524,1525,1520,885,1738,886,1739,887,1740,884,1737,3429,3430,3428,3432,888,1741,3803,3804,3805,3802,3806,2713,2714,2715,2712,2716,1328,1329,1330,1327,1331,2804,2805,2806,2803,2807,2538,3847,3848,3846,3849,2516,2517,2513,2515,2518,3606,3604,3842,3843,3844,3841,3845,3938,3936,3937,3308,3309,3310,3307,3311,3313,3314,3315,3312,3316,2879,2880,2877,2493,1916,2558,2559,2556,1917,686,687,1891,2301,2913,2914,2915,2912,2916,688,685,689,2708,2709,2711,2242,3745,3743,3747,2246,4158,4365,2283,2281,3623,3625,4322,4321,4360,1828,1829,3434,3435,3436,3433,3437,3261,3262,3260,3264,3266,3267,3268,3265,3269,2741,2742,2743,2740,2744,2336,3451,3752,4071,2903,2904,2905,2902,2906,3033,3034,3035,3032,3036,3928,3926,3927,3457,3458,3459,3456,3460,2979,2799,2800,2801,2798,2802,3039,3037,4403,958,1783,959,1784,960,1785,957,1782,961,1786,3863,3865,3866,3867,3864,3868,914,915,916,913,917,1149,1150,1151,1148,1152,2869,2870,2867,2434,2431,2436,2430,3497,3496,3499,1301,2736,2084,2085,2086,2087,1303,2488,2490,2491,1304,4034,4035,4036,4033,4037,3569,3570,3568,3572,4326,4325,3018,3019,3017,3021,3921,3474,3472,3473,2751,2752,2753,2750,2754,3564,3565,3566,3563,3567,3177,3170,3838,1385,3490,3491,3492,3489,3493,2004,3487,2839,2837,2838,2820,4481,2467,2468,2469,4413,2002,2470,2466,1497,1825,3105,2619,2620,2621,2618,2622,2634,2635,2633,2637,2849,2847,2848,2006,1892,2312,2310,4387,4388,4386,4389,1925,640,641,642,639,643,4074,4075,4077],"den":[]}},
|
||||
"173":{"shop":"Diamond Shop","music":true,"now":{"clothing":[],"den":[3485,3442,3433,3613,1279,2576,3436,649,5561,2565,3563,3564,5562,3565,3483,3447,4423,3566,3759,4403,4404,4405,4406,3567,4511,3587,3484,3588,3568,4509,3400,3439,4499,4487,4505,4508,4498,4488,4504,4489,4502,4493,4496,4483,4491,4486,4503,4501,4490,4495,4500,4497,4494,4506,4485,4507,4484,4492,3159,3486,3569,3153,4407,4408,4409,4410,4411,4412,4413,4476,4480,4481,4478,4479,4477,5593,5594,4422,4420,4421,4418,4414,4415,4416,4417,4419,3570,895,3571,3572,3445,3482,3573,3140,3481,3702,2947,66,2279,3574,3993,1278,3042,5654,5655,1673,4159,3575,3487,3576,3444,4512,3441,4510,3620,948,3409,3577,3578,3370,3360,3366,3364,3359,3363,3365,3361,3701,3579,3581,742,4425,4431,4429,4427,4426,4430,4428,4441,4442,4443,4438,4437,4439,4440,3758,4151,3582,3440,3583,3584,3446,1610,5301,3435,4150,4432,4435,4436,4433,4424,4154,4156,1478,2610,2247,1683,2250,3659,3060,3662,1921,2224,2645,1679,2641,3661,2863,1919,2225,2611,1346,2851,1680,2442,2245,2226,3051,2246,2443,2441,1681,2445,2249,1682,1917,3053,2444,1918,3660,1922,1920,3059,3058,2248,1684,3052,1623,3443,3586,650,4157,4153,4152,3438,4473,4472,4474,4475]},"former":{"clothing":[],"den":[4603,4608,4606,4607,4206,5075,4636,3314,4265,2839,2842,2841,2840,3407,3408,2843,3271,4947,4946,4949,3788,3783,3790,3787,3784,4360,2514,3764,5656,5124,5113,5122,4641,4369,4632,5552,3830,4574,4582,4576,3794,3782,5078,4827,4822,4823,4834,4833,4830,4829,4824,4828,4825,4831,4826,5405,4226,4197,4194,4195,4186,4188,4189,4190,4185,4193,4187,4191,5883,5879,5885,5877,5881,5878,5880,5886,5882,4680,4675,4674,4676,4685,4677,4684,4683,4682,4679,4681,4678,4376,3792,3740,5328,704,4896,3822,3820,3821,3819,3227,5376,5789,5781,5785,5790,5784,5787,5780,5782,5786,5788,5783,4232,1070,5072,3229,3288,4239,3930,4137,3041,2110,2118,3040,2120,3329,5119,5120,5409,5174,3848,5331,5337,5558,2606,4601,4572,3849,2812,3319,4148,4149,3813,5140,3629,5556,5559,5555,4217,3169,1872,4270,3694,3689,3684,3685,3688,3692,3313,3686,3683,3687,3693,3691,3690,5540,5543,5546,5545,5547,5544,5541,5542,4372,4128,3749,3748,4131,5184,5179,5180,5181,5182,5183,5199,5201,5210,5202,5203,5205,5204,5200,5206,5207,5208,5209,5211,5212,4379,5058,5059,5062,5063,5057,5066,5067,5065,5064,5061,5060,4166,4165,4167,4639,4640,4935,3121,4233,4579,4637,5085,3844,4578,4299,4271,4269,3763,3816,5068,3811,5135,4267,4171,4172,4170,4168,4164,3845,3165,3167,3818,4301,4302,4300,4303,3739,3733,3731,3730,3729,3735,3737,3728,3727,3736,3732,3734,5101,3281,3624,3623,3675,3669,3666,3674,3672,3670,3673,3676,3665,3667,3671,3668,2312,2314,2313,5229,5230,5220,4224,4263,4264,4266,3745,4331,4136,5114,5553,5310,5551,4219,3282,4050,4044,4075,4048,4078,4077,4076,4045,4079,4080,4047,3268,2790,2791,5307,5175,3541,5315,4018,4008,4013,4024,4012,4015,4007,4009,4014,4017,4011,3544,3540,3542,3543,5103,4334,2871,2872,2873,4333,2870,5407,5125,5126,5127,5128,5129,5130,5131,5132,5133,5134,4237,4236,4235,5311,5312,5305,3741,3747,5306,3742,5309,3746,3352,3347,3350,3348,3346,3351,3349,4658,2616,1273,3809,5136,4192,3326,1249,3726,3094,3379,1359,4638,5408,1773,2629,3385,4049,3927,2619,1641,1300,3028,1268,2161,2343,3650,5843,3823,1747,2002,3796,2713,1811,5410,4906,4897,3725,4642,5406,3797,3085,3077,1274,3107,3030,3828,4298,3923,3929,3925,3921,3924,3926,3920,1160,3922,3847,3861,3867,3858,3864,3863,3860,3868,3857,3865,3859,3869,5487,5489,5488,5486,5485,5492,5490,5491,4268,3627,3309,3310,3308,5564,5565,3631,4577,3931,3125,3779,3269,3862,866,3619,3835,3836,3841,3840,3870,3834,2475,5316,5317,4231,2651,2649,2650,3778,3647,3652,3646,3648,3649,5335,4339,4335,4338,4337,4330,5069,4934,5144,5143,4926,4929,5142,4933,4598,4602,4597,3176,4631,1449,5381,3312,5219,1915,3766,3846,4133,3721,5145,5146,5147,5148,5149,5150,5151,5152,5153,5154,5155,5156,5030,5019,5008,5032,5023,5016,5013,5014,5026,5021,5025,5004,5002,5033,5006,5015,5010,5028,5022,5018,5020,5017,5012,5007,5027,5034,5003,5005,5024,5011,5009,5029,5031,4209,4208,4207,4203,4200,4205,4201,4202,4204,5343,5341,5342,5338,5344,5347,5340,5339,5345,5346,3166,3780,4635,3318,3977,3988,3982,3979,3981,3987,3983,3985,3978,3986,3976,3980,4373,4370,4368,4708,4707,5326,3287,4218,4223,3817,4581,4604,4381,4229,4228,5100,2500,2499,2495,4580,1270,5185,5187,5196,5188,5189,5191,5190,5186,5192,5193,5194,5195,5197,5198,4132,5550,3626,4936,5117,3793,3795,3317,4850,2083,4852,4854,4856,4859,4851,4862,4861,4857,4860,4853,4855,4032,4026,4029,4030,4028,4037,4031,4027,4035,4033,4034,4036,4382,4135,3744,4134,5118,3932,5592,5591,5587,5589,5590,5588,4216,4222,4221,4220,2786,2787,2788,5350,5352,5353,5354,3789,4759,4768,4764,4760,4763,4767,4762,4769,4761,4765,4766,4770,5844,5845,5846,5847,5848,5849,5850,5851,5852,5853,4937,3170,3785,3786,4633,3316,5384,3190,3781,4073,4088,4074,4019,4087,3722,3278,4199,63,5833,5834,5835,5836,5837,5838,5839,5840,5841,5842,3720,3719,4214,4296,4295,4294,4125,5557,3750,3714,3716,3708,3710,2718,3712,3709,3715,3717,3713,3718,3707,3711,3221,3219,3217,5089,5083,5086,5084,5091,5092,5090,5082,5093,5087,5081,5088,5116,36Line truncated
|
||||
"177":{"shop":"Outback Imports","now":{"clothing":[],"den":[2297,2680,1559,1558,1444,1453,1514,47,48,49,53,1631,1562,1560,164,2299]},"former":{"clothing":[],"den":[3431,399,5635,1771,1968,1972,1570,736,2114,44,4068,2999,739,4781,403,1971,1965,404,1969,3959,3958,3463,3464,3462,3461,45,425,1566,2859,2858,2860,2856,2857,2862,1941,1943,1961,1944,1967,1942,1966,3000,2473,2474,2472,2464,2466,1365,46,1446,4005,2867,3523,1349,1520,4038,2548,4883,4002,933,2869,5707,5708,3989,1565,1572,1585,1574,4054,3590,2201,2213,2198,2203,2202,2197,2211,2212,2205,2206,2204,2210,54,4779,3005,3001,3002,1363,2644,4840,5793]}},
|
||||
"178":{"shop":"Hospital Shop","now":{"clothing":[658,655,659,657,654,656],"den":[]},"former":{"clothing":[660,980,1246,2644,985],"den":[]}},
|
||||
"179":{"shop":"Adventure Shop","now":{"clothing":[],"den":[1316,1318,1317,1321,1320,1319]},"former":{"clothing":[],"den":[]}},
|
||||
"184":{"shop":"Museum Shop","now":{"clothing":[127,128,123,552,129,131,1117],"den":[]},"former":{"clothing":[224,439,441,440,781,444,443,442,782,495,132,398,3028,3753,3365,997,4200,3874,4369,3276,3773,4028,3097,4291,3562,3257,2732,3807,4046,3379,2719,4082,2643,2974,3854,3195,798,1014,2749,2900,3691,4132,3479,3466,3633,3350,3030,3095,3003,3955,3601,3440,4243,840,220,839],"den":[]}},
|
||||
"191":{"shop":"Play-As-Your-Pet Shop","music":false,"now":{"clothing":[],"den":[1339,1334,1341,1338,1347,1336,1337,1340,1355,1333,1342,1332,1335]},"former":{"clothing":[],"den":[]}},
|
||||
"192":{"shop":"Play-As-Your-Pet Shop","music":false,"now":{"clothing":[],"den":[1339,1334,1341,1338,1347,1336,1337,1340,1355,1333,1342,1332,1335]},"former":{"clothing":[],"den":[]}},
|
||||
"193":{"shop":"Play-As-Your-Pet Shop","music":true,"now":{"clothing":[],"den":[1339,1334,1341,1338,1347,1336,1337,1340,1355,1333,1342,1332,1335]},"former":{"clothing":[],"den":[]}},
|
||||
"212":{"shop":"Royal Ridge","now":{"clothing":[],"den":[1548,1465,1466,1467,1464,1469,1470]},"former":{"clothing":[],"den":[]}},
|
||||
"216":{"shop":"April Fools' Shop","now":{"clothing":[1427,922,1156,740,923,1428,921,920],"den":[4893,4892,4891,4889,4887,4894,4888,4890,4878,4865,4863,4866,4471,4470,4482,4461,4463,3595,3600,3597,3598,2031,2038,2033,2035,2039,3596,912,909,907,910,908,911]},"former":{"clothing":[],"den":[]}},
|
||||
"234":{"shop":"Jam Mart Furniture (New Jammer)","now":{"clothing":[],"den":[338,131,295,647,152,357]},"former":{"clothing":[],"den":[]}},
|
||||
"238":{"shop":"Beta Shop","now":{"clothing":[],"den":[1674,1670,5618,1672,4925,4924,4921,4920,4922,1651,4923,1652,1675,5621,1659,5617,1667,5623,1660,1668,5619,1661,19,21,5631,5626,5630,5632,5624,5628,5627,5625,5629]},"former":{"clothing":[],"den":[3242,3247,3252,3253,1671,3254,3245,3243,3246,3251,3248,3255,3244]}},
|
||||
"250":{"shop":"Marine Marvels","now":{"clothing":[],"den":[1796,1798,1795,1797]},"former":{"clothing":[],"den":[]}},
|
||||
"271":{"shop":"Bounce House Shop","now":{"clothing":[],"den":[2578,1863,1862,1860,1859,1858,1856]},"former":{"clothing":[],"den":[]}},
|
||||
"323":{"shop":"Topiary Shop","now":{"clothing":[],"den":[2617,1432,642,1251,3913,3091,3373,714,1361,3904,1433,707,2630,3381,1066,971,2613,676,748,1642,1434,675,2941,1428,2155,2332,633,3391,1716,1997,608,808,1452,2711,1812,1200,3914,677,3903,3387,3082,4141,2945,1427,607,2943,643]},"former":{"clothing":[],"den":[]}},
|
||||
"324":{"shop":"Cloud Shop","now":{"clothing":[962,963,964,965,966,967],"den":[2008,2001,1996,2007,1999,2009,1986,1987,1988,1989,1991,1993]},"former":{"clothing":[],"den":[]}},
|
||||
"325":{"shop":"Cloud Shop","now":{"clothing":[962,963,964,965,966,967],"den":[2008,2001,1996,2007,1999,2009,1986,1987,1988,1989,1991,1993]},"former":{"clothing":[],"den":[]}},
|
||||
"345":{"shop":"Schoolhouse Shop","now":{"clothing":[],"den":[2795,2796,2797,2798,2150,2149,2148,2145,2139,2142,2140,2141,2147]},"former":{"clothing":[],"den":[]}},
|
||||
"346":{"shop":"AJ Birthday Shop","now":{"clothing":[1020,1019,1018,1017,1016,1015],"den":[3358,3357,3089,3079,3020,3018,3022,2707,2633,2626,2623,2336,2158,2004,1816,1758,1753,1755,1754,1301,1752,1759,1756,1757,1302,1114,1115,3354,1116,1117,3353,3356,3355,1118,1119,1120,1121,1122,1123,1124,1125,1127,1126,3875,3874,5001,5177,5392,5616,5893,2827,2825,2826,2823,2822,2824,1128]},"former":{"clothing":[],"den":[]}},
|
||||
"362":{"shop":"Theater Shop","now":{"clothing":[],"den":[2128,2136,2129,2138,2135,2130,2131,2134,2137,2127,2132,2133]},"former":{"clothing":[],"den":[]}},
|
||||
"374":{"shop":"Astronomy Shop","now":{"clothing":[],"den":[2379,2386,2385,2390,2382,2392,2388,2380,2391,2383,2384]},"former":{"clothing":[],"den":[2387]}},
|
||||
"396":{"shop":"??? (Basement of Secrets)","now":{"clothing":[],"den":[2544,2543,2542]},"former":{"clothing":[],"den":[]}},
|
||||
"399":{"shop":"Chinese New Year Shop and others","now":{"clothing":[],"den":[2520,2522,2519,2521,2524,2523,3512,3551,3501,3502,3498,3500,5278,5279,5284,5282,5280,5281,5283,5764,5763,5765,5769,5766,5767,5768,2992,2988,2997,2993,2994,4786,4794,4787,4795,4784,4793,4792,2730,2720,2728,2721,2723,2724,2727,2722,2729,2726,5038,5039,5047,5036,5040,5042,5045,4317,4326,4320,4327,4319,4325,4324,2957,2958,2962,2963,2979,2976,5469,5470,5475,5473,5471,5472,5474,1660,1051,497,2178,2357,607,763]},"former":{"clothing":[],"den":[]}},
|
||||
"400":{"shop":"Candy Shop","now":{"clothing":[],"den":[2560,2567,2568,2557,2558,2561,2559,2569,2556,2563,2564,2562]},"former":{"clothing":[],"den":[]}},
|
||||
"415":{"shop":"Diamond Shop","now":{"clothing":[1352,1353,1354,1351,1355,1570,1572,1574,1571,1573,1554,1511,4531,4529,4532,4530,4533,273,570,1537,856,735,734,736,733,737,608,607,606,609,610,1232,1230,1231,1233,1234,1495,772,567,584,568,773,569,1485,1541],"den":[]},"former":{"clothing":[2968,2969,2970,2967,2971,2262,2263,2264,1876,1878,1877,1875,566,2722,2723,2724,2725,2721,3280,3281,3282,3279,3283,3285,3286,3287,3284,3288,1515,1519,3423,3420,3419,3422,2254,2253,2255,3421,2417,2418,2420,2419,2421,2947,2951,2950,2949,2948,3356,3353,3354,3355,3357,3023,3024,3025,3022,3026,2185,2184,1895,2227,2237,2228,2226,2225,2229,2231,2236,2230,563,2126,2325,2326,2324,2322,2328,4079,4081,4078,4080,3628,3630,3627,3626,3629,2992,2993,2991,2994,2995,2918,2919,2920,2917,2921,2101,4015,2176,2179,1948,4013,4012,4011,4014,4018,2173,4022,2174,4016,4021,2177,1361,4019,1362,4020,2175,2172,4017,2178,2180,2181,4023,2769,2770,2771,2768,2772,2997,2998,2996,2999,3000,2874,2875,2872,2873,2876,3541,3539,3540,3538,3537,4409,4408,4406,4407,4410,3896,3898,2940,2937,2938,2941,2939,3899,3897,3900,3935,4383,3933,4376,4379,4385,4381,4384,3931,4377,4380,3932,3934,4378,4382,2020,4330,4331,4329,4332,3831,3834,3833,3835,3832,4239,4240,4241,4238,4242,2138,2021,4259,4257,4256,4258,4260,1904,1066,1334,1333,1067,1088,1906,3971,3972,3974,3973,3975,2930,2927,2928,2931,2929,2846,2844,2842,2843,2845,3820,3821,3818,3822,3819,3220,3221,3223,3222,3224,1370,1371,1368,1369,1372,4348,4345,4347,4346,4349,3981,3982,3984,3983,3985,3246,3244,3247,3245,3248,3507,3505,3516,3515,3512,3509,3511,3514,3508,3510,3871,3506,3513,3359,3360,3361,3358,3362,4448,4446,4425,4450,4432,4437,4454,4440,4427,4457,4449,4435,4456,4451,4447,4426,4438,4452,4431,4443,4455,4441,4433,4444,4439,4453,4460,4429,4445,4458,4461,4434,4459,4436,4430,4428,4442,3869,3870,4095,4097,4098,4094,4096,4498,4497,4500,4501,4499,1822,1823,1824,1821,1820,2728,2726,2727,2730,2729,1462,1309,1310,2923,2924,2925,2922,2926,2439,1884,2018,1882,2440,2963,2964,2965,2962,2966,2860,2858,2857,2861,2859,3191,3192,3190,3194,3193,2952,2956,2955,2954,2953,3134,3140,2300,3143,3137,2302,3142,3135,3141,3136,3138,2303,2304,3139,1893,2791,2789,2792,2790,2788,815,816,817,814,818,1852,1512,1516,1496,270,1498,2829,2830,2831,2828,2827,4004,4001,4003,4002,4005,1563,1566,1562,1565,1564,2794,2795,2796,2793,2797,2125,2773,2774,2777,2775,2776,376,2444,565,2159,4009,4006,4008,4007,4010,2141,3117,3116,3114,3118,3115,2865,2863,2862,2866,2864,1935,1934,3294,3295,3297,3296,3298,3523,3524,3522,3525,3529,3528,3531,3530,3526,3527,2015,3153,3155,3152,3179,3156,3154,3172,3178,3176,3180,2958,2959,2960,2957,2961,1339,902,1550,1804,1551,1805,1549,1803,1552,1806,1553,1807,3763,3760,3761,3764,3762,2639,2641,2642,2638,2640,2824,2825,2826,2823,2822,2562,2563,2564,2561,2565,1860,1858,1857,1861,1859,2626,2624,2623,2627,2625,1395,1396,1397,1394,2019,1398,1993,1992,1991,1994,1995,3207,3206,3208,3204,3205,4286,4282,4284,4283,4285,3212,3210,3211,3209,3213,2441,1524,1525,1520,1521,1523,1522,885,1738,1347,886,1739,887,1740,884,1737,1746,1744,1745,1747,3429,3430,3431,3428,3432,888,1741,2156,2155,3803,3804,3805,3802,3806,2153,3800,3797,3799,3798,3801,2713,2714,2715,2712,2716,2443,4092,4093,4091,4089,4090,3417,3415,3416,3418,3414,3612,3610,3613,3609,3611,1328,1329,1330,1327,1331,3976,3977,3979,3978,3980,2804,2805,2806,2803,2807,2512,2524,2538,2505,3847,3848,3846,3849,2502,2539,2942,2946,2945,2504,2511,3850,2520,3851,2551,2531,3765,3766,3767,3768,3769,2510,2507,2508,2509,2536,2516,2517,2514,2513,2515,2518,2537,2521,2506,3606,3607,3604,3605,3608,2503,3842,3843,3844,3841,3845,2519,2944,2943,1546,1544,1545,3940,3938,3936,2935,2932,2933,2936,2934,3937,3939,3989,3988,3986,3987,3990,3308,3309,3310,3307,3311,3313,3314,3315,3312,3316,2879,2880,2877,2878,2881,2100,2493,2494,2492,2495,2496,1914,1916,1913,2558,2557,2559,2556,2560,1917,1915,1243,2143,2139,2122,2130,2129,2127,3889,3886,3887,3890,3888,686,687,1891,2301,2913,2914,2915,2912,2916,688,685,2158,1868,1865,1866,1869,1867,2442,689,2708,2709,2710,2707,2711,2243,2244,2245,2242,2247,3745,3746,3744,3743,3747,2246,2248,3370,3373,3371,3121,3122,3119,3120,3123,3374,878,3372,4155,4157,4158,4159,4156,1962,2093,3554,3547,3548,3551,3549,3550,3553,3552,3556,3555,4366,4363,4364,4365,4367,2283,2280,2281,2279,2282,2123,3624,3622,3623,3625,3621,271,1849,4322,4323,4321,4324,1931,1961,4361,4358,4359,4360,4362,1887,1890,1826,1828,1829,3883,3882,3884,3881,3885,1885,3434,3435,3436,3433,3437,3261,3262,3263,3260,3264,3266,3267,3268,3265,3269,3816,3813,3814,3817,3815,3453,2335,3455,2333,3187,3188,3185,3186,3189,2741,2742,2743,2740,2744,2336,2334,3452,3451,3454,2337,3748,3751,3749,3752,3750,1946,1359,1360,2855,2853,2852,2856,2854,2987,2988,2986,2989,2990,1463,2271,2786,2784,2269,2787,2272,2270,2785,2273,2783,1850,4070,4069,4068,4071,4072,3536,3534,3535,3533,3532,3965,3961,3964,3962,3963,272,1281,2437,2903,2904,2905,2902,2906,1604,1656,1659,1660,2134,3033,3034,3035,3032,3036,2140,3930,3928,3926,3927,3929,2186,4287,4288,4290,1835,1836,1838,1837,1839,1Line truncated
|
||||
"420":{"shop":"Studio Corner","now":{"clothing":[],"den":[5509,1904,1914,1916,1911,1905,1906,1923,1924,1925,4957,1907,1928,1910,5510,4958,5609,5611]},"former":{"clothing":[],"den":[2924,3069,2718,3070,2923,3184,3012,5821,3071]}},
|
||||
"423":{"shop":"Epic Wonders","now":{"clothing":[],"den":[1177,956,728,1473,795,1157,1150,1170,2051,2041,2040,2054,2066,2052,1463,2067,1151,2276,850,1041,735,5607,3561,3293,851,4179,843,2315,2316,1217,1313,2193,730,921,1476]},"former":{"clothing":[],"den":[1178,1207,2792,1040,725,1576,3951,4116,4689,2477,4100,4282,1084,1264,1085,1222,1223,1263,1243,1242,1087,4089,2922,1208,922,3591,1209,4778,1522,2209,2270,5659,3455,2554,3505,4101,1176,4464,4466,4006,4842,4465,3960,4081,2447,1156,2448,1097,3876,3514,4841,852,803,1158,4211,4292,4106,3997,2030,2788,2675,1455,1457,1458,1435,1459,1456,2718,4112,1210,1215,1008,1132,3884,1009,5658,5660,1098,3184,4811,4817,802,4213,4212,4210,4333,5291,5761,5056,5467,731,1211,3635,3633,1216,5661,2353,804,2805,936,4777,1819,3936,2449,1845,729,4283,1137,4058,4053,4886,2359,1218,3933,1219,3992,2191,3503,4780]}},
|
||||
"584":{"shop":"??? (Epic Dens)","now":{"clothing":[],"den":[2643,2771,2400,2916,1351,2487,2407,1472,1489,3064,1599,2698,2711,3152,2360,3199,3215,3200,3203,3204,3206,3207,609,3376,2802,3411,1622,2337,3457,3477,3497,3506,1452,3510,3520,3524,3593,2809,3625,3622,3621,2642,2687,2406,2405,2927,2928,2933,2934,2935,2936,2794,2800,3888,3892,2485,3937,1637,1980,3991,3974,3995,4003,4046,4055,4061,4064,4099,4102,4109,4111,4124,4122,4121,4123,4120,4126,1852,4277,4284,4285,4288,4307,4315,4313,4391,4395,4448,4453,4462,4468,4521,4537,4558,4583,4588,4594,4612,4619,4621,4654,4693,4711,4730,4772,4843,4876,4885,4913,4944,4989,1947,2024,1975,2023,1974,2109,3291,2119,2116,5055,2751,2113,3261,1957,2106,2092,5178,3336,5213,3458,1571,5290,5300,5302,5319,5348,5370,5385,5393,5403,5404,5436,5468,5484,5493,2389,3147,2098,5581,5596,1042,5652,5677,5709,5760,5762,5794,5822,5824,2056,5873,5876,5925]},"former":{"clothing":[],"den":[]}},
|
||||
"589":{"shop":"Topiary Shop (Lit)","now":{"clothing":[],"den":[2618,1653,1380,1654,3916,3092,3374,1378,1383,3905,1655,1388,2631,3382,1376,1379,2614,1386,1644,1656,1387,2942,1658,2157,2333,1390,3392,1732,1998,1385,1384,2712,1813,1389,3915,1377,3906,1375,3388,3083,2946,1657,1381,2944,1382]},"former":{"clothing":[],"den":[]}},
|
||||
"625":{"shop":"Ocean Diamond Shop","now":{"clothing":[],"den":[3139,3144,3142,3138,3141,3143,3210,3214,3054,3056,3057,3055]},"former":{"clothing":[],"den":[]}},
|
||||
"626":{"shop":"Ocean Diamond Shop","now":{"clothing":[1455,1453,1456,1454],"den":[]},"former":{"clothing":[1945,3949,3948,3942,3941,3951,3952,3950,3943,3946,3947,3945,3944,1452,1451,4129,3993,3994],"den":[]}},
|
||||
"666":{"shop":"Forgotten Relics","now":{"clothing":[1590,1591,1592,1587,1588,1589,474],"den":[]},"former":{"clothing":[1959,1960],"den":[]}},
|
||||
"676":{"shop":"Alpha Headquarters","now":{"clothing":[1639,1640,1641,1638,1642],"den":[]},"former":{"clothing":[4506,2062,2063,2064,2061,2065,2381,2377,1712,1713,1714,1711,1715,2379,2378,2380],"den":[]}},
|
||||
"677":{"shop":"Alpha Headquarters","now":{"clothing":[1620,1621,1618,1622,1619],"den":[]},"former":{"clothing":[4505,2042,2043,2044,2041,2045,2366,2364,1692,1693,1694,1691,1695,2365,2363,2362],"den":[]}},
|
||||
"678":{"shop":"Alpha Headquarters","now":{"clothing":[1624,1625,1626,1623,1627],"den":[]},"former":{"clothing":[4507,2047,2048,2049,2046,2050,2357,2360,1697,1698,1699,1696,1700,2361,2359,2358],"den":[]}},
|
||||
"679":{"shop":"Alpha Headquarters","now":{"clothing":[1634,1635,1636,1633,1637],"den":[]},"former":{"clothing":[4504,2057,2058,2059,2056,2060,2375,2376,1707,1708,1709,1706,1710,2373,2372,2374],"den":[]}},
|
||||
"680":{"shop":"Alpha Headquarters","now":{"clothing":[1629,1630,1631,1628,1632],"den":[]},"former":{"clothing":[4502,2052,2053,2054,2051,2055,2369,2370,1702,1703,1704,1701,1705,2367,2371,2368],"den":[]}},
|
||||
"681":{"shop":"Alpha Headquarters","now":{"clothing":[1644,1645,1646,1643,1647],"den":[]},"former":{"clothing":[4503,2067,2068,2069,2066,2070,2382,2385,1717,1718,1719,1716,1720,2386,2384,2383],"den":[]}},
|
||||
"684":{"shop":"Diamond Shop","now":{"clothing":[],"den":[3440,3445,3447,3436,3433,3442,3439,3444,3441,3446,3435,3443,3438,3481,3482,3483,3484,3486,3487,3563,3564,3565,3566,3587,3588,3568,3569,3570,3571,3572,3573,3574,3584,3576,3577,3578,3586,3581,3579,3701,3702,3759,3758]},"former":{"clothing":[],"den":[]}},
|
||||
"687":{"shop":"Ancient Antiquities","now":{"clothing":[],"den":[3555,3556,3558,3557,3554,3559]},"former":{"clothing":[],"den":[4559,4562]}},
|
||||
"688":{"shop":"Ancient Armory","now":{"clothing":[1770,1771,1772,1769,1773,1899,1900,1901,1898,1902],"den":[]},"former":{"clothing":[],"den":[]}},
|
||||
"689":{"shop":"Diamond Shop","now":{"clothing":[],"den":[3567,3575,3582,3583]},"former":{"clothing":[],"den":[]}},
|
||||
"709":{"shop":"Giant Gift Pile (Shop)","now":{"clothing":[4165,4166,4167,4168,4169,4170,4171,4172,4173,4174,4175,4176,4177,4178,4179,4180,4181,4182,4183,4184,4185,4186,4187,4188,4189,4190,4191,4192,4193,4194,4195,4196],"den":[]},"former":{"clothing":[],"den":[]}},
|
||||
"713":{"shop":"Ancient Treasures","now":{"clothing":[],"den":[3850,3855,3851,3852,3854,3853]},"former":{"clothing":[],"den":[]}},
|
||||
"778":{"shop":"Eco Shop","now":{"clothing":[],"den":[4626,4625,4627,4629,4540,4541,4630]},"former":{"clothing":[],"den":[]}},
|
||||
"790":{"shop":"Spooky Shop (Phantom Vortex)","now":{"clothing":[3323,3324,3325,3322,3326,3328,3329,3330,3327,3331,3674,3675,3676,3673,3677,2566,2567,2568,2569,2570,2571,4100,4102,2578,2572,4104,2573,2574,2575,4101,2576,2577,4103,4099,3651,3650,2579,2580,2581,2582,2583,2584,2585,2586,2587,2588,2589,2590,2591,3046,3054,3052,3044,3045,3053,3043,3042,3050,3049,3047,3048,3051,3699,3700,3701,3698,3702,3724,3725,3726,3723,3727,2592,2593,2594,2595,2596,2597,2598,2599,2600,2601,2602,2603,2604,4117,4118,3070,4121,3074,4122,3079,3078,3069,4119,3071,3068,4120,3080,3073,3076,3075,3077,3072,4128,4107,2617,2605,2606,2607,2608,2609,2610,2611,4105,2612,2613,3653,3654,3655,3652,3656,2614,4110,4106,4109,4108,2615,2616,3704,3705,3706,3703,3707,3729,3730,3731,3728,3732,3308,3309,3310,3307,3311,3313,3314,3315,3312,3316,3061,3062,3063,3060,3064,3319,3320,3317,3318,3321,3333,3334,3336,3332,3335,3339,3340,3342,3338,3341,3694,3695,3696,3693,3697,3719,3720,3721,3718,3722,3067,3065,3066,3681,4116,4115,3679,3682,4114,4111,3680,3678,4113,4112,3709,3710,3711,3708,3712,3734,3735,3736,3733,3737,3670,3668,3669,3671,3672,3714,3715,3716,3713,3717,3739,3740,3741,3738,3742,3084,3649,3082,3085,3659,3647,3090,3091,3337,3089,3092,3661,3660,3658,3083,3081,3644,3643,3645,3642,3646,3657,3648,3662,3087,3088,3343,3086,3093,4124,4125,4126,4123,4127,3664,3665,3666,3663,3667,4539,4538,4537,4534,4535,4536,4542,4543,4540,4541,4544,4545,3059,3058,3057,3055,3056],"den":[]},"former":{"clothing":[],"den":[]}},
|
||||
"801":{"shop":"Jambassador Plushie Shop","now":{"clothing":[],"den":[5231,5422,5239,5424,5494,5466,4261,5235,5413,4259,5496,5456,5497,5457,4252,5419,4254,4257,4247,5415,5242,5411,4249,5498,5458,5237,5426,4255,4258,4245,5499,5459,5500,5460,5233,5416,5501,5464,5238,5417,5505,5461,5502,5465,5503,5462,5241,5420,4248,4250,5236,5423,4251,5232,5425,4260,5234,5427,4242,5412,5504,5463,4253,4244,5421,4243,5240,5414,4256,4246,5418]},"former":{"clothing":[],"den":[5495,5455]}},
|
||||
"803":{"shop":"Hall of Animals","now":{"clothing":[],"den":[782,668,662,656,836,548,500,622,787,501,1625,574,549,600,588,595,1626,551,505,1627,507,597,589,569,1628,552,515,516,1629,553,566,556,523,573,798,525,503,524,517,518,521,509,511,510,502,504,522,513,514,512,508,520,519,550,554,555,557,558,567,568,570,571,572,575,576,577,590,591,592,593,598,599,594,596,604,601,602,605,603,623,627,626,625,624,655,654,652,651,653,657,658,659,660,661,663,664,665,666,667,669,670,671,672,673,706,783,784,785,786,788,796,797,799,800,801,833,834,835,837,838]},"former":{"clothing":[],"den":[]}},
|
||||
"805":{"shop":"Hall of Animals","now":{"clothing":[],"den":[2608,1419,1247,3912,3090,3372,1358,3901,1421,2628,3383,2607,1638,1422,3023,1430,2238,2377,3393,1748,2006,2714,1855,3911,3902,3389,3080,4145,3025,1420,3024]},"former":{"clothing":[],"den":[]}},
|
||||
"806":{"shop":"Hall of Animals","now":{"clothing":[],"den":[1065,2156,1439,2621,2003,1815,1639,1436,1796,2706,621,442,3088,1798,970,3872,3078,2335,2625,445,443,480,1737,1450,3019,3017,1451,3380,1201,441,3021,809,3371,1250,479,447,2632,538,1360,444,750,3873,1795,1454,1797]},"former":{"clothing":[],"den":[]}},
|
||||
"807":{"shop":"Hall of Animals","now":{"clothing":[],"den":[2616,1273,1249,3726,3094,3379,1359,3907,1773,2629,3385,2619,1641,1300,3028,1268,2161,2343,1747,2002,2713,1811,3725,3908,3085,4144,3077,1274,3030]},"former":{"clothing":[],"den":[]}},
|
||||
"816":{"shop":"Phantom Emporium (Shop)","now":{"clothing":[3588,1658,3589,1657,1659,1660,1462,3590,3591,3595,3594,1516,1512,789,1449,1310,1309,1550,1552,1553,1551,1549,3592,3593,4603,4604,4605,4606],"den":[2840,2842,3408,3407,945,944,946,2110,2120,3040,3041,1236,1241,1237,1238,1239,1240,3324,1524,3328,3327,3325,1529,3329,3326,3323]},"former":{"clothing":[],"den":[]}},
|
||||
"817":{"shop":"Hall of Animals","now":{"clothing":[],"den":[4,5,6,7,10,11,12,14,17,18,20,22,23,25,28,26,29,30,31,5644,5645,5646,5647,5648,5649,5650,5657,5697,5698,5699,5700,5701,5702,5703,5704,5705,5706]},"former":{"clothing":[],"den":[]}},
|
||||
"818":{"shop":"Phantom Emporium (Shop)","now":{"clothing":[3588,1658,3589,1657,1659,1660,1462,3590,3591,3595,3594,1516,1512,789,1449,1310,1309,1550,1552,1553,1551,1549,3592,3593,4603,4604,4605,4606],"den":[2840,2842,3408,3407,945,944,946,2110,2120,3040,3041,1236,1241,1237,1238,1239,1240,3324,1524,3328,3327,3325,1529,3329,3326,3323]},"former":{"clothing":[],"den":[]}},
|
||||
"819":{"shop":"Phantom Emporium (Shop)","now":{"clothing":[3588,1658,3589,1657,1659,1660,1462,3590,3591,3595,3594,1516,1512,789,1449,1310,1309,1550,1552,1553,1551,1549,3592,3593,4603,4604,4605,4606],"den":[2840,2842,3408,3407,945,944,946,2110,2120,3040,3041,1236,1241,1237,1238,1239,1240,3324,1524,3328,3327,3325,1529,3329,3326,3323]},"former":{"clothing":[],"den":[]}}}}
|
||||
@@ -0,0 +1,103 @@
|
||||
"use strict";
|
||||
|
||||
const defpacks = require("./defpacks.js");
|
||||
const sales = require("./sales.js");
|
||||
const {DIAMOND_TYPES} = require("./player.js");
|
||||
const wiki = require("./shop-stock.json");
|
||||
|
||||
// what stands on each shop's shelves. no file of the game says: the official
|
||||
// server sent a shop's list when it was opened. lib/shop-stock.json has it
|
||||
// from the AJ Classic Wiki, per generic list (tools/shop-stock.py makes the
|
||||
// file and says which shop was taken for which list, and where that was a
|
||||
// guess): "now", what the wiki has on sale there, and "former", what was
|
||||
// sold there once. A shop stocks all of the first, and of the second what
|
||||
// is in its season today (lib/sales.js): a shop's seasonal things come back
|
||||
// to it each year, and what left for good stays away.
|
||||
|
||||
const DEF_ITEM = 1000;
|
||||
const DEF_DEN_ITEM = 1030;
|
||||
const DEF_DIAMOND = 1054;
|
||||
const DEF_COMBINED_LIST = 1060;
|
||||
|
||||
// "kind:refId" -> diamond def id, for what a diamond shop sells.
|
||||
let diamondIds = null;
|
||||
const diamondId = (type, refId) => {
|
||||
if (!diamondIds) {
|
||||
diamondIds = new Map();
|
||||
for (const id of defpacks.diamondIds()) {
|
||||
const def = defpacks.diamondDef(id);
|
||||
// an item with two defs keeps the later one.
|
||||
diamondIds.set(`${def.type}:${def.refId}`, id);
|
||||
}
|
||||
}
|
||||
return diamondIds.get(`${type}:${refId}`);
|
||||
};
|
||||
|
||||
const KINDS = {
|
||||
clothing: {salesKind: "clothing", sold: () => defpacks.clothingIds(), diamondType: DIAMOND_TYPES.clothing},
|
||||
den: {salesKind: "denItems", sold: () => defpacks.denItemIds(), diamondType: DIAMOND_TYPES.denItem},
|
||||
};
|
||||
|
||||
// the ids of one kind a list stocks. with `asDiamonds` they are diamond def
|
||||
// ids, and what has no diamond price is left out.
|
||||
const shelf = (stock, kind, asDiamonds) => {
|
||||
const {salesKind, sold, diamondType} = KINDS[kind];
|
||||
const sellable = new Set(sold());
|
||||
const music = kind === "den" && stock.music !== undefined ? new Set(defpacks.musicIds()) : null;
|
||||
const fits = id => sellable.has(id) && (!music || music.has(id) === stock.music);
|
||||
const ids = [];
|
||||
for (const [items, onlySeasonal] of [[stock.now[kind], false], [stock.former[kind], true]]) {
|
||||
for (const id of items.filter(fits)) {
|
||||
const entry = asDiamonds ? diamondId(diamondType, id) : id;
|
||||
if (entry !== undefined && (!onlySeasonal || sales.inSeason(asDiamonds ? "diamond" : salesKind, entry))) {
|
||||
ids.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
};
|
||||
|
||||
const make = (listId, type) => {
|
||||
const stock = wiki.lists[listId];
|
||||
if (!stock) {
|
||||
return null;
|
||||
}
|
||||
if (type === DEF_ITEM) {
|
||||
return {entries: shelf(stock, "clothing", false)};
|
||||
}
|
||||
if (type === DEF_DEN_ITEM) {
|
||||
return {entries: shelf(stock, "den", false)};
|
||||
}
|
||||
if (type === DEF_DIAMOND) {
|
||||
return {entries: [...shelf(stock, "clothing", true), ...shelf(stock, "den", true)]};
|
||||
}
|
||||
if (type === DEF_COMBINED_LIST) {
|
||||
// [kinds, count per kind, entries of each kind in turn]
|
||||
// (ItemXtCommManager.setupShopItemObject).
|
||||
const parts = [[DEF_ITEM, shelf(stock, "clothing", false)], [DEF_DEN_ITEM, shelf(stock, "den", false)]]
|
||||
.filter(([, ids]) => ids.length > 0);
|
||||
const count = parts.reduce((sum, [, ids]) => sum + ids.length, 0);
|
||||
return count === 0 ? null : {
|
||||
count,
|
||||
entries: [parts.map(([kind]) => kind).join(","), parts.map(([, ids]) => ids.length).join(","), ...parts.flatMap(([, ids]) => ids)],
|
||||
};
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// what the wiki has for this list, as the entries of a `gl` reply (and their
|
||||
// count, where that is not their number); null when it has nothing, and the
|
||||
// shop is stocked some other way. made once a day, as the seasons are.
|
||||
const made = new Map(); // list id -> {day, allOnSale, stock}
|
||||
const list = (listId, type) => {
|
||||
const key = Number(listId);
|
||||
const kept = made.get(key);
|
||||
if (kept && kept.day === sales.today() && kept.allOnSale === sales.everythingOnSale()) {
|
||||
return kept.stock;
|
||||
}
|
||||
const stock = make(key, type);
|
||||
made.set(key, {day: sales.today(), allOnSale: sales.everythingOnSale(), stock: stock && stock.entries.length > 0 ? stock : null});
|
||||
return made.get(key).stock;
|
||||
};
|
||||
|
||||
module.exports = {list};
|
||||
@@ -0,0 +1,109 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const accounts = require("./accounts.js");
|
||||
const bans = require("./bans.js");
|
||||
const config = require("../config.js");
|
||||
const limits = require("./limits.js");
|
||||
const {isUint} = require("./player.js");
|
||||
|
||||
// the client's own "Create Account" screens (createAccountFlow.CreateAccount).
|
||||
// they log in to a guest zone with no credentials, check the chosen names
|
||||
// with "la" and create the account with "lc".
|
||||
|
||||
const SIGNUP_ZONE = "sbiAccountZone";
|
||||
|
||||
// status codes CreateAccountGui.showLoginCreateResultMsg understands.
|
||||
const OK = 1;
|
||||
const FAILED = -1;
|
||||
const USERNAME_TAKEN = -3;
|
||||
const USERNAME_INVALID = -4;
|
||||
const PASSWORD_INVALID = -5;
|
||||
|
||||
const STATUS = {
|
||||
username_taken: USERNAME_TAKEN,
|
||||
invalid_username: USERNAME_INVALID,
|
||||
invalid_password: PASSWORD_INVALID,
|
||||
name_not_allowed: USERNAME_INVALID,
|
||||
};
|
||||
// names asked about on one guest connection: the screens ask once or twice.
|
||||
const MAX_NAME_CHECKS = 40;
|
||||
|
||||
// "la" check types
|
||||
const CHECK_AVATAR_NAME = "1";
|
||||
|
||||
// SBCrypto.encrypt: AES-256-CBC under SHA-256 of the session's random key,
|
||||
// sent as base64 of the IV followed by the ciphertext.
|
||||
const decryptPassword = (encoded, sessionKey) => {
|
||||
try {
|
||||
const raw = Buffer.from(encoded, "base64");
|
||||
const key = crypto.createHash("sha256").update(sessionKey, "utf8").digest();
|
||||
const decipher = crypto.createDecipheriv("aes-256-cbc", key, raw.subarray(0, 16));
|
||||
return Buffer.concat([decipher.update(raw.subarray(16)), decipher.final()]).toString("utf8");
|
||||
}
|
||||
catch (err) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const handlers = {
|
||||
// CreateAccountXtCommManager.sendLoginAvailableRequest: [checkType, name,
|
||||
// nameId1, nameId2, nameId3, language, deployVersion]. any animal name built
|
||||
// from the pickers is fine; usernames must be valid and free.
|
||||
la(session, roomId, [checkType, name]) {
|
||||
session.nameChecks = (session.nameChecks || 0) + 1;
|
||||
if (session.nameChecks > MAX_NAME_CHECKS) {
|
||||
session.close();
|
||||
return;
|
||||
}
|
||||
const problem = checkType === CHECK_AVATAR_NAME ? null : accounts.usernameProblem(String(name).trim());
|
||||
session.sendXt("la", -1, problem ? STATUS[problem] : OK);
|
||||
},
|
||||
|
||||
// CreateAccountXtCommManager.sendLoginCreateRequest: [username,
|
||||
// encryptedPassword, birthday, gender, sgParams, nameId1, nameId2, nameId3,
|
||||
// avatarType, language, country, deployVersion]. the reply
|
||||
// (CreateAccount.handleLoginCreate) is [status, accountId].
|
||||
lc(session, roomId, [username, encryptedPassword, , , , name1, name2, name3, avatarType]) {
|
||||
const password = session.key ? decryptPassword(String(encryptedPassword), session.key) : null;
|
||||
if (password === null) {
|
||||
session.sendXt("lc", -1, FAILED, 0);
|
||||
return;
|
||||
}
|
||||
// checked before the sign-up limit so a mistyped form does not use it up.
|
||||
const problem = accounts.usernameProblem(String(username).trim());
|
||||
if (problem) {
|
||||
session.sendXt("lc", -1, STATUS[problem], 0);
|
||||
return;
|
||||
}
|
||||
// the game's own sign-up screens cannot show the terms, so on a public
|
||||
// server an account is made on the sign-up page or in the client.
|
||||
if (config.isPublic) {
|
||||
session.sendXt("lc", -1, FAILED, 0);
|
||||
return;
|
||||
}
|
||||
if (bans.addressBan(session.address)) {
|
||||
console.log("[signup] refused a sign-up from a banned address");
|
||||
session.sendXt("lc", -1, FAILED, 0);
|
||||
return;
|
||||
}
|
||||
if (!limits.registrationAllowed(session.address, limits.isTrustedLocal(session.address))) {
|
||||
console.log(`[signup] too many sign-ups from ${session.address}`);
|
||||
session.sendXt("lc", -1, FAILED, 0);
|
||||
return;
|
||||
}
|
||||
const avatarName = [name1, name2, name3].every(isUint) ? `${name1}|${name2}|${name3}` : undefined;
|
||||
const result = accounts.register(username, password, {type: avatarType, name: avatarName});
|
||||
if (result.error) {
|
||||
session.sendXt("lc", -1, STATUS[result.error], 0);
|
||||
return;
|
||||
}
|
||||
session.sendXt("lc", -1, OK, result.account.id);
|
||||
},
|
||||
|
||||
// the first animal's look, sent alongside "lc"; the account already has it
|
||||
// and the client expects no reply.
|
||||
ln() {},
|
||||
};
|
||||
|
||||
module.exports = {handlers, SIGNUP_ZONE};
|
||||
@@ -0,0 +1,97 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const bans = require("./bans.js");
|
||||
const manage = require("./manage.js");
|
||||
const support = require("./support.js");
|
||||
const world = require("./world.js");
|
||||
|
||||
// what the admin panel (lib/panel.js) and the moderator panel
|
||||
// (lib/modpanel.js) both do. `by` is who is doing it, for the record:
|
||||
// "admin", or a moderator's username.
|
||||
|
||||
const disciplined = () => accounts.all()
|
||||
.map(account => {
|
||||
const ban = world.moderation.banOf(account);
|
||||
return {
|
||||
username: account.username,
|
||||
banned: ban ? ban.seconds : 0,
|
||||
reason: ban ? ban.reason : "",
|
||||
by: ban ? ban.by : "",
|
||||
since: ban ? ban.since : null,
|
||||
silenced: world.moderation.silenceRemaining(account),
|
||||
};
|
||||
})
|
||||
.filter(entry => entry.banned !== 0 || entry.silenced !== 0)
|
||||
.sort((a, b) => a.username.localeCompare(b.username));
|
||||
|
||||
const ADDRESS_ERRORS = {
|
||||
not_an_address: "Not an IP address.",
|
||||
own_address: "That is this machine's own address: with a proxy or a tunnel in front, everyone's.",
|
||||
already: "Already banned.",
|
||||
too_many: "Too many banned addresses.",
|
||||
};
|
||||
|
||||
// bans an address for good and puts out whoever plays from it.
|
||||
// returns {ban, out} or {error: text}.
|
||||
const banAddress = (address, reason, by) => {
|
||||
const result = bans.banAddress(address, reason, by);
|
||||
return result.error ? {error: ADDRESS_ERRORS[result.error]} : {ban: result.ban, out: world.disconnectAddress(result.ban.address)};
|
||||
};
|
||||
|
||||
// appeals with what each is against, as it stands now.
|
||||
const appealsFor = handled => bans.appeals(handled).map(appeal => {
|
||||
const account = accounts.byId(appeal.accountId);
|
||||
const ban = account ? world.moderation.banOf(account) : null;
|
||||
const address = appeal.addressKey ? bans.addressBan(appeal.addressKey) : null;
|
||||
return {...appeal, username: account ? account.username : appeal.username, gone: !account,
|
||||
ban: ban && {seconds: ban.seconds, reason: ban.reason}, address: address && {key: address.key, reason: address.reason}};
|
||||
});
|
||||
|
||||
// an appeal answered: approved lifts the account's ban, and the ban on the
|
||||
// address it was written from when it was about that.
|
||||
const answerAppeal = (accountId, approved, reply, by) => {
|
||||
const appeal = bans.waitingAppeal(accountId);
|
||||
if (!appeal) {
|
||||
return {error: "No such appeal waiting."};
|
||||
}
|
||||
bans.answerAppeal(appeal.accountId, approved, reply, by);
|
||||
const account = accounts.byId(appeal.accountId);
|
||||
if (!approved) {
|
||||
return {ok: `${appeal.username} stays banned.`, username: appeal.username};
|
||||
}
|
||||
if (account) {
|
||||
world.moderation.actions.unban(account, by);
|
||||
}
|
||||
if (appeal.addressKey) {
|
||||
bans.unbanAddress(appeal.addressKey, by);
|
||||
}
|
||||
return {ok: `${appeal.username} is no longer banned.`, username: appeal.username};
|
||||
};
|
||||
|
||||
// A player's request for another username, approved or denied. the player
|
||||
// picked the name under the sign-up rules; they are checked again, since it
|
||||
// may have been taken while it waited.
|
||||
const answerNameRequest = (id, approve) => {
|
||||
const request = support.nameRequestById(id);
|
||||
const account = request && accounts.byId(request.accountId);
|
||||
if (!request) {
|
||||
return {error: "No such request waiting."};
|
||||
}
|
||||
if (!approve || !account) {
|
||||
support.answerNameRequest(request.id, false);
|
||||
return {ok: account ? `${account.username} keeps their name.` : "That account is gone; the request was closed.", username: account ? account.username : ""};
|
||||
}
|
||||
world.disconnect(account);
|
||||
manage.forget(account);
|
||||
const oldName = account.username;
|
||||
const problem = accounts.rename(account, request.newName);
|
||||
if (problem) {
|
||||
return {error: problem === "username_taken" ? "That username has been taken since. Deny the request."
|
||||
: "That name does not pass the sign-up rules."};
|
||||
}
|
||||
support.answerNameRequest(request.id, true);
|
||||
return {ok: `${oldName} is now called ${account.username}. They log in with the new name and the same password.`, username: account.username};
|
||||
};
|
||||
|
||||
module.exports = {disciplined, banAddress, appealsFor, answerAppeal, answerNameRequest};
|
||||
@@ -0,0 +1,12 @@
|
||||
"use strict";
|
||||
|
||||
// features this server does not have, answered with the "nothing here" reply
|
||||
// each one's client code expects, so that the client carries on instead of
|
||||
// waiting on a spinner. each entry names the client method that reads it.
|
||||
|
||||
module.exports = {
|
||||
// ReferAFriendXtCommManager.referralHasAssociateResponse: 0 = no referrer.
|
||||
refh(session) {
|
||||
session.sendXt("refh", -1, 0);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,156 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
|
||||
// what players send from the account page (/account, lib/manage.js) for
|
||||
// whoever runs the server to answer in the admin panel: requests for a new
|
||||
// username, and feedback and bug reports.
|
||||
|
||||
const SCHEMA = `
|
||||
CREATE TABLE IF NOT EXISTS name_requests (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
created_at INTEGER NOT NULL,
|
||||
account_id INTEGER NOT NULL,
|
||||
old_name TEXT NOT NULL,
|
||||
new_name TEXT NOT NULL,
|
||||
reason TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'waiting',
|
||||
handled_at INTEGER
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS feedback (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
created_at INTEGER NOT NULL,
|
||||
account_id INTEGER NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
handled_at INTEGER
|
||||
);
|
||||
`;
|
||||
|
||||
const WAITING = "waiting";
|
||||
const APPROVED = "approved";
|
||||
const DENIED = "denied";
|
||||
const WITHDRAWN = "withdrawn";
|
||||
const KINDS = ["feedback", "bug"];
|
||||
const MAX_REASON = 300;
|
||||
const MAX_TEXT = 4000;
|
||||
const MAX_OPEN_FEEDBACK = 5000; // waiting to be read; further ones are refused
|
||||
const FEEDBACK_PER_DAY = 10; // per account
|
||||
const DAY_SECONDS = 86400;
|
||||
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
const db = () => accounts.database();
|
||||
const clean = (text, max) => String(text === undefined ? "" : text).replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, " ").trim().slice(0, max);
|
||||
|
||||
const load = () => db().exec(SCHEMA);
|
||||
|
||||
const nameRow = row => ({
|
||||
id: row.id,
|
||||
createdAt: row.created_at,
|
||||
accountId: row.account_id,
|
||||
oldName: row.old_name,
|
||||
newName: row.new_name,
|
||||
reason: row.reason,
|
||||
status: row.status,
|
||||
handledAt: row.handled_at,
|
||||
});
|
||||
|
||||
const waitingNameRequest = account => {
|
||||
const row = db().prepare("SELECT * FROM name_requests WHERE account_id = ? AND status = ? ORDER BY id DESC LIMIT 1").get(account.id, WAITING);
|
||||
return row ? nameRow(row) : null;
|
||||
};
|
||||
|
||||
const nameRequestsOf = account =>
|
||||
db().prepare("SELECT * FROM name_requests WHERE account_id = ? ORDER BY id DESC LIMIT 10").all(account.id).map(nameRow);
|
||||
|
||||
// asks for a new username. one request waits at a time: a new one replaces
|
||||
// it. returns {request} or {error: "invalid_username" | "username_taken" | "same_name"}.
|
||||
const requestName = (account, newName, reason) => {
|
||||
newName = typeof newName === "string" ? newName.trim() : "";
|
||||
if (newName === account.username) {
|
||||
return {error: "same_name"};
|
||||
}
|
||||
// changing only the capitals of one's own name is not "taken".
|
||||
const problem = newName.toLowerCase() === account.username.toLowerCase() ? null : accounts.usernameProblem(newName);
|
||||
if (problem) {
|
||||
return {error: problem};
|
||||
}
|
||||
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}"`);
|
||||
return {request: waitingNameRequest(account)};
|
||||
};
|
||||
|
||||
const withdrawNameRequest = account =>
|
||||
db().prepare("UPDATE name_requests SET status = ?, handled_at = ? WHERE account_id = ? AND status = ?").run(WITHDRAWN, now(), account.id, WAITING).changes > 0;
|
||||
|
||||
// requests waiting, oldest first; or with `handled`, the latest answered.
|
||||
const nameRequests = (handled = false) => db()
|
||||
.prepare(handled
|
||||
? "SELECT * FROM name_requests WHERE status IN (?, ?) ORDER BY handled_at DESC LIMIT 200"
|
||||
: "SELECT * FROM name_requests WHERE status = ? ORDER BY id LIMIT 500")
|
||||
.all(...(handled ? [APPROVED, DENIED] : [WAITING])).map(nameRow);
|
||||
|
||||
const nameRequestById = id => {
|
||||
const row = db().prepare("SELECT * FROM name_requests WHERE id = ? AND status = ?").get(Number(id), WAITING);
|
||||
return row ? nameRow(row) : null;
|
||||
};
|
||||
|
||||
const answerNameRequest = (id, approved) =>
|
||||
db().prepare("UPDATE name_requests SET status = ?, handled_at = ? WHERE id = ? AND status = ?")
|
||||
.run(approved ? APPROVED : DENIED, now(), Number(id), WAITING).changes > 0;
|
||||
|
||||
const feedbackRow = row => ({
|
||||
id: row.id,
|
||||
createdAt: row.created_at,
|
||||
username: row.username,
|
||||
kind: row.kind,
|
||||
text: row.text,
|
||||
handledAt: row.handled_at,
|
||||
});
|
||||
|
||||
const openFeedbackCount = () => db().prepare("SELECT COUNT(*) AS count FROM feedback WHERE handled_at IS NULL").get().count;
|
||||
|
||||
// returns {ok: true} or {error: "empty" | "unknown_kind" | "too_many"}.
|
||||
const sendFeedback = (account, kind, text) => {
|
||||
const body = clean(text, MAX_TEXT);
|
||||
if (!KINDS.includes(kind)) {
|
||||
return {error: "unknown_kind"};
|
||||
}
|
||||
if (!body) {
|
||||
return {error: "empty"};
|
||||
}
|
||||
const today = db().prepare("SELECT COUNT(*) AS count FROM feedback WHERE account_id = ? AND created_at > ?").get(account.id, now() - DAY_SECONDS).count;
|
||||
if (today >= FEEDBACK_PER_DAY || openFeedbackCount() >= MAX_OPEN_FEEDBACK) {
|
||||
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}"`);
|
||||
return {ok: true};
|
||||
};
|
||||
|
||||
const feedbackOf = account =>
|
||||
db().prepare("SELECT * FROM feedback WHERE account_id = ? ORDER BY id DESC LIMIT 20").all(account.id).map(feedbackRow);
|
||||
|
||||
const feedback = (handled = false) => db()
|
||||
.prepare(handled
|
||||
? "SELECT * FROM feedback WHERE handled_at IS NOT NULL ORDER BY handled_at DESC LIMIT 200"
|
||||
: "SELECT * FROM feedback WHERE handled_at IS NULL ORDER BY id LIMIT 500")
|
||||
.all().map(feedbackRow);
|
||||
|
||||
const markFeedbackRead = id => db().prepare("UPDATE feedback SET handled_at = ? WHERE id = ? AND handled_at IS NULL").run(now(), Number(id)).changes > 0;
|
||||
|
||||
// an account being deleted: what it sent goes with it.
|
||||
const forget = account => {
|
||||
db().prepare("DELETE FROM feedback WHERE account_id = ?").run(account.id);
|
||||
db().prepare("DELETE FROM name_requests WHERE account_id = ?").run(account.id);
|
||||
};
|
||||
|
||||
const openCount = () => openFeedbackCount() + db().prepare("SELECT COUNT(*) AS count FROM name_requests WHERE status = ?").get(WAITING).count;
|
||||
|
||||
module.exports = {
|
||||
load, requestName, withdrawNameRequest, waitingNameRequest, nameRequestsOf, nameRequests, nameRequestById, answerNameRequest,
|
||||
forget, sendFeedback, feedbackOf, feedback, markFeedbackRead, openCount, MAX_REASON, MAX_TEXT, KINDS,
|
||||
};
|
||||
@@ -0,0 +1,204 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
|
||||
// two-step sign-in: a six-digit code from an authenticator app, asked for
|
||||
// after the password by the client's sign-in (lib/http.js) and the account
|
||||
// page's (lib/manage.js). A player turns it on and off on the account page.
|
||||
// time-based one-time passwords as every authenticator app makes them
|
||||
// (RFC 6238: HMAC-SHA1, six digits, a new one every 30 seconds).
|
||||
//
|
||||
// on an account:
|
||||
// totp null, or {secret (base32), since, lastStep, recovery: [SHA-256
|
||||
// of a code, ...]} once it is on. lastStep is the time step of
|
||||
// the last code taken: a code works once.
|
||||
// totpSetup {secret, at} while it is being turned on: the secret was
|
||||
// shown and no code from it has been given yet.
|
||||
// devices [{hash, at, via}]: devices that need not give a code for
|
||||
// DEVICE_DAYS after one sign-in with a code. each holds a
|
||||
// random token; only its hash is kept here.
|
||||
//
|
||||
// A recovery code stands in for a code from the app, once: for a player
|
||||
// whose phone is gone. they are shown when two-step sign-in is turned on and
|
||||
// never again. the admin can turn it off for an account from the panel.
|
||||
//
|
||||
// the secret has to be kept as it is, since every code is worked out from
|
||||
// it: whoever can read the database can make codes. it never leaves the
|
||||
// server after it was shown at setup.
|
||||
|
||||
const STEP_SECONDS = 30;
|
||||
const DIGITS = 6;
|
||||
const WINDOW = 1; // steps either side of now that are taken: clocks differ
|
||||
const SETUP_MINUTES = 15;
|
||||
const RECOVERY_CODES = 8;
|
||||
const DEVICE_DAYS = 30;
|
||||
const MAX_DEVICES = 10;
|
||||
const DEVICE_TOKEN_HEX = 48;
|
||||
const ISSUER = "Burrow";
|
||||
|
||||
const BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||
|
||||
const base32Encode = bytes => {
|
||||
let bits = "";
|
||||
for (const byte of bytes) {
|
||||
bits += byte.toString(2).padStart(8, "0");
|
||||
}
|
||||
let out = "";
|
||||
for (let index = 0; index < bits.length; index += 5) {
|
||||
out += BASE32[parseInt(bits.slice(index, index + 5).padEnd(5, "0"), 2)];
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const base32Decode = text => {
|
||||
let bits = "";
|
||||
for (const char of text) {
|
||||
bits += BASE32.indexOf(char).toString(2).padStart(5, "0");
|
||||
}
|
||||
const bytes = [];
|
||||
for (let index = 0; index + 8 <= bits.length; index += 8) {
|
||||
bytes.push(parseInt(bits.slice(index, index + 8), 2));
|
||||
}
|
||||
return Buffer.from(bytes);
|
||||
};
|
||||
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
const sha256 = text => crypto.createHash("sha256").update(text).digest("hex");
|
||||
|
||||
const sameText = (one, other) => {
|
||||
const a = Buffer.from(String(one));
|
||||
const b = Buffer.from(String(other));
|
||||
return a.length === b.length && crypto.timingSafeEqual(a, b);
|
||||
};
|
||||
|
||||
// the code for one time step (RFC 4226, with the step as the counter).
|
||||
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) % 10 ** DIGITS).padStart(DIGITS, "0");
|
||||
};
|
||||
|
||||
// the time step a code belongs to if it is one the secret gives now, a
|
||||
// step early or a step late, and later than `after`; or null.
|
||||
const stepOf = (secret, code, after = 0, at = now()) => {
|
||||
const current = Math.floor(at / STEP_SECONDS);
|
||||
let found = null;
|
||||
// every candidate is compared, so that the time taken says nothing.
|
||||
for (let step = current - WINDOW; step <= current + WINDOW; step++) {
|
||||
if (sameText(codeAt(secret, step), code) && step > after) {
|
||||
found = step;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
};
|
||||
|
||||
const isOn = account => Boolean(account.totp);
|
||||
|
||||
// what an authenticator app takes, typed in or as a QR code.
|
||||
const uri = (username, secret) => {
|
||||
const label = encodeURIComponent(`${ISSUER}:${String(username).slice(0, 30)}`);
|
||||
return `otpauth://totp/${label}?secret=${secret}&issuer=${encodeURIComponent(ISSUER)}`;
|
||||
};
|
||||
|
||||
// begins turning it on: a new secret, to be confirmed with a code.
|
||||
const begin = account => {
|
||||
account.totpSetup = {secret: base32Encode(crypto.randomBytes(20)), at: now()};
|
||||
return {secret: account.totpSetup.secret, uri: uri(account.username, account.totpSetup.secret)};
|
||||
};
|
||||
|
||||
const RECOVERY_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789"; // no l, i, o, 0 or 1
|
||||
// sixteen characters (about 79 bits): only its plain hash is kept, which is
|
||||
// safe for a code this long and was thin for the ten of earlier setups
|
||||
// (those still work until used).
|
||||
const RECOVERY_LENGTH = 16;
|
||||
const OLD_RECOVERY_LENGTH = 10;
|
||||
const recoveryCode = () => {
|
||||
let code = "";
|
||||
while (code.length < RECOVERY_LENGTH) {
|
||||
const byte = crypto.randomBytes(1)[0];
|
||||
if (byte < RECOVERY_ALPHABET.length * 8) { // 248: no letter is likelier than another
|
||||
code += RECOVERY_ALPHABET[byte % RECOVERY_ALPHABET.length];
|
||||
}
|
||||
}
|
||||
return code.match(/.{4}/g).join("-");
|
||||
};
|
||||
// as typed: capitals, spaces and the dash do not matter.
|
||||
const recoveryKey = text => String(text).toLowerCase().replace(/[^a-z0-9]/g, "");
|
||||
|
||||
// turns it on if `code` is one the secret shown at setup gives. returns the
|
||||
// recovery codes, to be shown once, or null.
|
||||
const confirm = (account, code) => {
|
||||
const setup = account.totpSetup;
|
||||
if (!setup || now() - setup.at > SETUP_MINUTES * 60) {
|
||||
account.totpSetup = null;
|
||||
return null;
|
||||
}
|
||||
const step = stepOf(setup.secret, String(code).replace(/\s/g, ""));
|
||||
if (step === null) {
|
||||
return null;
|
||||
}
|
||||
const codes = Array.from({length: RECOVERY_CODES}, recoveryCode);
|
||||
account.totp = {secret: setup.secret, since: now(), lastStep: step, recovery: codes.map(one => sha256(recoveryKey(one)))};
|
||||
account.totpSetup = null;
|
||||
account.devices = [];
|
||||
return codes;
|
||||
};
|
||||
|
||||
// is `code` good for the account, as a code from the app or a recovery
|
||||
// code? either is used up by this. returns "code", "recovery" or null.
|
||||
const verify = (account, code) => {
|
||||
if (!account.totp || typeof code !== "string" || code.length > 60) {
|
||||
return null;
|
||||
}
|
||||
const digits = code.replace(/\s/g, "");
|
||||
if (/^\d{6}$/.test(digits)) {
|
||||
const step = stepOf(account.totp.secret, digits, account.totp.lastStep);
|
||||
if (step !== null) {
|
||||
account.totp.lastStep = step;
|
||||
return "code";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const index = account.totp.recovery.indexOf(sha256(recoveryKey(code)));
|
||||
if (index !== -1 && [RECOVERY_LENGTH, OLD_RECOVERY_LENGTH].includes(recoveryKey(code).length)) {
|
||||
account.totp.recovery.splice(index, 1);
|
||||
return "recovery";
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const turnOff = account => {
|
||||
account.totp = null;
|
||||
account.totpSetup = null;
|
||||
account.devices = [];
|
||||
};
|
||||
|
||||
const freshDevices = account => account.devices.filter(device => now() - device.at < DEVICE_DAYS * 86400);
|
||||
|
||||
// A token for the device that just signed in with a code. `via` says where
|
||||
// ("launcher" or "web").
|
||||
const trustDevice = (account, via) => {
|
||||
const token = crypto.randomBytes(DEVICE_TOKEN_HEX / 2).toString("hex");
|
||||
account.devices = [{hash: sha256(token), at: now(), via}, ...freshDevices(account)].slice(0, MAX_DEVICES);
|
||||
return token;
|
||||
};
|
||||
|
||||
const deviceTrusted = (account, token) => {
|
||||
if (typeof token !== "string" || token.length !== DEVICE_TOKEN_HEX) {
|
||||
return false;
|
||||
}
|
||||
account.devices = freshDevices(account);
|
||||
const hash = sha256(token);
|
||||
return account.devices.some(device => device.hash === hash);
|
||||
};
|
||||
|
||||
const forgetDevices = account => {
|
||||
account.devices = [];
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
DEVICE_DAYS, isOn, begin, confirm, verify, turnOff, trustDevice, deviceTrusted, forgetDevices, freshDevices,
|
||||
codeAt, stepOf, uri, base32Encode, base32Decode,
|
||||
};
|
||||
@@ -0,0 +1,434 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const masterpieces = require("./masterpieces.js");
|
||||
const {MAX_ITEMS, MAX_DEN_ITEMS} = require("./player.js");
|
||||
|
||||
// trading (client side: TradeXtCommManager, TradeManager). A player keeps a
|
||||
// trade list of items on offer. someone else asks for one of them, offering
|
||||
// items of their own; the owner accepts or declines; then both confirm and
|
||||
// the items change hands.
|
||||
|
||||
// TradeItem.itemType
|
||||
const TYPE_CLOTHING = 0;
|
||||
const TYPE_DEN_ITEM = 1;
|
||||
const TYPE_PET = 3;
|
||||
|
||||
const MAX_TRADE_ITEMS = 50;
|
||||
const MAX_PETS = 1000; // as in lib/pets.js
|
||||
|
||||
// "ti" request steps (first parameter from the client)
|
||||
const STEP_OFFER = "0";
|
||||
const STEP_ANSWER = "1";
|
||||
const STEP_CANCEL = "2";
|
||||
const STEP_CONFIRM = "3";
|
||||
|
||||
// "ti" reply statuses (TradeManager.onTradeItemsResponse)
|
||||
const TRADE_REQUESTED = 0; // to the owner: here is an offer
|
||||
const TRADE_PROGRESS = 1; // followed by 0 = please confirm, 1 = done
|
||||
const TRADE_DECLINED = 2;
|
||||
const TRADE_ITEM_GONE = 3;
|
||||
const TRADE_UNAVAILABLE = 4;
|
||||
const TRADE_CLOSED = 6; // just close the trade windows
|
||||
|
||||
const AWAITING_CONFIRMATION = 0;
|
||||
const COMPLETED = 1;
|
||||
|
||||
// item kinds inside a completed trade (TradeManager.displayTradeDone)
|
||||
const DONE_CLOTHING = 0;
|
||||
const DONE_DEN_ITEM = 1;
|
||||
const DONE_PET = 2;
|
||||
|
||||
const USERNAME_SHOWN = 1;
|
||||
const MAX_OFFERED = 50; // the patched client lets this many be offered (gui.TradeManager)
|
||||
const TRADES_KEPT = 50; // per account, for its page
|
||||
const MAX_WAITING_OFFERS = 50; // offers left on one account
|
||||
const MAX_OFFERS_MADE = 20; // by one account, still waiting
|
||||
|
||||
module.exports = ({findOnline, blocks}) => {
|
||||
// TradeManager.onTradeListReceived: [username, clothingCount, (defId,
|
||||
// invIdx, color)..., denItemCount, (defId, invIdx, version, approved,
|
||||
// imageId, creatorDbId, creatorUuid)..., petCount, (speciesId, invIdx,
|
||||
// createdTs, lBits, uBits, eBits, name, personality, toy, food)...]
|
||||
const sendTradeList = (to, account) => {
|
||||
const listed = type => account.tradeList.filter(entry => entry.type === type).map(entry => entry.inv);
|
||||
const clothing = account.items.filter(item => listed(TYPE_CLOTHING).includes(item.inv));
|
||||
const denItems = account.denItems.filter(item => listed(TYPE_DEN_ITEM).includes(item.inv) && masterpieces.itemApproved(item));
|
||||
const pets = account.pets.filter(pet => listed(TYPE_PET).includes(pet.inv));
|
||||
to.sendXt("tl", -1, account.username,
|
||||
clothing.length, ...clothing.flatMap(item => [item.def, item.inv, item.color]),
|
||||
denItems.length, ...denItems.flatMap(item => [item.def, item.inv, item.version, "true", ...masterpieces.itemFields(item)]),
|
||||
pets.length, ...pets.flatMap(pet => [pet.lBits & 0xFF, pet.inv, pet.createdAt, pet.lBits, pet.uBits, pet.eBits, pet.name, 0, 0, 0]));
|
||||
};
|
||||
|
||||
const owns = (account, type, inv) => {
|
||||
const collection = type === TYPE_CLOTHING ? account.items : type === TYPE_DEN_ITEM ? account.denItems : type === TYPE_PET ? account.pets : [];
|
||||
return collection.some(entry => entry.inv === inv);
|
||||
};
|
||||
|
||||
const collectionOf = (account, type) =>
|
||||
(type === TYPE_CLOTHING ? account.items : type === TYPE_DEN_ITEM ? account.denItems : type === TYPE_PET ? account.pets : []);
|
||||
|
||||
// A masterpiece still waiting for review is nobody's to trade.
|
||||
const find = (account, type, inv) => collectionOf(account, type)
|
||||
.find(entry => entry.inv === inv && (type !== TYPE_DEN_ITEM || masterpieces.itemApproved(entry)));
|
||||
|
||||
// the field layouts differ between the offer the owner is shown (no
|
||||
// inventory ids for clothing and den items) and the completed trade.
|
||||
const offerFields = (type, entry) => {
|
||||
if (type === TYPE_CLOTHING) {
|
||||
return [entry.def, entry.color];
|
||||
}
|
||||
if (type === TYPE_DEN_ITEM) {
|
||||
return [entry.def, entry.version, "true", ...masterpieces.itemFields(entry)];
|
||||
}
|
||||
return [entry.createdAt, entry.lBits & 0xFF, entry.inv, entry.lBits, entry.uBits, entry.eBits, 0, 0, 0, entry.name];
|
||||
};
|
||||
|
||||
const doneFields = (type, entry) => {
|
||||
if (type === TYPE_CLOTHING) {
|
||||
return [DONE_CLOTHING, entry.def, entry.inv, entry.color];
|
||||
}
|
||||
if (type === TYPE_DEN_ITEM) {
|
||||
return [DONE_DEN_ITEM, entry.def, entry.inv, entry.version, "true", ...masterpieces.itemFields(entry)];
|
||||
}
|
||||
return [DONE_PET, entry.createdAt, entry.inv, entry.lBits & 0xFF, entry.lBits, entry.uBits, entry.eBits, 0, 0, 0, entry.name];
|
||||
};
|
||||
|
||||
const doneType = type => (type === TYPE_CLOTHING ? DONE_CLOTHING : type === TYPE_DEN_ITEM ? DONE_DEN_ITEM : DONE_PET);
|
||||
|
||||
// the code the owner's client uses to check it has room: clothing 0-2 and
|
||||
// den items 3-5 by environment (land, ocean, both), pets 6.
|
||||
const wantedCode = (type, entry) => {
|
||||
if (type === TYPE_PET) {
|
||||
return 6;
|
||||
}
|
||||
const def = type === TYPE_CLOTHING ? defpacks.itemDef(entry.def) : defpacks.denItemDef(entry.def);
|
||||
const environment = {0: 0, 1: 1, 3: 2}[def ? Number(def.enviroType) : 0] || 0;
|
||||
return type === TYPE_CLOTHING ? environment : 3 + environment;
|
||||
};
|
||||
|
||||
// what a traded thing is called, for the trade history.
|
||||
const nameOf = (type, entry) => {
|
||||
if (type === TYPE_PET) {
|
||||
return defpacks.string((defpacks.petDef(entry.lBits & 0xFF) || {}).titleStrId) || "Pet";
|
||||
}
|
||||
const def = type === TYPE_CLOTHING ? defpacks.itemDef(entry.def) : defpacks.denItemDef(entry.def);
|
||||
return (def && defpacks.string(type === TYPE_CLOTHING ? def.titleStrId : def.nameStrId)) || (def && def.abbrName) || `Item ${entry.def}`;
|
||||
};
|
||||
const note = (account, other, got, gave) => {
|
||||
account.tradeHistory = [{at: Math.floor(Date.now() / 1000), with: other.username, got, gave}, ...account.tradeHistory].slice(0, TRADES_KEPT);
|
||||
};
|
||||
|
||||
// would `account` have room for what it gets, once what it gives is gone?
|
||||
const LIMITS = new Map([[TYPE_CLOTHING, MAX_ITEMS], [TYPE_DEN_ITEM, MAX_DEN_ITEMS], [TYPE_PET, MAX_PETS]]);
|
||||
const fits = (account, gets, gives) => [...LIMITS].every(([type, max]) => {
|
||||
const coming = gets.filter(item => item.type === type).length;
|
||||
return coming === 0 || collectionOf(account, type).length + coming - gives.filter(item => item.type === type).length <= max;
|
||||
});
|
||||
|
||||
// ends the trade `session` is part of, telling the other side with `status`.
|
||||
const abandon = (session, status) => {
|
||||
const {trade} = session;
|
||||
if (!trade) {
|
||||
return;
|
||||
}
|
||||
const other = trade.requester === session ? trade.owner : trade.requester;
|
||||
trade.requester.trade = trade.owner.trade = null;
|
||||
other.sendXt("ti", -1, status, session.account.username, USERNAME_SHOWN);
|
||||
};
|
||||
|
||||
// moves one entry between accounts. it gets a fresh inventory id, and
|
||||
// leaves the giver's trade list, animals and den.
|
||||
const transfer = (from, to, type, entry) => {
|
||||
const collection = collectionOf(from, type);
|
||||
collection.splice(collection.indexOf(entry), 1);
|
||||
from.tradeList = from.tradeList.filter(listed => !(listed.type === type && listed.inv === entry.inv));
|
||||
if (type === TYPE_PET) {
|
||||
for (const avatar of from.avatars) {
|
||||
avatar.petInvId = avatar.petInvId === entry.inv ? 0 : avatar.petInvId;
|
||||
}
|
||||
}
|
||||
const moved = {...entry, inv: to.nextInv++};
|
||||
if (type === TYPE_CLOTHING) {
|
||||
moved.on = [];
|
||||
}
|
||||
else if (type === TYPE_DEN_ITEM) {
|
||||
Object.assign(moved, {placed: false, x: 0, y: 0, flip: 0});
|
||||
delete moved.mannequin; // a mannequin changes hands bare
|
||||
}
|
||||
collectionOf(to, type).push(moved);
|
||||
return moved;
|
||||
};
|
||||
|
||||
// TradeXtCommManager.sendTradeItemsRequest: [0, ownerName, wantedType,
|
||||
// wantedInvIdx, clothingCount, denCount, extraDenCount, petCount,
|
||||
// ...clothingInvIdx, ...denInvIdx, ...petInvIdx]
|
||||
const offer = (session, params) => {
|
||||
const owner = findOnline(params[1]);
|
||||
const refuse = status => session.sendXt("ti", -1, status, owner ? owner.account.username : params[1], USERNAME_SHOWN);
|
||||
const numbers = params.slice(2).map(Number);
|
||||
// nor is there any trading between two players when one has blocked the other.
|
||||
if (!owner || owner === session || owner.trade || session.trade || !numbers.every(Number.isInteger)
|
||||
|| blocks.either(owner.account, session.account)
|
||||
|| !accounts.featureOn(owner.account, "trading") || !accounts.featureOn(session.account, "trading")) {
|
||||
refuse(TRADE_UNAVAILABLE);
|
||||
return;
|
||||
}
|
||||
const [wantedType, wantedInv, clothingCount, denCount, extraDenCount, petCount, ...invs] = numbers;
|
||||
// checked before anything is counted through: these numbers are the client's.
|
||||
const total = clothingCount + denCount + extraDenCount + petCount;
|
||||
if (![clothingCount, denCount, extraDenCount, petCount].every(count => count >= 0 && count <= MAX_OFFERED)
|
||||
|| total > MAX_OFFERED || invs.length !== total) {
|
||||
refuse(TRADE_UNAVAILABLE);
|
||||
return;
|
||||
}
|
||||
const wanted = find(owner.account, wantedType, wantedInv);
|
||||
if (!wanted || !owner.account.tradeList.some(listed => listed.type === wantedType && listed.inv === wantedInv)) {
|
||||
refuse(TRADE_ITEM_GONE);
|
||||
return;
|
||||
}
|
||||
const counts = [[TYPE_CLOTHING, clothingCount], [TYPE_DEN_ITEM, denCount + extraDenCount], [TYPE_PET, petCount]];
|
||||
const offered = [];
|
||||
let index = 0;
|
||||
for (const [type, count] of counts) {
|
||||
for (let i = 0; i < count; i++) {
|
||||
const entry = find(session.account, type, invs[index++]);
|
||||
if (entry && !offered.some(item => item.entry === entry)) {
|
||||
offered.push({type, entry});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (offered.length !== total) {
|
||||
refuse(TRADE_UNAVAILABLE);
|
||||
return;
|
||||
}
|
||||
session.trade = owner.trade = {requester: session, owner, wantedType, wanted, offered, accepted: false, confirmed: new Set()};
|
||||
// TradeManager.displayTradeRequested: [0, requesterName, moderatedFlag,
|
||||
// wantedCode, wantedInvIdx, clothingCount, denCount, petCount, ...items]
|
||||
const ofType = type => offered.filter(item => item.type === type);
|
||||
owner.sendXt("ti", -1, TRADE_REQUESTED, session.account.username, USERNAME_SHOWN,
|
||||
wantedCode(wantedType, wanted), wanted.inv,
|
||||
ofType(TYPE_CLOTHING).length, ofType(TYPE_DEN_ITEM).length, ofType(TYPE_PET).length,
|
||||
...[TYPE_CLOTHING, TYPE_DEN_ITEM, TYPE_PET].flatMap(type => ofType(type).flatMap(item => offerFields(type, item.entry))));
|
||||
};
|
||||
|
||||
// TradeXtCommManager.sendTradeItemAcceptOrReject: 1 accept, 0 decline, 2 busy
|
||||
const answer = (session, choice) => {
|
||||
const {trade} = session;
|
||||
if (!trade || trade.owner !== session || trade.accepted) {
|
||||
return;
|
||||
}
|
||||
if (choice !== "1") {
|
||||
abandon(session, choice === "2" ? TRADE_UNAVAILABLE : TRADE_DECLINED);
|
||||
return;
|
||||
}
|
||||
trade.accepted = true;
|
||||
trade.requester.sendXt("ti", -1, TRADE_PROGRESS, AWAITING_CONFIRMATION);
|
||||
trade.owner.sendXt("ti", -1, TRADE_PROGRESS, AWAITING_CONFIRMATION);
|
||||
};
|
||||
|
||||
// both sides must confirm; then the items change hands and each side is
|
||||
// told what it received and lost (TradeManager.displayTradeDone:
|
||||
// [1, 1, receivedCount, ...received, lostCount, (kind, invIdx)...]).
|
||||
const confirm = (session, yes) => {
|
||||
const {trade} = session;
|
||||
if (!trade || !trade.accepted) {
|
||||
return;
|
||||
}
|
||||
if (!yes) {
|
||||
abandon(session, TRADE_DECLINED);
|
||||
return;
|
||||
}
|
||||
trade.confirmed.add(session);
|
||||
if (trade.confirmed.size < 2) {
|
||||
return;
|
||||
}
|
||||
const {requester, owner, wantedType, wanted, offered} = trade;
|
||||
requester.trade = owner.trade = null;
|
||||
// either side may have recycled or re-traded something while deciding.
|
||||
const stillThere = collectionOf(owner.account, wantedType).includes(wanted)
|
||||
&& offered.every(item => collectionOf(requester.account, item.type).includes(item.entry))
|
||||
&& fits(requester.account, [{type: wantedType}], offered) && fits(owner.account, offered, [{type: wantedType}]);
|
||||
if (!stillThere) {
|
||||
requester.sendXt("ti", -1, TRADE_ITEM_GONE, owner.account.username, USERNAME_SHOWN);
|
||||
owner.sendXt("ti", -1, TRADE_ITEM_GONE, requester.account.username, USERNAME_SHOWN);
|
||||
return;
|
||||
}
|
||||
const toRequester = transfer(owner.account, requester.account, wantedType, wanted);
|
||||
const toOwner = offered.map(item => ({type: item.type, entry: transfer(requester.account, owner.account, item.type, item.entry)}));
|
||||
// for each side's account page: what went which way.
|
||||
const wantedName = [nameOf(wantedType, toRequester)];
|
||||
const offeredNames = toOwner.map(item => nameOf(item.type, item.entry));
|
||||
note(requester.account, owner.account, wantedName, offeredNames);
|
||||
note(owner.account, requester.account, offeredNames, wantedName);
|
||||
accounts.save();
|
||||
requester.sendXt("ti", -1, TRADE_PROGRESS, COMPLETED, 1, ...doneFields(wantedType, toRequester),
|
||||
offered.length, ...offered.flatMap(item => [doneType(item.type), item.entry.inv]));
|
||||
owner.sendXt("ti", -1, TRADE_PROGRESS, COMPLETED, toOwner.length, ...toOwner.flatMap(item => doneFields(item.type, item.entry)),
|
||||
1, doneType(wantedType), wanted.inv);
|
||||
};
|
||||
|
||||
// A player who disconnects mid-trade leaves the other side's windows open.
|
||||
const forget = session => abandon(session, TRADE_CLOSED);
|
||||
|
||||
const handlers = {
|
||||
// [username]
|
||||
tl(session, roomId, [username]) {
|
||||
const account = accounts.byName(username);
|
||||
if (account) {
|
||||
sendTradeList(session, account);
|
||||
}
|
||||
},
|
||||
|
||||
// TradeXtCommManager.sendTradeSetRequest: [removeCount, (type, invIdx)...,
|
||||
// addCount, (type, invIdx)...]
|
||||
ts(session, roomId, params) {
|
||||
const {account} = session;
|
||||
const numbers = params.map(Number);
|
||||
if (!numbers.every(Number.isInteger)) {
|
||||
return;
|
||||
}
|
||||
const removeCount = numbers[0];
|
||||
const removals = numbers.slice(1, 1 + removeCount * 2);
|
||||
const addCount = numbers[1 + removeCount * 2];
|
||||
const additions = numbers.slice(2 + removeCount * 2, 2 + (removeCount + addCount) * 2);
|
||||
for (let i = 0; i + 1 < removals.length; i += 2) {
|
||||
account.tradeList = account.tradeList.filter(entry => !(entry.type === removals[i] && entry.inv === removals[i + 1]));
|
||||
}
|
||||
for (let i = 0; i + 1 < additions.length; i += 2) {
|
||||
const [type, inv] = [additions[i], additions[i + 1]];
|
||||
if (account.tradeList.length < MAX_TRADE_ITEMS && owns(account, type, inv)
|
||||
&& !account.tradeList.some(entry => entry.type === type && entry.inv === inv)) {
|
||||
account.tradeList.push({type, inv});
|
||||
}
|
||||
}
|
||||
accounts.save();
|
||||
sendTradeList(session, account);
|
||||
},
|
||||
|
||||
// ["1"/"0"]: busy flag while the trade window is open; nothing to answer.
|
||||
tb() {},
|
||||
|
||||
ti(session, roomId, params) {
|
||||
switch (params[0]) {
|
||||
case STEP_OFFER:
|
||||
offer(session, params);
|
||||
break;
|
||||
case STEP_ANSWER:
|
||||
answer(session, params[1]);
|
||||
break;
|
||||
case STEP_CANCEL:
|
||||
abandon(session, TRADE_CLOSED);
|
||||
break;
|
||||
case STEP_CONFIRM:
|
||||
confirm(session, params[1] === "1");
|
||||
break;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// ---- offers left for someone who is not there (the account page)
|
||||
//
|
||||
// an offer asks for one thing on another player's trade list and gives
|
||||
// clothing or den items of one's own for it, as a trade in the game does,
|
||||
// but waits on the other account until its owner answers on their page.
|
||||
// it is account.tradeOffers of whoever is asked: {id, fromId, at, wanted:
|
||||
// {type, inv}, offered: [{type, inv}]}, `fromId` the account id of who
|
||||
// made it (an id, never a name: a name can pass to somebody else).
|
||||
|
||||
const describe = (account, {type, inv}) => {
|
||||
const entry = find(account, type, inv);
|
||||
return entry ? {type, inv, name: nameOf(type, entry)} : null;
|
||||
};
|
||||
|
||||
const offers = {
|
||||
// what `account` could give: its clothing and den items, by name.
|
||||
owned: account => [TYPE_CLOTHING, TYPE_DEN_ITEM].flatMap(type => collectionOf(account, type)
|
||||
.filter(entry => type !== TYPE_DEN_ITEM || (masterpieces.itemApproved(entry) && !entry.placed))
|
||||
.map(entry => ({type, inv: entry.inv, name: nameOf(type, entry)})))
|
||||
.sort((one, other) => one.name.localeCompare(other.name)),
|
||||
|
||||
// what `account` has up for trade (pets aside: they are not offered here).
|
||||
listed: account => account.tradeList.filter(entry => entry.type !== TYPE_PET).map(entry => describe(account, entry)).filter(Boolean),
|
||||
|
||||
// offers waiting on `account`, and the ones it made that still wait.
|
||||
incoming: account => account.tradeOffers.map(offer => {
|
||||
const from = accounts.byId(offer.fromId);
|
||||
return from && {id: offer.id, from: from.username, at: offer.at, wanted: describe(account, offer.wanted),
|
||||
offered: offer.offered.map(item => describe(from, item)).filter(Boolean)};
|
||||
}).filter(offer => offer && offer.wanted),
|
||||
outgoing: account => accounts.all().flatMap(other => other.tradeOffers.filter(offer => offer.fromId === account.id)
|
||||
.map(offer => ({id: offer.id, to: other.username, at: offer.at, wanted: describe(other, offer.wanted),
|
||||
offered: offer.offered.map(item => describe(account, item)).filter(Boolean)}))).filter(offer => offer.wanted),
|
||||
|
||||
// returns null, or why not: "unavailable" | "not_listed" | "nothing" | "not_yours" | "too_many".
|
||||
make(from, to, wanted, offered) {
|
||||
if (!to || to === from || blocks.either(from, to) || !accounts.featureOn(from, "trading") || !accounts.featureOn(to, "trading")) {
|
||||
return "unavailable";
|
||||
}
|
||||
const want = {type: Number(wanted && wanted.type), inv: Number(wanted && wanted.inv)};
|
||||
if (want.type === TYPE_PET || !find(to, want.type, want.inv) || !to.tradeList.some(listed => listed.type === want.type && listed.inv === want.inv)) {
|
||||
return "not_listed";
|
||||
}
|
||||
const give = (Array.isArray(offered) ? offered : []).map(item => ({type: Number(item && item.type), inv: Number(item && item.inv)}));
|
||||
if (give.length === 0 || give.length > MAX_OFFERED) {
|
||||
return "nothing";
|
||||
}
|
||||
if (new Set(give.map(item => `${item.type}:${item.inv}`)).size !== give.length
|
||||
|| !give.every(item => [TYPE_CLOTHING, TYPE_DEN_ITEM].includes(item.type) && find(from, item.type, item.inv))) {
|
||||
return "not_yours";
|
||||
}
|
||||
if (to.tradeOffers.length >= MAX_WAITING_OFFERS || offers.outgoing(from).length >= MAX_OFFERS_MADE) {
|
||||
return "too_many";
|
||||
}
|
||||
to.tradeOffers.push({id: to.nextInv++, fromId: from.id, at: Math.floor(Date.now() / 1000), wanted: want, offered: give});
|
||||
accounts.save();
|
||||
return null;
|
||||
},
|
||||
|
||||
// the asked account says yes or no. returns null, "no_offer", or "gone"
|
||||
// when something in it has left one of the inventories since (the offer
|
||||
// is dropped then).
|
||||
answer(account, id, accept, refresh) {
|
||||
const offer = account.tradeOffers.find(candidate => candidate.id === Number(id));
|
||||
if (!offer) {
|
||||
return "no_offer";
|
||||
}
|
||||
account.tradeOffers = account.tradeOffers.filter(candidate => candidate !== offer);
|
||||
const from = accounts.byId(offer.fromId);
|
||||
const wanted = find(account, offer.wanted.type, offer.wanted.inv);
|
||||
const given = from ? offer.offered.map(item => ({type: item.type, entry: find(from, item.type, item.inv)})) : [];
|
||||
if (accept && (!from || !wanted || given.some(item => !item.entry) || blocks.either(from, account)
|
||||
|| !fits(from, [offer.wanted], given) || !fits(account, given, [offer.wanted]))) {
|
||||
accounts.save();
|
||||
return "gone";
|
||||
}
|
||||
if (accept) {
|
||||
const wantedName = [nameOf(offer.wanted.type, wanted)];
|
||||
const givenNames = given.map(item => nameOf(item.type, item.entry));
|
||||
transfer(account, from, offer.wanted.type, wanted);
|
||||
given.forEach(item => transfer(from, account, item.type, item.entry));
|
||||
note(from, account, wantedName, givenNames);
|
||||
note(account, from, givenNames, wantedName);
|
||||
// whoever is in the game sees their inventories change.
|
||||
[account, from].forEach(refresh);
|
||||
}
|
||||
accounts.save();
|
||||
return null;
|
||||
},
|
||||
|
||||
withdraw(from, toName, id) {
|
||||
const to = accounts.byName(toName);
|
||||
const before = to ? to.tradeOffers.length : 0;
|
||||
if (to) {
|
||||
to.tradeOffers = to.tradeOffers.filter(offer => !(offer.id === Number(id) && offer.fromId === from.id));
|
||||
accounts.save();
|
||||
}
|
||||
return Boolean(to) && to.tradeOffers.length < before;
|
||||
},
|
||||
};
|
||||
|
||||
return {handlers, forget, offers};
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"wallpapers": [
|
||||
{"media": 4011, "button": 4000},
|
||||
{"media": 4012, "button": 4001},
|
||||
{"media": 4013, "button": 4002},
|
||||
{"media": 4014, "button": 4003},
|
||||
{"media": 4015, "button": 4004},
|
||||
{"media": 4016, "button": 4005},
|
||||
{"media": 4017, "button": 4006},
|
||||
{"media": 4018, "button": 4007},
|
||||
{"media": 4019, "button": 4008},
|
||||
{"media": 4020, "button": 4009},
|
||||
{"media": 4021, "button": 4010},
|
||||
{"media": 3941, "button": 3950},
|
||||
{"media": 3942, "button": 3951},
|
||||
{"media": 3943, "button": 3952},
|
||||
{"media": 3944, "button": 3954},
|
||||
{"media": 3945, "button": 3955},
|
||||
{"media": 3946, "button": 3956},
|
||||
{"media": 3947, "button": 3957},
|
||||
{"media": 3948, "button": 3958},
|
||||
{"media": 3949, "button": 3953},
|
||||
{"media": 3959, "button": 3962},
|
||||
{"media": 3960, "button": 3961},
|
||||
{"media": 3993, "button": 3984},
|
||||
{"media": 3994, "button": 3985},
|
||||
{"media": 3995, "button": 3986},
|
||||
{"media": 3996, "button": 3987},
|
||||
{"media": 3997, "button": 3988},
|
||||
{"media": 3998, "button": 3989},
|
||||
{"media": 3999, "button": 3990},
|
||||
{"media": 4023, "button": 4031},
|
||||
{"media": 4024, "button": 4032},
|
||||
{"media": 4025, "button": 4033},
|
||||
{"media": 4026, "button": 4034},
|
||||
{"media": 4027, "button": 4035},
|
||||
{"media": 4028, "button": 4036},
|
||||
{"media": 4029, "button": 4037},
|
||||
{"media": 4030, "button": 4038},
|
||||
{"media": 4040, "button": 4039},
|
||||
{"media": 6453, "button": 6460},
|
||||
{"media": 6454, "button": 6461},
|
||||
{"media": 6455, "button": 6462},
|
||||
{"media": 6456, "button": 6463},
|
||||
{"media": 6457, "button": 6464},
|
||||
{"media": 6459, "button": 6465},
|
||||
{"media": 3991, "button": 4003},
|
||||
{"media": 3992, "button": 4005},
|
||||
{"media": 6452, "button": 4000},
|
||||
{"media": 6458, "button": 4009}
|
||||
],
|
||||
"stickers": [6265,6266,6267,6268,6269,6270,6271,6281,6282,6283,6284,6285,6286,6287,6288,6289,6290,6291,6292,6293,6294,6295,6296,6297,6298,6299,6300,6301,6302,6303,6304,6305,6306]
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const accounts = require("./accounts.js");
|
||||
const masterpieces = require("./masterpieces.js");
|
||||
const limits = require("./limits.js");
|
||||
const {isUint} = require("./player.js");
|
||||
const {isSilenced} = require("./moderation.js");
|
||||
|
||||
// Jammer Walls (client side: PlayerWallManager, PlayerWallGui,
|
||||
// PlayerWallXtCommManager): a page per player where they and their visitors
|
||||
// leave short messages, decorated by its owner.
|
||||
//
|
||||
// the client does this in two parts. over the game socket it asks for a
|
||||
// token for one player's wall ("wt"); with that token it then talks JSON
|
||||
// over HTTP to the address in the playerWallHost flashvar (POST /wall here):
|
||||
// CHK "has it changed?", GET, PUT a message, DEL one, and a few more.
|
||||
//
|
||||
// A wall is account.wall: {privacy, posts, params, visits, hidden, modified,
|
||||
// readAt}; a new account's empty one is made in lib/accounts.js.
|
||||
|
||||
// who may open a wall (BuddyCard.onPlayerWallPrivacyGet), as for dens.
|
||||
const NOBODY = 0;
|
||||
const BUDDIES = 1;
|
||||
const EVERYONE = 2;
|
||||
|
||||
// PlayerWallManager.handleTokenResponse
|
||||
const TOKEN_OK = 1;
|
||||
const WALL_LOCKED = -1;
|
||||
const BUDDIES_ONLY = -2;
|
||||
const UNAVAILABLE = 0;
|
||||
|
||||
const TOKEN_MINUTES = 60;
|
||||
const MAX_TOKENS = 20000;
|
||||
const MAX_WALLS_OPEN = 20; // walls one player holds a token for at a time
|
||||
const MAX_POSTS = 100;
|
||||
const MAX_MESSAGE = 200; // the client's own box stops at 70
|
||||
const MAX_PARAMS_JSON = 8000;
|
||||
const MAX_HIDDEN = 500;
|
||||
const USERNAME_SHOWN = 1;
|
||||
// what an owner may set about their wall (PlayerWallGui.checkForWallParameterChanges):
|
||||
// background, stickers, masterpieces, the photo booth picture, status line.
|
||||
const OWNER_PARAMS = ["bg", "stk", "mp", "pb", "tag", "langId"];
|
||||
|
||||
// generic lists the wall window asks for: the wallpapers' buttons in the
|
||||
// "customize" popup, the wallpapers themselves (a wall's "bg" parameter is a
|
||||
// place in this list, 19 until its owner picks another), and stickers.
|
||||
// like the Jam-A-Gram cards these lists only existed on the official
|
||||
// servers; lib/wall-art.json holds what tools/find-art.py found on the
|
||||
// CDN. without the wallpaper list a wall never appears at all.
|
||||
const LIST_WALLPAPER_BUTTONS = 313;
|
||||
const LIST_WALLPAPERS = 314;
|
||||
const LIST_STICKERS = 646;
|
||||
const RESOURCE_WALL_LIKES = "jammerwall";
|
||||
const RESOURCE_MASTERPIECE_LIKES = "masterpiece";
|
||||
const art = JSON.parse(fs.readFileSync(path.join(__dirname, "wall-art.json"), "utf8"));
|
||||
|
||||
const postsPerTenMinutes = limits.limiter(60, 600000);
|
||||
|
||||
const clean = text => String(text).replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_MESSAGE);
|
||||
// A wall parameter is read by every visitor's game: a number or a short
|
||||
// text, or a short list of those or of small flat objects of those (the
|
||||
// stickers and paintings on a wall). nothing nested deeper, nothing long.
|
||||
const MAX_PARAM_TEXT = 300;
|
||||
const MAX_PARAM_ENTRIES = 60;
|
||||
const scalar = value => value === null || typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value))
|
||||
|| (typeof value === "string" && value.length <= MAX_PARAM_TEXT);
|
||||
const flat = value => scalar(value) || (typeof value === "object" && !Array.isArray(value)
|
||||
&& 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);
|
||||
|
||||
module.exports = ({blocks}) => {
|
||||
const tokens = new Map(); // token -> {viewer: account id, owner: account id, expires}
|
||||
|
||||
const mayOpen = (owner, viewer) => {
|
||||
if (owner === viewer) {
|
||||
return TOKEN_OK;
|
||||
}
|
||||
if (owner.wall.privacy === NOBODY || blocks.either(owner, viewer) || !accounts.featureOn(owner, "wall") || !accounts.featureOn(viewer, "wall")) {
|
||||
return WALL_LOCKED;
|
||||
}
|
||||
if (owner.wall.privacy === BUDDIES && !owner.buddies.includes(viewer.username.toLowerCase())) {
|
||||
return BUDDIES_ONLY;
|
||||
}
|
||||
return TOKEN_OK;
|
||||
};
|
||||
|
||||
// one token for a viewer and a wall, given again while it is good, and
|
||||
// tokens for no more than MAX_WALLS_OPEN walls a viewer: asking in a loop
|
||||
// gets the same few back and pushes nobody else's out.
|
||||
const issue = (viewer, owner) => {
|
||||
const mine = [];
|
||||
for (const [token, entry] of tokens) {
|
||||
if (entry.expires < Date.now()) {
|
||||
tokens.delete(token);
|
||||
}
|
||||
else if (entry.viewer === viewer.id) {
|
||||
mine.push([token, entry]);
|
||||
}
|
||||
}
|
||||
const same = mine.find(([, entry]) => entry.owner === owner.id);
|
||||
if (same) {
|
||||
same[1].expires = Date.now() + TOKEN_MINUTES * 60000;
|
||||
return same[0];
|
||||
}
|
||||
for (const [token] of mine.sort((one, other) => one[1].expires - other[1].expires).slice(0, Math.max(0, mine.length - MAX_WALLS_OPEN + 1))) {
|
||||
tokens.delete(token);
|
||||
}
|
||||
if (tokens.size >= MAX_TOKENS) {
|
||||
tokens.delete(tokens.keys().next().value);
|
||||
}
|
||||
const token = crypto.randomBytes(18).toString("hex");
|
||||
tokens.set(token, {viewer: viewer.id, owner: owner.id, expires: Date.now() + TOKEN_MINUTES * 60000});
|
||||
return token;
|
||||
};
|
||||
|
||||
// {viewer, owner} accounts for a token still good, else null.
|
||||
const resolve = token => {
|
||||
const entry = typeof token === "string" ? tokens.get(token) : null;
|
||||
if (!entry || entry.expires < Date.now()) {
|
||||
return null;
|
||||
}
|
||||
const viewer = accounts.byId(entry.viewer);
|
||||
const owner = accounts.byId(entry.owner);
|
||||
return viewer && owner && mayOpen(owner, viewer) === TOKEN_OK ? {viewer, owner} : null;
|
||||
};
|
||||
|
||||
// PlayerWallXtCommManager.getResponse: r = posts, n = notifications (replies
|
||||
// to the viewer elsewhere; not kept here), p = the wall's parameters with
|
||||
// the visit count and the time its owner last read it, t = last change.
|
||||
const getReply = (owner, viewer) => {
|
||||
const {wall} = owner;
|
||||
const hidden = new Set(wall.hidden);
|
||||
const reply = {
|
||||
s: true,
|
||||
r: wall.posts.filter(post => !hidden.has(post.x)),
|
||||
n: [],
|
||||
p: {...wall.params, visits: wall.visits, rdt: wall.readAt},
|
||||
t: wall.modified,
|
||||
};
|
||||
if (viewer === owner) {
|
||||
wall.readAt = Date.now();
|
||||
}
|
||||
return reply;
|
||||
};
|
||||
|
||||
const put = (owner, viewer, body) => {
|
||||
const colours = Array.isArray(body.ac) ? body.ac.slice(0, 3).map(String) : [];
|
||||
const message = clean(body.m === undefined ? "" : body.m);
|
||||
if (!message || isSilenced(viewer) || !colours.every(isUint) || !postsPerTenMinutes.allow(viewer.id)) {
|
||||
// PlayerWallGui.onMessageSent: cs -1 = "could not be posted"
|
||||
return {PUT: {s: false, cs: -1}};
|
||||
}
|
||||
const post = {
|
||||
x: crypto.randomBytes(8).toString("hex"),
|
||||
m: message,
|
||||
uid: viewer.id,
|
||||
un: viewer.username,
|
||||
um: USERNAME_SHOWN,
|
||||
u: viewer.uuid,
|
||||
s: whole(body.s), // pattern behind the message
|
||||
c: whole(body.c), // its colour
|
||||
t: Date.now(),
|
||||
ai: whole(body.ai), // the poster's animal, for the little portrait
|
||||
ac: colours.map(Number),
|
||||
ae: whole(body.ae),
|
||||
ap: whole(body.ap),
|
||||
l: whole(body.l),
|
||||
aci: whole(body.aci),
|
||||
};
|
||||
if (typeof body.pp === "string" && owner.wall.posts.some(other => other.x === body.pp)) {
|
||||
post.pp = body.pp; // a reply to that post
|
||||
}
|
||||
owner.wall.posts.push(post);
|
||||
owner.wall.posts = owner.wall.posts.slice(-MAX_POSTS);
|
||||
owner.wall.modified = post.t;
|
||||
accounts.save();
|
||||
return {PUT: {s: true}, x: post.x, t: post.t, GET: getReply(owner, viewer)};
|
||||
};
|
||||
|
||||
// POST /wall: one JSON command, one JSON answer.
|
||||
const http = body => {
|
||||
const cmd = String(body && body.cmd);
|
||||
const who = resolve(body && body.t);
|
||||
if (!who) {
|
||||
// any command but PUT reads "e" at the top; PUT reads it inside PUT.
|
||||
return cmd === "PUT" ? {PUT: {s: false, e: "token"}} : {s: false, e: "token"};
|
||||
}
|
||||
const {owner, viewer} = who;
|
||||
const {wall} = owner;
|
||||
const mine = owner === viewer;
|
||||
switch (cmd) {
|
||||
case "CHK":
|
||||
return {s: true, t: wall.modified};
|
||||
case "GET":
|
||||
return getReply(owner, viewer);
|
||||
case "PUT":
|
||||
return put(owner, viewer, body);
|
||||
case "DEL": {
|
||||
// the owner may remove anything; anyone may remove what they wrote.
|
||||
const post = wall.posts.find(candidate => candidate.x === body.x);
|
||||
if (!post || !(mine || post.uid === viewer.id)) {
|
||||
return {s: false};
|
||||
}
|
||||
wall.posts = wall.posts.filter(candidate => candidate !== post && candidate.pp !== post.x);
|
||||
wall.modified = Date.now();
|
||||
accounts.save();
|
||||
return {s: true};
|
||||
}
|
||||
case "GMB": // posts the owner chose to hide
|
||||
return {s: true, r: mine ? wall.hidden : []};
|
||||
case "AMB":
|
||||
if (!mine || typeof body.x !== "string" || !wall.posts.some(post => post.x === body.x)) {
|
||||
return {s: false};
|
||||
}
|
||||
wall.hidden = [...new Set([...wall.hidden, body.x])].slice(-MAX_HIDDEN);
|
||||
accounts.save();
|
||||
return {s: true};
|
||||
case "CLW":
|
||||
if (!mine) {
|
||||
return {s: false};
|
||||
}
|
||||
wall.posts = [];
|
||||
wall.hidden = [];
|
||||
wall.modified = Date.now();
|
||||
accounts.save();
|
||||
return {s: true};
|
||||
case "RMP": // masterpieces taken off the wall; there are none
|
||||
case "ACK": // notifications marked as read; there are none
|
||||
return {s: true};
|
||||
default:
|
||||
return {s: false, e: "unavailable"};
|
||||
}
|
||||
};
|
||||
|
||||
const byUuid = uuid => accounts.all().find(account => account.uuid === uuid) || null;
|
||||
const likes = owner => owner.wall.likes || [];
|
||||
|
||||
const handlers = {
|
||||
// the wall's like button (ResourceArrayXtCommManager): ["jammerwall",
|
||||
// ownerUuid, myUuid, ...] -> [success, likedByMe, likes].
|
||||
crg(session, roomId, [resource, ownerUuid]) {
|
||||
if (resource === RESOURCE_MASTERPIECE_LIKES) {
|
||||
// A masterpiece's likes: the second field is the painting's id.
|
||||
const painting = masterpieces.get(ownerUuid);
|
||||
session.sendXt("crg", -1, painting ? 1 : 0, painting && painting.likes.includes(session.account.id) ? 1 : 0, painting ? painting.likes.length : 0);
|
||||
return;
|
||||
}
|
||||
const owner = resource === RESOURCE_WALL_LIKES ? byUuid(ownerUuid) : null;
|
||||
session.sendXt("crg", -1, owner ? 1 : 0, owner && likes(owner).includes(session.account.id) ? 1 : 0, owner ? likes(owner).length : 0);
|
||||
},
|
||||
|
||||
// the same, pressed: -> [success]. one like a player, and not one's own wall.
|
||||
crp(session, roomId, [resource, ownerUuid]) {
|
||||
if (resource === RESOURCE_MASTERPIECE_LIKES) {
|
||||
session.sendXt("crp", -1, masterpieces.like(ownerUuid, session.account) ? 1 : 0);
|
||||
return;
|
||||
}
|
||||
const owner = resource === RESOURCE_WALL_LIKES ? byUuid(ownerUuid) : null;
|
||||
const allowed = Boolean(owner) && owner !== session.account && !likes(owner).includes(session.account.id)
|
||||
&& mayOpen(owner, session.account) === TOKEN_OK;
|
||||
if (allowed) {
|
||||
owner.wall.likes = [...likes(owner), session.account.id];
|
||||
accounts.save();
|
||||
}
|
||||
session.sendXt("crp", -1, allowed ? 1 : 0);
|
||||
},
|
||||
|
||||
// [username] -> [status, token, mayRead, mayWrite, username]
|
||||
wt(session, roomId, [username]) {
|
||||
const owner = accounts.byName(username);
|
||||
const status = owner ? mayOpen(owner, session.account) : UNAVAILABLE;
|
||||
if (status !== TOKEN_OK) {
|
||||
session.sendXt("wt", -1, status);
|
||||
return;
|
||||
}
|
||||
session.sendXt("wt", -1, TOKEN_OK, issue(session.account, owner), 1, 1, owner.username);
|
||||
},
|
||||
|
||||
// [setting]: who may open my wall -> [success]
|
||||
wss(session, roomId, [setting]) {
|
||||
const value = Number(setting);
|
||||
const valid = [NOBODY, BUDDIES, EVERYONE].includes(value);
|
||||
if (valid) {
|
||||
session.account.wall.privacy = value;
|
||||
accounts.save();
|
||||
}
|
||||
session.sendXt("wss", -1, valid ? 1 : 0);
|
||||
},
|
||||
|
||||
// [username] -> that player's setting
|
||||
wsg(session, roomId, [username]) {
|
||||
const owner = accounts.byName(username);
|
||||
session.sendXt("wsg", -1, owner ? owner.wall.privacy : NOBODY);
|
||||
},
|
||||
|
||||
// [JSON of the parameters that changed] -> [success]
|
||||
wps(session, roomId, params) {
|
||||
const {wall} = session.account;
|
||||
let changes;
|
||||
try {
|
||||
// "%" cannot travel inside a field, so nothing was split apart.
|
||||
changes = JSON.parse(params.join("%"));
|
||||
}
|
||||
catch (err) {
|
||||
changes = null;
|
||||
}
|
||||
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])) {
|
||||
session.sendXt("wps", -1, 0);
|
||||
return;
|
||||
}
|
||||
merged[key] = changes[key];
|
||||
}
|
||||
}
|
||||
if (!merged || JSON.stringify(merged).length > MAX_PARAMS_JSON) {
|
||||
session.sendXt("wps", -1, 0);
|
||||
return;
|
||||
}
|
||||
wall.params = merged;
|
||||
wall.modified = Date.now();
|
||||
accounts.save();
|
||||
session.sendXt("wps", -1, 1);
|
||||
},
|
||||
|
||||
// [username]: "I looked at that wall" -> [success]
|
||||
wci(session, roomId, [username]) {
|
||||
const owner = accounts.byName(username);
|
||||
if (owner && owner !== session.account && mayOpen(owner, session.account) === TOKEN_OK) {
|
||||
owner.wall.visits++;
|
||||
accounts.save();
|
||||
}
|
||||
session.sendXt("wci", -1, owner ? 1 : 0);
|
||||
},
|
||||
};
|
||||
|
||||
// GenericListXtCommManager.handleMediaResponse: (mediaId, name) pairs;
|
||||
// null when `listId` is not one of the wall window's lists.
|
||||
const list = listId => {
|
||||
const ids = {
|
||||
[LIST_WALLPAPER_BUTTONS]: art.wallpapers.map(wallpaper => wallpaper.button),
|
||||
[LIST_WALLPAPERS]: art.wallpapers.map(wallpaper => wallpaper.media),
|
||||
[LIST_STICKERS]: art.stickers,
|
||||
}[Number(listId)];
|
||||
return ids ? ids.flatMap(id => [id, 0]) : null;
|
||||
};
|
||||
|
||||
return {handlers, http, list};
|
||||
};
|
||||
@@ -0,0 +1,75 @@
|
||||
"use strict";
|
||||
|
||||
const accounts = require("./accounts.js");
|
||||
const achievements = require("./achievements.js");
|
||||
const defpacks = require("./defpacks.js");
|
||||
const dens = require("./dens.js");
|
||||
const {CURRENCIES, hasRoom, addClothing, sendClothingAdded} = require("./player.js");
|
||||
|
||||
// gifts lying about in the lands (client side: WorldItemsManager): a room
|
||||
// has up to three spots, a world-item def says which spot it sits in, what
|
||||
// it gives and which bit of a user var records that the player took it.
|
||||
// the real game put a few out at a time. here each spot shows the first
|
||||
// gift the player has not taken yet, so all of them come round in turn.
|
||||
|
||||
// WorldItemDef.giftType
|
||||
const GIFT_DEN_ITEM = "0";
|
||||
const GIFT_GEMS = "1";
|
||||
const GIFT_DIAMONDS = "2";
|
||||
const GIFT_CLOTHING = "3";
|
||||
const CURRENCY_OF = {[GIFT_GEMS]: 0, [GIFT_DIAMONDS]: 3};
|
||||
const NO_CURRENCY = -1;
|
||||
|
||||
const taken = (account, def) => ((Number(account.userVars[def.userVarRefId]) || 0) >>> Number(def.uvIndex)) & 1;
|
||||
|
||||
// the defs on show for this player, one per spot: generic list 583.
|
||||
const usable = account => {
|
||||
const bySpot = new Map();
|
||||
for (const id of defpacks.worldItemIds()) {
|
||||
const def = defpacks.worldItemDef(id);
|
||||
if (!bySpot.has(def.position) && !taken(account, def)) {
|
||||
bySpot.set(def.position, id);
|
||||
}
|
||||
}
|
||||
return [...bySpot.values()];
|
||||
};
|
||||
|
||||
const handlers = {
|
||||
// WorldItemsXtCommManager.sendAcceptGift: [defId, denItemVersion,
|
||||
// clothingColourIndex]. the reply (WorldItemsManager.onGiftResponse) is
|
||||
// [success, new currency amount or -1].
|
||||
wig(session, roomId, [defId, version, colorIndex]) {
|
||||
const {account} = session;
|
||||
const def = defpacks.worldItemDef(defId);
|
||||
if (!def || !usable(account).includes(Number(def.id))
|
||||
|| (def.giftType === GIFT_DEN_ITEM && !hasRoom(account, "denItems")) || (def.giftType === GIFT_CLOTHING && !hasRoom(account, "items"))) {
|
||||
session.sendXt("wig", -1, 0, NO_CURRENCY);
|
||||
return;
|
||||
}
|
||||
let amount = NO_CURRENCY;
|
||||
if (def.giftType === GIFT_DEN_ITEM && defpacks.denItemDef(def.giftRefId)) {
|
||||
dens.giveDenItem(account, def.giftRefId, version);
|
||||
dens.sendDenItems(session);
|
||||
}
|
||||
else if (def.giftType === GIFT_CLOTHING && defpacks.itemDef(def.giftRefId)) {
|
||||
const colors = String(defpacks.itemDef(def.giftRefId).colors).split(",");
|
||||
sendClothingAdded(session, addClothing(account, def.giftRefId, colors[Number(colorIndex)] || colors[0]));
|
||||
}
|
||||
else if (Object.hasOwn(CURRENCY_OF, def.giftType)) {
|
||||
const currency = CURRENCIES[CURRENCY_OF[def.giftType]];
|
||||
account.currency[currency] = (account.currency[currency] || 0) + Number(def.amount);
|
||||
achievements.currencyChanged(account, currency, Number(def.amount));
|
||||
amount = account.currency[currency];
|
||||
}
|
||||
else {
|
||||
session.sendXt("wig", -1, 0, NO_CURRENCY);
|
||||
return;
|
||||
}
|
||||
// the client reads the bit straight from its copy of the user var.
|
||||
achievements.set(account, def.userVarRefId, ((Number(account.userVars[def.userVarRefId]) || 0) | (1 << Number(def.uvIndex))) >>> 0);
|
||||
accounts.save();
|
||||
session.sendXt("wig", -1, 1, amount);
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = {handlers, usable};
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "aj-classic-private-server",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Local server for the AJ Classic desktop client",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"start": "node server.js",
|
||||
"test": "node test/smoke.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.5"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 10 KiB |
@@ -0,0 +1,62 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Burrow</title>
|
||||
<link rel="icon" type="image/png" href="/logo-square.png">
|
||||
<style>
|
||||
/* the captcha alone, in a small window the client opens over its login
|
||||
screen (its app/main.js); the answer goes back through that
|
||||
window's preload. */
|
||||
@font-face { font-family: "DigitalDelivery"; font-weight: 400; src: url("/fonts/CCDigitalDelivery-Regular.otf") format("opentype"); }
|
||||
:root { color-scheme: dark; }
|
||||
html, body { height: 100%; }
|
||||
body {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
background: #000;
|
||||
color: #8c8c8c;
|
||||
font: 14px/1.4 "DigitalDelivery", system-ui, "Segoe UI", sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
#status { margin: 0; text-align: center; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="widget"></div>
|
||||
<p id="status" role="status">Checking…</p>
|
||||
<script src="/captcha.js"></script>
|
||||
<script>
|
||||
"use strict";
|
||||
|
||||
const action = new URLSearchParams(location.search).get("action") === "signup" ? "signup" : "login";
|
||||
const status = document.getElementById("status");
|
||||
const done = token => {
|
||||
if (window.burrowCaptcha) {
|
||||
window.burrowCaptcha.done(token);
|
||||
}
|
||||
};
|
||||
if (!window.captcha.on) {
|
||||
status.textContent = "No captcha needed.";
|
||||
done("");
|
||||
}
|
||||
else {
|
||||
// cloudflare may try again after an error, and an answer can still come.
|
||||
const check = window.captcha.mount(document.getElementById("widget"), action, {appearance: "always", onAnswer: token => {
|
||||
status.textContent = "Done.";
|
||||
done(token);
|
||||
}});
|
||||
check.answer().then(token => {
|
||||
if (!token) {
|
||||
status.textContent = "Captcha failed. Close this and try again.";
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,83 @@
|
||||
"use strict";
|
||||
|
||||
// cloudflare turnstile on this server's pages (lib/captcha.js). the server
|
||||
// writes its site key in below, or "" when it asks for no captcha.
|
||||
//
|
||||
// const check = captcha.mount(element, "login") shows the widget in
|
||||
// `element`, as a page loads; await check.answer() before a request (it
|
||||
// waits while the player is still solving it; undefined when the server
|
||||
// asks for none, "" when the captcha could not load or run: say
|
||||
// captcha.FAILED then), and check.reset() after it: an answer is good once.
|
||||
window.captcha = (() => {
|
||||
const siteKey = "{{siteKey}}";
|
||||
let loading = null;
|
||||
|
||||
const load = () => {
|
||||
loading = loading || new Promise((resolve, reject) => {
|
||||
const script = document.createElement("script");
|
||||
script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
|
||||
script.onload = () => resolve(window.turnstile);
|
||||
script.onerror = () => {
|
||||
loading = null;
|
||||
reject(new Error("the captcha did not load"));
|
||||
};
|
||||
document.head.append(script);
|
||||
});
|
||||
return loading;
|
||||
};
|
||||
|
||||
// `options`: {appearance} ("interaction-only" by default: seen only when
|
||||
// cloudflare wants a click), {onAnswer(token)}.
|
||||
const mount = (element, action, options = {}) => {
|
||||
let widget = null;
|
||||
let answer = null; // a token, "" when none could be had, null while waiting
|
||||
let waiting = [];
|
||||
const settle = value => {
|
||||
answer = value;
|
||||
if (value && options.onAnswer) {
|
||||
options.onAnswer(value);
|
||||
}
|
||||
for (const resolve of waiting) {
|
||||
resolve(value);
|
||||
}
|
||||
waiting = [];
|
||||
};
|
||||
if (siteKey) {
|
||||
load().then(turnstile => {
|
||||
widget = turnstile.render(element, {
|
||||
sitekey: siteKey,
|
||||
action,
|
||||
theme: "dark",
|
||||
appearance: options.appearance || "interaction-only",
|
||||
callback: settle,
|
||||
"expired-callback": () => {
|
||||
answer = null;
|
||||
},
|
||||
// its code is cloudflare's (110200: this site's name is not on the widget)
|
||||
"error-callback": code => {
|
||||
console.log(`captcha error ${code}`);
|
||||
settle("");
|
||||
},
|
||||
});
|
||||
}, () => settle(""));
|
||||
}
|
||||
return {
|
||||
on: Boolean(siteKey),
|
||||
answer: () => {
|
||||
if (!siteKey) {
|
||||
return Promise.resolve(undefined);
|
||||
}
|
||||
return answer !== null ? Promise.resolve(answer) : new Promise(resolve => waiting.push(resolve));
|
||||
},
|
||||
// (a widget that never loaded keeps its "" so nothing waits on it)
|
||||
reset: () => {
|
||||
if (widget !== null) {
|
||||
answer = null;
|
||||
window.turnstile.reset(widget);
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
return {on: Boolean(siteKey), mount, FAILED: "Captcha could not load. Reload the page."};
|
||||
})();
|
||||
@@ -0,0 +1,259 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Chat commands</title>
|
||||
<link rel="icon" type="image/png" href="/logo-square.png">
|
||||
<style>
|
||||
/* black and white throughout, in the game's own text font: the look of
|
||||
the client (its app/index.html). Nothing is said by colour: what
|
||||
went wrong is white with a "!" before it, and what cannot be undone
|
||||
has a dashed edge. */
|
||||
@font-face { font-family: "DigitalDelivery"; font-weight: 400; src: url("/fonts/CCDigitalDelivery-Regular.otf") format("opentype"); }
|
||||
@font-face { font-family: "DigitalDelivery"; font-weight: 700; src: url("/fonts/CCDigitalDelivery-Bold.otf") format("opentype"); }
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #000;
|
||||
--panel: #0d0d0d;
|
||||
--raised: #1a1a1a;
|
||||
--line: #2e2e2e;
|
||||
--text: #fff;
|
||||
--muted: #8c8c8c;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
::selection { background: #fff; color: #000; }
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: var(--line); border-radius: 5px; border: 3px solid var(--bg); }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 32px 16px 48px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 15px/1.4 "DigitalDelivery", system-ui, "Segoe UI", sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
a { color: inherit; text-underline-offset: 3px; }
|
||||
h1 { margin: 0; font-size: 26px; font-weight: 700; letter-spacing: 0.01em; }
|
||||
h2 { margin: 0 0 6px; font-size: 17px; font-weight: 700; }
|
||||
h3 { font-size: 14px; font-weight: 700; }
|
||||
p { margin: 0 0 12px; color: var(--muted); }
|
||||
label { display: block; margin: 12px 0 5px; color: var(--muted); font-size: 13px; }
|
||||
.hint { font-weight: 400; color: var(--muted); font-size: 12px; }
|
||||
input, select, textarea {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
padding: 9px 14px 10px;
|
||||
transition: border-color 0.12s;
|
||||
}
|
||||
input::placeholder, textarea::placeholder { color: #555; }
|
||||
input:hover, select:hover, textarea:hover { border-color: #555; }
|
||||
input:focus, select:focus, textarea:focus { outline: none; border-color: var(--text); }
|
||||
input:disabled, select:disabled, textarea:disabled { opacity: 0.4; }
|
||||
select:not([multiple]) {
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
padding-right: 34px;
|
||||
background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%), linear-gradient(135deg, var(--muted) 50%, transparent 50%);
|
||||
background-position: calc(100% - 19px) 55%, calc(100% - 14px) 55%;
|
||||
background-size: 5px 5px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
input[type="checkbox"] {
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
flex: none;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
margin: 0 6px 0 0;
|
||||
padding: 0;
|
||||
vertical-align: -4px;
|
||||
border: 1px solid #666;
|
||||
border-radius: 6px;
|
||||
background: var(--panel);
|
||||
cursor: pointer;
|
||||
}
|
||||
input[type="checkbox"]:hover { border-color: var(--text); }
|
||||
input[type="checkbox"]:checked {
|
||||
border-color: var(--text);
|
||||
background: var(--text) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'%3E%3Cpath d='M4.5 9.5l3 3 6-7' fill='none' stroke='%23000' stroke-width='2.2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / 16px no-repeat;
|
||||
}
|
||||
button {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: none;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
padding: 7px 16px 8px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition: background 0.12s, border-color 0.12s, color 0.12s;
|
||||
}
|
||||
button:hover { background: var(--raised); border-color: #555; }
|
||||
button:disabled { opacity: 0.45; cursor: default; }
|
||||
button:focus-visible, a:focus-visible, input[type="checkbox"]:focus-visible { outline: 2px solid var(--text); outline-offset: 2px; }
|
||||
button.primary { font-weight: 700; color: #000; background: var(--text); border-color: var(--text); }
|
||||
button.primary:hover { background: #d9d9d9; border-color: #d9d9d9; }
|
||||
button.primary:disabled, button.primary:disabled:hover { background: #3a3a3a; border-color: #3a3a3a; color: #000; }
|
||||
button.danger { border-style: dashed; border-color: #666; }
|
||||
button.danger:hover { border-style: solid; border-color: var(--text); }
|
||||
.status, #status { min-height: 20px; margin: 10px 0 0; font-size: 13px; color: var(--muted); }
|
||||
.status.bad, #status.bad { color: var(--text); }
|
||||
.status.bad::before, #status.bad::before, .notice::before {
|
||||
content: "!";
|
||||
display: inline-block;
|
||||
width: 17px;
|
||||
height: 17px;
|
||||
margin-right: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--text);
|
||||
color: #000;
|
||||
font-weight: 700;
|
||||
line-height: 17px;
|
||||
text-align: center;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
|
||||
.wrap { max-width: 820px; margin: 0 auto; }
|
||||
header { display: flex; align-items: center; gap: 12px; margin-bottom: 20px; }
|
||||
header h1 { flex: 1; }
|
||||
section { padding: 20px; margin-bottom: 16px; background: var(--panel); border: 1px solid var(--line); border-radius: 18px; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
td { padding: 8px 8px 8px 0; border-top: 1px solid var(--line); vertical-align: top; color: var(--muted); }
|
||||
tr:first-child td { border-top: 0; }
|
||||
td:first-child { width: 42%; }
|
||||
/* what to type keeps a fixed-width face, as it is typed letter by letter. */
|
||||
code { font: 13px/1.5 ui-monospace, Consolas, monospace; color: var(--text); background: var(--raised); border: 1px solid var(--line); border-radius: 8px; padding: 1px 7px; white-space: nowrap; }
|
||||
td code { cursor: pointer; transition: background 0.12s, color 0.12s, border-color 0.12s; }
|
||||
td code:hover, td code:focus { outline: none; border-color: var(--text); }
|
||||
td code.copied { color: #000; background: var(--text); border-color: var(--text); }
|
||||
code i { font-style: normal; color: var(--muted); }
|
||||
td code.copied i { color: #000; }
|
||||
#copied { position: fixed; left: 50%; bottom: 24px; transform: translateX(-50%); margin: 0; padding: 6px 18px 7px; border-radius: 999px; background: var(--text); color: #000; font-size: 13px; font-weight: 700; }
|
||||
@media (max-width: 560px) { td, td:first-child { display: block; width: auto; padding: 4px 0; border-top: 0; } tr td:first-child { border-top: 1px solid var(--line); padding-top: 10px; } tr:first-child td:first-child { border-top: 0; } code { white-space: normal; } }
|
||||
.logo { display: block; height: 72px; margin: 0 0 12px; }
|
||||
.mark { height: 34px; flex: none; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<header>
|
||||
<img class="mark" src="/logo.png" alt="">
|
||||
<h1>Chat commands</h1>
|
||||
<a href="/account">Your account</a>
|
||||
</header>
|
||||
<section>
|
||||
<h2>Getting around</h2>
|
||||
<table>
|
||||
<tr><td><code>!go <i>PLACE</i></code></td><td>Go to a land or room.</td></tr>
|
||||
<tr><td><code>!go list</code></td><td>Places you can go.</td></tr>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Other players</h2>
|
||||
<table>
|
||||
<tr><td><code>!online</code></td><td>Who is online.</td></tr>
|
||||
<tr><td><code>!where <i>BUDDY</i></code></td><td>Where a buddy is.</td></tr>
|
||||
<tr><td><code>!w <i>BUDDY</i> <i>MESSAGE</i></code></td><td>Whisper to a buddy.</td></tr>
|
||||
<tr><td><code>!hideblocked on</code></td><td>Hide blocked players.</td></tr>
|
||||
<tr><td><code>!hideblocked off</code></td><td>Show them again.</td></tr>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Outfits</h2>
|
||||
<table>
|
||||
<tr><td><code>!outfit save <i>NAME</i></code></td><td>Save your outfit.</td></tr>
|
||||
<tr><td><code>!outfit wear <i>NAME</i></code></td><td>Wear a saved outfit.</td></tr>
|
||||
<tr><td><code>!outfit list</code></td><td>Your saved outfits.</td></tr>
|
||||
<tr><td><code>!outfit delete <i>NAME</i></code></td><td>Delete an outfit.</td></tr>
|
||||
<tr><td><code>!outfit off</code></td><td>Take everything off.</td></tr>
|
||||
<tr><td><code>!outfit undo</code></td><td>Undo the last change.</td></tr>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Dens</h2>
|
||||
<table>
|
||||
<tr><td><code>!den save <i>NAME</i></code></td><td>Save your den layout.</td></tr>
|
||||
<tr><td><code>!den load <i>NAME</i></code></td><td>Load a saved layout.</td></tr>
|
||||
<tr><td><code>!den list</code></td><td>Your saved layouts.</td></tr>
|
||||
<tr><td><code>!den delete <i>NAME</i></code></td><td>Delete a layout.</td></tr>
|
||||
<tr><td><code>!den copy</code></td><td>Copy the den you are in.</td></tr>
|
||||
<tr><td><code>!den undo</code></td><td>Undo Clear Den.</td></tr>
|
||||
<tr><td><code>!den name <i>NAME</i></code></td><td>Name your den.</td></tr>
|
||||
<tr><td><code>!den name off</code></td><td>Remove the name.</td></tr>
|
||||
<tr><td><code>!music all</code></td><td>Get every music track.</td></tr>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Themes</h2>
|
||||
<table>
|
||||
<tr><td><code>!theme list</code></td><td>All themes.</td></tr>
|
||||
<tr><td><code>!theme here <i>NAME</i></code></td><td>Theme this room.</td></tr>
|
||||
<tr><td><code>!theme here off</code></td><td>Remove it.</td></tr>
|
||||
<tr><td><code>!theme random on</code></td><td>A random theme each login.</td></tr>
|
||||
<tr><td><code>!theme random off</code></td><td>Stop that.</td></tr>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Other</h2>
|
||||
<table>
|
||||
<tr><td><code>!again <i>N</i></code></td><td>Buy your last purchase N more times.</td></tr>
|
||||
<tr><td><code>!mail clear</code></td><td>Delete read Jam-A-Grams.</td></tr>
|
||||
<tr><td><code>!become <i>NAME</i></code></td><td>Look like an alpha.</td></tr>
|
||||
<tr><td><code>!become list</code></td><td>Who you can become.</td></tr>
|
||||
<tr><td><code>!become off</code></td><td>Back to your animal.</td></tr>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
</div>
|
||||
<p id="copied" role="status" hidden>Copied</p>
|
||||
<script>
|
||||
"use strict";
|
||||
// a click copies the command up to its first placeholder
|
||||
const said = document.getElementById("copied");
|
||||
let hide = 0;
|
||||
const copy = text => (navigator.clipboard && window.isSecureContext
|
||||
? navigator.clipboard.writeText(text)
|
||||
: new Promise((done, failed) => {
|
||||
const box = document.createElement("textarea");
|
||||
box.value = text;
|
||||
box.style.position = "fixed";
|
||||
box.style.opacity = "0";
|
||||
document.body.appendChild(box);
|
||||
box.select();
|
||||
const copied = document.execCommand("copy");
|
||||
box.remove();
|
||||
(copied ? done : failed)();
|
||||
}));
|
||||
for (const command of document.querySelectorAll("td code")) {
|
||||
command.tabIndex = 0;
|
||||
command.setAttribute("role", "button");
|
||||
command.title = "Copy";
|
||||
const blank = command.querySelector("i");
|
||||
const text = blank ? command.textContent.slice(0, command.textContent.indexOf(blank.textContent)) : command.textContent;
|
||||
const act = () => copy(text).then(() => {
|
||||
command.classList.add("copied");
|
||||
said.hidden = false;
|
||||
clearTimeout(hide);
|
||||
hide = setTimeout(() => { said.hidden = true; }, 1200);
|
||||
setTimeout(() => command.classList.remove("copied"), 600);
|
||||
}, () => {});
|
||||
command.addEventListener("click", act);
|
||||
command.addEventListener("keydown", event => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
act();
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,51 @@
|
||||
# threats
|
||||
kys
|
||||
kill yourself
|
||||
kill urself
|
||||
go kill yourself
|
||||
go die
|
||||
hang yourself
|
||||
neck yourself
|
||||
i will rape you
|
||||
ill rape you
|
||||
rape you
|
||||
rape
|
||||
i hope you die
|
||||
hope you die
|
||||
slit your wrists
|
||||
|
||||
# slurs
|
||||
nigger*
|
||||
nigga*
|
||||
nigg
|
||||
niglet*
|
||||
chink*
|
||||
gook*
|
||||
spic
|
||||
spics
|
||||
wetback*
|
||||
beaner*
|
||||
kike*
|
||||
coon
|
||||
coons
|
||||
paki
|
||||
pakis
|
||||
raghead*
|
||||
towelhead*
|
||||
sandnigger*
|
||||
jigaboo*
|
||||
porchmonkey*
|
||||
faggot*
|
||||
fag
|
||||
fags
|
||||
fagg*
|
||||
dyke
|
||||
dykes
|
||||
tranny
|
||||
trannies
|
||||
troon*
|
||||
shemale*
|
||||
retard
|
||||
retards
|
||||
retarded
|
||||
mongoloid*
|
||||
@@ -0,0 +1,35 @@
|
||||
# list from level1.txt also applies
|
||||
|
||||
fuck*
|
||||
fuk
|
||||
fuking
|
||||
fck
|
||||
fcking
|
||||
motherfuck*
|
||||
mf
|
||||
stfu
|
||||
gtfo
|
||||
shit*
|
||||
bullshit*
|
||||
bitch*
|
||||
biatch*
|
||||
cunt*
|
||||
cock
|
||||
cocks
|
||||
cocksucker*
|
||||
dick
|
||||
dicks
|
||||
dickhead*
|
||||
pussy
|
||||
pussies
|
||||
asshole*
|
||||
arsehole*
|
||||
bastard*
|
||||
whore*
|
||||
slut*
|
||||
twat*
|
||||
wanker*
|
||||
jackass*
|
||||
dumbass*
|
||||
douche*
|
||||
bollocks
|
||||
@@ -0,0 +1,118 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Game Client</title>
|
||||
</head>
|
||||
<body>
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
</style>
|
||||
<embed id="flash-content"></embed>
|
||||
<script>
|
||||
"use strict";
|
||||
|
||||
// local stand-in for desktop.animaljam.com/gameClient/game/index.html.
|
||||
// same contract with the launcher (gui/gamePreload.js) and the SWF.
|
||||
|
||||
const flashContent = document.getElementById("flash-content");
|
||||
// only a SWF from this server may call into this page. with "always"
|
||||
// any SWF the game came to load, from anywhere, could: and this page
|
||||
// is handed the player's login token.
|
||||
flashContent.setAttribute("allowScriptAccess", "sameDomain");
|
||||
flashContent.setAttribute("wmode", "window");
|
||||
flashContent.style.width = "100vw";
|
||||
flashContent.style.height = "100vh";
|
||||
|
||||
window.ipc.on("flashVarsReady", (event, flashVars) => {
|
||||
const flashVarsParams = Object.entries(flashVars)
|
||||
.map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`)
|
||||
.join("&");
|
||||
|
||||
flashContent.setAttribute("FlashVars", flashVarsParams);
|
||||
// the game from the address this page came from, whatever name the
|
||||
// server knows itself by: "sameDomain" above goes by that.
|
||||
const client = new URL(flashVars.clientURL, location.href);
|
||||
flashContent.src = location.origin + client.pathname + client.search;
|
||||
flashContent.style.display = "block";
|
||||
});
|
||||
|
||||
window.ipc.on("removed", () => document.body.innerHTML = "");
|
||||
|
||||
// the client's top bar: the game's HUD shown or hidden (AJClient.setHudShown
|
||||
// in the patched SWF).
|
||||
window.ipc.on("hud", (event, shown) => {
|
||||
try {
|
||||
flashContent.ajHud(shown === true);
|
||||
}
|
||||
catch (err) {
|
||||
// not this server's SWF, or the game is not up yet.
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener("resize", resize);
|
||||
|
||||
// ExternalInterface functions called by the SWF.
|
||||
function complete_signup(username, password) {
|
||||
window.ipc.sendToHost("signupCompleted", {username, password});
|
||||
}
|
||||
|
||||
function aj_initialized() {
|
||||
// the game has read its start values; the login token among them
|
||||
// need not stay in the page.
|
||||
flashContent.removeAttribute("FlashVars");
|
||||
window.ipc.sendToHost("initialized");
|
||||
for (let i = 0; i < 50; i++) {
|
||||
setTimeout(() => resize(), i * 500);
|
||||
}
|
||||
}
|
||||
|
||||
// pictures drawn in the last second, told by the patched SWF once a
|
||||
// second (AJClient.onSmoothFrame), for the client's top bar.
|
||||
function ajFps(count) {
|
||||
window.ipc.sendToHost("fps", count);
|
||||
}
|
||||
|
||||
function ajPrint(imageData) {
|
||||
window.ipc.sendToHost("printImage", imageData);
|
||||
}
|
||||
|
||||
function reloadSwfOrGetIP(reloadSwf, params) {
|
||||
window.ipc.sendToHost("reloadGame", reloadSwf, params);
|
||||
}
|
||||
|
||||
// moderator remote-control and analytics hooks; nothing to do locally.
|
||||
function mrc() {}
|
||||
function handleGAEvent() {}
|
||||
function handleKey() {}
|
||||
|
||||
function resize() {
|
||||
if (flashContent && flashContent.handleResize) {
|
||||
try {
|
||||
flashContent.handleResize(window.innerWidth, window.innerHeight);
|
||||
}
|
||||
catch (err) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("error", event => {
|
||||
window.ipc.sendToHost("reportError", (event.error && event.error.stack) || event.message);
|
||||
});
|
||||
|
||||
window.addEventListener("beforeunload", event => {
|
||||
if (flashContent && typeof flashContent.unloadAJClient === "function") {
|
||||
try {
|
||||
flashContent.unloadAJClient();
|
||||
}
|
||||
catch (err) {
|
||||
}
|
||||
}
|
||||
delete event["returnValue"];
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,420 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Burrow</title>
|
||||
<meta name="description" content="Burrow, an AJ Classic private server.">
|
||||
<link rel="icon" type="image/png" href="/logo-square.png">
|
||||
<style>
|
||||
@font-face { font-family: "DigitalDelivery"; font-weight: 400; font-display: swap; src: url("/fonts/CCDigitalDelivery-Regular.otf") format("opentype"); }
|
||||
@font-face { font-family: "DigitalDelivery"; font-weight: 700; font-display: swap; src: url("/fonts/CCDigitalDelivery-Bold.otf") format("opentype"); }
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #000;
|
||||
--panel: #0d0d0d;
|
||||
--raised: #1a1a1a;
|
||||
--line: #2e2e2e;
|
||||
--text: #fff;
|
||||
--muted: #8c8c8c;
|
||||
--wide: 1160px;
|
||||
--paws: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='150' height='150' viewBox='0 0 150 150'%3E%3Cg fill='%23fff'%3E%3Cg transform='translate(34 38) rotate(-20)'%3E%3Cellipse cy='8' rx='10' ry='8'/%3E%3Ccircle cx='-12' cy='-3' r='4'/%3E%3Ccircle cx='-4.5' cy='-10' r='4.2'/%3E%3Ccircle cx='4.5' cy='-10' r='4.2'/%3E%3Ccircle cx='12' cy='-3' r='4'/%3E%3C/g%3E%3Cg transform='translate(108 112) rotate(24)'%3E%3Cellipse cy='8' rx='10' ry='8'/%3E%3Ccircle cx='-12' cy='-3' r='4'/%3E%3Ccircle cx='-4.5' cy='-10' r='4.2'/%3E%3Ccircle cx='4.5' cy='-10' r='4.2'/%3E%3Ccircle cx='12' cy='-3' r='4'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
::selection { background: #fff; color: #000; }
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: var(--line); border-radius: 5px; border: 3px solid var(--bg); }
|
||||
html { scroll-behavior: smooth; scroll-padding-top: 76px; }
|
||||
body {
|
||||
margin: 0;
|
||||
overflow-x: hidden;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 16px/1.45 "DigitalDelivery", system-ui, "Segoe UI", sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
a { color: inherit; text-underline-offset: 3px; }
|
||||
img { display: block; max-width: 100%; }
|
||||
h1, h2, h3, p { margin: 0; }
|
||||
.wrap { width: 100%; max-width: var(--wide); margin: 0 auto; padding: 0 20px; }
|
||||
|
||||
.pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 9px 20px 10px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
transition: background 0.14s, border-color 0.14s, color 0.14s, transform 0.14s, box-shadow 0.14s;
|
||||
}
|
||||
.pill:hover { background: var(--raised); border-color: #555; }
|
||||
.pill.main { color: #000; background: var(--text); border-color: var(--text); }
|
||||
.pill.main:hover { background: #fff; transform: translate(-2px, -2px); box-shadow: 4px 4px 0 #000, 5px 5px 0 var(--text); }
|
||||
.pill.main:active { transform: none; box-shadow: none; }
|
||||
.pill.big { padding: 14px 30px 15px; font-size: 18px; }
|
||||
.pill.soon, .pill.soon:hover { color: var(--muted); background: none; border: 1px dashed #555; cursor: default; transform: none; box-shadow: none; }
|
||||
.pill svg { width: 18px; height: 18px; flex: none; }
|
||||
|
||||
#nav {
|
||||
position: fixed;
|
||||
top: 12px;
|
||||
left: 50%;
|
||||
z-index: 20;
|
||||
width: calc(100% - 24px);
|
||||
max-width: var(--wide);
|
||||
transform: translateX(-50%);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 7px 8px 7px 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
background: rgba(0, 0, 0, 0.72);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
backdrop-filter: blur(14px);
|
||||
}
|
||||
#nav .brand { display: flex; align-items: center; gap: 10px; margin-right: auto; font-size: 18px; font-weight: 700; text-decoration: none; }
|
||||
#nav .brand img { height: 28px; }
|
||||
#nav a.link { padding: 6px 13px 7px; border-radius: 999px; font-size: 14px; color: var(--muted); text-decoration: none; transition: color 0.12s, background 0.12s; }
|
||||
#nav a.link:hover { color: var(--text); background: var(--raised); }
|
||||
#nav a.icon { display: flex; padding: 8px; }
|
||||
#nav a.icon svg { width: 18px; height: 18px; }
|
||||
#nav .pill { padding: 7px 16px 8px; font-size: 14px; }
|
||||
|
||||
#hero {
|
||||
position: relative;
|
||||
min-height: 100vh;
|
||||
min-height: 100svh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 92px 20px 84px;
|
||||
text-align: center;
|
||||
overflow: hidden;
|
||||
--mx: 50%;
|
||||
--my: 38%;
|
||||
}
|
||||
#hero .paws {
|
||||
position: absolute;
|
||||
top: -150px; right: -150px; bottom: -150px; left: -150px;
|
||||
background: var(--paws);
|
||||
opacity: 0.06;
|
||||
animation: drift 40s linear infinite;
|
||||
}
|
||||
#hero .dots {
|
||||
position: absolute;
|
||||
top: 0; right: 0; bottom: 0; left: 0;
|
||||
background: radial-gradient(#fff 1.3px, transparent 1.8px) 0 0 / 22px 22px;
|
||||
opacity: 0.55;
|
||||
-webkit-mask-image: radial-gradient(420px circle at var(--mx) var(--my), #000 0, transparent 100%);
|
||||
mask-image: radial-gradient(420px circle at var(--mx) var(--my), #000 0, transparent 100%);
|
||||
}
|
||||
#hero .fade { position: absolute; right: 0; bottom: 0; left: 0; height: 160px; background: linear-gradient(transparent, #000); }
|
||||
@keyframes drift { to { transform: translate(150px, 150px); } }
|
||||
#hero > .in { position: relative; display: flex; flex-direction: column; align-items: center; width: 100%; }
|
||||
|
||||
#name { position: relative; margin-top: 8px; line-height: 0.8; }
|
||||
#name h1, #name span {
|
||||
display: block;
|
||||
font-size: clamp(76px, 19vw, 250px);
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.03em;
|
||||
line-height: 0.8;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
#name h1 { position: relative; z-index: 2; }
|
||||
#name span {
|
||||
position: absolute;
|
||||
top: 0; left: 0; right: 0;
|
||||
color: transparent;
|
||||
-webkit-text-stroke: 1.5px #fff;
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
}
|
||||
#name span:nth-of-type(1) { transform: translateY(11%); opacity: 0.5; }
|
||||
#name span:nth-of-type(2) { transform: translateY(22%); opacity: 0.26; }
|
||||
#name span:nth-of-type(3) { transform: translateY(33%); opacity: 0.1; }
|
||||
#bunny {
|
||||
position: relative;
|
||||
z-index: 3;
|
||||
height: auto;
|
||||
width: clamp(140px, 21vw, 260px);
|
||||
margin-bottom: calc(clamp(140px, 21vw, 260px) * -0.2);
|
||||
filter: drop-shadow(0 10px 0 rgba(0, 0, 0, 0.55));
|
||||
animation: breathe 5s ease-in-out infinite;
|
||||
transform-origin: 50% 100%;
|
||||
}
|
||||
@keyframes breathe { 50% { transform: scale(1.02, 0.975); } }
|
||||
#line {
|
||||
margin-top: clamp(50px, 8.5vw, 112px);
|
||||
max-width: 620px;
|
||||
font-size: clamp(17px, 2.2vw, 23px);
|
||||
color: var(--muted);
|
||||
}
|
||||
#line b { color: var(--text); }
|
||||
#hero .buttons { display: flex; flex-wrap: wrap; justify-content: center; gap: 12px; margin-top: 24px; }
|
||||
#hero .buttons.small { gap: 10px; margin-top: 12px; }
|
||||
#hero .buttons.small .pill { padding: 7px 16px 8px; font-size: 14px; color: #fff; }
|
||||
/* the only colour on any page of ours: these two keep their brands' */
|
||||
#hero .pill[data-link="discord"] { background: #5865f2; border-color: #5865f2; }
|
||||
#hero .pill[data-link="discord"]:hover { background: #4752c4; border-color: #4752c4; }
|
||||
#hero .pill[data-link="github"] { background: #24292f; border-color: #3d444d; }
|
||||
#hero .pill[data-link="github"]:hover { background: #32383f; }
|
||||
|
||||
#state { margin-top: 22px; font-size: 15px; color: var(--muted); min-height: 22px; }
|
||||
|
||||
section { position: relative; padding: 84px 0; }
|
||||
.head { display: flex; flex-direction: column; align-items: flex-start; gap: 14px; margin-bottom: 38px; }
|
||||
.head h2 { font-size: clamp(38px, 6.4vw, 78px); font-weight: 700; line-height: 0.95; letter-spacing: -0.02em; text-transform: uppercase; }
|
||||
.head h2 em { font-style: normal; color: transparent; -webkit-text-stroke: 1.5px #fff; }
|
||||
.head.mid { align-items: center; text-align: center; }
|
||||
|
||||
#list { display: grid; grid-template-columns: 1fr 1fr; column-gap: 56px; margin: 0; padding: 0; list-style: none; }
|
||||
#list li {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 20px;
|
||||
padding: 17px 4px 18px;
|
||||
border-top: 1px solid var(--line);
|
||||
transition: padding 0.18s, border-color 0.18s;
|
||||
}
|
||||
#list li:hover { padding-left: 14px; border-color: var(--text); }
|
||||
#list h3 { font-size: 21px; font-weight: 700; line-height: 1.15; white-space: nowrap; }
|
||||
#list p { color: var(--muted); font-size: 15px; text-align: right; }
|
||||
#list li:hover p { color: var(--text); }
|
||||
|
||||
#get {
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
align-items: center;
|
||||
gap: 30px;
|
||||
padding: clamp(30px, 6vw, 70px);
|
||||
border-radius: 36px;
|
||||
color: #000;
|
||||
background: var(--text);
|
||||
overflow: hidden;
|
||||
}
|
||||
#get::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: -150px; right: -150px; bottom: -150px; left: -150px;
|
||||
background: var(--paws);
|
||||
filter: invert(1);
|
||||
opacity: 0.07;
|
||||
animation: drift 40s linear infinite reverse;
|
||||
}
|
||||
#get::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 0; right: 0; bottom: 0;
|
||||
width: 55%;
|
||||
background: radial-gradient(#000 2px, transparent 2.6px) 0 0 / 16px 16px;
|
||||
opacity: 0.5;
|
||||
-webkit-mask-image: linear-gradient(90deg, transparent, #000);
|
||||
mask-image: linear-gradient(90deg, transparent, #000);
|
||||
}
|
||||
#get > * { position: relative; z-index: 1; }
|
||||
#get h2 { font-size: clamp(40px, 7vw, 92px); font-weight: 700; line-height: 0.9; letter-spacing: -0.03em; text-transform: uppercase; }
|
||||
#get p { margin-top: 14px; font-size: 17px; color: #333; }
|
||||
#get .side { display: flex; flex-direction: column; align-items: center; gap: 18px; }
|
||||
#get .hole { display: flex; align-items: center; justify-content: center; width: clamp(170px, 21vw, 250px); height: clamp(170px, 21vw, 250px); border-radius: 50%; background: #000; box-shadow: 0 0 0 10px #fff, 0 0 0 11.5px #000; }
|
||||
#get .hole img { width: 82%; margin-top: 8%; }
|
||||
#get .pill { color: #fff; background: #000; border-color: #000; }
|
||||
#get .pill:hover { transform: translate(-2px, -2px); box-shadow: 4px 4px 0 #fff, 5px 5px 0 #000; }
|
||||
#get .pill.soon, #get .pill.soon:hover { color: #555; background: none; border: 1px dashed #555; transform: none; box-shadow: none; }
|
||||
|
||||
footer { margin-top: 30px; padding: 40px 0 44px; border-top: 1px solid var(--line); font-size: 14px; color: var(--muted); }
|
||||
footer .row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 22px; }
|
||||
footer .brand { display: flex; align-items: center; gap: 10px; margin-right: auto; font-size: 20px; font-weight: 700; color: var(--text); text-decoration: none; }
|
||||
footer .brand img { height: 32px; }
|
||||
footer a { text-decoration: none; }
|
||||
footer a:hover { color: var(--text); text-decoration: underline; }
|
||||
footer p { margin-top: 22px; max-width: 760px; font-size: 13px; }
|
||||
|
||||
.js .rise { opacity: 0; transform: translateY(26px); transition: opacity 0.6s ease-out, transform 0.6s cubic-bezier(.2, .8, .2, 1); transition-delay: var(--wait, 0s); }
|
||||
.js .rise.in { opacity: 1; transform: none; }
|
||||
|
||||
@media (max-width: 960px) {
|
||||
#get { grid-template-columns: 1fr; text-align: center; }
|
||||
#get::after { width: 100%; -webkit-mask-image: linear-gradient(transparent 55%, #000); mask-image: linear-gradient(transparent 55%, #000); opacity: 0.25; }
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
#nav a.link { display: none; }
|
||||
#name h1, #name span { font-size: 21vw; }
|
||||
#bunny { width: 30vw; margin-bottom: -5vw; }
|
||||
#line { margin-top: 11vw; }
|
||||
section { padding: 60px 0; }
|
||||
#list { grid-template-columns: 1fr; }
|
||||
}
|
||||
@media (max-width: 380px) {
|
||||
#nav .brand span { display: none; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
html { scroll-behavior: auto; }
|
||||
*, *::before, *::after { animation: none !important; transition: none !important; }
|
||||
.js .rise { opacity: 1; transform: none; }
|
||||
}
|
||||
</style>
|
||||
<script>document.documentElement.className = "js";</script>
|
||||
</head>
|
||||
<body data-download="{{downloadUrl}}" data-github="{{githubUrl}}" data-discord="{{discordUrl}}">
|
||||
<nav id="nav" aria-label="Main">
|
||||
<a class="brand" href="#top"><img src="/logo.png" alt=""><span>Burrow</span></a>
|
||||
<a class="link" href="#here">Features</a>
|
||||
<a class="link" href="/commands">Commands</a>
|
||||
<a class="link" href="/account">Account</a>
|
||||
<a class="link icon" data-link="github" href="#" aria-label="GitHub" hidden><svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 .5a11.5 11.5 0 0 0-3.64 22.41c.58.1.79-.25.79-.56v-2.1c-3.2.7-3.88-1.37-3.88-1.37-.52-1.33-1.28-1.69-1.28-1.69-1.05-.71.08-.7.08-.7 1.16.08 1.77 1.19 1.77 1.19 1.03 1.76 2.7 1.25 3.36.96.1-.75.4-1.25.73-1.54-2.56-.29-5.25-1.28-5.25-5.69 0-1.26.45-2.29 1.19-3.09-.12-.29-.52-1.47.11-3.05 0 0 .97-.31 3.17 1.18a11 11 0 0 1 5.78 0c2.2-1.49 3.17-1.18 3.17-1.18.63 1.58.23 2.76.11 3.05.74.8 1.19 1.83 1.19 3.09 0 4.42-2.7 5.4-5.27 5.68.42.36.78 1.06.78 2.14v3.17c0 .31.21.67.8.56A11.5 11.5 0 0 0 12 .5z"/></svg></a>
|
||||
<a class="link icon" data-link="discord" href="#" aria-label="Discord" hidden><svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M19.6 5.2A17.5 17.5 0 0 0 15.3 3.9l-.5 1.1a16 16 0 0 0-5.5 0L8.7 3.9A17.5 17.5 0 0 0 4.4 5.2C1.7 9.3 1 13.3 1.3 17.200a17.7 17.7 0 0 0 5.3 2.700l1.1-1.800a11.5 11.5 0 0 1-1.8-.900l.400-.300a12.6 12.6 0 0 0 11.4 0l.400.300c-.600.4-1.2.700-1.8.900l1.1 1.800a17.7 17.7 0 0 0 5.3-2.700c.400-4.5-.700-8.4-3.1-12zM8.7 14.700c-1 0-1.9-1-1.9-2.200s.800-2.2 1.9-2.2 1.9 1 1.9 2.2-.800 2.2-1.9 2.200zm6.6 0c-1 0-1.9-1-1.9-2.200s.800-2.2 1.9-2.2 1.9 1 1.9 2.2-.800 2.2-1.9 2.200z"/></svg></a>
|
||||
<a class="pill main" href="/register">Create account</a>
|
||||
</nav>
|
||||
|
||||
<header id="hero">
|
||||
<div class="paws" aria-hidden="true"></div>
|
||||
<div class="dots" aria-hidden="true"></div>
|
||||
<div class="fade" aria-hidden="true"></div>
|
||||
<div class="in" id="top">
|
||||
<img id="bunny" src="/logo.png" alt="" width="300" height="244">
|
||||
<div id="name">
|
||||
<h1>Burrow</h1>
|
||||
<span aria-hidden="true">Burrow</span><span aria-hidden="true">Burrow</span><span aria-hidden="true">Burrow</span>
|
||||
</div>
|
||||
<p id="line">an AJ Classic private server</p>
|
||||
<div class="buttons">
|
||||
<a class="pill main big" href="#download">Download</a>
|
||||
<a class="pill big" href="/register">Create account</a>
|
||||
</div>
|
||||
<div class="buttons small">
|
||||
<a class="pill" data-link="discord" href="#"><svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M19.6 5.2A17.5 17.5 0 0 0 15.3 3.9l-.5 1.1a16 16 0 0 0-5.5 0L8.7 3.9A17.5 17.5 0 0 0 4.4 5.2C1.7 9.3 1 13.3 1.3 17.200a17.7 17.7 0 0 0 5.3 2.700l1.1-1.800a11.5 11.5 0 0 1-1.8-.900l.400-.300a12.6 12.6 0 0 0 11.4 0l.400.300c-.600.4-1.2.700-1.8.900l1.1 1.800a17.7 17.7 0 0 0 5.3-2.700c.400-4.5-.700-8.4-3.1-12zM8.7 14.700c-1 0-1.9-1-1.9-2.200s.800-2.2 1.9-2.2 1.9 1 1.9 2.2-.800 2.2-1.9 2.200zm6.6 0c-1 0-1.9-1-1.9-2.200s.800-2.2 1.9-2.2 1.9 1 1.9 2.2-.800 2.2-1.9 2.200z"/></svg>Discord</a>
|
||||
<a class="pill" data-link="github" href="#"><svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 .5a11.5 11.5 0 0 0-3.64 22.41c.58.1.79-.25.79-.56v-2.1c-3.2.7-3.88-1.37-3.88-1.37-.52-1.33-1.28-1.69-1.28-1.69-1.05-.71.08-.7.08-.7 1.16.08 1.77 1.19 1.77 1.19 1.03 1.76 2.7 1.25 3.36.96.1-.75.4-1.25.73-1.54-2.56-.29-5.25-1.28-5.25-5.69 0-1.26.45-2.29 1.19-3.09-.12-.29-.52-1.47.11-3.05 0 0 .97-.31 3.17 1.18a11 11 0 0 1 5.78 0c2.2-1.49 3.17-1.18 3.17-1.18.63 1.58.23 2.76.11 3.05.74.8 1.19 1.83 1.19 3.09 0 4.42-2.7 5.4-5.27 5.68.42.36.78 1.06.78 2.14v3.17c0 .31.21.67.8.56A11.5 11.5 0 0 0 12 .5z"/></svg>GitHub</a>
|
||||
</div>
|
||||
<p id="state" role="status"></p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<section id="here">
|
||||
<div class="wrap">
|
||||
<div class="head rise">
|
||||
<h2>Everything <em>unlocked</em></h2>
|
||||
</div>
|
||||
<ul id="list" class="rise">
|
||||
<li><h3>Item giver</h3><p>any item in custom colours</p></li>
|
||||
<li><h3>Membership unlocked</h3></li>
|
||||
<li><h3>Every animal and pet</h3><p>in stores all the time</p></li>
|
||||
<li><h3>Restored content</h3><p>removed content and concept dens</p></li>
|
||||
<li><h3>Themes</h3><p>any season or holiday</p></li>
|
||||
<li><h3>Alphas</h3><p>play as an alpha</p></li>
|
||||
<li><h3>Profiles</h3><p>bio, badges and better player cards</p></li>
|
||||
<li><h3>Chat upgraded</h3><p>fewer limits, whispers</p></li>
|
||||
<li><h3>Custom names</h3><p>for animals and pets</p></li>
|
||||
<li><h3>Bigger inventory</h3><p>higher limits</p></li>
|
||||
<li><h3>Custom client</h3><p>with improvements of its own</p></li>
|
||||
<li><h3>QOL improvements</h3><p>all over the game</p></li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="download">
|
||||
<div class="wrap">
|
||||
<div id="get" class="rise">
|
||||
<div>
|
||||
<h2>Get Burrow</h2>
|
||||
<p>Windows, Linux, macOS</p>
|
||||
</div>
|
||||
<div class="side">
|
||||
<div class="hole"><img src="/logo.png" alt="" loading="lazy"></div>
|
||||
<a class="pill big soon" id="get-button" aria-disabled="true">Soon</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<div class="wrap">
|
||||
<div class="row">
|
||||
<a class="brand" href="#top"><img src="/logo.png" alt="">Burrow</a>
|
||||
<a href="/register">Create account</a>
|
||||
<a href="/account">Account</a>
|
||||
<a href="/commands">Commands</a>
|
||||
<a data-link="github" href="#" hidden>GitHub</a>
|
||||
<a data-link="discord" href="#" hidden>Discord</a>
|
||||
<a href="/terms">Terms</a>
|
||||
<a href="/privacy">Privacy</a>
|
||||
</div>
|
||||
<p>Burrow is an unofficial fan project, not affiliated with or endorsed by WildWorks. Animal Jam is a trademark of WildWorks, Inc.</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
"use strict";
|
||||
const $ = id => document.getElementById(id);
|
||||
|
||||
// the server fills these addresses in from config.js; an unset one gets no link
|
||||
const address = name => {
|
||||
const value = document.body.dataset[name] || "";
|
||||
return /^https?:\/\//.test(value) || /^\/[^/]/.test(value) ? value : "";
|
||||
};
|
||||
for (const name of ["github", "discord"]) {
|
||||
for (const link of document.querySelectorAll(`[data-link="${name}"]`)) {
|
||||
if (address(name)) {
|
||||
link.href = address(name);
|
||||
link.rel = "noopener";
|
||||
link.hidden = false;
|
||||
} else if (link.classList.contains("pill")) {
|
||||
link.removeAttribute("href");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (address("download")) {
|
||||
const button = $("get-button");
|
||||
button.href = address("download");
|
||||
button.textContent = "Download";
|
||||
button.classList.remove("soon");
|
||||
button.removeAttribute("aria-disabled");
|
||||
}
|
||||
|
||||
const showState = state => {
|
||||
$("state").textContent = state ? `${Number(state.online) || 0} online` : "Offline";
|
||||
};
|
||||
const askState = () => fetch("/api/status", {cache: "no-store"})
|
||||
.then(answer => (answer.ok ? answer.json() : null))
|
||||
.then(showState, () => showState(null));
|
||||
askState();
|
||||
setInterval(() => { if (!document.hidden) { askState(); } }, 30000);
|
||||
|
||||
const still = matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
|
||||
const hero = $("hero");
|
||||
hero.addEventListener("pointermove", event => {
|
||||
const box = hero.getBoundingClientRect();
|
||||
hero.style.setProperty("--mx", `${event.clientX - box.left}px`);
|
||||
hero.style.setProperty("--my", `${event.clientY - box.top}px`);
|
||||
});
|
||||
|
||||
const arrive = element => element.classList.add("in");
|
||||
if ("IntersectionObserver" in window && !still) {
|
||||
const watcher = new IntersectionObserver(entries => {
|
||||
for (const entry of entries) {
|
||||
if (entry.isIntersecting) {
|
||||
arrive(entry.target);
|
||||
watcher.unobserve(entry.target);
|
||||
}
|
||||
}
|
||||
}, {rootMargin: "0px 0px -8% 0px"});
|
||||
document.querySelectorAll(".rise").forEach(element => watcher.observe(element));
|
||||
} else {
|
||||
document.querySelectorAll(".rise").forEach(element => element.classList.add("in"));
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 42 KiB |
@@ -0,0 +1,981 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Moderators</title>
|
||||
<link rel="icon" type="image/png" href="/logo-square.png">
|
||||
<style>
|
||||
/* black and white throughout, in the game's own text font: the look of
|
||||
the client (its app/index.html). Nothing is said by colour: what
|
||||
went wrong is white with a "!" before it, and what cannot be undone
|
||||
has a dashed edge. */
|
||||
@font-face { font-family: "DigitalDelivery"; font-weight: 400; src: url("/fonts/CCDigitalDelivery-Regular.otf") format("opentype"); }
|
||||
@font-face { font-family: "DigitalDelivery"; font-weight: 700; src: url("/fonts/CCDigitalDelivery-Bold.otf") format("opentype"); }
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #000;
|
||||
--panel: #0d0d0d;
|
||||
--raised: #1a1a1a;
|
||||
--line: #2e2e2e;
|
||||
--text: #fff;
|
||||
--muted: #8c8c8c;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
::selection { background: #fff; color: #000; }
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: var(--line); border-radius: 5px; border: 3px solid var(--bg); }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 24px 16px 48px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 15px/1.4 "DigitalDelivery", system-ui, "Segoe UI", sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
a { color: inherit; text-underline-offset: 3px; }
|
||||
h1 { margin: 0; font-size: 26px; font-weight: 700; letter-spacing: 0.01em; }
|
||||
h2 { margin: 0 0 6px; font-size: 17px; font-weight: 700; }
|
||||
h3 { font-size: 14px; font-weight: 700; }
|
||||
p { margin: 0 0 12px; color: var(--muted); }
|
||||
label { display: block; margin: 12px 0 5px; color: var(--muted); font-size: 13px; }
|
||||
.hint { font-weight: 400; color: var(--muted); font-size: 12px; }
|
||||
input, select, textarea {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
padding: 9px 14px 10px;
|
||||
transition: border-color 0.12s;
|
||||
}
|
||||
input::placeholder, textarea::placeholder { color: #555; }
|
||||
input:hover, select:hover, textarea:hover { border-color: #555; }
|
||||
input:focus, select:focus, textarea:focus { outline: none; border-color: var(--text); }
|
||||
input:disabled, select:disabled, textarea:disabled { opacity: 0.4; }
|
||||
select:not([multiple]) {
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
padding-right: 34px;
|
||||
background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%), linear-gradient(135deg, var(--muted) 50%, transparent 50%);
|
||||
background-position: calc(100% - 19px) 55%, calc(100% - 14px) 55%;
|
||||
background-size: 5px 5px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
input[type="checkbox"] {
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
flex: none;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
margin: 0 6px 0 0;
|
||||
padding: 0;
|
||||
vertical-align: -4px;
|
||||
border: 1px solid #666;
|
||||
border-radius: 6px;
|
||||
background: var(--panel);
|
||||
cursor: pointer;
|
||||
}
|
||||
input[type="checkbox"]:hover { border-color: var(--text); }
|
||||
input[type="checkbox"]:checked {
|
||||
border-color: var(--text);
|
||||
background: var(--text) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'%3E%3Cpath d='M4.5 9.5l3 3 6-7' fill='none' stroke='%23000' stroke-width='2.2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / 16px no-repeat;
|
||||
}
|
||||
button {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: none;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
padding: 7px 16px 8px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition: background 0.12s, border-color 0.12s, color 0.12s;
|
||||
}
|
||||
button:hover { background: var(--raised); border-color: #555; }
|
||||
button:disabled { opacity: 0.45; cursor: default; }
|
||||
button:focus-visible, a:focus-visible, input[type="checkbox"]:focus-visible { outline: 2px solid var(--text); outline-offset: 2px; }
|
||||
button.primary { font-weight: 700; color: #000; background: var(--text); border-color: var(--text); }
|
||||
button.primary:hover { background: #d9d9d9; border-color: #d9d9d9; }
|
||||
button.primary:disabled, button.primary:disabled:hover { background: #3a3a3a; border-color: #3a3a3a; color: #000; }
|
||||
button.danger { border-style: dashed; border-color: #666; }
|
||||
button.danger:hover { border-style: solid; border-color: var(--text); }
|
||||
.status, #status { min-height: 20px; margin: 10px 0 0; font-size: 13px; color: var(--muted); }
|
||||
.status.bad, #status.bad { color: var(--text); }
|
||||
.status.bad::before, #status.bad::before, .notice::before {
|
||||
content: "!";
|
||||
display: inline-block;
|
||||
width: 17px;
|
||||
height: 17px;
|
||||
margin-right: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--text);
|
||||
color: #000;
|
||||
font-weight: 700;
|
||||
line-height: 17px;
|
||||
text-align: center;
|
||||
}
|
||||
@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; }
|
||||
|
||||
#gate {
|
||||
max-width: 380px;
|
||||
margin: 6vh auto 0;
|
||||
padding: 24px;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 18px;
|
||||
}
|
||||
#gate h1 { margin-bottom: 4px; }
|
||||
#gate input { width: 100%; }
|
||||
#gate button { width: 100%; margin-top: 18px; padding: 10px 16px 11px; }
|
||||
#captcha { margin-top: 16px; }
|
||||
|
||||
#panel { max-width: 1080px; margin: 0 auto; }
|
||||
header { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; flex-wrap: wrap; }
|
||||
header h1 { flex: 1; }
|
||||
/* the pages: one row of names, the chosen one filled. */
|
||||
nav { display: flex; gap: 2px; margin-bottom: 16px; padding: 3px; border: 1px solid var(--line); border-radius: 22px; flex-wrap: wrap; }
|
||||
nav button { border: 0; color: var(--muted); padding: 6px 14px 7px; }
|
||||
nav button:hover { color: var(--text); }
|
||||
nav button[aria-selected="true"] { color: #000; background: var(--text); font-weight: 700; }
|
||||
section { background: var(--panel); border: 1px solid var(--line); border-radius: 18px; padding: 18px; margin-bottom: 16px; }
|
||||
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; margin-bottom: 16px; }
|
||||
.tile { padding: 12px 14px 11px; border: 1px solid var(--line); border-radius: 18px; }
|
||||
.tile .value { font-size: 26px; font-weight: 700; line-height: 1.15; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
|
||||
.tile .name { margin-top: 2px; font-size: 11px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--muted); }
|
||||
.columns { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 16px; }
|
||||
.columns section { margin: 0; }
|
||||
dl { display: grid; grid-template-columns: auto 1fr; gap: 6px 16px; margin: 0; }
|
||||
dt { color: var(--muted); }
|
||||
dd { margin: 0; overflow-wrap: anywhere; }
|
||||
.table-wrap { overflow-x: auto; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td { text-align: left; padding: 7px 10px; border-bottom: 1px solid var(--line); white-space: nowrap; }
|
||||
th { font-size: 11px; text-transform: uppercase; letter-spacing: 0.1em; color: var(--muted); font-weight: 400; }
|
||||
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
td button { padding: 2px 12px 3px; font-weight: 700; }
|
||||
tbody tr:last-child td { border-bottom: 0; }
|
||||
tbody tr.selected td { background: var(--raised); }
|
||||
tbody tr.pick { cursor: pointer; }
|
||||
.empty { color: var(--muted); padding: 8px 0; }
|
||||
.toolbar { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; }
|
||||
.toolbar input[type="search"] { flex: 1; min-width: 180px; }
|
||||
.tag { display: inline-block; padding: 1px 9px 2px; border: 1px solid var(--line); border-radius: 999px; font-size: 11px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted); }
|
||||
.tag.good { color: #000; background: var(--text); border-color: var(--text); font-weight: 700; }
|
||||
.tag.bad { color: var(--text); border-color: var(--text); font-weight: 700; }
|
||||
#detail { margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--line); }
|
||||
.actions { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 12px; }
|
||||
.action .hint { margin: 8px 0 0; }
|
||||
.action { border: 1px solid var(--line); border-radius: 18px; padding: 14px; }
|
||||
.action h3 { margin: 0 0 8px; }
|
||||
.action .row { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.action .row input, .action .row select { flex: 1; min-width: 90px; }
|
||||
.action .buttons { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
/* what the server printed keeps a fixed-width face: it is read in columns. */
|
||||
#log {
|
||||
height: 60vh;
|
||||
overflow: auto;
|
||||
margin: 0;
|
||||
padding: 12px 14px;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
font: 12px/1.5 ui-monospace, Consolas, monospace;
|
||||
color: #bdbdbd;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
#log .time { color: var(--muted); }
|
||||
#log .error { color: var(--text); font-weight: 700; }
|
||||
.report { border: 1px solid var(--line); border-radius: 18px; padding: 14px; margin-bottom: 12px; }
|
||||
.report h3 { margin: 0 0 4px; }
|
||||
.report .typed { margin: 8px 0; padding: 8px 12px; background: var(--bg); border: 1px solid var(--line); border-radius: 14px; overflow-wrap: anywhere; }
|
||||
.report pre { margin: 8px 0; padding: 8px 12px; background: var(--bg); border: 1px solid var(--line); border-radius: 14px; font: 12px/1.5 ui-monospace, Consolas, monospace; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 180px; overflow: auto; }
|
||||
.report .buttons { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; }
|
||||
.paintings { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 12px; }
|
||||
.painting { border: 1px solid var(--line); border-radius: 18px; padding: 14px; }
|
||||
.painting img { display: block; width: 100%; height: auto; border-radius: 10px; background: #fff; }
|
||||
.painting h3 { margin: 8px 0 2px; }
|
||||
.painting .buttons { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; }
|
||||
textarea { width: 100%; resize: vertical; }
|
||||
.send-row { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; align-items: center; }
|
||||
#owned { margin-top: 16px; }
|
||||
#owned ul { margin: 4px 0 12px; padding-left: 18px; columns: 220px; }
|
||||
#ban-record h3 { margin: 14px 0 4px; }
|
||||
#ban-record ul { margin: 0; padding-left: 18px; font-size: 13px; overflow-wrap: anywhere; }
|
||||
#ban-record li { margin: 3px 0; }
|
||||
#ban-record li button { padding: 2px 10px 3px; font-size: 12px; }
|
||||
#owned li { break-inside: avoid; }
|
||||
#password-form { max-width: 360px; }
|
||||
#password-form input { width: 100%; }
|
||||
#password-form button { margin-top: 16px; }
|
||||
.logo { display: block; height: 72px; margin: 0 0 12px; }
|
||||
.mark { height: 34px; flex: none; }
|
||||
#chat-lines { margin: 0; padding: 0; list-style: none; }
|
||||
#chat-lines li, #chat-context li { display: flex; gap: 10px; align-items: baseline; padding: 6px 4px; border-bottom: 1px solid var(--line); }
|
||||
#chat-lines li:last-child, #chat-context li:last-child { border-bottom: 0; }
|
||||
.chat-time { flex: none; width: 128px; color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
|
||||
.chat-who { flex: none; max-width: 190px; padding: 0; border: 0; font-weight: 700; text-align: left; overflow: hidden; text-overflow: ellipsis; }
|
||||
.chat-who:hover { background: none; text-decoration: underline; }
|
||||
.chat-text { flex: 1; min-width: 0; overflow-wrap: anywhere; }
|
||||
.chat-room { display: block; color: var(--muted); font-size: 12px; }
|
||||
.chat-more { flex: none; padding: 2px 10px 3px; font-size: 12px; }
|
||||
#chat-context { margin: 0; padding: 0; list-style: none; }
|
||||
#chat-context li.this { background: var(--raised); border-radius: 10px; }
|
||||
#player-facts { margin-bottom: 14px; }
|
||||
#player-history { margin: 0; padding-left: 18px; font-size: 13px; overflow-wrap: anywhere; }
|
||||
.actions { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 12px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main id="gate" hidden>
|
||||
<img class="logo" src="/logo.png" alt="">
|
||||
<h1>Moderators</h1>
|
||||
<form id="gate-form">
|
||||
<label for="username">Username</label>
|
||||
<input id="username" autocomplete="username" maxlength="100" spellcheck="false" required>
|
||||
<label for="password">Password</label>
|
||||
<input id="password" type="password" autocomplete="current-password" maxlength="100" required>
|
||||
<label for="code">2FA code</label>
|
||||
<input id="code" inputmode="numeric" autocomplete="one-time-code" maxlength="20" spellcheck="false" required>
|
||||
<div id="captcha"></div>
|
||||
<button class="primary" id="gate-button">Sign in</button>
|
||||
</form>
|
||||
<p class="status" id="gate-status" role="status"></p>
|
||||
</main>
|
||||
|
||||
<div id="panel" hidden>
|
||||
<header>
|
||||
<img class="mark" src="/logo.png" alt="">
|
||||
<h1>Moderators</h1>
|
||||
<span class="hint" id="who"></span>
|
||||
<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>
|
||||
</nav>
|
||||
|
||||
<div data-view="players">
|
||||
<section>
|
||||
<div class="toolbar">
|
||||
<input id="player-search" type="search" placeholder="Search" aria-label="Search players">
|
||||
<span class="hint" id="online-count"></span>
|
||||
</div>
|
||||
<div class="table-wrap"><table>
|
||||
<thead><tr><th>Name</th><th>State</th><th>Where</th><th>Last seen</th></tr></thead>
|
||||
<tbody id="players"></tbody>
|
||||
</table></div>
|
||||
<div class="empty" id="no-players" hidden>No players match.</div>
|
||||
</section>
|
||||
<section id="detail" hidden>
|
||||
<h2 id="detail-name"></h2>
|
||||
<p class="status" id="detail-status" role="status"></p>
|
||||
<dl id="player-facts"></dl>
|
||||
<div class="actions">
|
||||
<div class="action">
|
||||
<h3>Ban</h3>
|
||||
<div class="row"><input id="ban-hours" type="number" min="0" placeholder="Hours (0 = forever)" aria-label="Ban length in hours">
|
||||
<input id="ban-reason" maxlength="300" placeholder="Reason" autocomplete="off" aria-label="Reason, shown to the banned player"></div>
|
||||
<div class="row" style="margin-top:8px">
|
||||
<button type="button" data-action="ban" class="danger">Ban</button>
|
||||
<button type="button" data-action="banReason">Save reason</button>
|
||||
<button type="button" data-action="unban">Lift</button>
|
||||
<button type="button" data-action="banAddress" class="danger">Ban address</button></div>
|
||||
</div>
|
||||
<div class="action">
|
||||
<h3>Chat</h3>
|
||||
<div class="row"><input id="silence-hours" type="number" min="0" placeholder="Hours (0 = until lifted)" aria-label="Silence length in hours">
|
||||
<button type="button" data-action="silence">Silence</button>
|
||||
<button type="button" data-action="unsilence">Lift</button></div>
|
||||
<div class="row" style="margin-top:8px"><button type="button" id="open-chat">Chat history</button></div>
|
||||
</div>
|
||||
<div class="action">
|
||||
<h3>Message</h3>
|
||||
<div class="row"><input id="message-text" maxlength="200" placeholder="Text" aria-label="Message">
|
||||
<button type="button" data-action="message">Send</button></div>
|
||||
<div class="row" style="margin-top:8px"><button type="button" data-action="kick">Disconnect</button></div>
|
||||
</div>
|
||||
<div class="action">
|
||||
<h3>Username and bio</h3>
|
||||
<div class="row">
|
||||
<button type="button" data-action="rejectName" class="danger">Reject username</button>
|
||||
<button type="button" data-action="acceptName">Take back</button>
|
||||
<button type="button" data-action="clearBio">Clear bio</button></div>
|
||||
</div>
|
||||
</div>
|
||||
<h3 style="margin:16px 0 4px" id="history-title" hidden>Ban history</h3>
|
||||
<ul id="player-history"></ul>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div data-view="chat" hidden>
|
||||
<section>
|
||||
<form id="chat-form" class="toolbar">
|
||||
<input id="chat-player" maxlength="100" placeholder="Player" autocomplete="off" spellcheck="false" aria-label="Player">
|
||||
<input id="chat-room" maxlength="100" placeholder="Room" autocomplete="off" spellcheck="false" aria-label="Room">
|
||||
<input id="chat-text" maxlength="100" placeholder="Words" autocomplete="off" aria-label="Words" style="flex:1">
|
||||
<button class="primary" type="submit">Search</button>
|
||||
</form>
|
||||
<p class="status" id="chat-status" role="status"></p>
|
||||
<div id="context-box" hidden>
|
||||
<div class="toolbar"><h2 style="margin:0;flex:1" id="context-title"></h2><button type="button" id="context-close">Close</button></div>
|
||||
<ul id="chat-context"></ul>
|
||||
</div>
|
||||
<ul id="chat-lines"></ul>
|
||||
<div class="empty" id="no-chat" hidden>Nothing here.</div>
|
||||
<div class="send-row"><button type="button" id="chat-older" hidden>Older</button></div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div data-view="reports" hidden>
|
||||
<section>
|
||||
<div class="toolbar">
|
||||
<h2 style="margin:0;flex:1">Reports</h2>
|
||||
<select id="report-filter" aria-label="Which reports">
|
||||
<option value="0">Waiting</option>
|
||||
<option value="1">Dealt with</option>
|
||||
</select>
|
||||
</div>
|
||||
<p class="status" id="report-status" role="status"></p>
|
||||
<div id="reports"></div>
|
||||
<div class="empty" id="no-reports" hidden>Nothing here.</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div data-view="requests" hidden>
|
||||
<section>
|
||||
<div class="toolbar">
|
||||
<h2 style="margin:0;flex:1">Requests</h2>
|
||||
<select id="request-filter" aria-label="Which requests">
|
||||
<option value="0">Waiting</option>
|
||||
<option value="1">Answered</option>
|
||||
</select>
|
||||
</div>
|
||||
<p class="status" id="request-status" role="status"></p>
|
||||
<h2>Ban appeals</h2>
|
||||
<div id="appeals"></div>
|
||||
<div class="empty" id="no-appeals" hidden>Nothing here.</div>
|
||||
<h2 style="margin-top:20px">Username changes</h2>
|
||||
<div id="name-requests"></div>
|
||||
<div class="empty" id="no-name-requests" hidden>Nothing here.</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div data-view="masterpieces" hidden>
|
||||
<section>
|
||||
<div class="toolbar">
|
||||
<h2 style="margin:0;flex:1">Masterpieces</h2>
|
||||
<select id="masterpiece-filter" aria-label="Which masterpieces">
|
||||
<option value="waiting">Waiting</option>
|
||||
<option value="approved">On show</option>
|
||||
</select>
|
||||
</div>
|
||||
<p class="status" id="masterpiece-status" role="status"></p>
|
||||
<div class="paintings" id="masterpieces"></div>
|
||||
<div class="empty" id="no-masterpieces" hidden>Nothing here.</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div data-view="bans" hidden>
|
||||
<section>
|
||||
<h2>Banned and silenced</h2>
|
||||
<p class="status" id="ban-status" role="status"></p>
|
||||
<div class="table-wrap"><table>
|
||||
<thead><tr><th>Name</th><th>Ban</th><th>Reason</th><th>By</th><th>Chat</th><th></th></tr></thead>
|
||||
<tbody id="bans"></tbody>
|
||||
</table></div>
|
||||
<div class="empty" id="no-bans" hidden>Nobody is banned or silenced.</div>
|
||||
</section>
|
||||
<section>
|
||||
<h2>Banned addresses</h2>
|
||||
<div class="table-wrap"><table>
|
||||
<thead><tr><th>Address</th><th>Reason</th><th>By</th><th>Since</th><th></th></tr></thead>
|
||||
<tbody id="addresses"></tbody>
|
||||
</table></div>
|
||||
<div class="empty" id="no-addresses" hidden>No address is banned.</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/captcha.js"></script>
|
||||
<script>
|
||||
"use strict";
|
||||
|
||||
const $ = id => document.getElementById(id);
|
||||
const REFRESH_MS = 8000;
|
||||
|
||||
let signedIn = false;
|
||||
let tab = "players";
|
||||
let selected = null; // the username of the player whose box is open
|
||||
let players = [];
|
||||
let chatQuery = null; // what the Chat page shows: {username, room, text}
|
||||
let chatLines = [];
|
||||
let timer = null;
|
||||
|
||||
const el = (tag, text, className) => {
|
||||
const node = document.createElement(tag);
|
||||
if (text !== undefined) {
|
||||
node.textContent = text;
|
||||
}
|
||||
if (className) {
|
||||
node.className = className;
|
||||
}
|
||||
return node;
|
||||
};
|
||||
const button = (label, onClick, className) => {
|
||||
const node = el("button", label, className);
|
||||
node.type = "button";
|
||||
node.addEventListener("click", async () => {
|
||||
node.disabled = true;
|
||||
await onClick();
|
||||
node.disabled = false;
|
||||
});
|
||||
return node;
|
||||
};
|
||||
|
||||
const setStatus = (element, text, bad = false) => {
|
||||
element.textContent = text;
|
||||
element.classList.toggle("bad", bad);
|
||||
};
|
||||
|
||||
const when = seconds => (seconds ? new Date(seconds * 1000).toLocaleString([], {dateStyle: "medium", timeStyle: "short"}) : "never");
|
||||
const duration = seconds => {
|
||||
for (const [size, name] of [[86400, "day"], [3600, "hour"], [60, "minute"]]) {
|
||||
if (seconds >= size) {
|
||||
const count = Math.floor(seconds / size);
|
||||
return `${count} ${name}${count === 1 ? "" : "s"}`;
|
||||
}
|
||||
}
|
||||
return "under a minute";
|
||||
};
|
||||
const left = seconds => (seconds === -1 ? "Until lifted" : seconds ? `${duration(seconds)} left` : "—");
|
||||
|
||||
let check = null; // the captcha (public/captcha.js), once the sign-in is shown
|
||||
|
||||
const showGate = message => {
|
||||
check = check || window.captcha.mount($("captcha"), "login");
|
||||
clearTimeout(timer);
|
||||
signedIn = false;
|
||||
$("panel").hidden = true;
|
||||
$("gate").hidden = false;
|
||||
$("password").value = "";
|
||||
$("code").value = "";
|
||||
setStatus($("gate-status"), message || "", Boolean(message));
|
||||
};
|
||||
|
||||
const api = async (path, body) => {
|
||||
try {
|
||||
const response = await fetch(`/mod/api/${path}`, body === undefined ? {} : {
|
||||
method: "POST",
|
||||
headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (response.status === 401 && signedIn) {
|
||||
showGate("Your session ended. Sign in again.");
|
||||
}
|
||||
return {ok: response.ok, status: response.status, data};
|
||||
}
|
||||
catch (err) {
|
||||
return {ok: false, status: 0, data: {error: "The server did not answer."}};
|
||||
}
|
||||
};
|
||||
const said = result => result.data.ok || result.data.error || "That did not work.";
|
||||
|
||||
const stateTags = player => {
|
||||
const tags = [];
|
||||
if (player.online) {
|
||||
tags.push(el("span", "Online", "tag good"));
|
||||
}
|
||||
if (player.banned !== 0) {
|
||||
tags.push(el("span", player.banned === -1 ? "Banned" : `Banned ${duration(player.banned)}`, "tag bad"));
|
||||
}
|
||||
if (player.silenced !== 0) {
|
||||
tags.push(el("span", "Silenced", "tag bad"));
|
||||
}
|
||||
if (player.nameRejected) {
|
||||
tags.push(el("span", "Name rejected", "tag bad"));
|
||||
}
|
||||
if (player.moderator) {
|
||||
tags.push(el("span", "Moderator", "tag"));
|
||||
}
|
||||
return tags;
|
||||
};
|
||||
|
||||
const renderPlayers = () => {
|
||||
$("players").replaceChildren(...players.map(player => {
|
||||
const row = el("tr", undefined, player.username === selected ? "pick selected" : "pick");
|
||||
const stateCell = el("td");
|
||||
stateCell.append(...stateTags(player).flatMap(tag => [tag, " "]));
|
||||
row.append(el("td", player.username), stateCell, el("td", player.room || "—"), el("td", player.online ? "Now" : when(player.lastSeen)));
|
||||
row.addEventListener("click", () => select(player.username === selected ? null : player.username));
|
||||
return row;
|
||||
}));
|
||||
$("no-players").hidden = players.length > 0;
|
||||
};
|
||||
|
||||
const HISTORY = {ban: "Banned", unban: "Ban lifted", reason: "Reason changed", appeal: "Appealed",
|
||||
appeal_approved: "Appeal approved", appeal_denied: "Appeal denied"};
|
||||
const loadDetail = async () => {
|
||||
$("detail").hidden = !selected;
|
||||
if (!selected) {
|
||||
return;
|
||||
}
|
||||
const username = selected;
|
||||
const result = await api(`player?username=${encodeURIComponent(username)}`);
|
||||
if (username !== selected) {
|
||||
return;
|
||||
}
|
||||
if (!result.ok) {
|
||||
selected = null;
|
||||
$("detail").hidden = true;
|
||||
return;
|
||||
}
|
||||
const player = result.data;
|
||||
$("detail-name").textContent = player.username;
|
||||
const facts = [
|
||||
["State", null],
|
||||
["Where", player.online ? player.room : "Offline"],
|
||||
["Last seen", player.online ? "Now" : when(player.lastSeen)],
|
||||
["Joined", when(player.createdAt)],
|
||||
["Ban", player.banned === 0 ? "—" : `${left(player.banned)} · ${player.banReason}`],
|
||||
["Chat", player.silenced === 0 ? "—" : `Silenced: ${left(player.silenced).toLowerCase()}`],
|
||||
["Reports waiting", String(player.openReports)],
|
||||
["Appeal", player.appeal ? `${player.appeal.status} · ${player.appeal.text}` : "—"],
|
||||
["Discord", player.discord || "—"],
|
||||
["Bio", player.bio || "—"],
|
||||
];
|
||||
$("player-facts").replaceChildren(...facts.flatMap(([name, value]) => {
|
||||
const cell = el("dd", value === null ? undefined : value);
|
||||
if (value === null) {
|
||||
const tags = stateTags(player);
|
||||
cell.append(...(tags.length ? tags.flatMap(tag => [tag, " "]) : ["—"]));
|
||||
}
|
||||
return [el("dt", name), cell];
|
||||
}));
|
||||
if (document.activeElement !== $("ban-reason")) {
|
||||
$("ban-reason").value = player.banned === 0 ? "" : player.banReason;
|
||||
}
|
||||
$("history-title").hidden = player.history.length === 0;
|
||||
$("player-history").replaceChildren(...player.history.map(entry => el("li", [when(entry.at), HISTORY[entry.action] || entry.action,
|
||||
entry.action === "ban" ? (entry.seconds === -1 ? "for good" : duration(entry.seconds)) : "", entry.reason, entry.by && `by ${entry.by}`]
|
||||
.filter(Boolean).join(" · "))));
|
||||
};
|
||||
|
||||
const select = username => {
|
||||
selected = username;
|
||||
setStatus($("detail-status"), "");
|
||||
for (const id of ["ban-hours", "ban-reason", "silence-hours", "message-text"]) {
|
||||
$(id).value = "";
|
||||
}
|
||||
renderPlayers();
|
||||
loadDetail();
|
||||
};
|
||||
|
||||
// from another page: that player's box, whether or not the search shows them.
|
||||
const openPlayer = username => {
|
||||
$("player-search").value = username;
|
||||
selected = username;
|
||||
showTab("players");
|
||||
};
|
||||
|
||||
const numberFrom = id => ($(id).value.trim() === "" ? NaN : Number($(id).value));
|
||||
const actionBody = action => {
|
||||
switch (action) {
|
||||
case "ban": return {hours: numberFrom("ban-hours"), reason: $("ban-reason").value};
|
||||
case "banReason": case "banAddress": return {reason: $("ban-reason").value};
|
||||
case "silence": return {hours: numberFrom("silence-hours")};
|
||||
case "message": return {text: $("message-text").value};
|
||||
default: return {};
|
||||
}
|
||||
};
|
||||
const CONFIRM = {
|
||||
banAddress: name => `Ban the address ${name} last signed in from, for good?`,
|
||||
rejectName: name => `Reject the username ${name}? They are signed out and must pick another.`,
|
||||
};
|
||||
|
||||
$("detail").addEventListener("click", async event => {
|
||||
const pressed = event.target.closest("button[data-action]");
|
||||
if (!pressed || !selected) {
|
||||
return;
|
||||
}
|
||||
const {action} = pressed.dataset;
|
||||
if (CONFIRM[action] && !window.confirm(CONFIRM[action](selected))) {
|
||||
return;
|
||||
}
|
||||
pressed.disabled = true;
|
||||
const result = await api("act", {username: selected, action, ...actionBody(action)});
|
||||
pressed.disabled = false;
|
||||
setStatus($("detail-status"), said(result), !result.ok);
|
||||
if (result.ok) {
|
||||
$("ban-hours").value = "";
|
||||
$("silence-hours").value = "";
|
||||
$("message-text").value = "";
|
||||
refresh();
|
||||
}
|
||||
});
|
||||
|
||||
$("player-search").addEventListener("input", () => refresh());
|
||||
|
||||
const chatUrl = before => `chat?username=${encodeURIComponent(chatQuery.username)}&room=${encodeURIComponent(chatQuery.room)}`
|
||||
+ `&text=${encodeURIComponent(chatQuery.text)}&before=${before}`;
|
||||
|
||||
const lineNode = (line, inContext = false) => {
|
||||
const item = el("li", undefined, inContext && line.marked ? "this" : "");
|
||||
const who = button(line.username, () => openPlayer(line.username), "chat-who");
|
||||
const text = el("span", undefined, "chat-text");
|
||||
text.append(line.text, el("span", line.whisperTo ? `Whisper to ${line.whisperTo}` : line.room, "chat-room"));
|
||||
item.append(el("span", when(line.at), "chat-time"), who, text);
|
||||
if (!inContext) {
|
||||
item.append(button("Around", () => showContext(line.id), "chat-more"));
|
||||
}
|
||||
return item;
|
||||
};
|
||||
|
||||
const renderChat = more => {
|
||||
$("chat-lines").replaceChildren(...chatLines.map(line => lineNode(line)));
|
||||
$("no-chat").hidden = chatLines.length > 0;
|
||||
$("chat-older").hidden = !more;
|
||||
};
|
||||
|
||||
const loadChat = async older => {
|
||||
if (!chatQuery) {
|
||||
chatQuery = {username: "", room: "", text: ""};
|
||||
}
|
||||
const before = older && chatLines.length ? chatLines[chatLines.length - 1].id : 0;
|
||||
const result = await api(chatUrl(before));
|
||||
if (!result.ok) {
|
||||
setStatus($("chat-status"), said(result), true);
|
||||
return;
|
||||
}
|
||||
chatLines = older ? [...chatLines, ...result.data.lines] : result.data.lines;
|
||||
setStatus($("chat-status"), result.data.days > 0 ? `Kept ${result.data.days} days.` : "Chat is not being kept.");
|
||||
renderChat(result.data.more);
|
||||
};
|
||||
|
||||
const showContext = async id => {
|
||||
const result = await api(`chat/around?id=${id}`);
|
||||
if (!result.ok) {
|
||||
setStatus($("chat-status"), said(result), true);
|
||||
return;
|
||||
}
|
||||
const {line, lines} = result.data;
|
||||
$("context-title").textContent = line.whisperTo ? `${line.username} and ${line.whisperTo}` : line.room;
|
||||
$("chat-context").replaceChildren(...lines.map(entry => lineNode({...entry, marked: entry.id === line.id}, true)));
|
||||
$("context-box").hidden = false;
|
||||
$("context-box").scrollIntoView({block: "nearest"});
|
||||
};
|
||||
$("context-close").addEventListener("click", () => {
|
||||
$("context-box").hidden = true;
|
||||
});
|
||||
|
||||
$("chat-form").addEventListener("submit", event => {
|
||||
event.preventDefault();
|
||||
chatQuery = {username: $("chat-player").value.trim(), room: $("chat-room").value.trim(), text: $("chat-text").value.trim()};
|
||||
$("context-box").hidden = true;
|
||||
loadChat(false);
|
||||
});
|
||||
$("chat-older").addEventListener("click", () => loadChat(true));
|
||||
|
||||
const openChat = username => {
|
||||
$("chat-player").value = username;
|
||||
$("chat-room").value = "";
|
||||
$("chat-text").value = "";
|
||||
chatQuery = {username, room: "", text: ""};
|
||||
$("context-box").hidden = true;
|
||||
showTab("chat");
|
||||
};
|
||||
$("open-chat").addEventListener("click", () => selected && openChat(selected));
|
||||
|
||||
const renderReports = data => {
|
||||
const handled = $("report-filter").value === "1";
|
||||
$("report-count").textContent = data.open ? ` (${data.open})` : "";
|
||||
$("reports").replaceChildren(...data.reports.map(report => {
|
||||
const box = el("div", undefined, "report");
|
||||
box.append(el("h3", `${report.target} — ${report.reason}`),
|
||||
el("div", `Reported by ${report.reporter} on ${when(report.createdAt)}${report.room ? `, in ${report.room}` : ""}`, "hint"));
|
||||
if (report.detail) {
|
||||
box.append(el("div", report.detail, "typed"));
|
||||
}
|
||||
if (report.context) {
|
||||
box.append(el("pre", report.context));
|
||||
}
|
||||
const buttons = el("div", undefined, "buttons");
|
||||
buttons.append(button("Player", () => openPlayer(report.target)), button("Chat history", () => openChat(report.target)));
|
||||
if (handled) {
|
||||
box.append(el("div", `Dealt with on ${when(report.handledAt)}`, "hint"));
|
||||
}
|
||||
else {
|
||||
buttons.append(button("Dealt with", async () => {
|
||||
const result = await api("report", {id: report.id});
|
||||
setStatus($("report-status"), said(result), !result.ok);
|
||||
refresh();
|
||||
}, "primary"));
|
||||
}
|
||||
box.append(buttons);
|
||||
return box;
|
||||
}));
|
||||
$("no-reports").hidden = data.reports.length > 0;
|
||||
};
|
||||
$("report-filter").addEventListener("change", () => refresh());
|
||||
|
||||
const renderRequests = data => {
|
||||
const handled = $("request-filter").value === "1";
|
||||
const answer = async body => {
|
||||
const result = await api("request", body);
|
||||
setStatus($("request-status"), said(result), !result.ok);
|
||||
if (document.activeElement) {
|
||||
document.activeElement.blur();
|
||||
}
|
||||
refresh();
|
||||
};
|
||||
// typed replies are left alone while one is being written.
|
||||
if (!$("appeals").contains(document.activeElement) || document.activeElement.tagName !== "INPUT") {
|
||||
$("appeals").replaceChildren(...data.appeals.map(appeal => {
|
||||
const box = el("div", undefined, "report");
|
||||
box.append(el("h3", appeal.username), el("div", `Sent on ${when(appeal.createdAt)}${appeal.gone ? " · account deleted" : ""}`, "hint"));
|
||||
if (appeal.ban) {
|
||||
box.append(el("div", `Banned${appeal.ban.seconds === -1 ? " for good" : `, ${duration(appeal.ban.seconds)} left`} · ${appeal.ban.reason}`, "hint"));
|
||||
}
|
||||
if (appeal.ofAddress) {
|
||||
box.append(el("div", "Their address is banned.", "hint"));
|
||||
}
|
||||
box.append(el("div", appeal.text, "typed"));
|
||||
if (handled) {
|
||||
box.append(el("div", `${appeal.status === "approved" ? "Approved" : "Denied"} on ${when(appeal.handledAt)}${appeal.reply ? ` · ${appeal.reply}` : ""}`, "hint"));
|
||||
return box;
|
||||
}
|
||||
const reply = el("input");
|
||||
reply.maxLength = 500;
|
||||
reply.placeholder = "Reply (optional)";
|
||||
reply.setAttribute("aria-label", `Reply to ${appeal.username}`);
|
||||
reply.style.width = "100%";
|
||||
const buttons = el("div", undefined, "buttons");
|
||||
buttons.append(button("Unban", () => answer({action: "appealApprove", id: appeal.accountId, reply: reply.value}), "primary"),
|
||||
button("Deny", () => answer({action: "appealDeny", id: appeal.accountId, reply: reply.value})),
|
||||
button("Player", () => openPlayer(appeal.username)), button("Chat history", () => openChat(appeal.username)));
|
||||
box.append(reply, buttons);
|
||||
return box;
|
||||
}));
|
||||
}
|
||||
$("no-appeals").hidden = data.appeals.length > 0;
|
||||
$("name-requests").replaceChildren(...data.names.map(request => {
|
||||
const box = el("div", undefined, "report");
|
||||
box.append(el("h3", `${request.oldName} → ${request.newName}`), el("div", `Asked on ${when(request.createdAt)}`, "hint"));
|
||||
if (request.reason) {
|
||||
box.append(el("div", request.reason, "typed"));
|
||||
}
|
||||
if (handled) {
|
||||
box.append(el("div", `${request.status === "approved" ? "Approved" : "Denied"} on ${when(request.handledAt)}`, "hint"));
|
||||
}
|
||||
else {
|
||||
const buttons = el("div", undefined, "buttons");
|
||||
buttons.append(button("Approve", () => answer({action: "approve", id: request.id}), "primary"), button("Deny", () => answer({action: "deny", id: request.id})));
|
||||
box.append(buttons);
|
||||
}
|
||||
return box;
|
||||
}));
|
||||
$("no-name-requests").hidden = data.names.length > 0;
|
||||
};
|
||||
$("request-filter").addEventListener("change", () => refresh());
|
||||
|
||||
let paintingsShown = "";
|
||||
const renderMasterpieces = data => {
|
||||
const which = $("masterpiece-filter").value;
|
||||
const paintings = data[which];
|
||||
$("masterpiece-count").textContent = data.waiting.length ? ` (${data.waiting.length})` : "";
|
||||
$("no-masterpieces").hidden = paintings.length > 0;
|
||||
// drawn again only when the list changed, so the pictures do not flicker.
|
||||
const shown = `${which} ${paintings.map(painting => painting.id).join(" ")}`;
|
||||
if (shown === paintingsShown) {
|
||||
return;
|
||||
}
|
||||
paintingsShown = shown;
|
||||
$("masterpieces").replaceChildren(...paintings.map(painting => {
|
||||
const box = el("div", undefined, "painting");
|
||||
const picture = el("img");
|
||||
picture.src = `/mod/api/masterpiece?id=${encodeURIComponent(painting.id)}`;
|
||||
picture.alt = `Painting by ${painting.creator}`;
|
||||
picture.loading = "lazy";
|
||||
box.append(picture, el("h3", painting.creator), el("div", when(painting.createdAt), "hint"));
|
||||
const buttons = el("div", undefined, "buttons");
|
||||
const does = (label, action, className) => button(label, async () => {
|
||||
const result = await api("masterpiece", {id: painting.id, action});
|
||||
setStatus($("masterpiece-status"), said(result), !result.ok);
|
||||
refresh();
|
||||
}, className);
|
||||
if (which === "waiting") {
|
||||
buttons.append(does("Approve", "approve", "primary"), does("Reject", "reject", "danger"));
|
||||
}
|
||||
else {
|
||||
buttons.append(does("Remove", "remove", "danger"));
|
||||
}
|
||||
buttons.append(button("Player", () => openPlayer(painting.creator)));
|
||||
box.append(buttons);
|
||||
return box;
|
||||
}));
|
||||
};
|
||||
$("masterpiece-filter").addEventListener("change", () => refresh());
|
||||
|
||||
const renderBans = data => {
|
||||
$("bans").replaceChildren(...data.accounts.map(account => {
|
||||
const row = el("tr");
|
||||
const buttons = el("td");
|
||||
const lifts = (label, action) => button(label, async () => {
|
||||
const result = await api("act", {username: account.username, action});
|
||||
setStatus($("ban-status"), said(result), !result.ok);
|
||||
refresh();
|
||||
});
|
||||
if (account.banned !== 0) {
|
||||
buttons.append(lifts("Lift ban", "unban"), " ");
|
||||
}
|
||||
if (account.silenced !== 0) {
|
||||
buttons.append(lifts("Lift silence", "unsilence"), " ");
|
||||
}
|
||||
buttons.append(button("Player", () => openPlayer(account.username)));
|
||||
row.append(el("td", account.username), el("td", left(account.banned)), el("td", account.reason || "—"), el("td", account.by || "—"),
|
||||
el("td", account.silenced === 0 ? "—" : `Silenced: ${left(account.silenced).toLowerCase()}`), buttons);
|
||||
return row;
|
||||
}));
|
||||
$("no-bans").hidden = data.accounts.length > 0;
|
||||
$("addresses").replaceChildren(...data.addresses.map(ban => {
|
||||
const row = el("tr");
|
||||
const buttons = el("td");
|
||||
buttons.append(button("Unban", async () => {
|
||||
const result = await api("address", {id: ban.id});
|
||||
setStatus($("ban-status"), said(result), !result.ok);
|
||||
refresh();
|
||||
}));
|
||||
row.append(el("td", ban.address), el("td", ban.reason), el("td", ban.by || "—"), el("td", when(ban.createdAt)), buttons);
|
||||
return row;
|
||||
}));
|
||||
$("no-addresses").hidden = data.addresses.length > 0;
|
||||
};
|
||||
|
||||
const refresh = async () => {
|
||||
clearTimeout(timer);
|
||||
if (!signedIn) {
|
||||
return;
|
||||
}
|
||||
const shown = tab;
|
||||
const counts = await api("overview");
|
||||
if (counts.ok) {
|
||||
$("report-count").textContent = counts.data.reports ? ` (${counts.data.reports})` : "";
|
||||
$("request-count").textContent = counts.data.requests ? ` (${counts.data.requests})` : "";
|
||||
$("masterpiece-count").textContent = counts.data.paintings ? ` (${counts.data.paintings})` : "";
|
||||
$("online-count").textContent = `${counts.data.online} playing`;
|
||||
}
|
||||
if (shown === "players") {
|
||||
const result = await api(`players?q=${encodeURIComponent($("player-search").value.trim())}`);
|
||||
if (result.ok) {
|
||||
players = result.data.players;
|
||||
renderPlayers();
|
||||
await loadDetail();
|
||||
}
|
||||
}
|
||||
else if (shown === "chat") {
|
||||
// only the first page keeps itself up to date: older pages stay as they were read.
|
||||
if (!chatQuery || chatLines.length <= 100) {
|
||||
await loadChat(false);
|
||||
}
|
||||
}
|
||||
else if (shown === "reports") {
|
||||
const result = await api(`reports?handled=${$("report-filter").value}`);
|
||||
if (result.ok) {
|
||||
renderReports(result.data);
|
||||
}
|
||||
}
|
||||
else if (shown === "requests") {
|
||||
const result = await api(`requests?handled=${$("request-filter").value}`);
|
||||
if (result.ok) {
|
||||
renderRequests(result.data);
|
||||
}
|
||||
}
|
||||
else if (shown === "masterpieces") {
|
||||
const result = await api("masterpieces");
|
||||
if (result.ok) {
|
||||
renderMasterpieces(result.data);
|
||||
}
|
||||
}
|
||||
else if (shown === "bans") {
|
||||
const result = await api("bans");
|
||||
if (result.ok) {
|
||||
renderBans(result.data);
|
||||
}
|
||||
}
|
||||
if (signedIn) {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(refresh, REFRESH_MS);
|
||||
}
|
||||
};
|
||||
|
||||
const showTab = name => {
|
||||
tab = name;
|
||||
for (const one of document.querySelectorAll("nav button")) {
|
||||
one.setAttribute("aria-selected", String(one.dataset.tab === name));
|
||||
}
|
||||
for (const view of document.querySelectorAll("[data-view]")) {
|
||||
view.hidden = view.dataset.view !== name;
|
||||
}
|
||||
refresh();
|
||||
};
|
||||
for (const one of document.querySelectorAll("nav button")) {
|
||||
one.addEventListener("click", () => showTab(one.dataset.tab));
|
||||
}
|
||||
|
||||
const showPanel = username => {
|
||||
signedIn = true;
|
||||
$("who").textContent = username;
|
||||
$("gate").hidden = true;
|
||||
$("panel").hidden = false;
|
||||
showTab(tab);
|
||||
};
|
||||
|
||||
$("gate-form").addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
$("gate-button").disabled = true;
|
||||
const answer = await check.answer();
|
||||
if (answer === "") {
|
||||
$("gate-button").disabled = false;
|
||||
setStatus($("gate-status"), window.captcha.FAILED, true);
|
||||
return;
|
||||
}
|
||||
const result = await api("login", {username: $("username").value, password: $("password").value, code: $("code").value.trim(), captcha: answer});
|
||||
check.reset();
|
||||
$("gate-button").disabled = false;
|
||||
if (result.ok) {
|
||||
showPanel(result.data.username);
|
||||
}
|
||||
else {
|
||||
setStatus($("gate-status"), said(result), true);
|
||||
$("code").value = "";
|
||||
}
|
||||
});
|
||||
|
||||
$("sign-out").addEventListener("click", async () => {
|
||||
await api("logout", {});
|
||||
showGate("");
|
||||
});
|
||||
|
||||
const start = async () => {
|
||||
const result = await api("state");
|
||||
if (result.ok && result.data.signedIn) {
|
||||
showPanel(result.data.username);
|
||||
}
|
||||
else {
|
||||
showGate(result.status === 0 ? result.data.error : "");
|
||||
}
|
||||
};
|
||||
|
||||
start();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,257 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Privacy Policy · Burrow</title>
|
||||
<link rel="icon" type="image/png" href="/logo-square.png">
|
||||
<style>
|
||||
/* black and white throughout, in the game's own text font: the look of
|
||||
the client (its app/index.html). Nothing is said by colour: what
|
||||
went wrong is white with a "!" before it, and what cannot be undone
|
||||
has a dashed edge. */
|
||||
@font-face { font-family: "DigitalDelivery"; font-weight: 400; src: url("/fonts/CCDigitalDelivery-Regular.otf") format("opentype"); }
|
||||
@font-face { font-family: "DigitalDelivery"; font-weight: 700; src: url("/fonts/CCDigitalDelivery-Bold.otf") format("opentype"); }
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #000;
|
||||
--panel: #0d0d0d;
|
||||
--raised: #1a1a1a;
|
||||
--line: #2e2e2e;
|
||||
--text: #fff;
|
||||
--muted: #8c8c8c;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
::selection { background: #fff; color: #000; }
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: var(--line); border-radius: 5px; border: 3px solid var(--bg); }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 32px 16px 48px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 15px/1.4 "DigitalDelivery", system-ui, "Segoe UI", sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
a { color: inherit; text-underline-offset: 3px; }
|
||||
h1 { margin: 0; font-size: 26px; font-weight: 700; letter-spacing: 0.01em; }
|
||||
h2 { margin: 0 0 6px; font-size: 17px; font-weight: 700; }
|
||||
h3 { font-size: 14px; font-weight: 700; }
|
||||
p { margin: 0 0 12px; color: var(--muted); }
|
||||
label { display: block; margin: 12px 0 5px; color: var(--muted); font-size: 13px; }
|
||||
.hint { font-weight: 400; color: var(--muted); font-size: 12px; }
|
||||
input, select, textarea {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
padding: 9px 14px 10px;
|
||||
transition: border-color 0.12s;
|
||||
}
|
||||
input::placeholder, textarea::placeholder { color: #555; }
|
||||
input:hover, select:hover, textarea:hover { border-color: #555; }
|
||||
input:focus, select:focus, textarea:focus { outline: none; border-color: var(--text); }
|
||||
input:disabled, select:disabled, textarea:disabled { opacity: 0.4; }
|
||||
select:not([multiple]) {
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
padding-right: 34px;
|
||||
background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%), linear-gradient(135deg, var(--muted) 50%, transparent 50%);
|
||||
background-position: calc(100% - 19px) 55%, calc(100% - 14px) 55%;
|
||||
background-size: 5px 5px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
input[type="checkbox"] {
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
flex: none;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
margin: 0 6px 0 0;
|
||||
padding: 0;
|
||||
vertical-align: -4px;
|
||||
border: 1px solid #666;
|
||||
border-radius: 6px;
|
||||
background: var(--panel);
|
||||
cursor: pointer;
|
||||
}
|
||||
input[type="checkbox"]:hover { border-color: var(--text); }
|
||||
input[type="checkbox"]:checked {
|
||||
border-color: var(--text);
|
||||
background: var(--text) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'%3E%3Cpath d='M4.5 9.5l3 3 6-7' fill='none' stroke='%23000' stroke-width='2.2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / 16px no-repeat;
|
||||
}
|
||||
button {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: none;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
padding: 7px 16px 8px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition: background 0.12s, border-color 0.12s, color 0.12s;
|
||||
}
|
||||
button:hover { background: var(--raised); border-color: #555; }
|
||||
button:disabled { opacity: 0.45; cursor: default; }
|
||||
button:focus-visible, a:focus-visible, input[type="checkbox"]:focus-visible { outline: 2px solid var(--text); outline-offset: 2px; }
|
||||
button.primary { font-weight: 700; color: #000; background: var(--text); border-color: var(--text); }
|
||||
button.primary:hover { background: #d9d9d9; border-color: #d9d9d9; }
|
||||
button.primary:disabled, button.primary:disabled:hover { background: #3a3a3a; border-color: #3a3a3a; color: #000; }
|
||||
button.danger { border-style: dashed; border-color: #666; }
|
||||
button.danger:hover { border-style: solid; border-color: var(--text); }
|
||||
.status, #status { min-height: 20px; margin: 10px 0 0; font-size: 13px; color: var(--muted); }
|
||||
.status.bad, #status.bad { color: var(--text); }
|
||||
.status.bad::before, #status.bad::before, .notice::before {
|
||||
content: "!";
|
||||
display: inline-block;
|
||||
width: 17px;
|
||||
height: 17px;
|
||||
margin-right: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--text);
|
||||
color: #000;
|
||||
font-weight: 700;
|
||||
line-height: 17px;
|
||||
text-align: center;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
|
||||
.wrap { max-width: 820px; margin: 0 auto; }
|
||||
header { display: flex; align-items: center; gap: 12px; margin-bottom: 8px; }
|
||||
header h1 { flex: 1; }
|
||||
section { padding: 20px; margin-bottom: 16px; background: var(--panel); border: 1px solid var(--line); border-radius: 18px; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
td { padding: 8px 8px 8px 0; border-top: 1px solid var(--line); vertical-align: top; color: var(--muted); }
|
||||
tr:first-child td { border-top: 0; }
|
||||
td:first-child { width: 42%; }
|
||||
/* what to type keeps a fixed-width face, as it is typed letter by letter. */
|
||||
code { font: 13px/1.5 ui-monospace, Consolas, monospace; color: var(--text); background: var(--raised); border: 1px solid var(--line); border-radius: 8px; padding: 1px 7px; white-space: nowrap; }
|
||||
@media (max-width: 560px) { td, td:first-child { display: block; width: auto; padding: 4px 0; border-top: 0; } tr td:first-child { border-top: 1px solid var(--line); padding-top: 10px; } tr:first-child td:first-child { border-top: 0; } code { white-space: normal; } }
|
||||
.logo { display: block; height: 72px; margin: 0 0 12px; }
|
||||
.mark { height: 34px; flex: none; }
|
||||
.wrap { max-width: 720px; margin: 0 auto; }
|
||||
header { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }
|
||||
header h1 { flex: 1; }
|
||||
.mark { height: 34px; flex: none; }
|
||||
.notice { padding: 12px 16px; margin-bottom: 16px; border: 1px solid var(--text); border-radius: 18px; color: var(--text); }
|
||||
section { padding: 20px; margin-bottom: 16px; background: var(--panel); border: 1px solid var(--line); border-radius: 18px; }
|
||||
section p, section li { color: #cfcfcf; }
|
||||
section p:last-child, section ul:last-child { margin-bottom: 0; }
|
||||
ul { margin: 0 0 12px; padding-left: 20px; }
|
||||
li { margin: 4px 0; }
|
||||
table { width: 100%; border-collapse: collapse; font-size: 14px; }
|
||||
th, td { text-align: left; vertical-align: top; padding: 7px 8px; border-top: 1px solid var(--line); color: #cfcfcf; }
|
||||
th { border-top: 0; color: var(--muted); font-weight: 400; font-size: 11px; letter-spacing: 0.1em; text-transform: uppercase; }
|
||||
.scroll { overflow-x: auto; }
|
||||
.updated { color: var(--muted); font-size: 13px; margin: 0 0 16px; }
|
||||
footer { text-align: center; font-size: 13px; color: var(--muted); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<header>
|
||||
<img class="mark" src="/logo.png" alt="">
|
||||
<h1>Privacy Policy</h1>
|
||||
<a href="/terms">Terms of Service</a>
|
||||
</header>
|
||||
<div class="notice">Burrow is an unofficial fan project. It is not affiliated with, endorsed by or connected to WildWorks, Inc. or Animal Jam. Animal Jam and Animal Jam Classic are trademarks of WildWorks, Inc.</div>
|
||||
<p class="updated">Version {{version}}. This policy covers the Burrow server at {{site}}, its website and its client.</p>
|
||||
|
||||
<section>
|
||||
<h2>1. Who is responsible</h2>
|
||||
<p>The controller of your personal data is the operator of Burrow, {{operator}}. Contact for anything in this policy: {{legalEmail}}. General contact: {{adminEmail}}.</p>
|
||||
<p>We do not sell data, show ads, track you across sites or send marketing. We do not collect your real name, email address or date of birth. The only statistics we see are the overall traffic figures described in section 4.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>2. What we collect and why</h2>
|
||||
<div class="scroll"><table>
|
||||
<thead><tr><th>Data</th><th>Why</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>Username, password (stored only as a salted hash), and the date and version of the terms you accepted</td><td>To give you an account</td></tr>
|
||||
<tr><td>Your game data: animals, items, dens, pets, buddies, block list, trades, achievements, settings</td><td>To run the game for you</td></tr>
|
||||
<tr><td>What you choose to write or make: bio, Discord username (optional), Jam-A-Grams, wall posts, paintings, feedback</td><td>To show or deliver it as you asked</td></tr>
|
||||
<tr><td>Typed chat and whispers, with the room and time</td><td>Moderation: reviewing reports and deciding on bans</td></tr>
|
||||
<tr><td>IP address at each sign-in, and sign-in times</td><td>Security: your sign-in history, limiting abuse, address bans</td></tr>
|
||||
<tr><td>Reports, bans and their reasons, appeals, username rejections</td><td>Moderation and preventing ban evasion</td></tr>
|
||||
<tr><td>2FA secret and trusted-device tokens, if you turn 2FA on</td><td>To protect your account</td></tr>
|
||||
<tr><td>Technical error reports sent by the game client</td><td>Fixing bugs</td></tr>
|
||||
</tbody>
|
||||
</table></div>
|
||||
<p style="margin-top:12px">Creating an account requires the first row only. Everything else comes from playing.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>3. Who can see it</h2>
|
||||
<ul>
|
||||
<li><b>Other players</b> see your username, animals, den, bio, Discord username if you add one, badges, when you joined and were last seen, your chat in the room you are in, and whether you are currently banned.</li>
|
||||
<li><b>Moderators</b> can also read stored chat and whispers, reports, and ban history. They cannot see your IP address, sign-in history, password or inventory.</li>
|
||||
<li><b>The administrator</b> can see everything listed in section 2.</li>
|
||||
<li><b>Our hosting provider</b> stores the data on our behalf, in {{hostedIn}}. If that is outside your country, your data is transferred there to provide the service.</li>
|
||||
<li><b>Cloudflare</b> carries part of the traffic to this server. See section 4.</li>
|
||||
</ul>
|
||||
<p>We share data with nobody else, unless the law requires it. WildWorks receives nothing from us about you.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>4. Cloudflare</h2>
|
||||
<p>Parts of Burrow are reached through Cloudflare, Inc., which protects the server from attacks and delivers pages faster. When your connection passes through Cloudflare, it processes your IP address and technical details of the request (such as browser type, the page requested and the time), and may set a cookie that is needed for security. Cloudflare operates worldwide, so this can happen outside your country, including in the United States.</p>
|
||||
<p>When you sign in or create an account, a Cloudflare captcha (Turnstile) checks that you are a person. It looks at your IP address and at signals from your browser and device, and only tells us whether the check passed.</p>
|
||||
<p>Cloudflare gives us overall traffic statistics, such as the number of requests and visitors and the countries they come from. These do not identify you and we do not combine them with your account.</p>
|
||||
<p>Cloudflare handles this data under its own policy: <a href="https://www.cloudflare.com/privacypolicy/" target="_blank" rel="noopener noreferrer">cloudflare.com/privacypolicy</a>.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>5. How long we keep it</h2>
|
||||
<div class="scroll"><table>
|
||||
<thead><tr><th>Data</th><th>Kept</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>Account and game data</td><td>Until you delete your account</td></tr>
|
||||
<tr><td>Chat and whispers</td><td>30 days</td></tr>
|
||||
<tr><td>Sign-in history with IP addresses</td><td>Your last 40 sign-ins, and none older than 90 days</td></tr>
|
||||
<tr><td>Error reports and server logs</td><td>Up to 30 days</td></tr>
|
||||
<tr><td>Handled reports, feedback and username requests</td><td>12 months</td></tr>
|
||||
<tr><td>Ban records</td><td>While the account exists, then 12 months</td></tr>
|
||||
<tr><td>Banned IP addresses</td><td>Until the ban is lifted</td></tr>
|
||||
<tr><td>Backups</td><td>14 days</td></tr>
|
||||
</tbody>
|
||||
</table></div>
|
||||
<p style="margin-top:12px">When you delete your account we delete your game data, chat, appeal, feedback, username requests and paintings straight away. Your username is held for 30 days so nobody can pass as you, and ban records are kept as shown above. Copies in backups disappear within 14 days.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>6. Your rights</h2>
|
||||
<p>Wherever you live, you can use these on <a href="/account">your account page</a>:</p>
|
||||
<ul>
|
||||
<li><b>Access and portability:</b> "Download your data" gives you a file with everything we hold about your account.</li>
|
||||
<li><b>Correction:</b> change your password, bio, Discord username and settings, or request a new username.</li>
|
||||
<li><b>Deletion:</b> "Delete account" removes your account for good. This also works while you are banned.</li>
|
||||
</ul>
|
||||
<p>You can also ask us to restrict or stop a use of your data, or ask any question, by writing to {{legalEmail}}. We answer within one month.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>7. Children</h2>
|
||||
<p>Burrow is for people aged 13 and over, or the higher age at which the law of your country lets you agree to the use of your data on your own (up to 16 in parts of Europe). We do not knowingly collect data from anyone younger and we do not offer parental consent. If we learn that an account belongs to someone under that age we delete it. Parents and guardians can ask for this at {{legalEmail}}.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>8. Cookies and your device</h2>
|
||||
<p>The website sets only cookies that are needed to keep you signed in: a session cookie on your account page (12 hours) and, if you choose "Trust this device", a 2FA cookie (30 days). The client keeps your saved sign-in on your own computer if you tick "Remember me". Cloudflare may add a security cookie of its own (section 4). There are no advertising or tracking cookies.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>9. Security</h2>
|
||||
<p>Passwords are stored only as salted hashes, sign-in tokens as hashes, and connections are encrypted when the server address begins with https. No system is perfectly secure. If a breach puts your data at risk we will tell you in the game and on this site.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>10. Changes</h2>
|
||||
<p>If this policy changes, the version at the top changes with it, and significant changes are announced in the game or on this site before they apply.</p>
|
||||
</section>
|
||||
|
||||
<footer><a href="/terms">Terms</a> · <a href="/privacy">Privacy</a> · <a href="/register">Create account</a> · <a href="/account">Your account</a></footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,358 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Create an account</title>
|
||||
<link rel="icon" type="image/png" href="/logo-square.png">
|
||||
<style>
|
||||
/* black and white throughout, in the game's own text font: the look of
|
||||
the client (its app/index.html). Nothing is said by colour: what
|
||||
went wrong is white with a "!" before it, and what cannot be undone
|
||||
has a dashed edge. */
|
||||
@font-face { font-family: "DigitalDelivery"; font-weight: 400; src: url("/fonts/CCDigitalDelivery-Regular.otf") format("opentype"); }
|
||||
@font-face { font-family: "DigitalDelivery"; font-weight: 700; src: url("/fonts/CCDigitalDelivery-Bold.otf") format("opentype"); }
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #000;
|
||||
--panel: #0d0d0d;
|
||||
--raised: #1a1a1a;
|
||||
--line: #2e2e2e;
|
||||
--text: #fff;
|
||||
--muted: #8c8c8c;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
::selection { background: #fff; color: #000; }
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: var(--line); border-radius: 5px; border: 3px solid var(--bg); }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 40px 16px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 15px/1.4 "DigitalDelivery", system-ui, "Segoe UI", sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
a { color: inherit; text-underline-offset: 3px; }
|
||||
h1 { margin: 0; font-size: 26px; font-weight: 700; letter-spacing: 0.01em; }
|
||||
h2 { margin: 0 0 6px; font-size: 17px; font-weight: 700; }
|
||||
h3 { font-size: 14px; font-weight: 700; }
|
||||
p { margin: 0 0 12px; color: var(--muted); }
|
||||
label { display: block; margin: 12px 0 5px; color: var(--muted); font-size: 13px; }
|
||||
.hint { font-weight: 400; color: var(--muted); font-size: 12px; }
|
||||
input, select, textarea {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
padding: 9px 14px 10px;
|
||||
transition: border-color 0.12s;
|
||||
}
|
||||
input::placeholder, textarea::placeholder { color: #555; }
|
||||
input:hover, select:hover, textarea:hover { border-color: #555; }
|
||||
input:focus, select:focus, textarea:focus { outline: none; border-color: var(--text); }
|
||||
input:disabled, select:disabled, textarea:disabled { opacity: 0.4; }
|
||||
select:not([multiple]) {
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
padding-right: 34px;
|
||||
background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%), linear-gradient(135deg, var(--muted) 50%, transparent 50%);
|
||||
background-position: calc(100% - 19px) 55%, calc(100% - 14px) 55%;
|
||||
background-size: 5px 5px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
input[type="checkbox"] {
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
flex: none;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
margin: 0 6px 0 0;
|
||||
padding: 0;
|
||||
vertical-align: -4px;
|
||||
border: 1px solid #666;
|
||||
border-radius: 6px;
|
||||
background: var(--panel);
|
||||
cursor: pointer;
|
||||
}
|
||||
input[type="checkbox"]:hover { border-color: var(--text); }
|
||||
input[type="checkbox"]:checked {
|
||||
border-color: var(--text);
|
||||
background: var(--text) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'%3E%3Cpath d='M4.5 9.5l3 3 6-7' fill='none' stroke='%23000' stroke-width='2.2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / 16px no-repeat;
|
||||
}
|
||||
button {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: none;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
padding: 7px 16px 8px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition: background 0.12s, border-color 0.12s, color 0.12s;
|
||||
}
|
||||
button:hover { background: var(--raised); border-color: #555; }
|
||||
button:disabled { opacity: 0.45; cursor: default; }
|
||||
button:focus-visible, a:focus-visible, input[type="checkbox"]:focus-visible { outline: 2px solid var(--text); outline-offset: 2px; }
|
||||
button.primary { font-weight: 700; color: #000; background: var(--text); border-color: var(--text); }
|
||||
button.primary:hover { background: #d9d9d9; border-color: #d9d9d9; }
|
||||
button.primary:disabled, button.primary:disabled:hover { background: #3a3a3a; border-color: #3a3a3a; color: #000; }
|
||||
button.danger { border-style: dashed; border-color: #666; }
|
||||
button.danger:hover { border-style: solid; border-color: var(--text); }
|
||||
.status, #status { min-height: 20px; margin: 10px 0 0; font-size: 13px; color: var(--muted); }
|
||||
.status.bad, #status.bad { color: var(--text); }
|
||||
.status.bad::before, #status.bad::before, .notice::before {
|
||||
content: "!";
|
||||
display: inline-block;
|
||||
width: 17px;
|
||||
height: 17px;
|
||||
margin-right: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--text);
|
||||
color: #000;
|
||||
font-weight: 700;
|
||||
line-height: 17px;
|
||||
text-align: center;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
|
||||
main {
|
||||
max-width: 720px;
|
||||
margin: 0 auto;
|
||||
padding: 24px;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 18px;
|
||||
}
|
||||
main.narrow { max-width: 380px; }
|
||||
h1 { margin: 0 0 16px; }
|
||||
p { margin: 0 0 18px; }
|
||||
.steps { font-size: 11px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--muted); margin: 0 0 6px; }
|
||||
.chooser { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 20px; align-items: stretch; }
|
||||
@media (max-width: 600px) { .chooser { grid-template-columns: 1fr; } }
|
||||
.animals { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; align-content: start; }
|
||||
.animal { white-space: normal; padding: 8px 4px 8px; margin: 0; width: auto; border-radius: 18px; font-size: 13px; color: var(--muted); }
|
||||
.animal img { display: block; width: 100%; aspect-ratio: 1; border-radius: 12px; filter: grayscale(1); opacity: 0.6; transition: filter 0.15s, opacity 0.15s; }
|
||||
.animal span { display: block; margin-top: 4px; }
|
||||
.animal:hover img, .animal[aria-checked="true"] img { filter: none; opacity: 1; }
|
||||
.animal[aria-checked="true"] { border-color: var(--text); box-shadow: inset 0 0 0 1px var(--text); color: var(--text); background: var(--bg); }
|
||||
.stage {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 300px;
|
||||
padding: 16px;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 18px;
|
||||
text-align: center;
|
||||
}
|
||||
.stage img { width: 100%; max-width: 300px; max-height: 300px; }
|
||||
.stage .name { font-size: 20px; font-weight: 700; margin-top: 6px; }
|
||||
.stage .empty { color: var(--muted); }
|
||||
.picked { display: flex; align-items: center; gap: 12px; padding: 10px 12px; margin-bottom: 6px; border: 1px solid var(--line); border-radius: 18px; }
|
||||
.picked img { width: 56px; height: 56px; border-radius: 10px; }
|
||||
.picked div { flex: 1; font-weight: 700; }
|
||||
label { margin: 14px 0 5px; }
|
||||
input { width: 100%; background: var(--bg); }
|
||||
button.primary { width: 100%; margin-top: 20px; padding: 10px 16px 11px; font-size: 16px; }
|
||||
button.plain { width: auto; margin: 0; padding: 4px 14px 5px; font-size: 13px; }
|
||||
#status { margin: 14px 0 0; text-align: center; }
|
||||
label.agree { display: flex; align-items: flex-start; gap: 10px; margin-top: 18px; color: var(--text); font-size: 13px; cursor: pointer; }
|
||||
label.agree input { width: 18px; margin: 1px 0 0; }
|
||||
footer { max-width: 720px; margin: 14px auto 0; text-align: center; font-size: 13px; color: var(--muted); }
|
||||
.logo { display: block; height: 72px; margin: 0 0 12px; }
|
||||
.mark { height: 34px; flex: none; }
|
||||
.captcha { display: flex; justify-content: center; margin-top: 16px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main id="card">
|
||||
<img class="logo" src="/logo.png" alt="">
|
||||
<div id="step-animal">
|
||||
<div class="steps">Step 1 of 2</div>
|
||||
<h1>Choose an animal</h1>
|
||||
<div class="chooser">
|
||||
<div class="animals" id="animals" role="radiogroup" aria-label="Your first animal"></div>
|
||||
<div class="stage" aria-live="polite">
|
||||
<div class="empty" id="stage-empty"></div>
|
||||
<img id="stage-art" alt="" hidden>
|
||||
<div class="name" id="stage-name" hidden></div>
|
||||
</div>
|
||||
</div>
|
||||
<button class="primary" id="next" type="button" disabled>Next</button>
|
||||
</div>
|
||||
|
||||
<div id="step-account" hidden>
|
||||
<div class="steps">Step 2 of 2</div>
|
||||
<h1>Create your account</h1>
|
||||
<div class="picked">
|
||||
<img id="picked-art" alt="">
|
||||
<div id="picked-name"></div>
|
||||
<button class="plain" id="back" type="button">Change</button>
|
||||
</div>
|
||||
<form id="form">
|
||||
<label for="username">Username <span class="hint">3 to 20 letters, digits or spaces</span></label>
|
||||
<input id="username" name="username" autocomplete="username" maxlength="20" required>
|
||||
<label for="password">Password <span class="hint">10 or more, with A-Z, a-z and 0-9</span></label>
|
||||
<input id="password" name="password" type="password" autocomplete="new-password" minlength="10" maxlength="100" required>
|
||||
<label for="confirm">Password again</label>
|
||||
<input id="confirm" name="confirm" type="password" autocomplete="new-password" required>
|
||||
<label class="agree"><input id="agreed" name="agreed" type="checkbox" required>
|
||||
<span>I am 13 or older, and old enough in my country to agree to this myself. I agree to the <a href="/terms" target="_blank" rel="noopener">Terms of Service</a> and the <a href="/privacy" target="_blank" rel="noopener">Privacy Policy</a>.</span></label>
|
||||
<div class="captcha" id="captcha"></div>
|
||||
<button class="primary" id="submit" type="submit">Create account</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div id="step-done" hidden>
|
||||
<h1>Welcome, <span id="done-name"></span></h1>
|
||||
<p><a href="/account">Your account</a></p>
|
||||
</div>
|
||||
|
||||
<div id="status" role="status"></div>
|
||||
</main>
|
||||
<footer>Already have an account? <a href="/account">Manage it</a></footer>
|
||||
<footer>Burrow is an unofficial fan project, not affiliated with WildWorks or Animal Jam. <a href="/terms">Terms</a> · <a href="/privacy">Privacy</a></footer>
|
||||
|
||||
<script src="/captcha.js"></script>
|
||||
<script>
|
||||
"use strict";
|
||||
|
||||
// the animals the server lets a new account start as (lib/admin.js),
|
||||
// in the order the official sign-up page shows them.
|
||||
const ANIMALS = [
|
||||
[4, "wolf", "Wolf"], [13, "rhino", "Rhino"], [8, "bunny", "Bunny"],
|
||||
[1, "tiger", "Tiger"], [18, "seal", "Seal"], [5, "koala", "Koala"],
|
||||
[6, "panda", "Panda"], [24, "penguin", "Penguin"], [7, "monkey", "Monkey"],
|
||||
];
|
||||
|
||||
const MESSAGES = {
|
||||
invalid_username: "Usernames are 3 to 20 letters, digits, spaces, dots or dashes, with at least three letters.",
|
||||
username_taken: "That username is already taken.",
|
||||
name_not_allowed: "That username is not allowed.",
|
||||
invalid_password: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit.",
|
||||
choose_animal: "Choose an animal first.",
|
||||
too_many_registrations: "Too many accounts were created from your address. Try again in an hour.",
|
||||
address_banned: "Your address is banned.",
|
||||
agree_first: "Tick the box to agree first.",
|
||||
captcha_required: "Complete the captcha.",
|
||||
captcha_failed: "Captcha failed. Try again.",
|
||||
captcha_unavailable: "Captcha unavailable. Try again later.",
|
||||
};
|
||||
|
||||
const $ = id => document.getElementById(id);
|
||||
const form = $("form");
|
||||
const check = window.captcha.mount($("captcha"), "signup");
|
||||
let chosen = null; // [id, file name, name]
|
||||
|
||||
const setStatus = (text, bad) => {
|
||||
$("status").textContent = text;
|
||||
$("status").classList.toggle("bad", bad);
|
||||
};
|
||||
|
||||
const showStep = name => {
|
||||
for (const step of ["animal", "account", "done"]) {
|
||||
$(`step-${step}`).hidden = step !== name;
|
||||
}
|
||||
$("card").classList.toggle("narrow", name !== "animal");
|
||||
setStatus("", false);
|
||||
};
|
||||
|
||||
const choose = animal => {
|
||||
chosen = animal;
|
||||
for (const button of $("animals").children) {
|
||||
const picked = button.dataset.id === String(animal[0]);
|
||||
button.setAttribute("aria-checked", String(picked));
|
||||
button.tabIndex = picked ? 0 : -1;
|
||||
}
|
||||
$("stage-empty").hidden = true;
|
||||
$("stage-art").src = `/signup/hero_${animal[1]}.svg`;
|
||||
$("stage-art").alt = animal[2];
|
||||
$("stage-art").hidden = false;
|
||||
$("stage-name").textContent = animal[2];
|
||||
$("stage-name").hidden = false;
|
||||
$("next").disabled = false;
|
||||
};
|
||||
|
||||
ANIMALS.forEach((animal, index) => {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "animal";
|
||||
button.dataset.id = animal[0];
|
||||
button.setAttribute("role", "radio");
|
||||
button.setAttribute("aria-checked", "false");
|
||||
button.tabIndex = index === 0 ? 0 : -1;
|
||||
const picture = document.createElement("img");
|
||||
picture.src = `/signup/thumb_${animal[1]}.svg`;
|
||||
picture.alt = "";
|
||||
const name = document.createElement("span");
|
||||
name.textContent = animal[2];
|
||||
button.append(picture, name);
|
||||
button.addEventListener("click", () => choose(animal));
|
||||
$("animals").append(button);
|
||||
});
|
||||
|
||||
$("animals").addEventListener("keydown", event => {
|
||||
const step = {ArrowRight: 1, ArrowDown: 3, ArrowLeft: -1, ArrowUp: -3}[event.key];
|
||||
const buttons = [...$("animals").children];
|
||||
const at = buttons.indexOf(document.activeElement);
|
||||
if (step === undefined || at === -1) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
const to = (at + step + buttons.length) % buttons.length;
|
||||
buttons[to].focus();
|
||||
choose(ANIMALS[to]);
|
||||
});
|
||||
|
||||
$("next").addEventListener("click", () => {
|
||||
$("picked-art").src = `/signup/thumb_${chosen[1]}.svg`;
|
||||
$("picked-name").textContent = `Starting as a ${chosen[2].toLowerCase()}`;
|
||||
showStep("account");
|
||||
form.username.focus();
|
||||
});
|
||||
|
||||
$("back").addEventListener("click", () => showStep("animal"));
|
||||
|
||||
form.addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
if (form.password.value !== form.confirm.value) {
|
||||
setStatus("The two passwords do not match.", true);
|
||||
return;
|
||||
}
|
||||
$("submit").disabled = true;
|
||||
try {
|
||||
const answer = await check.answer();
|
||||
if (answer === "") {
|
||||
setStatus(window.captcha.FAILED, true);
|
||||
$("submit").disabled = false;
|
||||
return;
|
||||
}
|
||||
const response = await fetch("/api/register", {
|
||||
method: "POST",
|
||||
headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify({username: form.username.value, password: form.password.value, avatarType: chosen[0], agreed: form.agreed.checked,
|
||||
captcha: answer}),
|
||||
});
|
||||
check.reset();
|
||||
const body = await response.json();
|
||||
if (response.ok) {
|
||||
$("done-name").textContent = body.username;
|
||||
form.reset();
|
||||
showStep("done");
|
||||
}
|
||||
else {
|
||||
setStatus(MESSAGES[body.error] || "Could not create the account.", true);
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
setStatus("The server did not answer.", true);
|
||||
}
|
||||
$("submit").disabled = false;
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||