Compare commits

...
17 Commits
Author SHA1 Message Date
Snipzil b11ae1dfa8 feat: add unified Discord bot and dashboard 2026-10-20 22:13:50 -04:00
Snipzil 113bf9342e fix: show developer badge to all players 2026-10-20 22:13:50 -04:00
Snipzil 131fb8b025 docs(contributing): add security guidelines for GitHub webhooks
Include instructions on verifying route signatures for signed push
webhooks and precautions against exposing webhook secrets in logs,
commits, or pull requests.
2026-10-20 21:42:02 -04:00
Snipzil 8afc66de21 docs: add CONTRIBUTING.md
Add a contribution guide outlining local setup instructions,
testing requirements, security protocols, and development standards
for the project.
2026-10-20 20:35:20 -04:00
Snipzil 059f059a9e Merge branch 'main' of https://github.com/burrow-dev/burrow-server 2026-10-20 19:16:08 -04:00
Snipzil d20920dc3c chore(deploy): add OpenRC support and deployment helpers
Add OpenRC service and configuration files to support automated server
updates on systems without systemd timers.

- Add `deploy/update-loop.sh` to handle periodic updates for OpenRC.
- Add `deploy/burrow-update.openrc` and `deploy/burrow-update.conf`.
- Update `deploy/update.sh` to support both systemd and OpenRC service
  restarts.
- Add `deploy/README.md` with installation instructions.
- Update `.gitignore` to allow the deployment documentation.
2026-10-20 19:16:04 -04:00
BurrowdevandClaude Opus 5.5 8fb5cfe6d8 feat(theatre): a video of your own on the theatre screen, fitted to it
In a theatre, "Your Video" opens a box for a YouTube, Vimeo or .mp4 /
.webm / .mp3 link that plays for that player alone; nothing of it goes to
the server. A staff video for the room comes first and the player's own
waits for it.

The game now tells the page where the theatre's screen is
(AJClient.reportTheatreScreen: the original player's 512 by 288, in stage
coordinates), so both videos sit exactly on it at any window size. It
also tells which parts of it the game's windows, buttons and chat
balloons are drawn over, and the page cuts those out of the videos and
hides its controls under them: a web page is otherwise always drawn over
the game.

The box is in the game's own look. Desktop players need client 1.3.2,
which lets the game page load the video players and the one file link the
player chose. buildVersion 78.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 02:13:42 +03:00
BurrowdevandClaude Opus 5.5 8368692b99 feat(modpanel): the mod log as its own page
The admin panel's "What they did" table, in the moderator panel too: the
latest 300 entries. A new permission, staff.log, which moderators and
admins have by default, guards the page and its route.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 23:44:16 +03:00
BurrowdevandClaude Opus 5.5 0f367c55b8 feat(admin): a temporary password for a player who lost access
The account view's Lost access box gives the account a new random password
(12 characters, none that look alike), shown once with a Copy button. It
signs them out everywhere and forgets trusted devices; "Turn off their 2FA
too" is for a lost authenticator. Written to the mod log, without the
password.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 23:44:16 +03:00
BurrowdevandClaude Opus 5.5 a860a67626 feat(guide): guides only by the admin, and seen by everyone
The login's Guide option made a player a guide on their own screen only:
the room's avatar packet never said so, so everyone else drew a plain
player. "ac" now sends the guide field (bit 4, after a blend colour of 0),
which gives the guide's name tag and chat bubble on every client.

Guide is now given in the admin panel (Make guide / Remove guide, logged).
Asked for at login by anyone else, it is refused, with a plain message on
arrival. A guide's custom client can still leave it off; the official
launcher asks nothing, and a guide shows as one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 23:44:11 +03:00
BurrowdevandClaude Opus 5.5 da9f2fd5a6 feat(rules): the game's rules window shows data/rules.txt
The rules were written into the client, so changing them meant a new
build. GET /rules.txt reads data/rules.txt on every ask (no restart
needed; data/ is what prod keeps between deploys and lets the server
write), making it with "Example" when there is none. The rules window
fetches it each time it opens: a line starting "# " is a heading in the
old rules' heading style, the rest is shown as it is written (escaped,
never HTML). 64 KB at most. buildVersion 75.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 16:26:12 +03:00
BurrowdevandClaude Opus 5.5 0c3bfd97b3 feat(masterpieces): daily limit, a day's wait, the same picture approved again
- accounts under a day old cannot paint for a frame: the easel's token is
  refused and a message box says how long is left
  (AJ_MASTERPIECE_MIN_AGE, 86400; the tests use 0).
- 10 new pictures an account in any 24 hours (config.masterpiecesPerDay),
  counted in the database (masterpiece_uploads) so a restart does not
  forget them; past it HQ says when the next one may go. a picture
  approved before is not a new one.
