mirror of
https://github.com/burrow-dev/burrow-server.git
synced 2026-11-19 17:37:50 -05:00
Compare commits
99
Commits
555360aa1b
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8e117ff26f | ||
|
|
29c0eff454 | ||
|
|
f72e346c03 | ||
|
|
4355994253 | ||
|
|
c7efda7030 | ||
|
|
7de41ceed5 | ||
|
|
15f321fb00 | ||
|
|
6c273554d7 | ||
|
|
22fb7f0fa5 | ||
|
|
e9097a9a4f | ||
|
|
7cfef493fa | ||
|
|
44af83f1c5 | ||
|
|
b22708a4ba | ||
|
|
494f252c5b | ||
|
|
6b707fbc1d | ||
|
|
b45fd195df | ||
|
|
e2454447d9 | ||
|
|
0da5daabc9 | ||
|
|
3b53c8dab8 | ||
|
|
83c2fc3b0b | ||
|
|
c1a85f9b5d | ||
|
|
d44612bd08 | ||
|
|
9156c6e392 | ||
|
|
3930d2dabe | ||
|
|
9985ae7625 | ||
|
|
3139384ef3 | ||
|
|
e67fbe95e1 | ||
|
|
3423df10f8 | ||
|
|
8839f86e6c | ||
|
|
92ebb4d07c | ||
|
|
974f68490e | ||
|
|
43f2717b44 | ||
|
|
6645bf66b3 | ||
|
|
43ae95fbca | ||
|
|
34db374527 | ||
|
|
3256135df3 | ||
|
|
9efb2558fc | ||
|
|
9720d309fa | ||
|
|
64eab1f8ad | ||
|
|
a8ab031616 | ||
|
|
b11ae1dfa8 | ||
|
|
113bf9342e | ||
|
|
131fb8b025 | ||
|
|
8afc66de21 | ||
|
|
059f059a9e | ||
|
|
d20920dc3c | ||
|
|
8fb5cfe6d8 | ||
|
|
8368692b99 | ||
|
|
0f367c55b8 | ||
|
|
a860a67626 | ||
|
|
da9f2fd5a6 | ||
|
|
0c3bfd97b3 | ||
|
|
096ceafea7 | ||
|
|
2344270291 | ||
|
|
a77a1bcfb4 | ||
|
|
04b8d325ea | ||
|
|
c5b1bc37d9 | ||
|
|
9f69b3511b | ||
|
|
8e7b193621 | ||
|
|
08780d7e69 | ||
|
|
8babe9cb39 | ||
|
|
5c9b2e0066 | ||
|
|
7dee29010a | ||
|
|
94b8de801e | ||
|
|
95946c5b02 | ||
|
|
4997315239 | ||
|
|
1e365b95c5 | ||
|
|
a359371a48 | ||
|
|
33f56074a4 | ||
|
|
1d9b70f32e | ||
|
|
3770341514 | ||
|
|
422719dade | ||
|
|
bb532a78bb | ||
|
|
3c2053f434 | ||
|
|
b551a587a9 | ||
|
|
6db96325dd | ||
|
|
408b7d4864 | ||
|
|
783feb7788 | ||
|
|
ee06e8ca77 | ||
|
|
d8a9c1f881 | ||
|
|
59d9d7e5fa | ||
|
|
331c3e6025 | ||
|
|
e05565787f | ||
|
|
da7eb9af58 | ||
|
|
13c2f04d52 | ||
|
|
31cbd87ff8 | ||
|
|
b813d89cfa | ||
|
|
cf729d52dc | ||
|
|
0e86592d40 | ||
|
|
d09ee94e16 | ||
|
|
bcefbc2d8a | ||
|
|
3611e566be | ||
|
|
57abc8746d | ||
|
|
ceda20ffc8 | ||
|
|
f3983fcf67 | ||
|
|
627e6f9180 | ||
|
|
6563d5de99 | ||
|
|
2fba9f1612 | ||
|
|
63dc43ebb3 |
No files matched your search
@@ -2,10 +2,16 @@
|
|||||||
"server": [
|
"server": [
|
||||||
"ajcontent.akamaized.net",
|
"ajcontent.akamaized.net",
|
||||||
"burrow.moe",
|
"burrow.moe",
|
||||||
|
"cdn.jsdelivr.net",
|
||||||
"challenges.cloudflare.com",
|
"challenges.cloudflare.com",
|
||||||
|
"discord.com",
|
||||||
|
"duckduckgo.com",
|
||||||
"play.burrow.moe",
|
"play.burrow.moe",
|
||||||
|
"player.vimeo.com",
|
||||||
|
"vision.googleapis.com",
|
||||||
"www.cloudflare.com",
|
"www.cloudflare.com",
|
||||||
"www.w3.org"
|
"www.w3.org",
|
||||||
|
"www.youtube-nocookie.com"
|
||||||
],
|
],
|
||||||
"swf": [
|
"swf": [
|
||||||
"academy.animaljam.com",
|
"academy.animaljam.com",
|
||||||
|
|||||||
@@ -4,7 +4,8 @@
|
|||||||
// what the security audit of 2026-10-16 found true of this server, checked on
|
// what the security audit of 2026-10-16 found true of this server, checked on
|
||||||
// every push so that it stays true (or is changed on purpose):
|
// every push so that it stays true (or is changed on purpose):
|
||||||
//
|
//
|
||||||
// - it uses no npm packages, so there is no supply chain to break into
|
// - it has only the one pinned Discord gateway dependency needed by the
|
||||||
|
// optional staff bot; additions are refused to keep the supply chain small
|
||||||
// - the server code starts no other programs and runs no generated code
|
// - the server code starts no other programs and runs no generated code
|
||||||
// - the server code names no web address outside .github/allowed-hosts.json
|
// - the server code names no web address outside .github/allowed-hosts.json
|
||||||
// - no private key, certificate key or .env file is committed
|
// - no private key, certificate key or .env file is committed
|
||||||
@@ -22,17 +23,35 @@ const tracked = execFileSync("git", ["ls-files", "-z"], {encoding: "utf8"}).spli
|
|||||||
const problems = [];
|
const problems = [];
|
||||||
const fail = (file, message) => problems.push({file, message});
|
const fail = (file, message) => problems.push({file, message});
|
||||||
|
|
||||||
// no npm packages
|
// The server stayed dependency-free until the optional Discord staff bot. Its
|
||||||
|
// maintained gateway/components implementation is pinned exactly and captured
|
||||||
|
// in package-lock.json; no other package is permitted without deliberately
|
||||||
|
// extending this allowlist and its review surface.
|
||||||
const pkg = JSON.parse(fs.readFileSync("package.json", "utf8"));
|
const pkg = JSON.parse(fs.readFileSync("package.json", "utf8"));
|
||||||
|
const ALLOWED_DEPENDENCIES = {dependencies: {"discord.js": "14.26.4"}};
|
||||||
for (const field of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies", "bundledDependencies"]) {
|
for (const field of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies", "bundledDependencies"]) {
|
||||||
if (pkg[field] && Object.keys(pkg[field]).length) {
|
const actual = pkg[field] || {};
|
||||||
fail("package.json", `${field} is not empty. The server has no npm packages on purpose; if one is really needed, change this check in the same pull request and say why.`);
|
const allowedDependencies = ALLOWED_DEPENDENCIES[field] || {};
|
||||||
|
if (JSON.stringify(Object.keys(actual).sort().map(name => [name, actual[name]])) !== JSON.stringify(Object.keys(allowedDependencies).sort().map(name => [name, allowedDependencies[name]]))) {
|
||||||
|
fail("package.json", `${field} differs from its approved dependency allowlist. Keep dependencies empty except for the pinned Discord staff-bot gateway, or deliberately update this check and explain why.`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (const lock of ["package-lock.json", "yarn.lock", "pnpm-lock.yaml"]) {
|
for (const lock of ["yarn.lock", "pnpm-lock.yaml"]) {
|
||||||
if (tracked.includes(lock)) {
|
if (tracked.includes(lock)) fail(lock, "use the reviewed package-lock.json; alternate package-manager lockfiles are not allowed.");
|
||||||
fail(lock, "a lockfile means npm packages; see package.json above.");
|
}
|
||||||
|
if (fs.existsSync("package-lock.json")) {
|
||||||
|
try {
|
||||||
|
const lock = JSON.parse(fs.readFileSync("package-lock.json", "utf8"));
|
||||||
|
if (lock.lockfileVersion !== 3 || lock.packages?.[""]?.dependencies?.["discord.js"] !== "14.26.4") {
|
||||||
|
fail("package-lock.json", "must be the npm v3 lockfile for the pinned [email protected] dependency.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
catch {
|
||||||
|
fail("package-lock.json", "is not a readable npm lockfile.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
fail("package-lock.json", "is required to review the pinned Discord bot dependency.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// the server's own code: what the game server runs
|
// the server's own code: what the game server runs
|
||||||
@@ -88,4 +107,4 @@ if (problems.length) {
|
|||||||
}
|
}
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
console.log(`${serverCode.length} server files and ${tracked.length} tracked files checked: no packages, no program starts or generated code, no unlisted hosts, no keys, everything parses`);
|
console.log(`${serverCode.length} server files and ${tracked.length} tracked files checked: only the pinned Discord bot dependency, no program starts or generated code, no unlisted hosts, no keys, everything parses`);
|
||||||
@@ -20,6 +20,8 @@ __pycache__/
|
|||||||
|
|
||||||
# internal markdown files
|
# internal markdown files
|
||||||
*.md
|
*.md
|
||||||
|
!deploy/README.md
|
||||||
|
!/CONTRIBUTING.md
|
||||||
/HANDOFF.md
|
/HANDOFF.md
|
||||||
/DISCOVERIES.md
|
/DISCOVERIES.md
|
||||||
/GOING-PUBLIC.md
|
/GOING-PUBLIC.md
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# Contributing to Burrow
|
||||||
|
|
||||||
|
Thanks for helping make Burrow safer, kinder, and more reliable. Keep changes small, explain the player-facing effect, and open a pull request against the repository's default branch.
|
||||||
|
|
||||||
|
## Local setup
|
||||||
|
|
||||||
|
Use Node.js 22.5 or later, Git, and an existing checkout containing the tracked client and cached game assets. Install the reviewed runtime dependency with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm ci
|
||||||
|
```
|
||||||
|
|
||||||
|
Run the server with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm start
|
||||||
|
```
|
||||||
|
|
||||||
|
The local web server defaults to `http://127.0.0.1:8080` and the game server to port `9339`. Do not commit `data/`, `cache/`, `.env` files, tokens, recovery-mail credentials, Discord bot tokens, or production exports.
|
||||||
|
|
||||||
|
## Before opening a pull request
|
||||||
|
|
||||||
|
Run the smoke suite and repository invariants from the repository root:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm test
|
||||||
|
node .github/scripts/invariants.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Add focused coverage under `test/` when changing a game protocol, permissions, account state, moderation, or web route. Explain any test that cannot run locally and include the exact failure output.
|
||||||
|
|
||||||
|
Use Conventional Commit messages; the pull-request workflow checks them. Keep the change limited to its purpose and describe security implications, especially for authentication, staff permissions, moderation, player data, network input, or media.
|
||||||
|
|
||||||
|
## Security requirements
|
||||||
|
|
||||||
|
Burrow handles account credentials, 2FA, game sessions, player reports, and moderation records. Treat every browser, game, and Discord input as untrusted.
|
||||||
|
|
||||||
|
- Never log, display, or commit passwords, session tokens, recovery links, IP addresses, device identifiers, private keys, or bot tokens.
|
||||||
|
- Do not add web hosts, execute programs from server code, evaluate generated text, or add dependencies without updating and explaining the invariant checks.
|
||||||
|
- `[email protected]` is the only approved runtime dependency. Keep it exactly pinned and update `package-lock.json` in the same pull request when its reviewed version changes.
|
||||||
|
- Preserve permission checks and staff-rank protections. New moderation actions must use the existing role model and leave an audit record.
|
||||||
|
|
||||||
|
The CI security workflow parses all server JavaScript, checks allowed external hosts, scans commits for secrets, and reviews the Flash files that clients load.
|
||||||
|
|
||||||
|
## Discord bot changes
|
||||||
|
|
||||||
|
The optional Discord staff bot is enabled only with `AJ_DISCORD_BOT_TOKEN` and `AJ_DISCORD_GUILD_ID`. It trusts a Discord user only after the user has linked that identity to an active Burrow staff account with 2FA. Do not create an alternate Discord-only permission system.
|
||||||
|
|
||||||
|
All visible bot messages, including errors, status cards, reports, audit logs, and interaction updates, must use Discord Components V2: set `MessageFlags.IsComponentsV2` and use containers/text displays rather than `content` or embeds. Keep player-supplied text safe from mentions and avoid relaying chat, addresses, device data, or tokens to Discord.
|
||||||
|
|
||||||
|
GitHub update cards are produced only from signed push webhooks. Keep that route signature-verified before parsing or posting a payload, limit request size, and do not expose webhook secrets in commits, logs, cards, or pull requests.
|
||||||
|
|
||||||
|
## Server and panel changes
|
||||||
|
|
||||||
|
The server code lives in `lib/`; browser pages live in `public/`; protocol behavior is primarily in `lib/world.js` and the related feature modules. Reuse the panel's shared moderation action path instead of copying bans, warnings, silences, or rank checks into a new surface.
|
||||||
|
|
||||||
|
Document new environment variables in `README.md`. Make optional integrations fail closed or remain disabled when configuration is absent; they must never stop gameplay, moderation records, or account storage when an external service is unavailable.
|
||||||
|
|
||||||
|
## Client and asset changes
|
||||||
|
|
||||||
|
Changes under `swf-src/` require rebuilding the tracked client with Java and JPEXS/FFDec:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
tools/build-client.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
On Windows, run the script through Git Bash or an equivalent POSIX shell. Commit both the source change and the resulting `swf/ajclient.swf` when the client is changed. Do not edit files under `tools/decompiled/` unless the build tool explicitly consumes that source; they are reference output.
|
||||||
|
|
||||||
|
Badge artwork is generated by `tools/make-badges.py`; follow the script's usage notes and commit all generated badge assets together.
|
||||||
|
|
||||||
|
## Pull-request checklist
|
||||||
|
|
||||||
|
- [ ] The change has a clear player, staff, or maintenance outcome.
|
||||||
|
- [ ] Tests and invariants pass, or the exception is explained.
|
||||||
|
- [ ] No secret, personal data, cache, database, or generated local output is included.
|
||||||
|
- [ ] New Discord output uses Components V2 and respects the existing permission/audit model.
|
||||||
|
- [ ] Client source and rebuilt SWF are both included when applicable.
|
||||||
@@ -1,6 +1,20 @@
|
|||||||
# Burrow
|
# Burrow
|
||||||
Burrow is a private server for AJ Classic.
|
Burrow is a private server for AJ Classic.
|
||||||
|
|
||||||
|
## Account-recovery email
|
||||||
|
|
||||||
|
Set `AJ_RECOVERY_MAIL_URL` and `AJ_RECOVERY_MAIL_TOKEN` to an HTTPS mail-relay or transactional-email webhook. Burrow posts `{to, subject, text}` with a Bearer token. Until both are configured, email recovery intentionally does not issue a usable reset link. New web sign-ups are asked for a recovery email; password and 2FA recovery require the one-time link sent there.
|
||||||
|
|
||||||
|
## Discord staff bot
|
||||||
|
|
||||||
|
Set `AJ_DISCORD_BOT_TOKEN` and `AJ_DISCORD_GUILD_ID` to enable Burrow's Discord bot. It registers `/burrow status|player|reports|staff|announce`, `/moderate warn|silence|unsilence|kick|ban|unban`, and Discord-server moderation commands `/discord timeout|untimeout|kick|ban|unban|purge`. A Discord user must first link their account through Burrow's existing Discord sign-in and hold active Burrow staff status with 2FA; every command then follows the same role permissions, staff-rank safeguards, actions, and audit log as the moderator panel. Discord-native actions cannot target active linked Burrow staff accounts and also require the bot's Discord role to have the matching server permission.
|
||||||
|
|
||||||
|
`AJ_DISCORD_REPORTS_CHANNEL_ID` optionally posts each new in-game report with a **Mark handled** button. `AJ_DISCORD_STATUS_CHANNEL_ID` optionally maintains a public live-status card. Set `AJ_DISCORD_GAME_LOGS_CHANNEL_ID` for player sign-in/sign-out logs, `AJ_DISCORD_MOD_LOGS_CHANNEL_ID` for the full moderation audit trail (web panel, in-game staff commands, admin actions, and Discord moderation), and `AJ_DISCORD_BOT_LOGS_CHANNEL_ID` for Discord command/button audit events. Game logs deliberately omit IPs, device IDs, auth tokens, and chat text. All bot replies and notifications use Discord Components V2 (containers and text displays), not legacy message content or embeds.
|
||||||
|
|
||||||
|
The owner dashboard's **Discord** tab can start, stop, reconnect, and synchronize the bot; edit notification-channel IDs, the GitHub repository, public status card, security rules, support-ticket settings, and welcome/goodbye notices; and publish the public card immediately. Environment values supply the initial channel configuration. The bot token, guild ID, and GitHub webhook secret deliberately stay in the server environment rather than in the dashboard database.
|
||||||
|
|
||||||
|
For GitHub update cards, set `AJ_GITHUB_REPOSITORY` to `owner/repository`, `AJ_GITHUB_WEBHOOK_SECRET`, and `AJ_DISCORD_UPDATES_CHANNEL_ID`. Then add a GitHub webhook for `https://your-public-burrow-host/discord/github`, choose `application/json`, use the same secret, and subscribe to **Pushes**. Signed pushes appear as polished Components V2 cards with commit summaries and a GitHub compare button; commits that change the Flash client or client assets are labelled **Game update**, while other pushes are **Server update**.
|
||||||
|
|
||||||
# Security
|
# Security
|
||||||
An independent security audit by a Strawberry Jam contributor, who is not part of the Burrow team, found no malware in the Burrow client or server (client v1.2.0, server as of 17 October 2026). Every file in every installer was checked against its source and against the official Electron, NSIS and Adobe Flash releases. The report also lists the weaknesses found, with fixes, and every check can be repeated by anyone.
|
An independent security audit by a Strawberry Jam contributor, who is not part of the Burrow team, found no malware in the Burrow client or server (client v1.2.0, server as of 17 October 2026). Every file in every installer was checked against its source and against the official Electron, NSIS and Adobe Flash releases. The report also lists the weaknesses found, with fixes, and every check can be repeated by anyone.
|
||||||
|
|
||||||
@@ -12,3 +26,6 @@ Every push to this repository is checked automatically (`.github/workflows/secur
|
|||||||
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.
|
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.
|
||||||
|
|
||||||
**Takedown procedure: WildWorks, Inc. or its authorized representatives may request the removal of content, or of Burrow as a whole, by writing to [email protected]. Upon verification of authority, the request will be carried out promptly.**
|
**Takedown procedure: WildWorks, Inc. or its authorized representatives may request the removal of content, or of Burrow as a whole, by writing to [email protected]. Upon verification of authority, the request will be carried out promptly.**
|
||||||
|
|
||||||
|
# Credits
|
||||||
|
Emoji in chat are drawn with [Twemoji](https://github.com/jdecked/twemoji), © Twitter, Inc. and other contributors, under [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/).
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
const path = require("path");
|
const path = require("path");
|
||||||
|
|
||||||
const env = process.env;
|
const env = process.env;
|
||||||
|
const googleVisionApiKey = env.AJ_GOOGLE_VISION_API_KEY;
|
||||||
const LOOPBACK_NAMES = ["127.0.0.1", "::1", "localhost"];
|
const LOOPBACK_NAMES = ["127.0.0.1", "::1", "localhost"];
|
||||||
const bindAddress = env.AJ_BIND || "127.0.0.1";
|
const bindAddress = env.AJ_BIND || "127.0.0.1";
|
||||||
const httpPort = Number(env.AJ_HTTP_PORT || 8080);
|
const httpPort = Number(env.AJ_HTTP_PORT || 8080);
|
||||||
@@ -84,6 +85,13 @@ module.exports = {
|
|||||||
// cookies are only sent back over an encrypted connection when players
|
// cookies are only sent back over an encrypted connection when players
|
||||||
// have one, whoever does the encrypting.
|
// have one, whoever does the encrypting.
|
||||||
secureCookies: baseUrl.startsWith("https:"),
|
secureCookies: baseUrl.startsWith("https:"),
|
||||||
|
// Google Cloud Vision SafeSearch, used for player-uploaded custom item art
|
||||||
|
// and masterpieces. Off when no key is configured (useful for local work).
|
||||||
|
// When on, a Google outage rejects uploads rather than letting unscanned
|
||||||
|
// images through.
|
||||||
|
googleVision: googleVisionApiKey ? {
|
||||||
|
endpoint: `https://vision.googleapis.com/v1/images:annotate?key=${encodeURIComponent(googleVisionApiKey)}`,
|
||||||
|
} : null,
|
||||||
// the admin panel answers this machine alone on a public server (reach it
|
// 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,
|
// 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.
|
// separated by commas. on a local server it answers whoever can reach it.
|
||||||
@@ -93,11 +101,57 @@ module.exports = {
|
|||||||
// tried or an account is made, with both set. off without them.
|
// tried or an account is made, with both set. off without them.
|
||||||
turnstile: env.AJ_TURNSTILE_SITE_KEY && env.AJ_TURNSTILE_SECRET
|
turnstile: env.AJ_TURNSTILE_SITE_KEY && env.AJ_TURNSTILE_SECRET
|
||||||
? {siteKey: env.AJ_TURNSTILE_SITE_KEY, secret: env.AJ_TURNSTILE_SECRET} : null,
|
? {siteKey: env.AJ_TURNSTILE_SITE_KEY, secret: env.AJ_TURNSTILE_SECRET} : null,
|
||||||
|
// A stalled CAPTCHA provider must not consume all of the VPS's outbound
|
||||||
|
// sockets. This only limits simultaneous verification requests; normal
|
||||||
|
// players use one, and a rejected request can safely be retried.
|
||||||
|
maxConcurrentCaptchaChecks: Math.max(1, Math.min(100, Number(env.AJ_CAPTCHA_MAX_CONCURRENT) || 24)),
|
||||||
|
|
||||||
|
// Account-recovery mail is delivered to this HTTPS webhook. It receives
|
||||||
|
// {to, subject, text}; point it at the transactional-mail provider or
|
||||||
|
// small mail relay you use. Recovery is deliberately unavailable until
|
||||||
|
// both values are set, rather than ever exposing a reset link in a page.
|
||||||
|
recoveryMail: env.AJ_RECOVERY_MAIL_URL && env.AJ_RECOVERY_MAIL_TOKEN
|
||||||
|
? {url: env.AJ_RECOVERY_MAIL_URL, token: env.AJ_RECOVERY_MAIL_TOKEN} : null,
|
||||||
|
|
||||||
// asset mirror: anything not served locally is fetched once from here and
|
// asset mirror: anything not served locally is fetched once from here and
|
||||||
// cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only.
|
// cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only.
|
||||||
upstreamContent: env.AJ_UPSTREAM || "https://ajcontent.akamaized.net/",
|
upstreamContent: env.AJ_UPSTREAM || "https://ajcontent.akamaized.net/",
|
||||||
|
// emoji pictures for chat (lib/emoji.js): Twemoji's, at one version
|
||||||
|
emojiUpstream: env.AJ_EMOJI_UPSTREAM || "https://cdn.jsdelivr.net/gh/jdecked/[email protected]/assets/72x72/",
|
||||||
offline: env.AJ_OFFLINE === "1",
|
offline: env.AJ_OFFLINE === "1",
|
||||||
|
// the client's device ids (lib/devices.js): a game whose launcher sent none
|
||||||
|
// (a client from before 1.3.0, the official launcher, or one that left
|
||||||
|
// them out) is turned away at its login, its popup saying to update.
|
||||||
|
// AJ_REQUIRE_DEVICE=0 lets them in (an account seen on banned hardware
|
||||||
|
// before is still kept out).
|
||||||
|
requireDevice: env.AJ_REQUIRE_DEVICE !== "0",
|
||||||
|
// Discord (lib/discord.js): an application's id and secret for linking a
|
||||||
|
// player's Discord account on the account page and for allowed accounts to
|
||||||
|
// sign in to /dashboard/admin (OAuth2 redirects:
|
||||||
|
// <siteUrl>account/discord/callback,
|
||||||
|
// <siteUrl>dashboard/admin/discord/callback, and
|
||||||
|
// <siteUrl>dashboard/staff/discord/callback), and a bot in Burrow's Discord
|
||||||
|
// server for the booster badge. linking is off without the first two, the
|
||||||
|
// booster badge left alone without the last two.
|
||||||
|
discord: {
|
||||||
|
clientId: env.AJ_DISCORD_CLIENT_ID || "",
|
||||||
|
clientSecret: env.AJ_DISCORD_CLIENT_SECRET || "",
|
||||||
|
botToken: env.AJ_DISCORD_BOT_TOKEN || "",
|
||||||
|
guildId: env.AJ_DISCORD_GUILD_ID || "",
|
||||||
|
// Optional Components V2 notification channels. Leave any empty to
|
||||||
|
// disable that stream: reports, public status, game joins/leaves, the
|
||||||
|
// moderation audit trail, and Discord bot command/audit events.
|
||||||
|
reportsChannelId: env.AJ_DISCORD_REPORTS_CHANNEL_ID || "",
|
||||||
|
statusChannelId: env.AJ_DISCORD_STATUS_CHANNEL_ID || "",
|
||||||
|
gameLogsChannelId: env.AJ_DISCORD_GAME_LOGS_CHANNEL_ID || "",
|
||||||
|
moderationLogsChannelId: env.AJ_DISCORD_MOD_LOGS_CHANNEL_ID || "",
|
||||||
|
botLogsChannelId: env.AJ_DISCORD_BOT_LOGS_CHANNEL_ID || "",
|
||||||
|
// A signed GitHub push webhook at /discord/github can turn commits into
|
||||||
|
// a Components V2 update card. All three values are needed to enable it.
|
||||||
|
githubRepository: env.AJ_GITHUB_REPOSITORY || "", // owner/repository
|
||||||
|
githubWebhookSecret: env.AJ_GITHUB_WEBHOOK_SECRET || "",
|
||||||
|
updatesChannelId: env.AJ_DISCORD_UPDATES_CHANNEL_ID || "",
|
||||||
|
},
|
||||||
deployVersion: env.AJ_DEPLOY_VERSION || "1830",
|
deployVersion: env.AJ_DEPLOY_VERSION || "1830",
|
||||||
// older builds the CDN still serves, asked in turn for a room file the
|
// 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.
|
// current build has dropped. 1828 is the last with the Summer Carnival.
|
||||||
@@ -116,7 +170,11 @@ module.exports = {
|
|||||||
// 41: the game's text says "Burrow" where it said Animal Jam.
|
// 41: the game's text says "Burrow" where it said Animal Jam.
|
||||||
// 48: the item giver (the item finder renamed) with previews and hex colours;
|
// 48: the item giver (the item finder renamed) with previews and hex colours;
|
||||||
// 49 and 50: its link to a colour picker.
|
// 49 and 50: its link to a colour picker.
|
||||||
buildVersion: env.AJ_BUILD_VERSION || "57",
|
// 61: the Owner, Moderator, Developer and Verified name tag badges seen by everyone.
|
||||||
|
// 62: "Custom pictures" in the settings menu, to hide players' item pictures.
|
||||||
|
// 83: den items tinted (the tint in their version, DenItemHelper.applyTint).
|
||||||
|
// 84: fixes from the owner's list of bugs (bugs.txt, 2026-10-23).
|
||||||
|
buildVersion: env.AJ_BUILD_VERSION || "92",
|
||||||
// what the official CDN is asked for; not ours to change.
|
// what the official CDN is asked for; not ours to change.
|
||||||
upstreamBuildVersion: "3",
|
upstreamBuildVersion: "3",
|
||||||
|
|
||||||
@@ -149,7 +207,7 @@ module.exports = {
|
|||||||
// are written into both pages. the emails and the host's country are
|
// 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
|
// placeholders until set; the operator is, at the owner's word, said to
|
||||||
// be in the EU without a name or a country.
|
// be in the EU without a name or a country.
|
||||||
termsVersion: "2026-10-17",
|
termsVersion: "2026-10-24",
|
||||||
legalEmail: env.AJ_LEGAL_EMAIL || "[email protected]",
|
legalEmail: env.AJ_LEGAL_EMAIL || "[email protected]",
|
||||||
adminEmail: env.AJ_ADMIN_EMAIL || "[email protected]",
|
adminEmail: env.AJ_ADMIN_EMAIL || "[email protected]",
|
||||||
operator: env.AJ_OPERATOR || "an individual based in the European Union",
|
operator: env.AJ_OPERATOR || "an individual based in the European Union",
|
||||||
@@ -246,8 +304,24 @@ module.exports = {
|
|||||||
{room: "appondale.room_museum", shown: "appondale.room_museum_ant", months: [2, 4, 6, 8, 10, 12]},
|
{room: "appondale.room_museum", shown: "appondale.room_museum_ant", months: [2, 4, 6, 8, 10, 12]},
|
||||||
],
|
],
|
||||||
startupRoom: "jamaa_township.room_main",
|
startupRoom: "jamaa_township.room_main",
|
||||||
shards: [{id: 1, name: "Aldan"}],
|
// where a player who does not start in their den arrives: one of these at
|
||||||
maxUsersPerRoom: 80,
|
// random, of those that are not full (lib/world.js). AJ_SPAWN_ROOMS: a
|
||||||
|
// list of its own, comma-separated (the tests' is the township alone).
|
||||||
|
spawnRooms: env.AJ_SPAWN_ROOMS ? env.AJ_SPAWN_ROOMS.split(",").map(room => room.trim()).filter(Boolean)
|
||||||
|
: ["jamaa_township.room_main", "sarepia.room_main", "crystal_sands.room_main", "coral_canyons.room_main",
|
||||||
|
"mountains_of_shivveer.room_main", "appondale.room_main", "lost_temple_of_zios.room_main", "aussie.room_main", "balloosh.room_main"],
|
||||||
|
// the worlds, each its own copy of every land (rooms are "path#world";
|
||||||
|
// dens and parties are everyone's). a player arrives in one at random and
|
||||||
|
// can switch in the settings menu (gui.ServerSelector). the game names
|
||||||
|
// world N after the Nth name of its own list (551 Aldan, 552 Congo...,
|
||||||
|
// generic list 16), so the names here are only for the panels and logs.
|
||||||
|
// AJ_WORLDS: how many (the tests' is one).
|
||||||
|
// the admin panel can change how many while the server runs (lib/world.js
|
||||||
|
// setWorldCount), which then outlasts a restart.
|
||||||
|
worldNames: ["Aldan", "Congo", "Draa", "Grande", "Kama", "Nile", "Pecos", "Ramu", "Tigris", "Zambezi"],
|
||||||
|
shards: ["Aldan", "Congo", "Draa", "Grande", "Kama", "Nile", "Pecos", "Ramu", "Tigris", "Zambezi"]
|
||||||
|
.slice(0, Math.min(10, Math.max(1, Number(env.AJ_WORLDS) || 2))).map((name, i) => ({id: i + 1, name})),
|
||||||
|
maxUsersPerRoom: 40,
|
||||||
// everything in every shop for nothing (AJ_FREE_SHOPS=1). off unless
|
// 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.
|
// asked for: what the game's shops make of a price of 0 has not been seen.
|
||||||
freeShops: env.AJ_FREE_SHOPS === "1",
|
freeShops: env.AJ_FREE_SHOPS === "1",
|
||||||
@@ -275,6 +349,14 @@ module.exports = {
|
|||||||
cacheMissesPerTenMinutes: 1500, // a first visit with an empty cache fetches several hundred files
|
cacheMissesPerTenMinutes: 1500, // a first visit with an empty cache fetches several hundred files
|
||||||
upstreamTimeoutMs: 20000,
|
upstreamTimeoutMs: 20000,
|
||||||
maxCacheBytes: Number(env.AJ_MAX_CACHE_MB || 8192) * 1024 * 1024,
|
maxCacheBytes: Number(env.AJ_MAX_CACHE_MB || 8192) * 1024 * 1024,
|
||||||
|
// how often at most the packs with custom items in are made again after
|
||||||
|
// one changes (lib/defpacks.js clientPack); the tests use 0, made at once.
|
||||||
|
packRemakeMs: env.AJ_PACK_REMAKE_MS === undefined ? 15000 : Number(env.AJ_PACK_REMAKE_MS),
|
||||||
|
// masterpieces (lib/masterpieces.js): seconds an account must have had
|
||||||
|
// before it paints one (AJ_MASTERPIECE_MIN_AGE; the tests use 0), and new
|
||||||
|
// pictures an account may post in any 24 hours.
|
||||||
|
masterpieceMinAccountAge: env.AJ_MASTERPIECE_MIN_AGE === undefined ? 86400 : Number(env.AJ_MASTERPIECE_MIN_AGE),
|
||||||
|
masterpiecesPerDay: 10,
|
||||||
maxConnections: 2000,
|
maxConnections: 2000,
|
||||||
maxHttpConnections: 2000, // open at once, in all
|
maxHttpConnections: 2000, // open at once, in all
|
||||||
maxHttpConnectionsPerAddress: 40, // the game opens a good many at once while it loads
|
maxHttpConnectionsPerAddress: 40, // the game opens a good many at once while it loads
|
||||||
@@ -282,14 +364,34 @@ module.exports = {
|
|||||||
tlsHandshakeTimeoutMs: 10000,
|
tlsHandshakeTimeoutMs: 10000,
|
||||||
maxMessagesPerTenSeconds: 400, // per game socket; walking sends a few a second
|
maxMessagesPerTenSeconds: 400, // per game socket; walking sends a few a second
|
||||||
loginTimeoutMs: 30000, // a game socket must log in within this
|
loginTimeoutMs: 30000, // a game socket must log in within this
|
||||||
idleTimeoutMs: 15 * 60000, // the client sends a keep-alive far more often
|
// a client sends nothing while its player is away, and signs itself out
|
||||||
|
// after 75 minutes of that (com.sbi.client.KeepAlive): the socket waits longer.
|
||||||
|
idleTimeoutMs: 80 * 60000,
|
||||||
tokenLifetimeDays: 30, // login tokens kept by the launcher's "remember me"
|
tokenLifetimeDays: 30, // login tokens kept by the launcher's "remember me"
|
||||||
maxChatLength: 300,
|
// a line as sent: the client's chat box takes 200 (gui.ChatHistory), and
|
||||||
|
// each emoji goes as a tag of 8 or more ("\{1f600}"). lib/chatspam.js
|
||||||
|
// cuts down what is long for no good reason.
|
||||||
|
maxChatLength: 600,
|
||||||
|
// how old an account must be before it may give its items pictures
|
||||||
|
// (lib/playeritems.js), so a picture turned away is not simply sent again
|
||||||
|
// from a new account. not for this machine's own requests (AJ_ITEM_ART_MIN_HOURS).
|
||||||
|
itemArtMinAccountHours: Number(env.AJ_ITEM_ART_MIN_HOURS || 24),
|
||||||
|
// warnings (lib/moderation.js warn): the Nth one within `days` also
|
||||||
|
// silences the player for that many minutes, [[N, minutes], ...]. a
|
||||||
|
// longer silence already on them stays. steps [] turns it off.
|
||||||
|
warningSilence: {days: 30, steps: [[3, 60], [5, 24 * 60]]},
|
||||||
// days typed chat and whispers are kept for the moderator panel's chat
|
// days typed chat and whispers are kept for the moderator panel's chat
|
||||||
// history (lib/chatlog.js); 0 keeps none.
|
// 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),
|
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 ...
|
chatLinesPerWindow: 5, // typed chat lines one player may send ...
|
||||||
chatWindowMs: 3000, // ... in this long
|
chatWindowMs: 3000, // ... in this long
|
||||||
|
roomActionsPerWindow: 6, // emotes, actions and the like one player may send a room ...
|
||||||
|
roomActionWindowMs: 3000, // ... in this long (the rest reach nobody)
|
||||||
|
// eco den items (lib/eco.js): credits an hour for each point of eco power
|
||||||
|
// placed in a den, and what an account is given the first time it looks
|
||||||
|
// (an Eco Solar Panel's price)
|
||||||
|
ecoCreditsPerPointHour: 1,
|
||||||
|
ecoStartCredits: 1500,
|
||||||
maxBytesPerTenSeconds: 512 * 1024, // per game socket; saving a full den is about 40 KB
|
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
|
// 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
|
// player at every login and is never taken out again, so there is an end
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# Deployment helpers
|
||||||
|
|
||||||
|
`update.sh` fetches the configured branch, fast-forwards only, validates changed
|
||||||
|
JavaScript, and restarts the server only when a loaded server file changed. It
|
||||||
|
runs as root, but uses `BURROW_USER` for Git operations.
|
||||||
|
|
||||||
|
## systemd
|
||||||
|
|
||||||
|
The existing `burrow-update.service` and `burrow-update.timer` check for an
|
||||||
|
update every two minutes.
|
||||||
|
|
||||||
|
## OpenRC
|
||||||
|
|
||||||
|
The OpenRC service keeps a small foreground loop alive and runs the same
|
||||||
|
updater every two minutes. It does not require cron.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
install -m 755 deploy/burrow-update.openrc /etc/init.d/burrow-update
|
||||||
|
install -m 644 deploy/burrow-update.conf /etc/conf.d/burrow-update
|
||||||
|
rc-update add burrow-update default
|
||||||
|
rc-service burrow-update start
|
||||||
|
```
|
||||||
|
|
||||||
|
Uncomment and change values in `/etc/conf.d/burrow-update` when the server is
|
||||||
|
not installed at `/home/aj/ajc-private-server`, runs as a different user, or
|
||||||
|
uses a differently named OpenRC service. `BURROW_UPDATE_INTERVAL` is a positive
|
||||||
|
number of seconds and defaults to `120`.
|
||||||
|
|
||||||
|
`update.sh` selects OpenRC automatically when run by OpenRC. Set
|
||||||
|
`BURROW_INIT=openrc` when running it manually or from another supervisor. Set
|
||||||
|
`BURROW_INIT=systemd` to force systemd.
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# Copy to /etc/conf.d/burrow-update to override these values for OpenRC.
|
||||||
|
# This file is intentionally safe to source as a shell configuration file.
|
||||||
|
|
||||||
|
# BURROW_DIR=/home/aj/ajc-private-server
|
||||||
|
# BURROW_USER=aj
|
||||||
|
# BURROW_SERVICE=burrow
|
||||||
|
# BURROW_BRANCH=main
|
||||||
|
# BURROW_UPDATE_INTERVAL=120
|
||||||
|
# BURROW_INIT=openrc
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
#!/sbin/openrc-run
|
||||||
|
# Install as /etc/init.d/burrow-update (see deploy/README.md).
|
||||||
|
|
||||||
|
description="Update the Burrow server from GitHub"
|
||||||
|
supervisor=supervise-daemon
|
||||||
|
command=/bin/bash
|
||||||
|
command_args="${BURROW_DIR:-/home/aj/ajc-private-server}/deploy/update-loop.sh"
|
||||||
|
pidfile="/run/${RC_SVCNAME}.pid"
|
||||||
|
stopgroup=yes
|
||||||
|
|
||||||
|
# update.sh uses this to choose rc-service when it restarts Burrow.
|
||||||
|
: "${BURROW_INIT:=openrc}"
|
||||||
|
export BURROW_INIT
|
||||||
|
|
||||||
|
depend() {
|
||||||
|
need net
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Runs update.sh repeatedly for init systems without a timer facility.
|
||||||
|
set -u
|
||||||
|
|
||||||
|
interval=${BURROW_UPDATE_INTERVAL:-120}
|
||||||
|
case "$interval" in
|
||||||
|
''|*[!0-9]*)
|
||||||
|
echo "BURROW_UPDATE_INTERVAL must be a positive number of seconds" >&2
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ "$interval" -eq 0 ]; then
|
||||||
|
echo "BURROW_UPDATE_INTERVAL must be greater than zero" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||||
|
|
||||||
|
while :; do
|
||||||
|
# A failed fetch or rejected update should not stop future update attempts.
|
||||||
|
"$script_dir/update.sh" || echo "burrow update failed; will retry in $interval seconds" >&2
|
||||||
|
sleep "$interval"
|
||||||
|
done
|
||||||
+40
-5
@@ -1,15 +1,35 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# brings the server to origin's main and restarts it when the change needs it.
|
# 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.
|
# Run as root by either burrow-update.timer or the OpenRC updater service; git
|
||||||
|
# itself runs as the server's user.
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
dir=${BURROW_DIR:-/home/aj/ajc-private-server}
|
dir=${BURROW_DIR:-/home/aj/ajc-private-server}
|
||||||
user=${BURROW_USER:-aj}
|
user=${BURROW_USER:-aj}
|
||||||
service=${BURROW_SERVICE:-burrow}
|
service=${BURROW_SERVICE:-burrow}
|
||||||
branch=${BURROW_BRANCH:-main}
|
branch=${BURROW_BRANCH:-main}
|
||||||
|
init=${BURROW_INIT:-}
|
||||||
|
|
||||||
git() { runuser -u "$user" -- git -C "$dir" "$@"; }
|
git() { runuser -u "$user" -- git -C "$dir" "$@"; }
|
||||||
|
|
||||||
|
restart_service() {
|
||||||
|
case "$init" in
|
||||||
|
systemd) systemctl restart "$service" ;;
|
||||||
|
openrc) rc-service "$service" restart ;;
|
||||||
|
"")
|
||||||
|
if [ -d /run/openrc ] || [ -n "${RC_SVCNAME:-}" ]; then
|
||||||
|
rc-service "$service" restart
|
||||||
|
else
|
||||||
|
systemctl restart "$service"
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "unknown BURROW_INIT value: $init (expected systemd or openrc)" >&2
|
||||||
|
return 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
git fetch --quiet origin "$branch"
|
git fetch --quiet origin "$branch"
|
||||||
old=$(git rev-parse HEAD)
|
old=$(git rev-parse HEAD)
|
||||||
new=$(git rev-parse "origin/$branch")
|
new=$(git rev-parse "origin/$branch")
|
||||||
@@ -27,9 +47,24 @@ for file in $(git diff --name-only "$old" "$new" -- '*.js'); do
|
|||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
|
|
||||||
# public/ is read from disk on every request; the rest is loaded once, at start
|
# the npm packages (only discord.js, for the optional Discord bot): installed
|
||||||
if git diff --name-only "$old" "$new" | grep -qvE '^(public/|client-updates/|test/|tools/|deploy/|[^/]+\.md$|\.gitignore$)'; then
|
# again when the lockfile changed, or when they never were. a failed install
|
||||||
systemctl restart "$service"
|
# leaves the bot off; the game itself needs none of them.
|
||||||
|
if [ -f "$dir/package-lock.json" ] && { ! git diff --quiet "$old" "$new" -- package-lock.json || [ ! -d "$dir/node_modules" ]; }; then
|
||||||
|
if command -v npm >/dev/null && runuser -u "$user" -- npm --prefix "$dir" ci --omit=dev --no-audit --no-fund; then
|
||||||
|
echo "npm packages installed"
|
||||||
|
else
|
||||||
|
echo "npm packages could not be installed; the Discord bot stays off" >&2
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# public/ is read from disk on every request; the rest is loaded once, at start.
|
||||||
|
# the list is taken whole first: piped straight into grep -q, a long one (a
|
||||||
|
# push of many files) had git cut off mid-write ("Broken pipe"), which
|
||||||
|
# pipefail read as nothing to restart for.
|
||||||
|
changed=$(git diff --name-only "$old" "$new")
|
||||||
|
if grep -qvE '^(public/|client-updates/|test/|tools/|deploy/|[^/]+\.md$|\.gitignore$)' <<<"$changed"; then
|
||||||
|
restart_service
|
||||||
echo "updated $old -> $new, restarted $service"
|
echo "updated $old -> $new, restarted $service"
|
||||||
else
|
else
|
||||||
echo "updated $old -> $new, no restart needed"
|
echo "updated $old -> $new, no restart needed"
|
||||||
|
|||||||
+124
-28
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const crypto = require("crypto");
|
const crypto = require("crypto");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
@@ -45,7 +46,7 @@ const SCHEMA = `
|
|||||||
// fields stored in their own columns rather than in `state`.
|
// fields stored in their own columns rather than in `state`.
|
||||||
const COLUMN_FIELDS = ["id", "username", "salt", "hash", "createdAt"];
|
const COLUMN_FIELDS = ["id", "username", "salt", "hash", "createdAt"];
|
||||||
// how the game treats the account this session; set again at every login.
|
// how the game treats the account this session; set again at every login.
|
||||||
const SESSION_FIELDS = ["accountType", "isGuide", "isModerator", "membershipDays", "startInDen", "startRoom"];
|
const SESSION_FIELDS = ["accountType", "isGuide", "guideRefused", "isModerator", "membershipDays", "startInDen", "startRoom"];
|
||||||
const DEFAULT_MEMBERSHIP_DAYS = 9999;
|
const DEFAULT_MEMBERSHIP_DAYS = 9999;
|
||||||
const MAX_ACCOUNT_TYPE = 5;
|
const MAX_ACCOUNT_TYPE = 5;
|
||||||
const MEMBERSHIP_TYPES = [0, 2]; // non-member, member
|
const MEMBERSHIP_TYPES = [0, 2]; // non-member, member
|
||||||
@@ -60,7 +61,9 @@ const USER_VAR_SETTINGS = 363; // the settings menu's switches, a bit each (gui.
|
|||||||
// the chat filter an account starts with: level 1 slurs and threats, mode 1
|
// the chat filter an account starts with: level 1 slurs and threats, mode 1
|
||||||
// the whole message left out (see account.filter below).
|
// the whole message left out (see account.filter below).
|
||||||
const DEFAULT_FILTER = {level: 1, mode: 1, words: ""};
|
const DEFAULT_FILTER = {level: 1, mode: 1, words: ""};
|
||||||
|
const chatStyles = require("./chatstyles.js");
|
||||||
const MAX_PASSWORD_LENGTH = 100;
|
const MAX_PASSWORD_LENGTH = 100;
|
||||||
|
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
// parts of the game a player can switch off for their own account, each
|
// parts of the game a player can switch off for their own account, each
|
||||||
// enforced where the game asks for it (featureOn below).
|
// enforced where the game asks for it (featureOn below).
|
||||||
// the Early Member badge (lib/badges.js) goes to an account made while
|
// the Early Member badge (lib/badges.js) goes to an account made while
|
||||||
@@ -76,7 +79,10 @@ const LOGIN_DAYS_KEPT = 90; // and none older than this: they hold addresses
|
|||||||
let db = null;
|
let db = null;
|
||||||
const byKey = new Map(); // lowercased username -> account
|
const byKey = new Map(); // lowercased username -> account
|
||||||
const byId = new Map();
|
const byId = new Map();
|
||||||
const savedState = new Map(); // account id -> state JSON as last written
|
// account id -> digest of the state JSON as last written: enough to tell a
|
||||||
|
// change, without a second copy of every account's state (~13 KB each).
|
||||||
|
const savedState = new Map();
|
||||||
|
const stateDigest = json => crypto.createHash("sha256").update(json).digest("base64");
|
||||||
// A name somebody gave up (a rename, a deleted account) is nobody's to take
|
// 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.
|
// for a while: whoever had it is still known by it to the players they met.
|
||||||
const NAME_HELD_DAYS = 30;
|
const NAME_HELD_DAYS = 30;
|
||||||
@@ -215,6 +221,9 @@ const normalize = account => {
|
|||||||
// what the player set on the account page (lib/manage.js).
|
// what the player set on the account page (lib/manage.js).
|
||||||
account.features = {...Object.fromEntries(FEATURES.map(name => [name, true])), ...account.features}; // false = switched off
|
account.features = {...Object.fromEntries(FEATURES.map(name => [name, true])), ...account.features}; // false = switched off
|
||||||
account.locked = account.locked === true; // nobody gets into the game until its owner unlocks it
|
account.locked = account.locked === true; // nobody gets into the game until its owner unlocks it
|
||||||
|
account.recoveryEmail = typeof account.recoveryEmail === "string" && EMAIL_PATTERN.test(account.recoveryEmail)
|
||||||
|
? account.recoveryEmail.toLowerCase() : "";
|
||||||
|
account.recoveryTokens = Array.isArray(account.recoveryTokens) ? account.recoveryTokens.filter(token => token && token.expires > now()) : [];
|
||||||
account.logins = account.logins || []; // {at, via, address, ok}, newest first: lib/accounts.js recordLogin
|
account.logins = account.logins || []; // {at, via, address, ok}, newest first: lib/accounts.js recordLogin
|
||||||
account.roomThemes = account.roomThemes || {}; // room -> theme, for rooms given a look of their own ("!theme here")
|
account.roomThemes = account.roomThemes || {}; // room -> theme, for rooms given a look of their own ("!theme here")
|
||||||
account.randomTheme = account.randomTheme === true; // a theme picked afresh at every login
|
account.randomTheme = account.randomTheme === true; // a theme picked afresh at every login
|
||||||
@@ -242,9 +251,18 @@ const normalize = account => {
|
|||||||
// the name tag: colour in the low byte, badge above it, bit 16 hides the
|
// the name tag: colour in the low byte, badge above it, bit 16 hides the
|
||||||
// adventure level shape (avatar.NameBar.setColorAndBadge).
|
// adventure level shape (avatar.NameBar.setColorAndBadge).
|
||||||
account.nameBarData = Number.isInteger(account.nameBarData) ? account.nameBarData : 0;
|
account.nameBarData = Number.isInteger(account.nameBarData) ? account.nameBarData : 0;
|
||||||
|
// Personal chat appearance. The renderer receives it with each spoken line
|
||||||
|
// (lib/world.js), never as a client-controlled packet field.
|
||||||
|
account.chatStyle = chatStyles.normalize(account.chatStyle);
|
||||||
account.disguise = Number.isInteger(account.disguise) ? account.disguise : 0; // NPC id, see lib/disguises.js
|
account.disguise = Number.isInteger(account.disguise) ? account.disguise : 0; // NPC id, see lib/disguises.js
|
||||||
// shown on the player's card: lib/badges.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.discord = typeof account.discord === "string" ? account.discord : ""; // their Discord username, as Discord gave it (lib/discord.js)
|
||||||
|
if (account.discordId !== undefined && !/^\d{5,25}$/.test(String(account.discordId))) {
|
||||||
|
delete account.discordId; // the linked Discord account's id
|
||||||
|
}
|
||||||
|
// Set only by the owner in /admin. A matching linked Discord identity may
|
||||||
|
// use this account to open the owner dashboard (lib/discord.js).
|
||||||
|
account.adminDashboardAccess = account.adminDashboardAccess === true;
|
||||||
account.badges = Array.isArray(account.badges) ? account.badges : []; // badge ids, given in the admin panel
|
account.badges = Array.isArray(account.badges) ? account.badges : []; // badge ids, given in the admin panel
|
||||||
account.bio = typeof account.bio === "string" ? account.bio : ""; // their own words, for the card's Bio tab
|
account.bio = typeof account.bio === "string" ? account.bio : ""; // their own words, for the card's Bio tab
|
||||||
// seconds spent in the game in all (lib/world.js counts it), and whether
|
// seconds spent in the game in all (lib/world.js counts it), and whether
|
||||||
@@ -270,6 +288,8 @@ const normalize = account => {
|
|||||||
account.totp = account.totp || null;
|
account.totp = account.totp || null;
|
||||||
account.totpSetup = account.totpSetup || null;
|
account.totpSetup = account.totpSetup || null;
|
||||||
account.devices = Array.isArray(account.devices) ? account.devices : [];
|
account.devices = Array.isArray(account.devices) ? account.devices : [];
|
||||||
|
// the computers it signed in from, keyed (lib/devices.js): [{kind, id, first, last}].
|
||||||
|
account.hwids = Array.isArray(account.hwids) ? account.hwids : [];
|
||||||
account.nextInv = account.nextInv || 2;
|
account.nextInv = account.nextInv || 2;
|
||||||
account.numLogins = account.numLogins || 0;
|
account.numLogins = account.numLogins || 0;
|
||||||
account.uuid = account.uuid || crypto.randomUUID();
|
account.uuid = account.uuid || crypto.randomUUID();
|
||||||
@@ -286,13 +306,17 @@ const MAX_START_ROOM = 80;
|
|||||||
function setLoginChoices(account, choices) {
|
function setLoginChoices(account, choices) {
|
||||||
const asked = config.loginChoices && choices && typeof choices === "object" ? choices : {};
|
const asked = config.loginChoices && choices && typeof choices === "object" ? choices : {};
|
||||||
const whole = (value, max) => Number.isInteger(value) && value >= 0 && value <= max;
|
const whole = (value, max) => Number.isInteger(value) && value >= 0 && value <= max;
|
||||||
// member or not, and guide or not, are the player's own choice on any
|
// member or not is the player's own choice on any server; the rest only
|
||||||
// server; the rest only with config.loginChoices: another account type
|
// with config.loginChoices: another account type shows to everyone.
|
||||||
// shows to everyone.
|
|
||||||
const own = choices && typeof choices === "object" ? choices : {};
|
const own = choices && typeof choices === "object" ? choices : {};
|
||||||
const type = MEMBERSHIP_TYPES.includes(own.accountType) ? own.accountType : asked.accountType;
|
const type = MEMBERSHIP_TYPES.includes(own.accountType) ? own.accountType : asked.accountType;
|
||||||
account.accountType = whole(type, MAX_ACCOUNT_TYPE) ? type : config.defaultAccountType;
|
account.accountType = whole(type, MAX_ACCOUNT_TYPE) ? type : config.defaultAccountType;
|
||||||
account.isGuide = own.isGuide === true;
|
// guide (the name tag, the chat bubble, what others see) only for an
|
||||||
|
// account the admin made one (lib/panel.js); asked for without that, it is
|
||||||
|
// refused. a guide's own client may leave it off; the official launcher
|
||||||
|
// asks nothing, and a guide is one.
|
||||||
|
account.isGuide = account.guideGiven === true && (choices && typeof choices === "object" ? own.isGuide === true : true);
|
||||||
|
account.guideRefused = own.isGuide === true && account.guideGiven !== true;
|
||||||
account.isModerator = asked.isModerator === true;
|
account.isModerator = asked.isModerator === true;
|
||||||
account.membershipDays = whole(asked.membershipDays, MAX_MEMBERSHIP_DAYS) ? asked.membershipDays : DEFAULT_MEMBERSHIP_DAYS;
|
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
|
// where to start is the player's to say on any server: their own den in
|
||||||
@@ -318,7 +342,7 @@ const insert = (username, salt, hash, createdAt, state) => {
|
|||||||
const result = db.prepare("INSERT INTO accounts (username, username_key, password_salt, password_hash, created_at, state) VALUES (?, ?, ?, ?, ?, ?)")
|
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);
|
.run(username, username.toLowerCase(), salt, hash, createdAt, json);
|
||||||
account.id = Number(result.lastInsertRowid);
|
account.id = Number(result.lastInsertRowid);
|
||||||
savedState.set(account.id, json);
|
savedState.set(account.id, stateDigest(json));
|
||||||
remember(account);
|
remember(account);
|
||||||
touch(account);
|
touch(account);
|
||||||
return account;
|
return account;
|
||||||
@@ -346,15 +370,18 @@ const importLegacyFile = () => {
|
|||||||
}
|
}
|
||||||
db.exec("COMMIT");
|
db.exec("COMMIT");
|
||||||
fs.renameSync(file, `${file}.imported`);
|
fs.renameSync(file, `${file}.imported`);
|
||||||
console.log(`[accounts] imported ${byKey.size} accounts from accounts.json`);
|
console.log(`[accounts] imported ${logText(byKey.size)} accounts from accounts.json`);
|
||||||
};
|
};
|
||||||
|
|
||||||
const load = () => {
|
const load = () => {
|
||||||
fs.mkdirSync(config.dataDir, {recursive: true});
|
fs.mkdirSync(config.dataDir, {recursive: true});
|
||||||
db = new DatabaseSync(path.join(config.dataDir, "game.sqlite"));
|
db = new DatabaseSync(path.join(config.dataDir, "game.sqlite"));
|
||||||
// busy_timeout: something else writing to the file for a moment (a tool,
|
// busy_timeout: something else writing to the file for a moment (a tool,
|
||||||
// a copy being made) is waited for, not an error.
|
// a copy being made) is waited for, not an error. synchronous NORMAL: with
|
||||||
db.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;");
|
// WAL the disk is synced at checkpoints, not after every commit, which
|
||||||
|
// held the game up on each chat line and save; a crash of the server
|
||||||
|
// loses nothing, a power cut at most the last moment's writes.
|
||||||
|
db.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;");
|
||||||
db.exec(SCHEMA);
|
db.exec(SCHEMA);
|
||||||
for (const row of db.prepare("SELECT * FROM accounts").all()) {
|
for (const row of db.prepare("SELECT * FROM accounts").all()) {
|
||||||
const account = normalize({
|
const account = normalize({
|
||||||
@@ -365,7 +392,7 @@ const load = () => {
|
|||||||
createdAt: row.created_at,
|
createdAt: row.created_at,
|
||||||
...JSON.parse(row.state),
|
...JSON.parse(row.state),
|
||||||
});
|
});
|
||||||
savedState.set(account.id, row.state);
|
savedState.set(account.id, stateDigest(row.state));
|
||||||
remember(account);
|
remember(account);
|
||||||
}
|
}
|
||||||
importLegacyFile();
|
importLegacyFile();
|
||||||
@@ -389,7 +416,7 @@ const load = () => {
|
|||||||
// runs the server is told which, to rename by hand if they see fit.
|
// 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);
|
const unusual = [...byId.values()].filter(account => names.refused(account.username)).map(account => account.username);
|
||||||
if (unusual.length) {
|
if (unusual.length) {
|
||||||
console.log(`[accounts] usernames that could not be chosen today: ${unusual.slice(0, 50).join(", ")}${unusual.length > 50 ? ", ..." : ""}`);
|
console.log(`[accounts] usernames that could not be chosen today: ${logText(unusual.slice(0, 50).join(", "))}${logText(unusual.length > 50 ? ", ..." : "")}`);
|
||||||
}
|
}
|
||||||
// once: the Early Member badge for the accounts that were there before
|
// once: the Early Member badge for the accounts that were there before
|
||||||
// it existed, the oldest hundred of them.
|
// it existed, the oldest hundred of them.
|
||||||
@@ -412,7 +439,7 @@ const load = () => {
|
|||||||
for (const row of db.prepare("SELECT token, account_id, created_at FROM tokens").all()) {
|
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});
|
tokens.set(row.token, {id: row.account_id, createdAt: row.created_at});
|
||||||
}
|
}
|
||||||
console.log(`[accounts] ${byKey.size} accounts in ${path.join(config.dataDir, "game.sqlite")}`);
|
console.log(`[accounts] ${logText(byKey.size)} accounts in ${logText(path.join(config.dataDir, "game.sqlite"))}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Which accounts a save looks at. turning an account into JSON to see
|
// Which accounts a save looks at. turning an account into JSON to see
|
||||||
@@ -459,7 +486,7 @@ const release = account => {
|
|||||||
|
|
||||||
const changedState = (account, changed) => {
|
const changedState = (account, changed) => {
|
||||||
const json = stateJson(account);
|
const json = stateJson(account);
|
||||||
if (savedState.get(account.id) !== json) {
|
if (savedState.get(account.id) !== stateDigest(json)) {
|
||||||
changed.push([account.id, json]);
|
changed.push([account.id, json]);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -567,7 +594,7 @@ const flush = ({some = false} = {}) => {
|
|||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
for (const [id, json] of changed) {
|
for (const [id, json] of changed) {
|
||||||
savedState.set(id, json);
|
savedState.set(id, stateDigest(json));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -636,7 +663,7 @@ const backup = async () => {
|
|||||||
for (const name of old) {
|
for (const name of old) {
|
||||||
fs.unlinkSync(path.join(folder, name));
|
fs.unlinkSync(path.join(folder, name));
|
||||||
}
|
}
|
||||||
console.log(`[accounts] backup written: ${file}`);
|
console.log(`[accounts] backup written: ${logText(file)}`);
|
||||||
};
|
};
|
||||||
const startBackups = () => {
|
const startBackups = () => {
|
||||||
const attempt = () => {
|
const attempt = () => {
|
||||||
@@ -669,9 +696,26 @@ const retire = key => {
|
|||||||
// A new password: ten characters or more, with a capital letter, a small
|
// 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
|
// one and a digit among them. passwords chosen before this rule still sign
|
||||||
// in; it is asked of the next one.
|
// in; it is asked of the next one.
|
||||||
const passwordProblem = password =>
|
// the words most often under a password that meets the rules ("Password123",
|
||||||
(typeof password !== "string" || password.length < MIN_PASSWORD_LENGTH || password.length > MAX_PASSWORD_LENGTH
|
// "Sunshine2024"): with its digits and signs taken off, a password that is
|
||||||
|| !/[A-Z]/.test(password) || !/[a-z]/.test(password) || !/[0-9]/.test(password) ? "invalid_password" : null);
|
// one of these is refused, as is one with the username in it.
|
||||||
|
const COMMON_PASSWORD_WORDS = new Set(["password", "passw", "pass", "qwerty", "qwertyuiop", "asdfgh", "asdfghjkl", "zxcvbn", "abcdef", "abcdefg",
|
||||||
|
"abcdefgh", "abcdefghij", "welcome", "letmein", "iloveyou", "admin", "administrator", "monkey", "dragon", "football", "baseball", "soccer",
|
||||||
|
"sunshine", "princess", "starwars", "superman", "batman", "master", "shadow", "michael", "jennifer", "charlie", "freedom", "whatever",
|
||||||
|
"trustno", "hello", "secret", "login", "changeme", "animaljam", "animal", "jamaa", "jammer", "wildworks", "burrow", "summer", "winter",
|
||||||
|
"spring", "autumn", "january", "minecraft", "roblox", "fortnite", "pokemon", "computer", "internet", "cookie", "chocolate", "butterfly"]);
|
||||||
|
const passwordProblem = (password, username = "") => {
|
||||||
|
if (typeof password !== "string" || password.length < MIN_PASSWORD_LENGTH || password.length > MAX_PASSWORD_LENGTH
|
||||||
|
|| !/[A-Z]/.test(password) || !/[a-z]/.test(password) || !/[0-9]/.test(password)) {
|
||||||
|
return "invalid_password";
|
||||||
|
}
|
||||||
|
const lower = password.toLowerCase();
|
||||||
|
const name = String(username || "").toLowerCase().replace(/[^a-z0-9]/g, "");
|
||||||
|
if (COMMON_PASSWORD_WORDS.has(lower.replace(/[^a-z]/g, "")) || (name.length >= 3 && lower.replace(/[^a-z0-9]/g, "").includes(name))) {
|
||||||
|
return "weak_password";
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
// creates an account. `avatar` gives the first animal's {type, name}; the
|
// 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
|
// name may be left out, and is then the player's. there is no default
|
||||||
@@ -680,7 +724,7 @@ const passwordProblem = password =>
|
|||||||
// "invalid_password" | "choose_animal"}.
|
// "invalid_password" | "choose_animal"}.
|
||||||
const register = (username, password, avatar = {}) => {
|
const register = (username, password, avatar = {}) => {
|
||||||
username = typeof username === "string" ? username.trim() : username;
|
username = typeof username === "string" ? username.trim() : username;
|
||||||
const error = usernameProblem(username) || passwordProblem(password) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal");
|
const error = usernameProblem(username) || passwordProblem(password, username) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal");
|
||||||
if (error) {
|
if (error) {
|
||||||
return {error};
|
return {error};
|
||||||
}
|
}
|
||||||
@@ -691,8 +735,37 @@ const register = (username, password, avatar = {}) => {
|
|||||||
activeAvatar: 1,
|
activeAvatar: 1,
|
||||||
// early Member, for an account made while there are no more than a hundred.
|
// early Member, for an account made while there are no more than a hundred.
|
||||||
badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [],
|
badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [],
|
||||||
|
recoveryEmail: typeof avatar.email === "string" && EMAIL_PATTERN.test(avatar.email.trim()) ? avatar.email.trim().toLowerCase() : "",
|
||||||
});
|
});
|
||||||
console.log(`[accounts] registered "${username}" (id ${account.id})`);
|
console.log(`[accounts] registered "${logText(username)}" (id ${logText(account.id)})`);
|
||||||
|
return {account};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Public sign-ups can arrive in a burst. scryptSync is fine for the local,
|
||||||
|
// legacy Create Account socket but it would freeze all players while each web
|
||||||
|
// registration is derived. Keep the same validation and database insert on
|
||||||
|
// the main thread, but derive its password on libuv's worker pool. Check the
|
||||||
|
// username again after awaiting: another request may have claimed it first.
|
||||||
|
const registerAsync = async (username, password, avatar = {}) => {
|
||||||
|
username = typeof username === "string" ? username.trim() : username;
|
||||||
|
let error = usernameProblem(username) || passwordProblem(password, username) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal");
|
||||||
|
if (error) {
|
||||||
|
return {error};
|
||||||
|
}
|
||||||
|
const salt = crypto.randomBytes(16).toString("hex");
|
||||||
|
const hash = await hashPasswordAsync(password, salt);
|
||||||
|
error = usernameProblem(username) || passwordProblem(password, username) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal");
|
||||||
|
if (error) {
|
||||||
|
return {error};
|
||||||
|
}
|
||||||
|
const type = Number(avatar.type);
|
||||||
|
const account = insert(username, salt, hash, now(), {
|
||||||
|
avatars: [newAvatar({perUserAvId: 1, avInvId: 1}, avatar.name || username, type, -1)],
|
||||||
|
activeAvatar: 1,
|
||||||
|
badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [],
|
||||||
|
recoveryEmail: typeof avatar.email === "string" && EMAIL_PATTERN.test(avatar.email.trim()) ? avatar.email.trim().toLowerCase() : "",
|
||||||
|
});
|
||||||
|
console.log(`[accounts] registered "${logText(username)}" (id ${logText(account.id)})`);
|
||||||
return {account};
|
return {account};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -738,9 +811,10 @@ const authenticateAsync = async (username, password) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// gives the account a new password and signs it out everywhere. returns
|
// gives the account a new password and signs it out everywhere. returns
|
||||||
// "invalid_password" when the password is not acceptable, else null.
|
// "invalid_password" (the rules) or "weak_password" (a common one, or the
|
||||||
|
// username in it) when the password is not acceptable, else null.
|
||||||
const setPassword = (account, password) => {
|
const setPassword = (account, password) => {
|
||||||
const problem = passwordProblem(password);
|
const problem = passwordProblem(password, account.username);
|
||||||
if (problem) {
|
if (problem) {
|
||||||
return problem;
|
return problem;
|
||||||
}
|
}
|
||||||
@@ -768,7 +842,10 @@ const storableUsernameProblem = username => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// gives the account a new username, and carries it into everyone's buddy and
|
// gives the account a new username, and carries it into everyone's buddy and
|
||||||
// block lists. returns "invalid_username" or "username_taken", else null.
|
// block lists. The staff dashboard stores a few human-readable names beside
|
||||||
|
// account ids; keep those labels current too, so a rename does not split a
|
||||||
|
// player's history across two names. Returns "invalid_username" or
|
||||||
|
// "username_taken", else null.
|
||||||
// the player must not be online: the game knows them by the old name.
|
// 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
|
// with `anyName` (the admin panel) the sign-up rules about length and
|
||||||
// characters do not apply; see storableUsernameProblem.
|
// characters do not apply; see storableUsernameProblem.
|
||||||
@@ -789,7 +866,19 @@ const rename = (account, username, anyName = false) => {
|
|||||||
db.prepare("DELETE FROM retired_names WHERE name_key = ?").run(newKey);
|
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);
|
db.prepare("UPDATE accounts SET username = ?, username_key = ? WHERE id = ?").run(username, newKey, account.id);
|
||||||
console.log(`[accounts] renamed "${account.username}" to "${username}" (id ${account.id})`);
|
console.log(`[accounts] renamed "${logText(account.username)}" to "${logText(username)}" (id ${logText(account.id)})`);
|
||||||
|
for (const [table, column] of [
|
||||||
|
["reports", "reporter"], ["reports", "target"], ["feedback", "username"],
|
||||||
|
["chat_log", "username"], ["chat_log", "to_name"], ["appeals", "username"],
|
||||||
|
["ban_log", "username"], ["mod_log", "by"], ["mod_log", "target"],
|
||||||
|
]) {
|
||||||
|
// A few lean unit tests load the account store without every dashboard
|
||||||
|
// module. The tables are present in the actual server, but keep rename
|
||||||
|
// usable in that smaller setup too.
|
||||||
|
if (db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table)) {
|
||||||
|
db.prepare(`UPDATE ${table} SET ${column} = ? WHERE ${column} = ? COLLATE NOCASE`).run(username, account.username);
|
||||||
|
}
|
||||||
|
}
|
||||||
byKey.delete(oldKey);
|
byKey.delete(oldKey);
|
||||||
account.username = username;
|
account.username = username;
|
||||||
byKey.set(newKey, account);
|
byKey.set(newKey, account);
|
||||||
@@ -848,7 +937,7 @@ const remove = account => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
save(...named);
|
save(...named);
|
||||||
console.log(`[accounts] deleted "${account.username}" (id ${account.id})`);
|
console.log(`[accounts] deleted "${logText(account.username)}" (id ${logText(account.id)})`);
|
||||||
};
|
};
|
||||||
|
|
||||||
// small server-wide values kept in the database (the admin panel's password).
|
// small server-wide values kept in the database (the admin panel's password).
|
||||||
@@ -884,10 +973,17 @@ const byToken = token => {
|
|||||||
|
|
||||||
const byName = username => touch(byKey.get(String(username).toLowerCase())) || null;
|
const byName = username => touch(byKey.get(String(username).toLowerCase())) || null;
|
||||||
|
|
||||||
|
// a username as its account spells it, or null. only asks whether there is
|
||||||
|
// one: unlike byName it does not count as the account being in use.
|
||||||
|
const nameOf = username => {
|
||||||
|
const account = byKey.get(String(username).toLowerCase());
|
||||||
|
return account ? account.username : null;
|
||||||
|
};
|
||||||
|
|
||||||
const accountById = id => touch(byId.get(Number(id))) || null;
|
const accountById = id => touch(byId.get(Number(id))) || null;
|
||||||
|
|
||||||
const all = () => [...byId.values()];
|
const all = () => [...byId.values()];
|
||||||
|
|
||||||
const database = () => db;
|
const database = () => db;
|
||||||
|
|
||||||
module.exports = {FEATURES, featureOn, recordLogin, revokeTokens, load, save, flush, hold, release, startBackups, database, setLoginChoices, setPassword, rename, remove, setting, setSetting, hashPassword, register, usernameProblem, authenticate, authenticateAsync, issueToken, byToken, byName, byId: accountById, newAvatar, freeAvatarSlot, all};
|
module.exports = {FEATURES, featureOn, recordLogin, revokeTokens, load, save, flush, hold, release, startBackups, database, setLoginChoices, setPassword, rename, remove, setting, setSetting, hashPassword, register, registerAsync, usernameProblem, authenticate, authenticateAsync, issueToken, byToken, byName, nameOf, byId: accountById, newAvatar, freeAvatarSlot, all};
|
||||||
+199
-14
@@ -2,10 +2,17 @@
|
|||||||
|
|
||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
const bans = require("./bans.js");
|
const bans = require("./bans.js");
|
||||||
|
const cdn = require("./cdn.js");
|
||||||
|
const colours = require("./colours.js");
|
||||||
const captcha = require("./captcha.js");
|
const captcha = require("./captcha.js");
|
||||||
const defpacks = require("./defpacks.js");
|
const defpacks = require("./defpacks.js");
|
||||||
|
const devices = require("./devices.js");
|
||||||
const config = require("../config.js");
|
const config = require("../config.js");
|
||||||
|
const roles = require("./roles.js");
|
||||||
const dens = require("./dens.js");
|
const dens = require("./dens.js");
|
||||||
|
const itemControl = require("./itemcontrol.js");
|
||||||
|
const customItems = require("./customitems.js");
|
||||||
|
const itemArt = require("./itemart.js");
|
||||||
const limits = require("./limits.js");
|
const limits = require("./limits.js");
|
||||||
const world = require("./world.js");
|
const world = require("./world.js");
|
||||||
const {addClothing, sendClothingAdded, isUint} = require("./player.js");
|
const {addClothing, sendClothingAdded, isUint} = require("./player.js");
|
||||||
@@ -21,6 +28,7 @@ const MAX_FAVOURITES = 200; // finder items remembered per account
|
|||||||
const STARTER_ANIMALS = [1, 4, 5, 6, 7, 8, 13, 18, 24];
|
const STARTER_ANIMALS = [1, 4, 5, 6, 7, 8, 13, 18, 24];
|
||||||
|
|
||||||
let catalog = null;
|
let catalog = null;
|
||||||
|
let catalogVersion = -1; // defpacks.customVersion() it was built at: staff add items as the server runs
|
||||||
|
|
||||||
const buildCatalog = () => [
|
const buildCatalog = () => [
|
||||||
...defpacks.clothingIds().map(id => {
|
...defpacks.clothingIds().map(id => {
|
||||||
@@ -35,13 +43,23 @@ const buildCatalog = () => [
|
|||||||
|
|
||||||
// `favourites` is an account's finderGiven, or null: with nothing typed, the
|
// `favourites` is an account's finderGiven, or null: with nothing typed, the
|
||||||
// items that account took most often come first, the latest first among
|
// items that account took most often come first, the latest first among
|
||||||
// equals. (The in-game finder says whose search it is.)
|
// equals. (The in-game finder says whose search it is.) items locked out of
|
||||||
const search = (params, favourites = null) => {
|
// the finder (lib/itemcontrol.js) are left out, unless `seesLocked`: then
|
||||||
catalog = catalog || buildCatalog();
|
// they are marked. an item a player made (lib/playeritems.js) is found by
|
||||||
|
// its maker only (`askerId`), and by those who see locked ones. with
|
||||||
|
// "base=1", only the game's own items that can be made into a new one.
|
||||||
|
const search = (params, favourites = null, seesLocked = false, askerId = null) => {
|
||||||
|
if (!catalog || catalogVersion !== defpacks.customVersion()) {
|
||||||
|
catalog = buildCatalog();
|
||||||
|
catalogVersion = defpacks.customVersion();
|
||||||
|
}
|
||||||
const kind = params.get("kind") || "all";
|
const kind = params.get("kind") || "all";
|
||||||
const words = (params.get("q") || "").toLowerCase().split(/\s+/).filter(Boolean);
|
const words = (params.get("q") || "").toLowerCase().split(/\s+/).filter(Boolean);
|
||||||
const matches = catalog.filter(entry => (kind === "all" || entry.kind === kind)
|
const matches = catalog.filter(entry => (kind === "all" || entry.kind === kind)
|
||||||
&& words.every(word => entry.search.includes(word) || String(entry.id) === word));
|
&& words.every(word => entry.search.includes(word) || String(entry.id) === word)
|
||||||
|
&& (seesLocked || !itemControl.isLocked(entry.kind, entry.id))
|
||||||
|
&& (seesLocked || [null, askerId].includes(customItems.ownerOf(entry.kind, entry.id)))
|
||||||
|
&& (params.get("base") !== "1" || customItems.copyable(entry.kind, entry.id)));
|
||||||
matches.sort((a, b) => words.includes(String(b.id)) - words.includes(String(a.id)));
|
matches.sort((a, b) => words.includes(String(b.id)) - words.includes(String(a.id)));
|
||||||
if (words.length === 0 && favourites) {
|
if (words.length === 0 && favourites) {
|
||||||
const taken = entry => favourites[`${entry.kind}:${entry.id}`] || {count: 0, at: 0};
|
const taken = entry => favourites[`${entry.kind}:${entry.id}`] || {count: 0, at: 0};
|
||||||
@@ -49,20 +67,50 @@ const search = (params, favourites = null) => {
|
|||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
total: matches.length,
|
total: matches.length,
|
||||||
results: matches.slice(0, MAX_RESULTS).map(({kind: entryKind, id, name, cost, colors}) => ({kind: entryKind, id, name, cost, colors})),
|
results: matches.slice(0, MAX_RESULTS).map(({kind: entryKind, id, name, cost, colors}) => {
|
||||||
|
const locked = seesLocked && itemControl.isLocked(entryKind, id);
|
||||||
|
return {kind: entryKind, id, name: locked ? `${name} (locked)` : name, cost, colors, ...(locked ? {locked} : {})};
|
||||||
|
}),
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// the variants each den item's art has (tools/den-variants.sh):
|
||||||
|
// {versions: [...], colours?: [[hex, ...] per variant]}, or null.
|
||||||
|
let denVariants = null;
|
||||||
|
const variantsOf = id => {
|
||||||
|
if (!denVariants) {
|
||||||
|
try {
|
||||||
|
denVariants = require("./den-variants.json");
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
denVariants = {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return denVariants[Number(id)] || null;
|
||||||
|
};
|
||||||
|
const SPECIAL_MANNEQUIN = "4";
|
||||||
|
const MAX_TINT_SLOT = 0x7FFFFF; // what fits above a den item's variant (8 bits) in its version, kept positive
|
||||||
|
const MAX_PRESETS = 40;
|
||||||
|
|
||||||
// one to four "#RRGGBB", spaces or commas between. the # is wanted: six
|
// one to four "#RRGGBB", spaces or commas between. the # is wanted: six
|
||||||
// digits alone are a colour id
|
// digits alone are a colour id
|
||||||
const HEX_COLOURS = /^#[0-9a-f]{6}([\s,]+#[0-9a-f]{6}){0,3}$/i;
|
const HEX_COLOURS = /^#[0-9a-f]{6}([\s,]+#[0-9a-f]{6}){0,3}$/i;
|
||||||
|
|
||||||
const give = body => {
|
// `seesLocked`: who asks may take items locked out of the finder.
|
||||||
|
const give = (body, seesLocked = false) => {
|
||||||
const account = accounts.byName(body.username);
|
const account = accounts.byName(body.username);
|
||||||
if (!account) {
|
if (!account) {
|
||||||
return {status: 404, body: {error: "No such account"}};
|
return {status: 404, body: {error: "No such account"}};
|
||||||
}
|
}
|
||||||
|
const maker = customItems.ownerOf(body.kind, body.id);
|
||||||
|
if (!seesLocked && maker !== null && maker !== account.id) {
|
||||||
|
return {status: 403, body: {error: "That item is another player's own."}};
|
||||||
|
}
|
||||||
|
if (!seesLocked && itemControl.isLocked(body.kind, body.id)) {
|
||||||
|
return {status: 403, body: {error: "That item is locked out of the item finder."}};
|
||||||
|
}
|
||||||
const session = world.findOnline(account.username);
|
const session = world.findOnline(account.username);
|
||||||
|
const given = {}; // what the item was given as: its colour, or its version
|
||||||
if (body.kind === "clothing") {
|
if (body.kind === "clothing") {
|
||||||
const def = defpacks.itemDef(body.id);
|
const def = defpacks.itemDef(body.id);
|
||||||
const colors = def ? String(def.colors).split(",") : [];
|
const colors = def ? String(def.colors).split(",") : [];
|
||||||
@@ -84,9 +132,18 @@ const give = body => {
|
|||||||
}
|
}
|
||||||
custom = String(entry.id);
|
custom = String(entry.id);
|
||||||
}
|
}
|
||||||
|
// a colour id written signed, as lists of the game's colours often do
|
||||||
|
// them: the same 32 bits, kept as the game keeps colours (unsigned), so
|
||||||
|
// -16777216 is 4278190080.
|
||||||
|
if (/^-\d{1,10}$/.test(custom) && Number(custom) >= -0x80000000) {
|
||||||
|
custom = String(Number(custom) >>> 0);
|
||||||
|
}
|
||||||
if (custom && !isUint(custom)) {
|
if (custom && !isUint(custom)) {
|
||||||
return {status: 400, body: {error: "Colour: an id, or #RRGGBB"}};
|
return {status: 400, body: {error: "Colour: an id, or #RRGGBB"}};
|
||||||
}
|
}
|
||||||
|
if (custom && !colours.known(Number(custom))) {
|
||||||
|
return {status: 400, body: {error: "No such custom colour"}};
|
||||||
|
}
|
||||||
const color = custom || colors[Number(body.colorIndex) || 0];
|
const color = custom || colors[Number(body.colorIndex) || 0];
|
||||||
if (!def || !defpacks.clothingIds().includes(Number(def.id)) || color === undefined) {
|
if (!def || !defpacks.clothingIds().includes(Number(def.id)) || color === undefined) {
|
||||||
return {status: 400, body: {error: "No such clothing item or colour"}};
|
return {status: 400, body: {error: "No such clothing item or colour"}};
|
||||||
@@ -95,6 +152,7 @@ const give = body => {
|
|||||||
if (!item) {
|
if (!item) {
|
||||||
return {status: 409, body: {error: "That inventory is full"}};
|
return {status: 409, body: {error: "That inventory is full"}};
|
||||||
}
|
}
|
||||||
|
given.color = Number(color);
|
||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
if (session) {
|
if (session) {
|
||||||
sendClothingAdded(session, item);
|
sendClothingAdded(session, item);
|
||||||
@@ -104,12 +162,48 @@ const give = body => {
|
|||||||
if (!defpacks.denItemIds().includes(Number(body.id))) {
|
if (!defpacks.denItemIds().includes(Number(body.id))) {
|
||||||
return {status: 400, body: {error: "No such den item"}};
|
return {status: 400, body: {error: "No such den item"}};
|
||||||
}
|
}
|
||||||
if (!dens.giveDenItem(account, body.id)) {
|
// `version`: one of the variants its art has (above), 0 by default.
|
||||||
|
// `tint` ("#RRGGBB") and `tintStrength` (1-100, 100 by default): the
|
||||||
|
// whole item in shades of that colour, which the patched client draws
|
||||||
|
// (DenItemHelper.applyTint). the tint is a custom colour entry
|
||||||
|
// (lib/colours.js, [rgb, strength, 0, 0]), and 1 + its number goes in
|
||||||
|
// the version above the variant's 8 bits, so it goes wherever the item
|
||||||
|
// goes: dens, trades, gifts.
|
||||||
|
const variants = variantsOf(body.id);
|
||||||
|
const variant = body.version === undefined || body.version === "" ? 0 : Number(body.version);
|
||||||
|
if (!Number.isInteger(variant) || (variant !== 0 && !(variants && variants.versions.includes(variant)))) {
|
||||||
|
return {status: 400, body: {error: "That item has no such variant"}};
|
||||||
|
}
|
||||||
|
let version = variant;
|
||||||
|
const tint = typeof body.tint === "string" ? body.tint.trim() : "";
|
||||||
|
if (tint) {
|
||||||
|
const strength = body.tintStrength === undefined || body.tintStrength === "" ? 100 : Number(body.tintStrength);
|
||||||
|
if (!/^#[0-9a-f]{6}$/i.test(tint) || !Number.isInteger(strength) || strength < 1 || strength > 100) {
|
||||||
|
return {status: 400, body: {error: "Tint: #RRGGBB, strength 1 to 100"}};
|
||||||
|
}
|
||||||
|
if ((defpacks.denItemDef(body.id) || {}).specialType === SPECIAL_MANNEQUIN) {
|
||||||
|
return {status: 400, body: {error: "Mannequins cannot be tinted"}};
|
||||||
|
}
|
||||||
|
const entry = world.makeColour(account, [parseInt(tint.slice(1), 16), strength, 0, 0], session);
|
||||||
|
if (!entry) {
|
||||||
|
return {status: 400, body: {error: "Bad colour"}};
|
||||||
|
}
|
||||||
|
if (entry.full) {
|
||||||
|
return {status: 429, body: {error: "No more new colours today. Colours made before can still be used."}};
|
||||||
|
}
|
||||||
|
const slot = entry.id - colours.CUSTOM_BASE + 1;
|
||||||
|
if (slot > MAX_TINT_SLOT) {
|
||||||
|
return {status: 503, body: {error: "No more tints can be made"}};
|
||||||
|
}
|
||||||
|
version |= slot << 8;
|
||||||
|
}
|
||||||
|
if (!dens.giveDenItem(account, body.id, version)) {
|
||||||
return {status: 409, body: {error: "That inventory is full"}};
|
return {status: 409, body: {error: "That inventory is full"}};
|
||||||
}
|
}
|
||||||
if (session) {
|
if (session) {
|
||||||
dens.sendDenItems(session);
|
dens.sendDenItems(session);
|
||||||
}
|
}
|
||||||
|
given.version = version;
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
return {status: 400, body: {error: "Unknown item kind"}};
|
return {status: 400, body: {error: "Unknown item kind"}};
|
||||||
@@ -120,11 +214,90 @@ const give = body => {
|
|||||||
const kept = Object.entries(account.finderGiven).sort((one, other) => other[1].at - one[1].at).slice(0, MAX_FAVOURITES);
|
const kept = Object.entries(account.finderGiven).sort((one, other) => other[1].at - one[1].at).slice(0, MAX_FAVOURITES);
|
||||||
account.finderGiven = Object.fromEntries(kept);
|
account.finderGiven = Object.fromEntries(kept);
|
||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
return {status: 200, body: {ok: true, online: Boolean(session)}};
|
return {status: 200, body: {ok: true, online: Boolean(session), ...given}};
|
||||||
|
};
|
||||||
|
|
||||||
|
// the game's 256 colours (the CDN's paletteData; PaletteHelper.setGamePalette),
|
||||||
|
// as "rrggbb", once read. null while the file cannot be had.
|
||||||
|
let palette = null;
|
||||||
|
const loadPalette = async () => {
|
||||||
|
if (!palette) {
|
||||||
|
const file = await cdn.get(cdn.hashedPath("paletteData"));
|
||||||
|
if (file && file.length >= 4 && file.readInt32BE(0) === 1024) {
|
||||||
|
palette = Array.from({length: 256}, (unused, index) => (file.readUInt32BE(4 + index * 4) & 0xFFFFFF).toString(16).padStart(6, "0"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return palette;
|
||||||
|
};
|
||||||
|
// a packed colour's four, as "rrggbb" (a custom colour's own, or the
|
||||||
|
// palette's at each of its four bytes, colour 1 the top one).
|
||||||
|
const coloursOf = id => {
|
||||||
|
const custom = colours.rgbsOf(id);
|
||||||
|
if (custom) {
|
||||||
|
return custom.map(rgb => rgb.toString(16).padStart(6, "0"));
|
||||||
|
}
|
||||||
|
return palette ? [24, 16, 8, 0].map(shift => palette[(id >>> shift) & 0xFF]) : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// the web item giver (/account/items, lib/manage.js): a search as the
|
||||||
|
// in-game one, with what each item may be given as: a clothing item's own
|
||||||
|
// colours, a den item's variants and whether it takes a tint.
|
||||||
|
const searchFor = async (account, params) => {
|
||||||
|
await loadPalette();
|
||||||
|
const found = search(params, account.finderGiven, roles.can(account, "items.create"), account.id);
|
||||||
|
return {...found, results: found.results.map(result => {
|
||||||
|
// a custom item's own picture, which the game shows in place of its art
|
||||||
|
const custom = customItems.get(result.kind, result.id);
|
||||||
|
const entry = {...result, art: custom ? itemArt.urlOf(custom, "/account/api/itemart") : null};
|
||||||
|
if (entry.kind === "clothing") {
|
||||||
|
const def = defpacks.itemDef(entry.id);
|
||||||
|
const ids = def ? String(def.colors).split(",").map(Number).filter(Number.isInteger).slice(0, MAX_PRESETS) : [];
|
||||||
|
return {...entry, presets: ids.map(id => ({id: id >>> 0, colours: coloursOf(id >>> 0)}))};
|
||||||
|
}
|
||||||
|
const variants = variantsOf(entry.id);
|
||||||
|
return {...entry, variants: variants ? variants.versions : [], variantColours: variants && variants.colours ? variants.colours : null,
|
||||||
|
tintable: (defpacks.denItemDef(entry.id) || {}).specialType !== SPECIAL_MANNEQUIN};
|
||||||
|
})};
|
||||||
|
};
|
||||||
|
|
||||||
|
// ... and its colour boxes, which turn colours to the game's numbers and
|
||||||
|
// back as they are typed: with `id`, a custom colour's four ("rrggbb"); with
|
||||||
|
// `rgbs` (four "rrggbb", commas between), the custom colour already made of
|
||||||
|
// those four, or null (Give would make it); with neither, the game's 256.
|
||||||
|
const colourLookup = async params => {
|
||||||
|
if (params.has("id")) {
|
||||||
|
const text = params.get("id");
|
||||||
|
const id = /^-?\d{1,10}$/.test(text) && Number(text) >= -0x80000000 && Number(text) <= 0xFFFFFFFF ? Number(text) >>> 0 : null;
|
||||||
|
const rgbs = id === null ? null : colours.rgbsOf(id);
|
||||||
|
return rgbs ? {status: 200, body: {id, colours: rgbs.map(rgb => rgb.toString(16).padStart(6, "0"))}}
|
||||||
|
: {status: 404, body: {error: "No such custom colour"}};
|
||||||
|
}
|
||||||
|
if (params.has("rgbs")) {
|
||||||
|
const rgbs = params.get("rgbs").split(",").map(hex => (/^[0-9a-f]{6}$/i.test(hex) ? parseInt(hex, 16) : NaN));
|
||||||
|
const entry = colours.allocate(rgbs, false);
|
||||||
|
if (!entry) {
|
||||||
|
return {status: 400, body: {error: "Four colours: rrggbb,rrggbb,rrggbb,rrggbb"}};
|
||||||
|
}
|
||||||
|
return {status: 200, body: {id: entry.full ? null : entry.id}};
|
||||||
|
}
|
||||||
|
return {status: 200, body: {palette: await loadPalette()}};
|
||||||
|
};
|
||||||
|
|
||||||
|
// ... and its Give, for the account signed in on that page.
|
||||||
|
const giveAs = (account, body) => {
|
||||||
|
if (!givesPerMinute.allow(account.id)) {
|
||||||
|
return {status: 429, body: {error: "Too many at once. Try again in a minute."}};
|
||||||
|
}
|
||||||
|
return give({...body, username: account.username}, roles.can(account, "items.create"));
|
||||||
};
|
};
|
||||||
|
|
||||||
const FORBIDDEN = {status: 403, body: {error: "forbidden"}};
|
const FORBIDDEN = {status: 403, body: {error: "forbidden"}};
|
||||||
|
|
||||||
|
// may whoever asks see and take items locked out of the finder? staff who
|
||||||
|
// may lock them (admins and developers) do; so does the owner, on this
|
||||||
|
// machine, asking with no account's token (the /shop page).
|
||||||
|
const seesLocked = (account, from) => (account ? roles.can(account, "items.create") : from.local);
|
||||||
|
|
||||||
// the account a login token is for, while it may play. A ban leaves the
|
// 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),
|
// 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.
|
// and it is good for nothing else until the ban is over.
|
||||||
@@ -142,7 +315,8 @@ const handle = async (route, params, body, from) => {
|
|||||||
case "GET /api/search": {
|
case "GET /api/search": {
|
||||||
const asking = accounts.byName(params.get("username") || "");
|
const asking = accounts.byName(params.get("username") || "");
|
||||||
const known = asking && (from.local || holderOf(params.get("token")) === asking);
|
const known = asking && (from.local || holderOf(params.get("token")) === asking);
|
||||||
return {status: 200, body: search(params, known ? asking.finderGiven : null)};
|
return {status: 200, body: search(params, known ? asking.finderGiven : null, seesLocked(params.get("token") ? holderOf(params.get("token")) : null, from),
|
||||||
|
known ? asking.id : null)};
|
||||||
}
|
}
|
||||||
case "GET /api/accounts":
|
case "GET /api/accounts":
|
||||||
if (!from.local) {
|
if (!from.local) {
|
||||||
@@ -157,7 +331,7 @@ const handle = async (route, params, body, from) => {
|
|||||||
if (!from.local && !givesPerMinute.allow(owner.id)) {
|
if (!from.local && !givesPerMinute.allow(owner.id)) {
|
||||||
return {status: 429, body: {error: "Too many at once. Try again in a minute."}};
|
return {status: 429, body: {error: "Too many at once. Try again in a minute."}};
|
||||||
}
|
}
|
||||||
return give(body || {});
|
return give(body || {}, seesLocked((body || {}).token ? owner : null, from));
|
||||||
}
|
}
|
||||||
case "POST /api/theme": {
|
case "POST /api/theme": {
|
||||||
const account = accounts.byName((body || {}).username);
|
const account = accounts.byName((body || {}).username);
|
||||||
@@ -204,14 +378,25 @@ const handle = async (route, params, body, from) => {
|
|||||||
}
|
}
|
||||||
const ban = world.moderation.banOf(account);
|
const ban = world.moderation.banOf(account);
|
||||||
const addressBan = ban ? null : bans.addressBan(from.address);
|
const addressBan = ban ? null : bans.addressBan(from.address);
|
||||||
|
const deviceBan = ban || addressBan ? null : devices.banOfAccount(account);
|
||||||
return {status: 200, body: ban ? {banned: "account", banned_seconds: ban.seconds, ban_reason: ban.reason}
|
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}};
|
: addressBan ? {banned: "address", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason}
|
||||||
|
: deviceBan ? {banned: "device", banned_seconds: world.moderation.PERMANENT, ban_reason: deviceBan.reason} : {banned: null}};
|
||||||
}
|
}
|
||||||
case "POST /api/register": {
|
case "POST /api/register": {
|
||||||
if (bans.addressBan(from.address)) {
|
if (bans.addressBan(from.address)) {
|
||||||
return {status: 403, body: {error: "address_banned"}};
|
return {status: 403, body: {error: "address_banned"}};
|
||||||
}
|
}
|
||||||
const {username, password, avatarType} = body || {};
|
// the client says which computer it is on (lib/devices.js); the sign-up
|
||||||
|
// page cannot, and an account made there still signs in through the client.
|
||||||
|
const device = devices.read((body || {}).device);
|
||||||
|
if (device && devices.banOf(device)) {
|
||||||
|
return {status: 403, body: {error: "device_banned"}};
|
||||||
|
}
|
||||||
|
const {username, password, avatarType, email} = body || {};
|
||||||
|
if (config.recoveryMail && (typeof email !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim()))) {
|
||||||
|
return {status: 400, body: {error: "invalid_email"}};
|
||||||
|
}
|
||||||
// the terms and the privacy policy, and old enough to agree to them:
|
// the terms and the privacy policy, and old enough to agree to them:
|
||||||
// said by the one signing up, on the page or in the client.
|
// said by the one signing up, on the page or in the client.
|
||||||
if ((body || {}).agreed !== true) {
|
if ((body || {}).agreed !== true) {
|
||||||
@@ -233,7 +418,7 @@ const handle = async (route, params, body, from) => {
|
|||||||
if (!STARTER_ANIMALS.includes(avatarType)) {
|
if (!STARTER_ANIMALS.includes(avatarType)) {
|
||||||
return {status: 400, body: {error: "choose_animal"}};
|
return {status: 400, body: {error: "choose_animal"}};
|
||||||
}
|
}
|
||||||
const result = accounts.register(username, password, {type: avatarType});
|
const result = await accounts.registerAsync(username, password, {type: avatarType, email});
|
||||||
if (result.account) {
|
if (result.account) {
|
||||||
result.account.agreed = {version: config.termsVersion, at: Math.floor(Date.now() / 1000)};
|
result.account.agreed = {version: config.termsVersion, at: Math.floor(Date.now() / 1000)};
|
||||||
accounts.save(result.account);
|
accounts.save(result.account);
|
||||||
@@ -247,4 +432,4 @@ const handle = async (route, params, body, from) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = {handle};
|
module.exports = {handle, search, searchFor, colourLookup, giveAs};
|
||||||
+2
-1
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
// adventures. the engine is in the client (quest/QuestManager): it places
|
// 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
|
// 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
|
// decided by scripts on the official server, which no file holds, so each
|
||||||
@@ -145,7 +146,7 @@ module.exports = ({enterRoom, joinRoom, tell}) => {
|
|||||||
family[1](tools(session, quest), key, ...args);
|
family[1](tools(session, quest), key, ...args);
|
||||||
}
|
}
|
||||||
else if (key !== null && kind !== "pickedUp") {
|
else if (key !== null && kind !== "pickedUp") {
|
||||||
console.log(`[adventure] ${quest.script.title}: nothing written for "${kind} ${key}"`);
|
console.log(`[adventure] ${logText(quest.script.title)}: nothing written for "${logText(kind)} ${logText(key)}"`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -537,9 +537,12 @@ module.exports = {
|
|||||||
for (const number of [2, 3, 4]) {
|
for (const number of [2, 3, 4]) {
|
||||||
set(q, `cork_${number}${pick("abc")}`, 1, 1, 0);
|
set(q, `cork_${number}${pick("abc")}`, 1, 1, 0);
|
||||||
}
|
}
|
||||||
for (const number of [1, 2, 3, 4]) {
|
// the last key's other places lie off where an animal can walk:
|
||||||
|
// players had to jump to it. it lies where the recording had it.
|
||||||
|
for (const number of [1, 2, 3]) {
|
||||||
set(q, `bunny_key_${number}${pick("abcdef")}`, 1, 1, 0);
|
set(q, `bunny_key_${number}${pick("abcdef")}`, 1, 1, 0);
|
||||||
}
|
}
|
||||||
|
set(q, "bunny_key_4c", 1, 1, 0);
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
+105
-32
@@ -177,40 +177,89 @@ class Amf3Reader {
|
|||||||
// writer for what the reader above produces from a defPack: plain objects,
|
// writer for what the reader above produces from a defPack: plain objects,
|
||||||
// arrays (with or without string keys), strings, numbers, booleans and null.
|
// arrays (with or without string keys), strings, numbers, booleans and null.
|
||||||
// nothing is written as a reference except repeated strings.
|
// nothing is written as a reference except repeated strings.
|
||||||
|
// written into one buffer that grows: a pack is megabytes of small values,
|
||||||
|
// and a Buffer for each of them took seconds for the item pack.
|
||||||
class Amf3Writer {
|
class Amf3Writer {
|
||||||
constructor() {
|
constructor() {
|
||||||
this.parts = [];
|
this.buf = Buffer.allocUnsafe(1 << 16);
|
||||||
|
this.pos = 0;
|
||||||
this.strings = new Map();
|
this.strings = new Map();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
room(bytes) {
|
||||||
|
if (this.pos + bytes > this.buf.length) {
|
||||||
|
let size = this.buf.length * 2;
|
||||||
|
while (size < this.pos + bytes) {
|
||||||
|
size *= 2;
|
||||||
|
}
|
||||||
|
const bigger = Buffer.allocUnsafe(size);
|
||||||
|
this.buf.copy(bigger, 0, 0, this.pos);
|
||||||
|
this.buf = bigger;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
byte(value) {
|
||||||
|
this.room(1);
|
||||||
|
this.buf[this.pos++] = value;
|
||||||
|
}
|
||||||
|
|
||||||
u29(value) {
|
u29(value) {
|
||||||
|
this.room(4);
|
||||||
|
const {buf} = this;
|
||||||
if (value < 0x80) {
|
if (value < 0x80) {
|
||||||
this.parts.push(Buffer.from([value]));
|
buf[this.pos++] = value;
|
||||||
}
|
}
|
||||||
else if (value < 0x4000) {
|
else if (value < 0x4000) {
|
||||||
this.parts.push(Buffer.from([(value >> 7) | 0x80, value & 0x7f]));
|
buf[this.pos++] = (value >> 7) | 0x80;
|
||||||
|
buf[this.pos++] = value & 0x7f;
|
||||||
}
|
}
|
||||||
else if (value < 0x200000) {
|
else if (value < 0x200000) {
|
||||||
this.parts.push(Buffer.from([(value >> 14) | 0x80, ((value >> 7) & 0x7f) | 0x80, value & 0x7f]));
|
buf[this.pos++] = (value >> 14) | 0x80;
|
||||||
|
buf[this.pos++] = ((value >> 7) & 0x7f) | 0x80;
|
||||||
|
buf[this.pos++] = value & 0x7f;
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
this.parts.push(Buffer.from([(value >> 22) | 0x80, ((value >> 15) & 0x7f) | 0x80, ((value >> 8) & 0x7f) | 0x80, value & 0xff]));
|
buf[this.pos++] = (value >> 22) | 0x80;
|
||||||
|
buf[this.pos++] = ((value >> 15) & 0x7f) | 0x80;
|
||||||
|
buf[this.pos++] = ((value >> 8) & 0x7f) | 0x80;
|
||||||
|
buf[this.pos++] = value & 0xff;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
string(text) {
|
string(text) {
|
||||||
if (text === "") {
|
if (text === "") {
|
||||||
this.u29(1);
|
this.u29(1);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
else if (this.strings.has(text)) {
|
const known = this.strings.get(text);
|
||||||
this.u29(this.strings.get(text) << 1);
|
if (known !== undefined) {
|
||||||
|
this.u29(known << 1);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
else {
|
this.strings.set(text, this.strings.size);
|
||||||
this.strings.set(text, this.strings.size);
|
// nearly every string of a pack is short and ASCII: its bytes are its
|
||||||
const bytes = Buffer.from(text, "utf8");
|
// characters, copied here rather than through Buffer's utf8 writer.
|
||||||
this.u29((bytes.length << 1) | 1);
|
if (text.length < 64) {
|
||||||
this.parts.push(bytes);
|
let ascii = true;
|
||||||
|
for (let i = 0; i < text.length; i++) {
|
||||||
|
if (text.charCodeAt(i) > 0x7f) {
|
||||||
|
ascii = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ascii) {
|
||||||
|
this.u29((text.length << 1) | 1);
|
||||||
|
this.room(text.length);
|
||||||
|
for (let i = 0; i < text.length; i++) {
|
||||||
|
this.buf[this.pos++] = text.charCodeAt(i);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
const length = Buffer.byteLength(text, "utf8");
|
||||||
|
this.u29((length << 1) | 1);
|
||||||
|
this.room(length);
|
||||||
|
this.pos += this.buf.write(text, this.pos, "utf8");
|
||||||
}
|
}
|
||||||
|
|
||||||
pairs(entries) {
|
pairs(entries) {
|
||||||
@@ -222,45 +271,69 @@ class Amf3Writer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
value(value) {
|
value(value) {
|
||||||
if (value === undefined) {
|
// most values of a pack are strings: asked first
|
||||||
this.parts.push(Buffer.from([0x00]));
|
if (typeof value === "string") {
|
||||||
|
this.byte(0x06);
|
||||||
|
this.string(value);
|
||||||
|
}
|
||||||
|
else if (value === undefined) {
|
||||||
|
this.byte(0x00);
|
||||||
}
|
}
|
||||||
else if (value === null) {
|
else if (value === null) {
|
||||||
this.parts.push(Buffer.from([0x01]));
|
this.byte(0x01);
|
||||||
}
|
}
|
||||||
else if (typeof value === "boolean") {
|
else if (typeof value === "boolean") {
|
||||||
this.parts.push(Buffer.from([value ? 0x03 : 0x02]));
|
this.byte(value ? 0x03 : 0x02);
|
||||||
}
|
}
|
||||||
else if (typeof value === "number") {
|
else if (typeof value === "number") {
|
||||||
if (Number.isInteger(value) && value >= -0x10000000 && value < 0x10000000) {
|
if (Number.isInteger(value) && value >= -0x10000000 && value < 0x10000000) {
|
||||||
this.parts.push(Buffer.from([0x04]));
|
this.byte(0x04);
|
||||||
this.u29(value & 0x1fffffff);
|
this.u29(value & 0x1fffffff);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
const bytes = Buffer.alloc(9);
|
this.byte(0x05);
|
||||||
bytes[0] = 0x05;
|
this.room(8);
|
||||||
bytes.writeDoubleBE(value, 1);
|
this.pos = this.buf.writeDoubleBE(value, this.pos);
|
||||||
this.parts.push(bytes);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (typeof value === "string") {
|
|
||||||
this.parts.push(Buffer.from([0x06]));
|
|
||||||
this.string(value);
|
|
||||||
}
|
|
||||||
else if (Array.isArray(value)) {
|
else if (Array.isArray(value)) {
|
||||||
this.parts.push(Buffer.from([0x09]));
|
this.byte(0x09);
|
||||||
this.u29((value.length << 1) | 1);
|
this.u29((value.length << 1) | 1);
|
||||||
// string keys set on the array beside its numbered elements.
|
// string keys set on the array beside its numbered elements (an array
|
||||||
this.pairs(Object.entries(value).filter(([key]) => !/^\d+$/.test(key)));
|
// with as many keys as elements has none).
|
||||||
|
const keys = Object.keys(value);
|
||||||
|
this.pairs(keys.length === value.length ? [] : keys.filter(key => !/^\d+$/.test(key)).map(key => [key, value[key]]));
|
||||||
for (const element of value) {
|
for (const element of value) {
|
||||||
this.value(element);
|
this.value(element);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (typeof value === "object" && !Buffer.isBuffer(value)) {
|
else if (value instanceof Date) {
|
||||||
|
// A date (a room file's timestamps): its milliseconds, written in place.
|
||||||
|
this.byte(0x08);
|
||||||
|
this.u29(1);
|
||||||
|
this.room(8);
|
||||||
|
this.pos = this.buf.writeDoubleBE(value.getTime(), this.pos);
|
||||||
|
}
|
||||||
|
else if (Buffer.isBuffer(value)) {
|
||||||
|
// A ByteArray (a room file's pictures and shapes).
|
||||||
|
this.byte(0x0c);
|
||||||
|
this.u29((value.length << 1) | 1);
|
||||||
|
this.room(value.length);
|
||||||
|
this.pos += value.copy(this.buf, this.pos);
|
||||||
|
}
|
||||||
|
else if (typeof value === "object") {
|
||||||
// A dynamic object of no class, with its traits written in place.
|
// A dynamic object of no class, with its traits written in place.
|
||||||
this.parts.push(Buffer.from([0x0a, 0x0b]));
|
this.byte(0x0a);
|
||||||
|
this.byte(0x0b);
|
||||||
|
this.string("");
|
||||||
|
// its own keys in Object.keys order, without an array of entries for each object
|
||||||
|
for (const key in value) {
|
||||||
|
if (Object.hasOwn(value, key)) {
|
||||||
|
this.string(key);
|
||||||
|
this.value(value[key]);
|
||||||
|
}
|
||||||
|
}
|
||||||
this.string("");
|
this.string("");
|
||||||
this.pairs(Object.entries(value));
|
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
throw new Error("Cannot write this value as AMF3");
|
throw new Error("Cannot write this value as AMF3");
|
||||||
@@ -273,6 +346,6 @@ module.exports = {
|
|||||||
encode: value => {
|
encode: value => {
|
||||||
const writer = new Amf3Writer();
|
const writer = new Amf3Writer();
|
||||||
writer.value(value);
|
writer.value(value);
|
||||||
return Buffer.concat(writer.parts);
|
return writer.buf.subarray(0, writer.pos);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
+11
-3
@@ -97,6 +97,12 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
|
|||||||
const messageRoom = session.room ? session.room.id : -1;
|
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];
|
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);
|
session.sendXt("as", messageRoom, ...common, avatar.petInvId, avatar.questLevel || 0);
|
||||||
|
// Nothing more goes to the switching player here. The client swaps the
|
||||||
|
// animals during the transform animation (AvatarSwitch "hideAvatar"),
|
||||||
|
// copying the in-world avatar into the switcher slot first and asking
|
||||||
|
// for "ad" itself when it needs to. An unasked "ad"/"il" lands on the
|
||||||
|
// in-world avatar before that copy, so the old animal vanished from the
|
||||||
|
// switcher and the new one showed twice.
|
||||||
if (session.pos) {
|
if (session.pos) {
|
||||||
for (const other of others(session)) {
|
for (const other of others(session)) {
|
||||||
other.sendXt("as", messageRoom, ...common, ...petFields(activePet(account)), avatar.questLevel || 0);
|
other.sendXt("as", messageRoom, ...common, ...petFields(activePet(account)), avatar.questLevel || 0);
|
||||||
@@ -104,12 +110,12 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
// AvatarSwitch.avatarKillResponse: [success, ?]
|
// AvatarSwitch.avatarKillResponse: [success, gems]
|
||||||
ak(session, roomId, [perUserAvId]) {
|
ak(session, roomId, [perUserAvId]) {
|
||||||
const {account} = session;
|
const {account} = session;
|
||||||
const avatar = account.avatars.find(candidate => candidate.perUserAvId === Number(perUserAvId));
|
const avatar = account.avatars.find(candidate => candidate.perUserAvId === Number(perUserAvId));
|
||||||
if (!avatar || avatar === activeAvatar(account) || account.avatars.length < 2) {
|
if (!avatar || avatar === activeAvatar(account) || account.avatars.length < 2) {
|
||||||
session.sendXt("ak", -1, 0, 0);
|
session.sendXt("ak", -1, 0, account.currency.gems);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
account.avatars = account.avatars.filter(candidate => candidate !== avatar);
|
account.avatars = account.avatars.filter(candidate => candidate !== avatar);
|
||||||
@@ -117,7 +123,9 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
|
|||||||
item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId);
|
item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId);
|
||||||
}
|
}
|
||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
session.sendXt("ak", -1, 1, 0);
|
// [success, gems]: the animal switcher (AvatarSwitcher.recycleAvatarCallback)
|
||||||
|
// shows the second as the player's gems, so it is their total, unchanged.
|
||||||
|
session.sendXt("ak", -1, 1, account.currency.gems);
|
||||||
},
|
},
|
||||||
|
|
||||||
// AvatarXtCommManager.requestColorChange: [color1, color2, color3, nameBarData]
|
// AvatarXtCommManager.requestColorChange: [color1, color2, color3, nameBarData]
|
||||||
|
|||||||
+6
-2
@@ -33,8 +33,12 @@ const cdn = require("./cdn.js");
|
|||||||
// there are no more than a hundred (lib/accounts.js); the admin may give
|
// there are no more than a hundred (lib/accounts.js); the admin may give
|
||||||
// it and take it away like any other.
|
// it and take it away like any other.
|
||||||
|
|
||||||
// in the order they are listed and drawn.
|
// in the order they are listed and drawn. the Verified, Owner, Moderator and
|
||||||
|
// Developer name tags show their badge to everyone, not only to buddies:
|
||||||
|
// their def ids are in PUBLIC_BADGE_IDS of swf-src/AvatarWorldView.as.
|
||||||
const BADGES = [
|
const BADGES = [
|
||||||
|
// first, so its tick comes straight after the name, as on other sites.
|
||||||
|
{id: "verified", label: "Verified", tag: {def: 76, media: 20014, bit: 21}},
|
||||||
{id: "owner", label: "Owner", tag: {def: 63, media: 20001, bit: 8}},
|
{id: "owner", label: "Owner", tag: {def: 63, media: 20001, bit: 8}},
|
||||||
{id: "moderator", label: "Moderator", tag: {def: 64, media: 20002, bit: 9}},
|
{id: "moderator", label: "Moderator", tag: {def: 64, media: 20002, bit: 9}},
|
||||||
{id: "contributor", label: "Contributor", tag: {def: 65, media: 20003, bit: 10}},
|
{id: "contributor", label: "Contributor", tag: {def: 65, media: 20003, bit: 10}},
|
||||||
@@ -61,7 +65,7 @@ const set = (account, ids) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// A Discord username as Discord has them now: 2 to 32 of a-z, 0-9, "_" and
|
// 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.
|
// ".", with no two dots in a row. players link theirs (lib/discord.js).
|
||||||
const DISCORD_NAME = /^(?!.*\.\.)[a-z0-9_.]{2,32}$/;
|
const DISCORD_NAME = /^(?!.*\.\.)[a-z0-9_.]{2,32}$/;
|
||||||
|
|
||||||
// returns the username as it will be kept ("" for none), or null when it
|
// returns the username as it will be kept ("" for none), or null when it
|
||||||
|
|||||||
+2
-1
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
const limits = require("./limits.js");
|
const limits = require("./limits.js");
|
||||||
const net = require("net");
|
const net = require("net");
|
||||||
@@ -158,7 +159,7 @@ const appeal = (account, text, addressKey = "") => {
|
|||||||
}
|
}
|
||||||
db().prepare("INSERT INTO appeals (account_id, created_at, username, text, address_key) VALUES (?, ?, ?, ?, ?)").run(account.id, now(), account.username, body, addressKey);
|
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"});
|
record({account, address: addressKey, action: "appeal"});
|
||||||
console.log(`[bans] "${account.username}" appealed`);
|
console.log(`[bans] "${logText(account.username)}" appealed`);
|
||||||
return {appeal: appealOf(account)};
|
return {appeal: appealOf(account)};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+8
-3
@@ -40,7 +40,7 @@ const requestsPerTenMinutes = limits.limiter(20, 600000);
|
|||||||
// and reads a hosted party's name as three string ids.
|
// and reads a hosted party's name as three string ids.
|
||||||
const roomTitle = room => room.displayName;
|
const roomTitle = room => room.displayName;
|
||||||
|
|
||||||
module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
|
module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft, worldOf, worldName}) => {
|
||||||
// BuddyXtCommManager.buddyStatusResponse: [1, username, uuid, moderatedFlag,
|
// BuddyXtCommManager.buddyStatusResponse: [1, username, uuid, moderatedFlag,
|
||||||
// online, accountType, buddyFlag, avatarName, perUserAvId, partyTimeLeft]
|
// online, accountType, buddyFlag, avatarName, perUserAvId, partyTimeLeft]
|
||||||
const sendStatus = (to, account, buddyFlag) => {
|
const sendStatus = (to, account, buddyFlag) => {
|
||||||
@@ -195,11 +195,16 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
|
|||||||
// gets [roomName, displayName, displayNameStringId, cannotGoThere]; an
|
// gets [roomName, displayName, displayNameStringId, cannotGoThere]; an
|
||||||
// empty room means offline. the last field greys out the card's "go to"
|
// empty room means offline. the last field greys out the card's "go to"
|
||||||
// button (BuddyCard.checkBuddyRoomAgainstMine), so it is 0: every room
|
// button (BuddyCard.checkBuddyRoomAgainstMine), so it is 0: every room
|
||||||
// here can be walked into. someone who blocked the asker looks offline.
|
// here can be walked into. the room's name carries its world, and "go
|
||||||
|
// to" joins it by that name, so it leads into the buddy's world, which
|
||||||
|
// is named after the room when it is not the asker's. someone who
|
||||||
|
// blocked the asker looks offline.
|
||||||
br(session, roomId, [username]) {
|
br(session, roomId, [username]) {
|
||||||
const target = findOnline(username);
|
const target = findOnline(username);
|
||||||
if (target && target.room && !target.account.blocked.includes(key(session.account))) {
|
if (target && target.room && !target.account.blocked.includes(key(session.account))) {
|
||||||
session.sendXt("br", -1, target.room.name, roomTitle(target.room), 0, 0);
|
const world = worldOf(target.room.name);
|
||||||
|
const elsewhere = world !== 0 && world !== session.worldId;
|
||||||
|
session.sendXt("br", -1, target.room.name, `${roomTitle(target.room)}${elsewhere ? ` (${worldName(world)})` : ""}`, 0, 0);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
session.sendXt("br", -1, "", "", 0, 0);
|
session.sendXt("br", -1, "", "", 0, 0);
|
||||||
|
|||||||
+19
-3
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const crypto = require("crypto");
|
const crypto = require("crypto");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
@@ -25,10 +26,12 @@ const MAX_ANSWER_LENGTH = 2048;
|
|||||||
const PASS_MS = 600000;
|
const PASS_MS = 600000;
|
||||||
const PASS_USES = 5;
|
const PASS_USES = 5;
|
||||||
const MAX_PASSES = 10000;
|
const MAX_PASSES = 10000;
|
||||||
|
const MAX_VERIFYING = config.maxConcurrentCaptchaChecks;
|
||||||
|
|
||||||
const on = Boolean(config.turnstile);
|
const on = Boolean(config.turnstile);
|
||||||
const passes = new Map(); // SHA-256 of a pass -> {id: account id, key: address key, expiry, uses}
|
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");
|
const sha256 = text => crypto.createHash("sha256").update(String(text)).digest("hex");
|
||||||
|
let verifying = 0;
|
||||||
|
|
||||||
// for the pages: what each answer means
|
// for the pages: what each answer means
|
||||||
const MESSAGES = {
|
const MESSAGES = {
|
||||||
@@ -69,6 +72,13 @@ const verify = async (answer, from, action) => {
|
|||||||
if (typeof answer !== "string" || !answer || answer.length > MAX_ANSWER_LENGTH) {
|
if (typeof answer !== "string" || !answer || answer.length > MAX_ANSWER_LENGTH) {
|
||||||
return "captcha_required";
|
return "captcha_required";
|
||||||
}
|
}
|
||||||
|
// A burst of valid-looking tokens should not turn an upstream Turnstile
|
||||||
|
// slowdown into thousands of open fetches on this VPS. Refuse quickly;
|
||||||
|
// the browser can reset its widget and retry after the short outage.
|
||||||
|
if (verifying >= MAX_VERIFYING) {
|
||||||
|
return "captcha_unavailable";
|
||||||
|
}
|
||||||
|
verifying++;
|
||||||
const form = new URLSearchParams({secret: config.turnstile.secret, response: answer});
|
const form = new URLSearchParams({secret: config.turnstile.secret, response: answer});
|
||||||
if (!limits.isLoopback(from.address)) {
|
if (!limits.isLoopback(from.address)) {
|
||||||
form.set("remoteip", from.address);
|
form.set("remoteip", from.address);
|
||||||
@@ -79,9 +89,12 @@ const verify = async (answer, from, action) => {
|
|||||||
result = await response.json();
|
result = await response.json();
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
console.log(`[captcha] cloudflare did not answer: ${err.message}`);
|
console.log(`[captcha] cloudflare did not answer: ${logText(err.message)}`);
|
||||||
return "captcha_unavailable";
|
return "captcha_unavailable";
|
||||||
}
|
}
|
||||||
|
finally {
|
||||||
|
verifying--;
|
||||||
|
}
|
||||||
// an answer made for another form is no answer for this one. cloudflare's
|
// an answer made for another form is no answer for this one. cloudflare's
|
||||||
// test keys give none.
|
// test keys give none.
|
||||||
if (!result || result.success !== true || (result.action && result.action !== action)) {
|
if (!result || result.success !== true || (result.action && result.action !== action)) {
|
||||||
@@ -103,8 +116,11 @@ const check = async (body, from, action, account) => {
|
|||||||
return verify(body.captcha, from, action);
|
return verify(body.captcha, from, action);
|
||||||
};
|
};
|
||||||
|
|
||||||
// a page's security policy, letting the widget in when it is on.
|
// a page's security policy: public/captcha.js always (the page calls it even
|
||||||
const policy = csp => (on ? `${csp.replace("script-src ", `script-src 'self' ${ORIGIN} `)}; frame-src ${ORIGIN}` : csp);
|
// when off), and the widget too when it is on.
|
||||||
|
const policy = csp => (on
|
||||||
|
? `${csp.replace("script-src ", `script-src 'self' ${ORIGIN} `).replace("connect-src ", `connect-src 'self' ${ORIGIN} `)}; frame-src ${ORIGIN}`
|
||||||
|
: csp.replace("script-src ", "script-src 'self' "));
|
||||||
|
|
||||||
// a page with public/captcha.js asked for under a name that changes with the
|
// 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
|
// script and the key: cloudflare keeps .js files for hours, whatever the
|
||||||
|
|||||||
+6
-5
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const crypto = require("crypto");
|
const crypto = require("crypto");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
@@ -69,7 +70,7 @@ const measure = async folder => {
|
|||||||
};
|
};
|
||||||
measure(config.cacheDir).then(() => {
|
measure(config.cacheDir).then(() => {
|
||||||
if (cacheBytes > config.maxCacheBytes) {
|
if (cacheBytes > config.maxCacheBytes) {
|
||||||
console.log(`[cdn] the cache holds ${Math.round(cacheBytes / 1048576)} MB, over its limit: new files are served but not kept (AJ_MAX_CACHE_MB)`);
|
console.log(`[cdn] the cache holds ${logText(Math.round(cacheBytes / 1048576))} MB, over its limit: new files are served but not kept (AJ_MAX_CACHE_MB)`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -84,7 +85,7 @@ const download = async (relPath, file) => {
|
|||||||
}
|
}
|
||||||
missing.add(relPath);
|
missing.add(relPath);
|
||||||
}
|
}
|
||||||
console.log(`[cdn] ${res.status} ${relPath}`);
|
console.log(`[cdn] ${logText(res.status)} ${logText(relPath)}`);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const body = Buffer.from(await res.arrayBuffer());
|
const body = Buffer.from(await res.arrayBuffer());
|
||||||
@@ -99,10 +100,10 @@ const download = async (relPath, file) => {
|
|||||||
const tmp = `${file}.${process.pid}.tmp`;
|
const tmp = `${file}.${process.pid}.tmp`;
|
||||||
await fs.promises.writeFile(tmp, body);
|
await fs.promises.writeFile(tmp, body);
|
||||||
await fs.promises.rename(tmp, file);
|
await fs.promises.rename(tmp, file);
|
||||||
console.log(`[cdn] cached ${relPath} (${body.length} bytes)`);
|
console.log(`[cdn] cached ${logText(relPath)} (${logText(body.length)} bytes)`);
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
console.log(`[cdn] could not cache ${relPath}: ${err.message}`);
|
console.log(`[cdn] could not cache ${logText(relPath)}: ${logText(err.message)}`);
|
||||||
}
|
}
|
||||||
return body;
|
return body;
|
||||||
};
|
};
|
||||||
@@ -134,7 +135,7 @@ const getExact = async (asked, mayFetch = () => true) => {
|
|||||||
// A download that fails (the CDN not answering in time) is "not there"
|
// 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.
|
// for now, and is tried again the next time the file is asked for.
|
||||||
inFlight.set(relPath, download(relPath, file).catch(err => {
|
inFlight.set(relPath, download(relPath, file).catch(err => {
|
||||||
console.log(`[cdn] could not fetch ${relPath}: ${err.message}`);
|
console.log(`[cdn] could not fetch ${logText(relPath)}: ${logText(err.message)}`);
|
||||||
return null;
|
return null;
|
||||||
}).finally(() => inFlight.delete(relPath)));
|
}).finally(() => inFlight.delete(relPath)));
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-2
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
|
|
||||||
@@ -142,11 +143,11 @@ const rules = () => {
|
|||||||
parsed.push({line, clauses});
|
parsed.push({line, clauses});
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
console.log(`[filter] lib/chat-filter.txt: a rule that could not be read was left out: ${line}`);
|
console.log(`[filter] lib/chat-filter.txt: a rule that could not be read was left out: ${logText(line)}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
kept = {mtime, rules: parsed};
|
kept = {mtime, rules: parsed};
|
||||||
console.log(`[filter] ${parsed.length} rules`);
|
console.log(`[filter] ${logText(parsed.length)} rules`);
|
||||||
}
|
}
|
||||||
return kept.rules;
|
return kept.rules;
|
||||||
};
|
};
|
||||||
|
|||||||
+68
-11
@@ -3,7 +3,8 @@
|
|||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
const config = require("../config.js");
|
const config = require("../config.js");
|
||||||
|
|
||||||
// what players typed: chat in a room, and whispers. kept for the moderator
|
// what players typed: chat in a room, whispers, Jam-a-Grams and posts on
|
||||||
|
// each other's Jammer Walls. kept for the moderator
|
||||||
// panel (lib/modpanel.js), which is where a moderator reads what was said
|
// panel (lib/modpanel.js), which is where a moderator reads what was said
|
||||||
// before deciding anything; nothing else reads it. lines older than
|
// before deciding anything; nothing else reads it. lines older than
|
||||||
// config.chatLogDays are deleted, and an account's lines go when the
|
// config.chatLogDays are deleted, and an account's lines go when the
|
||||||
@@ -26,6 +27,11 @@ const SCHEMA = `
|
|||||||
|
|
||||||
const CHAT = "chat";
|
const CHAT = "chat";
|
||||||
const WHISPER = "whisper";
|
const WHISPER = "whisper";
|
||||||
|
const JAMAGRAM = "jamagram";
|
||||||
|
const WALL = "wall";
|
||||||
|
const KINDS = [CHAT, WHISPER, JAMAGRAM, WALL];
|
||||||
|
// what the server's filter kept from being sent is kept with this in front.
|
||||||
|
const NOT_SENT = "(not sent) ";
|
||||||
const DAY_SECONDS = 86400;
|
const DAY_SECONDS = 86400;
|
||||||
const MAX_TEXT = 600;
|
const MAX_TEXT = 600;
|
||||||
const PAGE = 100;
|
const PAGE = 100;
|
||||||
@@ -40,28 +46,69 @@ const prune = () => {
|
|||||||
|
|
||||||
const load = () => {
|
const load = () => {
|
||||||
db().exec(SCHEMA);
|
db().exec(SCHEMA);
|
||||||
|
// lines the filter stopped are marked, and found by a small index of their own.
|
||||||
|
if (!db().prepare("PRAGMA table_info(chat_log)").all().some(column => column.name === "stopped")) {
|
||||||
|
db().exec("ALTER TABLE chat_log ADD COLUMN stopped INTEGER NOT NULL DEFAULT 0");
|
||||||
|
db().prepare("UPDATE chat_log SET stopped = 1 WHERE substr(text, 1, ?) = ?").run(NOT_SENT.length, NOT_SENT);
|
||||||
|
}
|
||||||
|
db().exec("CREATE INDEX IF NOT EXISTS chat_log_stopped ON chat_log (at) WHERE stopped = 1");
|
||||||
prune();
|
prune();
|
||||||
setInterval(prune, DAY_SECONDS * 1000 / 4).unref();
|
setInterval(prune, DAY_SECONDS * 1000 / 4).unref();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const stoppedFlag = text => (String(text).startsWith(NOT_SENT) ? 1 : 0);
|
||||||
|
|
||||||
// A line said in `room` (its name as the world knows it), or with `to` a
|
// A line said in `room` (its name as the world knows it), or with `to` a
|
||||||
// whisper to that player.
|
// whisper to that player.
|
||||||
const record = (account, room, text, to = "") => {
|
const record = (account, room, text, to = "") => {
|
||||||
if (config.chatLogDays <= 0) {
|
if (config.chatLogDays <= 0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
db().prepare("INSERT INTO chat_log (at, account_id, username, room, kind, to_name, text) VALUES (?, ?, ?, ?, ?, ?, ?)")
|
db().prepare("INSERT INTO chat_log (at, account_id, username, room, kind, to_name, text, stopped) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
|
||||||
.run(now(), account.id, account.username, String(room || ""), to ? WHISPER : CHAT, to, String(text).slice(0, MAX_TEXT));
|
.run(now(), account.id, account.username, String(room || ""), to ? WHISPER : CHAT, to, String(text).slice(0, MAX_TEXT), stoppedFlag(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});
|
// A Jam-a-Gram's words (`kind` JAMAGRAM), or a post on a Jammer Wall
|
||||||
|
// (WALL): `to` is who it was sent to, or whose wall it is.
|
||||||
|
const recordTo = (account, kind, to, text) => {
|
||||||
|
if (config.chatLogDays <= 0 || !KINDS.includes(kind)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
db().prepare("INSERT INTO chat_log (at, account_id, username, room, kind, to_name, text, stopped) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
|
||||||
|
.run(now(), account.id, account.username, "", kind, String(to || ""), String(text).slice(0, MAX_TEXT), stoppedFlag(text));
|
||||||
|
};
|
||||||
|
|
||||||
|
const row = line => ({id: line.id, at: line.at, username: line.username, room: line.room, kind: line.kind, to: line.to_name,
|
||||||
|
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
|
// 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.
|
// to, or sent to), by room, by words in them, by kind (one of KINDS, or
|
||||||
const search = ({username = "", room = "", text = "", before = 0}) => {
|
// "notsent" for what the filter stopped), from `until` (seconds) back, and
|
||||||
|
// `before` an id for the next page. `direction` narrows the username to
|
||||||
|
// what they sent ("sent") or what was sent to them ("received").
|
||||||
|
const search = ({username = "", room = "", text = "", kind = "", direction = "", until = 0, before = 0}) => {
|
||||||
const where = [];
|
const where = [];
|
||||||
const values = [];
|
const values = [];
|
||||||
if (username) {
|
if (KINDS.includes(kind)) {
|
||||||
|
where.push("kind = ?");
|
||||||
|
values.push(kind);
|
||||||
|
}
|
||||||
|
else if (kind === "notsent") {
|
||||||
|
where.push("stopped = 1");
|
||||||
|
}
|
||||||
|
if (until > 0) {
|
||||||
|
where.push("at <= ?");
|
||||||
|
values.push(Math.floor(until));
|
||||||
|
}
|
||||||
|
if (username && direction === "sent") {
|
||||||
|
where.push("username = ? COLLATE NOCASE");
|
||||||
|
values.push(username);
|
||||||
|
}
|
||||||
|
else if (username && direction === "received") {
|
||||||
|
where.push("to_name = ? COLLATE NOCASE");
|
||||||
|
values.push(username);
|
||||||
|
}
|
||||||
|
else if (username) {
|
||||||
where.push("(username = ? COLLATE NOCASE OR to_name = ? COLLATE NOCASE)");
|
where.push("(username = ? COLLATE NOCASE OR to_name = ? COLLATE NOCASE)");
|
||||||
values.push(username, username);
|
values.push(username, username);
|
||||||
}
|
}
|
||||||
@@ -87,9 +134,9 @@ const around = id => {
|
|||||||
if (!line) {
|
if (!line) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const [same, values] = line.kind === WHISPER
|
const [same, values] = line.kind === CHAT
|
||||||
? ["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]]
|
||||||
: ["kind = ? AND room = ?", [CHAT, line.room]];
|
: ["kind = ? AND ((username = ? AND to_name = ?) OR (username = ? AND to_name = ?))", [line.kind, line.username, line.to_name, line.to_name, line.username]];
|
||||||
const earlier = db().prepare(`SELECT * FROM chat_log WHERE ${same} AND id < ? ORDER BY id DESC LIMIT ?`).all(...values, line.id, AROUND).reverse();
|
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);
|
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)};
|
return {line: row(line), lines: [...earlier, line, ...later].map(row)};
|
||||||
@@ -99,9 +146,19 @@ const around = id => {
|
|||||||
// of their data a player may ask for (lib/manage.js).
|
// 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);
|
const saidBy = account => db().prepare("SELECT * FROM chat_log WHERE account_id = ? ORDER BY id").all(account.id).map(row);
|
||||||
|
|
||||||
|
// how many of an account's lines the server's filter stopped, in the last
|
||||||
|
// `days` days.
|
||||||
|
const notSentCount = (account, days) => db().prepare("SELECT COUNT(*) AS n FROM chat_log WHERE account_id = ? AND at > ? AND stopped = 1")
|
||||||
|
.get(account.id, now() - days * DAY_SECONDS).n;
|
||||||
|
|
||||||
|
// those the filter stopped most often in the last `days` days: [{username, count, last}].
|
||||||
|
const mostStopped = (days, limit) => db().prepare(`SELECT username, COUNT(*) AS count, MAX(at) AS last FROM chat_log
|
||||||
|
WHERE stopped = 1 AND at > ? GROUP BY account_id ORDER BY count DESC LIMIT ?`)
|
||||||
|
.all(now() - days * DAY_SECONDS, limit).map(entry => ({username: entry.username, count: entry.count, last: entry.last}));
|
||||||
|
|
||||||
// an account being deleted: what it said goes with it.
|
// an account being deleted: what it said goes with it.
|
||||||
const forget = account => {
|
const forget = account => {
|
||||||
db().prepare("DELETE FROM chat_log WHERE account_id = ?").run(account.id);
|
db().prepare("DELETE FROM chat_log WHERE account_id = ?").run(account.id);
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = {load, record, search, around, saidBy, forget, PAGE};
|
module.exports = {load, record, recordTo, search, around, saidBy, notSentCount, mostStopped, forget, PAGE, JAMAGRAM, WALL, NOT_SENT};
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
// typed chat made fit to read before anyone sees it (lib/world.js, pubMsg):
|
||||||
|
// not a filter of what is said (that is lib/chatfilter.js) but of how much
|
||||||
|
// of it there is. a key held down ("aaaaaaaaaa..."), a word said over and
|
||||||
|
// over, one long run of letters with no space, a line all in capitals, a
|
||||||
|
// wall of emoji: each is cut down, and the line still goes. the same line
|
||||||
|
// said again and again in a short while does not.
|
||||||
|
|
||||||
|
const MAX_RUN = 5; // the same character this many times at most ("nooooo")
|
||||||
|
const MAX_REPEAT = 4; // the same word or emoji this many times in a row
|
||||||
|
const MAX_WORD = 32; // letters with no space between
|
||||||
|
const MAX_EMOJI = 12; // emoji in a line ("\{1f600}", as the client sends them)
|
||||||
|
const SHOUT_LENGTH = 12; // a line this long or more ...
|
||||||
|
const SHOUT_SHARE = 0.7; // ... with this share of its letters capitals is lowered
|
||||||
|
const REPEAT_LINES = 3; // the last few lines a player said ...
|
||||||
|
const REPEAT_MS = 20000; // ... within this long: one of those again is not sent
|
||||||
|
|
||||||
|
const EMOJI = /\\\{[0-9a-f]{2,6}(?:-[0-9a-f]{2,6}){0,9}\}/g;
|
||||||
|
|
||||||
|
// the line made tidy. emoji tags count as one character each here.
|
||||||
|
const tidy = text => {
|
||||||
|
// every emoji as one character for now (a private-use one), so that the
|
||||||
|
// rules below see it as one: put back at the end
|
||||||
|
const emoji = [];
|
||||||
|
let line = String(text).replace(EMOJI, tag => {
|
||||||
|
emoji.push(tag);
|
||||||
|
return String.fromCharCode(0xE000);
|
||||||
|
});
|
||||||
|
// a character held down (not a digit: "1000000" is a number)
|
||||||
|
line = line.replace(new RegExp(`(.)\\1{${MAX_RUN},}`, "gu"), (run, char) => (/\d/.test(char) ? run : char.repeat(MAX_RUN)));
|
||||||
|
// one long run with no space
|
||||||
|
line = line.split(" ").map(word => (word.length > MAX_WORD ? word.slice(0, MAX_WORD) : word)).join(" ");
|
||||||
|
// the same word (or emoji) over and over: in a row, with or without spaces
|
||||||
|
line = line.replace(new RegExp(`((?:\\S+?)\\s*)\\1{${MAX_REPEAT},}`, "giu"), (run, once) => (/\d/.test(once) ? run : once.repeat(MAX_REPEAT)));
|
||||||
|
// shouting
|
||||||
|
const letters = line.replace(/[^A-Za-z]/g, "");
|
||||||
|
if (letters.length >= SHOUT_LENGTH && letters.replace(/[^A-Z]/g, "").length / letters.length >= SHOUT_SHARE) {
|
||||||
|
line = line.toLowerCase();
|
||||||
|
}
|
||||||
|
// the emoji back, no more than MAX_EMOJI of them
|
||||||
|
let kept = 0;
|
||||||
|
let at = 0;
|
||||||
|
line = line.replace(new RegExp(String.fromCharCode(0xE000), "g"), () => {
|
||||||
|
const tag = emoji[at++];
|
||||||
|
return kept++ < MAX_EMOJI ? tag : "";
|
||||||
|
});
|
||||||
|
return line.replace(/\s{2,}/g, " ").trim();
|
||||||
|
};
|
||||||
|
|
||||||
|
// was this line said by them just now (one of their last few, a short while
|
||||||
|
// ago)? kept on the session, as recentChat is.
|
||||||
|
const repeated = (session, line) => {
|
||||||
|
const now = Date.now();
|
||||||
|
const said = (session.saidLately || []).filter(entry => now - entry.at < REPEAT_MS);
|
||||||
|
const again = said.some(entry => entry.line.toLowerCase() === line.toLowerCase());
|
||||||
|
session.saidLately = [...said, {line, at: now}].slice(-REPEAT_LINES);
|
||||||
|
return again;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {tidy, repeated};
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
// The style travels with a chat line, rather than with an avatar-create
|
||||||
|
// packet, so a new choice takes effect immediately and is seen by everybody
|
||||||
|
// who sees that line. Keep it small and entirely server-generated: clients
|
||||||
|
// never get to choose the fields sent to other players.
|
||||||
|
const DEFAULT = Object.freeze({background: "ffffff", accent: "dfe8ff", text: "445559", border: "9aabb0", opacity: 75,
|
||||||
|
animation: "none", speed: 100, gradient: "linear", angle: 45, strength: 100, outline: 1,
|
||||||
|
stops: "ffffff:0;dfe8ff:100"});
|
||||||
|
const ANIMATIONS = new Set(["none", "pulse", "shimmer", "flow", "rainbow"]);
|
||||||
|
const GRADIENTS = new Set(["solid", "linear", "radial"]);
|
||||||
|
const COLOR = /^[0-9a-f]{6}$/i;
|
||||||
|
|
||||||
|
const color = (value, fallback) => typeof value === "string" && COLOR.test(value) ? value.toLowerCase() : fallback;
|
||||||
|
const number = (value, fallback, low, high) => Number.isInteger(value) && value >= low && value <= high ? value : fallback;
|
||||||
|
const direction = value => {
|
||||||
|
const angle = number(value, DEFAULT.angle, 0, 315);
|
||||||
|
return angle % 45 === 0 ? angle : DEFAULT.angle;
|
||||||
|
};
|
||||||
|
|
||||||
|
const stops = (value, background, accent) => {
|
||||||
|
if (typeof value === "string") {
|
||||||
|
const parsed = value.split(";").map(stop => {
|
||||||
|
const match = /^([0-9a-f]{6}):(100|[1-9]?\d)$/i.exec(stop);
|
||||||
|
return match ? {color: match[1].toLowerCase(), position: Number(match[2])} : null;
|
||||||
|
});
|
||||||
|
if (parsed.length >= 2 && parsed.length <= 5 && parsed.every(Boolean)
|
||||||
|
&& parsed[0].position === 0 && parsed.at(-1).position === 100
|
||||||
|
&& parsed.every((stop, index) => index === 0 || stop.position > parsed[index - 1].position)) {
|
||||||
|
return parsed.map(stop => `${stop.color}:${stop.position}`).join(";");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return `${background}:0;${accent}:100`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const normalize = value => {
|
||||||
|
const source = value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
||||||
|
let background = color(source.background, DEFAULT.background);
|
||||||
|
let accent = color(source.accent, DEFAULT.accent);
|
||||||
|
const gradientStops = stops(source.stops, background, accent);
|
||||||
|
const stopParts = gradientStops.split(";");
|
||||||
|
background = stopParts[0].slice(0, 6);
|
||||||
|
accent = stopParts.at(-1).slice(0, 6);
|
||||||
|
return {
|
||||||
|
background,
|
||||||
|
accent,
|
||||||
|
text: color(source.text, DEFAULT.text),
|
||||||
|
border: color(source.border, DEFAULT.border),
|
||||||
|
opacity: number(source.opacity, DEFAULT.opacity, 25, 100),
|
||||||
|
animation: ANIMATIONS.has(source.animation) ? source.animation : DEFAULT.animation,
|
||||||
|
speed: number(source.speed, DEFAULT.speed, 40, 300),
|
||||||
|
gradient: GRADIENTS.has(source.gradient) ? source.gradient : DEFAULT.gradient,
|
||||||
|
angle: direction(source.angle),
|
||||||
|
strength: number(source.strength, DEFAULT.strength, 0, 100),
|
||||||
|
outline: number(source.outline, DEFAULT.outline, 0, 4),
|
||||||
|
stops: gradientStops,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const same = (one, two) => Object.keys(DEFAULT).every(key => one[key] === two[key]);
|
||||||
|
|
||||||
|
// `normalize` is intentionally forgiving when old account data is loaded.
|
||||||
|
// Incoming editor requests are not: every field must already be canonical.
|
||||||
|
const valid = value => Boolean(value) && typeof value === "object" && !Array.isArray(value)
|
||||||
|
&& Object.keys(DEFAULT).every(key => value[key] === normalize(value)[key]);
|
||||||
|
|
||||||
|
const fields = value => {
|
||||||
|
const style = normalize(value);
|
||||||
|
return [style.background, style.accent, style.text, style.border, style.opacity, style.animation, style.speed,
|
||||||
|
style.gradient, style.angle, style.strength, style.outline, style.stops];
|
||||||
|
};
|
||||||
|
|
||||||
|
// Twelve comma-separated, URL-safe fields; empty means the original game bubble.
|
||||||
|
const packet = value => {
|
||||||
|
const style = normalize(value);
|
||||||
|
return same(style, DEFAULT) ? "" : fields(style).join(",");
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {DEFAULT, normalize, valid, fields, packet};
|
||||||
+134
@@ -0,0 +1,134 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const accounts = require("./accounts.js");
|
||||||
|
const defpacks = require("./defpacks.js");
|
||||||
|
|
||||||
|
// codes players type into the game's "Redeem Code" window
|
||||||
|
// (gameRedemption.CodeRedemptionPopup, "grc" in lib/world.js), made in the
|
||||||
|
// admin panel. a code gives one thing: a clothing item (in a colour), a den
|
||||||
|
// item, gems or diamonds, as a gift from Burrow HQ (lib/ecards.js
|
||||||
|
// sendFromHq). each account may use a code once; a code may also have an
|
||||||
|
// end to how many times it is used in all, and is then spent.
|
||||||
|
|
||||||
|
const SCHEMA = `
|
||||||
|
CREATE TABLE IF NOT EXISTS redeem_codes (
|
||||||
|
code TEXT PRIMARY KEY,
|
||||||
|
kind TEXT NOT NULL,
|
||||||
|
item INTEGER NOT NULL DEFAULT 0,
|
||||||
|
amount INTEGER NOT NULL DEFAULT 0,
|
||||||
|
color INTEGER,
|
||||||
|
uses INTEGER NOT NULL DEFAULT 0,
|
||||||
|
used INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS redeem_uses (
|
||||||
|
code TEXT NOT NULL,
|
||||||
|
account_id INTEGER NOT NULL,
|
||||||
|
at INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (code, account_id)
|
||||||
|
);
|
||||||
|
`;
|
||||||
|
|
||||||
|
const KINDS = ["clothing", "den", "gems", "diamonds"];
|
||||||
|
const CODE = /^[A-Z0-9-]{3,32}$/; // what the game's box lets be typed (and in capitals)
|
||||||
|
const MAX_AMOUNT = 10000000;
|
||||||
|
const MAX_USES = 1000000;
|
||||||
|
|
||||||
|
let made = false;
|
||||||
|
const db = () => {
|
||||||
|
const database = accounts.database();
|
||||||
|
if (!made) {
|
||||||
|
database.exec(SCHEMA);
|
||||||
|
made = true;
|
||||||
|
}
|
||||||
|
return database;
|
||||||
|
};
|
||||||
|
const now = () => Math.floor(Date.now() / 1000);
|
||||||
|
const normal = code => String(code || "").trim().toUpperCase();
|
||||||
|
|
||||||
|
const row = entry => ({code: entry.code, kind: entry.kind, item: entry.item, amount: entry.amount, color: entry.color,
|
||||||
|
uses: entry.uses, used: entry.used, createdAt: entry.created_at});
|
||||||
|
|
||||||
|
const list = () => db().prepare("SELECT * FROM redeem_codes ORDER BY created_at DESC").all().map(row);
|
||||||
|
|
||||||
|
// {code, kind, item, amount, color, uses}: returns {ok} or {error}.
|
||||||
|
const create = fields => {
|
||||||
|
const code = normal(fields.code);
|
||||||
|
const kind = String(fields.kind || "");
|
||||||
|
const uses = Number(fields.uses) || 0;
|
||||||
|
if (!CODE.test(code)) {
|
||||||
|
return {error: "A code is 3 to 32 letters, digits and dashes."};
|
||||||
|
}
|
||||||
|
if (!KINDS.includes(kind)) {
|
||||||
|
return {error: "A code gives clothing, a den item, gems or diamonds."};
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(uses) || uses < 0 || uses > MAX_USES) {
|
||||||
|
return {error: "Uses: 0 for any number, or how many in all."};
|
||||||
|
}
|
||||||
|
let item = 0;
|
||||||
|
let amount = 0;
|
||||||
|
let color = null;
|
||||||
|
if (kind === "clothing") {
|
||||||
|
item = Number(fields.item);
|
||||||
|
const def = defpacks.itemDef(item);
|
||||||
|
if (!def || !defpacks.clothingIds().includes(item)) {
|
||||||
|
return {error: "No clothing item with that id."};
|
||||||
|
}
|
||||||
|
const own = String(def.colors).split(",").map(Number);
|
||||||
|
const chosen = fields.color === undefined || String(fields.color).trim() === "" ? own[0] : Number(fields.color);
|
||||||
|
if (!Number.isInteger(chosen) || chosen < -0x80000000 || chosen > 0xFFFFFFFF) {
|
||||||
|
return {error: "A colour as the game writes it (a whole number), or none for the item's own."};
|
||||||
|
}
|
||||||
|
color = chosen >>> 0;
|
||||||
|
}
|
||||||
|
else if (kind === "den") {
|
||||||
|
item = Number(fields.item);
|
||||||
|
if (!defpacks.denItemIds().includes(item)) {
|
||||||
|
return {error: "No den item with that id."};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
amount = Number(fields.amount);
|
||||||
|
if (!Number.isInteger(amount) || amount < 1 || amount > MAX_AMOUNT) {
|
||||||
|
return {error: "An amount from 1 to 10,000,000."};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (db().prepare("SELECT 1 FROM redeem_codes WHERE code = ?").get(code)) {
|
||||||
|
return {error: "That code is taken."};
|
||||||
|
}
|
||||||
|
db().prepare("INSERT INTO redeem_codes (code, kind, item, amount, color, uses, used, created_at) VALUES (?, ?, ?, ?, ?, ?, 0, ?)")
|
||||||
|
.run(code, kind, item, amount, color, uses, now());
|
||||||
|
return {ok: `${code} made.`};
|
||||||
|
};
|
||||||
|
|
||||||
|
const remove = code => db().prepare("DELETE FROM redeem_codes WHERE code = ?").run(normal(code)).changes > 0;
|
||||||
|
|
||||||
|
// a code typed in the game, for `account`: {gift} for lib/ecards.js
|
||||||
|
// sendFromHq, or {error: "unknown" | "used" | "spent"}. the use is noted.
|
||||||
|
const redeem = (account, typed) => {
|
||||||
|
const code = normal(typed);
|
||||||
|
const entry = CODE.test(code) ? db().prepare("SELECT * FROM redeem_codes WHERE code = ?").get(code) : null;
|
||||||
|
if (!entry) {
|
||||||
|
return {error: "unknown"};
|
||||||
|
}
|
||||||
|
if (db().prepare("SELECT 1 FROM redeem_uses WHERE code = ? AND account_id = ?").get(code, account.id)) {
|
||||||
|
return {error: "used"};
|
||||||
|
}
|
||||||
|
if (entry.uses > 0 && entry.used >= entry.uses) {
|
||||||
|
return {error: "spent"};
|
||||||
|
}
|
||||||
|
db().prepare("INSERT INTO redeem_uses (code, account_id, at) VALUES (?, ?, ?)").run(code, account.id, now());
|
||||||
|
db().prepare("UPDATE redeem_codes SET used = used + 1 WHERE code = ?").run(code);
|
||||||
|
const gift = entry.kind === "clothing" ? {kind: "clothing", id: entry.item, color: entry.color}
|
||||||
|
: entry.kind === "den" ? {kind: "den", id: entry.item} : {kind: entry.kind, amount: entry.amount};
|
||||||
|
return {gift, code};
|
||||||
|
};
|
||||||
|
|
||||||
|
// a use taken back, when the gift could not be sent after all
|
||||||
|
const unredeem = (account, code) => {
|
||||||
|
if (db().prepare("DELETE FROM redeem_uses WHERE code = ? AND account_id = ?").run(code, account.id).changes > 0) {
|
||||||
|
db().prepare("UPDATE redeem_codes SET used = MAX(used - 1, 0) WHERE code = ?").run(code);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {list, create, remove, redeem, unredeem, KINDS};
|
||||||
+6
-2
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
|
|
||||||
// custom colours. the game stores a colour as four palette indexes packed in
|
// custom colours. the game stores a colour as four palette indexes packed in
|
||||||
@@ -29,7 +30,7 @@ const load = () => {
|
|||||||
entries.set(row.id, row.rgb.split(",").map(Number));
|
entries.set(row.id, row.rgb.split(",").map(Number));
|
||||||
nextId = Math.max(nextId, row.id + 1);
|
nextId = Math.max(nextId, row.id + 1);
|
||||||
}
|
}
|
||||||
console.log(`[colours] ${entries.size} custom colours`);
|
console.log(`[colours] ${logText(entries.size)} custom colours`);
|
||||||
};
|
};
|
||||||
|
|
||||||
const valid = rgbs => rgbs.length === 4 && rgbs.every(value => Number.isInteger(value) && value >= 0 && value <= MAX_RGB);
|
const valid = rgbs => rgbs.length === 4 && rgbs.every(value => Number.isInteger(value) && value >= 0 && value <= MAX_RGB);
|
||||||
@@ -70,4 +71,7 @@ const chunks = (size = 200) => {
|
|||||||
// the custom range), or an entry of the table?
|
// the custom range), or an entry of the table?
|
||||||
const known = id => id < CUSTOM_BASE || id > MAX_ID || entries.has(id);
|
const known = id => id < CUSTOM_BASE || id > MAX_ID || entries.has(id);
|
||||||
|
|
||||||
module.exports = {load, allocate, chunks, known, count: () => entries.size};
|
// the four RGB values of an entry, or null.
|
||||||
|
const rgbsOf = id => entries.get(id) || null;
|
||||||
|
|
||||||
|
module.exports = {CUSTOM_BASE, load, allocate, chunks, known, rgbsOf, count: () => entries.size};
|
||||||
+500
-2
@@ -2,10 +2,16 @@
|
|||||||
|
|
||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
const chatlog = require("./chatlog.js");
|
const chatlog = require("./chatlog.js");
|
||||||
|
const customItems = require("./customitems.js");
|
||||||
|
const itemControl = require("./itemcontrol.js");
|
||||||
|
const wearRules = require("./wearrules.js");
|
||||||
|
const modNotes = require("./modnotes.js");
|
||||||
const defpacks = require("./defpacks.js");
|
const defpacks = require("./defpacks.js");
|
||||||
const disguises = require("./disguises.js");
|
const disguises = require("./disguises.js");
|
||||||
const dens = require("./dens.js");
|
const dens = require("./dens.js");
|
||||||
const {isSilenced} = require("./moderation.js");
|
const {isSilenced} = require("./moderation.js");
|
||||||
|
const modlog = require("./modlog.js");
|
||||||
|
const roles = require("./roles.js");
|
||||||
const {MAX_DEN_ITEMS, MAX_WORN, activeAvatar, wornItems} = require("./player.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
|
// things players can do by typing "!something" in the chat box, for what
|
||||||
@@ -47,7 +53,7 @@ const MAX_AGAIN = 100;
|
|||||||
// A hosted party's own name is three string ids, no use outside the game.
|
// 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);
|
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}) => {
|
module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideBlocked, refreshForOthers, travel, reloadRoom, buyAgain, ask, staffMove, setInvisible, staffModeration}) => {
|
||||||
// A plain message box with an OK button.
|
// A plain message box with an OK button.
|
||||||
const tell = (session, text) => session.sendXt("xtl", -1, String(text).replace(/%/g, " percent"));
|
const tell = (session, text) => session.sendXt("xtl", -1, String(text).replace(/%/g, " percent"));
|
||||||
|
|
||||||
@@ -68,7 +74,10 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
|
|||||||
const {account} = session;
|
const {account} = session;
|
||||||
const avatar = activeAvatar(account);
|
const avatar = activeAvatar(account);
|
||||||
const before = wornItems(account, avatar);
|
const before = wornItems(account, avatar);
|
||||||
const wanted = account.items.filter(item => invs.includes(item.inv)).slice(0, MAX_WORN);
|
// Saved outfits are a second equip route, so they obey the same rule as
|
||||||
|
// the item editor. A saved id remains in the outfit in case staff later
|
||||||
|
// remove the rule; it simply cannot be put on while blocked.
|
||||||
|
const wanted = account.items.filter(item => invs.includes(item.inv) && wearRules.mayWear(item.def, avatar.type)).slice(0, MAX_WORN);
|
||||||
const takenOff = before.filter(item => !wanted.includes(item));
|
const takenOff = before.filter(item => !wanted.includes(item));
|
||||||
account.outfitUndo = {avInvId: avatar.avInvId, items: before.map(item => item.inv)};
|
account.outfitUndo = {avInvId: avatar.avInvId, items: before.map(item => item.inv)};
|
||||||
for (const item of takenOff) {
|
for (const item of takenOff) {
|
||||||
@@ -500,6 +509,491 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
|
|||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ---- staff commands (lib/roles.js). each checks the role's permission on
|
||||||
|
// every use, and what is done is written down under the staff member's
|
||||||
|
// name, as in the moderator panel. to anyone without the permission they
|
||||||
|
// are plain chat, like any other "!word" the server does not know.
|
||||||
|
const MAX_STAFF_HOURS = 24 * 365 * 10;
|
||||||
|
const MAX_WARNING = 200;
|
||||||
|
const MAX_WARNINGS_SHOWN = 5;
|
||||||
|
const MAX_ITEMS_LISTED = 8;
|
||||||
|
const MAX_NOTES_SHOWN = 5; // "!notes": the latest, in one message box
|
||||||
|
|
||||||
|
const staffMay = (session, permission) => {
|
||||||
|
const moderation = staffModeration();
|
||||||
|
return roles.can(session.account, permission, moderation.banRemaining(session.account) !== 0);
|
||||||
|
};
|
||||||
|
|
||||||
|
// the longest run of leading words naming an online player, and the words
|
||||||
|
// after it: usernames may have spaces in them.
|
||||||
|
const splitName = words => {
|
||||||
|
for (let count = words.length; count > 0; count--) {
|
||||||
|
const target = findOnline(words.slice(0, count).join(" "));
|
||||||
|
if (target) {
|
||||||
|
return {target, rest: words.slice(count)};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {target: null, rest: words};
|
||||||
|
};
|
||||||
|
|
||||||
|
// the same for any account, online or not.
|
||||||
|
const splitAccount = words => {
|
||||||
|
for (let count = words.length; count > 0; count--) {
|
||||||
|
const account = accounts.byName(words.slice(0, count).join(" "));
|
||||||
|
if (account) {
|
||||||
|
return account;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// finds the player the command is about, and checks the staff member may
|
||||||
|
// act on them (`onStaff`: also on staff below their rank).
|
||||||
|
const withTarget = (session, words, usage, onStaff, run) => {
|
||||||
|
const {target, rest} = splitName(words);
|
||||||
|
if (!words.length) {
|
||||||
|
tell(session, usage);
|
||||||
|
}
|
||||||
|
else if (!target) {
|
||||||
|
tell(session, `${words.join(" ")} is not online.`);
|
||||||
|
}
|
||||||
|
else if (target === session) {
|
||||||
|
tell(session, "That is you.");
|
||||||
|
}
|
||||||
|
else if (onStaff && !roles.outranks(session.account, target.account)) {
|
||||||
|
tell(session, "Staff of your rank or above are for someone higher up to deal with.");
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
run(target, rest);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const logged = (session, action, target, detail = "") =>
|
||||||
|
modlog.record(session.account.username, `${action} (in game)`, target.account.username, detail);
|
||||||
|
|
||||||
|
// what lib/itemcontrol.js tells about items taken.
|
||||||
|
const worldForItems = {itemsTaken: (...args) => require("./world.js").itemsTaken(...args)};
|
||||||
|
|
||||||
|
const lockCommand = (session, words, locked) => {
|
||||||
|
const [kind, id] = [(words[0] || "").toLowerCase(), words[1]];
|
||||||
|
if (words.length !== 2) {
|
||||||
|
tell(session, `Use: !${locked ? "lock" : "unlock"} clothing|den ID`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = itemControl.setLocked(kind, id, locked);
|
||||||
|
tell(session, result.error || result.ok);
|
||||||
|
if (result.ok) {
|
||||||
|
modlog.record(session.account.username, locked ? "item locked (in game)" : "item unlocked (in game)", "", `${kind} ${id}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// an account named by the first words (a name may have spaces: the longest
|
||||||
|
// that is one), and the words after it.
|
||||||
|
const accountAndRest = words => {
|
||||||
|
for (let count = words.length; count > 0; count--) {
|
||||||
|
const account = accounts.byName(words.slice(0, count).join(" "));
|
||||||
|
if (account) {
|
||||||
|
return {account, rest: words.slice(count)};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {account: null, rest: words};
|
||||||
|
};
|
||||||
|
|
||||||
|
const staffCommands = {
|
||||||
|
// A short-lived room control for owners, admins and developers. It uses
|
||||||
|
// the avatar protocol rather than persisting any player appearance.
|
||||||
|
roomfx: {
|
||||||
|
permission: "room.effects",
|
||||||
|
run(session, words) {
|
||||||
|
const room = session.room;
|
||||||
|
const effect = (words[0] || "").toLowerCase();
|
||||||
|
if (!room || !["small", "normal", "big", "rainbow", "clear"].includes(effect)) {
|
||||||
|
tell(session, "Use: !roomfx small, !roomfx normal, !roomfx big, !roomfx rainbow, or !roomfx clear");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const send = (type, value) => {
|
||||||
|
for (const target of room.sessions) {
|
||||||
|
for (const viewer of room.sessions) {
|
||||||
|
viewer.sendXt("uc", room.id, target.id, String(value), type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const stopRainbow = () => {
|
||||||
|
if (room.roomEffectTimer) {
|
||||||
|
clearInterval(room.roomEffectTimer);
|
||||||
|
delete room.roomEffectTimer;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if (effect === "rainbow") {
|
||||||
|
stopRainbow();
|
||||||
|
let hue = 0;
|
||||||
|
room.roomEffectTimer = setInterval(() => {
|
||||||
|
if (room.sessions.size === 0) {
|
||||||
|
stopRainbow();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const colour = [0xFF4040, 0xFFB340, 0xF8FF40, 0x50E860, 0x40CFFF, 0x7560FF, 0xDC55FF][hue++ % 7];
|
||||||
|
send(8, colour);
|
||||||
|
}, 350);
|
||||||
|
room.roomEffectTimer.unref();
|
||||||
|
tell(session, "Rainbow effect started for everyone in this room. !roomfx clear stops it.");
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
stopRainbow();
|
||||||
|
if (effect === "small" || effect === "big" || effect === "normal") {
|
||||||
|
send(14, effect === "small" ? 0.7 : effect === "big" ? 1.35 : 1);
|
||||||
|
tell(session, `Everyone in this room is now ${effect === "normal" ? "normal size" : effect}.`);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
send(8, 0);
|
||||||
|
send(14, 1);
|
||||||
|
tell(session, "Room effects cleared.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
modlog.record(session.account.username, "room effect (in game)", "", `${effect}: ${roomTitle(room)}`);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// "!item clothing|den ID NAME": a new item made from the game's item ID
|
||||||
|
// (lib/customitems.js), free, every colour of the one it is made from;
|
||||||
|
// everyone has it at once. the moderator panel's Items page does more.
|
||||||
|
// "!item list": the latest made.
|
||||||
|
item: {
|
||||||
|
permission: "items.create",
|
||||||
|
run(session, words) {
|
||||||
|
const usage = "Use: !item clothing|den ID NAME, or !item list";
|
||||||
|
if ((words[0] || "").toLowerCase() === "list") {
|
||||||
|
const latest = customItems.list().slice(0, MAX_ITEMS_LISTED)
|
||||||
|
.map(entry => `${entry.id} ${entry.name} (${entry.kind === "den" ? "den" : "clothing"}${entry.inShop ? "" : ", off sale"})`);
|
||||||
|
tell(session, latest.length ? `Latest items made: ${latest.join("; ")}` : "No items made yet.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const kind = (words[0] || "").toLowerCase();
|
||||||
|
if (!customItems.KINDS.includes(kind) || !/^\d+$/.test(words[1] || "") || words.length < 3) {
|
||||||
|
tell(session, usage);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = customItems.create(kind, {base: words[1], name: words.slice(2).join(" ")}, session.account.username);
|
||||||
|
if (result.error) {
|
||||||
|
tell(session, result.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const {item} = result;
|
||||||
|
tell(session, `Made ${item.name}, ${kind === "den" ? "den item" : "clothing"} ${item.id}. It is in the item finder now.`);
|
||||||
|
modlog.record(session.account.username, "item made (in game)", "", `${kind} ${item.id} ${item.name}`);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
staff: {
|
||||||
|
permission: "staff.list",
|
||||||
|
run(session) {
|
||||||
|
const on = players().filter(other => roles.isActiveStaff(other.account))
|
||||||
|
.map(other => `${other.account.username} (${roles.ROLES[roles.roleOf(other.account)].label})`);
|
||||||
|
tell(session, on.length ? `Staff online: ${on.join(", ")}` : "No staff online.");
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// Opens the same in-game moderation window as a player's card. This is
|
||||||
|
// useful when a moderator already knows the name and does not need to
|
||||||
|
// hunt through search results first.
|
||||||
|
mod: {
|
||||||
|
permission: "player.view",
|
||||||
|
run(session, words) {
|
||||||
|
const target = words.length ? findOnline(words.join(" ")) : null;
|
||||||
|
if (!target) {
|
||||||
|
tell(session, words.length ? `${words.join(" ")} is not online.` : "Use: !mod PLAYER");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (target.account !== session.account && roles.roleOf(target.account) && !roles.outranks(session.account, target.account)) {
|
||||||
|
tell(session, "Staff of your rank or above are for someone higher up to deal with.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
session.sendXt("xui", -1, "moderate", target.account.username);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// Owners, admins and developers get the room-effects panel from chat.
|
||||||
|
// `host` is an intuitive alias for event hosts.
|
||||||
|
event: {
|
||||||
|
permission: "room.effects",
|
||||||
|
run(session) {
|
||||||
|
session.sendXt("xui", -1, "event");
|
||||||
|
},
|
||||||
|
},
|
||||||
|
host: {
|
||||||
|
permission: "room.effects",
|
||||||
|
run(session) {
|
||||||
|
session.sendXt("xui", -1, "event");
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// "!note PLAYER text": a note for the other staff (lib/modnotes.js),
|
||||||
|
// never shown to the player. "!notes PLAYER": the latest few.
|
||||||
|
note: {
|
||||||
|
permission: "player.view",
|
||||||
|
run(session, words) {
|
||||||
|
const {account, rest} = accountAndRest(words);
|
||||||
|
if (!account || !rest.length) {
|
||||||
|
tell(session, account || !words.length ? "Use: !note PLAYER text" : `No player called ${words[0]}.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (account === session.account) {
|
||||||
|
tell(session, "That is you.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (roles.roleOf(account) && !roles.outranks(session.account, account)) {
|
||||||
|
tell(session, "Staff of your rank or above are for someone higher up to deal with.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = modNotes.add(account, session.account.username, rest.join(" "));
|
||||||
|
if (result.error) {
|
||||||
|
tell(session, result.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tell(session, `Note on ${account.username} added.`);
|
||||||
|
modlog.record(session.account.username, "note (in game)", account.username, result.note.text);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
notes: {
|
||||||
|
permission: "player.view",
|
||||||
|
run(session, words) {
|
||||||
|
const account = words.length ? accounts.byName(words.join(" ")) : null;
|
||||||
|
if (!account) {
|
||||||
|
tell(session, words.length ? `No player called ${words.join(" ")}.` : "Use: !notes PLAYER");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const latest = modNotes.list(account).slice(0, MAX_NOTES_SHOWN)
|
||||||
|
.map(note => `${new Date(note.at * 1000).toISOString().slice(0, 10)} ${note.by}: ${note.text}`);
|
||||||
|
tell(session, latest.length ? `Notes on ${account.username}: ${latest.join(" | ")}` : `No notes on ${account.username}.`);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// "!invisible": unseen by players in every room until said again (staff
|
||||||
|
// still see them), as the game's own moderators could be.
|
||||||
|
invisible: {
|
||||||
|
permission: "staff.invisible",
|
||||||
|
run(session) {
|
||||||
|
setInvisible(session, !session.invisible);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
reject: {
|
||||||
|
permission: "player.names",
|
||||||
|
run(session, words) {
|
||||||
|
withTarget(session, words, "Use: !reject PLAYER", true, target => {
|
||||||
|
if (target.account.nameRejected) {
|
||||||
|
tell(session, `${target.account.username}'s name is already rejected.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
staffModeration().actions.rejectName(target.account, session.account.username);
|
||||||
|
tell(session, `${target.account.username} was signed out and must choose a new name.`);
|
||||||
|
logged(session, "rejected username", target);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// "!lock clothing|den ID", "!unlock clothing|den ID", "!locked": items
|
||||||
|
// kept out of the item finder for players (lib/itemcontrol.js).
|
||||||
|
lock: {
|
||||||
|
permission: "items.create",
|
||||||
|
run(session, words) {
|
||||||
|
lockCommand(session, words, true);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
unlock: {
|
||||||
|
permission: "items.create",
|
||||||
|
run(session, words) {
|
||||||
|
lockCommand(session, words, false);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
locked: {
|
||||||
|
permission: "items.create",
|
||||||
|
run(session) {
|
||||||
|
const list = itemControl.lockedList().slice(0, MAX_ITEMS_LISTED)
|
||||||
|
.map(entry => `${entry.kind} ${entry.id} ${entry.name || "(no name)"}`);
|
||||||
|
tell(session, list.length ? `Locked out of the item finder: ${list.join("; ")}` : "Nothing is locked out of the item finder.");
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// "!take PLAYER clothing|den ID": every one of that item, out of their
|
||||||
|
// inventory, online or not.
|
||||||
|
take: {
|
||||||
|
permission: "items.create",
|
||||||
|
run(session, words) {
|
||||||
|
const usage = "Use: !take PLAYER clothing|den ID";
|
||||||
|
// the name may have spaces: the kind and the id are the last two words.
|
||||||
|
const [kind, id] = words.slice(-2).map(word => word.toLowerCase());
|
||||||
|
const account = words.length >= 3 ? accounts.byName(words.slice(0, -2).join(" ")) : null;
|
||||||
|
if (words.length < 3 || !/^\d+$/.test(id)) {
|
||||||
|
tell(session, usage);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!account) {
|
||||||
|
tell(session, `No player called ${words.slice(0, -2).join(" ")}.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (account !== session.account && !roles.outranks(session.account, account) && roles.roleOf(account)) {
|
||||||
|
tell(session, "Staff of your rank or above are for someone higher up to deal with.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = itemControl.take(account.username, kind, id, worldForItems);
|
||||||
|
tell(session, result.error || result.ok);
|
||||||
|
if (result.ok) {
|
||||||
|
modlog.record(session.account.username, "item taken (in game)", account.username, `${kind} ${id} x${result.count}`);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
summon: {
|
||||||
|
permission: "player.summon",
|
||||||
|
run(session, words) {
|
||||||
|
withTarget(session, words, "Use: !summon PLAYER", true, target => {
|
||||||
|
const result = staffMove(target.account.username, session.account.username);
|
||||||
|
if (!result.ok) {
|
||||||
|
tell(session, result.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tell(session, `${target.account.username} was brought here.`);
|
||||||
|
logged(session, "summon", target, result.room);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
goto: {
|
||||||
|
permission: "player.goto",
|
||||||
|
run(session, words) {
|
||||||
|
withTarget(session, words, "Use: !goto PLAYER", false, target => {
|
||||||
|
const result = staffMove(session.account.username, target.account.username);
|
||||||
|
if (!result.ok) {
|
||||||
|
tell(session, result.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
logged(session, "goto", target, result.room);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
kick: {
|
||||||
|
permission: "player.kick",
|
||||||
|
run(session, words) {
|
||||||
|
withTarget(session, words, "Use: !kick PLAYER", true, target => {
|
||||||
|
const name = target.account.username;
|
||||||
|
if (staffModeration().actions.kick(target.account)) {
|
||||||
|
tell(session, `${name} was disconnected.`);
|
||||||
|
logged(session, "kick", target);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
tell(session, `${name} is not online.`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// "!silence PLAYER HOURS" (0: until lifted), "!silence PLAYER off".
|
||||||
|
silence: {
|
||||||
|
permission: "chat.silence",
|
||||||
|
run(session, words) {
|
||||||
|
withTarget(session, words, "Use: !silence PLAYER HOURS (0 until lifted), or !silence PLAYER off", true, (target, rest) => {
|
||||||
|
const {actions, PERMANENT} = staffModeration();
|
||||||
|
const name = target.account.username;
|
||||||
|
const amount = (rest[0] || "").toLowerCase();
|
||||||
|
if (amount === "off") {
|
||||||
|
actions.silence(target.account, 0);
|
||||||
|
tell(session, `${name} can chat again.`);
|
||||||
|
logged(session, "unsilence", target);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const hours = /^\d{1,6}$/.test(amount) ? Number(amount) : NaN;
|
||||||
|
if (!(hours >= 0 && hours <= MAX_STAFF_HOURS)) {
|
||||||
|
tell(session, "Use: !silence PLAYER HOURS (0 until lifted), or !silence PLAYER off");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
actions.silence(target.account, hours === 0 ? PERMANENT : hours * 3600);
|
||||||
|
tell(session, hours === 0 ? `${name} cannot chat until it is lifted.` : `${name} cannot chat for ${hours} hours.`);
|
||||||
|
logged(session, "silence", target, String(hours || "until lifted"));
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// "!warn PLAYER [REASON] [note]": a warning, kept on the account and
|
||||||
|
// shown with the game's own warning popup. REASON is behavior (the
|
||||||
|
// default), bullying, personal or scamming; the note is for staff.
|
||||||
|
// "!warn PLAYER custom TEXT": a warning in the staff member's own
|
||||||
|
// words, which is what the player is shown.
|
||||||
|
warn: {
|
||||||
|
permission: "player.warn",
|
||||||
|
run(session, words) {
|
||||||
|
const usage = `Use: !warn PLAYER [${staffModeration().WARNINGS.join("|")}] [note], or !warn PLAYER custom TEXT`;
|
||||||
|
withTarget(session, words, usage, true, (target, rest) => {
|
||||||
|
const {WARNINGS, actions} = staffModeration();
|
||||||
|
const asked = (rest[0] || "").toLowerCase();
|
||||||
|
const reason = WARNINGS.includes(asked) ? asked : "behavior";
|
||||||
|
const note = (WARNINGS.includes(asked) ? rest.slice(1) : rest).join(" ").trim().slice(0, MAX_WARNING);
|
||||||
|
if (reason === "custom" && !note) {
|
||||||
|
tell(session, "Use: !warn PLAYER custom TEXT (the text is what they are shown)");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = actions.warn(target.account, reason, session.account.username, note);
|
||||||
|
tell(session, `${target.account.username} warned (${reason}): warning ${result.count}.`
|
||||||
|
+ (result.silencedMinutes ? ` Silenced for ${result.silencedMinutes} minutes, for that many warnings.` : ""));
|
||||||
|
logged(session, "warn", target, note ? `${reason} · ${note}` : reason);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// "!message PLAYER text": a message box from the moderators.
|
||||||
|
message: {
|
||||||
|
permission: "player.warn",
|
||||||
|
run(session, words) {
|
||||||
|
withTarget(session, words, "Use: !message PLAYER text", true, (target, rest) => {
|
||||||
|
const text = rest.join(" ").trim().slice(0, MAX_WARNING);
|
||||||
|
if (!text) {
|
||||||
|
tell(session, "Use: !message PLAYER text");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (staffModeration().actions.message(target.account, text)) {
|
||||||
|
tell(session, `Shown to ${target.account.username}.`);
|
||||||
|
logged(session, "message", target, text);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
tell(session, `${target.account.username} is not online.`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// "!unwarn PLAYER": takes back their latest warning (one given by
|
||||||
|
// mistake), online or not.
|
||||||
|
unwarn: {
|
||||||
|
permission: "player.warn",
|
||||||
|
run(session, words) {
|
||||||
|
const account = splitAccount(words);
|
||||||
|
if (!account) {
|
||||||
|
tell(session, words.length ? `No player called ${words.join(" ")}.` : "Use: !unwarn PLAYER");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (account === session.account) {
|
||||||
|
tell(session, "That is you.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!roles.outranks(session.account, account)) {
|
||||||
|
tell(session, "Staff of your rank or above are for someone higher up to deal with.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const removed = staffModeration().actions.unwarn(account);
|
||||||
|
if (!removed) {
|
||||||
|
tell(session, `${account.username} has no warnings.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tell(session, `Took back ${account.username}'s latest warning (${removed.reason}).`);
|
||||||
|
modlog.record(session.account.username, "unwarn (in game)", account.username, removed.reason);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// "!warnings PLAYER": their latest warnings, online or not.
|
||||||
|
warnings: {
|
||||||
|
permission: "player.warn",
|
||||||
|
run(session, words) {
|
||||||
|
const account = splitAccount(words);
|
||||||
|
if (!account) {
|
||||||
|
tell(session, words.length ? `No player called ${words.join(" ")}.` : "Use: !warnings PLAYER");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const list = account.warnings || [];
|
||||||
|
if (!list.length) {
|
||||||
|
tell(session, `${account.username} has no warnings.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const latest = list.slice(-MAX_WARNINGS_SHOWN).reverse()
|
||||||
|
.map(entry => `${new Date(entry.at * 1000).toISOString().slice(0, 10)} ${entry.reason} by ${entry.by}${entry.note ? ` (${entry.note})` : ""}`);
|
||||||
|
tell(session, `${account.username} has ${list.length} warning${list.length === 1 ? "" : "s"}. Latest: ${latest.join("; ")}`);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
// runs `text` if it is a command. returns what to do with the chat line:
|
// 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.
|
// null to swallow it, or the text everyone should see in its place.
|
||||||
@@ -509,6 +1003,10 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
|
|||||||
}
|
}
|
||||||
const typed = text.slice(PREFIX.length).trim().split(/\s+/);
|
const typed = text.slice(PREFIX.length).trim().split(/\s+/);
|
||||||
const [name, ...words] = typed.map(word => word.toLowerCase());
|
const [name, ...words] = typed.map(word => word.toLowerCase());
|
||||||
|
if (Object.hasOwn(staffCommands, name) && staffMay(session, staffCommands[name].permission)) {
|
||||||
|
staffCommands[name].run(session, typed.slice(1));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
if (Object.hasOwn(asTyped, name) && (name !== "den" || typed.length > 1)) {
|
if (Object.hasOwn(asTyped, name) && (name !== "den" || typed.length > 1)) {
|
||||||
asTyped[name](session, typed.slice(1));
|
asTyped[name](session, typed.slice(1));
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -0,0 +1,465 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
|
const accounts = require("./accounts.js");
|
||||||
|
const defpacks = require("./defpacks.js");
|
||||||
|
const limits = require("./limits.js");
|
||||||
|
|
||||||
|
// items the staff make while the server runs, with no restart of the server
|
||||||
|
// or of anybody's game. each is an existing item's art (the clothing piece
|
||||||
|
// or den item it is made from) under an id, name, price and colours of its
|
||||||
|
// own. the server's tables and the packs new games fetch have it at once
|
||||||
|
// (defpacks.setCustomItem); games already playing are sent its def row
|
||||||
|
// ("xdi", which the patched client adds to its tables), and so is a game at
|
||||||
|
// login if its packs may be older than the item (sendAll).
|
||||||
|
//
|
||||||
|
// an item can be taken out of the shop, renamed and repriced, or deleted:
|
||||||
|
// then it goes from every inventory too (lib/itemcontrol.js).
|
||||||
|
|
||||||
|
// ids far above the game's own (clothing to about 4,600, den items to about
|
||||||
|
// 6,000), one range per pack; names go under localization ids above the
|
||||||
|
// server's other added strings (lib/defpacks.js ADDED_STRINGS, 9000001 on).
|
||||||
|
const FIRST_ID = 50000;
|
||||||
|
const STRING_BASE = {clothing: 9100000, den: 9200000};
|
||||||
|
const KINDS = ["clothing", "den"];
|
||||||
|
const MAX_NAME = 40;
|
||||||
|
const MAX_COST = 1000000;
|
||||||
|
const MAX_COLOURS = 16;
|
||||||
|
const MAX_ITEMS = 5000; // per kind
|
||||||
|
const CHUNK = 40; // def rows per "xdi" message
|
||||||
|
const TYPE_CLOTHING = "1";
|
||||||
|
const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items that can be copied: plain, mannequin
|
||||||
|
const CURRENCY_GEMS = "0";
|
||||||
|
// the fields of a def row the patched client reads from "xdi"
|
||||||
|
// (ItemXtCommManager.addItemDef, DenXtCommManager.addDenItemDef): the rest of
|
||||||
|
// the base's row is only weight, ~600 bytes a row and 5000 rows at login.
|
||||||
|
const CLIENT_FIELDS = {
|
||||||
|
clothing: ["id", "layerDefId", "layerId", "type", "value", "titleStrId", "isGiftable", "membersOnly", "itemStatus", "enviroType",
|
||||||
|
"avatarUseFlags", "recycleValue", "currencyType", "defense", "attack", "attackMediaRefId", "combatType", "modifierType",
|
||||||
|
"modifierValue", "criticalHit", "combinedCost", "colors", "availabilityStartTime", "availabilityEndTime"],
|
||||||
|
den: ["id", "abbrName", "combinedCost", "cost", "currencyType", "enviroType", "flag", "gameDefId", "itemStatus", "layer",
|
||||||
|
"mannequinAvatarDefId", "mannequinCatId", "membersOnly", "nameStrId", "parentArrayId", "promoType", "recycleValue",
|
||||||
|
"scalePercent", "sortCat", "specialType", "typeCat", "availabilityStartTime", "availabilityEndTime", "ecoPower"],
|
||||||
|
};
|
||||||
|
// how long a fetch of the packs is taken to describe a game of that address
|
||||||
|
// that logs in (sendAll). a game logs in minutes after it fetched them.
|
||||||
|
const PACKS_SEEN_MS = 2 * 3600000;
|
||||||
|
const MAX_PACKS_SEEN = 100000; // addresses
|
||||||
|
|
||||||
|
const SCHEMA = `CREATE TABLE IF NOT EXISTS custom_items (
|
||||||
|
kind TEXT NOT NULL, id INTEGER NOT NULL, base INTEGER NOT NULL, name TEXT NOT NULL,
|
||||||
|
cost INTEGER NOT NULL, members INTEGER NOT NULL, colors TEXT NOT NULL, in_shop INTEGER NOT NULL,
|
||||||
|
created_by TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (kind, id))`;
|
||||||
|
|
||||||
|
const items = new Map(KINDS.map(kind => [kind, new Map()])); // kind -> id -> entry
|
||||||
|
let made = 0; // entries in the order they were made (`seq`), for lists
|
||||||
|
let broadcast = () => {}; // (cmd, ...params) to every game playing; set by lib/world.js
|
||||||
|
// address key -> {at, clothing, den, names}: the version (defpacks
|
||||||
|
// customVersion) of the packs with custom items in that address last
|
||||||
|
// fetched, the oldest within PACKS_SEEN_MS (players behind one address
|
||||||
|
// fetch at different times). an entry's `changed` is the version of its last change.
|
||||||
|
const packsSeen = new Map();
|
||||||
|
|
||||||
|
const db = () => accounts.database();
|
||||||
|
const now = () => Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
|
const baseDef = (kind, id) => (kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id));
|
||||||
|
|
||||||
|
// the file name an uploaded music track is asked for by (lib/custommusic.js):
|
||||||
|
// a new upload is a new name, so no game plays an old copy from its cache.
|
||||||
|
const audioName = entry => `CustomMusic${entry.id}_${entry.audio}`;
|
||||||
|
let audioGone = () => {}; // (entry): an uploaded track's item was deleted; set by lib/custommusic.js
|
||||||
|
|
||||||
|
// the def row of an entry: its base's row with its own id, name, price and
|
||||||
|
// colours, always on sale and marked new.
|
||||||
|
const rowOf = entry => {
|
||||||
|
const base = baseDef(entry.kind, entry.base);
|
||||||
|
const own = {
|
||||||
|
id: String(entry.id),
|
||||||
|
membersOnly: entry.members ? "1" : "0",
|
||||||
|
itemStatus: "1",
|
||||||
|
availabilityStartTime: "0",
|
||||||
|
availabilityEndTime: "0",
|
||||||
|
currencyType: CURRENCY_GEMS,
|
||||||
|
recycleValue: "0",
|
||||||
|
combinedCost: "",
|
||||||
|
};
|
||||||
|
if (entry.kind === "den") {
|
||||||
|
// a music track uploaded by staff (lib/custommusic.js): the game plays
|
||||||
|
// "audio/<abbrName>.mp3", which the server answers with its file
|
||||||
|
if (entry.audio) {
|
||||||
|
own.abbrName = audioName(entry);
|
||||||
|
}
|
||||||
|
return {...base, ...own, nameStrId: String(STRING_BASE.den + entry.id - FIRST_ID), cost: String(entry.cost)};
|
||||||
|
}
|
||||||
|
return {...base, ...own, titleStrId: String(STRING_BASE.clothing + entry.id - FIRST_ID), value: String(entry.cost), colors: entry.colors.join(","), isGiftable: "1"};
|
||||||
|
};
|
||||||
|
|
||||||
|
const apply = entry => {
|
||||||
|
defpacks.setCustomItem(entry.kind, rowOf(entry), entry.name, entry.inShop);
|
||||||
|
entry.changed = defpacks.customVersion();
|
||||||
|
};
|
||||||
|
|
||||||
|
// what "xdi" carries of an entry: the fields the client reads, its name and
|
||||||
|
// picture. clothing goes through the clients' pack transform, so the wear
|
||||||
|
// rules reach custom items too.
|
||||||
|
const clientRow = entry => {
|
||||||
|
const row = entry.kind === "clothing" ? defpacks.clientItemRow(rowOf(entry)) : rowOf(entry);
|
||||||
|
const out = {};
|
||||||
|
for (const field of CLIENT_FIELDS[entry.kind]) {
|
||||||
|
if (row[field] !== undefined) {
|
||||||
|
out[field] = row[field];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {...out, name: entry.name, art: entry.artPending ? "" : entry.art || "", artMode: entry.artMode || "sticker"};
|
||||||
|
};
|
||||||
|
|
||||||
|
// "xdi" [.., .., kind, json]: def rows with their names, as JSON. a field
|
||||||
|
// may not hold "%" (lib/sfs.js drops it), so a "%" in a name is written as
|
||||||
|
// JSON's %.
|
||||||
|
const xtRows = rows => JSON.stringify(rows).replace(/%/g, "\\u0025");
|
||||||
|
|
||||||
|
const messages = entries => {
|
||||||
|
const out = [];
|
||||||
|
for (const kind of KINDS) {
|
||||||
|
// a picture waiting for a moderator is not shown yet
|
||||||
|
const rows = entries.filter(entry => entry.kind === kind && !entry.pending).map(clientRow);
|
||||||
|
for (let at = 0; at < rows.length; at += CHUNK) {
|
||||||
|
out.push([kind, xtRows(rows.slice(at, at + CHUNK))]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
|
// The patched client accepts ordinary clothing rows through xdi as well as
|
||||||
|
// newly made ones. That lets a moderation rule take effect in an already
|
||||||
|
// open editor instead of waiting for its next def-pack download.
|
||||||
|
const sendClothingDefs = ids => {
|
||||||
|
const rows = [...new Set(ids.map(Number))].map(id => {
|
||||||
|
const entry = items.get("clothing").get(id);
|
||||||
|
// A refreshed custom row must retain the extra xdi-only fields. Omitting
|
||||||
|
// them makes a live client lose its custom name or picture while its
|
||||||
|
// avatar-use flag is being updated.
|
||||||
|
return entry ? {...defpacks.clientItemRow(rowOf(entry)), name: entry.name, art: entry.artPending ? "" : entry.art || "",
|
||||||
|
artMode: entry.artMode || "sticker"} : defpacks.clientItemDef(id);
|
||||||
|
}).filter(row => row && row.type === TYPE_CLOTHING);
|
||||||
|
for (let at = 0; at < rows.length; at += CHUNK) {
|
||||||
|
broadcast("xdi", "clothing", xtRows(rows.slice(at, at + CHUNK)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const announce = entry => {
|
||||||
|
if (entry.pending) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const params of messages([entry])) {
|
||||||
|
broadcast("xdi", ...params);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const fromRow = row => ({
|
||||||
|
kind: row.kind, id: row.id, base: row.base, name: row.name, cost: row.cost, members: row.members === 1,
|
||||||
|
colors: row.colors ? row.colors.split(",").map(Number) : [], inShop: row.in_shop === 1, createdBy: row.created_by, createdAt: row.created_at,
|
||||||
|
ownerId: row.owner_id ?? null,
|
||||||
|
art: row.art || null,
|
||||||
|
artMode: LOOKS.includes(row.art_mode) ? row.art_mode : "sticker",
|
||||||
|
pending: row.pending === 1,
|
||||||
|
artPending: row.art_pending === 1,
|
||||||
|
audio: /^[0-9a-f]{8,64}$/.test(row.audio || "") ? row.audio : null,
|
||||||
|
});
|
||||||
|
|
||||||
|
// a player-made item (lib/playeritems.js) has the maker's account id;
|
||||||
|
// staff-made ones none. an item with a picture of its own (lib/itemart.js)
|
||||||
|
// has its version. the columns came later than the table.
|
||||||
|
const addOwnerColumn = () => {
|
||||||
|
const columns = db().prepare("PRAGMA table_info(custom_items)").all().map(column => column.name);
|
||||||
|
if (!columns.includes("owner_id")) {
|
||||||
|
db().exec("ALTER TABLE custom_items ADD COLUMN owner_id INTEGER");
|
||||||
|
}
|
||||||
|
if (!columns.includes("art")) {
|
||||||
|
db().exec("ALTER TABLE custom_items ADD COLUMN art TEXT");
|
||||||
|
}
|
||||||
|
if (!columns.includes("art_mode")) {
|
||||||
|
db().exec("ALTER TABLE custom_items ADD COLUMN art_mode TEXT");
|
||||||
|
}
|
||||||
|
// waiting for a moderator (lib/playeritems.js, when the admin asks for it):
|
||||||
|
// the item itself, or only its newest picture
|
||||||
|
if (!columns.includes("pending")) {
|
||||||
|
db().exec("ALTER TABLE custom_items ADD COLUMN pending INTEGER");
|
||||||
|
}
|
||||||
|
if (!columns.includes("art_pending")) {
|
||||||
|
db().exec("ALTER TABLE custom_items ADD COLUMN art_pending INTEGER");
|
||||||
|
}
|
||||||
|
// a music track uploaded by staff (lib/custommusic.js): its file's version
|
||||||
|
if (!columns.includes("audio")) {
|
||||||
|
db().exec("ALTER TABLE custom_items ADD COLUMN audio TEXT");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const load = () => {
|
||||||
|
db().exec(SCHEMA);
|
||||||
|
addOwnerColumn();
|
||||||
|
for (const row of db().prepare("SELECT * FROM custom_items ORDER BY rowid").all()) {
|
||||||
|
const entry = {...fromRow(row), seq: made++};
|
||||||
|
if (!baseDef(entry.kind, entry.base)) {
|
||||||
|
console.log(`[custom items] ${logText(entry.kind)} ${logText(entry.id)} is made from ${logText(entry.base)}, which is not in the packs; left out`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
items.get(entry.kind).set(entry.id, entry);
|
||||||
|
if (!entry.pending) {
|
||||||
|
apply(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(`[custom items] ${logText(items.get("clothing").size)} clothing, ${logText(items.get("den").size)} den items`);
|
||||||
|
};
|
||||||
|
|
||||||
|
// checks what staff typed. returns {error} or the cleaned values.
|
||||||
|
const NAME_PATTERN = /^[\p{L}\p{N} '&!?.,:()#+\-]+$/u;
|
||||||
|
const clean = (kind, fields, current = null) => {
|
||||||
|
const out = {};
|
||||||
|
if (fields.name !== undefined || !current) {
|
||||||
|
const name = String(fields.name || "").trim().replace(/\s+/g, " ");
|
||||||
|
if (!name || name.length > MAX_NAME || !NAME_PATTERN.test(name)) {
|
||||||
|
return {error: `A name of 1 to ${MAX_NAME} letters, numbers, spaces and simple punctuation, please.`};
|
||||||
|
}
|
||||||
|
out.name = name;
|
||||||
|
}
|
||||||
|
if (fields.cost !== undefined || !current) {
|
||||||
|
const cost = Number(fields.cost === undefined || fields.cost === "" ? 0 : fields.cost);
|
||||||
|
if (!Number.isInteger(cost) || cost < 0 || cost > MAX_COST) {
|
||||||
|
return {error: `A price from 0 to ${MAX_COST} gems, please.`};
|
||||||
|
}
|
||||||
|
out.cost = cost;
|
||||||
|
}
|
||||||
|
if (fields.members !== undefined || !current) {
|
||||||
|
out.members = fields.members === true || fields.members === "1" || fields.members === 1;
|
||||||
|
}
|
||||||
|
if (fields.inShop !== undefined || !current) {
|
||||||
|
out.inShop = fields.inShop === undefined ? true : fields.inShop === true || fields.inShop === "1" || fields.inShop === 1;
|
||||||
|
}
|
||||||
|
if (kind === "clothing" && (fields.colors !== undefined || !current)) {
|
||||||
|
const base = baseDef(kind, current ? current.base : fields.base);
|
||||||
|
const baseColours = String(base.colors).split(",").map(Number);
|
||||||
|
let colors = fields.colors;
|
||||||
|
if (colors === undefined || colors === null || colors === "") {
|
||||||
|
colors = baseColours;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
colors = (Array.isArray(colors) ? colors : String(colors).split(",")).map(value => Number(String(value).trim()));
|
||||||
|
}
|
||||||
|
// a colour is a packed palette number, as in the packs (or a custom colour
|
||||||
|
// id, lib/colours.js).
|
||||||
|
if (colors.length === 0 || colors.length > MAX_COLOURS || !colors.every(value => Number.isInteger(value) && value >= 0 && value <= 0xFFFFFFFF)) {
|
||||||
|
return {error: `1 to ${MAX_COLOURS} colours, each a number as the packs have them.`};
|
||||||
|
}
|
||||||
|
out.colors = colors;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
|
// makes an item from `base`, an existing clothing piece or den item.
|
||||||
|
// `ownerId`: the player who made it (lib/playeritems.js), or null for staff.
|
||||||
|
// `pending`: it waits for a moderator (approve), out of the game till then.
|
||||||
|
// returns {item} or {error}.
|
||||||
|
const create = (kind, fields, by, ownerId = null, pending = false) => {
|
||||||
|
if (!KINDS.includes(kind)) {
|
||||||
|
return {error: "The kind is clothing or den."};
|
||||||
|
}
|
||||||
|
const baseId = Number(fields.base);
|
||||||
|
const base = Number.isInteger(baseId) ? baseDef(kind, baseId) : null;
|
||||||
|
if (!base || baseId >= FIRST_ID) {
|
||||||
|
return {error: `No ${kind === "den" ? "den item" : "clothing"} with the id ${fields.base} to make it from (it must be one of the game's own).`};
|
||||||
|
}
|
||||||
|
if (kind === "clothing" && base.type !== TYPE_CLOTHING) {
|
||||||
|
return {error: `${baseId} is a body part, not clothing.`};
|
||||||
|
}
|
||||||
|
if (kind === "den" && !OFFERED_SPECIAL_TYPES.includes(base.specialType)) {
|
||||||
|
return {error: `Den item ${baseId} does something of its own (a portal, a game, ...) and cannot be copied.`};
|
||||||
|
}
|
||||||
|
if (items.get(kind).size >= MAX_ITEMS) {
|
||||||
|
return {error: "There are as many custom items of that kind as there can be."};
|
||||||
|
}
|
||||||
|
const values = clean(kind, {...fields, base: baseId});
|
||||||
|
if (values.error) {
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
const id = Math.max(FIRST_ID - 1, ...items.get(kind).keys()) + 1;
|
||||||
|
// `fields.audio`: an uploaded music track's version (lib/custommusic.js)
|
||||||
|
const audio = kind === "den" && /^[0-9a-f]{8,64}$/.test(String(fields.audio || "")) ? String(fields.audio) : null;
|
||||||
|
const entry = {kind, id, base: baseId, colors: [], ...values, createdBy: String(by), createdAt: now(), ownerId, artMode: "sticker", pending, artPending: false,
|
||||||
|
audio, seq: made++};
|
||||||
|
db().prepare("INSERT INTO custom_items (kind, id, base, name, cost, members, colors, in_shop, created_by, created_at, owner_id, pending, audio) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
|
||||||
|
.run(kind, id, baseId, entry.name, entry.cost, entry.members ? 1 : 0, entry.colors.join(","), entry.inShop ? 1 : 0, entry.createdBy, entry.createdAt, ownerId, pending ? 1 : 0, audio);
|
||||||
|
items.get(kind).set(id, entry);
|
||||||
|
if (!pending) {
|
||||||
|
apply(entry);
|
||||||
|
announce(entry);
|
||||||
|
}
|
||||||
|
return {item: entry};
|
||||||
|
};
|
||||||
|
|
||||||
|
// changes the name, price, members-only, colours or whether it is on sale.
|
||||||
|
const update = (kind, id, fields) => {
|
||||||
|
const entry = items.has(kind) && items.get(kind).get(Number(id));
|
||||||
|
if (!entry) {
|
||||||
|
return {error: "No such custom item."};
|
||||||
|
}
|
||||||
|
const values = clean(kind, fields, entry);
|
||||||
|
if (values.error) {
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
Object.assign(entry, values);
|
||||||
|
db().prepare("UPDATE custom_items SET name = ?, cost = ?, members = ?, colors = ?, in_shop = ? WHERE kind = ? AND id = ?")
|
||||||
|
.run(entry.name, entry.cost, entry.members ? 1 : 0, entry.colors.join(","), entry.inShop ? 1 : 0, kind, entry.id);
|
||||||
|
if (!entry.pending) {
|
||||||
|
apply(entry);
|
||||||
|
announce(entry);
|
||||||
|
}
|
||||||
|
return {item: entry};
|
||||||
|
};
|
||||||
|
|
||||||
|
// how a clothing item with a picture of its own is worn: "sticker" (the
|
||||||
|
// picture where the item would be) or "texture" (the item's shape, painted
|
||||||
|
// with the picture). the patched client draws it (LayerBitmap.paintLayer).
|
||||||
|
const LOOKS = ["sticker", "texture"];
|
||||||
|
|
||||||
|
// returns {item} or {error}; every game is told.
|
||||||
|
const setArtMode = (kind, id, mode) => {
|
||||||
|
const entry = items.has(kind) && items.get(kind).get(Number(id));
|
||||||
|
if (!entry) {
|
||||||
|
return {error: "No such custom item."};
|
||||||
|
}
|
||||||
|
if (!LOOKS.includes(mode)) {
|
||||||
|
return {error: "The look is sticker or texture."};
|
||||||
|
}
|
||||||
|
entry.artMode = mode;
|
||||||
|
db().prepare("UPDATE custom_items SET art_mode = ? WHERE kind = ? AND id = ?").run(mode, kind, entry.id);
|
||||||
|
entry.changed = defpacks.customChanged();
|
||||||
|
announce(entry);
|
||||||
|
return {item: entry};
|
||||||
|
};
|
||||||
|
|
||||||
|
// its picture's version (lib/itemart.js), or null for none; every game is told.
|
||||||
|
// `pending`: the picture waits for a moderator, and is not shown till then.
|
||||||
|
const setArt = (kind, id, art, pending = false) => {
|
||||||
|
const entry = items.has(kind) && items.get(kind).get(Number(id));
|
||||||
|
if (!entry) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
entry.art = art || null;
|
||||||
|
entry.artPending = Boolean(art && pending);
|
||||||
|
db().prepare("UPDATE custom_items SET art = ?, art_pending = ? WHERE kind = ? AND id = ?").run(entry.art, entry.artPending ? 1 : 0, kind, entry.id);
|
||||||
|
entry.changed = defpacks.customChanged();
|
||||||
|
announce(entry);
|
||||||
|
};
|
||||||
|
|
||||||
|
// a moderator lets an item, or its picture, in (lib/playeritems.js approve).
|
||||||
|
// returns the entry, or null when there was nothing waiting.
|
||||||
|
const approve = (kind, id) => {
|
||||||
|
const entry = items.has(kind) && items.get(kind).get(Number(id));
|
||||||
|
if (!entry || (!entry.pending && !entry.artPending)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
entry.pending = false;
|
||||||
|
entry.artPending = false;
|
||||||
|
db().prepare("UPDATE custom_items SET pending = 0, art_pending = 0 WHERE kind = ? AND id = ?").run(kind, entry.id);
|
||||||
|
apply(entry);
|
||||||
|
announce(entry);
|
||||||
|
return entry;
|
||||||
|
};
|
||||||
|
|
||||||
|
// deletes it from the tables (games playing keep its def row, which nothing
|
||||||
|
// uses now). taking it from the players who have it is the caller's.
|
||||||
|
// returns {item} or {error}.
|
||||||
|
const remove = (kind, id) => {
|
||||||
|
const entry = items.has(kind) && items.get(kind).get(Number(id));
|
||||||
|
if (!entry) {
|
||||||
|
return {error: "No such custom item."};
|
||||||
|
}
|
||||||
|
db().prepare("DELETE FROM custom_items WHERE kind = ? AND id = ?").run(kind, entry.id);
|
||||||
|
items.get(kind).delete(entry.id);
|
||||||
|
defpacks.unsetCustomItem(kind, entry.id);
|
||||||
|
if (entry.audio) {
|
||||||
|
audioGone(entry);
|
||||||
|
}
|
||||||
|
return {item: entry};
|
||||||
|
};
|
||||||
|
|
||||||
|
const list = () => KINDS.flatMap(kind => [...items.get(kind).values()])
|
||||||
|
.sort((one, other) => other.seq - one.seq);
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
KINDS,
|
||||||
|
FIRST_ID,
|
||||||
|
audioName,
|
||||||
|
onAudioGone: callback => {
|
||||||
|
audioGone = callback;
|
||||||
|
},
|
||||||
|
load,
|
||||||
|
create,
|
||||||
|
update,
|
||||||
|
remove,
|
||||||
|
setArt,
|
||||||
|
setArtMode,
|
||||||
|
approve,
|
||||||
|
// what waits for a moderator: items, and pictures, the oldest first
|
||||||
|
waiting: () => list().filter(entry => entry.pending || entry.artPending).reverse(),
|
||||||
|
LOOKS,
|
||||||
|
list,
|
||||||
|
get: (kind, id) => (items.has(kind) && items.get(kind).get(Number(id))) || null,
|
||||||
|
// the account id of the player who made an item, or null (staff's, or
|
||||||
|
// one of the game's own).
|
||||||
|
ownerOf: (kind, id) => {
|
||||||
|
const entry = items.has(kind) && items.get(kind).get(Number(id));
|
||||||
|
return entry ? entry.ownerId : null;
|
||||||
|
},
|
||||||
|
// can this base be made into an item? (the checks of create, for a list
|
||||||
|
// to offer only those.)
|
||||||
|
copyable: (kind, id) => {
|
||||||
|
const def = baseDef(kind, id);
|
||||||
|
return Boolean(def) && Number(id) < FIRST_ID && (kind === "clothing" ? def.type === TYPE_CLOTHING : OFFERED_SPECIAL_TYPES.includes(def.specialType));
|
||||||
|
},
|
||||||
|
// the base an item's art is from, for a list showing what each is.
|
||||||
|
baseName: entry => {
|
||||||
|
const def = baseDef(entry.kind, entry.base);
|
||||||
|
return def ? defpacks.string(entry.kind === "den" ? def.nameStrId : def.titleStrId) || String(def.abbrName || entry.base) : String(entry.base);
|
||||||
|
},
|
||||||
|
// an address was sent a pack with custom items in: "clothing", "den" or
|
||||||
|
// "names" (lib/defpacks.js customPackKind), made at `version`.
|
||||||
|
sawPack(key, packKind, version) {
|
||||||
|
const time = Date.now();
|
||||||
|
const seen = packsSeen.get(key);
|
||||||
|
if (seen && time - seen.at < PACKS_SEEN_MS) {
|
||||||
|
if (seen[packKind] === undefined) {
|
||||||
|
seen[packKind] = version;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
packsSeen.delete(key);
|
||||||
|
packsSeen.set(key, {at: time, [packKind]: version});
|
||||||
|
// the oldest are first
|
||||||
|
for (const [oldKey, old] of packsSeen) {
|
||||||
|
if (packsSeen.size <= MAX_PACKS_SEEN && time - old.at < PACKS_SEEN_MS) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
packsSeen.delete(oldKey);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
// the custom items a game logging in may not have: those changed since its
|
||||||
|
// address fetched the packs, and those with a picture (which the packs do
|
||||||
|
// not carry); every one when the address fetched none lately.
|
||||||
|
sendAll(session) {
|
||||||
|
const seen = packsSeen.get(limits.key(session.address));
|
||||||
|
const fresh = seen && Date.now() - seen.at < PACKS_SEEN_MS && seen.names !== undefined ? seen : null;
|
||||||
|
const since = kind => (fresh && fresh[kind] !== undefined ? Math.min(fresh[kind], fresh.names) : -1);
|
||||||
|
const needed = entry => !entry.pending && (entry.changed > since(entry.kind) || (entry.art && !entry.artPending));
|
||||||
|
for (const params of messages(list().reverse().filter(needed))) {
|
||||||
|
session.sendXt("xdi", -1, ...params);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
sendClothingDefs,
|
||||||
|
// lib/world.js says how to reach every game playing.
|
||||||
|
connect(broadcastXt) {
|
||||||
|
broadcast = broadcastXt;
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const crypto = require("crypto");
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
|
const cdn = require("./cdn.js");
|
||||||
|
const config = require("../config.js");
|
||||||
|
const customItems = require("./customitems.js");
|
||||||
|
const extraMusic = require("./extramusic.js");
|
||||||
|
|
||||||
|
// music tracks staff upload in the panels (permission "music.upload",
|
||||||
|
// lib/roles.js): an MP3 made a den music item while the server runs, as the
|
||||||
|
// extra tracks of lib/extramusic.js are. each is a custom den item
|
||||||
|
// (lib/customitems.js) made from the game's "Jam On", with an `audio`
|
||||||
|
// version of its own: games are sent its def row at once, players get it
|
||||||
|
// from the item finder (or the shop, if staff put it on sale), and deleting
|
||||||
|
// it takes it from everyone, as with any custom item.
|
||||||
|
//
|
||||||
|
// a den music item plays "audio/<abbrName>.mp3" from the content server
|
||||||
|
// (DenItemHolder); for these the server answers with the file uploaded, kept
|
||||||
|
// in data/custom-music/<item id>-<version>.mp3 (the data folder is the one
|
||||||
|
// place the server writes to).
|
||||||
|
|
||||||
|
const MAX_BYTES = 15 * 1024 * 1024;
|
||||||
|
const MIN_BYTES = 4 * 1024;
|
||||||
|
const VERSION_LENGTH = 12;
|
||||||
|
const FOLDER = () => path.join(config.dataDir, "custom-music");
|
||||||
|
const fileOf = entry => path.join(FOLDER(), `${entry.id}-${entry.audio}.mp3`);
|
||||||
|
|
||||||
|
// MPEG audio layer III, as the game's Flash plays it: an ID3v2 tag may come
|
||||||
|
// first; then a frame header whose next frame is where its length says.
|
||||||
|
const BITRATES = {
|
||||||
|
1: [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
|
||||||
|
2: [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
|
||||||
|
};
|
||||||
|
const SAMPLE_RATES = {3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000]};
|
||||||
|
|
||||||
|
// the frame at `at`: {length, sampleRate} or null.
|
||||||
|
const frameAt = (data, at) => {
|
||||||
|
if (at + 4 > data.length || data[at] !== 0xFF || (data[at + 1] & 0xE0) !== 0xE0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const version = (data[at + 1] >> 3) & 3; // 3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5
|
||||||
|
const layer = (data[at + 1] >> 1) & 3; // 1 is layer III
|
||||||
|
const bitrateIndex = data[at + 2] >> 4;
|
||||||
|
const rateIndex = (data[at + 2] >> 2) & 3;
|
||||||
|
const padding = (data[at + 2] >> 1) & 1;
|
||||||
|
if (version === 1 || layer !== 1 || bitrateIndex === 0 || bitrateIndex === 15 || rateIndex === 3) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const bitrate = BITRATES[version === 3 ? 1 : 2][bitrateIndex] * 1000;
|
||||||
|
const sampleRate = SAMPLE_RATES[version][rateIndex];
|
||||||
|
return {length: Math.floor(((version === 3 ? 144 : 72) * bitrate) / sampleRate) + padding, sampleRate};
|
||||||
|
};
|
||||||
|
|
||||||
|
// null for an MP3 the game can play, or what is wrong with it.
|
||||||
|
const problem = data => {
|
||||||
|
if (!Buffer.isBuffer(data) || data.length < MIN_BYTES) {
|
||||||
|
return "That file is too small to be a song.";
|
||||||
|
}
|
||||||
|
if (data.length > MAX_BYTES) {
|
||||||
|
return `That file is too big: ${MAX_BYTES / 1024 / 1024} MB at most.`;
|
||||||
|
}
|
||||||
|
let at = 0;
|
||||||
|
if (data.toString("latin1", 0, 3) === "ID3" && data.length > 10) {
|
||||||
|
at = 10 + (((data[6] & 0x7F) << 21) | ((data[7] & 0x7F) << 14) | ((data[8] & 0x7F) << 7) | (data[9] & 0x7F)) + (data[5] & 0x10 ? 10 : 0);
|
||||||
|
}
|
||||||
|
// the first frame: the header, then two more where their lengths say
|
||||||
|
for (const end = Math.min(data.length, at + 64 * 1024); at < end; at++) {
|
||||||
|
const first = frameAt(data, at);
|
||||||
|
const second = first && frameAt(data, at + first.length);
|
||||||
|
const third = second && frameAt(data, at + first.length + second.length);
|
||||||
|
if (third) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "That is not an MP3 file (MPEG audio layer III).";
|
||||||
|
};
|
||||||
|
|
||||||
|
const tracks = () => customItems.list().filter(entry => entry.kind === "den" && entry.audio);
|
||||||
|
|
||||||
|
// content path ("1830/audio/<hash>") -> entry, made again when the tracks change.
|
||||||
|
let paths = null;
|
||||||
|
const pathMap = () => {
|
||||||
|
if (!paths) {
|
||||||
|
paths = new Map(tracks().map(entry => [cdn.hashedPath(`audio/${customItems.audioName(entry)}.mp3`), entry]));
|
||||||
|
}
|
||||||
|
return paths;
|
||||||
|
};
|
||||||
|
|
||||||
|
// what to answer a content request with when it is for one of these
|
||||||
|
// tracks: {body, type}; undefined when it is not.
|
||||||
|
const asset = async relPath => {
|
||||||
|
const entry = pathMap().get(relPath);
|
||||||
|
if (!entry) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const body = await fs.promises.readFile(fileOf(entry)).catch(() => null);
|
||||||
|
return {body, type: "audio/mpeg"};
|
||||||
|
};
|
||||||
|
|
||||||
|
// an upload made a track: {item} or {error}. `fields`: {name, cost, inShop, members}.
|
||||||
|
const add = (data, fields, by) => {
|
||||||
|
const wrong = problem(data);
|
||||||
|
if (wrong) {
|
||||||
|
return {error: wrong};
|
||||||
|
}
|
||||||
|
const audio = crypto.createHash("sha256").update(data).digest("hex").slice(0, VERSION_LENGTH);
|
||||||
|
fs.mkdirSync(FOLDER(), {recursive: true, mode: 0o700});
|
||||||
|
// written before the item exists, so no game asks for a file not there yet
|
||||||
|
const waiting = path.join(FOLDER(), `new-${audio}-${process.pid}.mp3`);
|
||||||
|
fs.writeFileSync(waiting, data, {mode: 0o600});
|
||||||
|
const result = customItems.create("den", {name: fields.name, cost: fields.cost, members: fields.members,
|
||||||
|
inShop: fields.inShop === true, base: extraMusic.TEMPLATE, audio}, by);
|
||||||
|
if (result.error) {
|
||||||
|
fs.rmSync(waiting, {force: true});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
fs.renameSync(waiting, fileOf(result.item));
|
||||||
|
paths = null;
|
||||||
|
console.log(`[custom music] ${logText(by)} uploaded "${logText(result.item.name)}" (den item ${logText(result.item.id)}, ${logText(data.length)} bytes)`);
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
// the file of a track, for staff to listen to before or after: {data} or null.
|
||||||
|
const file = id => {
|
||||||
|
const entry = tracks().find(track => track.id === Number(id));
|
||||||
|
if (!entry) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const data = (() => {
|
||||||
|
try {
|
||||||
|
return fs.readFileSync(fileOf(entry));
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return data ? {data, entry} : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// for the panels: newest first
|
||||||
|
const list = () => tracks().map(entry => ({id: entry.id, name: entry.name, cost: entry.cost, inShop: entry.inShop,
|
||||||
|
createdBy: entry.createdBy, createdAt: entry.createdAt,
|
||||||
|
bytes: (() => {
|
||||||
|
try {
|
||||||
|
return fs.statSync(fileOf(entry)).size;
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
})()}));
|
||||||
|
|
||||||
|
// a track's item was deleted (lib/itemcontrol.js deleteCustom): its file goes too.
|
||||||
|
customItems.onAudioGone(entry => {
|
||||||
|
fs.rmSync(fileOf(entry), {force: true});
|
||||||
|
paths = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
// at start: files of tracks no longer there (and of uploads cut short) go.
|
||||||
|
const load = () => {
|
||||||
|
const kept = new Set(tracks().map(entry => path.basename(fileOf(entry))));
|
||||||
|
let gone = 0;
|
||||||
|
for (const name of fs.existsSync(FOLDER()) ? fs.readdirSync(FOLDER()) : []) {
|
||||||
|
if (!kept.has(name)) {
|
||||||
|
fs.rmSync(path.join(FOLDER(), name), {force: true});
|
||||||
|
gone++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(`[custom music] ${logText(kept.size)} uploaded tracks${gone ? `, ${logText(gone)} stray files removed` : ""}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {MAX_BYTES, problem, asset, add, file, list, load};
|
||||||
+228
-20
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const zlib = require("zlib");
|
const zlib = require("zlib");
|
||||||
const amf3 = require("./amf3.js");
|
const amf3 = require("./amf3.js");
|
||||||
const cdn = require("./cdn.js");
|
const cdn = require("./cdn.js");
|
||||||
@@ -7,6 +8,7 @@ const config = require("../config.js");
|
|||||||
const sales = require("./sales.js");
|
const sales = require("./sales.js");
|
||||||
const badges = require("./badges.js");
|
const badges = require("./badges.js");
|
||||||
const extraMusic = require("./extramusic.js");
|
const extraMusic = require("./extramusic.js");
|
||||||
|
const wearRules = require("./wearrules.js");
|
||||||
|
|
||||||
// defPack ids, from loader.DefPacksDefHelper in the client.
|
// defPack ids, from loader.DefPacksDefHelper in the client.
|
||||||
const DEF_ITEM = 1000;
|
const DEF_ITEM = 1000;
|
||||||
@@ -41,8 +43,10 @@ const DEF_PET_TOY = 1063;
|
|||||||
const DEF_WORLD_ITEMS = 1064;
|
const DEF_WORLD_ITEMS = 1064;
|
||||||
const DEF_NPC = 1025;
|
const DEF_NPC = 1025;
|
||||||
const DEF_NAMEBAR_BADGE = 1049;
|
const DEF_NAMEBAR_BADGE = 1049;
|
||||||
|
const DEF_EMOTICON = 1036;
|
||||||
|
const DEF_NEWSPAPER = 1065; // the Jamaa Journal's pages (newspaper.NewspaperManager)
|
||||||
|
|
||||||
const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items: plain, mannequin
|
const OFFERED_SPECIAL_TYPES = ["0", "4", "6", "7"]; // den items: plain, mannequin, eco producer and consumer (lib/eco.js)
|
||||||
const DEN_ITEM_MASTERPIECE = 2725;
|
const DEN_ITEM_MASTERPIECE = 2725;
|
||||||
|
|
||||||
const packs = new Map();
|
const packs = new Map();
|
||||||
@@ -69,6 +73,32 @@ const LAYER_EYES = "3";
|
|||||||
const TYPE_CLOTHING = "1";
|
const TYPE_CLOTHING = "1";
|
||||||
const EVERY_AVATAR = "9007199254740991"; // avatarUseFlags with a bit set for each animal type
|
const EVERY_AVATAR = "9007199254740991"; // avatarUseFlags with a bit set for each animal type
|
||||||
|
|
||||||
|
// ItemXtCommManager checks bit (avatar type - 1). BigInt avoids losing a
|
||||||
|
// bit in JavaScript's 53-bit Number representation while preserving the
|
||||||
|
// string form the AMF def pack uses.
|
||||||
|
const clientAvatarUseFlags = itemId => {
|
||||||
|
let flags = BigInt(EVERY_AVATAR);
|
||||||
|
for (const type of wearRules.blockedTypes(itemId)) {
|
||||||
|
if (type <= 53) {
|
||||||
|
flags &= ~(1n << BigInt(type - 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return String(flags);
|
||||||
|
};
|
||||||
|
|
||||||
|
// One transform is used for fetched packs and for the live `xdi` definition
|
||||||
|
// updates sent to games that are already running.
|
||||||
|
const clientItemRow = def => {
|
||||||
|
const row = {...def};
|
||||||
|
if (row.type === TYPE_CLOTHING) {
|
||||||
|
row.avatarUseFlags = clientAvatarUseFlags(row.id);
|
||||||
|
}
|
||||||
|
else if (row.type === "0" && row.layerId === LAYER_EYES) {
|
||||||
|
row.avatarUseFlags = EVERY_AVATAR;
|
||||||
|
}
|
||||||
|
return row;
|
||||||
|
};
|
||||||
|
|
||||||
// rooms the official room pack no longer lists but whose files an older
|
// rooms the official room pack no longer lists but whose files an older
|
||||||
// build on the CDN still has (lib/cdn.js looks there): the Summer Carnival,
|
// build on the CDN still has (lib/cdn.js looks there): the Summer Carnival,
|
||||||
// dropped after build 1828.
|
// dropped after build 1828.
|
||||||
@@ -143,12 +173,22 @@ const withRestoredParties = pack => {
|
|||||||
// text of our own, for things the game has no string for. added to the
|
// 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).
|
// English localization pack under ids far above the game's (about 41,000).
|
||||||
const ADDED_STRINGS = {
|
const ADDED_STRINGS = {
|
||||||
|
// the login popup for a launcher too old to send device ids (lib/world.js
|
||||||
|
// LOGIN_OUTDATED), in place of "Your account is currently under maintenance."
|
||||||
|
11198: "Your client is outdated. Update at https://burrow.moe/download",
|
||||||
9000001: "Castle (2010 draft)",
|
9000001: "Castle (2010 draft)",
|
||||||
9000002: "Water Park (three slides)",
|
9000002: "Water Park (three slides)",
|
||||||
9000003: "Water Park (five slides)",
|
9000003: "Water Park (five slides)",
|
||||||
9000004: "Crystal Palace (concept)",
|
9000004: "Crystal Palace (concept)",
|
||||||
// the buddy game the client's files call "fourGem"; no string says so.
|
// the buddy game the client's files call "fourGem"; no string says so.
|
||||||
9000005: "Four Gems",
|
9000005: "Four Gems",
|
||||||
|
// a shop's title when its room gives it none (lib/world.js SHOP_KIND_TITLES)
|
||||||
|
9000010: "Clothing Shop",
|
||||||
|
9000011: "Den Shop",
|
||||||
|
9000012: "Den Rooms",
|
||||||
|
9000013: "Shop",
|
||||||
|
9000014: "Exchange",
|
||||||
|
9000015: "Diamond Shop",
|
||||||
};
|
};
|
||||||
|
|
||||||
// the game under this server's name. its text says "Animal Jam", "Animal
|
// the game under this server's name. its text says "Animal Jam", "Animal
|
||||||
@@ -175,7 +215,64 @@ const withOurName = pack => {
|
|||||||
return pack;
|
return pack;
|
||||||
};
|
};
|
||||||
|
|
||||||
const withAddedStrings = pack => withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings()));
|
// the moderators' message boxes (FacilitatorXtCommManager "fp") keep
|
||||||
|
// "\n" as two characters, which the client shows just as written
|
||||||
|
// ("--Message From Moderator--\n\nhello"). real line breaks in their place.
|
||||||
|
const LITERAL_LINE_BREAKS = ["11134", "11135"];
|
||||||
|
const withLineBreaks = pack => {
|
||||||
|
for (const id of LITERAL_LINE_BREAKS) {
|
||||||
|
if (typeof pack[id] === "string") {
|
||||||
|
pack[id] = pack[id].replace(/\\n/g, "\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pack;
|
||||||
|
};
|
||||||
|
|
||||||
|
// items the staff make while the server runs (lib/customitems.js): an
|
||||||
|
// existing item's art under a new id, name and price. their rows and names
|
||||||
|
// are kept here, and go into the packs like the rows above, after the
|
||||||
|
// renaming (a name staff chose is left as they wrote it).
|
||||||
|
const customRows = new Map([[DEF_ITEM, new Map()], [DEF_DEN_ITEM, new Map()]]); // pack -> id -> row
|
||||||
|
const customStrings = {}; // localization id -> name
|
||||||
|
const customInShop = {clothing: new Set(), den: new Set()}; // ids on sale
|
||||||
|
let customVersion = 0; // goes up with every change, for anything that keeps a list of items
|
||||||
|
|
||||||
|
const withCustomRows = id => pack => {
|
||||||
|
const at = new Map(Object.entries(pack).map(([key, def]) => [String(def.id), key]));
|
||||||
|
let next = Math.max(-1, ...Object.keys(pack).map(Number).filter(Number.isInteger)) + 1;
|
||||||
|
for (const row of customRows.get(id).values()) {
|
||||||
|
// a changed row replaces the one the pack was made with.
|
||||||
|
pack[at.has(row.id) ? at.get(row.id) : next++] = {...row};
|
||||||
|
}
|
||||||
|
return pack;
|
||||||
|
};
|
||||||
|
|
||||||
|
// colours of clothing items from a dump of a beta-era inventory (art id,
|
||||||
|
// then the colour as 4 bytes, little-endian), added after each item's own
|
||||||
|
// so the colours already given keep their place. the shop shows a list's
|
||||||
|
// first 8 only, so these are had from the item givers.
|
||||||
|
const DUMP_COLOURS = new Map([
|
||||||
|
[231, [0x6929C069]], // Rare Eyeball Hat (Beta EyeBall; tried in the game)
|
||||||
|
[224, [0x67520169]], // Creature Mask (Beta Creature Mask)
|
||||||
|
[136, [0x2C083069, 0x55153131]], // Tiara (Beta Tiara, Milky Tiara)
|
||||||
|
[135, [0x83550505]], // Arctic Hood (Beta Hood)
|
||||||
|
[169, [0x937FF63B]], // Elf Helmet (Beta Elf)
|
||||||
|
[714, [0x00000069]], // Furry Hat (Real Magenta Furry Hat)
|
||||||
|
[649, [0x2E2D1906]], // Turquoise Ring (1st Glitched Ring)
|
||||||
|
]);
|
||||||
|
|
||||||
|
const withDumpColours = pack => {
|
||||||
|
for (const def of Object.values(pack)) {
|
||||||
|
const added = def && DUMP_COLOURS.get(Number(def.id));
|
||||||
|
if (added) {
|
||||||
|
const colours = String(def.colors).split(",").filter(Boolean);
|
||||||
|
def.colors = [...colours, ...added.map(String).filter(colour => !colours.includes(colour))].join(",");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pack;
|
||||||
|
};
|
||||||
|
|
||||||
|
const withAddedStrings = pack => Object.assign(withLineBreaks(withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings()))), customStrings);
|
||||||
|
|
||||||
// the extra music tracks (lib/extramusic.js), as den items like the
|
// the extra music tracks (lib/extramusic.js), as den items like the
|
||||||
// official tracks.
|
// official tracks.
|
||||||
@@ -236,8 +333,8 @@ const SHARED_CHANGES = new Map([
|
|||||||
[DEF_ROOM, withRestoredRooms],
|
[DEF_ROOM, withRestoredRooms],
|
||||||
[DEF_PARTY, withRestoredParties],
|
[DEF_PARTY, withRestoredParties],
|
||||||
[DEF_DEN_ROOM, withoutPrices(DEF_DEN_ROOM, withAddedDens)],
|
[DEF_DEN_ROOM, withoutPrices(DEF_DEN_ROOM, withAddedDens)],
|
||||||
[DEF_DEN_ITEM, withoutPrices(DEF_DEN_ITEM, withExtraMusic)],
|
[DEF_DEN_ITEM, withoutPrices(DEF_DEN_ITEM, pack => withCustomRows(DEF_DEN_ITEM)(withExtraMusic(pack)))],
|
||||||
[DEF_ITEM, withoutPrices(DEF_ITEM)],
|
[DEF_ITEM, withoutPrices(DEF_ITEM, pack => withCustomRows(DEF_ITEM)(withDumpColours(pack)))],
|
||||||
[DEF_DIAMOND, withoutPrices(DEF_DIAMOND)],
|
[DEF_DIAMOND, withoutPrices(DEF_DIAMOND)],
|
||||||
[DEF_PET, withoutPrices(DEF_PET)],
|
[DEF_PET, withoutPrices(DEF_PET)],
|
||||||
[DEF_LOCALIZATION_EN, withAddedStrings],
|
[DEF_LOCALIZATION_EN, withAddedStrings],
|
||||||
@@ -281,9 +378,9 @@ const alwaysOnSale = (pack, ids) => {
|
|||||||
// the rows put back or added (SHARED_CHANGES).
|
// the rows put back or added (SHARED_CHANGES).
|
||||||
const CLIENT_PACKS = new Map([
|
const CLIENT_PACKS = new Map([
|
||||||
[DEF_ITEM, pack => {
|
[DEF_ITEM, pack => {
|
||||||
for (const def of Object.values(pack)) {
|
for (const [key, def] of Object.entries(pack)) {
|
||||||
if (def.type === TYPE_CLOTHING || (def.type === "0" && def.layerId === LAYER_EYES)) {
|
if (def.type === TYPE_CLOTHING || (def.type === "0" && def.layerId === LAYER_EYES)) {
|
||||||
def.avatarUseFlags = EVERY_AVATAR;
|
pack[key] = clientItemRow(def);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
sales.stamp("clothing", pack);
|
sales.stamp("clothing", pack);
|
||||||
@@ -306,24 +403,51 @@ const CLIENT_PACKS = new Map([
|
|||||||
[DEF_NAMEBAR_BADGE, () => {}],
|
[DEF_NAMEBAR_BADGE, () => {}],
|
||||||
]);
|
]);
|
||||||
const clientPackPaths = new Map([...CLIENT_PACKS.keys()].map(id => [cdn.hashedPath(`defPacks/${id}`), id]));
|
const clientPackPaths = new Map([...CLIENT_PACKS.keys()].map(id => [cdn.hashedPath(`defPacks/${id}`), id]));
|
||||||
const clientPackBodies = new Map(); // id -> {day, allOnSale, body}
|
const clientPackBodies = new Map(); // id -> {day, allOnSale, body, version, madeAt}
|
||||||
|
const clientPacksChanged = new Set(); // ids whose body is older than a custom item change
|
||||||
|
const clientPacksMaking = new Map(); // id -> the promise of the body being made
|
||||||
|
// a pack is made again after a custom item change at most every
|
||||||
|
// config.packRemakeMs: the item pack takes ~70 ms of the one thread at 5000
|
||||||
|
// items (~300 ms at 50000), and players make items many times a minute.
|
||||||
|
// until then the body made before goes out, with the version it has; a
|
||||||
|
// game logging in is sent what changed after it (lib/customitems.js sendAll).
|
||||||
|
const deflateRaw = require("util").promisify(zlib.deflateRaw);
|
||||||
|
// the packs custom items are in: their rows, and their names
|
||||||
|
const CUSTOM_PACK_KINDS = new Map([[DEF_ITEM, "clothing"], [DEF_DEN_ITEM, "den"], [DEF_LOCALIZATION_EN, "names"]]);
|
||||||
|
|
||||||
// the pack at `relPath` as clients should get it, or null when it is not
|
const makeClientPack = async id => {
|
||||||
// one of the above (and comes straight from the CDN).
|
// the version before the rows are read: a change while it is made counts
|
||||||
|
// as after, and is sent at login (more than needed, never less)
|
||||||
|
const version = customVersion;
|
||||||
|
const pack = await loadChanged(id);
|
||||||
|
CLIENT_PACKS.get(id)(pack);
|
||||||
|
// deflated on libuv's threads, not this one
|
||||||
|
const body = await deflateRaw(amf3.encode(pack));
|
||||||
|
const made = {day: sales.today(), allOnSale: sales.everythingOnSale(), body, version, madeAt: Date.now()};
|
||||||
|
clientPackBodies.set(id, made);
|
||||||
|
if (customVersion === version) {
|
||||||
|
clientPacksChanged.delete(id);
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
};
|
||||||
|
|
||||||
|
// the pack at `relPath` as clients should get it, {body, version}, or null
|
||||||
|
// when it is not one of the above (and comes straight from the CDN).
|
||||||
|
// `version`: customVersion() of the custom items in it.
|
||||||
const clientPack = async relPath => {
|
const clientPack = async relPath => {
|
||||||
const id = clientPackPaths.get(relPath);
|
const id = clientPackPaths.get(relPath);
|
||||||
if (id === undefined) {
|
if (id === undefined) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const made = clientPackBodies.get(id);
|
const made = clientPackBodies.get(id);
|
||||||
if (made && made.day === sales.today() && made.allOnSale === sales.everythingOnSale()) {
|
if (made && made.day === sales.today() && made.allOnSale === sales.everythingOnSale()
|
||||||
return made.body;
|
&& (!clientPacksChanged.has(id) || Date.now() - made.madeAt < config.packRemakeMs)) {
|
||||||
|
return made;
|
||||||
}
|
}
|
||||||
const pack = await loadChanged(id);
|
if (!clientPacksMaking.has(id)) {
|
||||||
CLIENT_PACKS.get(id)(pack);
|
clientPacksMaking.set(id, makeClientPack(id).finally(() => clientPacksMaking.delete(id)));
|
||||||
const body = zlib.deflateRawSync(amf3.encode(pack));
|
}
|
||||||
clientPackBodies.set(id, {day: sales.today(), allOnSale: sales.everythingOnSale(), body});
|
return clientPacksMaking.get(id);
|
||||||
return body;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// most packs are tables: an object of rows keyed by row index.
|
// most packs are tables: an object of rows keyed by row index.
|
||||||
@@ -361,6 +485,10 @@ let musicIds = []; // den items that are music tracks
|
|||||||
let roomDefsById = new Map();
|
let roomDefsById = new Map();
|
||||||
let badgeIds = []; // name tag badges, ascending
|
let badgeIds = []; // name tag badges, ascending
|
||||||
let npcDefs = new Map(); // the characters of the adventures, see lib/disguises.js
|
let npcDefs = new Map(); // the characters of the adventures, see lib/disguises.js
|
||||||
|
// An avatar attachment is named by its emoticon definition id on the wire,
|
||||||
|
// while AvatarWorldView needs the media id stored by that definition.
|
||||||
|
let emoticonMediaIds = new Map();
|
||||||
|
let journalPages = []; // the Jamaa Journal's pages: {id, page (media id), start (seconds)}
|
||||||
|
|
||||||
// A pack whose feature can be done without: missing (offline and never
|
// A pack whose feature can be done without: missing (offline and never
|
||||||
// cached) just leaves that feature empty.
|
// cached) just leaves that feature empty.
|
||||||
@@ -369,7 +497,7 @@ const loadOptional = async id => {
|
|||||||
return await load(id);
|
return await load(id);
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
console.log(`[defs] ${err.message}; the feature that uses it is off`);
|
console.log(`[defs] ${logText(err.message)}; the feature that uses it is off`);
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -390,8 +518,9 @@ const init = async () => {
|
|||||||
petIds = [...petDefs.keys()];
|
petIds = [...petDefs.keys()];
|
||||||
denItemDefs = new Map((await load(DEF_DEN_ITEM)).map(def => [Number(def.id), def]));
|
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
|
// 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,
|
// stock, ...). of those mannequins (4) are modelled, in lib/dens.js, and
|
||||||
// so plain den items and mannequins are what is offered.
|
// the eco items (6, 7) in lib/eco.js, so those and plain den items are
|
||||||
|
// what is offered.
|
||||||
// the Masterpiece item is a painting's frame, made in the Art Studio and
|
// the Masterpiece item is a painting's frame, made in the Art Studio and
|
||||||
// nowhere else (lib/masterpieces.js).
|
// nowhere else (lib/masterpieces.js).
|
||||||
denItemIds = [...denItemDefs].filter(([id, def]) => OFFERED_SPECIAL_TYPES.includes(def.specialType) && id !== DEN_ITEM_MASTERPIECE).map(([id]) => id);
|
denItemIds = [...denItemDefs].filter(([id, def]) => OFFERED_SPECIAL_TYPES.includes(def.specialType) && id !== DEN_ITEM_MASTERPIECE).map(([id]) => id);
|
||||||
@@ -427,6 +556,9 @@ const init = async () => {
|
|||||||
petFoodDefs = await loadOptional(DEF_PET_FOOD);
|
petFoodDefs = await loadOptional(DEF_PET_FOOD);
|
||||||
petToyDefs = await loadOptional(DEF_PET_TOY);
|
petToyDefs = await loadOptional(DEF_PET_TOY);
|
||||||
npcDefs = new Map((await loadOptional(DEF_NPC)).map(def => [Number(def.id), def]));
|
npcDefs = new Map((await loadOptional(DEF_NPC)).map(def => [Number(def.id), def]));
|
||||||
|
emoticonMediaIds = new Map((await loadOptional(DEF_EMOTICON)).map(def => [Number(def.id), Number(def.mediaRef)]));
|
||||||
|
journalPages = (await loadOptional(DEF_NEWSPAPER)).map(def => ({id: Number(def.id), page: Number(def.pageMediaRefId),
|
||||||
|
start: Number(def.availabilityStartTime) || 0})).filter(page => page.page > 0);
|
||||||
partyDefs = new Map((await loadOptional(DEF_PARTY)).map(def => {
|
partyDefs = new Map((await loadOptional(DEF_PARTY)).map(def => {
|
||||||
const room = roomPathsById.get(Number(def.roomDefId));
|
const room = roomPathsById.get(Number(def.roomDefId));
|
||||||
return [Number(def.id), {
|
return [Number(def.id), {
|
||||||
@@ -439,11 +571,75 @@ const init = async () => {
|
|||||||
isGame: def.isGame === "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`);
|
console.log(`[defs] ${logText(avatarDefs.size)} avatars, ${logText(roomDefsByPath.size)} rooms, ${logText(clothingIds.length)} clothing items, ${logText(denItemIds.length)} den items, ${logText(petIds.length)} pets`);
|
||||||
|
};
|
||||||
|
|
||||||
|
// puts a custom item (lib/customitems.js) in, or changes one already in:
|
||||||
|
// `kind` "clothing" or "den", `row` its full def row (strings, as in the
|
||||||
|
// packs), `name` its English name under the row's string id. the server's
|
||||||
|
// tables have it at once, and the packs clients fetch are made again.
|
||||||
|
// `inShop` false takes it out of the shop (the ones players have still draw).
|
||||||
|
const setCustomItem = (kind, row, name, inShop = true) => {
|
||||||
|
const pack = kind === "den" ? DEF_DEN_ITEM : DEF_ITEM;
|
||||||
|
const id = Number(row.id);
|
||||||
|
const stringId = kind === "den" ? row.nameStrId : row.titleStrId;
|
||||||
|
customRows.get(pack).set(id, row);
|
||||||
|
customStrings[stringId] = name;
|
||||||
|
strings[stringId] = name;
|
||||||
|
stringIds = null;
|
||||||
|
if (packs.has(pack)) {
|
||||||
|
packs.set(pack, [...packs.get(pack).filter(def => Number(def.id) !== id), row]);
|
||||||
|
}
|
||||||
|
if (kind === "den") {
|
||||||
|
denItemDefs.set(id, row);
|
||||||
|
denItemIds = denItemIds.includes(id) ? denItemIds : [...denItemIds, id];
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
itemDefs.set(id, row);
|
||||||
|
clothingIds = clothingIds.includes(id) ? clothingIds : [...clothingIds, id];
|
||||||
|
}
|
||||||
|
customInShop[kind][inShop ? "add" : "delete"](id);
|
||||||
|
clientPacksChanged.add(pack);
|
||||||
|
clientPacksChanged.add(DEF_LOCALIZATION_EN);
|
||||||
|
customVersion++;
|
||||||
|
};
|
||||||
|
|
||||||
|
// a custom item deleted (lib/customitems.js): out of the tables and the
|
||||||
|
// packs new games fetch. its name stays under its string id, unused.
|
||||||
|
const unsetCustomItem = (kind, id) => {
|
||||||
|
const pack = kind === "den" ? DEF_DEN_ITEM : DEF_ITEM;
|
||||||
|
const number = Number(id);
|
||||||
|
customRows.get(pack).delete(number);
|
||||||
|
if (packs.has(pack)) {
|
||||||
|
packs.set(pack, packs.get(pack).filter(def => Number(def.id) !== number));
|
||||||
|
}
|
||||||
|
if (kind === "den") {
|
||||||
|
denItemDefs.delete(number);
|
||||||
|
denItemIds = denItemIds.filter(one => one !== number);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
itemDefs.delete(number);
|
||||||
|
clothingIds = clothingIds.filter(one => one !== number);
|
||||||
|
}
|
||||||
|
customInShop[kind].delete(number);
|
||||||
|
clientPacksChanged.add(pack);
|
||||||
|
customVersion++;
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
init,
|
init,
|
||||||
|
setCustomItem,
|
||||||
|
unsetCustomItem,
|
||||||
|
// the custom items on sale, the newest first.
|
||||||
|
customShopIds: kind => [...customInShop[kind]].reverse(),
|
||||||
|
customVersion: () => customVersion,
|
||||||
|
// a change of a custom item that is not in the packs (its picture): one
|
||||||
|
// more version, for a game logging in to be told of it
|
||||||
|
customChanged: () => ++customVersion,
|
||||||
|
// the avatarUseFlags every clothing row has in the clients' pack (any animal)
|
||||||
|
EVERY_AVATAR,
|
||||||
|
// "clothing", "den" or "names" for a pack path with custom items in (lib/customitems.js sawPack), else null.
|
||||||
|
customPackKind: relPath => CUSTOM_PACK_KINDS.get(clientPackPaths.get(relPath)) || null,
|
||||||
load,
|
load,
|
||||||
itemDef: id => itemDefs.get(Number(id)),
|
itemDef: id => itemDefs.get(Number(id)),
|
||||||
clothingIds: () => clothingIds,
|
clothingIds: () => clothingIds,
|
||||||
@@ -451,6 +647,14 @@ module.exports = {
|
|||||||
denItemDef: id => denItemDefs.get(Number(id)),
|
denItemDef: id => denItemDefs.get(Number(id)),
|
||||||
denItemIds: () => denItemIds,
|
denItemIds: () => denItemIds,
|
||||||
clientPack,
|
clientPack,
|
||||||
|
// A changing rule must not leave the cached item pack permissive. The next
|
||||||
|
// client request remakes it, and current games receive an xdi row too.
|
||||||
|
invalidateClientItemPack: () => clientPackBodies.delete(DEF_ITEM),
|
||||||
|
clientItemRow,
|
||||||
|
clientItemDef: id => {
|
||||||
|
const def = itemDefs.get(Number(id));
|
||||||
|
return def ? clientItemRow(def) : null;
|
||||||
|
},
|
||||||
string: id => (Object.hasOwn(strings, id) ? String(strings[id]) : ""),
|
string: id => (Object.hasOwn(strings, id) ? String(strings[id]) : ""),
|
||||||
stringId: text => {
|
stringId: text => {
|
||||||
if (!stringIds) {
|
if (!stringIds) {
|
||||||
@@ -465,6 +669,10 @@ module.exports = {
|
|||||||
},
|
},
|
||||||
badgeIds: () => badgeIds,
|
badgeIds: () => badgeIds,
|
||||||
npcDef: id => npcDefs.get(Number(id)),
|
npcDef: id => npcDefs.get(Number(id)),
|
||||||
|
emoticonMediaId: id => emoticonMediaIds.get(Number(id)) || 0,
|
||||||
|
// the media ids of the newest Jamaa Journal pages out by `now` (seconds), newest first
|
||||||
|
newestJournalPages: (count, now = Date.now() / 1000) => journalPages.filter(page => page.start <= now)
|
||||||
|
.sort((one, other) => other.start - one.start || other.id - one.id).slice(0, count).map(page => page.page),
|
||||||
oddDenItemIds: () => oddDenItemIds,
|
oddDenItemIds: () => oddDenItemIds,
|
||||||
// den items that exist to be given by id and are in no shop.
|
// den items that exist to be given by id and are in no shop.
|
||||||
unsoldDenItemIds: () => extraMusic.ids,
|
unsoldDenItemIds: () => extraMusic.ids,
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
{"1":{"versions":[0,1,2,3,4,5,6,7],"colours":[["56c3d8","1078ff","4acaff","4876ba"],["8f48ff","3d00a7","5e1dff","5d0089"],["ff99f0","e150ff","ff6bf7","ff3dba"],["ac0912","ea004f","c40000","a10000"],["ff732b","dd3c4d","ff742d","e84138"],["f3ff86","d0ee19","e6ff3b","dfff05"],["63ff66","007917","23b700","035000"],["63565d","201219","551f4c","2f151f"]]},"9":{"versions":[0,1]},"13":{"versions":[0,1,2,3]},"19":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["7cbbff","2388ff","b9fffc","6bc1ff"],["be5bff","9348ff","42195b","ac43ff"],["e689c2","e45dad","fbfbfb","ea65c4"],["c8a0cd","cc434c","887e8e","ff4b4b"],["efcd34","e57712","ffffff","7bfff2"],["fff81a","fff81a","835c40","ff6bb3"],["4cbf00","43910b","ade53b","57de00"],["9e9e9e","5c5c7f","727c72","ffbf15"],["9e1616","3a3a3a","0f0f0f","ff1d1d"],["644b18","503000","e0b61f","7b4100"]]},"21":{"versions":[0,1,2]},"27":{"versions":[0,1,2,3]},"36":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["2b5eff","ffd646","56b8ff","b7ecff"],["ee58ff","5e0096","ffcf84","e3bcff"],["ff50d8","fbfbfb","ffbc1d","ffffef"],["ff3418","050505","ff9e53","ffffff"],["ff7323","ffa640","ffe42d","c7fcff"],["f8ff12","150f00","f3ff1a","050500"],["4caf00","adff3b","fff87e","c4ffe2"],["969696","ffdb5b","e0e5ff","809ca2"],["3d3d3d","830004","fafafa","0d0d0d"],["644b18","2b0c00","b9ab00","314800"]]},"37":{"versions":[0,1,3,4,5,6,7],"colours":[["a1daff","7bbfe8","b7eaff","4893ff"],["ceafff","a550ff","5d00b7","9c50ff"],["ff9999","990000","e95353","e11515"],["ffca94","f4a500","d07200","e37d48"],["dbe700","ecd743","ffff02","fff20a"],["afffa4","0a9100","75ff5e","30ff0d"],["727272","909090","f6f6f6","dedede"]]},"45":{"versions":[0,1,2,3,4,5,6,7]},"48":{"versions":[0,1,2,3,4,5,6,7]},"49":{"versions":[0,1,2,3,4,5,6,7]},"53":{"versions":[0,1,2,3,4,5,6,7]},"54":{"versions":[0,1,2,3,4,5,6,7]},"56":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["3e89d0","0d3673","b17400"],["9361ff","42195b","ff8ce4"],["f771a8","ff33a9","ffffff"],["d24743","ae3d59","434343"],["cf6227","e78100","ffe63d"],["ffea30","ff6d1a","bc7900"],["bde745","ff9400","dfaa00"],["969696","525252","ffffff"],["303030","f1f1f1","7d7d7d"],["91602d","ffe463","acb43e"]]},"83":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["c7f3ff","408aff","6bdaff"],["c976ff","5e0096","dcd4ff"],["ff89f3","ff4cac","f5d7ff"],["e43437","ffffff","ffffff"],["fd7500","ffcd63","fffbea"],["ffff3d","150f00","e2fff4"],["4caf00","adff3b","ffffff"],["969696","6b7c6b","dedede"],["212121","6b4496","030303"],["713700","ffffff","fffff2"]]},"91":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["3d5977","c47821","bc8000","ab6412"],["906fa5","705091","af8957","56486c"],["e5768c","f1f1da","e9b3c7","e2c1ce"],["bd483e","373736","7f5437","30312e"],["c37138","3a3539","c75524","474446"],["b46d00","ffe042","787878","525252"],["6b7e48","433422","a16951","58462c"],["8ca0a6","7b8f90","cc9d5d","dcdaa6"],["434342","4b4641","2b3331","212121"],["8a6341","78502a","dbab64","c3b39a"]]},"131":{"versions":[0,1,2,3,4,5]},"147":{"versions":[0,1,2,3,4,5,6,7],"colours":[["7bb8f7","fffedc","dcfcff","ffffff"],["9b4eff","ffeff5","eacaff","aa69ff"],["ff9efa","f33de9","ffd2fb","ca00c4"],["d20000","636363","e62525","616161"],["ef8454","e0ffdf","efe4ce","ffffff"],["fff802","af6f2b","faff58","1ecf00"],["3dc43d","7b7800","35ee45","31cc00"],["505050","ffffff","686868","494949"]]},"152":{"versions":[0,1,2,3,4,5,6,7],"colours":[["7bb8f7","ade0e6","e0db00"],["af37d7","3b0038","f0e579"],["e825e1","ff99f7","cfcfcf"],["d20000","ffacac","eddc6b"],["ff732b","ffda76","cecece"],["ede80a","a2a700","d1d1d1"],["3dc43d","afffa4","ffd938"],["484848","757575","fffaa4"]]},"226":{"versions":[0,1,2,3,4,5,6,7],"colours":[["060043","c4dbff","0015b4","3548ff"],["f5f5f5","42195b","8d00f2","ae74eb"],["ff71e3","ffeaf1","d400c9","ff3dba"],["ac0912","fffee7","fbffa7","ea0000"],["ede3a0","d8822e","fbdf9e","be4e33"],["fff812","639ac6","949400","dfd300"],["fffbca","008903","faffbc","008e3e"],["ffffff","505050","ffffff","343434"]]},"295":{"versions":[0,1,2,3,4,5,6,7],"colours":[["3458dd","4696ff"],["9a47d8","b875ff"],["ff8193","ffc4c6"],["ff2d2d","ff9c9c"],["f57a00","ffd47b"],["e7e700","ffffbb"],["05af00","daffa3"],["7d7d7d","d5d5d5"]]},"348":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["4589ff","fffbac","4086ff","7bc744"],["a640ff","fff986","6300c2","cbe26a"],["ffffff","00b999","ff35e5","bc910e"],["01000a","ff3333","bf0000","ffffff"],["ff7a00","d6d6af","ffffff","3a5000"],["fff800","73e3e0","f7f000","b1ea8c"],["4caf00","adff3b","7dd700","c4ffe2"],["727272","bebebe","e0e5ff","a6a6a6"],["404040","3d3d3d","828282","5e0000"],["644b18","d6c72b","664d00","506a16"]]},"350":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["48c5ff","ffff18","5bff35","0dff1e"],["a846ff","ff650d","ffff33","43f1ff"],["ff73d9","ff30c2","ffffff","00f2eb"],["ff2d2d","828282","ffe925","fdea00"],["e76a00","35f700","ffed10","fff930"],["ffff00","4bfaff","23f700","13ff02"],["76ff20","21ea00","ff7210","ffff02"],["ffffff","cfecff","0affff","fff928"],["717171","3c3c3c","00fdf6","02fff2"],["92663a","ffcfLine truncated
|
||||||
+34
-10
@@ -1,11 +1,14 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
const achievements = require("./achievements.js");
|
const achievements = require("./achievements.js");
|
||||||
const config = require("../config.js");
|
const config = require("../config.js");
|
||||||
const defpacks = require("./defpacks.js");
|
const defpacks = require("./defpacks.js");
|
||||||
|
const wearRules = require("./wearrules.js");
|
||||||
const epicDens = require("./epicdens.js");
|
const epicDens = require("./epicdens.js");
|
||||||
const masterpieces = require("./masterpieces.js");
|
const masterpieces = require("./masterpieces.js");
|
||||||
|
const eco = require("./eco.js");
|
||||||
const {CURRENCIES, MAX_DEN_ITEMS, hasRoom, activeAvatar, resolvePurchase, isUint} = require("./player.js");
|
const {CURRENCIES, MAX_DEN_ITEMS, hasRoom, activeAvatar, resolvePurchase, isUint} = require("./player.js");
|
||||||
|
|
||||||
// den items: owning, placing and recycling furniture (client side:
|
// den items: owning, placing and recycling furniture (client side:
|
||||||
@@ -51,13 +54,21 @@ const LAYER_EYES = "3";
|
|||||||
|
|
||||||
const isMannequin = item => (defpacks.denItemDef(item.def) || {}).specialType === SPECIAL_MANNEQUIN;
|
const isMannequin = item => (defpacks.denItemDef(item.def) || {}).specialType === SPECIAL_MANNEQUIN;
|
||||||
|
|
||||||
|
const mannequinAvatarType = item => Number((defpacks.denItemDef(item.def) || {}).mannequinAvatarDefId) || 0;
|
||||||
|
|
||||||
const mannequinOf = item => item.mannequin || {colors: [0, 0, 0], pattern: 0, eyes: 0, worn: [0, 0, 0, 0, 0]};
|
const 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];
|
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
|
// the clothing a mannequin of `owner`'s wears, slot by slot (undefined for
|
||||||
// an empty slot or a piece the owner no longer has).
|
// an empty slot or a piece the owner no longer has).
|
||||||
const mannequinClothes = (owner, item) => mannequinOf(item).worn.map(inv => (inv ? owner.items.find(piece => piece.inv === inv) : undefined));
|
const mannequinClothes = (owner, item) => {
|
||||||
|
const type = mannequinAvatarType(item);
|
||||||
|
return mannequinOf(item).worn.map(inv => {
|
||||||
|
const piece = inv ? owner.items.find(candidate => candidate.inv === inv) : undefined;
|
||||||
|
return piece && (!type || wearRules.mayWear(piece.def, type)) ? piece : undefined;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
// for the owner's own list (MannequinData.setupDataInvIdsOnly): the body,
|
// for the owner's own list (MannequinData.setupDataInvIdsOnly): the body,
|
||||||
// then the five inventory ids.
|
// then the five inventory ids.
|
||||||
@@ -73,12 +84,13 @@ const mannequinShownFields = (owner, item) =>
|
|||||||
// what the den editor sent for one mannequin, checked: [baseColor,
|
// what the den editor sent for one mannequin, checked: [baseColor,
|
||||||
// patternColor, patternDefId, eyeColor, eyeDefId, tail, leg, back, neck,
|
// patternColor, patternDefId, eyeColor, eyeDefId, tail, leg, back, neck,
|
||||||
// head]. null when any of it is not a whole number in range.
|
// head]. null when any of it is not a whole number in range.
|
||||||
const readMannequin = (account, fields) => {
|
const readMannequin = (account, item, fields) => {
|
||||||
if (fields.length !== 10 || !fields.every(isUint)) {
|
if (fields.length !== 10 || !fields.every(isUint)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const [base, patternColor, pattern, eyeColor, eyes, ...worn] = fields.map(Number);
|
const [base, patternColor, pattern, eyeColor, eyes, ...worn] = fields.map(Number);
|
||||||
const bodyPart = (defId, layer) => (defId && (defpacks.itemDef(defId) || {}).layerId === layer ? defId : 0);
|
const bodyPart = (defId, layer) => (defId && (defpacks.itemDef(defId) || {}).layerId === layer ? defId : 0);
|
||||||
|
const type = mannequinAvatarType(item);
|
||||||
return {
|
return {
|
||||||
colors: [base, patternColor, eyeColor],
|
colors: [base, patternColor, eyeColor],
|
||||||
pattern: bodyPart(pattern, LAYER_PATTERN),
|
pattern: bodyPart(pattern, LAYER_PATTERN),
|
||||||
@@ -86,7 +98,7 @@ const readMannequin = (account, fields) => {
|
|||||||
worn: worn.map((inv, slot) => {
|
worn: worn.map((inv, slot) => {
|
||||||
const piece = inv && account.items.find(candidate => candidate.inv === inv);
|
const piece = inv && account.items.find(candidate => candidate.inv === inv);
|
||||||
const def = piece && defpacks.itemDef(piece.def);
|
const def = piece && defpacks.itemDef(piece.def);
|
||||||
return def && MANNEQUIN_SLOT_LAYERS[slot].includes(def.layerId) ? inv : 0;
|
return def && MANNEQUIN_SLOT_LAYERS[slot].includes(def.layerId) && (!type || wearRules.mayWear(piece.def, type)) ? inv : 0;
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -108,9 +120,14 @@ const petsInDen = account => account.pets.filter(pet => pet.inDen && pet.inDen.d
|
|||||||
// it is not placed there. the three after "approved" are a masterpiece's
|
// it is not placed there. the three after "approved" are a masterpiece's
|
||||||
// (lib/masterpieces.js); one not approved yet the client keeps out of dens,
|
// (lib/masterpieces.js); one not approved yet the client keeps out of dens,
|
||||||
// trades and the recycler.
|
// trades and the recycler.
|
||||||
|
// an item whose def is gone (a custom item deleted) is left out of both: the
|
||||||
|
// client skipped it without reading all its fields, and read every item after
|
||||||
|
// it wrong, placed ones as not placed and the den's floor and wallpaper lost.
|
||||||
|
const known = item => Boolean(defpacks.denItemDef(item.def));
|
||||||
|
|
||||||
const sendDenItems = session => {
|
const sendDenItems = session => {
|
||||||
const {account} = session;
|
const {account} = session;
|
||||||
const {denItems} = account;
|
const denItems = account.denItems.filter(known);
|
||||||
const pets = petsInDen(account);
|
const pets = petsInDen(account);
|
||||||
session.sendXt("di", -1, account.activeDen, denItems.length, pets.length,
|
session.sendXt("di", -1, account.activeDen, denItems.length, pets.length,
|
||||||
...denItems.flatMap(item => {
|
...denItems.flatMap(item => {
|
||||||
@@ -123,19 +140,22 @@ const sendDenItems = session => {
|
|||||||
|
|
||||||
// DenXtCommManager.denStateResponse: [itemCount, petCount, forceReload,
|
// DenXtCommManager.denStateResponse: [itemCount, petCount, forceReload,
|
||||||
// (invIdx, defId, placed, x, y, version, flipped, userNameLink, imageId,
|
// (invIdx, defId, placed, x, y, version, flipped, userNameLink, imageId,
|
||||||
// creatorDbId, creatorUuid, [mannequin], ?)..., (invIdx, lBits, uBits, eBits,
|
// creatorDbId, creatorUuid, [mannequin], eco state)..., (invIdx, lBits, uBits, eBits,
|
||||||
// category, x, y, flipped, createdTs, personality, toy, food, name)...].
|
// category, x, y, flipped, createdTs, personality, toy, food, name)...].
|
||||||
// forceReload makes the client finish a pending room change, so it is set
|
// forceReload makes the client finish a pending room change, so it is set
|
||||||
// when the den has just been entered.
|
// when the den has just been entered.
|
||||||
const sendDenState = (session, room, forceReload = true) => {
|
const sendDenState = (session, room, forceReload = true) => {
|
||||||
const owner = room.denOwner;
|
const owner = room.denOwner;
|
||||||
const placed = itemsInDen(owner).filter(item => masterpieces.itemApproved(item));
|
const placed = itemsInDen(owner).filter(item => known(item) && masterpieces.itemApproved(item));
|
||||||
const pets = petsInDen(owner);
|
const pets = petsInDen(owner);
|
||||||
session.sendXt("ds", room.id, placed.length, pets.length, forceReload ? 1 : 0,
|
session.sendXt("ds", room.id, placed.length, pets.length, forceReload ? 1 : 0,
|
||||||
...placed.flatMap(item => {
|
...placed.flatMap(item => {
|
||||||
const spot = spotOf(item, owner.activeDen);
|
const spot = spotOf(item, owner.activeDen);
|
||||||
return [item.inv, item.def, 1, spot.x, spot.y, item.version, spot.flip, "", ...masterpieces.itemFields(item),
|
// Keep the editor's real placement category. Sending every placed
|
||||||
...mannequinShownFields(owner, item), 0];
|
// object as category 1 made wall/floor items enter the wrong display
|
||||||
|
// layer when a den was reloaded or another player visited.
|
||||||
|
return [item.inv, item.def, spot.cat || 1, spot.x, spot.y, item.version, spot.flip, "", ...masterpieces.itemFields(item),
|
||||||
|
...mannequinShownFields(owner, item), eco.consumerState(owner, item)];
|
||||||
}),
|
}),
|
||||||
...pets.flatMap(pet => [pet.inv, pet.lBits, pet.uBits, pet.eBits, PET_CATEGORY, pet.inDen.x, pet.inDen.y, pet.inDen.flip,
|
...pets.flatMap(pet => [pet.inv, pet.lBits, pet.uBits, pet.eBits, PET_CATEGORY, pet.inDen.x, pet.inDen.y, pet.inDen.flip,
|
||||||
pet.createdAt, pet.personality || 0, pet.toy || 0, pet.food || 0, pet.name]));
|
pet.createdAt, pet.personality || 0, pet.toy || 0, pet.food || 0, pet.name]));
|
||||||
@@ -260,7 +280,7 @@ const handlers = ({others, findOnline}) => {
|
|||||||
const item = giveDenItem(account, masterpieces.DEN_ITEM, frame);
|
const item = giveDenItem(account, masterpieces.DEN_ITEM, frame);
|
||||||
item.image = String(paintingId);
|
item.image = String(paintingId);
|
||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
console.log(`[world] ${account.username} made masterpiece ${item.image}${masterpieces.itemApproved(item) ? "" : " (waiting for review in the admin panel)"}`);
|
console.log(`[world] ${logText(account.username)} made masterpiece ${logText(item.image)}${logText(masterpieces.itemApproved(item) ? "" : " (waiting for review in the admin panel)")}`);
|
||||||
session.sendXt("db", -1, 1, account.currency.diamonds || 0, 0, CURRENCY_DIAMONDS, item.inv);
|
session.sendXt("db", -1, 1, account.currency.diamonds || 0, 0, CURRENCY_DIAMONDS, item.inv);
|
||||||
sendDenItems(session);
|
sendDenItems(session);
|
||||||
};
|
};
|
||||||
@@ -366,6 +386,10 @@ const handlers = ({others, findOnline}) => {
|
|||||||
session.sendXt("dss", -1);
|
session.sendXt("dss", -1);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// the eco credits earned at the den's rate until now (lib/eco.js)
|
||||||
|
if (account.eco) {
|
||||||
|
eco.accrue(account);
|
||||||
|
}
|
||||||
const applied = [];
|
const applied = [];
|
||||||
const byInv = new Map(account.denItems.map(candidate => [candidate.inv, candidate]));
|
const byInv = new Map(account.denItems.map(candidate => [candidate.inv, candidate]));
|
||||||
const mannequins = account.denItems.filter(candidate => candidate.mannequin);
|
const mannequins = account.denItems.filter(candidate => candidate.mannequin);
|
||||||
@@ -403,7 +427,7 @@ const handlers = ({others, findOnline}) => {
|
|||||||
else {
|
else {
|
||||||
delete item.spots[account.activeDen];
|
delete item.spots[account.activeDen];
|
||||||
}
|
}
|
||||||
const mannequin = isMannequin(item) && readMannequin(account, outfit);
|
const mannequin = isMannequin(item) && readMannequin(account, item, outfit);
|
||||||
if (mannequin) {
|
if (mannequin) {
|
||||||
// A piece of clothing is on one mannequin at a time.
|
// A piece of clothing is on one mannequin at a time.
|
||||||
for (const other of mannequins) {
|
for (const other of mannequins) {
|
||||||
|
|||||||
+443
@@ -0,0 +1,443 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
|
const crypto = require("crypto");
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
const accounts = require("./accounts.js");
|
||||||
|
const config = require("../config.js");
|
||||||
|
|
||||||
|
// the computers players sign in from, for telling alts apart and keeping a
|
||||||
|
// banned player's computer out (the "device ban" of the panels).
|
||||||
|
//
|
||||||
|
// the client (1.3.0 and on) sends, with every sign-in, hashes of what it
|
||||||
|
// can read about the computer: the system's own id (MachineGuid on Windows,
|
||||||
|
// IOPlatformUUID on macOS, /etc/machine-id on Linux), the board's id or
|
||||||
|
// serial, the disks' serials, the network cards' addresses, and an id of
|
||||||
|
// its own it keeps in two or three places. none of them is sent as it is:
|
||||||
|
// each is SHA-256 of "burrow-device:<kind>:<value>", and here that is keyed
|
||||||
|
// again with a secret of this server's (data/device-key), so what is kept
|
||||||
|
// is of no use anywhere else.
|
||||||
|
//
|
||||||
|
// two computers are taken for one when they share at least MIN_MATCHING of
|
||||||
|
// these (owner, 2026-10-23: one or two in common was too often someone
|
||||||
|
// else's), for a ban and for an alt alike: someone who edits
|
||||||
|
// /etc/machine-id or deletes MachineGuid still has the same board, disks
|
||||||
|
// and the client's own id. the network card's address (MAC_KIND) does not
|
||||||
|
// count towards them: it is easily changed and sometimes shared, so it bans
|
||||||
|
// nothing; it is written down for the moderators instead. values every cheap board or VM has ("To be filled by
|
||||||
|
// O.E.M.", all zeros) are left out here, so that no ban falls on everyone
|
||||||
|
// who has one. what the client noticed was wrong (the system id missing, or
|
||||||
|
// not shaped as it always is) comes as notes, and is written down too.
|
||||||
|
//
|
||||||
|
// the client is open source, so a player who builds their own can send
|
||||||
|
// anything; this keeps out the usual ban evader (a VPN, a new account),
|
||||||
|
// not a determined one. the moderators see the alerts and decide.
|
||||||
|
|
||||||
|
const SCHEMA = `
|
||||||
|
CREATE TABLE IF NOT EXISTS device_bans (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
ids TEXT NOT NULL,
|
||||||
|
reason TEXT NOT NULL,
|
||||||
|
by TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
account_id INTEGER,
|
||||||
|
username TEXT NOT NULL DEFAULT ''
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS device_alerts (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
at INTEGER NOT NULL,
|
||||||
|
account_id INTEGER NOT NULL,
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
kind TEXT NOT NULL,
|
||||||
|
detail TEXT NOT NULL DEFAULT ''
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS device_alerts_account ON device_alerts (account_id, id);
|
||||||
|
`;
|
||||||
|
|
||||||
|
const KINDS = ["os", "board", "disk", "install", "mac"];
|
||||||
|
const STRONG = ["os", "board", "disk", "install"];
|
||||||
|
const MAC_KIND = "mac";
|
||||||
|
const MIN_MATCHING = 3; // ids but a network card's two computers share to be taken for one
|
||||||
|
const LISTS = ["disk", "mac"]; // sent as lists; the rest one each
|
||||||
|
const MAX_IN_LIST = 8;
|
||||||
|
const MAX_KEPT = 60; // ids an account keeps, the latest
|
||||||
|
const DAYS_KEPT = 90; // what a ban by account takes, and alts look at
|
||||||
|
const ALERT_EVERY_SECONDS = 86400; // one alert of a kind for an account a day
|
||||||
|
const MAX_ALERTS_SHOWN = 200;
|
||||||
|
const MAX_REASON = 300;
|
||||||
|
const HASH = /^[0-9a-f]{64}$/;
|
||||||
|
const NOTE = /^[a-z_]{1,24}$/;
|
||||||
|
// notes from the client that mean someone has been at the computer's ids.
|
||||||
|
const TAMPER_NOTES = {
|
||||||
|
os_missing: "the system id is missing",
|
||||||
|
os_odd: "the system id is not shaped like one",
|
||||||
|
install_mismatch: "the client's own ids disagree",
|
||||||
|
};
|
||||||
|
|
||||||
|
// values that are everyone's: on cheap boards, in VMs, or where the maker
|
||||||
|
// wrote nothing. the client sends them hashed like any other, so they are
|
||||||
|
// hashed here the same way to be known.
|
||||||
|
const JUNK = {
|
||||||
|
os: ["00000000-0000-0000-0000-000000000000", "ffffffff-ffff-ffff-ffff-ffffffffffff", "00000000000000000000000000000000",
|
||||||
|
"ffffffffffffffffffffffffffffffff"],
|
||||||
|
board: ["00000000-0000-0000-0000-000000000000", "ffffffff-ffff-ffff-ffff-ffffffffffff", "03000200-0400-0500-0006-000700080009",
|
||||||
|
"12345678-1234-5678-90ab-cddeefaabbcc", "to be filled by o.e.m.", "default string", "system serial number", "chassis serial number",
|
||||||
|
"not applicable", "not specified", "none", "n/a", "0", "0123456789", "123456789", "1234567890", "serial", "invalid"],
|
||||||
|
disk: ["0", "none", "0000_0000_0000_0000", "default string", "to be filled by o.e.m.", "not specified"],
|
||||||
|
mac: ["00:00:00:00:00:00", "ff:ff:ff:ff:ff:ff"],
|
||||||
|
};
|
||||||
|
const clientHash = (kind, value) => crypto.createHash("sha256").update(`burrow-device:${kind}:${value}`).digest("hex");
|
||||||
|
const JUNK_HASHES = new Set(Object.entries(JUNK).flatMap(([kind, values]) => values.map(value => clientHash(kind, value))));
|
||||||
|
|
||||||
|
const now = () => Math.floor(Date.now() / 1000);
|
||||||
|
const db = () => accounts.database();
|
||||||
|
const clean = (text, max) => String(text === undefined || text === null ? "" : text).replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, max);
|
||||||
|
const NO_REASON = "Not provided";
|
||||||
|
|
||||||
|
let key = null; // this server's secret for keying the ids
|
||||||
|
const banned = new Map(); // "kind:id" -> ban {id, ids, reason, by, createdAt, accountId, username}
|
||||||
|
const holders = new Map(); // "kind:id" -> Set of account ids that used it
|
||||||
|
|
||||||
|
const keyFile = () => path.join(config.dataDir, "device-key");
|
||||||
|
|
||||||
|
// the account's ids: [{kind, id, first, last}], the latest first.
|
||||||
|
const idsOf = account => {
|
||||||
|
if (!Array.isArray(account.hwids)) {
|
||||||
|
account.hwids = [];
|
||||||
|
}
|
||||||
|
return account.hwids;
|
||||||
|
};
|
||||||
|
const tag = entry => `${entry.kind}:${entry.id}`;
|
||||||
|
const isStrong = id => STRONG.includes(id.split(":")[0]);
|
||||||
|
|
||||||
|
const banRow = row => ({id: row.id, ids: JSON.parse(row.ids), reason: row.reason, by: row.by, createdAt: row.created_at,
|
||||||
|
accountId: row.account_id, username: row.username});
|
||||||
|
|
||||||
|
const load = () => {
|
||||||
|
try {
|
||||||
|
key = fs.readFileSync(keyFile());
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
key = crypto.randomBytes(32);
|
||||||
|
fs.writeFileSync(keyFile(), key, {mode: 0o600});
|
||||||
|
}
|
||||||
|
db().exec(SCHEMA);
|
||||||
|
for (const row of db().prepare("SELECT * FROM device_bans").all()) {
|
||||||
|
const ban = banRow(row);
|
||||||
|
for (const id of ban.ids) {
|
||||||
|
banned.set(id, ban);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const account of accounts.all()) {
|
||||||
|
for (const entry of idsOf(account)) {
|
||||||
|
remember(account, tag(entry));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const remember = (account, id) => {
|
||||||
|
if (!holders.has(id)) {
|
||||||
|
holders.set(id, new Set());
|
||||||
|
}
|
||||||
|
holders.get(id).add(account.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
// what a sign-in said about its computer (`device` from its body), keyed:
|
||||||
|
// {ids: [{kind, id}], notes: [..]}, or null when it said nothing usable.
|
||||||
|
const read = device => {
|
||||||
|
if (!device || typeof device !== "object" || device.v !== 1 || !device.ids || typeof device.ids !== "object") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const ids = [];
|
||||||
|
for (const kind of KINDS) {
|
||||||
|
const given = device.ids[kind];
|
||||||
|
const values = LISTS.includes(kind) ? (Array.isArray(given) ? given.slice(0, MAX_IN_LIST) : []) : [given];
|
||||||
|
for (const value of values) {
|
||||||
|
const hash = String(value || "").toLowerCase();
|
||||||
|
if (HASH.test(hash) && !JUNK_HASHES.has(hash)) {
|
||||||
|
ids.push({kind, id: crypto.createHmac("sha256", key).update(`${kind}:${hash}`).digest("hex").slice(0, 32)});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const notes = Array.isArray(device.notes) ? device.notes.slice(0, 8).map(String).filter(note => NOTE.test(note)) : [];
|
||||||
|
// something to tell one computer by, beyond a network card.
|
||||||
|
return ids.some(entry => STRONG.includes(entry.kind)) ? {ids, notes} : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// the ban that has at least MIN_MATCHING of these "kind:id" in it, or
|
||||||
|
// null. network cards' addresses are not counted (see the top).
|
||||||
|
const banMatching = ids => {
|
||||||
|
const strong = new Set(ids.filter(isStrong));
|
||||||
|
const looked = new Set();
|
||||||
|
for (const id of strong) {
|
||||||
|
const ban = banned.get(id);
|
||||||
|
if (ban && !looked.has(ban.id)) {
|
||||||
|
looked.add(ban.id);
|
||||||
|
if (ban.ids.filter(one => strong.has(one)).length >= MIN_MATCHING) {
|
||||||
|
return ban;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// the ban that keeps this computer out, or null.
|
||||||
|
const banOf = device => banMatching(device.ids.map(tag));
|
||||||
|
|
||||||
|
// the ban on any computer the account signed in from lately, or null: for
|
||||||
|
// the client asking why its game was stopped.
|
||||||
|
const banOfAccount = account => banMatching(idsOf(account).filter(entry => entry.last > now() - DAYS_KEPT * 86400).map(tag));
|
||||||
|
|
||||||
|
const alert = (account, kind, detail) => {
|
||||||
|
const last = db().prepare("SELECT at FROM device_alerts WHERE account_id = ? AND kind = ? ORDER BY id DESC LIMIT 1").get(account.id, kind);
|
||||||
|
if (last && last.at > now() - ALERT_EVERY_SECONDS) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
db().prepare("INSERT INTO device_alerts (at, account_id, username, kind, detail) VALUES (?, ?, ?, ?, ?)").run(now(), account.id, account.username, kind, detail);
|
||||||
|
console.log(`[devices] ${logText(account.username)}: ${logText(kind)} (${logText(detail)})`);
|
||||||
|
};
|
||||||
|
|
||||||
|
// an account signed in from this computer: its ids are kept, and what looks
|
||||||
|
// wrong is written down. `isBanned(account)` says whether another account is
|
||||||
|
// banned now (lib/moderation.js), for "shares a computer with a banned one".
|
||||||
|
const seen = (account, device, isBanned) => {
|
||||||
|
const list = idsOf(account);
|
||||||
|
const at = now();
|
||||||
|
for (const entry of device.ids) {
|
||||||
|
const kept = list.find(other => other.kind === entry.kind && other.id === entry.id);
|
||||||
|
if (kept) {
|
||||||
|
kept.last = at;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
list.push({kind: entry.kind, id: entry.id, first: at, last: at});
|
||||||
|
}
|
||||||
|
remember(account, tag(entry));
|
||||||
|
}
|
||||||
|
list.sort((one, other) => other.last - one.last);
|
||||||
|
for (const dropped of list.splice(MAX_KEPT)) {
|
||||||
|
const set = holders.get(tag(dropped));
|
||||||
|
if (set) {
|
||||||
|
set.delete(account.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const tampered = device.notes.filter(note => TAMPER_NOTES[note]).map(note => TAMPER_NOTES[note]);
|
||||||
|
if (tampered.length) {
|
||||||
|
alert(account, "tampered", tampered.join(", "));
|
||||||
|
}
|
||||||
|
const nearBan = device.ids.find(entry => entry.kind === MAC_KIND && banned.has(tag(entry)));
|
||||||
|
if (nearBan) {
|
||||||
|
alert(account, "near_ban", `same network card as a hardware ban (${banned.get(tag(nearBan)).username || "no account"})`);
|
||||||
|
}
|
||||||
|
const shared = new Map(); // account id -> ids in common
|
||||||
|
for (const entry of device.ids.filter(one => STRONG.includes(one.kind))) {
|
||||||
|
for (const id of holders.get(tag(entry)) || []) {
|
||||||
|
if (id !== account.id) {
|
||||||
|
shared.set(id, (shared.get(id) || 0) + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const sharers = new Set();
|
||||||
|
for (const [id, count] of shared) {
|
||||||
|
const other = count >= MIN_MATCHING ? accounts.byId(id) : null;
|
||||||
|
if (other && isBanned(other)) {
|
||||||
|
sharers.add(other.username);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (sharers.size) {
|
||||||
|
alert(account, "shares_banned", `same hardware as banned ${[...sharers].slice(0, 5).join(", ")}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// the other accounts that used one of this one's computers, sharing at
|
||||||
|
// least MIN_MATCHING of its ids: [{username, kinds: [kind]}], most in
|
||||||
|
// common first.
|
||||||
|
const alts = account => {
|
||||||
|
const found = new Map(); // account id -> {kinds: Set, strong: ids in common but network cards}
|
||||||
|
for (const entry of idsOf(account)) {
|
||||||
|
for (const id of holders.get(tag(entry)) || []) {
|
||||||
|
if (id !== account.id) {
|
||||||
|
if (!found.has(id)) {
|
||||||
|
found.set(id, {kinds: new Set(), strong: 0});
|
||||||
|
}
|
||||||
|
found.get(id).kinds.add(entry.kind);
|
||||||
|
found.get(id).strong += STRONG.includes(entry.kind) ? 1 : 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...found].filter(([, shared]) => shared.strong >= MIN_MATCHING)
|
||||||
|
.map(([id, shared]) => ({account: accounts.byId(id), kinds: [...shared.kinds], strong: shared.strong}))
|
||||||
|
.filter(entry => entry.account)
|
||||||
|
.sort((one, other) => other.strong - one.strong || other.kinds.length - one.kinds.length || one.account.username.localeCompare(other.account.username))
|
||||||
|
.map(entry => ({username: entry.account.username, kinds: entry.kinds}));
|
||||||
|
};
|
||||||
|
|
||||||
|
// how many computers' worth of ids an account has, for the panels.
|
||||||
|
const knownFor = account => ({ids: idsOf(account).length, lastAt: idsOf(account).reduce((latest, entry) => Math.max(latest, entry.last), 0)});
|
||||||
|
|
||||||
|
// bans every computer the account signed in from in the last DAYS_KEPT
|
||||||
|
// days. returns {ban} or {error}. `out(ban)` puts out whoever plays from
|
||||||
|
// one of them.
|
||||||
|
const banAccount = (account, reason, by) => {
|
||||||
|
const ids = [...new Set(idsOf(account).filter(entry => entry.last > now() - DAYS_KEPT * 86400).map(tag))];
|
||||||
|
if (ids.filter(isStrong).length < MIN_MATCHING) {
|
||||||
|
return {error: `Fewer than ${MIN_MATCHING} hardware IDs known for them.`};
|
||||||
|
}
|
||||||
|
if (ids.filter(isStrong).every(id => banned.has(id))) {
|
||||||
|
return {error: "Their hardware is banned already."};
|
||||||
|
}
|
||||||
|
const text = clean(reason, MAX_REASON) || NO_REASON;
|
||||||
|
const result = db().prepare("INSERT INTO device_bans (ids, reason, by, created_at, account_id, username) VALUES (?, ?, ?, ?, ?, ?)")
|
||||||
|
.run(JSON.stringify(ids), text, by, now(), account.id, account.username);
|
||||||
|
const ban = {id: Number(result.lastInsertRowid), ids, reason: text, by, createdAt: now(), accountId: account.id, username: account.username};
|
||||||
|
for (const id of ids) {
|
||||||
|
banned.set(id, ban);
|
||||||
|
}
|
||||||
|
return {ban};
|
||||||
|
};
|
||||||
|
|
||||||
|
// the accounts playing from one of a ban's computers, by their latest ids:
|
||||||
|
// those with at least MIN_MATCHING of its ids.
|
||||||
|
const accountsUnder = ban => {
|
||||||
|
const found = new Map(); // account id -> ids in common
|
||||||
|
for (const id of new Set(ban.ids.filter(isStrong))) {
|
||||||
|
for (const accountId of holders.get(id) || []) {
|
||||||
|
found.set(accountId, (found.get(accountId) || 0) + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...found].filter(([, count]) => count >= MIN_MATCHING).map(([id]) => accounts.byId(id)).filter(Boolean);
|
||||||
|
};
|
||||||
|
|
||||||
|
const unban = id => {
|
||||||
|
const row = db().prepare("SELECT * FROM device_bans WHERE id = ?").get(Number(id));
|
||||||
|
if (!row) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const ban = banRow(row);
|
||||||
|
db().prepare("DELETE FROM device_bans WHERE id = ?").run(ban.id);
|
||||||
|
for (const one of ban.ids) {
|
||||||
|
if (banned.get(one) && banned.get(one).id === ban.id) {
|
||||||
|
banned.delete(one);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ban;
|
||||||
|
};
|
||||||
|
|
||||||
|
// one ban as kept, with the account it was made with (accountId), or null:
|
||||||
|
// for the moderator panel to see whose it is before lifting it.
|
||||||
|
const banById = id => {
|
||||||
|
const row = db().prepare("SELECT * FROM device_bans WHERE id = ?").get(Number(id));
|
||||||
|
return row ? banRow(row) : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// the bans, newest first: their ids, and the accounts that used them.
|
||||||
|
const MAX_LISTED_ACCOUNTS = 20;
|
||||||
|
const list = () => db().prepare("SELECT * FROM device_bans ORDER BY id DESC").all().map(banRow)
|
||||||
|
.map(ban => ({id: ban.id, username: ban.username, reason: ban.reason, by: ban.by, createdAt: ban.createdAt,
|
||||||
|
ids: ban.ids.map(one => ({kind: one.split(":")[0], id: one.split(":")[1]})),
|
||||||
|
accounts: accountsUnder(ban).map(account => account.username).sort().slice(0, MAX_LISTED_ACCOUNTS)}));
|
||||||
|
|
||||||
|
// the account's ids for the panels, the latest first: [{kind, id, first,
|
||||||
|
// last, banned: the ban's id or 0, others: how many other accounts used it}].
|
||||||
|
const idsFor = account => idsOf(account).map(entry => {
|
||||||
|
const ban = banned.get(tag(entry));
|
||||||
|
const set = holders.get(tag(entry));
|
||||||
|
return {kind: entry.kind, id: entry.id, first: entry.first, last: entry.last, banned: ban ? ban.id : 0,
|
||||||
|
others: set ? [...set].filter(id => id !== account.id).length : 0};
|
||||||
|
});
|
||||||
|
|
||||||
|
// the bans that keep the account's computers out (by any of its ids but a
|
||||||
|
// network card's, however old), and those made with it: what "unban
|
||||||
|
// computers" on its page lifts.
|
||||||
|
const bansOfAccount = account => {
|
||||||
|
const found = new Map();
|
||||||
|
for (const entry of idsOf(account)) {
|
||||||
|
const ban = banned.get(tag(entry));
|
||||||
|
if (ban && STRONG.includes(entry.kind)) {
|
||||||
|
found.set(ban.id, ban);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const ban of banned.values()) {
|
||||||
|
if (ban.accountId === account.id) {
|
||||||
|
found.set(ban.id, ban);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...found.values()];
|
||||||
|
};
|
||||||
|
|
||||||
|
// the accounts that used an id, or any id starting with what was typed (a
|
||||||
|
// "kind:" in front is let be): {error} or {players: [{account, kinds,
|
||||||
|
// lastAt}]}, the latest first.
|
||||||
|
const MIN_ID_QUERY = 6;
|
||||||
|
const MAX_ID_FOUND = 100;
|
||||||
|
const search = query => {
|
||||||
|
const wanted = String(query || "").trim().toLowerCase().replace(/^[a-z]+:/, "").slice(0, 32);
|
||||||
|
if (wanted.length < MIN_ID_QUERY || !/^[0-9a-f]+$/.test(wanted)) {
|
||||||
|
return {error: `Type at least ${MIN_ID_QUERY} characters of a hardware ID.`};
|
||||||
|
}
|
||||||
|
const found = new Map(); // account id -> {kinds, lastAt}
|
||||||
|
for (const [key, set] of holders) {
|
||||||
|
const [kind, id] = key.split(":");
|
||||||
|
if (!id.startsWith(wanted)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const accountId of set) {
|
||||||
|
const account = accounts.byId(accountId);
|
||||||
|
const entry = account && idsOf(account).find(one => one.kind === kind && one.id === id);
|
||||||
|
if (entry) {
|
||||||
|
const kept = found.get(accountId) || {account, kinds: new Set(), lastAt: 0};
|
||||||
|
kept.kinds.add(kind);
|
||||||
|
kept.lastAt = Math.max(kept.lastAt, entry.last);
|
||||||
|
found.set(accountId, kept);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {players: [...found.values()].map(entry => ({...entry, kinds: [...entry.kinds]}))
|
||||||
|
.sort((one, other) => other.lastAt - one.lastAt).slice(0, MAX_ID_FOUND)};
|
||||||
|
};
|
||||||
|
|
||||||
|
// is any of the account's computers banned? the ban's id, or 0.
|
||||||
|
const bannedId = account => {
|
||||||
|
const ban = banOfAccount(account);
|
||||||
|
return ban ? ban.id : 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ALERT_NAMES = {tampered: "Hardware IDs tampered with", near_ban: "Network card of a hardware ban", shares_banned: "Same hardware as a banned player"};
|
||||||
|
const alertRow = row => ({id: row.id, at: row.at, username: row.username, kind: row.kind, name: ALERT_NAMES[row.kind] || row.kind, detail: row.detail});
|
||||||
|
const alerts = () => db().prepare("SELECT * FROM device_alerts ORDER BY id DESC LIMIT ?").all(MAX_ALERTS_SHOWN).map(alertRow);
|
||||||
|
const alertsOf = account => db().prepare("SELECT * FROM device_alerts WHERE account_id = ? ORDER BY id DESC LIMIT 50").all(account.id).map(alertRow);
|
||||||
|
|
||||||
|
// an account being deleted: its ids and alerts go. bans stay: they are of
|
||||||
|
// computers, not of the account.
|
||||||
|
const forget = account => {
|
||||||
|
for (const entry of idsOf(account)) {
|
||||||
|
const set = holders.get(tag(entry));
|
||||||
|
if (set) {
|
||||||
|
set.delete(account.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
db().prepare("DELETE FROM device_alerts WHERE account_id = ?").run(account.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
// sign-in tokens last given to (or brought back by) a launcher that sent no
|
||||||
|
// device ids: one from before 1.3.0, or not ours. with config.requireDevice
|
||||||
|
// its sign-in still goes through, so that the game loads and its own login
|
||||||
|
// popup can say to update (lib/world.js), which a refused sign-in cannot.
|
||||||
|
// kept by hash, in memory: such a launcher signs in again each time it starts.
|
||||||
|
const MAX_OUTDATED = 20000;
|
||||||
|
const outdatedTokens = new Set();
|
||||||
|
const tokenKey = token => crypto.createHash("sha256").update(String(token)).digest("hex");
|
||||||
|
const noteLauncher = (token, hasIds) => {
|
||||||
|
const key = tokenKey(token);
|
||||||
|
if (hasIds) {
|
||||||
|
outdatedTokens.delete(key);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (outdatedTokens.size >= MAX_OUTDATED) {
|
||||||
|
outdatedTokens.delete(outdatedTokens.values().next().value);
|
||||||
|
}
|
||||||
|
outdatedTokens.add(key);
|
||||||
|
};
|
||||||
|
const launcherOutdated = token => outdatedTokens.has(tokenKey(token));
|
||||||
|
|
||||||
|
module.exports = {noteLauncher, launcherOutdated, load, read, banOf, banOfAccount, seen, alts, knownFor, banAccount, accountsUnder, unban, banById, list, idsFor, bansOfAccount, search, bannedId, alerts, alertsOf, forget, clientHash};
|
||||||
+295
@@ -0,0 +1,295 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const crypto = require("crypto");
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
|
const accounts = require("./accounts.js");
|
||||||
|
const badges = require("./badges.js");
|
||||||
|
const config = require("../config.js");
|
||||||
|
|
||||||
|
// a player's Discord account, linked on the account page by signing in to
|
||||||
|
// Discord (OAuth2, scope "identify"): the only way a Discord username gets
|
||||||
|
// onto a player's card, so the name shown is theirs. one Discord account
|
||||||
|
// for one Burrow account, or a single boost would badge a player's every
|
||||||
|
// account.
|
||||||
|
//
|
||||||
|
// the Discord Server Booster badge follows the linked account: given while
|
||||||
|
// it boosts Burrow's Discord server, taken off when it stops, checked when
|
||||||
|
// the account is linked and again every RECHECK_HOURS. Burrow's bot asks
|
||||||
|
// Discord (GET /guilds/<id>/members/<user id>, which needs no privileged
|
||||||
|
// intent: the bot only has to be in the server). an account that is not
|
||||||
|
// linked keeps whatever badges the admin gave it.
|
||||||
|
//
|
||||||
|
// with AJ_DISCORD_CLIENT_ID and AJ_DISCORD_CLIENT_SECRET unset, linking is
|
||||||
|
// off; without AJ_DISCORD_BOT_TOKEN and AJ_DISCORD_GUILD_ID, the booster
|
||||||
|
// badge is left alone.
|
||||||
|
|
||||||
|
const API = "https://discord.com/api/v10";
|
||||||
|
const AUTHORIZE = "https://discord.com/oauth2/authorize";
|
||||||
|
const STATE_MINUTES = 10;
|
||||||
|
const MAX_STATES = 10000;
|
||||||
|
const RECHECK_HOURS = 6;
|
||||||
|
const RECHECK_GAP_MS = 300; // between two members asked about, under Discord's rate limit
|
||||||
|
const TIMEOUT_MS = 15000;
|
||||||
|
const BOOSTER = "booster";
|
||||||
|
|
||||||
|
const linking = () => Boolean(config.discord.clientId && config.discord.clientSecret);
|
||||||
|
const boostChecks = () => Boolean(config.discord.botToken && config.discord.guildId);
|
||||||
|
const redirectUri = () => `${config.siteUrl}account/discord/callback`;
|
||||||
|
const adminRedirectUri = () => `${config.siteUrl}dashboard/admin/discord/callback`;
|
||||||
|
const staffRedirectUri = () => `${config.siteUrl}dashboard/staff/discord/callback`;
|
||||||
|
|
||||||
|
// a link under way: state (in Discord's address) -> {accountId, nonce (in a
|
||||||
|
// cookie of the browser that asked), expires}. both must come back.
|
||||||
|
const states = new Map();
|
||||||
|
const adminStates = new Map();
|
||||||
|
const staffStates = new Map();
|
||||||
|
|
||||||
|
const newState = statesMap => {
|
||||||
|
for (const [state, entry] of statesMap) {
|
||||||
|
if (entry.expires < Date.now()) {
|
||||||
|
statesMap.delete(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (statesMap.size >= MAX_STATES) {
|
||||||
|
statesMap.delete(statesMap.keys().next().value);
|
||||||
|
}
|
||||||
|
const state = crypto.randomBytes(24).toString("hex");
|
||||||
|
const nonce = crypto.randomBytes(24).toString("hex");
|
||||||
|
statesMap.set(state, {nonce, expires: Date.now() + STATE_MINUTES * 60000});
|
||||||
|
return {state, nonce};
|
||||||
|
};
|
||||||
|
|
||||||
|
const authorize = (redirect, state) => {
|
||||||
|
const url = new URL(AUTHORIZE);
|
||||||
|
url.search = new URLSearchParams({client_id: config.discord.clientId, response_type: "code", scope: "identify",
|
||||||
|
redirect_uri: redirect, state, prompt: "consent"}).toString();
|
||||||
|
return url.href;
|
||||||
|
};
|
||||||
|
|
||||||
|
const start = account => {
|
||||||
|
const {state, nonce} = newState(states);
|
||||||
|
states.get(state).accountId = account.id;
|
||||||
|
return {url: authorize(redirectUri(), state), nonce};
|
||||||
|
};
|
||||||
|
|
||||||
|
// A separate OAuth state and redirect for the owner dashboard. The Discord
|
||||||
|
// account must already be linked to a Burrow account explicitly granted
|
||||||
|
// adminDashboardAccess; knowing a Discord name is never enough.
|
||||||
|
const startAdmin = () => {
|
||||||
|
const {state, nonce} = newState(adminStates);
|
||||||
|
return {url: authorize(adminRedirectUri(), state), nonce};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Staff sign in through a separately scoped state and callback. A Discord
|
||||||
|
// identity is only useful here after its owner has linked it to their own
|
||||||
|
// Burrow account; modpanel.js also verifies that account remains active staff.
|
||||||
|
const startStaff = () => {
|
||||||
|
const {state, nonce} = newState(staffStates);
|
||||||
|
return {url: authorize(staffRedirectUri(), state), nonce};
|
||||||
|
};
|
||||||
|
|
||||||
|
const call = async (path, options = {}) => {
|
||||||
|
const res = await fetch(`${API}${path}`, {...options, signal: AbortSignal.timeout(TIMEOUT_MS)});
|
||||||
|
const body = await res.json().catch(() => ({}));
|
||||||
|
return {status: res.status, body};
|
||||||
|
};
|
||||||
|
|
||||||
|
// how a Discord username is kept and shown: as Discord spells them now, or,
|
||||||
|
// for an old "name#1234" one, without the characters a card cannot carry.
|
||||||
|
const shownName = user => badges.discordName(user.username)
|
||||||
|
|| `${String(user.username).replace(/[,|%\s]/g, "")}${user.discriminator && user.discriminator !== "0" ? `#${user.discriminator}` : ""}`.slice(0, 40);
|
||||||
|
|
||||||
|
const setBooster = (account, on) => {
|
||||||
|
if (account.badges.includes(BOOSTER) === on) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
badges.set(account, on ? [...account.badges, BOOSTER] : account.badges.filter(id => id !== BOOSTER));
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
// whether the linked account boosts the server now: true, false, or null
|
||||||
|
// when Discord could not be asked.
|
||||||
|
const boosting = async account => {
|
||||||
|
if (!boostChecks() || !account.discordId) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (let attempt = 0; attempt < 3; attempt++) {
|
||||||
|
const {status, body} = await call(`/guilds/${config.discord.guildId}/members/${account.discordId}`,
|
||||||
|
{headers: {Authorization: `Bot ${config.discord.botToken}`}}).catch(() => ({status: 0, body: {}}));
|
||||||
|
if (status === 200) {
|
||||||
|
return Boolean(body.premium_since);
|
||||||
|
}
|
||||||
|
if (status === 404) {
|
||||||
|
return false; // not in the server (any more)
|
||||||
|
}
|
||||||
|
if (status === 429) {
|
||||||
|
await new Promise(resolve => setTimeout(resolve, Math.min(60, Number(body.retry_after) || 5) * 1000));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
console.log(`[discord] could not check ${logText(account.username)}'s boost: ${logText(status)}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const checkBoost = async account => {
|
||||||
|
const on = await boosting(account);
|
||||||
|
if (on !== null && setBooster(account, on)) {
|
||||||
|
accounts.save(account);
|
||||||
|
console.log(`[discord] ${logText(account.username)} ${on ? "boosts: booster badge given" : "no longer boosts: booster badge taken off"}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// the end of a link: the code Discord gave, for the state and the nonce the
|
||||||
|
// browser brought back. {ok, account} or {error}.
|
||||||
|
const finish = async (state, nonce, code) => {
|
||||||
|
const entry = typeof state === "string" ? states.get(state) : null;
|
||||||
|
states.delete(state);
|
||||||
|
const digest = text => crypto.createHash("sha256").update(String(text)).digest();
|
||||||
|
if (!entry || entry.expires < Date.now() || typeof nonce !== "string" || !crypto.timingSafeEqual(digest(entry.nonce), digest(nonce))) {
|
||||||
|
return {error: "expired"};
|
||||||
|
}
|
||||||
|
const account = accounts.byId(entry.accountId);
|
||||||
|
if (!account || typeof code !== "string" || !code) {
|
||||||
|
return {error: "expired"};
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const token = await call("/oauth2/token", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {"Content-Type": "application/x-www-form-urlencoded"},
|
||||||
|
body: new URLSearchParams({client_id: config.discord.clientId, client_secret: config.discord.clientSecret,
|
||||||
|
grant_type: "authorization_code", code, redirect_uri: redirectUri()}).toString(),
|
||||||
|
});
|
||||||
|
if (token.status !== 200 || !token.body.access_token) {
|
||||||
|
return {error: "discord"};
|
||||||
|
}
|
||||||
|
const me = await call("/users/@me", {headers: {Authorization: `Bearer ${token.body.access_token}`}});
|
||||||
|
if (me.status !== 200 || !/^\d{5,25}$/.test(String(me.body.id))) {
|
||||||
|
return {error: "discord"};
|
||||||
|
}
|
||||||
|
const id = String(me.body.id);
|
||||||
|
if (accounts.all().some(other => other !== account && other.discordId === id)) {
|
||||||
|
return {error: "taken"};
|
||||||
|
}
|
||||||
|
account.discordId = id;
|
||||||
|
account.discord = shownName(me.body);
|
||||||
|
accounts.save(account);
|
||||||
|
console.log(`[discord] ${logText(account.username)} linked Discord ${logText(account.discord)} (${logText(id)})`);
|
||||||
|
await checkBoost(account);
|
||||||
|
return {ok: true, account};
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.log(`[discord] link failed: ${logText(err.message)}`);
|
||||||
|
return {error: "discord"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const finishAdmin = async (state, nonce, code) => {
|
||||||
|
const entry = typeof state === "string" ? adminStates.get(state) : null;
|
||||||
|
adminStates.delete(state);
|
||||||
|
const digest = text => crypto.createHash("sha256").update(String(text)).digest();
|
||||||
|
if (!entry || entry.expires < Date.now() || typeof nonce !== "string" || !crypto.timingSafeEqual(digest(entry.nonce), digest(nonce)) || !code) {
|
||||||
|
return {error: "expired"};
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const token = await call("/oauth2/token", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {"Content-Type": "application/x-www-form-urlencoded"},
|
||||||
|
body: new URLSearchParams({client_id: config.discord.clientId, client_secret: config.discord.clientSecret,
|
||||||
|
grant_type: "authorization_code", code, redirect_uri: adminRedirectUri()}).toString(),
|
||||||
|
});
|
||||||
|
if (token.status !== 200 || !token.body.access_token) {
|
||||||
|
return {error: "discord"};
|
||||||
|
}
|
||||||
|
const me = await call("/users/@me", {headers: {Authorization: `Bearer ${token.body.access_token}`}});
|
||||||
|
if (me.status !== 200 || !/^\d{5,25}$/.test(String(me.body.id))) {
|
||||||
|
return {error: "discord"};
|
||||||
|
}
|
||||||
|
const account = accounts.all().find(candidate => candidate.discordId === String(me.body.id) && candidate.adminDashboardAccess);
|
||||||
|
return account ? {ok: true, account} : {error: "denied"};
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.log(`[discord] admin sign-in failed: ${logText(err.message)}`);
|
||||||
|
return {error: "discord"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const finishStaff = async (state, nonce, code) => {
|
||||||
|
const entry = typeof state === "string" ? staffStates.get(state) : null;
|
||||||
|
staffStates.delete(state);
|
||||||
|
const digest = text => crypto.createHash("sha256").update(String(text)).digest();
|
||||||
|
if (!entry || entry.expires < Date.now() || typeof nonce !== "string" || !crypto.timingSafeEqual(digest(entry.nonce), digest(nonce)) || !code) {
|
||||||
|
return {error: "expired"};
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const token = await call("/oauth2/token", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {"Content-Type": "application/x-www-form-urlencoded"},
|
||||||
|
body: new URLSearchParams({client_id: config.discord.clientId, client_secret: config.discord.clientSecret,
|
||||||
|
grant_type: "authorization_code", code, redirect_uri: staffRedirectUri()}).toString(),
|
||||||
|
});
|
||||||
|
if (token.status !== 200 || !token.body.access_token) {
|
||||||
|
return {error: "discord"};
|
||||||
|
}
|
||||||
|
const me = await call("/users/@me", {headers: {Authorization: `Bearer ${token.body.access_token}`}});
|
||||||
|
if (me.status !== 200 || !/^\d{5,25}$/.test(String(me.body.id))) {
|
||||||
|
return {error: "discord"};
|
||||||
|
}
|
||||||
|
const account = accounts.all().find(candidate => candidate.discordId === String(me.body.id));
|
||||||
|
return account ? {ok: true, account} : {error: "denied"};
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.log(`[discord] staff sign-in failed: ${logText(err.message)}`);
|
||||||
|
return {error: "discord"};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// the link undone, by the player or an admin; the booster badge goes with it.
|
||||||
|
const unlink = account => {
|
||||||
|
const had = Boolean(account.discordId || account.discord);
|
||||||
|
delete account.discordId;
|
||||||
|
account.discord = "";
|
||||||
|
if (had) {
|
||||||
|
setBooster(account, false);
|
||||||
|
}
|
||||||
|
accounts.save(account);
|
||||||
|
return had;
|
||||||
|
};
|
||||||
|
|
||||||
|
// every linked account in turn, a little apart, again and again.
|
||||||
|
let rechecking = false;
|
||||||
|
const recheckAll = async () => {
|
||||||
|
if (rechecking || !boostChecks()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
rechecking = true;
|
||||||
|
try {
|
||||||
|
for (const account of accounts.all().filter(one => one.discordId)) {
|
||||||
|
await checkBoost(account);
|
||||||
|
await new Promise(resolve => setTimeout(resolve, RECHECK_GAP_MS));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
rechecking = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// at start: Discord usernames typed in by hand before linking existed are
|
||||||
|
// cleared (only a linked one is shown now), then the boosts are looked at
|
||||||
|
// and looked at again every RECHECK_HOURS.
|
||||||
|
const startup = () => {
|
||||||
|
const typed = accounts.all().filter(account => account.discord && !account.discordId);
|
||||||
|
for (const account of typed) {
|
||||||
|
account.discord = "";
|
||||||
|
}
|
||||||
|
if (typed.length) {
|
||||||
|
accounts.save(...typed);
|
||||||
|
console.log(`[discord] ${typed.length} Discord usernames typed in by hand were cleared`);
|
||||||
|
}
|
||||||
|
if (boostChecks()) {
|
||||||
|
setTimeout(recheckAll, 30000).unref();
|
||||||
|
setInterval(recheckAll, RECHECK_HOURS * 3600000).unref();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {linking, boostChecks, start, finish, startAdmin, finishAdmin, startStaff, finishStaff, unlink, startup};
|
||||||
@@ -0,0 +1,962 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
// Burrow's Discord control surface. It is intentionally a thin client over
|
||||||
|
// lib/modpanel.js: Discord proves who clicked a command, and the panel then
|
||||||
|
// proves that their linked Burrow account is still active staff and applies
|
||||||
|
// its usual permission and rank rules. There is no Discord-only staff list.
|
||||||
|
|
||||||
|
// discord.js is loaded when the bot starts, not with the server: a server
|
||||||
|
// without the package installed (npm ci) runs as before, the bot off.
|
||||||
|
let ActionRowBuilder;
|
||||||
|
let ButtonBuilder;
|
||||||
|
let ButtonStyle;
|
||||||
|
let ChannelType;
|
||||||
|
let Client;
|
||||||
|
let GatewayIntentBits;
|
||||||
|
let PermissionFlagsBits;
|
||||||
|
let SlashCommandBuilder;
|
||||||
|
const loadDiscordJs = () => {
|
||||||
|
if (Client) return true;
|
||||||
|
try {
|
||||||
|
({ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelType, Client, GatewayIntentBits, PermissionFlagsBits, SlashCommandBuilder} = require("discord.js"));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.log(`[discord-bot] discord.js could not be loaded (run npm ci): ${logText(err.message)}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const crypto = require("crypto");
|
||||||
|
const accounts = require("./accounts.js");
|
||||||
|
const config = require("../config.js");
|
||||||
|
const modpanel = require("./modpanel.js");
|
||||||
|
const modlog = require("./modlog.js");
|
||||||
|
const reports = require("./reports.js");
|
||||||
|
const world = require("./world.js");
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
|
|
||||||
|
// discord.js's MessageFlags.IsComponentsV2 and MessageFlags.Ephemeral, which
|
||||||
|
// cards need before the package is loaded
|
||||||
|
const COMPONENTS_V2 = 1 << 15;
|
||||||
|
const EPHEMERAL = 1 << 6;
|
||||||
|
const STATUS_MESSAGE_SETTING = "discordBotStatusMessage";
|
||||||
|
const STATUS_TITLE_SETTING = "discordBotStatusTitle";
|
||||||
|
const STATUS_NOTE_SETTING = "discordBotStatusNote";
|
||||||
|
const STATUS_BANNER_SETTING = "discordBotStatusBanner";
|
||||||
|
const STATUS_EVERY_MS = 5 * 60000;
|
||||||
|
const REPORT_BUTTON_PREFIX = "burrow:report:";
|
||||||
|
const MAX_GITHUB_WEBHOOK_BYTES = 512 * 1024;
|
||||||
|
const CONFIG_SETTING_PREFIX = "discordBotConfig:";
|
||||||
|
const SECURITY_SETTING = "discordBotSecurity";
|
||||||
|
const COMMUNITY_SETTING = "discordBotCommunity";
|
||||||
|
const CHANNELS = [
|
||||||
|
["reportsChannelId", "Reports"],
|
||||||
|
["statusChannelId", "Public status"],
|
||||||
|
["gameLogsChannelId", "In-game activity"],
|
||||||
|
["moderationLogsChannelId", "Moderation audit"],
|
||||||
|
["botLogsChannelId", "Discord bot audit"],
|
||||||
|
["updatesChannelId", "GitHub updates"],
|
||||||
|
];
|
||||||
|
const MANAGED_CONFIG = [...CHANNELS.map(([key]) => key), "githubRepository"];
|
||||||
|
let loadedDashboardConfig = false;
|
||||||
|
let securityConfigLoaded = false;
|
||||||
|
let securityConfig = null;
|
||||||
|
let communityConfig = null;
|
||||||
|
let communityConfigLoaded = false;
|
||||||
|
const recentMessages = new Map();
|
||||||
|
const recentJoins = [];
|
||||||
|
let lastRaidAlertAt = 0;
|
||||||
|
|
||||||
|
// Text Displays accept markdown. Keep player-provided strings readable while
|
||||||
|
// ensuring a report cannot ping a Discord role or user.
|
||||||
|
const safe = (value, max = 1000) => String(value === undefined || value === null ? "" : value)
|
||||||
|
.replace(/@/g, "@\u200b").replace(/`/g, "'").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, max);
|
||||||
|
|
||||||
|
// Discord fetches the banner itself, so only absolute http(s) URLs work.
|
||||||
|
// Blank means the card has no banner; null means the URL was rejected.
|
||||||
|
const bannerUrl = value => {
|
||||||
|
const text = String(value || "").trim();
|
||||||
|
if (!text) return "";
|
||||||
|
try {
|
||||||
|
const url = new URL(text);
|
||||||
|
return /^https?:$/.test(url.protocol) && text.length <= 500 ? url.toString() : null;
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const statusSettings = () => ({
|
||||||
|
title: safe(accounts.setting(STATUS_TITLE_SETTING) || "Burrow status", 80) || "Burrow status",
|
||||||
|
note: safe(accounts.setting(STATUS_NOTE_SETTING) || "", 500),
|
||||||
|
banner: bannerUrl(accounts.setting(STATUS_BANNER_SETTING)) || "",
|
||||||
|
});
|
||||||
|
|
||||||
|
const setStatusSettings = ({title, note, banner}) => {
|
||||||
|
const next = {
|
||||||
|
title: safe(title || "Burrow status", 80) || "Burrow status",
|
||||||
|
note: safe(note || "", 500),
|
||||||
|
banner: bannerUrl(banner),
|
||||||
|
};
|
||||||
|
if (next.banner === null) return {error: "Banner must be an http(s) image URL of 500 characters or fewer, or blank for none."};
|
||||||
|
accounts.setSetting(STATUS_TITLE_SETTING, next.title);
|
||||||
|
accounts.setSetting(STATUS_NOTE_SETTING, next.note);
|
||||||
|
accounts.setSetting(STATUS_BANNER_SETTING, next.banner);
|
||||||
|
return next;
|
||||||
|
};
|
||||||
|
|
||||||
|
const securitySettings = () => {
|
||||||
|
if (securityConfigLoaded) return {...securityConfig};
|
||||||
|
const defaults = {enabled: false, blockInvites: true, blockedWords: [], spamLimit: 6, raidJoinLimit: 12};
|
||||||
|
try {
|
||||||
|
const saved = JSON.parse(accounts.setting(SECURITY_SETTING) || "{}");
|
||||||
|
const words = Array.isArray(saved.blockedWords) ? saved.blockedWords.map(word => safe(word, 60).toLowerCase()).filter(Boolean).slice(0, 50) : [];
|
||||||
|
securityConfig = {
|
||||||
|
enabled: saved.enabled === true,
|
||||||
|
blockInvites: saved.blockInvites !== false,
|
||||||
|
blockedWords: [...new Set(words)],
|
||||||
|
spamLimit: Number.isInteger(saved.spamLimit) && saved.spamLimit >= 2 && saved.spamLimit <= 20 ? saved.spamLimit : defaults.spamLimit,
|
||||||
|
raidJoinLimit: Number.isInteger(saved.raidJoinLimit) && saved.raidJoinLimit >= 3 && saved.raidJoinLimit <= 100 ? saved.raidJoinLimit : defaults.raidJoinLimit,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
securityConfig = defaults;
|
||||||
|
}
|
||||||
|
securityConfigLoaded = true;
|
||||||
|
return {...securityConfig};
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateSecuritySettings = values => {
|
||||||
|
const words = String(values.blockedWords || "").split(/\r?\n|,/)
|
||||||
|
.map(word => safe(word, 60).toLowerCase()).filter(Boolean).slice(0, 50);
|
||||||
|
const spamLimit = Number(values.spamLimit);
|
||||||
|
const raidJoinLimit = Number(values.raidJoinLimit);
|
||||||
|
if (!Number.isInteger(spamLimit) || spamLimit < 2 || spamLimit > 20 || !Number.isInteger(raidJoinLimit) || raidJoinLimit < 3 || raidJoinLimit > 100) {
|
||||||
|
return {error: "Spam limit must be 2 to 20 and raid join limit must be 3 to 100."};
|
||||||
|
}
|
||||||
|
securityConfig = {enabled: values.enabled === true, blockInvites: values.blockInvites === true,
|
||||||
|
blockedWords: [...new Set(words)], spamLimit, raidJoinLimit};
|
||||||
|
securityConfigLoaded = true;
|
||||||
|
accounts.setSetting(SECURITY_SETTING, JSON.stringify(securityConfig));
|
||||||
|
return {ok: "Discord security settings saved. Reconnect the bot to apply message and join monitoring.", security: securitySettings()};
|
||||||
|
};
|
||||||
|
|
||||||
|
const communitySettings = () => {
|
||||||
|
if (communityConfigLoaded) return {...communityConfig};
|
||||||
|
try {
|
||||||
|
const saved = JSON.parse(accounts.setting(COMMUNITY_SETTING) || "{}");
|
||||||
|
communityConfig = {ticketCategoryId: channelId(saved.ticketCategoryId) || "", ticketStaffRoleId: channelId(saved.ticketStaffRoleId) || "",
|
||||||
|
welcomeChannelId: channelId(saved.welcomeChannelId) || "", welcomeMessage: safe(saved.welcomeMessage || "Welcome {user} to {server}!", 500),
|
||||||
|
goodbyeChannelId: channelId(saved.goodbyeChannelId) || "", goodbyeMessage: safe(saved.goodbyeMessage || "Goodbye {user}.", 500)};
|
||||||
|
}
|
||||||
|
catch { communityConfig = {ticketCategoryId: "", ticketStaffRoleId: "", welcomeChannelId: "", welcomeMessage: "Welcome {user} to {server}!", goodbyeChannelId: "", goodbyeMessage: "Goodbye {user}."}; }
|
||||||
|
communityConfigLoaded = true;
|
||||||
|
return {...communityConfig};
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateCommunitySettings = values => {
|
||||||
|
const current = communitySettings();
|
||||||
|
const next = {...current};
|
||||||
|
for (const key of ["ticketCategoryId", "ticketStaffRoleId", "welcomeChannelId", "goodbyeChannelId"]) {
|
||||||
|
const id = channelId(values[key]);
|
||||||
|
if (id === null) return {error: "Discord channel, category, and role IDs must contain only 5 to 25 digits."};
|
||||||
|
next[key] = id;
|
||||||
|
}
|
||||||
|
next.welcomeMessage = safe(values.welcomeMessage || "", 500);
|
||||||
|
next.goodbyeMessage = safe(values.goodbyeMessage || "", 500);
|
||||||
|
communityConfig = next;
|
||||||
|
communityConfigLoaded = true;
|
||||||
|
accounts.setSetting(COMMUNITY_SETTING, JSON.stringify(next));
|
||||||
|
return {ok: "Community and ticket settings saved.", community: communitySettings()};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Non-secret routing settings are owner-controlled in the dashboard. The bot
|
||||||
|
// token and webhook secret deliberately remain environment-only, so a copied
|
||||||
|
// database or dashboard session cannot disclose them.
|
||||||
|
const loadDashboardConfig = () => {
|
||||||
|
if (loadedDashboardConfig) return;
|
||||||
|
for (const key of MANAGED_CONFIG) {
|
||||||
|
const saved = accounts.setting(`${CONFIG_SETTING_PREFIX}${key}`);
|
||||||
|
if (saved !== null) config.discord[key] = saved;
|
||||||
|
}
|
||||||
|
loadedDashboardConfig = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const channelId = value => {
|
||||||
|
const id = String(value === undefined || value === null ? "" : value).trim();
|
||||||
|
return id === "" || /^\d{5,25}$/.test(id) ? id : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateDashboardConfig = values => {
|
||||||
|
loadDashboardConfig();
|
||||||
|
const previousStatusChannelId = config.discord.statusChannelId || "";
|
||||||
|
const next = {};
|
||||||
|
for (const [key] of CHANNELS) {
|
||||||
|
const id = channelId(values[key]);
|
||||||
|
if (id === null) return {error: "Discord channel IDs must contain only 5 to 25 digits."};
|
||||||
|
next[key] = id;
|
||||||
|
}
|
||||||
|
const repository = String(values.githubRepository === undefined || values.githubRepository === null ? "" : values.githubRepository).trim();
|
||||||
|
if (repository && !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\/[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/.test(repository)) {
|
||||||
|
return {error: "GitHub repository must use the form owner/repository."};
|
||||||
|
}
|
||||||
|
next.githubRepository = repository;
|
||||||
|
for (const key of MANAGED_CONFIG) {
|
||||||
|
config.discord[key] = next[key];
|
||||||
|
accounts.setSetting(`${CONFIG_SETTING_PREFIX}${key}`, next[key]);
|
||||||
|
}
|
||||||
|
if (next.statusChannelId !== previousStatusChannelId) {
|
||||||
|
accounts.setSetting(STATUS_MESSAGE_SETTING, "");
|
||||||
|
}
|
||||||
|
return {ok: "Discord routing settings saved.", configuration: dashboardStatus()};
|
||||||
|
};
|
||||||
|
|
||||||
|
const duration = seconds => {
|
||||||
|
if (seconds === -1) return "permanent";
|
||||||
|
if (!seconds) return "none";
|
||||||
|
const hours = Math.ceil(Number(seconds) / 3600);
|
||||||
|
return `${hours} hour${hours === 1 ? "" : "s"}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Components V2 means every visible response—success, refusal, report alert
|
||||||
|
// and status card—uses a Container and Text Displays. Never add `content` or
|
||||||
|
// `embeds` to these payloads: Discord ignores them for Components V2.
|
||||||
|
const card = ({title, sections = [], tone = 0x5865f2, ephemeral = false, components = []}) => ({
|
||||||
|
flags: COMPONENTS_V2 | (ephemeral ? EPHEMERAL : 0),
|
||||||
|
allowedMentions: {parse: []},
|
||||||
|
components: [{
|
||||||
|
type: 17, // Container
|
||||||
|
accent_color: tone,
|
||||||
|
components: [
|
||||||
|
{type: 10, content: `## ${safe(title, 160)}`}, // Text Display
|
||||||
|
...sections.filter(Boolean).slice(0, 8).flatMap((section, index) => [
|
||||||
|
...(index ? [{type: 14, divider: true, spacing: 1}] : []), // Separator
|
||||||
|
{type: 10, content: safe(section, 1800)},
|
||||||
|
]),
|
||||||
|
...components,
|
||||||
|
],
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
|
||||||
|
const success = (title, sections, ephemeral = true) => card({title, sections, tone: 0x57f287, ephemeral});
|
||||||
|
const warning = (message, ephemeral = true) => card({title: "Burrow", sections: [message], tone: 0xfee75c, ephemeral});
|
||||||
|
const failure = (message, ephemeral = true) => card({title: "Burrow", sections: [message], tone: 0xed4245, ephemeral});
|
||||||
|
|
||||||
|
// Staff audit streams use the same compact Components V2 pattern as SRP-Bot:
|
||||||
|
// a brief summary, structured fields, and a durable log timestamp.
|
||||||
|
const logCard = ({title, description = "", fields = [], tone = 0x5865f2}) => {
|
||||||
|
const shown = fields.filter(field => field && field.name && field.value !== undefined && field.value !== null).slice(0, 12);
|
||||||
|
const components = [{type: 10, content: [
|
||||||
|
`## ${safe(title, 160)}`,
|
||||||
|
description ? safe(description, 900) : "",
|
||||||
|
].filter(Boolean).join("\n")}];
|
||||||
|
|
||||||
|
if (shown.length) {
|
||||||
|
components.push({type: 14, divider: true, spacing: 1});
|
||||||
|
components.push({type: 10, content: shown
|
||||||
|
.map(field => `• **${safe(field.name, 80)}:** ${safe(field.value, 500)}`)
|
||||||
|
.join("\n")
|
||||||
|
.slice(0, 1800)});
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
components.push({type: 14, divider: false, spacing: 1});
|
||||||
|
components.push({type: 10, content: `_Logged <t:${now}:F> (<t:${now}:R>)_`});
|
||||||
|
return {
|
||||||
|
flags: COMPONENTS_V2,
|
||||||
|
allowedMentions: {parse: []},
|
||||||
|
components: [{type: 17, accent_color: tone, components}],
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const commandDefinitions = () => [
|
||||||
|
new SlashCommandBuilder().setName("burrow").setDescription("View Burrow server and player information")
|
||||||
|
.addSubcommand(command => command.setName("status").setDescription("Show the live Burrow server status"))
|
||||||
|
.addSubcommand(command => command.setName("player").setDescription("Look up a Burrow player")
|
||||||
|
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true)))
|
||||||
|
.addSubcommand(command => command.setName("reports").setDescription("Show open player reports"))
|
||||||
|
.addSubcommand(command => command.setName("staff").setDescription("Show Burrow staff"))
|
||||||
|
.addSubcommand(command => command.setName("announce").setDescription("Send an announcement to everyone playing")
|
||||||
|
.addStringOption(option => option.setName("message").setDescription("Announcement shown in-game").setRequired(true).setMaxLength(300))),
|
||||||
|
new SlashCommandBuilder().setName("moderate").setDescription("Moderate Burrow through your linked staff account")
|
||||||
|
.addSubcommand(command => command.setName("warn").setDescription("Warn a player")
|
||||||
|
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))
|
||||||
|
.addStringOption(option => option.setName("reason").setDescription("Warning reason, e.g. behavior or custom").setRequired(true))
|
||||||
|
.addStringOption(option => option.setName("note").setDescription("Required explanation for a custom warning")))
|
||||||
|
.addSubcommand(command => command.setName("silence").setDescription("Stop a player from chatting")
|
||||||
|
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))
|
||||||
|
.addIntegerOption(option => option.setName("hours").setDescription("Whole hours; 0 means until lifted").setRequired(true).setMinValue(0).setMaxValue(87600)))
|
||||||
|
.addSubcommand(command => command.setName("unsilence").setDescription("Let a player chat again")
|
||||||
|
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true)))
|
||||||
|
.addSubcommand(command => command.setName("kick").setDescription("Disconnect an online player")
|
||||||
|
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true)))
|
||||||
|
.addSubcommand(command => command.setName("ban").setDescription("Ban a player")
|
||||||
|
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))
|
||||||
|
.addIntegerOption(option => option.setName("hours").setDescription("Whole hours; 0 means permanent").setRequired(true).setMinValue(0).setMaxValue(87600))
|
||||||
|
.addStringOption(option => option.setName("reason").setDescription("Why this player is being banned").setRequired(true)))
|
||||||
|
.addSubcommand(command => command.setName("unban").setDescription("Lift a player's Burrow ban")
|
||||||
|
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))),
|
||||||
|
new SlashCommandBuilder().setName("discord").setDescription("Moderate this Discord server through Burrow staff permissions")
|
||||||
|
.addSubcommand(command => command.setName("timeout").setDescription("Temporarily silence a Discord member")
|
||||||
|
.addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true))
|
||||||
|
.addIntegerOption(option => option.setName("hours").setDescription("Whole hours, up to 28 days").setRequired(true).setMinValue(1).setMaxValue(672))
|
||||||
|
.addStringOption(option => option.setName("reason").setDescription("Why this member is being timed out").setMaxLength(300)))
|
||||||
|
.addSubcommand(command => command.setName("untimeout").setDescription("Remove a Discord member timeout")
|
||||||
|
.addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true))
|
||||||
|
.addStringOption(option => option.setName("reason").setDescription("Why the timeout is being removed").setMaxLength(300)))
|
||||||
|
.addSubcommand(command => command.setName("kick").setDescription("Remove a Discord member from this server")
|
||||||
|
.addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true))
|
||||||
|
.addStringOption(option => option.setName("reason").setDescription("Why this member is being removed").setMaxLength(300)))
|
||||||
|
.addSubcommand(command => command.setName("ban").setDescription("Ban a Discord member from this server")
|
||||||
|
.addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true))
|
||||||
|
.addStringOption(option => option.setName("reason").setDescription("Why this member is being banned").setMaxLength(300)))
|
||||||
|
.addSubcommand(command => command.setName("unban").setDescription("Lift a Discord server ban")
|
||||||
|
.addStringOption(option => option.setName("user_id").setDescription("Discord user ID").setRequired(true).setMinLength(5).setMaxLength(25))
|
||||||
|
.addStringOption(option => option.setName("reason").setDescription("Why the ban is being removed").setMaxLength(300)))
|
||||||
|
.addSubcommand(command => command.setName("purge").setDescription("Delete recent messages in this channel")
|
||||||
|
.addIntegerOption(option => option.setName("amount").setDescription("Messages to delete (1 to 100)").setRequired(true).setMinValue(1).setMaxValue(100))
|
||||||
|
.addStringOption(option => option.setName("reason").setDescription("Why messages are being removed").setMaxLength(300))),
|
||||||
|
new SlashCommandBuilder().setName("ticket").setDescription("Open or manage a private support ticket")
|
||||||
|
.addSubcommand(command => command.setName("open").setDescription("Open a private support ticket")
|
||||||
|
.addStringOption(option => option.setName("subject").setDescription("What you need help with").setRequired(true).setMaxLength(80)))
|
||||||
|
.addSubcommand(command => command.setName("close").setDescription("Close this support ticket")),
|
||||||
|
].map(command => command.toJSON());
|
||||||
|
|
||||||
|
// a command or button counts for a staff member signed in to the panel with
|
||||||
|
// their 2FA code (modpanel.discordBot.commandActor): Discord alone is not them.
|
||||||
|
const actorFor = interaction => modpanel.discordBot.commandActor(interaction.user.id);
|
||||||
|
|
||||||
|
const reportButton = report => new ActionRowBuilder().addComponents(
|
||||||
|
new ButtonBuilder().setCustomId(`${REPORT_BUTTON_PREFIX}${report.id}:handled`).setLabel("Mark handled").setStyle(ButtonStyle.Success),
|
||||||
|
).toJSON();
|
||||||
|
|
||||||
|
const reportCard = (report, {handled = false, ephemeral = false} = {}) => card({
|
||||||
|
title: handled ? `Report #${report.id} handled` : `Report #${report.id}`,
|
||||||
|
tone: handled ? 0x57f287 : 0xfee75c,
|
||||||
|
ephemeral,
|
||||||
|
sections: [
|
||||||
|
`**${safe(report.reporter, 40)}** reported **${safe(report.target, 40)}**\n${safe(report.reason, 200)}`,
|
||||||
|
report.detail ? `**Details**\n${safe(report.detail, 500)}` : "*No additional details.*",
|
||||||
|
report.room ? `Room: \`${safe(report.room, 100)}\`` : "",
|
||||||
|
],
|
||||||
|
components: handled ? [] : [{type: 14, divider: true, spacing: 1}, reportButton(report)],
|
||||||
|
});
|
||||||
|
|
||||||
|
const playerCard = player => success(`Player: ${player.username}`, [
|
||||||
|
`**Status**\n${player.online ? `Online${player.room ? ` in ${safe(player.room, 100)}` : ""}` : "Offline"}\nRole: ${player.role || "Player"}`,
|
||||||
|
`**Moderation**\nBan: ${duration(player.banned)}\nSilence: ${duration(player.silenced)}\nWarnings: ${player.warnings}\nOpen reports: ${player.openReports}`,
|
||||||
|
player.discord ? `**Discord**\n${safe(player.discord, 80)}` : "",
|
||||||
|
]);
|
||||||
|
|
||||||
|
const statusCard = status => {
|
||||||
|
const settings = statusSettings();
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
const startedAt = now - status.uptimeSeconds;
|
||||||
|
const rooms = `${status.rooms} room${status.rooms === 1 ? "" : "s"}`;
|
||||||
|
const playUrl = new URL("gameClient/game/index.html", config.siteUrl).toString();
|
||||||
|
|
||||||
|
// This is intentionally public-only: moderation reports and queue depth are
|
||||||
|
// staff data and do not belong in a community-facing server-status post.
|
||||||
|
return {
|
||||||
|
flags: COMPONENTS_V2,
|
||||||
|
allowedMentions: {parse: []},
|
||||||
|
components: [{
|
||||||
|
type: 17,
|
||||||
|
accent_color: 0x7c5ce7,
|
||||||
|
components: [
|
||||||
|
{type: 10, content: `## ${safe(settings.title, 80)}`},
|
||||||
|
{type: 14, divider: true, spacing: 1},
|
||||||
|
{type: 10, content: ["### STATUS", "🟢 **Online**", settings.note ? `\n${safe(settings.note, 500)}` : ""].filter(Boolean).join("\n")},
|
||||||
|
{type: 14, divider: true, spacing: 1},
|
||||||
|
{type: 10, content: `### PLAYERS\n\`${status.players} online\` • \`${rooms}\``},
|
||||||
|
{type: 14, divider: true, spacing: 1},
|
||||||
|
{type: 10, content: `### UPTIME\nStarted <t:${startedAt}:R> • ${status.memoryMb} MB memory`},
|
||||||
|
...settings.banner ? [{type: 12, items: [{media: {url: settings.banner}}]}] : [],
|
||||||
|
{type: 1, components: [{type: 2, style: 5, label: "Play Burrow", url: playUrl}]},
|
||||||
|
{type: 10, content: `_Last updated <t:${now}:R>_`},
|
||||||
|
],
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const staffCard = staff => success("Burrow staff", staff.length
|
||||||
|
? [staff.map(member => `**${safe(member.username, 40)}** — ${safe(member.role, 30)}${member.twoStep ? " · 2FA" : ""}`).join("\n")]
|
||||||
|
: ["No active Burrow staff accounts."]);
|
||||||
|
|
||||||
|
const inConfiguredGuild = interaction => interaction.guildId === config.discord.guildId;
|
||||||
|
|
||||||
|
const replyResult = async (interaction, result, title = "Burrow") => {
|
||||||
|
if (result.error) {
|
||||||
|
await interaction.editReply(failure(result.error));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await interaction.editReply(success(title, [result.ok, result.detail].filter(Boolean)));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleBurrow = async interaction => {
|
||||||
|
const actor = actorFor(interaction);
|
||||||
|
const subcommand = interaction.options.getSubcommand();
|
||||||
|
if (subcommand === "status") {
|
||||||
|
const result = modpanel.discordBot.status(actor);
|
||||||
|
await interaction.editReply(result.error ? failure(result.error) : {...statusCard(result), flags: COMPONENTS_V2 | EPHEMERAL});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (subcommand === "player") {
|
||||||
|
const result = modpanel.discordBot.player(actor, interaction.options.getString("username", true));
|
||||||
|
await interaction.editReply(result.error ? failure(result.error) : {...playerCard(result.player), flags: COMPONENTS_V2 | EPHEMERAL});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (subcommand === "staff") {
|
||||||
|
const result = modpanel.discordBot.staff(actor);
|
||||||
|
await interaction.editReply(result.error ? failure(result.error) : staffCard(result.staff));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (subcommand === "announce") {
|
||||||
|
await replyResult(interaction, modpanel.discordBot.announce(actor, interaction.options.getString("message", true)), "In-game announcement");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = modpanel.discordBot.reports(actor);
|
||||||
|
if (result.error) {
|
||||||
|
await interaction.editReply(failure(result.error));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const shown = result.reports.slice(0, 5);
|
||||||
|
await interaction.editReply(success("Open reports", [
|
||||||
|
`${result.open} open report${result.open === 1 ? "" : "s"}.`,
|
||||||
|
shown.length ? shown.map(report => `#${report.id} — **${safe(report.target, 40)}** — ${safe(report.reason, 100)}`).join("\n") : "No reports are waiting.",
|
||||||
|
]));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleModerate = async interaction => {
|
||||||
|
const actor = actorFor(interaction);
|
||||||
|
const subcommand = interaction.options.getSubcommand();
|
||||||
|
const username = interaction.options.getString("username", true);
|
||||||
|
const fields = {action: subcommand};
|
||||||
|
if (subcommand === "warn") {
|
||||||
|
fields.reason = interaction.options.getString("reason", true);
|
||||||
|
fields.note = interaction.options.getString("note") || "";
|
||||||
|
}
|
||||||
|
if (subcommand === "silence" || subcommand === "ban") {
|
||||||
|
fields.hours = interaction.options.getInteger("hours", true);
|
||||||
|
}
|
||||||
|
if (subcommand === "ban") {
|
||||||
|
fields.reason = interaction.options.getString("reason", true);
|
||||||
|
}
|
||||||
|
await replyResult(interaction, modpanel.discordBot.act(actor, username, fields), `Moderation: ${subcommand}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const nativeDiscordPermission = action => ({
|
||||||
|
timeout: "chat.silence",
|
||||||
|
untimeout: "chat.silence",
|
||||||
|
kick: "player.kick",
|
||||||
|
ban: "player.ban",
|
||||||
|
unban: "player.ban",
|
||||||
|
purge: "player.kick",
|
||||||
|
})[action] || "";
|
||||||
|
|
||||||
|
const handleDiscordModeration = async interaction => {
|
||||||
|
const actor = actorFor(interaction);
|
||||||
|
const action = interaction.options.getSubcommand();
|
||||||
|
const refused = modpanel.discordBot.authorize(actor, nativeDiscordPermission(action));
|
||||||
|
if (refused) {
|
||||||
|
await interaction.editReply(failure(refused.error));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const reason = safe(interaction.options.getString("reason") || `Burrow staff action by ${actor.username}`, 300);
|
||||||
|
const user = action === "unban" ? null : interaction.options.getUser("member", true);
|
||||||
|
if (user && modpanel.discordBot.actor(user.id)) {
|
||||||
|
await interaction.editReply(failure("Discord-native moderation cannot target an active linked Burrow staff account."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
let detail = "";
|
||||||
|
let target = user ? user.username : interaction.options.getString("user_id", true);
|
||||||
|
if (action === "timeout" || action === "untimeout" || action === "kick") {
|
||||||
|
const member = await interaction.guild.members.fetch(user.id);
|
||||||
|
if (action === "timeout") {
|
||||||
|
const hours = interaction.options.getInteger("hours", true);
|
||||||
|
await member.timeout(hours * 3600000, reason);
|
||||||
|
detail = `${hours} hour${hours === 1 ? "" : "s"}`;
|
||||||
|
}
|
||||||
|
else if (action === "untimeout") {
|
||||||
|
await member.timeout(null, reason);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
await member.kick(reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (action === "ban") {
|
||||||
|
await interaction.guild.members.ban(user.id, {reason, deleteMessageSeconds: 0});
|
||||||
|
}
|
||||||
|
else if (action === "unban") {
|
||||||
|
if (!/^\d{5,25}$/.test(target)) throw new Error("bad_user_id");
|
||||||
|
await interaction.guild.members.unban(target, reason);
|
||||||
|
}
|
||||||
|
else if (action === "purge") {
|
||||||
|
const amount = interaction.options.getInteger("amount", true);
|
||||||
|
if (!interaction.channel || !interaction.channel.isTextBased() || typeof interaction.channel.bulkDelete !== "function") throw new Error("not_text_channel");
|
||||||
|
const deleted = await interaction.channel.bulkDelete(amount, true);
|
||||||
|
detail = `${deleted.size} message${deleted.size === 1 ? "" : "s"}`;
|
||||||
|
target = "this channel";
|
||||||
|
}
|
||||||
|
else throw new Error("unknown_action");
|
||||||
|
modlog.record(actor.username, `Discord ${action}`, target, detail || reason);
|
||||||
|
await interaction.editReply(success(`Discord ${action}`, [`${safe(target, 80)} — ${detail || "completed"}.`].concat(reason ? [`Reason: ${reason}`] : [])));
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
if (err.message === "bad_user_id") {
|
||||||
|
await interaction.editReply(failure("Enter a valid Discord user ID."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log(`[discord-bot] Discord ${action} failed: ${logText(err.message)}`);
|
||||||
|
await interaction.editReply(failure("Discord could not complete that action. Check the bot permission and role position."));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const ticketOwner = channel => (channel && /^burrow-ticket:(\d{5,25})$/.exec(channel.topic || "") || [])[1] || "";
|
||||||
|
|
||||||
|
const handleTicket = async interaction => {
|
||||||
|
const action = interaction.options.getSubcommand();
|
||||||
|
const settings = communitySettings();
|
||||||
|
if (action === "open") {
|
||||||
|
if (!settings.ticketCategoryId || !settings.ticketStaffRoleId) {
|
||||||
|
await interaction.editReply(failure("Tickets are not configured. Ask an owner to set the ticket category and staff role in the Discord dashboard."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const subject = safe(interaction.options.getString("subject", true), 80);
|
||||||
|
const channel = await interaction.guild.channels.create({
|
||||||
|
name: `ticket-${interaction.user.id}`,
|
||||||
|
type: ChannelType.GuildText,
|
||||||
|
parent: settings.ticketCategoryId,
|
||||||
|
topic: `burrow-ticket:${interaction.user.id}`,
|
||||||
|
permissionOverwrites: [
|
||||||
|
{id: interaction.guild.roles.everyone.id, deny: [PermissionFlagsBits.ViewChannel]},
|
||||||
|
{id: interaction.user.id, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory]},
|
||||||
|
{id: settings.ticketStaffRoleId, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory]},
|
||||||
|
{id: client.user.id, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ManageChannels, PermissionFlagsBits.ReadMessageHistory]},
|
||||||
|
],
|
||||||
|
}).catch(() => null);
|
||||||
|
if (!channel) {
|
||||||
|
await interaction.editReply(failure("Discord could not open the ticket. Check the category, staff role, and bot channel permissions."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await channel.send(card({title: "Support ticket", tone: 0x5865f2, sections: [`Opened by **${safe(interaction.user.username, 80)}**\nSubject: ${subject}`, "A staff member will reply here. Use `/ticket close` when this is resolved."]}));
|
||||||
|
await interaction.editReply(success("Ticket opened", [`Your private ticket: ${channel}`]));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const owner = ticketOwner(interaction.channel);
|
||||||
|
const staff = modpanel.discordBot.actor(interaction.user.id);
|
||||||
|
if (!owner || (owner !== interaction.user.id && !staff)) {
|
||||||
|
await interaction.editReply(failure("Only the ticket opener or linked Burrow staff can close this ticket."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await interaction.channel.setName(`closed-${interaction.channel.name}`.slice(0, 100)).catch(() => {});
|
||||||
|
if (owner) await interaction.channel.permissionOverwrites.edit(owner, {ViewChannel: false}).catch(() => {});
|
||||||
|
modlog.record(staff ? staff.username : interaction.user.username, "Discord ticket closed", interaction.channel.name);
|
||||||
|
await interaction.editReply(success("Ticket closed", ["The opener can no longer view this channel. Staff retain it for the support record."]));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleButton = async interaction => {
|
||||||
|
const match = new RegExp(`^${REPORT_BUTTON_PREFIX.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(\\d+):handled$`).exec(interaction.customId);
|
||||||
|
if (!match) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!inConfiguredGuild(interaction)) {
|
||||||
|
await interaction.reply(failure("This control belongs to another Discord server.")).catch(() => {});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const result = modpanel.discordBot.handleReport(actorFor(interaction), Number(match[1]));
|
||||||
|
if (result.error) {
|
||||||
|
await interaction.reply(failure(result.error)).catch(() => {});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
await interaction.update(success(`Report #${Number(match[1])} handled`, [result.ok], false)).catch(() => {});
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
let client = null;
|
||||||
|
let statusTimer = null;
|
||||||
|
let unsubscribeReports = null;
|
||||||
|
let unsubscribeGameActivity = null;
|
||||||
|
let unsubscribeModeration = null;
|
||||||
|
let securityGatewayOn = false;
|
||||||
|
|
||||||
|
const channelFor = async id => {
|
||||||
|
if (!id || !client || !client.isReady()) return null;
|
||||||
|
const channel = await client.channels.fetch(id).catch(() => null);
|
||||||
|
return channel && channel.isTextBased() ? channel : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const postCard = async (channelId, payload, label) => {
|
||||||
|
const channel = await channelFor(channelId);
|
||||||
|
if (channel) {
|
||||||
|
await channel.send(payload).catch(err => console.log(`[discord-bot] ${label} failed: ${logText(err.message)}`));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const publishStatus = async () => {
|
||||||
|
const channel = await channelFor(config.discord.statusChannelId);
|
||||||
|
if (!channel) return {error: "The public status channel is not configured or the Discord bot is not connected."};
|
||||||
|
const players = world.players();
|
||||||
|
const payload = statusCard({players: players.length, rooms: new Set(players.map(player => player.room).filter(Boolean)).size,
|
||||||
|
reports: reports.openCount(), uptimeSeconds: Math.floor(process.uptime()), memoryMb: Math.round(process.memoryUsage().rss / 1048576)});
|
||||||
|
// The public status card needs no staff actor; it exposes only aggregate
|
||||||
|
// counts. Store its message id in the server database so restarts edit it.
|
||||||
|
const saved = accounts.setting(STATUS_MESSAGE_SETTING);
|
||||||
|
const existing = saved && await channel.messages.fetch(saved).catch(() => null);
|
||||||
|
if (existing) {
|
||||||
|
const updated = await existing.edit(payload).then(() => true).catch(err => {
|
||||||
|
console.log(`[discord-bot] status update failed: ${logText(err.message)}`);
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
return updated ? {ok: "The public status card was updated."} : {error: "Discord could not update the public status card."};
|
||||||
|
}
|
||||||
|
const message = await channel.send(payload).catch(err => {
|
||||||
|
console.log(`[discord-bot] status post failed: ${logText(err.message)}`);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
if (!message) return {error: "Discord could not post the public status card."};
|
||||||
|
accounts.setSetting(STATUS_MESSAGE_SETTING, message.id);
|
||||||
|
return {ok: "The public status card was posted."};
|
||||||
|
};
|
||||||
|
|
||||||
|
const notifyReport = async report => {
|
||||||
|
await postCard(config.discord.reportsChannelId, reportCard(report), "report notification");
|
||||||
|
};
|
||||||
|
|
||||||
|
const notifyGameActivity = async entry => {
|
||||||
|
const minutes = Math.max(1, Math.ceil((entry.playedSeconds || 0) / 60));
|
||||||
|
const signedIn = entry.type === "login";
|
||||||
|
await postCard(config.discord.gameLogsChannelId, logCard({
|
||||||
|
title: "In-game activity",
|
||||||
|
description: signedIn ? "A player signed in." : "A player signed out.",
|
||||||
|
tone: signedIn ? 0x57f287 : 0x5865f2,
|
||||||
|
fields: [
|
||||||
|
{name: "Player", value: entry.username},
|
||||||
|
{name: "Event", value: signedIn ? "Signed in" : "Signed out"},
|
||||||
|
...(!signedIn ? [{name: "Session", value: `${minutes} minute${minutes === 1 ? "" : "s"}`}] : []),
|
||||||
|
],
|
||||||
|
}), "game activity log");
|
||||||
|
};
|
||||||
|
|
||||||
|
const notifyModeration = async entry => {
|
||||||
|
await postCard(config.discord.moderationLogsChannelId, logCard({
|
||||||
|
title: "Moderation audit",
|
||||||
|
description: "A Burrow staff action was recorded.",
|
||||||
|
tone: 0xfee75c,
|
||||||
|
fields: [
|
||||||
|
{name: "Staff", value: entry.by},
|
||||||
|
{name: "Action", value: entry.action},
|
||||||
|
...(entry.target ? [{name: "Player", value: entry.target}] : []),
|
||||||
|
...(entry.detail ? [{name: "Details", value: entry.detail}] : []),
|
||||||
|
],
|
||||||
|
}), "moderation log");
|
||||||
|
};
|
||||||
|
|
||||||
|
const notifyBot = async (interaction, action) => {
|
||||||
|
const actor = modpanel.discordBot.actor(interaction.user.id);
|
||||||
|
await postCard(config.discord.botLogsChannelId, logCard({
|
||||||
|
title: "Discord bot audit",
|
||||||
|
description: "A Discord command or control was used.",
|
||||||
|
tone: actor ? 0x5865f2 : 0xed4245,
|
||||||
|
fields: [
|
||||||
|
{name: "Discord user", value: `${interaction.user.username} (${interaction.user.id})`},
|
||||||
|
{name: "Action", value: action},
|
||||||
|
{name: "Linked staff account", value: actor ? actor.username : "No active linked Burrow staff account."},
|
||||||
|
],
|
||||||
|
}), "Discord bot audit log");
|
||||||
|
};
|
||||||
|
|
||||||
|
const securityIncident = async (title, sections, detail = "") => {
|
||||||
|
await postCard(config.discord.moderationLogsChannelId, logCard({
|
||||||
|
title,
|
||||||
|
description: "Discord security activity detected.",
|
||||||
|
tone: 0xed4245,
|
||||||
|
fields: [{name: "Details", value: sections.filter(Boolean).join("\n")}],
|
||||||
|
}), "Discord security log");
|
||||||
|
modlog.record("discord security", title.toLowerCase(), "", detail);
|
||||||
|
};
|
||||||
|
|
||||||
|
const isConfiguredGuild = guild => Boolean(guild && guild.id === config.discord.guildId);
|
||||||
|
|
||||||
|
const inspectDiscordMessage = async message => {
|
||||||
|
const settings = securitySettings();
|
||||||
|
if (!settings.enabled || message.author?.bot || !isConfiguredGuild(message.guild)) return;
|
||||||
|
const at = Date.now();
|
||||||
|
const key = message.author.id;
|
||||||
|
const times = (recentMessages.get(key) || []).filter(time => time > at - 10000);
|
||||||
|
times.push(at);
|
||||||
|
recentMessages.set(key, times);
|
||||||
|
const text = String(message.content || "").toLowerCase();
|
||||||
|
const hasInvite = settings.blockInvites && /(?:discord\.gg|discord(?:app)?\.com\/invite)\//i.test(text);
|
||||||
|
const word = settings.blockedWords.find(entry => text.includes(entry));
|
||||||
|
const reason = times.length > settings.spamLimit ? "message spam" : hasInvite ? "Discord invite" : word ? "blocked word" : "";
|
||||||
|
if (!reason) return;
|
||||||
|
if (message.deletable) await message.delete().catch(() => {});
|
||||||
|
await securityIncident("Discord AutoMod", [
|
||||||
|
`Member: **${safe(message.author.username, 80)}**`,
|
||||||
|
`Action: deleted message for ${reason}.`,
|
||||||
|
], `${safe(message.author.username, 80)}: ${reason}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const inspectDiscordJoin = async member => {
|
||||||
|
const settings = securitySettings();
|
||||||
|
if (!settings.enabled || !isConfiguredGuild(member.guild)) return;
|
||||||
|
const at = Date.now();
|
||||||
|
recentJoins.push(at);
|
||||||
|
while (recentJoins.length && recentJoins[0] <= at - 60000) recentJoins.shift();
|
||||||
|
if (recentJoins.length < settings.raidJoinLimit || lastRaidAlertAt > at - 60000) return;
|
||||||
|
lastRaidAlertAt = at;
|
||||||
|
await securityIncident("Discord anti-raid alert", [
|
||||||
|
`${recentJoins.length} members joined in the last minute.`,
|
||||||
|
"Review recent joins and use the dashboard or Discord moderation controls if action is needed.",
|
||||||
|
], `${recentJoins.length} joins in one minute`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const communityNotice = async (member, kind) => {
|
||||||
|
const settings = communitySettings();
|
||||||
|
const channelId = kind === "welcome" ? settings.welcomeChannelId : settings.goodbyeChannelId;
|
||||||
|
const template = kind === "welcome" ? settings.welcomeMessage : settings.goodbyeMessage;
|
||||||
|
if (!channelId || !isConfiguredGuild(member.guild)) return;
|
||||||
|
const message = safe(template.replace(/\{user\}/gi, member.user.username).replace(/\{server\}/gi, member.guild.name), 500);
|
||||||
|
if (message) await postCard(channelId, card({title: kind === "welcome" ? "Welcome" : "Goodbye", tone: kind === "welcome" ? 0x57f287 : 0x5865f2, sections: [message]}), `${kind} notice`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const githubUpdatesOn = () => {
|
||||||
|
loadDashboardConfig();
|
||||||
|
return Boolean(config.discord.githubRepository && config.discord.githubWebhookSecret && config.discord.updatesChannelId);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Safe to expose to the owner dashboard: it deliberately contains state and
|
||||||
|
// channel ids only, never the bot token or GitHub webhook secret.
|
||||||
|
const dashboardStatus = () => {
|
||||||
|
loadDashboardConfig();
|
||||||
|
return {
|
||||||
|
botTokenConfigured: Boolean(config.discord.botToken),
|
||||||
|
guildId: config.discord.guildId || "",
|
||||||
|
connected: Boolean(client && client.isReady()),
|
||||||
|
commands: ["/burrow status", "/burrow player", "/burrow reports", "/burrow staff", "/burrow announce", "/moderate warn", "/moderate silence", "/moderate unsilence", "/moderate kick", "/moderate ban", "/moderate unban", "/discord timeout", "/discord untimeout", "/discord kick", "/discord ban", "/discord unban", "/discord purge"],
|
||||||
|
channels: CHANNELS.map(([key, name]) => ({key, name, id: config.discord[key] || "", configured: Boolean(config.discord[key])})),
|
||||||
|
github: {
|
||||||
|
repository: config.discord.githubRepository || "",
|
||||||
|
webhookSecretConfigured: Boolean(config.discord.githubWebhookSecret),
|
||||||
|
updatesEnabled: githubUpdatesOn(),
|
||||||
|
endpoint: "/discord/github",
|
||||||
|
},
|
||||||
|
statusCard: statusSettings(),
|
||||||
|
security: {...securitySettings(), monitoring: securityGatewayOn},
|
||||||
|
community: communitySettings(),
|
||||||
|
modules: [
|
||||||
|
{name: "Burrow staff tools", detail: "Player lookup, reports, staff list, in-game announcements, and game moderation", enabled: Boolean(config.discord.botToken && config.discord.guildId)},
|
||||||
|
{name: "Discord moderation", detail: "Timeout, kick, ban, unban, and purge; gated by linked Burrow staff permissions", enabled: Boolean(config.discord.botToken && config.discord.guildId)},
|
||||||
|
{name: "Activity and audit logs", detail: "In-game activity, reports, moderation, and bot command audit streams", enabled: CHANNELS.some(([key]) => key !== "updatesChannelId" && Boolean(config.discord[key]))},
|
||||||
|
{name: "GitHub updates", detail: "Signed commit cards, with client changes marked as game updates", enabled: githubUpdatesOn()},
|
||||||
|
{name: "AutoMod and anti-raid", detail: "Blocked words, invite blocking, anti-spam, and join-rate alerts", enabled: securitySettings().enabled},
|
||||||
|
{name: "Tickets and member notices", detail: "Private support tickets plus configurable welcome and goodbye cards", enabled: Boolean(communitySettings().ticketCategoryId && communitySettings().ticketStaffRoleId)},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const githubBody = req => new Promise((resolve, reject) => {
|
||||||
|
const chunks = [];
|
||||||
|
let size = 0;
|
||||||
|
req.on("data", chunk => {
|
||||||
|
size += chunk.length;
|
||||||
|
if (size > MAX_GITHUB_WEBHOOK_BYTES) {
|
||||||
|
req.destroy();
|
||||||
|
reject(new Error("too_large"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
chunks.push(chunk);
|
||||||
|
});
|
||||||
|
req.on("end", () => resolve(Buffer.concat(chunks)));
|
||||||
|
req.on("error", reject);
|
||||||
|
});
|
||||||
|
|
||||||
|
const githubSignatureMatches = (body, signature) => {
|
||||||
|
if (!/^sha256=[0-9a-f]{64}$/i.test(String(signature || ""))) return false;
|
||||||
|
const expected = `sha256=${crypto.createHmac("sha256", config.discord.githubWebhookSecret).update(body).digest("hex")}`;
|
||||||
|
return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(String(signature)));
|
||||||
|
};
|
||||||
|
|
||||||
|
const changedFiles = commit => [commit.added, commit.modified, commit.removed].flat().filter(file => typeof file === "string");
|
||||||
|
const gameChange = payload => (payload.commits || []).some(commit => changedFiles(commit)
|
||||||
|
.some(file => /^(swf\/|swf-src\/|client-updates\/|public\/(?:badges|music|fonts)\/)/.test(file)));
|
||||||
|
|
||||||
|
const githubUpdateCard = payload => {
|
||||||
|
const commits = Array.isArray(payload.commits) ? payload.commits.slice(-5) : [];
|
||||||
|
const isGameUpdate = gameChange(payload);
|
||||||
|
const compare = config.githubUrl ? `${config.githubUrl.replace(/\/$/, "")}/compare/${safe(payload.before, 40)}...${safe(payload.after, 40)}` : "";
|
||||||
|
const branch = String(payload.ref || "").replace(/^refs\/heads\//, "") || "default branch";
|
||||||
|
return card({
|
||||||
|
title: isGameUpdate ? "Game update" : "Server update",
|
||||||
|
tone: isGameUpdate ? 0x57f287 : 0x5865f2,
|
||||||
|
sections: [
|
||||||
|
`**${safe(config.discord.githubRepository, 100)}** · ${safe(branch, 100)}\n${commits.length} new commit${commits.length === 1 ? "" : "s"}`,
|
||||||
|
commits.length ? commits.map(commit => `\`${safe(String(commit.id || "").slice(0, 7), 7)}\` ${safe(String(commit.message || "").split("\n")[0], 180)} — ${safe(commit.author && commit.author.name, 80)}`).join("\n") : "No commit details were supplied.",
|
||||||
|
],
|
||||||
|
components: compare ? [{type: 1, components: [{type: 2, style: 5, label: "View on GitHub", url: compare}]}] : [],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// GitHub calls this public endpoint. It is intentionally signature-first:
|
||||||
|
// an untrusted request never reaches Discord or becomes a log entry.
|
||||||
|
const handleGithubWebhook = async (req, res) => {
|
||||||
|
const answer = status => { res.writeHead(status, {"Content-Length": 0}); res.end(); };
|
||||||
|
if (!githubUpdatesOn()) {
|
||||||
|
answer(404);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (req.method !== "POST") {
|
||||||
|
answer(405);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let body;
|
||||||
|
try {
|
||||||
|
body = await githubBody(req);
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
answer(413);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!githubSignatureMatches(body, req.headers["x-hub-signature-256"])) {
|
||||||
|
answer(401);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (req.headers["x-github-event"] === "ping") {
|
||||||
|
answer(204);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (req.headers["x-github-event"] !== "push") {
|
||||||
|
answer(204);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let payload;
|
||||||
|
try {
|
||||||
|
payload = JSON.parse(body.toString("utf8"));
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
answer(400);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (payload.repository?.full_name !== config.discord.githubRepository || payload.deleted === true) {
|
||||||
|
answer(204);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const channel = await channelFor(config.discord.updatesChannelId);
|
||||||
|
if (!channel) {
|
||||||
|
answer(503); // GitHub retries after the bot finishes reconnecting.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const posted = await channel.send(githubUpdateCard(payload)).then(() => true).catch(err => {
|
||||||
|
console.log(`[discord-bot] GitHub update post failed: ${logText(err.message)}`);
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
answer(posted ? 204 : 503);
|
||||||
|
};
|
||||||
|
|
||||||
|
const syncCommands = async () => {
|
||||||
|
if (!client || !client.isReady()) return {error: "The Discord bot is not connected."};
|
||||||
|
const guild = await client.guilds.fetch(config.discord.guildId).catch(() => null);
|
||||||
|
if (!guild) return {error: "The configured Discord server could not be found."};
|
||||||
|
const synced = await guild.commands.set(commandDefinitions()).then(() => true).catch(err => {
|
||||||
|
console.log(`[discord-bot] command registration failed: ${logText(err.message)}`);
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
return synced ? {ok: "Discord slash commands are synchronized."} : {error: "Discord could not synchronize slash commands."};
|
||||||
|
};
|
||||||
|
|
||||||
|
const startup = () => {
|
||||||
|
loadDashboardConfig();
|
||||||
|
const security = securitySettings();
|
||||||
|
const community = communitySettings();
|
||||||
|
if (!config.discord.botToken || !config.discord.guildId) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (client) return true;
|
||||||
|
if (!loadDiscordJs()) return false;
|
||||||
|
securityGatewayOn = security.enabled;
|
||||||
|
const memberEvents = securityGatewayOn || Boolean(community.welcomeChannelId || community.goodbyeChannelId);
|
||||||
|
client = new Client({intents: securityGatewayOn
|
||||||
|
? [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers]
|
||||||
|
: memberEvents ? [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers] : [GatewayIntentBits.Guilds]});
|
||||||
|
client.once("ready", async () => {
|
||||||
|
console.log(`[discord-bot] signed in as ${logText(client.user.tag)}`);
|
||||||
|
const synced = await syncCommands();
|
||||||
|
console.log(`[discord-bot] ${synced.ok || synced.error}`);
|
||||||
|
await publishStatus();
|
||||||
|
});
|
||||||
|
client.on("interactionCreate", async interaction => {
|
||||||
|
if (interaction.user.bot) return;
|
||||||
|
if (interaction.isButton()) {
|
||||||
|
await notifyBot(interaction, `button ${interaction.customId}`).catch(() => {});
|
||||||
|
await handleButton(interaction);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!interaction.isChatInputCommand() || !inConfiguredGuild(interaction)) return;
|
||||||
|
await notifyBot(interaction, `/${interaction.commandName} ${interaction.options.getSubcommand(false) || ""}`.trim()).catch(() => {});
|
||||||
|
await interaction.deferReply({flags: EPHEMERAL}).catch(() => {});
|
||||||
|
if (!interaction.deferred) return;
|
||||||
|
try {
|
||||||
|
if (interaction.commandName === "burrow") await handleBurrow(interaction);
|
||||||
|
else if (interaction.commandName === "moderate") await handleModerate(interaction);
|
||||||
|
else if (interaction.commandName === "discord") await handleDiscordModeration(interaction);
|
||||||
|
else if (interaction.commandName === "ticket") await handleTicket(interaction);
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.error(`[discord-bot] interaction failed: ${err.stack || err.message}`);
|
||||||
|
await interaction.editReply(failure("The command could not be completed.")).catch(() => {});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
client.on("error", err => console.error(`[discord-bot] client error: ${err.message}`));
|
||||||
|
if (securityGatewayOn) {
|
||||||
|
client.on("messageCreate", message => { inspectDiscordMessage(message).catch(err => console.error(`[discord-bot] AutoMod failed: ${err.message}`)); });
|
||||||
|
client.on("guildMemberAdd", member => { inspectDiscordJoin(member).catch(err => console.error(`[discord-bot] anti-raid check failed: ${err.message}`)); });
|
||||||
|
}
|
||||||
|
if (memberEvents) {
|
||||||
|
client.on("guildMemberAdd", member => { communityNotice(member, "welcome").catch(err => console.error(`[discord-bot] welcome notice failed: ${err.message}`)); });
|
||||||
|
client.on("guildMemberRemove", member => { communityNotice(member, "goodbye").catch(err => console.error(`[discord-bot] goodbye notice failed: ${err.message}`)); });
|
||||||
|
}
|
||||||
|
unsubscribeReports = reports.onFile(notifyReport);
|
||||||
|
unsubscribeGameActivity = world.onGameActivity(notifyGameActivity);
|
||||||
|
unsubscribeModeration = modlog.onRecord(notifyModeration);
|
||||||
|
statusTimer = setInterval(() => { publishStatus().catch(err => console.error(`[discord-bot] status failed: ${err.message}`)); }, STATUS_EVERY_MS);
|
||||||
|
statusTimer.unref();
|
||||||
|
client.login(config.discord.botToken).catch(err => console.error(`[discord-bot] login failed: ${err.message}`));
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const shutdown = () => {
|
||||||
|
if (statusTimer) clearInterval(statusTimer);
|
||||||
|
statusTimer = null;
|
||||||
|
if (unsubscribeReports) unsubscribeReports();
|
||||||
|
unsubscribeReports = null;
|
||||||
|
if (unsubscribeGameActivity) unsubscribeGameActivity();
|
||||||
|
unsubscribeGameActivity = null;
|
||||||
|
if (unsubscribeModeration) unsubscribeModeration();
|
||||||
|
unsubscribeModeration = null;
|
||||||
|
if (client) client.destroy();
|
||||||
|
client = null;
|
||||||
|
securityGatewayOn = false;
|
||||||
|
recentMessages.clear();
|
||||||
|
recentJoins.length = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const control = async action => {
|
||||||
|
if (action === "stop") {
|
||||||
|
if (!client) return {error: "The Discord bot is already stopped."};
|
||||||
|
shutdown();
|
||||||
|
return {ok: "Discord bot stopped. Game and panel services remain online."};
|
||||||
|
}
|
||||||
|
if (action === "start") {
|
||||||
|
return startup() ? {ok: "Discord bot is starting."} : {error: "Set AJ_DISCORD_BOT_TOKEN and AJ_DISCORD_GUILD_ID, and install discord.js (npm ci), before starting the bot."};
|
||||||
|
}
|
||||||
|
if (action === "reconnect") {
|
||||||
|
shutdown();
|
||||||
|
return startup() ? {ok: "Discord bot is reconnecting."} : {error: "Set AJ_DISCORD_BOT_TOKEN and AJ_DISCORD_GUILD_ID, and install discord.js (npm ci), before reconnecting the bot."};
|
||||||
|
}
|
||||||
|
if (action === "sync") return syncCommands();
|
||||||
|
return {error: "Unknown Discord bot control."};
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {startup, shutdown, control, card, COMPONENTS_V2, dashboardStatus, updateDashboardConfig, updateSecuritySettings, updateCommunitySettings, setStatusSettings, publishStatus, handleGithubWebhook};
|
||||||
+1
-1
@@ -1,4 +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],
|
"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]
|
"stamps": [13,11,2889,2896,1602,2886,1604,12,2877,2885,1603,2894,10,2899,2891,2876,376,2878,2879,2880,2881,2882,2884,2888,2898,2887,2890,377,2892,2893,2895,2900,378,2901,2902]
|
||||||
}
|
}
|
||||||
+61
-14
@@ -1,10 +1,12 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
const achievements = require("./achievements.js");
|
const achievements = require("./achievements.js");
|
||||||
const chatFilter = require("./chatfilter.js");
|
const chatFilter = require("./chatfilter.js");
|
||||||
|
const chatlog = require("./chatlog.js");
|
||||||
const defpacks = require("./defpacks.js");
|
const defpacks = require("./defpacks.js");
|
||||||
const dens = require("./dens.js");
|
const dens = require("./dens.js");
|
||||||
const limits = require("./limits.js");
|
const limits = require("./limits.js");
|
||||||
@@ -15,9 +17,12 @@ const {CURRENCIES, hasRoom, addClothing, sendClothingAdded, sendClothingRemoved}
|
|||||||
// ECardXtCommManager): a card, a stamp, a short message and perhaps a gift,
|
// ECardXtCommManager): a card, a stamp, a short message and perhaps a gift,
|
||||||
// kept in the receiver's inbox (account.ecards) until they delete it.
|
// 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
|
// which cards and stamps exist was a list on the official servers. the cards
|
||||||
// offered here were found by looking through the CDN's media files for card
|
// 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).
|
// artwork (tools/find-art.py found what is in lib/ecard-art.json); the
|
||||||
|
// stamps are the official list itself, as a recording of the official game
|
||||||
|
// has it (lib/official-lists.json, list 44): the ones guessed before were
|
||||||
|
// partly not stamps at all, and showed nothing.
|
||||||
|
|
||||||
// ECard.type: what, if anything, comes with the card
|
// ECard.type: what, if anything, comes with the card
|
||||||
const TYPE_PLAIN = 0;
|
const TYPE_PLAIN = 0;
|
||||||
@@ -49,10 +54,15 @@ const INBOX_FULL = -1;
|
|||||||
const NOT_ACCEPTING = -2;
|
const NOT_ACCEPTING = -2;
|
||||||
const FAILED = 0;
|
const FAILED = 0;
|
||||||
|
|
||||||
// who may send to a player (ECardInbox's settings popup).
|
// who may send to a player, as kept (account.ecardPrivacy).
|
||||||
const FROM_EVERYONE = 0;
|
const FROM_EVERYONE = 0;
|
||||||
const FROM_BUDDIES = 1;
|
const FROM_BUDDIES = 1;
|
||||||
const FROM_NOBODY = 2;
|
const FROM_NOBODY = 2;
|
||||||
|
// ECardInbox's settings popup sends the place of the option picked, and its
|
||||||
|
// artwork has Nobody first and Everyone last: the other way round from the
|
||||||
|
// above. turned over both ways between the two (buddies is in the middle).
|
||||||
|
const SETTING_COUNT = 3;
|
||||||
|
const turnedOver = value => SETTING_COUNT - 1 - value;
|
||||||
|
|
||||||
const LIST_CARDS = 10;
|
const LIST_CARDS = 10;
|
||||||
const LIST_STAMPS = 44;
|
const LIST_STAMPS = 44;
|
||||||
@@ -67,8 +77,23 @@ const now = () => Math.floor(Date.now() / 1000);
|
|||||||
const clean = text => String(text).replace(/[\u0000-\u001f\u007f%]/g, " ").trim().slice(0, MAX_MESSAGE);
|
const clean = text => String(text).replace(/[\u0000-\u001f\u007f%]/g, " ").trim().slice(0, MAX_MESSAGE);
|
||||||
|
|
||||||
module.exports = ({findOnline, blocks}) => {
|
module.exports = ({findOnline, blocks}) => {
|
||||||
|
// a gift the game can show and take: its item still exists (a custom item
|
||||||
|
// may have been deleted since), or an amount that makes sense. any other
|
||||||
|
// left the gift windows stuck; it is treated as no gift at all.
|
||||||
|
const MAX_GIFT_AMOUNT = 10000000;
|
||||||
|
const giftUsable = gift => {
|
||||||
|
if (gift.type === TYPE_CLOTHING) {
|
||||||
|
return Boolean(defpacks.itemDef(gift.def)) && Number.isFinite(Number(gift.color));
|
||||||
|
}
|
||||||
|
if (gift.type === TYPE_DEN_ITEM) {
|
||||||
|
return Boolean(defpacks.denItemDef(gift.def));
|
||||||
|
}
|
||||||
|
const amount = Number(gift.def);
|
||||||
|
return Object.hasOwn(CURRENCY_OF, gift.type) && Number.isInteger(amount) && amount > 0 && amount <= MAX_GIFT_AMOUNT;
|
||||||
|
};
|
||||||
|
|
||||||
// A card from the server carrying gems or diamonds: one of the popups.
|
// 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));
|
const isRedemption = card => Boolean(card.hq && card.gift && giftUsable(card.gift) && Object.hasOwn(CURRENCY_OF, card.gift.type));
|
||||||
|
|
||||||
// who sent a card: by account id, and for cards from before ids were
|
// who sent a card: by account id, and for cards from before ids were
|
||||||
// kept by the name on them.
|
// kept by the name on them.
|
||||||
@@ -88,15 +113,20 @@ module.exports = ({findOnline, blocks}) => {
|
|||||||
const sender = card.hq ? null : senderOf(card);
|
const sender = card.hq ? null : senderOf(card);
|
||||||
const senderType = isRedemption(card) ? FROM_REDEMPTION : card.hq ? FROM_HQ : FROM_PLAYER;
|
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;
|
const name = card.secret ? "" : senderType === FROM_HQ ? HQ_NAME_STRING : card.hq ? HQ_NAME : card.from;
|
||||||
|
const gift = card.gift && giftUsable(card.gift) ? card.gift : null;
|
||||||
return [
|
return [
|
||||||
card.id, name, card.card, card.stamp, card.read ? 1 : 0, card.msg, card.gift ? card.gift.type : TYPE_PLAIN,
|
card.id, name, card.card, card.stamp, card.read ? 1 : 0, card.msg, gift ? gift.type : TYPE_PLAIN,
|
||||||
card.gift ? giftId(card.gift) : 0, card.gift ? card.gift.color : 0, card.gift ? card.gift.name : 0,
|
gift ? giftId(gift) : 0, gift ? gift.color : 0, gift ? gift.name : 0,
|
||||||
card.hq || card.secret ? MEMBER : sender ? sender.accountType : 0,
|
card.hq || card.secret ? MEMBER : sender ? sender.accountType : 0,
|
||||||
0, // name bar data
|
0, // name bar data
|
||||||
0, // secondary type
|
0, // secondary type
|
||||||
senderType,
|
senderType,
|
||||||
USERNAME_SHOWN,
|
USERNAME_SHOWN,
|
||||||
"", // additional gift data
|
// additional gift data: for clothing, "item|<def id>", so that the
|
||||||
|
// patched client (ECardInbox) can show a custom item as itself (its
|
||||||
|
// own picture and name) and not as the art it was made from. (the
|
||||||
|
// "|" keeps the game from taking it for an HQ gift's own message.)
|
||||||
|
gift && gift.type === TYPE_CLOTHING ? `item|${gift.def}` : "",
|
||||||
card.secret ? SECRET_VALENTINE : 0,
|
card.secret ? SECRET_VALENTINE : 0,
|
||||||
];
|
];
|
||||||
};
|
};
|
||||||
@@ -149,7 +179,11 @@ module.exports = ({findOnline, blocks}) => {
|
|||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
// for these the card's "gift id" and "gift name" are both the amount.
|
// 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};
|
const amount = Number(gift.amount);
|
||||||
|
if (!Number.isInteger(amount) || amount < 1 || amount > MAX_GIFT_AMOUNT) {
|
||||||
|
return "An amount from 1 to 10,000,000";
|
||||||
|
}
|
||||||
|
attached = {type: gift.kind === "gems" ? TYPE_GEMS : TYPE_DIAMONDS, def: amount, color: 0, name: amount};
|
||||||
}
|
}
|
||||||
// the gift popup takes a message that starts with a number for the id of
|
// the gift popup takes a message that starts with a number for the id of
|
||||||
// a localization string (StartupPopups.setupGiftPopup).
|
// a localization string (StartupPopups.setupGiftPopup).
|
||||||
@@ -212,8 +246,8 @@ module.exports = ({findOnline, blocks}) => {
|
|||||||
}
|
}
|
||||||
else if (Object.hasOwn(CURRENCY_OF, gift.type)) {
|
else if (Object.hasOwn(CURRENCY_OF, gift.type)) {
|
||||||
const currency = CURRENCIES[CURRENCY_OF[gift.type]];
|
const currency = CURRENCIES[CURRENCY_OF[gift.type]];
|
||||||
account.currency[currency] = (account.currency[currency] || 0) + gift.def;
|
account.currency[currency] = (account.currency[currency] || 0) + Number(gift.def);
|
||||||
achievements.currencyChanged(account, currency, gift.def);
|
achievements.currencyChanged(account, currency, Number(gift.def));
|
||||||
// ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason]
|
// ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason]
|
||||||
session.sendXt("cu", -1, CURRENCY_OF[gift.type], account.currency[currency], 0);
|
session.sendXt("cu", -1, CURRENCY_OF[gift.type], account.currency[currency], 0);
|
||||||
}
|
}
|
||||||
@@ -245,7 +279,8 @@ module.exports = ({findOnline, blocks}) => {
|
|||||||
// silenced: no words of their own reach anyone, in a card either.
|
// 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))
|
if (!to || to === account || !art.cards.includes(Number(card)) || !art.stamps.includes(Number(stamp))
|
||||||
|| !accounts.featureOn(account, "jamagrams") || (isSilenced(account) && clean(message || "") !== "")
|
|| !accounts.featureOn(account, "jamagrams") || (isSilenced(account) && clean(message || "") !== "")
|
||||||
|| !sendsPerTenMinutes.allow(account.id)) {
|
// The client also skips its per-recipient cap for moderators.
|
||||||
|
|| (!account.isModerator && !sendsPerTenMinutes.allow(account.id))) {
|
||||||
reply(FAILED);
|
reply(FAILED);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -260,7 +295,8 @@ module.exports = ({findOnline, blocks}) => {
|
|||||||
const rule = chatFilter.broken(clean(message || ""));
|
const rule = chatFilter.broken(clean(message || ""));
|
||||||
if (rule) {
|
if (rule) {
|
||||||
chatFilter.warn(session);
|
chatFilter.warn(session);
|
||||||
console.log(`[filter] ${account.username} in a Jam-a-Gram to ${to.username}: "${clean(message || "")}" (${rule})`);
|
console.log(`[filter] ${logText(account.username)} in a Jam-a-Gram to ${logText(to.username)}: "${logText(clean(message || ""))}" (${logText(rule)})`);
|
||||||
|
chatlog.recordTo(account, chatlog.JAMAGRAM, to.username, chatlog.NOT_SENT + clean(message || ""));
|
||||||
reply(FAILED);
|
reply(FAILED);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -279,6 +315,8 @@ module.exports = ({findOnline, blocks}) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
deliver(to, {from: account.username, fromId: account.id, card: Number(card), stamp: Number(stamp), msg: clean(message || ""), gift});
|
deliver(to, {from: account.username, fromId: account.id, card: Number(card), stamp: Number(stamp), msg: clean(message || ""), gift});
|
||||||
|
// for the panels (lib/chatlog.js), as typed chat is.
|
||||||
|
chatlog.recordTo(account, chatlog.JAMAGRAM, to.username, clean(message || "") + (gift ? " [with a gift]" : ""));
|
||||||
achievements.add(account, achievements.VARS.jamAGramsSent);
|
achievements.add(account, achievements.VARS.jamAGramsSent);
|
||||||
if (gift) {
|
if (gift) {
|
||||||
achievements.add(account, achievements.VARS.giftsSent);
|
achievements.add(account, achievements.VARS.giftsSent);
|
||||||
@@ -315,6 +353,13 @@ module.exports = ({findOnline, blocks}) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const {gift} = card;
|
const {gift} = card;
|
||||||
|
// a gift that cannot be had (above): gone, and the window let go
|
||||||
|
if (!giftUsable(gift)) {
|
||||||
|
card.gift = null;
|
||||||
|
accounts.save(session.account);
|
||||||
|
session.sendXt("eg", -1, msgId, 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
// no room for it: it stays in the card until there is.
|
// no room for it: it stays in the card until there is.
|
||||||
if (accept === "1" && ((gift.type === TYPE_CLOTHING && !hasRoom(session.account, "items"))
|
if (accept === "1" && ((gift.type === TYPE_CLOTHING && !hasRoom(session.account, "items"))
|
||||||
|| (gift.type === TYPE_DEN_ITEM && !hasRoom(session.account, "denItems")))) {
|
|| (gift.type === TYPE_DEN_ITEM && !hasRoom(session.account, "denItems")))) {
|
||||||
@@ -335,7 +380,7 @@ module.exports = ({findOnline, blocks}) => {
|
|||||||
|
|
||||||
// [setting] -> eCardIsolationHandler: [success]
|
// [setting] -> eCardIsolationHandler: [success]
|
||||||
ei(session, roomId, [setting]) {
|
ei(session, roomId, [setting]) {
|
||||||
const value = Number(setting);
|
const value = turnedOver(Number(setting));
|
||||||
const valid = [FROM_EVERYONE, FROM_BUDDIES, FROM_NOBODY].includes(value);
|
const valid = [FROM_EVERYONE, FROM_BUDDIES, FROM_NOBODY].includes(value);
|
||||||
if (valid) {
|
if (valid) {
|
||||||
session.account.ecardPrivacy = value;
|
session.account.ecardPrivacy = value;
|
||||||
@@ -364,5 +409,7 @@ module.exports = ({findOnline, blocks}) => {
|
|||||||
return card ? senderOf(card) : null;
|
return card ? senderOf(card) : null;
|
||||||
};
|
};
|
||||||
|
|
||||||
return {handlers, list, unread, redemptions, sendFromHq, noteFromHq, secretSender, SECRET_NAME: "Secret Valentine"};
|
// the setting as the inbox's settings popup shows it (above)
|
||||||
|
const privacyShown = account => turnedOver(account.ecardPrivacy || FROM_EVERYONE);
|
||||||
|
return {handlers, list, unread, redemptions, privacyShown, sendFromHq, noteFromHq, secretSender, SECRET_NAME: "Secret Valentine"};
|
||||||
};
|
};
|
||||||
+227
@@ -0,0 +1,227 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const accounts = require("./accounts.js");
|
||||||
|
const achievements = require("./achievements.js");
|
||||||
|
const config = require("../config.js");
|
||||||
|
const defpacks = require("./defpacks.js");
|
||||||
|
|
||||||
|
// the eco den items: producers (special type 6, the Eco Solar Panel and
|
||||||
|
// Eco Wind Turbine) and consumers (7, the eco lamps and fan), sold for eco
|
||||||
|
// credits in the Eco Shop (list 778). client side: gui.EcoScorePopup (a
|
||||||
|
// producer clicked), gui.EcoPointsPopup (a consumer clicked),
|
||||||
|
// DenItemHolder.updateConsumers. the official server's rules were never
|
||||||
|
// recorded; these are this server's:
|
||||||
|
//
|
||||||
|
// - a den's generation is the eco power of the producers placed in its
|
||||||
|
// owner's den in use; consumers switched on take theirs from it, in
|
||||||
|
// inventory order, and one that no longer fits is "offline" (state 2)
|
||||||
|
// until there is power for it again. its switch stays on.
|
||||||
|
// - generation turns into credits, config.ecoCreditsPerPointHour a point
|
||||||
|
// an hour, waiting to be collected ("Get Your Credits") up to the
|
||||||
|
// meter's full 240. an account's first look (an eco window, or the
|
||||||
|
// Eco Shop) gets it config.ecoStartCredits, enough for its first producer.
|
||||||
|
// - the eco score (generation less use) earns the three eco plaques, one
|
||||||
|
// at a time, through user var 465 (a bit each).
|
||||||
|
|
||||||
|
const SPECIAL_PRODUCER = "6";
|
||||||
|
const SPECIAL_CONSUMER = "7";
|
||||||
|
const WIND_TURBINE = 4541;
|
||||||
|
const SOLAR_PANEL = 4540;
|
||||||
|
const CURRENCY_ECO = 11;
|
||||||
|
const ECO_SHOP_LIST = 778;
|
||||||
|
const MAX_WAITING = 240; // EcoScorePopup.updateCreditProgressMeter: the meter is full at 240
|
||||||
|
const USER_VAR_REWARDS = 465;
|
||||||
|
const REWARDS = [
|
||||||
|
{bit: 0, score: 5, def: 4611}, // Wood Eco Plaque
|
||||||
|
{bit: 1, score: 15, def: 4610}, // Silver Eco Plaque
|
||||||
|
{bit: 2, score: 30, def: 4609}, // Gold Eco Plaque
|
||||||
|
];
|
||||||
|
const HOUR_MS = 3600000;
|
||||||
|
|
||||||
|
const OFF = 0;
|
||||||
|
const ON = 1;
|
||||||
|
const OFFLINE = 2;
|
||||||
|
|
||||||
|
const special = item => {
|
||||||
|
const def = defpacks.denItemDef(item.def);
|
||||||
|
return def ? String(def.specialType) : "";
|
||||||
|
};
|
||||||
|
const power = item => Number((defpacks.denItemDef(item.def) || {}).ecoPower) || 0;
|
||||||
|
const placedInUse = account => account.denItems.filter(item => item.spots && item.spots[account.activeDen]);
|
||||||
|
|
||||||
|
// the den in use as the eco windows see it: {generation, consumption,
|
||||||
|
// turbines, panels, consumers: [item], states: Map(inv -> 0 off, 1 on, 2 offline)}
|
||||||
|
const stateOf = account => {
|
||||||
|
const placed = placedInUse(account);
|
||||||
|
const producers = placed.filter(item => special(item) === SPECIAL_PRODUCER);
|
||||||
|
const consumers = placed.filter(item => special(item) === SPECIAL_CONSUMER).sort((one, other) => one.inv - other.inv);
|
||||||
|
const generation = producers.reduce((sum, item) => sum + power(item), 0);
|
||||||
|
let consumption = 0;
|
||||||
|
const states = new Map();
|
||||||
|
for (const item of consumers) {
|
||||||
|
if (!item.ecoOn) {
|
||||||
|
states.set(item.inv, OFF);
|
||||||
|
}
|
||||||
|
else if (consumption + power(item) <= generation) {
|
||||||
|
consumption += power(item);
|
||||||
|
states.set(item.inv, ON);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
states.set(item.inv, OFFLINE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
generation,
|
||||||
|
consumption,
|
||||||
|
turbines: producers.filter(item => item.def === WIND_TURBINE).length,
|
||||||
|
panels: producers.filter(item => item.def === SOLAR_PANEL).length,
|
||||||
|
consumers,
|
||||||
|
states,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// a den item's eco field in the den's state (DenStateItem's last): 0 for
|
||||||
|
// all but consumers
|
||||||
|
const consumerState = (account, item) => (special(item) === SPECIAL_CONSUMER ? stateOf(account).states.get(item.inv) || OFF : OFF);
|
||||||
|
|
||||||
|
const perHour = generation => generation * (Number(config.ecoCreditsPerPointHour) || 0);
|
||||||
|
|
||||||
|
// brings the waiting credits up to now, at the rate the den has now. the
|
||||||
|
// caller saves.
|
||||||
|
const accrue = account => {
|
||||||
|
const now = Date.now();
|
||||||
|
if (!account.eco) {
|
||||||
|
account.eco = {waiting: 0, at: now};
|
||||||
|
const start = Math.max(0, Math.floor(Number(config.ecoStartCredits) || 0));
|
||||||
|
account.currency.ecoCredits = (account.currency.ecoCredits || 0) + start;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const rate = perHour(stateOf(account).generation);
|
||||||
|
const hours = Math.max(0, now - account.eco.at) / HOUR_MS;
|
||||||
|
account.eco.waiting = Math.min(MAX_WAITING, (Number(account.eco.waiting) || 0) + rate * hours);
|
||||||
|
account.eco.at = now;
|
||||||
|
};
|
||||||
|
|
||||||
|
// seconds until one more whole credit waits, 0 when none will
|
||||||
|
const secondsToNext = account => {
|
||||||
|
const rate = perHour(stateOf(account).generation);
|
||||||
|
if (rate <= 0 || account.eco.waiting >= MAX_WAITING) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const short = 1 - (account.eco.waiting % 1);
|
||||||
|
return Math.max(1, Math.ceil(short / rate * 3600));
|
||||||
|
};
|
||||||
|
|
||||||
|
const nextReward = account => {
|
||||||
|
const bits = Number(account.userVars[USER_VAR_REWARDS]) || 0;
|
||||||
|
return REWARDS.find(reward => !(bits & (1 << reward.bit))) || null;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = ({others, ecards}) => {
|
||||||
|
const sendCredits = session => session.sendXt("cu", -1, CURRENCY_ECO, session.account.currency.ecoCredits || 0, 0);
|
||||||
|
|
||||||
|
// the consumers' states to the owner and, when they are in it, everyone
|
||||||
|
// else in the den: DenXtCommManager.denEcoConsumerResponse [consumption,
|
||||||
|
// generation, count, (invIdx, state)...].
|
||||||
|
const sendConsumers = session => {
|
||||||
|
const {account} = session;
|
||||||
|
const state = stateOf(account);
|
||||||
|
const fields = [state.consumption, state.generation, state.consumers.length,
|
||||||
|
...state.consumers.flatMap(item => [item.inv, state.states.get(item.inv)])];
|
||||||
|
session.sendXt("dEc", -1, ...fields);
|
||||||
|
if (session.room && session.room.denOwner === account) {
|
||||||
|
for (const other of others(session)) {
|
||||||
|
other.sendXt("dEc", -1, ...fields);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlers = {
|
||||||
|
// requestDenEcoCreditRefresh -> EcoStateResponse: [turbines, panels,
|
||||||
|
// consumers, generation, consumption, score required, next reward bit,
|
||||||
|
// credits waiting, seconds to the next].
|
||||||
|
dEf(session) {
|
||||||
|
const {account} = session;
|
||||||
|
const firstLook = !account.eco;
|
||||||
|
accrue(account);
|
||||||
|
accounts.save(account);
|
||||||
|
if (firstLook) {
|
||||||
|
sendCredits(session);
|
||||||
|
}
|
||||||
|
const state = stateOf(account);
|
||||||
|
const reward = nextReward(account);
|
||||||
|
session.sendXt("dEf", -1, state.turbines, state.panels, state.consumers.length, state.generation, state.consumption,
|
||||||
|
reward ? reward.score : REWARDS[REWARDS.length - 1].score, reward ? reward.bit : -1,
|
||||||
|
Math.floor(account.eco.waiting), secondsToNext(account));
|
||||||
|
},
|
||||||
|
|
||||||
|
// requestDenEcoCreditRedeem: the waiting credits collected -> [success,
|
||||||
|
// seconds to the next].
|
||||||
|
dEr(session) {
|
||||||
|
const {account} = session;
|
||||||
|
accrue(account);
|
||||||
|
const credits = Math.floor(account.eco.waiting);
|
||||||
|
if (credits < 1) {
|
||||||
|
accounts.save(account);
|
||||||
|
session.sendXt("dEr", -1, 0, secondsToNext(account));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
account.eco.waiting -= credits;
|
||||||
|
account.currency.ecoCredits = (account.currency.ecoCredits || 0) + credits;
|
||||||
|
achievements.currencyChanged(account, "ecoCredits", credits);
|
||||||
|
accounts.save(account);
|
||||||
|
sendCredits(session);
|
||||||
|
session.sendXt("dEr", -1, 1, secondsToNext(account));
|
||||||
|
},
|
||||||
|
|
||||||
|
// requestDenEcoConsumer: [invIdx, "1" on | "0" off]
|
||||||
|
dEc(session, roomId, [invIdx, on]) {
|
||||||
|
const {account} = session;
|
||||||
|
const item = account.denItems.find(candidate => candidate.inv === Number(invIdx));
|
||||||
|
if (item && special(item) === SPECIAL_CONSUMER) {
|
||||||
|
accrue(account);
|
||||||
|
item.ecoOn = on === "1";
|
||||||
|
accounts.save(account);
|
||||||
|
}
|
||||||
|
sendConsumers(session);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// user var 465, set by the eco score window's gift: the value is the bit
|
||||||
|
// of the reward asked for. given when it is the next one and the score is
|
||||||
|
// there; the plaque comes as a gift from HQ. true when the var was this.
|
||||||
|
const userVar = (session, id, bit) => {
|
||||||
|
if (Number(id) !== USER_VAR_REWARDS) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const {account} = session;
|
||||||
|
const reward = nextReward(account);
|
||||||
|
const state = stateOf(account);
|
||||||
|
if (reward && reward.bit === Number(bit) && state.generation - state.consumption >= reward.score
|
||||||
|
&& !ecards.sendFromHq(account, "Eco Reward", {kind: "den", id: reward.def})) {
|
||||||
|
account.userVars[USER_VAR_REWARDS] = (Number(account.userVars[USER_VAR_REWARDS]) || 0) | (1 << reward.bit);
|
||||||
|
accounts.save(account);
|
||||||
|
}
|
||||||
|
if (account.userVars[USER_VAR_REWARDS] === undefined) {
|
||||||
|
account.userVars[USER_VAR_REWARDS] = 0;
|
||||||
|
}
|
||||||
|
achievements.sendVar(session, USER_VAR_REWARDS);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
// the Eco Shop opened: an account that never had eco credits is given
|
||||||
|
// its first, to buy its first producer with.
|
||||||
|
const shopOpened = session => {
|
||||||
|
if (!session.account.eco) {
|
||||||
|
accrue(session.account);
|
||||||
|
accounts.save(session.account);
|
||||||
|
sendCredits(session);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return {handlers, userVar, shopOpened, SHOP_LIST: ECO_SHOP_LIST};
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports.accrue = accrue;
|
||||||
|
module.exports.consumerState = consumerState;
|
||||||
|
module.exports.SPECIAL_TYPES = [SPECIAL_PRODUCER, SPECIAL_CONSUMER];
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
const config = require("../config.js");
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
|
|
||||||
|
// pictures of emoji, for the patched client's chat bubbles (gui.ChatBalloon):
|
||||||
|
// the game's font has none, so an emoji typed in chat (with Windows' emoji
|
||||||
|
// panel, say) is drawn as one of these. they are Twemoji's (CC-BY 4.0,
|
||||||
|
// jdecked/twemoji on GitHub), asked of config.emojiUpstream once
|
||||||
|
// each and kept in data/emoji. a name is the emoji's code points in hex,
|
||||||
|
// joined by "-", as Twemoji names its files ("1f600", "1f468-200d-1f469").
|
||||||
|
|
||||||
|
const NAME = /^[0-9a-f]{2,6}(?:-[0-9a-f]{2,6}){0,9}$/;
|
||||||
|
const MAX_BYTES = 64 * 1024;
|
||||||
|
const MAX_MISSING = 5000;
|
||||||
|
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
|
||||||
|
const DIR = path.join(config.dataDir, "emoji");
|
||||||
|
|
||||||
|
const missing = new Set(); // names the upstream does not have
|
||||||
|
const pending = new Map(); // name -> promise, so that one is asked for once
|
||||||
|
|
||||||
|
const isName = name => typeof name === "string" && NAME.test(name);
|
||||||
|
|
||||||
|
const fileOf = name => path.join(DIR, `${name}.png`);
|
||||||
|
|
||||||
|
const fetchUpstream = async name => {
|
||||||
|
const res = await fetch(`${config.emojiUpstream}${name}.png`, {signal: AbortSignal.timeout(config.upstreamTimeoutMs)});
|
||||||
|
if (!res.ok) {
|
||||||
|
if (res.status === 404 || res.status === 403) {
|
||||||
|
if (missing.size >= MAX_MISSING) {
|
||||||
|
missing.clear();
|
||||||
|
}
|
||||||
|
missing.add(name);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const body = Buffer.from(await res.arrayBuffer());
|
||||||
|
// a PNG, and a small one, or nothing is kept
|
||||||
|
if (body.length > MAX_BYTES || !body.subarray(0, 8).equals(PNG_SIGNATURE)) {
|
||||||
|
console.log(`[emoji] not a picture: ${logText(name)}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(DIR, {recursive: true});
|
||||||
|
const tmp = `${fileOf(name)}.${process.pid}.tmp`;
|
||||||
|
fs.writeFileSync(tmp, body);
|
||||||
|
fs.renameSync(tmp, fileOf(name));
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.log(`[emoji] could not keep ${logText(name)}: ${logText(err.message)}`);
|
||||||
|
}
|
||||||
|
return body;
|
||||||
|
};
|
||||||
|
|
||||||
|
// the picture for `name`: a Buffer, or null. `mayFetch()`: whether one not
|
||||||
|
// kept yet may be asked of the upstream for this request (asked only then).
|
||||||
|
const get = async (name, mayFetch) => {
|
||||||
|
if (!isName(name) || missing.has(name)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return await fs.promises.readFile(fileOf(name));
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
if (err.code !== "ENOENT") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!mayFetch()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!pending.has(name)) {
|
||||||
|
pending.set(name, fetchUpstream(name).catch(() => null).finally(() => pending.delete(name)));
|
||||||
|
}
|
||||||
|
return pending.get(name);
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {get, isName};
|
||||||
+4
-1
@@ -3,13 +3,15 @@
|
|||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
const bans = require("./bans.js");
|
const bans = require("./bans.js");
|
||||||
const chatlog = require("./chatlog.js");
|
const chatlog = require("./chatlog.js");
|
||||||
|
const devices = require("./devices.js");
|
||||||
const masterpieces = require("./masterpieces.js");
|
const masterpieces = require("./masterpieces.js");
|
||||||
const support = require("./support.js");
|
const support = require("./support.js");
|
||||||
const world = require("./world.js");
|
const world = require("./world.js");
|
||||||
|
|
||||||
// an account deleted for good, by its owner (lib/manage.js) or by the admin
|
// 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
|
// (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
|
// lines, its appeal, its feedback and username requests, the computers it
|
||||||
|
// was used from (lib/devices.js), and the paintings
|
||||||
// it made (from whoever holds one by now). what stays is said in the
|
// 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
|
// 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.
|
// moderators did, under the name it had, until lib/retention.js ends it.
|
||||||
@@ -20,6 +22,7 @@ module.exports = account => {
|
|||||||
}
|
}
|
||||||
bans.forget(account);
|
bans.forget(account);
|
||||||
chatlog.forget(account);
|
chatlog.forget(account);
|
||||||
|
devices.forget(account);
|
||||||
support.forget(account);
|
support.forget(account);
|
||||||
accounts.remove(account);
|
accounts.remove(account);
|
||||||
};
|
};
|
||||||
+53
-2
@@ -1,5 +1,7 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
const zlib = require("zlib");
|
const zlib = require("zlib");
|
||||||
const amf3 = require("./amf3.js");
|
const amf3 = require("./amf3.js");
|
||||||
const cdn = require("./cdn.js");
|
const cdn = require("./cdn.js");
|
||||||
@@ -13,15 +15,57 @@ const cdn = require("./cdn.js");
|
|||||||
// (DenItemHolder), and the CDN has no such files for these. each one's
|
// (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
|
// 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
|
// 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.
|
// client first asks for it. nothing of it is kept in this repository,
|
||||||
|
// except the tracks that are files of their own (`mp3`, in public/music/).
|
||||||
|
|
||||||
const FIRST_ID = 6001; // the official den items end at 5925
|
const FIRST_ID = 6001; // the official den items end at 5925
|
||||||
const STRING_BASE = 9000100;
|
const STRING_BASE = 9000100;
|
||||||
const VOLUME = "40"; // the def's `flag`, as the official tracks have it
|
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
|
const TEMPLATE = 614; // "Jam On": each new row starts as a copy of this track's
|
||||||
|
|
||||||
|
// music files from the game's development CDN that no den item plays,
|
||||||
|
// kept in public/music/ and titled with their file names. tracks that
|
||||||
|
// already are den items there under another name (the same audio, or the
|
||||||
|
// same track by its name and length) were left out.
|
||||||
|
const DEV_MUSIC = [
|
||||||
|
"aj_BD_newTheme.mp3", "AJ_cinema_lobby.mp3", "AJ_CS_mus_over_flow.mp3", "aj_dr_musIntro.mp3", "aj_dr_musOutro.mp3",
|
||||||
|
"aj_eat_em_up.mp3", "aj_fallingPhantoms.mp3", "aj_mus_BD_FullSpectrum.mp3", "aj_mus_BD_muffled.mp3",
|
||||||
|
"aj_mus_BD_OceanFullSpectrum.mp3", "aj_mus_Best_Dressed1.mp3", "aj_mus_bestDressedOcean1.mp3",
|
||||||
|
"aj_mus_bestDressedOceanMuffled.mp3", "aj_mus_carnival.mp3", "aj_mus_club.mp3", "AJ_mus_den_sitar.mp3",
|
||||||
|
"aj_mus_dolphin.mp3", "AJ_mus_double_up.mp3", "aj_mus_flag_room.mp3", "AJ_mus_gem_ball.mp3",
|
||||||
|
"aj_mus_gem_breaker.mp3", "aj_mus_hassel_hoff.mp3", "aj_mus_hedgehog.mp3", "aj_mus_horseRaceLP.mp3",
|
||||||
|
"AJ_mus_jamaa_township.mp3", "aj_mus_oceans_shop.mp3", "AJ_Mus_Phantom_Fighter.mp3", "aj_mus_phantoms_treasure.mp3",
|
||||||
|
"aj_mus_pillBug.mp3", "aj_mus_rare_item_shop.mp3", "aj_mus_shiveer_tent.mp3", "aj_mus_sorting_game.mp3",
|
||||||
|
"AJ_Mus_spider_shooter.mp3", "aj_mus_Thierrys_aquarium.mp3", "aj_mus_touchPool.mp3", "AJ_mus_twister.mp3",
|
||||||
|
"aj_mus_wolfParty.mp3", "aj_musBackToSchoolParty.mp3", "aj_musBestGuess.mp3", "aj_musChineseNewYear.mp3",
|
||||||
|
"aj_musEagleLP.mp3", "aj_musHospital.mp3", "aj_musNewJammaIntro.mp3", "aj_musNPEintro.mp3", "aj_musOutback.mp3",
|
||||||
|
"aj_musOutbackShop.mp3", "aj_musPhntmKingIntro.mp3", "aj_musSpotOn.mp3", "aj_musStingerRaceIntro.mp3",
|
||||||
|
"aj_musStingerRaceOver.mp3", "aj_musTelescopeRoom.mp3", "aj_musVolcanoGreely.mp3", "AJ_Native_American.mp3",
|
||||||
|
"aj_petshop_mus.mp3", "AJ_reggaeton.mp3", "AJ_Shopping_music.mp3", "ajm_musBossBattle25.mp3", "ajm_musCloud.mp3",
|
||||||
|
"ajm_musFFFruitShack.mp3", "ajm_musFFSplash.mp3", "ajm_musFFTheater.mp3", "ajm_tugOfWar.mp3", "ajmusMasterp.mp3",
|
||||||
|
"ajq_forbodingTheme.mp3", "ajq_MiraThemeFinal.mp3", "ajq_mus2PhntmKings.mp3", "ajq_musAdvent20Hub.mp3",
|
||||||
|
"ajq_musBattleoftheForrest.mp3", "ajq_musbunnyBurrow.mp3", "ajq_musCave.mp3", "ajq_musCaveBossBattle.mp3",
|
||||||
|
"ajq_musCaveSlides.mp3", "ajq_musCharge.mp3", "ajq_musCombat.mp3", "ajq_musCraftingVillage.mp3",
|
||||||
|
"ajq_musDungeon.mp3", "ajq_musEerieGreelyCave.mp3", "ajq_musFactoryBossLp.mp3", "ajq_musFroggyMarsh.mp3",
|
||||||
|
"ajq_musGraveyard.mp3", "ajq_musHauntedForest.mp3", "ajq_musInToDeep.mp3", "ajq_musIntotheCaves.mp3",
|
||||||
|
"ajq_musMadGreely.mp3", "ajq_musMiraTomb.mp3", "ajq_musOceanQuest9.mp3", "ajq_musOuterLimits.mp3",
|
||||||
|
"ajq_musPeckSafe.mp3", "ajq_musPecksSecret.mp3", "ajq_musPhntmCreepy.mp3", "ajq_musPhntmDiguise.mp3",
|
||||||
|
"ajq_musPhntmInvasion.mp3", "ajq_musPhntmKingIntro.mp3", "ajq_musPhntmRetreat.mp3", "ajq_musPumpkinPatch.mp3",
|
||||||
|
"ajq_musQ22FinalRoom.mp3", "ajq_musQuest.mp3", "ajq_musQuest19Cave.mp3", "ajq_musQuest22.mp3",
|
||||||
|
"ajq_musQuest22B.mp3", "ajq_MusQuest23.mp3", "ajq_MusQuest23Intro.mp3", "ajq_musQuestStealth.mp3",
|
||||||
|
"ajq_musRoofTop.mp3", "ajq_musSafeLP.mp3", "ajq_musScienceLab.mp3", "ajq_musSearch4GreelyLP.mp3",
|
||||||
|
"ajq_musSirGilbertsCastle.mp3", "ajq_musSpooky.mp3", "ajq_musSpotted.mp3", "ajq_musSuspicious.mp3",
|
||||||
|
"ajq_musTrainingForrest.mp3", "ajq_musTreeHutPlayful.mp3", "ajq_musTugOfWarIdleLP.mp3", "ajq_musTurningTheTide.mp3",
|
||||||
|
"ajq_musTutorial.mp3", "ajq_musVolcanoFreeze.mp3", "ajq_musVolIn.mp3", "ajq_musVolOut.mp3", "ajq_musWinterFun.mp3",
|
||||||
|
"ajw_musWildExplorers.mp3", "ajw_musWildExplorersTent.mp3", "astronomy_mus_think.mp3", "fs_mus_intro.mp3",
|
||||||
|
"Mus_AP_Interface.mp3", "Mus_Art_Studio_theme.mp3", "MusAppondaleMuseum.mp3", "MusBirdsOfParadise.mp3",
|
||||||
|
"MusDenDef.mp3", "TD_mus_120bpm_lp.mp3", "TD_mus_80bpm_lp.mp3", "TD_mus_80bpm_nw.mp3", "TD_mus_80bpm_we.mp3",
|
||||||
|
];
|
||||||
|
|
||||||
// {file, title, sound: the sound's exported name ("" for the only, unnamed
|
// {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}
|
// one), and where it is: a media id, or a room file and the asset in it, or
|
||||||
|
// an MP3 of this server's own in public/music/ (`mp3`)}. new tracks go at the
|
||||||
|
// end: a track's item id is its place in the list.
|
||||||
const TRACKS = [
|
const TRACKS = [
|
||||||
{file: "XtraNarration", title: "Narration", media: 1904, sound: "Narration"},
|
{file: "XtraNarration", title: "Narration", media: 1904, sound: "Narration"},
|
||||||
{file: "XtraUnnamed", title: "Unnamed Sound", media: 46, sound: ""},
|
{file: "XtraUnnamed", title: "Unnamed Sound", media: 46, sound: ""},
|
||||||
@@ -32,6 +76,8 @@ const TRACKS = [
|
|||||||
{file: "XtraVolcano", title: "Volcano", media: 2507, sound: "aj_musVolcanoFull"},
|
{file: "XtraVolcano", title: "Volcano", media: 2507, sound: "aj_musVolcanoFull"},
|
||||||
...[1, 2, 3, 4].map(layer => ({file: `XtraConcert${layer}`, title: `Concert Layer ${layer}`,
|
...[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}`})),
|
room: "party/venue_concert", asset: "Concert\\Concert_Party_Front_Lights.swf", sound: `layer${layer}`})),
|
||||||
|
{file: "XtraDebugMusic", title: "AJ_Debug_Music.mp3", mp3: "AJ_Debug_Music.mp3"},
|
||||||
|
...DEV_MUSIC.map(mp3 => ({file: `Xtra_${mp3.slice(0, -4)}`, title: mp3, mp3})),
|
||||||
].map((track, index) => ({...track, id: FIRST_ID + index, stringId: STRING_BASE + index}));
|
].map((track, index) => ({...track, id: FIRST_ID + index, stringId: STRING_BASE + index}));
|
||||||
|
|
||||||
const ids = TRACKS.map(track => track.id);
|
const ids = TRACKS.map(track => track.id);
|
||||||
@@ -87,7 +133,12 @@ const soundIn = (swf, name) => {
|
|||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const MUSIC_DIR = path.join(__dirname, "..", "public", "music");
|
||||||
|
|
||||||
const extract = async track => {
|
const extract = async track => {
|
||||||
|
if (track.mp3) {
|
||||||
|
return fs.promises.readFile(path.join(MUSIC_DIR, track.mp3));
|
||||||
|
}
|
||||||
if (track.media) {
|
if (track.media) {
|
||||||
const swf = await cdn.get(cdn.hashedPath(`media/${track.media}`));
|
const swf = await cdn.get(cdn.hashedPath(`media/${track.media}`));
|
||||||
return swf ? soundIn(swf, track.sound) : null;
|
return swf ? soundIn(swf, track.sound) : null;
|
||||||
|
|||||||
+101
-70
@@ -1,84 +1,118 @@
|
|||||||
[
|
[
|
||||||
{"id": 4, "swf": "Pachinko", "title": "Gem Ball", "type": 1, "vars": [16, 17, 0], "icon": 4295},
|
{"id": 1, "swf": "PVP_TicTacToe", "title": "Tic Tac Toe", "type": 0, "vars": [63,0,0], "icon": 5063, "card": 5055, "buddy": true},
|
||||||
{"id": 5, "swf": "MiniGame_Memory", "title": "Double Up", "type": 1, "vars": [6, 7, 83], "icon": 4291},
|
{"id": 4, "swf": "Pachinko", "title": "Gem Ball", "type": 1, "vars": [16,17,0], "icon": 4295, "card": 58},
|
||||||
{"id": 6, "swf": "MoatMadness", "title": "Overflow", "type": 1, "vars": [8, 9, 80], "icon": 4300},
|
{"id": 5, "swf": "MiniGame_Memory", "title": "Double Up", "type": 1, "vars": [6,7,0], "icon": 4291, "card": 61},
|
||||||
{"id": 10, "swf": "ParachuteGlider", "title": "Wind Rider", "type": 1, "vars": [12, 13, 79], "start": "seed", "icon": 4311},
|
{"id": 6, "swf": "MoatMadness", "title": "Overflow", "type": 1, "vars": [8,9,9], "icon": 4300, "card": 59},
|
||||||
{"id": 11, "swf": "Trivia", "title": "Temple of Trivia", "type": 1, "vars": [10, 11, 0], "ready": false, "icon": 4309},
|
{"id": 10, "swf": "ParachuteGlider", "title": "Wind Rider", "type": 1, "vars": [12,13,0], "start": "seedAndCrosshairs", "icon": 4311, "card": 65},
|
||||||
{"id": 12, "swf": "RiverRace", "title": "River Race", "type": 1, "vars": [22, 23, 0], "start": "seed"},
|
{"id": 11, "swf": "Trivia", "title": "Temple of Trivia", "type": 1, "vars": [10,11,0], "icon": 4309, "card": 64, "ready": false},
|
||||||
{"id": 13, "swf": "PhantomFighter", "title": "Phantom Fighter", "type": 1, "vars": [14, 15, 84], "icon": 4312},
|
{"id": 12, "swf": "RiverRace", "title": "River Race", "type": 1, "vars": [22,23,0], "start": "seed", "card": 62},
|
||||||
{"id": 14, "swf": "SpiderShooter", "title": "Spider Zapper", "type": 1, "vars": [18, 19, 82], "start": "seed", "icon": 4305},
|
{"id": 13, "swf": "PhantomFighter", "title": "Phantom Fighter", "type": 1, "vars": [14,15,0], "icon": 4312, "card": 60},
|
||||||
|
{"id": 14, "swf": "SpiderShooter", "title": "Spider Zapper", "type": 1, "vars": [18,19,0], "start": "seedAndCrosshairs", "icon": 4305, "card": 63},
|
||||||
{"id": 15, "swf": "MicroPopcorn", "title": "Popcorn Machine", "type": 0},
|
{"id": 15, "swf": "MicroPopcorn", "title": "Popcorn Machine", "type": 0},
|
||||||
{"id": 16, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 16, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
{"id": 17, "swf": "MicroSmoothie", "title": "Smoothie Machine", "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": 18, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
{"id": 20, "swf": "Twister", "title": "Twister", "type": 1, "vars": [24, 25, 81], "icon": 4310},
|
{"id": 19, "swf": "WindRider", "title": "Sky High", "type": 1, "vars": [26,27,0], "icon": 4304, "card": 78},
|
||||||
{"id": 22, "swf": "DistanceChallenge", "title": "Long Shot", "type": 1, "vars": [20, 21, 0], "icon": 4298},
|
{"id": 20, "swf": "Twister", "title": "Twister", "type": 1, "vars": [24,25,0], "icon": 4310, "card": 79},
|
||||||
{"id": 23, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1},
|
{"id": 21, "swf": "FrogFlyer", "title": "Long Shot", "type": 1, "ready": false},
|
||||||
{"id": 26, "swf": "ArtStudioPottery", "title": "Pottery", "type": 1},
|
{"id": 22, "swf": "DistanceChallenge", "title": "Long Shot", "type": 1, "vars": [20,21,21], "icon": 4298, "card": 80},
|
||||||
{"id": 27, "swf": "MicroPhantom", "title": "Phantom Vortex", "type": 0},
|
{"id": 23, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1, "card": 58},
|
||||||
{"id": 28, "swf": "TowerDefense", "title": "Pest Control", "type": 1, "vars": [130, 131, 132], "icon": 4301},
|
{"id": 24, "swf": "ArtStudioColor", "title": "Coloring", "type": 1, "card": 58, "ready": false},
|
||||||
{"id": 30, "swf": "GemBreaker", "title": "Gem Breaker", "type": 1, "vars": [91, 93, 92], "start": "seedAndPlayers", "icon": 4313},
|
{"id": 25, "swf": "ParachuteGliderTest", "title": "Wind Rider", "type": 1, "card": 65, "ready": false},
|
||||||
{"id": 34, "swf": "MicroMiraSays", "title": "Mira Says", "type": 1, "vars": [77, 76, 0], "icon": 4299},
|
{"id": 26, "swf": "ArtStudioPottery", "title": "Pottery", "type": 1, "card": 58},
|
||||||
{"id": 35, "swf": "FortSmasher", "title": "Fruit Slinger", "type": 1, "vars": [143, 144, 145], "ready": false, "icon": 4294},
|
{"id": 27, "swf": "MicroPhantom", "title": "Phantom Vortex", "type": 0, "card": 69},
|
||||||
{"id": 36, "swf": "MicroHotCocoa", "title": "Hot Cocoa Machine", "type": 0},
|
{"id": 28, "swf": "TowerDefense", "title": "Pest Control", "type": 1, "vars": [130,131,132], "icon": 4301, "card": 456},
|
||||||
{"id": 37, "swf": "SuperSort", "title": "Super Sort", "type": 1, "vars": [31, 32, 37], "icon": 4307},
|
{"id": 29, "swf": "GemBreaker", "title": "Gem Breaker", "type": 1, "start": "seedAndPlayers", "card": 58},
|
||||||
{"id": 39, "swf": "PillBugs", "title": "Pill Bugs", "type": 1, "vars": [277, 278, 279], "icon": 4303},
|
{"id": 30, "swf": "GemBreaker", "title": "Gem Breaker", "type": 1, "vars": [91,32,0], "start": "seedAndPlayers", "icon": 4313, "card": 354},
|
||||||
{"id": 40, "swf": "BradyExpeditions", "title": "Brady Expeditions", "type": 1},
|
{"id": 31, "swf": "PVP_ConnectFour", "title": "Four Gems", "type": 0, "icon": 5057, "card": 5049, "buddy": true},
|
||||||
{"id": 41, "swf": "PhantomsTreasure", "title": "Phantom's Treasure", "type": 1, "vars": [281, 283, 282], "icon": 4302},
|
{"id": 32, "swf": "PVP_RockPaperScissor", "title": "Rock Paper Scissors", "type": 0, "icon": 5060, "card": 5052, "buddy": true},
|
||||||
{"id": 42, "swf": "FeedingFrenzy", "title": "Eat 'Em Up", "type": 1, "vars": [284, 285, 0], "icon": 4292},
|
{"id": 34, "swf": "MicroMiraSays", "title": "Mira Says", "type": 1, "vars": [77,76,0], "icon": 4299, "card": 288},
|
||||||
{"id": 43, "swf": "MicroPetWash", "title": "Pet Wash", "type": 0},
|
{"id": 35, "swf": "FortSmasher", "title": "Fruit Slinger", "type": 1, "vars": [74,75,0], "icon": 4294, "card": 541, "ready": false},
|
||||||
{"id": 48, "swf": "FashionShow", "title": "Best Dressed", "type": 1, "vars": [292, 293, 294], "ready": false, "icon": 4288},
|
{"id": 36, "swf": "MicroHotCocoa", "title": "Hot Cocoa Machine", "type": 0, "vars": [95,0,0]},
|
||||||
{"id": 51, "swf": "ArtStudioPainting", "title": "Painting", "type": 1},
|
{"id": 37, "swf": "SuperSort", "title": "Super Sort", "type": 1, "vars": [31,32,37], "icon": 4307, "card": 353},
|
||||||
{"id": 52, "swf": "MicroPetSalon", "title": "Pet Stop", "type": 0},
|
{"id": 38, "swf": "PVP_ShellGame", "title": "Shell Game", "type": 0, "icon": 5062, "card": 5054, "buddy": true},
|
||||||
{"id": 55, "swf": "MicroGameInvasion", "title": "Phantom Invasion", "type": 0},
|
{"id": 39, "swf": "PillBugs", "title": "Pill Bugs", "type": 1, "vars": [277,278,279], "icon": 4303, "card": 1098},
|
||||||
|
{"id": 40, "swf": "BradyChemistrySet", "title": "Brady's Lab", "type": 0, "vars": [115,0,0]},
|
||||||
|
{"id": 41, "swf": "PhantomsTreasure", "title": "Phantom's Treasure", "type": 1, "vars": [281,283,282], "icon": 4302, "card": 1140},
|
||||||
|
{"id": 42, "swf": "FeedingFrenzy", "title": "Eat 'Em Up", "type": 1, "vars": [284,0,0], "icon": 4292, "card": 1170},
|
||||||
|
{"id": 43, "swf": "MicroPetWash", "title": "Pet Wash", "type": 0, "vars": [51,0,0]},
|
||||||
|
{"id": 45, "swf": "PVP_Marbles", "title": "Marbles", "type": 0, "icon": 5058, "card": 5050, "buddy": true},
|
||||||
|
{"id": 46, "swf": "OffTheHook", "title": "Off the Hook", "type": 1, "card": 79, "ready": false},
|
||||||
|
{"id": 47, "swf": "Pinball", "title": "Double Up", "type": 1, "card": 61, "ready": false},
|
||||||
|
{"id": 48, "swf": "FashionShow", "title": "Best Dressed", "type": 1, "vars": [292,293,294], "icon": 4288, "card": 1205, "ready": false},
|
||||||
|
{"id": 49, "swf": "Geography", "title": "Geography", "type": 1, "card": 79, "ready": false},
|
||||||
|
{"id": 51, "swf": "ArtStudioPainting", "title": "Painting", "type": 1, "vars": [78,0,0], "card": 4849},
|
||||||
|
{"id": 52, "swf": "MicroPetSalon", "title": "Pet Stop", "type": 0, "vars": [280,0,0], "card": 1205},
|
||||||
|
{"id": 53, "swf": "PVP_Scooped", "title": "Scooped", "type": 0, "icon": 5061, "card": 5053, "buddy": true},
|
||||||
|
{"id": 54, "swf": "Glide", "title": "Glide", "type": 1, "card": 79, "ready": false},
|
||||||
|
{"id": 55, "swf": "MicroGameInvasion", "title": "Phantom Invasion", "type": 0, "card": 1205},
|
||||||
|
{"id": 56, "swf": "ActivityGeography", "title": "Eat 'Em Up", "type": 1, "card": 1205, "ready": false},
|
||||||
{"id": 57, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 57, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
|
{"id": 58, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
{"id": 59, "swf": "MicroCrane", "title": "The Claw", "type": 0, "icon": 4290},
|
{"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": 60, "swf": "TouchPool", "title": "Touch Pool", "type": 1, "vars": [310,308,309], "icon": 5229, "card": 5228},
|
||||||
{"id": 61, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 61, "swf": "MicroCrane", "title": "The Claw", "type": 0, "card": 65},
|
||||||
{"id": 62, "swf": "HorseRace", "title": "Jamaa Derby", "type": 1, "vars": [327, 328, 330], "ready": false, "icon": 4297},
|
{"id": 62, "swf": "HorseRace", "title": "Jamaa Derby", "type": 1, "vars": [327,328,330], "icon": 4297, "card": 1510, "ready": false},
|
||||||
{"id": 63, "swf": "MicroPuppy", "title": "Disc Toss", "type": 0, "vars": [313, 314, 315], "pet": 4},
|
{"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": 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": 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": 66, "swf": "FashionShow", "title": "Best Dressed", "type": 1, "vars": [292,293,294], "icon": 4289, "card": 1482, "ready": false},
|
||||||
{"id": 68, "swf": "Skeeball", "title": "Phantom Ball", "type": 1, "tickets": 10},
|
{"id": 67, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
{"id": 69, "swf": "WhackPhantom", "title": "Whack-A-Phantom", "type": 1, "tickets": 10},
|
{"id": 68, "swf": "Skeeball", "title": "Phantom Ball", "type": 0, "tickets": 10},
|
||||||
{"id": 70, "swf": "CandyCatcher", "title": "Candy Catch", "type": 1, "tickets": 10},
|
{"id": 69, "swf": "WhackPhantom", "title": "Whack-A-Phantom", "type": 0, "vars": [78,0,0], "tickets": 10, "card": 300},
|
||||||
|
{"id": 70, "swf": "CandyCatcher", "title": "Candy Catch", "type": 0, "tickets": 10, "card": 300},
|
||||||
{"id": 71, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 71, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
{"id": 72, "swf": "MicroGameInvasion", "title": "Phantom Invasion", "type": 0},
|
{"id": 72, "swf": "MicroGameInvasion", "title": "Phantom Invasion", "type": 0, "card": 259},
|
||||||
{"id": 73, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 1},
|
{"id": 73, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 1, "vars": [78,0,0], "card": 1205},
|
||||||
{"id": 74, "swf": "CottonCandy", "title": "Cotton Candy Machine", "type": 0},
|
{"id": 74, "swf": "CottonCandy", "title": "Cotton Candy Machine", "type": 0, "vars": [78,0,0]},
|
||||||
{"id": 75, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 75, "swf": "MicroCrane", "title": "The Claw", "type": 0, "card": 300},
|
||||||
{"id": 76, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1},
|
{"id": 76, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
|
||||||
{"id": 77, "swf": "FallingPhantoms", "title": "Falling Phantoms", "type": 1, "vars": [344, 345, 346], "ready": false, "icon": 4293},
|
{"id": 77, "swf": "FallingPhantoms", "title": "Falling Phantoms", "type": 1, "vars": [344,345,346], "icon": 4293, "card": 1622, "ready": false},
|
||||||
{"id": 78, "swf": "DolphinRace", "title": "Splash and Dash", "type": 1, "vars": [357, 358, 360], "ready": false, "icon": 4306},
|
{"id": 78, "swf": "DolphinRace", "title": "Splash and Dash", "type": 1, "vars": [357,358,360], "icon": 4306, "card": 1804, "ready": false},
|
||||||
{"id": 80, "swf": "ShootingGallery", "title": "Carnival Darts", "type": 1, "tickets": 100},
|
{"id": 80, "swf": "ShootingGallery", "title": "Carnival Darts", "type": 0, "tickets": 100},
|
||||||
{"id": 81, "swf": "MicroPetSalon", "title": "Pet Stop", "type": 0},
|
{"id": 81, "swf": "MicroPetSalon", "title": "Pet Stop", "type": 0, "vars": [57,0,0], "card": 259},
|
||||||
{"id": 82, "swf": "FastFoodies", "title": "Fast Foodies", "type": 1, "vars": [445, 444, 446], "icon": 5727},
|
{"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": 83, "swf": "HedgeHog", "title": "Hedge Hog", "type": 1, "vars": [349,350,351], "icon": 4296, "card": 1713},
|
||||||
{"id": 85, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 85, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
{"id": 86, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1},
|
{"id": 86, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
|
||||||
{"id": 87, "swf": "BradyChemistrySet", "title": "Brady's Lab", "type": 0},
|
{"id": 87, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
|
||||||
{"id": 88, "swf": "SafetyQuiz", "title": "Safety Quiz", "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": 89, "swf": "ArtStudioPrint", "title": "Coloring", "type": 0},
|
||||||
{"id": 96, "swf": "DunkAPhantom", "title": "Dunk-A-Phantom", "type": 1, "tickets": 10},
|
{"id": 90, "swf": "BradyExpeditions", "title": "Brady Expeditions", "type": 1},
|
||||||
{"id": 97, "swf": "SpotOn", "title": "Spot On", "type": 1, "vars": [386, 387, 388], "icon": 4321},
|
{"id": 91, "swf": "MicroSmoothie", "title": "Smoothie Machine", "type": 0},
|
||||||
|
{"id": 92, "swf": "ParachuteGlider2", "title": "Wind Rider", "type": 1, "card": 65, "ready": false},
|
||||||
|
{"id": 93, "swf": "QuestParachuteGlider", "title": "Wind Rider", "type": 1, "vars": [12,13,0], "card": 65, "ready": false},
|
||||||
|
{"id": 94, "swf": "EagleFlap", "title": "Swoopy Eagle", "type": 1, "vars": [378,377,0], "icon": 4308, "card": 2647},
|
||||||
|
{"id": 95, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
|
||||||
|
{"id": 96, "swf": "DunkAPhantom", "title": "Dunk-A-Phantom", "type": 0, "tickets": 10, "card": 300},
|
||||||
|
{"id": 97, "swf": "SpotOn", "title": "Spot On", "type": 1, "vars": [386,387,388], "icon": 4321, "card": 3561},
|
||||||
|
{"id": 98, "swf": "MicroCrane", "title": "The Claw", "type": 0, "vars": [5,0,0]},
|
||||||
{"id": 99, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 99, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
{"id": 100, "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": 101, "swf": "PVP_Memory", "title": "Pairs", "type": 0, "icon": 5059, "card": 5051, "buddy": true},
|
||||||
|
{"id": 102, "swf": "TrueFalse", "title": "Best Guess", "type": 1, "vars": [403,0,0], "card": 3748, "ready": false},
|
||||||
{"id": 103, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 103, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
{"id": 104, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 104, "swf": "MicroCrane", "title": "The Claw", "type": 0, "card": 300},
|
||||||
{"id": 105, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 105, "swf": "MicroCrane", "title": "The Claw", "type": 0, "card": 61},
|
||||||
{"id": 106, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 106, "swf": "MicroCrane", "title": "The Claw", "type": 0, "card": 61},
|
||||||
{"id": 107, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 107, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
|
{"id": 108, "swf": "PVP_Bowling", "title": "Bowling", "type": 0, "icon": 5056, "card": 5048, "buddy": true},
|
||||||
{"id": 109, "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": 110, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
|
{"id": 111, "swf": "MicroGoldPanning", "title": "Long Shot", "type": 0, "vars": [415,0,0], "ready": false},
|
||||||
|
{"id": 112, "swf": "MicroOatHarvest", "title": "Slingshot", "type": 0, "vars": [415,0,0], "ready": false},
|
||||||
|
{"id": 113, "swf": "MicroWoodGather", "title": "Slingshot", "type": 0, "vars": [415,0,0], "ready": false},
|
||||||
|
{"id": 114, "swf": "MicroStoneMining", "title": "Slingshot", "type": 0, "vars": [415,0,0], "ready": false},
|
||||||
|
{"id": 115, "swf": "MicroBambooHarvest", "title": "Slingshot", "type": 0, "vars": [415,0,0], "ready": false},
|
||||||
{"id": 116, "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": 117, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
{"id": 118, "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": 119, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
{"id": 120, "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": 121, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
|
{"id": 122, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
|
||||||
{"id": 123, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 123, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
|
{"id": 124, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
|
||||||
{"id": 125, "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": 126, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
{"id": 127, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 127, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
@@ -89,9 +123,11 @@
|
|||||||
{"id": 132, "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": 133, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
{"id": 134, "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": 135, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
|
||||||
{"id": 138, "swf": "FastFoodies", "title": "Fast Foodies", "type": 1, "vars": [445, 444, 446]},
|
{"id": 136, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
|
||||||
{"id": 139, "swf": "ArtStudioGridDrawing", "title": "Pixel Painting", "type": 1},
|
{"id": 137, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
|
||||||
|
{"id": 138, "swf": "FastFoodies", "title": "Fast Foodies", "type": 1, "vars": [445,444,446], "icon": 5727, "card": 5723},
|
||||||
|
{"id": 139, "swf": "ArtStudioGridDrawing", "title": "Pixel Painting", "type": 1, "card": 5958},
|
||||||
{"id": 140, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 140, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
{"id": 141, "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": 142, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
@@ -103,16 +139,11 @@
|
|||||||
{"id": 148, "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": 149, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
{"id": 150, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
{"id": 150, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
|
{"id": 151, "swf": "ArtStudioGridDrawing", "title": "Pixel Painting", "type": 1, "vars": [78,0,0], "card": 5958},
|
||||||
|
{"id": 152, "swf": "ArtStudioPrint", "title": "Coloring", "type": 0},
|
||||||
{"id": 153, "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": 154, "swf": "MicroCrane", "title": "The Claw", "type": 0},
|
||||||
{"id": 155, "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": 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": 158, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 1, "vars": [78,0,0], "card": 1205}
|
||||||
{"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}
|
|
||||||
]
|
]
|
||||||
+419
-35
@@ -1,23 +1,34 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const crypto = require("crypto");
|
const crypto = require("crypto");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const http = require("http");
|
const http = require("http");
|
||||||
const https = require("https");
|
const https = require("https");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
|
const customItems = require("./customitems.js");
|
||||||
|
const itemArt = require("./itemart.js");
|
||||||
|
const emoji = require("./emoji.js");
|
||||||
|
const modlog = require("./modlog.js");
|
||||||
|
const roles = require("./roles.js");
|
||||||
const admin = require("./admin.js");
|
const admin = require("./admin.js");
|
||||||
const bans = require("./bans.js");
|
const bans = require("./bans.js");
|
||||||
const captcha = require("./captcha.js");
|
const captcha = require("./captcha.js");
|
||||||
const cdn = require("./cdn.js");
|
const cdn = require("./cdn.js");
|
||||||
const config = require("../config.js");
|
const config = require("../config.js");
|
||||||
|
const devices = require("./devices.js");
|
||||||
const defpacks = require("./defpacks.js");
|
const defpacks = require("./defpacks.js");
|
||||||
const limits = require("./limits.js");
|
const limits = require("./limits.js");
|
||||||
const manage = require("./manage.js");
|
const manage = require("./manage.js");
|
||||||
const modpanel = require("./modpanel.js");
|
const modpanel = require("./modpanel.js");
|
||||||
|
const discordBot = require("./discordbot.js");
|
||||||
const badges = require("./badges.js");
|
const badges = require("./badges.js");
|
||||||
const extraMusic = require("./extramusic.js");
|
const extraMusic = require("./extramusic.js");
|
||||||
|
const customMusic = require("./custommusic.js");
|
||||||
|
const itemControl = require("./itemcontrol.js");
|
||||||
const masterpieces = require("./masterpieces.js");
|
const masterpieces = require("./masterpieces.js");
|
||||||
|
const themeRooms = require("./themerooms.js");
|
||||||
const panel = require("./panel.js");
|
const panel = require("./panel.js");
|
||||||
const totp = require("./totp.js");
|
const totp = require("./totp.js");
|
||||||
const world = require("./world.js");
|
const world = require("./world.js");
|
||||||
@@ -43,6 +54,19 @@ const MIME = {
|
|||||||
".otf": "font/otf",
|
".otf": "font/otf",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// The desktop webview caches the SWF aggressively. Include the local SWF's
|
||||||
|
// timestamp in its URL so a freshly built client is actually picked up after
|
||||||
|
// the server restarts, without making an operator remember to bump a config
|
||||||
|
// value by hand.
|
||||||
|
const clientRevision = () => {
|
||||||
|
try {
|
||||||
|
return Math.floor(fs.statSync(config.clientSwf).mtimeMs).toString(36);
|
||||||
|
}
|
||||||
|
catch (_) {
|
||||||
|
return "unknown";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const flashVars = () => ({
|
const flashVars = () => ({
|
||||||
content: config.baseUrl,
|
content: config.baseUrl,
|
||||||
// the game's own server to the SWF, whatever its name: it loads the card
|
// the game's own server to the SWF, whatever its name: it loads the card
|
||||||
@@ -62,10 +86,14 @@ const flashVars = () => ({
|
|||||||
// member or not may be chosen on any server (lib/accounts.js)
|
// member or not may be chosen on any server (lib/accounts.js)
|
||||||
membershipChoice: true,
|
membershipChoice: true,
|
||||||
smoke_version: config.deployVersion,
|
smoke_version: config.deployVersion,
|
||||||
clientURL: `${config.baseUrl}${config.deployVersion}/ajclient.swf?v=${config.buildVersion}`,
|
clientURL: `${config.baseUrl}${config.deployVersion}/ajclient.swf?v=${config.buildVersion}-${clientRevision()}`,
|
||||||
startupRoom: config.startupRoom,
|
startupRoom: config.startupRoom,
|
||||||
// "-1" turns the client's stats socket off.
|
// "-1" turns the client's stats socket off.
|
||||||
sbStatTrackerIp: "-1",
|
sbStatTrackerIp: "-1",
|
||||||
|
// the client's Discord rich presence (its app/discord.js): the Discord
|
||||||
|
// application it shows as, "" for none, and where its button goes.
|
||||||
|
discordAppId: config.discord.clientId,
|
||||||
|
presenceUrl: `${config.siteUrl}download`,
|
||||||
sbStatModulator: "0",
|
sbStatModulator: "0",
|
||||||
currentTimestamp: Math.floor(Date.now() / 1000),
|
currentTimestamp: Math.floor(Date.now() / 1000),
|
||||||
country: "US",
|
country: "US",
|
||||||
@@ -138,6 +166,161 @@ const formParts = (contentType, body) => {
|
|||||||
return parts;
|
return parts;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// a custom item's picture set or taken away (?kind=&id=[&remove=1], the
|
||||||
|
// picture as the body): by its maker, or by staff who make items. who asks
|
||||||
|
// is the holder of a game's token (/api/itemart?token=, the client's Item
|
||||||
|
// Maker), or `signedIn` (req) -> account: the account page's or the
|
||||||
|
// moderator panel's session, whose cookies only go to their own paths
|
||||||
|
// (/account/api/itemart, /mod/api/itemart), from this server's own pages.
|
||||||
|
// every answer is 200, with {ok} or {error}: the game's Flash cannot read
|
||||||
|
// the body of any other.
|
||||||
|
// `adminSignedIn` (req) -> boolean: the admin panel's session, which acts as
|
||||||
|
// staff who make items, and is written down as "admin".
|
||||||
|
const itemArtUpload = async (req, res, url, from, signedIn = null, adminSignedIn = null) => {
|
||||||
|
if ((req.method === "GET" || req.method === "HEAD") && (signedIn || adminSignedIn)) {
|
||||||
|
itemArtView(req, res, url, signedIn, adminSignedIn);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (req.method !== "POST" || !limits.originAllowed(req)) {
|
||||||
|
send(res, 200, {error: "forbidden"});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const token = url.searchParams.get("token");
|
||||||
|
const holder = token ? accounts.byToken(token) : null;
|
||||||
|
const asAdmin = Boolean(adminSignedIn && adminSignedIn(req));
|
||||||
|
const account = asAdmin ? null : signedIn ? signedIn(req) : holder && world.moderation.banRemaining(holder) === 0 ? holder : null;
|
||||||
|
if (!account && !asAdmin) {
|
||||||
|
send(res, 200, {error: "Sign in first."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const kind = url.searchParams.get("kind");
|
||||||
|
const entry = customItems.get(kind, url.searchParams.get("id"));
|
||||||
|
if (!entry) {
|
||||||
|
send(res, 200, {error: "No such custom item."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const staffMay = asAdmin || roles.can(account, "items.create");
|
||||||
|
if (!staffMay && entry.ownerId !== account.id) {
|
||||||
|
send(res, 200, {error: "That is not one of your items."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const playerItems = require("./playeritems.js");
|
||||||
|
const refusal = staffMay || url.searchParams.get("remove") === "1" ? null : playerItems.uploadRefusal(account, from.local);
|
||||||
|
if (refusal) {
|
||||||
|
send(res, 200, refusal);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!from.local && !asAdmin && !artUploads.allow(account.id)) {
|
||||||
|
send(res, 200, {error: "Too many pictures today. Try again tomorrow."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let result;
|
||||||
|
if (url.searchParams.get("remove") === "1") {
|
||||||
|
result = itemArt.remove(kind, entry.id);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const data = await readBody(req, itemArt.MAX_UPLOAD + 1).catch(() => null);
|
||||||
|
// a player's own picture waits for a moderator unless the admin says not;
|
||||||
|
// one turned away before may not come back.
|
||||||
|
const waits = !staffMay && playerItems.pictureWaits();
|
||||||
|
result = data ? await itemArt.set(kind, entry.id, data, waits, staffMay ? null : playerItems.pictureRefused)
|
||||||
|
: {error: `That picture is too big: ${Math.round(itemArt.MAX_UPLOAD / 1024 / 1024)} MB at most.`};
|
||||||
|
}
|
||||||
|
if (result.ok) {
|
||||||
|
const owner = entry.ownerId === null ? null : accounts.byId(entry.ownerId);
|
||||||
|
modlog.record(asAdmin ? "admin" : account.username, url.searchParams.get("remove") === "1" ? "item picture removed" : "item picture set",
|
||||||
|
owner && owner !== account ? owner.username : "", `${kind} ${entry.id} ${entry.name}`);
|
||||||
|
}
|
||||||
|
send(res, 200, result);
|
||||||
|
};
|
||||||
|
|
||||||
|
// music tracks uploaded in the panels (lib/custommusic.js), at
|
||||||
|
// /mod/api/music (staff with "music.upload") and /admin/api/music:
|
||||||
|
// GET: the tracks; GET ?play=<id>: one's file, to listen to;
|
||||||
|
// POST ?name=&cost=&inShop=1, the MP3 as the body: a new track;
|
||||||
|
// POST ?delete=<id>: the track deleted, and taken from every player.
|
||||||
|
// `signedIn` (req) -> account: the moderator panel's session;
|
||||||
|
// `adminSignedIn` (req) -> boolean: the admin panel's, written down as "admin".
|
||||||
|
const musicUploads = limits.limiter(30, 3600000); // tracks an hour, per staff member
|
||||||
|
const musicRoute = async (req, res, url, from, signedIn = null, adminSignedIn = null) => {
|
||||||
|
res.setHeader("Cache-Control", "no-store");
|
||||||
|
const asAdmin = Boolean(adminSignedIn && adminSignedIn(req));
|
||||||
|
const account = asAdmin ? null : signedIn ? signedIn(req) : null;
|
||||||
|
if (!asAdmin && !(account && roles.can(account, "music.upload"))) {
|
||||||
|
send(res, 403, {error: "Your role cannot upload music."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const by = asAdmin ? "admin" : account.username;
|
||||||
|
if (req.method === "GET" || req.method === "HEAD") {
|
||||||
|
if (url.searchParams.has("play")) {
|
||||||
|
const track = customMusic.file(url.searchParams.get("play"));
|
||||||
|
if (!track) {
|
||||||
|
send(res, 404, "Not found", "text/plain");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox");
|
||||||
|
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||||
|
send(res, 200, track.data, "audio/mpeg");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
send(res, 200, {tracks: customMusic.list(), maxBytes: customMusic.MAX_BYTES});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (req.method !== "POST" || !limits.originAllowed(req)) {
|
||||||
|
send(res, 403, {error: "forbidden"});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (url.searchParams.has("delete")) {
|
||||||
|
const entry = customItems.get("den", url.searchParams.get("delete"));
|
||||||
|
if (!entry || !entry.audio) {
|
||||||
|
send(res, 404, {error: "No such uploaded track."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = itemControl.deleteCustom("den", entry.id, world);
|
||||||
|
if (result.ok) {
|
||||||
|
modlog.record(by, "music deleted", "", `den ${entry.id} ${entry.name}`);
|
||||||
|
}
|
||||||
|
send(res, result.ok ? 200 : 400, result);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!asAdmin && !musicUploads.allow(account.id)) {
|
||||||
|
send(res, 429, {error: "Too many uploads. Try again later."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = await readBody(req, customMusic.MAX_BYTES + 1).catch(() => null);
|
||||||
|
if (!data) {
|
||||||
|
send(res, 413, {error: `That file is too big: ${customMusic.MAX_BYTES / 1024 / 1024} MB at most.`});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = customMusic.add(data, {name: url.searchParams.get("name"), cost: url.searchParams.get("cost") || 0,
|
||||||
|
inShop: url.searchParams.get("inShop") === "1"}, by);
|
||||||
|
if (result.error) {
|
||||||
|
send(res, 400, result);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
modlog.record(by, "music uploaded", "", `den ${result.item.id} ${result.item.name}`);
|
||||||
|
send(res, 200, {ok: `"${result.item.name}" is den item ${result.item.id}. Players can get it from the item finder now${result.item.inShop ? ", and the shop" : ""}.`,
|
||||||
|
item: {id: result.item.id, name: result.item.name}});
|
||||||
|
};
|
||||||
|
|
||||||
|
// a picture still waiting for a moderator, which /itemart/ does not serve:
|
||||||
|
// to its maker (the account page) and to staff who review or make items.
|
||||||
|
const itemArtView = (req, res, url, signedIn, adminSignedIn) => {
|
||||||
|
res.setHeader("Cache-Control", "private, no-store");
|
||||||
|
const asAdmin = Boolean(adminSignedIn && adminSignedIn(req));
|
||||||
|
const account = asAdmin ? null : signedIn ? signedIn(req) : null;
|
||||||
|
const entry = customItems.get(url.searchParams.get("kind"), url.searchParams.get("id"));
|
||||||
|
const allowed = entry && (asAdmin || (account && (entry.ownerId === account.id || roles.can(account, "items.approve") || roles.can(account, "items.create"))));
|
||||||
|
const picture = allowed ? itemArt.file(entry.kind, entry.id, true) : null;
|
||||||
|
if (!picture) {
|
||||||
|
send(res, 404, "Not found", "text/plain");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox");
|
||||||
|
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||||
|
send(res, 200, picture.data, `image/${picture.type}`);
|
||||||
|
};
|
||||||
|
|
||||||
const send = (res, status, body, type = "application/json") => {
|
const send = (res, status, body, type = "application/json") => {
|
||||||
const data = Buffer.isBuffer(body) ? body : Buffer.from(typeof body === "string" ? body : JSON.stringify(body));
|
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.writeHead(status, {"Content-Type": type, "Content-Length": data.length});
|
||||||
@@ -155,6 +338,8 @@ const MISSING_ASSET_SECONDS = 600; // how long a client may keep the CDN's "no s
|
|||||||
const cacheMisses = limits.limiter(config.cacheMissesPerTenMinutes, TEN_MINUTES_MS); // files fetched from the official CDN for one address
|
const 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 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 paintingPosts = limits.limiter(60, TEN_MINUTES_MS); // per address; each also needs a token from the game
|
||||||
|
const artUploads = limits.limiter(10, 24 * 3600000); // custom items' pictures, per account a day
|
||||||
|
const emojiFetches = limits.limiter(600, TEN_MINUTES_MS); // emoji pictures not kept yet, asked of the upstream, per address
|
||||||
const PAINTING_PATH = /^\/masterpieces\/([0-9a-f-]{36})$/;
|
const PAINTING_PATH = /^\/masterpieces\/([0-9a-f-]{36})$/;
|
||||||
|
|
||||||
// where clients ask for the HUD artwork; ours is a changed copy.
|
// where clients ask for the HUD artwork; ours is a changed copy.
|
||||||
@@ -194,7 +379,7 @@ const repeatedError = text => {
|
|||||||
const THEMED_ROOM = /^(\d+)\/roomDefs\/theme_(\d+)\/(.+)$/;
|
const THEMED_ROOM = /^(\d+)\/roomDefs\/theme_(\d+)\/(.+)$/;
|
||||||
|
|
||||||
// the web pages, as against what the game and the client load
|
// the web pages, as against what the game and the client load
|
||||||
const SITE_PAGES = /^\/(?:register|terms|privacy|commands|shop|account|mod|download)?\/?$/;
|
const SITE_PAGES = /^\/(?:register|terms|privacy|commands|shop|account|mod|admin|dashboard|download)?\/?$/;
|
||||||
|
|
||||||
// the installers /download offers, those of them config.downloadsDir has
|
// the installers /download offers, those of them config.downloadsDir has
|
||||||
const DOWNLOADS = [
|
const DOWNLOADS = [
|
||||||
@@ -249,6 +434,7 @@ const CAPTCHA_PAGE_HEADERS = {...PAGE_HEADERS, "Content-Security-Policy": captch
|
|||||||
// write, from config.js.
|
// write, from config.js.
|
||||||
const LEGAL_VALUES = {legalEmail: config.legalEmail, adminEmail: config.adminEmail, operator: config.operator, hostedIn: config.hostedIn,
|
const LEGAL_VALUES = {legalEmail: config.legalEmail, adminEmail: config.adminEmail, operator: config.operator, hostedIn: config.hostedIn,
|
||||||
version: config.termsVersion, site: new URL(config.siteUrl).host};
|
version: config.termsVersion, site: new URL(config.siteUrl).host};
|
||||||
|
const MAX_RULES_LENGTH = 65536; // characters of data/rules.txt the game is sent
|
||||||
const escapeHtml = text => String(text).replace(/[&<>"]/g, sign => ({"&": "&", "<": "<", ">": ">", "\"": """})[sign]);
|
const escapeHtml = text => String(text).replace(/[&<>"]/g, sign => ({"&": "&", "<": "<", ">": ">", "\"": """})[sign]);
|
||||||
const sendLegalPage = async (res, file) => {
|
const sendLegalPage = async (res, file) => {
|
||||||
for (const [name, value] of Object.entries(PAGE_HEADERS)) {
|
for (const [name, value] of Object.entries(PAGE_HEADERS)) {
|
||||||
@@ -371,9 +557,10 @@ const renameAndSignIn = (res, body, from) => {
|
|||||||
manage.forget(account);
|
manage.forget(account);
|
||||||
accounts.recordLogin(account, "launcher", from.address);
|
accounts.recordLogin(account, "launcher", from.address);
|
||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
console.log(`[accounts] a rejected username was replaced by "${account.username}"`);
|
console.log(`[accounts] a rejected username was replaced by "${logText(account.username)}"`);
|
||||||
accounts.setLoginChoices(account, body.login_choices);
|
accounts.setLoginChoices(account, body.login_choices);
|
||||||
const token = accounts.issueToken(account);
|
const token = accounts.issueToken(account);
|
||||||
|
devices.noteLauncher(token, Boolean(devices.read(body.device)));
|
||||||
send(res, 200, {auth_token: token, refresh_token: token, device_token: entry.deviceToken});
|
send(res, 200, {auth_token: token, refresh_token: token, device_token: entry.deviceToken});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -383,36 +570,63 @@ const authenticate = async (req, res, from) => {
|
|||||||
renameAndSignIn(res, body, from);
|
renameAndSignIn(res, body, from);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const byRefresh = body.refresh_token !== undefined;
|
// the computer it is on (lib/devices.js): a client that does not say is
|
||||||
|
// out of date (before 1.3.0) or not ours. it is signed in all the same,
|
||||||
|
// and its token noted (signInChecked): with config.requireDevice the game
|
||||||
|
// then loads and its login popup says to update (lib/world.js), where a
|
||||||
|
// refusal here only ever showed "The server refused the login (426)".
|
||||||
|
const device = devices.read(body.device);
|
||||||
const accountKey = String(body.username).trim().toLowerCase();
|
const accountKey = String(body.username).trim().toLowerCase();
|
||||||
if (!from.local && failuresByAddress.blocked(from.key)) {
|
if (!from.local && failuresByAddress.blocked(from.key)) {
|
||||||
send(res, 429, {error_code: 429, error: "too_many_attempts"});
|
send(res, 429, {error_code: 429, error: "too_many_attempts"});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// A saved sign-in ("remember me"): the account its token is good for,
|
||||||
|
// which is what the rest goes by. a token is only ever given after a
|
||||||
|
// whole sign-in (password, captcha and 2FA code), so one that is good
|
||||||
|
// stands in for them; one that is not is refused here, whatever else
|
||||||
|
// the request says. (Whether the request offers a token is not what
|
||||||
|
// decides: only the server's own answer for it.)
|
||||||
|
const saved = accounts.byToken(body.refresh_token); // null for none, or for one that is not good
|
||||||
|
if (saved) {
|
||||||
|
await signInChecked(res, body, from, saved, true, device);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (body.refresh_token !== undefined) {
|
||||||
|
failuresByAddress.record(from.key);
|
||||||
|
// error_code 100 = expired refresh token
|
||||||
|
send(res, 401, {error_code: 100});
|
||||||
|
return;
|
||||||
|
}
|
||||||
// a password is not looked at before the captcha. the custom client
|
// a password is not looked at before the captcha. the custom client
|
||||||
// knows these errors; the official launcher shows them as a wrong password.
|
// knows these errors; the official launcher shows them as a wrong password.
|
||||||
const captchaProblem = byRefresh ? null : await captcha.check(body, from, "login", accounts.byName(accountKey));
|
const captchaProblem = await captcha.check(body, from, "login", accounts.byName(accountKey));
|
||||||
if (captchaProblem) {
|
if (captchaProblem) {
|
||||||
send(res, captchaProblem === "captcha_unavailable" ? 503 : 401, {error_code: 101, error: captchaProblem});
|
send(res, captchaProblem === "captcha_unavailable" ? 503 : 401, {error_code: 101, error: captchaProblem});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const account = byRefresh
|
const account = await accounts.authenticateAsync(body.username, body.password);
|
||||||
? accounts.byToken(body.refresh_token)
|
|
||||||
: await accounts.authenticateAsync(body.username, body.password);
|
|
||||||
if (!account) {
|
if (!account) {
|
||||||
failuresByAddress.record(from.key);
|
failuresByAddress.record(from.key);
|
||||||
if (!byRefresh) {
|
// A wrong password shows in the account's own login history.
|
||||||
// A wrong password shows in the account's own login history.
|
const tried = accounts.byName(accountKey);
|
||||||
const tried = accounts.byName(accountKey);
|
if (tried) {
|
||||||
if (tried) {
|
accounts.recordLogin(tried, "launcher", from.address, false);
|
||||||
accounts.recordLogin(tried, "launcher", from.address, false);
|
accounts.save(tried);
|
||||||
accounts.save(tried);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
// error_code 100 = expired refresh token, 101 = wrong credentials
|
// error_code 101 = wrong credentials
|
||||||
send(res, 401, {error_code: byRefresh ? 100 : 101});
|
send(res, 401, {error_code: 101});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
await signInChecked(res, body, from, account, false, device);
|
||||||
|
};
|
||||||
|
|
||||||
|
// the rest of a sign-in, for an account whose password was right (`saved`
|
||||||
|
// false) or whose saved sign-in's token was good (`saved` true; then it is
|
||||||
|
// not asked for a 2FA code again, and the token it has is the one it keeps).
|
||||||
|
// `device`: the computer it is on (lib/devices.js), or null for a client that does not say.
|
||||||
|
const signInChecked = async (res, body, from, account, saved, device) => {
|
||||||
|
const byRefresh = saved === true;
|
||||||
// banned: said here, with how long is left (-1 for good), where a client
|
// 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
|
// 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
|
// the one line it has for that, which says neither. the password (or the
|
||||||
@@ -430,6 +644,15 @@ const authenticate = async (req, res, from) => {
|
|||||||
send(res, 401, {error_code: 101, error: "address_banned", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason});
|
send(res, 401, {error_code: 101, error: "address_banned", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// A banned computer (lib/devices.js): for good, whichever account. a
|
||||||
|
// client that sent no ids (before 1.3.0) is judged by the hardware the
|
||||||
|
// account was seen on.
|
||||||
|
const deviceBan = device ? devices.banOf(device) : devices.banOfAccount(account);
|
||||||
|
if (deviceBan) {
|
||||||
|
console.log(`[devices] "${logText(account.username)}" refused: hardware banned (ban ${logText(deviceBan.id)})`);
|
||||||
|
send(res, 401, {error_code: 101, error: "device_banned", banned_seconds: world.moderation.PERMANENT, ban_reason: deviceBan.reason});
|
||||||
|
return;
|
||||||
|
}
|
||||||
// locked by its owner on the account page: the password is right, and
|
// 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.
|
// still nobody gets in. the launcher shows this as a failed sign-in.
|
||||||
if (account.locked) {
|
if (account.locked) {
|
||||||
@@ -466,13 +689,17 @@ const authenticate = async (req, res, from) => {
|
|||||||
send(res, 401, {error_code: 101, error: "name_rejected", rename_ticket: renameTicket(account, deviceToken)});
|
send(res, 401, {error_code: 101, error: "name_rejected", rename_ticket: renameTicket(account, deviceToken)});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (device) {
|
||||||
|
devices.seen(account, device, other => world.moderation.banRemaining(other) !== 0);
|
||||||
|
}
|
||||||
if (!byRefresh) {
|
if (!byRefresh) {
|
||||||
accounts.recordLogin(account, "launcher", from.address);
|
accounts.recordLogin(account, "launcher", from.address);
|
||||||
accounts.save(account);
|
|
||||||
}
|
}
|
||||||
|
accounts.save(account);
|
||||||
// the custom client's advanced settings; the official launcher sends none.
|
// the custom client's advanced settings; the official launcher sends none.
|
||||||
accounts.setLoginChoices(account, body.login_choices);
|
accounts.setLoginChoices(account, body.login_choices);
|
||||||
const token = byRefresh ? body.refresh_token : accounts.issueToken(account);
|
const token = byRefresh ? body.refresh_token : accounts.issueToken(account);
|
||||||
|
devices.noteLauncher(token, Boolean(device));
|
||||||
send(res, 200, {auth_token: token, refresh_token: token, device_token: deviceToken});
|
send(res, 200, {auth_token: token, refresh_token: token, device_token: deviceToken});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -493,6 +720,10 @@ const player = (req, res) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handle = async (req, res) => {
|
const handle = async (req, res) => {
|
||||||
|
// over https, browsers are told to keep to it (a year)
|
||||||
|
if (config.secureCookies) {
|
||||||
|
res.setHeader("Strict-Transport-Security", "max-age=31536000");
|
||||||
|
}
|
||||||
const url = new URL(req.url, config.baseUrl);
|
const url = new URL(req.url, config.baseUrl);
|
||||||
const route = `${req.method} ${url.pathname}`;
|
const route = `${req.method} ${url.pathname}`;
|
||||||
|
|
||||||
@@ -508,22 +739,60 @@ const handle = async (req, res) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const isAdmin = url.pathname === "/admin" || url.pathname.startsWith("/admin/");
|
const dashboardAdmin = url.pathname === "/dashboard/admin" || url.pathname.startsWith("/dashboard/admin/")
|
||||||
|
|| url.pathname === "/dashboard/api/admin" || url.pathname.startsWith("/dashboard/api/admin/");
|
||||||
|
const dashboardStaff = url.pathname === "/dashboard/staff" || url.pathname.startsWith("/dashboard/staff/")
|
||||||
|
|| url.pathname === "/dashboard/api/staff" || url.pathname.startsWith("/dashboard/api/staff/");
|
||||||
|
const isDashboard = url.pathname === "/dashboard" || dashboardAdmin || dashboardStaff;
|
||||||
|
const isAdmin = url.pathname === "/admin" || url.pathname.startsWith("/admin/") || dashboardAdmin;
|
||||||
const isAccount = url.pathname === "/account" || url.pathname.startsWith("/account/");
|
const isAccount = url.pathname === "/account" || url.pathname.startsWith("/account/");
|
||||||
const isMod = url.pathname === "/mod" || url.pathname.startsWith("/mod/");
|
const isMod = url.pathname === "/mod" || url.pathname.startsWith("/mod/") || dashboardStaff;
|
||||||
|
|
||||||
// the pages that keep a cookie answer only under this server's own names:
|
// the pages that keep a cookie answer only under this server's own names:
|
||||||
// a request sent here by a page of another name (one whose name was made
|
// a request sent here by a page of another name (one whose name was made
|
||||||
// to point at this machine, say) is not theirs to make. nor is such a
|
// to point at this machine, say) is not theirs to make. nor is such a
|
||||||
// request ever this machine's own, wherever it came from.
|
// request ever this machine's own, wherever it came from.
|
||||||
if (!limits.hostAllowed(req)) {
|
if (!limits.hostAllowed(req)) {
|
||||||
if (isAdmin || isAccount || isMod) {
|
if (isDashboard || isAdmin || isAccount || isMod) {
|
||||||
send(res, 421, {error: "wrong_host"});
|
send(res, 421, {error: "wrong_host"});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
from.local = false;
|
from.local = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GitHub sends signed push events here for optional Discord update cards.
|
||||||
|
if (url.pathname === "/discord/github") {
|
||||||
|
await discordBot.handleGithubWebhook(req, res);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// One entry point for the owner and staff dashboards. The old addresses
|
||||||
|
// stay as bookmark-friendly redirects; their APIs remain available for
|
||||||
|
// installed tools and are not redirected.
|
||||||
|
if (req.method === "GET" && url.pathname === "/dashboard/") {
|
||||||
|
res.writeHead(302, {Location: `/dashboard${url.search}`, "Content-Length": 0});
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (req.method === "GET" && url.pathname === "/dashboard") {
|
||||||
|
res.setHeader("Cache-Control", "no-store");
|
||||||
|
res.setHeader("X-Frame-Options", "DENY");
|
||||||
|
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||||
|
res.setHeader("Referrer-Policy", "no-referrer");
|
||||||
|
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "dashboard.html")), "text/html; charset=utf-8");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (req.method === "GET" && url.pathname === "/admin") {
|
||||||
|
res.writeHead(302, {Location: "/dashboard/admin", "Content-Length": 0});
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (req.method === "GET" && url.pathname === "/mod") {
|
||||||
|
res.writeHead(302, {Location: "/dashboard/staff", "Content-Length": 0});
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// the admin panel sets its own, stricter headers: none of the cross-origin
|
// the admin panel sets its own, stricter headers: none of the cross-origin
|
||||||
// allowances below apply to it. on a public server it is not there at all
|
// allowances below apply to it. on a public server it is not there at all
|
||||||
// for anyone but this machine and the addresses named (config.adminAllow).
|
// for anyone but this machine and the addresses named (config.adminAllow).
|
||||||
@@ -532,10 +801,29 @@ const handle = async (req, res) => {
|
|||||||
send(res, 404, "Not found", "text/plain");
|
send(res, 404, "Not found", "text/plain");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (dashboardAdmin) {
|
||||||
|
url.pathname = url.pathname.startsWith("/dashboard/api/admin")
|
||||||
|
? url.pathname.replace("/dashboard/api/admin", "/admin/api")
|
||||||
|
: url.pathname.replace("/dashboard/admin", "/admin");
|
||||||
|
}
|
||||||
|
if (url.pathname === "/admin/api/itemart") {
|
||||||
|
res.setHeader("Cache-Control", "no-store");
|
||||||
|
await itemArtUpload(req, res, url, from, null, panel.signedIn);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (url.pathname === "/admin/api/music") {
|
||||||
|
await musicRoute(req, res, url, from, null, panel.signedIn);
|
||||||
|
return;
|
||||||
|
}
|
||||||
await panel.handle(req, res, url, from, {send, readJson});
|
await panel.handle(req, res, url, from, {send, readJson});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (isAccount && url.pathname === "/account/api/itemart") {
|
||||||
|
res.setHeader("Cache-Control", "no-store");
|
||||||
|
await itemArtUpload(req, res, url, from, manage.signedInAs);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (isAccount) {
|
if (isAccount) {
|
||||||
await manage.handle(req, res, url, from, {send, readJson});
|
await manage.handle(req, res, url, from, {send, readJson});
|
||||||
return;
|
return;
|
||||||
@@ -543,6 +831,20 @@ const handle = async (req, res) => {
|
|||||||
|
|
||||||
// and the moderator panel (lib/modpanel.js), which is there for anyone to
|
// and the moderator panel (lib/modpanel.js), which is there for anyone to
|
||||||
// reach: its moderators are players, wherever they are.
|
// reach: its moderators are players, wherever they are.
|
||||||
|
if (dashboardStaff) {
|
||||||
|
url.pathname = url.pathname.startsWith("/dashboard/api/staff")
|
||||||
|
? url.pathname.replace("/dashboard/api/staff", "/mod/api")
|
||||||
|
: url.pathname.replace("/dashboard/staff", "/mod");
|
||||||
|
}
|
||||||
|
if (isMod && url.pathname === "/mod/api/itemart") {
|
||||||
|
res.setHeader("Cache-Control", "no-store");
|
||||||
|
await itemArtUpload(req, res, url, from, modpanel.signedInAs);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (isMod && url.pathname === "/mod/api/music") {
|
||||||
|
await musicRoute(req, res, url, from, modpanel.signedInAs);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (isMod) {
|
if (isMod) {
|
||||||
await modpanel.handle(req, res, url, from, {send, readJson});
|
await modpanel.handle(req, res, url, from, {send, readJson});
|
||||||
return;
|
return;
|
||||||
@@ -568,6 +870,39 @@ const handle = async (req, res) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// custom items' own pictures (lib/itemart.js): served as the picture
|
||||||
|
// they are and nothing else.
|
||||||
|
const artPath = /^\/itemart\/(clothing|den)\/(\d{1,9})\.png$/.exec(url.pathname);
|
||||||
|
if (artPath && (req.method === "GET" || req.method === "HEAD")) {
|
||||||
|
const picture = itemArt.file(artPath[1], artPath[2]);
|
||||||
|
if (!picture) {
|
||||||
|
send(res, 404, "Not found", "text/plain");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
||||||
|
res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox");
|
||||||
|
res.setHeader("Content-Disposition", "inline");
|
||||||
|
send(res, 200, picture.data, `image/${picture.type}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// emoji pictures for chat bubbles (lib/emoji.js)
|
||||||
|
const emojiPath = /^\/emoji\/([0-9a-f-]{2,80})\.png$/.exec(url.pathname);
|
||||||
|
if (emojiPath && (req.method === "GET" || req.method === "HEAD")) {
|
||||||
|
const picture = await emoji.get(emojiPath[1], () => from.local || emojiFetches.allow(from.key));
|
||||||
|
if (!picture) {
|
||||||
|
send(res, 404, "Not found", "text/plain");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
||||||
|
res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox");
|
||||||
|
send(res, 200, picture, "image/png");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (url.pathname === "/api/itemart") {
|
||||||
|
await itemArtUpload(req, res, url, from);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (url.pathname.startsWith("/api/")) {
|
if (url.pathname.startsWith("/api/")) {
|
||||||
// the item finder's API changes accounts, so other sites open in a
|
// the item finder's API changes accounts, so other sites open in a
|
||||||
// browser on this machine must not be able to call it.
|
// browser on this machine must not be able to call it.
|
||||||
@@ -674,6 +1009,10 @@ const handle = async (req, res) => {
|
|||||||
res.setHeader("Cache-Control", "public, max-age=86400");
|
res.setHeader("Cache-Control", "public, max-age=86400");
|
||||||
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "ban-icon.png")), MIME[".png"]);
|
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "ban-icon.png")), MIME[".png"]);
|
||||||
return;
|
return;
|
||||||
|
case "GET /burrow-status-banner.png": // public banner used by the Discord status card
|
||||||
|
res.setHeader("Cache-Control", "public, max-age=86400");
|
||||||
|
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "burrow-status-banner.png")), MIME[".png"]);
|
||||||
|
return;
|
||||||
case "GET /bio-icon.png": // the button of the card's Bio tab
|
case "GET /bio-icon.png": // the button of the card's Bio tab
|
||||||
res.setHeader("Cache-Control", "public, max-age=86400");
|
res.setHeader("Cache-Control", "public, max-age=86400");
|
||||||
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "bio-icon.png")), MIME[".png"]);
|
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "bio-icon.png")), MIME[".png"]);
|
||||||
@@ -711,7 +1050,7 @@ const handle = async (req, res) => {
|
|||||||
if (trace ? config.logPackets : from.local || errorReports.allow(from.key)) {
|
if (trace ? config.logPackets : from.local || errorReports.allow(from.key)) {
|
||||||
const again = trace ? "" : repeatedError(`${section} ${message}`);
|
const again = trace ? "" : repeatedError(`${section} ${message}`);
|
||||||
if (again !== null) {
|
if (again !== null) {
|
||||||
console.log(`[${trace ? "client-trace" : "client-error"}] (${section}) ${message}${again}`);
|
console.log(`[${logText(trace ? "client-trace" : "client-error")}] (${logText(section)}) ${logText(message)}${logText(again)}`);
|
||||||
if (!trace) {
|
if (!trace) {
|
||||||
keepClientError(`${new Date().toISOString()} (${section}) ${message}${again}\n`);
|
keepClientError(`${new Date().toISOString()} (${section}) ${message}${again}\n`);
|
||||||
}
|
}
|
||||||
@@ -734,29 +1073,56 @@ const handle = async (req, res) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const parts = formParts(req.headers["content-type"], await readBody(req, masterpieces.MAX_IMAGE_BYTES + 16 * 1024));
|
const parts = formParts(req.headers["content-type"], await readBody(req, masterpieces.MAX_IMAGE_BYTES + 16 * 1024));
|
||||||
const uuid = masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image"));
|
const {uuid, refusal, maker} = await masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image"));
|
||||||
|
// the game only says it could not be sent: HQ says why
|
||||||
|
if (refusal && maker) {
|
||||||
|
world.tellAccount(maker, refusal);
|
||||||
|
}
|
||||||
send(res, 200, uuid ? {success: true, uuid} : {success: false});
|
send(res, 200, uuid ? {success: true, uuid} : {success: false});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
case "GET /crossdomain.xml":
|
case "GET /crossdomain.xml":
|
||||||
send(res, 200, CROSS_DOMAIN, "text/xml");
|
send(res, 200, CROSS_DOMAIN, "text/xml");
|
||||||
return;
|
return;
|
||||||
|
// the game's rules window (AJClient.showRules) shows this file, read
|
||||||
|
// again on every ask so it can be changed on a running server; made
|
||||||
|
// with a placeholder when there is none.
|
||||||
|
case "GET /rules.txt": {
|
||||||
|
const file = path.join(config.dataDir, "rules.txt");
|
||||||
|
let text;
|
||||||
|
try {
|
||||||
|
text = await fs.promises.readFile(file, "utf8");
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
if (err.code !== "ENOENT") {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
text = "Example\n";
|
||||||
|
await fs.promises.writeFile(file, text, {flag: "wx"}).catch(() => {});
|
||||||
|
}
|
||||||
|
res.setHeader("Cache-Control", "no-cache");
|
||||||
|
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||||
|
send(res, 200, text.slice(0, MAX_RULES_LENGTH), "text/plain; charset=utf-8");
|
||||||
|
return;
|
||||||
|
}
|
||||||
case "GET /gameClient/game/index.html":
|
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.
|
// 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("X-Frame-Options", "DENY");
|
||||||
res.setHeader("Referrer-Policy", "no-referrer");
|
res.setHeader("Referrer-Policy", "no-referrer");
|
||||||
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "game.html")), MIME[".html"]);
|
// the admin's switch for the theatre browser (lib/panel.js), for the page to read
|
||||||
|
send(res, 200, String(await fs.promises.readFile(path.join(config.publicDir, "game.html")))
|
||||||
|
.replace("<html>", panel.theatreBrowserOn() ? '<html data-theatre-browser="on">' : "<html>"), MIME[".html"]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (req.method !== "GET" && req.method !== "HEAD") {
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
||||||
console.log(`[http] unhandled ${route}`);
|
console.log(`[http] unhandled ${logText(route)}`);
|
||||||
send(res, 404, {error: "not_found"});
|
send(res, 404, {error: "not_found"});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (config.logPackets) {
|
if (config.logPackets) {
|
||||||
console.log(`[http] GET ${url.pathname}`);
|
console.log(`[http] GET ${logText(url.pathname)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// asset SWFs import their fonts from this fixed path next to the game page;
|
// asset SWFs import their fonts from this fixed path next to the game page;
|
||||||
@@ -780,7 +1146,15 @@ const handle = async (req, res) => {
|
|||||||
return session ? limits.key(session.address) : null;
|
return session ? limits.key(session.address) : null;
|
||||||
};
|
};
|
||||||
const picture = masterpieces.mayView(painting[1], from.key, playingFrom) || from.local ? masterpieces.image(painting[1]) : 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");
|
if (picture) {
|
||||||
|
send(res, 200, picture, MIME[".jpg"]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// one that cannot be shown (waiting to be looked at, seen from an
|
||||||
|
// address not its maker's game's, or its file gone) is the Burrow logo:
|
||||||
|
// given nothing, the game waited for it for good, behind its spinner.
|
||||||
|
res.setHeader("Cache-Control", "no-store");
|
||||||
|
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "logo-square.png")), MIME[".png"]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -796,15 +1170,21 @@ const handle = async (req, res) => {
|
|||||||
send(res, body ? 200 : 404, body || "Not found", body ? MIME[".swf"] : "text/plain");
|
send(res, body ? 200 : 404, body || "Not found", body ? MIME[".swf"] : "text/plain");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// the extra den music tracks, which the CDN does not have as files.
|
// the extra den music tracks, which the CDN does not have as files, and
|
||||||
const extra = await extraMusic.asset(relPath);
|
// those uploaded by staff.
|
||||||
|
const extra = await extraMusic.asset(relPath) || await customMusic.asset(relPath);
|
||||||
if (extra) {
|
if (extra) {
|
||||||
send(res, extra.body ? 200 : 404, extra.body || "Not found", extra.body ? extra.type : "text/plain");
|
send(res, extra.body ? 200 : 404, extra.body || "Not found", extra.body ? extra.type : "text/plain");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const clientPack = await defpacks.clientPack(relPath);
|
const clientPack = await defpacks.clientPack(relPath);
|
||||||
if (clientPack) {
|
if (clientPack) {
|
||||||
send(res, 200, clientPack, "application/octet-stream");
|
// what custom items this game has from its packs (customItems.sendAll)
|
||||||
|
const packKind = defpacks.customPackKind(relPath);
|
||||||
|
if (packKind) {
|
||||||
|
customItems.sawPack(from.key, packKind, clientPack.version);
|
||||||
|
}
|
||||||
|
send(res, 200, clientPack.body, "application/octet-stream");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// A room file in a seasonal theme ("<build>/roomDefs/theme_<other
|
// A room file in a seasonal theme ("<build>/roomDefs/theme_<other
|
||||||
@@ -812,8 +1192,11 @@ const handle = async (req, res) => {
|
|||||||
// or from the current one when the room did not exist yet back then.
|
// or from the current one when the room did not exist yet back then.
|
||||||
const themed = THEMED_ROOM.exec(relPath);
|
const themed = THEMED_ROOM.exec(relPath);
|
||||||
const mayFetch = () => from.local || cacheMisses.allow(from.key);
|
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))
|
const currentPath = themed ? `${themed[1]}/roomDefs/${themed[3]}` : relPath;
|
||||||
|| await cdn.get(themed ? `${themed[1]}/roomDefs/${themed[3]}` : relPath, mayFetch);
|
const oldBody = themed && themed[2] !== themed[1] && Object.values(config.themes).some(theme => theme.build === Number(themed[2]))
|
||||||
|
&& await cdn.get(`${themed[2]}/roomDefs/${themed[3]}`, mayFetch);
|
||||||
|
// its shops and other spots as today's room has them (lib/themerooms.js)
|
||||||
|
const body = oldBody ? await themeRooms.fix(relPath, oldBody, () => cdn.get(currentPath, mayFetch)) : await cdn.get(currentPath, mayFetch);
|
||||||
if (!body) {
|
if (!body) {
|
||||||
// one the CDN does not have is asked for again and again (the same few
|
// one the CDN does not have is asked for again and again (the same few
|
||||||
// hundred, by every client that meets them): its client may keep the
|
// hundred, by every client that meets them): its client may keep the
|
||||||
@@ -822,7 +1205,7 @@ const handle = async (req, res) => {
|
|||||||
res.setHeader("Cache-Control", `public, max-age=${MISSING_ASSET_SECONDS}`);
|
res.setHeader("Cache-Control", `public, max-age=${MISSING_ASSET_SECONDS}`);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
console.log(`[http] 404 ${url.pathname}`);
|
console.log(`[http] 404 ${logText(url.pathname)}`);
|
||||||
}
|
}
|
||||||
send(res, 404, "Not found", "text/plain");
|
send(res, 404, "Not found", "text/plain");
|
||||||
return;
|
return;
|
||||||
@@ -834,7 +1217,8 @@ const handle = async (req, res) => {
|
|||||||
const start = () => new Promise((resolve, reject) => {
|
const start = () => new Promise((resolve, reject) => {
|
||||||
const onRequest = (req, res) => {
|
const onRequest = (req, res) => {
|
||||||
handle(req, res).catch(err => {
|
handle(req, res).catch(err => {
|
||||||
console.log(`[http] ${req.method} ${req.url} failed: ${err.message}`);
|
// the path only: a query may hold a login token (the item finder's, the Item Maker's)
|
||||||
|
console.log(`[http] ${logText(req.method)} ${logText(String(req.url).split("?")[0])} failed: ${logText(err.message)}`);
|
||||||
if (!res.headersSent) {
|
if (!res.headersSent) {
|
||||||
send(res, 500, {error: "server_error"});
|
send(res, 500, {error: "server_error"});
|
||||||
}
|
}
|
||||||
@@ -883,7 +1267,7 @@ const start = () => new Promise((resolve, reject) => {
|
|||||||
});
|
});
|
||||||
server.once("error", reject);
|
server.once("error", reject);
|
||||||
server.listen(config.httpPort, config.bindAddress, () => {
|
server.listen(config.httpPort, config.bindAddress, () => {
|
||||||
console.log(`[http] listening on ${config.bindAddress}:${config.httpPort}${config.webTls ? " (TLS)" : ""}`);
|
console.log(`[http] listening on ${logText(config.bindAddress)}:${logText(config.httpPort)}${logText(config.webTls ? " (TLS)" : "")}`);
|
||||||
resolve(server);
|
resolve(server);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const config = require("../config.js");
|
||||||
|
|
||||||
|
// Google Cloud Vision SafeSearch detects adult and racy material. We keep
|
||||||
|
// this dependency-free and use its REST API so deploying the server needs no
|
||||||
|
// service-account files or Google SDK in node_modules.
|
||||||
|
const UNSAFE = new Set(["LIKELY", "VERY_LIKELY"]);
|
||||||
|
const TIMEOUT_MS = 10000;
|
||||||
|
|
||||||
|
// {blocked, error}; `error` deliberately fails closed when the scanner is
|
||||||
|
// enabled: accepting an image while the safety service is unavailable would
|
||||||
|
// make this protection easy to bypass.
|
||||||
|
const scan = async image => {
|
||||||
|
if (!config.googleVision) {
|
||||||
|
return {blocked: false};
|
||||||
|
}
|
||||||
|
if (!Buffer.isBuffer(image) || image.length === 0) {
|
||||||
|
return {blocked: true, error: "That picture could not be checked for safety."};
|
||||||
|
}
|
||||||
|
const abort = new AbortController();
|
||||||
|
const timer = setTimeout(() => abort.abort(), TIMEOUT_MS);
|
||||||
|
try {
|
||||||
|
const response = await fetch(config.googleVision.endpoint, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {"Content-Type": "application/json"},
|
||||||
|
signal: abort.signal,
|
||||||
|
body: JSON.stringify({
|
||||||
|
requests: [{image: {content: image.toString("base64")}, features: [{type: "SAFE_SEARCH_DETECTION"}]}],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const result = await response.json().catch(() => null);
|
||||||
|
const safeSearch = result && result.responses && result.responses[0] && result.responses[0].safeSearchAnnotation;
|
||||||
|
if (!response.ok || !safeSearch) {
|
||||||
|
console.error(`[image-moderation] Google Vision request failed (${response.status})`);
|
||||||
|
return {blocked: true, error: "Picture safety checking is temporarily unavailable. Please try again."};
|
||||||
|
}
|
||||||
|
if (UNSAFE.has(safeSearch.adult) || UNSAFE.has(safeSearch.racy)) {
|
||||||
|
return {blocked: true, error: "That picture was blocked because it may contain nudity or other NSFW content."};
|
||||||
|
}
|
||||||
|
return {blocked: false};
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.error(`[image-moderation] Google Vision request failed: ${err.message}`);
|
||||||
|
return {blocked: true, error: "Picture safety checking is temporarily unavailable. Please try again."};
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {scan};
|
||||||
+403
@@ -0,0 +1,403 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const crypto = require("crypto");
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
const zlib = require("zlib");
|
||||||
|
const config = require("../config.js");
|
||||||
|
const customItems = require("./customitems.js");
|
||||||
|
const imageModeration = require("./image-moderation.js");
|
||||||
|
|
||||||
|
// custom items' own pictures: uploaded by the item's maker (or staff), shown
|
||||||
|
// by the patched client in place of the item's icon, and for a den item in
|
||||||
|
// place of the item standing in a den (AJClient.customArtUrl). worn
|
||||||
|
// clothing keeps the art it was made from: that is drawn for every animal
|
||||||
|
// and pose, which one picture cannot be.
|
||||||
|
//
|
||||||
|
// a picture is checked before it is kept: a PNG, a JPEG or a GIF by its own
|
||||||
|
// bytes (whatever it is called), of a sensible size, and kept without what
|
||||||
|
// else such files carry (a photo's EXIF, with where it was taken; PNG text;
|
||||||
|
// GIF comments). a BMP is made a PNG. (the pages and the game turn other
|
||||||
|
// kinds, and pictures too big, into a PNG before they send them.)
|
||||||
|
// kept as data/itemart/<kind>-<id>.<png|jpg|gif>; its version, a hash, is on
|
||||||
|
// the item (customItems.setArt), so a new picture is a new address.
|
||||||
|
|
||||||
|
const MAX_BYTES = 100 * 1024; // a picture kept: every player who sees the item downloads it
|
||||||
|
const MAX_UPLOAD = 2 * 1024 * 1024; // one sent (a BMP is bigger than the PNG it becomes)
|
||||||
|
const MAX_SIDE = 256; // drawn fitted to the item anyway (a den item's place is 160)
|
||||||
|
const MIN_SIDE = 8;
|
||||||
|
const DIR = path.join(config.dataDir, "itemart");
|
||||||
|
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
|
||||||
|
// the PNG chunks a picture needs; text, times, EXIF and the like are dropped
|
||||||
|
const PNG_KEPT = new Set(["IHDR", "PLTE", "IDAT", "IEND", "tRNS", "gAMA", "cHRM", "sRGB", "iCCP", "sBIT", "pHYs"]);
|
||||||
|
|
||||||
|
const TYPES = ["png", "jpeg", "gif"];
|
||||||
|
const EXTENSION = {png: "png", jpeg: "jpg", gif: "gif"};
|
||||||
|
const VERSION_MARK = {png: "p", jpeg: "j", gif: "g"};
|
||||||
|
|
||||||
|
const fileOf = (kind, id, type) => path.join(DIR, `${kind}-${Number(id)}.${EXTENSION[type]}`);
|
||||||
|
|
||||||
|
// a GIF's blocks, without comments, plain text and any application block but
|
||||||
|
// the one that says it loops; null when it is not a whole GIF. kept animated.
|
||||||
|
const cleanGif = data => {
|
||||||
|
const head = data.toString("latin1", 0, 6);
|
||||||
|
if (data.length < 14 || (head !== "GIF87a" && head !== "GIF89a")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const width = data.readUInt16LE(6);
|
||||||
|
const height = data.readUInt16LE(8);
|
||||||
|
const packed = data[10];
|
||||||
|
let at = 13 + (packed & 0x80 ? 3 * (2 << (packed & 7)) : 0);
|
||||||
|
if (at > data.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const kept = [data.subarray(0, at)];
|
||||||
|
// sub-blocks from `from`: where they end (after the 0 that ends them)
|
||||||
|
const subBlocksEnd = from => {
|
||||||
|
let i = from;
|
||||||
|
while (i < data.length && data[i] !== 0) {
|
||||||
|
i += data[i] + 1;
|
||||||
|
}
|
||||||
|
return i < data.length ? i + 1 : -1;
|
||||||
|
};
|
||||||
|
let images = 0;
|
||||||
|
while (at < data.length) {
|
||||||
|
const block = data[at];
|
||||||
|
if (block === 0x3B) {
|
||||||
|
kept.push(data.subarray(at, at + 1));
|
||||||
|
return images ? {data: Buffer.concat(kept), width, height, type: "gif"} : null;
|
||||||
|
}
|
||||||
|
if (block === 0x2C) {
|
||||||
|
if (at + 10 > data.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const local = data[at + 9];
|
||||||
|
const start = at;
|
||||||
|
at += 10 + (local & 0x80 ? 3 * (2 << (local & 7)) : 0) + 1; // the descriptor, its colours, the LZW code size
|
||||||
|
const end = subBlocksEnd(at);
|
||||||
|
if (end === -1) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
kept.push(data.subarray(start, end));
|
||||||
|
at = end;
|
||||||
|
images++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (block === 0x21 && at + 2 <= data.length) {
|
||||||
|
const label = data[at + 1];
|
||||||
|
const end = subBlocksEnd(at + 2);
|
||||||
|
if (end === -1) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const loops = label === 0xFF && data.toString("latin1", at + 3, at + 14) === "NETSCAPE2.0";
|
||||||
|
if (label === 0xF9 || loops) {
|
||||||
|
kept.push(data.subarray(at, end));
|
||||||
|
}
|
||||||
|
at = end;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// a PNG of RGBA pixels (`pixels`, width * height * 4 bytes, rows top down).
|
||||||
|
const CRC_TABLE = Array.from({length: 256}, (unused, n) => {
|
||||||
|
let c = n;
|
||||||
|
for (let k = 0; k < 8; k++) {
|
||||||
|
c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1;
|
||||||
|
}
|
||||||
|
return c >>> 0;
|
||||||
|
});
|
||||||
|
const crc32 = buffer => {
|
||||||
|
let c = 0xFFFFFFFF;
|
||||||
|
for (const byte of buffer) {
|
||||||
|
c = CRC_TABLE[(c ^ byte) & 0xFF] ^ (c >>> 8);
|
||||||
|
}
|
||||||
|
return (c ^ 0xFFFFFFFF) >>> 0;
|
||||||
|
};
|
||||||
|
const pngChunk = (type, body) => {
|
||||||
|
const length = Buffer.alloc(4);
|
||||||
|
length.writeUInt32BE(body.length);
|
||||||
|
const typed = Buffer.concat([Buffer.from(type, "latin1"), body]);
|
||||||
|
const crc = Buffer.alloc(4);
|
||||||
|
crc.writeUInt32BE(crc32(typed));
|
||||||
|
return Buffer.concat([length, typed, crc]);
|
||||||
|
};
|
||||||
|
const encodePng = (width, height, pixels) => {
|
||||||
|
const header = Buffer.alloc(13);
|
||||||
|
header.writeUInt32BE(width, 0);
|
||||||
|
header.writeUInt32BE(height, 4);
|
||||||
|
header[8] = 8; // bits a channel
|
||||||
|
header[9] = 6; // RGBA
|
||||||
|
const rows = Buffer.alloc((width * 4 + 1) * height);
|
||||||
|
for (let y = 0; y < height; y++) {
|
||||||
|
pixels.copy(rows, y * (width * 4 + 1) + 1, y * width * 4, (y + 1) * width * 4);
|
||||||
|
}
|
||||||
|
return Buffer.concat([PNG_SIGNATURE, pngChunk("IHDR", header), pngChunk("IDAT", zlib.deflateSync(rows)), pngChunk("IEND", Buffer.alloc(0))]);
|
||||||
|
};
|
||||||
|
|
||||||
|
// RGBA pixels shrunk to fit `side` (each new pixel the mean of those it covers).
|
||||||
|
const shrink = (width, height, pixels, side) => {
|
||||||
|
const scale = Math.min(1, side / width, side / height);
|
||||||
|
if (scale === 1) {
|
||||||
|
return {width, height, pixels};
|
||||||
|
}
|
||||||
|
const w = Math.max(1, Math.round(width * scale));
|
||||||
|
const h = Math.max(1, Math.round(height * scale));
|
||||||
|
const out = Buffer.alloc(w * h * 4);
|
||||||
|
for (let y = 0; y < h; y++) {
|
||||||
|
const y0 = Math.floor(y / scale);
|
||||||
|
const y1 = Math.min(height, Math.max(y0 + 1, Math.floor((y + 1) / scale)));
|
||||||
|
for (let x = 0; x < w; x++) {
|
||||||
|
const x0 = Math.floor(x / scale);
|
||||||
|
const x1 = Math.min(width, Math.max(x0 + 1, Math.floor((x + 1) / scale)));
|
||||||
|
const sum = [0, 0, 0, 0];
|
||||||
|
for (let sy = y0; sy < y1; sy++) {
|
||||||
|
for (let sx = x0; sx < x1; sx++) {
|
||||||
|
for (let c = 0; c < 4; c++) {
|
||||||
|
sum[c] += pixels[(sy * width + sx) * 4 + c];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const count = (y1 - y0) * (x1 - x0);
|
||||||
|
for (let c = 0; c < 4; c++) {
|
||||||
|
out[(y * w + x) * 4 + c] = Math.round(sum[c] / count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {width: w, height: h, pixels: out};
|
||||||
|
};
|
||||||
|
|
||||||
|
// a BMP (uncompressed, or bit fields: 1, 4, 8, 24 or 32 bits a pixel) as a
|
||||||
|
// PNG, shrunk to fit; null when it is not one this can read.
|
||||||
|
const MAX_BMP_SIDE = 4096;
|
||||||
|
const bmpToPng = data => {
|
||||||
|
if (data.length < 54 || data.toString("latin1", 0, 2) !== "BM") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const offset = data.readUInt32LE(10);
|
||||||
|
const headerSize = data.readUInt32LE(14);
|
||||||
|
if (headerSize < 40) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const width = data.readInt32LE(18);
|
||||||
|
const rawHeight = data.readInt32LE(22);
|
||||||
|
const height = Math.abs(rawHeight);
|
||||||
|
const bits = data.readUInt16LE(28);
|
||||||
|
const compression = data.readUInt32LE(30);
|
||||||
|
if (width < 1 || height < 1 || width > MAX_BMP_SIDE || height > MAX_BMP_SIDE || ![1, 4, 8, 24, 32].includes(bits) || ![0, 3].includes(compression)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const stride = Math.ceil(width * bits / 32) * 4;
|
||||||
|
if (offset + stride * height > data.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const paletteAt = 14 + headerSize;
|
||||||
|
const pixels = Buffer.alloc(width * height * 4);
|
||||||
|
const hasAlpha = bits === 32 && (headerSize >= 56 || compression === 3);
|
||||||
|
for (let y = 0; y < height; y++) {
|
||||||
|
const row = offset + (rawHeight > 0 ? height - 1 - y : y) * stride;
|
||||||
|
for (let x = 0; x < width; x++) {
|
||||||
|
const o = (y * width + x) * 4;
|
||||||
|
let b;
|
||||||
|
let g;
|
||||||
|
let r;
|
||||||
|
let a = 255;
|
||||||
|
if (bits >= 24) {
|
||||||
|
const p = row + x * (bits / 8);
|
||||||
|
[b, g, r] = [data[p], data[p + 1], data[p + 2]];
|
||||||
|
if (hasAlpha) {
|
||||||
|
a = data[p + 3];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const perByte = 8 / bits;
|
||||||
|
const byte = data[row + Math.floor(x / perByte)];
|
||||||
|
const index = (byte >> ((perByte - 1 - (x % perByte)) * bits)) & ((1 << bits) - 1);
|
||||||
|
const entry = paletteAt + index * 4;
|
||||||
|
if (entry + 3 > data.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
[b, g, r] = [data[entry], data[entry + 1], data[entry + 2]];
|
||||||
|
}
|
||||||
|
pixels[o] = r;
|
||||||
|
pixels[o + 1] = g;
|
||||||
|
pixels[o + 2] = b;
|
||||||
|
pixels[o + 3] = a;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const small = shrink(width, height, pixels, MAX_SIDE);
|
||||||
|
return {data: encodePng(small.width, small.height, small.pixels), width: small.width, height: small.height, type: "png"};
|
||||||
|
};
|
||||||
|
|
||||||
|
// a PNG's chunks, without the ones not kept; null when it is not a whole PNG.
|
||||||
|
const cleanPng = data => {
|
||||||
|
if (data.length < 33 || !data.subarray(0, 8).equals(PNG_SIGNATURE)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const kept = [PNG_SIGNATURE];
|
||||||
|
let at = 8;
|
||||||
|
let width = 0;
|
||||||
|
let height = 0;
|
||||||
|
let ended = false;
|
||||||
|
while (at + 12 <= data.length) {
|
||||||
|
const length = data.readUInt32BE(at);
|
||||||
|
const type = data.toString("latin1", at + 4, at + 8);
|
||||||
|
if (at + 12 + length > data.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (type === "IHDR") {
|
||||||
|
width = data.readUInt32BE(at + 8);
|
||||||
|
height = data.readUInt32BE(at + 12);
|
||||||
|
}
|
||||||
|
if (PNG_KEPT.has(type)) {
|
||||||
|
kept.push(data.subarray(at, at + 12 + length));
|
||||||
|
}
|
||||||
|
at += 12 + length;
|
||||||
|
if (type === "IEND") {
|
||||||
|
ended = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ended && width && height ? {data: Buffer.concat(kept), width, height, type: "png"} : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// a JPEG without its APP1..APP15 (EXIF, XMP, ...) and comment segments;
|
||||||
|
// null when it is not one. its size is read from the frame header.
|
||||||
|
const cleanJpeg = data => {
|
||||||
|
if (data.length < 4 || data[0] !== 0xFF || data[1] !== 0xD8) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const kept = [data.subarray(0, 2)];
|
||||||
|
let at = 2;
|
||||||
|
let width = 0;
|
||||||
|
let height = 0;
|
||||||
|
while (at + 4 <= data.length) {
|
||||||
|
if (data[at] !== 0xFF) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const marker = data[at + 1];
|
||||||
|
if (marker === 0xD9) {
|
||||||
|
kept.push(data.subarray(at, at + 2));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const length = data.readUInt16BE(at + 2);
|
||||||
|
if (length < 2 || at + 2 + length > data.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const segment = data.subarray(at, at + 2 + length);
|
||||||
|
// start of frame (not DHT, JPG or DAC): the size
|
||||||
|
if (marker >= 0xC0 && marker <= 0xCF && ![0xC4, 0xC8, 0xCC].includes(marker)) {
|
||||||
|
height = data.readUInt16BE(at + 5);
|
||||||
|
width = data.readUInt16BE(at + 7);
|
||||||
|
}
|
||||||
|
const dropped = (marker >= 0xE1 && marker <= 0xEF) || marker === 0xFE;
|
||||||
|
if (!dropped) {
|
||||||
|
kept.push(segment);
|
||||||
|
}
|
||||||
|
at += 2 + length;
|
||||||
|
// start of scan: the compressed data runs to the end
|
||||||
|
if (marker === 0xDA) {
|
||||||
|
kept.push(data.subarray(at));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return width && height ? {data: Buffer.concat(kept), width, height, type: "jpeg"} : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// checks and cleans an upload: {data, type} or {error}.
|
||||||
|
const check = data => {
|
||||||
|
if (!Buffer.isBuffer(data) || data.length === 0) {
|
||||||
|
return {error: "Choose a picture first."};
|
||||||
|
}
|
||||||
|
if (data.length > MAX_UPLOAD) {
|
||||||
|
return {error: `That picture is too big: ${Math.round(MAX_UPLOAD / 1024 / 1024)} MB at most.`};
|
||||||
|
}
|
||||||
|
const image = cleanPng(data) || cleanJpeg(data) || cleanGif(data) || bmpToPng(data);
|
||||||
|
if (!image) {
|
||||||
|
return {error: "That is not a PNG, JPEG, GIF or BMP picture."};
|
||||||
|
}
|
||||||
|
if (image.data.length > MAX_BYTES) {
|
||||||
|
return {error: `That picture is too big: ${Math.round(MAX_BYTES / 1024)} KB at most once cleaned. A smaller one, please.`};
|
||||||
|
}
|
||||||
|
if (image.width > MAX_SIDE || image.height > MAX_SIDE || image.width < MIN_SIDE || image.height < MIN_SIDE) {
|
||||||
|
return {error: `A picture from ${MIN_SIDE} to ${MAX_SIDE} pixels on each side, please.`};
|
||||||
|
}
|
||||||
|
return image;
|
||||||
|
};
|
||||||
|
|
||||||
|
const digest = data => crypto.createHash("sha256").update(data).digest("hex");
|
||||||
|
|
||||||
|
// sets an item's picture. resolves to {ok, art} or {error}.
|
||||||
|
// `pending`: it waits for a moderator before anyone is shown it (lib/playeritems.js).
|
||||||
|
// `refused(hash)`: whether a picture of that SHA-256 (once cleaned) was
|
||||||
|
// turned away before, and may not be sent again.
|
||||||
|
const set = async (kind, id, data, pending = false, refused = null) => {
|
||||||
|
const entry = customItems.get(kind, id);
|
||||||
|
if (!entry) {
|
||||||
|
return {error: "No such custom item."};
|
||||||
|
}
|
||||||
|
const image = check(data);
|
||||||
|
if (image.error) {
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
if (refused && refused(digest(image.data))) {
|
||||||
|
return {error: "A moderator turned that picture away before. Choose another one."};
|
||||||
|
}
|
||||||
|
const safety = await imageModeration.scan(image.data);
|
||||||
|
if (safety.blocked) {
|
||||||
|
return {error: safety.error};
|
||||||
|
}
|
||||||
|
fs.mkdirSync(DIR, {recursive: true});
|
||||||
|
for (const type of TYPES) {
|
||||||
|
fs.rmSync(fileOf(kind, entry.id, type), {force: true});
|
||||||
|
}
|
||||||
|
fs.writeFileSync(fileOf(kind, entry.id, image.type), image.data);
|
||||||
|
const art = `${VERSION_MARK[image.type]}${crypto.createHash("sha256").update(image.data).digest("hex").slice(0, 12)}`;
|
||||||
|
customItems.setArt(kind, entry.id, art, pending);
|
||||||
|
return {ok: pending ? `${entry.name}'s new picture is waiting for a moderator to approve it.` : `${entry.name} has a new picture.`, art};
|
||||||
|
};
|
||||||
|
|
||||||
|
// takes an item's picture away (its maker's choice, or staff's).
|
||||||
|
const remove = (kind, id) => {
|
||||||
|
const entry = customItems.get(kind, id);
|
||||||
|
if (!entry || !entry.art) {
|
||||||
|
return {error: "That item has no picture of its own."};
|
||||||
|
}
|
||||||
|
for (const type of TYPES) {
|
||||||
|
fs.rmSync(fileOf(kind, entry.id, type), {force: true});
|
||||||
|
}
|
||||||
|
customItems.setArt(kind, entry.id, null);
|
||||||
|
return {ok: `${entry.name}'s picture was taken away.`};
|
||||||
|
};
|
||||||
|
|
||||||
|
// the picture to serve: {data, type} or null. one waiting for a moderator
|
||||||
|
// only `withPending`: for the maker and the moderators (lib/http.js).
|
||||||
|
const file = (kind, id, withPending = false) => {
|
||||||
|
const entry = customItems.get(kind, id);
|
||||||
|
if (!entry || !entry.art || (entry.artPending && !withPending)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const type = TYPES.find(one => entry.art.startsWith(VERSION_MARK[one])) || "png";
|
||||||
|
try {
|
||||||
|
return {data: fs.readFileSync(fileOf(kind, entry.id, type)), type};
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// the SHA-256 of an item's picture as kept, waiting or not: null for none.
|
||||||
|
const digestOf = (kind, id) => {
|
||||||
|
const picture = file(kind, id, true);
|
||||||
|
return picture ? digest(picture.data) : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// where a page shows an item's picture: the public address once anyone may
|
||||||
|
// see it; while it waits, `base` (the page's own /…/api/itemart, which asks
|
||||||
|
// who it is first).
|
||||||
|
const urlOf = (entry, base) => (!entry.art ? null : entry.artPending
|
||||||
|
? `${base}?kind=${entry.kind}&id=${entry.id}&v=${entry.art}` : `/itemart/${entry.kind}/${entry.id}.png?v=${entry.art}`);
|
||||||
|
|
||||||
|
module.exports = {set, remove, file, check, digestOf, urlOf, MAX_BYTES, MAX_UPLOAD};
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const accounts = require("./accounts.js");
|
||||||
|
const customItems = require("./customitems.js");
|
||||||
|
const defpacks = require("./defpacks.js");
|
||||||
|
const wearRules = require("./wearrules.js");
|
||||||
|
|
||||||
|
// what staff who make items (items.create: admins and developers) may do
|
||||||
|
// about who has them:
|
||||||
|
//
|
||||||
|
// - lock an item out of the item finder (lib/admin.js): players no longer
|
||||||
|
// find it there or take it from it. staff who may lock still do, with the
|
||||||
|
// item marked locked. it stays wherever else it is (a shop, a trade).
|
||||||
|
// - take an item from one player: every one of it they have.
|
||||||
|
// - delete a custom item (lib/customitems.js): out of the game, and out of
|
||||||
|
// every inventory.
|
||||||
|
|
||||||
|
const LOCKS_SETTING = "finderLocks";
|
||||||
|
const KINDS = ["clothing", "den"];
|
||||||
|
|
||||||
|
let locks = null; // Set of "kind:id"
|
||||||
|
|
||||||
|
const key = (kind, id) => `${kind}:${Number(id)}`;
|
||||||
|
|
||||||
|
const lockSet = () => {
|
||||||
|
if (!locks) {
|
||||||
|
let saved = [];
|
||||||
|
try {
|
||||||
|
saved = JSON.parse(accounts.setting(LOCKS_SETTING) || "[]");
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
saved = [];
|
||||||
|
}
|
||||||
|
locks = new Set(Array.isArray(saved) ? saved.map(String) : []);
|
||||||
|
}
|
||||||
|
return locks;
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveLocks = () => accounts.setSetting(LOCKS_SETTING, JSON.stringify([...lockSet()]));
|
||||||
|
|
||||||
|
const defOf = (kind, id) => (kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id));
|
||||||
|
|
||||||
|
const nameOf = (kind, id) => {
|
||||||
|
const def = defOf(kind, id);
|
||||||
|
if (!def) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return kind === "den" ? defpacks.string(def.nameStrId) || def.abbrName || "" : defpacks.string(def.titleStrId);
|
||||||
|
};
|
||||||
|
|
||||||
|
const describe = (kind, id) => `${nameOf(kind, id) || "(no name)"} (${kind === "den" ? "den item" : "clothing"} ${Number(id)})`;
|
||||||
|
|
||||||
|
// checks a kind and id typed by staff: {kind, id} of an item that exists, or {error}.
|
||||||
|
const item = (kind, id) => {
|
||||||
|
const number = Number(id);
|
||||||
|
if (!KINDS.includes(kind)) {
|
||||||
|
return {error: "The kind is clothing or den."};
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(number) || !defOf(kind, number) || (kind === "clothing" && !defpacks.clothingIds().includes(number))) {
|
||||||
|
return {error: `No ${kind === "den" ? "den item" : "clothing"} with the id ${id}.`};
|
||||||
|
}
|
||||||
|
return {kind, id: number};
|
||||||
|
};
|
||||||
|
|
||||||
|
const isLocked = (kind, id) => lockSet().has(key(kind, id));
|
||||||
|
|
||||||
|
// returns {ok} or {error}.
|
||||||
|
const setLocked = (kind, id, locked) => {
|
||||||
|
const found = item(kind, id);
|
||||||
|
if (found.error) {
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
const was = isLocked(found.kind, found.id);
|
||||||
|
if (was === locked) {
|
||||||
|
return {error: `${describe(found.kind, found.id)} is ${locked ? "already" : "not"} locked.`};
|
||||||
|
}
|
||||||
|
lockSet()[locked ? "add" : "delete"](key(found.kind, found.id));
|
||||||
|
saveLocks();
|
||||||
|
return {ok: `${describe(found.kind, found.id)} is ${locked ? "locked out of" : "back in"} the item finder.`};
|
||||||
|
};
|
||||||
|
|
||||||
|
const lockedList = () => [...lockSet()].map(entry => {
|
||||||
|
const [kind, id] = entry.split(":");
|
||||||
|
return {kind, id: Number(id), name: nameOf(kind, id)};
|
||||||
|
});
|
||||||
|
|
||||||
|
// The animals a moderator can select in the dashboard. Avatar types, rather
|
||||||
|
// than a hand-written list of species, keep this correct for packs added in
|
||||||
|
// a later game build.
|
||||||
|
const wearAnimals = () => defpacks.avatarTypes().sort((one, two) => one - two).map(type => {
|
||||||
|
const def = defpacks.avatarDef(type) || {};
|
||||||
|
return {id: Number(type), name: defpacks.string(def.titleStrRef || def.nameStrId) || def.abbrName || `Animal ${type}`};
|
||||||
|
});
|
||||||
|
|
||||||
|
const wearRuleList = () => wearRules.all().flatMap(rule => {
|
||||||
|
const found = item("clothing", rule.id);
|
||||||
|
return found.error ? [] : [{id: found.id, name: nameOf(found.kind, found.id), blockedTypes: rule.blocked}];
|
||||||
|
});
|
||||||
|
|
||||||
|
// Remove a new restriction from every possible display of an item. A clothing
|
||||||
|
// association has an avatar slot; a mannequin keeps the inventory ids in
|
||||||
|
// five den-item slots. Both must be cleaned or a rule can be bypassed by
|
||||||
|
// switching animals or visiting a den.
|
||||||
|
const removeBlockedUses = (account, itemId, blocked) => {
|
||||||
|
const disallowedAvatarSlots = new Set(account.avatars.filter(avatar => blocked.has(Number(avatar.type))).map(avatar => avatar.avInvId));
|
||||||
|
const matchingInventory = new Set(account.items.filter(piece => piece.def === itemId).map(piece => piece.inv));
|
||||||
|
let removed = 0;
|
||||||
|
let clothingChanged = false;
|
||||||
|
let mannequinChanged = false;
|
||||||
|
for (const piece of account.items) {
|
||||||
|
if (piece.def !== itemId || !Array.isArray(piece.on)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const kept = piece.on.filter(avInvId => !disallowedAvatarSlots.has(avInvId));
|
||||||
|
if (kept.length !== piece.on.length) {
|
||||||
|
removed += piece.on.length - kept.length;
|
||||||
|
piece.on = kept;
|
||||||
|
clothingChanged = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const denItem of account.denItems) {
|
||||||
|
const mannequinType = Number((defpacks.denItemDef(denItem.def) || {}).mannequinAvatarDefId);
|
||||||
|
if (!blocked.has(mannequinType) || !denItem.mannequin || !Array.isArray(denItem.mannequin.worn)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const kept = denItem.mannequin.worn.map(inv => (matchingInventory.has(Number(inv)) ? 0 : inv));
|
||||||
|
if (kept.some((inv, index) => inv !== denItem.mannequin.worn[index])) {
|
||||||
|
removed += kept.filter(inv => inv === 0).length - denItem.mannequin.worn.filter(inv => inv === 0).length;
|
||||||
|
denItem.mannequin.worn = kept;
|
||||||
|
mannequinChanged = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {changed: clothingChanged || mannequinChanged, mannequinChanged, removed};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Make a clothing item unavailable to the selected animal types. `world`
|
||||||
|
// refreshes games and den visitors after the persistent state is cleaned.
|
||||||
|
const setWearRule = (id, blockedTypes, world) => {
|
||||||
|
const found = item("clothing", id);
|
||||||
|
if (found.error) {
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
const animals = wearAnimals();
|
||||||
|
const allowed = new Set(animals.map(animal => animal.id));
|
||||||
|
if (!Array.isArray(blockedTypes) || blockedTypes.length > allowed.size || !blockedTypes.every(Number.isInteger)
|
||||||
|
|| blockedTypes.some(type => !allowed.has(type))) {
|
||||||
|
return {error: "Choose only animals from the list."};
|
||||||
|
}
|
||||||
|
const blocked = [...new Set(blockedTypes)].sort((one, two) => one - two);
|
||||||
|
const changedRule = wearRules.setBlockedTypes(found.id, blocked).changed;
|
||||||
|
let accountsChanged = 0;
|
||||||
|
let removed = 0;
|
||||||
|
const blockedSet = new Set(blocked);
|
||||||
|
for (const account of accounts.all()) {
|
||||||
|
const cleaned = removeBlockedUses(account, found.id, blockedSet);
|
||||||
|
if (!cleaned.changed) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
accountsChanged++;
|
||||||
|
removed += cleaned.removed;
|
||||||
|
accounts.save(account);
|
||||||
|
world.wearRulesChanged(account, cleaned.mannequinChanged);
|
||||||
|
}
|
||||||
|
// Packs downloaded after this moment, and games already open, use the
|
||||||
|
// same rule-to-flag transformation. Server checks above remain authority.
|
||||||
|
defpacks.invalidateClientItemPack();
|
||||||
|
customItems.sendClothingDefs([found.id]);
|
||||||
|
const animalNames = blocked.map(type => animals.find(animal => animal.id === type).name);
|
||||||
|
const subject = describe(found.kind, found.id);
|
||||||
|
const suffix = blocked.length ? `cannot be worn by ${animalNames.join(", ")}.` : "can be worn by every animal again.";
|
||||||
|
return {ok: `${subject} ${suffix}${removed ? ` Took it off ${removed} existing use${removed === 1 ? "" : "s"}.` : ""}`,
|
||||||
|
detail: `clothing ${found.id}; blocked types ${blocked.join(",") || "none"}; ${accountsChanged} account${accountsChanged === 1 ? "" : "s"} changed`, changed: changedRule};
|
||||||
|
};
|
||||||
|
|
||||||
|
// every one of an item an account has, out of its inventory (and its trade
|
||||||
|
// list). `world` tells a game playing (lib/world.js itemsTaken). returns how
|
||||||
|
// many went.
|
||||||
|
const takeFromAccount = (account, kind, id, world) => {
|
||||||
|
const number = Number(id);
|
||||||
|
const collection = kind === "den" ? "denItems" : "items";
|
||||||
|
const gone = account[collection].filter(entry => entry.def === number);
|
||||||
|
if (!gone.length) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const invs = new Set(gone.map(entry => entry.inv));
|
||||||
|
account[collection] = account[collection].filter(entry => !invs.has(entry.inv));
|
||||||
|
account.tradeList = account.tradeList.filter(entry => !invs.has(entry.inv));
|
||||||
|
accounts.save();
|
||||||
|
world.itemsTaken(account, kind, [...invs], kind === "clothing" && gone.some(entry => entry.on.length > 0));
|
||||||
|
return gone.length;
|
||||||
|
};
|
||||||
|
|
||||||
|
// from one player, by username. returns {ok, count} or {error}.
|
||||||
|
const take = (username, kind, id, world) => {
|
||||||
|
const account = accounts.byName(username);
|
||||||
|
if (!account) {
|
||||||
|
return {error: `No player called ${username}.`};
|
||||||
|
}
|
||||||
|
// a deleted custom item can be gone from the tables and still be owned:
|
||||||
|
// the id is taken as it is then.
|
||||||
|
const found = item(kind, id);
|
||||||
|
if (found.error && !(KINDS.includes(kind) && Number.isInteger(Number(id)))) {
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
const count = takeFromAccount(account, kind, id, world);
|
||||||
|
return count ? {ok: `Took ${count} of ${describe(kind, id)} from ${account.username}.`, count}
|
||||||
|
: {error: `${account.username} has no ${describe(kind, id)}.`};
|
||||||
|
};
|
||||||
|
|
||||||
|
// a custom item out of the game, and out of everyone's inventory. returns {ok} or {error}.
|
||||||
|
const deleteCustom = (kind, id, world) => {
|
||||||
|
const entry = customItems.get(kind, id);
|
||||||
|
if (!entry) {
|
||||||
|
return {error: "No such custom item."};
|
||||||
|
}
|
||||||
|
let count = 0;
|
||||||
|
for (const account of accounts.all()) {
|
||||||
|
count += takeFromAccount(account, kind, entry.id, world);
|
||||||
|
}
|
||||||
|
if (entry.art) {
|
||||||
|
require("./itemart.js").remove(kind, entry.id);
|
||||||
|
}
|
||||||
|
customItems.remove(kind, entry.id);
|
||||||
|
if (lockSet().delete(key(kind, entry.id))) {
|
||||||
|
saveLocks();
|
||||||
|
}
|
||||||
|
if (kind === "clothing") {
|
||||||
|
wearRules.forget(entry.id);
|
||||||
|
}
|
||||||
|
return {ok: `Deleted ${entry.name} (${kind === "den" ? "den item" : "clothing"} ${entry.id})${count ? `, and took ${count} from players` : ""}.`};
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {isLocked, setLocked, lockedList, wearAnimals, wearRuleList, setWearRule, take, deleteCustom};
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
// pictures of items for the web item giver (public/items.html), from the
|
||||||
|
// game's own files on the CDN:
|
||||||
|
//
|
||||||
|
// - clothing: the icon the game shows in a closet (item.SimpleIcon), a
|
||||||
|
// paletted bitmap the page colours itself as the game does
|
||||||
|
// (LayerBitmap.paintFrame), so any four colours show without asking again.
|
||||||
|
// - den items: their art, a SWF, which public/item-preview.html plays with
|
||||||
|
// Ruffle through public/item-preview.swf (tools/preview-host).
|
||||||
|
//
|
||||||
|
// both are the same for everyone, so no sign-in is asked for them.
|
||||||
|
|
||||||
|
const zlib = require("zlib");
|
||||||
|
const amf3 = require("./amf3.js");
|
||||||
|
const cdn = require("./cdn.js");
|
||||||
|
const customItems = require("./customitems.js");
|
||||||
|
const defpacks = require("./defpacks.js");
|
||||||
|
|
||||||
|
const ICON_AVATAR = 1; // the avatar every closet icon is drawn for (Item.makeSmallIcon)
|
||||||
|
const ICON_LARGE = 25; // SimpleIcon.AN_ICON_L
|
||||||
|
const ICON_SMALL = 26; // SimpleIcon.AN_ICON_S
|
||||||
|
const IMAGE_VERSION = 0x7080900; // what ImageServerURL accepts
|
||||||
|
|
||||||
|
// DenItem.getIconId: which of an item's pictures the den shows, by its sort category.
|
||||||
|
const iconId = sortCat => ([0, 99, 6, 5].includes(sortCat) ? 1 : sortCat === 1 ? 2 : [2, 3, 4].includes(sortCat) ? 3 : sortCat + 1);
|
||||||
|
|
||||||
|
// a custom item is drawn as the game's item it was made from.
|
||||||
|
const baseIdOf = (kind, id) => {
|
||||||
|
const entry = customItems.get(kind, id);
|
||||||
|
return entry ? entry.base : Number(id);
|
||||||
|
};
|
||||||
|
|
||||||
|
// a clothing item's closet icon, large if there is one: {w, h, b} with b the
|
||||||
|
// first frame's run-length bytes, base64 (LayerBitmap.paintFrame reads them).
|
||||||
|
// null when it has none.
|
||||||
|
const clothingIcon = async id => {
|
||||||
|
const def = defpacks.itemDef(id);
|
||||||
|
if (!def || !Number.isInteger(Number(def.layerDefId))) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (const size of [ICON_LARGE, ICON_SMALL]) {
|
||||||
|
const file = await cdn.get(cdn.hashedPath(`imageArrays/${((ICON_AVATAR << 24) | (size << 16) | Number(def.layerDefId)) >>> 0}`));
|
||||||
|
try {
|
||||||
|
const image = file && amf3.decode(zlib.inflateSync(file));
|
||||||
|
const frame = image && image.v === IMAGE_VERSION && Array.isArray(image.f) && image.f[0];
|
||||||
|
if (frame && Buffer.isBuffer(frame.b) && frame.w > 0 && frame.h > 0) {
|
||||||
|
return {w: frame.w, h: frame.h, b: frame.b.toString("base64")};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
// not an icon this can read: the next size, or none.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// a den item's art as the SWF it holds, or null.
|
||||||
|
const denArt = async id => {
|
||||||
|
const def = defpacks.denItemDef(id);
|
||||||
|
const baseId = baseIdOf("den", id);
|
||||||
|
const baseDef = defpacks.denItemDef(baseId);
|
||||||
|
if (!def || !baseDef) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const file = await cdn.get(cdn.hashedPath(`items/${((baseId << 16) | iconId(Number(baseDef.sortCat))) >>> 0}`));
|
||||||
|
try {
|
||||||
|
const wrapped = file && amf3.decode(file);
|
||||||
|
return wrapped && wrapped.ba ? Buffer.from(wrapped.ba) : null;
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {clothingIcon, denArt};
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
const achievements = require("./achievements.js");
|
const achievements = require("./achievements.js");
|
||||||
const defpacks = require("./defpacks.js");
|
const defpacks = require("./defpacks.js");
|
||||||
|
const wearRules = require("./wearrules.js");
|
||||||
const {CURRENCIES, MAX_ITEMS, MAX_WORN, activeAvatar, addClothing, sendClothingAdded, sendClothingRemoved, resolvePurchase} = require("./player.js");
|
const {CURRENCIES, MAX_ITEMS, MAX_WORN, activeAvatar, addClothing, sendClothingAdded, sendClothingRemoved, resolvePurchase} = require("./player.js");
|
||||||
|
|
||||||
// clothing: buying, wearing and recycling (client side: ItemXtCommManager).
|
// clothing: buying, wearing and recycling (client side: ItemXtCommManager).
|
||||||
@@ -18,6 +19,8 @@ const LAYER_EYES = "3";
|
|||||||
const MAX_RECYCLED_AT_ONCE = 500;
|
const MAX_RECYCLED_AT_ONCE = 500;
|
||||||
const MAX_USED_AT_ONCE = 200; // pieces put on or taken off in one message
|
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
|
const RECYCLE_FRACTION = 0.3; // matches recyclePercentage sent at login
|
||||||
|
const CURRENCY_GEMS = 0; // ItemXtCommManager.currencyUpdateResponse's currency type
|
||||||
|
const PHOTO_GEMS = 50; // what the photo booth says a picture costs (string 14789)
|
||||||
|
|
||||||
module.exports = ({others, sendItemList}) => {
|
module.exports = ({others, sendItemList}) => {
|
||||||
// ItemXtCommManager.itemBuyResponse: [status, shopId, newAmount, currencyType]
|
// ItemXtCommManager.itemBuyResponse: [status, shopId, newAmount, currencyType]
|
||||||
@@ -82,6 +85,13 @@ module.exports = ({others, sendItemList}) => {
|
|||||||
}
|
}
|
||||||
const item = account.items.find(candidate => candidate.inv === invIdx);
|
const item = account.items.find(candidate => candidate.inv === invIdx);
|
||||||
if (item) {
|
if (item) {
|
||||||
|
// The client flag only makes the control gray. Never trust it: a
|
||||||
|
// crafted iu packet or a stale client must not bypass a staff rule.
|
||||||
|
// Check before changing `on`, so a refused request cannot take off
|
||||||
|
// an otherwise valid item as a side effect.
|
||||||
|
if (worn && !wearRules.mayWear(item.def, avatar.type)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId);
|
item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId);
|
||||||
// no more than MAX_WORN on one animal: what is over stays off.
|
// 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) {
|
if (worn && account.items.filter(candidate => candidate.on.includes(avatar.avInvId)).length >= MAX_WORN) {
|
||||||
@@ -133,6 +143,43 @@ module.exports = ({others, sendItemList}) => {
|
|||||||
session.sendXt("ce", -1, 1, account.currency[paid]);
|
session.sendXt("ce", -1, 1, account.currency[paid]);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// gui.MuseumDonation: [amount], gems given to the museum's causes. the
|
||||||
|
// reply (currencyDonationResponse) is [1] or [0]; the gems go, and the
|
||||||
|
// account keeps count of what it has given.
|
||||||
|
cd(session, roomId, [amount]) {
|
||||||
|
const {account} = session;
|
||||||
|
const gems = /^\d{1,9}$/.test(String(amount)) ? Number(amount) : 0;
|
||||||
|
if (gems < 1 || (account.currency.gems || 0) < gems) {
|
||||||
|
session.sendXt("cd", -1, 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
account.currency.gems -= gems;
|
||||||
|
account.gemsDonated = (account.gemsDonated || 0) + gems;
|
||||||
|
achievements.currencyChanged(account, "gems", -gems);
|
||||||
|
accounts.save(account);
|
||||||
|
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
|
||||||
|
session.sendXt("cd", -1, 1);
|
||||||
|
},
|
||||||
|
|
||||||
|
// the photo booth's picture (gui.PhotoBooth), PHOTO_GEMS gems. "apc"
|
||||||
|
// asks first: [gems after, or -1 for too few]; "apb", once the player
|
||||||
|
// keeps the picture, pays: [gem total]. neither was answered, and the
|
||||||
|
// booth waited behind its spinner for good.
|
||||||
|
apc(session) {
|
||||||
|
const gems = session.account.currency.gems || 0;
|
||||||
|
session.sendXt("apc", -1, gems >= PHOTO_GEMS ? gems - PHOTO_GEMS : -1);
|
||||||
|
},
|
||||||
|
|
||||||
|
apb(session) {
|
||||||
|
const {account} = session;
|
||||||
|
if ((account.currency.gems || 0) >= PHOTO_GEMS) {
|
||||||
|
account.currency.gems -= PHOTO_GEMS;
|
||||||
|
achievements.currencyChanged(account, "gems", -PHOTO_GEMS);
|
||||||
|
accounts.save(account);
|
||||||
|
}
|
||||||
|
session.sendXt("apb", -1, account.currency.gems || 0);
|
||||||
|
},
|
||||||
|
|
||||||
// ItemXtCommManager.requestItemRecycle: [invIdx, ...]. the reply
|
// ItemXtCommManager.requestItemRecycle: [invIdx, ...]. the reply
|
||||||
// (itemRecycleResponse) is [count, newGemTotal, ...recycledInvIdx], and
|
// (itemRecycleResponse) is [count, newGemTotal, ...recycledInvIdx], and
|
||||||
// the recycling window then waits, behind its spinner, for the item
|
// the recycling window then waits, behind its spinner, for the item
|
||||||
|
|||||||
@@ -0,0 +1,212 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
// a picture's fingerprint, to know a masterpiece again when it comes back
|
||||||
|
// re-encoded (lib/masterpieces.js): the Art Studio paints a saved .ajart
|
||||||
|
// again a little differently, so the JPEG's bytes differ while every 8 by 8
|
||||||
|
// block's average stays within a fraction of a step.
|
||||||
|
//
|
||||||
|
// the fingerprint is the average of each block, per component, read from
|
||||||
|
// the JPEG's DC coefficients alone (no inverse DCT): a baseline JPEG (what
|
||||||
|
// the Art Studio writes) with no subsampling and no restart markers. any
|
||||||
|
// other JPEG has none, and only its exact bytes are known again.
|
||||||
|
//
|
||||||
|
// layout: [width (uint16), height (uint16), components (uint8)], then a byte
|
||||||
|
// per block and component, block by block in rows.
|
||||||
|
|
||||||
|
const HEADER = 5;
|
||||||
|
const SAME_WITHIN = 2; // of 255, per block: a mark of a few pixels moves its block by more
|
||||||
|
const THUMB = 16; // the thumbnail's side, for finding candidates quickly
|
||||||
|
|
||||||
|
// a Huffman table as JPEG decoders keep it: per code length the smallest
|
||||||
|
// and largest code and where its values start.
|
||||||
|
const huffmanTable = (counts, values) => {
|
||||||
|
const minCode = new Int32Array(17);
|
||||||
|
const maxCode = new Int32Array(18).fill(-1);
|
||||||
|
const valPtr = new Int32Array(17);
|
||||||
|
let code = 0;
|
||||||
|
let k = 0;
|
||||||
|
for (let length = 1; length <= 16; length++) {
|
||||||
|
valPtr[length] = k;
|
||||||
|
minCode[length] = code;
|
||||||
|
code += counts[length - 1];
|
||||||
|
k += counts[length - 1];
|
||||||
|
maxCode[length] = counts[length - 1] ? code - 1 : -1;
|
||||||
|
code <<= 1;
|
||||||
|
}
|
||||||
|
maxCode[17] = 0x7FFFFFFF;
|
||||||
|
return {minCode, maxCode, valPtr, values};
|
||||||
|
};
|
||||||
|
|
||||||
|
// the fingerprint of a JPEG, or null.
|
||||||
|
const fingerprint = buf => {
|
||||||
|
try {
|
||||||
|
return read(buf);
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const read = buf => {
|
||||||
|
const tables = {};
|
||||||
|
const quant = {};
|
||||||
|
let frame = null;
|
||||||
|
let scan = null;
|
||||||
|
let at = 2;
|
||||||
|
while (!scan) {
|
||||||
|
if (at + 4 > buf.length || buf[at] !== 0xFF) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const marker = buf[at + 1];
|
||||||
|
const length = buf.readUInt16BE(at + 2);
|
||||||
|
const body = buf.subarray(at + 4, at + 2 + length);
|
||||||
|
if (marker === 0xDB) {
|
||||||
|
for (let p = 0; p + 65 <= body.length; p += 65) {
|
||||||
|
if (body[p] >> 4) {
|
||||||
|
return null; // 16-bit tables: not the Art Studio's
|
||||||
|
}
|
||||||
|
quant[body[p] & 15] = body[p + 1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (marker === 0xC4) {
|
||||||
|
for (let p = 0; p + 17 <= body.length;) {
|
||||||
|
const counts = body.subarray(p + 1, p + 17);
|
||||||
|
const total = counts.reduce((sum, count) => sum + count, 0);
|
||||||
|
tables[(body[p] >> 4 ? "ac" : "dc") + (body[p] & 15)] = huffmanTable(counts, body.subarray(p + 17, p + 17 + total));
|
||||||
|
p += 17 + total;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (marker === 0xC0 || marker === 0xC1) {
|
||||||
|
const comps = body[5];
|
||||||
|
frame = {height: body.readUInt16BE(1), width: body.readUInt16BE(3), comps: []};
|
||||||
|
for (let c = 0; c < comps; c++) {
|
||||||
|
if (body[7 + c * 3] !== 0x11) {
|
||||||
|
return null; // subsampled
|
||||||
|
}
|
||||||
|
frame.comps.push(body[8 + c * 3]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (marker === 0xDD || (marker >= 0xC2 && marker <= 0xCF && marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC)) {
|
||||||
|
return null; // restart markers, progressive, lossless or arithmetic
|
||||||
|
}
|
||||||
|
else if (marker === 0xDA) {
|
||||||
|
scan = [];
|
||||||
|
for (let c = 0; c < body[0]; c++) {
|
||||||
|
scan.push({dc: tables[`dc${body[2 + c * 2] >> 4}`], ac: tables[`ac${body[2 + c * 2] & 15}`]});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
at += 2 + length;
|
||||||
|
}
|
||||||
|
if (!frame || frame.width < 1 || frame.height < 1 || scan.length !== frame.comps.length || scan.length < 1 || scan.length > 3
|
||||||
|
|| scan.some(table => !table.dc || !table.ac) || frame.comps.some(id => quant[id] === undefined)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the entropy-coded data, its 0xFF bytes followed by a stuffed 0x00
|
||||||
|
let pos = at;
|
||||||
|
let bits = 0;
|
||||||
|
let left = 0;
|
||||||
|
const bit = () => {
|
||||||
|
if (left === 0) {
|
||||||
|
if (pos >= buf.length) {
|
||||||
|
throw new Error("ran out");
|
||||||
|
}
|
||||||
|
bits = buf[pos++];
|
||||||
|
if (bits === 0xFF) {
|
||||||
|
if (buf[pos] !== 0) {
|
||||||
|
throw new Error("marker in the data");
|
||||||
|
}
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
left = 8;
|
||||||
|
}
|
||||||
|
left--;
|
||||||
|
return (bits >> left) & 1;
|
||||||
|
};
|
||||||
|
const decode = table => {
|
||||||
|
let code = bit();
|
||||||
|
let length = 1;
|
||||||
|
while (code > table.maxCode[length]) {
|
||||||
|
code = (code << 1) | bit();
|
||||||
|
if (++length > 16) {
|
||||||
|
throw new Error("bad code");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return table.values[table.valPtr[length] + code - table.minCode[length]];
|
||||||
|
};
|
||||||
|
const receive = size => {
|
||||||
|
let value = 0;
|
||||||
|
for (let i = 0; i < size; i++) {
|
||||||
|
value = (value << 1) | bit();
|
||||||
|
}
|
||||||
|
return value < 1 << (size - 1) ? value - (1 << size) + 1 : value;
|
||||||
|
};
|
||||||
|
|
||||||
|
const across = Math.ceil(frame.width / 8);
|
||||||
|
const down = Math.ceil(frame.height / 8);
|
||||||
|
const comps = scan.length;
|
||||||
|
const out = Buffer.alloc(HEADER + across * down * comps);
|
||||||
|
out.writeUInt16BE(frame.width, 0);
|
||||||
|
out.writeUInt16BE(frame.height, 2);
|
||||||
|
out[4] = comps;
|
||||||
|
const predicted = new Int32Array(comps);
|
||||||
|
for (let block = 0; block < across * down; block++) {
|
||||||
|
for (let c = 0; c < comps; c++) {
|
||||||
|
const size = decode(scan[c].dc);
|
||||||
|
predicted[c] += size ? receive(size) : 0;
|
||||||
|
// the DC coefficient is eight times the block's average, less 128
|
||||||
|
const average = Math.round(predicted[c] * quant[frame.comps[c]] / 8 + 128);
|
||||||
|
out[HEADER + block * comps + c] = Math.max(0, Math.min(255, average));
|
||||||
|
for (let k = 1; k < 64;) {
|
||||||
|
const runSize = decode(scan[c].ac);
|
||||||
|
if ((runSize & 15) === 0) {
|
||||||
|
if (runSize >> 4 !== 15) {
|
||||||
|
break; // end of block
|
||||||
|
}
|
||||||
|
k += 16;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
k += runSize >> 4;
|
||||||
|
receive(runSize & 15);
|
||||||
|
k++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
|
// the first component (brightness) in THUMB by THUMB, to find candidates
|
||||||
|
// among many fingerprints before comparing whole ones.
|
||||||
|
const thumbnail = print => {
|
||||||
|
const across = Math.ceil(print.readUInt16BE(0) / 8);
|
||||||
|
const down = Math.ceil(print.readUInt16BE(2) / 8);
|
||||||
|
const comps = print[4];
|
||||||
|
const sums = new Float64Array(THUMB * THUMB);
|
||||||
|
const counts = new Float64Array(THUMB * THUMB);
|
||||||
|
for (let y = 0; y < down; y++) {
|
||||||
|
for (let x = 0; x < across; x++) {
|
||||||
|
const cell = Math.floor(y * THUMB / down) * THUMB + Math.floor(x * THUMB / across);
|
||||||
|
sums[cell] += print[HEADER + (y * across + x) * comps];
|
||||||
|
counts[cell]++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Buffer.from(sums.map((sum, cell) => (counts[cell] ? Math.round(sum / counts[cell]) : 0)));
|
||||||
|
};
|
||||||
|
|
||||||
|
// could these two be the same picture? (thumbnails: a cheap first look)
|
||||||
|
const thumbnailsClose = (one, other) => one.length === other.length && one.every((value, i) => Math.abs(value - other[i]) <= SAME_WITHIN);
|
||||||
|
|
||||||
|
// the same picture: the same size, and no block further apart than a step or two.
|
||||||
|
const samePicture = (one, other) => {
|
||||||
|
if (!one || !other || one.length !== other.length || one.compare(other, 0, HEADER, 0, HEADER) !== 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (let i = HEADER; i < one.length; i++) {
|
||||||
|
if (Math.abs(one[i] - other[i]) > SAME_WITHIN) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {fingerprint, thumbnail, thumbnailsClose, samePicture};
|
||||||
+31
-1
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const net = require("net");
|
||||||
const config = require("../config.js");
|
const config = require("../config.js");
|
||||||
|
|
||||||
// small in-memory rate limits for the parts of the server that strangers can
|
// small in-memory rate limits for the parts of the server that strangers can
|
||||||
@@ -28,6 +29,25 @@ const key = address => {
|
|||||||
|
|
||||||
const isLoopback = address => LOOPBACK.includes(String(address || "").replace(/^::ffff:/i, ""));
|
const isLoopback = address => LOOPBACK.includes(String(address || "").replace(/^::ffff:/i, ""));
|
||||||
|
|
||||||
|
// the addresses Cloudflare's edge connects from, as it publishes them at
|
||||||
|
// https://www.cloudflare.com/ips/ (they seldom change; add any new range here).
|
||||||
|
const CLOUDFLARE = new net.BlockList();
|
||||||
|
for (const range of ["173.245.48.0/20", "103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22", "141.101.64.0/18",
|
||||||
|
"108.162.192.0/18", "190.93.240.0/20", "188.114.96.0/20", "197.234.240.0/22", "198.41.128.0/17", "162.158.0.0/15",
|
||||||
|
"104.16.0.0/13", "104.24.0.0/14", "172.64.0.0/13", "131.0.72.0/22"]) {
|
||||||
|
const [prefix, bits] = range.split("/");
|
||||||
|
CLOUDFLARE.addSubnet(prefix, Number(bits), "ipv4");
|
||||||
|
}
|
||||||
|
for (const range of ["2400:cb00::/32", "2606:4700::/32", "2803:f800::/32", "2405:b500::/32", "2405:8100::/32",
|
||||||
|
"2a06:98c0::/29", "2c0f:f248::/32"]) {
|
||||||
|
const [prefix, bits] = range.split("/");
|
||||||
|
CLOUDFLARE.addSubnet(prefix, Number(bits), "ipv6");
|
||||||
|
}
|
||||||
|
const fromCloudflare = address => {
|
||||||
|
const family = net.isIP(address);
|
||||||
|
return family !== 0 && CLOUDFLARE.check(address, family === 4 ? "ipv4" : "ipv6");
|
||||||
|
};
|
||||||
|
|
||||||
// is this address the server's own machine, and does that count for
|
// 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.)
|
// anything here? (It must not when a local reverse proxy forwards everyone.)
|
||||||
const isTrustedLocal = address => config.trustLocalRequests && isLoopback(address);
|
const isTrustedLocal = address => config.trustLocalRequests && isLoopback(address);
|
||||||
@@ -45,7 +65,17 @@ const clientOf = req => {
|
|||||||
const own = String(req.socket.remoteAddress || "").replace(/^::ffff:/i, "");
|
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 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 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;
|
// the last X-Forwarded-For entry is the one the local proxy appended: who
|
||||||
|
// connected to it (the first is whatever the visitor sent, so it is never
|
||||||
|
// used). Behind Cloudflare that is Cloudflare's own edge, which made every
|
||||||
|
// visitor one address (and left remoteip out of the Turnstile check), so
|
||||||
|
// then CF-Connecting-IP is the visitor. Only when that hop is Cloudflare:
|
||||||
|
// anyone who reaches the server directly can send the header too. Neither
|
||||||
|
// header counts unless the local reverse proxy has been trusted.
|
||||||
|
const lastHop = (hops.at(-1) || "").replace(/^::ffff:/i, "");
|
||||||
|
const cloudflareAddress = String(req.headers["cf-connecting-ip"] || "").trim().replace(/^::ffff:/i, "");
|
||||||
|
const reported = net.isIP(cloudflareAddress) && fromCloudflare(lastHop) ? cloudflareAddress : lastHop;
|
||||||
|
const address = config.trustedProxy && isLoopback(own) && reported ? reported.replace(/^::ffff:/i, "").slice(0, 60) : own;
|
||||||
const direct = isLoopback(own) && !forwarded;
|
const direct = isLoopback(own) && !forwarded;
|
||||||
return {address, key: key(address), direct, local: direct && config.trustLocalRequests};
|
return {address, key: key(address), direct, local: direct && config.trustLocalRequests};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
// a value from outside (a username, an address, what a client sent) as it
|
||||||
|
// may go into a line of the server's log: on one line, and with no control
|
||||||
|
// characters, so that it cannot pass for a line of the server's own (a name
|
||||||
|
// with a line break in it, "...\n[admin] signed in") or move the terminal's
|
||||||
|
// cursor about. (U+2028 and U+2029, which end a line too, are in the second.)
|
||||||
|
const OTHER_BREAKS_AND_CONTROLS = new RegExp("[\x00-\x1f\x7f-\x9f\u2028\u2029]", "g");
|
||||||
|
|
||||||
|
// (line feeds go first, and to nothing: the form code scanning knows as a
|
||||||
|
// log's sanitiser. carriage returns, and the rest, are then replaced.)
|
||||||
|
const logText = value => String(value)
|
||||||
|
.replace(/\n/g, "")
|
||||||
|
.replace(/\r/g, " ")
|
||||||
|
.replace(OTHER_BREAKS_AND_CONTROLS, "?");
|
||||||
|
|
||||||
|
module.exports = {logText};
|
||||||
+380
-19
@@ -1,5 +1,9 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
|
const customItems = require("./customitems.js");
|
||||||
|
const itemControl = require("./itemcontrol.js");
|
||||||
|
const playerItems = require("./playeritems.js");
|
||||||
const crypto = require("crypto");
|
const crypto = require("crypto");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
@@ -8,6 +12,7 @@ const config = require("../config.js");
|
|||||||
const limits = require("./limits.js");
|
const limits = require("./limits.js");
|
||||||
const achievements = require("./achievements.js");
|
const achievements = require("./achievements.js");
|
||||||
const badges = require("./badges.js");
|
const badges = require("./badges.js");
|
||||||
|
const discord = require("./discord.js");
|
||||||
const bans = require("./bans.js");
|
const bans = require("./bans.js");
|
||||||
const captcha = require("./captcha.js");
|
const captcha = require("./captcha.js");
|
||||||
const chatlog = require("./chatlog.js");
|
const chatlog = require("./chatlog.js");
|
||||||
@@ -17,7 +22,12 @@ const masterpieces = require("./masterpieces.js");
|
|||||||
const defpacks = require("./defpacks.js");
|
const defpacks = require("./defpacks.js");
|
||||||
const support = require("./support.js");
|
const support = require("./support.js");
|
||||||
const totp = require("./totp.js");
|
const totp = require("./totp.js");
|
||||||
|
const recoveryMail = require("./recoverymail.js");
|
||||||
const world = require("./world.js");
|
const world = require("./world.js");
|
||||||
|
const chatStyles = require("./chatstyles.js");
|
||||||
|
const roles = require("./roles.js");
|
||||||
|
const admin = require("./admin.js");
|
||||||
|
const itemPreview = require("./itempreview.js");
|
||||||
|
|
||||||
// the account page at /account: what a player can do about their own
|
// the account page at /account: what a player can do about their own
|
||||||
// account from a browser. they sign in with the game's username and
|
// account from a browser. they sign in with the game's username and
|
||||||
@@ -36,9 +46,40 @@ const world = require("./world.js");
|
|||||||
const COOKIE = "ajc_account";
|
const COOKIE = "ajc_account";
|
||||||
// A device that gave its two-step code keeps this for 30 days (lib/totp.js).
|
// A device that gave its two-step code keeps this for 30 days (lib/totp.js).
|
||||||
const DEVICE_COOKIE = "ajc_device";
|
const DEVICE_COOKIE = "ajc_device";
|
||||||
|
// a Discord link under way (lib/discord.js): the browser that started it
|
||||||
|
// must be the one that comes back. Lax, as Discord's redirect back is from
|
||||||
|
// another site, which the page's own (Strict) cookie is not sent from.
|
||||||
|
const DISCORD_COOKIE = "ajc_dlink";
|
||||||
|
const discordCookie = (value, maxAgeSeconds) =>
|
||||||
|
`${DISCORD_COOKIE}=${value}; Path=/account/discord; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
|
||||||
const SESSION_HOURS = 12;
|
const SESSION_HOURS = 12;
|
||||||
const TEN_MINUTES_MS = 600000;
|
const TEN_MINUTES_MS = 600000;
|
||||||
|
// "Sign in with the Burrow client": the page starts it, and keeps this
|
||||||
|
// cookie; the link it opens (burrow://account?n=<nonce>) has the client ask
|
||||||
|
// for a ticket with its own login token, which it then opens in the
|
||||||
|
// browser at /account/client. the ticket signs in only the browser that
|
||||||
|
// holds the nonce it was asked for, so a burrow:// link from anywhere else
|
||||||
|
// signs nobody in, and a ticket sent to someone else opens nothing for them.
|
||||||
|
const CLIENT_COOKIE = "ajc_clink";
|
||||||
|
const clientCookie = (value, maxAgeSeconds) =>
|
||||||
|
`${CLIENT_COOKIE}=${value}; Path=/account/client; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
|
||||||
|
const CLIENT_START_MS = 5 * 60 * 1000;
|
||||||
|
const CLIENT_TICKET_MS = 2 * 60 * 1000;
|
||||||
|
const MAX_CLIENT_STARTS = 10000;
|
||||||
|
const clientStarts = new Map(); // SHA-256 of a nonce -> expiry (ms)
|
||||||
|
const clientTickets = new Map(); // SHA-256 of a ticket -> {id: account id, nonce: SHA-256 of its nonce, expiry: ms}
|
||||||
|
const clientStartsByAddress = limits.limiter(20, TEN_MINUTES_MS);
|
||||||
|
const clientTicketsByAccount = limits.limiter(10, TEN_MINUTES_MS);
|
||||||
|
const dropExpired = map => {
|
||||||
|
for (const [hash, entry] of map) {
|
||||||
|
if ((typeof entry === "number" ? entry : entry.expiry) < Date.now()) {
|
||||||
|
map.delete(hash);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
const MAX_NOTE = 120;
|
const MAX_NOTE = 120;
|
||||||
|
const RECOVERY_TOKEN_MS = 30 * 60 * 1000;
|
||||||
|
const recoveryHash = token => crypto.createHash("sha256").update(token).digest("hex");
|
||||||
|
|
||||||
// wrong passwords before further tries from an address are refused for a
|
// wrong passwords before further tries from an address are refused for a
|
||||||
// while, as for the launcher's sign-in (lib/http.js).
|
// while, as for the launcher's sign-in (lib/http.js).
|
||||||
@@ -48,6 +89,21 @@ const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_M
|
|||||||
// at it and is then signed out.
|
// at it and is then signed out.
|
||||||
const WRONG_PASSWORDS_ALLOWED = 5;
|
const WRONG_PASSWORDS_ALLOWED = 5;
|
||||||
const wrongPasswords = limits.limiter(WRONG_PASSWORDS_ALLOWED, TEN_MINUTES_MS);
|
const wrongPasswords = limits.limiter(WRONG_PASSWORDS_ALLOWED, TEN_MINUTES_MS);
|
||||||
|
const recoveryRequests = limits.limiter(5, TEN_MINUTES_MS);
|
||||||
|
// recovery mail sent for one account, from any address: a few an hour.
|
||||||
|
const recoveryMailsPerAccount = limits.limiter(3, 3600000);
|
||||||
|
// a 2FA reset by email waits this long after a password reset by email, so
|
||||||
|
// that someone who has only the mailbox cannot do one after the other.
|
||||||
|
const EMAIL_RESET_GAP_MS = 7 * 24 * 3600000;
|
||||||
|
// why a 2FA reset by email cannot be done for this account now, or null.
|
||||||
|
// it also needs the account's password (recover/complete). staff ask the
|
||||||
|
// admin (lib/panel.js), whose 2FA reset ends their role's use until they
|
||||||
|
// turn it on again: a mailbox must not make someone staff.
|
||||||
|
const twoStepResetProblem = account => roles.roleOf(account)
|
||||||
|
? "Staff accounts cannot remove 2FA by email. Ask the admin."
|
||||||
|
: account.emailPasswordResetAt && Date.now() - account.emailPasswordResetAt < EMAIL_RESET_GAP_MS
|
||||||
|
? "2FA cannot be removed by email within 7 days of a password reset by email."
|
||||||
|
: null;
|
||||||
// what may be done from the page of a ban (above).
|
// what may be done from the page of a ban (above).
|
||||||
const BANNED_MAY = ["password", "twoStepStart", "twoStepConfirm", "twoStepOff", "forgetDevices", "delete", "appeal"];
|
const BANNED_MAY = ["password", "twoStepStart", "twoStepConfirm", "twoStepOff", "forgetDevices", "delete", "appeal"];
|
||||||
// and from the page of a rejected username: the same, with a new name in
|
// and from the page of a rejected username: the same, with a new name in
|
||||||
@@ -100,6 +156,13 @@ const signOutOthers = (account, req) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ends the account's sessions in the moderator panel (lib/modpanel.js, which
|
||||||
|
// needs this file, so it is asked for when used): with the others when the
|
||||||
|
// password changes or the owner signs out everywhere, and when the account
|
||||||
|
// locks or turns 2FA off, so that a session from before does not come back
|
||||||
|
// with it.
|
||||||
|
const endStaffSessions = account => require("./modpanel.js").forget(account);
|
||||||
|
|
||||||
const twoStepOf = account => ({on: totp.isOn(account), since: account.totp ? account.totp.since : null,
|
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});
|
recoveryLeft: account.totp ? account.totp.recovery.length : 0, devices: totp.freshDevices(account).length, deviceDays: totp.DEVICE_DAYS});
|
||||||
|
|
||||||
@@ -124,6 +187,7 @@ const bannedProfile = (account, ban) => {
|
|||||||
appeal: appeal && {createdAt: appeal.createdAt, text: appeal.text, status: appeal.status, reply: appeal.reply, handledAt: appeal.handledAt},
|
appeal: appeal && {createdAt: appeal.createdAt, text: appeal.text, status: appeal.status, reply: appeal.reply, handledAt: appeal.handledAt},
|
||||||
appealLimit: bans.MAX_APPEAL,
|
appealLimit: bans.MAX_APPEAL,
|
||||||
twoStep: twoStepOf(account),
|
twoStep: twoStepOf(account),
|
||||||
|
recoveryEmail: account.recoveryEmail ? `${account.recoveryEmail.slice(0, 2)}…${account.recoveryEmail.slice(account.recoveryEmail.lastIndexOf("@"))}` : "",
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -145,16 +209,25 @@ const profile = (account, from) => {
|
|||||||
logins: account.numLogins || 0,
|
logins: account.numLogins || 0,
|
||||||
playtime: account.playtime,
|
playtime: account.playtime,
|
||||||
playtimePublic: account.playtimePublic,
|
playtimePublic: account.playtimePublic,
|
||||||
|
chatStyle: chatStyles.normalize(account.chatStyle),
|
||||||
animals: account.avatars.length,
|
animals: account.avatars.length,
|
||||||
animalType: avatar ? avatar.type : null,
|
animalType: avatar ? avatar.type : null,
|
||||||
items: account.items.length,
|
items: account.items.length,
|
||||||
denItems: account.denItems.length,
|
denItems: account.denItems.length,
|
||||||
|
// what they made in the game's Item Maker (lib/playeritems.js)
|
||||||
|
customItems: playerItems.madeBy(account).map(entry => ({kind: entry.kind, id: entry.id, name: entry.name,
|
||||||
|
art: require("./itemart.js").urlOf(entry, "/account/api/itemart"), artWaiting: Boolean(entry.artPending), look: entry.artMode || "sticker"})),
|
||||||
|
picturesStopped: Boolean(account.artBlocked),
|
||||||
|
customItemLimits: {perDay: playerItems.PER_DAY, inAll: playerItems.IN_ALL},
|
||||||
pets: account.pets.length,
|
pets: account.pets.length,
|
||||||
buddies: account.buddies.length,
|
buddies: account.buddies.length,
|
||||||
banned: null,
|
banned: null,
|
||||||
locked: account.locked,
|
locked: account.locked,
|
||||||
twoStep: twoStepOf(account),
|
twoStep: twoStepOf(account),
|
||||||
|
recoveryEmail: account.recoveryEmail ? `${account.recoveryEmail.slice(0, 2)}…${account.recoveryEmail.slice(account.recoveryEmail.lastIndexOf("@"))}` : "",
|
||||||
discord: account.discord,
|
discord: account.discord,
|
||||||
|
discordLinked: Boolean(account.discordId),
|
||||||
|
discordLinking: discord.linking(),
|
||||||
bio: account.bio,
|
bio: account.bio,
|
||||||
bioLimit: badges.MAX_BIO,
|
bioLimit: badges.MAX_BIO,
|
||||||
badges: badges.of(account).map(badge => badge.label),
|
badges: badges.of(account).map(badge => badge.label),
|
||||||
@@ -179,7 +252,7 @@ const profile = (account, from) => {
|
|||||||
// hash, the 2FA secret, device passes), and what other tables hold of it.
|
// hash, the 2FA secret, device passes), and what other tables hold of it.
|
||||||
// what others wrote about it (reports, a moderator's notes) is not theirs
|
// what others wrote about it (reports, a moderator's notes) is not theirs
|
||||||
// to be handed, and is not here.
|
// to be handed, and is not here.
|
||||||
const SECRET_FIELDS = ["salt", "hash", "totp", "totpSetup", "devices"];
|
const SECRET_FIELDS = ["salt", "hash", "totp", "totpSetup", "devices", "modNotes", "recoveryTokens"];
|
||||||
const dataOf = account => ({
|
const dataOf = account => ({
|
||||||
exportedAt: new Date().toISOString(),
|
exportedAt: new Date().toISOString(),
|
||||||
server: config.baseUrl,
|
server: config.baseUrl,
|
||||||
@@ -250,7 +323,7 @@ const act = (account, body, req, from, res) => {
|
|||||||
}
|
}
|
||||||
delete account.nameRejected;
|
delete account.nameRejected;
|
||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
console.log(`[account] a rejected username was replaced by "${account.username}" from ${from.address}`);
|
console.log(`[account] a rejected username was replaced by "${logText(account.username)}" from ${logText(from.address)}`);
|
||||||
return {ok: "Saved."};
|
return {ok: "Saved."};
|
||||||
}
|
}
|
||||||
// one for each account, ever: an answer that wants a follow-up says
|
// one for each account, ever: an answer that wants a follow-up says
|
||||||
@@ -267,12 +340,15 @@ const act = (account, body, req, from, res) => {
|
|||||||
if (!passwordAgain(account, body.current)) {
|
if (!passwordAgain(account, body.current)) {
|
||||||
return {error: "Wrong password."};
|
return {error: "Wrong password."};
|
||||||
}
|
}
|
||||||
if (accounts.setPassword(account, body.password)) {
|
const passwordProblem = accounts.setPassword(account, body.password);
|
||||||
return {error: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."};
|
if (passwordProblem) {
|
||||||
|
return {error: passwordProblem === "weak_password" ? "That password is too easy to guess: it is a common one, or has your username in it."
|
||||||
|
: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."};
|
||||||
}
|
}
|
||||||
world.moderation.actions.kick(account);
|
world.moderation.actions.kick(account);
|
||||||
signOutOthers(account, req);
|
signOutOthers(account, req);
|
||||||
console.log(`[account] "${account.username}" changed their password from ${from.address}`);
|
endStaffSessions(account);
|
||||||
|
console.log(`[account] "${logText(account.username)}" changed their password from ${logText(from.address)}`);
|
||||||
return {ok: "Password changed."};
|
return {ok: "Password changed."};
|
||||||
}
|
}
|
||||||
case "requestName": {
|
case "requestName": {
|
||||||
@@ -291,9 +367,10 @@ const act = (account, body, req, from, res) => {
|
|||||||
// out of the game now, and no saved sign-in gets back in.
|
// out of the game now, and no saved sign-in gets back in.
|
||||||
accounts.revokeTokens(account);
|
accounts.revokeTokens(account);
|
||||||
world.moderation.actions.kick(account);
|
world.moderation.actions.kick(account);
|
||||||
|
endStaffSessions(account);
|
||||||
}
|
}
|
||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
console.log(`[account] "${account.username}" ${account.locked ? "locked" : "unlocked"} from ${from.address}`);
|
console.log(`[account] "${logText(account.username)}" ${logText(account.locked ? "locked" : "unlocked")} from ${logText(from.address)}`);
|
||||||
return {ok: account.locked ? "Locked." : "Unlocked."};
|
return {ok: account.locked ? "Locked." : "Unlocked."};
|
||||||
}
|
}
|
||||||
case "feature": {
|
case "feature": {
|
||||||
@@ -322,11 +399,12 @@ const act = (account, body, req, from, res) => {
|
|||||||
const recovery = totp.confirm(account, body.code);
|
const recovery = totp.confirm(account, body.code);
|
||||||
if (!recovery) {
|
if (!recovery) {
|
||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
return {error: "Wrong code."};
|
// confirm() drops a setup older than 15 minutes: no code can match it now.
|
||||||
|
return {error: account.totpSetup ? "Wrong code." : "Setup timed out. Turn 2FA on again and scan the new QR code."};
|
||||||
}
|
}
|
||||||
accounts.revokeTokens(account);
|
accounts.revokeTokens(account);
|
||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
console.log(`[account] "${account.username}" turned two-step sign-in on from ${from.address}`);
|
console.log(`[account] "${logText(account.username)}" turned two-step sign-in on from ${logText(from.address)}`);
|
||||||
return {ok: "2FA is on.", recovery};
|
return {ok: "2FA is on.", recovery};
|
||||||
}
|
}
|
||||||
// turning it off: the password and a code (or a recovery code).
|
// turning it off: the password and a code (or a recovery code).
|
||||||
@@ -343,8 +421,9 @@ const act = (account, body, req, from, res) => {
|
|||||||
}
|
}
|
||||||
totp.turnOff(account);
|
totp.turnOff(account);
|
||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
|
endStaffSessions(account);
|
||||||
res.setHeader("Set-Cookie", cookieHeader("", 0, DEVICE_COOKIE));
|
res.setHeader("Set-Cookie", cookieHeader("", 0, DEVICE_COOKIE));
|
||||||
console.log(`[account] "${account.username}" turned two-step sign-in off from ${from.address}`);
|
console.log(`[account] "${logText(account.username)}" turned two-step sign-in off from ${logText(from.address)}`);
|
||||||
return {ok: "2FA is off."};
|
return {ok: "2FA is off."};
|
||||||
}
|
}
|
||||||
case "forgetDevices":
|
case "forgetDevices":
|
||||||
@@ -352,6 +431,20 @@ const act = (account, body, req, from, res) => {
|
|||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
return {ok: "Trusted devices forgotten."};
|
return {ok: "Trusted devices forgotten."};
|
||||||
// their bio, for the Bio tab of their card in the game. empty takes it off.
|
// their bio, for the Bio tab of their card in the game. empty takes it off.
|
||||||
|
// their own custom items: a new name, or gone (from everyone who has
|
||||||
|
// one). a picture is sent to /api/itemart.
|
||||||
|
case "itemLook":
|
||||||
|
return playerItems.setLook(account, String(body.kind), body.id, String(body.look));
|
||||||
|
case "itemRename":
|
||||||
|
return playerItems.rename(account, String(body.kind), body.id, body.name);
|
||||||
|
case "itemDelete": {
|
||||||
|
const entry = customItems.get(String(body.kind), body.id);
|
||||||
|
if (!entry || entry.ownerId !== account.id) {
|
||||||
|
return {error: "That is not one of your items."};
|
||||||
|
}
|
||||||
|
const result = itemControl.deleteCustom(entry.kind, entry.id, world);
|
||||||
|
return result.error ? result : {ok: `Deleted ${entry.name}.`};
|
||||||
|
}
|
||||||
case "bio": {
|
case "bio": {
|
||||||
// typed words others read: not while they cannot chat.
|
// typed words others read: not while they cannot chat.
|
||||||
if (world.moderation.isSilenced(account)) {
|
if (world.moderation.isSilenced(account)) {
|
||||||
@@ -365,7 +458,7 @@ const act = (account, body, req, from, res) => {
|
|||||||
// each other (lib/chat-filter.txt).
|
// each other (lib/chat-filter.txt).
|
||||||
const rule = chatFilter.broken(bio);
|
const rule = chatFilter.broken(bio);
|
||||||
if (rule) {
|
if (rule) {
|
||||||
console.log(`[filter] "${account.username}" bio not saved (${rule}): ${JSON.stringify(bio)}`);
|
console.log(`[filter] "${logText(account.username)}" bio not saved (${logText(rule)}): ${logText(JSON.stringify(bio))}`);
|
||||||
return {error: "Your bio has words that are not allowed here."};
|
return {error: "Your bio has words that are not allowed here."};
|
||||||
}
|
}
|
||||||
account.bio = bio;
|
account.bio = bio;
|
||||||
@@ -377,16 +470,26 @@ const act = (account, body, req, from, res) => {
|
|||||||
account.playtimePublic = body.on === true;
|
account.playtimePublic = body.on === true;
|
||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
return {ok: account.playtimePublic ? "Others can see your playtime on your card." : "Your playtime is private."};
|
return {ok: account.playtimePublic ? "Others can see your playtime on your card." : "Your playtime is private."};
|
||||||
// their Discord username, for their card in the game. empty takes it off.
|
// A player can choose every colour, opacity, animation and animation
|
||||||
case "discord": {
|
// speed. Validation is deliberately here as well as in the page: saved
|
||||||
const name = badges.discordName(body.name);
|
// state is not trusted just because it came from our own browser UI.
|
||||||
if (name === null) {
|
case "chatStyle": {
|
||||||
return {error: "Not a Discord username."};
|
if (!chatStyles.valid(body.style)) {
|
||||||
|
return {error: "Choose valid chat colours and animation settings."};
|
||||||
}
|
}
|
||||||
account.discord = name;
|
account.chatStyle = chatStyles.normalize(body.style);
|
||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
return {ok: name ? "Saved." : "Removed."};
|
return {ok: "Chat style saved. Your next message will use it."};
|
||||||
}
|
}
|
||||||
|
// their Discord account, for their card in the game: it is linked by
|
||||||
|
// signing in to Discord (GET /account/discord/link), and only taken off
|
||||||
|
// here, with the booster badge it brought.
|
||||||
|
case "discord":
|
||||||
|
if (String(body.name || "") !== "") {
|
||||||
|
return {error: "Link your Discord account instead."};
|
||||||
|
}
|
||||||
|
discord.unlink(account);
|
||||||
|
return {ok: "Removed."};
|
||||||
// the player's own words about a buddy; only they see them.
|
// the player's own words about a buddy; only they see them.
|
||||||
case "buddyNote": {
|
case "buddyNote": {
|
||||||
const key = String(body.name || "").toLowerCase();
|
const key = String(body.name || "").toLowerCase();
|
||||||
@@ -433,6 +536,7 @@ const act = (account, body, req, from, res) => {
|
|||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
world.moderation.actions.kick(account);
|
world.moderation.actions.kick(account);
|
||||||
signOutOthers(account, req);
|
signOutOthers(account, req);
|
||||||
|
endStaffSessions(account);
|
||||||
return {ok: "Signed out everywhere."};
|
return {ok: "Signed out everywhere."};
|
||||||
// for good: the password again, and the username typed out.
|
// for good: the password again, and the username typed out.
|
||||||
case "delete": {
|
case "delete": {
|
||||||
@@ -445,8 +549,9 @@ const act = (account, body, req, from, res) => {
|
|||||||
const name = account.username;
|
const name = account.username;
|
||||||
world.disconnect(account);
|
world.disconnect(account);
|
||||||
signOutOthers(account, null);
|
signOutOthers(account, null);
|
||||||
|
endStaffSessions(account);
|
||||||
erase(account);
|
erase(account);
|
||||||
console.log(`[account] "${name}" deleted their account from ${from.address}`);
|
console.log(`[account] "${logText(name)}" deleted their account from ${logText(from.address)}`);
|
||||||
return {ok: "Account deleted.", deleted: true};
|
return {ok: "Account deleted.", deleted: true};
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
@@ -463,6 +568,16 @@ const PAGE_HEADERS = {
|
|||||||
+ "form-action 'none'; frame-ancestors 'none'; base-uri 'none'"),
|
+ "form-action 'none'; frame-ancestors 'none'; base-uri 'none'"),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// the web item giver shows den items in frames of public/item-preview.html,
|
||||||
|
// which plays them with Ruffle (a Flash player, from jsDelivr).
|
||||||
|
const ITEMS_PAGE_POLICY = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; "
|
||||||
|
+ "frame-src 'self'; form-action 'none'; frame-ancestors 'none'; base-uri 'none'";
|
||||||
|
const RUFFLE = "https://cdn.jsdelivr.net/npm/@ruffle-rs/[email protected]/";
|
||||||
|
const PREVIEW_POLICY = `default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval' ${RUFFLE}; connect-src 'self' ${RUFFLE}; `
|
||||||
|
+ "style-src 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' data: blob:; worker-src blob:; "
|
||||||
|
+ "form-action 'none'; frame-ancestors 'self'; base-uri 'none'; sandbox allow-scripts";
|
||||||
|
const artFetches = limits.limiter(600, 600000); // item pictures for the web item giver, per address in ten minutes
|
||||||
|
|
||||||
// A request that changes something must come from this server's own page.
|
// A request that changes something must come from this server's own page.
|
||||||
const sameOrigin = limits.originAllowed;
|
const sameOrigin = limits.originAllowed;
|
||||||
|
|
||||||
@@ -478,6 +593,45 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "account.html"))), "text/html; charset=utf-8");
|
web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "account.html"))), "text/html; charset=utf-8");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// the item giver on the web (public/items.html), with this page's sign-in.
|
||||||
|
if (route === "GET /account/items") {
|
||||||
|
res.setHeader("Content-Security-Policy", ITEMS_PAGE_POLICY);
|
||||||
|
web.send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "items.html")), "text/html; charset=utf-8");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// its den item previews (lib/itempreview.js): a page of their own in a
|
||||||
|
// frame, sandboxed, as they run a Flash player from elsewhere (Ruffle).
|
||||||
|
if (route === "GET /account/item-preview") {
|
||||||
|
res.setHeader("Content-Security-Policy", PREVIEW_POLICY);
|
||||||
|
res.setHeader("X-Frame-Options", "SAMEORIGIN");
|
||||||
|
web.send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "item-preview.html")), "text/html; charset=utf-8");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const art = /^GET \/account\/(item-preview\.swf|art\/(clothing|den)\/(\d{1,9}))$/.exec(route);
|
||||||
|
if (art) {
|
||||||
|
// fetched from the preview's sandbox, which has no origin of its own
|
||||||
|
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||||
|
if (art[1] === "item-preview.swf") {
|
||||||
|
web.send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "item-preview.swf")), "application/x-shockwave-flash");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!artFetches.allow(from.address)) {
|
||||||
|
reply(429, {error: "Too many at once. Try again in a minute."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const found = art[2] === "den" ? await itemPreview.denArt(Number(art[3])) : await itemPreview.clothingIcon(Number(art[3]));
|
||||||
|
if (!found) {
|
||||||
|
reply(404, {error: "No picture."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.setHeader("Cache-Control", "public, max-age=3600");
|
||||||
|
web.send(res, 200, found, art[2] === "den" ? "application/x-shockwave-flash" : "application/json");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (route === "GET /account/recover") {
|
||||||
|
web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "recover.html"))), "text/html; charset=utf-8");
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (req.method === "POST" && !sameOrigin(req)) {
|
if (req.method === "POST" && !sameOrigin(req)) {
|
||||||
reply(403, {error: "forbidden"});
|
reply(403, {error: "forbidden"});
|
||||||
return;
|
return;
|
||||||
@@ -485,6 +639,87 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
const body = req.method === "POST" ? await web.readJson(req) : {};
|
const body = req.method === "POST" ? await web.readJson(req) : {};
|
||||||
|
|
||||||
switch (route) {
|
switch (route) {
|
||||||
|
case "POST /account/api/recover/request": {
|
||||||
|
// Always give the same reply: neither account names nor email addresses
|
||||||
|
// can be discovered from this endpoint.
|
||||||
|
if (!from.local && !recoveryRequests.allow(from.key)) {
|
||||||
|
reply(429, {ok: "If the account and recovery email match, we sent a recovery link."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const account = accounts.byName(String(body.username || ""));
|
||||||
|
const email = String(body.email || "").trim().toLowerCase();
|
||||||
|
const kind = body.kind === "twoStep" ? "twoStep" : "password";
|
||||||
|
if (account && account.recoveryEmail && account.recoveryEmail === email && recoveryMail.available()
|
||||||
|
&& recoveryMailsPerAccount.allow(account.id)) {
|
||||||
|
const token = crypto.randomBytes(32).toString("hex");
|
||||||
|
account.recoveryTokens = (account.recoveryTokens || []).filter(entry => entry.expires > Date.now());
|
||||||
|
account.recoveryTokens.push({hash: recoveryHash(token), kind, expires: Date.now() + RECOVERY_TOKEN_MS});
|
||||||
|
accounts.save(account);
|
||||||
|
const link = new URL(`/account/recover?token=${token}`, config.siteUrl).href;
|
||||||
|
const sent = await recoveryMail.send({to: account.recoveryEmail, subject: "Burrow account recovery",
|
||||||
|
text: `A ${kind === "twoStep" ? "2FA reset" : "password reset"} was requested for ${account.username}. Open this link within 30 minutes:\n${link}\n\nIf this was not you, ignore this email.`});
|
||||||
|
if (!sent) {
|
||||||
|
account.recoveryTokens = account.recoveryTokens.filter(entry => entry.hash !== recoveryHash(token));
|
||||||
|
accounts.save(account);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reply(200, {ok: "If the account and recovery email match, we sent a recovery link."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case "POST /account/api/recover/check": {
|
||||||
|
const token = String(body.token || "");
|
||||||
|
const account = [...accounts.all()].find(candidate => (candidate.recoveryTokens || []).some(entry => entry.hash === recoveryHash(token) && entry.expires > Date.now()));
|
||||||
|
const entry = account && account.recoveryTokens.find(candidate => candidate.hash === recoveryHash(token) && candidate.expires > Date.now());
|
||||||
|
const refused = entry && entry.kind === "twoStep" ? twoStepResetProblem(account) : null;
|
||||||
|
reply(entry && !refused ? 200 : 400, entry && !refused ? {kind: entry.kind} : {error: refused || "This recovery link is invalid or expired."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case "POST /account/api/recover/complete": {
|
||||||
|
const token = String(body.token || "");
|
||||||
|
const account = [...accounts.all()].find(candidate => (candidate.recoveryTokens || []).some(entry => entry.hash === recoveryHash(token) && entry.expires > Date.now()));
|
||||||
|
const entry = account && account.recoveryTokens.find(candidate => candidate.hash === recoveryHash(token) && candidate.expires > Date.now());
|
||||||
|
if (!entry) {
|
||||||
|
reply(400, {error: "This recovery link is invalid or expired."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (entry.kind === "password") {
|
||||||
|
const problem = accounts.setPassword(account, body.password);
|
||||||
|
if (problem) {
|
||||||
|
reply(400, {error: problem === "weak_password" ? "That password is too easy to guess." : "Use 10+ characters with an uppercase letter, lowercase letter and digit."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
account.emailPasswordResetAt = Date.now();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const refused = twoStepResetProblem(account);
|
||||||
|
if (refused) {
|
||||||
|
reply(400, {error: refused});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// the mailbox and the password: the link alone does not remove 2FA.
|
||||||
|
if (!from.local && failuresByAddress.blocked(from.key)) {
|
||||||
|
reply(429, {error: "Too many attempts. Try later."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (await accounts.authenticateAsync(account.username, body.password) !== account) {
|
||||||
|
failuresByAddress.record(from.key);
|
||||||
|
reply(401, {error: "Wrong password."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (totp.isOn(account)) {
|
||||||
|
totp.turnOff(account);
|
||||||
|
accounts.revokeTokens(account);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
account.recoveryTokens = [];
|
||||||
|
accounts.save(account);
|
||||||
|
signOutOthers(account, null);
|
||||||
|
endStaffSessions(account);
|
||||||
|
world.moderation.actions.kick(account);
|
||||||
|
console.log(`[recovery] ${logText(entry.kind)} reset for "${logText(account.username)}" after email verification from ${logText(from.address)}`);
|
||||||
|
reply(200, {ok: entry.kind === "password" ? "Password reset. You can sign in now." : "2FA reset. You can sign in now."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
case "POST /account/api/login": {
|
case "POST /account/api/login": {
|
||||||
const key = String(body.username || "").trim().toLowerCase();
|
const key = String(body.username || "").trim().toLowerCase();
|
||||||
if (!from.local && failuresByAddress.blocked(from.key)) {
|
if (!from.local && failuresByAddress.blocked(from.key)) {
|
||||||
@@ -542,6 +777,96 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
reply(200, {ok: true});
|
reply(200, {ok: true});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// "Sign in with the Burrow client" (above), from the page: the nonce for
|
||||||
|
// the burrow:// link, which this browser keeps as a cookie too.
|
||||||
|
case "POST /account/api/client-start": {
|
||||||
|
if (!from.local && !clientStartsByAddress.allow(from.key)) {
|
||||||
|
reply(429, {error: "Too many attempts. Try later."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
dropExpired(clientStarts);
|
||||||
|
if (clientStarts.size >= MAX_CLIENT_STARTS) {
|
||||||
|
reply(503, {error: "Try again in a few minutes."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const nonce = crypto.randomBytes(24).toString("hex");
|
||||||
|
clientStarts.set(sha256(nonce), Date.now() + CLIENT_START_MS);
|
||||||
|
res.setHeader("Set-Cookie", clientCookie(nonce, CLIENT_START_MS / 1000));
|
||||||
|
reply(200, {nonce});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// ... from the client, with its login token (no Origin: the client's main
|
||||||
|
// process): where to send the browser, which signs in there. a token is
|
||||||
|
// only given after a whole sign-in, 2FA code included (lib/http.js).
|
||||||
|
case "POST /account/api/client-ticket": {
|
||||||
|
const nonce = typeof body.nonce === "string" && /^[0-9a-f]{48}$/.test(body.nonce) ? body.nonce : "";
|
||||||
|
const started = nonce && clientStarts.get(sha256(nonce));
|
||||||
|
if (!started || started < Date.now()) {
|
||||||
|
reply(400, {error: "Start again from the account page."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!from.local && failuresByAddress.blocked(from.key)) {
|
||||||
|
reply(429, {error: "Too many attempts. Try later."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const account = accounts.byToken(body.token);
|
||||||
|
if (!account) {
|
||||||
|
failuresByAddress.record(from.key);
|
||||||
|
reply(401, {error: "Log in to Burrow again first."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!clientTicketsByAccount.allow(account.id)) {
|
||||||
|
reply(429, {error: "Too many attempts. Try later."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
dropExpired(clientTickets);
|
||||||
|
const ticket = crypto.randomBytes(24).toString("hex");
|
||||||
|
clientTickets.set(sha256(ticket), {id: account.id, nonce: sha256(nonce), expiry: Date.now() + CLIENT_TICKET_MS});
|
||||||
|
reply(200, {url: new URL(`/account/client?ticket=${ticket}`, config.siteUrl).href, username: account.username});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ... and the ticket, opened by the client in the browser: signed in when
|
||||||
|
// this browser started it (its cookie). a ticket is good once, whatever
|
||||||
|
// happens. the page that follows says how it went.
|
||||||
|
if (route === "GET /account/client") {
|
||||||
|
const given = String(url.searchParams.get("ticket") || "");
|
||||||
|
const ticket = /^[0-9a-f]{48}$/.test(given) ? clientTickets.get(sha256(given)) : null;
|
||||||
|
if (ticket) {
|
||||||
|
clientTickets.delete(sha256(given));
|
||||||
|
}
|
||||||
|
const nonce = (new RegExp(`(?:^|;\\s*)${CLIENT_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1];
|
||||||
|
const account = ticket && ticket.expiry > Date.now() ? accounts.byId(ticket.id) : null;
|
||||||
|
const result = !account ? "expired" : !nonce || sha256(nonce) !== ticket.nonce ? "elsewhere" : "ok";
|
||||||
|
const cookies = [clientCookie("", 0)];
|
||||||
|
if (result === "ok") {
|
||||||
|
clientStarts.delete(ticket.nonce);
|
||||||
|
accounts.recordLogin(account, "web", from.address);
|
||||||
|
accounts.save(account);
|
||||||
|
signIn(res, account, cookies);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
res.setHeader("Set-Cookie", cookies);
|
||||||
|
}
|
||||||
|
// a page of this site's own that goes on to the account page, rather than
|
||||||
|
// a redirect: the (SameSite=Strict) cookie then surely goes with it.
|
||||||
|
res.setHeader("Cache-Control", "no-store");
|
||||||
|
web.send(res, 200, `<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=/account?client=${result}"><title>Burrow</title>`,
|
||||||
|
"text/html; charset=utf-8");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// back from Discord (lib/discord.js): the state and the nonce must be the
|
||||||
|
// ones the link began with. the page then says how it went.
|
||||||
|
if (route === "GET /account/discord/callback") {
|
||||||
|
const nonce = (new RegExp(`(?:^|;\\s*)${DISCORD_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1];
|
||||||
|
const result = url.searchParams.get("error") ? {error: "cancelled"}
|
||||||
|
: await discord.finish(url.searchParams.get("state"), nonce, url.searchParams.get("code"));
|
||||||
|
res.setHeader("Set-Cookie", discordCookie("", 0));
|
||||||
|
res.writeHead(302, {Location: `/account?discord=${result.ok ? "linked" : result.error}`});
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const account = signedInAs(req);
|
const account = signedInAs(req);
|
||||||
@@ -550,6 +875,20 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
switch (route) {
|
switch (route) {
|
||||||
|
// the page's "Link Discord": off to Discord's sign-in, which comes back
|
||||||
|
// to /account/discord/callback.
|
||||||
|
case "GET /account/discord/link": {
|
||||||
|
if (!discord.linking() || banFor(account, from)) {
|
||||||
|
res.writeHead(302, {Location: "/account?discord=off"});
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const {url: to, nonce} = discord.start(account);
|
||||||
|
res.setHeader("Set-Cookie", discordCookie(nonce, 600));
|
||||||
|
res.writeHead(302, {Location: to});
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
// A copy of their data, as a file. also from the page of a ban.
|
// A copy of their data, as a file. also from the page of a ban.
|
||||||
case "GET /account/api/export":
|
case "GET /account/api/export":
|
||||||
if (!writesPerTenMinutes.allow(account.id)) {
|
if (!writesPerTenMinutes.allow(account.id)) {
|
||||||
@@ -562,6 +901,28 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
case "GET /account/api/me":
|
case "GET /account/api/me":
|
||||||
reply(200, profile(account, from));
|
reply(200, profile(account, from));
|
||||||
return;
|
return;
|
||||||
|
// the item giver (above, and lib/admin.js): for the account signed in
|
||||||
|
// here only, as the in-game one is for the one playing; not while banned.
|
||||||
|
case "GET /account/api/giver":
|
||||||
|
case "GET /account/api/colour":
|
||||||
|
case "POST /account/api/give": {
|
||||||
|
if (banFor(account, from) || account.nameRejected) {
|
||||||
|
reply(403, {error: "Not now."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (route === "GET /account/api/colour") {
|
||||||
|
const result = await admin.colourLookup(url.searchParams);
|
||||||
|
reply(result.status, result.body);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (req.method === "GET") {
|
||||||
|
reply(200, await admin.searchFor(account, url.searchParams));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = admin.giveAs(account, body);
|
||||||
|
reply(result.status, result.body);
|
||||||
|
return;
|
||||||
|
}
|
||||||
// for the trade offer form: what the player could give, and what
|
// for the trade offer form: what the player could give, and what
|
||||||
// another player has up for trade.
|
// another player has up for trade.
|
||||||
case "GET /account/api/tradable": {
|
case "GET /account/api/tradable": {
|
||||||
@@ -601,4 +962,4 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
// called when an account's name changes or it is deleted: its page sessions end.
|
// called when an account's name changes or it is deleted: its page sessions end.
|
||||||
const forget = account => signOutOthers(account, null);
|
const forget = account => signOutOthers(account, null);
|
||||||
|
|
||||||
module.exports = {handle, forget};
|
module.exports = {handle, forget, signedInAs};
|
||||||
+255
-26
@@ -6,6 +6,8 @@ const path = require("path");
|
|||||||
const config = require("../config.js");
|
const config = require("../config.js");
|
||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
const limits = require("./limits.js");
|
const limits = require("./limits.js");
|
||||||
|
const imageModeration = require("./image-moderation.js");
|
||||||
|
const jpegPrint = require("./jpegprint.js");
|
||||||
|
|
||||||
// masterpieces: paintings from the Art Studio, framed and hung in a den
|
// masterpieces: paintings from the Art Studio, framed and hung in a den
|
||||||
// (client side: game.artStudioPainting.ArtStudioPainting, the same in
|
// (client side: game.artStudioPainting.ArtStudioPainting, the same in
|
||||||
@@ -40,9 +42,27 @@ const SCHEMA = `
|
|||||||
status INTEGER NOT NULL,
|
status INTEGER NOT NULL,
|
||||||
frame INTEGER NOT NULL,
|
frame INTEGER NOT NULL,
|
||||||
reviewed_at INTEGER,
|
reviewed_at INTEGER,
|
||||||
|
reviewed_by TEXT,
|
||||||
likes TEXT NOT NULL,
|
likes TEXT NOT NULL,
|
||||||
image BLOB NOT NULL
|
image BLOB NOT NULL
|
||||||
);
|
);
|
||||||
|
-- every picture taken in, for the daily limit (pictures thrown away
|
||||||
|
-- unframed count too)
|
||||||
|
CREATE TABLE IF NOT EXISTS masterpiece_uploads (
|
||||||
|
creator_id INTEGER NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS masterpiece_uploads_by ON masterpiece_uploads (creator_id, created_at);
|
||||||
|
-- pictures a moderator or the admin approved once: the same picture
|
||||||
|
-- again, the same file (SHA-256) or the same painting saved and painted
|
||||||
|
-- again (its fingerprint, lib/jpegprint.js), is approved as it is framed
|
||||||
|
CREATE TABLE IF NOT EXISTS masterpiece_approved_pictures (
|
||||||
|
hash TEXT PRIMARY KEY,
|
||||||
|
approved_at INTEGER NOT NULL,
|
||||||
|
approved_by TEXT NOT NULL,
|
||||||
|
fingerprint BLOB,
|
||||||
|
thumb BLOB
|
||||||
|
);
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const UPLOADED = 0; // posted, not made into an item yet
|
const UPLOADED = 0; // posted, not made into an item yet
|
||||||
@@ -77,14 +97,35 @@ const fileOf = id => path.join(folder(), `${id}.jpg`);
|
|||||||
const GALLERY_SPOTS = 12; // PartyManager.setupMasterpiecesInRoom
|
const GALLERY_SPOTS = 12; // PartyManager.setupMasterpiecesInRoom
|
||||||
|
|
||||||
const uploadsPerHour = limits.limiter(30, 3600000);
|
const uploadsPerHour = limits.limiter(30, 3600000);
|
||||||
|
const DAY = 86400;
|
||||||
|
const AUTO_APPROVER = "auto"; // reviewedBy of a painting approved for a picture approved before
|
||||||
const now = () => Math.floor(Date.now() / 1000);
|
const now = () => Math.floor(Date.now() / 1000);
|
||||||
const db = () => accounts.database();
|
const db = () => accounts.database();
|
||||||
|
|
||||||
const known = new Map(); // id -> {id, creator, createdAt, status, frame, likes: [account ids]}
|
const known = new Map(); // id -> {id, creator, createdAt, status, frame, reviewedAt, reviewedBy, likes: [account ids], hash}
|
||||||
|
const approvedPictures = new Map(); // hash -> thumbnail of its fingerprint, or null: masterpiece_approved_pictures
|
||||||
const tokens = new Map(); // upload token -> {account id, expires (ms)}
|
const tokens = new Map(); // upload token -> {account id, expires (ms)}
|
||||||
|
|
||||||
const load = () => {
|
const load = () => {
|
||||||
db().exec(SCHEMA);
|
db().exec(SCHEMA);
|
||||||
|
// who approved it: a moderator's username, "admin", or null when nobody
|
||||||
|
// looked (review was off, or it was approved before this was kept).
|
||||||
|
const columns = db().prepare("PRAGMA table_info(masterpieces)").all().map(column => column.name);
|
||||||
|
if (!columns.includes("reviewed_by")) {
|
||||||
|
db().exec("ALTER TABLE masterpieces ADD COLUMN reviewed_by TEXT");
|
||||||
|
}
|
||||||
|
// the picture's SHA-256 (hashOf) and fingerprint (lib/jpegprint.js), to know it again
|
||||||
|
if (!columns.includes("hash")) {
|
||||||
|
db().exec("ALTER TABLE masterpieces ADD COLUMN hash TEXT");
|
||||||
|
}
|
||||||
|
if (!columns.includes("fingerprint")) {
|
||||||
|
db().exec("ALTER TABLE masterpieces ADD COLUMN fingerprint BLOB");
|
||||||
|
}
|
||||||
|
const pictureColumns = db().prepare("PRAGMA table_info(masterpiece_approved_pictures)").all().map(column => column.name);
|
||||||
|
if (!pictureColumns.includes("fingerprint")) {
|
||||||
|
db().exec("ALTER TABLE masterpiece_approved_pictures ADD COLUMN fingerprint BLOB");
|
||||||
|
db().exec("ALTER TABLE masterpiece_approved_pictures ADD COLUMN thumb BLOB");
|
||||||
|
}
|
||||||
fs.mkdirSync(folder(), {recursive: true});
|
fs.mkdirSync(folder(), {recursive: true});
|
||||||
// pictures still in the table move out into files, once.
|
// pictures still in the table move out into files, once.
|
||||||
for (const row of db().prepare("SELECT id FROM masterpieces WHERE length(image) > 0").all()) {
|
for (const row of db().prepare("SELECT id FROM masterpieces WHERE length(image) > 0").all()) {
|
||||||
@@ -92,15 +133,138 @@ const load = () => {
|
|||||||
fs.writeFileSync(fileOf(row.id), Buffer.from(picture));
|
fs.writeFileSync(fileOf(row.id), Buffer.from(picture));
|
||||||
db().prepare("UPDATE masterpieces SET image = ? WHERE id = ?").run(NO_IMAGE, row.id);
|
db().prepare("UPDATE masterpieces SET image = ? WHERE id = ?").run(NO_IMAGE, row.id);
|
||||||
}
|
}
|
||||||
for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, likes FROM masterpieces").all()) {
|
for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, reviewed_at, reviewed_by, likes, hash FROM masterpieces").all()) {
|
||||||
known.set(row.id, {id: row.id, creator: row.creator_id, createdAt: row.created_at, status: row.status, frame: row.frame, likes: JSON.parse(row.likes)});
|
known.set(row.id, {id: row.id, creator: row.creator_id, createdAt: row.created_at, status: row.status, frame: row.frame,
|
||||||
|
reviewedAt: row.reviewed_at, reviewedBy: row.reviewed_by, likes: JSON.parse(row.likes), hash: row.hash || null});
|
||||||
}
|
}
|
||||||
|
for (const row of db().prepare("SELECT hash, thumb FROM masterpiece_approved_pictures").all()) {
|
||||||
|
approvedPictures.set(row.hash, row.thumb ? Buffer.from(row.thumb) : null);
|
||||||
|
}
|
||||||
|
backfill();
|
||||||
|
};
|
||||||
|
|
||||||
|
const hashOf = image => crypto.createHash("sha256").update(image).digest("hex");
|
||||||
|
|
||||||
|
const printOf = painting => {
|
||||||
|
const row = db().prepare("SELECT fingerprint FROM masterpieces WHERE id = ?").get(painting.id);
|
||||||
|
return row && row.fingerprint ? Buffer.from(row.fingerprint) : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// the approved pictures (their hashes) that this picture is: the same file,
|
||||||
|
// or the same painting by its fingerprint.
|
||||||
|
const approvedMatches = (hash, print) => {
|
||||||
|
const found = approvedPictures.has(hash) ? [hash] : [];
|
||||||
|
if (print) {
|
||||||
|
const thumb = jpegPrint.thumbnail(print);
|
||||||
|
for (const [other, otherThumb] of approvedPictures) {
|
||||||
|
if (other !== hash && otherThumb && jpegPrint.thumbnailsClose(thumb, otherThumb)) {
|
||||||
|
const row = db().prepare("SELECT fingerprint FROM masterpiece_approved_pictures WHERE hash = ?").get(other);
|
||||||
|
if (row && row.fingerprint && jpegPrint.samePicture(print, Buffer.from(row.fingerprint))) {
|
||||||
|
found.push(other);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
};
|
||||||
|
|
||||||
|
const pictureApproved = (hash, print) => Boolean(hash) && approvedMatches(hash, print).length > 0;
|
||||||
|
|
||||||
|
const notePictureApproved = (painting, print) => {
|
||||||
|
const thumb = print ? jpegPrint.thumbnail(print) : null;
|
||||||
|
db().prepare("INSERT OR IGNORE INTO masterpiece_approved_pictures (hash, approved_at, approved_by, fingerprint, thumb) VALUES (?, ?, ?, ?, ?)")
|
||||||
|
.run(painting.hash, painting.reviewedAt || now(), painting.reviewedBy, print, thumb);
|
||||||
|
if (!approvedPictures.has(painting.hash)) {
|
||||||
|
approvedPictures.set(painting.hash, thumb);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// paintings from before pictures were known again get their hash and
|
||||||
|
// fingerprint, a few at a time after start (each is a file read and some
|
||||||
|
// milliseconds of decoding, on the thread the game shares); those a person
|
||||||
|
// approved make their pictures approved ones.
|
||||||
|
const BACKFILL_BATCH = 20;
|
||||||
|
const backfill = () => {
|
||||||
|
const missing = db().prepare("SELECT id FROM masterpieces WHERE fingerprint IS NULL OR hash IS NULL").all().map(row => row.id);
|
||||||
|
const notedAgain = db().prepare("SELECT hash FROM masterpiece_approved_pictures WHERE fingerprint IS NULL").all().map(row => row.hash);
|
||||||
|
const step = () => {
|
||||||
|
for (const id of missing.splice(0, BACKFILL_BATCH)) {
|
||||||
|
const painting = known.get(id);
|
||||||
|
let image = null;
|
||||||
|
try {
|
||||||
|
image = painting ? fs.readFileSync(fileOf(id)) : null;
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
image = null;
|
||||||
|
}
|
||||||
|
if (!image) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
painting.hash = hashOf(image);
|
||||||
|
const print = jpegPrint.fingerprint(image);
|
||||||
|
db().prepare("UPDATE masterpieces SET hash = ?, fingerprint = ? WHERE id = ?").run(painting.hash, print, id);
|
||||||
|
if (painting.status === APPROVED && painting.reviewedBy && painting.reviewedBy !== AUTO_APPROVER) {
|
||||||
|
notePictureApproved(painting, print);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// pictures approved before fingerprints were kept: from a painting of
|
||||||
|
// theirs, once every painting has its own
|
||||||
|
for (const hash of missing.length ? [] : notedAgain.splice(0, BACKFILL_BATCH)) {
|
||||||
|
const row = db().prepare("SELECT fingerprint FROM masterpieces WHERE hash = ? AND fingerprint IS NOT NULL").get(hash);
|
||||||
|
if (row) {
|
||||||
|
const print = Buffer.from(row.fingerprint);
|
||||||
|
const thumb = jpegPrint.thumbnail(print);
|
||||||
|
db().prepare("UPDATE masterpiece_approved_pictures SET fingerprint = ?, thumb = ? WHERE hash = ?").run(print, thumb, hash);
|
||||||
|
approvedPictures.set(hash, thumb);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (missing.length || notedAgain.length) {
|
||||||
|
setTimeout(step, 200).unref();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if (missing.length || notedAgain.length) {
|
||||||
|
setTimeout(step, 1000).unref();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// why this account may not paint for a frame now, as words for the player,
|
||||||
|
// or null when it may: too new an account (asked at the easel, step 1), or
|
||||||
|
// as many new pictures in the last 24 hours as a day allows (asked of a
|
||||||
|
// picture not approved before, step 2). `whenFree` speaks of the wait.
|
||||||
|
const whenFree = seconds => {
|
||||||
|
const hours = Math.ceil(seconds / 3600);
|
||||||
|
return hours > 1 ? `in ${hours} hours` : `in ${Math.max(1, Math.ceil(seconds / 60))} minutes`;
|
||||||
|
};
|
||||||
|
const tooNew = account => {
|
||||||
|
const age = now() - (Number(account.createdAt) || 0);
|
||||||
|
if (age < config.masterpieceMinAccountAge) {
|
||||||
|
return `Accounts can make Masterpieces once they are a day old. Try again ${whenFree(config.masterpieceMinAccountAge - age)}.`;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
const tooMany = account => {
|
||||||
|
const recent = db().prepare("SELECT created_at FROM masterpiece_uploads WHERE creator_id = ? AND created_at > ? ORDER BY created_at")
|
||||||
|
.all(account.id, now() - DAY);
|
||||||
|
const perDay = config.masterpiecesPerDay;
|
||||||
|
if (recent.length >= perDay) {
|
||||||
|
return `You can make ${perDay} new Masterpieces a day. Try again ${whenFree(recent[recent.length - perDay].created_at + DAY - now())}.`;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const needsReview = () => accounts.setting(REVIEW_SETTING) !== "0";
|
const needsReview = () => accounts.setting(REVIEW_SETTING) !== "0";
|
||||||
const setNeedsReview = on => accounts.setSetting(REVIEW_SETTING, on ? "1" : "0");
|
const setNeedsReview = on => accounts.setSetting(REVIEW_SETTING, on ? "1" : "0");
|
||||||
|
|
||||||
const forget = id => {
|
// `unapprove`: it was taken back by staff, so its picture is no longer one
|
||||||
|
// approved before (a painting thrown away unframed leaves it alone).
|
||||||
|
const forget = (id, unapprove = false) => {
|
||||||
|
const painting = known.get(id);
|
||||||
|
if (unapprove && painting && painting.hash) {
|
||||||
|
for (const hash of approvedMatches(painting.hash, printOf(painting))) {
|
||||||
|
db().prepare("DELETE FROM masterpiece_approved_pictures WHERE hash = ?").run(hash);
|
||||||
|
approvedPictures.delete(hash);
|
||||||
|
}
|
||||||
|
}
|
||||||
known.delete(id);
|
known.delete(id);
|
||||||
db().prepare("DELETE FROM masterpieces WHERE id = ?").run(id);
|
db().prepare("DELETE FROM masterpieces WHERE id = ?").run(id);
|
||||||
fs.rmSync(fileOf(id), {force: true});
|
fs.rmSync(fileOf(id), {force: true});
|
||||||
@@ -118,6 +282,7 @@ const sweep = () => {
|
|||||||
forget(painting.id);
|
forget(painting.id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
db().prepare("DELETE FROM masterpiece_uploads WHERE created_at <= ?").run(now() - DAY);
|
||||||
};
|
};
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
try {
|
try {
|
||||||
@@ -128,8 +293,12 @@ setInterval(() => {
|
|||||||
}
|
}
|
||||||
}, 600000).unref();
|
}, 600000).unref();
|
||||||
|
|
||||||
// A token for one upload by this account (step 1).
|
// A token for one upload by this account (step 1), or null when it is
|
||||||
|
// `tooNew`, which says why.
|
||||||
const issueToken = account => {
|
const issueToken = account => {
|
||||||
|
if (tooNew(account)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
for (const [token, entry] of tokens) {
|
for (const [token, entry] of tokens) {
|
||||||
if (entry.account === account.id) {
|
if (entry.account === account.id) {
|
||||||
tokens.delete(token);
|
tokens.delete(token);
|
||||||
@@ -181,15 +350,33 @@ const looksLikeJpeg = image => {
|
|||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
// step 2. returns the new painting's id, or null when the token is not
|
// step 2. resolves to {uuid}, the new painting's id, or {uuid: null} when
|
||||||
// good, the picture is not a JPEG of a sane size, or the account has posted
|
// the token is not good, the picture is not a JPEG of a sane size, or the
|
||||||
// too many.
|
// account has posted too many; with `refusal` and `maker` when the player
|
||||||
const upload = (token, image) => {
|
// should be told why.
|
||||||
|
const upload = async (token, image) => {
|
||||||
const entry = typeof token === "string" ? tokens.get(token) : null;
|
const entry = typeof token === "string" ? tokens.get(token) : null;
|
||||||
tokens.delete(token);
|
tokens.delete(token);
|
||||||
if (!entry || entry.expires < Date.now() || !Buffer.isBuffer(image) || image.length > MAX_IMAGE_BYTES || !looksLikeJpeg(image)
|
if (!entry || entry.expires < Date.now() || !Buffer.isBuffer(image) || image.length > MAX_IMAGE_BYTES || !looksLikeJpeg(image)
|
||||||
|| !uploadsPerHour.allow(entry.account)) {
|
|| !uploadsPerHour.allow(entry.account)) {
|
||||||
return null;
|
return {uuid: null};
|
||||||
|
}
|
||||||
|
// a picture approved before is not a new one and does not count
|
||||||
|
const hash = hashOf(image);
|
||||||
|
const print = jpegPrint.fingerprint(image);
|
||||||
|
const approvedBefore = pictureApproved(hash, print);
|
||||||
|
const maker = accounts.byId(entry.account);
|
||||||
|
const refusal = maker && !approvedBefore ? tooNew(maker) || tooMany(maker) : null;
|
||||||
|
if (!maker || refusal) {
|
||||||
|
return {uuid: null, refusal, maker};
|
||||||
|
}
|
||||||
|
const safety = await imageModeration.scan(image);
|
||||||
|
if (safety.blocked) {
|
||||||
|
console.log(`[masterpieces] rejected unsafe upload from account ${entry.account}`);
|
||||||
|
return {uuid: null};
|
||||||
|
}
|
||||||
|
if (!approvedBefore) {
|
||||||
|
db().prepare("INSERT INTO masterpiece_uploads (creator_id, created_at) VALUES (?, ?)").run(entry.account, now());
|
||||||
}
|
}
|
||||||
// one painting at a time is between the easel and the frame.
|
// one painting at a time is between the easel and the frame.
|
||||||
for (const painting of [...known.values()]) {
|
for (const painting of [...known.values()]) {
|
||||||
@@ -197,18 +384,21 @@ const upload = (token, image) => {
|
|||||||
forget(painting.id);
|
forget(painting.id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, likes: []};
|
const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, reviewedAt: null, reviewedBy: null, likes: [], hash};
|
||||||
fs.writeFileSync(fileOf(painting.id), image);
|
fs.writeFileSync(fileOf(painting.id), image);
|
||||||
db().prepare("INSERT INTO masterpieces (id, creator_id, created_at, status, frame, likes, image) VALUES (?, ?, ?, ?, ?, '[]', ?)")
|
db().prepare("INSERT INTO masterpieces (id, creator_id, created_at, status, frame, likes, image, hash, fingerprint) VALUES (?, ?, ?, ?, ?, '[]', ?, ?, ?)")
|
||||||
.run(painting.id, painting.creator, painting.createdAt, painting.status, painting.frame, NO_IMAGE);
|
.run(painting.id, painting.creator, painting.createdAt, painting.status, painting.frame, NO_IMAGE, hash, print);
|
||||||
known.set(painting.id, painting);
|
known.set(painting.id, painting);
|
||||||
return painting.id;
|
return {uuid: painting.id};
|
||||||
};
|
};
|
||||||
|
|
||||||
const setStatus = (painting, status) => {
|
// `by`: who approved it, when someone did.
|
||||||
|
const setStatus = (painting, status, by = null) => {
|
||||||
painting.status = status;
|
painting.status = status;
|
||||||
db().prepare("UPDATE masterpieces SET status = ?, frame = ?, reviewed_at = ? WHERE id = ?")
|
painting.reviewedAt = status === APPROVED ? now() : null;
|
||||||
.run(status, painting.frame, status === APPROVED ? now() : null, painting.id);
|
painting.reviewedBy = status === APPROVED ? by : null;
|
||||||
|
db().prepare("UPDATE masterpieces SET status = ?, frame = ?, reviewed_at = ?, reviewed_by = ? WHERE id = ?")
|
||||||
|
.run(status, painting.frame, painting.reviewedAt, painting.reviewedBy, painting.id);
|
||||||
};
|
};
|
||||||
|
|
||||||
// may this account make an item of that painting, in that frame? (Step 3,
|
// may this account make an item of that painting, in that frame? (Step 3,
|
||||||
@@ -223,11 +413,19 @@ const claimable = (account, id, frame) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// step 3, paid for: the painting is an item now. true when it is approved
|
// step 3, paid for: the painting is an item now. true when it is approved
|
||||||
// on the spot.
|
// on the spot: review is off, or its picture was approved before.
|
||||||
const claim = (id, frame) => {
|
const claim = (id, frame) => {
|
||||||
const painting = known.get(String(id));
|
const painting = known.get(String(id));
|
||||||
painting.frame = frame;
|
painting.frame = frame;
|
||||||
setStatus(painting, needsReview() ? PENDING : APPROVED);
|
if (!needsReview()) {
|
||||||
|
setStatus(painting, APPROVED);
|
||||||
|
}
|
||||||
|
else if (pictureApproved(painting.hash, printOf(painting))) {
|
||||||
|
setStatus(painting, APPROVED, AUTO_APPROVER);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
setStatus(painting, PENDING);
|
||||||
|
}
|
||||||
return painting.status === APPROVED;
|
return painting.status === APPROVED;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -262,13 +460,26 @@ const mayView = (id, address, addressOf) => {
|
|||||||
return painting.status === APPROVED || Boolean(maker && addressOf(maker) && addressOf(maker) === address);
|
return painting.status === APPROVED || Boolean(maker && addressOf(maker) && addressOf(maker) === address);
|
||||||
};
|
};
|
||||||
|
|
||||||
const approve = id => {
|
// `by`: the moderator's username, or "admin". its picture is approved from
|
||||||
|
// now on, and the same picture waiting in other paintings is approved with
|
||||||
|
// it. the paintings approved, none when `id` was not waiting.
|
||||||
|
const approve = (id, by) => {
|
||||||
const painting = get(id);
|
const painting = get(id);
|
||||||
if (!painting || painting.status !== PENDING) {
|
if (!painting || painting.status !== PENDING) {
|
||||||
return false;
|
return [];
|
||||||
}
|
}
|
||||||
setStatus(painting, APPROVED);
|
setStatus(painting, APPROVED, by);
|
||||||
return true;
|
if (!painting.hash) {
|
||||||
|
return [painting];
|
||||||
|
}
|
||||||
|
const print = printOf(painting);
|
||||||
|
notePictureApproved(painting, print);
|
||||||
|
const twins = [...known.values()].filter(other => other.status === PENDING
|
||||||
|
&& (other.hash === painting.hash || (print && jpegPrint.samePicture(print, printOf(other)))));
|
||||||
|
for (const twin of twins) {
|
||||||
|
setStatus(twin, APPROVED, AUTO_APPROVER);
|
||||||
|
}
|
||||||
|
return [painting, ...twins];
|
||||||
};
|
};
|
||||||
|
|
||||||
// is a den item fit to be shown, traded and recycled? anything that is not
|
// is a den item fit to be shown, traded and recycled? anything that is not
|
||||||
@@ -312,13 +523,31 @@ const gallery = () => {
|
|||||||
return {pool: hung.slice(0, GALLERY_SPOTS), pluspool: hung.slice(GALLERY_SPOTS)};
|
return {pool: hung.slice(0, GALLERY_SPOTS), pluspool: hung.slice(GALLERY_SPOTS)};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// newest first: the waiting ones by when they were made, the approved ones
|
||||||
|
// by when they were approved, so that one let in by mistake is near the top.
|
||||||
const list = status => [...known.values()].filter(painting => painting.status === status)
|
const list = status => [...known.values()].filter(painting => painting.status === status)
|
||||||
.sort((one, other) => other.createdAt - one.createdAt)
|
.sort((one, other) => (other.reviewedAt || other.createdAt) - (one.reviewedAt || one.createdAt))
|
||||||
.map(painting => {
|
.map(painting => {
|
||||||
const maker = creatorOf(painting.id);
|
const maker = creatorOf(painting.id);
|
||||||
return {id: painting.id, creator: maker ? maker.username : "(deleted account)", createdAt: painting.createdAt, frame: painting.frame, likes: painting.likes.length};
|
return {id: painting.id, creator: maker ? maker.username : "(deleted account)", createdAt: painting.createdAt, frame: painting.frame, likes: painting.likes.length,
|
||||||
|
approvedAt: painting.reviewedAt, approvedBy: painting.reviewedBy};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// both lists for the panels, narrowed to makers whose names have
|
||||||
|
// `creator` in them (the one of exactly that name first): {waiting,
|
||||||
|
// approved}, newest first.
|
||||||
|
const listsFor = creator => {
|
||||||
|
const wanted = String(creator || "").trim().toLowerCase().slice(0, 100);
|
||||||
|
const narrowed = paintings => (wanted ? paintings.filter(painting => painting.creator.toLowerCase().includes(wanted))
|
||||||
|
.sort((one, other) => Number(other.creator.toLowerCase() === wanted) - Number(one.creator.toLowerCase() === wanted)) : paintings);
|
||||||
|
return {waiting: narrowed(list(PENDING)), approved: narrowed(list(APPROVED))};
|
||||||
|
};
|
||||||
|
|
||||||
|
// the last `count` approved, the latest first, for the moderator panel to
|
||||||
|
// take one back from: only the ones `by` approved, when given.
|
||||||
|
const recentlyApproved = (count, by = "") => list(APPROVED)
|
||||||
|
.filter(painting => !by || String(painting.approvedBy || "").toLowerCase() === by.toLowerCase()).slice(0, count);
|
||||||
|
|
||||||
const madeBy = account => [...known.values()].filter(painting => painting.creator === account.id).map(painting => painting.id);
|
const madeBy = account => [...known.values()].filter(painting => painting.creator === account.id).map(painting => painting.id);
|
||||||
|
|
||||||
// generic lists: (mediaId, name string id) pairs, or null when `listId` is
|
// generic lists: (mediaId, name string id) pairs, or null when `listId` is
|
||||||
@@ -327,7 +556,7 @@ const frameList = listId =>
|
|||||||
([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null);
|
([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null);
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, frameList,
|
load, issueToken, tooNew, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, recentlyApproved, frameList,
|
||||||
needsReview, setNeedsReview, madeBy,
|
needsReview, setNeedsReview, madeBy,
|
||||||
PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES,
|
PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES,
|
||||||
};
|
};
|
||||||
+301
-22
@@ -6,6 +6,7 @@ const defpacks = require("./defpacks.js");
|
|||||||
const buddyGames = require("./buddygames.js");
|
const buddyGames = require("./buddygames.js");
|
||||||
const masterpieces = require("./masterpieces.js");
|
const masterpieces = require("./masterpieces.js");
|
||||||
const dens = require("./dens.js");
|
const dens = require("./dens.js");
|
||||||
|
const customItems = require("./customitems.js");
|
||||||
const limits = require("./limits.js");
|
const limits = require("./limits.js");
|
||||||
const {activeAvatar, addClothing, sendClothingAdded} = require("./player.js");
|
const {activeAvatar, addClothing, sendClothingAdded} = require("./player.js");
|
||||||
|
|
||||||
@@ -16,10 +17,14 @@ const {activeAvatar, addClothing, sendClothingAdded} = require("./player.js");
|
|||||||
// game: the room it runs in, the start signal, gem awards, and for some
|
// game: the room it runs in, the start signal, gem awards, and for some
|
||||||
// games a few messages of their own.
|
// games a few messages of their own.
|
||||||
//
|
//
|
||||||
// lib/games.json is that table, put back together from what still names the
|
// lib/games.json is that table, as a recording of the official game has it
|
||||||
// ids: arcade-machine den items (gameDefId and a name), the room files (which
|
// (its "mi" reply, made with tools/recorder.js): which class each id runs,
|
||||||
// id stands where), the names GameCardPopup has for each game class, and the
|
// in a window or in the room's place, its user vars and its pictures. it
|
||||||
// achievement defs (which user vars a game counts in). entries:
|
// was first put back together from what still names the ids (arcade-machine
|
||||||
|
// den items, the room files, GameCardPopup's names, the achievement defs),
|
||||||
|
// which had some ids wrong: the print kits, the carnival games (run in the
|
||||||
|
// room, not in its place), Brady's lab, and the buddy games, given ids of
|
||||||
|
// other games' as nothing then named theirs. entries:
|
||||||
// id game def id
|
// id game def id
|
||||||
// swf the game's key in game.IncludeMinigames
|
// swf the game's key in game.IncludeMinigames
|
||||||
// title its name; sent as the id of the localization string that says so
|
// title its name; sent as the id of the localization string that says so
|
||||||
@@ -32,16 +37,16 @@ const {activeAvatar, addClothing, sendClothingAdded} = require("./player.js");
|
|||||||
// icon media id of its picture in the HUD's Games window; the games with
|
// icon media id of its picture in the HUD's Games window; the games with
|
||||||
// one are the ones that window lists
|
// one are the ones that window lists
|
||||||
// buddy true: one of the eight games two players play from a player's
|
// 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
|
// card (lib/buddygames.js)
|
||||||
// client names them, and the official table is gone.
|
// card the game's title picture on its "Play!" popup; a buddy game's
|
||||||
// card a buddy game's picture, on the card's game tab and in the
|
// in the invitation
|
||||||
// invitation
|
|
||||||
//
|
//
|
||||||
// every other game is played alone (minPlayers = maxPlayers = 1): the
|
// every other game is played alone (minPlayers = maxPlayers = 1): the
|
||||||
// multiplayer ones each have a protocol of their own between the players.
|
// 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 games = new Map(require("./games.json").map(game => [game.id, game]));
|
||||||
|
|
||||||
|
const GAME_AFTERGLOW_MS = 15000; // how long a game's room id is still taken after leaving it (leave)
|
||||||
const IN_ROOM = 0;
|
const IN_ROOM = 0;
|
||||||
const MAX_GEMS_PER_AWARD = 5000;
|
const MAX_GEMS_PER_AWARD = 5000;
|
||||||
const MAX_MASTERY_PER_AWARD = 100;
|
const MAX_MASTERY_PER_AWARD = 100;
|
||||||
@@ -63,6 +68,10 @@ const CARNIVAL_COST = 5; // gems a go
|
|||||||
const MAX_TICKETS_PER_GO = 300;
|
const MAX_TICKETS_PER_GO = 300;
|
||||||
const CURRENCY_TICKETS = 1;
|
const CURRENCY_TICKETS = 1;
|
||||||
const INVASION_COST = 10; // gems a go, as the machine's own screen says
|
const INVASION_COST = 10; // gems a go, as the machine's own screen says
|
||||||
|
const SMOOTHIE_COLOURS = new Set(["purple", "orange", "red", "yellow"]);
|
||||||
|
// The game's attachment state is client-defined (for example, the cocoa
|
||||||
|
// recipe). It is not an item id and must never become protocol markup.
|
||||||
|
const attachmentExtra = value => String(value ?? "").replace(/[\r\n%,]/g, "").slice(0, 128);
|
||||||
|
|
||||||
const awardsPerMinute = limits.limiter(120, 60000);
|
const awardsPerMinute = limits.limiter(120, 60000);
|
||||||
const invitesPerMinute = limits.limiter(20, 60000);
|
const invitesPerMinute = limits.limiter(20, 60000);
|
||||||
@@ -75,8 +84,35 @@ const messagesPerMinute = limits.limiter(900, 60000);
|
|||||||
// the "start" message a game waits for once it has said it is ready.
|
// the "start" message a game waits for once it has said it is ready.
|
||||||
const START = {
|
const START = {
|
||||||
seed: () => [serial()],
|
seed: () => [serial()],
|
||||||
seedAndPlayers: game => [serial(), game.players.length],
|
// then each player's sfs id and a field the game skips: a game knows
|
||||||
|
// which player is its own by the id (GemBreakerPlayer.init), and only
|
||||||
|
// that one aims and shoots.
|
||||||
|
seedAndPlayers: game => [serial(), game.players.length, ...game.players.flatMap(player => [player.id, 0])],
|
||||||
|
// Spider Zapper and Wind Rider (SpiderShooterPlayer.init,
|
||||||
|
// ParachuteGliderPlayer.init): each player's sfs id and where it starts.
|
||||||
|
// given only the seed they had no players, none of them their own:
|
||||||
|
// nothing could be shot, and nobody glided.
|
||||||
|
seedAndCrosshairs: game => [serial(), game.players.length,
|
||||||
|
...game.players.flatMap((player, at) => [player.id, CROSSHAIR_X + at * CROSSHAIR_GAP, CROSSHAIR_Y])],
|
||||||
};
|
};
|
||||||
|
const CROSSHAIR_X = 400;
|
||||||
|
const CROSSHAIR_GAP = 100;
|
||||||
|
const CROSSHAIR_Y = 300;
|
||||||
|
|
||||||
|
// the room games several players play together: "Multiplayer" on the
|
||||||
|
// game's waiting list (MinigameManager.setupWaitListPopup), for players in
|
||||||
|
// the same room. each client plays the same game from the same start, and
|
||||||
|
// the server passes each player's moves on to the others: `relay` names
|
||||||
|
// the messages passed on, true for those that go with the sender's sfs id
|
||||||
|
// first. a full list starts the game.
|
||||||
|
const MULTIPLAYER = {
|
||||||
|
// GemBreaker.message: "pos" [sfsUserId, cannon angle], "shoot" [the shot's
|
||||||
|
// nine numbers], "playerLost" [the next round's seed]. two players, a
|
||||||
|
// field each, first to win two rounds.
|
||||||
|
GemBreaker: {max: 2, relay: {pos: true, shoot: false, playerLost: false}},
|
||||||
|
};
|
||||||
|
const MAX_RELAYED_FIELDS = 12;
|
||||||
|
const RELAYED_FIELD = /^[-0-9a-zA-Z.]{1,32}$/;
|
||||||
|
|
||||||
// serial numbers the client mixes into its award messages; any number will do.
|
// serial numbers the client mixes into its award messages; any number will do.
|
||||||
function serial() {
|
function serial() {
|
||||||
@@ -85,7 +121,7 @@ function serial() {
|
|||||||
|
|
||||||
let nextGameRoomId = 500000; // well clear of the world's room ids
|
let nextGameRoomId = 500000; // well clear of the world's room ids
|
||||||
|
|
||||||
module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => {
|
||||||
// MinigameInfo.init, the 19 fields the "mi" reply carries for a game.
|
// MinigameInfo.init, the 19 fields the "mi" reply carries for a game.
|
||||||
const info = game => [
|
const info = game => [
|
||||||
game.id,
|
game.id,
|
||||||
@@ -93,11 +129,14 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
|||||||
defpacks.stringId(game.title) || defpacks.stringId(FALLBACK_TITLE),
|
defpacks.stringId(game.title) || defpacks.stringId(FALLBACK_TITLE),
|
||||||
game.swf, // extName
|
game.swf, // extName
|
||||||
game.swf, // swfName
|
game.swf, // swfName
|
||||||
game.buddy ? 2 : 1, game.buddy ? 2 : 1, // min and max players
|
// min and max players: more than one gives the game a waiting list
|
||||||
|
// with "Single Player" and "Multiplayer" (lib/minigames.js MULTIPLAYER).
|
||||||
|
game.buddy ? 2 : MULTIPLAYER[game.swf] ? MULTIPLAYER[game.swf].max : 1,
|
||||||
|
game.buddy ? 2 : MULTIPLAYER[game.swf] ? MULTIPLAYER[game.swf].max : 1,
|
||||||
0, // max spectators
|
0, // max spectators
|
||||||
game.type,
|
game.type,
|
||||||
// the game card: the title picture on the "play" popup (not known), and
|
// the game card: the title picture on the "play" popup, and for a buddy
|
||||||
// for a buddy game the picture in the invitation.
|
// game the picture in the invitation.
|
||||||
game.card || 0,
|
game.card || 0,
|
||||||
...(game.vars || [0, 0, 0]),
|
...(game.vars || [0, 0, 0]),
|
||||||
game.buddy ? 1 : 0, // ready for player-versus-player: listed on players' cards
|
game.buddy ? 1 : 0, // ready for player-versus-player: listed on players' cards
|
||||||
@@ -124,6 +163,82 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// A buddy game's bubble over a player's head, which anyone else in the
|
||||||
|
// room can click to play them (UserCommXtCommManager.sendCustomPVPMessage:
|
||||||
|
// a chat line "on|off" of type 12 with the game's id after it). the client
|
||||||
|
// reads it back as "on|<gameDefId>" or "off", and its sender waits for
|
||||||
|
// their own before going on. `session.pvpBubble` is the game's id.
|
||||||
|
const BUBBLE = "12";
|
||||||
|
const bubbleLine = session => [`on|${session.pvpBubble}`, BUBBLE, 0];
|
||||||
|
const bubbleSeers = session => watchers(session).filter(other => !blocks.either(other.account, session.account));
|
||||||
|
// the bubble goes for everyone else. the player's own "off" waits, when
|
||||||
|
// they are in a game, till they are out of it: it would end the game the
|
||||||
|
// client has only just set up (MinigameManager.readySelfForPvpGame).
|
||||||
|
const dropBubble = session => {
|
||||||
|
if (!session.pvpBubble) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
session.pvpBubble = null;
|
||||||
|
if (session.room) {
|
||||||
|
for (const other of bubbleSeers(session)) {
|
||||||
|
other.sendXt("uc", session.room.id, session.id, "off", BUBBLE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const bubbleOff = session => {
|
||||||
|
if (session.game) {
|
||||||
|
session.bubbleOffOwed = true;
|
||||||
|
}
|
||||||
|
else if (session.room) {
|
||||||
|
session.bubbleOffOwed = false;
|
||||||
|
session.sendXt("uc", session.room.id, session.id, "off", BUBBLE);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const bubble = (session, word, gameDefId) => {
|
||||||
|
if (word !== "on") {
|
||||||
|
dropBubble(session);
|
||||||
|
bubbleOff(session);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const def = games.get(Number(gameDefId));
|
||||||
|
if (!def || !def.buddy || !Object.hasOwn(buddyGames, def.swf) || !session.room || session.game || session.invite
|
||||||
|
|| session.invisible || !accounts.featureOn(session.account, "gameInvites")) {
|
||||||
|
if (session.room && !session.game) {
|
||||||
|
tell(session, session.invisible ? "Nobody can see you to play with you." : "You cannot ask for a game right now.");
|
||||||
|
}
|
||||||
|
dropBubble(session);
|
||||||
|
bubbleOff(session);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
session.pvpBubble = def.id;
|
||||||
|
for (const other of [session, ...bubbleSeers(session)]) {
|
||||||
|
other.sendXt("uc", session.room.id, session.id, ...bubbleLine(session));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// a bubble that is up, for a player who has just been shown its owner.
|
||||||
|
const showBubble = (to, owner) => {
|
||||||
|
if (owner.pvpBubble && owner.room && to !== owner && !blocks.either(to.account, owner.account)) {
|
||||||
|
to.sendXt("uc", owner.room.id, owner.id, ...bubbleLine(owner));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Food-machine games reward a short-lived avatar attachment. Replying
|
||||||
|
// with "_a" is important: MinigameManager turns it into the same local
|
||||||
|
// attachment action used by den objects, which then sends the normal
|
||||||
|
// user-communication packet to the room. Sending that packet ourselves
|
||||||
|
// skips the local state and leaves the player with nothing visible.
|
||||||
|
const grantAttachment = (session, game, reply, emoticonDefId, extra = "") => {
|
||||||
|
if (game.attachmentGranted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const state = attachmentExtra(extra);
|
||||||
|
if (!defpacks.emoticonMediaId(emoticonDefId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
game.attachmentGranted = true;
|
||||||
|
reply("_a", emoticonDefId, state);
|
||||||
|
};
|
||||||
|
|
||||||
// takes the player out of the game they are in, if any, and out of an
|
// takes the player out of the game they are in, if any, and out of an
|
||||||
// invitation.
|
// invitation.
|
||||||
const leave = session => {
|
const leave = session => {
|
||||||
@@ -133,7 +248,21 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
session.game = null;
|
session.game = null;
|
||||||
|
// an in-room game may say it is done just before it hands over what it
|
||||||
|
// made (the Juice Bar's smoothie, the Cocoa Hut's drink: an attachment,
|
||||||
|
// lib/world.js pubMsg), labelled with the game's room
|
||||||
|
session.lastGame = {roomId: game.roomId, until: Date.now() + GAME_AFTERGLOW_MS};
|
||||||
|
if (session.bubbleOffOwed) {
|
||||||
|
bubbleOff(session);
|
||||||
|
}
|
||||||
game.players = game.players.filter(player => player !== session);
|
game.players = game.players.filter(player => player !== session);
|
||||||
|
if (game.lobby) {
|
||||||
|
if (game.players.length === 0) {
|
||||||
|
lobbies.delete(game.lobby);
|
||||||
|
}
|
||||||
|
tellLobby(game);
|
||||||
|
return;
|
||||||
|
}
|
||||||
// the games' own "player left": [sfsUserId]. A buddy game takes it for
|
// 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
|
// 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
|
// decided is not told. three of them only the clients know the end of
|
||||||
@@ -180,6 +309,11 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
|||||||
// minigamePetMastery) and who is in the game (joinGameResponse).
|
// minigamePetMastery) and who is in the game (joinGameResponse).
|
||||||
const seat = (session, game, music) => {
|
const seat = (session, game, music) => {
|
||||||
const avatar = activeAvatar(session.account);
|
const avatar = activeAvatar(session.account);
|
||||||
|
// off to a game: a bubble still up goes (and its owner is told after).
|
||||||
|
if (session.pvpBubble) {
|
||||||
|
dropBubble(session);
|
||||||
|
session.bubbleOffOwed = true;
|
||||||
|
}
|
||||||
session.game = game;
|
session.game = game;
|
||||||
session.sendXt("rj", -1, 1, `game${game.def.id}_${game.roomId}`, game.roomId, game.players.length, game.players.length, 0, 0,
|
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, 1, 0, 1, game.def.type === IN_ROOM ? 1 : 0, // isPrivate, isGame, isLimbo, isTemp, isSubRoom
|
||||||
@@ -191,6 +325,59 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
|||||||
session.sendXt("mj", game.roomId, ...game.players.map(player => player.id));
|
session.sendXt("mj", game.roomId, ...game.players.map(player => player.id));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// the waiting lists of multiplayer room games: "<gameDefId> <room>" -> a
|
||||||
|
// game not started yet. one is answered "mj" from the room the players
|
||||||
|
// wait in, with who waits: the client draws them from that room, so they
|
||||||
|
// stay in it till the list is full.
|
||||||
|
const lobbies = new Map();
|
||||||
|
const tellLobby = game => {
|
||||||
|
for (const player of game.players) {
|
||||||
|
player.sendXt("mj", game.waitRoom.id, ...game.players.map(other => other.id));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const joinLobby = (session, def, multi) => {
|
||||||
|
const key = `${def.id} ${session.room.name}`;
|
||||||
|
let game = lobbies.get(key);
|
||||||
|
if (game && game.players.some(player => blocks.either(player.account, session.account))) {
|
||||||
|
session.sendXt("mj", -1, "as", 0);
|
||||||
|
tell(session, "Someone already waiting for that game is not someone you play with. Try again later.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!game) {
|
||||||
|
game = {roomId: nextGameRoomId++, def, multi, players: [], started: false, ready: new Set(), lobby: key, waitRoom: session.room};
|
||||||
|
lobbies.set(key, game);
|
||||||
|
}
|
||||||
|
game.players.push(session);
|
||||||
|
session.game = game;
|
||||||
|
tellLobby(game);
|
||||||
|
if (game.players.length >= multi.max) {
|
||||||
|
lobbies.delete(key);
|
||||||
|
game.lobby = null;
|
||||||
|
for (const player of game.players) {
|
||||||
|
const music = player.room ? player.room.customMusicDef : 0;
|
||||||
|
if (def.type !== IN_ROOM) {
|
||||||
|
leaveRoom(player);
|
||||||
|
}
|
||||||
|
seat(player, game, music);
|
||||||
|
}
|
||||||
|
start(game);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// a move in a multiplayer room game, passed on to the other players.
|
||||||
|
const relay = (session, game, word, params) => {
|
||||||
|
const withId = game.multi.relay[word];
|
||||||
|
if (!game.started || params.length > MAX_RELAYED_FIELDS || !params.every(field => RELAYED_FIELD.test(String(field)))
|
||||||
|
|| !messagesPerMinute.allow(session.account.id)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const other of game.players) {
|
||||||
|
if (other !== session) {
|
||||||
|
other.sendXt("mm", game.roomId, word, ...(withId ? [session.id] : []), ...params);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// starts a buddy game between two players (lib/buddygames.js says what
|
// 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.
|
// `match` is). it runs in a window over whatever room each is in.
|
||||||
const startMatch = (def, sender, target) => {
|
const startMatch = (def, sender, target) => {
|
||||||
@@ -239,8 +426,12 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
|||||||
// den items a claw machine can drop: the plushies, of the machine's own
|
// den items a claw machine can drop: the plushies, of the machine's own
|
||||||
// animal when it is named for one ("The Wolf Claw").
|
// animal when it is named for one ("The Wolf Claw").
|
||||||
let plushies = null;
|
let plushies = null;
|
||||||
|
// the game's own den items only: a custom item (and a player's own, which
|
||||||
|
// is nobody else's to win) may be missing from the winner's game, whose
|
||||||
|
// prize popup then threw (DenItem.initShopItem) and left the game frozen.
|
||||||
|
const gameOwnDenItemIds = () => defpacks.denItemIds().filter(id => id < customItems.FIRST_ID);
|
||||||
const clawPrizes = game => {
|
const clawPrizes = game => {
|
||||||
plushies = plushies || defpacks.denItemIds().filter(id => /plush/i.test(defpacks.denItemDef(id).abbrName));
|
plushies = plushies || gameOwnDenItemIds().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 item = defpacks.denItemIds().map(id => defpacks.denItemDef(id)).find(def => Number(def.gameDefId) === game.id);
|
||||||
const animal = item ? /^ArcCraneGame(.+)$/.exec(item.abbrName) : null;
|
const animal = item ? /^ArcCraneGame(.+)$/.exec(item.abbrName) : null;
|
||||||
const own = animal ? plushies.filter(id => defpacks.denItemDef(id).abbrName.toLowerCase().includes(animal[1].toLowerCase())) : [];
|
const own = animal ? plushies.filter(id => defpacks.denItemDef(id).abbrName.toLowerCase().includes(animal[1].toLowerCase())) : [];
|
||||||
@@ -251,7 +442,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
|||||||
// machines aside.
|
// machines aside.
|
||||||
let phantomItems = null;
|
let phantomItems = null;
|
||||||
const invasionPrizes = () => {
|
const invasionPrizes = () => {
|
||||||
phantomItems = phantomItems || defpacks.denItemIds().filter(id => /phantom/i.test(defpacks.denItemDef(id).abbrName)
|
phantomItems = phantomItems || gameOwnDenItemIds().filter(id => /phantom/i.test(defpacks.denItemDef(id).abbrName)
|
||||||
&& !/^Arc/.test(defpacks.denItemDef(id).abbrName) && defpacks.string(defpacks.denItemDef(id).nameStrId));
|
&& !/^Arc/.test(defpacks.denItemDef(id).abbrName) && defpacks.string(defpacks.denItemDef(id).nameStrId));
|
||||||
return phantomItems.length ? phantomItems : defpacks.denItemIds().slice(0, 1);
|
return phantomItems.length ? phantomItems : defpacks.denItemIds().slice(0, 1);
|
||||||
};
|
};
|
||||||
@@ -295,13 +486,59 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// refused to an account under a day old: the game shows its "could not
|
||||||
|
// send" popup, and a plain message box ("xtl") says why.
|
||||||
const uploadToken = (session, game, [, purpose], reply) => {
|
const uploadToken = (session, game, [, purpose], reply) => {
|
||||||
reply("tkn", 1, 0, masterpieces.issueToken(session.account), 0, purpose === undefined ? 1 : Number(purpose) || 1);
|
const token = masterpieces.issueToken(session.account);
|
||||||
|
if (!token) {
|
||||||
|
const why = masterpieces.tooNew(session.account) || "Your Masterpiece could not be sent. Try again later.";
|
||||||
|
session.sendXt("xtl", -1, why.replace(/%/g, " percent"));
|
||||||
|
}
|
||||||
|
reply("tkn", token ? 1 : 0, 0, token || "", 0, purpose === undefined ? 1 : Number(purpose) || 1);
|
||||||
};
|
};
|
||||||
|
|
||||||
// what a game asks of the server while it runs, by game class and then by
|
// 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".
|
// the message's first word. `reply` answers the asker as an "mm".
|
||||||
const MESSAGES = {
|
const MESSAGES = {
|
||||||
|
// These machines do not give an inventory item. They award temporary
|
||||||
|
// Holdable Icons: popcorn (emoticon 1), smoothies (2), and hot cocoa
|
||||||
|
// (5). The final field carries the selected visual state.
|
||||||
|
MicroPopcorn: {
|
||||||
|
_a(session, game, [kind], reply) {
|
||||||
|
if (kind === "1") {
|
||||||
|
grantAttachment(session, game, reply, 1);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MicroSmoothie: {
|
||||||
|
_a(session, game, [kind, colour], reply) {
|
||||||
|
const selected = String(colour || "").toLowerCase();
|
||||||
|
if (kind === "2" && SMOOTHIE_COLOURS.has(selected)) {
|
||||||
|
grantAttachment(session, game, reply, 2, selected);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MicroHotCocoa: {
|
||||||
|
_a(session, game, [kind, cocoaInfo], reply) {
|
||||||
|
if (kind === "5") {
|
||||||
|
grantAttachment(session, game, reply, 5, cocoaInfo);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
CottonCandy: {
|
||||||
|
_a(session, game, [kind, emoticonInfo], reply) {
|
||||||
|
if (kind === "30") {
|
||||||
|
grantAttachment(session, game, reply, 30, emoticonInfo);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
BradyChemistrySet: {
|
||||||
|
_a(session, game, [kind, emoticonInfo], reply) {
|
||||||
|
if (kind === "6") {
|
||||||
|
grantAttachment(session, game, reply, 6, emoticonInfo);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
// the claw machines: "cp" pays for a go and learns whether the claw
|
// the claw machines: "cp" pays for a go and learns whether the claw
|
||||||
// will hold and what on ([won, isDenItem, defId, ?, version]; anything
|
// will hold and what on ([won, isDenItem, defId, ?, version]; anything
|
||||||
// but 1 or 0 for `won` means "not enough gems"); "cd" keeps (1) or
|
// but 1 or 0 for `won` means "not enough gems"); "cd" keeps (1) or
|
||||||
@@ -335,7 +572,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
|||||||
WindRider: {
|
WindRider: {
|
||||||
go() {},
|
go() {},
|
||||||
gw(session, game, params, reply) {
|
gw(session, game, params, reply) {
|
||||||
const ids = defpacks.clothingIds();
|
const ids = defpacks.clothingIds().filter(id => id < customItems.FIRST_ID);
|
||||||
const def = Math.random() < SKY_HIGH_PRIZE_CHANCE ? defpacks.itemDef(ids[Math.floor(Math.random() * ids.length)]) : null;
|
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;
|
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);
|
reply("gw", def ? "1" : "0", def ? def.id : 0, 0, def ? session.gamePrize.color : 0);
|
||||||
@@ -373,6 +610,18 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
|||||||
},
|
},
|
||||||
// the touch pool: the same again, with six prizes; which one is in the
|
// the touch pool: the same again, with six prizes; which one is in the
|
||||||
// first number.
|
// first number.
|
||||||
|
// Spider Zapper, after each wave: "wave" [1 if the player shot enough,
|
||||||
|
// else 0] -> "wavesuccess" (the next wave) or "wavefail" (the end), and
|
||||||
|
// "waveend" [spiders shot] -> "waveend" [spiders shot] (its results).
|
||||||
|
// they went unanswered and the game waited after the first wave.
|
||||||
|
SpiderShooter: {
|
||||||
|
wave(session, game, [passed], reply) {
|
||||||
|
reply(passed === "1" ? "wavesuccess" : "wavefail");
|
||||||
|
},
|
||||||
|
waveend(session, game, [shot], reply) {
|
||||||
|
reply("waveend", /^\d{1,4}$/.test(String(shot)) ? Number(shot) : 0);
|
||||||
|
},
|
||||||
|
},
|
||||||
TouchPool: {
|
TouchPool: {
|
||||||
ts(session, game, params, reply) {
|
ts(session, game, params, reply) {
|
||||||
session.prizeSerial = serial();
|
session.prizeSerial = serial();
|
||||||
@@ -451,7 +700,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
|||||||
},
|
},
|
||||||
|
|
||||||
// MinigameManager.launchGame: [gameDefId, multiplayer, proModeId, ?].
|
// MinigameManager.launchGame: [gameDefId, multiplayer, proModeId, ?].
|
||||||
mj(session, roomId, [gameDefId]) {
|
mj(session, roomId, [gameDefId, multiplayer]) {
|
||||||
leave(session); // a game left without a word, if any
|
leave(session); // a game left without a word, if any
|
||||||
const def = games.get(Number(gameDefId));
|
const def = games.get(Number(gameDefId));
|
||||||
if (!def || def.ready === false || def.buddy || !session.room) {
|
if (!def || def.ready === false || def.buddy || !session.room) {
|
||||||
@@ -461,6 +710,10 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
|||||||
tell(session, "That game is not ready on this server yet.");
|
tell(session, "That game is not ready on this server yet.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (multiplayer === "1" && Object.hasOwn(MULTIPLAYER, def.swf)) {
|
||||||
|
joinLobby(session, def, MULTIPLAYER[def.swf]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
const game = {roomId: nextGameRoomId++, def, players: [session], started: false, ready: new Set()};
|
const game = {roomId: nextGameRoomId++, def, players: [session], started: false, ready: new Set()};
|
||||||
const music = session.room.customMusicDef; // the client takes this from every room join
|
const music = session.room.customMusicDef; // the client takes this from every room join
|
||||||
if (def.type !== IN_ROOM) {
|
if (def.type !== IN_ROOM) {
|
||||||
@@ -490,6 +743,10 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
|||||||
matchMessage(session, game, String(word), params);
|
matchMessage(session, game, String(word), params);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (game.multi && Object.hasOwn(game.multi.relay, String(word))) {
|
||||||
|
relay(session, game, String(word), params);
|
||||||
|
return;
|
||||||
|
}
|
||||||
const reply = (...fields) => session.sendXt("mm", game.roomId, ...fields);
|
const reply = (...fields) => session.sendXt("mm", game.roomId, ...fields);
|
||||||
const own = game.def.tickets ? carnival : MESSAGES[game.def.swf];
|
const own = game.def.tickets ? carnival : MESSAGES[game.def.swf];
|
||||||
if (own && Object.hasOwn(own, word)) {
|
if (own && Object.hasOwn(own, word)) {
|
||||||
@@ -594,13 +851,29 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
|||||||
session.invite = target.invite = {def, sender: session, target};
|
session.invite = target.invite = {def, sender: session, target};
|
||||||
target.sendXt("mp", -1, def.id, 0, session.account.username, 1);
|
target.sendXt("mp", -1, def.id, 0, session.account.username, 1);
|
||||||
},
|
},
|
||||||
// an open challenge to whoever walks up (UserCommXtCommManager.sendCustomPVPMessage); not offered.
|
// a click on another player's game bubble (MinigameXtCommManager
|
||||||
mcp() {},
|
// .sendMinigameCustomPvpJoinMsg): [gameDefId, 0, their username]. the
|
||||||
|
// game starts at once, as an invitation said yes to; a bubble that is
|
||||||
|
// gone by now is answered as an invitation said no to
|
||||||
|
// (MinigameManager.pvpResponse), which puts the clicker back as they were.
|
||||||
|
mcp(session, roomId, [gameDefId, , username]) {
|
||||||
|
const def = games.get(Number(gameDefId));
|
||||||
|
const host = findOnline(String(username || ""));
|
||||||
|
const free = player => player && player.room && !player.game && !player.invite;
|
||||||
|
if (!def || !host || host === session || host.pvpBubble !== def.id || host.room !== session.room
|
||||||
|
|| !free(session) || !free(host) || blocks.either(session.account, host.account)
|
||||||
|
|| !accounts.featureOn(session.account, "gameInvites")) {
|
||||||
|
session.sendXt("mp", -1, def ? def.id : Number(gameDefId) || 0, 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
startMatch(def, host, session);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// the HUD's Games window (GameJoinPopup, generic list 341): the playable
|
// the HUD's Games window (GameJoinPopup, generic list 341): the playable
|
||||||
// games that have a picture for it, by name.
|
// games that have a picture for it, by name. A buddy game's card picture
|
||||||
const library = [...games.values()].filter(game => game.icon && game.ready !== false)
|
// is drawn the same way, and picking one there puts its bubble up.
|
||||||
|
const library = [...games.values()].filter(game => (game.icon || (game.buddy && game.card)) && game.ready !== false)
|
||||||
.sort((one, other) => one.title.localeCompare(other.title)).map(game => game.id);
|
.sort((one, other) => one.title.localeCompare(other.title)).map(game => game.id);
|
||||||
|
|
||||||
// the buddy games' descriptions, sent unasked when a player arrives: a
|
// the buddy games' descriptions, sent unasked when a player arrives: a
|
||||||
@@ -615,6 +888,12 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
|
|||||||
handlers,
|
handlers,
|
||||||
leave,
|
leave,
|
||||||
greet,
|
greet,
|
||||||
|
bubble,
|
||||||
|
showBubble,
|
||||||
|
// out of the room: nobody there is left to see the bubble.
|
||||||
|
roomLeft: session => {
|
||||||
|
session.pvpBubble = null;
|
||||||
|
},
|
||||||
library: () => library,
|
library: () => library,
|
||||||
// the room a player in a room-replacing game came from, for the panel.
|
// the room a player in a room-replacing game came from, for the panel.
|
||||||
playing: session => (session.game ? session.game.def.title : null),
|
playing: session => (session.game ? session.game.def.title : null),
|
||||||
|
|||||||
+130
-1
@@ -4,6 +4,7 @@ const accounts = require("./accounts.js");
|
|||||||
const achievements = require("./achievements.js");
|
const achievements = require("./achievements.js");
|
||||||
const bans = require("./bans.js");
|
const bans = require("./bans.js");
|
||||||
const dens = require("./dens.js");
|
const dens = require("./dens.js");
|
||||||
|
const config = require("../config.js");
|
||||||
const {CURRENCIES} = require("./player.js");
|
const {CURRENCIES} = require("./player.js");
|
||||||
|
|
||||||
// moderation: kick, ban, silence, clear a den, grant gems, message a player.
|
// moderation: kick, ban, silence, clear a den, grant gems, message a player.
|
||||||
@@ -18,6 +19,23 @@ const CURRENCY_GEMS = 0;
|
|||||||
// client says "You earned N ..." in a popup when the amount went up.
|
// client says "You earned N ..." in a popup when the amount went up.
|
||||||
const REASON_ANNOUNCE = 3;
|
const REASON_ANNOUNCE = 3;
|
||||||
|
|
||||||
|
// a warning's reason, and the client's own warning popup for it
|
||||||
|
// (FacilitatorXtCommManager.showContextualWarningPopup, "fw"): its artwork
|
||||||
|
// and its words, which this server's strings already say in its own name.
|
||||||
|
const WARNINGS = {
|
||||||
|
behavior: 4, // "Inappropriate Behavior"
|
||||||
|
bullying: 1, // "Bullying"
|
||||||
|
personal: 3, // "Personal Information"
|
||||||
|
scamming: 9, // "Scamming"
|
||||||
|
// in the staff member's own words: its note is what the player is shown,
|
||||||
|
// in a message box (there is no popup for it), and it cannot be left out.
|
||||||
|
custom: null,
|
||||||
|
};
|
||||||
|
const CUSTOM_WARNING = "custom";
|
||||||
|
const MAX_WARNINGS_KEPT = 100;
|
||||||
|
const MAX_WARNING_NOTE = 200;
|
||||||
|
const SECONDS_PER_DAY = 86400;
|
||||||
|
|
||||||
const now = () => Math.floor(Date.now() / 1000);
|
const now = () => Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
// seconds of ban left, PERMANENT, or 0 when not banned.
|
// seconds of ban left, PERMANENT, or 0 when not banned.
|
||||||
@@ -35,6 +53,21 @@ const banOf = account => {
|
|||||||
return seconds === 0 ? null : {seconds, reason: account.banReason || bans.NO_REASON, by: account.bannedBy || "", since: account.bannedAt || null};
|
return seconds === 0 ? null : {seconds, reason: account.banReason || bans.NO_REASON, by: account.bannedBy || "", since: account.bannedAt || null};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// the warnings an account has had in the last config.warningSilence.days
|
||||||
|
// (all of them when that is 0).
|
||||||
|
const recentWarnings = account => {
|
||||||
|
const days = (config.warningSilence || {}).days || 0;
|
||||||
|
const since = now() - days * SECONDS_PER_DAY;
|
||||||
|
return (account.warnings || []).filter(entry => !days || entry.at >= since).length;
|
||||||
|
};
|
||||||
|
|
||||||
|
// the minutes of silence a warning brings when it is the Nth recent one
|
||||||
|
// (config.warningSilence.steps, [[N, minutes], ...]); 0 for none.
|
||||||
|
const silenceForWarning = count => {
|
||||||
|
const step = ((config.warningSilence || {}).steps || []).find(([warnings]) => warnings === count);
|
||||||
|
return step ? step[1] : 0;
|
||||||
|
};
|
||||||
|
|
||||||
const isSilenced = account => account.silencedUntil === PERMANENT || (account.silencedUntil || 0) > now();
|
const isSilenced = account => account.silencedUntil === PERMANENT || (account.silencedUntil || 0) > now();
|
||||||
|
|
||||||
// seconds of silence left, PERMANENT, or 0 when the account may chat.
|
// seconds of silence left, PERMANENT, or 0 when the account may chat.
|
||||||
@@ -52,6 +85,16 @@ module.exports = ({findOnline}) => {
|
|||||||
|
|
||||||
// A "message from moderator" popup; also used to answer chat commands.
|
// A "message from moderator" popup; also used to answer chat commands.
|
||||||
const notify = (session, text) => discipline(session, "fp", text, 0);
|
const notify = (session, text) => discipline(session, "fp", text, 0);
|
||||||
|
// a warning as the player sees it: the game's popup for its reason, or a
|
||||||
|
// custom one's words.
|
||||||
|
const showWarning = (session, entry) => {
|
||||||
|
if (entry.reason === CUSTOM_WARNING && entry.note) {
|
||||||
|
notify(session, `Warning: ${entry.note}`);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
discipline(session, "fw", WARNINGS[entry.reason] ?? WARNINGS.behavior);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const actions = {
|
const actions = {
|
||||||
kick(target) {
|
kick(target) {
|
||||||
@@ -140,6 +183,34 @@ module.exports = ({findOnline}) => {
|
|||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// every post they wrote on anyone's Jammer Wall (lib/walls.js), their
|
||||||
|
// own included, and the replies to those, as deleting a post in the game
|
||||||
|
// takes its replies. returns {posts, replies, walls}.
|
||||||
|
clearWallPosts(author) {
|
||||||
|
const changed = [];
|
||||||
|
let posts = 0;
|
||||||
|
let replies = 0;
|
||||||
|
for (const owner of accounts.all()) {
|
||||||
|
const {wall} = owner;
|
||||||
|
const gone = new Set(wall.posts.filter(post => post.uid === author.id).map(post => post.x));
|
||||||
|
if (!gone.size) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const kept = wall.posts.filter(post => !gone.has(post.x) && !gone.has(post.pp));
|
||||||
|
posts += gone.size;
|
||||||
|
replies += wall.posts.length - kept.length - gone.size;
|
||||||
|
const left = new Set(kept.map(post => post.x));
|
||||||
|
wall.posts = kept;
|
||||||
|
wall.hidden = wall.hidden.filter(id => left.has(id));
|
||||||
|
wall.modified = Date.now();
|
||||||
|
changed.push(owner);
|
||||||
|
}
|
||||||
|
if (changed.length) {
|
||||||
|
accounts.save(...changed);
|
||||||
|
}
|
||||||
|
return {posts, replies, walls: changed.length};
|
||||||
|
},
|
||||||
|
|
||||||
grantGems(target, amount) {
|
grantGems(target, amount) {
|
||||||
return actions.grantCurrency(target, CURRENCY_GEMS, amount, false);
|
return actions.grantCurrency(target, CURRENCY_GEMS, amount, false);
|
||||||
},
|
},
|
||||||
@@ -171,6 +242,51 @@ module.exports = ({findOnline}) => {
|
|||||||
notify(session, text);
|
notify(session, text);
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// a warning: kept on the account (who, when, why and a note for staff),
|
||||||
|
// and shown with the game's own warning popup: now if they are in a
|
||||||
|
// room, else once they are next (greet). the Nth warning within
|
||||||
|
// config.warningSilence.days may also silence them for a while; a
|
||||||
|
// longer silence already on them is left alone.
|
||||||
|
// returns {count, online, silencedMinutes}, or null for a reason that
|
||||||
|
// is not one (or a custom warning with nothing to say).
|
||||||
|
warn(target, reason, by, note = "") {
|
||||||
|
const text = String(note).trim().slice(0, MAX_WARNING_NOTE);
|
||||||
|
if (!Object.hasOwn(WARNINGS, reason) || (reason === CUSTOM_WARNING && !text)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const session = findOnline(target.username);
|
||||||
|
const seen = Boolean(session && session.greeted);
|
||||||
|
const entry = {at: now(), by, reason, note: text, seen};
|
||||||
|
target.warnings = [...(target.warnings || []), entry].slice(-MAX_WARNINGS_KEPT);
|
||||||
|
accounts.save();
|
||||||
|
if (seen) {
|
||||||
|
showWarning(session, entry);
|
||||||
|
}
|
||||||
|
let silencedMinutes = silenceForWarning(recentWarnings(target));
|
||||||
|
const left = silenceRemaining(target);
|
||||||
|
if (silencedMinutes && left !== PERMANENT && left < silencedMinutes * SECONDS_PER_MINUTE) {
|
||||||
|
actions.silence(target, silencedMinutes * SECONDS_PER_MINUTE);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
silencedMinutes = 0;
|
||||||
|
}
|
||||||
|
return {count: target.warnings.length, online: Boolean(session), silencedMinutes};
|
||||||
|
},
|
||||||
|
|
||||||
|
// takes back their latest warning (one given by mistake). a silence it
|
||||||
|
// brought stays; that is lifted on its own (silence 0). returns the
|
||||||
|
// warning taken back, or null when there is none.
|
||||||
|
unwarn(target) {
|
||||||
|
const list = target.warnings || [];
|
||||||
|
if (!list.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const removed = list[list.length - 1];
|
||||||
|
target.warnings = list.slice(0, -1);
|
||||||
|
accounts.save();
|
||||||
|
return removed;
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// the client's moderator requests, refused whoever sends them. each
|
// the client's moderator requests, refused whoever sends them. each
|
||||||
@@ -178,7 +294,20 @@ module.exports = ({findOnline}) => {
|
|||||||
const refuse = reply => session => session.sendXt(reply, -1, 0);
|
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() {}};
|
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};
|
// the first room has loaded (lib/world.js): a warning given while they
|
||||||
|
// were away is shown now, the latest only (the game has one warning
|
||||||
|
// popup), and all of them count as seen.
|
||||||
|
const greet = session => {
|
||||||
|
const unseen = (session.account.warnings || []).filter(entry => entry.seen === false);
|
||||||
|
if (!unseen.length) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
unseen.forEach(entry => { entry.seen = true; });
|
||||||
|
accounts.save();
|
||||||
|
showWarning(session, unseen[unseen.length - 1]);
|
||||||
|
};
|
||||||
|
|
||||||
|
return {handlers, actions, greet, banRemaining, banOf, isSilenced, silenceRemaining, PERMANENT, WARNINGS: Object.keys(WARNINGS)};
|
||||||
};
|
};
|
||||||
|
|
||||||
Object.assign(module.exports, {isSilenced, banRemaining, banOf});
|
Object.assign(module.exports, {isSilenced, banRemaining, banOf});
|
||||||
+26
-3
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
|
|
||||||
// what each moderator did in the moderator panel (lib/modpanel.js), for
|
// what each moderator did in the moderator panel (lib/modpanel.js), for
|
||||||
@@ -17,15 +18,37 @@ const SCHEMA = `
|
|||||||
`;
|
`;
|
||||||
const MAX_DETAIL = 400;
|
const MAX_DETAIL = 400;
|
||||||
const SHOWN = 300;
|
const SHOWN = 300;
|
||||||
|
const listeners = new Set();
|
||||||
|
|
||||||
const load = () => accounts.database().exec(SCHEMA);
|
const load = () => accounts.database().exec(SCHEMA);
|
||||||
|
|
||||||
const record = (by, action, target = "", detail = "") => {
|
const record = (by, action, target = "", detail = "") => {
|
||||||
|
const entry = {at: Math.floor(Date.now() / 1000), by: String(by), action: String(action), target: String(target), detail: String(detail).slice(0, MAX_DETAIL)};
|
||||||
accounts.database().prepare("INSERT INTO mod_log (at, by, action, target, detail) VALUES (?, ?, ?, ?, ?)")
|
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));
|
.run(entry.at, entry.by, entry.action, entry.target, entry.detail);
|
||||||
console.log(`[mod] ${by}: ${action}${target ? ` "${target}"` : ""}`);
|
console.log(`[mod] ${logText(by)}: ${logText(action)}${logText(target ? ` "${target}"` : "")}`);
|
||||||
|
for (const listener of listeners) {
|
||||||
|
try {
|
||||||
|
listener(entry);
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.error(`[modlog] listener failed: ${logText(err.message)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const recent = () => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log ORDER BY id DESC LIMIT ?").all(SHOWN);
|
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};
|
// what staff did to one player, newest first, for their timeline.
|
||||||
|
const about = username => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log WHERE target = ? COLLATE NOCASE ORDER BY id DESC LIMIT 100")
|
||||||
|
.all(String(username));
|
||||||
|
|
||||||
|
// Optional integrations subscribe here rather than wrapping record(), so an
|
||||||
|
// unavailable Discord channel can never stop a moderation action or its DB
|
||||||
|
// audit record from being written.
|
||||||
|
const onRecord = listener => {
|
||||||
|
listeners.add(listener);
|
||||||
|
return () => listeners.delete(listener);
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {load, record, recent, about, onRecord};
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const crypto = require("crypto");
|
||||||
|
const accounts = require("./accounts.js");
|
||||||
|
|
||||||
|
// moderators' notes on a player: what staff want one another to know about
|
||||||
|
// them ("talked to them about trading, seemed fine"), on the player's page
|
||||||
|
// of the moderator panel and with "!notes" in the game. the player is never
|
||||||
|
// shown them (lib/manage.js leaves them out of their data).
|
||||||
|
//
|
||||||
|
// on an account: modNotes [{id, at, by, text}], the oldest first.
|
||||||
|
|
||||||
|
const MAX_NOTES = 100;
|
||||||
|
const MAX_TEXT = 500;
|
||||||
|
|
||||||
|
const now = () => Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
|
const list = account => [...(account.modNotes || [])].reverse();
|
||||||
|
|
||||||
|
// returns {note} or {error}.
|
||||||
|
const add = (account, by, text) => {
|
||||||
|
const clean = String(text || "").replace(/\s+/g, " ").trim().slice(0, MAX_TEXT);
|
||||||
|
if (!clean) {
|
||||||
|
return {error: "Write the note first."};
|
||||||
|
}
|
||||||
|
const note = {id: crypto.randomBytes(6).toString("hex"), at: now(), by: String(by), text: clean};
|
||||||
|
account.modNotes = [...(account.modNotes || []), note].slice(-MAX_NOTES);
|
||||||
|
accounts.save();
|
||||||
|
return {note};
|
||||||
|
};
|
||||||
|
|
||||||
|
// a note taken away by whoever wrote it, or by someone who may remove anyone's
|
||||||
|
// (`anyone`). returns {note} or {error}.
|
||||||
|
const remove = (account, id, by, anyone) => {
|
||||||
|
const note = (account.modNotes || []).find(entry => entry.id === String(id));
|
||||||
|
if (!note) {
|
||||||
|
return {error: "No such note."};
|
||||||
|
}
|
||||||
|
if (!anyone && note.by.toLowerCase() !== String(by).toLowerCase()) {
|
||||||
|
return {error: "Only whoever wrote a note, or an admin, can remove it."};
|
||||||
|
}
|
||||||
|
account.modNotes = account.modNotes.filter(entry => entry !== note);
|
||||||
|
accounts.save();
|
||||||
|
return {note};
|
||||||
|
};
|
||||||
|
|
||||||
|
// the newest notes on anybody, with whom they are about.
|
||||||
|
const recent = count => accounts.all()
|
||||||
|
.flatMap(account => (account.modNotes || []).map(note => ({...note, about: account.username})))
|
||||||
|
.sort((one, other) => other.at - one.at)
|
||||||
|
.slice(0, count);
|
||||||
|
|
||||||
|
module.exports = {list, add, remove, recent, MAX_TEXT};
|
||||||
+819
-31
File diff suppressed because it is too large.
Load diff
+18
-10
@@ -35,23 +35,31 @@ const stretched = word => /(.)\1\1/.test(word);
|
|||||||
// above. "word" is for a line marked "=": in lib/sexual-names.txt the rest
|
// above. "word" is for a line marked "=": in lib/sexual-names.txt the rest
|
||||||
// are matched anywhere in a name.
|
// are matched anywhere in a name.
|
||||||
const lists = new Map(); // file -> {mtime, entries}
|
const lists = new Map(); // file -> {mtime, entries}
|
||||||
|
// the file is opened once, and its time and its words are both of what was
|
||||||
|
// opened: a list changed in between cannot be read under the old one's time.
|
||||||
const read = file => {
|
const read = file => {
|
||||||
let mtime = 0;
|
let fd;
|
||||||
try {
|
try {
|
||||||
mtime = fs.statSync(file).mtimeMs;
|
fd = fs.openSync(file, "r");
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
const kept = lists.get(file);
|
try {
|
||||||
if (kept && kept.mtime === mtime) {
|
const mtime = fs.fstatSync(fd).mtimeMs;
|
||||||
return kept.entries;
|
const kept = lists.get(file);
|
||||||
|
if (kept && kept.mtime === mtime) {
|
||||||
|
return kept.entries;
|
||||||
|
}
|
||||||
|
const entries = fs.readFileSync(fd, "utf8").split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith("#"))
|
||||||
|
.map(line => ({text: line.replace(/^=/, "").replace(/\*$/, "").split(/\s+/).map(plain).join(""), prefix: line.endsWith("*"), word: line.startsWith("=")}))
|
||||||
|
.filter(entry => entry.text.length >= 2);
|
||||||
|
lists.set(file, {mtime, entries});
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
fs.closeSync(fd);
|
||||||
}
|
}
|
||||||
const entries = fs.readFileSync(file, "utf8").split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith("#"))
|
|
||||||
.map(line => ({text: line.replace(/^=/, "").replace(/\*$/, "").split(/\s+/).map(plain).join(""), prefix: line.endsWith("*"), word: line.startsWith("=")}))
|
|
||||||
.filter(entry => entry.text.length >= 2);
|
|
||||||
lists.set(file, {mtime, entries});
|
|
||||||
return entries;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let epicDens = null;
|
let epicDens = null;
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
{"10":{"type":1033,"count":141,"entries":["9329","0","9326","0","9332","0","9330","0","9331","0","9327","0","9328","0","9167","0","9170","0","9172","0","9174","0","9175","0","9176","0","9013","0","9014","0","9015","0","9016","0","9017","0","4452","0","2702","0","4451","0","2706","0","4453","0","2762","0","2711","0","2716","0","2715","0","2723","0","2697","0","2717","0","4478","0","1250","0","1251","0","1354","0","1426","0","1627","0","5738","0","346","0","86","0","124","0","118","0","2805","0","2806","0","2807","0","2808","0","2809","0","2810","0","2811","0","2812","0","2813","0","2814","0","2815","0","2816","0","2817","0","2818","0","2819","0","2820","0","2821","0","2822","0","2823","0","2824","0","2825","0","2826","0","2827","0","2828","0","1","0","4547","0","4542","0","4544","0","4549","0","4540","0","4548","0","4538","0","4539","0","4541","0","4543","0","4545","0","4546","0","2708","0","4470","0","356","0","5077","0","5078","0","5079","0","2705","0","4457","0","4465","0","2703","0","2709","0","5092","0","5093","0","5094","0","5095","0","4856","0","2712","0","2713","0","2714","0","4477","0","6130","0","6138","0","4777","0","4778","0","4779","0","4780","0","4855","0","5980","0","5981","0","4435","0","4946","0","4460","0","4461","0","4462","0","2707","0","4454","0","5088","0","5089","0","5090","0","5091","0","4455","0","2700","0","1188","0","2704","0","4459","0","4467","0","4468","0","4469","0","4393","0","5073","0","5074","0","5075","0","5076","0","4410","0","5084","0","5085","0","5086","0","5087","0","4466","0","5080","0","5081","0","5082","0","5083","0"]},"16":{"type":1023,"count":50,"entries":["551","552","553","554","555","556","557","564","558","569","559","1831","573","560","578","561","576","562","563","579","565","1841","568","574","566","1845","567","570","577","575","1830","571","1844","1826","572","1835","1839","1832","1843","1829","1827","1842","1828","1846","1838","1833","1840","1836","1837","1834"]},"44":{"type":1033,"count":35,"entries":["13","0","11","0","2889","0","2896","0","1602","0","2886","0","1604","0","12","0","2877","0","2885","0","1603","0","2894","0","10","0","2899","0","2891","0","2876","0","376","0","2878","0","2879","0","2880","0","2881","0","2882","0","2884","0","2888","0","2898","0","2887","0","2890","0","377","0","2892","0","2893","0","2895","0","2900","0","378","0","2901","0","2902","0"]},"53":{"type":1033,"count":14,"entries":["1389","1603","1545","1600","1595","1601","1265","1604","1470","1599","1232","1790","2279","3726","2015","0","7061","18253","1185","912","1192","1571","1186","913","1187","914","6189","0"],"note":"not recorded: the Journey Book's pages, found among the media files by their jb_title parts, and each land's name"},"54":{"type":1035,"count":160,"entries":["634","7044","32198","32199","10","459","0","635","7045","32200","32201","10","459","1","636","7046","32202","32203","10","459","2","637","7047","32204","32205","10","459","3","638","7048","32206","32207","10","459","4","639","7049","32208","32209","10","459","5","640","7050","32210","32211","10","459","6","641","7051","32212","32213","10","459","7","642","7052","32214","32215","10","459","8","643","7053","32216","32217","10","459","9","606","6667","31309","31310","14","457","0","607","6666","31311","31312","14","457","1","608","6668","31313","31314","14","457","2","609","6670","31303","31304","14","457","3","610","6665","31307","31308","14","457","4","611","6669","31305","31306","14","457","5","578","6180","30096","30097","14","456","11","577","6181","30094","30095","14","456","10","576","6187","30092","30093","14","456","9","575","6186","30090","30091","14","456","8","574","6179","30088","30089","14","456","7","573","6178","30086","30087","14","456","6","572","6177","30084","30085","14","456","5","571","6176","30082","30083","14","456","4","570","6183","30080","30081","14","456","3","569","6182","30078","30079","14","456","2","568","6185","30076","30077","14","456","1","567","6184","30074","30075","14","456","0","140","775","812","848","10","289","0","141","777","814","850","10","289","1","142","780","817","853","10","289","2","143","125","808","844","10","289","3","144","776","813","849","10","289","4","145","772","809","845","10","289","5","146","774","811","847","10","289","6","147","778","815","851","10","289","7","148","781","818","854","10","289","8","149","779","816","852","10","289","9","150","773","810","846","10","289","10","151","815","832","868","10","291","0","152","821","840","876","10","291","1","153","817","834","871","10","291","2","154","824","843","883","10","291","3","155","820","839","875","10","291","4","156","819","838","873","10","291","5","157","818","835","872","10","291","6","158","822","841","879","10","291","7","159","823","842","880","10","291","8","160","816","833","869","10","291","9","161","784","821","857","10","290","0","162","786","823","859","10","290","1","163","813","830","866","10","290","2","164","788","825","861","10","290","3","165","783","820","856","10","Line truncated
|
||||||
+467
-53
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const crypto = require("crypto");
|
const crypto = require("crypto");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
@@ -7,17 +8,23 @@ const accounts = require("./accounts.js");
|
|||||||
const achievements = require("./achievements.js");
|
const achievements = require("./achievements.js");
|
||||||
const adopt = require("./adopt.js");
|
const adopt = require("./adopt.js");
|
||||||
const badges = require("./badges.js");
|
const badges = require("./badges.js");
|
||||||
|
const discordLinks = require("./discord.js");
|
||||||
|
const discordBot = require("./discordbot.js");
|
||||||
const bans = require("./bans.js");
|
const bans = require("./bans.js");
|
||||||
const colours = require("./colours.js");
|
const colours = require("./colours.js");
|
||||||
|
const chatlog = require("./chatlog.js");
|
||||||
const config = require("../config.js");
|
const config = require("../config.js");
|
||||||
|
const devices = require("./devices.js");
|
||||||
const defpacks = require("./defpacks.js");
|
const defpacks = require("./defpacks.js");
|
||||||
const limits = require("./limits.js");
|
const limits = require("./limits.js");
|
||||||
const log = require("./log.js");
|
const log = require("./log.js");
|
||||||
const masterpieces = require("./masterpieces.js");
|
const masterpieces = require("./masterpieces.js");
|
||||||
const modlog = require("./modlog.js");
|
const modlog = require("./modlog.js");
|
||||||
const modpanel = require("./modpanel.js");
|
const modpanel = require("./modpanel.js");
|
||||||
|
const playerItems = require("./playeritems.js");
|
||||||
const erase = require("./erase.js");
|
const erase = require("./erase.js");
|
||||||
const reports = require("./reports.js");
|
const reports = require("./reports.js");
|
||||||
|
const roles = require("./roles.js");
|
||||||
const sales = require("./sales.js");
|
const sales = require("./sales.js");
|
||||||
const stats = require("./stats.js");
|
const stats = require("./stats.js");
|
||||||
const staff = require("./staff.js");
|
const staff = require("./staff.js");
|
||||||
@@ -25,6 +32,7 @@ const support = require("./support.js");
|
|||||||
const totp = require("./totp.js");
|
const totp = require("./totp.js");
|
||||||
const manage = require("./manage.js");
|
const manage = require("./manage.js");
|
||||||
const world = require("./world.js");
|
const world = require("./world.js");
|
||||||
|
const codes = require("./codes.js");
|
||||||
const {activeAvatar} = require("./player.js");
|
const {activeAvatar} = require("./player.js");
|
||||||
|
|
||||||
// the admin panel at /admin: the only place the server is administered from.
|
// the admin panel at /admin: the only place the server is administered from.
|
||||||
@@ -37,6 +45,7 @@ const {activeAvatar} = require("./player.js");
|
|||||||
|
|
||||||
const PASSWORD_SETTING = "admin_password"; // "salt:hash"
|
const PASSWORD_SETTING = "admin_password"; // "salt:hash"
|
||||||
const COOKIE = "ajc_admin";
|
const COOKIE = "ajc_admin";
|
||||||
|
const DISCORD_COOKIE = "ajc_admin_discord";
|
||||||
const SESSION_HOURS = 12;
|
const SESSION_HOURS = 12;
|
||||||
const MIN_PASSWORD_LENGTH = 8;
|
const MIN_PASSWORD_LENGTH = 8;
|
||||||
const MAX_PASSWORD_LENGTH = 200;
|
const MAX_PASSWORD_LENGTH = 200;
|
||||||
@@ -47,6 +56,7 @@ const TEN_MINUTES_MS = 600000;
|
|||||||
const DAY_SECONDS = 86400;
|
const DAY_SECONDS = 86400;
|
||||||
const MAX_ANNOUNCEMENT = 300;
|
const MAX_ANNOUNCEMENT = 300;
|
||||||
const MAX_OWNED_LISTED = 300;
|
const MAX_OWNED_LISTED = 300;
|
||||||
|
const MAX_LISTED = 100; // accounts in one search of the Accounts page
|
||||||
// currencies the panel can hand out, as indexes into CURRENCIES.
|
// currencies the panel can hand out, as indexes into CURRENCIES.
|
||||||
const GIFT_CURRENCIES = {gems: 0, tickets: 1, diamonds: 3};
|
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
|
// who a ban is written down as given by. the panel has one password and so
|
||||||
@@ -83,9 +93,14 @@ const passwordAcceptable = password =>
|
|||||||
typeof password === "string" && password.length >= MIN_PASSWORD_LENGTH && password.length <= MAX_PASSWORD_LENGTH;
|
typeof password === "string" && password.length >= MIN_PASSWORD_LENGTH && password.length <= MAX_PASSWORD_LENGTH;
|
||||||
|
|
||||||
const load = () => {
|
const load = () => {
|
||||||
|
// the number of worlds the admin chose last (world.setWorldCount)
|
||||||
|
const worlds = accounts.setting(world.WORLD_COUNT_SETTING);
|
||||||
|
if (worlds !== null) {
|
||||||
|
world.setWorldCount(worlds, false);
|
||||||
|
}
|
||||||
if (!hasPassword()) {
|
if (!hasPassword()) {
|
||||||
setupCode = crypto.randomBytes(5).toString("hex");
|
setupCode = crypto.randomBytes(5).toString("hex");
|
||||||
console.log(`[admin] no admin password yet: open ${config.baseUrl}admin to choose one`
|
console.log(`[admin] no admin password yet: open ${logText(config.baseUrl)}admin to choose one`
|
||||||
+ ` (from another machine it will ask for this setup code: ${setupCode})`);
|
+ ` (from another machine it will ask for this setup code: ${setupCode})`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -105,9 +120,27 @@ const signedIn = req => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const cookieHeader = (token, maxAgeSeconds) =>
|
const cookieHeader = (token, maxAgeSeconds) =>
|
||||||
`${COOKIE}=${token}; Path=/admin; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
|
`${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
|
||||||
|
|
||||||
const signIn = res => {
|
const discordCookie = (value, maxAgeSeconds) =>
|
||||||
|
`${DISCORD_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
|
||||||
|
|
||||||
|
// a Discord sign-in waiting for the 2FA code of the account it is linked
|
||||||
|
// to: SHA-256 of the token in its cookie -> {id, expiry, tries}. Discord
|
||||||
|
// alone does not open this panel, as the password alone does not open the
|
||||||
|
// moderator panel.
|
||||||
|
const pendingDiscord = new Map();
|
||||||
|
const PENDING_COOKIE = "ajc_admin_pending";
|
||||||
|
const PENDING_MINUTES = 5;
|
||||||
|
const PENDING_TRIES = 5;
|
||||||
|
const pendingCookieHeader = (token, maxAgeSeconds) =>
|
||||||
|
`${PENDING_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
|
||||||
|
const pendingToken = req => (new RegExp(`(?:^|;\\s*)${PENDING_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1] || null;
|
||||||
|
// may this account still sign in here with Discord?
|
||||||
|
const discordAdmin = account => Boolean(account && account.adminDashboardAccess && account.discordId && totp.isOn(account) && !account.locked);
|
||||||
|
|
||||||
|
// `extraCookies` go out with the session's own.
|
||||||
|
const signIn = (res, extraCookies = []) => {
|
||||||
for (const [hash, expiry] of sessions) {
|
for (const [hash, expiry] of sessions) {
|
||||||
if (expiry < Date.now()) {
|
if (expiry < Date.now()) {
|
||||||
sessions.delete(hash);
|
sessions.delete(hash);
|
||||||
@@ -115,7 +148,7 @@ const signIn = res => {
|
|||||||
}
|
}
|
||||||
const token = crypto.randomBytes(24).toString("hex");
|
const token = crypto.randomBytes(24).toString("hex");
|
||||||
sessions.set(sha256(token), Date.now() + SESSION_HOURS * 3600000);
|
sessions.set(sha256(token), Date.now() + SESSION_HOURS * 3600000);
|
||||||
res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600));
|
res.setHeader("Set-Cookie", [cookieHeader(token, SESSION_HOURS * 3600), ...extraCookies]);
|
||||||
};
|
};
|
||||||
|
|
||||||
const signOut = (req, res) => {
|
const signOut = (req, res) => {
|
||||||
@@ -137,6 +170,8 @@ const accountRow = (account, playing) => {
|
|||||||
locked: account.locked,
|
locked: account.locked,
|
||||||
twoStep: totp.isOn(account),
|
twoStep: totp.isOn(account),
|
||||||
discord: account.discord,
|
discord: account.discord,
|
||||||
|
adminDashboardAccess: Boolean(account.adminDashboardAccess),
|
||||||
|
guide: account.guideGiven === true,
|
||||||
bio: account.bio,
|
bio: account.bio,
|
||||||
badges: account.badges,
|
badges: account.badges,
|
||||||
featuresOff: accounts.FEATURES.filter(name => !accounts.featureOn(account, name)),
|
featuresOff: accounts.FEATURES.filter(name => !accounts.featureOn(account, name)),
|
||||||
@@ -148,13 +183,22 @@ const accountRow = (account, playing) => {
|
|||||||
// seconds left, -1 for permanent, 0 for not banned
|
// seconds left, -1 for permanent, 0 for not banned
|
||||||
banned: ban,
|
banned: ban,
|
||||||
banReason: ban === 0 ? "" : account.banReason || bans.NO_REASON,
|
banReason: ban === 0 ? "" : account.banReason || bans.NO_REASON,
|
||||||
moderator: Boolean(account.moderator),
|
moderator: Boolean(roles.roleOf(account)),
|
||||||
|
role: roles.roleOf(account),
|
||||||
|
// what they may do (their role's, with their own grants and denies)
|
||||||
|
permissions: roles.permissionsOf(account),
|
||||||
|
permGrants: account.permGrants || [],
|
||||||
|
permDenies: account.permDenies || [],
|
||||||
nameRejected: Boolean(account.nameRejected),
|
nameRejected: Boolean(account.nameRejected),
|
||||||
silenced: world.moderation.isSilenced(account),
|
silenced: world.moderation.isSilenced(account),
|
||||||
animals: account.avatars.length,
|
animals: account.avatars.length,
|
||||||
level: activeAvatar(account).questLevel || 0,
|
level: activeAvatar(account).questLevel || 0,
|
||||||
items: account.items.length + account.denItems.length,
|
items: account.items.length + account.denItems.length,
|
||||||
gems: account.currency.gems || 0,
|
gems: account.currency.gems || 0,
|
||||||
|
deviceBanned: devices.bannedId(account) !== 0,
|
||||||
|
devicesKnown: devices.knownFor(account).ids,
|
||||||
|
stoppedThisWeek: chatlog.notSentCount(account, 7),
|
||||||
|
paintings: masterpieces.madeBy(account).length,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -262,6 +306,12 @@ const ROOM_GROUP_NOTES = {
|
|||||||
adventures: "adventure maps; nothing in them moves",
|
adventures: "adventure maps; nothing in them moves",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// the theatre's browser (experimental; the server's game.html and client
|
||||||
|
// 1.3.3): off unless the admin turns it on. what players see in it never
|
||||||
|
// reaches the server; this only says whether the game offers it.
|
||||||
|
const THEATRE_BROWSER_SETTING = "theatreBrowser";
|
||||||
|
const theatreBrowserOn = () => accounts.setting(THEATRE_BROWSER_SETTING) === "on";
|
||||||
|
|
||||||
const debugState = () => ({
|
const debugState = () => ({
|
||||||
players: world.players().map(player => player.username).sort((a, b) => a.localeCompare(b)),
|
players: world.players().map(player => player.username).sort((a, b) => a.localeCompare(b)),
|
||||||
rooms: defpacks.roomPaths().map(roomPath => {
|
rooms: defpacks.roomPaths().map(roomPath => {
|
||||||
@@ -269,6 +319,9 @@ const debugState = () => ({
|
|||||||
return {path: roomPath, group, note: ROOM_NOTES[roomPath] || ROOM_GROUP_NOTES[group] || ""};
|
return {path: roomPath, group, note: ROOM_NOTES[roomPath] || ROOM_GROUP_NOTES[group] || ""};
|
||||||
}).sort((a, b) => a.path.localeCompare(b.path)),
|
}).sort((a, b) => a.path.localeCompare(b.path)),
|
||||||
everythingOnSale: sales.everythingOnSale(),
|
everythingOnSale: sales.everythingOnSale(),
|
||||||
|
theatreBrowser: theatreBrowserOn(),
|
||||||
|
worlds: config.shards.length,
|
||||||
|
maxWorlds: config.worldNames.length,
|
||||||
});
|
});
|
||||||
|
|
||||||
const debugAct = body => {
|
const debugAct = body => {
|
||||||
@@ -286,6 +339,17 @@ const debugAct = body => {
|
|||||||
? "Sale dates are off: every item shows, for players who start the game from now on."
|
? "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."};
|
: "Sale dates are back on, for players who start the game from now on."};
|
||||||
}
|
}
|
||||||
|
if (body.action === "worlds") {
|
||||||
|
const count = world.setWorldCount(body.count);
|
||||||
|
return count ? {ok: `${count} ${count === 1 ? "world" : "worlds"}: ${config.shards.map(shard => shard.name).join(", ")}.`}
|
||||||
|
: {error: "A number of worlds, please."};
|
||||||
|
}
|
||||||
|
if (body.action === "theatreBrowser") {
|
||||||
|
accounts.setSetting(THEATRE_BROWSER_SETTING, body.on === true ? "on" : "off");
|
||||||
|
return {ok: body.on === true
|
||||||
|
? "The theatre browser is on, for players on client 1.3.3 or newer once their game page loads again."
|
||||||
|
: "The theatre browser is off, once players' game pages load again."};
|
||||||
|
}
|
||||||
return {error: "Unknown debug action."};
|
return {error: "Unknown debug action."};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -361,6 +425,13 @@ const gift = (account, body) => {
|
|||||||
|
|
||||||
const MAX_QUEST_LEVEL = 100;
|
const MAX_QUEST_LEVEL = 100;
|
||||||
|
|
||||||
|
// a password for a player who lost theirs: read out or pasted to them, so
|
||||||
|
// nothing that looks like something else (0 O, 1 l I).
|
||||||
|
const TEMP_PASSWORD_LETTERS = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
|
||||||
|
const TEMP_PASSWORD_LENGTH = 12;
|
||||||
|
const randomPassword = () => Array.from({length: TEMP_PASSWORD_LENGTH},
|
||||||
|
() => TEMP_PASSWORD_LETTERS[crypto.randomInt(TEMP_PASSWORD_LETTERS.length)]).join("");
|
||||||
|
|
||||||
const wholeNumber = (value, min, max) => (Number.isInteger(value) && value >= min && value <= max ? value : null);
|
const wholeNumber = (value, min, max) => (Number.isInteger(value) && value >= min && value <= max ? value : null);
|
||||||
|
|
||||||
// returns {ok: text} or {error: text}.
|
// returns {ok: text} or {error: text}.
|
||||||
@@ -368,30 +439,12 @@ const act = (account, body) => {
|
|||||||
const {actions, PERMANENT} = world.moderation;
|
const {actions, PERMANENT} = world.moderation;
|
||||||
const name = account.username;
|
const name = account.username;
|
||||||
switch (body.action) {
|
switch (body.action) {
|
||||||
case "password": {
|
|
||||||
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
|
// the owner locks and unlocks on the account page; this is for when
|
||||||
// they cannot.
|
// they cannot.
|
||||||
case "unlock":
|
case "unlock":
|
||||||
account.locked = false;
|
account.locked = false;
|
||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
return {ok: `${name} is unlocked.`};
|
return {ok: `${name} is unlocked.`};
|
||||||
// for a player who lost their phone and their recovery codes: their
|
|
||||||
// password alone signs them in again.
|
|
||||||
case "twoStepOff":
|
|
||||||
if (!totp.isOn(account)) {
|
|
||||||
return {error: `${name} does not use 2FA.`};
|
|
||||||
}
|
|
||||||
totp.turnOff(account);
|
|
||||||
accounts.save(account);
|
|
||||||
return {ok: `2FA is off for ${name}.`};
|
|
||||||
case "rename": {
|
case "rename": {
|
||||||
world.disconnect(account);
|
world.disconnect(account);
|
||||||
manage.forget(account);
|
manage.forget(account);
|
||||||
@@ -435,16 +488,13 @@ const act = (account, body) => {
|
|||||||
world.checkNameTag(account);
|
world.checkNameTag(account);
|
||||||
return {ok: account.badges.length ? `${name} has: ${badges.of(account).map(badge => badge.label).join(", ")}.` : `${name} has no badges.`};
|
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
|
// their linked Discord account (lib/discord.js), taken off.
|
||||||
// page; empty takes it off.
|
|
||||||
case "discord": {
|
case "discord": {
|
||||||
const discord = badges.discordName(body.name);
|
// only taken off: a player links their own (lib/discord.js)
|
||||||
if (discord === null) {
|
if (String(body.name || "") !== "") {
|
||||||
return {error: "Not a Discord username."};
|
return {error: "Players link their Discord themselves, on the account page."};
|
||||||
}
|
}
|
||||||
account.discord = discord;
|
return discordLinks.unlink(account) ? {ok: "Discord unlinked."} : {error: `${name} has no Discord linked.`};
|
||||||
accounts.save(account);
|
|
||||||
return {ok: discord ? `Discord set to "${discord}".` : "Discord cleared."};
|
|
||||||
}
|
}
|
||||||
// their bio, which they otherwise write on the account page; empty
|
// their bio, which they otherwise write on the account page; empty
|
||||||
// takes it off.
|
// takes it off.
|
||||||
@@ -477,6 +527,11 @@ const act = (account, body) => {
|
|||||||
return {ok: `${name} is no longer banned.`};
|
return {ok: `${name} is no longer banned.`};
|
||||||
case "kick":
|
case "kick":
|
||||||
return actions.kick(account) ? {ok: `${name} was disconnected.`} : {error: `${name} is not online.`};
|
return actions.kick(account) ? {ok: `${name} was disconnected.`} : {error: `${name} is not online.`};
|
||||||
|
// every computer they signed in from lately (lib/devices.js).
|
||||||
|
case "banDevices":
|
||||||
|
return staff.banDevices(account, body.reason, BY);
|
||||||
|
case "unbanDevices":
|
||||||
|
return staff.unbanDevicesOf(account, BY);
|
||||||
// counted in hours; the game's own notice counts minutes.
|
// counted in hours; the game's own notice counts minutes.
|
||||||
case "silence": {
|
case "silence": {
|
||||||
const hours = wholeNumber(body.hours, 0, MAX_BAN_HOURS);
|
const hours = wholeNumber(body.hours, 0, MAX_BAN_HOURS);
|
||||||
@@ -488,18 +543,87 @@ const act = (account, body) => {
|
|||||||
}
|
}
|
||||||
// A moderator may use the moderator panel (lib/modpanel.js), with this
|
// A moderator may use the moderator panel (lib/modpanel.js), with this
|
||||||
// account's password and its 2FA, which it has to have.
|
// account's password and its 2FA, which it has to have.
|
||||||
|
// (the older on/off switch; "role" below is the full one.)
|
||||||
case "moderator":
|
case "moderator":
|
||||||
if (body.on === true) {
|
roles.setRole(account, body.on === true ? "moderator" : null);
|
||||||
account.moderator = true;
|
if (body.on !== true) {
|
||||||
}
|
|
||||||
else {
|
|
||||||
delete account.moderator;
|
|
||||||
modpanel.forget(account);
|
modpanel.forget(account);
|
||||||
}
|
}
|
||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
return {ok: body.on === true
|
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 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.`};
|
: `${name} is no longer a moderator.`};
|
||||||
|
// A staff role (lib/roles.js): helper, moderator, admin, or none. What
|
||||||
|
// each allows is listed under "GET /admin/api/roles".
|
||||||
|
case "role": {
|
||||||
|
const role = body.role === null || body.role === "" || body.role === "none" ? null : String(body.role);
|
||||||
|
if (!roles.setRole(account, role)) {
|
||||||
|
return {error: `No such role. Roles: ${Object.keys(roles.ROLES).join(", ")}, or none.`};
|
||||||
|
}
|
||||||
|
if (role === null) {
|
||||||
|
modpanel.forget(account);
|
||||||
|
}
|
||||||
|
accounts.save();
|
||||||
|
world.refreshStaff(account);
|
||||||
|
if (role === null) {
|
||||||
|
return {ok: `${name} has no staff role.`};
|
||||||
|
}
|
||||||
|
const label = roles.ROLES[role].label.toLowerCase();
|
||||||
|
return {ok: `${name} is now ${/^[aeiou]/.test(label) ? "an" : "a"} ${label}.${totp.isOn(account) ? "" : " They have no 2FA yet, so their role does nothing until they turn it on."}`};
|
||||||
|
}
|
||||||
|
// one staff member's own permissions, beyond their role's or taken from
|
||||||
|
// it ({grants: [...], denies: [...]}).
|
||||||
|
case "permissions": {
|
||||||
|
if (!roles.roleOf(account)) {
|
||||||
|
return {error: `${name} has no staff role: give them one first.`};
|
||||||
|
}
|
||||||
|
roles.setAccountPermissions(account, body.grants, body.denies);
|
||||||
|
accounts.save();
|
||||||
|
world.refreshStaff(account);
|
||||||
|
modlog.record("admin", "permissions changed", account.username,
|
||||||
|
`+${(account.permGrants || []).join(",") || "none"} -${(account.permDenies || []).join(",") || "none"}`);
|
||||||
|
return {ok: `${name}'s permissions are saved.`};
|
||||||
|
}
|
||||||
|
// guide: lets the player log in as one (lib/accounts.js setLoginChoices).
|
||||||
|
// it shows from their next login.
|
||||||
|
// lost access: a new random password, shown here once. it signs them out
|
||||||
|
// everywhere (lib/accounts.js setPassword); with `twoStepOff` their 2FA
|
||||||
|
// goes as well, for a lost authenticator.
|
||||||
|
case "tempPassword": {
|
||||||
|
let password = randomPassword();
|
||||||
|
// the account rules want a capital, a small letter and a digit, and no
|
||||||
|
// common word or the username in it: draw again until it has them.
|
||||||
|
while (accounts.setPassword(account, password)) {
|
||||||
|
password = randomPassword();
|
||||||
|
}
|
||||||
|
const twoStepOff = body.twoStepOff === true && totp.isOn(account);
|
||||||
|
if (twoStepOff) {
|
||||||
|
totp.turnOff(account);
|
||||||
|
}
|
||||||
|
accounts.save(account);
|
||||||
|
world.disconnect(account);
|
||||||
|
manage.forget(account);
|
||||||
|
modpanel.forget(account);
|
||||||
|
modlog.record("admin", "temporary password set", account.username, twoStepOff ? "2FA turned off" : "");
|
||||||
|
return {ok: `${name}'s password is now ${password}${twoStepOff ? " and their 2FA is off" : ""}. Ask them to change it on their account page.`, password};
|
||||||
|
}
|
||||||
|
case "guide": {
|
||||||
|
const on = body.on === true;
|
||||||
|
account.guideGiven = on;
|
||||||
|
accounts.save(account);
|
||||||
|
modlog.record("admin", on ? "made a guide" : "no longer a guide", account.username, "");
|
||||||
|
return {ok: on ? `${name} is a guide from their next login.` : `${name} is no longer a guide from their next login.`};
|
||||||
|
}
|
||||||
|
case "adminDashboardAccess": {
|
||||||
|
const on = body.on === true;
|
||||||
|
if (on && !account.discordId) {
|
||||||
|
return {error: `${name} must link their Discord account before it can be allowed.`};
|
||||||
|
}
|
||||||
|
account.adminDashboardAccess = on;
|
||||||
|
accounts.save(account);
|
||||||
|
modlog.record("admin", on ? "admin dashboard access given" : "admin dashboard access removed", account.username, account.discord || "");
|
||||||
|
return {ok: on ? `${name} may now sign in to this dashboard with their linked Discord account.` : `${name}'s Discord dashboard access was removed.`};
|
||||||
|
}
|
||||||
case "rejectName":
|
case "rejectName":
|
||||||
actions.rejectName(account, BY);
|
actions.rejectName(account, BY);
|
||||||
manage.forget(account);
|
manage.forget(account);
|
||||||
@@ -521,6 +645,15 @@ const act = (account, body) => {
|
|||||||
case "clearDen":
|
case "clearDen":
|
||||||
actions.clearDen(account);
|
actions.clearDen(account);
|
||||||
return {ok: `Everything in ${name}'s den went back to their inventory.`};
|
return {ok: `Everything in ${name}'s den went back to their inventory.`};
|
||||||
|
case "clearWallPosts": {
|
||||||
|
const {posts, replies, walls} = actions.clearWallPosts(account);
|
||||||
|
if (!posts) {
|
||||||
|
return {error: `${name} has no posts on any Jammer Wall.`};
|
||||||
|
}
|
||||||
|
const text = `${posts} wall ${posts === 1 ? "post" : "posts"} by ${name} removed from ${walls} ${walls === 1 ? "wall" : "walls"}`
|
||||||
|
+ `${replies ? ` (with ${replies} ${replies === 1 ? "reply" : "replies"} to them)` : ""}.`;
|
||||||
|
return {ok: text, detail: `${posts} posts, ${replies} replies, ${walls} walls`};
|
||||||
|
}
|
||||||
case "gems": {
|
case "gems": {
|
||||||
const amount = wholeNumber(body.amount, -MAX_GEMS, MAX_GEMS);
|
const amount = wholeNumber(body.amount, -MAX_GEMS, MAX_GEMS);
|
||||||
if (amount === null) {
|
if (amount === null) {
|
||||||
@@ -547,7 +680,7 @@ const PAGE_HEADERS = {
|
|||||||
"X-Frame-Options": "DENY",
|
"X-Frame-Options": "DENY",
|
||||||
"X-Content-Type-Options": "nosniff",
|
"X-Content-Type-Options": "nosniff",
|
||||||
"Referrer-Policy": "no-referrer",
|
"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'; "
|
"Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; media-src 'self'; font-src 'self'; "
|
||||||
+ "form-action 'none'; frame-ancestors 'none'; base-uri 'none'",
|
+ "form-action 'none'; frame-ancestors 'none'; base-uri 'none'",
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -569,6 +702,46 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
web.send(res, 200, await stats.withView(await fs.promises.readFile(path.join(config.publicDir, "admin.html"))), "text/html; charset=utf-8");
|
web.send(res, 200, await stats.withView(await fs.promises.readFile(path.join(config.publicDir, "admin.html"))), "text/html; charset=utf-8");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// Discord redirects do not carry the normal Strict admin cookie, so their
|
||||||
|
// own short-lived nonce cookie is Lax and scoped to this callback alone.
|
||||||
|
if (route === "GET /admin/discord/login") {
|
||||||
|
if (!hasPassword() || !discordLinks.linking()) {
|
||||||
|
res.writeHead(302, {Location: "/dashboard/admin?discord=off"});
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const {url: to, nonce} = discordLinks.startAdmin();
|
||||||
|
res.setHeader("Set-Cookie", discordCookie(nonce, 600));
|
||||||
|
res.writeHead(302, {Location: to});
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (route === "GET /admin/discord/callback") {
|
||||||
|
const nonce = (new RegExp(`(?:^|;\\s*)${DISCORD_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1];
|
||||||
|
const result = url.searchParams.get("error") ? {error: "cancelled"}
|
||||||
|
: await discordLinks.finishAdmin(url.searchParams.get("state"), nonce, url.searchParams.get("code"));
|
||||||
|
// Discord has said who this is; the panel opens once that account's 2FA
|
||||||
|
// code is given too (POST /admin/api/discord/code).
|
||||||
|
if (result.ok && !discordAdmin(result.account)) {
|
||||||
|
result.ok = false;
|
||||||
|
result.error = totp.isOn(result.account) ? "denied" : "twostep";
|
||||||
|
}
|
||||||
|
const cookies = [discordCookie("", 0)];
|
||||||
|
if (result.ok) {
|
||||||
|
for (const [hash, pending] of pendingDiscord) {
|
||||||
|
if (pending.expiry < Date.now()) {
|
||||||
|
pendingDiscord.delete(hash);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const token = crypto.randomBytes(24).toString("hex");
|
||||||
|
pendingDiscord.set(sha256(token), {id: result.account.id, expiry: Date.now() + PENDING_MINUTES * 60000, tries: 0});
|
||||||
|
cookies.push(pendingCookieHeader(token, PENDING_MINUTES * 60));
|
||||||
|
}
|
||||||
|
res.setHeader("Set-Cookie", cookies);
|
||||||
|
res.writeHead(302, {Location: `/dashboard/admin?discord=${result.ok ? "code" : result.error}`});
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (req.method === "POST" && !sameOrigin(req)) {
|
if (req.method === "POST" && !sameOrigin(req)) {
|
||||||
reply(403, {error: "forbidden"});
|
reply(403, {error: "forbidden"});
|
||||||
return;
|
return;
|
||||||
@@ -577,7 +750,7 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
|
|
||||||
switch (route) {
|
switch (route) {
|
||||||
case "GET /admin/api/state":
|
case "GET /admin/api/state":
|
||||||
reply(200, {needsSetup: !hasPassword(), needsSetupCode: !from.local, signedIn: signedIn(req)});
|
reply(200, {needsSetup: !hasPassword(), needsSetupCode: !from.local, signedIn: signedIn(req), discordLogin: discordLinks.linking()});
|
||||||
return;
|
return;
|
||||||
|
|
||||||
// choosing the first password. whoever is at the server's own machine may;
|
// choosing the first password. whoever is at the server's own machine may;
|
||||||
@@ -604,7 +777,7 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
}
|
}
|
||||||
storePassword(body.password);
|
storePassword(body.password);
|
||||||
setupCode = null;
|
setupCode = null;
|
||||||
console.log(`[admin] admin password chosen from ${from.address}`);
|
console.log(`[admin] admin password chosen from ${logText(from.address)}`);
|
||||||
signIn(res);
|
signIn(res);
|
||||||
reply(200, {ok: true});
|
reply(200, {ok: true});
|
||||||
return;
|
return;
|
||||||
@@ -617,16 +790,54 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
}
|
}
|
||||||
if (!hasPassword() || !passwordMatches(body.password)) {
|
if (!hasPassword() || !passwordMatches(body.password)) {
|
||||||
recordFailure(from.key);
|
recordFailure(from.key);
|
||||||
console.log(`[admin] failed sign-in from ${from.address}`);
|
console.log(`[admin] failed sign-in from ${logText(from.address)}`);
|
||||||
reply(401, {error: "Wrong password."});
|
reply(401, {error: "Wrong password."});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
console.log(`[admin] signed in from ${from.address}`);
|
console.log(`[admin] signed in from ${logText(from.address)}`);
|
||||||
signIn(res);
|
signIn(res);
|
||||||
reply(200, {ok: true});
|
reply(200, {ok: true});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the second half of a Discord sign-in: the linked account's 2FA code.
|
||||||
|
case "POST /admin/api/discord/code": {
|
||||||
|
if (tooManyFailures(from.key)) {
|
||||||
|
reply(429, {error: "Too many attempts. Try again in a few minutes."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const token = pendingToken(req);
|
||||||
|
const hash = token ? sha256(token) : null;
|
||||||
|
const pending = hash ? pendingDiscord.get(hash) : null;
|
||||||
|
const account = pending && pending.expiry > Date.now() ? accounts.byId(pending.id) : null;
|
||||||
|
if (!discordAdmin(account)) {
|
||||||
|
if (hash) {
|
||||||
|
pendingDiscord.delete(hash);
|
||||||
|
}
|
||||||
|
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
|
||||||
|
reply(401, {error: "The Discord sign-in expired. Sign in with Discord again.", expired: true});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!totp.verify(account, String(body.code || ""))) {
|
||||||
|
recordFailure(from.key);
|
||||||
|
console.log(`[admin] wrong 2FA code after Discord for ${logText(account.username)} from ${logText(from.address)}`);
|
||||||
|
pending.tries++;
|
||||||
|
if (pending.tries >= PENDING_TRIES) {
|
||||||
|
pendingDiscord.delete(hash);
|
||||||
|
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
|
||||||
|
reply(401, {error: "Too many wrong codes. Sign in with Discord again.", expired: true});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
reply(401, {error: "Wrong code."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pendingDiscord.delete(hash);
|
||||||
|
signIn(res, [pendingCookieHeader("", 0)]);
|
||||||
|
console.log(`[admin] ${logText(account.username)} signed in with Discord and a code from ${logText(from.address)}`);
|
||||||
|
reply(200, {ok: true});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
case "POST /admin/api/logout":
|
case "POST /admin/api/logout":
|
||||||
signOut(req, res);
|
signOut(req, res);
|
||||||
reply(200, {ok: true});
|
reply(200, {ok: true});
|
||||||
@@ -638,14 +849,121 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// what players made that waits (the moderator panel's Review), and the
|
||||||
|
// admin's switches for the Item Maker: {enabled, approval}.
|
||||||
|
if (url.pathname === "/admin/api/review" || url.pathname === "/admin/api/item-switches") {
|
||||||
|
const done = (result, action, target = "", detail = "") => {
|
||||||
|
if (result.ok) {
|
||||||
|
modlog.record("admin", action, target, result.detail || detail);
|
||||||
|
}
|
||||||
|
reply(result.ok ? 200 : 400, result.ok ? {ok: result.ok} : {error: result.error});
|
||||||
|
};
|
||||||
|
if (route === "POST /admin/api/item-switches") {
|
||||||
|
const flag = value => (value === undefined ? undefined : value === true);
|
||||||
|
playerItems.setSwitches({enabled: flag(body.enabled), approval: flag(body.approval), artApproval: flag(body.artApproval)});
|
||||||
|
const pictures = playerItems.pictureWaits() ? "pictures wait for a moderator" : "pictures are shown at once";
|
||||||
|
done({ok: `The Item Maker is ${playerItems.enabled() ? "on" : "off"}; new items ${playerItems.approvalOn() ? "wait for a moderator first" : "are in the game at once"}; ${pictures}.`},
|
||||||
|
"item maker settings", "", `${playerItems.enabled() ? "on" : "off"}, approval ${playerItems.approvalOn() ? "on" : "off"}, pictures ${playerItems.pictureWaits() ? "wait" : "at once"}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
modpanel.reviewRoutes(route.replace(" /admin/api/", " "), body, reply, done, "admin", "/admin/api/itemart");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// custom items (lib/customitems.js): the moderator panel's pages, the
|
||||||
|
// admin written down as "admin", and free to take from anyone.
|
||||||
|
if (url.pathname.startsWith("/admin/api/items")) {
|
||||||
|
const done = (result, action, target = "", detail = "") => {
|
||||||
|
if (result.ok) {
|
||||||
|
modlog.record("admin", action, target, result.detail || detail);
|
||||||
|
}
|
||||||
|
reply(result.ok ? 200 : 400, result.ok ? {ok: result.ok} : {error: result.error});
|
||||||
|
};
|
||||||
|
modpanel.itemRoutes(route.replace(" /admin/api/", " "), url, body, reply, done, {username: "admin", artBase: "/admin/api/itemart", mayTake: () => true});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
switch (route) {
|
switch (route) {
|
||||||
case "GET /admin/api/overview":
|
case "GET /admin/api/overview":
|
||||||
reply(200, overview());
|
reply(200, overview());
|
||||||
return;
|
return;
|
||||||
|
|
||||||
|
case "GET /admin/api/discord":
|
||||||
|
reply(200, discordBot.dashboardStatus());
|
||||||
|
return;
|
||||||
|
|
||||||
|
case "POST /admin/api/discord/status": {
|
||||||
|
const statusCard = discordBot.setStatusSettings({title: body.title, note: body.note, banner: body.banner});
|
||||||
|
if (statusCard.error) {
|
||||||
|
reply(400, {error: statusCard.error});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
modlog.record("admin", "Discord public status card changed", "", `title: ${statusCard.title}, banner: ${statusCard.banner || "none"}`);
|
||||||
|
reply(200, {ok: "Status-card text saved. Use Publish now to update Discord.", statusCard});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "POST /admin/api/discord/status/publish": {
|
||||||
|
const result = await discordBot.publishStatus();
|
||||||
|
if (result.ok) {
|
||||||
|
modlog.record("admin", "Discord public status card published");
|
||||||
|
}
|
||||||
|
reply(result.ok ? 200 : 400, result);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "POST /admin/api/discord/config": {
|
||||||
|
const result = discordBot.updateDashboardConfig(body);
|
||||||
|
if (result.ok) {
|
||||||
|
modlog.record("admin", "Discord bot routing settings changed");
|
||||||
|
}
|
||||||
|
reply(result.ok ? 200 : 400, result);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "POST /admin/api/discord/security": {
|
||||||
|
const result = discordBot.updateSecuritySettings(body);
|
||||||
|
if (result.ok) {
|
||||||
|
modlog.record("admin", "Discord security settings changed");
|
||||||
|
}
|
||||||
|
reply(result.ok ? 200 : 400, result);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "POST /admin/api/discord/community": {
|
||||||
|
const result = discordBot.updateCommunitySettings(body);
|
||||||
|
if (result.ok) modlog.record("admin", "Discord community and ticket settings changed");
|
||||||
|
reply(result.ok ? 200 : 400, result);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "POST /admin/api/discord/control": {
|
||||||
|
const action = String(body.action || "");
|
||||||
|
const result = await discordBot.control(action);
|
||||||
|
if (result.ok) {
|
||||||
|
modlog.record("admin", `Discord bot ${action}`);
|
||||||
|
}
|
||||||
|
reply(result.ok ? 200 : 400, result);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a page of accounts by name (lib/staff.js says in what order), never
|
||||||
|
// all of them: with thousands, sending every one every few seconds
|
||||||
|
// slowed the page and the game alike.
|
||||||
case "GET /admin/api/accounts": {
|
case "GET /admin/api/accounts": {
|
||||||
const playing = new Map(world.players().map(player => [player.username, player.room || "(between rooms)"]));
|
const playing = new Map(world.players().map(player => [player.username, player.room || "(between rooms)"]));
|
||||||
reply(200, {accounts: accounts.all().map(account => accountRow(account, playing)), badges: badges.BADGES});
|
const filter = url.searchParams.get("filter");
|
||||||
|
const keep = filter === "online" ? (account, online) => online.has(account.username)
|
||||||
|
: filter === "banned" ? account => world.moderation.banRemaining(account) !== 0 : () => true;
|
||||||
|
const {found, total} = staff.findAccounts(url.searchParams.get("q"), keep, MAX_LISTED);
|
||||||
|
reply(200, {accounts: found.map(account => accountRow(account, playing)), total, badges: badges.BADGES});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// one account's row, for the one that is open whatever the list shows.
|
||||||
|
case "GET /admin/api/account": {
|
||||||
|
const account = accounts.byName(url.searchParams.get("username") || "");
|
||||||
|
const playing = new Map(world.players().map(player => [player.username, player.room || "(between rooms)"]));
|
||||||
|
reply(account ? 200 : 404, account ? {account: accountRow(account, playing), badges: badges.BADGES} : {error: "No such account."});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -660,6 +978,28 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
reply(found.error ? 400 : 200, found);
|
reply(found.error ? 400 : 200, found);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// who signed in from a computer, by one of its ids or the start of one.
|
||||||
|
case "GET /admin/api/device-search": {
|
||||||
|
const found = staff.byDevice(url.searchParams.get("q"));
|
||||||
|
reply(found.error ? 400 : 200, found.error ? found : {players: found.players.map(entry => ({...entry,
|
||||||
|
online: Boolean(world.findOnline(entry.username))}))});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// what players typed, sent and posted (lib/chatlog.js), as the moderators see it.
|
||||||
|
case "GET /admin/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), kind: params.get("kind") || "", direction: params.get("direction") || "", until: Number(params.get("until")) || 0,
|
||||||
|
before: Number(params.get("before")) || 0});
|
||||||
|
reply(200, {lines, more: lines.length === chatlog.PAGE, days: config.chatLogDays});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case "GET /admin/api/chat/around": {
|
||||||
|
const found = chatlog.around(url.searchParams.get("id"));
|
||||||
|
reply(found ? 200 : 404, found || {error: "No such line."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
case "GET /admin/api/logs": {
|
case "GET /admin/api/logs": {
|
||||||
const lines = log.recent(Number(url.searchParams.get("after")) || 0, (url.searchParams.get("filter") || "").slice(0, 100));
|
const lines = log.recent(Number(url.searchParams.get("after")) || 0, (url.searchParams.get("filter") || "").slice(0, 100));
|
||||||
@@ -675,7 +1015,11 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
}
|
}
|
||||||
const result = act(account, body);
|
const result = act(account, body);
|
||||||
if (result.ok) {
|
if (result.ok) {
|
||||||
console.log(`[admin] ${body.action} on "${account.username}"`);
|
console.log(`[admin] ${logText(body.action)} on "${logText(account.username)}"`);
|
||||||
|
// in the record beside the moderators', for the player's timeline.
|
||||||
|
if (!["password", "lastSeen", "level"].includes(body.action)) {
|
||||||
|
modlog.record(BY, body.action, account.username, result.detail || "");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
reply(result.ok ? 200 : 400, result);
|
reply(result.ok ? 200 : 400, result);
|
||||||
return;
|
return;
|
||||||
@@ -688,10 +1032,63 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
case "GET /admin/api/bans":
|
case "GET /admin/api/bans":
|
||||||
reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans()});
|
reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans(), devices: devices.list(), alerts: devices.alerts()});
|
||||||
|
return;
|
||||||
|
|
||||||
|
// A device ban lifted (lib/devices.js).
|
||||||
|
case "POST /admin/api/device": {
|
||||||
|
const result = staff.unbanDevices(body.id, BY);
|
||||||
|
if (result.ok) {
|
||||||
|
console.log(`[admin] device ban ${logText(Number(body.id))} lifted`);
|
||||||
|
modlog.record(BY, "hardware ban lifted", result.username || "");
|
||||||
|
}
|
||||||
|
reply(result.ok ? 200 : 400, result);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// other accounts the same person may have, their story, and who the
|
||||||
|
// chat filter stopped most this week (lib/staff.js, lib/chatlog.js).
|
||||||
|
case "GET /admin/api/alts": {
|
||||||
|
const account = accounts.byName(url.searchParams.get("username") || "");
|
||||||
|
reply(account ? 200 : 404, account ? {alts: staff.altsOf(account), ids: devices.idsFor(account)} : {error: "No such account."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case "GET /admin/api/timeline": {
|
||||||
|
const account = accounts.byName(url.searchParams.get("username") || "");
|
||||||
|
reply(account ? 200 : 404, account ? {events: staff.timelineOf(account)} : {error: "No such account."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case "GET /admin/api/filterhits":
|
||||||
|
reply(200, {players: chatlog.mostStopped(7, 50)});
|
||||||
|
return;
|
||||||
|
|
||||||
|
// what waits, for the tabs and the page's title, on every page.
|
||||||
|
case "GET /admin/api/counts":
|
||||||
|
reply(200, {reports: reports.openCount(), support: support.openCount() + bans.openAppeals(), masterpieces: masterpieces.list(masterpieces.PENDING).length});
|
||||||
return;
|
return;
|
||||||
|
|
||||||
// who may use the moderator panel, and what each did there.
|
// who may use the moderator panel, and what each did there.
|
||||||
|
// the staff roles and what each may do.
|
||||||
|
case "GET /admin/api/roles":
|
||||||
|
reply(200, {roles: Object.entries(roles.ROLES).map(([id, role]) => ({id, label: role.label, rank: role.rank, permissions: roles.rolePermissions(id),
|
||||||
|
defaults: role.permissions, changed: roles.roleChanged(id)})), permissions: roles.PERMISSIONS});
|
||||||
|
return;
|
||||||
|
// a role's permissions changed ({role, permissions: [...]}), or back to
|
||||||
|
// its defaults ({role, reset: true}). its staff who are playing are told.
|
||||||
|
case "POST /admin/api/roles": {
|
||||||
|
const role = String(body.role || "");
|
||||||
|
if (!roles.setRolePermissions(role, body.reset === true ? null : Array.isArray(body.permissions) ? body.permissions : [])) {
|
||||||
|
reply(400, {error: "No such role."});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const player of accounts.all().filter(account => roles.roleOf(account) === role)) {
|
||||||
|
world.refreshStaff(player);
|
||||||
|
}
|
||||||
|
console.log(`[admin] permissions of the ${logText(role)} role ${logText(body.reset === true ? "reset" : "changed")}`);
|
||||||
|
modlog.record("admin", body.reset === true ? "role permissions reset" : "role permissions changed", "", `${role}: ${roles.rolePermissions(role).join(", ")}`);
|
||||||
|
reply(200, {ok: `${roles.ROLES[role].label}: ${body.reset === true ? "back to its defaults" : "saved"}.`});
|
||||||
|
return;
|
||||||
|
}
|
||||||
case "GET /admin/api/moderators":
|
case "GET /admin/api/moderators":
|
||||||
reply(200, {moderators: modpanel.moderators(), log: modlog.recent()});
|
reply(200, {moderators: modpanel.moderators(), log: modlog.recent()});
|
||||||
return;
|
return;
|
||||||
@@ -705,7 +1102,7 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
case "POST /admin/api/address": {
|
case "POST /admin/api/address": {
|
||||||
const result = addressAct(body);
|
const result = addressAct(body);
|
||||||
if (result.ok) {
|
if (result.ok) {
|
||||||
console.log(`[admin] address ${body.action}: ${limits.key(body.address)}`);
|
console.log(`[admin] address ${logText(body.action)}: ${logText(limits.key(body.address))}`);
|
||||||
}
|
}
|
||||||
reply(result.ok ? 200 : 400, result);
|
reply(result.ok ? 200 : 400, result);
|
||||||
return;
|
return;
|
||||||
@@ -722,7 +1119,24 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
case "POST /admin/api/debug": {
|
case "POST /admin/api/debug": {
|
||||||
const result = debugAct(body);
|
const result = debugAct(body);
|
||||||
if (result.ok) {
|
if (result.ok) {
|
||||||
console.log(`[admin] debug: ${body.action} ${body.action === "teleport" ? `${body.username} -> ${body.room}` : body.on === true}`);
|
console.log(`[admin] debug: ${logText(body.action)} ${logText(body.action === "teleport" ? `${body.username} -> ${body.room}` : body.on === true)}`);
|
||||||
|
}
|
||||||
|
reply(result.ok ? 200 : 400, result);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// codes for the game's Redeem Code window (lib/codes.js), each giving
|
||||||
|
// an item, gems or diamonds
|
||||||
|
case "GET /admin/api/codes":
|
||||||
|
reply(200, {codes: codes.list(), kinds: codes.KINDS});
|
||||||
|
return;
|
||||||
|
|
||||||
|
case "POST /admin/api/codes": {
|
||||||
|
const result = body.action === "remove"
|
||||||
|
? (codes.remove(body.code) ? {ok: "Code deleted."} : {error: "No such code."})
|
||||||
|
: codes.create(body);
|
||||||
|
if (result.ok) {
|
||||||
|
console.log(`[admin] redemption code ${logText(body.action === "remove" ? "deleted" : "made")}: ${logText(String(body.code || "").toUpperCase())}`);
|
||||||
}
|
}
|
||||||
reply(result.ok ? 200 : 400, result);
|
reply(result.ok ? 200 : 400, result);
|
||||||
return;
|
return;
|
||||||
@@ -743,7 +1157,7 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const reached = world.announce(text, body.room ? String(body.room) : null);
|
const reached = world.announce(text, body.room ? String(body.room) : null);
|
||||||
console.log(`[admin] announcement to ${body.room ? `room ${body.room}` : "everyone"} (${reached} players)`);
|
console.log(`[admin] announcement to ${logText(body.room ? `room ${body.room}` : "everyone")} (${logText(reached)} players)`);
|
||||||
reply(200, {ok: reached === 1 ? "Shown to 1 player." : `Shown to ${reached} players.`});
|
reply(200, {ok: reached === 1 ? "Shown to 1 player." : `Shown to ${reached} players.`});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -753,8 +1167,8 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
case "GET /admin/api/masterpieces":
|
case "GET /admin/api/masterpieces":
|
||||||
reply(200, {
|
reply(200, {
|
||||||
review: masterpieces.needsReview(),
|
review: masterpieces.needsReview(),
|
||||||
waiting: masterpieces.list(masterpieces.PENDING),
|
...masterpieces.listsFor(url.searchParams.get("creator")),
|
||||||
approved: masterpieces.list(masterpieces.APPROVED),
|
waitingCount: masterpieces.list(masterpieces.PENDING).length,
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
|
|
||||||
@@ -778,7 +1192,7 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
: "New masterpieces are approved as they are made. Ones already waiting still wait."};
|
: "New masterpieces are approved as they are made. Ones already waiting still wait."};
|
||||||
}
|
}
|
||||||
else if (body.action === "approve") {
|
else if (body.action === "approve") {
|
||||||
result = world.approveMasterpiece(id) ? {ok: "Approved. Its maker has been told and can hang it now."} : {error: "No such painting waiting."};
|
result = world.approveMasterpiece(id, "admin") ? {ok: "Approved. Its maker has been told and can hang it now."} : {error: "No such painting waiting."};
|
||||||
}
|
}
|
||||||
else if (body.action === "reject" || body.action === "remove") {
|
else if (body.action === "reject" || body.action === "remove") {
|
||||||
result = world.removeMasterpiece(id)
|
result = world.removeMasterpiece(id)
|
||||||
@@ -788,7 +1202,7 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
result = {error: "Unknown action."};
|
result = {error: "Unknown action."};
|
||||||
}
|
}
|
||||||
if (result.ok) {
|
if (result.ok) {
|
||||||
console.log(`[admin] masterpiece ${body.action} ${id || body.on === true}`);
|
console.log(`[admin] masterpiece ${logText(body.action)} ${logText(id || body.on === true)}`);
|
||||||
}
|
}
|
||||||
reply(result.ok ? 200 : 400, result);
|
reply(result.ok ? 200 : 400, result);
|
||||||
return;
|
return;
|
||||||
@@ -830,7 +1244,7 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
result = {error: "Unknown action."};
|
result = {error: "Unknown action."};
|
||||||
}
|
}
|
||||||
if (result.ok) {
|
if (result.ok) {
|
||||||
console.log(`[admin] support: ${body.action} ${Number(body.id)}`);
|
console.log(`[admin] support: ${logText(body.action)} ${logText(Number(body.id))}`);
|
||||||
}
|
}
|
||||||
reply(result.ok ? 200 : 400, result);
|
reply(result.ok ? 200 : 400, result);
|
||||||
return;
|
return;
|
||||||
@@ -858,4 +1272,4 @@ const handle = async (req, res, url, from, web) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = {load, handle, PASSWORD_SETTING};
|
module.exports = {load, handle, signedIn, theatreBrowserOn, PASSWORD_SETTING};
|
||||||
+5
-2
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
const config = require("../config.js");
|
const config = require("../config.js");
|
||||||
const defpacks = require("./defpacks.js");
|
const defpacks = require("./defpacks.js");
|
||||||
@@ -116,7 +117,9 @@ module.exports = ({enterRoom, findOnline, blocks}) => {
|
|||||||
// PartyManager.customPartyJoinResponse: [success, reason]
|
// PartyManager.customPartyJoinResponse: [success, reason]
|
||||||
const joinHosted = (session, host) => {
|
const joinHosted = (session, host) => {
|
||||||
const party = host && partyOf(host);
|
const party = host && partyOf(host);
|
||||||
if (!party || blocks.either(host, session.account)) {
|
// A one-use staff teleport may inspect a hosted party despite a block;
|
||||||
|
// ordinary party joins retain the host's privacy rule.
|
||||||
|
if (!party || (!session.staffTravel && blocks.either(host, session.account))) {
|
||||||
session.sendXt("sjp", -1, 0, party ? "BLK" : "NPP");
|
session.sendXt("sjp", -1, 0, party ? "BLK" : "NPP");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -190,7 +193,7 @@ module.exports = ({enterRoom, findOnline, blocks}) => {
|
|||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
const party = {host: account, defId: def.id, name: `${name1}|${name2}|${name3}`, music: Number(music), endsAt: now() + config.partyMinutes * 60};
|
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);
|
hosted.set(account.username.toLowerCase(), party);
|
||||||
console.log(`[world] ${account.username} is hosting a party (def ${def.id})`);
|
console.log(`[world] ${logText(account.username)} is hosting a party (def ${logText(def.id)})`);
|
||||||
session.sendXt("cu", -1, CURRENCY_DIAMONDS, account.currency.diamonds, 0);
|
session.sendXt("cu", -1, CURRENCY_DIAMONDS, account.currency.diamonds, 0);
|
||||||
session.sendXt("scp", -1, 1, 1, party.endsAt - now());
|
session.sendXt("scp", -1, 1, 1, party.endsAt - now());
|
||||||
joinHosted(session, account);
|
joinHosted(session, account);
|
||||||
|
|||||||
+39
-3
@@ -3,7 +3,7 @@
|
|||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
const achievements = require("./achievements.js");
|
const achievements = require("./achievements.js");
|
||||||
const defpacks = require("./defpacks.js");
|
const defpacks = require("./defpacks.js");
|
||||||
const {activeAvatar, isUint} = require("./player.js");
|
const {activeAvatar, activePet, isUint} = require("./player.js");
|
||||||
|
|
||||||
// pets (client side: PetManager, PetXtCommManager). A pet's species and look
|
// pets (client side: PetManager, PetXtCommManager). A pet's species and look
|
||||||
// are packed into three integers by PetManager.packPetBits; the species is
|
// are packed into three integers by PetManager.packPetBits; the species is
|
||||||
@@ -30,6 +30,13 @@ const MASTERY_FULL = 100;
|
|||||||
const MASTERY_PER_ROOM = 5;
|
const MASTERY_PER_ROOM = 5;
|
||||||
const MASTERY_BITS = 0xF00; // the part of uBits PetInventory writes
|
const MASTERY_BITS = 0xF00; // the part of uBits PetInventory writes
|
||||||
const SECONDS_TO_HATCH = 259200; // PetManager.hasHatched
|
const SECONDS_TO_HATCH = 259200; // PetManager.hasHatched
|
||||||
|
// not one of the game's: the pet chooser's "play as your pet" switch
|
||||||
|
// (gui.PetInventory), kept with the user vars so it reaches the client at
|
||||||
|
// login. on, whichever pet is out stands in for the avatar, in any room, as
|
||||||
|
// at a Play-As-Your-Pet party.
|
||||||
|
const USER_VAR_PET_FORM = 9008;
|
||||||
|
|
||||||
|
const inPetForm = account => Number(account.userVars[USER_VAR_PET_FORM]) === 1 && Boolean(activePet(account));
|
||||||
|
|
||||||
const random = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
|
const random = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
|
||||||
|
|
||||||
@@ -106,6 +113,24 @@ module.exports = ({others, findOnline, petFields}) => {
|
|||||||
|
|
||||||
const ownPet = (account, invIdx) => account.pets.find(candidate => candidate.inv === Number(invIdx));
|
const ownPet = (account, invIdx) => account.pets.find(candidate => candidate.inv === Number(invIdx));
|
||||||
|
|
||||||
|
// tells the player and everyone who sees them whether the pet stands in
|
||||||
|
// for the avatar (UserCommXtCommManager, user communication type 13).
|
||||||
|
const sendPetForm = session => {
|
||||||
|
if (session.pos) {
|
||||||
|
const state = inPetForm(session.account) ? "on" : "off";
|
||||||
|
for (const other of [session, ...others(session)]) {
|
||||||
|
other.sendXt("uc", session.room.id, session.id, state, "13");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// the pet chooser's switch. on with no pet out is kept for the next pet.
|
||||||
|
const setPetForm = (session, on) => {
|
||||||
|
achievements.set(session.account, USER_VAR_PET_FORM, on ? 1 : 0);
|
||||||
|
accounts.save(session.account);
|
||||||
|
sendPetForm(session);
|
||||||
|
};
|
||||||
|
|
||||||
const handlers = {
|
const handlers = {
|
||||||
// PetManager.onPetListResponse: [found, username, count, (invIdx,
|
// PetManager.onPetListResponse: [found, username, count, (invIdx,
|
||||||
// createdTs, name, lBits, uBits, eBits, mastery, personality, toy, food,
|
// createdTs, name, lBits, uBits, eBits, mastery, personality, toy, food,
|
||||||
@@ -146,6 +171,7 @@ module.exports = ({others, findOnline, petFields}) => {
|
|||||||
session.sendXt("ps", -1, 0);
|
session.sendXt("ps", -1, 0);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const wasPetForm = inPetForm(account);
|
||||||
activeAvatar(account).petInvId = pet ? pet.inv : 0;
|
activeAvatar(account).petInvId = pet ? pet.inv : 0;
|
||||||
accounts.save(account);
|
accounts.save(account);
|
||||||
const messageRoom = session.room ? session.room.id : -1;
|
const messageRoom = session.room ? session.room.id : -1;
|
||||||
@@ -155,6 +181,11 @@ module.exports = ({others, findOnline, petFields}) => {
|
|||||||
other.sendXt("ps", messageRoom, 1, session.id, ...petFields(pet));
|
other.sendXt("ps", messageRoom, 1, session.id, ...petFields(pet));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// with no pet out the avatar comes back; the next pet out takes its
|
||||||
|
// place again while the switch is on.
|
||||||
|
if (wasPetForm !== inPetForm(account)) {
|
||||||
|
sendPetForm(session);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
// PetManager.onPetDismissResponse: [success, invIdx]
|
// PetManager.onPetDismissResponse: [success, invIdx]
|
||||||
@@ -165,7 +196,11 @@ module.exports = ({others, findOnline, petFields}) => {
|
|||||||
session.sendXt("pd", -1, 0, invIdx);
|
session.sendXt("pd", -1, 0, invIdx);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const wasPetForm = inPetForm(account);
|
||||||
account.pets = account.pets.filter(candidate => candidate !== pet);
|
account.pets = account.pets.filter(candidate => candidate !== pet);
|
||||||
|
if (wasPetForm && !inPetForm(account)) {
|
||||||
|
sendPetForm(session);
|
||||||
|
}
|
||||||
for (const avatar of account.avatars) {
|
for (const avatar of account.avatars) {
|
||||||
if (avatar.petInvId === pet.inv) {
|
if (avatar.petInvId === pet.inv) {
|
||||||
avatar.petInvId = 0;
|
avatar.petInvId = 0;
|
||||||
@@ -199,7 +234,8 @@ module.exports = ({others, findOnline, petFields}) => {
|
|||||||
// EggPetHatchedPopup: [petInvIdx, nameId1, nameId2] names a pet hatched
|
// EggPetHatchedPopup: [petInvIdx, nameId1, nameId2] names a pet hatched
|
||||||
// from an egg. PetManager.onPetEggNameResponse: [success, invIdx, name].
|
// from an egg. PetManager.onPetEggNameResponse: [success, invIdx, name].
|
||||||
pn(session, roomId, [invIdx, name1, name2]) {
|
pn(session, roomId, [invIdx, name1, name2]) {
|
||||||
const pet = ownPet(session.account, invIdx);
|
const {account} = session;
|
||||||
|
const pet = ownPet(account, invIdx);
|
||||||
const def = pet && defpacks.petDef(pet.lBits & 0xFF);
|
const def = pet && defpacks.petDef(pet.lBits & 0xFF);
|
||||||
if (!pet || ![name1, name2].every(isUint) || pet.name || !def || def.isEgg !== "1"
|
if (!pet || ![name1, name2].every(isUint) || pet.name || !def || def.isEgg !== "1"
|
||||||
|| pet.createdAt + SECONDS_TO_HATCH > Math.floor(Date.now() / 1000)) {
|
|| pet.createdAt + SECONDS_TO_HATCH > Math.floor(Date.now() / 1000)) {
|
||||||
@@ -234,5 +270,5 @@ module.exports = ({others, findOnline, petFields}) => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
return {handlers, walked, giveCharacter, favouritesList, personalityList, PERSONALITY_LIST};
|
return {handlers, walked, giveCharacter, favouritesList, personalityList, PERSONALITY_LIST, inPetForm, setPetForm};
|
||||||
};
|
};
|
||||||
+15
-3
@@ -1,6 +1,7 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
const defpacks = require("./defpacks.js");
|
const defpacks = require("./defpacks.js");
|
||||||
|
const wearRules = require("./wearrules.js");
|
||||||
// accessors over an account's animals, pets and items (shape: accounts.js).
|
// accessors over an account's animals, pets and items (shape: accounts.js).
|
||||||
|
|
||||||
// SbiConstants.CURRENCY_NAMES; an item's currencyType indexes into this.
|
// SbiConstants.CURRENCY_NAMES; an item's currencyType indexes into this.
|
||||||
@@ -32,13 +33,24 @@ const avatarById = (account, perUserAvId) =>
|
|||||||
|
|
||||||
const activePet = account => account.pets.find(pet => pet.inv === activeAvatar(account).petInvId) || null;
|
const activePet = account => account.pets.find(pet => pet.inv === activeAvatar(account).petInvId) || null;
|
||||||
|
|
||||||
const wornItems = (account, avatar) => account.items.filter(item => item.on.includes(avatar.avInvId));
|
// The persisted state is also filtered here, not only where a player tries
|
||||||
|
// to put an item on. That keeps an old/corrupt pairing from reaching player
|
||||||
|
// cards or other people in a room while a dashboard rule is being applied.
|
||||||
|
const wornItems = (account, avatar) => account.items.filter(item => item.on.includes(avatar.avInvId)
|
||||||
|
&& wearRules.mayWear(item.def, avatar.type));
|
||||||
|
|
||||||
// item.EquippedAvatars: comma-separated 32-bit words, one bit per avInvId of
|
// item.EquippedAvatars: comma-separated 32-bit words, one bit per avInvId of
|
||||||
// an animal wearing the item.
|
// an animal wearing the item.
|
||||||
const equippedBits = item => {
|
// With an account, omit stale pairings that are no longer allowed. The full
|
||||||
|
// inventory protocol otherwise exposes those bits and a later avatar switch
|
||||||
|
// can appear to revive a prohibited item.
|
||||||
|
const equippedBits = (item, account = null) => {
|
||||||
const words = [0];
|
const words = [0];
|
||||||
for (const avInvId of item.on) {
|
const wornBy = account ? item.on.filter(avInvId => {
|
||||||
|
const avatar = account.avatars.find(candidate => candidate.avInvId === avInvId);
|
||||||
|
return avatar && wearRules.mayWear(item.def, avatar.type);
|
||||||
|
}) : item.on;
|
||||||
|
for (const avInvId of wornBy) {
|
||||||
const word = avInvId >>> 5;
|
const word = avInvId >>> 5;
|
||||||
while (words.length <= word) {
|
while (words.length <= word) {
|
||||||
words.push(0);
|
words.push(0);
|
||||||
|
|||||||
@@ -0,0 +1,303 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const accounts = require("./accounts.js");
|
||||||
|
const config = require("../config.js");
|
||||||
|
const customItems = require("./customitems.js");
|
||||||
|
const dens = require("./dens.js");
|
||||||
|
const itemControl = require("./itemcontrol.js");
|
||||||
|
const modlog = require("./modlog.js");
|
||||||
|
const names = require("./names.js");
|
||||||
|
const {addClothing, sendClothingAdded} = require("./player.js");
|
||||||
|
|
||||||
|
// items players make for themselves (the patched client's Item Maker, in the
|
||||||
|
// settings menu): one of the game's clothing pieces or den items under a
|
||||||
|
// name of their own, as staff make them (lib/customitems.js), but free, never
|
||||||
|
// in a shop, and in the item finder for its maker only. the maker is given
|
||||||
|
// one at once; it can be worn, placed and traded like any other. a maker
|
||||||
|
// may delete their own; staff may delete anyone's (the moderator panel).
|
||||||
|
//
|
||||||
|
// "xcm" from the client: ["info"], ["make", kind, baseId, name],
|
||||||
|
// ["rename", kind, id, name], ["look", kind, id, "sticker" | "texture"]
|
||||||
|
// (how one with a picture is worn) or ["delete", kind, id]. its picture is
|
||||||
|
// uploaded over HTTP (lib/itemart.js, POST /api/itemart). the answer is always "xcm" [ok 1 | 0, what to say,
|
||||||
|
// left today, left in all, the maker's items as JSON]
|
||||||
|
|
||||||
|
// the admin's two switches (the admin panel's Items page): whether players
|
||||||
|
// may make items at all, and whether what they make (an item, or a new
|
||||||
|
// picture for one) waits for a moderator first (items.approve: the
|
||||||
|
// moderator panel's Review page), out of the game till then.
|
||||||
|
const ENABLED_SETTING = "playerItems";
|
||||||
|
const APPROVAL_SETTING = "playerItemApproval";
|
||||||
|
const enabled = () => accounts.setting(ENABLED_SETTING) !== "off";
|
||||||
|
const approvalOn = () => accounts.setting(APPROVAL_SETTING) === "on";
|
||||||
|
// pictures are seen by everyone who meets the item, so a player's waits for
|
||||||
|
// a moderator even when items do not: unless the admin turns this off too.
|
||||||
|
const ART_APPROVAL_SETTING = "playerArtApproval";
|
||||||
|
const artApprovalOn = () => accounts.setting(ART_APPROVAL_SETTING) !== "off";
|
||||||
|
const pictureWaits = () => approvalOn() || artApprovalOn();
|
||||||
|
const setSwitches = ({enabled: on, approval, artApproval}) => {
|
||||||
|
if (on !== undefined) {
|
||||||
|
accounts.setSetting(ENABLED_SETTING, on ? "on" : "off");
|
||||||
|
}
|
||||||
|
if (approval !== undefined) {
|
||||||
|
accounts.setSetting(APPROVAL_SETTING, approval ? "on" : "off");
|
||||||
|
}
|
||||||
|
if (artApproval !== undefined) {
|
||||||
|
accounts.setSetting(ART_APPROVAL_SETTING, artApproval ? "on" : "off");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- what keeps pictures players upload decent
|
||||||
|
//
|
||||||
|
// - a picture turned away (or taken off by a moderator) is remembered by
|
||||||
|
// its SHA-256, and the same picture cannot be sent again;
|
||||||
|
// - each counts against its maker: at ART_STRIKES their uploads stop,
|
||||||
|
// till a moderator lets them again (account.artBlocked);
|
||||||
|
// - an account younger than config.itemArtMinAccountHours may not upload.
|
||||||
|
const ART_STRIKES = 3;
|
||||||
|
const REFUSED_SETTING = "refusedArt";
|
||||||
|
const MAX_REFUSED = 5000;
|
||||||
|
let refused = null; // Set of SHA-256 hex
|
||||||
|
|
||||||
|
const refusedSet = () => {
|
||||||
|
if (!refused) {
|
||||||
|
let saved = [];
|
||||||
|
try {
|
||||||
|
saved = JSON.parse(accounts.setting(REFUSED_SETTING) || "[]");
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
saved = [];
|
||||||
|
}
|
||||||
|
refused = new Set(Array.isArray(saved) ? saved.map(String) : []);
|
||||||
|
}
|
||||||
|
return refused;
|
||||||
|
};
|
||||||
|
const pictureRefused = hash => refusedSet().has(hash);
|
||||||
|
|
||||||
|
// {error} when `account` may not upload a picture now, else null. `local`:
|
||||||
|
// the request is from this machine (no wait for a new account).
|
||||||
|
const uploadRefusal = (account, local = false) => {
|
||||||
|
if (account.artBlocked) {
|
||||||
|
return {error: "A moderator has turned off picture uploads for your account."};
|
||||||
|
}
|
||||||
|
const hours = config.itemArtMinAccountHours;
|
||||||
|
if (!local && hours > 0 && Math.floor(Date.now() / 1000) - (account.createdAt || 0) < hours * 3600) {
|
||||||
|
return {error: `New accounts can add pictures after ${hours} hours. Try again later.`};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// stops or lets again one player's uploads; letting them again clears the
|
||||||
|
// pictures counted against them.
|
||||||
|
const setUploadsBlocked = (account, blocked) => {
|
||||||
|
account.artBlocked = Boolean(blocked);
|
||||||
|
if (!blocked) {
|
||||||
|
account.artRefusals = 0;
|
||||||
|
}
|
||||||
|
accounts.save(account);
|
||||||
|
return {ok: blocked ? `${account.username} can no longer upload pictures.` : `${account.username} can upload pictures again.`};
|
||||||
|
};
|
||||||
|
|
||||||
|
// a picture turned away or taken off: never again, and counted against its
|
||||||
|
// maker (not against staff, whose items have no maker). before it is removed.
|
||||||
|
// returns what to add to what the moderator is told.
|
||||||
|
const strike = entry => {
|
||||||
|
const hash = require("./itemart.js").digestOf(entry.kind, entry.id);
|
||||||
|
if (hash) {
|
||||||
|
const set = refusedSet();
|
||||||
|
set.add(hash);
|
||||||
|
const kept = [...set].slice(-MAX_REFUSED);
|
||||||
|
refused = new Set(kept);
|
||||||
|
accounts.setSetting(REFUSED_SETTING, JSON.stringify(kept));
|
||||||
|
}
|
||||||
|
const maker = entry.ownerId === null ? null : accounts.byId(entry.ownerId);
|
||||||
|
if (!maker) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
maker.artRefusals = (maker.artRefusals || 0) + 1;
|
||||||
|
if (maker.artRefusals >= ART_STRIKES && !maker.artBlocked) {
|
||||||
|
maker.artBlocked = true;
|
||||||
|
accounts.save(maker);
|
||||||
|
modlog.record("system", "picture uploads stopped", maker.username, `${maker.artRefusals} pictures turned away`);
|
||||||
|
return ` That is ${maker.artRefusals} for ${maker.username}: their picture uploads are stopped.`;
|
||||||
|
}
|
||||||
|
accounts.save(maker);
|
||||||
|
return ` ${maker.username} has had ${maker.artRefusals} of ${ART_STRIKES} pictures turned away.`;
|
||||||
|
};
|
||||||
|
|
||||||
|
// a moderator takes an item's picture off, shown or waiting (after a report).
|
||||||
|
const takePicture = (kind, id) => {
|
||||||
|
const entry = customItems.get(kind, id);
|
||||||
|
if (!entry || !entry.art) {
|
||||||
|
return {error: "That item has no picture of its own."};
|
||||||
|
}
|
||||||
|
const said = strike(entry);
|
||||||
|
const result = require("./itemart.js").remove(kind, entry.id);
|
||||||
|
return result.error ? result : {ok: `${result.ok}${said}`};
|
||||||
|
};
|
||||||
|
|
||||||
|
const PER_DAY = 5;
|
||||||
|
const IN_ALL = 20;
|
||||||
|
const DAY = 86400;
|
||||||
|
|
||||||
|
const RENAMES_PER_HOUR = 10;
|
||||||
|
|
||||||
|
const now = () => Math.floor(Date.now() / 1000);
|
||||||
|
const renames = require("./limits.js").limiter(RENAMES_PER_HOUR, 3600000); // per account: each is sent to every game
|
||||||
|
|
||||||
|
const madeBy = account => customItems.list().filter(entry => entry.ownerId === account.id);
|
||||||
|
|
||||||
|
const left = account => {
|
||||||
|
const mine = madeBy(account);
|
||||||
|
const today = mine.filter(entry => entry.createdAt > now() - DAY).length;
|
||||||
|
return {today: Math.max(0, Math.min(PER_DAY - today, IN_ALL - mine.length)), inAll: Math.max(0, IN_ALL - mine.length)};
|
||||||
|
};
|
||||||
|
|
||||||
|
// returns {ok} or {error}.
|
||||||
|
const make = (session, kind, baseId, name) => {
|
||||||
|
const {account} = session;
|
||||||
|
if (!enabled()) {
|
||||||
|
return {error: "The Item Maker is turned off on this server for now."};
|
||||||
|
}
|
||||||
|
if (!customItems.KINDS.includes(kind) || !/^\d+$/.test(String(baseId))) {
|
||||||
|
return {error: "Choose an item to make yours from."};
|
||||||
|
}
|
||||||
|
if (!customItems.copyable(kind, Number(baseId))) {
|
||||||
|
return {error: "That item cannot be made into one of your own. Choose another."};
|
||||||
|
}
|
||||||
|
const room = left(account);
|
||||||
|
if (room.inAll === 0) {
|
||||||
|
return {error: `You have made ${IN_ALL} items, as many as there can be. Delete one to make another.`};
|
||||||
|
}
|
||||||
|
if (room.today === 0) {
|
||||||
|
return {error: `You have made ${PER_DAY} items today. Try again tomorrow.`};
|
||||||
|
}
|
||||||
|
const clean = String(name || "").trim().replace(/\s+/g, " ");
|
||||||
|
if (clean && names.refused(clean)) {
|
||||||
|
return {error: "That name is not allowed."};
|
||||||
|
}
|
||||||
|
const waits = approvalOn();
|
||||||
|
const result = customItems.create(kind, {base: Number(baseId), name: clean, cost: 0, members: false, inShop: false}, account.username, account.id, waits);
|
||||||
|
if (result.error) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
const {item} = result;
|
||||||
|
if (waits) {
|
||||||
|
modlog.record(account.username, "item made by a player, waiting for approval", "", `${kind} ${item.id} ${item.name}`);
|
||||||
|
return {ok: `${item.name} is waiting for a moderator to approve it. It is yours as soon as they do.`};
|
||||||
|
}
|
||||||
|
giveTo(account, item, session);
|
||||||
|
modlog.record(account.username, "item made by a player", "", `${kind} ${item.id} ${item.name}`);
|
||||||
|
return {ok: `Made ${item.name}. It is in your ${kind === "den" ? "den items" : "clothing"} now.`};
|
||||||
|
};
|
||||||
|
|
||||||
|
// one of the item, to its maker: now in their game if `session` is it
|
||||||
|
const giveTo = (account, item, session) => {
|
||||||
|
if (item.kind === "den") {
|
||||||
|
if (dens.giveDenItem(account, item.id) && session) {
|
||||||
|
dens.sendDenItems(session);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const given = addClothing(account, item.id, item.colors[0]);
|
||||||
|
accounts.save(account);
|
||||||
|
if (session) {
|
||||||
|
sendClothingAdded(session, given);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// a moderator's answer about what waits (lib/modpanel.js, lib/panel.js): an
|
||||||
|
// item let in is given to its maker; one turned away is deleted, or only
|
||||||
|
// its picture taken away. `world` finds whether its maker is playing, and
|
||||||
|
// tells games about items taken. returns {ok} or {error}.
|
||||||
|
const review = (kind, id, approve, by, world) => {
|
||||||
|
const entry = customItems.get(kind, id);
|
||||||
|
if (!entry || (!entry.pending && !entry.artPending)) {
|
||||||
|
return {error: "That is not waiting for approval."};
|
||||||
|
}
|
||||||
|
const maker = entry.ownerId === null ? null : accounts.byId(entry.ownerId);
|
||||||
|
const wasNew = entry.pending;
|
||||||
|
if (approve) {
|
||||||
|
customItems.approve(kind, entry.id);
|
||||||
|
if (wasNew && maker) {
|
||||||
|
giveTo(maker, entry, world.findOnline(maker.username));
|
||||||
|
}
|
||||||
|
return {ok: wasNew ? `${entry.name} is in the game, and ${maker ? maker.username : "its maker"} has one.` : `${entry.name}'s picture is shown now.`};
|
||||||
|
}
|
||||||
|
if (wasNew) {
|
||||||
|
itemControl.deleteCustom(kind, entry.id, world);
|
||||||
|
return {ok: `${entry.name} was turned away and deleted.`};
|
||||||
|
}
|
||||||
|
const said = strike(entry);
|
||||||
|
require("./itemart.js").remove(kind, entry.id);
|
||||||
|
return {ok: `${entry.name}'s new picture was turned away.${said}`};
|
||||||
|
};
|
||||||
|
|
||||||
|
// a new name for one of their own (every game is told: customItems.update).
|
||||||
|
const rename = (account, kind, id, name) => {
|
||||||
|
const entry = customItems.get(kind, id);
|
||||||
|
if (!entry || entry.ownerId !== account.id) {
|
||||||
|
return {error: "That is not one of your items."};
|
||||||
|
}
|
||||||
|
if (!renames.allow(account.id)) {
|
||||||
|
return {error: "Too many renames. Try again in an hour."};
|
||||||
|
}
|
||||||
|
const clean = String(name || "").trim().replace(/\s+/g, " ");
|
||||||
|
if (clean && names.refused(clean)) {
|
||||||
|
return {error: "That name is not allowed."};
|
||||||
|
}
|
||||||
|
const result = customItems.update(kind, entry.id, {name: clean});
|
||||||
|
return result.error ? result : {ok: `Renamed it ${result.item.name}.`};
|
||||||
|
};
|
||||||
|
|
||||||
|
// how one of their own is worn ("sticker" or "texture")
|
||||||
|
const setLook = (account, kind, id, mode) => {
|
||||||
|
const entry = customItems.get(kind, id);
|
||||||
|
if (!entry || entry.ownerId !== account.id) {
|
||||||
|
return {error: "That is not one of your items."};
|
||||||
|
}
|
||||||
|
const result = customItems.setArtMode(kind, entry.id, String(mode));
|
||||||
|
return result.error ? result : {ok: `${entry.name} is worn as ${mode === "texture" ? "its shape, with your picture in it" : "your picture"}.`};
|
||||||
|
};
|
||||||
|
|
||||||
|
const remove = (session, kind, id, world) => {
|
||||||
|
const entry = customItems.get(kind, id);
|
||||||
|
if (!entry || entry.ownerId !== session.account.id) {
|
||||||
|
return {error: "That is not one of your items."};
|
||||||
|
}
|
||||||
|
const result = itemControl.deleteCustom(kind, entry.id, world);
|
||||||
|
return result.error ? result : {ok: `Deleted ${entry.name}.`};
|
||||||
|
};
|
||||||
|
|
||||||
|
const reply = (session, result) => {
|
||||||
|
const room = left(session.account);
|
||||||
|
const mine = madeBy(session.account).map(entry => ({kind: entry.kind, id: entry.id, name: entry.name, base: entry.base, art: entry.artPending ? "" : entry.art || "",
|
||||||
|
artMode: entry.artMode || "sticker", waiting: entry.pending ? "item" : entry.artPending ? "picture" : ""}));
|
||||||
|
session.sendXt("xcm", -1, result.error ? 0 : 1, String(result.error || result.ok || "").replace(/%/g, " percent"), room.today, room.inAll,
|
||||||
|
JSON.stringify(mine).replace(/%/g, "\\u0025"));
|
||||||
|
};
|
||||||
|
|
||||||
|
// `world` tells games about items taken (lib/world.js itemsTaken).
|
||||||
|
const handlers = world => ({
|
||||||
|
xcm(session, roomId, [action, kind, id, ...words]) {
|
||||||
|
if (action === "make") {
|
||||||
|
reply(session, make(session, kind, id, words.join(" ")));
|
||||||
|
}
|
||||||
|
else if (action === "look") {
|
||||||
|
reply(session, setLook(session.account, kind, id, words[0]));
|
||||||
|
}
|
||||||
|
else if (action === "rename") {
|
||||||
|
reply(session, rename(session.account, kind, id, words.join(" ")));
|
||||||
|
}
|
||||||
|
else if (action === "delete") {
|
||||||
|
reply(session, remove(session, kind, id, world));
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
reply(session, enabled() ? {ok: ""} : {error: "The Item Maker is turned off on this server for now."});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = {handlers, madeBy, rename, setLook, review, enabled, approvalOn, artApprovalOn, pictureWaits, setSwitches,
|
||||||
|
pictureRefused, uploadRefusal, setUploadsBlocked, takePicture, ART_STRIKES, PER_DAY, IN_ALL};
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const config = require("../config.js");
|
||||||
|
|
||||||
|
const send = async ({to, subject, text}) => {
|
||||||
|
if (!config.recoveryMail) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const response = await fetch(config.recoveryMail.url, {method: "POST", headers: {
|
||||||
|
"Content-Type": "application/json", "Authorization": `Bearer ${config.recoveryMail.token}`,
|
||||||
|
}, body: JSON.stringify({to, subject, text})});
|
||||||
|
return response.ok;
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.error("[recovery] email delivery failed");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {available: () => Boolean(config.recoveryMail), send};
|
||||||
+25
-3
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
const limits = require("./limits.js");
|
const limits = require("./limits.js");
|
||||||
|
|
||||||
@@ -44,6 +45,7 @@ const MERGE_SECONDS = 10;
|
|||||||
const perTenMinutes = limits.limiter(10, 600000);
|
const perTenMinutes = limits.limiter(10, 600000);
|
||||||
const now = () => Math.floor(Date.now() / 1000);
|
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 clean = (text, max) => String(text === undefined ? "" : text).replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, " ").trim().slice(0, max);
|
||||||
|
const listeners = new Set();
|
||||||
|
|
||||||
const load = () => accounts.database().exec(SCHEMA);
|
const load = () => accounts.database().exec(SCHEMA);
|
||||||
|
|
||||||
@@ -67,9 +69,18 @@ const file = ({reporter, target, reason, detail = "", context = "", room = ""})
|
|||||||
if (!perTenMinutes.allow(reporter.toLowerCase()) || openCount() >= MAX_OPEN) {
|
if (!perTenMinutes.allow(reporter.toLowerCase()) || openCount() >= MAX_OPEN) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
db.prepare("INSERT INTO reports (created_at, reporter, target, reason, detail, context, room) VALUES (?, ?, ?, ?, ?, ?, ?)")
|
const inserted = 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));
|
.run(now(), reporter, target, Number.isInteger(reason) ? reason : 0, clean(detail, MAX_DETAIL), clean(context, MAX_CONTEXT), clean(room, 100));
|
||||||
console.log(`[world] ${reporter} reported "${target}" (${REASONS[reason] || `reason ${reason}`})`);
|
console.log(`[world] ${logText(reporter)} reported "${logText(target)}" (${logText(REASONS[reason] || `reason ${reason}`)})`);
|
||||||
|
const report = row(db.prepare("SELECT * FROM reports WHERE id = ?").get(Number(inserted.lastInsertRowid)));
|
||||||
|
for (const listener of listeners) {
|
||||||
|
try {
|
||||||
|
listener(report);
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.error(`[reports] listener failed: ${logText(err.message)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -94,4 +105,15 @@ const list = (handled = false) => accounts.database()
|
|||||||
|
|
||||||
const markHandled = id => accounts.database().prepare("UPDATE reports SET handled_at = ? WHERE id = ? AND handled_at IS NULL").run(now(), id).changes > 0;
|
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};
|
// Lets optional integrations (the Discord bot) receive a newly filed report
|
||||||
|
// without making a report depend on an external service being available.
|
||||||
|
const onFile = listener => {
|
||||||
|
listeners.add(listener);
|
||||||
|
return () => listeners.delete(listener);
|
||||||
|
};
|
||||||
|
|
||||||
|
// the reports about one player, newest first, for their timeline.
|
||||||
|
const about = username => accounts.database().prepare("SELECT * FROM reports WHERE target = ? COLLATE NOCASE ORDER BY id DESC LIMIT 100")
|
||||||
|
.all(String(username)).map(row);
|
||||||
|
|
||||||
|
module.exports = {load, file, list, about, markHandled, onFile, openCount, MAX_DETAIL};
|
||||||
+205
@@ -0,0 +1,205 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const accounts = require("./accounts.js");
|
||||||
|
const totp = require("./totp.js");
|
||||||
|
|
||||||
|
// staff roles, and what each may do. an account holds at most one role
|
||||||
|
// (`role` on the account), set by the admin. an account from before roles
|
||||||
|
// that is only marked `moderator` counts as a moderator, so nothing that
|
||||||
|
// worked before stops working.
|
||||||
|
//
|
||||||
|
// a role is a list of permissions, and every staff action checks the one it
|
||||||
|
// needs, in the moderator panel (lib/modpanel.js) and in the game
|
||||||
|
// (lib/commands.js) alike. a higher role holds everything a lower one does.
|
||||||
|
// staff never act on staff of their own rank or above: that is for someone
|
||||||
|
// higher up, and for the admin in the end.
|
||||||
|
|
||||||
|
const PERMISSIONS = {
|
||||||
|
"server.view": "see read-only server health in the moderator panel",
|
||||||
|
"server.announce": "send an announcement to everyone playing",
|
||||||
|
"player.view": "see players, chat, reports, requests, bans and paintings in the moderator panel, and keep notes on players (!note, !notes)",
|
||||||
|
"staff.list": "see which staff are online (!staff)",
|
||||||
|
"player.warn": "warn a player, take a warning back, send them a message and mark a report dealt with (!warn, !unwarn, !warnings, !message)",
|
||||||
|
"player.goto": "go to the room a player is in (!goto)",
|
||||||
|
"chat.silence": "silence and unsilence a player (!silence)",
|
||||||
|
"player.kick": "disconnect a player (!kick)",
|
||||||
|
"player.summon": "bring a player to the room you are in (!summon)",
|
||||||
|
"staff.invisible": "go unseen in rooms, as the game's moderators could (!invisible)",
|
||||||
|
"player.ban": "ban, unban, change a ban's reason and answer ban appeals",
|
||||||
|
"player.names": "reject or accept a name, answer requests for a new one, clear a bio, remove a player's Jammer Wall posts",
|
||||||
|
"address.ban": "ban the address a player last signed in from, or the computers they use, and lift those bans",
|
||||||
|
"items.approve": "approve or turn away the items and pictures players make, when the admin has asked for that",
|
||||||
|
"masterpieces.approve": "approve or remove the paintings players frame as masterpieces (the Masterpieces page)",
|
||||||
|
"items.restrict": "stop a clothing item from being worn by selected animal types",
|
||||||
|
"items.create": "make new items from the game's art, change and delete them, lock items out of the item finder and take items from players (!item, !lock, !unlock, !locked, !take)",
|
||||||
|
"room.effects": "run temporary room-wide size and colour effects (!roomfx)",
|
||||||
|
"theater.control": "play or stop a YouTube video for everyone in the theatre",
|
||||||
|
"music.upload": "upload MP3s as den music tracks, and delete those uploaded (the Music page)",
|
||||||
|
"staff.log": "read the mod log: what staff did, in the panels and the game (the Mod log page)",
|
||||||
|
};
|
||||||
|
|
||||||
|
const HELPER = ["server.view", "player.view", "staff.list", "player.warn", "player.goto", "chat.silence"];
|
||||||
|
const MODERATOR = [...HELPER, "player.kick", "player.summon", "staff.invisible", "player.ban", "player.names", "address.ban", "items.approve", "masterpieces.approve", "items.restrict", "theater.control", "staff.log"];
|
||||||
|
const ADMIN = [...MODERATOR, "server.announce", "items.create", "room.effects", "music.upload"];
|
||||||
|
// a developer makes things, and moderates nobody.
|
||||||
|
const DEVELOPER = ["server.view", "staff.list", "items.create", "room.effects", "theater.control"];
|
||||||
|
|
||||||
|
const ROLES = {
|
||||||
|
developer: {rank: 1, label: "Developer", permissions: DEVELOPER},
|
||||||
|
helper: {rank: 1, label: "Helper", permissions: HELPER},
|
||||||
|
moderator: {rank: 2, label: "Moderator", permissions: MODERATOR},
|
||||||
|
admin: {rank: 3, label: "Admin", permissions: ADMIN},
|
||||||
|
};
|
||||||
|
|
||||||
|
// the role an account holds, or null.
|
||||||
|
const roleOf = account => {
|
||||||
|
if (!account) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (Object.hasOwn(ROLES, account.role)) {
|
||||||
|
return account.role;
|
||||||
|
}
|
||||||
|
return account.moderator ? "moderator" : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const rankOf = account => {
|
||||||
|
const role = roleOf(account);
|
||||||
|
return role ? ROLES[role].rank : 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// may this account act as staff at all right now? as for the moderator
|
||||||
|
// panel: a role, 2FA turned on, not locked and not banned. `banned` says
|
||||||
|
// whether the account is banned (passed in, so that this file needs nothing
|
||||||
|
// of the world's).
|
||||||
|
const isActiveStaff = (account, banned = false) =>
|
||||||
|
Boolean(roleOf(account) && totp.isOn(account) && !account.locked && !banned);
|
||||||
|
|
||||||
|
// what each role may do can be changed by the admin (the admin panel's
|
||||||
|
// Moderators page): kept as a setting, {role: [permission, ...]}, a role
|
||||||
|
// not in it holding its defaults above. one staff member can be given more
|
||||||
|
// than their role, or less (`permGrants`, `permDenies` on the account, from
|
||||||
|
// their page in the admin panel). a role and 2FA are still what makes
|
||||||
|
// someone staff at all (isActiveStaff).
|
||||||
|
const ROLE_SETTING = "rolePermissions";
|
||||||
|
let roleOverrides = null;
|
||||||
|
|
||||||
|
const overrides = () => {
|
||||||
|
if (!roleOverrides) {
|
||||||
|
try {
|
||||||
|
const saved = JSON.parse(accounts.setting(ROLE_SETTING) || "{}");
|
||||||
|
roleOverrides = saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
roleOverrides = {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return roleOverrides;
|
||||||
|
};
|
||||||
|
|
||||||
|
// the permissions in a list that are ones, each once
|
||||||
|
const known = list => [...new Set(Array.isArray(list) ? list.map(String) : [])].filter(permission => Object.hasOwn(PERMISSIONS, permission));
|
||||||
|
|
||||||
|
const rolePermissions = role => (Object.hasOwn(overrides(), role) ? known(overrides()[role]) : [...ROLES[role].permissions]);
|
||||||
|
|
||||||
|
const roleChanged = role => Object.hasOwn(overrides(), role);
|
||||||
|
|
||||||
|
// a role's permissions, or its defaults again (`list` null). false for no such role.
|
||||||
|
const setRolePermissions = (role, list) => {
|
||||||
|
if (!Object.hasOwn(ROLES, role)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const changed = {...overrides()};
|
||||||
|
if (list === null) {
|
||||||
|
delete changed[role];
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
changed[role] = known(list);
|
||||||
|
}
|
||||||
|
accounts.setSetting(ROLE_SETTING, JSON.stringify(changed));
|
||||||
|
roleOverrides = changed;
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
// masterpieces.approve was split from items.approve (2026-10-21), which
|
||||||
|
// judged paintings before. once: a role list the admin changed, and a staff
|
||||||
|
// member's own grants and denies, that held items.approve hold this too.
|
||||||
|
const SPLIT_SETTING = "permissionSplitMasterpieces";
|
||||||
|
const load = () => {
|
||||||
|
if (accounts.setting(SPLIT_SETTING)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const withSplit = list => (Array.isArray(list) && list.includes("items.approve") && !list.includes("masterpieces.approve")
|
||||||
|
? [...list, "masterpieces.approve"] : list);
|
||||||
|
const changed = {...overrides()};
|
||||||
|
for (const role of Object.keys(changed)) {
|
||||||
|
changed[role] = withSplit(changed[role]);
|
||||||
|
}
|
||||||
|
accounts.setSetting(ROLE_SETTING, JSON.stringify(changed));
|
||||||
|
roleOverrides = changed;
|
||||||
|
for (const account of accounts.all()) {
|
||||||
|
if (account.permGrants || account.permDenies) {
|
||||||
|
const grants = withSplit(account.permGrants);
|
||||||
|
const denies = withSplit(account.permDenies);
|
||||||
|
if (grants !== account.permGrants || denies !== account.permDenies) {
|
||||||
|
if (grants) account.permGrants = grants;
|
||||||
|
if (denies) account.permDenies = denies;
|
||||||
|
accounts.save(account);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
accounts.setSetting(SPLIT_SETTING, "1");
|
||||||
|
};
|
||||||
|
|
||||||
|
const permissionsOf = account => {
|
||||||
|
const role = roleOf(account);
|
||||||
|
if (!role) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const denied = new Set(known(account.permDenies));
|
||||||
|
return [...new Set([...rolePermissions(role), ...known(account.permGrants)])].filter(permission => !denied.has(permission));
|
||||||
|
};
|
||||||
|
|
||||||
|
// one staff member's own: given beyond their role, and taken from it. a
|
||||||
|
// permission in both is given. the caller saves the account.
|
||||||
|
const setAccountPermissions = (account, grants, denies) => {
|
||||||
|
const given = known(grants);
|
||||||
|
const taken = known(denies).filter(permission => !given.includes(permission));
|
||||||
|
if (given.length) {
|
||||||
|
account.permGrants = given;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
delete account.permGrants;
|
||||||
|
}
|
||||||
|
if (taken.length) {
|
||||||
|
account.permDenies = taken;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
delete account.permDenies;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const can = (account, permission, banned = false) =>
|
||||||
|
isActiveStaff(account, banned) && permissionsOf(account).includes(permission);
|
||||||
|
|
||||||
|
// may `actor` act on `target`? never on themselves, nor on staff of their
|
||||||
|
// own rank or above.
|
||||||
|
const outranks = (actor, target) => actor !== target && rankOf(actor) > rankOf(target);
|
||||||
|
|
||||||
|
// sets the role (one of ROLES, or null for none). `moderator` is kept in
|
||||||
|
// step for anything that still reads it.
|
||||||
|
const setRole = (account, role) => {
|
||||||
|
if (role === null || role === "" || role === "none") {
|
||||||
|
delete account.role;
|
||||||
|
delete account.moderator;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!Object.hasOwn(ROLES, role)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
account.role = role;
|
||||||
|
account.moderator = true;
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {load, PERMISSIONS, ROLES, roleOf, rankOf, isActiveStaff, permissionsOf, rolePermissions, roleChanged, setRolePermissions,
|
||||||
|
setAccountPermissions, can, outranks, setRole};
|
||||||
+9
-4
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const zlib = require("zlib");
|
const zlib = require("zlib");
|
||||||
const amf3 = require("./amf3.js");
|
const amf3 = require("./amf3.js");
|
||||||
const cdn = require("./cdn.js");
|
const cdn = require("./cdn.js");
|
||||||
@@ -13,8 +14,9 @@ const defpacks = require("./defpacks.js");
|
|||||||
// then AMF3), so reading it here costs no extra download once anyone has
|
// then AMF3), so reading it here costs no extra download once anyone has
|
||||||
// been in the room.
|
// been in the room.
|
||||||
|
|
||||||
// what the room editor left in files nobody named.
|
// what the room editor left in files nobody named ("default": the museum's
|
||||||
const UNNAMED = "Display Name";
|
// theatre).
|
||||||
|
const UNNAMED = ["display name", "default"];
|
||||||
// rooms whose file has no name and whose path does not spell it either.
|
// rooms whose file has no name and whose path does not spell it either.
|
||||||
const NAMES = new Map([
|
const NAMES = new Map([
|
||||||
["jamaa_township.room_diamonds", "Diamond Shop"],
|
["jamaa_township.room_diamonds", "Diamond Shop"],
|
||||||
@@ -23,6 +25,9 @@ const NAMES = new Map([
|
|||||||
["aussie.room_main", "Kimbara Outback"],
|
["aussie.room_main", "Kimbara Outback"],
|
||||||
["aussie.room_aushop", "Outback Imports"],
|
["aussie.room_aushop", "Outback Imports"],
|
||||||
["aussie.room_hos", "Medical Center"],
|
["aussie.room_hos", "Medical Center"],
|
||||||
|
["appondale.room_museumtheater", "Museum Theater"],
|
||||||
|
["crystal_sands.room_tiertheater", "Tierney's Theater"],
|
||||||
|
["lost_temple_of_zios.bb_theater", "Temple Theater"],
|
||||||
]);
|
]);
|
||||||
const VOLUME_SHOP = 12; // ActorVolume.type: clicking it opens generic list `typeDefId`
|
const VOLUME_SHOP = 12; // ActorVolume.type: clicking it opens generic list `typeDefId`
|
||||||
|
|
||||||
@@ -36,7 +41,7 @@ const parse = body => {
|
|||||||
const settings = (room.actors.ActorSettings || [])[0] || {};
|
const settings = (room.actors.ActorSettings || [])[0] || {};
|
||||||
const volumes = room.actors.ActorVolume || [];
|
const volumes = room.actors.ActorVolume || [];
|
||||||
return {
|
return {
|
||||||
name: typeof settings.name === "string" && settings.name.trim() !== UNNAMED ? settings.name.trim() : "",
|
name: typeof settings.name === "string" && !UNNAMED.includes(settings.name.trim().toLowerCase()) ? settings.name.trim() : "",
|
||||||
shops: new Set(volumes.filter(volume => Number(volume.type) === VOLUME_SHOP).map(volume => Number(volume.typeDefId))),
|
shops: new Set(volumes.filter(volume => Number(volume.type) === VOLUME_SHOP).map(volume => Number(volume.typeDefId))),
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -71,7 +76,7 @@ const preload = async () => {
|
|||||||
remember(base, body);
|
remember(base, body);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
console.log(`[rooms] names of ${rooms.size} rooms read from the cache`);
|
console.log(`[rooms] names of ${logText(rooms.size)} rooms read from the cache`);
|
||||||
};
|
};
|
||||||
|
|
||||||
// A name made from the path, for a room not read yet or left unnamed:
|
// A name made from the path, for a room not read yet or left unnamed:
|
||||||
|
|||||||
+43
-14
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const crypto = require("crypto");
|
const crypto = require("crypto");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const net = require("net");
|
const net = require("net");
|
||||||
@@ -17,7 +18,10 @@ const limits = require("./limits.js");
|
|||||||
const POLICY = '<cross-domain-policy><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>';
|
const POLICY = '<cross-domain-policy><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>';
|
||||||
const MAX_MESSAGE = 64 * 1024;
|
const MAX_MESSAGE = 64 * 1024;
|
||||||
const RATE_WINDOW_MS = 10000;
|
const RATE_WINDOW_MS = 10000;
|
||||||
const MAX_BACKLOG = 4 * 1024 * 1024;
|
// above what login writes in one go before the client reads any of it: every
|
||||||
|
// custom colour and custom item def (~4.2 MB on 2026-10-19, at the caps of
|
||||||
|
// 20000 colours and 5000 clothing), which a 4 MB limit cut off for everyone.
|
||||||
|
const MAX_BACKLOG = 16 * 1024 * 1024;
|
||||||
const MAX_ERRORS_PER_WINDOW = 20;
|
const MAX_ERRORS_PER_WINDOW = 20;
|
||||||
// the Create Account screens are done in a few minutes; a guest connection
|
// 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.
|
// does not get to stay for as long as it keeps sending something.
|
||||||
@@ -27,6 +31,8 @@ const SIGNUP_LIFETIME_MS = 5 * 60000;
|
|||||||
const forLog = message => message.replace(/(<pword><!\[CDATA\[)[\s\S]*?(\]\]>)/, "$1(hidden)$2");
|
const forLog = message => message.replace(/(<pword><!\[CDATA\[)[\s\S]*?(\]\]>)/, "$1(hidden)$2");
|
||||||
|
|
||||||
const connections = new Map(); // remote address -> open sockets
|
const connections = new Map(); // remote address -> open sockets
|
||||||
|
let connectionCount = 0;
|
||||||
|
const metrics = {accepted: 0, rejected: 0, floodDisconnects: 0, handlerErrors: 0};
|
||||||
|
|
||||||
let nextUserId = 1;
|
let nextUserId = 1;
|
||||||
|
|
||||||
@@ -49,7 +55,7 @@ class Session {
|
|||||||
write(message) {
|
write(message) {
|
||||||
if (this.socket.writable) {
|
if (this.socket.writable) {
|
||||||
if (config.logPackets) {
|
if (config.logPackets) {
|
||||||
console.log(`[game] -> ${this.name} ${message}`);
|
console.log(`[game] -> ${logText(this.name)} ${logText(message)}`);
|
||||||
}
|
}
|
||||||
this.socket.write(message + "\0");
|
this.socket.write(message + "\0");
|
||||||
// A client that stopped reading must not pile up messages here forever.
|
// A client that stopped reading must not pile up messages here forever.
|
||||||
@@ -96,7 +102,7 @@ const parseSys = message => {
|
|||||||
const start = handlers => new Promise((resolve, reject) => {
|
const start = handlers => new Promise((resolve, reject) => {
|
||||||
const dispatch = (session, message) => {
|
const dispatch = (session, message) => {
|
||||||
if (config.logPackets) {
|
if (config.logPackets) {
|
||||||
console.log(`[game] <- ${session.name} ${forLog(message)}`);
|
console.log(`[game] <- ${logText(session.name)} ${logText(forLog(message))}`);
|
||||||
}
|
}
|
||||||
if (message.startsWith("<policy-file-request")) {
|
if (message.startsWith("<policy-file-request")) {
|
||||||
session.socket.end(POLICY + "\0");
|
session.socket.end(POLICY + "\0");
|
||||||
@@ -138,13 +144,18 @@ const start = handlers => new Promise((resolve, reject) => {
|
|||||||
const onConnection = socket => {
|
const onConnection = socket => {
|
||||||
const address = limits.key(socket.remoteAddress);
|
const address = limits.key(socket.remoteAddress);
|
||||||
const open = connections.get(address) || 0;
|
const open = connections.get(address) || 0;
|
||||||
const total = [...connections.values()].reduce((sum, count) => sum + count, 0);
|
// Kept as a counter instead of summing every address on every new socket.
|
||||||
|
// Under a burst of logins the old O(addresses) work delayed everyone else.
|
||||||
|
const total = connectionCount;
|
||||||
socket.on("error", () => {});
|
socket.on("error", () => {});
|
||||||
if (open >= config.maxConnectionsPerAddress || total >= config.maxConnections) {
|
if (open >= config.maxConnectionsPerAddress || total >= config.maxConnections) {
|
||||||
|
metrics.rejected++;
|
||||||
socket.destroy();
|
socket.destroy();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
connections.set(address, open + 1);
|
connections.set(address, open + 1);
|
||||||
|
connectionCount++;
|
||||||
|
metrics.accepted++;
|
||||||
|
|
||||||
const session = new Session(socket);
|
const session = new Session(socket);
|
||||||
let buffer = Buffer.alloc(0);
|
let buffer = Buffer.alloc(0);
|
||||||
@@ -153,7 +164,7 @@ const start = handlers => new Promise((resolve, reject) => {
|
|||||||
let bytesInWindow = 0;
|
let bytesInWindow = 0;
|
||||||
let errorsInWindow = 0;
|
let errorsInWindow = 0;
|
||||||
socket.setNoDelay(true);
|
socket.setNoDelay(true);
|
||||||
console.log(`[game] ${session.remote} connected as #${session.id}`);
|
console.log(`[game] ${logText(session.remote)} connected as #${logText(session.id)}`);
|
||||||
|
|
||||||
// whoever connects has to log in (or start signing up) promptly, and
|
// whoever connects has to log in (or start signing up) promptly, and
|
||||||
// nobody may sit silent for long: the client sends keep-alives.
|
// nobody may sit silent for long: the client sends keep-alives.
|
||||||
@@ -178,11 +189,15 @@ const start = handlers => new Promise((resolve, reject) => {
|
|||||||
}
|
}
|
||||||
bytesInWindow += chunk.length;
|
bytesInWindow += chunk.length;
|
||||||
if (bytesInWindow > config.maxBytesPerTenSeconds) {
|
if (bytesInWindow > config.maxBytesPerTenSeconds) {
|
||||||
console.log(`[game] ${session.name} disconnected for flooding`);
|
metrics.floodDisconnects++;
|
||||||
|
console.log(`[game] ${logText(session.name)} disconnected for flooding`);
|
||||||
socket.destroy();
|
socket.destroy();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
buffer = Buffer.concat([buffer, chunk]);
|
// Node normally gives complete SmartFox packets in one chunk. Avoiding
|
||||||
|
// Buffer.concat in that common case reduces allocation and GC during
|
||||||
|
// busy logins; fragments still retain the exact old behaviour.
|
||||||
|
buffer = buffer.length === 0 ? chunk : Buffer.concat([buffer, chunk]);
|
||||||
let end;
|
let end;
|
||||||
while ((end = buffer.indexOf(0)) !== -1) {
|
while ((end = buffer.indexOf(0)) !== -1) {
|
||||||
if (end > MAX_MESSAGE) {
|
if (end > MAX_MESSAGE) {
|
||||||
@@ -190,7 +205,8 @@ const start = handlers => new Promise((resolve, reject) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (++messagesInWindow > config.maxMessagesPerTenSeconds) {
|
if (++messagesInWindow > config.maxMessagesPerTenSeconds) {
|
||||||
console.log(`[game] ${session.name} disconnected for flooding`);
|
metrics.floodDisconnects++;
|
||||||
|
console.log(`[game] ${logText(session.name)} disconnected for flooding`);
|
||||||
socket.destroy();
|
socket.destroy();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -200,12 +216,13 @@ const start = handlers => new Promise((resolve, reject) => {
|
|||||||
dispatch(session, message);
|
dispatch(session, message);
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
|
metrics.handlerErrors++;
|
||||||
// one line a failure, and an end to them: a client that sends
|
// one line a failure, and an end to them: a client that sends
|
||||||
// nonsense in a loop is not to fill the log.
|
// nonsense in a loop is not to fill the log.
|
||||||
const where = String(err.stack || "").split("\n")[1] || "";
|
const where = String(err.stack || "").split("\n")[1] || "";
|
||||||
console.log(`[game] error handling message from ${session.name}: ${err.message}${where ? ` (${where.trim()})` : ""}`);
|
console.log(`[game] error handling message from ${logText(session.name)}: ${logText(err.message)}${logText(where ? ` (${where.trim()})` : "")}`);
|
||||||
if (++errorsInWindow > MAX_ERRORS_PER_WINDOW) {
|
if (++errorsInWindow > MAX_ERRORS_PER_WINDOW) {
|
||||||
console.log(`[game] ${session.name} disconnected: too many messages that could not be handled`);
|
console.log(`[game] ${logText(session.name)} disconnected: too many messages that could not be handled`);
|
||||||
socket.destroy();
|
socket.destroy();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -228,13 +245,14 @@ const start = handlers => new Promise((resolve, reject) => {
|
|||||||
else {
|
else {
|
||||||
connections.delete(address);
|
connections.delete(address);
|
||||||
}
|
}
|
||||||
console.log(`[game] ${session.name} disconnected`);
|
connectionCount = Math.max(0, connectionCount - 1);
|
||||||
|
console.log(`[game] ${logText(session.name)} disconnected`);
|
||||||
// nothing thrown while a player is seen off may take the server down.
|
// nothing thrown while a player is seen off may take the server down.
|
||||||
try {
|
try {
|
||||||
handlers.close(session);
|
handlers.close(session);
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
console.log(`[game] error while ${session.name} left: ${err.stack}`);
|
console.log(`[game] error while ${logText(session.name)} left: ${logText(err.stack)}`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -271,9 +289,20 @@ const start = handlers => new Promise((resolve, reject) => {
|
|||||||
}
|
}
|
||||||
server.once("error", reject);
|
server.once("error", reject);
|
||||||
server.listen(config.gamePort, config.gameBindAddress, () => {
|
server.listen(config.gamePort, config.gameBindAddress, () => {
|
||||||
console.log(`[game] listening on ${config.gameBindAddress}:${config.gamePort}${config.tls ? " (TLS)" : ""}`);
|
console.log(`[game] listening on ${logText(config.gameBindAddress)}:${logText(config.gamePort)}${logText(config.tls ? " (TLS)" : "")}`);
|
||||||
resolve(server);
|
resolve(server);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = {start};
|
// This intentionally exposes counts only: staff can see whether the service
|
||||||
|
// is healthy without receiving player addresses or packet contents.
|
||||||
|
const health = () => ({
|
||||||
|
openConnections: connectionCount,
|
||||||
|
connectedAddresses: connections.size,
|
||||||
|
accepted: metrics.accepted,
|
||||||
|
rejected: metrics.rejected,
|
||||||
|
floodDisconnects: metrics.floodDisconnects,
|
||||||
|
handlerErrors: metrics.handlerErrors,
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = {start, health};
|
||||||
+3
-1
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const crypto = require("crypto");
|
const crypto = require("crypto");
|
||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
const bans = require("./bans.js");
|
const bans = require("./bans.js");
|
||||||
@@ -24,6 +25,7 @@ const STATUS = {
|
|||||||
username_taken: USERNAME_TAKEN,
|
username_taken: USERNAME_TAKEN,
|
||||||
invalid_username: USERNAME_INVALID,
|
invalid_username: USERNAME_INVALID,
|
||||||
invalid_password: PASSWORD_INVALID,
|
invalid_password: PASSWORD_INVALID,
|
||||||
|
weak_password: PASSWORD_INVALID, // the game's screens have one word for both
|
||||||
name_not_allowed: USERNAME_INVALID,
|
name_not_allowed: USERNAME_INVALID,
|
||||||
};
|
};
|
||||||
// names asked about on one guest connection: the screens ask once or twice.
|
// names asked about on one guest connection: the screens ask once or twice.
|
||||||
@@ -88,7 +90,7 @@ const handlers = {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!limits.registrationAllowed(session.address, limits.isTrustedLocal(session.address))) {
|
if (!limits.registrationAllowed(session.address, limits.isTrustedLocal(session.address))) {
|
||||||
console.log(`[signup] too many sign-ups from ${session.address}`);
|
console.log(`[signup] too many sign-ups from ${logText(session.address)}`);
|
||||||
session.sendXt("lc", -1, FAILED, 0);
|
session.sendXt("lc", -1, FAILED, 0);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
+132
-1
@@ -2,7 +2,11 @@
|
|||||||
|
|
||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
const bans = require("./bans.js");
|
const bans = require("./bans.js");
|
||||||
|
const devices = require("./devices.js");
|
||||||
|
const limits = require("./limits.js");
|
||||||
const manage = require("./manage.js");
|
const manage = require("./manage.js");
|
||||||
|
const modlog = require("./modlog.js");
|
||||||
|
const reports = require("./reports.js");
|
||||||
const support = require("./support.js");
|
const support = require("./support.js");
|
||||||
const world = require("./world.js");
|
const world = require("./world.js");
|
||||||
|
|
||||||
@@ -25,6 +29,29 @@ const disciplined = () => accounts.all()
|
|||||||
.filter(entry => entry.banned !== 0 || entry.silenced !== 0)
|
.filter(entry => entry.banned !== 0 || entry.silenced !== 0)
|
||||||
.sort((a, b) => a.username.localeCompare(b.username));
|
.sort((a, b) => a.username.localeCompare(b.username));
|
||||||
|
|
||||||
|
// accounts by name, for both panels' search: at most `limit`, those named
|
||||||
|
// exactly what was typed first, then those whose names start with it, then
|
||||||
|
// those with it anywhere, online players first within each and then by
|
||||||
|
// name. so "John" is never lost among John123 and Johnathan. with nothing
|
||||||
|
// typed: online players, then the ones seen last. `keep` narrows it
|
||||||
|
// (online, banned...). returns {found, total}: total is how many matched.
|
||||||
|
const MAX_FOUND = 50;
|
||||||
|
const findAccounts = (query, keep = () => true, limit = MAX_FOUND) => {
|
||||||
|
const wanted = String(query || "").trim().toLowerCase().slice(0, 100);
|
||||||
|
const online = new Set(world.players().map(player => player.username));
|
||||||
|
const rank = name => {
|
||||||
|
const low = name.toLowerCase();
|
||||||
|
return low === wanted ? 0 : low.startsWith(wanted) ? 1 : 2;
|
||||||
|
};
|
||||||
|
const matched = accounts.all().filter(account => account.username.toLowerCase().includes(wanted) && keep(account, online));
|
||||||
|
const sorted = wanted
|
||||||
|
? matched.sort((a, b) => rank(a.username) - rank(b.username) || Number(online.has(b.username)) - Number(online.has(a.username))
|
||||||
|
|| a.username.localeCompare(b.username))
|
||||||
|
: matched.sort((a, b) => Number(online.has(b.username)) - Number(online.has(a.username))
|
||||||
|
|| (b.lastSeen || b.lastLogin || 0) - (a.lastSeen || a.lastLogin || 0));
|
||||||
|
return {found: sorted.slice(0, limit), total: matched.length};
|
||||||
|
};
|
||||||
|
|
||||||
// the accounts that signed in from an address, or from any address that
|
// the accounts that signed in from an address, or from any address that
|
||||||
// starts with what was typed ("203.0.113." for the lot): from the sign-in
|
// starts with what was typed ("203.0.113." for the lot): from the sign-in
|
||||||
// histories, which hold the last 90 days (lib/accounts.js). failed tries
|
// histories, which hold the last 90 days (lib/accounts.js). failed tries
|
||||||
@@ -67,6 +94,110 @@ const banAddress = (address, reason, by) => {
|
|||||||
return result.error ? {error: ADDRESS_ERRORS[result.error]} : {ban: result.ban, out: world.disconnectAddress(result.ban.address)};
|
return result.error ? {error: ADDRESS_ERRORS[result.error]} : {ban: result.ban, out: world.disconnectAddress(result.ban.address)};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// bans every computer the account signed in from lately (lib/devices.js),
|
||||||
|
// and puts out whoever plays from one of them, whichever account. their
|
||||||
|
// sign-ins stay, as with an address ban: the client asks with one why its
|
||||||
|
// game stopped, and the account page stays open to them for an appeal; the
|
||||||
|
// game itself turns them away (lib/world.js). returns {ok, detail} or {error}.
|
||||||
|
const banDevices = (account, reason, by) => {
|
||||||
|
const result = devices.banAccount(account, reason, by);
|
||||||
|
if (result.error) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
const under = devices.accountsUnder(result.ban);
|
||||||
|
const out = world.disconnectBanned(under);
|
||||||
|
bans.record({account, action: "device_ban", seconds: -1, reason: result.ban.reason, by});
|
||||||
|
const others = under.filter(one => one !== account).map(one => one.username);
|
||||||
|
return {ok: `${account.username} is hardware banned (${result.ban.ids.length} IDs).${out ? ` ${out} playing from them ${out === 1 ? "was" : "were"} put out.` : ""}`
|
||||||
|
+ `${others.length ? ` Also used by: ${others.slice(0, 10).join(", ")}${others.length > 10 ? "…" : ""}.` : ""}`, detail: result.ban.reason};
|
||||||
|
};
|
||||||
|
|
||||||
|
const unbanDevices = (id, by) => {
|
||||||
|
const ban = devices.unban(id);
|
||||||
|
if (!ban) {
|
||||||
|
return {error: "No such hardware ban."};
|
||||||
|
}
|
||||||
|
bans.record({account: accounts.byId(ban.accountId), action: "device_unban", by});
|
||||||
|
return {ok: `The hardware ban made with ${ban.username || "that account"} is lifted.`, username: ban.username};
|
||||||
|
};
|
||||||
|
|
||||||
|
// every computer ban that keeps the account out, or was made with it, lifted.
|
||||||
|
const unbanDevicesOf = (account, by) => {
|
||||||
|
const lifted = devices.bansOfAccount(account).map(ban => unbanDevices(ban.id, by)).filter(result => result.ok);
|
||||||
|
if (!lifted.length) {
|
||||||
|
return {error: "None of their hardware is banned."};
|
||||||
|
}
|
||||||
|
const names = [...new Set(lifted.map(result => result.username).filter(Boolean))];
|
||||||
|
return {ok: `${lifted.length === 1 ? "1 hardware ban was" : `${lifted.length} hardware bans were`} lifted${names.length ? ` (made with ${names.join(", ")})` : ""}.`,
|
||||||
|
detail: names.join(", ")};
|
||||||
|
};
|
||||||
|
|
||||||
|
// the accounts that used a computer id, or one starting with what was
|
||||||
|
// typed (lib/devices.js): {error} or {players: [{username, kinds, lastAt}]}.
|
||||||
|
const byDevice = query => {
|
||||||
|
const found = devices.search(query);
|
||||||
|
return found.error ? found : {players: found.players.map(entry => ({username: entry.account.username, kinds: entry.kinds, lastAt: entry.lastAt}))};
|
||||||
|
};
|
||||||
|
|
||||||
|
// other accounts the same person may have: those that used one of its
|
||||||
|
// computers (lib/devices.js), and those that signed in from one of its
|
||||||
|
// addresses in the last 90 days. [{username, devices: [kind],
|
||||||
|
// addresses: count, online, banned}], the likeliest first. the addresses
|
||||||
|
// themselves are not given: moderators do not see them.
|
||||||
|
const altsOf = account => {
|
||||||
|
const found = new Map();
|
||||||
|
const entry = username => {
|
||||||
|
if (!found.has(username)) {
|
||||||
|
found.set(username, {username, devices: [], addresses: 0});
|
||||||
|
}
|
||||||
|
return found.get(username);
|
||||||
|
};
|
||||||
|
for (const alt of devices.alts(account)) {
|
||||||
|
Object.assign(entry(alt.username), {devices: alt.kinds});
|
||||||
|
}
|
||||||
|
const mine = new Set(account.logins.filter(login => login.ok && login.address && !limits.isLoopback(login.address)).map(login => login.address));
|
||||||
|
if (mine.size) {
|
||||||
|
for (const other of accounts.all()) {
|
||||||
|
if (other !== account) {
|
||||||
|
const shared = new Set(other.logins.filter(login => login.ok && mine.has(login.address)).map(login => login.address));
|
||||||
|
if (shared.size) {
|
||||||
|
entry(other.username).addresses = shared.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...found.values()].map(alt => {
|
||||||
|
const other = accounts.byName(alt.username);
|
||||||
|
return {...alt, online: Boolean(world.findOnline(alt.username)), banned: other ? world.moderation.banRemaining(other) : 0,
|
||||||
|
deviceBanned: other ? devices.bannedId(other) !== 0 : false};
|
||||||
|
}).sort((one, other) => Number(other.devices.length > 0) - Number(one.devices.length > 0)
|
||||||
|
|| other.devices.length - one.devices.length || other.addresses - one.addresses || one.username.localeCompare(other.username)).slice(0, 100);
|
||||||
|
};
|
||||||
|
|
||||||
|
// one player's story, newest first: bans given and lifted, what staff did
|
||||||
|
// to them, the reports about them, and what their computers gave away
|
||||||
|
// (lib/devices.js). [{at, kind, text, by}].
|
||||||
|
const BAN_WORDS = {ban: "Banned", unban: "Ban lifted", reason: "Ban reason changed", appeal: "Appealed", appeal_approved: "Appeal approved",
|
||||||
|
appeal_denied: "Appeal denied", device_ban: "Hardware banned", device_unban: "Hardware ban lifted"};
|
||||||
|
const timelineOf = account => {
|
||||||
|
const events = [];
|
||||||
|
for (const entry of bans.historyOf(account)) {
|
||||||
|
const length = entry.action === "ban" ? (entry.seconds === -1 ? "for good" : `${Math.round(entry.seconds / 3600)} h`) : "";
|
||||||
|
events.push({at: entry.at, kind: "ban", text: [BAN_WORDS[entry.action] || entry.action, length, entry.reason].filter(Boolean).join(" · "), by: entry.by});
|
||||||
|
}
|
||||||
|
for (const entry of modlog.about(account.username)) {
|
||||||
|
events.push({at: entry.at, kind: "staff", text: [entry.action, entry.detail].filter(Boolean).join(" · "), by: entry.by});
|
||||||
|
}
|
||||||
|
for (const report of reports.about(account.username)) {
|
||||||
|
events.push({at: report.createdAt, kind: "report", text: `Reported: ${report.reason}${report.detail ? ` · ${report.detail}` : ""}${report.handledAt ? "" : " (waiting)"}`,
|
||||||
|
by: report.reporter});
|
||||||
|
}
|
||||||
|
for (const entry of devices.alertsOf(account)) {
|
||||||
|
events.push({at: entry.at, kind: "alert", text: `${entry.name} · ${entry.detail}`, by: ""});
|
||||||
|
}
|
||||||
|
return events.sort((one, other) => other.at - one.at).slice(0, 200);
|
||||||
|
};
|
||||||
|
|
||||||
// appeals with what each is against, as it stands now.
|
// appeals with what each is against, as it stands now.
|
||||||
const appealsFor = handled => bans.appeals(handled).map(appeal => {
|
const appealsFor = handled => bans.appeals(handled).map(appeal => {
|
||||||
const account = accounts.byId(appeal.accountId);
|
const account = accounts.byId(appeal.accountId);
|
||||||
@@ -122,4 +253,4 @@ const answerNameRequest = (id, approve) => {
|
|||||||
return {ok: `${oldName} is now called ${account.username}. They log in with the new name and the same password.`, username: account.username};
|
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, byAddress, banAddress, appealsFor, answerAppeal, answerNameRequest};
|
module.exports = {disciplined, findAccounts, byAddress, banAddress, banDevices, unbanDevices, unbanDevicesOf, byDevice, altsOf, timelineOf, appealsFor, answerAppeal, answerNameRequest};
|
||||||
+3
-2
@@ -1,5 +1,6 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
|
|
||||||
// what players send from the account page (/account, lib/manage.js) for
|
// what players send from the account page (/account, lib/manage.js) for
|
||||||
@@ -79,7 +80,7 @@ const requestName = (account, newName, reason) => {
|
|||||||
db().prepare("UPDATE name_requests SET status = ?, handled_at = ? WHERE account_id = ? AND status = ?").run(WITHDRAWN, now(), account.id, WAITING);
|
db().prepare("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 (?, ?, ?, ?, ?)")
|
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));
|
.run(now(), account.id, account.username, newName, clean(reason, MAX_REASON));
|
||||||
console.log(`[support] "${account.username}" asked to be called "${newName}"`);
|
console.log(`[support] "${logText(account.username)}" asked to be called "${logText(newName)}"`);
|
||||||
return {request: waitingNameRequest(account)};
|
return {request: waitingNameRequest(account)};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -127,7 +128,7 @@ const sendFeedback = (account, kind, text) => {
|
|||||||
return {error: "too_many"};
|
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);
|
db().prepare("INSERT INTO feedback (created_at, account_id, username, kind, text) VALUES (?, ?, ?, ?, ?)").run(now(), account.id, account.username, kind, body);
|
||||||
console.log(`[support] ${kind === "bug" ? "bug report" : "feedback"} from "${account.username}"`);
|
console.log(`[support] ${logText(kind === "bug" ? "bug report" : "feedback")} from "${logText(account.username)}"`);
|
||||||
return {ok: true};
|
return {ok: true};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
const zlib = require("zlib");
|
||||||
|
const amf3 = require("./amf3.js");
|
||||||
|
|
||||||
|
// a room file of a seasonal theme comes from an older build (lib/http.js,
|
||||||
|
// roomAsSeenBy in lib/world.js), and so do its clickable spots: a shop there
|
||||||
|
// names the generic list it had then, which today's lists may have as
|
||||||
|
// something else or as nothing, so one theme's shops worked and another's
|
||||||
|
// did not. each spot the room has today too (by its name) is given today's
|
||||||
|
// list, kind and message; what only the old room has stays as it was.
|
||||||
|
|
||||||
|
// the volume fields that say what a click does (RoomManagerWorld: type 1 a
|
||||||
|
// minigame by typeDefId, 7 a message, 12 a generic list)
|
||||||
|
const ACTION_FIELDS = ["type", "typeDefId", "message"];
|
||||||
|
const MAX_KEPT = 40; // rooms remembered, made once each (files of up to a few MB)
|
||||||
|
|
||||||
|
const kept = new Map(); // old file's path -> the file with today's spots, or null for "as it was"
|
||||||
|
|
||||||
|
const volumes = room => (room && room.actors && Array.isArray(room.actors.ActorVolume) ? room.actors.ActorVolume : []);
|
||||||
|
|
||||||
|
const withTodaysSpots = (oldBody, currentBody) => {
|
||||||
|
const old = amf3.decode(zlib.inflateSync(oldBody));
|
||||||
|
const today = new Map(volumes(amf3.decode(zlib.inflateSync(currentBody))).filter(volume => volume && volume.name).map(volume => [volume.name, volume]));
|
||||||
|
let changed = false;
|
||||||
|
for (const volume of volumes(old)) {
|
||||||
|
const now = volume && today.get(volume.name);
|
||||||
|
if (now && ACTION_FIELDS.some(field => volume[field] !== now[field])) {
|
||||||
|
for (const field of ACTION_FIELDS) {
|
||||||
|
if (now[field] === undefined) {
|
||||||
|
delete volume[field];
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
volume[field] = now[field];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return changed ? zlib.deflateSync(amf3.encode(old)) : oldBody;
|
||||||
|
};
|
||||||
|
|
||||||
|
// `oldBody` with today's spots, `current` giving today's file (or null);
|
||||||
|
// the old one as it was when that cannot be had or read.
|
||||||
|
const fix = async (key, oldBody, current) => {
|
||||||
|
if (kept.has(key)) {
|
||||||
|
return kept.get(key) || oldBody;
|
||||||
|
}
|
||||||
|
let body = oldBody;
|
||||||
|
try {
|
||||||
|
const currentBody = await current();
|
||||||
|
if (currentBody) {
|
||||||
|
body = withTodaysSpots(oldBody, currentBody);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.log(`[themes] ${key}: ${err.message}`);
|
||||||
|
body = oldBody;
|
||||||
|
}
|
||||||
|
if (kept.size >= MAX_KEPT) {
|
||||||
|
kept.delete(kept.keys().next().value);
|
||||||
|
}
|
||||||
|
kept.set(key, body === oldBody ? null : body);
|
||||||
|
return body;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {fix};
|
||||||
+17
-7
@@ -15,7 +15,7 @@ const TYPE_CLOTHING = 0;
|
|||||||
const TYPE_DEN_ITEM = 1;
|
const TYPE_DEN_ITEM = 1;
|
||||||
const TYPE_PET = 3;
|
const TYPE_PET = 3;
|
||||||
|
|
||||||
const MAX_TRADE_ITEMS = 50;
|
const MAX_TRADE_ITEMS = 200; // on a trade list (the game sets no end to it; past this the rest were dropped)
|
||||||
const MAX_PETS = 1000; // as in lib/pets.js
|
const MAX_PETS = 1000; // as in lib/pets.js
|
||||||
|
|
||||||
// "ti" request steps (first parameter from the client)
|
// "ti" request steps (first parameter from the client)
|
||||||
@@ -53,8 +53,11 @@ module.exports = ({findOnline, blocks}) => {
|
|||||||
// createdTs, lBits, uBits, eBits, name, personality, toy, food)...]
|
// createdTs, lBits, uBits, eBits, name, personality, toy, food)...]
|
||||||
const sendTradeList = (to, account) => {
|
const sendTradeList = (to, account) => {
|
||||||
const listed = type => account.tradeList.filter(entry => entry.type === type).map(entry => entry.inv);
|
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));
|
// one whose def is gone (a custom item deleted) is left out: the client
|
||||||
const denItems = account.denItems.filter(item => listed(TYPE_DEN_ITEM).includes(item.inv) && masterpieces.itemApproved(item));
|
// cannot make an item of it, and the list stopped there.
|
||||||
|
const clothing = account.items.filter(item => listed(TYPE_CLOTHING).includes(item.inv) && defpacks.itemDef(item.def));
|
||||||
|
const denItems = account.denItems.filter(item => listed(TYPE_DEN_ITEM).includes(item.inv) && masterpieces.itemApproved(item)
|
||||||
|
&& defpacks.denItemDef(item.def));
|
||||||
const pets = account.pets.filter(pet => listed(TYPE_PET).includes(pet.inv));
|
const pets = account.pets.filter(pet => listed(TYPE_PET).includes(pet.inv));
|
||||||
to.sendXt("tl", -1, account.username,
|
to.sendXt("tl", -1, account.username,
|
||||||
clothing.length, ...clothing.flatMap(item => [item.def, item.inv, item.color]),
|
clothing.length, ...clothing.flatMap(item => [item.def, item.inv, item.color]),
|
||||||
@@ -71,8 +74,10 @@ module.exports = ({findOnline, blocks}) => {
|
|||||||
(type === TYPE_CLOTHING ? account.items : type === TYPE_DEN_ITEM ? account.denItems : type === TYPE_PET ? account.pets : []);
|
(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.
|
// A masterpiece still waiting for review is nobody's to trade.
|
||||||
|
// nor one whose def is gone.
|
||||||
const find = (account, type, inv) => collectionOf(account, type)
|
const find = (account, type, inv) => collectionOf(account, type)
|
||||||
.find(entry => entry.inv === inv && (type !== TYPE_DEN_ITEM || masterpieces.itemApproved(entry)));
|
.find(entry => entry.inv === inv && (type !== TYPE_DEN_ITEM || masterpieces.itemApproved(entry))
|
||||||
|
&& (type === TYPE_CLOTHING ? Boolean(defpacks.itemDef(entry.def)) : type === TYPE_DEN_ITEM ? Boolean(defpacks.denItemDef(entry.def)) : true));
|
||||||
|
|
||||||
// the field layouts differ between the offer the owner is shown (no
|
// the field layouts differ between the offer the owner is shown (no
|
||||||
// inventory ids for clothing and den items) and the completed trade.
|
// inventory ids for clothing and den items) and the completed trade.
|
||||||
@@ -129,6 +134,10 @@ module.exports = ({findOnline, blocks}) => {
|
|||||||
return coming === 0 || collectionOf(account, type).length + coming - gives.filter(item => item.type === type).length <= max;
|
return coming === 0 || collectionOf(account, type).length + coming - gives.filter(item => item.type === type).length <= max;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const endTrade = trade => {
|
||||||
|
trade.requester.trade = trade.owner.trade = null;
|
||||||
|
};
|
||||||
|
|
||||||
// ends the trade `session` is part of, telling the other side with `status`.
|
// ends the trade `session` is part of, telling the other side with `status`.
|
||||||
const abandon = (session, status) => {
|
const abandon = (session, status) => {
|
||||||
const {trade} = session;
|
const {trade} = session;
|
||||||
@@ -136,7 +145,7 @@ module.exports = ({findOnline, blocks}) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const other = trade.requester === session ? trade.owner : trade.requester;
|
const other = trade.requester === session ? trade.owner : trade.requester;
|
||||||
trade.requester.trade = trade.owner.trade = null;
|
endTrade(trade);
|
||||||
other.sendXt("ti", -1, status, session.account.username, USERNAME_SHOWN);
|
other.sendXt("ti", -1, status, session.account.username, USERNAME_SHOWN);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -250,7 +259,7 @@ module.exports = ({findOnline, blocks}) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const {requester, owner, wantedType, wanted, offered} = trade;
|
const {requester, owner, wantedType, wanted, offered} = trade;
|
||||||
requester.trade = owner.trade = null;
|
endTrade(trade);
|
||||||
// either side may have recycled or re-traded something while deciding.
|
// either side may have recycled or re-traded something while deciding.
|
||||||
const stillThere = collectionOf(owner.account, wantedType).includes(wanted)
|
const stillThere = collectionOf(owner.account, wantedType).includes(wanted)
|
||||||
&& offered.every(item => collectionOf(requester.account, item.type).includes(item.entry))
|
&& offered.every(item => collectionOf(requester.account, item.type).includes(item.entry))
|
||||||
@@ -312,7 +321,8 @@ module.exports = ({findOnline, blocks}) => {
|
|||||||
sendTradeList(session, account);
|
sendTradeList(session, account);
|
||||||
},
|
},
|
||||||
|
|
||||||
// ["1"/"0"]: busy flag while the trade window is open; nothing to answer.
|
// ["1"/"0"]: busy flag while the trade window is open; nothing to
|
||||||
|
// answer.
|
||||||
tb() {},
|
tb() {},
|
||||||
|
|
||||||
ti(session, roomId, params) {
|
ti(session, roomId, params) {
|
||||||
|
|||||||
+16
-2
@@ -1,10 +1,12 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
const {logText} = require("./logtext.js");
|
||||||
const crypto = require("crypto");
|
const crypto = require("crypto");
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const path = require("path");
|
const path = require("path");
|
||||||
const accounts = require("./accounts.js");
|
const accounts = require("./accounts.js");
|
||||||
const chatFilter = require("./chatfilter.js");
|
const chatFilter = require("./chatfilter.js");
|
||||||
|
const chatlog = require("./chatlog.js");
|
||||||
const masterpieces = require("./masterpieces.js");
|
const masterpieces = require("./masterpieces.js");
|
||||||
const limits = require("./limits.js");
|
const limits = require("./limits.js");
|
||||||
const {isUint} = require("./player.js");
|
const {isUint} = require("./player.js");
|
||||||
@@ -72,6 +74,15 @@ const flat = value => scalar(value) || (typeof value === "object" && !Array.isAr
|
|||||||
&& Object.keys(value).length <= 12 && Object.values(value).every(scalar));
|
&& 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 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);
|
const whole = value => (Number.isInteger(Number(value)) ? Number(value) : 0);
|
||||||
|
// the photo booth picture ("pb", PlayerWallGui): one level deeper than the
|
||||||
|
// rest, {avatar: {id, color1.., eyes, pattern}, bgid, pet: {ts, lbits, ..} |
|
||||||
|
// null, items: [{id, color}, ..]}. it was turned away as too deep, and the
|
||||||
|
// owner's whole change with it: the photo never stayed. an animal wearing
|
||||||
|
// nothing has no items list at all (null), which was turned away too.
|
||||||
|
const MAX_PHOTO_ITEMS = 30;
|
||||||
|
const photoParam = value => value === null || (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length <= 6
|
||||||
|
&& Object.entries(value).every(([key, part]) => (key === "items" ? part === null || (Array.isArray(part) && part.length <= MAX_PHOTO_ITEMS && part.every(flat))
|
||||||
|
: key === "avatar" || key === "pet" ? part === null || flat(part) : scalar(part))));
|
||||||
|
|
||||||
module.exports = ({blocks, findOnline}) => {
|
module.exports = ({blocks, findOnline}) => {
|
||||||
const tokens = new Map(); // token -> {viewer: account id, owner: account id, expires}
|
const tokens = new Map(); // token -> {viewer: account id, owner: account id, expires}
|
||||||
@@ -154,7 +165,8 @@ module.exports = ({blocks, findOnline}) => {
|
|||||||
// the server's filter (lib/chatfilter.js) too.
|
// the server's filter (lib/chatfilter.js) too.
|
||||||
const rule = message ? chatFilter.broken(message) : null;
|
const rule = message ? chatFilter.broken(message) : null;
|
||||||
if (rule) {
|
if (rule) {
|
||||||
console.log(`[filter] ${viewer.username} on ${owner.username}'s wall: "${message}" (${rule})`);
|
console.log(`[filter] ${logText(viewer.username)} on ${logText(owner.username)}'s wall: "${logText(message)}" (${logText(rule)})`);
|
||||||
|
chatlog.recordTo(viewer, chatlog.WALL, owner.username, chatlog.NOT_SENT + message);
|
||||||
const session = findOnline(viewer.username);
|
const session = findOnline(viewer.username);
|
||||||
if (session) {
|
if (session) {
|
||||||
chatFilter.warn(session);
|
chatFilter.warn(session);
|
||||||
@@ -184,6 +196,8 @@ module.exports = ({blocks, findOnline}) => {
|
|||||||
if (typeof body.pp === "string" && owner.wall.posts.some(other => other.x === body.pp)) {
|
if (typeof body.pp === "string" && owner.wall.posts.some(other => other.x === body.pp)) {
|
||||||
post.pp = body.pp; // a reply to that post
|
post.pp = body.pp; // a reply to that post
|
||||||
}
|
}
|
||||||
|
// for the panels (lib/chatlog.js), as typed chat is.
|
||||||
|
chatlog.recordTo(viewer, chatlog.WALL, owner.username, message);
|
||||||
owner.wall.posts.push(post);
|
owner.wall.posts.push(post);
|
||||||
owner.wall.posts = owner.wall.posts.slice(-MAX_POSTS);
|
owner.wall.posts = owner.wall.posts.slice(-MAX_POSTS);
|
||||||
owner.wall.modified = post.t;
|
owner.wall.modified = post.t;
|
||||||
@@ -321,7 +335,7 @@ module.exports = ({blocks, findOnline}) => {
|
|||||||
const merged = changes && typeof changes === "object" && !Array.isArray(changes) ? {...wall.params} : null;
|
const merged = changes && typeof changes === "object" && !Array.isArray(changes) ? {...wall.params} : null;
|
||||||
for (const key of merged ? OWNER_PARAMS : []) {
|
for (const key of merged ? OWNER_PARAMS : []) {
|
||||||
if (changes[key] !== undefined) {
|
if (changes[key] !== undefined) {
|
||||||
if (!plainParam(changes[key])) {
|
if (!(key === "pb" ? photoParam(changes[key]) : plainParam(changes[key]))) {
|
||||||
session.sendXt("wps", -1, 0);
|
session.sendXt("wps", -1, 0);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
// Loaded only when a rule is read or saved. defpacks.js is imported while
|
||||||
|
// accounts.js is still defining its exports, so a top-level require here
|
||||||
|
// would retain that partial `{}` forever.
|
||||||
|
const accounts = () => require("./accounts.js");
|
||||||
|
|
||||||
|
// Clothing that staff have said must not be worn by certain animal types.
|
||||||
|
// This is deliberately its own small module: game code, def packs and the
|
||||||
|
// dashboards all ask the same source of truth, while itemcontrol.js owns
|
||||||
|
// validating dashboard input and removing existing uses.
|
||||||
|
|
||||||
|
const SETTING = "clothingWearRules";
|
||||||
|
|
||||||
|
let rules = null; // Map<clothing def id, Set<avatar type>>
|
||||||
|
|
||||||
|
const positiveInteger = value => Number.isSafeInteger(value) && value > 0;
|
||||||
|
|
||||||
|
const ruleMap = () => {
|
||||||
|
if (rules) {
|
||||||
|
return rules;
|
||||||
|
}
|
||||||
|
let saved = {};
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(accounts().setting(SETTING) || "{}");
|
||||||
|
saved = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
saved = {};
|
||||||
|
}
|
||||||
|
rules = new Map();
|
||||||
|
for (const [id, types] of Object.entries(saved)) {
|
||||||
|
const itemId = Number(id);
|
||||||
|
if (!positiveInteger(itemId) || !Array.isArray(types)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const blocked = new Set(types.map(Number).filter(positiveInteger));
|
||||||
|
if (blocked.size) {
|
||||||
|
rules.set(itemId, blocked);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rules;
|
||||||
|
};
|
||||||
|
|
||||||
|
const save = () => {
|
||||||
|
const stored = {};
|
||||||
|
for (const [id, types] of [...ruleMap()].sort(([one], [two]) => one - two)) {
|
||||||
|
stored[id] = [...types].sort((one, two) => one - two);
|
||||||
|
}
|
||||||
|
accounts().setSetting(SETTING, JSON.stringify(stored));
|
||||||
|
};
|
||||||
|
|
||||||
|
const blockedTypes = itemId => [...(ruleMap().get(Number(itemId)) || [])].sort((one, two) => one - two);
|
||||||
|
|
||||||
|
const all = () => [...ruleMap()].map(([id]) => ({id, blocked: blockedTypes(id)})).sort((one, two) => one.id - two.id);
|
||||||
|
|
||||||
|
const mayWear = (itemId, avatarType) => !ruleMap().get(Number(itemId))?.has(Number(avatarType));
|
||||||
|
|
||||||
|
// `types` has already been checked against the avatar definitions by
|
||||||
|
// itemcontrol.js. Keeping this module generic lets it also be used while a
|
||||||
|
// def pack is being made, without a defpacks <-> wearrules dependency cycle.
|
||||||
|
const setBlockedTypes = (itemId, types) => {
|
||||||
|
const id = Number(itemId);
|
||||||
|
if (!positiveInteger(id)) {
|
||||||
|
return {changed: false, blocked: []};
|
||||||
|
}
|
||||||
|
const next = new Set((Array.isArray(types) ? types : []).map(Number).filter(positiveInteger));
|
||||||
|
const before = blockedTypes(id);
|
||||||
|
if (next.size) {
|
||||||
|
ruleMap().set(id, next);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
ruleMap().delete(id);
|
||||||
|
}
|
||||||
|
const after = blockedTypes(id);
|
||||||
|
const changed = before.length !== after.length || before.some((type, index) => type !== after[index]);
|
||||||
|
if (changed) {
|
||||||
|
save();
|
||||||
|
}
|
||||||
|
return {changed, blocked: after};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Custom clothing ids are never reused, but clearing their rule at deletion
|
||||||
|
// keeps the setting accurate and avoids showing a stale dashboard entry.
|
||||||
|
const forget = itemId => {
|
||||||
|
if (ruleMap().delete(Number(itemId))) {
|
||||||
|
save();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {blockedTypes, all, mayWear, setBlockedTypes, forget};
|
||||||
+866
-65
File diff suppressed because it is too large.
Load diff
Generated
+333
@@ -0,0 +1,333 @@
|
|||||||
|
{
|
||||||
|
"name": "aj-classic-private-server",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "aj-classic-private-server",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"dependencies": {
|
||||||
|
"discord.js": "14.26.4"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22.5"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@discordjs/builders": {
|
||||||
|
"version": "1.14.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz",
|
||||||
|
"integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@discordjs/formatters": "^0.6.2",
|
||||||
|
"@discordjs/util": "^1.2.0",
|
||||||
|
"@sapphire/shapeshift": "^4.0.0",
|
||||||
|
"discord-api-types": "^0.38.40",
|
||||||
|
"fast-deep-equal": "^3.1.3",
|
||||||
|
"ts-mixer": "^6.0.4",
|
||||||
|
"tslib": "^2.6.3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.11.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@discordjs/collection": {
|
||||||
|
"version": "1.5.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz",
|
||||||
|
"integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.11.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@discordjs/formatters": {
|
||||||
|
"version": "0.6.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.2.tgz",
|
||||||
|
"integrity": "sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"discord-api-types": "^0.38.33"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.11.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@discordjs/rest": {
|
||||||
|
"version": "2.6.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.3.tgz",
|
||||||
|
"integrity": "sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@discordjs/collection": "^2.1.1",
|
||||||
|
"@discordjs/util": "^1.2.0",
|
||||||
|
"@sapphire/async-queue": "^1.5.3",
|
||||||
|
"@sapphire/snowflake": "^3.5.5",
|
||||||
|
"@vladfrangu/async_event_emitter": "^2.4.6",
|
||||||
|
"discord-api-types": "^0.38.50",
|
||||||
|
"magic-bytes.js": "^1.13.0",
|
||||||
|
"tslib": "^2.6.3",
|
||||||
|
"undici": "^6.27.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@discordjs/rest/node_modules/@discordjs/collection": {
|
||||||
|
"version": "2.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",
|
||||||
|
"integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@discordjs/rest/node_modules/@sapphire/snowflake": {
|
||||||
|
"version": "3.5.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz",
|
||||||
|
"integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=v14.0.0",
|
||||||
|
"npm": ">=7.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@discordjs/rest/node_modules/undici": {
|
||||||
|
"version": "6.29.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz",
|
||||||
|
"integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.17"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@discordjs/util": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"discord-api-types": "^0.38.33"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@discordjs/ws": {
|
||||||
|
"version": "1.2.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.3.tgz",
|
||||||
|
"integrity": "sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@discordjs/collection": "^2.1.0",
|
||||||
|
"@discordjs/rest": "^2.5.1",
|
||||||
|
"@discordjs/util": "^1.1.0",
|
||||||
|
"@sapphire/async-queue": "^1.5.2",
|
||||||
|
"@types/ws": "^8.5.10",
|
||||||
|
"@vladfrangu/async_event_emitter": "^2.2.4",
|
||||||
|
"discord-api-types": "^0.38.1",
|
||||||
|
"tslib": "^2.6.2",
|
||||||
|
"ws": "^8.17.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.11.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@discordjs/ws/node_modules/@discordjs/collection": {
|
||||||
|
"version": "2.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",
|
||||||
|
"integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@sapphire/async-queue": {
|
||||||
|
"version": "1.5.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz",
|
||||||
|
"integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=v14.0.0",
|
||||||
|
"npm": ">=7.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@sapphire/shapeshift": {
|
||||||
|
"version": "4.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-4.0.0.tgz",
|
||||||
|
"integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"fast-deep-equal": "^3.1.3",
|
||||||
|
"lodash": "^4.17.21"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=v16"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@sapphire/snowflake": {
|
||||||
|
"version": "3.5.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.3.tgz",
|
||||||
|
"integrity": "sha512-jjmJywLAFoWeBi1W7994zZyiNWPIiqRRNAmSERxyg93xRGzNYvGjlZ0gR6x0F4gPRi2+0O6S71kOZYyr3cxaIQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=v14.0.0",
|
||||||
|
"npm": ">=7.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@types/node": {
|
||||||
|
"version": "26.6.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",
|
||||||
|
"integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"undici-types": "~8.9.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@types/ws": {
|
||||||
|
"version": "8.18.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz",
|
||||||
|
"integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/node": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@vladfrangu/async_event_emitter": {
|
||||||
|
"version": "2.4.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.4.7.tgz",
|
||||||
|
"integrity": "sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=v14.0.0",
|
||||||
|
"npm": ">=7.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/discord-api-types": {
|
||||||
|
"version": "0.38.57",
|
||||||
|
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.57.tgz",
|
||||||
|
"integrity": "sha512-R1CTSSt4RshqCq23j2Xq2ZscvzB4LzG9OB1CYQdKUGdw8Ti/oF/72EEtK2mNpagG/Vj9NcBT7dw9lKLf+Dacfg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/discord.js": {
|
||||||
|
"version": "14.26.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.26.4.tgz",
|
||||||
|
"integrity": "sha512-4oBp8tc6Kf8IDBwAHhbsMaAqx1b5fob9SNasZT7V6yyyUydoO5i5fGuX7TmvRtR+q/WgKRnRViRoAWnG7fNyvA==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@discordjs/builders": "^1.14.1",
|
||||||
|
"@discordjs/collection": "1.5.3",
|
||||||
|
"@discordjs/formatters": "^0.6.2",
|
||||||
|
"@discordjs/rest": "^2.6.1",
|
||||||
|
"@discordjs/util": "^1.2.0",
|
||||||
|
"@discordjs/ws": "^1.2.3",
|
||||||
|
"@sapphire/snowflake": "3.5.3",
|
||||||
|
"discord-api-types": "^0.38.40",
|
||||||
|
"fast-deep-equal": "3.1.3",
|
||||||
|
"lodash.snakecase": "4.1.1",
|
||||||
|
"magic-bytes.js": "^1.13.0",
|
||||||
|
"tslib": "^2.6.3",
|
||||||
|
"undici": "6.24.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/fast-deep-equal": {
|
||||||
|
"version": "3.1.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
||||||
|
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/lodash": {
|
||||||
|
"version": "4.18.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
|
||||||
|
"integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/lodash.snakecase": {
|
||||||
|
"version": "4.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz",
|
||||||
|
"integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/magic-bytes.js": {
|
||||||
|
"version": "1.13.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.1.tgz",
|
||||||
|
"integrity": "sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/ts-mixer": {
|
||||||
|
"version": "6.0.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz",
|
||||||
|
"integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/tslib": {
|
||||||
|
"version": "2.8.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||||
|
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||||
|
"license": "0BSD"
|
||||||
|
},
|
||||||
|
"node_modules/undici": {
|
||||||
|
"version": "6.24.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/undici/-/undici-6.24.1.tgz",
|
||||||
|
"integrity": "sha512-sC+b0tB1whOCzbtlx20fx3WgCXwkW627p4EA9uM+/tNNPkSS+eSEld6pAs9nDv7WbY1UUljBMYPtu9BCOrCWKA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.17"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/undici-types": {
|
||||||
|
"version": "8.9.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
|
||||||
|
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/ws": {
|
||||||
|
"version": "8.22.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
|
||||||
|
"integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"bufferutil": "^4.0.1",
|
||||||
|
"utf-8-validate": ">=5.0.2"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"bufferutil": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"utf-8-validate": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,5 +10,8 @@
|
|||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=22.5"
|
"node": ">=22.5"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"discord.js": "14.26.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+470
-21
@@ -94,6 +94,8 @@
|
|||||||
transition: background 0.12s, border-color 0.12s, color 0.12s;
|
transition: background 0.12s, border-color 0.12s, color 0.12s;
|
||||||
}
|
}
|
||||||
button:hover { background: var(--raised); border-color: #555; }
|
button:hover { background: var(--raised); border-color: #555; }
|
||||||
|
a.button { border: 1px solid var(--line); border-radius: 999px; padding: 7px 16px 8px; white-space: nowrap; text-decoration: none; }
|
||||||
|
a.button:hover { background: var(--raised); border-color: #555; }
|
||||||
button:disabled { opacity: 0.45; cursor: default; }
|
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: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 { font-weight: 700; color: #000; background: var(--text); border-color: var(--text); }
|
||||||
@@ -116,7 +118,7 @@
|
|||||||
line-height: 17px;
|
line-height: 17px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
|
@media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } }
|
||||||
.wrap { max-width: 760px; margin: 0 auto; }
|
.wrap { max-width: 760px; margin: 0 auto; }
|
||||||
label.check { display: flex; align-items: center; color: var(--text); font-size: 14px; cursor: pointer; }
|
label.check { display: flex; align-items: center; color: var(--text); font-size: 14px; cursor: pointer; }
|
||||||
/* dark on white whatever the page: that is what a phone's camera reads. */
|
/* dark on white whatever the page: that is what a phone's camera reads. */
|
||||||
@@ -136,6 +138,14 @@
|
|||||||
input:not([type="checkbox"]), textarea { width: 100%; }
|
input:not([type="checkbox"]), textarea { width: 100%; }
|
||||||
textarea { min-height: 110px; resize: vertical; }
|
textarea { min-height: 110px; resize: vertical; }
|
||||||
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-top: 12px; }
|
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-top: 12px; }
|
||||||
|
/* their own custom items: a card each, its picture on the left */
|
||||||
|
.my-items { display: grid; gap: 10px; margin-top: 10px; }
|
||||||
|
.my-item { display: grid; grid-template-columns: 72px 1fr; gap: 12px; align-items: center; padding: 10px; border: 1px solid var(--line); border-radius: 14px; }
|
||||||
|
.my-item .art { width: 72px; height: 72px; border-radius: 10px; background: var(--raised, #1a1a1a); display: grid; place-items: center; overflow: hidden; color: var(--muted); font-size: 11px; text-align: center; }
|
||||||
|
.my-item .art img { max-width: 100%; max-height: 100%; image-rendering: auto; }
|
||||||
|
.my-item .row { margin-top: 6px; }
|
||||||
|
.my-item input[type="text"] { flex: 1; min-width: 140px; }
|
||||||
|
.my-item input[type="file"] { display: none; }
|
||||||
.captcha { margin-top: 12px; }
|
.captcha { margin-top: 12px; }
|
||||||
.tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; }
|
.tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; }
|
||||||
.tile { padding: 12px 14px 11px; border: 1px solid var(--line); border-radius: 18px; }
|
.tile { padding: 12px 14px 11px; border: 1px solid var(--line); border-radius: 18px; }
|
||||||
@@ -167,6 +177,26 @@
|
|||||||
.ban-head { display: flex; align-items: center; gap: 12px; margin-bottom: 4px; }
|
.ban-head { display: flex; align-items: center; gap: 12px; margin-bottom: 4px; }
|
||||||
.ban-head img { width: 44px; height: 44px; flex: none; }
|
.ban-head img { width: 44px; height: 44px; flex: none; }
|
||||||
.ban-head h2 { margin: 0; font-size: 22px; }
|
.ban-head h2 { margin: 0; font-size: 22px; }
|
||||||
|
.chat-style-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 12px; }
|
||||||
|
.chat-style-grid input[type="color"] { width: 100%; height: 42px; padding: 3px; cursor: pointer; }
|
||||||
|
.gradient-editor { margin: 14px 0; padding: 12px; border: 1px solid var(--line); border-radius: 12px; }
|
||||||
|
.gradient-editor-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; }
|
||||||
|
.gradient-stops { display: grid; gap: 8px; }
|
||||||
|
.gradient-ramp { height: 22px; margin-bottom: 10px; border: 1px solid var(--line); border-radius: 999px; }
|
||||||
|
.gradient-stop { display: grid; grid-template-columns: 50px minmax(100px, 1fr) 72px auto; align-items: center; gap: 8px; }
|
||||||
|
.gradient-stop input[type="color"] { width: 50px; height: 36px; padding: 2px; cursor: pointer; }
|
||||||
|
.gradient-stop input[type="range"] { margin: 0; }
|
||||||
|
.gradient-stop output { color: var(--muted); font-size: 12px; text-align: right; }
|
||||||
|
.chat-preview { min-height: 74px; display: grid; place-items: center; margin-top: 14px; padding: 12px 18px; border: 1px solid var(--line); border-radius: 18px; text-align: center; font-weight: 700; background: linear-gradient(120deg, #fff, #dfe8ff); color: #445559; }
|
||||||
|
.chat-preview.pulse { animation: chatPulse 1.5s ease-in-out infinite alternate; }
|
||||||
|
.chat-preview.shimmer { background-size: 250% 100%; animation: chatShimmer 1.5s linear infinite; }
|
||||||
|
.chat-preview.flow { background-size: 220% 220%; animation: chatFlow 1.5s linear infinite alternate; }
|
||||||
|
.chat-preview.rainbow { animation: chatRainbow 2s linear infinite; }
|
||||||
|
@keyframes chatPulse { to { opacity: .55; } }
|
||||||
|
@keyframes chatShimmer { to { background-position: 100% 0; } }
|
||||||
|
@keyframes chatFlow { to { background-position: 100% 100%; } }
|
||||||
|
@keyframes chatRainbow { to { filter: hue-rotate(360deg); } }
|
||||||
|
@media (max-width: 440px) { .chat-style-grid { grid-template-columns: 1fr; } }
|
||||||
#ban-section pre { margin: 0 0 12px; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; }
|
#ban-section pre { margin: 0 0 12px; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||||
#ban-section h3 { margin: 18px 0 0; }
|
#ban-section h3 { margin: 18px 0 0; }
|
||||||
</style>
|
</style>
|
||||||
@@ -187,16 +217,17 @@
|
|||||||
<label class="check" style="margin-top:12px"><input id="remember-device" type="checkbox"> Trust this device for 30 days</label>
|
<label class="check" style="margin-top:12px"><input id="remember-device" type="checkbox"> Trust this device for 30 days</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="captcha" id="captcha"></div>
|
<div class="captcha" id="captcha"></div>
|
||||||
<div class="row"><button class="primary" type="submit">Sign in</button></div>
|
<div class="row"><button class="primary" type="submit">Sign in</button><button id="client-sign-in" type="button">Sign in with the Burrow client</button></div>
|
||||||
</form>
|
</form>
|
||||||
<p class="status" id="gate-status" role="status"></p>
|
<p class="status" id="gate-status" role="status"></p>
|
||||||
<p class="hint" style="margin:10px 0 0">No account yet? <a href="/register">Create one</a></p>
|
<p class="hint" style="margin:10px 0 0">No account yet? <a href="/register">Create one</a> · <a href="/account/recover">Forgot password or 2FA?</a></p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="page" hidden>
|
<div id="page" hidden>
|
||||||
<header>
|
<header>
|
||||||
<img class="mark" src="/logo.png" alt="">
|
<img class="mark" src="/logo.png" alt="">
|
||||||
<h1 id="title"></h1>
|
<h1 id="title"></h1>
|
||||||
|
<a class="button" id="item-giver" href="/account/items">Item giver</a>
|
||||||
<button id="sign-out" type="button">Sign out</button>
|
<button id="sign-out" type="button">Sign out</button>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@@ -234,7 +265,11 @@
|
|||||||
|
|
||||||
<section>
|
<section>
|
||||||
<h2>Buddies</h2>
|
<h2>Buddies</h2>
|
||||||
<div id="buddies"></div>
|
<!-- closed at first: a long list made the page slow to scroll -->
|
||||||
|
<details id="buddies-box" hidden>
|
||||||
|
<summary id="buddies-summary">Buddies</summary>
|
||||||
|
<div id="buddies"></div>
|
||||||
|
</details>
|
||||||
<p class="hint" id="no-buddies" hidden>No buddies yet.</p>
|
<p class="hint" id="no-buddies" hidden>No buddies yet.</p>
|
||||||
<p class="status" id="buddy-status" role="status"></p>
|
<p class="status" id="buddy-status" role="status"></p>
|
||||||
</section>
|
</section>
|
||||||
@@ -285,7 +320,10 @@
|
|||||||
|
|
||||||
<section>
|
<section>
|
||||||
<h2>Den visitors</h2>
|
<h2>Den visitors</h2>
|
||||||
<div id="visits"></div>
|
<details id="visits-box" hidden>
|
||||||
|
<summary id="visits-summary">Visitors</summary>
|
||||||
|
<div id="visits"></div>
|
||||||
|
</details>
|
||||||
<p class="hint" id="no-visits" hidden>No visitors yet.</p>
|
<p class="hint" id="no-visits" hidden>No visitors yet.</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -303,6 +341,14 @@
|
|||||||
</details>
|
</details>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>My items</h2>
|
||||||
|
<p class="hint" id="my-items-hint"></p>
|
||||||
|
<div class="my-items" id="my-items"></div>
|
||||||
|
<p class="hint" id="no-my-items" hidden>You have not made any items yet. Make one in the game: Settings, then Item Maker.</p>
|
||||||
|
<p class="status" id="my-items-status" role="status"></p>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="kept" id="rename-section" hidden>
|
<section class="kept" id="rename-section" hidden>
|
||||||
<h2>Username rejected</h2>
|
<h2>Username rejected</h2>
|
||||||
<form id="rename-form">
|
<form id="rename-form">
|
||||||
@@ -338,6 +384,35 @@
|
|||||||
<p class="status" id="bio-status" role="status"></p>
|
<p class="status" id="bio-status" role="status"></p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section id="chat-bubble">
|
||||||
|
<h2>Chat bubble</h2>
|
||||||
|
<p>Choose how your spoken chat bubbles look for everyone using Burrow's current client.</p>
|
||||||
|
<form id="chat-style-form">
|
||||||
|
<div class="gradient-editor">
|
||||||
|
<div class="gradient-editor-head"><b>Gradient colours</b><button id="chat-stop-add" type="button">Add colour</button></div>
|
||||||
|
<div class="gradient-ramp" id="chat-ramp"></div>
|
||||||
|
<div class="gradient-stops" id="chat-stops"></div>
|
||||||
|
</div>
|
||||||
|
<div class="chat-style-grid">
|
||||||
|
<div hidden><input id="chat-background" type="color" value="#ffffff"></div>
|
||||||
|
<div hidden><input id="chat-accent" type="color" value="#dfe8ff"></div>
|
||||||
|
<div><label for="chat-text-colour">Text colour</label><input id="chat-text-colour" type="color" value="#445559"></div>
|
||||||
|
<div><label for="chat-border">Border</label><input id="chat-border" type="color" value="#9aabb0"></div>
|
||||||
|
<div><label for="chat-opacity">Opacity <span class="hint" id="chat-opacity-value"></span></label><input id="chat-opacity" type="range" min="25" max="100" value="75"></div>
|
||||||
|
<div><label for="chat-gradient">Gradient</label><select id="chat-gradient"><option value="linear">Linear</option><option value="radial">Radial</option><option value="solid">Solid</option></select></div>
|
||||||
|
<div><label for="chat-angle">Direction</label><select id="chat-angle"><option value="0">0°</option><option value="45">45°</option><option value="90">90°</option><option value="135">135°</option><option value="180">180°</option><option value="225">225°</option><option value="270">270°</option><option value="315">315°</option></select></div>
|
||||||
|
<div><label for="chat-strength">Gradient strength <span class="hint" id="chat-strength-value"></span></label><input id="chat-strength" type="range" min="0" max="100" value="100"></div>
|
||||||
|
<div><label for="chat-outline">Outline thickness <span class="hint" id="chat-outline-value"></span></label><input id="chat-outline" type="range" min="0" max="4" step="1" value="1"></div>
|
||||||
|
<div><label for="chat-animation">Animation</label><select id="chat-animation"><option value="none">Still</option><option value="pulse">Pulse</option><option value="shimmer">Shimmer</option><option value="flow">Flow</option><option value="rainbow">Rainbow</option></select></div>
|
||||||
|
<div><label for="chat-speed">Animation speed <span class="hint" id="chat-speed-value"></span></label><input id="chat-speed" type="range" min="40" max="300" value="100"></div>
|
||||||
|
</div>
|
||||||
|
<div class="chat-preview" id="chat-preview">Your chat bubble preview</div>
|
||||||
|
<div class="row"><button id="chat-style-swap" type="button">Swap gradient</button><button id="chat-style-random" type="button">Random gradient</button></div>
|
||||||
|
<div class="row"><button class="primary" type="submit">Save chat style</button><button id="chat-style-reset" type="button">Use original bubble</button></div>
|
||||||
|
</form>
|
||||||
|
<p class="status" id="chat-style-status" role="status"></p>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section>
|
<section>
|
||||||
<h2>Playtime</h2>
|
<h2>Playtime</h2>
|
||||||
<p id="playtime-text"></p>
|
<p id="playtime-text"></p>
|
||||||
@@ -351,12 +426,10 @@
|
|||||||
<section>
|
<section>
|
||||||
<h2>Discord</h2>
|
<h2>Discord</h2>
|
||||||
<p id="badges" hidden></p>
|
<p id="badges" hidden></p>
|
||||||
<form id="discord-form">
|
<p id="discord-shown"></p>
|
||||||
<label for="discord-name">Username</label>
|
<p class="hint" id="discord-about">Shown on your card in the game. Sign in to Discord to link your account; boosting Burrow's Discord server gives you the Server Booster badge while you boost.</p>
|
||||||
<input id="discord-name" maxlength="33" autocomplete="off" spellcheck="false">
|
<div class="row"><button class="primary" id="discord-link" type="button">Link Discord</button>
|
||||||
<div class="row"><button class="primary" type="submit">Save</button>
|
<button id="discord-remove" type="button">Unlink</button></div>
|
||||||
<button id="discord-remove" type="button">Remove</button></div>
|
|
||||||
</form>
|
|
||||||
<p class="status" id="discord-status" role="status"></p>
|
<p class="status" id="discord-status" role="status"></p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -490,8 +563,12 @@
|
|||||||
];
|
];
|
||||||
const VIA = {game: "Game", launcher: "Client", web: "This page", mod: "Moderator panel"};
|
const VIA = {game: "Game", launcher: "Client", web: "This page", mod: "Moderator panel"};
|
||||||
const ANIMALS = {1: "Tiger", 4: "Wolf", 5: "Koala", 6: "Panda", 7: "Monkey", 8: "Bunny", 13: "Rhino", 18: "Seal", 24: "Penguin"};
|
const ANIMALS = {1: "Tiger", 4: "Wolf", 5: "Koala", 6: "Panda", 7: "Monkey", 8: "Bunny", 13: "Rhino", 18: "Seal", 24: "Penguin"};
|
||||||
|
const DEFAULT_CHAT_STYLE = {background: "ffffff", accent: "dfe8ff", text: "445559", border: "9aabb0", opacity: 75,
|
||||||
|
animation: "none", speed: 100, gradient: "linear", angle: 45, strength: 100, outline: 1,
|
||||||
|
stops: "ffffff:0;dfe8ff:100"};
|
||||||
|
|
||||||
let account = null;
|
let account = null;
|
||||||
|
let chatStops = [];
|
||||||
let twoStepSetup = null; // {secret, uri} while two-step sign-in is being turned on
|
let twoStepSetup = null; // {secret, uri} while two-step sign-in is being turned on
|
||||||
let twoStepCodes = null; // the recovery codes, until the player says they kept them
|
let twoStepCodes = null; // the recovery codes, until the player says they kept them
|
||||||
|
|
||||||
@@ -513,6 +590,126 @@
|
|||||||
$(id).classList.toggle("bad", bad);
|
$(id).classList.toggle("bad", bad);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const parseChatStops = style => {
|
||||||
|
const parsed = String(style.stops || "").split(";").map(value => {
|
||||||
|
const match = /^([0-9a-f]{6}):(100|[1-9]?\d)$/i.exec(value);
|
||||||
|
return match ? {color: match[1].toLowerCase(), position: Number(match[2])} : null;
|
||||||
|
});
|
||||||
|
return parsed.length >= 2 && parsed.length <= 5 && parsed.every(Boolean)
|
||||||
|
? parsed : [{color: style.background, position: 0}, {color: style.accent, position: 100}];
|
||||||
|
};
|
||||||
|
|
||||||
|
const styleValue = () => {
|
||||||
|
if (chatStops.length < 2) chatStops = parseChatStops(DEFAULT_CHAT_STYLE);
|
||||||
|
chatStops.sort((one, two) => one.position - two.position);
|
||||||
|
chatStops[0].position = 0;
|
||||||
|
chatStops.at(-1).position = 100;
|
||||||
|
const background = chatStops[0].color;
|
||||||
|
const accent = chatStops.at(-1).color;
|
||||||
|
$("chat-background").value = `#${background}`;
|
||||||
|
$("chat-accent").value = `#${accent}`;
|
||||||
|
return {
|
||||||
|
background, accent,
|
||||||
|
text: $("chat-text-colour").value.slice(1).toLowerCase(),
|
||||||
|
border: $("chat-border").value.slice(1).toLowerCase(),
|
||||||
|
opacity: Number($("chat-opacity").value),
|
||||||
|
animation: $("chat-animation").value,
|
||||||
|
speed: Number($("chat-speed").value),
|
||||||
|
gradient: $("chat-gradient").value,
|
||||||
|
angle: Number($("chat-angle").value),
|
||||||
|
strength: Number($("chat-strength").value),
|
||||||
|
outline: Number($("chat-outline").value),
|
||||||
|
stops: chatStops.map(stop => `${stop.color}:${stop.position}`).join(";"),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const paintChatPreview = () => {
|
||||||
|
const style = styleValue();
|
||||||
|
const preview = $("chat-preview");
|
||||||
|
preview.className = `chat-preview ${style.animation}`;
|
||||||
|
const mix = (one, two, amount) => one.map((part, index) => Math.round(part + (two[index] - part) * amount));
|
||||||
|
const rgb = hex => [0, 2, 4].map(at => parseInt(hex.slice(at, at + 2), 16));
|
||||||
|
const stops = parseChatStops(style).map((stop, index) => {
|
||||||
|
const colour = index ? mix(rgb(style.background), rgb(stop.color), style.strength / 100) : rgb(stop.color);
|
||||||
|
return `#${colour.map(part => part.toString(16).padStart(2, "0")).join("")} ${stop.position}%`;
|
||||||
|
}).join(", ");
|
||||||
|
preview.style.background = style.gradient === "solid" ? `#${style.background}` : style.gradient === "radial"
|
||||||
|
? `radial-gradient(circle, ${stops})`
|
||||||
|
: `linear-gradient(${style.angle}deg, ${stops})`;
|
||||||
|
preview.style.color = `#${style.text}`;
|
||||||
|
preview.style.borderColor = `#${style.border}`;
|
||||||
|
preview.style.borderWidth = `${style.outline}px`;
|
||||||
|
preview.style.opacity = String(style.opacity / 100);
|
||||||
|
preview.style.animationDuration = `${Math.max(.25, 1.5 * 100 / style.speed)}s`;
|
||||||
|
$("chat-opacity-value").textContent = `${style.opacity}%`;
|
||||||
|
$("chat-speed-value").textContent = `${style.speed}%`;
|
||||||
|
$("chat-strength-value").textContent = `${style.strength}%`;
|
||||||
|
$("chat-outline-value").textContent = `${style.outline}px`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderChatStops = () => {
|
||||||
|
chatStops.sort((one, two) => one.position - two.position);
|
||||||
|
const holder = $("chat-stops");
|
||||||
|
holder.replaceChildren();
|
||||||
|
$("chat-ramp").style.background = `linear-gradient(90deg, ${chatStops.map(stop => `#${stop.color} ${stop.position}%`).join(", ")})`;
|
||||||
|
chatStops.forEach((stop, index) => {
|
||||||
|
const row = el("div", undefined, "gradient-stop");
|
||||||
|
const colour = document.createElement("input");
|
||||||
|
colour.type = "color";
|
||||||
|
colour.value = `#${stop.color}`;
|
||||||
|
colour.setAttribute("aria-label", `Gradient colour ${index + 1}`);
|
||||||
|
const position = document.createElement("input");
|
||||||
|
position.type = "range";
|
||||||
|
position.min = String(index ? chatStops[index - 1].position + 1 : 0);
|
||||||
|
position.max = String(index < chatStops.length - 1 ? chatStops[index + 1].position - 1 : 100);
|
||||||
|
position.value = String(stop.position);
|
||||||
|
position.disabled = index === 0 || index === chatStops.length - 1;
|
||||||
|
const value = document.createElement("output");
|
||||||
|
value.textContent = index === 0 ? "Start" : index === chatStops.length - 1 ? "End" : `${stop.position}%`;
|
||||||
|
const remove = document.createElement("button");
|
||||||
|
remove.type = "button";
|
||||||
|
remove.textContent = "Remove";
|
||||||
|
remove.disabled = chatStops.length <= 2;
|
||||||
|
colour.addEventListener("input", () => {
|
||||||
|
stop.color = colour.value.slice(1).toLowerCase();
|
||||||
|
renderChatStops();
|
||||||
|
paintChatPreview();
|
||||||
|
});
|
||||||
|
position.addEventListener("input", () => {
|
||||||
|
stop.position = Number(position.value);
|
||||||
|
value.textContent = `${stop.position}%`;
|
||||||
|
$("chat-ramp").style.background = `linear-gradient(90deg, ${chatStops.map(item => `#${item.color} ${item.position}%`).join(", ")})`;
|
||||||
|
paintChatPreview();
|
||||||
|
});
|
||||||
|
remove.addEventListener("click", () => {
|
||||||
|
chatStops.splice(index, 1);
|
||||||
|
renderChatStops();
|
||||||
|
paintChatPreview();
|
||||||
|
});
|
||||||
|
row.append(colour, position, value, remove);
|
||||||
|
holder.append(row);
|
||||||
|
});
|
||||||
|
$("chat-stop-add").disabled = chatStops.length >= 5;
|
||||||
|
};
|
||||||
|
|
||||||
|
const fillChatStyle = style => {
|
||||||
|
style = {...DEFAULT_CHAT_STYLE, ...style};
|
||||||
|
chatStops = parseChatStops(style);
|
||||||
|
$("chat-background").value = `#${style.background}`;
|
||||||
|
$("chat-accent").value = `#${style.accent}`;
|
||||||
|
$("chat-text-colour").value = `#${style.text}`;
|
||||||
|
$("chat-border").value = `#${style.border}`;
|
||||||
|
$("chat-opacity").value = String(style.opacity);
|
||||||
|
$("chat-animation").value = style.animation;
|
||||||
|
$("chat-speed").value = String(style.speed);
|
||||||
|
$("chat-gradient").value = style.gradient;
|
||||||
|
$("chat-angle").value = String(style.angle);
|
||||||
|
$("chat-strength").value = String(style.strength);
|
||||||
|
$("chat-outline").value = String(style.outline);
|
||||||
|
renderChatStops();
|
||||||
|
paintChatPreview();
|
||||||
|
};
|
||||||
|
|
||||||
const api = async (path, body) => {
|
const api = async (path, body) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/account/api/${path}`, body === undefined ? {} : {
|
const response = await fetch(`/account/api/${path}`, body === undefined ? {} : {
|
||||||
@@ -596,6 +793,133 @@
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// their own custom items (lib/playeritems.js): rename, a picture of its
|
||||||
|
// own (sent as it is to /api/itemart, which checks and cleans it), delete.
|
||||||
|
const renderMyItems = () => {
|
||||||
|
const items = account.customItems || [];
|
||||||
|
const limits = account.customItemLimits || {perDay: 0, inAll: 0};
|
||||||
|
$("my-items-hint").textContent = `Items you made in the game's Item Maker: ${items.length} of ${limits.inAll}, up to ${limits.perDay} a day. `
|
||||||
|
+ "A picture (any kind: one too big is made smaller) is shown as the item's icon, and for a den item in the den, once a moderator has checked it. "
|
||||||
|
+ (account.picturesStopped ? "A moderator has turned off picture uploads for your account." : "Pictures must suit everyone: one turned away counts against you.");
|
||||||
|
$("no-my-items").hidden = items.length > 0;
|
||||||
|
$("my-items").replaceChildren(...items.map(item => {
|
||||||
|
const card = el("div", undefined, "my-item");
|
||||||
|
const art = el("div", item.art ? undefined : "No picture", "art");
|
||||||
|
if (item.art) {
|
||||||
|
const picture = el("img");
|
||||||
|
picture.src = item.art;
|
||||||
|
picture.alt = "";
|
||||||
|
art.append(picture);
|
||||||
|
}
|
||||||
|
const body = el("div");
|
||||||
|
body.append(el("strong", `${item.name}`), el("span", ` · ${item.kind === "den" ? "den item" : "clothing"} ${item.id}${item.artWaiting ? " · picture waiting for a moderator" : ""}`, "hint"));
|
||||||
|
const nameRow = el("div", undefined, "row");
|
||||||
|
const name = el("input");
|
||||||
|
name.type = "text";
|
||||||
|
name.maxLength = 40;
|
||||||
|
name.value = item.name;
|
||||||
|
name.setAttribute("aria-label", `New name for ${item.name}`);
|
||||||
|
const rename = el("button", "Rename");
|
||||||
|
rename.type = "button";
|
||||||
|
rename.addEventListener("click", () => act({action: "itemRename", kind: item.kind, id: item.id, name: name.value}, "my-items-status"));
|
||||||
|
nameRow.append(name, rename);
|
||||||
|
const artRow = el("div", undefined, "row");
|
||||||
|
const file = el("input");
|
||||||
|
file.type = "file";
|
||||||
|
file.accept = "image/*";
|
||||||
|
const choose = el("button", item.art ? "New picture" : "Add picture");
|
||||||
|
choose.type = "button";
|
||||||
|
choose.addEventListener("click", () => file.click());
|
||||||
|
file.addEventListener("change", () => file.files[0] && sendPicture(item, file.files[0]));
|
||||||
|
artRow.append(file, choose);
|
||||||
|
if (item.art && item.kind === "clothing") {
|
||||||
|
// how it is worn: the picture itself, or the item's shape painted with it
|
||||||
|
const look = el("select");
|
||||||
|
look.setAttribute("aria-label", `How ${item.name} is worn`);
|
||||||
|
for (const [value, text] of [["sticker", "Worn as the picture"], ["texture", "Worn as its shape, with the picture in it"]]) {
|
||||||
|
const option = el("option", text);
|
||||||
|
option.value = value;
|
||||||
|
look.append(option);
|
||||||
|
}
|
||||||
|
look.value = item.look || "sticker";
|
||||||
|
look.addEventListener("change", () => act({action: "itemLook", kind: item.kind, id: item.id, look: look.value}, "my-items-status"));
|
||||||
|
artRow.append(look);
|
||||||
|
}
|
||||||
|
if (item.art) {
|
||||||
|
const remove = el("button", "Remove picture");
|
||||||
|
remove.type = "button";
|
||||||
|
remove.addEventListener("click", () => sendPicture(item, null));
|
||||||
|
artRow.append(remove);
|
||||||
|
}
|
||||||
|
const del = el("button", "Delete", "danger");
|
||||||
|
del.type = "button";
|
||||||
|
del.addEventListener("click", () => {
|
||||||
|
if (confirm(`Delete ${item.name}? It goes from everyone who has it, and cannot be undone.`)) {
|
||||||
|
act({action: "itemDelete", kind: item.kind, id: item.id}, "my-items-status");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
artRow.append(del);
|
||||||
|
body.append(nameRow, artRow);
|
||||||
|
card.append(art, body);
|
||||||
|
return card;
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
// a picture made ready to send (lib/itemart.js): as it is when the
|
||||||
|
// server takes it as it is (a PNG, JPEG or GIF small enough: a GIF keeps
|
||||||
|
// moving), else drawn into a PNG that fits, smaller until it is small
|
||||||
|
// enough. any picture this browser can open will do (WebP, AVIF, BMP...).
|
||||||
|
// null when it cannot be read at all.
|
||||||
|
const PICTURE_SIDE = 256;
|
||||||
|
const PICTURE_BYTES = 100 * 1024;
|
||||||
|
const preparePicture = async file => {
|
||||||
|
const kept = ["image/png", "image/jpeg", "image/gif"].includes(file.type);
|
||||||
|
let image = null;
|
||||||
|
try {
|
||||||
|
image = await createImageBitmap(file);
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
return kept ? file : null;
|
||||||
|
}
|
||||||
|
if (kept && file.size <= PICTURE_BYTES && image.width <= PICTURE_SIDE && image.height <= PICTURE_SIDE) {
|
||||||
|
image.close();
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
for (const side of [PICTURE_SIDE, 192, 128, 96]) {
|
||||||
|
const scale = Math.min(1, side / image.width, side / image.height);
|
||||||
|
const canvas = document.createElement("canvas");
|
||||||
|
canvas.width = Math.max(1, Math.round(image.width * scale));
|
||||||
|
canvas.height = Math.max(1, Math.round(image.height * scale));
|
||||||
|
canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
|
||||||
|
const blob = await new Promise(resolve => canvas.toBlob(resolve, "image/png"));
|
||||||
|
if (blob && blob.size <= PICTURE_BYTES) {
|
||||||
|
image.close();
|
||||||
|
return blob;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
image.close();
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const sendPicture = async (item, chosen) => {
|
||||||
|
const file = chosen ? await preparePicture(chosen) : null;
|
||||||
|
if (chosen && !file) {
|
||||||
|
setStatus("my-items-status", "That picture could not be read. Try a PNG, JPEG or GIF.", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setStatus("my-items-status", file ? "Sending the picture..." : "Taking the picture away...");
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/account/api/itemart?kind=${encodeURIComponent(item.kind)}&id=${encodeURIComponent(item.id)}${file ? "" : "&remove=1"}`,
|
||||||
|
{method: "POST", headers: {"Content-Type": "application/octet-stream"}, body: file || new Uint8Array(0)});
|
||||||
|
const data = await response.json().catch(() => ({}));
|
||||||
|
setStatus("my-items-status", data.ok || data.error || "That did not work.", !data.ok);
|
||||||
|
await load();
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
setStatus("my-items-status", "The server did not answer.", true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const render = () => {
|
const render = () => {
|
||||||
$("gate").hidden = true;
|
$("gate").hidden = true;
|
||||||
$("page").hidden = false;
|
$("page").hidden = false;
|
||||||
@@ -614,7 +938,11 @@
|
|||||||
if (account.nameRejected) {
|
if (account.nameRejected) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
renderMyItems();
|
||||||
$("lock-notice").hidden = !account.locked;
|
$("lock-notice").hidden = !account.locked;
|
||||||
|
if (!$("chat-style-form").contains(document.activeElement)) {
|
||||||
|
fillChatStyle(account.chatStyle);
|
||||||
|
}
|
||||||
|
|
||||||
const tiles = [
|
const tiles = [
|
||||||
[account.online ? "Playing now" : account.lastSeen ? when(account.lastSeen) : "Not played yet", "Last seen"],
|
[account.online ? "Playing now" : account.lastSeen ? when(account.lastSeen) : "Not played yet", "Last seen"],
|
||||||
@@ -661,11 +989,11 @@
|
|||||||
$("bio-text").maxLength = account.bioLimit + 20; // room for the line ends a browser counts double
|
$("bio-text").maxLength = account.bioLimit + 20; // room for the line ends a browser counts double
|
||||||
$("bio-remove").hidden = !account.bio;
|
$("bio-remove").hidden = !account.bio;
|
||||||
bioCount();
|
bioCount();
|
||||||
// not while it is being typed in: every answer from the server draws the page again.
|
// linked by signing in to Discord (lib/discord.js), not typed in
|
||||||
if (document.activeElement !== $("discord-name")) {
|
$("discord-shown").textContent = account.discordLinked ? `Linked: ${account.discord}` : "Not linked.";
|
||||||
$("discord-name").value = account.discord;
|
$("discord-link").textContent = account.discordLinked ? "Link another" : "Link Discord";
|
||||||
}
|
$("discord-link").hidden = !account.discordLinking;
|
||||||
$("discord-remove").hidden = !account.discord;
|
$("discord-remove").hidden = !account.discordLinked;
|
||||||
$("badges").hidden = account.badges.length === 0;
|
$("badges").hidden = account.badges.length === 0;
|
||||||
$("badges").textContent = `Badges: ${account.badges.join(", ")}`;
|
$("badges").textContent = `Badges: ${account.badges.join(", ")}`;
|
||||||
|
|
||||||
@@ -701,6 +1029,8 @@
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
$("no-buddies").hidden = account.buddyList.length > 0;
|
$("no-buddies").hidden = account.buddyList.length > 0;
|
||||||
|
$("buddies-box").hidden = account.buddyList.length === 0;
|
||||||
|
$("buddies-summary").textContent = `Show ${account.buddyList.length.toLocaleString()} ${account.buddyList.length === 1 ? "buddy" : "buddies"}`;
|
||||||
|
|
||||||
$("blocked").replaceChildren(...account.blocked.map(name => {
|
$("blocked").replaceChildren(...account.blocked.map(name => {
|
||||||
const row = el("div", undefined, "switch");
|
const row = el("div", undefined, "switch");
|
||||||
@@ -746,6 +1076,8 @@
|
|||||||
return entry;
|
return entry;
|
||||||
}));
|
}));
|
||||||
$("no-visits").hidden = account.denVisits.length > 0;
|
$("no-visits").hidden = account.denVisits.length > 0;
|
||||||
|
$("visits-box").hidden = account.denVisits.length === 0;
|
||||||
|
$("visits-summary").textContent = `Show ${account.denVisits.length.toLocaleString()} ${account.denVisits.length === 1 ? "visit" : "visits"}`;
|
||||||
|
|
||||||
$("achievement-summary").textContent = `${account.achievements.earned} of ${account.achievements.of} earned.`;
|
$("achievement-summary").textContent = `${account.achievements.earned} of ${account.achievements.of} earned.`;
|
||||||
$("achievements").replaceChildren(...account.achievements.counted.map(counted => {
|
$("achievements").replaceChildren(...account.achievements.counted.map(counted => {
|
||||||
@@ -794,12 +1126,79 @@
|
|||||||
if (result.ok) {
|
if (result.ok) {
|
||||||
account = result.data;
|
account = result.data;
|
||||||
render();
|
render();
|
||||||
|
// back from linking Discord: how it went, once
|
||||||
|
if (discordResult && Object.hasOwn(DISCORD_RESULTS, discordResult)) {
|
||||||
|
setStatus("discord-status", DISCORD_RESULTS[discordResult], discordResult !== "linked");
|
||||||
|
history.replaceState(null, "", location.pathname + location.hash);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
showGate(result.status === 0 ? result.data.error : "");
|
showGate(result.status === 0 ? result.data.error : "");
|
||||||
|
if (Object.hasOwn(CLIENT_RESULTS, clientResult || "")) {
|
||||||
|
setStatus("gate-status", CLIENT_RESULTS[clientResult], true);
|
||||||
|
}
|
||||||
|
// never by itself on the way back from it: a browser that would
|
||||||
|
// not keep the sign-in would open tab after tab.
|
||||||
|
else if (!clientResult && clientRemembered()) {
|
||||||
|
signInWithClient();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (clientResult) {
|
||||||
|
if (result.ok && clientResult === "ok") {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(CLIENT_KEY, "1");
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
// not kept: the button stays the way in.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
history.replaceState(null, "", location.pathname + location.hash);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// "Sign in with the Burrow client" (lib/manage.js): the browser asks
|
||||||
|
// whether to open Burrow, which opens this page again signed in (in a
|
||||||
|
// new tab: this one follows). once that has worked in this browser, the
|
||||||
|
// page asks by itself each time it opens signed out.
|
||||||
|
const CLIENT_KEY = "burrow-client-sign-in";
|
||||||
|
const CLIENT_RESULTS = {
|
||||||
|
ok: "Burrow signed you in, but this browser did not keep it. Sign in with your password.",
|
||||||
|
expired: "That sign-in took too long. Try again.",
|
||||||
|
elsewhere: "Burrow opened the page in another browser than the one you started in. Start from this browser again, or sign in with your password.",
|
||||||
|
};
|
||||||
|
const clientResult = new URLSearchParams(location.search).get("client");
|
||||||
|
const clientRemembered = () => {
|
||||||
|
try {
|
||||||
|
return localStorage.getItem(CLIENT_KEY) === "1";
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let clientWait = null;
|
||||||
|
const signInWithClient = async () => {
|
||||||
|
const started = await api("client-start", {});
|
||||||
|
if (!started.ok) {
|
||||||
|
setStatus("gate-status", started.data.error || "That did not work.", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setStatus("gate-status", "Opening Burrow… Allow it if your browser asks. Burrow must be logged in, or remember you.");
|
||||||
|
location.href = `burrow://account?n=${started.data.nonce}`;
|
||||||
|
clearInterval(clientWait);
|
||||||
|
const until = Date.now() + 120000;
|
||||||
|
clientWait = setInterval(async () => {
|
||||||
|
if (account || Date.now() > until) {
|
||||||
|
clearInterval(clientWait);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((await api("me")).ok) {
|
||||||
|
clearInterval(clientWait);
|
||||||
|
await load();
|
||||||
|
}
|
||||||
|
}, 2000);
|
||||||
|
};
|
||||||
|
$("client-sign-in").addEventListener("click", signInWithClient);
|
||||||
|
|
||||||
$("sign-in").addEventListener("submit", async event => {
|
$("sign-in").addEventListener("submit", async event => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const answer = captchaPass ? undefined : await check.answer();
|
const answer = captchaPass ? undefined : await check.answer();
|
||||||
@@ -1196,12 +1595,62 @@
|
|||||||
});
|
});
|
||||||
$("bio-remove").addEventListener("click", () => act({action: "bio", text: ""}, "bio-status"));
|
$("bio-remove").addEventListener("click", () => act({action: "bio", text: ""}, "bio-status"));
|
||||||
|
|
||||||
$("discord-form").addEventListener("submit", async event => {
|
["chat-background", "chat-accent", "chat-text-colour", "chat-border", "chat-opacity", "chat-gradient", "chat-angle", "chat-strength", "chat-outline", "chat-animation", "chat-speed"].forEach(id => {
|
||||||
event.preventDefault();
|
$(id).addEventListener("input", paintChatPreview);
|
||||||
$("discord-name").blur();
|
$(id).addEventListener("change", paintChatPreview);
|
||||||
await act({action: "discord", name: $("discord-name").value}, "discord-status");
|
|
||||||
});
|
});
|
||||||
$("discord-remove").addEventListener("click", () => act({action: "discord", name: ""}, "discord-status"));
|
$("chat-style-form").addEventListener("submit", async event => {
|
||||||
|
event.preventDefault();
|
||||||
|
await act({action: "chatStyle", style: styleValue()}, "chat-style-status");
|
||||||
|
});
|
||||||
|
$("chat-stop-add").addEventListener("click", () => {
|
||||||
|
if (chatStops.length >= 5) return;
|
||||||
|
let gapAt = 0;
|
||||||
|
for (let index = 1; index < chatStops.length - 1; index++) {
|
||||||
|
if (chatStops[index + 1].position - chatStops[index].position > chatStops[gapAt + 1].position - chatStops[gapAt].position) gapAt = index;
|
||||||
|
}
|
||||||
|
const before = chatStops[gapAt];
|
||||||
|
const after = chatStops[gapAt + 1];
|
||||||
|
const rgb = hex => [0, 2, 4].map(at => parseInt(hex.slice(at, at + 2), 16));
|
||||||
|
const mixed = rgb(before.color).map((part, index) => Math.round((part + rgb(after.color)[index]) / 2).toString(16).padStart(2, "0")).join("");
|
||||||
|
chatStops.splice(gapAt + 1, 0, {color: mixed, position: Math.round((before.position + after.position) / 2)});
|
||||||
|
renderChatStops();
|
||||||
|
paintChatPreview();
|
||||||
|
});
|
||||||
|
$("chat-style-swap").addEventListener("click", () => {
|
||||||
|
chatStops = chatStops.slice().reverse().map(stop => ({color: stop.color, position: 100 - stop.position}));
|
||||||
|
renderChatStops();
|
||||||
|
paintChatPreview();
|
||||||
|
});
|
||||||
|
$("chat-style-random").addEventListener("click", () => {
|
||||||
|
const randomColour = () => Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, "0");
|
||||||
|
chatStops.forEach(stop => { stop.color = randomColour(); });
|
||||||
|
renderChatStops();
|
||||||
|
paintChatPreview();
|
||||||
|
});
|
||||||
|
$("chat-style-reset").addEventListener("click", async () => {
|
||||||
|
fillChatStyle(DEFAULT_CHAT_STYLE);
|
||||||
|
await act({action: "chatStyle", style: DEFAULT_CHAT_STYLE}, "chat-style-status");
|
||||||
|
});
|
||||||
|
|
||||||
|
// off to Discord's sign-in; it comes back to /account?discord=<how it went>
|
||||||
|
$("discord-link").addEventListener("click", () => {
|
||||||
|
location.href = "/account/discord/link";
|
||||||
|
});
|
||||||
|
$("discord-remove").addEventListener("click", () => {
|
||||||
|
if (confirm("Unlink your Discord account? It comes off your card, and so does the Server Booster badge.")) {
|
||||||
|
act({action: "discord", name: ""}, "discord-status");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const DISCORD_RESULTS = {
|
||||||
|
linked: "Discord linked.",
|
||||||
|
cancelled: "Linking was cancelled.",
|
||||||
|
expired: "That took too long, or was started in another browser. Try again.",
|
||||||
|
taken: "That Discord account is linked to another Burrow account.",
|
||||||
|
discord: "Discord did not answer. Try again later.",
|
||||||
|
off: "Linking Discord is not available right now.",
|
||||||
|
};
|
||||||
|
const discordResult = new URLSearchParams(location.search).get("discord");
|
||||||
|
|
||||||
$("lock").addEventListener("click", () => {
|
$("lock").addEventListener("click", () => {
|
||||||
if (!account.locked && !window.confirm("Lock the account? Nobody gets in until you unlock it here.")) {
|
if (!account.locked && !window.confirm("Lock the account? Nobody gets in until you unlock it here.")) {
|
||||||
|
|||||||
+2240
-162
File diff suppressed because it is too large.
Load diff
Binary file not shown.
|
After Width: | Height: | Size: 945 B |
Binary file not shown.
|
After Width: | Height: | Size: 1.6 MiB |
+7
-1
@@ -25,17 +25,21 @@
|
|||||||
-webkit-font-smoothing: antialiased;
|
-webkit-font-smoothing: antialiased;
|
||||||
}
|
}
|
||||||
#status { margin: 0; text-align: center; }
|
#status { margin: 0; text-align: center; }
|
||||||
|
button { display: none; border: 1px solid #8c8c8c; border-radius: 5px; padding: 6px 12px; background: transparent; color: #ddd; font: inherit; cursor: pointer; }
|
||||||
|
button.show { display: block; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="widget"></div>
|
<div id="widget"></div>
|
||||||
<p id="status" role="status">Checking…</p>
|
<p id="status" role="status">Checking…</p>
|
||||||
|
<button id="retry" type="button">Try again</button>
|
||||||
<script src="/captcha.js"></script>
|
<script src="/captcha.js"></script>
|
||||||
<script>
|
<script>
|
||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
const action = new URLSearchParams(location.search).get("action") === "signup" ? "signup" : "login";
|
const action = new URLSearchParams(location.search).get("action") === "signup" ? "signup" : "login";
|
||||||
const status = document.getElementById("status");
|
const status = document.getElementById("status");
|
||||||
|
const retry = document.getElementById("retry");
|
||||||
const done = token => {
|
const done = token => {
|
||||||
if (window.burrowCaptcha) {
|
if (window.burrowCaptcha) {
|
||||||
window.burrowCaptcha.done(token);
|
window.burrowCaptcha.done(token);
|
||||||
@@ -53,10 +57,12 @@
|
|||||||
}});
|
}});
|
||||||
check.answer().then(token => {
|
check.answer().then(token => {
|
||||||
if (!token) {
|
if (!token) {
|
||||||
status.textContent = "Captcha failed. Close this and try again.";
|
status.textContent = "Captcha could not load. Check your connection or content blocker.";
|
||||||
|
retry.classList.add("show");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
retry.addEventListener("click", () => location.reload());
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
+72
-23
@@ -10,14 +10,29 @@
|
|||||||
// captcha.FAILED then), and check.reset() after it: an answer is good once.
|
// captcha.FAILED then), and check.reset() after it: an answer is good once.
|
||||||
window.captcha = (() => {
|
window.captcha = (() => {
|
||||||
const siteKey = "{{siteKey}}";
|
const siteKey = "{{siteKey}}";
|
||||||
|
const LOAD_TIMEOUT_MS = 15000;
|
||||||
let loading = null;
|
let loading = null;
|
||||||
|
|
||||||
const load = () => {
|
const load = () => {
|
||||||
loading = loading || new Promise((resolve, reject) => {
|
loading = loading || new Promise((resolve, reject) => {
|
||||||
const script = document.createElement("script");
|
const script = document.createElement("script");
|
||||||
script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
|
script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
|
||||||
script.onload = () => resolve(window.turnstile);
|
const timer = setTimeout(() => {
|
||||||
|
loading = null;
|
||||||
|
reject(new Error("the captcha took too long to load"));
|
||||||
|
}, LOAD_TIMEOUT_MS);
|
||||||
|
script.onload = () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
if (window.turnstile && typeof window.turnstile.render === "function") {
|
||||||
|
resolve(window.turnstile);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
loading = null;
|
||||||
|
reject(new Error("the captcha did not start"));
|
||||||
|
}
|
||||||
|
};
|
||||||
script.onerror = () => {
|
script.onerror = () => {
|
||||||
|
clearTimeout(timer);
|
||||||
loading = null;
|
loading = null;
|
||||||
reject(new Error("the captcha did not load"));
|
reject(new Error("the captcha did not load"));
|
||||||
};
|
};
|
||||||
@@ -26,12 +41,15 @@ window.captcha = (() => {
|
|||||||
return loading;
|
return loading;
|
||||||
};
|
};
|
||||||
|
|
||||||
// `options`: {appearance} ("interaction-only" by default: seen only when
|
// `options`: {appearance} ("always" by default: hidden till cloudflare
|
||||||
// cloudflare wants a click), {onAnswer(token)}.
|
// wanted a click, it was taken for one that never showed), {onAnswer(token)}.
|
||||||
|
const MAX_RETRIES = 2; // a widget that errs is started again this often first
|
||||||
const mount = (element, action, options = {}) => {
|
const mount = (element, action, options = {}) => {
|
||||||
let widget = null;
|
let widget = null;
|
||||||
let answer = null; // a token, "" when none could be had, null while waiting
|
let answer = null; // a token, "" when none could be had, null while waiting
|
||||||
let waiting = [];
|
let waiting = [];
|
||||||
|
let retries = 0;
|
||||||
|
let starting = false;
|
||||||
const settle = value => {
|
const settle = value => {
|
||||||
answer = value;
|
answer = value;
|
||||||
if (value && options.onAnswer) {
|
if (value && options.onAnswer) {
|
||||||
@@ -42,42 +60,73 @@ window.captcha = (() => {
|
|||||||
}
|
}
|
||||||
waiting = [];
|
waiting = [];
|
||||||
};
|
};
|
||||||
if (siteKey) {
|
const start = () => {
|
||||||
|
if (!siteKey || starting || widget !== null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
starting = true;
|
||||||
load().then(turnstile => {
|
load().then(turnstile => {
|
||||||
widget = turnstile.render(element, {
|
starting = false;
|
||||||
sitekey: siteKey,
|
try {
|
||||||
action,
|
widget = turnstile.render(element, {
|
||||||
theme: "dark",
|
sitekey: siteKey,
|
||||||
appearance: options.appearance || "interaction-only",
|
action,
|
||||||
callback: settle,
|
theme: "dark",
|
||||||
"expired-callback": () => {
|
appearance: options.appearance || "always",
|
||||||
answer = null;
|
callback: value => {
|
||||||
},
|
retries = 0;
|
||||||
// its code is cloudflare's (110200: this site's name is not on the widget)
|
settle(value);
|
||||||
"error-callback": code => {
|
},
|
||||||
console.log(`captcha error ${code}`);
|
"expired-callback": () => {
|
||||||
settle("");
|
answer = null;
|
||||||
},
|
},
|
||||||
});
|
// its code is cloudflare's (110200: this site's name is not on
|
||||||
}, () => settle(""));
|
// the widget). many pass with a second go: it is had first.
|
||||||
}
|
"error-callback": code => {
|
||||||
|
console.log(`captcha error ${code}`);
|
||||||
|
if (retries < MAX_RETRIES) {
|
||||||
|
retries++;
|
||||||
|
answer = null;
|
||||||
|
setTimeout(() => window.turnstile.reset(widget), 1000 * retries);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
settle("");
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.log(`captcha could not start: ${err.message}`);
|
||||||
|
settle("");
|
||||||
|
}
|
||||||
|
}, () => {
|
||||||
|
starting = false;
|
||||||
|
settle("");
|
||||||
|
});
|
||||||
|
};
|
||||||
|
start();
|
||||||
return {
|
return {
|
||||||
on: Boolean(siteKey),
|
on: Boolean(siteKey),
|
||||||
answer: () => {
|
answer: () => {
|
||||||
if (!siteKey) {
|
if (!siteKey) {
|
||||||
return Promise.resolve(undefined);
|
return Promise.resolve(undefined);
|
||||||
}
|
}
|
||||||
|
// one that could not load is tried again when an answer is wanted
|
||||||
|
if (answer === "" && widget === null) {
|
||||||
|
answer = null;
|
||||||
|
start();
|
||||||
|
}
|
||||||
return answer !== null ? Promise.resolve(answer) : new Promise(resolve => waiting.push(resolve));
|
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: () => {
|
reset: () => {
|
||||||
if (widget !== null) {
|
if (widget !== null) {
|
||||||
answer = null;
|
answer = null;
|
||||||
|
retries = 0;
|
||||||
window.turnstile.reset(widget);
|
window.turnstile.reset(widget);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
return {on: Boolean(siteKey), mount, FAILED: "Captcha could not load. Reload the page."};
|
return {on: Boolean(siteKey), mount, FAILED: "Captcha could not load. Check your connection or content blocker, then reload."};
|
||||||
})();
|
})();
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Burrow dashboard</title>
|
||||||
|
<link rel="icon" type="image/png" href="/logo-square.png">
|
||||||
|
<style>
|
||||||
|
@font-face { font-family: DigitalDelivery; src: url("/fonts/CCDigitalDelivery-Regular.otf") format("opentype"); }
|
||||||
|
@font-face { font-family: DigitalDelivery; font-weight: 700; src: url("/fonts/CCDigitalDelivery-Bold.otf") format("opentype"); }
|
||||||
|
:root { color-scheme: dark; } * { box-sizing: border-box; }
|
||||||
|
body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px; background: #000; color: #fff; font: 16px/1.45 DigitalDelivery, system-ui, sans-serif; }
|
||||||
|
main { width: min(720px, 100%); padding: clamp(24px, 6vw, 48px); border: 1px solid #333; border-radius: 22px; background: #0d0d0d; }
|
||||||
|
header { display: flex; align-items: center; gap: 15px; margin-bottom: 28px; } header img { width: 54px; height: 54px; object-fit: contain; } h1 { margin: 0; font-size: 30px; } p { color: #aaa; margin: 5px 0 0; }
|
||||||
|
.choices { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 14px; } a { display: block; padding: 20px; color: inherit; text-decoration: none; border: 1px solid #3a3a3a; border-radius: 15px; background: #151515; } a:hover, a:focus-visible { background: #222; border-color: #fff; outline: none; } strong { display: block; font-size: 19px; margin-bottom: 5px; } .hint { font-size: 13px; color: #aaa; } footer { margin-top: 24px; font-size: 12px; color: #777; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>
|
||||||
|
<header><img src="/logo.png" alt=""><div><h1>Burrow dashboard</h1><p>One place for running and moderating your server.</p></div></header>
|
||||||
|
<div class="choices">
|
||||||
|
<a href="/dashboard/admin"><strong>Owner dashboard</strong><span class="hint">Server settings, accounts, logs, items, roles, and all administration.</span></a>
|
||||||
|
<a href="/dashboard/staff"><strong>Staff dashboard</strong><span class="hint">Player care, reports, moderation, review, and server health.</span></a>
|
||||||
|
</div>
|
||||||
|
<footer>Access remains role-based. Staff never receive owner controls.</footer>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+1022
-3
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,67 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Item preview</title>
|
||||||
|
<style>
|
||||||
|
html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: #1a1a1a; }
|
||||||
|
ruffle-player, ruffle-object, ruffle-embed { display: block; width: 100%; height: 100%; }
|
||||||
|
</style>
|
||||||
|
<script>
|
||||||
|
// ruffle's own settings: no menus, overlays or sound.
|
||||||
|
window.RufflePlayer = {config: {
|
||||||
|
publicPath: "https://cdn.jsdelivr.net/npm/@ruffle-rs/[email protected]/",
|
||||||
|
polyfills: false,
|
||||||
|
autoplay: "on",
|
||||||
|
unmuteOverlay: "hidden",
|
||||||
|
splashScreen: false,
|
||||||
|
contextMenu: "off",
|
||||||
|
letterbox: "off",
|
||||||
|
backgroundColor: "#1A1A1A", // the giver page's
|
||||||
|
volume: 0,
|
||||||
|
openUrlMode: "deny",
|
||||||
|
allowScriptAccess: false,
|
||||||
|
showSwfDownload: false,
|
||||||
|
warnOnUnsupportedContent: false,
|
||||||
|
logLevel: "error",
|
||||||
|
}};
|
||||||
|
</script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/@ruffle-rs/[email protected]/ruffle.js" integrity="sha256-JgNqlFZwiN+z3oinWejtEKTOoHspUArzbzRe70JCAJg=" crossorigin="anonymous"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<script>
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
// one den item for the web item giver (public/items.html), in a frame of
|
||||||
|
// its own: #id=&v=&tint=rrggbb&s=, as Give would give it. its art plays
|
||||||
|
// in public/item-preview.swf (tools/preview-host), which sets the
|
||||||
|
// variant and tint as a den does. served sandboxed (lib/manage.js): this
|
||||||
|
// page has no origin, so no sign-in, of its own.
|
||||||
|
let player = null;
|
||||||
|
|
||||||
|
const show = () => {
|
||||||
|
const wanted = new URLSearchParams(location.hash.slice(1));
|
||||||
|
const id = /^\d{1,9}$/.test(wanted.get("id") || "") ? wanted.get("id") : null;
|
||||||
|
if (player) {
|
||||||
|
player.remove();
|
||||||
|
player = null;
|
||||||
|
}
|
||||||
|
if (!id || !window.RufflePlayer || !window.RufflePlayer.newest) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
player = window.RufflePlayer.newest().createPlayer();
|
||||||
|
document.body.append(player);
|
||||||
|
const parameters = {art: new URL(`/account/art/den/${id}`, location.href).href, version: String(Number(wanted.get("v")) || 0)};
|
||||||
|
if (/^[0-9a-f]{6}$/i.test(wanted.get("tint") || "")) {
|
||||||
|
parameters.tint = wanted.get("tint");
|
||||||
|
parameters.strength = String(Number(wanted.get("s")) || 100);
|
||||||
|
}
|
||||||
|
const movie = {url: new URL("/account/item-preview.swf", location.href).href, parameters};
|
||||||
|
(player.ruffle ? player.ruffle().load(movie) : player.load(movie)).catch(() => {});
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener("hashchange", show);
|
||||||
|
show();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Binary file not shown.
@@ -0,0 +1,786 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Item giver</title>
|
||||||
|
<link rel="icon" type="image/png" href="/logo-square.png">
|
||||||
|
<style>
|
||||||
|
/* the account page's look (public/account.html): black and white, in
|
||||||
|
the game's own text font. the only colours are the items' own. */
|
||||||
|
@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; }
|
||||||
|
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; flex: 1; }
|
||||||
|
h2 { margin: 0 0 6px; font-size: 17px; font-weight: 700; }
|
||||||
|
h3 { margin: 16px 0 8px; font-size: 14px; font-weight: 700; }
|
||||||
|
p { margin: 0 0 12px; color: var(--muted); }
|
||||||
|
.wrap { max-width: 760px; margin: 0 auto; }
|
||||||
|
header { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }
|
||||||
|
header img { width: 40px; height: 40px; }
|
||||||
|
section {
|
||||||
|
padding: 20px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 18px;
|
||||||
|
}
|
||||||
|
input, select {
|
||||||
|
font: inherit;
|
||||||
|
color: var(--text);
|
||||||
|
background: var(--bg);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 14px;
|
||||||
|
padding: 9px 14px 10px;
|
||||||
|
}
|
||||||
|
input:hover, select:hover { border-color: #555; }
|
||||||
|
input:focus, select:focus { outline: none; border-color: var(--text); }
|
||||||
|
input:disabled { opacity: 0.4; }
|
||||||
|
button, a.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;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
button:hover, a.button:hover { background: var(--raised); border-color: #555; }
|
||||||
|
button:disabled { opacity: 0.45; cursor: default; }
|
||||||
|
button:focus-visible, a:focus-visible, input: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[aria-pressed="true"] { border-color: var(--text); background: var(--raised); }
|
||||||
|
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
|
||||||
|
#search-row input { flex: 1; min-width: 180px; }
|
||||||
|
.status { min-height: 20px; margin: 10px 0 0; font-size: 13px; color: var(--muted); }
|
||||||
|
.status.bad { color: var(--text); }
|
||||||
|
.status.bad::before { content: "! "; font-weight: 700; }
|
||||||
|
#results { list-style: none; margin: 12px 0 0; padding: 0; display: grid; gap: 6px; }
|
||||||
|
#results button {
|
||||||
|
display: flex; width: 100%; gap: 10px; align-items: baseline;
|
||||||
|
border-radius: 14px; padding: 9px 14px 10px; text-align: left; white-space: normal;
|
||||||
|
}
|
||||||
|
#results .name { flex: 1; overflow-wrap: anywhere; }
|
||||||
|
.meta { font-size: 12px; color: var(--muted); white-space: nowrap; }
|
||||||
|
.swatches { display: inline-flex; gap: 3px; vertical-align: middle; }
|
||||||
|
.swatch { width: 16px; height: 16px; border-radius: 5px; border: 1px solid rgba(255, 255, 255, 0.25); }
|
||||||
|
#presets, #variants { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||||
|
#presets button, #variants button { padding: 6px 10px 7px; border-radius: 12px; }
|
||||||
|
.slot { display: grid; grid-template-columns: 74px 44px 1fr; gap: 8px; align-items: center; margin-bottom: 8px; }
|
||||||
|
.slot span { color: var(--muted); font-size: 13px; }
|
||||||
|
.colour-slot { grid-template-columns: 74px 44px minmax(0, 160px) 96px; }
|
||||||
|
input.aj { width: 100%; min-width: 0; font-variant-numeric: tabular-nums; }
|
||||||
|
#whole-row { margin-top: 4px; }
|
||||||
|
#whole-row > span:first-child { width: 74px; color: var(--muted); font-size: 13px; }
|
||||||
|
#whole { width: 190px; }
|
||||||
|
#whole-note { white-space: normal; }
|
||||||
|
input[type="color"] { width: 44px; height: 38px; padding: 3px; border-radius: 10px; cursor: pointer; }
|
||||||
|
input.hex { width: 100%; max-width: 160px; font-variant-numeric: tabular-nums; text-transform: lowercase; }
|
||||||
|
input[type="range"] { flex: 1; padding: 0; border: none; accent-color: #fff; }
|
||||||
|
label.check { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; }
|
||||||
|
#give-row { margin-top: 16px; }
|
||||||
|
#item-head { display: flex; gap: 16px; align-items: center; }
|
||||||
|
#item-head > div:first-child { flex: 1; min-width: 0; }
|
||||||
|
#preview {
|
||||||
|
position: relative; flex: none; width: 160px; height: 160px;
|
||||||
|
display: grid; place-items: center;
|
||||||
|
background: var(--raised); border: 1px solid var(--line); border-radius: 14px; overflow: hidden;
|
||||||
|
}
|
||||||
|
#preview canvas, #preview img { max-width: 144px; max-height: 144px; }
|
||||||
|
#preview iframe { width: 100%; height: 100%; border: 0; }
|
||||||
|
#preview-note { position: absolute; inset: auto 8px 6px; font-size: 11px; text-align: center; color: var(--muted); }
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.slot { grid-template-columns: 64px 44px 1fr; }
|
||||||
|
.colour-slot { grid-template-columns: 64px 44px minmax(0, 1fr) 56px; }
|
||||||
|
.colour-slot span { white-space: nowrap; }
|
||||||
|
#whole-row > span:first-child { width: auto; }
|
||||||
|
#whole { width: 100%; }
|
||||||
|
#item-head { flex-direction: column-reverse; align-items: flex-start; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="wrap">
|
||||||
|
<header>
|
||||||
|
<img src="/logo.png" alt="">
|
||||||
|
<h1>Item giver</h1>
|
||||||
|
<a class="button" href="/account">Your account</a>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section id="gate" hidden>
|
||||||
|
<h2 id="gate-title">Sign in first</h2>
|
||||||
|
<p id="gate-text">The item giver uses your account page's sign-in.</p>
|
||||||
|
<a class="button" href="/account">Go to your account page</a>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="finder" hidden>
|
||||||
|
<p id="who"></p>
|
||||||
|
<div class="row" id="search-row">
|
||||||
|
<input id="query" type="search" placeholder="Name or id" maxlength="60" autocomplete="off" spellcheck="false" aria-label="Search items">
|
||||||
|
<select id="kind" aria-label="Kind of item">
|
||||||
|
<option value="all">Everything</option>
|
||||||
|
<option value="clothing">Clothing</option>
|
||||||
|
<option value="den">Den items</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<p class="status" id="search-status" role="status"></p>
|
||||||
|
<ul id="results"></ul>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="detail" hidden>
|
||||||
|
<div id="item-head">
|
||||||
|
<div>
|
||||||
|
<h2 id="item-name"></h2>
|
||||||
|
<p class="meta" id="item-meta"></p>
|
||||||
|
</div>
|
||||||
|
<div id="preview" aria-label="How it looks">
|
||||||
|
<canvas id="preview-icon" hidden></canvas>
|
||||||
|
<img id="preview-art" alt="" hidden>
|
||||||
|
<iframe id="preview-den" title="How it looks" sandbox="allow-scripts" hidden></iframe>
|
||||||
|
<span id="preview-note"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="clothing-part">
|
||||||
|
<h3>The item's own colours</h3>
|
||||||
|
<div id="presets"></div>
|
||||||
|
<h3>Your own colours</h3>
|
||||||
|
<div id="slots"></div>
|
||||||
|
<div class="row" id="whole-row">
|
||||||
|
<span>Whole item</span>
|
||||||
|
<input class="aj" id="whole" inputmode="numeric" maxlength="11" spellcheck="false" autocomplete="off" placeholder="AJ colour" aria-label="The whole item's colour as the game writes it">
|
||||||
|
<span class="meta" id="whole-note"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="den-part">
|
||||||
|
<h3>Variant</h3>
|
||||||
|
<div id="variants"></div>
|
||||||
|
<p id="no-variants" hidden>This item has no other variants.</p>
|
||||||
|
<h3>Tint</h3>
|
||||||
|
<p id="tint-off" hidden>Mannequins cannot be tinted.</p>
|
||||||
|
<div id="tint-on">
|
||||||
|
<label class="check"><input id="tint" type="checkbox"> The whole item in shades of a colour</label>
|
||||||
|
<div class="slot" style="margin-top:10px">
|
||||||
|
<span>Colour</span>
|
||||||
|
<input type="color" id="tint-picker" value="#4ab3f4" aria-label="Tint colour">
|
||||||
|
<input class="hex" id="tint-hex" value="#4ab3f4" maxlength="7" spellcheck="false" aria-label="Tint colour as #RRGGBB">
|
||||||
|
</div>
|
||||||
|
<div class="row">
|
||||||
|
<span class="meta">Strength</span>
|
||||||
|
<input type="range" id="tint-strength" min="1" max="100" value="70" aria-label="Tint strength">
|
||||||
|
<span class="meta" id="tint-strength-text">70%</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row" id="give-row">
|
||||||
|
<button class="primary" id="give" type="button">Give</button>
|
||||||
|
<span class="meta" id="give-what"></span>
|
||||||
|
</div>
|
||||||
|
<p class="status" id="give-status" role="status"></p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
// the item giver on the web (lib/admin.js searchFor and giveAs, by way
|
||||||
|
// of lib/manage.js), signed in as on the account page: items go to that
|
||||||
|
// account, as the in-game giver's go to the one playing.
|
||||||
|
const $ = id => document.getElementById(id);
|
||||||
|
const KINDS = {clothing: "Clothing", den: "Den item"};
|
||||||
|
|
||||||
|
let chosen = null; // the result picked
|
||||||
|
let preset = 0; // the item's own colour picked, or null for the slots' own
|
||||||
|
let variant = 0;
|
||||||
|
|
||||||
|
const setStatus = (id, text, bad = false) => {
|
||||||
|
$(id).textContent = text;
|
||||||
|
$(id).classList.toggle("bad", bad);
|
||||||
|
};
|
||||||
|
|
||||||
|
const api = async (path, body) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/account/api/${path}`, body === undefined ? {} : {
|
||||||
|
method: "POST",
|
||||||
|
headers: {"Content-Type": "application/json"},
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
return {ok: response.ok, status: response.status, data: await response.json().catch(() => ({}))};
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
return {ok: false, status: 0, data: {error: "The server did not answer."}};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// "#abc", "abc", "#aabbcc" or "aabbcc" as "#aabbcc"; null for anything else.
|
||||||
|
const readHex = text => {
|
||||||
|
const match = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(text).trim());
|
||||||
|
if (!match) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const digits = match[1].length === 3 ? match[1].replace(/./g, digit => digit + digit) : match[1];
|
||||||
|
return `#${digits.toLowerCase()}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const swatches = colours => {
|
||||||
|
const box = document.createElement("span");
|
||||||
|
box.className = "swatches";
|
||||||
|
for (const colour of colours) {
|
||||||
|
const swatch = document.createElement("span");
|
||||||
|
swatch.className = "swatch";
|
||||||
|
swatch.style.background = `#${colour}`;
|
||||||
|
box.append(swatch);
|
||||||
|
}
|
||||||
|
return box;
|
||||||
|
};
|
||||||
|
|
||||||
|
// a colour picker and a #RRGGBB box that follow each other; `onChange`
|
||||||
|
// is told of each colour taken.
|
||||||
|
const pairUp = (picker, box, onChange) => {
|
||||||
|
picker.addEventListener("input", () => {
|
||||||
|
box.value = picker.value;
|
||||||
|
onChange();
|
||||||
|
});
|
||||||
|
box.addEventListener("input", () => {
|
||||||
|
const hex = readHex(box.value);
|
||||||
|
box.setCustomValidity(hex ? "" : "#RRGGBB");
|
||||||
|
if (hex) {
|
||||||
|
picker.value = hex;
|
||||||
|
onChange();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
box.addEventListener("change", () => {
|
||||||
|
const hex = readHex(box.value);
|
||||||
|
box.value = hex || picker.value;
|
||||||
|
box.setCustomValidity("");
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// the game's way of writing colours: one number for the whole item, its
|
||||||
|
// four colours' places in the game's palette of 256, colour 1 the top
|
||||||
|
// byte; written unsigned, or signed as lists of the game's colours often
|
||||||
|
// have them. top byte 0xFD: a custom colour, four RGB values of the
|
||||||
|
// server's own (lib/colours.js), not palette places.
|
||||||
|
let palette = null; // the game's 256 colours, "#rrggbb", once the server says
|
||||||
|
let customId = null; // the custom colour the four make, when one is known
|
||||||
|
const CUSTOM_TOP = 0xFD;
|
||||||
|
const isCustom = value => value >>> 24 === CUSTOM_TOP;
|
||||||
|
const readWhole = text => {
|
||||||
|
const value = /^-?\d{1,10}$/.test(String(text).trim()) ? Number(String(text).trim()) : NaN;
|
||||||
|
return value >= -0x80000000 && value <= 0xFFFFFFFF ? value >>> 0 : null;
|
||||||
|
};
|
||||||
|
// one colour's place, 0 to 255; -128 to -1 are 128 to 255 written signed
|
||||||
|
const readIndex = text => {
|
||||||
|
const value = /^-?\d{1,3}$/.test(String(text).trim()) ? Number(String(text).trim()) : NaN;
|
||||||
|
return value >= -128 && value <= 255 ? (value + 256) % 256 : null;
|
||||||
|
};
|
||||||
|
const pack = indexes => indexes.reduce((value, index) => value * 256 + index, 0);
|
||||||
|
|
||||||
|
// a slot set: its colour, and its place in the palette or null. `from`
|
||||||
|
// is the box typed in, left as typed.
|
||||||
|
const setSlot = (slot, hex, index, from = null) => {
|
||||||
|
slot.index = index;
|
||||||
|
if (from !== "hex") {
|
||||||
|
slot.picker.value = hex;
|
||||||
|
slot.box.value = hex;
|
||||||
|
}
|
||||||
|
if (from !== "aj") {
|
||||||
|
slot.aj.value = index === null ? "" : String(index);
|
||||||
|
slot.aj.setCustomValidity("");
|
||||||
|
}
|
||||||
|
slot.aj.placeholder = index === null && palette ? "custom" : "AJ";
|
||||||
|
};
|
||||||
|
|
||||||
|
// what Give gives: a colour id, or null for a custom colour still to make.
|
||||||
|
const wholeValue = () => {
|
||||||
|
if (preset !== null && chosen && chosen.presets[preset]) {
|
||||||
|
return chosen.presets[preset].id;
|
||||||
|
}
|
||||||
|
if (customId !== null) {
|
||||||
|
return customId;
|
||||||
|
}
|
||||||
|
return slots.every(slot => slot.index !== null) ? pack(slots.map(slot => slot.index)) : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
let lookupTimer = null;
|
||||||
|
const showWhole = () => {
|
||||||
|
const value = wholeValue();
|
||||||
|
if (document.activeElement !== $("whole")) {
|
||||||
|
$("whole").value = value === null ? "" : String(value);
|
||||||
|
$("whole").setCustomValidity("");
|
||||||
|
}
|
||||||
|
$("whole-note").textContent = value === null ? "A new custom colour, made when you give it."
|
||||||
|
: `${value} unsigned · ${value | 0} signed${isCustom(value) ? " · a custom colour" : ""}`;
|
||||||
|
// four colours not all the palette's: a custom colour they make already?
|
||||||
|
clearTimeout(lookupTimer);
|
||||||
|
if (value === null) {
|
||||||
|
const asked = slots.map(slot => slot.picker.value.slice(1)).join(",");
|
||||||
|
lookupTimer = setTimeout(async () => {
|
||||||
|
const result = await api(`colour?rgbs=${asked}`);
|
||||||
|
if (result.ok && result.data.id !== null && preset === null && customId === null
|
||||||
|
&& slots.map(slot => slot.picker.value.slice(1)).join(",") === asked) {
|
||||||
|
customId = result.data.id;
|
||||||
|
showWhole();
|
||||||
|
showChoice();
|
||||||
|
}
|
||||||
|
}, 200);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// a whole item's colour taken: from the whole box (`from`) or one of the item's own.
|
||||||
|
const applyWhole = async (value, from = null, own = null) => {
|
||||||
|
if (isCustom(value)) {
|
||||||
|
const colours = own || await api(`colour?id=${value}`).then(result => (result.ok ? result.data.colours : null));
|
||||||
|
if (!colours) {
|
||||||
|
$("whole-note").textContent = "No such custom colour.";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (from === "whole" && readWhole($("whole").value) !== value) {
|
||||||
|
return; // typed on since
|
||||||
|
}
|
||||||
|
colours.forEach((colour, index) => setSlot(slots[index], `#${colour}`, null));
|
||||||
|
customId = value;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
[24, 16, 8, 0].forEach((shift, index) => {
|
||||||
|
const place = value >>> shift & 255;
|
||||||
|
setSlot(slots[index], palette ? palette[place] : own ? `#${own[index]}` : slots[index].picker.value, place);
|
||||||
|
});
|
||||||
|
customId = null;
|
||||||
|
}
|
||||||
|
showChoice();
|
||||||
|
};
|
||||||
|
|
||||||
|
const slots = [];
|
||||||
|
for (let slot = 0; slot < 4; slot++) {
|
||||||
|
const row = document.createElement("div");
|
||||||
|
row.className = "slot colour-slot";
|
||||||
|
const name = document.createElement("span");
|
||||||
|
name.textContent = `Colour ${slot + 1}`;
|
||||||
|
const picker = document.createElement("input");
|
||||||
|
picker.type = "color";
|
||||||
|
picker.value = "#ffffff";
|
||||||
|
picker.setAttribute("aria-label", `Colour ${slot + 1}`);
|
||||||
|
const box = document.createElement("input");
|
||||||
|
box.className = "hex";
|
||||||
|
box.maxLength = 7;
|
||||||
|
box.spellcheck = false;
|
||||||
|
box.value = "#ffffff";
|
||||||
|
box.setAttribute("aria-label", `Colour ${slot + 1} as #RRGGBB`);
|
||||||
|
const aj = document.createElement("input");
|
||||||
|
aj.className = "aj";
|
||||||
|
aj.inputMode = "numeric";
|
||||||
|
aj.maxLength = 4;
|
||||||
|
aj.spellcheck = false;
|
||||||
|
aj.autocomplete = "off";
|
||||||
|
aj.placeholder = "AJ";
|
||||||
|
aj.title = "Its place in the game's palette: 0 to 255 (-128 to -1 written signed)";
|
||||||
|
aj.setAttribute("aria-label", `Colour ${slot + 1} as the game writes it, 0 to 255`);
|
||||||
|
const own = {picker, box, aj, index: null};
|
||||||
|
pairUp(picker, box, () => {
|
||||||
|
const place = palette ? palette.indexOf(picker.value) : -1;
|
||||||
|
setSlot(own, picker.value, place < 0 ? null : place, "hex");
|
||||||
|
preset = null;
|
||||||
|
customId = null;
|
||||||
|
showChoice();
|
||||||
|
});
|
||||||
|
aj.addEventListener("input", () => {
|
||||||
|
const place = readIndex(aj.value);
|
||||||
|
aj.setCustomValidity(place === null || !palette ? "0 to 255" : "");
|
||||||
|
if (place !== null && palette) {
|
||||||
|
setSlot(own, palette[place], place, "aj");
|
||||||
|
preset = null;
|
||||||
|
customId = null;
|
||||||
|
showChoice();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
aj.addEventListener("change", () => setSlot(own, own.picker.value, own.index));
|
||||||
|
row.append(name, picker, box, aj);
|
||||||
|
$("slots").append(row);
|
||||||
|
slots.push(own);
|
||||||
|
}
|
||||||
|
$("whole").addEventListener("input", () => {
|
||||||
|
const value = readWhole($("whole").value);
|
||||||
|
$("whole").setCustomValidity(value === null ? "A colour id, signed or not" : "");
|
||||||
|
if (value !== null) {
|
||||||
|
preset = null;
|
||||||
|
applyWhole(value, "whole");
|
||||||
|
}
|
||||||
|
else if ($("whole").value.trim()) {
|
||||||
|
$("whole-note").textContent = "A whole number: -2147483648 to 4294967295.";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
$("whole").addEventListener("change", showChoice);
|
||||||
|
pairUp($("tint-picker"), $("tint-hex"), () => {
|
||||||
|
$("tint").checked = true;
|
||||||
|
showChoice();
|
||||||
|
});
|
||||||
|
$("tint").addEventListener("change", showChoice);
|
||||||
|
$("tint-strength").addEventListener("input", () => {
|
||||||
|
$("tint-strength-text").textContent = `${$("tint-strength").value}%`;
|
||||||
|
$("tint").checked = true;
|
||||||
|
showChoice();
|
||||||
|
});
|
||||||
|
|
||||||
|
// the item as it would be given (lib/itempreview.js). clothing: its
|
||||||
|
// closet icon, coloured here as the game colours it
|
||||||
|
// (PaletteHelper.BuildAnimalPalette, LayerBitmap.paintFrame). den items:
|
||||||
|
// their art played in a frame of public/item-preview.html. a custom
|
||||||
|
// item with a picture of its own: that picture.
|
||||||
|
const icons = new Map(); // clothing id: its icon, {w, h, bytes}, or null
|
||||||
|
const rgbOf = hex => parseInt(hex.slice(1), 16);
|
||||||
|
const gradient = (palette, rgb, start, count) => {
|
||||||
|
let [red, green, blue] = [rgb >> 16 & 255, rgb >> 8 & 255, rgb & 255];
|
||||||
|
const [stepRed, stepGreen, stepBlue] = [red, green, blue].map(value => Math.floor(value / (count + 2)));
|
||||||
|
for (let at = start + count - 1, left = count; left > 0; left--, at--) {
|
||||||
|
[255, 192, 128, 64].forEach((alpha, shade) => {
|
||||||
|
palette[at + 25 * shade] = [red, green, blue, alpha];
|
||||||
|
});
|
||||||
|
red -= stepRed;
|
||||||
|
green -= stepGreen;
|
||||||
|
blue -= stepBlue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const mix = (one, other) => [16, 8, 0].reduce((sum, shift) => sum | (((one >> shift & 255) + (other >> shift & 255)) >> 1) << shift, 0);
|
||||||
|
const paletteOf = ([one, two, three, four]) => {
|
||||||
|
const palette = [];
|
||||||
|
[[one, 1, 3], [two, 4, 3], [three, 7, 3], [four, 10, 3], [mix(one, two), 13, 2], [mix(two, three), 15, 2],
|
||||||
|
[mix(one, three), 17, 2], [mix(one, four), 19, 2], [mix(two, four), 21, 2], [mix(three, four), 23, 2]]
|
||||||
|
.forEach(([rgb, start, count]) => gradient(palette, rgb, start, count));
|
||||||
|
return palette;
|
||||||
|
};
|
||||||
|
const paintIcon = (icon, colours) => {
|
||||||
|
const canvas = $("preview-icon");
|
||||||
|
canvas.width = icon.w;
|
||||||
|
canvas.height = icon.h;
|
||||||
|
const context = canvas.getContext("2d");
|
||||||
|
const image = context.createImageData(icon.w, icon.h);
|
||||||
|
const palette = paletteOf(colours.map(rgbOf));
|
||||||
|
const bytes = icon.bytes;
|
||||||
|
let [x, y, at] = [0, 0, 0];
|
||||||
|
while (at < bytes.length) {
|
||||||
|
let index = bytes[at++];
|
||||||
|
let run = 1;
|
||||||
|
if (index & 0x80) {
|
||||||
|
index &= 0x7F;
|
||||||
|
run = bytes[at++] + 1;
|
||||||
|
}
|
||||||
|
if (index === 0) {
|
||||||
|
x += run;
|
||||||
|
if (x >= icon.w) {
|
||||||
|
const over = x - icon.w;
|
||||||
|
x = over % icon.w;
|
||||||
|
y += Math.floor(over / icon.w) + 1;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const colour = palette[index];
|
||||||
|
for (; run > 0; run--) {
|
||||||
|
if (colour && y < icon.h) {
|
||||||
|
image.data.set(colour, (y * icon.w + x) * 4);
|
||||||
|
}
|
||||||
|
if (++x === icon.w) {
|
||||||
|
x = 0;
|
||||||
|
y++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
context.putImageData(image, 0, 0);
|
||||||
|
};
|
||||||
|
|
||||||
|
let previewShown = null; // what the preview shows, to change only what changed
|
||||||
|
let denTimer = null;
|
||||||
|
const showPreview = () => {
|
||||||
|
const entry = chosen;
|
||||||
|
const note = text => {
|
||||||
|
$("preview-note").textContent = text;
|
||||||
|
};
|
||||||
|
const only = id => {
|
||||||
|
for (const one of ["preview-icon", "preview-art", "preview-den"]) {
|
||||||
|
$(one).hidden = one !== id;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if (entry.art) {
|
||||||
|
if (previewShown !== entry.art) {
|
||||||
|
previewShown = entry.art;
|
||||||
|
only("preview-art");
|
||||||
|
note("");
|
||||||
|
$("preview-art").src = entry.art;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (entry.kind === "clothing") {
|
||||||
|
const colours = slots.map(slot => slot.picker.value);
|
||||||
|
const icon = icons.get(entry.id);
|
||||||
|
if (icon === undefined) {
|
||||||
|
only(null);
|
||||||
|
note("Loading…");
|
||||||
|
icons.set(entry.id, false);
|
||||||
|
fetch(`/account/art/clothing/${entry.id}`).then(response => (response.ok ? response.json() : null)).catch(() => null).then(found => {
|
||||||
|
icons.set(entry.id, found ? {w: found.w, h: found.h, bytes: Uint8Array.from(atob(found.b), letter => letter.charCodeAt(0))} : null);
|
||||||
|
if (chosen === entry) {
|
||||||
|
showPreview();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (icon) {
|
||||||
|
only("preview-icon");
|
||||||
|
note("");
|
||||||
|
paintIcon(icon, colours);
|
||||||
|
}
|
||||||
|
else if (icon === null) {
|
||||||
|
only(null);
|
||||||
|
note("No picture");
|
||||||
|
}
|
||||||
|
previewShown = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const wanted = new URLSearchParams({id: entry.id, v: variant});
|
||||||
|
if (entry.tintable && $("tint").checked) {
|
||||||
|
wanted.set("tint", $("tint-picker").value.slice(1));
|
||||||
|
wanted.set("s", $("tint-strength").value);
|
||||||
|
}
|
||||||
|
const address = `/account/item-preview#${wanted}`;
|
||||||
|
if (previewShown === address) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
previewShown = address;
|
||||||
|
only("preview-den");
|
||||||
|
note("");
|
||||||
|
// a new player each time: a slider dragged waits for it to stop
|
||||||
|
clearTimeout(denTimer);
|
||||||
|
denTimer = setTimeout(() => {
|
||||||
|
$("preview-den").src = address;
|
||||||
|
}, $("preview-den").src ? 250 : 0);
|
||||||
|
};
|
||||||
|
|
||||||
|
// what Give would give, said beside it.
|
||||||
|
function showChoice() {
|
||||||
|
for (const [index, button] of [...$("presets").children].entries()) {
|
||||||
|
button.setAttribute("aria-pressed", String(index === preset));
|
||||||
|
}
|
||||||
|
for (const button of $("variants").children) {
|
||||||
|
button.setAttribute("aria-pressed", String(Number(button.dataset.variant) === variant));
|
||||||
|
}
|
||||||
|
if (!chosen) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
showPreview();
|
||||||
|
if (chosen.kind === "clothing") {
|
||||||
|
showWhole();
|
||||||
|
const value = wholeValue();
|
||||||
|
$("give-what").textContent = preset !== null ? `Its own colour ${preset + 1} (${value})`
|
||||||
|
: value !== null ? `Colour ${value}` : `A new colour of ${slots.map(slot => slot.picker.value).join(" ")}`;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const parts = [chosen.variants.length ? `Variant ${chosen.variants.indexOf(variant) + 1}` : "As it is"];
|
||||||
|
if (chosen.tintable && $("tint").checked) {
|
||||||
|
parts.push(`tinted ${$("tint-picker").value} at ${$("tint-strength").value}%`);
|
||||||
|
}
|
||||||
|
$("give-what").textContent = parts.join(", ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const choosePreset = index => {
|
||||||
|
preset = index;
|
||||||
|
applyWhole(chosen.presets[index].id, null, chosen.presets[index].colours);
|
||||||
|
};
|
||||||
|
|
||||||
|
const choose = entry => {
|
||||||
|
chosen = entry;
|
||||||
|
$("detail").hidden = false;
|
||||||
|
$("item-name").textContent = entry.name;
|
||||||
|
$("item-meta").textContent = `${KINDS[entry.kind]} · id ${entry.id}${entry.cost ? ` · ${entry.cost} gems in shops` : ""}`;
|
||||||
|
$("clothing-part").hidden = entry.kind !== "clothing";
|
||||||
|
$("den-part").hidden = entry.kind !== "den";
|
||||||
|
setStatus("give-status", "");
|
||||||
|
if (entry.kind === "clothing") {
|
||||||
|
$("presets").textContent = "";
|
||||||
|
entry.presets.forEach((option, index) => {
|
||||||
|
const button = document.createElement("button");
|
||||||
|
button.type = "button";
|
||||||
|
button.title = `Colour ${index + 1} (${option.id})`;
|
||||||
|
button.append(option.colours ? swatches(option.colours) : String(index + 1));
|
||||||
|
button.addEventListener("click", () => choosePreset(index));
|
||||||
|
$("presets").append(button);
|
||||||
|
});
|
||||||
|
if (entry.presets.length) {
|
||||||
|
choosePreset(0);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
preset = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
$("variants").textContent = "";
|
||||||
|
variant = entry.variants.length ? entry.variants[0] : 0;
|
||||||
|
entry.variants.forEach((version, index) => {
|
||||||
|
const button = document.createElement("button");
|
||||||
|
button.type = "button";
|
||||||
|
button.dataset.variant = String(version);
|
||||||
|
button.title = `Variant ${index + 1}`;
|
||||||
|
button.append(entry.variantColours ? swatches(entry.variantColours[index]) : String(index + 1));
|
||||||
|
button.addEventListener("click", () => {
|
||||||
|
variant = version;
|
||||||
|
showChoice();
|
||||||
|
});
|
||||||
|
$("variants").append(button);
|
||||||
|
});
|
||||||
|
$("no-variants").hidden = entry.variants.length > 0;
|
||||||
|
$("tint-on").hidden = !entry.tintable;
|
||||||
|
$("tint-off").hidden = entry.tintable;
|
||||||
|
$("tint").checked = false;
|
||||||
|
}
|
||||||
|
showChoice();
|
||||||
|
$("detail").scrollIntoView({behavior: "smooth", block: "nearest"});
|
||||||
|
};
|
||||||
|
|
||||||
|
const showResults = found => {
|
||||||
|
const list = $("results");
|
||||||
|
list.textContent = "";
|
||||||
|
for (const entry of found.results) {
|
||||||
|
const row = document.createElement("li");
|
||||||
|
const button = document.createElement("button");
|
||||||
|
button.type = "button";
|
||||||
|
const name = document.createElement("span");
|
||||||
|
name.className = "name";
|
||||||
|
name.textContent = entry.name;
|
||||||
|
const meta = document.createElement("span");
|
||||||
|
meta.className = "meta";
|
||||||
|
meta.textContent = `${KINDS[entry.kind]} · ${entry.id}`;
|
||||||
|
button.append(name, meta);
|
||||||
|
button.addEventListener("click", () => choose(entry));
|
||||||
|
row.append(button);
|
||||||
|
list.append(row);
|
||||||
|
}
|
||||||
|
setStatus("search-status", found.total === 0 ? "Nothing found." : found.total > found.results.length
|
||||||
|
? `${found.total} found; the first ${found.results.length} shown. Type more to narrow it down.` : `${found.total} found.`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const showGate = (title, text) => {
|
||||||
|
$("gate").hidden = false;
|
||||||
|
$("finder").hidden = true;
|
||||||
|
$("detail").hidden = true;
|
||||||
|
$("gate-title").textContent = title;
|
||||||
|
$("gate-text").textContent = text;
|
||||||
|
};
|
||||||
|
|
||||||
|
let asked = 0;
|
||||||
|
const search = async () => {
|
||||||
|
const mine = ++asked;
|
||||||
|
const result = await api(`giver?q=${encodeURIComponent($("query").value.trim())}&kind=${encodeURIComponent($("kind").value)}`);
|
||||||
|
if (mine !== asked) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (result.status === 401) {
|
||||||
|
showGate("Sign in first", "The item giver uses your account page's sign-in.");
|
||||||
|
}
|
||||||
|
else if (result.status === 403) {
|
||||||
|
showGate("Not now", "The item giver is not open to this account at the moment. Your account page says why.");
|
||||||
|
}
|
||||||
|
else if (!result.ok) {
|
||||||
|
setStatus("search-status", result.data.error || "That did not work.", true);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
$("gate").hidden = true;
|
||||||
|
$("finder").hidden = false;
|
||||||
|
showResults(result.data);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let typing = null;
|
||||||
|
$("query").addEventListener("input", () => {
|
||||||
|
clearTimeout(typing);
|
||||||
|
typing = setTimeout(search, 250);
|
||||||
|
});
|
||||||
|
$("kind").addEventListener("change", search);
|
||||||
|
|
||||||
|
$("give").addEventListener("click", async () => {
|
||||||
|
if (!chosen) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const body = {kind: chosen.kind, id: chosen.id};
|
||||||
|
if (chosen.kind === "clothing") {
|
||||||
|
const value = wholeValue();
|
||||||
|
if (preset !== null) {
|
||||||
|
body.colorIndex = preset;
|
||||||
|
}
|
||||||
|
else if (value !== null) {
|
||||||
|
body.color = String(value);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
body.color = slots.map(slot => slot.picker.value).join(" ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
body.version = variant;
|
||||||
|
if (chosen.tintable && $("tint").checked) {
|
||||||
|
body.tint = $("tint-picker").value;
|
||||||
|
body.tintStrength = Number($("tint-strength").value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$("give").disabled = true;
|
||||||
|
const result = await api("give", body);
|
||||||
|
$("give").disabled = false;
|
||||||
|
if (result.status === 401) {
|
||||||
|
showGate("Sign in again", "Your account page's sign-in ended.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!result.ok) {
|
||||||
|
setStatus("give-status", result.data.error || "That did not work.", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const as = result.data.color !== undefined ? ` Its colour in the game: ${result.data.color}.` : result.data.version ? ` Its version in the game: ${result.data.version}.` : "";
|
||||||
|
setStatus("give-status", `${chosen.name}: given. ${result.data.online ? "It is in your inventory in the game now." : "It is in your inventory next time you play."}${as}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
api("colour").then(result => {
|
||||||
|
if (result.ok && result.data.palette) {
|
||||||
|
palette = result.data.palette.map(colour => `#${colour}`);
|
||||||
|
for (const slot of slots) {
|
||||||
|
const place = palette.indexOf(slot.picker.value);
|
||||||
|
setSlot(slot, slot.picker.value, slot.index !== null ? slot.index : place < 0 ? null : place);
|
||||||
|
}
|
||||||
|
showChoice();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
for (const slot of slots) {
|
||||||
|
slot.aj.disabled = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
api("me").then(result => {
|
||||||
|
if (result.ok) {
|
||||||
|
$("who").textContent = `Items go to ${result.data.username}.`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
search();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+2496
-254
File diff suppressed because it is too large.
Load diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 316 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user