- a picture a moderator or the admin approved is approved again as it is
  framed, and the same picture waiting is approved with it, its makers
  told: the same file (SHA-256), or the same painting saved and painted
  again, which comes back as other bytes. lib/jpegprint.js reads every
  8x8 block's average from a baseline JPEG's DC coefficients (~2.6 ms for
  the Art Studio's 711x434); the same size with no block more than 2 of
  255 apart is the same picture (a saved .ajart painted again: 1).
- staff taking a painting back forgets its picture.
- paintings from before get their hash and fingerprint a few at a time
  after start; those a person approved make their pictures approved ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 16:21:20 +03:00
BurrowdevandClaude Opus 5.5 096ceafea7 feat(pets): play as your pet in any room, from the pet chooser
A switch in the pet chooser (the settings menu's own On/Off switch, at
the top left of the pet's picture) puts the pet that is out in the
avatar's place, for everyone, as at a Play-As-Your-Pet party: the pet
at the party's size where the avatar stands, turning as it walks, its
name on the name bar, chat balloons and emotes over it, the pet in the
HUD. Hidden at the party itself.

- kept as user var 9008 (9007 is the performance profile), so it holds
  through rooms and logins and is kept for the next pet when the pet is
  put away. the server tells the room by user communication type 13,
  also to players coming in later.
- WorldPet and AvatarWorldView ask the avatar's own form instead of the
  room-wide party test; a pet that cannot come into the room leaves the
  avatar shown.
- the type-13 handler read a variable it never set, so every client took
  every message for "off" and nobody else saw the form.
- the action menu's pet button does the pet's trick again (5c9b2e0 had
  made it the switch, which only hid the avatar).

Flying pets keep to the ground's walls (the party lets them over).
buildVersion 74.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 15:25:35 +03:00
BurrowdevandClaude Opus 5.5 2344270291 feat(music): staff upload MP3s as den music tracks
A "Music" page in both panels: an MP3 (MPEG layer III frames, 4 KB to
15 MB) becomes a den music track at once, with no restart.

- lib/custommusic.js: a custom den item made from "Jam On" (614) with a
  new `audio` column, the file's version. Its abbrName is
  CustomMusic<id>_<version>, which the content handler answers from
  data/custom-music/<id>-<version>.mp3, so a new upload is a new name and
  no game plays an old copy from its cache.
- games get it by "xdi" with no client change; players from the item
  finder, or the shop when staff tick "on sale".
- deleting it takes it from every inventory and removes the file.
- /mod/api/music and /admin/api/music: list, play, upload (name, cost,
  inShop in the query), delete; 30 uploads an hour per staff member;
  "music uploaded"/"music deleted" in the mod log.
- new permission music.upload, on the Admin role by default; a role list
  the admin has changed needs it ticked. The panels' CSP allows
  media-src 'self' for the preview players.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 15:25:27 +03:00
BurrowdevandClaude Opus 5.5 a77a1bcfb4 fix(pets): name a hatched egg without throwing
"pn" (EggPetHatchedPopup) saved `account`, which that handler never
defined since aa455f5: a ReferenceError after the name was set in
memory, so no reply went out and the game's loading spiral never ended,
and the name was not saved, so the popup came back at every login.
"account is not defined" at lib/pets.js in prod's log several times an
hour since 10-17.

qol.js names the egg it buys and waits for the answer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 15:25:12 +03:00
BurrowdevandClaude Opus 5.5 04b8d325ea perf(defpacks): make the item packs again without holding the game up
A custom item change made the item and name packs again on the next
fetch, on the one thread every game shares: ~360 ms at 5000 items,
~1.6 s at 50000, after every change, players making them many times a
minute. Nearly all of it was the AMF3 writer.

- the writer fills one growing buffer instead of a Buffer per value
  (byte-identical output, checked against the old one on every cached
  pack): the item pack 230 -> 52 ms at 5000 items, 1524 -> 231 ms at 50000.
- a changed pack is made again at most every AJ_PACK_REMAKE_MS (15 s);
  until then the one made before goes out with the custom item version
  it has, and customItems.sendAll sends a game logging in what its packs
  lack by that version. one remake at a time; deflated on libuv's threads.
- tests make the packs again at once (AJ_PACK_REMAKE_MS=0), and a run of
  the items test checks the throttled case.

Busy evening simulated in-process (a change every 3 s, packs fetched
6 a second, 30 s): longest hold-up 329 -> 61 ms at 5000 items, 1648 ->
359 ms at 50000 (p99 240 -> 6 ms).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 14:44:07 +03:00
BurrowdevandClaude Opus 5.5 c5b1bc37d9 fix: send a game at login only the custom items its packs lack
Every custom item's full def row went to every game at login, though the
item and name packs it fetched minutes before already have them all: with
5000 clothing and 452 den items that was 3.3 MB, 4.2 MB with the colours,
over the send backlog limit (94b8de8 raised it).

- a fetch of the item, den item or name pack notes, per address, how far
  the custom items had changed; at login a game is sent the items changed
  since, and those with a picture (the packs have no pictures). an address
  that fetched nothing lately is sent all, as before.
- "xdi" rows carry the fields the client reads (addItemDef,
  addDenItemDef), not the whole base row, and clothing is for any animal
  as in the pack.
- accounts keep a digest of the state last written, not a copy of it
  (~13 KB an account, ~185 MB on prod).

Measured locally with prod-sized data (20000 colours, 5452 items, 14k
accounts): the login burst 4.2 MB -> 1.5 MB (the colours are most of what
is left), live heap after start 419 -> 297 MB.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 14:44:07 +03:00
46 changed files with 4681 additions and 215 deletions

No files matched your search

+27 -8
View File
@@ -4,7 +4,8 @@
// 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):
//
// - 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 names no web address outside .github/allowed-hosts.json
// - 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 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 ALLOWED_DEPENDENCIES = {dependencies: {"discord.js": "14.26.4"}};
for (const field of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies", "bundledDependencies"]) {
if (pkg[field] && Object.keys(pkg[field]).length) {
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 actual = pkg[field] || {};
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"]) {
if (tracked.includes(lock)) {
fail(lock, "a lockfile means npm packages; see package.json above.");
for (const lock of ["yarn.lock", "pnpm-lock.yaml"]) {
if (tracked.includes(lock)) fail(lock, "use the reviewed package-lock.json; alternate package-manager lockfiles are not allowed.");
}
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
@@ -88,4 +107,4 @@ if (problems.length) {
}
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`);
+2
View File
@@ -20,6 +20,8 @@ __pycache__/
# internal markdown files
*.md
!deploy/README.md
!/CONTRIBUTING.md
/HANDOFF.md
/DISCOVERIES.md
/GOING-PUBLIC.md
+77
View File
@@ -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.
+10
View File
@@ -5,6 +5,16 @@ Burrow is a private server for AJ Classic.
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
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.
+23 -2
View File
@@ -134,6 +134,19 @@ module.exports = {
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",
// older builds the CDN still serves, asked in turn for a room file the
@@ -153,9 +166,9 @@ module.exports = {
// 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;
// 49 and 50: its link to a colour picker.
// 61: the Owner, Moderator and Verified name tag badges seen by everyone.
// 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.
buildVersion: env.AJ_BUILD_VERSION || "71",
buildVersion: env.AJ_BUILD_VERSION || "78",
// what the official CDN is asked for; not ours to change.
upstreamBuildVersion: "3",
@@ -327,6 +340,14 @@ module.exports = {
cacheMissesPerTenMinutes: 1500, // a first visit with an empty cache fetches several hundred files
upstreamTimeoutMs: 20000,
maxCacheBytes: Number(env.AJ_MAX_CACHE_MB || 8192) * 1024 * 1024,
// 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,
maxHttpConnections: 2000, // open at once, in all
maxHttpConnectionsPerAddress: 40, // the game opens a good many at once while it loads
+31
View File
@@ -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.
+9
View File
@@ -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
+17
View File
@@ -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
}
+24
View File
@@ -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
+23 -3
View File
@@ -1,15 +1,35 @@
#!/usr/bin/env bash
# brings the server to origin's main and restarts it when the change needs it.
# run as root by burrow-update.timer; git itself runs as the server's user.
# Brings the server to origin's main and restarts it when the change needs it.
# Run as root by either burrow-update.timer or the OpenRC updater service; git
# itself runs as the server's user.
set -euo pipefail
dir=${BURROW_DIR:-/home/aj/ajc-private-server}
user=${BURROW_USER:-aj}
service=${BURROW_SERVICE:-burrow}
branch=${BURROW_BRANCH:-main}
init=${BURROW_INIT:-}
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"
old=$(git rev-parse HEAD)
new=$(git rev-parse "origin/$branch")
@@ -33,7 +53,7 @@ done
# 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
systemctl restart "$service"
restart_service
echo "updated $old -> $new, restarted $service"
else
echo "updated $old -> $new, no restart needed"
+17 -10
View File
@@ -46,7 +46,7 @@ const SCHEMA = `
// fields stored in their own columns rather than in `state`.
const COLUMN_FIELDS = ["id", "username", "salt", "hash", "createdAt"];
// how the game treats the account this session; set again at every login.
const SESSION_FIELDS = ["accountType", "isGuide", "isModerator", "membershipDays", "startInDen", "startRoom"];
const SESSION_FIELDS = ["accountType", "isGuide", "guideRefused", "isModerator", "membershipDays", "startInDen", "startRoom"];
const DEFAULT_MEMBERSHIP_DAYS = 9999;
const MAX_ACCOUNT_TYPE = 5;
const MEMBERSHIP_TYPES = [0, 2]; // non-member, member
@@ -78,7 +78,10 @@ const LOGIN_DAYS_KEPT = 90; // and none older than this: they hold addresses
let db = null;
const byKey = new Map(); // lowercased username -> account
const byId = new Map();
const savedState = new Map(); // account id -> state JSON as last written
// 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
// for a while: whoever had it is still known by it to the players they met.
const NAME_HELD_DAYS = 30;
@@ -299,13 +302,17 @@ const MAX_START_ROOM = 80;
function setLoginChoices(account, choices) {
const asked = config.loginChoices && choices && typeof choices === "object" ? choices : {};
const whole = (value, max) => Number.isInteger(value) && value >= 0 && value <= max;
// member or not, and guide or not, are the player's own choice on any
// server; the rest only with config.loginChoices: another account type
// shows to everyone.
// member or not is the player's own choice on any server; the rest only
// with config.loginChoices: another account type shows to everyone.
const own = choices && typeof choices === "object" ? choices : {};
const type = MEMBERSHIP_TYPES.includes(own.accountType) ? own.accountType : asked.accountType;
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.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
@@ -331,7 +338,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 (?, ?, ?, ?, ?, ?)")
.run(username, username.toLowerCase(), salt, hash, createdAt, json);
account.id = Number(result.lastInsertRowid);
savedState.set(account.id, json);
savedState.set(account.id, stateDigest(json));
remember(account);
touch(account);
return account;
@@ -381,7 +388,7 @@ const load = () => {
createdAt: row.created_at,
...JSON.parse(row.state),
});
savedState.set(account.id, row.state);
savedState.set(account.id, stateDigest(row.state));
remember(account);
}
importLegacyFile();
@@ -475,7 +482,7 @@ const release = account => {
const changedState = (account, changed) => {
const json = stateJson(account);
if (savedState.get(account.id) !== json) {
if (savedState.get(account.id) !== stateDigest(json)) {
changed.push([account.id, json]);
return true;
}
@@ -583,7 +590,7 @@ const flush = ({some = false} = {}) => {
throw err;
}
for (const [id, json] of changed) {
savedState.set(id, json);
savedState.set(id, stateDigest(json));
}
};
+90 -31
View File
@@ -177,40 +177,89 @@ class Amf3Reader {
// writer for what the reader above produces from a defPack: plain objects,
// arrays (with or without string keys), strings, numbers, booleans and null.
// nothing is written as a reference except repeated strings.
// 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 {
constructor() {
this.parts = [];
this.buf = Buffer.allocUnsafe(1 << 16);
this.pos = 0;
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) {
this.room(4);
const {buf} = this;
if (value < 0x80) {
this.parts.push(Buffer.from([value]));
buf[this.pos++] = value;
}
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) {
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 {
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) {
if (text === "") {
this.u29(1);
return;
}
else if (this.strings.has(text)) {
this.u29(this.strings.get(text) << 1);
const known = this.strings.get(text);
if (known !== undefined) {
this.u29(known << 1);
return;
}
else {
this.strings.set(text, this.strings.size);
const bytes = Buffer.from(text, "utf8");
this.u29((bytes.length << 1) | 1);
this.parts.push(bytes);
this.strings.set(text, this.strings.size);
// nearly every string of a pack is short and ASCII: its bytes are its
// characters, copied here rather than through Buffer's utf8 writer.
if (text.length < 64) {
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) {
@@ -222,45 +271,55 @@ class Amf3Writer {
}
value(value) {
if (value === undefined) {
this.parts.push(Buffer.from([0x00]));
// most values of a pack are strings: asked first
if (typeof value === "string") {
this.byte(0x06);
this.string(value);
}
else if (value === undefined) {
this.byte(0x00);
}
else if (value === null) {
this.parts.push(Buffer.from([0x01]));
this.byte(0x01);
}
else if (typeof value === "boolean") {
this.parts.push(Buffer.from([value ? 0x03 : 0x02]));
this.byte(value ? 0x03 : 0x02);
}
else if (typeof value === "number") {
if (Number.isInteger(value) && value >= -0x10000000 && value < 0x10000000) {
this.parts.push(Buffer.from([0x04]));
this.byte(0x04);
this.u29(value & 0x1fffffff);
}
else {
const bytes = Buffer.alloc(9);
bytes[0] = 0x05;
bytes.writeDoubleBE(value, 1);
this.parts.push(bytes);
this.byte(0x05);
this.room(8);
this.pos = this.buf.writeDoubleBE(value, this.pos);
}
}
else if (typeof value === "string") {
this.parts.push(Buffer.from([0x06]));
this.string(value);
}
else if (Array.isArray(value)) {
this.parts.push(Buffer.from([0x09]));
this.byte(0x09);
this.u29((value.length << 1) | 1);
// string keys set on the array beside its numbered elements.
this.pairs(Object.entries(value).filter(([key]) => !/^\d+$/.test(key)));
// string keys set on the array beside its numbered elements (an array
// 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) {
this.value(element);
}
}
else if (typeof value === "object" && !Buffer.isBuffer(value)) {
// A dynamic object of no class, with its traits written in place.
this.parts.push(Buffer.from([0x0a, 0x0b]));
this.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.pairs(Object.entries(value));
}
else {
throw new Error("Cannot write this value as AMF3");
@@ -273,6 +332,6 @@ module.exports = {
encode: value => {
const writer = new Amf3Writer();
writer.value(value);
return Buffer.concat(writer.parts);
return writer.buf.subarray(0, writer.pos);
},
};
+3 -3
View File
@@ -33,9 +33,9 @@ const cdn = require("./cdn.js");
// there are no more than a hundred (lib/accounts.js); the admin may give
// it and take it away like any other.
// in the order they are listed and drawn. the Verified, Owner and Moderator
// name tags show their badge to everyone, not only to buddies: their def ids
// are in PUBLIC_BADGE_IDS of swf-src/AvatarWorldView.as.
// 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 = [
// first, so its tick comes straight after the name, as on other sites.
{id: "verified", label: "Verified", tag: {def: 76, media: 20014, bit: 21}},
+100 -11
View File
@@ -3,14 +3,15 @@
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 every game
// at login, in case it was started before the item was made.
// ("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).
@@ -29,6 +30,21 @@ 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,
@@ -38,12 +54,22 @@ const SCHEMA = `CREATE TABLE IF NOT EXISTS custom_items (
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 => {
@@ -59,12 +85,34 @@ const rowOf = entry => {
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);
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
@@ -75,9 +123,7 @@ const messages = entries => {
const out = [];
for (const kind of KINDS) {
// a picture waiting for a moderator is not shown yet
const rows = entries.filter(entry => entry.kind === kind && !entry.pending)
.map(entry => ({...(kind === "clothing" ? defpacks.clientItemRow(rowOf(entry)) : rowOf(entry)), name: entry.name,
art: entry.artPending ? "" : entry.art || "", artMode: entry.artMode || "sticker"}));
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))]);
}
@@ -119,6 +165,7 @@ const fromRow = row => ({
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;
@@ -143,6 +190,10 @@ const addOwnerColumn = () => {
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 = () => {
@@ -233,10 +284,12 @@ const create = (kind, fields, by, ownerId = null, pending = false) => {
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,
seq: made++};
db().prepare("INSERT INTO custom_items (kind, id, base, name, cost, members, colors, in_shop, created_by, created_at, owner_id, pending) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
.run(kind, id, baseId, entry.name, entry.cost, entry.members ? 1 : 0, entry.colors.join(","), entry.inShop ? 1 : 0, entry.createdBy, entry.createdAt, ownerId, pending ? 1 : 0);
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);
@@ -281,6 +334,7 @@ const setArtMode = (kind, id, mode) => {
}
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};
};
@@ -295,6 +349,7 @@ const setArt = (kind, id, art, pending = false) => {
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);
};
@@ -324,6 +379,9 @@ const remove = (kind, id) => {
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};
};
@@ -333,6 +391,10 @@ const list = () => KINDS.flatMap(kind => [...items.get(kind).values()])
module.exports = {
KINDS,
FIRST_ID,
audioName,
onAudioGone: callback => {
audioGone = callback;
},
load,
create,
update,
@@ -362,9 +424,36 @@ module.exports = {
const def = baseDef(entry.kind, entry.base);
return def ? defpacks.string(entry.kind === "den" ? def.nameStrId : def.titleStrId) || String(def.abbrName || entry.base) : String(entry.base);
},
// every custom item, for a game logging in.
// 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) {
for (const params of messages(list().reverse().filter(entry => !entry.pending))) {
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);
}
},
+174
View File
@@ -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};
+47 -13
View File
@@ -370,24 +370,51 @@ const CLIENT_PACKS = new Map([
[DEF_NAMEBAR_BADGE, () => {}],
]);
const clientPackPaths = new Map([...CLIENT_PACKS.keys()].map(id => [cdn.hashedPath(`defPacks/${id}`), id]));
const clientPackBodies = new Map(); // id -> {day, allOnSale, body}
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
// one of the above (and comes straight from the CDN).
const makeClientPack = async id => {
// 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 id = clientPackPaths.get(relPath);
if (id === undefined) {
return null;
}
const made = clientPackBodies.get(id);
if (made && made.day === sales.today() && made.allOnSale === sales.everythingOnSale()) {
return made.body;
if (made && made.day === sales.today() && made.allOnSale === sales.everythingOnSale()
&& (!clientPacksChanged.has(id) || Date.now() - made.madeAt < config.packRemakeMs)) {
return made;
}
const pack = await loadChanged(id);
CLIENT_PACKS.get(id)(pack);
const body = zlib.deflateRawSync(amf3.encode(pack));
clientPackBodies.set(id, {day: sales.today(), allOnSale: sales.everythingOnSale(), body});
return body;
if (!clientPacksMaking.has(id)) {
clientPacksMaking.set(id, makeClientPack(id).finally(() => clientPacksMaking.delete(id)));
}
return clientPacksMaking.get(id);
};
// most packs are tables: an object of rows keyed by row index.
@@ -535,8 +562,8 @@ const setCustomItem = (kind, row, name, inShop = true) => {
clothingIds = clothingIds.includes(id) ? clothingIds : [...clothingIds, id];
}
customInShop[kind][inShop ? "add" : "delete"](id);
clientPackBodies.delete(pack);
clientPackBodies.delete(DEF_LOCALIZATION_EN);
clientPacksChanged.add(pack);
clientPacksChanged.add(DEF_LOCALIZATION_EN);
customVersion++;
};
@@ -558,7 +585,7 @@ const unsetCustomItem = (kind, id) => {
clothingIds = clothingIds.filter(one => one !== number);
}
customInShop[kind].delete(number);
clientPackBodies.delete(pack);
clientPacksChanged.add(pack);
customVersion++;
};
@@ -569,6 +596,13 @@ module.exports = {
// 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,
itemDef: id => itemDefs.get(Number(id)),
clothingIds: () => clothingIds,
+865
View File
@@ -0,0 +1,865 @@
"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.
const {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
ChannelType,
Client,
GatewayIntentBits,
MessageFlags,
PermissionFlagsBits,
SlashCommandBuilder,
} = require("discord.js");
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");
const COMPONENTS_V2 = MessageFlags.IsComponentsV2;
const EPHEMERAL = MessageFlags.Ephemeral;
const STATUS_MESSAGE_SETTING = "discordBotStatusMessage";
const STATUS_TITLE_SETTING = "discordBotStatusTitle";
const STATUS_NOTE_SETTING = "discordBotStatusNote";
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);
const statusSettings = () => ({
title: safe(accounts.setting(STATUS_TITLE_SETTING) || "Burrow status", 80) || "Burrow status",
note: safe(accounts.setting(STATUS_NOTE_SETTING) || "", 500),
});
const setStatusSettings = ({title, note}) => {
const next = {
title: safe(title || "Burrow status", 80) || "Burrow status",
note: safe(note || "", 500),
};
accounts.setSetting(STATUS_TITLE_SETTING, next.title);
accounts.setSetting(STATUS_NOTE_SETTING, next.note);
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});
const commands = [
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());
const actorFor = interaction => modpanel.discordBot.actor(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();
return card({title: settings.title, tone: 0x5865f2, sections: [
settings.note ? `**Status message**\n${settings.note}` : "",
`**Online**\n${status.players} players in ${status.rooms} room${status.rooms === 1 ? "" : "s"}`,
`**Moderation queue**\n${status.reports} open report${status.reports === 1 ? "" : "s"}`,
`**Server**\nUptime: <t:${Math.floor(Date.now() / 1000 - status.uptimeSeconds)}:R>\nMemory: ${status.memoryMb} MB`,
]});
};
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 = actorFor(interaction);
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 payload = statusCard({players: 0, rooms: 0, 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 played = entry.type === "logout" ? `\nSession: ${minutes} minute${minutes === 1 ? "" : "s"}` : "";
await postCard(config.discord.gameLogsChannelId, card({
title: "In-game player activity",
tone: entry.type === "login" ? 0x57f287 : 0x5865f2,
sections: [`**${safe(entry.username, 40)}** ${entry.type === "login" ? "signed in" : "signed out"}.${played}`],
}), "game activity log");
};
const notifyModeration = async entry => {
await postCard(config.discord.moderationLogsChannelId, card({
title: "Moderation audit",
tone: 0xfee75c,
sections: [
`**${safe(entry.by, 50)}** — ${safe(entry.action, 120)}`,
entry.target ? `Player: **${safe(entry.target, 50)}**` : "",
entry.detail ? `Details: ${safe(entry.detail, 500)}` : "",
],
}), "moderation log");
};
const notifyBot = async (interaction, action) => {
const actor = modpanel.discordBot.actor(interaction.user.id);
await postCard(config.discord.botLogsChannelId, card({
title: "Discord bot audit",
tone: actor ? 0x5865f2 : 0xed4245,
sections: [
`Discord user: **${safe(interaction.user.username, 80)}** (\`${safe(interaction.user.id, 30)}\`)`,
`Action: ${safe(action, 160)}`,
actor ? `Linked staff account: **${safe(actor.username, 40)}**` : "No active linked Burrow staff account.",
],
}), "Discord bot audit log");
};
const securityIncident = async (title, sections, detail = "") => {
await postCard(config.discord.moderationLogsChannelId, card({title, tone: 0xed4245, sections}), "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(commands).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;
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 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 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};
+122 -4
View File
@@ -22,8 +22,11 @@ const defpacks = require("./defpacks.js");
const limits = require("./limits.js");
const manage = require("./manage.js");
const modpanel = require("./modpanel.js");
const discordBot = require("./discordbot.js");
const badges = require("./badges.js");
const extraMusic = require("./extramusic.js");
const customMusic = require("./custommusic.js");
const itemControl = require("./itemcontrol.js");
const masterpieces = require("./masterpieces.js");
const panel = require("./panel.js");
const totp = require("./totp.js");
@@ -230,6 +233,75 @@ const itemArtUpload = async (req, res, url, from, signedIn = null, adminSignedIn
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) => {
@@ -361,6 +433,7 @@ const CAPTCHA_PAGE_HEADERS = {...PAGE_HEADERS, "Content-Security-Policy": captch
// write, from config.js.
const LEGAL_VALUES = {legalEmail: config.legalEmail, adminEmail: config.adminEmail, operator: config.operator, hostedIn: config.hostedIn,
version: config.termsVersion, site: new URL(config.siteUrl).host};
const MAX_RULES_LENGTH = 65536; // characters of data/rules.txt the game is sent
const escapeHtml = text => String(text).replace(/[&<>"]/g, sign => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;"})[sign]);
const sendLegalPage = async (res, file) => {
for (const [name, value] of Object.entries(PAGE_HEADERS)) {
@@ -686,6 +759,12 @@ const handle = async (req, res) => {
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.
@@ -731,6 +810,10 @@ const handle = async (req, res) => {
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});
return;
}
@@ -757,6 +840,10 @@ const handle = async (req, res) => {
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) {
await modpanel.handle(req, res, url, from, {send, readJson});
return;
@@ -981,13 +1068,38 @@ const handle = async (req, res) => {
return;
}
const parts = formParts(req.headers["content-type"], await readBody(req, masterpieces.MAX_IMAGE_BYTES + 16 * 1024));
const uuid = await 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});
return;
}
case "GET /crossdomain.xml":
send(res, 200, CROSS_DOMAIN, "text/xml");
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":
// 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");
@@ -1043,15 +1155,21 @@ const handle = async (req, res) => {
send(res, body ? 200 : 404, body || "Not found", body ? MIME[".swf"] : "text/plain");
return;
}
// the extra den music tracks, which the CDN does not have as files.
const extra = await extraMusic.asset(relPath);
// the extra den music tracks, which the CDN does not have as files, and
// those uploaded by staff.
const extra = await extraMusic.asset(relPath) || await customMusic.asset(relPath);
if (extra) {
send(res, extra.body ? 200 : 404, extra.body || "Not found", extra.body ? extra.type : "text/plain");
return;
}
const clientPack = await defpacks.clientPack(relPath);
if (clientPack) {
send(res, 200, clientPack, "application/octet-stream");
// 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;
}
// A room file in a seasonal theme ("<build>/roomDefs/theme_<other
+212
View File
@@ -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};
+215 -21
View File
@@ -7,6 +7,7 @@ const config = require("../config.js");
const accounts = require("./accounts.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
// (client side: game.artStudioPainting.ArtStudioPainting, the same in
@@ -45,6 +46,23 @@ const SCHEMA = `
likes TEXT 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
@@ -79,19 +97,35 @@ const fileOf = id => path.join(folder(), `${id}.jpg`);
const GALLERY_SPOTS = 12; // PartyManager.setupMasterpiecesInRoom
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 db = () => accounts.database();
const known = new Map(); // id -> {id, creator, createdAt, status, frame, reviewedAt, reviewedBy, 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 load = () => {
db().exec(SCHEMA);
// who approved it: a moderator's username, "admin", or null when nobody
// looked (review was off, or it was approved before this was kept).
if (!db().prepare("PRAGMA table_info(masterpieces)").all().some(column => column.name === "reviewed_by")) {
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});
// 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()) {
@@ -99,16 +133,138 @@ const load = () => {
fs.writeFileSync(fileOf(row.id), Buffer.from(picture));
db().prepare("UPDATE masterpieces SET image = ? WHERE id = ?").run(NO_IMAGE, row.id);
}
for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, reviewed_at, reviewed_by, 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,
reviewedAt: row.reviewed_at, reviewedBy: row.reviewed_by, likes: JSON.parse(row.likes)});
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 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);
db().prepare("DELETE FROM masterpieces WHERE id = ?").run(id);
fs.rmSync(fileOf(id), {force: true});
@@ -126,6 +282,7 @@ const sweep = () => {
forget(painting.id);
}
}
db().prepare("DELETE FROM masterpiece_uploads WHERE created_at <= ?").run(now() - DAY);
};
setInterval(() => {
try {
@@ -136,8 +293,12 @@ setInterval(() => {
}
}, 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 => {
if (tooNew(account)) {
return null;
}
for (const [token, entry] of tokens) {
if (entry.account === account.id) {
tokens.delete(token);
@@ -189,20 +350,33 @@ const looksLikeJpeg = image => {
return false;
};
// step 2. resolves to the new painting's id, or null when the token is not
// good, the picture is not a JPEG of a sane size, or the account has posted
// too many.
// step 2. resolves to {uuid}, the new painting's id, or {uuid: null} when
// the token is not good, the picture is not a JPEG of a sane size, or the
// account has posted too many; with `refusal` and `maker` when the player
// should be told why.
const upload = async (token, image) => {
const entry = typeof token === "string" ? tokens.get(token) : null;
tokens.delete(token);
if (!entry || entry.expires < Date.now() || !Buffer.isBuffer(image) || image.length > MAX_IMAGE_BYTES || !looksLikeJpeg(image)
|| !uploadsPerHour.allow(entry.account)) {
return null;
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 null;
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.
for (const painting of [...known.values()]) {
@@ -210,12 +384,12 @@ const upload = async (token, image) => {
forget(painting.id);
}
}
const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, reviewedAt: null, reviewedBy: null, 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);
db().prepare("INSERT INTO masterpieces (id, creator_id, created_at, status, frame, likes, image) VALUES (?, ?, ?, ?, ?, '[]', ?)")
.run(painting.id, painting.creator, painting.createdAt, painting.status, painting.frame, NO_IMAGE);
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, hash, print);
known.set(painting.id, painting);
return painting.id;
return {uuid: painting.id};
};
// `by`: who approved it, when someone did.
@@ -239,11 +413,19 @@ const claimable = (account, id, frame) => {
};
// 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 painting = known.get(String(id));
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;
};
@@ -278,14 +460,26 @@ const mayView = (id, address, addressOf) => {
return painting.status === APPROVED || Boolean(maker && addressOf(maker) && addressOf(maker) === address);
};
// `by`: the moderator's username, or "admin".
// `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);
if (!painting || painting.status !== PENDING) {
return false;
return [];
}
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
@@ -362,7 +556,7 @@ const frameList = listId =>
([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null);
module.exports = {
load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, recentlyApproved, frameList,
load, issueToken, tooNew, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, recentlyApproved, frameList,
needsReview, setNeedsReview, madeBy,
PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES,
};
+8 -1
View File
@@ -464,8 +464,15 @@ module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => {
},
};
// 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) => {
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
+20 -2
View File
@@ -18,13 +18,23 @@ const SCHEMA = `
`;
const MAX_DETAIL = 400;
const SHOWN = 300;
const listeners = new Set();
const load = () => accounts.database().exec(SCHEMA);
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 (?, ?, ?, ?, ?)")
.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] ${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);
@@ -33,4 +43,12 @@ const recent = () => accounts.database().prepare("SELECT at, by, action, target,
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));
module.exports = {load, record, recent, about};
// 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};
+98 -2
View File
@@ -395,7 +395,7 @@ const PAGE_HEADERS = {
"X-Frame-Options": "DENY",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
"Content-Security-Policy": captcha.policy("default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; "
"Content-Security-Policy": captcha.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'"),
};
@@ -670,6 +670,17 @@ const handle = async (req, res, url, from, web) => {
return;
}
// the mod log (lib/modlog.js): what staff did, as the admin panel's
// Moderators page shows it.
if (route === "GET /mod/api/modlog") {
if (!roles.can(mod, "staff.log")) {
reply(403, {error: "Your role does not allow that."});
return;
}
reply(200, {log: modlog.recent()});
return;
}
// everything else shows players and what they did: not for a role that
// only makes things.
if (!roles.can(mod, "player.view")) {
@@ -1073,4 +1084,89 @@ const moderators = () => accounts.all().filter(account => roles.roleOf(account))
.map(account => ({username: account.username, role: roles.roleOf(account), twoStep: totp.isOn(account), lastSeen: account.lastSeen || null}))
.sort((a, b) => a.username.localeCompare(b.username));
module.exports = {handle, forget, moderators, signedInAs, itemRoutes, reviewRoutes};
// The Discord bot is deliberately a small adapter over the panel rather than
// its own moderator system. Its actor is a Discord user id that is already
// linked to one Burrow account. From there these methods use the same role,
// rank, permission and action checks as POST /mod/api/act, and log every
// successful change under the staff member's normal Burrow username.
const discordActor = discordId => {
const account = accounts.all().find(candidate => candidate.discordId === String(discordId));
return mayModerate(account) ? account : null;
};
const discordError = (actor, permission) => !actor
? {error: "Link this Discord account to an active Burrow staff account first."}
: !roles.can(actor, permission) ? {error: "Your Burrow role cannot do that."} : null;
const discordStatus = actor => {
const error = discordError(actor, "server.view");
if (error) {
return error;
}
const memory = process.memoryUsage();
const players = world.players();
return {ok: true, uptimeSeconds: Math.floor(process.uptime()), players: players.length,
rooms: new Set(players.map(player => player.room).filter(Boolean)).size,
reports: reports.openCount(), memoryMb: Math.round(memory.rss / 1048576)};
};
const discordPlayer = (actor, username) => {
const error = discordError(actor, "player.view");
if (error) {
return error;
}
const target = accounts.byName(String(username || "").trim());
return target ? {ok: true, player: playerDetail(target)} : {error: "No such player."};
};
const discordReports = actor => {
const error = discordError(actor, "player.view");
return error || {ok: true, reports: reports.list(false), open: reports.openCount()};
};
const discordStaff = actor => {
const error = discordError(actor, "staff.list");
return error || {ok: true, staff: moderators()};
};
const discordAnnounce = (actor, text) => {
const error = discordError(actor, "server.announce");
if (error) return error;
const message = String(text || "").trim().slice(0, 300);
if (!message) return {error: "The announcement is empty."};
const reached = world.announce(message);
modlog.record(actor.username, "Discord announcement", "", `${reached} player${reached === 1 ? "" : "s"}`);
return {ok: reached === 1 ? "Shown to 1 player." : `Shown to ${reached} players.`};
};
const discordHandleReport = (actor, id) => {
const error = discordError(actor, "player.warn");
if (error) {
return error;
}
const handled = reports.markHandled(Number(id));
if (handled) {
modlog.record(actor.username, "report dealt with", "", `#${Number(id)}`);
}
return handled ? {ok: "Marked as dealt with."} : {error: "No such report waiting."};
};
const discordAct = (actor, username, body) => {
if (!actor) {
return {error: "Link this Discord account to an active Burrow staff account first."};
}
const target = accounts.byName(String(username || "").trim());
if (!target) {
return {error: "No such player."};
}
const result = act(actor, target, body || {});
if (result.ok) {
modlog.record(actor.username, String(body.action), target.username, result.detail || "");
}
return result;
};
const discordBot = {actor: discordActor, authorize: discordError, status: discordStatus, player: discordPlayer, reports: discordReports,
staff: discordStaff, announce: discordAnnounce, handleReport: discordHandleReport, act: discordAct};
module.exports = {handle, forget, moderators, signedInAs, itemRoutes, reviewRoutes, discordBot};
+95 -1
View File
@@ -9,6 +9,7 @@ const achievements = require("./achievements.js");
const adopt = require("./adopt.js");
const badges = require("./badges.js");
const discordLinks = require("./discord.js");
const discordBot = require("./discordbot.js");
const bans = require("./bans.js");
const colours = require("./colours.js");
const chatlog = require("./chatlog.js");
@@ -149,6 +150,7 @@ const accountRow = (account, playing) => {
twoStep: totp.isOn(account),
discord: account.discord,
adminDashboardAccess: Boolean(account.adminDashboardAccess),
guide: account.guideGiven === true,
bio: account.bio,
badges: account.badges,
featuresOff: accounts.FEATURES.filter(name => !accounts.featureOn(account, name)),
@@ -382,6 +384,13 @@ const gift = (account, body) => {
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);
// returns {ok: text} or {error: text}.
@@ -534,6 +543,36 @@ const act = (account, body) => {
`+${(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) {
@@ -600,7 +639,7 @@ const PAGE_HEADERS = {
"X-Frame-Options": "DENY",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
"Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; "
"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'",
};
@@ -757,6 +796,61 @@ const handle = async (req, res, url, from, web) => {
reply(200, overview());
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});
modlog.record("admin", "Discord public status card changed", "", `title: ${statusCard.title}`);
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.
+38 -18
View File
@@ -3,7 +3,7 @@
const accounts = require("./accounts.js");
const achievements = require("./achievements.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
// 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_BITS = 0xF00; // the part of uBits PetInventory writes
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));
@@ -106,6 +113,24 @@ module.exports = ({others, findOnline, petFields}) => {
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 = {
// PetManager.onPetListResponse: [found, username, count, (invIdx,
// createdTs, name, lBits, uBits, eBits, mastery, personality, toy, food,
@@ -146,15 +171,8 @@ module.exports = ({others, findOnline, petFields}) => {
session.sendXt("ps", -1, 0);
return;
}
const wasPetForm = inPetForm(account);
activeAvatar(account).petInvId = pet ? pet.inv : 0;
if (!pet && session.petPlayerMode) {
session.petPlayerMode = false;
if (session.pos) {
for (const other of [session, ...others(session)]) {
other.sendXt("uc", session.room.id, session.id, "off", "13");
}
}
}
accounts.save(account);
const messageRoom = session.room ? session.room.id : -1;
session.sendXt("ps", messageRoom, 1, session.id, pet ? pet.inv : 0);
@@ -163,6 +181,11 @@ module.exports = ({others, findOnline, petFields}) => {
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]
@@ -173,14 +196,10 @@ module.exports = ({others, findOnline, petFields}) => {
session.sendXt("pd", -1, 0, invIdx);
return;
}
const wasPetForm = inPetForm(account);
account.pets = account.pets.filter(candidate => candidate !== pet);
if (session.petPlayerMode && activeAvatar(account).petInvId === pet.inv) {
session.petPlayerMode = false;
if (session.pos) {
for (const other of [session, ...others(session)]) {
other.sendXt("uc", session.room.id, session.id, "off", "13");
}
}
if (wasPetForm && !inPetForm(account)) {
sendPetForm(session);
}
for (const avatar of account.avatars) {
if (avatar.petInvId === pet.inv) {
@@ -215,7 +234,8 @@ module.exports = ({others, findOnline, petFields}) => {
// EggPetHatchedPopup: [petInvIdx, nameId1, nameId2] names a pet hatched
// from an egg. PetManager.onPetEggNameResponse: [success, invIdx, name].
pn(session, roomId, [invIdx, name1, name2]) {
const pet = ownPet(session.account, invIdx);
const {account} = session;
const pet = ownPet(account, invIdx);
const def = pet && defpacks.petDef(pet.lBits & 0xFF);
if (!pet || ![name1, name2].every(isUint) || pet.name || !def || def.isEgg !== "1"
|| pet.createdAt + SECONDS_TO_HATCH > Math.floor(Date.now() / 1000)) {
@@ -250,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};
};
+19 -2
View File
@@ -45,6 +45,7 @@ const MERGE_SECONDS = 10;
const perTenMinutes = limits.limiter(10, 600000);
const now = () => Math.floor(Date.now() / 1000);
const clean = (text, max) => String(text === undefined ? "" : text).replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, " ").trim().slice(0, max);
const listeners = new Set();
const load = () => accounts.database().exec(SCHEMA);
@@ -68,9 +69,18 @@ const file = ({reporter, target, reason, detail = "", context = "", room = ""})
if (!perTenMinutes.allow(reporter.toLowerCase()) || openCount() >= MAX_OPEN) {
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));
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;
};
@@ -95,8 +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;
// 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, openCount, MAX_DETAIL};
module.exports = {load, file, list, about, markHandled, onFile, openCount, MAX_DETAIL};
+5 -2
View File
@@ -16,6 +16,7 @@ const totp = require("./totp.js");
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)",
@@ -32,11 +33,13 @@ const PERMISSIONS = {
"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", "items.restrict", "theater.control"];
const ADMIN = [...MODERATOR, "items.create", "room.effects"];
const MODERATOR = [...HELPER, "player.kick", "player.summon", "staff.invisible", "player.ban", "player.names", "address.ban", "items.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"];
+53 -24
View File
@@ -161,6 +161,26 @@ const THEME_PATH_PREFIX = "theme_"; // lib/http.js looks for this
const chatLines = limits.limiter(config.chatLinesPerWindow, config.chatWindowMs);
const online = new Map(); // lowercased username -> session
const rooms = new Map(); // "path.name#shard" -> room
const gameActivityListeners = new Set();
// An intentionally small, privacy-safe activity feed for optional
// integrations. It names only the player and lifecycle event—never IPs,
// device identifiers, game tokens or chat text.
const gameActivity = entry => {
for (const listener of gameActivityListeners) {
try {
listener(entry);
}
catch (err) {
console.error(`[world] activity listener failed: ${logText(err.message)}`);
}
}
};
const onGameActivity = listener => {
gameActivityListeners.add(listener);
return () => gameActivityListeners.delete(listener);
};
// worlds (config.shards): a land room's name ends in "#<world>"; dens,
// parties and adventures have none and belong to no world. each player has
@@ -384,6 +404,7 @@ const login = (session, msg) => {
accounts.save(account);
online.set(key, session);
console.log(`[world] ${logText(account.username)} logged in as sfs user ${logText(session.id)}`);
gameActivity({type: "login", username: account.username, at: Math.floor(Date.now() / 1000)});
session.sendXtJson(-1, {_cmd: "login", status: "1", params: loginParams(session)});
// every custom colour, before anything that might be drawn with one
// (XtReplyDemuxer -> PaletteHelper.handleCustomColors in the patched SWF).
@@ -459,17 +480,20 @@ const sendAvatarCreate = (to, target) => {
avatar.questLevel || 0,
1, // userNameModeratedFlag
lastSeenField(account, Boolean(findOnline(account.username))), // daysSinceLastLogin: see lib/player.js
// optional-field flags: bit 0 accountType, bit 1 nameBarData, bit 2 pet
pet ? 7 : 3,
// optional-field flags: bit 0 accountType, bit 1 nameBarData, bit 2 pet,
// bit 3 a blend colour (none: 0), bit 4 guide (the name tag and bubble
// every client draws for a guide)
3 | (pet ? 4 : 0) | (account.isGuide ? 24 : 0),
account.accountType,
account.nameBarData,
...(pet ? petFields(pet) : []));
...(pet ? petFields(pet) : []),
...(account.isGuide ? [0, 1] : []));
sendItemList(to, target, false);
disguises.show(to, target);
if (target.invisible) {
to.sendXt("xiv", -1, target.id, 1);
}
if (target.petPlayerMode) {
if (pets.inPetForm(account)) {
to.sendXt("uc", room.id, target.id, "on", "13");
}
// `ac` only creates the avatar. Actions normally travel as live `uc`
@@ -692,6 +716,9 @@ const handlers = {
if (motd) {
tell(session, motd);
}
if (session.account.guideRefused) {
session.sendXt("xtl", -1, "Guide is only for players the Burrow team has made guides.");
}
buddies.greet(session);
minigames.greet(session);
moderation.greet(session);
@@ -1373,6 +1400,8 @@ setInterval(() => {
}, 60000).unref();
const leaveWorld = session => {
const username = session.account && session.account.username;
const playedSeconds = session.playStarted ? Math.max(0, Math.round((Date.now() - session.playStarted) / 1000)) : 0;
minigames.leave(session);
trades.forget(session);
leaveRoom(session);
@@ -1384,6 +1413,7 @@ const leaveWorld = session => {
accounts.release(session.account);
accounts.save(session.account);
buddies.announce(session.account);
gameActivity({type: "logout", username, at: Math.floor(Date.now() / 1000), playedSeconds});
}
};
@@ -1772,15 +1802,12 @@ module.exports = {
minigames.bubble(session, fields[0], fields[2]);
return;
}
// Per-player pet form. It is deliberately a user-communication
// message so every client already in the room updates the same
// avatar, while the normal pet-out state stays unchanged.
// Per-player pet form (the pet chooser's switch, lib/pets.js). It
// is deliberately a user-communication message so every client
// already in the room updates the same avatar, while the normal
// pet-out state stays unchanged.
if (fields[1] === "13") {
const enabled = fields[0] === "on" && Boolean(activePet(session.account));
session.petPlayerMode = enabled;
for (const other of [session, ...watchers(session)]) {
other.sendXt("uc", session.room.id, session.id, enabled ? "on" : "off", "13");
}
pets.setPetForm(session, fields[0] === "on");
return;
}
// Type 3 is the action packet. It used to be sent only to people
@@ -2016,20 +2043,21 @@ module.exports = {
// the panel's Masterpieces page. A painting waiting for review is an
// item its maker cannot use yet; approving it tells them so, by a
// Jam-A-Gram from Animal Jam HQ and at once if they are playing. `by`
// is who approved it: a moderator's username, or "admin".
// is who approved it: a moderator's username, or "admin". the same
// picture waiting elsewhere is approved with it, and its makers told too.
approveMasterpiece(id, by) {
const maker = masterpieces.creatorOf(id);
if (!masterpieces.approve(id, by)) {
return false;
}
if (maker) {
ecards.noteFromHq(maker, "Your Masterpiece has been approved! It is with your den items.");
const session = findOnline(maker.username);
if (session) {
dens.sendDenItems(session);
const approved = masterpieces.approve(id, by);
for (const painting of approved) {
const maker = masterpieces.creatorOf(painting.id);
if (maker) {
ecards.noteFromHq(maker, "Your Masterpiece has been approved! It is with your den items.");
const session = findOnline(maker.username);
if (session) {
dens.sendDenItems(session);
}
}
}
return true;
return approved.length > 0;
},
// takes a painting away for good, from whoever has it by now: one that
// was not approved, or one that should not have been. its maker gets a
@@ -2054,7 +2082,7 @@ module.exports = {
account.denItems = account.denItems.filter(item => item.image !== painting.id);
account.tradeList = account.tradeList.filter(listed => !(listed.type === 1 && held.some(item => item.inv === listed.inv)));
}
masterpieces.forget(painting.id);
masterpieces.forget(painting.id, true);
if (maker) {
dens.giveDenItem(maker, masterpieces.TOKEN_DEN_ITEM);
ecards.noteFromHq(maker, "Your Masterpiece was not approved. Here is a Masterpiece Token to frame another one with.");
@@ -2130,4 +2158,5 @@ module.exports = {
room: session.room ? session.room.name.replace(/#(\d+)$/, (whole, id) => (worldOf(whole) ? ` (${worldName(Number(id))})` : whole)) : null,
address: session.address,
})),
onGameActivity,
};
+333
View File
@@ -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
}
}
}
}
}
+3
View File
@@ -10,5 +10,8 @@
},
"engines": {
"node": ">=22.5"
},
"dependencies": {
"discord.js": "14.26.4"
}
}
+395 -1
View File
@@ -413,8 +413,10 @@
<button role="tab" data-tab="masterpieces" aria-selected="false"><span class="icon" aria-hidden="true">&#9635;</span>Masterpieces<span id="masterpiece-count"></span></button>
<button role="tab" data-tab="items" aria-selected="false"><span class="icon" aria-hidden="true">&#10070;</span>Items</button>
<button role="tab" data-tab="wear-rules" aria-selected="false"><span class="icon" aria-hidden="true">&#9873;</span>Wear rules</button>
<button role="tab" data-tab="music" aria-selected="false"><span class="icon" aria-hidden="true">&#9835;</span>Music</button>
<button role="tab" data-tab="bans" aria-selected="false"><span class="icon" aria-hidden="true">&#8856;</span>Bans</button>
<button role="tab" data-tab="moderators" aria-selected="false"><span class="icon" aria-hidden="true">&#9733;</span>Moderators</button>
<button role="tab" data-tab="discord" aria-selected="false"><span class="icon" aria-hidden="true">&#128172;</span>Discord</button>
<button role="tab" data-tab="messages" aria-selected="false"><span class="icon" aria-hidden="true">&#9993;</span>Messages</button>
<button role="tab" data-tab="logs" aria-selected="false"><span class="icon" aria-hidden="true">&#9776;</span>Logs</button>
<button role="tab" data-tab="debug" aria-selected="false"><span class="icon" aria-hidden="true">&#9881;</span>Debug</button>
@@ -459,6 +461,96 @@
</section>
</div>
<div data-view="discord" hidden>
<section>
<h2>Discord staff bot</h2>
<p class="hint" id="discord-bot-summary">Checking Discord bot configuration…</p>
<dl id="discord-bot-facts"></dl>
<div class="send-row">
<button type="button" id="discord-bot-start">Start</button>
<button type="button" id="discord-bot-stop">Stop</button>
<button type="button" id="discord-bot-reconnect">Reconnect</button>
<button type="button" id="discord-bot-sync">Sync slash commands</button>
</div>
<p class="status" id="discord-bot-status" role="status"></p>
</section>
<section>
<h2>Bot modules</h2>
<p class="hint">Every listed module is configured on this page. Permissions for staff commands are managed in the dashboard’s Moderators role matrix.</p>
<div class="table-wrap"><table>
<thead><tr><th>Module</th><th>State</th><th>What it does</th></tr></thead>
<tbody id="discord-modules"></tbody>
</table></div>
</section>
<section>
<h2>Public status card</h2>
<p class="hint">This Components V2 card is updated every five minutes. Save changes, then publish immediately when the bot and public-status channel are configured.</p>
<form id="discord-status-form">
<label for="discord-status-title">Title</label>
<input id="discord-status-title" maxlength="80" placeholder="Burrow status" aria-label="Discord public status-card title">
<label for="discord-status-note">Status message</label>
<textarea id="discord-status-note" rows="3" maxlength="500" placeholder="Optional message shown above the live player and moderation counts." aria-label="Discord public status-card message"></textarea>
<div class="send-row">
<button class="primary" type="submit">Save status card</button>
<button type="button" id="discord-status-publish">Publish now</button>
</div>
</form>
<p class="status" id="discord-status-card-result" role="status"></p>
</section>
<section>
<h2>Notification channels</h2>
<p class="hint">Set a Discord channel ID for any stream you want. Leave a field empty to turn that stream off. Changes take effect immediately.</p>
<form id="discord-routing-form">
<div id="discord-channel-inputs"></div>
<label for="discord-github-repository">GitHub repository</label>
<input id="discord-github-repository" maxlength="201" placeholder="owner/repository" aria-label="GitHub repository for Discord update cards">
<div class="send-row"><button class="primary" type="submit">Save bot routing</button></div>
</form>
<p class="status" id="discord-routing-status" role="status"></p>
</section>
<section>
<h2>GitHub game updates</h2>
<p class="hint">Signed pushes become Components V2 commit cards. Client/SWF and game-asset pushes are marked as game updates.</p>
<dl id="github-update-facts"></dl>
</section>
<section>
<h2>Discord security</h2>
<p class="hint">AutoMod deletes matching messages and posts an audit card without storing message text. Anti-raid sends an alert when the join limit is reached. Enable the Message Content and Server Members intents for this bot in the Discord Developer Portal, then reconnect it.</p>
<form id="discord-security-form">
<label class="check"><input id="discord-security-enabled" type="checkbox"> Enable Discord AutoMod and anti-raid alerts</label>
<label class="check"><input id="discord-security-invites" type="checkbox"> Block Discord invite links</label>
<label for="discord-security-words">Blocked words or phrases</label>
<textarea id="discord-security-words" rows="4" maxlength="3000" placeholder="One word or phrase per line; matching is case-insensitive."></textarea>
<div class="row">
<label for="discord-security-spam">Messages allowed per 10 seconds</label>
<input id="discord-security-spam" type="number" min="2" max="20" step="1" inputmode="numeric">
<label for="discord-security-raid">Joins allowed per minute</label>
<input id="discord-security-raid" type="number" min="3" max="100" step="1" inputmode="numeric">
</div>
<div class="send-row"><button class="primary" type="submit">Save security settings</button></div>
</form>
<p class="status" id="discord-security-status" role="status"></p>
</section>
<section>
<h2>Tickets and member notices</h2>
<p class="hint">Tickets open with `/ticket open` and remain visible to the opener and the configured staff role. Welcome and goodbye messages support `{user}` and `{server}`.</p>
<form id="discord-community-form">
<label for="discord-ticket-category">Ticket category ID</label><input id="discord-ticket-category" inputmode="numeric" maxlength="25" placeholder="Required for tickets">
<label for="discord-ticket-staff-role">Ticket staff role ID</label><input id="discord-ticket-staff-role" inputmode="numeric" maxlength="25" placeholder="Required for tickets">
<label for="discord-welcome-channel">Welcome channel ID</label><input id="discord-welcome-channel" inputmode="numeric" maxlength="25" placeholder="Optional">
<textarea id="discord-welcome-message" rows="2" maxlength="500" placeholder="Welcome {user} to {server}!"></textarea>
<label for="discord-goodbye-channel">Goodbye channel ID</label><input id="discord-goodbye-channel" inputmode="numeric" maxlength="25" placeholder="Optional">
<textarea id="discord-goodbye-message" rows="2" maxlength="500" placeholder="Goodbye {user}."></textarea>
<div class="send-row"><button class="primary" type="submit">Save ticket and notice settings</button></div>
</form>
<p class="status" id="discord-community-status" role="status"></p>
</section>
<section>
<h2>Discord server moderation</h2>
<p class="hint">The consolidated bot also provides `/discord timeout`, `/discord untimeout`, `/discord kick`, `/discord ban`, `/discord unban`, and `/discord purge`. Give its Discord role the matching server permissions (Moderate Members, Kick Members, Ban Members, and Manage Messages) and keep that role above members it should moderate. Burrow staff permissions remain the first check.</p>
</section>
</div>
<div data-view="stats" hidden>
<!--stats-view-->
</div>
@@ -501,6 +593,15 @@
<div class="row"><input id="new-name" maxlength="100" placeholder="New username" autocomplete="off" spellcheck="false" aria-label="New username">
<button type="button" data-action="rename">Rename</button></div>
</div>
<div class="action">
<h3>Lost access</h3>
<p class="hint">A new random password, shown once. They are signed out everywhere and should change it on their account page.</p>
<div class="row"><label class="check"><input type="checkbox" id="temp-two-step-off"> Turn off their 2FA too</label></div>
<div class="row" style="margin-top:8px"><button type="button" data-action="tempPassword">Make temporary password</button></div>
<div class="row" style="margin-top:8px" id="temp-password-row" hidden>
<input id="temp-password" readonly aria-label="Temporary password" spellcheck="false" style="font-family:monospace">
<button type="button" id="temp-password-copy">Copy</button></div>
</div>
<div class="action">
<h3>Adventure level</h3>
<div class="row"><input id="quest-level" type="number" min="0" max="100" step="1" aria-label="Adventure level of the animal in use">
@@ -525,6 +626,8 @@
<h3>Badges</h3>
<div class="buttons" id="badge-boxes"></div>
<div class="row" style="margin-top:8px"><button type="button" data-action="badges">Set</button></div>
<div class="row" style="margin-top:8px" title="A guide's name tag and chat bubble, seen by everyone; from their next login">
<button type="button" data-action="guide" id="guide-toggle"></button></div>
<div class="row" style="margin-top:8px" title="Players link their Discord themselves, on the account page">
<span class="hint" id="discord-name"></span>
<button type="button" data-action="discord">Unlink Discord</button></div>
@@ -735,6 +838,31 @@
</section>
</div>
<div data-view="music" hidden>
<section>
<h2>Upload music</h2>
<p class="hint">An MP3 becomes a den music track at once, with no restart: players get it from the item finder (and the shop, if it is on sale) and play it in their dens like the game's own tracks. 44.1 kHz MP3s play best; 15 MB at most.</p>
<div class="actions">
<div class="action">
<h3>The track</h3>
<div class="row"><input id="music-file" type="file" accept=".mp3,audio/mpeg" aria-label="MP3 file"></div>
<div class="row" style="margin-top:8px"><input id="music-name" maxlength="40" placeholder="Name" aria-label="Name"></div>
<div class="row" style="margin-top:8px"><input id="music-cost" type="number" min="0" placeholder="Price in gems (0)" aria-label="Price in gems">
<label class="check"><input type="checkbox" id="music-shop"> On sale in the shop</label></div>
<div class="row" style="margin-top:8px"><button type="button" class="primary" id="music-upload">Upload</button></div>
</div>
</div>
<p class="status" id="music-status" role="status"></p>
</section>
<section>
<h2>Uploaded tracks</h2>
<div class="table-wrap"><table>
<thead><tr><th>Track</th><th class="num">Den item</th><th>Uploaded</th><th class="num">Size</th><th></th></tr></thead>
<tbody id="music-list"></tbody>
</table></div>
<div class="empty" id="no-music" hidden>None yet.</div>
</section>
</div>
<div data-view="items" hidden>
<section>
<h2 id="item-form-title">Make an item</h2>
@@ -1173,6 +1301,161 @@
$("server-facts").replaceChildren(...facts.flatMap(([name, value]) => [el("dt", name), el("dd", String(value))]));
};
const renderDiscord = data => {
const configured = data.botTokenConfigured && data.guildId;
$("discord-bot-summary").textContent = !configured
? "The Discord staff bot is off. Set AJ_DISCORD_BOT_TOKEN and AJ_DISCORD_GUILD_ID, then restart the server."
: data.connected ? "The Discord staff bot is connected and ready." : "The Discord staff bot is configured but is not connected. Check the server log and bot permissions.";
const facts = [
["Bot token", data.botTokenConfigured ? "Configured" : "Missing"],
["Guild", data.guildId || "Missing"],
["Connection", data.connected ? "Connected" : "Not connected"],
["Commands", (data.commands || []).join(", ") || "None"],
];
$("discord-bot-facts").replaceChildren(...facts.flatMap(([name, value]) => [el("dt", name), el("dd", value)]));
$("discord-modules").replaceChildren(...(data.modules || []).map(module => {
const row = el("tr");
row.append(el("td", module.name), el("td", module.enabled ? "Enabled" : "Off / needs setup"), el("td", module.detail));
return row;
}));
$("discord-bot-status").textContent = configured
? "Credentials and webhook secrets are intentionally never shown in this dashboard."
: "Add the missing environment variables to the service that starts Burrow; dashboard settings cannot store bot secrets.";
$("discord-bot-status").classList.toggle("bad", !configured || !data.connected);
const editingStatusCard = ["discord-status-title", "discord-status-note"].includes(document.activeElement && document.activeElement.id);
if (!editingStatusCard) {
$("discord-status-title").value = data.statusCard && data.statusCard.title || "Burrow status";
$("discord-status-note").value = data.statusCard && data.statusCard.note || "";
}
const editingRouting = document.activeElement && (document.activeElement.dataset.discordChannel || document.activeElement.id === "discord-github-repository");
if (!editingRouting) {
$("discord-channel-inputs").replaceChildren(...(data.channels || []).flatMap(channel => {
const label = el("label", channel.name);
label.htmlFor = `discord-channel-${channel.key}`;
const input = el("input");
input.id = label.htmlFor;
input.dataset.discordChannel = channel.key;
input.inputMode = "numeric";
input.maxLength = 25;
input.placeholder = "Discord channel ID (optional)";
input.value = channel.id || "";
input.setAttribute("aria-label", `${channel.name} Discord channel ID`);
return [label, input];
}));
$("discord-github-repository").value = data.github && data.github.repository || "";
}
const github = data.github || {};
const githubFacts = [
["Repository", github.repository || "Missing (AJ_GITHUB_REPOSITORY)"],
["Webhook secret", github.webhookSecretConfigured ? "Configured" : "Missing"],
["Update channel", (data.channels || []).some(channel => channel.name === "GitHub updates" && channel.configured) ? "Configured" : "Missing"],
["Webhook endpoint", github.endpoint || "/discord/github"],
["Update cards", github.updatesEnabled ? "Enabled" : "Off until all three settings are configured"],
];
$("github-update-facts").replaceChildren(...githubFacts.flatMap(([name, value]) => [el("dt", name), el("dd", value)]));
const editingSecurity = ["discord-security-words", "discord-security-spam", "discord-security-raid"].includes(document.activeElement && document.activeElement.id);
if (!editingSecurity) {
const security = data.security || {};
$("discord-security-enabled").checked = Boolean(security.enabled);
$("discord-security-invites").checked = Boolean(security.blockInvites);
$("discord-security-words").value = (security.blockedWords || []).join("\n");
$("discord-security-spam").value = String(security.spamLimit || 6);
$("discord-security-raid").value = String(security.raidJoinLimit || 12);
setStatus($("discord-security-status"), security.enabled
? security.monitoring ? "Security monitoring is active." : "Security is saved. Reconnect the bot after enabling Discord Message Content and Server Members intents."
: "Security monitoring is off.", security.enabled && !security.monitoring);
}
const editingCommunity = ["discord-ticket-category", "discord-ticket-staff-role", "discord-welcome-channel", "discord-welcome-message", "discord-goodbye-channel", "discord-goodbye-message"].includes(document.activeElement && document.activeElement.id);
if (!editingCommunity) {
const community = data.community || {};
$("discord-ticket-category").value = community.ticketCategoryId || "";
$("discord-ticket-staff-role").value = community.ticketStaffRoleId || "";
$("discord-welcome-channel").value = community.welcomeChannelId || "";
$("discord-welcome-message").value = community.welcomeMessage || "";
$("discord-goodbye-channel").value = community.goodbyeChannelId || "";
$("discord-goodbye-message").value = community.goodbyeMessage || "";
}
};
const controlDiscordBot = async action => {
const buttons = ["discord-bot-start", "discord-bot-stop", "discord-bot-reconnect", "discord-bot-sync"].map($);
buttons.forEach(button => { button.disabled = true; });
const result = await api("discord/control", {action});
buttons.forEach(button => { button.disabled = false; });
setStatus($("discord-bot-status"), said(result), !result.ok);
refresh();
};
$("discord-bot-start").addEventListener("click", () => controlDiscordBot("start"));
$("discord-bot-stop").addEventListener("click", () => controlDiscordBot("stop"));
$("discord-bot-reconnect").addEventListener("click", () => controlDiscordBot("reconnect"));
$("discord-bot-sync").addEventListener("click", () => controlDiscordBot("sync"));
$("discord-routing-form").addEventListener("submit", async event => {
event.preventDefault();
const button = event.submitter;
if (button) button.disabled = true;
const fields = {githubRepository: $("discord-github-repository").value};
for (const input of $("discord-channel-inputs").querySelectorAll("input[data-discord-channel]")) {
fields[input.dataset.discordChannel] = input.value;
}
const result = await api("discord/config", fields);
if (button) button.disabled = false;
setStatus($("discord-routing-status"), said(result), !result.ok);
if (result.ok) refresh();
});
$("discord-security-form").addEventListener("submit", async event => {
event.preventDefault();
const button = event.submitter;
if (button) button.disabled = true;
const result = await api("discord/security", {
enabled: $("discord-security-enabled").checked,
blockInvites: $("discord-security-invites").checked,
blockedWords: $("discord-security-words").value,
spamLimit: Number($("discord-security-spam").value),
raidJoinLimit: Number($("discord-security-raid").value),
});
if (button) button.disabled = false;
setStatus($("discord-security-status"), said(result), !result.ok);
if (result.ok) refresh();
});
$("discord-community-form").addEventListener("submit", async event => {
event.preventDefault();
const button = event.submitter;
if (button) button.disabled = true;
const result = await api("discord/community", {
ticketCategoryId: $("discord-ticket-category").value, ticketStaffRoleId: $("discord-ticket-staff-role").value,
welcomeChannelId: $("discord-welcome-channel").value, welcomeMessage: $("discord-welcome-message").value,
goodbyeChannelId: $("discord-goodbye-channel").value, goodbyeMessage: $("discord-goodbye-message").value,
});
if (button) button.disabled = false;
setStatus($("discord-community-status"), said(result), !result.ok);
if (result.ok) refresh();
});
$("discord-status-form").addEventListener("submit", async event => {
event.preventDefault();
const button = event.submitter;
if (button) button.disabled = true;
const result = await api("discord/status", {title: $("discord-status-title").value, note: $("discord-status-note").value});
if (button) button.disabled = false;
setStatus($("discord-status-card-result"), said(result), !result.ok);
if (result.ok && result.data.statusCard) {
$("discord-status-title").value = result.data.statusCard.title;
$("discord-status-note").value = result.data.statusCard.note;
}
});
$("discord-status-publish").addEventListener("click", async () => {
const button = $("discord-status-publish");
button.disabled = true;
const result = await api("discord/status/publish", {});
button.disabled = false;
setStatus($("discord-status-card-result"), said(result), !result.ok);
if (result.ok) refresh();
});
const accountState = account => {
const tags = [];
if (account.online) {
@@ -1501,6 +1784,8 @@
label.append(box, ` ${badge.label}`);
return label;
}));
$("temp-two-step-off").disabled = !current || !current.twoStep;
$("guide-toggle").textContent = current && current.guide ? "Remove guide" : "Make guide";
$("discord-name").textContent = current && current.discord ? `Discord: ${current.discord}` : "No Discord linked";
$("admin-dashboard-access").textContent = current && current.adminDashboardAccess ? "Remove Discord dashboard access" : "Allow Discord dashboard access";
$("admin-dashboard-access").disabled = !current || (!current.discord && !current.adminDashboardAccess);
@@ -1537,7 +1822,8 @@
selected = username;
current = null;
setStatus($("detail-status"), "");
for (const id of ["new-name", "ban-hours", "silence-hours", "message-text", "gems-amount", "gift-value", "gift-text"]) {
$("temp-password-row").hidden = true;
for (const id of ["temp-password", "new-name", "ban-hours", "silence-hours", "message-text", "gems-amount", "gift-value", "gift-text"]) {
$(id).value = "";
}
hashArg = username;
@@ -1690,6 +1976,8 @@
case "role": return {role: $("role-select").value};
case "permissions": return permissionChoices();
case "adminDashboardAccess": return {on: !(current || {}).adminDashboardAccess};
case "guide": return {on: !(current || {}).guide};
case "tempPassword": return {twoStepOff: $("temp-two-step-off").checked};
case "message": return {text: $("message-text").value};
case "gems": return {amount: numberFrom("gems-amount")};
case "gift": return giftBody();
@@ -1701,6 +1989,10 @@
}
};
$("temp-password-copy").addEventListener("click", () => {
navigator.clipboard.writeText($("temp-password").value).catch(() => $("temp-password").select());
});
// the "N ago" buttons fill the last-seen box and press Set.
$("detail").addEventListener("click", event => {
const quick = event.target.closest("button[data-ago]");
@@ -1730,6 +2022,9 @@
if (action === "banDevices" && !window.confirm(`Hardware ban ${selected}? Everyone on their hardware is put out.`)) {
return;
}
if (action === "tempPassword" && !window.confirm(`Give ${selected} a new random password? Their old one stops working and they are signed out everywhere.`)) {
return;
}
button.disabled = true;
const result = await api("account", {username: selected, action, ...actionBody(action)});
button.disabled = false;
@@ -1737,6 +2032,11 @@
if (result.ok && action === "delete") {
selected = null;
}
if (result.ok && action === "tempPassword") {
$("temp-password").value = result.data.password;
$("temp-password-row").hidden = false;
$("temp-two-step-off").checked = false;
}
if (result.ok && action === "rename") {
selected = result.data.username;
$("new-name").value = "";
@@ -2853,6 +3153,91 @@
setStatus($("control-status"), said(result), !result.ok);
});
// ---- music uploaded by staff (lib/custommusic.js): an MP3 made a den
// music track, which players get from the item finder at once
const MUSIC = "/admin/api/music";
let musicShown = "";
const musicCall = async (query, body) => {
try {
const response = await fetch(`${MUSIC}${query}`, {method: "POST", headers: {"Content-Type": "audio/mpeg"}, body});
return await response.json().catch(() => ({error: "That did not work."}));
}
catch (err) {
return {error: "The server did not answer."};
}
};
const renderMusic = data => {
const tracks = data.tracks || [];
// drawn again only when something changed: a track being listened to keeps playing
const shown = JSON.stringify(tracks);
if (shown === musicShown) {
return;
}
musicShown = shown;
$("no-music").hidden = tracks.length > 0;
$("music-list").replaceChildren(...tracks.map(track => {
const row = el("tr");
const name = el("td");
const player = el("audio");
player.controls = true;
player.preload = "none";
player.src = `${MUSIC}?play=${track.id}`;
player.style.cssText = "display:block;margin-top:6px;height:32px;max-width:260px";
name.append(el("strong", track.name), player);
const actions = el("td");
actions.append(button("Delete", async () => {
if (!confirm(`Delete "${track.name}"? It is taken from every player who has it. This cannot be undone.`)) {
return;
}
const result = await musicCall(`?delete=${track.id}`, new Uint8Array(0));
setStatus($("music-status"), result.ok || result.error || "That did not work.", !result.ok);
await loadMusic();
}, "danger"));
row.append(name, el("td", String(track.id), "num"), el("td", `${when(track.createdAt)} · ${track.createdBy}${track.inShop ? ` · on sale, ${track.cost} gems` : ""}`),
el("td", `${(track.bytes / 1048576).toFixed(1)} MB`, "num"), actions);
return row;
}));
};
const loadMusic = async () => {
try {
const response = await fetch(MUSIC);
const data = await response.json().catch(() => ({}));
if (response.ok) {
renderMusic(data);
}
}
catch (err) {
// shown again with the next refresh
}
};
// the name from the file's, until one is typed
$("music-file").addEventListener("change", () => {
const file = $("music-file").files[0];
if (file && !$("music-name").value.trim()) {
$("music-name").value = file.name.replace(/\.mp3$/i, "").replace(/[_]+/g, " ").slice(0, 40);
}
});
$("music-upload").addEventListener("click", async () => {
const file = $("music-file").files[0];
if (!file || !$("music-name").value.trim()) {
setStatus($("music-status"), file ? "Give the track a name." : "Choose an MP3 first.", true);
return;
}
$("music-upload").disabled = true;
setStatus($("music-status"), "Uploading...");
const query = `?name=${encodeURIComponent($("music-name").value.trim())}&cost=${encodeURIComponent($("music-cost").value || 0)}&inShop=${$("music-shop").checked ? 1 : 0}`;
const result = await musicCall(query, new Uint8Array(await file.arrayBuffer()));
$("music-upload").disabled = false;
setStatus($("music-status"), result.ok || result.error || "That did not work.", !result.ok);
if (result.ok) {
for (const id of ["music-file", "music-name", "music-cost"]) {
$(id).value = "";
}
$("music-shop").checked = false;
}
await loadMusic();
});
const refresh = async () => {
clearTimeout(timer);
if (!state || !state.signedIn) {
@@ -2883,6 +3268,12 @@
quickLockFind();
}
}
else if (tab === "discord") {
result = await api("discord");
if (result.ok) {
renderDiscord(result.data);
}
}
else if (tab === "accounts") {
const searchBy = $("account-search-by").value;
const query = searchBy !== "name" ? "" : $("account-search").value.trim();
@@ -2921,6 +3312,9 @@
else if (tab === "wear-rules") {
await loadWearRules();
}
else if (tab === "music") {
await loadMusic();
}
else if (tab === "items") {
result = await api("items");
if (result.ok) {
+486 -7
View File
@@ -14,24 +14,183 @@
position: relative;
z-index: 1;
}
#theatre-video {
/* the theatre's screen, as the game says where it is (ajTheatreScreen):
laid over the stage as Flash's "showAll" draws it, every size in
stage pixels times --s. the room's video (staff) and the player's
own both sit on it. */
@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"); }
#theatre {
--s: 1;
--px: calc(var(--s) * 1px);
position: fixed;
z-index: 2;
display: none;
left: 8.4vw;
top: 6.2vh;
width: 56.8vw;
height: 52.8vh;
overflow: hidden;
pointer-events: none;
font-family: "DigitalDelivery", Arial, Helvetica, sans-serif;
}
#theatre[hidden], #theatre [hidden] {
display: none !important;
}
/* the game draws over it just now (ajTheatreScreen) */
#theatre .covered {
visibility: hidden;
}
.theatre-screen {
position: absolute;
border: 0;
background: #000;
pointer-events: auto;
}
#theatre-video {
display: none;
}
#theatre-video.visible {
display: block;
}
#own-video > * {
width: 100%;
height: 100%;
border: 0;
display: block;
}
/* in the game's own colours: cream panels, brown edges, a green "go" */
#own-video-open {
position: absolute;
pointer-events: auto;
font: 700 calc(13 * var(--px)) / 1 "DigitalDelivery", Arial, sans-serif;
color: #6d4330;
background: linear-gradient(#fffbe6, #ffe9a6);
border: calc(2 * var(--px)) solid #7f6744;
border-radius: 999px;
padding: calc(6 * var(--px)) calc(14 * var(--px));
box-shadow: 0 calc(2 * var(--px)) 0 #7f6744;
cursor: pointer;
white-space: nowrap;
}
#own-video-open:hover {
background: linear-gradient(#fffef5, #fff0be);
}
#own-video-open:active {
transform: translateY(calc(2 * var(--px)));
box-shadow: none;
}
#own-video-box {
position: absolute;
pointer-events: auto;
box-sizing: border-box;
width: calc(360 * var(--px));
padding: calc(14 * var(--px)) calc(16 * var(--px)) calc(12 * var(--px));
color: #6d4330;
font-size: calc(13 * var(--px));
background: #fff2c4;
border: calc(4 * var(--px)) solid #7f6744;
border-radius: calc(18 * var(--px));
box-shadow: inset 0 0 0 calc(2 * var(--px)) #ffe39a, 0 calc(4 * var(--px)) 0 rgba(0, 0, 0, 0.35);
}
#own-video-box h2 {
margin: 0 calc(24 * var(--px)) calc(10 * var(--px)) 0;
font-size: calc(20 * var(--px));
font-weight: 700;
color: #fff;
letter-spacing: 0.02em;
text-shadow: 0 0 calc(2 * var(--px)) #6d4330, calc(1.5 * var(--px)) calc(1.5 * var(--px)) 0 #6d4330, calc(-1.5 * var(--px)) calc(1.5 * var(--px)) 0 #6d4330, calc(1.5 * var(--px)) calc(-1.5 * var(--px)) 0 #6d4330, calc(-1.5 * var(--px)) calc(-1.5 * var(--px)) 0 #6d4330;
}
#own-video-url {
box-sizing: border-box;
width: 100%;
font: 400 calc(13 * var(--px)) / 1.2 Arial, Helvetica, sans-serif;
color: #3d2716;
background: #fff;
border: calc(2 * var(--px)) solid #c9a86a;
border-radius: calc(9 * var(--px));
padding: calc(7 * var(--px)) calc(9 * var(--px));
box-shadow: inset 0 calc(2 * var(--px)) calc(3 * var(--px)) rgba(109, 67, 48, 0.25);
outline: none;
}
#own-video-url:focus {
border-color: #7f6744;
}
#own-video-url::placeholder {
color: #a88f6a;
}
.own-video-buttons {
display: flex;
justify-content: center;
gap: calc(10 * var(--px));
margin-top: calc(10 * var(--px));
}
.aj-button {
min-width: calc(88 * var(--px));
font: 700 calc(15 * var(--px)) / 1 "DigitalDelivery", Arial, sans-serif;
color: #fff;
border-radius: 999px;
padding: calc(7 * var(--px)) calc(16 * var(--px));
cursor: pointer;
text-shadow: 0 calc(1.5 * var(--px)) 0 rgba(0, 0, 0, 0.45);
}
.aj-button:active {
transform: translateY(calc(2 * var(--px)));
box-shadow: none !important;
}
.aj-button.go {
background: linear-gradient(#a6e05a, #4fa52f);
border: calc(2 * var(--px)) solid #2f7420;
box-shadow: inset 0 calc(2 * var(--px)) 0 rgba(255, 255, 255, 0.45), 0 calc(2 * var(--px)) 0 #2f7420;
}
.aj-button.go:hover {
background: linear-gradient(#b5ea6c, #5cb43a);
}
.aj-button.stop {
background: linear-gradient(#f59a6a, #d4482a);
border: calc(2 * var(--px)) solid #8e2b16;
box-shadow: inset 0 calc(2 * var(--px)) 0 rgba(255, 255, 255, 0.4), 0 calc(2 * var(--px)) 0 #8e2b16;
}
.aj-button.stop:hover {
background: linear-gradient(#ffab7c, #e05634);
}
#own-video-close {
position: absolute;
top: calc(-10 * var(--px));
right: calc(-10 * var(--px));
width: calc(30 * var(--px));
height: calc(30 * var(--px));
padding: 0;
font: 700 calc(18 * var(--px)) / 1 Arial, sans-serif;
color: #fff;
background: radial-gradient(circle at 50% 35%, #ff7a5c, #c8321a 70%);
border: calc(3 * var(--px)) solid #fff;
border-radius: 50%;
box-shadow: 0 0 0 calc(2 * var(--px)) #7f6744, 0 calc(2 * var(--px)) 0 calc(2 * var(--px)) rgba(0, 0, 0, 0.3);
cursor: pointer;
}
#own-video-close:hover {
background: radial-gradient(circle at 50% 35%, #ff8f74, #d93d22 70%);
}
#own-video-said {
min-height: calc(15 * var(--px));
margin: calc(8 * var(--px)) 0 0;
font: 400 calc(12 * var(--px)) / 1.25 Arial, Helvetica, sans-serif;
color: #a3341c;
text-align: center;
}
</style>
<embed id="flash-content"></embed>
<iframe id="theatre-video" title="Theatre video" allow="autoplay; encrypted-media" referrerpolicy="strict-origin-when-cross-origin"></iframe>
<div id="theatre" hidden>
<iframe id="theatre-video" class="theatre-screen" title="Theatre video" allow="autoplay; encrypted-media" referrerpolicy="strict-origin-when-cross-origin"></iframe>
<div id="own-video" class="theatre-screen" hidden></div>
<button type="button" id="own-video-open">&#9654; Your Video</button>
<form id="own-video-box" hidden>
<h2>Your Video</h2>
<button type="button" id="own-video-close" aria-label="Close">&times;</button>
<input id="own-video-url" type="url" placeholder="Paste a link: YouTube, Vimeo, .mp4, .webm, .mp3" autocomplete="off" spellcheck="false" aria-label="Video link">
<div class="own-video-buttons">
<button type="submit" class="aj-button go">Play</button>
<button type="button" id="own-video-stop" class="aj-button stop">Stop</button>
</div>
<p id="own-video-said" role="status"></p>
</form>
</div>
<script>
"use strict";
@@ -114,6 +273,130 @@
window.ipc.sendToHost("presence", String(text).slice(0, 100));
}
// the theatre's screen, from the game (AJClient.reportTheatreScreen):
// "x,y,width,height" in its 900 by 550 stage, or "" with none shown.
// the stage fills the page as Flash's "showAll" draws it: as big as
// fits, in the middle.
//
// after it, "|columns|row,row,..." when the game draws something over
// the screen (or just under it): a hex row of bits per COVER_CELL
// stage pixels. a web page is always drawn over the game, so those
// cells are cut out of the videos, and the button and box step aside.
const STAGE_W = 900;
const STAGE_H = 550;
const COVER_CELL = 4;
const theatre = document.getElementById("theatre");
let theatreScreen = null;
let theatreCover = []; // {x, y, w, h} in stage pixels from the screen's corner
function ajTheatreScreen(text) {
const parts = String(text || "").split("|");
const numbers = parts[0].split(",").map(Number);
theatreScreen = numbers.length === 4 && numbers.every(Number.isFinite) && numbers[2] > 0 && numbers[3] > 0
? {x: numbers[0], y: numbers[1], w: numbers[2], h: numbers[3]} : null;
theatreCover = theatreScreen && parts.length === 3 ? coverRects(Number(parts[1]), parts[2].split(",")) : [];
placeTheatre();
ownVideo.inTheatre(theatreScreen !== null);
}
// the covered cells as rectangles: runs along each row, and a run
// that the row above has too made taller.
function coverRects(columns, rows) {
const rects = [];
let above = new Map(); // "from,to" of the row above -> its rectangle
rows.forEach((hex, row) => {
const here = new Map();
let from = -1;
for (let column = 0; column <= columns; column++) {
const digit = column < columns ? parseInt(hex[column >> 2] || "0", 16) : 0;
const covered = column < columns && Boolean(digit & (8 >> (column & 3)));
if (covered && from < 0) {
from = column;
}
else if (!covered && from >= 0) {
const key = `${from},${column}`;
let rect = above.get(key);
if (rect) {
rect.h += COVER_CELL;
}
else {
rect = {x: from * COVER_CELL, y: row * COVER_CELL, w: (column - from) * COVER_CELL, h: COVER_CELL};
rects.push(rect);
}
here.set(key, rect);
from = -1;
}
}
above = here;
});
return rects;
}
// the screen with the covered rectangles cut out ("evenodd": each one
// is a hole, reached from the corner and back).
function coverClip(scale) {
if (!theatreCover.length) {
return "none";
}
const px = value => `${Math.round(value * scale * 10) / 10}px`;
const points = ["0 0", "100% 0", "100% 100%", "0 100%", "0 0"];
for (const {x, y, w, h} of theatreCover) {
points.push(`${px(x)} ${px(y)}`, `${px(x + w)} ${px(y)}`, `${px(x + w)} ${px(y + h)}`, `${px(x)} ${px(y + h)}`, `${px(x)} ${px(y)}`, "0 0");
}
return `polygon(evenodd, ${points.join(", ")})`;
}
// is any of this element (placed in #theatre) under the game's drawing?
function underCover(element, scale) {
if (element.hidden) {
return false;
}
const left = element.offsetLeft / scale - theatreScreen.x;
const top = element.offsetTop / scale - theatreScreen.y;
const right = left + element.offsetWidth / scale;
const bottom = top + element.offsetHeight / scale;
return theatreCover.some(rect => rect.x < right && rect.x + rect.w > left && rect.y < bottom && rect.y + rect.h > top);
}
const BUTTON_ROOM = 34; // stage pixels the button wants under the screen
const BOX_W = 360; // #own-video-box's width in stage pixels
const BOX_H = 170; // and about its height
function placeTheatre() {
theatre.hidden = theatreScreen === null;
if (!theatreScreen) {
return;
}
const scale = Math.min(window.innerWidth / STAGE_W, window.innerHeight / STAGE_H);
const place = (element, x, y, w, h) => {
element.style.left = `${x * scale}px`;
element.style.top = `${y * scale}px`;
if (w !== undefined) {
element.style.width = `${w * scale}px`;
element.style.height = `${h * scale}px`;
}
};
theatre.style.left = `${(window.innerWidth - STAGE_W * scale) / 2}px`;
theatre.style.top = `${(window.innerHeight - STAGE_H * scale) / 2}px`;
theatre.style.width = `${STAGE_W * scale}px`;
theatre.style.height = `${STAGE_H * scale}px`;
theatre.style.setProperty("--s", String(scale));
const {x, y, w, h} = theatreScreen;
place(theatreVideo, x, y, w, h);
place(document.getElementById("own-video"), x, y, w, h);
// the button under the screen's left corner, or inside it when the
// stage ends first; the box over the middle of the screen.
const below = y + h + 8 + BUTTON_ROOM <= STAGE_H;
place(document.getElementById("own-video-open"), x + 4, below ? y + h + 8 : y + h - BUTTON_ROOM);
place(document.getElementById("own-video-box"), x + (w - BOX_W) / 2, Math.max(4, y + (h - BOX_H) / 2));
const clip = coverClip(scale);
theatreVideo.style.clipPath = clip;
document.getElementById("own-video").style.clipPath = clip;
for (const id of ["own-video-open", "own-video-box"]) {
const element = document.getElementById(id);
element.classList.toggle("covered", underCover(element, scale));
}
}
window.addEventListener("resize", placeTheatre);
function ajPrint(imageData) {
window.ipc.sendToHost("printImage", imageData);
}
@@ -125,12 +408,208 @@
if (!/^[A-Za-z0-9_-]{11}$/.test(id)) {
theatreVideo.removeAttribute("src");
theatreVideo.classList.remove("visible");
ownVideo.roomVideo(false);
return;
}
theatreVideo.src = `https://www.youtube-nocookie.com/embed/${id}?autoplay=1&rel=0&modestbranding=1`;
theatreVideo.classList.add("visible");
// what staff play for the room comes first; the player's own waits.
ownVideo.roomVideo(true);
}
// a video of the player's own choosing on the theatre screen, seen by
// them alone: nothing of it goes to the server. YouTube and Vimeo
// links play in those sites' own players; any other http(s) address
// in a <video>, which plays a media file or nothing (a web page in it
// runs no script and asks nobody for anything).
const ownVideo = (() => {
const $ = id => document.getElementById(id);
const screen = $("own-video");
const opener = $("own-video-open");
const box = $("own-video-box");
const input = $("own-video-url");
const said = $("own-video-said");
const SAVED = "ownVideoUrl";
let here = false; // in a theatre
let roomPlaying = false;
let playing = null; // the element showing it
const embedFor = text => {
let url;
try {
url = new URL(text);
}
catch (err) {
return null;
}
if (url.protocol !== "https:" && url.protocol !== "http:") {
return null;
}
const host = url.hostname.replace(/^(?:www\.|m\.)/, "").toLowerCase();
let match = null;
if (host === "youtu.be") {
match = /^\/([A-Za-z0-9_-]{11})/.exec(url.pathname);
}
else if (host === "youtube.com" || host === "youtube-nocookie.com") {
match = url.pathname === "/watch" ? /^([A-Za-z0-9_-]{11})$/.exec(url.searchParams.get("v") || "")
: /^\/(?:embed|shorts|live)\/([A-Za-z0-9_-]{11})/.exec(url.pathname);
}
if (match) {
return {frame: `https://www.youtube-nocookie.com/embed/${match[1]}?autoplay=1&rel=0&modestbranding=1`};
}
if (host === "vimeo.com" || host === "player.vimeo.com") {
match = /^\/(?:video\/)?(\d{1,12})(?:\/|$)/.exec(url.pathname);
return match ? {frame: `https://player.vimeo.com/video/${match[1]}?autoplay=1`} : {error: "That Vimeo link has no video in it."};
}
if (host.endsWith("youtube.com")) {
return {error: "That YouTube link has no video in it."};
}
return {file: url.href};
};
const show = () => {
screen.hidden = !playing || !here || roomPlaying;
if (playing instanceof HTMLMediaElement) {
if (screen.hidden) {
playing.pause();
}
else {
playing.play().catch(() => {});
}
}
};
const stop = () => {
if (playing instanceof HTMLMediaElement) {
playing.pause();
playing.removeAttribute("src");
playing.load();
window.ipc.sendToHost("ownVideo", "");
}
screen.replaceChildren();
playing = null;
show();
};
// the desktop client loads nothing for this page from elsewhere but
// what it is told the player chose (client 1.3.2, app/main.js): it
// says when that address may load. an older client never answers.
const CLIENT_WAIT_MS = 1500;
let cleared = null; // {link, go}
window.ipc.on("ownVideoReady", (event, link) => {
if (cleared && cleared.link === link) {
cleared.go();
}
});
const whenCleared = link => new Promise(resolve => {
const timer = setTimeout(resolve, CLIENT_WAIT_MS);
cleared = {link, go: () => {
clearTimeout(timer);
resolve();
}};
window.ipc.sendToHost("ownVideo", link);
});
const play = text => {
const found = embedFor(String(text || "").trim());
if (!found || found.error) {
said.textContent = found ? found.error : "Paste a link starting with https://";
return;
}
stop();
if (found.frame) {
playing = document.createElement("iframe");
playing.title = "Your video";
playing.allow = "autoplay; encrypted-media; fullscreen";
playing.referrerPolicy = "strict-origin-when-cross-origin";
playing.src = found.frame;
}
else {
const video = document.createElement("video");
playing = video;
video.controls = true;
video.autoplay = true;
video.playsInline = true;
video.addEventListener("error", () => {
said.textContent = "That link did not play. It has to be a video or sound file (.mp4, .webm, .mp3), and the site has to allow it.";
});
whenCleared(found.file).then(() => {
if (playing === video) {
video.src = found.file;
show();
}
});
}
screen.append(playing);
said.textContent = roomPlaying ? "It plays when the theatre's own video stops." : "";
try {
localStorage.setItem(SAVED, input.value.trim());
}
catch (err) {
}
show();
};
opener.addEventListener("click", () => {
box.hidden = !box.hidden;
opener.hidden = !box.hidden;
placeTheatre();
if (!box.hidden) {
if (!input.value) {
try {
input.value = localStorage.getItem(SAVED) || "";
}
catch (err) {
}
}
input.focus();
input.select();
}
});
const close = () => {
box.hidden = true;
opener.hidden = false;
placeTheatre();
said.textContent = "";
};
$("own-video-close").addEventListener("click", close);
$("own-video-stop").addEventListener("click", () => {
stop();
said.textContent = "";
});
box.addEventListener("submit", event => {
event.preventDefault();
play(input.value);
});
input.addEventListener("keydown", event => {
if (event.key === "Escape") {
close();
}
});
return {
// in a theatre or not; out of one, the video is gone.
inTheatre(yes) {
if (yes === here) {
return;
}
here = yes;
if (!here) {
stop();
close();
}
show();
},
roomVideo(on) {
roomPlaying = on;
if (!on) {
said.textContent = "";
}
show();
},
};
})();
// The native theatre sign calls this through ExternalInterface. The
// SWF performs its own permission check before showing the controls.
function ajOpenTheatreControl() {
+139
View File
@@ -475,9 +475,11 @@
<button role="tab" data-tab="masterpieces" data-needs="player.view" aria-selected="false"><span class="icon" aria-hidden="true">&#9635;</span>Masterpieces<span id="masterpiece-count"></span></button>
<button role="tab" data-tab="bans" data-needs="player.view" aria-selected="false"><span class="icon" aria-hidden="true">&#8856;</span>Bans</button>
<button role="tab" data-tab="stats" data-needs="player.view" aria-selected="false"><span class="icon" aria-hidden="true">&#9636;</span>Stats</button>
<button role="tab" data-tab="mod-log" data-needs="staff.log" aria-selected="false" hidden><span class="icon" aria-hidden="true">&#9776;</span>Mod log</button>
<button role="tab" data-tab="review" data-needs="items.approve" aria-selected="false" hidden><span class="icon" aria-hidden="true">&#10004;</span>Review</button>
<button role="tab" data-tab="wear-rules" data-needs="items.restrict" aria-selected="false" hidden><span class="icon" aria-hidden="true">&#9873;</span>Wear rules</button>
<button role="tab" data-tab="items" data-needs="items.create" aria-selected="false" hidden><span class="icon" aria-hidden="true">&#10070;</span>Items</button>
<button role="tab" data-tab="music" data-needs="music.upload" aria-selected="false" hidden><span class="icon" aria-hidden="true">&#9835;</span>Music</button>
</nav>
<button id="sign-out" type="button">Sign out</button>
</aside>
@@ -897,6 +899,31 @@
</section>
</div>
<div data-view="music" hidden>
<section>
<h2>Upload music</h2>
<p class="hint">An MP3 becomes a den music track at once, with no restart: players get it from the item finder (and the shop, if it is on sale) and play it in their dens like the game's own tracks. 44.1 kHz MP3s play best; 15 MB at most.</p>
<div class="actions">
<div class="action">
<h3>The track</h3>
<div class="row"><input id="music-file" type="file" accept=".mp3,audio/mpeg" aria-label="MP3 file"></div>
<div class="row" style="margin-top:8px"><input id="music-name" maxlength="40" placeholder="Name" aria-label="Name"></div>
<div class="row" style="margin-top:8px"><input id="music-cost" type="number" min="0" placeholder="Price in gems (0)" aria-label="Price in gems">
<label class="check"><input type="checkbox" id="music-shop"> On sale in the shop</label></div>
<div class="row" style="margin-top:8px"><button type="button" class="primary" id="music-upload">Upload</button></div>
</div>
</div>
<p class="status" id="music-status" role="status"></p>
</section>
<section>
<h2>Uploaded tracks</h2>
<div class="table-wrap"><table>
<thead><tr><th>Track</th><th class="num">Den item</th><th>Uploaded</th><th class="num">Size</th><th></th></tr></thead>
<tbody id="music-list"></tbody>
</table></div>
<div class="empty" id="no-music" hidden>None yet.</div>
</section>
</div>
<div data-view="items" hidden>
<section>
<h2 id="item-form-title">Make an item</h2>
@@ -966,6 +993,17 @@
</section>
</div>
<div data-view="mod-log" hidden>
<section>
<h2>What staff did</h2>
<div class="table-wrap"><table>
<thead><tr><th>When</th><th>Who</th><th>What</th><th>Player</th><th>Detail</th></tr></thead>
<tbody id="mod-log"></tbody>
</table></div>
<div class="empty" id="no-mod-log" hidden>Nothing yet.</div>
</section>
</div>
<div data-view="bans" hidden>
<section>
<h2>Banned and silenced</h2>
@@ -2733,6 +2771,91 @@
$("server-updated").textContent = `Updated ${new Date(Number(data.now || Date.now())).toLocaleTimeString()}.`;
};
// ---- music uploaded by staff (lib/custommusic.js): an MP3 made a den
// music track, which players get from the item finder at once
const MUSIC = "/mod/api/music";
let musicShown = "";
const musicCall = async (query, body) => {
try {
const response = await fetch(`${MUSIC}${query}`, {method: "POST", headers: {"Content-Type": "audio/mpeg"}, body});
return await response.json().catch(() => ({error: "That did not work."}));
}
catch (err) {
return {error: "The server did not answer."};
}
};
const renderMusic = data => {
const tracks = data.tracks || [];
// drawn again only when something changed: a track being listened to keeps playing
const shown = JSON.stringify(tracks);
if (shown === musicShown) {
return;
}
musicShown = shown;
$("no-music").hidden = tracks.length > 0;
$("music-list").replaceChildren(...tracks.map(track => {
const row = el("tr");
const name = el("td");
const player = el("audio");
player.controls = true;
player.preload = "none";
player.src = `${MUSIC}?play=${track.id}`;
player.style.cssText = "display:block;margin-top:6px;height:32px;max-width:260px";
name.append(el("strong", track.name), player);
const actions = el("td");
actions.append(button("Delete", async () => {
if (!confirm(`Delete "${track.name}"? It is taken from every player who has it. This cannot be undone.`)) {
return;
}
const result = await musicCall(`?delete=${track.id}`, new Uint8Array(0));
setStatus($("music-status"), result.ok || result.error || "That did not work.", !result.ok);
await loadMusic();
}, "danger"));
row.append(name, el("td", String(track.id), "num"), el("td", `${when(track.createdAt)} · ${track.createdBy}${track.inShop ? ` · on sale, ${track.cost} gems` : ""}`),
el("td", `${(track.bytes / 1048576).toFixed(1)} MB`, "num"), actions);
return row;
}));
};
const loadMusic = async () => {
try {
const response = await fetch(MUSIC);
const data = await response.json().catch(() => ({}));
if (response.ok) {
renderMusic(data);
}
}
catch (err) {
// shown again with the next refresh
}
};
// the name from the file's, until one is typed
$("music-file").addEventListener("change", () => {
const file = $("music-file").files[0];
if (file && !$("music-name").value.trim()) {
$("music-name").value = file.name.replace(/\.mp3$/i, "").replace(/[_]+/g, " ").slice(0, 40);
}
});
$("music-upload").addEventListener("click", async () => {
const file = $("music-file").files[0];
if (!file || !$("music-name").value.trim()) {
setStatus($("music-status"), file ? "Give the track a name." : "Choose an MP3 first.", true);
return;
}
$("music-upload").disabled = true;
setStatus($("music-status"), "Uploading...");
const query = `?name=${encodeURIComponent($("music-name").value.trim())}&cost=${encodeURIComponent($("music-cost").value || 0)}&inShop=${$("music-shop").checked ? 1 : 0}`;
const result = await musicCall(query, new Uint8Array(await file.arrayBuffer()));
$("music-upload").disabled = false;
setStatus($("music-status"), result.ok || result.error || "That did not work.", !result.ok);
if (result.ok) {
for (const id of ["music-file", "music-name", "music-cost"]) {
$(id).value = "";
}
$("music-shop").checked = false;
}
await loadMusic();
});
const refresh = async () => {
clearTimeout(timer);
if (!signedIn) {
@@ -2850,6 +2973,19 @@
else if (shown === "stats") {
await window.statsView.load(api);
}
else if (shown === "mod-log") {
const result = await api("modlog");
if (result.ok) {
$("mod-log").replaceChildren(...result.data.log.map(entry => {
const row = el("tr");
const detail = el("td", entry.detail);
detail.style.whiteSpace = "normal";
row.append(el("td", when(entry.at)), el("td", entry.by), el("td", entry.action), el("td", entry.target || "—"), detail);
return row;
}));
$("no-mod-log").hidden = result.data.log.length > 0;
}
}
else if (shown === "bans") {
const [result, hits] = await Promise.all([api("bans"), api("filterhits")]);
if (result.ok) {
@@ -2868,6 +3004,9 @@
else if (shown === "wear-rules") {
await loadWearRules();
}
else if (shown === "music") {
await loadMusic();
}
else if (shown === "items") {
const result = await api("items");
if (result.ok) {
+5
View File
@@ -7,11 +7,13 @@ const accounts = require("./lib/accounts.js");
const bans = require("./lib/bans.js");
const devices = require("./lib/devices.js");
const discord = require("./lib/discord.js");
const discordBot = require("./lib/discordbot.js");
const chatlog = require("./lib/chatlog.js");
const modlog = require("./lib/modlog.js");
const retention = require("./lib/retention.js");
const colours = require("./lib/colours.js");
const customItems = require("./lib/customitems.js");
const customMusic = require("./lib/custommusic.js");
const config = require("./config.js");
const defpacks = require("./lib/defpacks.js");
const http = require("./lib/http.js");
@@ -41,6 +43,7 @@ const main = async () => {
accounts.startBackups();
colours.load();
customItems.load();
customMusic.load();
reports.load();
support.load();
bans.load();
@@ -54,11 +57,13 @@ const main = async () => {
panel.load();
await http.start();
await sfs.start(world);
discordBot.startup();
console.log(`[server] ready at ${config.baseUrl}`);
};
// stopped on purpose: what is waiting to be written is written first.
const stop = code => {
discordBot.shutdown();
stats.flush();
try {
accounts.flush();
+235 -3
View File
@@ -22,6 +22,7 @@ package
import createAccountFlow.CreateAccount;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Shape;
@@ -340,6 +341,181 @@ package
gMainFrame.stage.addEventListener("keyDown",onFinderKey,false,1000);
startEmojiButton();
placeTheatreButton();
gMainFrame.stage.addEventListener("enterFrame",reportTheatreScreen,false,0,true);
}
// where the theatre's screen is, for game.html to lay a web video over
// it exactly: the original player's 512 by 288 at the top left of the
// theatre layer's videoLayer (movie.VideoPlayerOSMF), in stage
// coordinates (900 by 550; the page scales them as "showAll" does).
// "x,y,width,height", or "" with no theatre screen shown; told only
// when it changes, as the room zooms and scrolls under it.
//
// a web video is always drawn over the whole game, so it also gets
// where the game draws something over the screen (the HUD, the buddy
// list, a Jammer Wall, chat balloons): "x,y,width,height|columns|rows",
// a hex row of bits per SCREEN_CELL stage pixels, top to bottom, over
// the screen and SCREEN_BELOW pixels under it (the page's own button
// sits there). the page cuts those cells out of the video.
private static const THEATRE_SCREEN_W:Number = 512;
private static const THEATRE_SCREEN_H:Number = 288;
private static const SCREEN_CELL:Number = 4;
private static const SCREEN_BELOW:Number = 44;
private static const SCREEN_COVER_EVERY:int = 4; // frames between looks
private static const SCREEN_COVER_ALPHA:uint = 64; // of 255: drawn on, as far as the video goes
private static var _theatreScreenTold:String = null;
private static var _theatreCover:String = "";
private static var _theatreCoverFrame:int = 0;
private static function reportTheatreScreen(param1:Event = null) : void
{
var _loc2_:String = "";
var _loc3_:Object = null;
var _loc4_:DisplayObject = null;
var _loc5_:Point = null;
var _loc6_:Point = null;
try
{
_loc3_ = RoomManagerWorld.instance != null ? RoomManagerWorld.instance.theaterWindow : null;
_loc4_ = _loc3_ != null && _loc3_.hasOwnProperty("videoLayer") ? _loc3_.videoLayer as DisplayObject : null;
if(_loc4_ != null && shownOnStage(_loc4_))
{
_loc5_ = _loc4_.localToGlobal(new Point(0,0));
_loc6_ = _loc4_.localToGlobal(new Point(THEATRE_SCREEN_W,THEATRE_SCREEN_H));
_loc2_ = [_loc5_.x,_loc5_.y,_loc6_.x - _loc5_.x,_loc6_.y - _loc5_.y].map(function(param1:Number, ... rest):String
{
return String(Math.round(param1 * 10) / 10);
}).join(",");
if(++_theatreCoverFrame >= SCREEN_COVER_EVERY || _theatreScreenTold == null || _theatreScreenTold.indexOf(_loc2_) != 0)
{
_theatreCoverFrame = 0;
_theatreCover = theatreCover(_loc3_ as DisplayObject,_loc5_.x,_loc5_.y,_loc6_.x - _loc5_.x,_loc6_.y - _loc5_.y);
}
if(_theatreCover != "")
{
_loc2_ += "|" + _theatreCover;
}
}
}
catch(e:Error)
{
_loc2_ = "";
}
if(_loc2_ == _theatreScreenTold || !ExternalInterface.available)
{
return;
}
_theatreScreenTold = _loc2_;
try
{
ExternalInterface.call("ajTheatreScreen",_loc2_);
}
catch(e:Error)
{
}
}
// what is drawn over the theatre screen, as above: the game's windows
// and buttons, and the room's chat balloons, drawn small, cell by cell.
// the rest is hidden for the moment of drawing, in between two frames:
// the screen, what lies under it, and the room itself (its seats and
// floor are drawn above the screen, and are no reason for the video or
// its button to step aside). "" for nothing, or when the game will not
// be drawn.
private static function theatreCover(param1:DisplayObject, param2:Number, param3:Number, param4:Number, param5:Number) : String
{
var _loc6_:Array = [];
var _loc7_:DisplayObject = param1;
var _loc8_:DisplayObjectContainer = null;
var _loc9_:int = 0;
var _loc10_:DisplayObject = null;
var _loc11_:int = Math.max(1,Math.ceil(param4 / SCREEN_CELL));
var _loc12_:int = Math.max(1,Math.ceil((param5 + SCREEN_BELOW) / SCREEN_CELL));
var _loc13_:BitmapData = null;
var _loc14_:Array = [];
var _loc15_:Boolean = false;
var _loc16_:int = 0;
var _loc17_:int = 0;
var _loc18_:int = 0;
var _loc19_:String = null;
try
{
if(_loc7_.visible)
{
_loc7_.visible = false;
_loc6_.push(_loc7_);
}
while(_loc7_.parent != null)
{
_loc8_ = _loc7_.parent;
_loc9_ = _loc8_.getChildIndex(_loc7_);
while(--_loc9_ >= 0)
{
_loc10_ = _loc8_.getChildAt(_loc9_);
if(_loc10_.visible)
{
_loc10_.visible = false;
_loc6_.push(_loc10_);
}
}
_loc7_ = _loc8_;
}
_loc8_ = RoomManagerWorld.instance.layerManager.bkg;
_loc9_ = _loc8_.numChildren;
while(--_loc9_ >= 0)
{
_loc10_ = _loc8_.getChildAt(_loc9_);
if(_loc10_ != RoomManagerWorld.instance.layerManager.room_chat && _loc10_.visible)
{
_loc10_.visible = false;
_loc6_.push(_loc10_);
}
}
_loc13_ = new BitmapData(_loc11_,_loc12_,true,0);
_loc13_.draw(gMainFrame.stage,new Matrix(1 / SCREEN_CELL,0,0,1 / SCREEN_CELL,-param2 / SCREEN_CELL,-param3 / SCREEN_CELL));
}
catch(e:Error)
{
if(_loc13_ != null)
{
_loc13_.dispose();
_loc13_ = null;
}
}
for each(_loc10_ in _loc6_)
{
_loc10_.visible = true;
}
if(_loc13_ == null)
{
return "";
}
_loc16_ = 0;
while(_loc16_ < _loc12_)
{
_loc19_ = "";
_loc17_ = 0;
while(_loc17_ < _loc11_)
{
_loc18_ = 0;
_loc9_ = 0;
while(_loc9_ < 4)
{
if(_loc17_ + _loc9_ < _loc11_ && _loc13_.getPixel32(_loc17_ + _loc9_,_loc16_) >>> 24 >= SCREEN_COVER_ALPHA)
{
_loc18_ |= 8 >> _loc9_;
_loc15_ = true;
}
_loc9_++;
}
_loc19_ += _loc18_.toString(16);
_loc17_ += 4;
}
_loc14_.push(_loc19_);
_loc16_++;
}
_loc13_.dispose();
return _loc15_ ? _loc11_ + "|" + _loc14_.join(",") : "";
}
public static function openTool(param1:int) : void
@@ -608,6 +784,14 @@ package
return settingOf(9006) != 1;
}
// the pet chooser's "play as your pet" switch (gui.PetInventory): the
// pet that is out stands in for the avatar in any room. user var 9008,
// which the server also reads to show the pet form to everyone.
public static function petFormOn() : Boolean
{
return settingOf(9008) == 1;
}
// an item's picture version, or null for none or with them hidden
private static function artOf(param1:String, param2:int) : String
{
@@ -1542,6 +1726,7 @@ package
// 9007 Performance profile: 1 Low-end, 2 High, unset Balanced. A
// profile changes only optional rendering work, never the
// game's native 24 FPS (which would slow its animations).
// 9008 Play as your pet (gui.PetInventory, lib/pets.js): 1 on.
private static var _smoothTimer:Timer;
@@ -2289,8 +2474,55 @@ package
drawChatFilter();
}
// the server's rules, word for word as the owner gave them
private static const RULES_HTML:String = "<font size=\"16\" color=\"#563421\"><b>[1] Be Respectful / Have Common Sense</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>This is quite self explanatory. Be kind, treat people how you would want to be treated. If someone is uncomfortable with something you are saying and or doing, please respect that of them and do not argue against it, even if it may seem ridiculous in your eyes.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[2] No Direct Harassment / Bullying</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>If you are being disrespectful towards another person, Moderators have every right to punish you. Please don't be an asshole. Thank you.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[3] Keep Personal Information for Yourself.</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>As friendly that people may seem on this platform, never share personal identifying details with ANYONE. This leads to a lot of unsafe situations. Please be safe and responsible with the information you give to other people.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[4] Keep Drama OUT</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>If you have personal issues with another person, it is not our responsibility unless said person is confirmed to be problematic towards something against the rules of our server. Please do not bring arguments into our public chat, you will be muted until things clear up. Keep it in DMS.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[5] No NSFW!</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>NSFW and Suggestive Content are entirely banned from the server, period. We do not want to be a place that allows predatory behavior to fester. If you are unsure of what specific details this goes under, feel free to ask in a ticket.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[8] Report Any Issues</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>Issues can be anything from harassment, a person you are uncomfortable with, bugs, etc. Moderators are always happy to help!</b></font><br><br><font size=\"13\" color=\"#6E4A2E\"><b>Burrow gives players more freedom than the original game, including free chat. If you do not want to see certain content you may utilise the client side chat filter and block players, which has an option to completely hide them on your side.</b></font><br><br><font size=\"13\" color=\"#6E4A2E\"><b>These options are found in the in-game settings or player cards.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>burrow.moe/terms</b></font>";
// the rules come from the server's data/rules.txt (GET /rules.txt), read
// each time the window opens, so they change without a new client: a
// line starting "# " is a heading, the rest is shown as it is written.
private static const RULES_HEADING:String = "<font size=\"16\" color=\"#563421\"><b>";
private static const RULES_BODY:String = "<font size=\"13\" color=\"#6E4A2E\"><b>";
private static function rulesHtml(param1:String) : String
{
var _loc2_:Array = param1.replace(/\r/g,"").split("\n");
var _loc3_:Array = [];
var _loc4_:String = null;
var _loc5_:int = 0;
while(_loc5_ < _loc2_.length)
{
_loc4_ = String(_loc2_[_loc5_]).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
if(_loc4_.indexOf("# ") == 0)
{
_loc3_.push(RULES_HEADING + _loc4_.substr(2) + "</b></font>");
}
else
{
_loc3_.push(RULES_BODY + _loc4_ + "</b></font>");
}
_loc5_++;
}
return _loc3_.join("<br>");
}
private function loadRules() : void
{
var _loc1_:URLLoader = new URLLoader();
_rulesText.htmlText = rulesHtml("Loading...");
_loc1_.addEventListener("complete",onRulesLoaded);
_loc1_.addEventListener("ioError",onRulesFailed);
_loc1_.addEventListener("securityError",onRulesFailed);
_loc1_.load(new URLRequest(gMainFrame.clientInfo.websiteURL + "rules.txt?t=" + new Date().getTime()));
}
private function onRulesLoaded(param1:Event) : void
{
_rulesText.htmlText = rulesHtml(String(URLLoader(param1.currentTarget).data));
_rulesText.scrollV = 1;
}
private function onRulesFailed(param1:Event) : void
{
_rulesText.htmlText = rulesHtml("The rules could not be loaded. Try again in a moment.");
}
private var _rulesWin:Sprite;
@@ -2338,7 +2570,6 @@ package
_rulesText.y = -158;
_rulesText.width = 462;
_rulesText.height = 338;
_rulesText.htmlText = RULES_HTML;
_loc5_ = GETDEFINITIONBYNAME("arrow_r_btnContOld");
_loc5_.rotation = -90;
_loc5_.x = 236;
@@ -2370,6 +2601,7 @@ package
_rulesWin.visible = param1;
if(param1)
{
loadRules();
_rulesText.scrollV = 1;
setChildIndex(_rulesWin,numChildren - 1);
}
-13
View File
@@ -700,19 +700,6 @@ package gui
{
var _loc2_:WorldPet = null;
param1.stopPropagation();
// Outside a play-as-your-pet event this button is the personal
// pet-form switch. The server echoes the change to everybody in
// the room, so this is not merely a local visual effect.
if(!GuiManager.isBeYourPetRoom())
{
if(AvatarManager.playerAvatarWorldView && AvatarManager.playerAvatarWorldView.getActivePet())
{
UserCommXtCommManager.sendPetPlayerMode(!GuiManager.isPlayingAsPet());
}
actionBtn.dispatchEvent(new MouseEvent("mouseDown"));
param1.currentTarget.downToUpState();
return;
}
if(AvatarManager.playerAvatarWorldView)
{
_loc2_ = AvatarManager.playerAvatarWorldView.getActivePet();
+76 -18
View File
@@ -65,9 +65,9 @@ package avatar
private static const SLIDE_FRAME_TIME:Number = 41.666666666666664;
// name tag badges everyone sees, buddy or not, as the game shows its
// News Crew camera (NameBar.isVIPBadge): the Owner, Moderator and
// Verified badges of lib/badges.js, by their def ids.
private static const PUBLIC_BADGE_IDS:Array = [63,64,76];
// News Crew camera (NameBar.isVIPBadge): the Owner, Moderator,
// Developer and Verified badges of lib/badges.js, by their def ids.
private static const PUBLIC_BADGE_IDS:Array = [63,64,66,76];
private static const GLOW_LAND_DEFAULT_COLOR:int = 5586479;
@@ -335,6 +335,12 @@ package avatar
private var _currPetName:String;
private var _shouldShowPetOnly:Boolean;
// the pet chooser's switch as last heard for this avatar (type-13 user
// communication), and the pet last set, to make it again in either form
private var _petPlayerMode:Boolean;
private var _petArgs:Array;
private var _emitParticles:Boolean;
@@ -552,7 +558,7 @@ package avatar
_loc12_ = 1;
}
_chatBalloon = GETDEFINITIONBYNAME("ChatBalloonAsset",false);
_chatBalloon.init(_avatar.avTypeId,AvatarUtility.getAvatarEmoteBgOffset,false,_loc12_,RoomManagerWorld.instance.layerManager.bkg.scaleX,SBTextField,onChatBallonAdventureDown,onChatBalloonPVPDown);
_chatBalloon.init(_avatar.avTypeId,emoteBgOffset,false,_loc12_,RoomManagerWorld.instance.layerManager.bkg.scaleX,SBTextField,onChatBallonAdventureDown,onChatBalloonPVPDown);
_chatLayer.addChild(_chatBalloon);
_moving = 0;
_lastMoveAngle = 2;
@@ -605,7 +611,7 @@ package avatar
_hudViewHolder.mouse.gotoAndStop(offScreenDefaultMouseFrameLabel());
}
}
_shouldShowPetOnly = GuiManager.isBeYourPetRoom() || userId == AvatarManager.playerSfsUserId && GuiManager.isPlayingAsPet();
_shouldShowPetOnly = GuiManager.isBeYourPetRoom() || (userId == AvatarManager.playerSfsUserId ? GuiManager.isPlayingAsPet() : _petPlayerMode);
if(_shouldShowPetOnly)
{
_layerAnim.alpha = 0;
@@ -2066,6 +2072,7 @@ package avatar
public function setActivePet(param1:Number, param2:uint, param3:uint, param4:uint, param5:String, param6:int, param7:int, param8:int, param9:int = 0) : void
{
_petArgs = [param1,param2,param3,param4,param5,param6,param7,param8,param9];
if(_pet)
{
if(_pet.parent == this)
@@ -2094,6 +2101,17 @@ package avatar
{
_splash.showShadow(true);
}
// another pet out in the pet form: the HUD shows the new one
if(_shouldShowPetOnly && userId == AvatarManager.playerSfsUserId)
{
GuiManager.setPersonalPetMode(true);
}
}
// a pet that cannot come into this room leaves the avatar shown
if(_shouldShowPetOnly && !_pet && !GuiManager.isBeYourPetRoom())
{
_shouldShowPetOnly = false;
showPetForm();
}
}
@@ -2102,8 +2120,30 @@ package avatar
// own state instead of asking the room-wide GuiManager predicate.
public function setPetPlayerMode(param1:Boolean) : void
{
var _loc2_:Boolean = param1 && _pet != null;
_shouldShowPetOnly = _loc2_ || GuiManager.isBeYourPetRoom();
var _loc2_:Boolean = false;
_petPlayerMode = param1;
_loc2_ = GuiManager.isBeYourPetRoom() || param1 && _petArgs != null && _petArgs[1] != 0;
if(_loc2_ != _shouldShowPetOnly)
{
_shouldShowPetOnly = _loc2_;
// WorldPet takes its size and place from the form when it is
// made, so the pet is made again
if(_petArgs != null)
{
setActivePet.apply(this,_petArgs);
}
}
showPetForm();
if(userId == AvatarManager.playerSfsUserId)
{
GuiManager.setPersonalPetMode(_shouldShowPetOnly);
}
}
// the avatar or its pet, as _shouldShowPetOnly says
private function showPetForm() : void
{
var _loc1_:UserInfo = null;
_layerAnim.alpha = _shouldShowPetOnly ? 0 : 1;
_layerAnim.avatarEnabled = !_shouldShowPetOnly;
if(_shouldShowPetOnly && _pet)
@@ -2117,12 +2157,32 @@ package avatar
else
{
_splash.showShadow(true);
_namebar.setAvName(_avatar.avName);
}
if(userId == AvatarManager.playerSfsUserId)
{
GuiManager.setPersonalPetMode(_loc2_);
_loc1_ = gMainFrame.userInfo.getUserInfoByUserName(_avatar.userName);
_namebar.setAvName(_avatar,Utility.isSettingOn(MySettings.SETTINGS_USERNAME_BADGE),_loc1_);
}
placeChatBalloon();
updateChatBallonBgOffsets();
}
// the pet stands in for this avatar: the party's or quest's form, or
// the pet chooser's switch (WorldPet asks)
public function isPetForm() : Boolean
{
return _shouldShowPetOnly;
}
// chat balloons and emotes sit over the pet in its form, as the
// party's do (AvatarUtility's pet offsets)
private function placeChatBalloon() : void
{
var _loc1_:Point = _shouldShowPetOnly ? new Point(10,-80) : AvatarUtility.getAvatarChatOffset(_avatar.avTypeId);
_chatBalloon.x = this.x + _loc1_.x;
_chatBalloon.y = this.y + _loc1_.y;
}
private function emoteBgOffset(param1:int) : Point
{
return _shouldShowPetOnly ? new Point(-5,-25) : AvatarUtility.getAvatarEmoteBgOffset(param1);
}
public function getActivePet() : WorldPet
@@ -2281,9 +2341,7 @@ package avatar
param2 *= _scale.y;
this.x = param1;
this.y = param2;
var _loc3_:Point = AvatarUtility.getAvatarChatOffset(_avatar.avTypeId);
_chatBalloon.x = this.x + _loc3_.x;
_chatBalloon.y = this.y + _loc3_.y;
placeChatBalloon();
if(_avSwitchedNPC)
{
_avSwitchedNPC.x = param1;
@@ -2359,9 +2417,9 @@ package avatar
{
_hudViewHolder.mouse.gotoAndStop(offScreenDefaultMouseFrameLabel());
}
if(GuiManager.isBeYourPetRoom())
_loc7_ = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(userName,perUserAvId);
if(_shouldShowPetOnly && _loc7_ && _loc7_.currPet)
{
_loc7_ = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(userName,perUserAvId);
_hudAvtOrPetView = new GuiPet(_loc7_.currPet.createdTs,0,_loc7_.currPet.lBits,_loc7_.currPet.uBits,_loc7_.currPet.eBits,_loc7_.currPet.type,_loc7_.currPet.name,_loc7_.currPet.personalityDefId,_loc7_.currPet.favoriteToyDefId,_loc7_.currPet.favoriteFoodDefId,onHudAvtOrPetView);
}
else
@@ -2479,7 +2537,7 @@ package avatar
var _loc3_:Number = NaN;
if(_hudAvtOrPetView)
{
if(GuiManager.isBeYourPetRoom())
if(_hudAvtOrPetView is GuiPet)
{
_hudAvtOrPetView.y = 15;
}
+5 -11
View File
@@ -181,10 +181,6 @@ package gui
private static var _petInventory:PetInventory;
// A player's voluntary pet form. Party and quest pet forms remain
// room-wide and are still reported by isBeYourPetRoom().
private static var _personalPetMode:Boolean = false;
private static var _joeyPopup:MovieClip;
private static var _secondaryJoeyPopup:MovieClip;
@@ -2616,7 +2612,7 @@ package gui
{
mainHud.charWindow.charLayer.removeChildAt(0);
}
if(isBeYourPetRoom())
if(isPlayingAsPet())
{
_loc1_ = PetManager.myActivePet;
if(_loc1_)
@@ -2911,18 +2907,16 @@ package gui
return QuestManager.isBeYourPetQuest() || PartyManager.isBeYourPetParty();
}
// A player's own pet form: the party's and the quest's for everyone in
// the room, or the pet chooser's switch with a pet out.
public static function isPlayingAsPet() : Boolean
{
return _personalPetMode || isBeYourPetRoom();
return isBeYourPetRoom() || AJClient.petFormOn() && PetManager.myActivePet != null;
}
// the player's own avatar came into or out of its pet form
public static function setPersonalPetMode(param1:Boolean) : void
{
if(_personalPetMode == param1)
{
return;
}
_personalPetMode = param1;
if(mainHud)
{
showHudAvt();
+74
View File
@@ -3,6 +3,7 @@ package gui
import Party.PartyManager;
import adoptAPet.AdoptAPetManager;
import avatar.AvatarManager;
import avatar.UserCommXtCommManager;
import com.sbi.analytics.SBTracker;
import com.sbi.popup.SBOkPopup;
import com.sbi.popup.SBYesNoPopup;
@@ -43,6 +44,12 @@ package gui
private var _inventoryMC:MovieClip;
private var _loadingMediaHelper:MediaHelper;
// "play as your pet": the settings menu's on/off switch, in any room
// but a Play-As-Your-Pet party's (AJClient.petFormOn)
private var _petFormSwitch:MovieClip;
private var _petFormOn:Boolean;
private var _loadingSpiralBig:LoadingSpiral;
@@ -222,6 +229,7 @@ package gui
_guiLayer.addChild(_inventoryMC);
DarkenManager.darken(_inventoryMC);
createItemWindows();
addPetFormSwitch();
addEventListeners();
if(_openCheckListImmediately)
{
@@ -246,6 +254,58 @@ package gui
}
// A double click on the big pet's name lets the player type another.
// the switch sits at the top left of the pet's picture, across from
// the certificate. on, whichever pet is out stands in for the avatar,
// for everyone (the server keeps it with the user vars and tells the
// room: UserCommXtCommManager type 13).
private function addPetFormSwitch() : void
{
var _loc1_:MovieClip = null;
if(GuiManager.isBeYourPetRoom())
{
return;
}
_loc1_ = GETDEFINITIONBYNAME("mySettingsToggle",false);
_petFormSwitch = _loc1_.toggleBtn;
_loc1_.removeChild(_petFormSwitch);
_petFormSwitch.x = 78;
_petFormSwitch.y = -143;
_petFormSwitch.buttonMode = true;
_petFormSwitch.useHandCursor = true;
_petFormSwitch.toggleBtn.toggleKnob.gotoAndStop("up");
_petFormSwitch.toggleBtn.toggleBG.gotoAndStop("up");
_petFormOn = AJClient.petFormOn();
_petFormSwitch.toggleBtn.gotoAndStop(_petFormOn ? "startingOn" : "startingOff");
LocalizationManager.translateId(_petFormSwitch.toggleBtn.valueTxt.onTxt,6324);
LocalizationManager.translateId(_petFormSwitch.toggleBtn.valueTxt.offTxt,6322);
_inventoryMC.addChild(_petFormSwitch);
}
private function onPetFormSwitch(param1:MouseEvent) : void
{
param1.stopPropagation();
_petFormOn = !_petFormOn;
_petFormSwitch.toggleBtn.gotoAndPlay(_petFormOn ? "on" : "off");
UserCommXtCommManager.sendPetPlayerMode(_petFormOn);
}
private function onPetFormSwitchOver(param1:MouseEvent) : void
{
param1.stopPropagation();
_petFormSwitch.toggleBtn.toggleBG.gotoAndStop("over");
_petFormSwitch.toggleBtn.toggleKnob.gotoAndStop("over");
GuiManager.toolTip.init(_petFormSwitch,"Play as your pet",58,-10);
GuiManager.toolTip.startTimer(param1);
}
private function onPetFormSwitchOut(param1:MouseEvent) : void
{
param1.stopPropagation();
_petFormSwitch.toggleBtn.toggleBG.gotoAndStop("up");
_petFormSwitch.toggleBtn.toggleKnob.gotoAndStop("up");
GuiManager.toolTip.resetTimerAndSetVisibility();
}
private function onPetRenamed(param1:String) : void
{
var _loc2_:int = 0;
@@ -852,6 +912,12 @@ package gui
_inventoryMC.salonBtn.addEventListener("mouseDown",onSalonBtn,false,0,true);
_inventoryMC.checklistBtn.addEventListener("mouseDown",onChecklistBtn,false,0,true);
_inventoryMC.certBtn.addEventListener("mouseDown",onCertBtn,false,0,true);
if(_petFormSwitch)
{
_petFormSwitch.addEventListener("mouseDown",onPetFormSwitch,false,0,true);
_petFormSwitch.addEventListener("rollOver",onPetFormSwitchOver,false,0,true);
_petFormSwitch.addEventListener("rollOut",onPetFormSwitchOut,false,0,true);
}
}
private function removeEventListeners() : void
@@ -866,6 +932,14 @@ package gui
_inventoryMC.salonBtn.removeEventListener("mouseDown",onSalonBtn);
_inventoryMC.checklistBtn.removeEventListener("mouseDown",onChecklistBtn);
_inventoryMC.certBtn.removeEventListener("mouseDown",onCertBtn);
if(_petFormSwitch)
{
_petFormSwitch.removeEventListener("mouseDown",onPetFormSwitch);
_petFormSwitch.removeEventListener("rollOver",onPetFormSwitchOver);
_petFormSwitch.removeEventListener("rollOut",onPetFormSwitchOut);
GuiManager.toolTip.resetTimerAndSetVisibility();
_petFormSwitch = null;
}
}
}
}
+1 -1
View File
@@ -725,7 +725,7 @@ package avatar
{
if(AvatarManager.avatarViewList[_loc19_])
{
AvatarManager.avatarViewList[_loc19_].setPetPlayerMode(_loc2_ == "on");
AvatarManager.avatarViewList[_loc19_].setPetPlayerMode(param1[3] == "on");
}
}
else
+421
View File
@@ -0,0 +1,421 @@
package pet
{
import avatar.AvatarWorldView;
import avatar.UserCommXtCommManager;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.geom.Matrix;
import gui.GuiManager;
public class WorldPet extends PetBase
{
public static const ANIM_IDLE:int = 0;
public static const ANIM_MOVE:int = 1;
public static const ANIM_IDLE_UP:int = 2;
public static const ANIM_MOVE_UP:int = 3;
public static const ANIM_CLICK:int = 4;
public static const ANIM_IDLE_WATER:int = 10;
public static const ANIM_IDLE_MUD:int = 20;
public static const ANIM_DANCE:int = 31;
public static const ANIM_SLEEP_OR_DIVE:int = 32;
public static const ANIM_HOP_OR_SWIRL:int = 33;
public static const ANIM_PLAY:int = 34;
public static const ANIM_SIT_OR_POSE:int = 35;
public static const ACTION_CLICK:int = 0;
public static const ACTION_SPARKLE:int = 1;
public static const PET_SPARKLE_TIME:int = 7200;
public static var _actionLookup:Array = [{
"name":":dance:",
"animId":31
},{
"name":":sleep:",
"animId":32
},{
"name":":dive:",
"animId":32
},{
"name":":hop:",
"animId":33
},{
"name":":swirl:",
"animId":33
},{
"name":":play:",
"animId":34
},{
"name":":sit:",
"animId":35
},{
"name":":sitNW:",
"animId":35
},{
"name":":sitSW:",
"animId":35
},{
"name":":sitSE:",
"animId":35
},{
"name":":sitNE:",
"animId":35
},{
"name":":pose:",
"animId":35
},{
"name":":poseLeft:",
"animId":35
},{
"name":":poseRight:",
"animId":35
}];
private var _parent:AvatarWorldView;
private var _mode:int;
private var _x:int;
private var _y:int;
private var _targetX:int;
private var _targetY:int;
private var _bNewTarget:Boolean;
private var _dirX:Number;
private var _dirY:Number;
private var _speed:Number;
private var _lastAnim:int;
private var _bFlip:Boolean;
private var _bBack:Boolean;
private var _bUpdateState:Boolean;
private var _parentLastX:Number;
private var _parentLastY:Number;
private var _bSpecialMove:Boolean;
private var _petLoaded:Boolean;
private var _sparkle:int;
private var _offsetX:int = 100;
private var _offsetY:int = -50;
private var _maxSpeed:Number = 1;
private var _accel:Number = 0.03;
private var _scale:Number = 1;
private var _minX:Number = -70;
private var _maxX:Number = 55;
private var _airPetYOffest:Number = -80;
private var _oceanPetXOffset:Number = 55;
private var _petLandLowXOffset:Number = 30;
public function WorldPet(param1:AvatarWorldView, param2:Number, param3:uint, param4:uint, param5:uint, param6:uint, param7:uint, param8:uint, param9:int = 0)
{
super(param2,param3,param4,param5,param6,param7,param8,onPetLoaded);
_sparkle = param9;
_parent = param1;
_targetX = 0;
_bNewTarget = true;
_mode = 1;
_lastAnim = -1;
_bUpdateState = true;
_bFlip = false;
_bBack = false;
_bSpecialMove = false;
_parent.addChild(this);
if(param1.userName.toLowerCase() == gMainFrame.server.userName.toLowerCase() && !_parent.isPetForm())
{
this.addEventListener("mouseDown",onClick,false,0,true);
}
else
{
this.mouseChildren = false;
this.mouseEnabled = false;
}
if(isEggAndHasNotHatched || (getType() == 0 || getType() == 2 || getType() == 4))
{
if(_parent.isPetForm())
{
_y = -5;
GuiManager.actionMgr.grayOutPetDanceBtn(false);
}
else
{
_y = 0;
}
}
else
{
GuiManager.actionMgr.grayOutPetDanceBtn(true);
if(_parent.isPetForm())
{
_y = -5;
}
else
{
_y = _airPetYOffest;
}
}
_parentLastX = _parent.x;
_parentLastY = _parent.y;
if(_parent.isPetForm())
{
_minX = 25;
_maxX = -30;
_x = _maxX;
_parentLastX = 0;
}
else
{
if(getType() == 2)
{
_minX -= _oceanPetXOffset;
_maxX += _oceanPetXOffset;
}
else if(getType() == 0)
{
if(param1.avTypeId != 5)
{
_minX -= _petLandLowXOffset;
}
}
_x = 0;
}
_targetX = 0;
}
override public function destroy() : void
{
super.destroy();
this.removeEventListener("mouseDown",onClick);
}
public function heartbeat(param1:int, param2:Boolean) : void
{
var _loc5_:int = 0;
var _loc3_:Matrix = null;
var _loc4_:int = 0;
if(_content && _parent && !_parent.isOffScreen)
{
if(_parent.isPetForm())
{
if(_parentLastX != _parent.x)
{
if(_parent.x > _parentLastX)
{
if(!_bFlip)
{
_parent.flipSplash(true);
_bFlip = true;
_x = _minX;
}
}
else if(_bFlip)
{
_parent.flipSplash(false);
_bFlip = false;
_x = _maxX;
}
_parentLastX = _parent.x;
}
}
else
{
if(_targetX == 0)
{
_targetX = _parent.hFlip ? _minX : _maxX;
}
if(_parentLastX != _parent.x)
{
_bFlip = _parent.x > _parentLastX ? true : false;
if(Math.abs(_parentLastX - _parent.x) > 13)
{
_targetX = _bFlip ? _minX : _maxX;
}
_parentLastX = _parent.x;
}
if(_parentLastY != _parent.y)
{
_bBack = _parent.y < _parentLastY - 10 ? true : false;
_parentLastY = _parent.y;
}
if(_x > _targetX)
{
_x -= 10;
if(_x <= _targetX)
{
_x = _targetX;
}
_bFlip = _x == _targetX ? true : false;
}
if(_x < _targetX)
{
_x += 10;
if(_x > _targetX)
{
_x = _targetX;
}
_bFlip = _x == _targetX ? false : true;
}
}
if(_bUpdateState)
{
PetManager.setPetState(_content,_lBits,_uBits,_eBits);
_bUpdateState = false;
}
_loc5_ = _parent.inSplashVolume() ? 10 : 0;
if(_loc5_ && _parent.splashLiquid == "mud")
{
_loc5_ = 20;
}
if(_parent.splashLiquid != "mud" && _parent.splashLiquid != "water")
{
_loc5_ = 0;
}
_loc3_ = _content.transform.matrix;
_loc3_.identity();
_loc3_.scale(_bFlip ? -_scale : _scale,_scale);
_loc3_.translate(_x,_y - param1);
_content.transform.matrix = _loc3_;
_loc4_ = _loc5_ + param2;
if(_bBack)
{
_loc4_ += 2;
}
if((param2 || _lastAnim <= 4) && _lastAnim != _loc4_)
{
_lastAnim = _loc4_;
_content.pet.setAnim(_loc4_);
}
if(_bSpecialMove)
{
_bSpecialMove = false;
if(!param2)
{
_content.pet.setAnim(4 + _loc5_);
}
}
}
}
public function setState(param1:Array) : void
{
_lBits = param1[0];
_uBits = param1[1];
_eBits = param1[2];
_bUpdateState = true;
}
public function setAction(param1:int, param2:int = 0) : void
{
switch(param1)
{
case 0:
onClick();
break;
case 1:
setSparkle(param2);
}
}
public function setActionByName(param1:String) : void
{
var _loc2_:int = 0;
for each(var _loc3_:Object in _actionLookup)
{
if(_loc3_.name == param1)
{
_loc2_ = int(_loc3_.animId);
if(_loc2_ > 0)
{
_lastAnim = _loc2_;
if(_content)
{
_content.pet.setAnim(_loc2_);
}
}
break;
}
}
}
public function onClick(param1:MouseEvent = null) : void
{
if(param1)
{
param1.stopPropagation();
UserCommXtCommManager.sendPetAction(0);
}
_bSpecialMove = true;
}
private function onPetLoaded(param1:MovieClip) : void
{
if(_parent.isPetForm())
{
_content.pet.scaleX = _content.pet.scaleY = 2;
}
_content.pet.setSparkle(_sparkle);
}
private function convertAvtAnimToPetAnim() : int
{
switch(_parent.animId)
{
case 23:
case 38:
return 31;
case 22:
case 41:
return 32;
case 17:
case 33:
return 33;
case 6:
case 39:
return 34;
case 2:
case 4:
case 40:
break;
default:
return _parent.isPetMovingTest() ? 0 : 1;
}
return 35;
}
}
}
BIN
View File
Binary file not shown.
+9 -3
View File
@@ -13,8 +13,11 @@ const os = require("os");
const path = require("path");
class GameClient {
constructor(gamePort) {
// `localAddress`: another loopback address to come from (127.0.0.2), for
// what the server tells apart by address.
constructor(gamePort, localAddress = undefined) {
this.gamePort = gamePort;
this.localAddress = localAddress;
this.queue = [];
this.varUpdates = [];
this.askedForGames = 0;
@@ -25,7 +28,7 @@ class GameClient {
connect() {
return new Promise((resolve, reject) => {
this.socket = net.connect(this.gamePort, "127.0.0.1", resolve);
this.socket = net.connect({port: this.gamePort, host: "127.0.0.1", localAddress: this.localAddress}, resolve);
this.socket.once("error", reject);
this.socket.on("data", chunk => {
this.buffer = Buffer.concat([this.buffer, chunk]);
@@ -163,7 +166,10 @@ const withServer = async (name, httpPort, gamePort, run, {dataDir: keptDir = nul
// everyone arrives in the township, as the tests expect
AJ_SPAWN_ROOMS: process.env.AJ_SPAWN_ROOMS || "jamaa_township.room_main",
// and in the one world
AJ_WORLDS: process.env.AJ_WORLDS || "1"},
AJ_WORLDS: process.env.AJ_WORLDS || "1",
// the packs made again at once after a custom item changes
AJ_PACK_REMAKE_MS: process.env.AJ_PACK_REMAKE_MS || "0",
AJ_MASTERPIECE_MIN_AGE: process.env.AJ_MASTERPIECE_MIN_AGE || "0"},
stdio: ["ignore", "pipe", "inherit"],
});
let output = "";
+71
View File
@@ -8,6 +8,7 @@
const assert = require("assert");
const crypto = require("crypto");
const fs = require("fs");
const http = require("http");
const os = require("os");
const path = require("path");
const zlib = require("zlib");
@@ -119,6 +120,34 @@ const untilDefs = async (client, kind) => {
}
}
};
// a game on another address: it fetches the packs with custom items in, and
// at login is sent of them only what they may lack (customItems.sendAll),
// all of it before the chat filter settings ("xfl").
const ELSEWHERE = "127.0.0.2";
const packsFrom = address => Promise.all([1000, 1030, 10230].map(id => new Promise((resolve, reject) => {
http.get(`${BASE}/${cdn.hashedPath(`defPacks/${id}`)}`, {localAddress: address}, res => {
assert.strictEqual(res.statusCode, 200);
res.resume();
res.on("end", resolve);
}).on("error", reject);
})));
const defsAtLogin = async (username, password, address) => {
const auth = await (await postJson(`${BASE}/authenticate`, {username, password})).json();
const client = new harness.GameClient(GAME_PORT, address);
await client.connect();
assert.strictEqual((await client.logIn(username, auth.auth_token)).status, "1");
const defs = {clothing: [], den: []};
for (;;) {
const fields = (await client.next()).split("%").slice(2, -1);
if (fields[0] === "xfl") {
client.socket.destroy();
return defs;
}
if (fields[0] === "xdi") {
defs[fields[2]].push(...JSON.parse(fields[3]));
}
}
};
const nextBox = async client => (await client.untilXt("xtl"))[2];
const shopList = async (client, roomId, shop) => {
client.xt("gl", roomId, shop);
@@ -194,6 +223,7 @@ const first = async () => {
const crownRow = byId(await pack(1000), 50000);
assert.strictEqual(crownRow.layerDefId, base.layerDefId);
assert.strictEqual(crownRow.avatarUseFlags, "9007199254740991"); // any animal, like all clothing here
assert.strictEqual(row.avatarUseFlags, crownRow.avatarUseFlags); // and so in what games playing are sent
assert.strictEqual((await strings())[9100000], "Test Crown");
// first in the shop of oddities, and Pat can buy it in a colour it has
@@ -235,6 +265,20 @@ const first = async () => {
say(devGame.client, devGame.roomId, `!item clothing ${base.id} Quick Hat`);
assert.strictEqual(await nextBox(devGame.client), "Made Quick Hat, clothing 50001. It is in the item finder now.");
assert.strictEqual((await untilDefs(pat.client, "clothing"))[0].name, "Quick Hat");
// a game whose address fetched the packs since has every item from them,
// and is sent none again; then only the one changed after
await packsFrom(ELSEWHERE);
assert.deepStrictEqual(await defsAtLogin("Lou", people.Lou, ELSEWHERE), {clothing: [], den: []});
assert.match((await dev("/mod/api/items", {action: "update", kind: "clothing", id: 50000, cost: 7})).data.ok, /changed/);
assert.strictEqual((await untilDefs(pat.client, "clothing"))[0].value, "7");
const changedSince = await defsAtLogin("Lou", people.Lou, ELSEWHERE);
assert.deepStrictEqual(changedSince.clothing.map(row => `${row.id} ${row.name} ${row.value}`), ["50000 Gold Crown 7"]);
assert.deepStrictEqual(changedSince.den, []);
// a row carries what the client reads of it, not the whole base row
const wire = ["id", "layerDefId", "layerId", "type", "value", "titleStrId", "isGiftable", "membersOnly", "itemStatus", "enviroType",
"avatarUseFlags", "recycleValue", "currencyType", "defense", "attack", "attackMediaRefId", "combatType", "modifierType",
"modifierValue", "criticalHit", "combinedCost", "colors", "availabilityStartTime", "availabilityEndTime", "name", "art", "artMode"];
assert.deepStrictEqual(Object.keys(changedSince.clothing[0]).filter(field => !wire.includes(field)), []);
say(devGame.client, devGame.roomId, "!item list");
assert.match(await nextBox(devGame.client), /^Latest items made: 50001 Quick Hat \(clothing\); 50000 Test Chair \(den\); 50000 Gold Crown \(clothing, off sale\)$/);
say(devGame.client, devGame.roomId, "!item hat 12 x");
@@ -385,6 +429,10 @@ const first = async () => {
const withArt = (await maker("info")).mine.find(sameItem);
assert.match(withArt.art, /^p[0-9a-f]{12}$/);
assert.deepStrictEqual(told, [[String(hatEntry.id), withArt.art]]);
// the packs have no pictures: a game logging in is sent each one, however new its packs
await packsFrom(ELSEWHERE);
const pictured = (await defsAtLogin("Lou", people.Lou, ELSEWHERE)).clothing;
assert.deepStrictEqual(pictured.filter(row => row.art).map(row => [row.id, row.art]), [[String(hatEntry.id), withArt.art]]);
const served = await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png?v=${withArt.art}`);
assert.deepStrictEqual([served.status, served.headers.get("content-type"), served.headers.get("x-content-type-options")], [200, "image/png", "nosniff"]);
const bytes = Buffer.from(await served.arrayBuffer());
@@ -584,11 +632,34 @@ const second = async () => {
lou.client.socket.destroy();
};
// the packs made again at most every AJ_PACK_REMAKE_MS after a change: one
// fetched before then is the one made before, and a game whose address
// fetched it is sent at login the item it lacks.
const REMAKE_MS = 5000;
const third = async () => {
const fetchedEarlier = "127.0.0.3";
await packsFrom(fetchedEarlier);
const lou = await arrive("Lou", people.Lou);
lou.client.xt("xcm", lou.roomId, "make", "clothing", made.base.id, "Lou Hat");
const answer = await lou.client.untilXt("xcm");
assert.strictEqual(answer[2], "1", answer[3]);
const louHat = JSON.parse(answer[6]).find(entry => entry.name === "Lou Hat");
assert.ok(!byId(await pack(1000), louHat.id)); // the pack of before, for a moment
const atLogin = await defsAtLogin("Pat", people.Pat, fetchedEarlier);
assert.deepStrictEqual(atLogin.clothing.filter(row => row.id === String(louHat.id)).map(row => row.name), ["Lou Hat"]);
await new Promise(resolve => setTimeout(resolve, REMAKE_MS + 200));
assert.strictEqual(byId(await pack(1000), louHat.id).titleStrId, String(9100000 + louHat.id - 50000));
assert.strictEqual((await strings())[9100000 + louHat.id - 50000], "Lou Hat");
lou.client.socket.destroy();
};
(async () => {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "aj-test-"));
try {
await harness.withServer("items test", HTTP_PORT, GAME_PORT, first, {dataDir});
await harness.withServer("items test (after a restart)", HTTP_PORT, GAME_PORT, second, {dataDir});
process.env.AJ_PACK_REMAKE_MS = String(REMAKE_MS);
await harness.withServer("items test (packs made again at most so often)", HTTP_PORT, GAME_PORT, third, {dataDir});
}
finally {
fs.rmSync(dataDir, {recursive: true, force: true, maxRetries: 10, retryDelay: 200});
+3
View File
@@ -180,6 +180,9 @@ const run = async () => {
const made = await a.untilXt("pc");
assert.strictEqual(made[2], "1");
assert.ok(Number(made[10]) <= Date.now() / 1000 - 259200);
// ... and named from the hatched popup (EggPetHatchedPopup waits for this answer)
a.xt("pn", roomId, made[5], 15386, 15428);
assert.deepStrictEqual((await a.untilXt("pn")).slice(2), ["1", made[5], "15386|15428"]);
// --- she starts in the township as ever, in a look picked at random if she asked for one
say(a, roomId, "!theme random on");
+1
View File
@@ -60,6 +60,7 @@ set -- \
gui.RecycleItems RecycleItems.as \
gui.AvatarEditor AvatarEditor.as \
gui.PetInventory PetInventory.as \
pet.WorldPet WorldPet.as \
gui.DenEditor DenEditor.as \
gui.TradeManager TradeManager.as \
avatar.AvatarView AvatarView.as \