Compare commits

..
77 Commits
Author SHA1 Message Date
Burrowdev 8e117ff26f feat: all four pattern colours, the in-game item giver again, and 18 and over
- a special animal's pattern has four colours, as its presets do: the
  pattern tab's 1 to 4 each have a colour table
- the Item Giver opens in the game again; the Item Maker's previews keep
  their own colours instead of the giver's colour box
- the drawn trading sign is gone
- sign-up, the terms and the privacy policy say 18 and over (terms
  version 2026-10-24)
- builds 92
2026-10-24 05:55:42 +03:00
Burrowdev 29c0eff454 fix: an animal adopted of the other kind than the room's no longer shows twice in the switcher
the switch took the animals out of the list by index, as if the one in use
were always first; one of the other kind, just adopted, goes first instead.
the list is now rebuilt by which animal is which. builds 87
2026-10-24 03:53:55 +03:00
Burrowdev f72e346c03 fix: the game starts again: MinigameManager is the game's own once more
recompiled, its static setup threw (#1065) as the game started, and the
game never got past its loading screen; builds 86
2026-10-24 02:12:18 +03:00
Burrowdev 4355994253 fix: eggs, pets, minigames, themes, HQ facts and more
- egg stands sell an egg again; a bought egg hatches and is named at once
- pets whose bits name no pet the game has no longer stop loading
- the adopt-a-pet gift path opens with nothing adopted yet
- Spider Zapper and Wind Rider start with their players: spiders can be
  shot, and Wind Rider is played; Spider Zapper's waves are answered
- Phantom's Treasure can be left from its title screen and level choice
- the Touch Pool's fact window always closes
- the last key in Return of the Phantoms lies where it can be reached
- the Alpha HQ's bios and relics open and close
- a land animal in water (and a sea one on land) is drawn when it stands
- a seasonal theme's room has today's shops in it (lib/themerooms.js)
- the Forgotten Archive sells its own stock, not unfinished pieces
- custom items whose def is gone stay out of trade lists
- the captcha is always shown, and tried again when it fails
- builds 85
2026-10-24 01:57:49 +03:00
Burrowdev c7efda7030 fix: eco items, wall, photo booth, chat emoji, den fixes
- the eco den items work: the Eco Shop sells the real eco items, solar
  panels and wind turbines placed in the den in use earn eco credits, lamps
  switch on while there is power for them, and the eco score earns the
  three eco plaques; a first look gives an account its first credits
- the item giver row opens the web item giver
- a painting that cannot be shown is the Burrow logo, not a wait for good
- Jammer Central's buttons work; What's New shows the newest Jamaa Journal
- the Jammer Wall opens even while the HUD is checking the player's own; a
  photo of an animal wearing nothing is kept; a wall photo of an animal the
  game does not know no longer stops the wall
- the photo booth's paid picture is answered
- emoji no longer push the line off centre; "\" keeps an emote or a
  ":name:" as typed; a repeated line with emoji is sent as it was said
- the emoji button hides with the HUD, not a moment after
- the join date on a player's card stays in its corner
- den items whose def is gone no longer garble the den and the inventory;
  custom pictures in a den no longer stop walking
- the den editor's switch and recycle buttons are always there
- the den inventory scrolls to an eleventh item
2026-10-23 23:00:00 +03:00
Burrowdev 7de41ceed5 feat: redemption codes, world count, den visitor count and more fixes
- codes made in the admin panel (Messages) give an item, gems or
  diamonds through the game's Redeem Code window, which was never
  answered; its "need help?" says what codes are here
- the number of worlds is set in the admin panel (Debug), live
- a den's owner is told how many are in it: the HUD's count and doorbell
- the map counts the player's buddies in each land of their world
- gifts whose item no longer exists, or with a nonsense amount, are no
  gift at all, rather than a window that will not close
- custom item pictures are 256 pixels and 100 KB at most
- the account page's buddies and den visitors fold away
- shops no longer count down "X days left"
2026-10-23 22:25:35 +03:00
Burrowdev 15f321fb00 fix: official game table and lists, feedback, museum and books
recordings of the official game (tools/recorder.js) had its game table and
several generic lists in them:

- lib/games.json follows the official table: the print kits, Brady's lab,
  the carnival games (in the room) and the buddy games have their real
  ids, and every game its "Play!" picture
- lists the server has nothing of its own for are answered as the official
  server did (lib/official-lists.json): the Journey Book's facts, and its
  pages and four of the Chamber of Knowledge's books rebuilt from the media
  files; Jam-A-Gram stamps are the official ones
- feedback windows send to the staff panels' feedback, over the game's own
  connection; museum gem donations are taken (cd)
- fact cards and museum exhibits missing from a list are had by their id
  (factDefs), and their arrows do nothing past the list
2026-10-23 21:52:59 +03:00
Burrowdev 6c273554d7 fix: trading, machine rewards and claw prizes from the owner's list
- a completed trade no longer plays the failure sound over the success one
- a sign over players who are trading, seen by everyone in the room
- every item added to a trade list is shown; lists keep up to 200 items
- the drink, popcorn and cotton candy machines always hand over what they
  made (the game sent nothing when it was like the last one it gave), the
  smoothie machine even when the game it is was not noted down, and the
  server takes a game's message for a moment after it is left
- claw machine, Phantom Invasion and Sky High prizes are the game's own
  items only: a custom item could be missing from the winner's game
2026-10-23 21:29:49 +03:00
Burrowdev 22fb7f0fa5 fix: settings, chat, video spots and other bugs from the owner's list
- Jam-A-Gram privacy: the inbox's options were taken the wrong way round
- report window: no instruction text over the reason
- the museum's theatre and other unnamed rooms get names; every shop a title
- "How did you hear?" is never offered (its window soft locked the game)
- video spots with nothing to play open a "Your Video" box on the game page;
  the trade list's help plays a video; the theatre's box no longer vanishes
- emotes, actions and phrases are limited per player, as typed chat is
- phrases from the menus come in the sender's chat bubble style
- settings: WASD, blocked players and custom items as two-sided switches,
  graphics at their best by default, a switch for bubble animations, and
  Manage Account beside two-step sign-in opens the account page
- pressing a @mention in a bubble no longer walks the player there
2026-10-23 21:12:04 +03:00
Burrowdev e9097a9a4f feat(items): beta-era colours for seven clothing items
colours from a dump of a beta-era inventory, added after each item's own
so the colours already given keep their place: Rare Eyeball Hat, Creature
Mask, Tiara (two), Arctic Hood, Elf Helmet, Furry Hat and Turquoise Ring.
the shop shows a list's first 8, so these are had from the item givers.
2026-10-23 19:56:44 +03:00
Burrowdev 7cfef493fa feat(account): web item giver with colour pickers, den variants, tints and previews
/account/items, linked from the account page and using its sign-in, gives
items to the account signed in:

- clothing: the item's own colours, or four colours of your own as a
  picker, #RRGGBB, or AJ's numbers (palette places, or the whole item's
  colour id signed or unsigned), converted as you type; hex colours not in
  the palette become an exact custom colour
- den items: the variants their art has (lib/den-variants.json, made by
  tools/den-variants.sh) and a whole-item tint with a strength, kept in the
  item's version above the variant and drawn by DenItemHelper (build 83)
- a preview of each: clothing icons coloured on the page as the game
  colours them, den items played by Ruffle in a sandboxed frame through
  public/item-preview.swf (tools/preview-host)

a give with a custom colour id that does not exist is refused.
2026-10-23 19:14:49 +03:00
Burrowdev 44af83f1c5 feat(account): sign in to the account page with the Burrow client
"Sign in with the Burrow client" on the account page's sign-in screen
opens burrow://account?n=<nonce>; the browser asks whether to open
Burrow. The client asks for a ticket with its login token
(POST /account/api/client-ticket) and opens /account/client?ticket= in
the browser, which signs in there. A ticket lasts 2 minutes, is good
once, and signs in only the browser holding the nonce's cookie, so a
burrow:// link from elsewhere signs nobody in and a ticket sent to
someone else opens nothing. The tab that started it follows by itself;
once it has worked in a browser, the page asks for Burrow by itself.
2026-10-23 07:04:45 +03:00
BurrowdevandClaude Opus 5.5 b22708a4ba feat(devices): hardware bans and alts need 3 matching IDs
A computer is taken for a banned one, and an account for an alt, only
when they share at least 3 hardware IDs (system, board, disk, the
client's own); one or two in common was too often someone else's.
Network card addresses still do not count. A hardware ban is refused
for an account with fewer than 3 IDs known, as it could match nobody.
MAC-only ("weak") alts no longer exist, so the flag is gone from the
panels.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 04:46:23 +03:00
SnipzilandClaude Opus 5.5 494f252c5b fix(avatars): switching animals no longer copies the new one over the old
Since 3423df1 the server followed an animal switch ("as") with that
animal's "ad" and full "il". The client swaps animals partway through the
transform animation: at "hideAvatar" it copies the in-world avatar into the
switcher slot being left, then loads the new animal onto the in-world one.
The extra "ad" arrived before that frame, had no request waiting for it, and
so was applied to the in-world avatar, and the "il" then matched it too. The
slot got a copy of the new animal, the old one was gone from the switcher,
and the other slots drew blank until the next login.

This reverts 3423df1. A newly bought animal's editor not opening until the
next login comes back with it and needs a fix that goes through the
client's own "ad" request.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 23:37:06 -04:00
SnipzilandClaude Opus 5.5 6b707fbc1d fix(theatre): a site the client keeps out opens in the player's own browser
The desktop client now shows only a few listed sites in the theatre's
browser (DuckDuckGo and Wikipedia, burrow-client "the browser shows a few
listed sites"), as its old Chromium has holes that will never be mended.
When it keeps an address out, browserState says so: the bar then reads
"<host> opens in your own browser, not here.", with the sites it shows
in the title, and "Open in your browser" hands the address to the client
to open in the system browser. A click on the notice goes back to the
address. A client that sends no `blocked` shows the bar as before.

duckduckgo.com, the browser's start page since 9720d30, is now listed
in .github/allowed-hosts.json, which the security check wanted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 23:06:05 -04:00
SnipzilandClaude Opus 5.5 b45fd195df fix(discord-bot): the public status card counts the players online
publishStatus gave the card players: 0 and rooms: 0, so the public card
always said "0 online • 0 rooms". It now counts world.players() and their
rooms, as /burrow status does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:54:27 -04:00
SnipzilandClaude Opus 5.5 e2454447d9 test(signin): Discord sign-ins take a 2FA code, and email recovery its limits
test/signin.js goes through both dashboards' Discord sign-in against a
stand-in for Discord's OAuth2 API (test/fake-discord.js, loaded into the
server with NODE_OPTIONS), and through email recovery against a mail
webhook of its own: Discord alone opens neither dashboard, a waiting
sign-in is used once and dies after five wrong codes, 2FA is removed by
email only with the password, not right after an email password reset and
never for staff, and one account gets three recovery emails an hour. It
fails without the two commits before it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:54:26 -04:00
SnipzilandClaude Opus 5.5 0da5daabc9 fix(account): removing 2FA by email also needs the password, and never for staff
A recovery link (7dee290) removed 2FA on the email alone, and a password
reset is email alone too, so a player's mailbox was their account, 2FA or
not. For staff, 2FA removed and turned on again with another app made
whoever had the mailbox active staff.

- a 2FA reset by email also takes the account's current password, and is
  refused for 7 days after a password reset by email
  (emailPasswordResetAt), so the two cannot be chained.
- never for an account with a staff role: they ask the admin, whose
  temporary password can turn 2FA off.
- at most three recovery emails an hour for one account, from any address.

The address is still never confirmed, nor shown or changed on the
account page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:54:26 -04:00
SnipzilandClaude Opus 5.5 3b53c8dab8 fix(staff): a Discord sign-in asks for the 2FA code, and the bot needs one too
Since 7dee290 a Discord account linked to a staff member opened the
moderator panel for 12 hours on Discord's word alone, with no password and
no 2FA code, though the normal sign-in asks for both every time; and since
b11ae1d the bot took /moderate and /burrow commands from that Discord
account alone. The link outlives a new password and "sign out
everywhere", so a taken-over Discord account was enough to act as the
staff member. The admin dashboard's Discord sign-in (adminDashboardAccess)
skipped its password the same way.

- /mod/discord/callback and /admin/discord/callback no longer sign in:
  they keep a pending sign-in for 5 minutes (a Strict cookie) and the page
  asks for the linked account's 2FA code (POST .../api/discord/code). Five
  wrong codes and it must start again at Discord. The admin one also needs
  the account to have 2FA on and not be locked.
- the bot's commands and buttons count only for a staff member with a
  panel session that took a code (modpanel.discordBot.commandActor): the
  password sign-in, or Discord and a code; not the game's token sign-in. A
  new password, signing out everywhere or 2FA turned off end those
  sessions (forget), and so the bot's use. Whose Discord it is still keeps
  linked staff out of /discord moderation, and lets them close tickets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:54:26 -04:00
SnipzilandClaude Opus 5.5 83c2fc3b0b feat(chat): custom chat bubbles
Players choose how their chat bubble looks, and everyone sees it.

- style: a gradient of 2 to 5 colour stops (linear at any 45° step,
  radial, or solid), its strength, text and border colours, outline
  thickness 0-4, opacity 25-100%, and an animation (still, pulse, shimmer,
  flow, rainbow) at 40-300% speed. lib/chatstyles.js keeps the one
  canonical form: forgiving for saved accounts, strict for requests.
- in the game: Settings > Chat Bubble > Customize opens an editor with
  presets (Ocean, Sunset, Forest, Midnight, Candy, Rainbow), a palette,
  Swap, Random, Reset and Save, and a live preview. "Custom bubbles: Off"
  draws everyone's bubbles normally on this computer only.
- on the web: the account page has a Chat bubble section with the same
  choices.
- wire: xcs with no fields asks for the saved style, with twelve (or an
  older client's 7, 10 or 11) saves it; the reply is the canonical twelve.
  A typed line ("uc") carries its sender's style after the stock extra
  field, only when it is not the default, so message and type stay where
  the game reads them and unpatched clients are unaffected.

ajclient.swf is built with this and the six client commits before it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:11 -04:00
SnipzilandClaude Opus 5.5 c1a85f9b5d test(smoke): a login choice cannot make a player a guide
Since a860a67 only the admin makes guides, so login_choices' isGuide is
refused; the smoke test still expected it to stick.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:11 -04:00
SnipzilandClaude Opus 5.5 d44612bd08 feat(client): any animation the client has, sent as "sja:<anim>,<flip>"
An action message "sja:<anim>,<flip>" plays animation <anim> (1 to 255)
on the sender's avatar for everyone else, and holds it as their idle
(AvatarWorldView.holdIdleAnim) until they walk or do another action, so the
game's idle refreshes don't stand them back up. Not in minigames. A
client without this finds no action by that name and ignores it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:11 -04:00
SnipzilandClaude Opus 5.5 9156c6e392 fix(chat): actions stay out of the chat history
Doing an action put its wire command (":sitS:", ":sitSW:" and the like)
in the player's own chat history. Actions still animate the avatar; they
are no longer added as chat lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:11 -04:00
SnipzilandClaude Opus 5.5 3930d2dabe feat(client): Expanded Inventory, more and smaller items a row
Strawberry Jam's setting, under Settings: the clothes picker and the
item, den and gift pickers show 3, 4 or 5 items a row instead of the
game's three, each scaled so a row is as wide as before. A + and - at the
avatar editor's item counter step between them. User vars 9009 (on) and
9010 (a row; unset is 5).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:11 -04:00
SnipzilandClaude Opus 5.5 9985ae7625 feat(dens): Back, Front and Auto beside the selected den item
The layer controls move from the den editor's top corner into the selected
item's own buttons (DenItemHolder), under the flip and link buttons'
column: Back, Front and Auto (natural depth). They show only for an item
that can be stacked, reorder it on screen at once, and a mouse-up between
the item and its buttons no longer deselects it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:11 -04:00
SnipzilandClaude Opus 5.5 3139384ef3 fix(client): every worn item drawn from a shared art layer is painted
LayerAnim kept one place and one colour for each requested image, so when
two worn items used the same art layer only the last was drawn. _order now
keeps every place (and its colour) an image is used in, and one image
response paints each of them, in their worn order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:10 -04:00
SnipzilandClaude Opus 5.5 e67fbe95e1 fix(jamagrams): moderators are not held to the Jam-a-Gram send limits
Moderators send follow-up cards while helping players. The server skips its
sends-per-ten-minutes limit for them, and the client's per-recipient
session cap (ECardXtCommManager, now in swf-src and built from there) is
skipped for userInfo.isModerator.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:10 -04:00
SnipzilandClaude Opus 5.5 3423df10f8 fix(avatars): a newly switched-to animal's editor opens
Switching animals ("as") changed the active animal, but the client keeps
an editor model of each animal and was never sent the new one's data or
clothes, so an animal bought this session showed in the switcher and its
editor would not open until the next login. The switch is now followed by
its "ad" and its full item list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:10 -04:00
SnipzilandClaude Opus 5.5 8839f86e6c feat(discord-bot): a public status card with a banner, and log cards with fields
- The status card is the players' card now: a title, "Online" and the
  admin's message, players and rooms, uptime and memory, an optional banner
  image and a "Play Burrow" button. The open report count is staff data and
  is no longer on it.
- The admin page's Discord tab takes a banner image URL (http(s), at most 500
  characters, blank for none), saved as discordBotStatusBanner and named in
  the mod log. GET /burrow-status-banner.png serves a banner of our own.
- The game activity, moderation, bot audit and security logs are one card
  shape (logCard): a summary line, a list of fields and when it was logged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:10 -04:00
SnipzilandClaude Opus 5.5 92ebb4d07c fix(limits): behind Cloudflare, a visitor is their CF-Connecting-IP
With a trusted local proxy the address was the last X-Forwarded-For hop,
which behind Cloudflare is Cloudflare's own edge: every visitor shared a
handful of addresses for the rate limits, and the Turnstile check was sent
an edge as remoteip. When that last hop is in Cloudflare's published
ranges (https://www.cloudflare.com/ips/), CF-Connecting-IP is used, if it
is an address. From anywhere else the header is ignored: someone who
reaches the server directly could otherwise name any address, past the
rate limits, address bans and AJ_ADMIN_ALLOW. Neither header is read
unless config.trustedProxy is on and the request came from loopback.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:10 -04:00
SnipzilandClaude Opus 5.5 974f68490e fix(captcha): cap Cloudflare checks in flight, and let a blocked widget be retried
- server: at most config.maxConcurrentCaptchaChecks (AJ_CAPTCHA_MAX_CONCURRENT,
  24 by default, 1 to 100) Turnstile checks wait on Cloudflare at once; past
  that the answer is captcha_unavailable at once, so a slow Cloudflare cannot
  hold thousands of sockets open. The page's policy lets it connect to
  challenges.cloudflare.com too.
- page: public/captcha.js gives up on a widget that has not loaded in 15 s,
  or that loaded without turnstile.render, instead of waiting for ever, and a
  render that throws counts as a failed answer. The game's captcha window says
  to check the connection or a content blocker, with a "Try again" button.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:24:59 -04:00
SnipzilandClaude Opus 5.5 43f2717b44 perf(signup): derive a web sign-up's password off the main thread
POST /api/register used accounts.register, whose scryptSync froze every
player for as long as each password took, so a burst of sign-ups was felt
in the game. accounts.registerAsync checks the same things, derives the
hash on libuv's pool (hashPasswordAsync), checks the name again after it
(another request may have taken it meanwhile) and inserts the account as
before. The game's own Create Account keeps the sync path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:24:59 -04:00
BurrowdevandClaude Opus 5.5 6645bf66b3 fix(theatre): the staff room video window plays, in the Your Video look
The VIDEOS sign's window threw on Play and Stop since 8babe9c
(onTheatreControl read _loc1 for _loc1_, ReferenceError #1065), so a
room video never started. It is now drawn as the page's Your Video box:
cream panel, outlined title, a white link box, green "Play for room"
and red "Stop" pills and the red round close button, over the middle of
the theatre's screen, with no dark cover over the stage. Enter plays,
Escape closes.

ajclient.swf is built with this and the two commits before it;
buildVersion 82.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:44 +03:00
BurrowdevandClaude Opus 5.5 43ae95fbca feat(filter): the chat filters cover animals' and pets' names
- server: a typed name the filter (lib/chat-filter.txt) stops is
  refused at xrn, with the game's warning and a line in the log; one
  saved before is cleared at login (the animal takes the username, the
  pet is "Pet"). the game's own word-id names are never looked at.
- client: LocalizationManager.translateAvatarName and translatePetName
  pass a typed name through the player's own filter
  (AJClient.filterName), wherever the game shows it. a name cannot be
  left out, so with "Hide the whole message" its words are starred.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:44 +03:00
BurrowdevandClaude Opus 5.5 34db374527 feat(pets): the pet form's name follows the Usernames / Animal Names switch
Playing as a pet showed the pet's name over it whatever the settings
menu said. Now it shows the player's username, as the switch does by
default, or the pet's name with Animal Names, and changes when the
switch is flipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:44 +03:00
BurrowdevandClaude Opus 5.5 3256135df3 feat(legal): Burrow is for players 16 and over
The website's sign-up box, the Terms of Service and the Privacy Policy
said 13 and over; they say 16 now, as the client does. The privacy
policy's "or the higher age your country sets (up to 16)" is gone, 16
being that highest age. termsVersion 2026-10-21.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:44 +03:00
BurrowdevandClaude Opus 5.5 9efb2558fc feat(roles): masterpieces.approve, its own permission
Approving and removing framed paintings was items.approve, which also
judges the items and pictures players make. masterpieces.approve now
guards it, on the server (POST /mod/api/masterpiece) and in the mod
panel's buttons and its "only ones I approved" filter. Moderators and
admins have it by default; seeing the Masterpieces page is still
player.view.

roles.load, once at start (setting permissionSplitMasterpieces): a role
list the admin changed, and a staff member's own grants and denies, that
held items.approve are given masterpieces.approve too, so nobody gains or
loses anything by the split.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:44 +03:00
BurrowdevandClaude Opus 5.5 9720d309fa feat(theatre): an experimental web browser on the theatre screen
In a theatre, "Browser" puts a web page on the screen for that player
alone, beside "Your Video". The desktop client (1.3.3) draws it in a
sandboxed webview of its own over the game page, which tells it where,
what the game draws over it, and where to go; nothing of it goes to the
server.

- off by default: the admin panel's Debug tab turns it on for everyone
  (setting theatreBrowser). the server marks the game page with
  data-theatre-browser="on" as it sends it (lib/http.js), and the page
  shows the button only when the server allows it and the client says it
  can draw it, so older clients never see a button that does nothing.
- the boxes over the screen share one style (.aj-box), and a clicked
  button no longer keeps Chromium 87's focus ring.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:44 +03:00
BurrowdevandClaude Opus 5.5 64eab1f8ad ci: allow the theatre's YouTube and Vimeo players
8fb5cfe's own-video player names www.youtube-nocookie.com and
player.vimeo.com in public/game.html, which the security check's
invariants refused: neither was in .github/allowed-hosts.json.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:44 +03:00
BurrowdevandClaude Opus 5.5 a8ab031616 fix(discord-bot): start the server without discord.js installed
b11ae1d made the server load discord.js at start, through lib/discordbot.js,
even with the bot off. update.sh installs no npm packages, so prod had none,
and every start failed with "Cannot find module 'discord.js'".

- lib/discordbot.js loads discord.js when the bot starts (a token and guild
  id set), not with the server. without the package the bot stays off, with
  a line in the log, and the panel's Start says to run npm ci. the two
  message flags cards use are written as numbers, and the slash commands
  are made when they are synchronized.
- deploy/update.sh runs npm ci --omit=dev when package-lock.json changed or
  node_modules is missing. a failed install leaves the bot off; the game
  needs no package.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 12:16:57 +03:00
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
Snipzil 9f69b3511b fix(dashboard): keep player search and review data current
Prevent slow or periodic account/player lookup responses from replacing a newer search, make both dashboard layouts usable on narrow screens, and use the unified dashboard masterpiece routes for staff and owner review images. Propagate approved username changes through moderation-facing history and cover report-name propagation with an end-to-end regression test.
2026-10-19 12:29:09 -04:00
Snipzil 8e7b193621 fix(world): replay active actions for late room joins
Remember a standing avatar's valid action and mirror marker, replay it after avatar creation for players entering or reloading a room, and clear it on movement or exit. Add an end-to-end regression test for late join animation sync.
2026-10-19 12:14:02 -04:00
Snipzil 08780d7e69 Merge branch 'main' of https://github.com/burrow-dev/burrow-server 2026-10-19 10:12:46 -04:00
Snipzil 8babe9cb39 feat(client): add staff tooling and resilient room UI
Deliver the in-game moderation and event overlays, theatre playback bridge, room-effect controls, staff shortcuts, friend-game prompts, and Windows emoji handling fixes.

Improve den editing with explicit front, behind, and natural stacking choices that persist without changing item position. Correct item display layers and custom artwork behavior, and make popup controls reliably closable.

Include performance-mode settings, animation and input safeguards, and rebuild ajclient.swf from the patched sources so the served client exactly matches the feature set.
2026-10-19 10:10:11 -04:00
Snipzil 5c9b2e0066 feat(world): expand events, rewards, and den behavior
Add owner/developer room-effect controls and chat shortcuts, staff movement that bypasses full or locked destinations, in-game moderation entry points, theatre video synchronization, and shared room effects.

Restore game and trade popups, reliably award refreshments and game rewards, support pet play outside parties, correct den placement categories, improve den item persistence, and refresh custom-item and masterpiece behavior.

Harden room, party, pet, minigame, and item state handling with matching feature and restored-system regression coverage.
2026-10-19 10:09:50 -04:00
Snipzil 7dee29010a feat(dashboard): unify secure staff administration
Provide a single /dashboard entry point for owner and staff tools, with Discord OAuth sign-in for approved owner accounts and active staff. Add owner-managed dashboard access grants, staff server health and update visibility, filtering, moderation improvements, item controls, and per-animal clothing restrictions.

Replace staff-triggered password and 2FA resets with email-verified account recovery. Persist validated recovery addresses, use short-lived hashed recovery tokens, expose recovery flows in registration and account pages, and keep mail delivery disabled until its webhook configuration is present.

Cover dashboard aliases, recovery restrictions, Discord access, monitoring, item locks, wear rules, and staff behavior with regression tests.
2026-10-19 10:09:35 -04:00
BurrowdevandClaude Opus 5.5 94b8de801e fix(sfs): let the login burst through the send backlog limit
Every custom colour and item def is written at login before the client
reads; at 20000 colours and 5000 clothing that is ~4.2 MB, over the 4 MB
backlog limit, so every login was cut off right after it succeeded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 07:10:05 +03:00
Burrowdev 95946c5b02 perf(db): sync sqlite at checkpoints, not after every commit 2026-10-19 04:24:33 +03:00
SnipzilandClaude Opus 5.5 4997315239 fix(stats): draw the graphs of a week and longer
the dates under the graphs of 7 days and more were formatted with weekday
and dateStyle together, which browsers refuse (a TypeError), so render()
stopped after the tiles and none of those graphs was drawn on the admin or
the moderator panel; only the last 24 hours were. the date is now spelled
out instead ("Sun, Oct 18, 2026").

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-18 14:13:59 -04:00
SnipzilandClaude Opus 5.5 1e365b95c5 fix(staff): check every moderator panel action, end panel sessions with the rest
From the 18 October security audit (S-9, S-10).

- the moderator panel only refused a role the actions in its permission
  map. hardware bans and lifting them were missing from it, and answering
  ban appeals (which lifts the ban, the address's too), name requests,
  paintings and reports were checked for player.view alone, so a Helper
  could do all of them. each now needs its own permission (address.ban,
  player.ban, player.names, items.approve, player.warn), with the rank
  check the other actions have, and an action missing from the map is
  refused. the page hides what the role cannot do.
- a new password, "Sign out everywhere", locking the account, turning 2FA
  off or deleting the account now also ends its moderator panel sessions,
  as the admin panel's reset already did, so a stolen panel session does
  not outlive them.
- test/staff.js covers both, and fails without either fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-18 13:17:58 -04:00
Burrowdev a359371a48 fix(deploy): restart after a push of many files
update.sh piped git diff --name-only straight into grep -q; grep stops at
the first match, so with a long list git hit a broken pipe and pipefail
made the test false: "no restart needed" after 33f5607 (134 music files).
The list is now taken whole, then searched.
2026-10-18 19:50:35 +03:00
Burrowdev 33f56074a4 feat: discord linking, @tags, music and sfx sliders, required device ids
- Discord: the account page links a player's Discord account through
  Discord's sign-in (lib/discord.js); only linked names are shown on cards
  (typed ones are cleared). A bot keeps the Server Booster badge on linked
  accounts that boost. The game tells the client where the player is, for
  the client's Discord rich presence (flashvars discordAppId).
- @username tags in chat, chat balloons and wall posts: only real players'
  names (asked of the server, "xmn"), names with spaces too, drawn on a
  blue box; a click opens the player's card.
- Settings: separate Music and SFX volume sliders for the old one.
- Device ids required: a launcher that sends none (before 1.3.0) is told
  at the game's login "Your client is outdated. Update at
  https://burrow.moe/download". AJ_REQUIRE_DEVICE=0 turns it off.
- Panels: clear a player's Jammer Wall posts; turning away masterpieces
  and player items asks first.
- Item Giver: negative colour ids (the same colour written signed).
- buildVersion 71; the client rebuilt with Snipzil's sitting fix.
2026-10-18 19:35:51 +03:00
Burrowdev 1d9b70f32e fix(avatars): keep the gem count when an animal is recycled
The animal switcher shows the second field of "ak" as the player's gems;
it was always 0, so recycling an animal showed 0 gems until the next login.
2026-10-18 19:35:16 +03:00
Burrowdev 3770341514 feat(music): dev cdn music files as den music items
The 133 music files on the game's development CDN that no den item plays,
in public/music/ (78 MB) and lib/extramusic.js (items 6013-6145), each
titled with its file name; the owner's debug track (6012) with them. Files
that already are den items under another name (the same audio, or the
same track by name and length) are left out.
2026-10-18 19:35:16 +03:00
Snipzil 422719dade feat(minigames): implement buddy game bubbles
Introduce a bubble system that allows players to signal availability for
specific buddy games. Other players in the same room can click the
bubble to initiate a game. The implementation handles bubble visibility
for new arrivals and ensures bubbles are cleared when players leave
rooms or start other activities.
2026-10-18 00:43:12 -04:00
Snipzil bb532a78bb Merge branch 'main' of https://github.com/burrow-dev/burrow-server 2026-10-18 00:04:41 -04:00
Snipzil 3c2053f434 fix(avatar): prevent player displacement when sitting or sleeping
Replace AvatarManager.checkIfAnimatingOnTopOf with P-code to fix an
issue where players were pushed off others within 100 pixels. This
also bypasses decompilation errors in the original class loops.
2026-10-18 00:04:23 -04:00
Burrowdev b551a587a9 feat: custom pictures setting, to hide the pictures players give items
A "Custom pictures" row in the game's settings menu, as Blocked players:
shown by default; hidden, every custom item is drawn with its base item's
art (icons, worn, placed in dens, Jam-A-Grams). Kept in user var 9006 (1 for
hidden), which the server stores like the other settings. buildVersion 62.
2026-10-18 06:22:17 +03:00
Burrowdev 6db96325dd fix: two worlds by default again
PR #5 made one world the default (AJ_WORLDS unset), which undid 31cbd87 on prod. Back to two; the tests still ask for one.
2026-10-18 05:53:23 +03:00
Burrowdev 408b7d4864 feat: owner, moderator and verified name tag badges seen by everyone
The game shows a name tag's badge to buddies only, except the News Crew
camera. AvatarWorldView now shows the Owner, Moderator and Verified badges
(def ids 63, 64, 76) to everyone too. ajclient.swf rebuilt with
tools/build-client.sh; buildVersion 61, so clients fetch it (PR #5's client
changes went out under 60 and may still be cached).
2026-10-18 05:44:09 +03:00
284 changed files with 35214 additions and 2732 deletions

No files matched your search

+5 -1
View File
@@ -4,10 +4,14 @@
"burrow.moe", "burrow.moe",
"cdn.jsdelivr.net", "cdn.jsdelivr.net",
"challenges.cloudflare.com", "challenges.cloudflare.com",
"discord.com",
"duckduckgo.com",
"play.burrow.moe", "play.burrow.moe",
"player.vimeo.com",
"vision.googleapis.com", "vision.googleapis.com",
"www.cloudflare.com", "www.cloudflare.com",
"www.w3.org" "www.w3.org",
"www.youtube-nocookie.com"
], ],
"swf": [ "swf": [
"academy.animaljam.com", "academy.animaljam.com",
+27 -8
View File
@@ -4,7 +4,8 @@
// what the security audit of 2026-10-16 found true of this server, checked on // what the security audit of 2026-10-16 found true of this server, checked on
// every push so that it stays true (or is changed on purpose): // every push so that it stays true (or is changed on purpose):
// //
// - it uses no npm packages, so there is no supply chain to break into // - it has only the one pinned Discord gateway dependency needed by the
// optional staff bot; additions are refused to keep the supply chain small
// - the server code starts no other programs and runs no generated code // - the server code starts no other programs and runs no generated code
// - the server code names no web address outside .github/allowed-hosts.json // - the server code names no web address outside .github/allowed-hosts.json
// - no private key, certificate key or .env file is committed // - no private key, certificate key or .env file is committed
@@ -22,17 +23,35 @@ const tracked = execFileSync("git", ["ls-files", "-z"], {encoding: "utf8"}).spli
const problems = []; const problems = [];
const fail = (file, message) => problems.push({file, message}); const fail = (file, message) => problems.push({file, message});
// no npm packages // The server stayed dependency-free until the optional Discord staff bot. Its
// maintained gateway/components implementation is pinned exactly and captured
// in package-lock.json; no other package is permitted without deliberately
// extending this allowlist and its review surface.
const pkg = JSON.parse(fs.readFileSync("package.json", "utf8")); const pkg = JSON.parse(fs.readFileSync("package.json", "utf8"));
const ALLOWED_DEPENDENCIES = {dependencies: {"discord.js": "14.26.4"}};
for (const field of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies", "bundledDependencies"]) { for (const field of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies", "bundledDependencies"]) {
if (pkg[field] && Object.keys(pkg[field]).length) { const actual = pkg[field] || {};
fail("package.json", `${field} is not empty. The server has no npm packages on purpose; if one is really needed, change this check in the same pull request and say why.`); const allowedDependencies = ALLOWED_DEPENDENCIES[field] || {};
if (JSON.stringify(Object.keys(actual).sort().map(name => [name, actual[name]])) !== JSON.stringify(Object.keys(allowedDependencies).sort().map(name => [name, allowedDependencies[name]]))) {
fail("package.json", `${field} differs from its approved dependency allowlist. Keep dependencies empty except for the pinned Discord staff-bot gateway, or deliberately update this check and explain why.`);
} }
} }
for (const lock of ["package-lock.json", "yarn.lock", "pnpm-lock.yaml"]) { for (const lock of ["yarn.lock", "pnpm-lock.yaml"]) {
if (tracked.includes(lock)) { if (tracked.includes(lock)) fail(lock, "use the reviewed package-lock.json; alternate package-manager lockfiles are not allowed.");
fail(lock, "a lockfile means npm packages; see package.json above."); }
if (fs.existsSync("package-lock.json")) {
try {
const lock = JSON.parse(fs.readFileSync("package-lock.json", "utf8"));
if (lock.lockfileVersion !== 3 || lock.packages?.[""]?.dependencies?.["discord.js"] !== "14.26.4") {
fail("package-lock.json", "must be the npm v3 lockfile for the pinned [email protected] dependency.");
}
} }
catch {
fail("package-lock.json", "is not a readable npm lockfile.");
}
}
else {
fail("package-lock.json", "is required to review the pinned Discord bot dependency.");
} }
// the server's own code: what the game server runs // the server's own code: what the game server runs
@@ -88,4 +107,4 @@ if (problems.length) {
} }
process.exit(1); process.exit(1);
} }
console.log(`${serverCode.length} server files and ${tracked.length} tracked files checked: no packages, no program starts or generated code, no unlisted hosts, no keys, everything parses`); console.log(`${serverCode.length} server files and ${tracked.length} tracked files checked: only the pinned Discord bot dependency, no program starts or generated code, no unlisted hosts, no keys, everything parses`);
+2
View File
@@ -20,6 +20,8 @@ __pycache__/
# internal markdown files # internal markdown files
*.md *.md
!deploy/README.md
!/CONTRIBUTING.md
/HANDOFF.md /HANDOFF.md
/DISCOVERIES.md /DISCOVERIES.md
/GOING-PUBLIC.md /GOING-PUBLIC.md
+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.
+14
View File
@@ -1,6 +1,20 @@
# Burrow # Burrow
Burrow is a private server for AJ Classic. Burrow is a private server for AJ Classic.
## Account-recovery email
Set `AJ_RECOVERY_MAIL_URL` and `AJ_RECOVERY_MAIL_TOKEN` to an HTTPS mail-relay or transactional-email webhook. Burrow posts `{to, subject, text}` with a Bearer token. Until both are configured, email recovery intentionally does not issue a usable reset link. New web sign-ups are asked for a recovery email; password and 2FA recovery require the one-time link sent there.
## Discord staff bot
Set `AJ_DISCORD_BOT_TOKEN` and `AJ_DISCORD_GUILD_ID` to enable Burrow's Discord bot. It registers `/burrow status|player|reports|staff|announce`, `/moderate warn|silence|unsilence|kick|ban|unban`, and Discord-server moderation commands `/discord timeout|untimeout|kick|ban|unban|purge`. A Discord user must first link their account through Burrow's existing Discord sign-in and hold active Burrow staff status with 2FA; every command then follows the same role permissions, staff-rank safeguards, actions, and audit log as the moderator panel. Discord-native actions cannot target active linked Burrow staff accounts and also require the bot's Discord role to have the matching server permission.
`AJ_DISCORD_REPORTS_CHANNEL_ID` optionally posts each new in-game report with a **Mark handled** button. `AJ_DISCORD_STATUS_CHANNEL_ID` optionally maintains a public live-status card. Set `AJ_DISCORD_GAME_LOGS_CHANNEL_ID` for player sign-in/sign-out logs, `AJ_DISCORD_MOD_LOGS_CHANNEL_ID` for the full moderation audit trail (web panel, in-game staff commands, admin actions, and Discord moderation), and `AJ_DISCORD_BOT_LOGS_CHANNEL_ID` for Discord command/button audit events. Game logs deliberately omit IPs, device IDs, auth tokens, and chat text. All bot replies and notifications use Discord Components V2 (containers and text displays), not legacy message content or embeds.
The owner dashboard's **Discord** tab can start, stop, reconnect, and synchronize the bot; edit notification-channel IDs, the GitHub repository, public status card, security rules, support-ticket settings, and welcome/goodbye notices; and publish the public card immediately. Environment values supply the initial channel configuration. The bot token, guild ID, and GitHub webhook secret deliberately stay in the server environment rather than in the dashboard database.
For GitHub update cards, set `AJ_GITHUB_REPOSITORY` to `owner/repository`, `AJ_GITHUB_WEBHOOK_SECRET`, and `AJ_DISCORD_UPDATES_CHANNEL_ID`. Then add a GitHub webhook for `https://your-public-burrow-host/discord/github`, choose `application/json`, use the same secret, and subscribe to **Pushes**. Signed pushes appear as polished Components V2 cards with commit summaries and a GitHub compare button; commits that change the Flash client or client assets are labelled **Game update**, while other pushes are **Server update**.
# Security # Security
An independent security audit by a Strawberry Jam contributor, who is not part of the Burrow team, found no malware in the Burrow client or server (client v1.2.0, server as of 17 October 2026). Every file in every installer was checked against its source and against the official Electron, NSIS and Adobe Flash releases. The report also lists the weaknesses found, with fixes, and every check can be repeated by anyone. An independent security audit by a Strawberry Jam contributor, who is not part of the Burrow team, found no malware in the Burrow client or server (client v1.2.0, server as of 17 October 2026). Every file in every installer was checked against its source and against the official Electron, NSIS and Adobe Flash releases. The report also lists the weaknesses found, with fixes, and every check can be repeated by anyone.
+70 -12
View File
@@ -101,6 +101,17 @@ module.exports = {
// tried or an account is made, with both set. off without them. // tried or an account is made, with both set. off without them.
turnstile: env.AJ_TURNSTILE_SITE_KEY && env.AJ_TURNSTILE_SECRET turnstile: env.AJ_TURNSTILE_SITE_KEY && env.AJ_TURNSTILE_SECRET
? {siteKey: env.AJ_TURNSTILE_SITE_KEY, secret: env.AJ_TURNSTILE_SECRET} : null, ? {siteKey: env.AJ_TURNSTILE_SITE_KEY, secret: env.AJ_TURNSTILE_SECRET} : null,
// A stalled CAPTCHA provider must not consume all of the VPS's outbound
// sockets. This only limits simultaneous verification requests; normal
// players use one, and a rejected request can safely be retried.
maxConcurrentCaptchaChecks: Math.max(1, Math.min(100, Number(env.AJ_CAPTCHA_MAX_CONCURRENT) || 24)),
// Account-recovery mail is delivered to this HTTPS webhook. It receives
// {to, subject, text}; point it at the transactional-mail provider or
// small mail relay you use. Recovery is deliberately unavailable until
// both values are set, rather than ever exposing a reset link in a page.
recoveryMail: env.AJ_RECOVERY_MAIL_URL && env.AJ_RECOVERY_MAIL_TOKEN
? {url: env.AJ_RECOVERY_MAIL_URL, token: env.AJ_RECOVERY_MAIL_TOKEN} : null,
// asset mirror: anything not served locally is fetched once from here and // asset mirror: anything not served locally is fetched once from here and
// cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only. // cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only.
@@ -108,12 +119,39 @@ module.exports = {
// emoji pictures for chat (lib/emoji.js): Twemoji's, at one version // emoji pictures for chat (lib/emoji.js): Twemoji's, at one version
emojiUpstream: env.AJ_EMOJI_UPSTREAM || "https://cdn.jsdelivr.net/gh/jdecked/[email protected]/assets/72x72/", emojiUpstream: env.AJ_EMOJI_UPSTREAM || "https://cdn.jsdelivr.net/gh/jdecked/[email protected]/assets/72x72/",
offline: env.AJ_OFFLINE === "1", offline: env.AJ_OFFLINE === "1",
// the client's device ids (lib/devices.js): with AJ_REQUIRE_DEVICE=1, a // the client's device ids (lib/devices.js): a game whose launcher sent none
// sign-in without them (a client from before 1.3.0, the official // (a client from before 1.3.0, the official launcher, or one that left
// launcher, or one that left them out) is refused. off for now, while // them out) is turned away at its login, its popup saying to update.
// players update to 1.3.0: they are let in, and an account seen on banned // AJ_REQUIRE_DEVICE=0 lets them in (an account seen on banned hardware
// hardware before is still kept out. // before is still kept out).
requireDevice: env.AJ_REQUIRE_DEVICE === "1", requireDevice: env.AJ_REQUIRE_DEVICE !== "0",
// Discord (lib/discord.js): an application's id and secret for linking a
// player's Discord account on the account page and for allowed accounts to
// sign in to /dashboard/admin (OAuth2 redirects:
// <siteUrl>account/discord/callback,
// <siteUrl>dashboard/admin/discord/callback, and
// <siteUrl>dashboard/staff/discord/callback), and a bot in Burrow's Discord
// server for the booster badge. linking is off without the first two, the
// booster badge left alone without the last two.
discord: {
clientId: env.AJ_DISCORD_CLIENT_ID || "",
clientSecret: env.AJ_DISCORD_CLIENT_SECRET || "",
botToken: env.AJ_DISCORD_BOT_TOKEN || "",
guildId: env.AJ_DISCORD_GUILD_ID || "",
// Optional Components V2 notification channels. Leave any empty to
// disable that stream: reports, public status, game joins/leaves, the
// moderation audit trail, and Discord bot command/audit events.
reportsChannelId: env.AJ_DISCORD_REPORTS_CHANNEL_ID || "",
statusChannelId: env.AJ_DISCORD_STATUS_CHANNEL_ID || "",
gameLogsChannelId: env.AJ_DISCORD_GAME_LOGS_CHANNEL_ID || "",
moderationLogsChannelId: env.AJ_DISCORD_MOD_LOGS_CHANNEL_ID || "",
botLogsChannelId: env.AJ_DISCORD_BOT_LOGS_CHANNEL_ID || "",
// A signed GitHub push webhook at /discord/github can turn commits into
// a Components V2 update card. All three values are needed to enable it.
githubRepository: env.AJ_GITHUB_REPOSITORY || "", // owner/repository
githubWebhookSecret: env.AJ_GITHUB_WEBHOOK_SECRET || "",
updatesChannelId: env.AJ_DISCORD_UPDATES_CHANNEL_ID || "",
},
deployVersion: env.AJ_DEPLOY_VERSION || "1830", deployVersion: env.AJ_DEPLOY_VERSION || "1830",
// older builds the CDN still serves, asked in turn for a room file the // older builds the CDN still serves, asked in turn for a room file the
// current build has dropped. 1828 is the last with the Summer Carnival. // current build has dropped. 1828 is the last with the Summer Carnival.
@@ -132,7 +170,11 @@ module.exports = {
// 41: the game's text says "Burrow" where it said Animal Jam. // 41: the game's text says "Burrow" where it said Animal Jam.
// 48: the item giver (the item finder renamed) with previews and hex colours; // 48: the item giver (the item finder renamed) with previews and hex colours;
// 49 and 50: its link to a colour picker. // 49 and 50: its link to a colour picker.
buildVersion: env.AJ_BUILD_VERSION || "60", // 61: the Owner, Moderator, Developer and Verified name tag badges seen by everyone.
// 62: "Custom pictures" in the settings menu, to hide players' item pictures.
// 83: den items tinted (the tint in their version, DenItemHelper.applyTint).
// 84: fixes from the owner's list of bugs (bugs.txt, 2026-10-23).
buildVersion: env.AJ_BUILD_VERSION || "92",
// what the official CDN is asked for; not ours to change. // what the official CDN is asked for; not ours to change.
upstreamBuildVersion: "3", upstreamBuildVersion: "3",
@@ -165,7 +207,7 @@ module.exports = {
// are written into both pages. the emails and the host's country are // are written into both pages. the emails and the host's country are
// placeholders until set; the operator is, at the owner's word, said to // placeholders until set; the operator is, at the owner's word, said to
// be in the EU without a name or a country. // be in the EU without a name or a country.
termsVersion: "2026-10-17", termsVersion: "2026-10-24",
legalEmail: env.AJ_LEGAL_EMAIL || "[email protected]", legalEmail: env.AJ_LEGAL_EMAIL || "[email protected]",
adminEmail: env.AJ_ADMIN_EMAIL || "[email protected]", adminEmail: env.AJ_ADMIN_EMAIL || "[email protected]",
operator: env.AJ_OPERATOR || "an individual based in the European Union", operator: env.AJ_OPERATOR || "an individual based in the European Union",
@@ -273,11 +315,12 @@ module.exports = {
// can switch in the settings menu (gui.ServerSelector). the game names // can switch in the settings menu (gui.ServerSelector). the game names
// world N after the Nth name of its own list (551 Aldan, 552 Congo..., // world N after the Nth name of its own list (551 Aldan, 552 Congo...,
// generic list 16), so the names here are only for the panels and logs. // generic list 16), so the names here are only for the panels and logs.
// AJ_WORLDS: how many. A local server starts with one shared world so two // AJ_WORLDS: how many (the tests' is one).
// players in the same land can always see one another; set AJ_WORLDS=2 or // the admin panel can change how many while the server runs (lib/world.js
// more to opt into separate copies of every land. // setWorldCount), which then outlasts a restart.
worldNames: ["Aldan", "Congo", "Draa", "Grande", "Kama", "Nile", "Pecos", "Ramu", "Tigris", "Zambezi"],
shards: ["Aldan", "Congo", "Draa", "Grande", "Kama", "Nile", "Pecos", "Ramu", "Tigris", "Zambezi"] shards: ["Aldan", "Congo", "Draa", "Grande", "Kama", "Nile", "Pecos", "Ramu", "Tigris", "Zambezi"]
.slice(0, Math.min(10, Math.max(1, Number(env.AJ_WORLDS) || 1))).map((name, i) => ({id: i + 1, name})), .slice(0, Math.min(10, Math.max(1, Number(env.AJ_WORLDS) || 2))).map((name, i) => ({id: i + 1, name})),
maxUsersPerRoom: 40, maxUsersPerRoom: 40,
// everything in every shop for nothing (AJ_FREE_SHOPS=1). off unless // everything in every shop for nothing (AJ_FREE_SHOPS=1). off unless
// asked for: what the game's shops make of a price of 0 has not been seen. // asked for: what the game's shops make of a price of 0 has not been seen.
@@ -306,6 +349,14 @@ module.exports = {
cacheMissesPerTenMinutes: 1500, // a first visit with an empty cache fetches several hundred files cacheMissesPerTenMinutes: 1500, // a first visit with an empty cache fetches several hundred files
upstreamTimeoutMs: 20000, upstreamTimeoutMs: 20000,
maxCacheBytes: Number(env.AJ_MAX_CACHE_MB || 8192) * 1024 * 1024, maxCacheBytes: Number(env.AJ_MAX_CACHE_MB || 8192) * 1024 * 1024,
// how often at most the packs with custom items in are made again after
// one changes (lib/defpacks.js clientPack); the tests use 0, made at once.
packRemakeMs: env.AJ_PACK_REMAKE_MS === undefined ? 15000 : Number(env.AJ_PACK_REMAKE_MS),
// masterpieces (lib/masterpieces.js): seconds an account must have had
// before it paints one (AJ_MASTERPIECE_MIN_AGE; the tests use 0), and new
// pictures an account may post in any 24 hours.
masterpieceMinAccountAge: env.AJ_MASTERPIECE_MIN_AGE === undefined ? 86400 : Number(env.AJ_MASTERPIECE_MIN_AGE),
masterpiecesPerDay: 10,
maxConnections: 2000, maxConnections: 2000,
maxHttpConnections: 2000, // open at once, in all maxHttpConnections: 2000, // open at once, in all
maxHttpConnectionsPerAddress: 40, // the game opens a good many at once while it loads maxHttpConnectionsPerAddress: 40, // the game opens a good many at once while it loads
@@ -334,6 +385,13 @@ module.exports = {
chatLogDays: env.AJ_CHAT_LOG_DAYS === undefined ? 30 : Math.max(0, Number(env.AJ_CHAT_LOG_DAYS) || 0), chatLogDays: env.AJ_CHAT_LOG_DAYS === undefined ? 30 : Math.max(0, Number(env.AJ_CHAT_LOG_DAYS) || 0),
chatLinesPerWindow: 5, // typed chat lines one player may send ... chatLinesPerWindow: 5, // typed chat lines one player may send ...
chatWindowMs: 3000, // ... in this long chatWindowMs: 3000, // ... in this long
roomActionsPerWindow: 6, // emotes, actions and the like one player may send a room ...
roomActionWindowMs: 3000, // ... in this long (the rest reach nobody)
// eco den items (lib/eco.js): credits an hour for each point of eco power
// placed in a den, and what an account is given the first time it looks
// (an Eco Solar Panel's price)
ecoCreditsPerPointHour: 1,
ecoStartCredits: 1500,
maxBytesPerTenSeconds: 512 * 1024, // per game socket; saving a full den is about 40 KB maxBytesPerTenSeconds: 512 * 1024, // per game socket; saving a full den is about 40 KB
// custom colours (lib/colours.js). every one ever made is sent to every // custom colours (lib/colours.js). every one ever made is sent to every
// player at every login and is never taken out again, so there is an end // player at every login and is never taken out again, so there is an end
+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
+40 -5
View File
@@ -1,15 +1,35 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# brings the server to origin's main and restarts it when the change needs it. # Brings the server to origin's main and restarts it when the change needs it.
# run as root by burrow-update.timer; git itself runs as the server's user. # Run as root by either burrow-update.timer or the OpenRC updater service; git
# itself runs as the server's user.
set -euo pipefail set -euo pipefail
dir=${BURROW_DIR:-/home/aj/ajc-private-server} dir=${BURROW_DIR:-/home/aj/ajc-private-server}
user=${BURROW_USER:-aj} user=${BURROW_USER:-aj}
service=${BURROW_SERVICE:-burrow} service=${BURROW_SERVICE:-burrow}
branch=${BURROW_BRANCH:-main} branch=${BURROW_BRANCH:-main}
init=${BURROW_INIT:-}
git() { runuser -u "$user" -- git -C "$dir" "$@"; } git() { runuser -u "$user" -- git -C "$dir" "$@"; }
restart_service() {
case "$init" in
systemd) systemctl restart "$service" ;;
openrc) rc-service "$service" restart ;;
"")
if [ -d /run/openrc ] || [ -n "${RC_SVCNAME:-}" ]; then
rc-service "$service" restart
else
systemctl restart "$service"
fi
;;
*)
echo "unknown BURROW_INIT value: $init (expected systemd or openrc)" >&2
return 2
;;
esac
}
git fetch --quiet origin "$branch" git fetch --quiet origin "$branch"
old=$(git rev-parse HEAD) old=$(git rev-parse HEAD)
new=$(git rev-parse "origin/$branch") new=$(git rev-parse "origin/$branch")
@@ -27,9 +47,24 @@ for file in $(git diff --name-only "$old" "$new" -- '*.js'); do
fi fi
done done
# public/ is read from disk on every request; the rest is loaded once, at start # the npm packages (only discord.js, for the optional Discord bot): installed
if git diff --name-only "$old" "$new" | grep -qvE '^(public/|client-updates/|test/|tools/|deploy/|[^/]+\.md$|\.gitignore$)'; then # again when the lockfile changed, or when they never were. a failed install
systemctl restart "$service" # leaves the bot off; the game itself needs none of them.
if [ -f "$dir/package-lock.json" ] && { ! git diff --quiet "$old" "$new" -- package-lock.json || [ ! -d "$dir/node_modules" ]; }; then
if command -v npm >/dev/null && runuser -u "$user" -- npm --prefix "$dir" ci --omit=dev --no-audit --no-fund; then
echo "npm packages installed"
else
echo "npm packages could not be installed; the Discord bot stays off" >&2
fi
fi
# public/ is read from disk on every request; the rest is loaded once, at start.
# the list is taken whole first: piped straight into grep -q, a long one (a
# push of many files) had git cut off mid-write ("Broken pipe"), which
# pipefail read as nothing to restart for.
changed=$(git diff --name-only "$old" "$new")
if grep -qvE '^(public/|client-updates/|test/|tools/|deploy/|[^/]+\.md$|\.gitignore$)' <<<"$changed"; then
restart_service
echo "updated $old -> $new, restarted $service" echo "updated $old -> $new, restarted $service"
else else
echo "updated $old -> $new, no restart needed" echo "updated $old -> $new, no restart needed"
+90 -15
View File
@@ -46,7 +46,7 @@ const SCHEMA = `
// fields stored in their own columns rather than in `state`. // fields stored in their own columns rather than in `state`.
const COLUMN_FIELDS = ["id", "username", "salt", "hash", "createdAt"]; const COLUMN_FIELDS = ["id", "username", "salt", "hash", "createdAt"];
// how the game treats the account this session; set again at every login. // how the game treats the account this session; set again at every login.
const SESSION_FIELDS = ["accountType", "isGuide", "isModerator", "membershipDays", "startInDen", "startRoom"]; const SESSION_FIELDS = ["accountType", "isGuide", "guideRefused", "isModerator", "membershipDays", "startInDen", "startRoom"];
const DEFAULT_MEMBERSHIP_DAYS = 9999; const DEFAULT_MEMBERSHIP_DAYS = 9999;
const MAX_ACCOUNT_TYPE = 5; const MAX_ACCOUNT_TYPE = 5;
const MEMBERSHIP_TYPES = [0, 2]; // non-member, member const MEMBERSHIP_TYPES = [0, 2]; // non-member, member
@@ -61,7 +61,9 @@ const USER_VAR_SETTINGS = 363; // the settings menu's switches, a bit each (gui.
// the chat filter an account starts with: level 1 slurs and threats, mode 1 // the chat filter an account starts with: level 1 slurs and threats, mode 1
// the whole message left out (see account.filter below). // the whole message left out (see account.filter below).
const DEFAULT_FILTER = {level: 1, mode: 1, words: ""}; const DEFAULT_FILTER = {level: 1, mode: 1, words: ""};
const chatStyles = require("./chatstyles.js");
const MAX_PASSWORD_LENGTH = 100; const MAX_PASSWORD_LENGTH = 100;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// parts of the game a player can switch off for their own account, each // parts of the game a player can switch off for their own account, each
// enforced where the game asks for it (featureOn below). // enforced where the game asks for it (featureOn below).
// the Early Member badge (lib/badges.js) goes to an account made while // the Early Member badge (lib/badges.js) goes to an account made while
@@ -77,7 +79,10 @@ const LOGIN_DAYS_KEPT = 90; // and none older than this: they hold addresses
let db = null; let db = null;
const byKey = new Map(); // lowercased username -> account const byKey = new Map(); // lowercased username -> account
const byId = new Map(); const byId = new Map();
const savedState = new Map(); // account id -> state JSON as last written // account id -> digest of the state JSON as last written: enough to tell a
// change, without a second copy of every account's state (~13 KB each).
const savedState = new Map();
const stateDigest = json => crypto.createHash("sha256").update(json).digest("base64");
// A name somebody gave up (a rename, a deleted account) is nobody's to take // A name somebody gave up (a rename, a deleted account) is nobody's to take
// for a while: whoever had it is still known by it to the players they met. // for a while: whoever had it is still known by it to the players they met.
const NAME_HELD_DAYS = 30; const NAME_HELD_DAYS = 30;
@@ -216,6 +221,9 @@ const normalize = account => {
// what the player set on the account page (lib/manage.js). // what the player set on the account page (lib/manage.js).
account.features = {...Object.fromEntries(FEATURES.map(name => [name, true])), ...account.features}; // false = switched off account.features = {...Object.fromEntries(FEATURES.map(name => [name, true])), ...account.features}; // false = switched off
account.locked = account.locked === true; // nobody gets into the game until its owner unlocks it account.locked = account.locked === true; // nobody gets into the game until its owner unlocks it
account.recoveryEmail = typeof account.recoveryEmail === "string" && EMAIL_PATTERN.test(account.recoveryEmail)
? account.recoveryEmail.toLowerCase() : "";
account.recoveryTokens = Array.isArray(account.recoveryTokens) ? account.recoveryTokens.filter(token => token && token.expires > now()) : [];
account.logins = account.logins || []; // {at, via, address, ok}, newest first: lib/accounts.js recordLogin account.logins = account.logins || []; // {at, via, address, ok}, newest first: lib/accounts.js recordLogin
account.roomThemes = account.roomThemes || {}; // room -> theme, for rooms given a look of their own ("!theme here") account.roomThemes = account.roomThemes || {}; // room -> theme, for rooms given a look of their own ("!theme here")
account.randomTheme = account.randomTheme === true; // a theme picked afresh at every login account.randomTheme = account.randomTheme === true; // a theme picked afresh at every login
@@ -243,9 +251,18 @@ const normalize = account => {
// the name tag: colour in the low byte, badge above it, bit 16 hides the // the name tag: colour in the low byte, badge above it, bit 16 hides the
// adventure level shape (avatar.NameBar.setColorAndBadge). // adventure level shape (avatar.NameBar.setColorAndBadge).
account.nameBarData = Number.isInteger(account.nameBarData) ? account.nameBarData : 0; account.nameBarData = Number.isInteger(account.nameBarData) ? account.nameBarData : 0;
// Personal chat appearance. The renderer receives it with each spoken line
// (lib/world.js), never as a client-controlled packet field.
account.chatStyle = chatStyles.normalize(account.chatStyle);
account.disguise = Number.isInteger(account.disguise) ? account.disguise : 0; // NPC id, see lib/disguises.js account.disguise = Number.isInteger(account.disguise) ? account.disguise : 0; // NPC id, see lib/disguises.js
// shown on the player's card: lib/badges.js. // shown on the player's card: lib/badges.js.
account.discord = typeof account.discord === "string" ? account.discord : ""; // their Discord username, as they gave it account.discord = typeof account.discord === "string" ? account.discord : ""; // their Discord username, as Discord gave it (lib/discord.js)
if (account.discordId !== undefined && !/^\d{5,25}$/.test(String(account.discordId))) {
delete account.discordId; // the linked Discord account's id
}
// Set only by the owner in /admin. A matching linked Discord identity may
// use this account to open the owner dashboard (lib/discord.js).
account.adminDashboardAccess = account.adminDashboardAccess === true;
account.badges = Array.isArray(account.badges) ? account.badges : []; // badge ids, given in the admin panel account.badges = Array.isArray(account.badges) ? account.badges : []; // badge ids, given in the admin panel
account.bio = typeof account.bio === "string" ? account.bio : ""; // their own words, for the card's Bio tab account.bio = typeof account.bio === "string" ? account.bio : ""; // their own words, for the card's Bio tab
// seconds spent in the game in all (lib/world.js counts it), and whether // seconds spent in the game in all (lib/world.js counts it), and whether
@@ -289,13 +306,17 @@ const MAX_START_ROOM = 80;
function setLoginChoices(account, choices) { function setLoginChoices(account, choices) {
const asked = config.loginChoices && choices && typeof choices === "object" ? choices : {}; const asked = config.loginChoices && choices && typeof choices === "object" ? choices : {};
const whole = (value, max) => Number.isInteger(value) && value >= 0 && value <= max; const whole = (value, max) => Number.isInteger(value) && value >= 0 && value <= max;
// member or not, and guide or not, are the player's own choice on any // member or not is the player's own choice on any server; the rest only
// server; the rest only with config.loginChoices: another account type // with config.loginChoices: another account type shows to everyone.
// shows to everyone.
const own = choices && typeof choices === "object" ? choices : {}; const own = choices && typeof choices === "object" ? choices : {};
const type = MEMBERSHIP_TYPES.includes(own.accountType) ? own.accountType : asked.accountType; const type = MEMBERSHIP_TYPES.includes(own.accountType) ? own.accountType : asked.accountType;
account.accountType = whole(type, MAX_ACCOUNT_TYPE) ? type : config.defaultAccountType; account.accountType = whole(type, MAX_ACCOUNT_TYPE) ? type : config.defaultAccountType;
account.isGuide = own.isGuide === true; // guide (the name tag, the chat bubble, what others see) only for an
// account the admin made one (lib/panel.js); asked for without that, it is
// refused. a guide's own client may leave it off; the official launcher
// asks nothing, and a guide is one.
account.isGuide = account.guideGiven === true && (choices && typeof choices === "object" ? own.isGuide === true : true);
account.guideRefused = own.isGuide === true && account.guideGiven !== true;
account.isModerator = asked.isModerator === true; account.isModerator = asked.isModerator === true;
account.membershipDays = whole(asked.membershipDays, MAX_MEMBERSHIP_DAYS) ? asked.membershipDays : DEFAULT_MEMBERSHIP_DAYS; account.membershipDays = whole(asked.membershipDays, MAX_MEMBERSHIP_DAYS) ? asked.membershipDays : DEFAULT_MEMBERSHIP_DAYS;
// where to start is the player's to say on any server: their own den in // where to start is the player's to say on any server: their own den in
@@ -321,7 +342,7 @@ const insert = (username, salt, hash, createdAt, state) => {
const result = db.prepare("INSERT INTO accounts (username, username_key, password_salt, password_hash, created_at, state) VALUES (?, ?, ?, ?, ?, ?)") const result = db.prepare("INSERT INTO accounts (username, username_key, password_salt, password_hash, created_at, state) VALUES (?, ?, ?, ?, ?, ?)")
.run(username, username.toLowerCase(), salt, hash, createdAt, json); .run(username, username.toLowerCase(), salt, hash, createdAt, json);
account.id = Number(result.lastInsertRowid); account.id = Number(result.lastInsertRowid);
savedState.set(account.id, json); savedState.set(account.id, stateDigest(json));
remember(account); remember(account);
touch(account); touch(account);
return account; return account;
@@ -356,8 +377,11 @@ const load = () => {
fs.mkdirSync(config.dataDir, {recursive: true}); fs.mkdirSync(config.dataDir, {recursive: true});
db = new DatabaseSync(path.join(config.dataDir, "game.sqlite")); db = new DatabaseSync(path.join(config.dataDir, "game.sqlite"));
// busy_timeout: something else writing to the file for a moment (a tool, // busy_timeout: something else writing to the file for a moment (a tool,
// a copy being made) is waited for, not an error. // a copy being made) is waited for, not an error. synchronous NORMAL: with
db.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;"); // WAL the disk is synced at checkpoints, not after every commit, which
// held the game up on each chat line and save; a crash of the server
// loses nothing, a power cut at most the last moment's writes.
db.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;");
db.exec(SCHEMA); db.exec(SCHEMA);
for (const row of db.prepare("SELECT * FROM accounts").all()) { for (const row of db.prepare("SELECT * FROM accounts").all()) {
const account = normalize({ const account = normalize({
@@ -368,7 +392,7 @@ const load = () => {
createdAt: row.created_at, createdAt: row.created_at,
...JSON.parse(row.state), ...JSON.parse(row.state),
}); });
savedState.set(account.id, row.state); savedState.set(account.id, stateDigest(row.state));
remember(account); remember(account);
} }
importLegacyFile(); importLegacyFile();
@@ -462,7 +486,7 @@ const release = account => {
const changedState = (account, changed) => { const changedState = (account, changed) => {
const json = stateJson(account); const json = stateJson(account);
if (savedState.get(account.id) !== json) { if (savedState.get(account.id) !== stateDigest(json)) {
changed.push([account.id, json]); changed.push([account.id, json]);
return true; return true;
} }
@@ -570,7 +594,7 @@ const flush = ({some = false} = {}) => {
throw err; throw err;
} }
for (const [id, json] of changed) { for (const [id, json] of changed) {
savedState.set(id, json); savedState.set(id, stateDigest(json));
} }
}; };
@@ -711,6 +735,35 @@ const register = (username, password, avatar = {}) => {
activeAvatar: 1, activeAvatar: 1,
// early Member, for an account made while there are no more than a hundred. // early Member, for an account made while there are no more than a hundred.
badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [], badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [],
recoveryEmail: typeof avatar.email === "string" && EMAIL_PATTERN.test(avatar.email.trim()) ? avatar.email.trim().toLowerCase() : "",
});
console.log(`[accounts] registered "${logText(username)}" (id ${logText(account.id)})`);
return {account};
};
// Public sign-ups can arrive in a burst. scryptSync is fine for the local,
// legacy Create Account socket but it would freeze all players while each web
// registration is derived. Keep the same validation and database insert on
// the main thread, but derive its password on libuv's worker pool. Check the
// username again after awaiting: another request may have claimed it first.
const registerAsync = async (username, password, avatar = {}) => {
username = typeof username === "string" ? username.trim() : username;
let error = usernameProblem(username) || passwordProblem(password, username) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal");
if (error) {
return {error};
}
const salt = crypto.randomBytes(16).toString("hex");
const hash = await hashPasswordAsync(password, salt);
error = usernameProblem(username) || passwordProblem(password, username) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal");
if (error) {
return {error};
}
const type = Number(avatar.type);
const account = insert(username, salt, hash, now(), {
avatars: [newAvatar({perUserAvId: 1, avInvId: 1}, avatar.name || username, type, -1)],
activeAvatar: 1,
badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [],
recoveryEmail: typeof avatar.email === "string" && EMAIL_PATTERN.test(avatar.email.trim()) ? avatar.email.trim().toLowerCase() : "",
}); });
console.log(`[accounts] registered "${logText(username)}" (id ${logText(account.id)})`); console.log(`[accounts] registered "${logText(username)}" (id ${logText(account.id)})`);
return {account}; return {account};
@@ -789,7 +842,10 @@ const storableUsernameProblem = username => {
}; };
// gives the account a new username, and carries it into everyone's buddy and // gives the account a new username, and carries it into everyone's buddy and
// block lists. returns "invalid_username" or "username_taken", else null. // block lists. The staff dashboard stores a few human-readable names beside
// account ids; keep those labels current too, so a rename does not split a
// player's history across two names. Returns "invalid_username" or
// "username_taken", else null.
// the player must not be online: the game knows them by the old name. // the player must not be online: the game knows them by the old name.
// with `anyName` (the admin panel) the sign-up rules about length and // with `anyName` (the admin panel) the sign-up rules about length and
// characters do not apply; see storableUsernameProblem. // characters do not apply; see storableUsernameProblem.
@@ -811,6 +867,18 @@ const rename = (account, username, anyName = false) => {
} }
db.prepare("UPDATE accounts SET username = ?, username_key = ? WHERE id = ?").run(username, newKey, account.id); db.prepare("UPDATE accounts SET username = ?, username_key = ? WHERE id = ?").run(username, newKey, account.id);
console.log(`[accounts] renamed "${logText(account.username)}" to "${logText(username)}" (id ${logText(account.id)})`); console.log(`[accounts] renamed "${logText(account.username)}" to "${logText(username)}" (id ${logText(account.id)})`);
for (const [table, column] of [
["reports", "reporter"], ["reports", "target"], ["feedback", "username"],
["chat_log", "username"], ["chat_log", "to_name"], ["appeals", "username"],
["ban_log", "username"], ["mod_log", "by"], ["mod_log", "target"],
]) {
// A few lean unit tests load the account store without every dashboard
// module. The tables are present in the actual server, but keep rename
// usable in that smaller setup too.
if (db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table)) {
db.prepare(`UPDATE ${table} SET ${column} = ? WHERE ${column} = ? COLLATE NOCASE`).run(username, account.username);
}
}
byKey.delete(oldKey); byKey.delete(oldKey);
account.username = username; account.username = username;
byKey.set(newKey, account); byKey.set(newKey, account);
@@ -905,10 +973,17 @@ const byToken = token => {
const byName = username => touch(byKey.get(String(username).toLowerCase())) || null; const byName = username => touch(byKey.get(String(username).toLowerCase())) || null;
// a username as its account spells it, or null. only asks whether there is
// one: unlike byName it does not count as the account being in use.
const nameOf = username => {
const account = byKey.get(String(username).toLowerCase());
return account ? account.username : null;
};
const accountById = id => touch(byId.get(Number(id))) || null; const accountById = id => touch(byId.get(Number(id))) || null;
const all = () => [...byId.values()]; const all = () => [...byId.values()];
const database = () => db; const database = () => db;
module.exports = {FEATURES, featureOn, recordLogin, revokeTokens, load, save, flush, hold, release, startBackups, database, setLoginChoices, setPassword, rename, remove, setting, setSetting, hashPassword, register, usernameProblem, authenticate, authenticateAsync, issueToken, byToken, byName, byId: accountById, newAvatar, freeAvatarSlot, all}; module.exports = {FEATURES, featureOn, recordLogin, revokeTokens, load, save, flush, hold, release, startBackups, database, setLoginChoices, setPassword, rename, remove, setting, setSetting, hashPassword, register, registerAsync, usernameProblem, authenticate, authenticateAsync, issueToken, byToken, byName, nameOf, byId: accountById, newAvatar, freeAvatarSlot, all};
+150 -5
View File
@@ -2,6 +2,8 @@
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const bans = require("./bans.js"); const bans = require("./bans.js");
const cdn = require("./cdn.js");
const colours = require("./colours.js");
const captcha = require("./captcha.js"); const captcha = require("./captcha.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const devices = require("./devices.js"); const devices = require("./devices.js");
@@ -10,6 +12,7 @@ const roles = require("./roles.js");
const dens = require("./dens.js"); const dens = require("./dens.js");
const itemControl = require("./itemcontrol.js"); const itemControl = require("./itemcontrol.js");
const customItems = require("./customitems.js"); const customItems = require("./customitems.js");
const itemArt = require("./itemart.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const world = require("./world.js"); const world = require("./world.js");
const {addClothing, sendClothingAdded, isUint} = require("./player.js"); const {addClothing, sendClothingAdded, isUint} = require("./player.js");
@@ -71,6 +74,24 @@ const search = (params, favourites = null, seesLocked = false, askerId = null) =
}; };
}; };
// the variants each den item's art has (tools/den-variants.sh):
// {versions: [...], colours?: [[hex, ...] per variant]}, or null.
let denVariants = null;
const variantsOf = id => {
if (!denVariants) {
try {
denVariants = require("./den-variants.json");
}
catch (err) {
denVariants = {};
}
}
return denVariants[Number(id)] || null;
};
const SPECIAL_MANNEQUIN = "4";
const MAX_TINT_SLOT = 0x7FFFFF; // what fits above a den item's variant (8 bits) in its version, kept positive
const MAX_PRESETS = 40;
// one to four "#RRGGBB", spaces or commas between. the # is wanted: six // one to four "#RRGGBB", spaces or commas between. the # is wanted: six
// digits alone are a colour id // digits alone are a colour id
const HEX_COLOURS = /^#[0-9a-f]{6}([\s,]+#[0-9a-f]{6}){0,3}$/i; const HEX_COLOURS = /^#[0-9a-f]{6}([\s,]+#[0-9a-f]{6}){0,3}$/i;
@@ -89,6 +110,7 @@ const give = (body, seesLocked = false) => {
return {status: 403, body: {error: "That item is locked out of the item finder."}}; return {status: 403, body: {error: "That item is locked out of the item finder."}};
} }
const session = world.findOnline(account.username); const session = world.findOnline(account.username);
const given = {}; // what the item was given as: its colour, or its version
if (body.kind === "clothing") { if (body.kind === "clothing") {
const def = defpacks.itemDef(body.id); const def = defpacks.itemDef(body.id);
const colors = def ? String(def.colors).split(",") : []; const colors = def ? String(def.colors).split(",") : [];
@@ -110,9 +132,18 @@ const give = (body, seesLocked = false) => {
} }
custom = String(entry.id); custom = String(entry.id);
} }
// a colour id written signed, as lists of the game's colours often do
// them: the same 32 bits, kept as the game keeps colours (unsigned), so
// -16777216 is 4278190080.
if (/^-\d{1,10}$/.test(custom) && Number(custom) >= -0x80000000) {
custom = String(Number(custom) >>> 0);
}
if (custom && !isUint(custom)) { if (custom && !isUint(custom)) {
return {status: 400, body: {error: "Colour: an id, or #RRGGBB"}}; return {status: 400, body: {error: "Colour: an id, or #RRGGBB"}};
} }
if (custom && !colours.known(Number(custom))) {
return {status: 400, body: {error: "No such custom colour"}};
}
const color = custom || colors[Number(body.colorIndex) || 0]; const color = custom || colors[Number(body.colorIndex) || 0];
if (!def || !defpacks.clothingIds().includes(Number(def.id)) || color === undefined) { if (!def || !defpacks.clothingIds().includes(Number(def.id)) || color === undefined) {
return {status: 400, body: {error: "No such clothing item or colour"}}; return {status: 400, body: {error: "No such clothing item or colour"}};
@@ -121,6 +152,7 @@ const give = (body, seesLocked = false) => {
if (!item) { if (!item) {
return {status: 409, body: {error: "That inventory is full"}}; return {status: 409, body: {error: "That inventory is full"}};
} }
given.color = Number(color);
accounts.save(account); accounts.save(account);
if (session) { if (session) {
sendClothingAdded(session, item); sendClothingAdded(session, item);
@@ -130,12 +162,48 @@ const give = (body, seesLocked = false) => {
if (!defpacks.denItemIds().includes(Number(body.id))) { if (!defpacks.denItemIds().includes(Number(body.id))) {
return {status: 400, body: {error: "No such den item"}}; return {status: 400, body: {error: "No such den item"}};
} }
if (!dens.giveDenItem(account, body.id)) { // `version`: one of the variants its art has (above), 0 by default.
// `tint` ("#RRGGBB") and `tintStrength` (1-100, 100 by default): the
// whole item in shades of that colour, which the patched client draws
// (DenItemHelper.applyTint). the tint is a custom colour entry
// (lib/colours.js, [rgb, strength, 0, 0]), and 1 + its number goes in
// the version above the variant's 8 bits, so it goes wherever the item
// goes: dens, trades, gifts.
const variants = variantsOf(body.id);
const variant = body.version === undefined || body.version === "" ? 0 : Number(body.version);
if (!Number.isInteger(variant) || (variant !== 0 && !(variants && variants.versions.includes(variant)))) {
return {status: 400, body: {error: "That item has no such variant"}};
}
let version = variant;
const tint = typeof body.tint === "string" ? body.tint.trim() : "";
if (tint) {
const strength = body.tintStrength === undefined || body.tintStrength === "" ? 100 : Number(body.tintStrength);
if (!/^#[0-9a-f]{6}$/i.test(tint) || !Number.isInteger(strength) || strength < 1 || strength > 100) {
return {status: 400, body: {error: "Tint: #RRGGBB, strength 1 to 100"}};
}
if ((defpacks.denItemDef(body.id) || {}).specialType === SPECIAL_MANNEQUIN) {
return {status: 400, body: {error: "Mannequins cannot be tinted"}};
}
const entry = world.makeColour(account, [parseInt(tint.slice(1), 16), strength, 0, 0], session);
if (!entry) {
return {status: 400, body: {error: "Bad colour"}};
}
if (entry.full) {
return {status: 429, body: {error: "No more new colours today. Colours made before can still be used."}};
}
const slot = entry.id - colours.CUSTOM_BASE + 1;
if (slot > MAX_TINT_SLOT) {
return {status: 503, body: {error: "No more tints can be made"}};
}
version |= slot << 8;
}
if (!dens.giveDenItem(account, body.id, version)) {
return {status: 409, body: {error: "That inventory is full"}}; return {status: 409, body: {error: "That inventory is full"}};
} }
if (session) { if (session) {
dens.sendDenItems(session); dens.sendDenItems(session);
} }
given.version = version;
} }
else { else {
return {status: 400, body: {error: "Unknown item kind"}}; return {status: 400, body: {error: "Unknown item kind"}};
@@ -146,7 +214,81 @@ const give = (body, seesLocked = false) => {
const kept = Object.entries(account.finderGiven).sort((one, other) => other[1].at - one[1].at).slice(0, MAX_FAVOURITES); const kept = Object.entries(account.finderGiven).sort((one, other) => other[1].at - one[1].at).slice(0, MAX_FAVOURITES);
account.finderGiven = Object.fromEntries(kept); account.finderGiven = Object.fromEntries(kept);
accounts.save(account); accounts.save(account);
return {status: 200, body: {ok: true, online: Boolean(session)}}; return {status: 200, body: {ok: true, online: Boolean(session), ...given}};
};
// the game's 256 colours (the CDN's paletteData; PaletteHelper.setGamePalette),
// as "rrggbb", once read. null while the file cannot be had.
let palette = null;
const loadPalette = async () => {
if (!palette) {
const file = await cdn.get(cdn.hashedPath("paletteData"));
if (file && file.length >= 4 && file.readInt32BE(0) === 1024) {
palette = Array.from({length: 256}, (unused, index) => (file.readUInt32BE(4 + index * 4) & 0xFFFFFF).toString(16).padStart(6, "0"));
}
}
return palette;
};
// a packed colour's four, as "rrggbb" (a custom colour's own, or the
// palette's at each of its four bytes, colour 1 the top one).
const coloursOf = id => {
const custom = colours.rgbsOf(id);
if (custom) {
return custom.map(rgb => rgb.toString(16).padStart(6, "0"));
}
return palette ? [24, 16, 8, 0].map(shift => palette[(id >>> shift) & 0xFF]) : null;
};
// the web item giver (/account/items, lib/manage.js): a search as the
// in-game one, with what each item may be given as: a clothing item's own
// colours, a den item's variants and whether it takes a tint.
const searchFor = async (account, params) => {
await loadPalette();
const found = search(params, account.finderGiven, roles.can(account, "items.create"), account.id);
return {...found, results: found.results.map(result => {
// a custom item's own picture, which the game shows in place of its art
const custom = customItems.get(result.kind, result.id);
const entry = {...result, art: custom ? itemArt.urlOf(custom, "/account/api/itemart") : null};
if (entry.kind === "clothing") {
const def = defpacks.itemDef(entry.id);
const ids = def ? String(def.colors).split(",").map(Number).filter(Number.isInteger).slice(0, MAX_PRESETS) : [];
return {...entry, presets: ids.map(id => ({id: id >>> 0, colours: coloursOf(id >>> 0)}))};
}
const variants = variantsOf(entry.id);
return {...entry, variants: variants ? variants.versions : [], variantColours: variants && variants.colours ? variants.colours : null,
tintable: (defpacks.denItemDef(entry.id) || {}).specialType !== SPECIAL_MANNEQUIN};
})};
};
// ... and its colour boxes, which turn colours to the game's numbers and
// back as they are typed: with `id`, a custom colour's four ("rrggbb"); with
// `rgbs` (four "rrggbb", commas between), the custom colour already made of
// those four, or null (Give would make it); with neither, the game's 256.
const colourLookup = async params => {
if (params.has("id")) {
const text = params.get("id");
const id = /^-?\d{1,10}$/.test(text) && Number(text) >= -0x80000000 && Number(text) <= 0xFFFFFFFF ? Number(text) >>> 0 : null;
const rgbs = id === null ? null : colours.rgbsOf(id);
return rgbs ? {status: 200, body: {id, colours: rgbs.map(rgb => rgb.toString(16).padStart(6, "0"))}}
: {status: 404, body: {error: "No such custom colour"}};
}
if (params.has("rgbs")) {
const rgbs = params.get("rgbs").split(",").map(hex => (/^[0-9a-f]{6}$/i.test(hex) ? parseInt(hex, 16) : NaN));
const entry = colours.allocate(rgbs, false);
if (!entry) {
return {status: 400, body: {error: "Four colours: rrggbb,rrggbb,rrggbb,rrggbb"}};
}
return {status: 200, body: {id: entry.full ? null : entry.id}};
}
return {status: 200, body: {palette: await loadPalette()}};
};
// ... and its Give, for the account signed in on that page.
const giveAs = (account, body) => {
if (!givesPerMinute.allow(account.id)) {
return {status: 429, body: {error: "Too many at once. Try again in a minute."}};
}
return give({...body, username: account.username}, roles.can(account, "items.create"));
}; };
const FORBIDDEN = {status: 403, body: {error: "forbidden"}}; const FORBIDDEN = {status: 403, body: {error: "forbidden"}};
@@ -251,7 +393,10 @@ const handle = async (route, params, body, from) => {
if (device && devices.banOf(device)) { if (device && devices.banOf(device)) {
return {status: 403, body: {error: "device_banned"}}; return {status: 403, body: {error: "device_banned"}};
} }
const {username, password, avatarType} = body || {}; const {username, password, avatarType, email} = body || {};
if (config.recoveryMail && (typeof email !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim()))) {
return {status: 400, body: {error: "invalid_email"}};
}
// the terms and the privacy policy, and old enough to agree to them: // the terms and the privacy policy, and old enough to agree to them:
// said by the one signing up, on the page or in the client. // said by the one signing up, on the page or in the client.
if ((body || {}).agreed !== true) { if ((body || {}).agreed !== true) {
@@ -273,7 +418,7 @@ const handle = async (route, params, body, from) => {
if (!STARTER_ANIMALS.includes(avatarType)) { if (!STARTER_ANIMALS.includes(avatarType)) {
return {status: 400, body: {error: "choose_animal"}}; return {status: 400, body: {error: "choose_animal"}};
} }
const result = accounts.register(username, password, {type: avatarType}); const result = await accounts.registerAsync(username, password, {type: avatarType, email});
if (result.account) { if (result.account) {
result.account.agreed = {version: config.termsVersion, at: Math.floor(Date.now() / 1000)}; result.account.agreed = {version: config.termsVersion, at: Math.floor(Date.now() / 1000)};
accounts.save(result.account); accounts.save(result.account);
@@ -287,4 +432,4 @@ const handle = async (route, params, body, from) => {
} }
}; };
module.exports = {handle, search}; module.exports = {handle, search, searchFor, colourLookup, giveAs};
+4 -1
View File
@@ -537,9 +537,12 @@ module.exports = {
for (const number of [2, 3, 4]) { for (const number of [2, 3, 4]) {
set(q, `cork_${number}${pick("abc")}`, 1, 1, 0); set(q, `cork_${number}${pick("abc")}`, 1, 1, 0);
} }
for (const number of [1, 2, 3, 4]) { // the last key's other places lie off where an animal can walk:
// players had to jump to it. it lies where the recording had it.
for (const number of [1, 2, 3]) {
set(q, `bunny_key_${number}${pick("abcdef")}`, 1, 1, 0); set(q, `bunny_key_${number}${pick("abcdef")}`, 1, 1, 0);
} }
set(q, "bunny_key_4c", 1, 1, 0);
}); });
}, },
+105 -32
View File
@@ -177,40 +177,89 @@ class Amf3Reader {
// writer for what the reader above produces from a defPack: plain objects, // writer for what the reader above produces from a defPack: plain objects,
// arrays (with or without string keys), strings, numbers, booleans and null. // arrays (with or without string keys), strings, numbers, booleans and null.
// nothing is written as a reference except repeated strings. // nothing is written as a reference except repeated strings.
// written into one buffer that grows: a pack is megabytes of small values,
// and a Buffer for each of them took seconds for the item pack.
class Amf3Writer { class Amf3Writer {
constructor() { constructor() {
this.parts = []; this.buf = Buffer.allocUnsafe(1 << 16);
this.pos = 0;
this.strings = new Map(); this.strings = new Map();
} }
room(bytes) {
if (this.pos + bytes > this.buf.length) {
let size = this.buf.length * 2;
while (size < this.pos + bytes) {
size *= 2;
}
const bigger = Buffer.allocUnsafe(size);
this.buf.copy(bigger, 0, 0, this.pos);
this.buf = bigger;
}
}
byte(value) {
this.room(1);
this.buf[this.pos++] = value;
}
u29(value) { u29(value) {
this.room(4);
const {buf} = this;
if (value < 0x80) { if (value < 0x80) {
this.parts.push(Buffer.from([value])); buf[this.pos++] = value;
} }
else if (value < 0x4000) { else if (value < 0x4000) {
this.parts.push(Buffer.from([(value >> 7) | 0x80, value & 0x7f])); buf[this.pos++] = (value >> 7) | 0x80;
buf[this.pos++] = value & 0x7f;
} }
else if (value < 0x200000) { else if (value < 0x200000) {
this.parts.push(Buffer.from([(value >> 14) | 0x80, ((value >> 7) & 0x7f) | 0x80, value & 0x7f])); buf[this.pos++] = (value >> 14) | 0x80;
buf[this.pos++] = ((value >> 7) & 0x7f) | 0x80;
buf[this.pos++] = value & 0x7f;
} }
else { else {
this.parts.push(Buffer.from([(value >> 22) | 0x80, ((value >> 15) & 0x7f) | 0x80, ((value >> 8) & 0x7f) | 0x80, value & 0xff])); buf[this.pos++] = (value >> 22) | 0x80;
buf[this.pos++] = ((value >> 15) & 0x7f) | 0x80;
buf[this.pos++] = ((value >> 8) & 0x7f) | 0x80;
buf[this.pos++] = value & 0xff;
} }
} }
string(text) { string(text) {
if (text === "") { if (text === "") {
this.u29(1); this.u29(1);
return;
} }
else if (this.strings.has(text)) { const known = this.strings.get(text);
this.u29(this.strings.get(text) << 1); if (known !== undefined) {
this.u29(known << 1);
return;
} }
else { this.strings.set(text, this.strings.size);
this.strings.set(text, this.strings.size); // nearly every string of a pack is short and ASCII: its bytes are its
const bytes = Buffer.from(text, "utf8"); // characters, copied here rather than through Buffer's utf8 writer.
this.u29((bytes.length << 1) | 1); if (text.length < 64) {
this.parts.push(bytes); let ascii = true;
for (let i = 0; i < text.length; i++) {
if (text.charCodeAt(i) > 0x7f) {
ascii = false;
break;
}
}
if (ascii) {
this.u29((text.length << 1) | 1);
this.room(text.length);
for (let i = 0; i < text.length; i++) {
this.buf[this.pos++] = text.charCodeAt(i);
}
return;
}
} }
const length = Buffer.byteLength(text, "utf8");
this.u29((length << 1) | 1);
this.room(length);
this.pos += this.buf.write(text, this.pos, "utf8");
} }
pairs(entries) { pairs(entries) {
@@ -222,45 +271,69 @@ class Amf3Writer {
} }
value(value) { value(value) {
if (value === undefined) { // most values of a pack are strings: asked first
this.parts.push(Buffer.from([0x00])); if (typeof value === "string") {
this.byte(0x06);
this.string(value);
}
else if (value === undefined) {
this.byte(0x00);
} }
else if (value === null) { else if (value === null) {
this.parts.push(Buffer.from([0x01])); this.byte(0x01);
} }
else if (typeof value === "boolean") { else if (typeof value === "boolean") {
this.parts.push(Buffer.from([value ? 0x03 : 0x02])); this.byte(value ? 0x03 : 0x02);
} }
else if (typeof value === "number") { else if (typeof value === "number") {
if (Number.isInteger(value) && value >= -0x10000000 && value < 0x10000000) { if (Number.isInteger(value) && value >= -0x10000000 && value < 0x10000000) {
this.parts.push(Buffer.from([0x04])); this.byte(0x04);
this.u29(value & 0x1fffffff); this.u29(value & 0x1fffffff);
} }
else { else {
const bytes = Buffer.alloc(9); this.byte(0x05);
bytes[0] = 0x05; this.room(8);
bytes.writeDoubleBE(value, 1); this.pos = this.buf.writeDoubleBE(value, this.pos);
this.parts.push(bytes);
} }
} }
else if (typeof value === "string") {
this.parts.push(Buffer.from([0x06]));
this.string(value);
}
else if (Array.isArray(value)) { else if (Array.isArray(value)) {
this.parts.push(Buffer.from([0x09])); this.byte(0x09);
this.u29((value.length << 1) | 1); this.u29((value.length << 1) | 1);
// string keys set on the array beside its numbered elements. // string keys set on the array beside its numbered elements (an array
this.pairs(Object.entries(value).filter(([key]) => !/^\d+$/.test(key))); // with as many keys as elements has none).
const keys = Object.keys(value);
this.pairs(keys.length === value.length ? [] : keys.filter(key => !/^\d+$/.test(key)).map(key => [key, value[key]]));
for (const element of value) { for (const element of value) {
this.value(element); this.value(element);
} }
} }
else if (typeof value === "object" && !Buffer.isBuffer(value)) { else if (value instanceof Date) {
// A date (a room file's timestamps): its milliseconds, written in place.
this.byte(0x08);
this.u29(1);
this.room(8);
this.pos = this.buf.writeDoubleBE(value.getTime(), this.pos);
}
else if (Buffer.isBuffer(value)) {
// A ByteArray (a room file's pictures and shapes).
this.byte(0x0c);
this.u29((value.length << 1) | 1);
this.room(value.length);
this.pos += value.copy(this.buf, this.pos);
}
else if (typeof value === "object") {
// A dynamic object of no class, with its traits written in place. // A dynamic object of no class, with its traits written in place.
this.parts.push(Buffer.from([0x0a, 0x0b])); this.byte(0x0a);
this.byte(0x0b);
this.string("");
// its own keys in Object.keys order, without an array of entries for each object
for (const key in value) {
if (Object.hasOwn(value, key)) {
this.string(key);
this.value(value[key]);
}
}
this.string(""); this.string("");
this.pairs(Object.entries(value));
} }
else { else {
throw new Error("Cannot write this value as AMF3"); throw new Error("Cannot write this value as AMF3");
@@ -273,6 +346,6 @@ module.exports = {
encode: value => { encode: value => {
const writer = new Amf3Writer(); const writer = new Amf3Writer();
writer.value(value); writer.value(value);
return Buffer.concat(writer.parts); return writer.buf.subarray(0, writer.pos);
}, },
}; };
+11 -3
View File
@@ -97,6 +97,12 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
const messageRoom = session.room ? session.room.id : -1; const messageRoom = session.room ? session.room.id : -1;
const common = [1, session.id, avatar.perUserAvId, avatar.avInvId, avatar.customAvId, avatar.type, ...avatar.colors, avatar.name]; const common = [1, session.id, avatar.perUserAvId, avatar.avInvId, avatar.customAvId, avatar.type, ...avatar.colors, avatar.name];
session.sendXt("as", messageRoom, ...common, avatar.petInvId, avatar.questLevel || 0); session.sendXt("as", messageRoom, ...common, avatar.petInvId, avatar.questLevel || 0);
// Nothing more goes to the switching player here. The client swaps the
// animals during the transform animation (AvatarSwitch "hideAvatar"),
// copying the in-world avatar into the switcher slot first and asking
// for "ad" itself when it needs to. An unasked "ad"/"il" lands on the
// in-world avatar before that copy, so the old animal vanished from the
// switcher and the new one showed twice.
if (session.pos) { if (session.pos) {
for (const other of others(session)) { for (const other of others(session)) {
other.sendXt("as", messageRoom, ...common, ...petFields(activePet(account)), avatar.questLevel || 0); other.sendXt("as", messageRoom, ...common, ...petFields(activePet(account)), avatar.questLevel || 0);
@@ -104,12 +110,12 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
} }
}, },
// AvatarSwitch.avatarKillResponse: [success, ?] // AvatarSwitch.avatarKillResponse: [success, gems]
ak(session, roomId, [perUserAvId]) { ak(session, roomId, [perUserAvId]) {
const {account} = session; const {account} = session;
const avatar = account.avatars.find(candidate => candidate.perUserAvId === Number(perUserAvId)); const avatar = account.avatars.find(candidate => candidate.perUserAvId === Number(perUserAvId));
if (!avatar || avatar === activeAvatar(account) || account.avatars.length < 2) { if (!avatar || avatar === activeAvatar(account) || account.avatars.length < 2) {
session.sendXt("ak", -1, 0, 0); session.sendXt("ak", -1, 0, account.currency.gems);
return; return;
} }
account.avatars = account.avatars.filter(candidate => candidate !== avatar); account.avatars = account.avatars.filter(candidate => candidate !== avatar);
@@ -117,7 +123,9 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId); item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId);
} }
accounts.save(account); accounts.save(account);
session.sendXt("ak", -1, 1, 0); // [success, gems]: the animal switcher (AvatarSwitcher.recycleAvatarCallback)
// shows the second as the player's gems, so it is their total, unchanged.
session.sendXt("ak", -1, 1, account.currency.gems);
}, },
// AvatarXtCommManager.requestColorChange: [color1, color2, color3, nameBarData] // AvatarXtCommManager.requestColorChange: [color1, color2, color3, nameBarData]
+4 -2
View File
@@ -33,7 +33,9 @@ const cdn = require("./cdn.js");
// there are no more than a hundred (lib/accounts.js); the admin may give // there are no more than a hundred (lib/accounts.js); the admin may give
// it and take it away like any other. // it and take it away like any other.
// in the order they are listed and drawn. // in the order they are listed and drawn. the Verified, Owner, Moderator and
// Developer name tags show their badge to everyone, not only to buddies:
// their def ids are in PUBLIC_BADGE_IDS of swf-src/AvatarWorldView.as.
const BADGES = [ const BADGES = [
// first, so its tick comes straight after the name, as on other sites. // first, so its tick comes straight after the name, as on other sites.
{id: "verified", label: "Verified", tag: {def: 76, media: 20014, bit: 21}}, {id: "verified", label: "Verified", tag: {def: 76, media: 20014, bit: 21}},
@@ -63,7 +65,7 @@ const set = (account, ids) => {
}; };
// A Discord username as Discord has them now: 2 to 32 of a-z, 0-9, "_" and // A Discord username as Discord has them now: 2 to 32 of a-z, 0-9, "_" and
// ".", with no two dots in a row. nobody checks that it is theirs. // ".", with no two dots in a row. players link theirs (lib/discord.js).
const DISCORD_NAME = /^(?!.*\.\.)[a-z0-9_.]{2,32}$/; const DISCORD_NAME = /^(?!.*\.\.)[a-z0-9_.]{2,32}$/;
// returns the username as it will be kept ("" for none), or null when it // returns the username as it will be kept ("" for none), or null when it
+13 -1
View File
@@ -26,10 +26,12 @@ const MAX_ANSWER_LENGTH = 2048;
const PASS_MS = 600000; const PASS_MS = 600000;
const PASS_USES = 5; const PASS_USES = 5;
const MAX_PASSES = 10000; const MAX_PASSES = 10000;
const MAX_VERIFYING = config.maxConcurrentCaptchaChecks;
const on = Boolean(config.turnstile); const on = Boolean(config.turnstile);
const passes = new Map(); // SHA-256 of a pass -> {id: account id, key: address key, expiry, uses} const passes = new Map(); // SHA-256 of a pass -> {id: account id, key: address key, expiry, uses}
const sha256 = text => crypto.createHash("sha256").update(String(text)).digest("hex"); const sha256 = text => crypto.createHash("sha256").update(String(text)).digest("hex");
let verifying = 0;
// for the pages: what each answer means // for the pages: what each answer means
const MESSAGES = { const MESSAGES = {
@@ -70,6 +72,13 @@ const verify = async (answer, from, action) => {
if (typeof answer !== "string" || !answer || answer.length > MAX_ANSWER_LENGTH) { if (typeof answer !== "string" || !answer || answer.length > MAX_ANSWER_LENGTH) {
return "captcha_required"; return "captcha_required";
} }
// A burst of valid-looking tokens should not turn an upstream Turnstile
// slowdown into thousands of open fetches on this VPS. Refuse quickly;
// the browser can reset its widget and retry after the short outage.
if (verifying >= MAX_VERIFYING) {
return "captcha_unavailable";
}
verifying++;
const form = new URLSearchParams({secret: config.turnstile.secret, response: answer}); const form = new URLSearchParams({secret: config.turnstile.secret, response: answer});
if (!limits.isLoopback(from.address)) { if (!limits.isLoopback(from.address)) {
form.set("remoteip", from.address); form.set("remoteip", from.address);
@@ -83,6 +92,9 @@ const verify = async (answer, from, action) => {
console.log(`[captcha] cloudflare did not answer: ${logText(err.message)}`); console.log(`[captcha] cloudflare did not answer: ${logText(err.message)}`);
return "captcha_unavailable"; return "captcha_unavailable";
} }
finally {
verifying--;
}
// an answer made for another form is no answer for this one. cloudflare's // an answer made for another form is no answer for this one. cloudflare's
// test keys give none. // test keys give none.
if (!result || result.success !== true || (result.action && result.action !== action)) { if (!result || result.success !== true || (result.action && result.action !== action)) {
@@ -107,7 +119,7 @@ const check = async (body, from, action, account) => {
// a page's security policy: public/captcha.js always (the page calls it even // a page's security policy: public/captcha.js always (the page calls it even
// when off), and the widget too when it is on. // when off), and the widget too when it is on.
const policy = csp => (on const policy = csp => (on
? `${csp.replace("script-src ", `script-src 'self' ${ORIGIN} `)}; frame-src ${ORIGIN}` ? `${csp.replace("script-src ", `script-src 'self' ${ORIGIN} `).replace("connect-src ", `connect-src 'self' ${ORIGIN} `)}; frame-src ${ORIGIN}`
: csp.replace("script-src ", "script-src 'self' ")); : csp.replace("script-src ", "script-src 'self' "));
// a page with public/captcha.js asked for under a name that changes with the // a page with public/captcha.js asked for under a name that changes with the
+79
View File
@@ -0,0 +1,79 @@
"use strict";
// The style travels with a chat line, rather than with an avatar-create
// packet, so a new choice takes effect immediately and is seen by everybody
// who sees that line. Keep it small and entirely server-generated: clients
// never get to choose the fields sent to other players.
const DEFAULT = Object.freeze({background: "ffffff", accent: "dfe8ff", text: "445559", border: "9aabb0", opacity: 75,
animation: "none", speed: 100, gradient: "linear", angle: 45, strength: 100, outline: 1,
stops: "ffffff:0;dfe8ff:100"});
const ANIMATIONS = new Set(["none", "pulse", "shimmer", "flow", "rainbow"]);
const GRADIENTS = new Set(["solid", "linear", "radial"]);
const COLOR = /^[0-9a-f]{6}$/i;
const color = (value, fallback) => typeof value === "string" && COLOR.test(value) ? value.toLowerCase() : fallback;
const number = (value, fallback, low, high) => Number.isInteger(value) && value >= low && value <= high ? value : fallback;
const direction = value => {
const angle = number(value, DEFAULT.angle, 0, 315);
return angle % 45 === 0 ? angle : DEFAULT.angle;
};
const stops = (value, background, accent) => {
if (typeof value === "string") {
const parsed = value.split(";").map(stop => {
const match = /^([0-9a-f]{6}):(100|[1-9]?\d)$/i.exec(stop);
return match ? {color: match[1].toLowerCase(), position: Number(match[2])} : null;
});
if (parsed.length >= 2 && parsed.length <= 5 && parsed.every(Boolean)
&& parsed[0].position === 0 && parsed.at(-1).position === 100
&& parsed.every((stop, index) => index === 0 || stop.position > parsed[index - 1].position)) {
return parsed.map(stop => `${stop.color}:${stop.position}`).join(";");
}
}
return `${background}:0;${accent}:100`;
};
const normalize = value => {
const source = value && typeof value === "object" && !Array.isArray(value) ? value : {};
let background = color(source.background, DEFAULT.background);
let accent = color(source.accent, DEFAULT.accent);
const gradientStops = stops(source.stops, background, accent);
const stopParts = gradientStops.split(";");
background = stopParts[0].slice(0, 6);
accent = stopParts.at(-1).slice(0, 6);
return {
background,
accent,
text: color(source.text, DEFAULT.text),
border: color(source.border, DEFAULT.border),
opacity: number(source.opacity, DEFAULT.opacity, 25, 100),
animation: ANIMATIONS.has(source.animation) ? source.animation : DEFAULT.animation,
speed: number(source.speed, DEFAULT.speed, 40, 300),
gradient: GRADIENTS.has(source.gradient) ? source.gradient : DEFAULT.gradient,
angle: direction(source.angle),
strength: number(source.strength, DEFAULT.strength, 0, 100),
outline: number(source.outline, DEFAULT.outline, 0, 4),
stops: gradientStops,
};
};
const same = (one, two) => Object.keys(DEFAULT).every(key => one[key] === two[key]);
// `normalize` is intentionally forgiving when old account data is loaded.
// Incoming editor requests are not: every field must already be canonical.
const valid = value => Boolean(value) && typeof value === "object" && !Array.isArray(value)
&& Object.keys(DEFAULT).every(key => value[key] === normalize(value)[key]);
const fields = value => {
const style = normalize(value);
return [style.background, style.accent, style.text, style.border, style.opacity, style.animation, style.speed,
style.gradient, style.angle, style.strength, style.outline, style.stops];
};
// Twelve comma-separated, URL-safe fields; empty means the original game bubble.
const packet = value => {
const style = normalize(value);
return same(style, DEFAULT) ? "" : fields(style).join(",");
};
module.exports = {DEFAULT, normalize, valid, fields, packet};
+134
View File
@@ -0,0 +1,134 @@
"use strict";
const accounts = require("./accounts.js");
const defpacks = require("./defpacks.js");
// codes players type into the game's "Redeem Code" window
// (gameRedemption.CodeRedemptionPopup, "grc" in lib/world.js), made in the
// admin panel. a code gives one thing: a clothing item (in a colour), a den
// item, gems or diamonds, as a gift from Burrow HQ (lib/ecards.js
// sendFromHq). each account may use a code once; a code may also have an
// end to how many times it is used in all, and is then spent.
const SCHEMA = `
CREATE TABLE IF NOT EXISTS redeem_codes (
code TEXT PRIMARY KEY,
kind TEXT NOT NULL,
item INTEGER NOT NULL DEFAULT 0,
amount INTEGER NOT NULL DEFAULT 0,
color INTEGER,
uses INTEGER NOT NULL DEFAULT 0,
used INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS redeem_uses (
code TEXT NOT NULL,
account_id INTEGER NOT NULL,
at INTEGER NOT NULL,
PRIMARY KEY (code, account_id)
);
`;
const KINDS = ["clothing", "den", "gems", "diamonds"];
const CODE = /^[A-Z0-9-]{3,32}$/; // what the game's box lets be typed (and in capitals)
const MAX_AMOUNT = 10000000;
const MAX_USES = 1000000;
let made = false;
const db = () => {
const database = accounts.database();
if (!made) {
database.exec(SCHEMA);
made = true;
}
return database;
};
const now = () => Math.floor(Date.now() / 1000);
const normal = code => String(code || "").trim().toUpperCase();
const row = entry => ({code: entry.code, kind: entry.kind, item: entry.item, amount: entry.amount, color: entry.color,
uses: entry.uses, used: entry.used, createdAt: entry.created_at});
const list = () => db().prepare("SELECT * FROM redeem_codes ORDER BY created_at DESC").all().map(row);
// {code, kind, item, amount, color, uses}: returns {ok} or {error}.
const create = fields => {
const code = normal(fields.code);
const kind = String(fields.kind || "");
const uses = Number(fields.uses) || 0;
if (!CODE.test(code)) {
return {error: "A code is 3 to 32 letters, digits and dashes."};
}
if (!KINDS.includes(kind)) {
return {error: "A code gives clothing, a den item, gems or diamonds."};
}
if (!Number.isInteger(uses) || uses < 0 || uses > MAX_USES) {
return {error: "Uses: 0 for any number, or how many in all."};
}
let item = 0;
let amount = 0;
let color = null;
if (kind === "clothing") {
item = Number(fields.item);
const def = defpacks.itemDef(item);
if (!def || !defpacks.clothingIds().includes(item)) {
return {error: "No clothing item with that id."};
}
const own = String(def.colors).split(",").map(Number);
const chosen = fields.color === undefined || String(fields.color).trim() === "" ? own[0] : Number(fields.color);
if (!Number.isInteger(chosen) || chosen < -0x80000000 || chosen > 0xFFFFFFFF) {
return {error: "A colour as the game writes it (a whole number), or none for the item's own."};
}
color = chosen >>> 0;
}
else if (kind === "den") {
item = Number(fields.item);
if (!defpacks.denItemIds().includes(item)) {
return {error: "No den item with that id."};
}
}
else {
amount = Number(fields.amount);
if (!Number.isInteger(amount) || amount < 1 || amount > MAX_AMOUNT) {
return {error: "An amount from 1 to 10,000,000."};
}
}
if (db().prepare("SELECT 1 FROM redeem_codes WHERE code = ?").get(code)) {
return {error: "That code is taken."};
}
db().prepare("INSERT INTO redeem_codes (code, kind, item, amount, color, uses, used, created_at) VALUES (?, ?, ?, ?, ?, ?, 0, ?)")
.run(code, kind, item, amount, color, uses, now());
return {ok: `${code} made.`};
};
const remove = code => db().prepare("DELETE FROM redeem_codes WHERE code = ?").run(normal(code)).changes > 0;
// a code typed in the game, for `account`: {gift} for lib/ecards.js
// sendFromHq, or {error: "unknown" | "used" | "spent"}. the use is noted.
const redeem = (account, typed) => {
const code = normal(typed);
const entry = CODE.test(code) ? db().prepare("SELECT * FROM redeem_codes WHERE code = ?").get(code) : null;
if (!entry) {
return {error: "unknown"};
}
if (db().prepare("SELECT 1 FROM redeem_uses WHERE code = ? AND account_id = ?").get(code, account.id)) {
return {error: "used"};
}
if (entry.uses > 0 && entry.used >= entry.uses) {
return {error: "spent"};
}
db().prepare("INSERT INTO redeem_uses (code, account_id, at) VALUES (?, ?, ?)").run(code, account.id, now());
db().prepare("UPDATE redeem_codes SET used = used + 1 WHERE code = ?").run(code);
const gift = entry.kind === "clothing" ? {kind: "clothing", id: entry.item, color: entry.color}
: entry.kind === "den" ? {kind: "den", id: entry.item} : {kind: entry.kind, amount: entry.amount};
return {gift, code};
};
// a use taken back, when the gift could not be sent after all
const unredeem = (account, code) => {
if (db().prepare("DELETE FROM redeem_uses WHERE code = ? AND account_id = ?").run(code, account.id).changes > 0) {
db().prepare("UPDATE redeem_codes SET used = MAX(used - 1, 0) WHERE code = ?").run(code);
}
};
module.exports = {list, create, remove, redeem, unredeem, KINDS};
+4 -1
View File
@@ -71,4 +71,7 @@ const chunks = (size = 200) => {
// the custom range), or an entry of the table? // the custom range), or an entry of the table?
const known = id => id < CUSTOM_BASE || id > MAX_ID || entries.has(id); const known = id => id < CUSTOM_BASE || id > MAX_ID || entries.has(id);
module.exports = {load, allocate, chunks, known, count: () => entries.size}; // the four RGB values of an entry, or null.
const rgbsOf = id => entries.get(id) || null;
module.exports = {CUSTOM_BASE, load, allocate, chunks, known, rgbsOf, count: () => entries.size};
+104 -1
View File
@@ -4,6 +4,7 @@ const accounts = require("./accounts.js");
const chatlog = require("./chatlog.js"); const chatlog = require("./chatlog.js");
const customItems = require("./customitems.js"); const customItems = require("./customitems.js");
const itemControl = require("./itemcontrol.js"); const itemControl = require("./itemcontrol.js");
const wearRules = require("./wearrules.js");
const modNotes = require("./modnotes.js"); const modNotes = require("./modnotes.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const disguises = require("./disguises.js"); const disguises = require("./disguises.js");
@@ -73,7 +74,10 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
const {account} = session; const {account} = session;
const avatar = activeAvatar(account); const avatar = activeAvatar(account);
const before = wornItems(account, avatar); const before = wornItems(account, avatar);
const wanted = account.items.filter(item => invs.includes(item.inv)).slice(0, MAX_WORN); // Saved outfits are a second equip route, so they obey the same rule as
// the item editor. A saved id remains in the outfit in case staff later
// remove the rule; it simply cannot be put on while blocked.
const wanted = account.items.filter(item => invs.includes(item.inv) && wearRules.mayWear(item.def, avatar.type)).slice(0, MAX_WORN);
const takenOff = before.filter(item => !wanted.includes(item)); const takenOff = before.filter(item => !wanted.includes(item));
account.outfitUndo = {avInvId: avatar.avInvId, items: before.map(item => item.inv)}; account.outfitUndo = {avInvId: avatar.avInvId, items: before.map(item => item.inv)};
for (const item of takenOff) { for (const item of takenOff) {
@@ -596,6 +600,59 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
}; };
const staffCommands = { const staffCommands = {
// A short-lived room control for owners, admins and developers. It uses
// the avatar protocol rather than persisting any player appearance.
roomfx: {
permission: "room.effects",
run(session, words) {
const room = session.room;
const effect = (words[0] || "").toLowerCase();
if (!room || !["small", "normal", "big", "rainbow", "clear"].includes(effect)) {
tell(session, "Use: !roomfx small, !roomfx normal, !roomfx big, !roomfx rainbow, or !roomfx clear");
return;
}
const send = (type, value) => {
for (const target of room.sessions) {
for (const viewer of room.sessions) {
viewer.sendXt("uc", room.id, target.id, String(value), type);
}
}
};
const stopRainbow = () => {
if (room.roomEffectTimer) {
clearInterval(room.roomEffectTimer);
delete room.roomEffectTimer;
}
};
if (effect === "rainbow") {
stopRainbow();
let hue = 0;
room.roomEffectTimer = setInterval(() => {
if (room.sessions.size === 0) {
stopRainbow();
return;
}
const colour = [0xFF4040, 0xFFB340, 0xF8FF40, 0x50E860, 0x40CFFF, 0x7560FF, 0xDC55FF][hue++ % 7];
send(8, colour);
}, 350);
room.roomEffectTimer.unref();
tell(session, "Rainbow effect started for everyone in this room. !roomfx clear stops it.");
}
else {
stopRainbow();
if (effect === "small" || effect === "big" || effect === "normal") {
send(14, effect === "small" ? 0.7 : effect === "big" ? 1.35 : 1);
tell(session, `Everyone in this room is now ${effect === "normal" ? "normal size" : effect}.`);
}
else {
send(8, 0);
send(14, 1);
tell(session, "Room effects cleared.");
}
}
modlog.record(session.account.username, "room effect (in game)", "", `${effect}: ${roomTitle(room)}`);
},
},
// "!item clothing|den ID NAME": a new item made from the game's item ID // "!item clothing|den ID NAME": a new item made from the game's item ID
// (lib/customitems.js), free, every colour of the one it is made from; // (lib/customitems.js), free, every colour of the one it is made from;
// everyone has it at once. the moderator panel's Items page does more. // everyone has it at once. the moderator panel's Items page does more.
@@ -633,6 +690,38 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
tell(session, on.length ? `Staff online: ${on.join(", ")}` : "No staff online."); tell(session, on.length ? `Staff online: ${on.join(", ")}` : "No staff online.");
}, },
}, },
// Opens the same in-game moderation window as a player's card. This is
// useful when a moderator already knows the name and does not need to
// hunt through search results first.
mod: {
permission: "player.view",
run(session, words) {
const target = words.length ? findOnline(words.join(" ")) : null;
if (!target) {
tell(session, words.length ? `${words.join(" ")} is not online.` : "Use: !mod PLAYER");
return;
}
if (target.account !== session.account && roles.roleOf(target.account) && !roles.outranks(session.account, target.account)) {
tell(session, "Staff of your rank or above are for someone higher up to deal with.");
return;
}
session.sendXt("xui", -1, "moderate", target.account.username);
},
},
// Owners, admins and developers get the room-effects panel from chat.
// `host` is an intuitive alias for event hosts.
event: {
permission: "room.effects",
run(session) {
session.sendXt("xui", -1, "event");
},
},
host: {
permission: "room.effects",
run(session) {
session.sendXt("xui", -1, "event");
},
},
// "!note PLAYER text": a note for the other staff (lib/modnotes.js), // "!note PLAYER text": a note for the other staff (lib/modnotes.js),
// never shown to the player. "!notes PLAYER": the latest few. // never shown to the player. "!notes PLAYER": the latest few.
note: { note: {
@@ -681,6 +770,20 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
setInvisible(session, !session.invisible); setInvisible(session, !session.invisible);
}, },
}, },
reject: {
permission: "player.names",
run(session, words) {
withTarget(session, words, "Use: !reject PLAYER", true, target => {
if (target.account.nameRejected) {
tell(session, `${target.account.username}'s name is already rejected.`);
return;
}
staffModeration().actions.rejectName(target.account, session.account.username);
tell(session, `${target.account.username} was signed out and must choose a new name.`);
logged(session, "rejected username", target);
});
},
},
// "!lock clothing|den ID", "!unlock clothing|den ID", "!locked": items // "!lock clothing|den ID", "!unlock clothing|den ID", "!locked": items
// kept out of the item finder for players (lib/itemcontrol.js). // kept out of the item finder for players (lib/itemcontrol.js).
lock: { lock: {
+121 -11
View File
@@ -3,14 +3,15 @@
const {logText} = require("./logtext.js"); const {logText} = require("./logtext.js");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const defpacks = require("./defpacks.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 // 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 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 // 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 // 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 // (defpacks.setCustomItem); games already playing are sent its def row
// ("xdi", which the patched client adds to its tables), and so is every game // ("xdi", which the patched client adds to its tables), and so is a game at
// at login, in case it was started before the item was made. // 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: // an item can be taken out of the shop, renamed and repriced, or deleted:
// then it goes from every inventory too (lib/itemcontrol.js). // 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 TYPE_CLOTHING = "1";
const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items that can be copied: plain, mannequin const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items that can be copied: plain, mannequin
const CURRENCY_GEMS = "0"; 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 ( 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, 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 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 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 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 db = () => accounts.database();
const now = () => Math.floor(Date.now() / 1000); const now = () => Math.floor(Date.now() / 1000);
const baseDef = (kind, id) => (kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id)); 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 // the def row of an entry: its base's row with its own id, name, price and
// colours, always on sale and marked new. // colours, always on sale and marked new.
const rowOf = entry => { const rowOf = entry => {
@@ -59,29 +85,69 @@ const rowOf = entry => {
combinedCost: "", combinedCost: "",
}; };
if (entry.kind === "den") { 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, 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"}; 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 // "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 // may not hold "%" (lib/sfs.js drops it), so a "%" in a name is written as
// JSON's %. // JSON's %.
const xtRows = rows => JSON.stringify(rows).replace(/%/g, "\\u0025");
const messages = entries => { const messages = entries => {
const out = []; const out = [];
for (const kind of KINDS) { for (const kind of KINDS) {
// a picture waiting for a moderator is not shown yet // a picture waiting for a moderator is not shown yet
const rows = entries.filter(entry => entry.kind === kind && !entry.pending) const rows = entries.filter(entry => entry.kind === kind && !entry.pending).map(clientRow);
.map(entry => ({...rowOf(entry), name: entry.name, art: entry.artPending ? "" : entry.art || "", artMode: entry.artMode || "sticker"}));
for (let at = 0; at < rows.length; at += CHUNK) { for (let at = 0; at < rows.length; at += CHUNK) {
out.push([kind, JSON.stringify(rows.slice(at, at + CHUNK)).replace(/%/g, "\\u0025")]); out.push([kind, xtRows(rows.slice(at, at + CHUNK))]);
} }
} }
return out; return out;
}; };
// The patched client accepts ordinary clothing rows through xdi as well as
// newly made ones. That lets a moderation rule take effect in an already
// open editor instead of waiting for its next def-pack download.
const sendClothingDefs = ids => {
const rows = [...new Set(ids.map(Number))].map(id => {
const entry = items.get("clothing").get(id);
// A refreshed custom row must retain the extra xdi-only fields. Omitting
// them makes a live client lose its custom name or picture while its
// avatar-use flag is being updated.
return entry ? {...defpacks.clientItemRow(rowOf(entry)), name: entry.name, art: entry.artPending ? "" : entry.art || "",
artMode: entry.artMode || "sticker"} : defpacks.clientItemDef(id);
}).filter(row => row && row.type === TYPE_CLOTHING);
for (let at = 0; at < rows.length; at += CHUNK) {
broadcast("xdi", "clothing", xtRows(rows.slice(at, at + CHUNK)));
}
};
const announce = entry => { const announce = entry => {
if (entry.pending) { if (entry.pending) {
return; return;
@@ -99,6 +165,7 @@ const fromRow = row => ({
artMode: LOOKS.includes(row.art_mode) ? row.art_mode : "sticker", artMode: LOOKS.includes(row.art_mode) ? row.art_mode : "sticker",
pending: row.pending === 1, pending: row.pending === 1,
artPending: row.art_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; // a player-made item (lib/playeritems.js) has the maker's account id;
@@ -123,6 +190,10 @@ const addOwnerColumn = () => {
if (!columns.includes("art_pending")) { if (!columns.includes("art_pending")) {
db().exec("ALTER TABLE custom_items ADD COLUMN art_pending INTEGER"); 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 = () => { const load = () => {
@@ -213,10 +284,12 @@ const create = (kind, fields, by, ownerId = null, pending = false) => {
return values; return values;
} }
const id = Math.max(FIRST_ID - 1, ...items.get(kind).keys()) + 1; 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, const entry = {kind, id, base: baseId, colors: [], ...values, createdBy: String(by), createdAt: now(), ownerId, artMode: "sticker", pending, artPending: false,
seq: made++}; 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) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") 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); .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); items.get(kind).set(id, entry);
if (!pending) { if (!pending) {
apply(entry); apply(entry);
@@ -261,6 +334,7 @@ const setArtMode = (kind, id, mode) => {
} }
entry.artMode = mode; entry.artMode = mode;
db().prepare("UPDATE custom_items SET art_mode = ? WHERE kind = ? AND id = ?").run(mode, kind, entry.id); db().prepare("UPDATE custom_items SET art_mode = ? WHERE kind = ? AND id = ?").run(mode, kind, entry.id);
entry.changed = defpacks.customChanged();
announce(entry); announce(entry);
return {item: entry}; return {item: entry};
}; };
@@ -275,6 +349,7 @@ const setArt = (kind, id, art, pending = false) => {
entry.art = art || null; entry.art = art || null;
entry.artPending = Boolean(art && pending); 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); 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); announce(entry);
}; };
@@ -304,6 +379,9 @@ const remove = (kind, id) => {
db().prepare("DELETE FROM custom_items WHERE kind = ? AND id = ?").run(kind, entry.id); db().prepare("DELETE FROM custom_items WHERE kind = ? AND id = ?").run(kind, entry.id);
items.get(kind).delete(entry.id); items.get(kind).delete(entry.id);
defpacks.unsetCustomItem(kind, entry.id); defpacks.unsetCustomItem(kind, entry.id);
if (entry.audio) {
audioGone(entry);
}
return {item: entry}; return {item: entry};
}; };
@@ -313,6 +391,10 @@ const list = () => KINDS.flatMap(kind => [...items.get(kind).values()])
module.exports = { module.exports = {
KINDS, KINDS,
FIRST_ID, FIRST_ID,
audioName,
onAudioGone: callback => {
audioGone = callback;
},
load, load,
create, create,
update, update,
@@ -342,12 +424,40 @@ module.exports = {
const def = baseDef(entry.kind, entry.base); 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); 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) { 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); session.sendXt("xdi", -1, ...params);
} }
}, },
sendClothingDefs,
// lib/world.js says how to reach every game playing. // lib/world.js says how to reach every game playing.
connect(broadcastXt) { connect(broadcastXt) {
broadcast = broadcastXt; broadcast = broadcastXt;
+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};
+137 -19
View File
@@ -8,6 +8,7 @@ const config = require("../config.js");
const sales = require("./sales.js"); const sales = require("./sales.js");
const badges = require("./badges.js"); const badges = require("./badges.js");
const extraMusic = require("./extramusic.js"); const extraMusic = require("./extramusic.js");
const wearRules = require("./wearrules.js");
// defPack ids, from loader.DefPacksDefHelper in the client. // defPack ids, from loader.DefPacksDefHelper in the client.
const DEF_ITEM = 1000; const DEF_ITEM = 1000;
@@ -42,8 +43,10 @@ const DEF_PET_TOY = 1063;
const DEF_WORLD_ITEMS = 1064; const DEF_WORLD_ITEMS = 1064;
const DEF_NPC = 1025; const DEF_NPC = 1025;
const DEF_NAMEBAR_BADGE = 1049; const DEF_NAMEBAR_BADGE = 1049;
const DEF_EMOTICON = 1036;
const DEF_NEWSPAPER = 1065; // the Jamaa Journal's pages (newspaper.NewspaperManager)
const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items: plain, mannequin const OFFERED_SPECIAL_TYPES = ["0", "4", "6", "7"]; // den items: plain, mannequin, eco producer and consumer (lib/eco.js)
const DEN_ITEM_MASTERPIECE = 2725; const DEN_ITEM_MASTERPIECE = 2725;
const packs = new Map(); const packs = new Map();
@@ -70,6 +73,32 @@ const LAYER_EYES = "3";
const TYPE_CLOTHING = "1"; const TYPE_CLOTHING = "1";
const EVERY_AVATAR = "9007199254740991"; // avatarUseFlags with a bit set for each animal type const EVERY_AVATAR = "9007199254740991"; // avatarUseFlags with a bit set for each animal type
// ItemXtCommManager checks bit (avatar type - 1). BigInt avoids losing a
// bit in JavaScript's 53-bit Number representation while preserving the
// string form the AMF def pack uses.
const clientAvatarUseFlags = itemId => {
let flags = BigInt(EVERY_AVATAR);
for (const type of wearRules.blockedTypes(itemId)) {
if (type <= 53) {
flags &= ~(1n << BigInt(type - 1));
}
}
return String(flags);
};
// One transform is used for fetched packs and for the live `xdi` definition
// updates sent to games that are already running.
const clientItemRow = def => {
const row = {...def};
if (row.type === TYPE_CLOTHING) {
row.avatarUseFlags = clientAvatarUseFlags(row.id);
}
else if (row.type === "0" && row.layerId === LAYER_EYES) {
row.avatarUseFlags = EVERY_AVATAR;
}
return row;
};
// rooms the official room pack no longer lists but whose files an older // rooms the official room pack no longer lists but whose files an older
// build on the CDN still has (lib/cdn.js looks there): the Summer Carnival, // build on the CDN still has (lib/cdn.js looks there): the Summer Carnival,
// dropped after build 1828. // dropped after build 1828.
@@ -144,12 +173,22 @@ const withRestoredParties = pack => {
// text of our own, for things the game has no string for. added to the // text of our own, for things the game has no string for. added to the
// English localization pack under ids far above the game's (about 41,000). // English localization pack under ids far above the game's (about 41,000).
const ADDED_STRINGS = { const ADDED_STRINGS = {
// the login popup for a launcher too old to send device ids (lib/world.js
// LOGIN_OUTDATED), in place of "Your account is currently under maintenance."
11198: "Your client is outdated. Update at https://burrow.moe/download",
9000001: "Castle (2010 draft)", 9000001: "Castle (2010 draft)",
9000002: "Water Park (three slides)", 9000002: "Water Park (three slides)",
9000003: "Water Park (five slides)", 9000003: "Water Park (five slides)",
9000004: "Crystal Palace (concept)", 9000004: "Crystal Palace (concept)",
// the buddy game the client's files call "fourGem"; no string says so. // the buddy game the client's files call "fourGem"; no string says so.
9000005: "Four Gems", 9000005: "Four Gems",
// a shop's title when its room gives it none (lib/world.js SHOP_KIND_TITLES)
9000010: "Clothing Shop",
9000011: "Den Shop",
9000012: "Den Rooms",
9000013: "Shop",
9000014: "Exchange",
9000015: "Diamond Shop",
}; };
// the game under this server's name. its text says "Animal Jam", "Animal // the game under this server's name. its text says "Animal Jam", "Animal
@@ -208,6 +247,31 @@ const withCustomRows = id => pack => {
return pack; return pack;
}; };
// colours of clothing items from a dump of a beta-era inventory (art id,
// then the colour as 4 bytes, little-endian), added after each item's own
// so the colours already given keep their place. the shop shows a list's
// first 8 only, so these are had from the item givers.
const DUMP_COLOURS = new Map([
[231, [0x6929C069]], // Rare Eyeball Hat (Beta EyeBall; tried in the game)
[224, [0x67520169]], // Creature Mask (Beta Creature Mask)
[136, [0x2C083069, 0x55153131]], // Tiara (Beta Tiara, Milky Tiara)
[135, [0x83550505]], // Arctic Hood (Beta Hood)
[169, [0x937FF63B]], // Elf Helmet (Beta Elf)
[714, [0x00000069]], // Furry Hat (Real Magenta Furry Hat)
[649, [0x2E2D1906]], // Turquoise Ring (1st Glitched Ring)
]);
const withDumpColours = pack => {
for (const def of Object.values(pack)) {
const added = def && DUMP_COLOURS.get(Number(def.id));
if (added) {
const colours = String(def.colors).split(",").filter(Boolean);
def.colors = [...colours, ...added.map(String).filter(colour => !colours.includes(colour))].join(",");
}
}
return pack;
};
const withAddedStrings = pack => Object.assign(withLineBreaks(withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings()))), customStrings); const withAddedStrings = pack => Object.assign(withLineBreaks(withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings()))), customStrings);
// the extra music tracks (lib/extramusic.js), as den items like the // the extra music tracks (lib/extramusic.js), as den items like the
@@ -270,7 +334,7 @@ const SHARED_CHANGES = new Map([
[DEF_PARTY, withRestoredParties], [DEF_PARTY, withRestoredParties],
[DEF_DEN_ROOM, withoutPrices(DEF_DEN_ROOM, withAddedDens)], [DEF_DEN_ROOM, withoutPrices(DEF_DEN_ROOM, withAddedDens)],
[DEF_DEN_ITEM, withoutPrices(DEF_DEN_ITEM, pack => withCustomRows(DEF_DEN_ITEM)(withExtraMusic(pack)))], [DEF_DEN_ITEM, withoutPrices(DEF_DEN_ITEM, pack => withCustomRows(DEF_DEN_ITEM)(withExtraMusic(pack)))],
[DEF_ITEM, withoutPrices(DEF_ITEM, withCustomRows(DEF_ITEM))], [DEF_ITEM, withoutPrices(DEF_ITEM, pack => withCustomRows(DEF_ITEM)(withDumpColours(pack)))],
[DEF_DIAMOND, withoutPrices(DEF_DIAMOND)], [DEF_DIAMOND, withoutPrices(DEF_DIAMOND)],
[DEF_PET, withoutPrices(DEF_PET)], [DEF_PET, withoutPrices(DEF_PET)],
[DEF_LOCALIZATION_EN, withAddedStrings], [DEF_LOCALIZATION_EN, withAddedStrings],
@@ -314,9 +378,9 @@ const alwaysOnSale = (pack, ids) => {
// the rows put back or added (SHARED_CHANGES). // the rows put back or added (SHARED_CHANGES).
const CLIENT_PACKS = new Map([ const CLIENT_PACKS = new Map([
[DEF_ITEM, pack => { [DEF_ITEM, pack => {
for (const def of Object.values(pack)) { for (const [key, def] of Object.entries(pack)) {
if (def.type === TYPE_CLOTHING || (def.type === "0" && def.layerId === LAYER_EYES)) { if (def.type === TYPE_CLOTHING || (def.type === "0" && def.layerId === LAYER_EYES)) {
def.avatarUseFlags = EVERY_AVATAR; pack[key] = clientItemRow(def);
} }
} }
sales.stamp("clothing", pack); sales.stamp("clothing", pack);
@@ -339,24 +403,51 @@ const CLIENT_PACKS = new Map([
[DEF_NAMEBAR_BADGE, () => {}], [DEF_NAMEBAR_BADGE, () => {}],
]); ]);
const clientPackPaths = new Map([...CLIENT_PACKS.keys()].map(id => [cdn.hashedPath(`defPacks/${id}`), id])); const clientPackPaths = new Map([...CLIENT_PACKS.keys()].map(id => [cdn.hashedPath(`defPacks/${id}`), id]));
const clientPackBodies = new Map(); // id -> {day, allOnSale, body} const clientPackBodies = new Map(); // id -> {day, allOnSale, body, version, madeAt}
const clientPacksChanged = new Set(); // ids whose body is older than a custom item change
const clientPacksMaking = new Map(); // id -> the promise of the body being made
// a pack is made again after a custom item change at most every
// config.packRemakeMs: the item pack takes ~70 ms of the one thread at 5000
// items (~300 ms at 50000), and players make items many times a minute.
// until then the body made before goes out, with the version it has; a
// game logging in is sent what changed after it (lib/customitems.js sendAll).
const deflateRaw = require("util").promisify(zlib.deflateRaw);
// the packs custom items are in: their rows, and their names
const CUSTOM_PACK_KINDS = new Map([[DEF_ITEM, "clothing"], [DEF_DEN_ITEM, "den"], [DEF_LOCALIZATION_EN, "names"]]);
// the pack at `relPath` as clients should get it, or null when it is not const makeClientPack = async id => {
// one of the above (and comes straight from the CDN). // the version before the rows are read: a change while it is made counts
// as after, and is sent at login (more than needed, never less)
const version = customVersion;
const pack = await loadChanged(id);
CLIENT_PACKS.get(id)(pack);
// deflated on libuv's threads, not this one
const body = await deflateRaw(amf3.encode(pack));
const made = {day: sales.today(), allOnSale: sales.everythingOnSale(), body, version, madeAt: Date.now()};
clientPackBodies.set(id, made);
if (customVersion === version) {
clientPacksChanged.delete(id);
}
return made;
};
// the pack at `relPath` as clients should get it, {body, version}, or null
// when it is not one of the above (and comes straight from the CDN).
// `version`: customVersion() of the custom items in it.
const clientPack = async relPath => { const clientPack = async relPath => {
const id = clientPackPaths.get(relPath); const id = clientPackPaths.get(relPath);
if (id === undefined) { if (id === undefined) {
return null; return null;
} }
const made = clientPackBodies.get(id); const made = clientPackBodies.get(id);
if (made && made.day === sales.today() && made.allOnSale === sales.everythingOnSale()) { if (made && made.day === sales.today() && made.allOnSale === sales.everythingOnSale()
return made.body; && (!clientPacksChanged.has(id) || Date.now() - made.madeAt < config.packRemakeMs)) {
return made;
} }
const pack = await loadChanged(id); if (!clientPacksMaking.has(id)) {
CLIENT_PACKS.get(id)(pack); clientPacksMaking.set(id, makeClientPack(id).finally(() => clientPacksMaking.delete(id)));
const body = zlib.deflateRawSync(amf3.encode(pack)); }
clientPackBodies.set(id, {day: sales.today(), allOnSale: sales.everythingOnSale(), body}); return clientPacksMaking.get(id);
return body;
}; };
// most packs are tables: an object of rows keyed by row index. // most packs are tables: an object of rows keyed by row index.
@@ -394,6 +485,10 @@ let musicIds = []; // den items that are music tracks
let roomDefsById = new Map(); let roomDefsById = new Map();
let badgeIds = []; // name tag badges, ascending let badgeIds = []; // name tag badges, ascending
let npcDefs = new Map(); // the characters of the adventures, see lib/disguises.js let npcDefs = new Map(); // the characters of the adventures, see lib/disguises.js
// An avatar attachment is named by its emoticon definition id on the wire,
// while AvatarWorldView needs the media id stored by that definition.
let emoticonMediaIds = new Map();
let journalPages = []; // the Jamaa Journal's pages: {id, page (media id), start (seconds)}
// A pack whose feature can be done without: missing (offline and never // A pack whose feature can be done without: missing (offline and never
// cached) just leaves that feature empty. // cached) just leaves that feature empty.
@@ -423,8 +518,9 @@ const init = async () => {
petIds = [...petDefs.keys()]; petIds = [...petDefs.keys()];
denItemDefs = new Map((await load(DEF_DEN_ITEM)).map(def => [Number(def.id), def])); denItemDefs = new Map((await load(DEF_DEN_ITEM)).map(def => [Number(def.id), def]));
// special types carry extra state (a den portal's destination, a shop's // special types carry extra state (a den portal's destination, a shop's
// stock, ...). of those only mannequins (4) are modelled, in lib/dens.js, // stock, ...). of those mannequins (4) are modelled, in lib/dens.js, and
// so plain den items and mannequins are what is offered. // the eco items (6, 7) in lib/eco.js, so those and plain den items are
// what is offered.
// the Masterpiece item is a painting's frame, made in the Art Studio and // the Masterpiece item is a painting's frame, made in the Art Studio and
// nowhere else (lib/masterpieces.js). // nowhere else (lib/masterpieces.js).
denItemIds = [...denItemDefs].filter(([id, def]) => OFFERED_SPECIAL_TYPES.includes(def.specialType) && id !== DEN_ITEM_MASTERPIECE).map(([id]) => id); denItemIds = [...denItemDefs].filter(([id, def]) => OFFERED_SPECIAL_TYPES.includes(def.specialType) && id !== DEN_ITEM_MASTERPIECE).map(([id]) => id);
@@ -460,6 +556,9 @@ const init = async () => {
petFoodDefs = await loadOptional(DEF_PET_FOOD); petFoodDefs = await loadOptional(DEF_PET_FOOD);
petToyDefs = await loadOptional(DEF_PET_TOY); petToyDefs = await loadOptional(DEF_PET_TOY);
npcDefs = new Map((await loadOptional(DEF_NPC)).map(def => [Number(def.id), def])); npcDefs = new Map((await loadOptional(DEF_NPC)).map(def => [Number(def.id), def]));
emoticonMediaIds = new Map((await loadOptional(DEF_EMOTICON)).map(def => [Number(def.id), Number(def.mediaRef)]));
journalPages = (await loadOptional(DEF_NEWSPAPER)).map(def => ({id: Number(def.id), page: Number(def.pageMediaRefId),
start: Number(def.availabilityStartTime) || 0})).filter(page => page.page > 0);
partyDefs = new Map((await loadOptional(DEF_PARTY)).map(def => { partyDefs = new Map((await loadOptional(DEF_PARTY)).map(def => {
const room = roomPathsById.get(Number(def.roomDefId)); const room = roomPathsById.get(Number(def.roomDefId));
return [Number(def.id), { return [Number(def.id), {
@@ -500,8 +599,8 @@ const setCustomItem = (kind, row, name, inShop = true) => {
clothingIds = clothingIds.includes(id) ? clothingIds : [...clothingIds, id]; clothingIds = clothingIds.includes(id) ? clothingIds : [...clothingIds, id];
} }
customInShop[kind][inShop ? "add" : "delete"](id); customInShop[kind][inShop ? "add" : "delete"](id);
clientPackBodies.delete(pack); clientPacksChanged.add(pack);
clientPackBodies.delete(DEF_LOCALIZATION_EN); clientPacksChanged.add(DEF_LOCALIZATION_EN);
customVersion++; customVersion++;
}; };
@@ -523,7 +622,7 @@ const unsetCustomItem = (kind, id) => {
clothingIds = clothingIds.filter(one => one !== number); clothingIds = clothingIds.filter(one => one !== number);
} }
customInShop[kind].delete(number); customInShop[kind].delete(number);
clientPackBodies.delete(pack); clientPacksChanged.add(pack);
customVersion++; customVersion++;
}; };
@@ -534,6 +633,13 @@ module.exports = {
// the custom items on sale, the newest first. // the custom items on sale, the newest first.
customShopIds: kind => [...customInShop[kind]].reverse(), customShopIds: kind => [...customInShop[kind]].reverse(),
customVersion: () => customVersion, customVersion: () => customVersion,
// a change of a custom item that is not in the packs (its picture): one
// more version, for a game logging in to be told of it
customChanged: () => ++customVersion,
// the avatarUseFlags every clothing row has in the clients' pack (any animal)
EVERY_AVATAR,
// "clothing", "den" or "names" for a pack path with custom items in (lib/customitems.js sawPack), else null.
customPackKind: relPath => CUSTOM_PACK_KINDS.get(clientPackPaths.get(relPath)) || null,
load, load,
itemDef: id => itemDefs.get(Number(id)), itemDef: id => itemDefs.get(Number(id)),
clothingIds: () => clothingIds, clothingIds: () => clothingIds,
@@ -541,6 +647,14 @@ module.exports = {
denItemDef: id => denItemDefs.get(Number(id)), denItemDef: id => denItemDefs.get(Number(id)),
denItemIds: () => denItemIds, denItemIds: () => denItemIds,
clientPack, clientPack,
// A changing rule must not leave the cached item pack permissive. The next
// client request remakes it, and current games receive an xdi row too.
invalidateClientItemPack: () => clientPackBodies.delete(DEF_ITEM),
clientItemRow,
clientItemDef: id => {
const def = itemDefs.get(Number(id));
return def ? clientItemRow(def) : null;
},
string: id => (Object.hasOwn(strings, id) ? String(strings[id]) : ""), string: id => (Object.hasOwn(strings, id) ? String(strings[id]) : ""),
stringId: text => { stringId: text => {
if (!stringIds) { if (!stringIds) {
@@ -555,6 +669,10 @@ module.exports = {
}, },
badgeIds: () => badgeIds, badgeIds: () => badgeIds,
npcDef: id => npcDefs.get(Number(id)), npcDef: id => npcDefs.get(Number(id)),
emoticonMediaId: id => emoticonMediaIds.get(Number(id)) || 0,
// the media ids of the newest Jamaa Journal pages out by `now` (seconds), newest first
newestJournalPages: (count, now = Date.now() / 1000) => journalPages.filter(page => page.start <= now)
.sort((one, other) => other.start - one.start || other.id - one.id).slice(0, count).map(page => page.page),
oddDenItemIds: () => oddDenItemIds, oddDenItemIds: () => oddDenItemIds,
// den items that exist to be given by id and are in no shop. // den items that exist to be given by id and are in no shop.
unsoldDenItemIds: () => extraMusic.ids, unsoldDenItemIds: () => extraMusic.ids,
+1
View File
@@ -0,0 +1 @@
{"1":{"versions":[0,1,2,3,4,5,6,7],"colours":[["56c3d8","1078ff","4acaff","4876ba"],["8f48ff","3d00a7","5e1dff","5d0089"],["ff99f0","e150ff","ff6bf7","ff3dba"],["ac0912","ea004f","c40000","a10000"],["ff732b","dd3c4d","ff742d","e84138"],["f3ff86","d0ee19","e6ff3b","dfff05"],["63ff66","007917","23b700","035000"],["63565d","201219","551f4c","2f151f"]]},"9":{"versions":[0,1]},"13":{"versions":[0,1,2,3]},"19":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["7cbbff","2388ff","b9fffc","6bc1ff"],["be5bff","9348ff","42195b","ac43ff"],["e689c2","e45dad","fbfbfb","ea65c4"],["c8a0cd","cc434c","887e8e","ff4b4b"],["efcd34","e57712","ffffff","7bfff2"],["fff81a","fff81a","835c40","ff6bb3"],["4cbf00","43910b","ade53b","57de00"],["9e9e9e","5c5c7f","727c72","ffbf15"],["9e1616","3a3a3a","0f0f0f","ff1d1d"],["644b18","503000","e0b61f","7b4100"]]},"21":{"versions":[0,1,2]},"27":{"versions":[0,1,2,3]},"36":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["2b5eff","ffd646","56b8ff","b7ecff"],["ee58ff","5e0096","ffcf84","e3bcff"],["ff50d8","fbfbfb","ffbc1d","ffffef"],["ff3418","050505","ff9e53","ffffff"],["ff7323","ffa640","ffe42d","c7fcff"],["f8ff12","150f00","f3ff1a","050500"],["4caf00","adff3b","fff87e","c4ffe2"],["969696","ffdb5b","e0e5ff","809ca2"],["3d3d3d","830004","fafafa","0d0d0d"],["644b18","2b0c00","b9ab00","314800"]]},"37":{"versions":[0,1,3,4,5,6,7],"colours":[["a1daff","7bbfe8","b7eaff","4893ff"],["ceafff","a550ff","5d00b7","9c50ff"],["ff9999","990000","e95353","e11515"],["ffca94","f4a500","d07200","e37d48"],["dbe700","ecd743","ffff02","fff20a"],["afffa4","0a9100","75ff5e","30ff0d"],["727272","909090","f6f6f6","dedede"]]},"45":{"versions":[0,1,2,3,4,5,6,7]},"48":{"versions":[0,1,2,3,4,5,6,7]},"49":{"versions":[0,1,2,3,4,5,6,7]},"53":{"versions":[0,1,2,3,4,5,6,7]},"54":{"versions":[0,1,2,3,4,5,6,7]},"56":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["3e89d0","0d3673","b17400"],["9361ff","42195b","ff8ce4"],["f771a8","ff33a9","ffffff"],["d24743","ae3d59","434343"],["cf6227","e78100","ffe63d"],["ffea30","ff6d1a","bc7900"],["bde745","ff9400","dfaa00"],["969696","525252","ffffff"],["303030","f1f1f1","7d7d7d"],["91602d","ffe463","acb43e"]]},"83":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["c7f3ff","408aff","6bdaff"],["c976ff","5e0096","dcd4ff"],["ff89f3","ff4cac","f5d7ff"],["e43437","ffffff","ffffff"],["fd7500","ffcd63","fffbea"],["ffff3d","150f00","e2fff4"],["4caf00","adff3b","ffffff"],["969696","6b7c6b","dedede"],["212121","6b4496","030303"],["713700","ffffff","fffff2"]]},"91":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["3d5977","c47821","bc8000","ab6412"],["906fa5","705091","af8957","56486c"],["e5768c","f1f1da","e9b3c7","e2c1ce"],["bd483e","373736","7f5437","30312e"],["c37138","3a3539","c75524","474446"],["b46d00","ffe042","787878","525252"],["6b7e48","433422","a16951","58462c"],["8ca0a6","7b8f90","cc9d5d","dcdaa6"],["434342","4b4641","2b3331","212121"],["8a6341","78502a","dbab64","c3b39a"]]},"131":{"versions":[0,1,2,3,4,5]},"147":{"versions":[0,1,2,3,4,5,6,7],"colours":[["7bb8f7","fffedc","dcfcff","ffffff"],["9b4eff","ffeff5","eacaff","aa69ff"],["ff9efa","f33de9","ffd2fb","ca00c4"],["d20000","636363","e62525","616161"],["ef8454","e0ffdf","efe4ce","ffffff"],["fff802","af6f2b","faff58","1ecf00"],["3dc43d","7b7800","35ee45","31cc00"],["505050","ffffff","686868","494949"]]},"152":{"versions":[0,1,2,3,4,5,6,7],"colours":[["7bb8f7","ade0e6","e0db00"],["af37d7","3b0038","f0e579"],["e825e1","ff99f7","cfcfcf"],["d20000","ffacac","eddc6b"],["ff732b","ffda76","cecece"],["ede80a","a2a700","d1d1d1"],["3dc43d","afffa4","ffd938"],["484848","757575","fffaa4"]]},"226":{"versions":[0,1,2,3,4,5,6,7],"colours":[["060043","c4dbff","0015b4","3548ff"],["f5f5f5","42195b","8d00f2","ae74eb"],["ff71e3","ffeaf1","d400c9","ff3dba"],["ac0912","fffee7","fbffa7","ea0000"],["ede3a0","d8822e","fbdf9e","be4e33"],["fff812","639ac6","949400","dfd300"],["fffbca","008903","faffbc","008e3e"],["ffffff","505050","ffffff","343434"]]},"295":{"versions":[0,1,2,3,4,5,6,7],"colours":[["3458dd","4696ff"],["9a47d8","b875ff"],["ff8193","ffc4c6"],["ff2d2d","ff9c9c"],["f57a00","ffd47b"],["e7e700","ffffbb"],["05af00","daffa3"],["7d7d7d","d5d5d5"]]},"348":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["4589ff","fffbac","4086ff","7bc744"],["a640ff","fff986","6300c2","cbe26a"],["ffffff","00b999","ff35e5","bc910e"],["01000a","ff3333","bf0000","ffffff"],["ff7a00","d6d6af","ffffff","3a5000"],["fff800","73e3e0","f7f000","b1ea8c"],["4caf00","adff3b","7dd700","c4ffe2"],["727272","bebebe","e0e5ff","a6a6a6"],["404040","3d3d3d","828282","5e0000"],["644b18","d6c72b","664d00","506a16"]]},"350":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["48c5ff","ffff18","5bff35","0dff1e"],["a846ff","ff650d","ffff33","43f1ff"],["ff73d9","ff30c2","ffffff","00f2eb"],["ff2d2d","828282","ffe925","fdea00"],["e76a00","35f700","ffed10","fff930"],["ffff00","4bfaff","23f700","13ff02"],["76ff20","21ea00","ff7210","ffff02"],["ffffff","cfecff","0affff","fff928"],["717171","3c3c3c","00fdf6","02fff2"],["92663a","ffcfLine truncated
+32 -9
View File
@@ -5,8 +5,10 @@ const accounts = require("./accounts.js");
const achievements = require("./achievements.js"); const achievements = require("./achievements.js");
const config = require("../config.js"); const config = require("../config.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const wearRules = require("./wearrules.js");
const epicDens = require("./epicdens.js"); const epicDens = require("./epicdens.js");
const masterpieces = require("./masterpieces.js"); const masterpieces = require("./masterpieces.js");
const eco = require("./eco.js");
const {CURRENCIES, MAX_DEN_ITEMS, hasRoom, activeAvatar, resolvePurchase, isUint} = require("./player.js"); const {CURRENCIES, MAX_DEN_ITEMS, hasRoom, activeAvatar, resolvePurchase, isUint} = require("./player.js");
// den items: owning, placing and recycling furniture (client side: // den items: owning, placing and recycling furniture (client side:
@@ -52,13 +54,21 @@ const LAYER_EYES = "3";
const isMannequin = item => (defpacks.denItemDef(item.def) || {}).specialType === SPECIAL_MANNEQUIN; const isMannequin = item => (defpacks.denItemDef(item.def) || {}).specialType === SPECIAL_MANNEQUIN;
const mannequinAvatarType = item => Number((defpacks.denItemDef(item.def) || {}).mannequinAvatarDefId) || 0;
const mannequinOf = item => item.mannequin || {colors: [0, 0, 0], pattern: 0, eyes: 0, worn: [0, 0, 0, 0, 0]}; const mannequinOf = item => item.mannequin || {colors: [0, 0, 0], pattern: 0, eyes: 0, worn: [0, 0, 0, 0, 0]};
const mannequinBody = ({colors, pattern, eyes}) => [colors[0], colors[1], pattern, colors[2], eyes]; const mannequinBody = ({colors, pattern, eyes}) => [colors[0], colors[1], pattern, colors[2], eyes];
// the clothing a mannequin of `owner`'s wears, slot by slot (undefined for // the clothing a mannequin of `owner`'s wears, slot by slot (undefined for
// an empty slot or a piece the owner no longer has). // an empty slot or a piece the owner no longer has).
const mannequinClothes = (owner, item) => mannequinOf(item).worn.map(inv => (inv ? owner.items.find(piece => piece.inv === inv) : undefined)); const mannequinClothes = (owner, item) => {
const type = mannequinAvatarType(item);
return mannequinOf(item).worn.map(inv => {
const piece = inv ? owner.items.find(candidate => candidate.inv === inv) : undefined;
return piece && (!type || wearRules.mayWear(piece.def, type)) ? piece : undefined;
});
};
// for the owner's own list (MannequinData.setupDataInvIdsOnly): the body, // for the owner's own list (MannequinData.setupDataInvIdsOnly): the body,
// then the five inventory ids. // then the five inventory ids.
@@ -74,12 +84,13 @@ const mannequinShownFields = (owner, item) =>
// what the den editor sent for one mannequin, checked: [baseColor, // what the den editor sent for one mannequin, checked: [baseColor,
// patternColor, patternDefId, eyeColor, eyeDefId, tail, leg, back, neck, // patternColor, patternDefId, eyeColor, eyeDefId, tail, leg, back, neck,
// head]. null when any of it is not a whole number in range. // head]. null when any of it is not a whole number in range.
const readMannequin = (account, fields) => { const readMannequin = (account, item, fields) => {
if (fields.length !== 10 || !fields.every(isUint)) { if (fields.length !== 10 || !fields.every(isUint)) {
return null; return null;
} }
const [base, patternColor, pattern, eyeColor, eyes, ...worn] = fields.map(Number); const [base, patternColor, pattern, eyeColor, eyes, ...worn] = fields.map(Number);
const bodyPart = (defId, layer) => (defId && (defpacks.itemDef(defId) || {}).layerId === layer ? defId : 0); const bodyPart = (defId, layer) => (defId && (defpacks.itemDef(defId) || {}).layerId === layer ? defId : 0);
const type = mannequinAvatarType(item);
return { return {
colors: [base, patternColor, eyeColor], colors: [base, patternColor, eyeColor],
pattern: bodyPart(pattern, LAYER_PATTERN), pattern: bodyPart(pattern, LAYER_PATTERN),
@@ -87,7 +98,7 @@ const readMannequin = (account, fields) => {
worn: worn.map((inv, slot) => { worn: worn.map((inv, slot) => {
const piece = inv && account.items.find(candidate => candidate.inv === inv); const piece = inv && account.items.find(candidate => candidate.inv === inv);
const def = piece && defpacks.itemDef(piece.def); const def = piece && defpacks.itemDef(piece.def);
return def && MANNEQUIN_SLOT_LAYERS[slot].includes(def.layerId) ? inv : 0; return def && MANNEQUIN_SLOT_LAYERS[slot].includes(def.layerId) && (!type || wearRules.mayWear(piece.def, type)) ? inv : 0;
}), }),
}; };
}; };
@@ -109,9 +120,14 @@ const petsInDen = account => account.pets.filter(pet => pet.inDen && pet.inDen.d
// it is not placed there. the three after "approved" are a masterpiece's // it is not placed there. the three after "approved" are a masterpiece's
// (lib/masterpieces.js); one not approved yet the client keeps out of dens, // (lib/masterpieces.js); one not approved yet the client keeps out of dens,
// trades and the recycler. // trades and the recycler.
// an item whose def is gone (a custom item deleted) is left out of both: the
// client skipped it without reading all its fields, and read every item after
// it wrong, placed ones as not placed and the den's floor and wallpaper lost.
const known = item => Boolean(defpacks.denItemDef(item.def));
const sendDenItems = session => { const sendDenItems = session => {
const {account} = session; const {account} = session;
const {denItems} = account; const denItems = account.denItems.filter(known);
const pets = petsInDen(account); const pets = petsInDen(account);
session.sendXt("di", -1, account.activeDen, denItems.length, pets.length, session.sendXt("di", -1, account.activeDen, denItems.length, pets.length,
...denItems.flatMap(item => { ...denItems.flatMap(item => {
@@ -124,19 +140,22 @@ const sendDenItems = session => {
// DenXtCommManager.denStateResponse: [itemCount, petCount, forceReload, // DenXtCommManager.denStateResponse: [itemCount, petCount, forceReload,
// (invIdx, defId, placed, x, y, version, flipped, userNameLink, imageId, // (invIdx, defId, placed, x, y, version, flipped, userNameLink, imageId,
// creatorDbId, creatorUuid, [mannequin], ?)..., (invIdx, lBits, uBits, eBits, // creatorDbId, creatorUuid, [mannequin], eco state)..., (invIdx, lBits, uBits, eBits,
// category, x, y, flipped, createdTs, personality, toy, food, name)...]. // category, x, y, flipped, createdTs, personality, toy, food, name)...].
// forceReload makes the client finish a pending room change, so it is set // forceReload makes the client finish a pending room change, so it is set
// when the den has just been entered. // when the den has just been entered.
const sendDenState = (session, room, forceReload = true) => { const sendDenState = (session, room, forceReload = true) => {
const owner = room.denOwner; const owner = room.denOwner;
const placed = itemsInDen(owner).filter(item => masterpieces.itemApproved(item)); const placed = itemsInDen(owner).filter(item => known(item) && masterpieces.itemApproved(item));
const pets = petsInDen(owner); const pets = petsInDen(owner);
session.sendXt("ds", room.id, placed.length, pets.length, forceReload ? 1 : 0, session.sendXt("ds", room.id, placed.length, pets.length, forceReload ? 1 : 0,
...placed.flatMap(item => { ...placed.flatMap(item => {
const spot = spotOf(item, owner.activeDen); const spot = spotOf(item, owner.activeDen);
return [item.inv, item.def, 1, spot.x, spot.y, item.version, spot.flip, "", ...masterpieces.itemFields(item), // Keep the editor's real placement category. Sending every placed
...mannequinShownFields(owner, item), 0]; // object as category 1 made wall/floor items enter the wrong display
// layer when a den was reloaded or another player visited.
return [item.inv, item.def, spot.cat || 1, spot.x, spot.y, item.version, spot.flip, "", ...masterpieces.itemFields(item),
...mannequinShownFields(owner, item), eco.consumerState(owner, item)];
}), }),
...pets.flatMap(pet => [pet.inv, pet.lBits, pet.uBits, pet.eBits, PET_CATEGORY, pet.inDen.x, pet.inDen.y, pet.inDen.flip, ...pets.flatMap(pet => [pet.inv, pet.lBits, pet.uBits, pet.eBits, PET_CATEGORY, pet.inDen.x, pet.inDen.y, pet.inDen.flip,
pet.createdAt, pet.personality || 0, pet.toy || 0, pet.food || 0, pet.name])); pet.createdAt, pet.personality || 0, pet.toy || 0, pet.food || 0, pet.name]));
@@ -367,6 +386,10 @@ const handlers = ({others, findOnline}) => {
session.sendXt("dss", -1); session.sendXt("dss", -1);
return; return;
} }
// the eco credits earned at the den's rate until now (lib/eco.js)
if (account.eco) {
eco.accrue(account);
}
const applied = []; const applied = [];
const byInv = new Map(account.denItems.map(candidate => [candidate.inv, candidate])); const byInv = new Map(account.denItems.map(candidate => [candidate.inv, candidate]));
const mannequins = account.denItems.filter(candidate => candidate.mannequin); const mannequins = account.denItems.filter(candidate => candidate.mannequin);
@@ -404,7 +427,7 @@ const handlers = ({others, findOnline}) => {
else { else {
delete item.spots[account.activeDen]; delete item.spots[account.activeDen];
} }
const mannequin = isMannequin(item) && readMannequin(account, outfit); const mannequin = isMannequin(item) && readMannequin(account, item, outfit);
if (mannequin) { if (mannequin) {
// A piece of clothing is on one mannequin at a time. // A piece of clothing is on one mannequin at a time.
for (const other of mannequins) { for (const other of mannequins) {
+84 -41
View File
@@ -19,11 +19,13 @@ const config = require("../config.js");
// again with a secret of this server's (data/device-key), so what is kept // again with a secret of this server's (data/device-key), so what is kept
// is of no use anywhere else. // is of no use anywhere else.
// //
// any one of them is a match: someone who edits /etc/machine-id or deletes // two computers are taken for one when they share at least MIN_MATCHING of
// MachineGuid still has the same disks and the client's own id. the network // these (owner, 2026-10-23: one or two in common was too often someone
// card's address alone (MAC_KIND) is a weak match: it is easily changed and // else's), for a ban and for an alt alike: someone who edits
// sometimes shared, so it bans nothing; it is written down for the // /etc/machine-id or deletes MachineGuid still has the same board, disks
// moderators instead. values every cheap board or VM has ("To be filled by // and the client's own id. the network card's address (MAC_KIND) does not
// count towards them: it is easily changed and sometimes shared, so it bans
// nothing; it is written down for the moderators instead. values every cheap board or VM has ("To be filled by
// O.E.M.", all zeros) are left out here, so that no ban falls on everyone // O.E.M.", all zeros) are left out here, so that no ban falls on everyone
// who has one. what the client noticed was wrong (the system id missing, or // who has one. what the client noticed was wrong (the system id missing, or
// not shaped as it always is) comes as notes, and is written down too. // not shaped as it always is) comes as notes, and is written down too.
@@ -56,6 +58,7 @@ const SCHEMA = `
const KINDS = ["os", "board", "disk", "install", "mac"]; const KINDS = ["os", "board", "disk", "install", "mac"];
const STRONG = ["os", "board", "disk", "install"]; const STRONG = ["os", "board", "disk", "install"];
const MAC_KIND = "mac"; const MAC_KIND = "mac";
const MIN_MATCHING = 3; // ids but a network card's two computers share to be taken for one
const LISTS = ["disk", "mac"]; // sent as lists; the rest one each const LISTS = ["disk", "mac"]; // sent as lists; the rest one each
const MAX_IN_LIST = 8; const MAX_IN_LIST = 8;
const MAX_KEPT = 60; // ids an account keeps, the latest const MAX_KEPT = 60; // ids an account keeps, the latest
@@ -106,6 +109,7 @@ const idsOf = account => {
return account.hwids; return account.hwids;
}; };
const tag = entry => `${entry.kind}:${entry.id}`; const tag = entry => `${entry.kind}:${entry.id}`;
const isStrong = id => STRONG.includes(id.split(":")[0]);
const banRow = row => ({id: row.id, ids: JSON.parse(row.ids), reason: row.reason, by: row.by, createdAt: row.created_at, const banRow = row => ({id: row.id, ids: JSON.parse(row.ids), reason: row.reason, by: row.by, createdAt: row.created_at,
accountId: row.account_id, username: row.username}); accountId: row.account_id, username: row.username});
@@ -161,27 +165,29 @@ const read = device => {
return ids.some(entry => STRONG.includes(entry.kind)) ? {ids, notes} : null; return ids.some(entry => STRONG.includes(entry.kind)) ? {ids, notes} : null;
}; };
// the ban that keeps this computer out, or null. a network card's address // the ban that has at least MIN_MATCHING of these "kind:id" in it, or
// alone keeps nobody out (see the top). // null. network cards' addresses are not counted (see the top).
const banOf = device => { const banMatching = ids => {
for (const entry of device.ids) { const strong = new Set(ids.filter(isStrong));
if (STRONG.includes(entry.kind) && banned.has(tag(entry))) { const looked = new Set();
return banned.get(tag(entry)); for (const id of strong) {
const ban = banned.get(id);
if (ban && !looked.has(ban.id)) {
looked.add(ban.id);
if (ban.ids.filter(one => strong.has(one)).length >= MIN_MATCHING) {
return ban;
}
} }
} }
return null; return null;
}; };
// the ban that keeps this computer out, or null.
const banOf = device => banMatching(device.ids.map(tag));
// the ban on any computer the account signed in from lately, or null: for // the ban on any computer the account signed in from lately, or null: for
// the client asking why its game was stopped. // the client asking why its game was stopped.
const banOfAccount = account => { const banOfAccount = account => banMatching(idsOf(account).filter(entry => entry.last > now() - DAYS_KEPT * 86400).map(tag));
for (const entry of idsOf(account)) {
if (STRONG.includes(entry.kind) && entry.last > now() - DAYS_KEPT * 86400 && banned.has(tag(entry))) {
return banned.get(tag(entry));
}
}
return null;
};
const alert = (account, kind, detail) => { const alert = (account, kind, detail) => {
const last = db().prepare("SELECT at FROM device_alerts WHERE account_id = ? AND kind = ? ORDER BY id DESC LIMIT 1").get(account.id, kind); const last = db().prepare("SELECT at FROM device_alerts WHERE account_id = ? AND kind = ? ORDER BY id DESC LIMIT 1").get(account.id, kind);
@@ -223,38 +229,47 @@ const seen = (account, device, isBanned) => {
if (nearBan) { if (nearBan) {
alert(account, "near_ban", `same network card as a hardware ban (${banned.get(tag(nearBan)).username || "no account"})`); alert(account, "near_ban", `same network card as a hardware ban (${banned.get(tag(nearBan)).username || "no account"})`);
} }
const sharers = new Set(); const shared = new Map(); // account id -> ids in common
for (const entry of device.ids.filter(one => STRONG.includes(one.kind))) { for (const entry of device.ids.filter(one => STRONG.includes(one.kind))) {
for (const id of holders.get(tag(entry)) || []) { for (const id of holders.get(tag(entry)) || []) {
const other = id === account.id ? null : accounts.byId(id); if (id !== account.id) {
if (other && isBanned(other)) { shared.set(id, (shared.get(id) || 0) + 1);
sharers.add(other.username);
} }
} }
} }
const sharers = new Set();
for (const [id, count] of shared) {
const other = count >= MIN_MATCHING ? accounts.byId(id) : null;
if (other && isBanned(other)) {
sharers.add(other.username);
}
}
if (sharers.size) { if (sharers.size) {
alert(account, "shares_banned", `same hardware as banned ${[...sharers].slice(0, 5).join(", ")}`); alert(account, "shares_banned", `same hardware as banned ${[...sharers].slice(0, 5).join(", ")}`);
} }
}; };
// the other accounts that used any of this one's computers: [{username, // the other accounts that used one of this one's computers, sharing at
// kinds: [kind], weak: true when only a network card}], most in common first. // least MIN_MATCHING of its ids: [{username, kinds: [kind]}], most in
// common first.
const alts = account => { const alts = account => {
const found = new Map(); // account id -> Set of kinds const found = new Map(); // account id -> {kinds: Set, strong: ids in common but network cards}
for (const entry of idsOf(account)) { for (const entry of idsOf(account)) {
for (const id of holders.get(tag(entry)) || []) { for (const id of holders.get(tag(entry)) || []) {
if (id !== account.id) { if (id !== account.id) {
if (!found.has(id)) { if (!found.has(id)) {
found.set(id, new Set()); found.set(id, {kinds: new Set(), strong: 0});
} }
found.get(id).add(entry.kind); found.get(id).kinds.add(entry.kind);
found.get(id).strong += STRONG.includes(entry.kind) ? 1 : 0;
} }
} }
} }
return [...found].map(([id, kinds]) => ({account: accounts.byId(id), kinds: [...kinds]})) return [...found].filter(([, shared]) => shared.strong >= MIN_MATCHING)
.map(([id, shared]) => ({account: accounts.byId(id), kinds: [...shared.kinds], strong: shared.strong}))
.filter(entry => entry.account) .filter(entry => entry.account)
.map(entry => ({username: entry.account.username, kinds: entry.kinds, weak: entry.kinds.every(kind => kind === MAC_KIND)})) .sort((one, other) => other.strong - one.strong || other.kinds.length - one.kinds.length || one.account.username.localeCompare(other.account.username))
.sort((one, other) => Number(one.weak) - Number(other.weak) || other.kinds.length - one.kinds.length || one.username.localeCompare(other.username)); .map(entry => ({username: entry.account.username, kinds: entry.kinds}));
}; };
// how many computers' worth of ids an account has, for the panels. // how many computers' worth of ids an account has, for the panels.
@@ -265,10 +280,10 @@ const knownFor = account => ({ids: idsOf(account).length, lastAt: idsOf(account)
// one of them. // one of them.
const banAccount = (account, reason, by) => { const banAccount = (account, reason, by) => {
const ids = [...new Set(idsOf(account).filter(entry => entry.last > now() - DAYS_KEPT * 86400).map(tag))]; const ids = [...new Set(idsOf(account).filter(entry => entry.last > now() - DAYS_KEPT * 86400).map(tag))];
if (!ids.some(id => STRONG.includes(id.split(":")[0]))) { if (ids.filter(isStrong).length < MIN_MATCHING) {
return {error: "No hardware IDs known for them."}; return {error: `Fewer than ${MIN_MATCHING} hardware IDs known for them.`};
} }
if (ids.filter(id => STRONG.includes(id.split(":")[0])).every(id => banned.has(id))) { if (ids.filter(isStrong).every(id => banned.has(id))) {
return {error: "Their hardware is banned already."}; return {error: "Their hardware is banned already."};
} }
const text = clean(reason, MAX_REASON) || NO_REASON; const text = clean(reason, MAX_REASON) || NO_REASON;
@@ -281,16 +296,16 @@ const banAccount = (account, reason, by) => {
return {ban}; return {ban};
}; };
// the accounts playing from one of a ban's computers, by their latest ids. // the accounts playing from one of a ban's computers, by their latest ids:
// those with at least MIN_MATCHING of its ids.
const accountsUnder = ban => { const accountsUnder = ban => {
const ids = new Set(ban.ids.filter(id => STRONG.includes(id.split(":")[0]))); const found = new Map(); // account id -> ids in common
const found = new Set(); for (const id of new Set(ban.ids.filter(isStrong))) {
for (const id of ids) {
for (const accountId of holders.get(id) || []) { for (const accountId of holders.get(id) || []) {
found.add(accountId); found.set(accountId, (found.get(accountId) || 0) + 1);
} }
} }
return [...found].map(id => accounts.byId(id)).filter(Boolean); return [...found].filter(([, count]) => count >= MIN_MATCHING).map(([id]) => accounts.byId(id)).filter(Boolean);
}; };
const unban = id => { const unban = id => {
@@ -308,6 +323,13 @@ const unban = id => {
return ban; return ban;
}; };
// one ban as kept, with the account it was made with (accountId), or null:
// for the moderator panel to see whose it is before lifting it.
const banById = id => {
const row = db().prepare("SELECT * FROM device_bans WHERE id = ?").get(Number(id));
return row ? banRow(row) : null;
};
// the bans, newest first: their ids, and the accounts that used them. // the bans, newest first: their ids, and the accounts that used them.
const MAX_LISTED_ACCOUNTS = 20; const MAX_LISTED_ACCOUNTS = 20;
const list = () => db().prepare("SELECT * FROM device_bans ORDER BY id DESC").all().map(banRow) const list = () => db().prepare("SELECT * FROM device_bans ORDER BY id DESC").all().map(banRow)
@@ -397,4 +419,25 @@ const forget = account => {
db().prepare("DELETE FROM device_alerts WHERE account_id = ?").run(account.id); db().prepare("DELETE FROM device_alerts WHERE account_id = ?").run(account.id);
}; };
module.exports = {load, read, banOf, banOfAccount, seen, alts, knownFor, banAccount, accountsUnder, unban, list, idsFor, bansOfAccount, search, bannedId, alerts, alertsOf, forget, clientHash}; // sign-in tokens last given to (or brought back by) a launcher that sent no
// device ids: one from before 1.3.0, or not ours. with config.requireDevice
// its sign-in still goes through, so that the game loads and its own login
// popup can say to update (lib/world.js), which a refused sign-in cannot.
// kept by hash, in memory: such a launcher signs in again each time it starts.
const MAX_OUTDATED = 20000;
const outdatedTokens = new Set();
const tokenKey = token => crypto.createHash("sha256").update(String(token)).digest("hex");
const noteLauncher = (token, hasIds) => {
const key = tokenKey(token);
if (hasIds) {
outdatedTokens.delete(key);
return;
}
if (outdatedTokens.size >= MAX_OUTDATED) {
outdatedTokens.delete(outdatedTokens.values().next().value);
}
outdatedTokens.add(key);
};
const launcherOutdated = token => outdatedTokens.has(tokenKey(token));
module.exports = {noteLauncher, launcherOutdated, load, read, banOf, banOfAccount, seen, alts, knownFor, banAccount, accountsUnder, unban, banById, list, idsFor, bansOfAccount, search, bannedId, alerts, alertsOf, forget, clientHash};
+295
View File
@@ -0,0 +1,295 @@
"use strict";
const crypto = require("crypto");
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js");
const badges = require("./badges.js");
const config = require("../config.js");
// a player's Discord account, linked on the account page by signing in to
// Discord (OAuth2, scope "identify"): the only way a Discord username gets
// onto a player's card, so the name shown is theirs. one Discord account
// for one Burrow account, or a single boost would badge a player's every
// account.
//
// the Discord Server Booster badge follows the linked account: given while
// it boosts Burrow's Discord server, taken off when it stops, checked when
// the account is linked and again every RECHECK_HOURS. Burrow's bot asks
// Discord (GET /guilds/<id>/members/<user id>, which needs no privileged
// intent: the bot only has to be in the server). an account that is not
// linked keeps whatever badges the admin gave it.
//
// with AJ_DISCORD_CLIENT_ID and AJ_DISCORD_CLIENT_SECRET unset, linking is
// off; without AJ_DISCORD_BOT_TOKEN and AJ_DISCORD_GUILD_ID, the booster
// badge is left alone.
const API = "https://discord.com/api/v10";
const AUTHORIZE = "https://discord.com/oauth2/authorize";
const STATE_MINUTES = 10;
const MAX_STATES = 10000;
const RECHECK_HOURS = 6;
const RECHECK_GAP_MS = 300; // between two members asked about, under Discord's rate limit
const TIMEOUT_MS = 15000;
const BOOSTER = "booster";
const linking = () => Boolean(config.discord.clientId && config.discord.clientSecret);
const boostChecks = () => Boolean(config.discord.botToken && config.discord.guildId);
const redirectUri = () => `${config.siteUrl}account/discord/callback`;
const adminRedirectUri = () => `${config.siteUrl}dashboard/admin/discord/callback`;
const staffRedirectUri = () => `${config.siteUrl}dashboard/staff/discord/callback`;
// a link under way: state (in Discord's address) -> {accountId, nonce (in a
// cookie of the browser that asked), expires}. both must come back.
const states = new Map();
const adminStates = new Map();
const staffStates = new Map();
const newState = statesMap => {
for (const [state, entry] of statesMap) {
if (entry.expires < Date.now()) {
statesMap.delete(state);
}
}
if (statesMap.size >= MAX_STATES) {
statesMap.delete(statesMap.keys().next().value);
}
const state = crypto.randomBytes(24).toString("hex");
const nonce = crypto.randomBytes(24).toString("hex");
statesMap.set(state, {nonce, expires: Date.now() + STATE_MINUTES * 60000});
return {state, nonce};
};
const authorize = (redirect, state) => {
const url = new URL(AUTHORIZE);
url.search = new URLSearchParams({client_id: config.discord.clientId, response_type: "code", scope: "identify",
redirect_uri: redirect, state, prompt: "consent"}).toString();
return url.href;
};
const start = account => {
const {state, nonce} = newState(states);
states.get(state).accountId = account.id;
return {url: authorize(redirectUri(), state), nonce};
};
// A separate OAuth state and redirect for the owner dashboard. The Discord
// account must already be linked to a Burrow account explicitly granted
// adminDashboardAccess; knowing a Discord name is never enough.
const startAdmin = () => {
const {state, nonce} = newState(adminStates);
return {url: authorize(adminRedirectUri(), state), nonce};
};
// Staff sign in through a separately scoped state and callback. A Discord
// identity is only useful here after its owner has linked it to their own
// Burrow account; modpanel.js also verifies that account remains active staff.
const startStaff = () => {
const {state, nonce} = newState(staffStates);
return {url: authorize(staffRedirectUri(), state), nonce};
};
const call = async (path, options = {}) => {
const res = await fetch(`${API}${path}`, {...options, signal: AbortSignal.timeout(TIMEOUT_MS)});
const body = await res.json().catch(() => ({}));
return {status: res.status, body};
};
// how a Discord username is kept and shown: as Discord spells them now, or,
// for an old "name#1234" one, without the characters a card cannot carry.
const shownName = user => badges.discordName(user.username)
|| `${String(user.username).replace(/[,|%\s]/g, "")}${user.discriminator && user.discriminator !== "0" ? `#${user.discriminator}` : ""}`.slice(0, 40);
const setBooster = (account, on) => {
if (account.badges.includes(BOOSTER) === on) {
return false;
}
badges.set(account, on ? [...account.badges, BOOSTER] : account.badges.filter(id => id !== BOOSTER));
return true;
};
// whether the linked account boosts the server now: true, false, or null
// when Discord could not be asked.
const boosting = async account => {
if (!boostChecks() || !account.discordId) {
return null;
}
for (let attempt = 0; attempt < 3; attempt++) {
const {status, body} = await call(`/guilds/${config.discord.guildId}/members/${account.discordId}`,
{headers: {Authorization: `Bot ${config.discord.botToken}`}}).catch(() => ({status: 0, body: {}}));
if (status === 200) {
return Boolean(body.premium_since);
}
if (status === 404) {
return false; // not in the server (any more)
}
if (status === 429) {
await new Promise(resolve => setTimeout(resolve, Math.min(60, Number(body.retry_after) || 5) * 1000));
continue;
}
console.log(`[discord] could not check ${logText(account.username)}'s boost: ${logText(status)}`);
return null;
}
return null;
};
const checkBoost = async account => {
const on = await boosting(account);
if (on !== null && setBooster(account, on)) {
accounts.save(account);
console.log(`[discord] ${logText(account.username)} ${on ? "boosts: booster badge given" : "no longer boosts: booster badge taken off"}`);
}
};
// the end of a link: the code Discord gave, for the state and the nonce the
// browser brought back. {ok, account} or {error}.
const finish = async (state, nonce, code) => {
const entry = typeof state === "string" ? states.get(state) : null;
states.delete(state);
const digest = text => crypto.createHash("sha256").update(String(text)).digest();
if (!entry || entry.expires < Date.now() || typeof nonce !== "string" || !crypto.timingSafeEqual(digest(entry.nonce), digest(nonce))) {
return {error: "expired"};
}
const account = accounts.byId(entry.accountId);
if (!account || typeof code !== "string" || !code) {
return {error: "expired"};
}
try {
const token = await call("/oauth2/token", {
method: "POST",
headers: {"Content-Type": "application/x-www-form-urlencoded"},
body: new URLSearchParams({client_id: config.discord.clientId, client_secret: config.discord.clientSecret,
grant_type: "authorization_code", code, redirect_uri: redirectUri()}).toString(),
});
if (token.status !== 200 || !token.body.access_token) {
return {error: "discord"};
}
const me = await call("/users/@me", {headers: {Authorization: `Bearer ${token.body.access_token}`}});
if (me.status !== 200 || !/^\d{5,25}$/.test(String(me.body.id))) {
return {error: "discord"};
}
const id = String(me.body.id);
if (accounts.all().some(other => other !== account && other.discordId === id)) {
return {error: "taken"};
}
account.discordId = id;
account.discord = shownName(me.body);
accounts.save(account);
console.log(`[discord] ${logText(account.username)} linked Discord ${logText(account.discord)} (${logText(id)})`);
await checkBoost(account);
return {ok: true, account};
}
catch (err) {
console.log(`[discord] link failed: ${logText(err.message)}`);
return {error: "discord"};
}
};
const finishAdmin = async (state, nonce, code) => {
const entry = typeof state === "string" ? adminStates.get(state) : null;
adminStates.delete(state);
const digest = text => crypto.createHash("sha256").update(String(text)).digest();
if (!entry || entry.expires < Date.now() || typeof nonce !== "string" || !crypto.timingSafeEqual(digest(entry.nonce), digest(nonce)) || !code) {
return {error: "expired"};
}
try {
const token = await call("/oauth2/token", {
method: "POST",
headers: {"Content-Type": "application/x-www-form-urlencoded"},
body: new URLSearchParams({client_id: config.discord.clientId, client_secret: config.discord.clientSecret,
grant_type: "authorization_code", code, redirect_uri: adminRedirectUri()}).toString(),
});
if (token.status !== 200 || !token.body.access_token) {
return {error: "discord"};
}
const me = await call("/users/@me", {headers: {Authorization: `Bearer ${token.body.access_token}`}});
if (me.status !== 200 || !/^\d{5,25}$/.test(String(me.body.id))) {
return {error: "discord"};
}
const account = accounts.all().find(candidate => candidate.discordId === String(me.body.id) && candidate.adminDashboardAccess);
return account ? {ok: true, account} : {error: "denied"};
}
catch (err) {
console.log(`[discord] admin sign-in failed: ${logText(err.message)}`);
return {error: "discord"};
}
};
const finishStaff = async (state, nonce, code) => {
const entry = typeof state === "string" ? staffStates.get(state) : null;
staffStates.delete(state);
const digest = text => crypto.createHash("sha256").update(String(text)).digest();
if (!entry || entry.expires < Date.now() || typeof nonce !== "string" || !crypto.timingSafeEqual(digest(entry.nonce), digest(nonce)) || !code) {
return {error: "expired"};
}
try {
const token = await call("/oauth2/token", {
method: "POST",
headers: {"Content-Type": "application/x-www-form-urlencoded"},
body: new URLSearchParams({client_id: config.discord.clientId, client_secret: config.discord.clientSecret,
grant_type: "authorization_code", code, redirect_uri: staffRedirectUri()}).toString(),
});
if (token.status !== 200 || !token.body.access_token) {
return {error: "discord"};
}
const me = await call("/users/@me", {headers: {Authorization: `Bearer ${token.body.access_token}`}});
if (me.status !== 200 || !/^\d{5,25}$/.test(String(me.body.id))) {
return {error: "discord"};
}
const account = accounts.all().find(candidate => candidate.discordId === String(me.body.id));
return account ? {ok: true, account} : {error: "denied"};
}
catch (err) {
console.log(`[discord] staff sign-in failed: ${logText(err.message)}`);
return {error: "discord"};
}
};
// the link undone, by the player or an admin; the booster badge goes with it.
const unlink = account => {
const had = Boolean(account.discordId || account.discord);
delete account.discordId;
account.discord = "";
if (had) {
setBooster(account, false);
}
accounts.save(account);
return had;
};
// every linked account in turn, a little apart, again and again.
let rechecking = false;
const recheckAll = async () => {
if (rechecking || !boostChecks()) {
return;
}
rechecking = true;
try {
for (const account of accounts.all().filter(one => one.discordId)) {
await checkBoost(account);
await new Promise(resolve => setTimeout(resolve, RECHECK_GAP_MS));
}
}
finally {
rechecking = false;
}
};
// at start: Discord usernames typed in by hand before linking existed are
// cleared (only a linked one is shown now), then the boosts are looked at
// and looked at again every RECHECK_HOURS.
const startup = () => {
const typed = accounts.all().filter(account => account.discord && !account.discordId);
for (const account of typed) {
account.discord = "";
}
if (typed.length) {
accounts.save(...typed);
console.log(`[discord] ${typed.length} Discord usernames typed in by hand were cleared`);
}
if (boostChecks()) {
setTimeout(recheckAll, 30000).unref();
setInterval(recheckAll, RECHECK_HOURS * 3600000).unref();
}
};
module.exports = {linking, boostChecks, start, finish, startAdmin, finishAdmin, startStaff, finishStaff, unlink, startup};
+962
View File
@@ -0,0 +1,962 @@
"use strict";
// Burrow's Discord control surface. It is intentionally a thin client over
// lib/modpanel.js: Discord proves who clicked a command, and the panel then
// proves that their linked Burrow account is still active staff and applies
// its usual permission and rank rules. There is no Discord-only staff list.
// discord.js is loaded when the bot starts, not with the server: a server
// without the package installed (npm ci) runs as before, the bot off.
let ActionRowBuilder;
let ButtonBuilder;
let ButtonStyle;
let ChannelType;
let Client;
let GatewayIntentBits;
let PermissionFlagsBits;
let SlashCommandBuilder;
const loadDiscordJs = () => {
if (Client) return true;
try {
({ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelType, Client, GatewayIntentBits, PermissionFlagsBits, SlashCommandBuilder} = require("discord.js"));
return true;
}
catch (err) {
console.log(`[discord-bot] discord.js could not be loaded (run npm ci): ${logText(err.message)}`);
return false;
}
};
const crypto = require("crypto");
const accounts = require("./accounts.js");
const config = require("../config.js");
const modpanel = require("./modpanel.js");
const modlog = require("./modlog.js");
const reports = require("./reports.js");
const world = require("./world.js");
const {logText} = require("./logtext.js");
// discord.js's MessageFlags.IsComponentsV2 and MessageFlags.Ephemeral, which
// cards need before the package is loaded
const COMPONENTS_V2 = 1 << 15;
const EPHEMERAL = 1 << 6;
const STATUS_MESSAGE_SETTING = "discordBotStatusMessage";
const STATUS_TITLE_SETTING = "discordBotStatusTitle";
const STATUS_NOTE_SETTING = "discordBotStatusNote";
const STATUS_BANNER_SETTING = "discordBotStatusBanner";
const STATUS_EVERY_MS = 5 * 60000;
const REPORT_BUTTON_PREFIX = "burrow:report:";
const MAX_GITHUB_WEBHOOK_BYTES = 512 * 1024;
const CONFIG_SETTING_PREFIX = "discordBotConfig:";
const SECURITY_SETTING = "discordBotSecurity";
const COMMUNITY_SETTING = "discordBotCommunity";
const CHANNELS = [
["reportsChannelId", "Reports"],
["statusChannelId", "Public status"],
["gameLogsChannelId", "In-game activity"],
["moderationLogsChannelId", "Moderation audit"],
["botLogsChannelId", "Discord bot audit"],
["updatesChannelId", "GitHub updates"],
];
const MANAGED_CONFIG = [...CHANNELS.map(([key]) => key), "githubRepository"];
let loadedDashboardConfig = false;
let securityConfigLoaded = false;
let securityConfig = null;
let communityConfig = null;
let communityConfigLoaded = false;
const recentMessages = new Map();
const recentJoins = [];
let lastRaidAlertAt = 0;
// Text Displays accept markdown. Keep player-provided strings readable while
// ensuring a report cannot ping a Discord role or user.
const safe = (value, max = 1000) => String(value === undefined || value === null ? "" : value)
.replace(/@/g, "@\u200b").replace(/`/g, "'").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, max);
// Discord fetches the banner itself, so only absolute http(s) URLs work.
// Blank means the card has no banner; null means the URL was rejected.
const bannerUrl = value => {
const text = String(value || "").trim();
if (!text) return "";
try {
const url = new URL(text);
return /^https?:$/.test(url.protocol) && text.length <= 500 ? url.toString() : null;
}
catch {
return null;
}
};
const statusSettings = () => ({
title: safe(accounts.setting(STATUS_TITLE_SETTING) || "Burrow status", 80) || "Burrow status",
note: safe(accounts.setting(STATUS_NOTE_SETTING) || "", 500),
banner: bannerUrl(accounts.setting(STATUS_BANNER_SETTING)) || "",
});
const setStatusSettings = ({title, note, banner}) => {
const next = {
title: safe(title || "Burrow status", 80) || "Burrow status",
note: safe(note || "", 500),
banner: bannerUrl(banner),
};
if (next.banner === null) return {error: "Banner must be an http(s) image URL of 500 characters or fewer, or blank for none."};
accounts.setSetting(STATUS_TITLE_SETTING, next.title);
accounts.setSetting(STATUS_NOTE_SETTING, next.note);
accounts.setSetting(STATUS_BANNER_SETTING, next.banner);
return next;
};
const securitySettings = () => {
if (securityConfigLoaded) return {...securityConfig};
const defaults = {enabled: false, blockInvites: true, blockedWords: [], spamLimit: 6, raidJoinLimit: 12};
try {
const saved = JSON.parse(accounts.setting(SECURITY_SETTING) || "{}");
const words = Array.isArray(saved.blockedWords) ? saved.blockedWords.map(word => safe(word, 60).toLowerCase()).filter(Boolean).slice(0, 50) : [];
securityConfig = {
enabled: saved.enabled === true,
blockInvites: saved.blockInvites !== false,
blockedWords: [...new Set(words)],
spamLimit: Number.isInteger(saved.spamLimit) && saved.spamLimit >= 2 && saved.spamLimit <= 20 ? saved.spamLimit : defaults.spamLimit,
raidJoinLimit: Number.isInteger(saved.raidJoinLimit) && saved.raidJoinLimit >= 3 && saved.raidJoinLimit <= 100 ? saved.raidJoinLimit : defaults.raidJoinLimit,
};
}
catch {
securityConfig = defaults;
}
securityConfigLoaded = true;
return {...securityConfig};
};
const updateSecuritySettings = values => {
const words = String(values.blockedWords || "").split(/\r?\n|,/)
.map(word => safe(word, 60).toLowerCase()).filter(Boolean).slice(0, 50);
const spamLimit = Number(values.spamLimit);
const raidJoinLimit = Number(values.raidJoinLimit);
if (!Number.isInteger(spamLimit) || spamLimit < 2 || spamLimit > 20 || !Number.isInteger(raidJoinLimit) || raidJoinLimit < 3 || raidJoinLimit > 100) {
return {error: "Spam limit must be 2 to 20 and raid join limit must be 3 to 100."};
}
securityConfig = {enabled: values.enabled === true, blockInvites: values.blockInvites === true,
blockedWords: [...new Set(words)], spamLimit, raidJoinLimit};
securityConfigLoaded = true;
accounts.setSetting(SECURITY_SETTING, JSON.stringify(securityConfig));
return {ok: "Discord security settings saved. Reconnect the bot to apply message and join monitoring.", security: securitySettings()};
};
const communitySettings = () => {
if (communityConfigLoaded) return {...communityConfig};
try {
const saved = JSON.parse(accounts.setting(COMMUNITY_SETTING) || "{}");
communityConfig = {ticketCategoryId: channelId(saved.ticketCategoryId) || "", ticketStaffRoleId: channelId(saved.ticketStaffRoleId) || "",
welcomeChannelId: channelId(saved.welcomeChannelId) || "", welcomeMessage: safe(saved.welcomeMessage || "Welcome {user} to {server}!", 500),
goodbyeChannelId: channelId(saved.goodbyeChannelId) || "", goodbyeMessage: safe(saved.goodbyeMessage || "Goodbye {user}.", 500)};
}
catch { communityConfig = {ticketCategoryId: "", ticketStaffRoleId: "", welcomeChannelId: "", welcomeMessage: "Welcome {user} to {server}!", goodbyeChannelId: "", goodbyeMessage: "Goodbye {user}."}; }
communityConfigLoaded = true;
return {...communityConfig};
};
const updateCommunitySettings = values => {
const current = communitySettings();
const next = {...current};
for (const key of ["ticketCategoryId", "ticketStaffRoleId", "welcomeChannelId", "goodbyeChannelId"]) {
const id = channelId(values[key]);
if (id === null) return {error: "Discord channel, category, and role IDs must contain only 5 to 25 digits."};
next[key] = id;
}
next.welcomeMessage = safe(values.welcomeMessage || "", 500);
next.goodbyeMessage = safe(values.goodbyeMessage || "", 500);
communityConfig = next;
communityConfigLoaded = true;
accounts.setSetting(COMMUNITY_SETTING, JSON.stringify(next));
return {ok: "Community and ticket settings saved.", community: communitySettings()};
};
// Non-secret routing settings are owner-controlled in the dashboard. The bot
// token and webhook secret deliberately remain environment-only, so a copied
// database or dashboard session cannot disclose them.
const loadDashboardConfig = () => {
if (loadedDashboardConfig) return;
for (const key of MANAGED_CONFIG) {
const saved = accounts.setting(`${CONFIG_SETTING_PREFIX}${key}`);
if (saved !== null) config.discord[key] = saved;
}
loadedDashboardConfig = true;
};
const channelId = value => {
const id = String(value === undefined || value === null ? "" : value).trim();
return id === "" || /^\d{5,25}$/.test(id) ? id : null;
};
const updateDashboardConfig = values => {
loadDashboardConfig();
const previousStatusChannelId = config.discord.statusChannelId || "";
const next = {};
for (const [key] of CHANNELS) {
const id = channelId(values[key]);
if (id === null) return {error: "Discord channel IDs must contain only 5 to 25 digits."};
next[key] = id;
}
const repository = String(values.githubRepository === undefined || values.githubRepository === null ? "" : values.githubRepository).trim();
if (repository && !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\/[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/.test(repository)) {
return {error: "GitHub repository must use the form owner/repository."};
}
next.githubRepository = repository;
for (const key of MANAGED_CONFIG) {
config.discord[key] = next[key];
accounts.setSetting(`${CONFIG_SETTING_PREFIX}${key}`, next[key]);
}
if (next.statusChannelId !== previousStatusChannelId) {
accounts.setSetting(STATUS_MESSAGE_SETTING, "");
}
return {ok: "Discord routing settings saved.", configuration: dashboardStatus()};
};
const duration = seconds => {
if (seconds === -1) return "permanent";
if (!seconds) return "none";
const hours = Math.ceil(Number(seconds) / 3600);
return `${hours} hour${hours === 1 ? "" : "s"}`;
};
// Components V2 means every visible response—success, refusal, report alert
// and status card—uses a Container and Text Displays. Never add `content` or
// `embeds` to these payloads: Discord ignores them for Components V2.
const card = ({title, sections = [], tone = 0x5865f2, ephemeral = false, components = []}) => ({
flags: COMPONENTS_V2 | (ephemeral ? EPHEMERAL : 0),
allowedMentions: {parse: []},
components: [{
type: 17, // Container
accent_color: tone,
components: [
{type: 10, content: `## ${safe(title, 160)}`}, // Text Display
...sections.filter(Boolean).slice(0, 8).flatMap((section, index) => [
...(index ? [{type: 14, divider: true, spacing: 1}] : []), // Separator
{type: 10, content: safe(section, 1800)},
]),
...components,
],
}],
});
const success = (title, sections, ephemeral = true) => card({title, sections, tone: 0x57f287, ephemeral});
const warning = (message, ephemeral = true) => card({title: "Burrow", sections: [message], tone: 0xfee75c, ephemeral});
const failure = (message, ephemeral = true) => card({title: "Burrow", sections: [message], tone: 0xed4245, ephemeral});
// Staff audit streams use the same compact Components V2 pattern as SRP-Bot:
// a brief summary, structured fields, and a durable log timestamp.
const logCard = ({title, description = "", fields = [], tone = 0x5865f2}) => {
const shown = fields.filter(field => field && field.name && field.value !== undefined && field.value !== null).slice(0, 12);
const components = [{type: 10, content: [
`## ${safe(title, 160)}`,
description ? safe(description, 900) : "",
].filter(Boolean).join("\n")}];
if (shown.length) {
components.push({type: 14, divider: true, spacing: 1});
components.push({type: 10, content: shown
.map(field => `• **${safe(field.name, 80)}:** ${safe(field.value, 500)}`)
.join("\n")
.slice(0, 1800)});
}
const now = Math.floor(Date.now() / 1000);
components.push({type: 14, divider: false, spacing: 1});
components.push({type: 10, content: `_Logged <t:${now}:F> (<t:${now}:R>)_`});
return {
flags: COMPONENTS_V2,
allowedMentions: {parse: []},
components: [{type: 17, accent_color: tone, components}],
};
};
const commandDefinitions = () => [
new SlashCommandBuilder().setName("burrow").setDescription("View Burrow server and player information")
.addSubcommand(command => command.setName("status").setDescription("Show the live Burrow server status"))
.addSubcommand(command => command.setName("player").setDescription("Look up a Burrow player")
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true)))
.addSubcommand(command => command.setName("reports").setDescription("Show open player reports"))
.addSubcommand(command => command.setName("staff").setDescription("Show Burrow staff"))
.addSubcommand(command => command.setName("announce").setDescription("Send an announcement to everyone playing")
.addStringOption(option => option.setName("message").setDescription("Announcement shown in-game").setRequired(true).setMaxLength(300))),
new SlashCommandBuilder().setName("moderate").setDescription("Moderate Burrow through your linked staff account")
.addSubcommand(command => command.setName("warn").setDescription("Warn a player")
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))
.addStringOption(option => option.setName("reason").setDescription("Warning reason, e.g. behavior or custom").setRequired(true))
.addStringOption(option => option.setName("note").setDescription("Required explanation for a custom warning")))
.addSubcommand(command => command.setName("silence").setDescription("Stop a player from chatting")
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))
.addIntegerOption(option => option.setName("hours").setDescription("Whole hours; 0 means until lifted").setRequired(true).setMinValue(0).setMaxValue(87600)))
.addSubcommand(command => command.setName("unsilence").setDescription("Let a player chat again")
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true)))
.addSubcommand(command => command.setName("kick").setDescription("Disconnect an online player")
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true)))
.addSubcommand(command => command.setName("ban").setDescription("Ban a player")
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))
.addIntegerOption(option => option.setName("hours").setDescription("Whole hours; 0 means permanent").setRequired(true).setMinValue(0).setMaxValue(87600))
.addStringOption(option => option.setName("reason").setDescription("Why this player is being banned").setRequired(true)))
.addSubcommand(command => command.setName("unban").setDescription("Lift a player's Burrow ban")
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))),
new SlashCommandBuilder().setName("discord").setDescription("Moderate this Discord server through Burrow staff permissions")
.addSubcommand(command => command.setName("timeout").setDescription("Temporarily silence a Discord member")
.addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true))
.addIntegerOption(option => option.setName("hours").setDescription("Whole hours, up to 28 days").setRequired(true).setMinValue(1).setMaxValue(672))
.addStringOption(option => option.setName("reason").setDescription("Why this member is being timed out").setMaxLength(300)))
.addSubcommand(command => command.setName("untimeout").setDescription("Remove a Discord member timeout")
.addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true))
.addStringOption(option => option.setName("reason").setDescription("Why the timeout is being removed").setMaxLength(300)))
.addSubcommand(command => command.setName("kick").setDescription("Remove a Discord member from this server")
.addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true))
.addStringOption(option => option.setName("reason").setDescription("Why this member is being removed").setMaxLength(300)))
.addSubcommand(command => command.setName("ban").setDescription("Ban a Discord member from this server")
.addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true))
.addStringOption(option => option.setName("reason").setDescription("Why this member is being banned").setMaxLength(300)))
.addSubcommand(command => command.setName("unban").setDescription("Lift a Discord server ban")
.addStringOption(option => option.setName("user_id").setDescription("Discord user ID").setRequired(true).setMinLength(5).setMaxLength(25))
.addStringOption(option => option.setName("reason").setDescription("Why the ban is being removed").setMaxLength(300)))
.addSubcommand(command => command.setName("purge").setDescription("Delete recent messages in this channel")
.addIntegerOption(option => option.setName("amount").setDescription("Messages to delete (1 to 100)").setRequired(true).setMinValue(1).setMaxValue(100))
.addStringOption(option => option.setName("reason").setDescription("Why messages are being removed").setMaxLength(300))),
new SlashCommandBuilder().setName("ticket").setDescription("Open or manage a private support ticket")
.addSubcommand(command => command.setName("open").setDescription("Open a private support ticket")
.addStringOption(option => option.setName("subject").setDescription("What you need help with").setRequired(true).setMaxLength(80)))
.addSubcommand(command => command.setName("close").setDescription("Close this support ticket")),
].map(command => command.toJSON());
// a command or button counts for a staff member signed in to the panel with
// their 2FA code (modpanel.discordBot.commandActor): Discord alone is not them.
const actorFor = interaction => modpanel.discordBot.commandActor(interaction.user.id);
const reportButton = report => new ActionRowBuilder().addComponents(
new ButtonBuilder().setCustomId(`${REPORT_BUTTON_PREFIX}${report.id}:handled`).setLabel("Mark handled").setStyle(ButtonStyle.Success),
).toJSON();
const reportCard = (report, {handled = false, ephemeral = false} = {}) => card({
title: handled ? `Report #${report.id} handled` : `Report #${report.id}`,
tone: handled ? 0x57f287 : 0xfee75c,
ephemeral,
sections: [
`**${safe(report.reporter, 40)}** reported **${safe(report.target, 40)}**\n${safe(report.reason, 200)}`,
report.detail ? `**Details**\n${safe(report.detail, 500)}` : "*No additional details.*",
report.room ? `Room: \`${safe(report.room, 100)}\`` : "",
],
components: handled ? [] : [{type: 14, divider: true, spacing: 1}, reportButton(report)],
});
const playerCard = player => success(`Player: ${player.username}`, [
`**Status**\n${player.online ? `Online${player.room ? ` in ${safe(player.room, 100)}` : ""}` : "Offline"}\nRole: ${player.role || "Player"}`,
`**Moderation**\nBan: ${duration(player.banned)}\nSilence: ${duration(player.silenced)}\nWarnings: ${player.warnings}\nOpen reports: ${player.openReports}`,
player.discord ? `**Discord**\n${safe(player.discord, 80)}` : "",
]);
const statusCard = status => {
const settings = statusSettings();
const now = Math.floor(Date.now() / 1000);
const startedAt = now - status.uptimeSeconds;
const rooms = `${status.rooms} room${status.rooms === 1 ? "" : "s"}`;
const playUrl = new URL("gameClient/game/index.html", config.siteUrl).toString();
// This is intentionally public-only: moderation reports and queue depth are
// staff data and do not belong in a community-facing server-status post.
return {
flags: COMPONENTS_V2,
allowedMentions: {parse: []},
components: [{
type: 17,
accent_color: 0x7c5ce7,
components: [
{type: 10, content: `## ${safe(settings.title, 80)}`},
{type: 14, divider: true, spacing: 1},
{type: 10, content: ["### STATUS", "🟢 **Online**", settings.note ? `\n${safe(settings.note, 500)}` : ""].filter(Boolean).join("\n")},
{type: 14, divider: true, spacing: 1},
{type: 10, content: `### PLAYERS\n\`${status.players} online\` • \`${rooms}\``},
{type: 14, divider: true, spacing: 1},
{type: 10, content: `### UPTIME\nStarted <t:${startedAt}:R> • ${status.memoryMb} MB memory`},
...settings.banner ? [{type: 12, items: [{media: {url: settings.banner}}]}] : [],
{type: 1, components: [{type: 2, style: 5, label: "Play Burrow", url: playUrl}]},
{type: 10, content: `_Last updated <t:${now}:R>_`},
],
}],
};
};
const staffCard = staff => success("Burrow staff", staff.length
? [staff.map(member => `**${safe(member.username, 40)}** — ${safe(member.role, 30)}${member.twoStep ? " · 2FA" : ""}`).join("\n")]
: ["No active Burrow staff accounts."]);
const inConfiguredGuild = interaction => interaction.guildId === config.discord.guildId;
const replyResult = async (interaction, result, title = "Burrow") => {
if (result.error) {
await interaction.editReply(failure(result.error));
return;
}
await interaction.editReply(success(title, [result.ok, result.detail].filter(Boolean)));
};
const handleBurrow = async interaction => {
const actor = actorFor(interaction);
const subcommand = interaction.options.getSubcommand();
if (subcommand === "status") {
const result = modpanel.discordBot.status(actor);
await interaction.editReply(result.error ? failure(result.error) : {...statusCard(result), flags: COMPONENTS_V2 | EPHEMERAL});
return;
}
if (subcommand === "player") {
const result = modpanel.discordBot.player(actor, interaction.options.getString("username", true));
await interaction.editReply(result.error ? failure(result.error) : {...playerCard(result.player), flags: COMPONENTS_V2 | EPHEMERAL});
return;
}
if (subcommand === "staff") {
const result = modpanel.discordBot.staff(actor);
await interaction.editReply(result.error ? failure(result.error) : staffCard(result.staff));
return;
}
if (subcommand === "announce") {
await replyResult(interaction, modpanel.discordBot.announce(actor, interaction.options.getString("message", true)), "In-game announcement");
return;
}
const result = modpanel.discordBot.reports(actor);
if (result.error) {
await interaction.editReply(failure(result.error));
return;
}
const shown = result.reports.slice(0, 5);
await interaction.editReply(success("Open reports", [
`${result.open} open report${result.open === 1 ? "" : "s"}.`,
shown.length ? shown.map(report => `#${report.id} — **${safe(report.target, 40)}** — ${safe(report.reason, 100)}`).join("\n") : "No reports are waiting.",
]));
};
const handleModerate = async interaction => {
const actor = actorFor(interaction);
const subcommand = interaction.options.getSubcommand();
const username = interaction.options.getString("username", true);
const fields = {action: subcommand};
if (subcommand === "warn") {
fields.reason = interaction.options.getString("reason", true);
fields.note = interaction.options.getString("note") || "";
}
if (subcommand === "silence" || subcommand === "ban") {
fields.hours = interaction.options.getInteger("hours", true);
}
if (subcommand === "ban") {
fields.reason = interaction.options.getString("reason", true);
}
await replyResult(interaction, modpanel.discordBot.act(actor, username, fields), `Moderation: ${subcommand}`);
};
const nativeDiscordPermission = action => ({
timeout: "chat.silence",
untimeout: "chat.silence",
kick: "player.kick",
ban: "player.ban",
unban: "player.ban",
purge: "player.kick",
})[action] || "";
const handleDiscordModeration = async interaction => {
const actor = actorFor(interaction);
const action = interaction.options.getSubcommand();
const refused = modpanel.discordBot.authorize(actor, nativeDiscordPermission(action));
if (refused) {
await interaction.editReply(failure(refused.error));
return;
}
const reason = safe(interaction.options.getString("reason") || `Burrow staff action by ${actor.username}`, 300);
const user = action === "unban" ? null : interaction.options.getUser("member", true);
if (user && modpanel.discordBot.actor(user.id)) {
await interaction.editReply(failure("Discord-native moderation cannot target an active linked Burrow staff account."));
return;
}
try {
let detail = "";
let target = user ? user.username : interaction.options.getString("user_id", true);
if (action === "timeout" || action === "untimeout" || action === "kick") {
const member = await interaction.guild.members.fetch(user.id);
if (action === "timeout") {
const hours = interaction.options.getInteger("hours", true);
await member.timeout(hours * 3600000, reason);
detail = `${hours} hour${hours === 1 ? "" : "s"}`;
}
else if (action === "untimeout") {
await member.timeout(null, reason);
}
else {
await member.kick(reason);
}
}
else if (action === "ban") {
await interaction.guild.members.ban(user.id, {reason, deleteMessageSeconds: 0});
}
else if (action === "unban") {
if (!/^\d{5,25}$/.test(target)) throw new Error("bad_user_id");
await interaction.guild.members.unban(target, reason);
}
else if (action === "purge") {
const amount = interaction.options.getInteger("amount", true);
if (!interaction.channel || !interaction.channel.isTextBased() || typeof interaction.channel.bulkDelete !== "function") throw new Error("not_text_channel");
const deleted = await interaction.channel.bulkDelete(amount, true);
detail = `${deleted.size} message${deleted.size === 1 ? "" : "s"}`;
target = "this channel";
}
else throw new Error("unknown_action");
modlog.record(actor.username, `Discord ${action}`, target, detail || reason);
await interaction.editReply(success(`Discord ${action}`, [`${safe(target, 80)} — ${detail || "completed"}.`].concat(reason ? [`Reason: ${reason}`] : [])));
}
catch (err) {
if (err.message === "bad_user_id") {
await interaction.editReply(failure("Enter a valid Discord user ID."));
return;
}
console.log(`[discord-bot] Discord ${action} failed: ${logText(err.message)}`);
await interaction.editReply(failure("Discord could not complete that action. Check the bot permission and role position."));
}
};
const ticketOwner = channel => (channel && /^burrow-ticket:(\d{5,25})$/.exec(channel.topic || "") || [])[1] || "";
const handleTicket = async interaction => {
const action = interaction.options.getSubcommand();
const settings = communitySettings();
if (action === "open") {
if (!settings.ticketCategoryId || !settings.ticketStaffRoleId) {
await interaction.editReply(failure("Tickets are not configured. Ask an owner to set the ticket category and staff role in the Discord dashboard."));
return;
}
const subject = safe(interaction.options.getString("subject", true), 80);
const channel = await interaction.guild.channels.create({
name: `ticket-${interaction.user.id}`,
type: ChannelType.GuildText,
parent: settings.ticketCategoryId,
topic: `burrow-ticket:${interaction.user.id}`,
permissionOverwrites: [
{id: interaction.guild.roles.everyone.id, deny: [PermissionFlagsBits.ViewChannel]},
{id: interaction.user.id, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory]},
{id: settings.ticketStaffRoleId, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory]},
{id: client.user.id, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ManageChannels, PermissionFlagsBits.ReadMessageHistory]},
],
}).catch(() => null);
if (!channel) {
await interaction.editReply(failure("Discord could not open the ticket. Check the category, staff role, and bot channel permissions."));
return;
}
await channel.send(card({title: "Support ticket", tone: 0x5865f2, sections: [`Opened by **${safe(interaction.user.username, 80)}**\nSubject: ${subject}`, "A staff member will reply here. Use `/ticket close` when this is resolved."]}));
await interaction.editReply(success("Ticket opened", [`Your private ticket: ${channel}`]));
return;
}
const owner = ticketOwner(interaction.channel);
const staff = modpanel.discordBot.actor(interaction.user.id);
if (!owner || (owner !== interaction.user.id && !staff)) {
await interaction.editReply(failure("Only the ticket opener or linked Burrow staff can close this ticket."));
return;
}
await interaction.channel.setName(`closed-${interaction.channel.name}`.slice(0, 100)).catch(() => {});
if (owner) await interaction.channel.permissionOverwrites.edit(owner, {ViewChannel: false}).catch(() => {});
modlog.record(staff ? staff.username : interaction.user.username, "Discord ticket closed", interaction.channel.name);
await interaction.editReply(success("Ticket closed", ["The opener can no longer view this channel. Staff retain it for the support record."]));
};
const handleButton = async interaction => {
const match = new RegExp(`^${REPORT_BUTTON_PREFIX.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(\\d+):handled$`).exec(interaction.customId);
if (!match) {
return false;
}
if (!inConfiguredGuild(interaction)) {
await interaction.reply(failure("This control belongs to another Discord server.")).catch(() => {});
return true;
}
const result = modpanel.discordBot.handleReport(actorFor(interaction), Number(match[1]));
if (result.error) {
await interaction.reply(failure(result.error)).catch(() => {});
return true;
}
await interaction.update(success(`Report #${Number(match[1])} handled`, [result.ok], false)).catch(() => {});
return true;
};
let client = null;
let statusTimer = null;
let unsubscribeReports = null;
let unsubscribeGameActivity = null;
let unsubscribeModeration = null;
let securityGatewayOn = false;
const channelFor = async id => {
if (!id || !client || !client.isReady()) return null;
const channel = await client.channels.fetch(id).catch(() => null);
return channel && channel.isTextBased() ? channel : null;
};
const postCard = async (channelId, payload, label) => {
const channel = await channelFor(channelId);
if (channel) {
await channel.send(payload).catch(err => console.log(`[discord-bot] ${label} failed: ${logText(err.message)}`));
}
};
const publishStatus = async () => {
const channel = await channelFor(config.discord.statusChannelId);
if (!channel) return {error: "The public status channel is not configured or the Discord bot is not connected."};
const players = world.players();
const payload = statusCard({players: players.length, rooms: new Set(players.map(player => player.room).filter(Boolean)).size,
reports: reports.openCount(), uptimeSeconds: Math.floor(process.uptime()), memoryMb: Math.round(process.memoryUsage().rss / 1048576)});
// The public status card needs no staff actor; it exposes only aggregate
// counts. Store its message id in the server database so restarts edit it.
const saved = accounts.setting(STATUS_MESSAGE_SETTING);
const existing = saved && await channel.messages.fetch(saved).catch(() => null);
if (existing) {
const updated = await existing.edit(payload).then(() => true).catch(err => {
console.log(`[discord-bot] status update failed: ${logText(err.message)}`);
return false;
});
return updated ? {ok: "The public status card was updated."} : {error: "Discord could not update the public status card."};
}
const message = await channel.send(payload).catch(err => {
console.log(`[discord-bot] status post failed: ${logText(err.message)}`);
return null;
});
if (!message) return {error: "Discord could not post the public status card."};
accounts.setSetting(STATUS_MESSAGE_SETTING, message.id);
return {ok: "The public status card was posted."};
};
const notifyReport = async report => {
await postCard(config.discord.reportsChannelId, reportCard(report), "report notification");
};
const notifyGameActivity = async entry => {
const minutes = Math.max(1, Math.ceil((entry.playedSeconds || 0) / 60));
const signedIn = entry.type === "login";
await postCard(config.discord.gameLogsChannelId, logCard({
title: "In-game activity",
description: signedIn ? "A player signed in." : "A player signed out.",
tone: signedIn ? 0x57f287 : 0x5865f2,
fields: [
{name: "Player", value: entry.username},
{name: "Event", value: signedIn ? "Signed in" : "Signed out"},
...(!signedIn ? [{name: "Session", value: `${minutes} minute${minutes === 1 ? "" : "s"}`}] : []),
],
}), "game activity log");
};
const notifyModeration = async entry => {
await postCard(config.discord.moderationLogsChannelId, logCard({
title: "Moderation audit",
description: "A Burrow staff action was recorded.",
tone: 0xfee75c,
fields: [
{name: "Staff", value: entry.by},
{name: "Action", value: entry.action},
...(entry.target ? [{name: "Player", value: entry.target}] : []),
...(entry.detail ? [{name: "Details", value: entry.detail}] : []),
],
}), "moderation log");
};
const notifyBot = async (interaction, action) => {
const actor = modpanel.discordBot.actor(interaction.user.id);
await postCard(config.discord.botLogsChannelId, logCard({
title: "Discord bot audit",
description: "A Discord command or control was used.",
tone: actor ? 0x5865f2 : 0xed4245,
fields: [
{name: "Discord user", value: `${interaction.user.username} (${interaction.user.id})`},
{name: "Action", value: action},
{name: "Linked staff account", value: actor ? actor.username : "No active linked Burrow staff account."},
],
}), "Discord bot audit log");
};
const securityIncident = async (title, sections, detail = "") => {
await postCard(config.discord.moderationLogsChannelId, logCard({
title,
description: "Discord security activity detected.",
tone: 0xed4245,
fields: [{name: "Details", value: sections.filter(Boolean).join("\n")}],
}), "Discord security log");
modlog.record("discord security", title.toLowerCase(), "", detail);
};
const isConfiguredGuild = guild => Boolean(guild && guild.id === config.discord.guildId);
const inspectDiscordMessage = async message => {
const settings = securitySettings();
if (!settings.enabled || message.author?.bot || !isConfiguredGuild(message.guild)) return;
const at = Date.now();
const key = message.author.id;
const times = (recentMessages.get(key) || []).filter(time => time > at - 10000);
times.push(at);
recentMessages.set(key, times);
const text = String(message.content || "").toLowerCase();
const hasInvite = settings.blockInvites && /(?:discord\.gg|discord(?:app)?\.com\/invite)\//i.test(text);
const word = settings.blockedWords.find(entry => text.includes(entry));
const reason = times.length > settings.spamLimit ? "message spam" : hasInvite ? "Discord invite" : word ? "blocked word" : "";
if (!reason) return;
if (message.deletable) await message.delete().catch(() => {});
await securityIncident("Discord AutoMod", [
`Member: **${safe(message.author.username, 80)}**`,
`Action: deleted message for ${reason}.`,
], `${safe(message.author.username, 80)}: ${reason}`);
};
const inspectDiscordJoin = async member => {
const settings = securitySettings();
if (!settings.enabled || !isConfiguredGuild(member.guild)) return;
const at = Date.now();
recentJoins.push(at);
while (recentJoins.length && recentJoins[0] <= at - 60000) recentJoins.shift();
if (recentJoins.length < settings.raidJoinLimit || lastRaidAlertAt > at - 60000) return;
lastRaidAlertAt = at;
await securityIncident("Discord anti-raid alert", [
`${recentJoins.length} members joined in the last minute.`,
"Review recent joins and use the dashboard or Discord moderation controls if action is needed.",
], `${recentJoins.length} joins in one minute`);
};
const communityNotice = async (member, kind) => {
const settings = communitySettings();
const channelId = kind === "welcome" ? settings.welcomeChannelId : settings.goodbyeChannelId;
const template = kind === "welcome" ? settings.welcomeMessage : settings.goodbyeMessage;
if (!channelId || !isConfiguredGuild(member.guild)) return;
const message = safe(template.replace(/\{user\}/gi, member.user.username).replace(/\{server\}/gi, member.guild.name), 500);
if (message) await postCard(channelId, card({title: kind === "welcome" ? "Welcome" : "Goodbye", tone: kind === "welcome" ? 0x57f287 : 0x5865f2, sections: [message]}), `${kind} notice`);
};
const githubUpdatesOn = () => {
loadDashboardConfig();
return Boolean(config.discord.githubRepository && config.discord.githubWebhookSecret && config.discord.updatesChannelId);
};
// Safe to expose to the owner dashboard: it deliberately contains state and
// channel ids only, never the bot token or GitHub webhook secret.
const dashboardStatus = () => {
loadDashboardConfig();
return {
botTokenConfigured: Boolean(config.discord.botToken),
guildId: config.discord.guildId || "",
connected: Boolean(client && client.isReady()),
commands: ["/burrow status", "/burrow player", "/burrow reports", "/burrow staff", "/burrow announce", "/moderate warn", "/moderate silence", "/moderate unsilence", "/moderate kick", "/moderate ban", "/moderate unban", "/discord timeout", "/discord untimeout", "/discord kick", "/discord ban", "/discord unban", "/discord purge"],
channels: CHANNELS.map(([key, name]) => ({key, name, id: config.discord[key] || "", configured: Boolean(config.discord[key])})),
github: {
repository: config.discord.githubRepository || "",
webhookSecretConfigured: Boolean(config.discord.githubWebhookSecret),
updatesEnabled: githubUpdatesOn(),
endpoint: "/discord/github",
},
statusCard: statusSettings(),
security: {...securitySettings(), monitoring: securityGatewayOn},
community: communitySettings(),
modules: [
{name: "Burrow staff tools", detail: "Player lookup, reports, staff list, in-game announcements, and game moderation", enabled: Boolean(config.discord.botToken && config.discord.guildId)},
{name: "Discord moderation", detail: "Timeout, kick, ban, unban, and purge; gated by linked Burrow staff permissions", enabled: Boolean(config.discord.botToken && config.discord.guildId)},
{name: "Activity and audit logs", detail: "In-game activity, reports, moderation, and bot command audit streams", enabled: CHANNELS.some(([key]) => key !== "updatesChannelId" && Boolean(config.discord[key]))},
{name: "GitHub updates", detail: "Signed commit cards, with client changes marked as game updates", enabled: githubUpdatesOn()},
{name: "AutoMod and anti-raid", detail: "Blocked words, invite blocking, anti-spam, and join-rate alerts", enabled: securitySettings().enabled},
{name: "Tickets and member notices", detail: "Private support tickets plus configurable welcome and goodbye cards", enabled: Boolean(communitySettings().ticketCategoryId && communitySettings().ticketStaffRoleId)},
],
};
};
const githubBody = req => new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
req.on("data", chunk => {
size += chunk.length;
if (size > MAX_GITHUB_WEBHOOK_BYTES) {
req.destroy();
reject(new Error("too_large"));
return;
}
chunks.push(chunk);
});
req.on("end", () => resolve(Buffer.concat(chunks)));
req.on("error", reject);
});
const githubSignatureMatches = (body, signature) => {
if (!/^sha256=[0-9a-f]{64}$/i.test(String(signature || ""))) return false;
const expected = `sha256=${crypto.createHmac("sha256", config.discord.githubWebhookSecret).update(body).digest("hex")}`;
return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(String(signature)));
};
const changedFiles = commit => [commit.added, commit.modified, commit.removed].flat().filter(file => typeof file === "string");
const gameChange = payload => (payload.commits || []).some(commit => changedFiles(commit)
.some(file => /^(swf\/|swf-src\/|client-updates\/|public\/(?:badges|music|fonts)\/)/.test(file)));
const githubUpdateCard = payload => {
const commits = Array.isArray(payload.commits) ? payload.commits.slice(-5) : [];
const isGameUpdate = gameChange(payload);
const compare = config.githubUrl ? `${config.githubUrl.replace(/\/$/, "")}/compare/${safe(payload.before, 40)}...${safe(payload.after, 40)}` : "";
const branch = String(payload.ref || "").replace(/^refs\/heads\//, "") || "default branch";
return card({
title: isGameUpdate ? "Game update" : "Server update",
tone: isGameUpdate ? 0x57f287 : 0x5865f2,
sections: [
`**${safe(config.discord.githubRepository, 100)}** · ${safe(branch, 100)}\n${commits.length} new commit${commits.length === 1 ? "" : "s"}`,
commits.length ? commits.map(commit => `\`${safe(String(commit.id || "").slice(0, 7), 7)}\` ${safe(String(commit.message || "").split("\n")[0], 180)} — ${safe(commit.author && commit.author.name, 80)}`).join("\n") : "No commit details were supplied.",
],
components: compare ? [{type: 1, components: [{type: 2, style: 5, label: "View on GitHub", url: compare}]}] : [],
});
};
// GitHub calls this public endpoint. It is intentionally signature-first:
// an untrusted request never reaches Discord or becomes a log entry.
const handleGithubWebhook = async (req, res) => {
const answer = status => { res.writeHead(status, {"Content-Length": 0}); res.end(); };
if (!githubUpdatesOn()) {
answer(404);
return;
}
if (req.method !== "POST") {
answer(405);
return;
}
let body;
try {
body = await githubBody(req);
}
catch {
answer(413);
return;
}
if (!githubSignatureMatches(body, req.headers["x-hub-signature-256"])) {
answer(401);
return;
}
if (req.headers["x-github-event"] === "ping") {
answer(204);
return;
}
if (req.headers["x-github-event"] !== "push") {
answer(204);
return;
}
let payload;
try {
payload = JSON.parse(body.toString("utf8"));
}
catch {
answer(400);
return;
}
if (payload.repository?.full_name !== config.discord.githubRepository || payload.deleted === true) {
answer(204);
return;
}
const channel = await channelFor(config.discord.updatesChannelId);
if (!channel) {
answer(503); // GitHub retries after the bot finishes reconnecting.
return;
}
const posted = await channel.send(githubUpdateCard(payload)).then(() => true).catch(err => {
console.log(`[discord-bot] GitHub update post failed: ${logText(err.message)}`);
return false;
});
answer(posted ? 204 : 503);
};
const syncCommands = async () => {
if (!client || !client.isReady()) return {error: "The Discord bot is not connected."};
const guild = await client.guilds.fetch(config.discord.guildId).catch(() => null);
if (!guild) return {error: "The configured Discord server could not be found."};
const synced = await guild.commands.set(commandDefinitions()).then(() => true).catch(err => {
console.log(`[discord-bot] command registration failed: ${logText(err.message)}`);
return false;
});
return synced ? {ok: "Discord slash commands are synchronized."} : {error: "Discord could not synchronize slash commands."};
};
const startup = () => {
loadDashboardConfig();
const security = securitySettings();
const community = communitySettings();
if (!config.discord.botToken || !config.discord.guildId) {
return false;
}
if (client) return true;
if (!loadDiscordJs()) return false;
securityGatewayOn = security.enabled;
const memberEvents = securityGatewayOn || Boolean(community.welcomeChannelId || community.goodbyeChannelId);
client = new Client({intents: securityGatewayOn
? [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers]
: memberEvents ? [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers] : [GatewayIntentBits.Guilds]});
client.once("ready", async () => {
console.log(`[discord-bot] signed in as ${logText(client.user.tag)}`);
const synced = await syncCommands();
console.log(`[discord-bot] ${synced.ok || synced.error}`);
await publishStatus();
});
client.on("interactionCreate", async interaction => {
if (interaction.user.bot) return;
if (interaction.isButton()) {
await notifyBot(interaction, `button ${interaction.customId}`).catch(() => {});
await handleButton(interaction);
return;
}
if (!interaction.isChatInputCommand() || !inConfiguredGuild(interaction)) return;
await notifyBot(interaction, `/${interaction.commandName} ${interaction.options.getSubcommand(false) || ""}`.trim()).catch(() => {});
await interaction.deferReply({flags: EPHEMERAL}).catch(() => {});
if (!interaction.deferred) return;
try {
if (interaction.commandName === "burrow") await handleBurrow(interaction);
else if (interaction.commandName === "moderate") await handleModerate(interaction);
else if (interaction.commandName === "discord") await handleDiscordModeration(interaction);
else if (interaction.commandName === "ticket") await handleTicket(interaction);
}
catch (err) {
console.error(`[discord-bot] interaction failed: ${err.stack || err.message}`);
await interaction.editReply(failure("The command could not be completed.")).catch(() => {});
}
});
client.on("error", err => console.error(`[discord-bot] client error: ${err.message}`));
if (securityGatewayOn) {
client.on("messageCreate", message => { inspectDiscordMessage(message).catch(err => console.error(`[discord-bot] AutoMod failed: ${err.message}`)); });
client.on("guildMemberAdd", member => { inspectDiscordJoin(member).catch(err => console.error(`[discord-bot] anti-raid check failed: ${err.message}`)); });
}
if (memberEvents) {
client.on("guildMemberAdd", member => { communityNotice(member, "welcome").catch(err => console.error(`[discord-bot] welcome notice failed: ${err.message}`)); });
client.on("guildMemberRemove", member => { communityNotice(member, "goodbye").catch(err => console.error(`[discord-bot] goodbye notice failed: ${err.message}`)); });
}
unsubscribeReports = reports.onFile(notifyReport);
unsubscribeGameActivity = world.onGameActivity(notifyGameActivity);
unsubscribeModeration = modlog.onRecord(notifyModeration);
statusTimer = setInterval(() => { publishStatus().catch(err => console.error(`[discord-bot] status failed: ${err.message}`)); }, STATUS_EVERY_MS);
statusTimer.unref();
client.login(config.discord.botToken).catch(err => console.error(`[discord-bot] login failed: ${err.message}`));
return true;
};
const shutdown = () => {
if (statusTimer) clearInterval(statusTimer);
statusTimer = null;
if (unsubscribeReports) unsubscribeReports();
unsubscribeReports = null;
if (unsubscribeGameActivity) unsubscribeGameActivity();
unsubscribeGameActivity = null;
if (unsubscribeModeration) unsubscribeModeration();
unsubscribeModeration = null;
if (client) client.destroy();
client = null;
securityGatewayOn = false;
recentMessages.clear();
recentJoins.length = 0;
};
const control = async action => {
if (action === "stop") {
if (!client) return {error: "The Discord bot is already stopped."};
shutdown();
return {ok: "Discord bot stopped. Game and panel services remain online."};
}
if (action === "start") {
return startup() ? {ok: "Discord bot is starting."} : {error: "Set AJ_DISCORD_BOT_TOKEN and AJ_DISCORD_GUILD_ID, and install discord.js (npm ci), before starting the bot."};
}
if (action === "reconnect") {
shutdown();
return startup() ? {ok: "Discord bot is reconnecting."} : {error: "Set AJ_DISCORD_BOT_TOKEN and AJ_DISCORD_GUILD_ID, and install discord.js (npm ci), before reconnecting the bot."};
}
if (action === "sync") return syncCommands();
return {error: "Unknown Discord bot control."};
};
module.exports = {startup, shutdown, control, card, COMPONENTS_V2, dashboardStatus, updateDashboardConfig, updateSecuritySettings, updateCommunitySettings, setStatusSettings, publishStatus, handleGithubWebhook};
+1 -1
View File
@@ -1,4 +1,4 @@
{ {
"cards": [1,2,3,4,5,7,8,86,118,119,124,128,152,154,155,201,283,284,329,346,355,356,361,380,382,384,385,387,388,389,390,391,1188,1206,1211,1222,1228,1242,1249,1250,1251,1354,1426,1520,1627,1768,1933,2235,2649,2697,2700,2702,2703,2704,2705,2706,2707,2708,2709,2711,2712,2713,2714,2715,2716,2717,2720,2723,2762,2763,2805,2806,2807,2808,2809,2810,2811,2812,2813,2814,2815,2816,2817,2818,2819,2820,2821,2822,2823,2824,2825,2826,2827,2828,3749,4393,4410,4411,4434,4435,4451,4452,4453,4454,4455,4457,4460,4461,4462,4464,4465,4466,4467,4468,4469,4470,4477,4478,4479,4538,4539,4540,4541,4542,4543,4544,4545,4546,4547,4548,4549,4777,4778,4779,4780,4855,4856,4946,5023,5024,5026,5066,5067,5068,5069,5070,5071,5073,5074,5075,5076,5077,5078,5079,5080,5081,5082,5083,5084,5085,5086,5087,5088,5089,5090,5091,5092,5093,5094,5095,5099,5100,5738,5980,5981,6130,6138,9013,9014,9015,9016,9017,9167,9170,9172,9174,9175,9326,9327,9328,9329,9330,9331,9332], "cards": [1,2,3,4,5,7,8,86,118,119,124,128,152,154,155,201,283,284,329,346,355,356,361,380,382,384,385,387,388,389,390,391,1188,1206,1211,1222,1228,1242,1249,1250,1251,1354,1426,1520,1627,1768,1933,2235,2649,2697,2700,2702,2703,2704,2705,2706,2707,2708,2709,2711,2712,2713,2714,2715,2716,2717,2720,2723,2762,2763,2805,2806,2807,2808,2809,2810,2811,2812,2813,2814,2815,2816,2817,2818,2819,2820,2821,2822,2823,2824,2825,2826,2827,2828,3749,4393,4410,4411,4434,4435,4451,4452,4453,4454,4455,4457,4460,4461,4462,4464,4465,4466,4467,4468,4469,4470,4477,4478,4479,4538,4539,4540,4541,4542,4543,4544,4545,4546,4547,4548,4549,4777,4778,4779,4780,4855,4856,4946,5023,5024,5026,5066,5067,5068,5069,5070,5071,5073,5074,5075,5076,5077,5078,5079,5080,5081,5082,5083,5084,5085,5086,5087,5088,5089,5090,5091,5092,5093,5094,5095,5099,5100,5738,5980,5981,6130,6138,9013,9014,9015,9016,9017,9167,9170,9172,9174,9175,9326,9327,9328,9329,9330,9331,9332],
"stamps": [10,11,12,13,15,16,17,18,19,20,21,22,23] "stamps": [13,11,2889,2896,1602,2886,1604,12,2877,2885,1603,2894,10,2899,2891,2876,376,2878,2879,2880,2881,2882,2884,2888,2898,2887,2890,377,2892,2893,2895,2900,378,2901,2902]
} }
+51 -13
View File
@@ -17,9 +17,12 @@ const {CURRENCIES, hasRoom, addClothing, sendClothingAdded, sendClothingRemoved}
// ECardXtCommManager): a card, a stamp, a short message and perhaps a gift, // ECardXtCommManager): a card, a stamp, a short message and perhaps a gift,
// kept in the receiver's inbox (account.ecards) until they delete it. // kept in the receiver's inbox (account.ecards) until they delete it.
// //
// which cards and stamps exist was a list on the official servers. the ones // which cards and stamps exist was a list on the official servers. the cards
// offered here were found by looking through the CDN's media files for card // offered here were found by looking through the CDN's media files for card
// artwork (tools/find-art.py found what is in lib/ecard-art.json). // artwork (tools/find-art.py found what is in lib/ecard-art.json); the
// stamps are the official list itself, as a recording of the official game
// has it (lib/official-lists.json, list 44): the ones guessed before were
// partly not stamps at all, and showed nothing.
// ECard.type: what, if anything, comes with the card // ECard.type: what, if anything, comes with the card
const TYPE_PLAIN = 0; const TYPE_PLAIN = 0;
@@ -51,10 +54,15 @@ const INBOX_FULL = -1;
const NOT_ACCEPTING = -2; const NOT_ACCEPTING = -2;
const FAILED = 0; const FAILED = 0;
// who may send to a player (ECardInbox's settings popup). // who may send to a player, as kept (account.ecardPrivacy).
const FROM_EVERYONE = 0; const FROM_EVERYONE = 0;
const FROM_BUDDIES = 1; const FROM_BUDDIES = 1;
const FROM_NOBODY = 2; const FROM_NOBODY = 2;
// ECardInbox's settings popup sends the place of the option picked, and its
// artwork has Nobody first and Everyone last: the other way round from the
// above. turned over both ways between the two (buddies is in the middle).
const SETTING_COUNT = 3;
const turnedOver = value => SETTING_COUNT - 1 - value;
const LIST_CARDS = 10; const LIST_CARDS = 10;
const LIST_STAMPS = 44; const LIST_STAMPS = 44;
@@ -69,8 +77,23 @@ const now = () => Math.floor(Date.now() / 1000);
const clean = text => String(text).replace(/[\u0000-\u001f\u007f%]/g, " ").trim().slice(0, MAX_MESSAGE); const clean = text => String(text).replace(/[\u0000-\u001f\u007f%]/g, " ").trim().slice(0, MAX_MESSAGE);
module.exports = ({findOnline, blocks}) => { module.exports = ({findOnline, blocks}) => {
// a gift the game can show and take: its item still exists (a custom item
// may have been deleted since), or an amount that makes sense. any other
// left the gift windows stuck; it is treated as no gift at all.
const MAX_GIFT_AMOUNT = 10000000;
const giftUsable = gift => {
if (gift.type === TYPE_CLOTHING) {
return Boolean(defpacks.itemDef(gift.def)) && Number.isFinite(Number(gift.color));
}
if (gift.type === TYPE_DEN_ITEM) {
return Boolean(defpacks.denItemDef(gift.def));
}
const amount = Number(gift.def);
return Object.hasOwn(CURRENCY_OF, gift.type) && Number.isInteger(amount) && amount > 0 && amount <= MAX_GIFT_AMOUNT;
};
// A card from the server carrying gems or diamonds: one of the popups. // A card from the server carrying gems or diamonds: one of the popups.
const isRedemption = card => Boolean(card.hq && card.gift && Object.hasOwn(CURRENCY_OF, card.gift.type)); const isRedemption = card => Boolean(card.hq && card.gift && giftUsable(card.gift) && Object.hasOwn(CURRENCY_OF, card.gift.type));
// who sent a card: by account id, and for cards from before ids were // who sent a card: by account id, and for cards from before ids were
// kept by the name on them. // kept by the name on them.
@@ -90,9 +113,10 @@ module.exports = ({findOnline, blocks}) => {
const sender = card.hq ? null : senderOf(card); const sender = card.hq ? null : senderOf(card);
const senderType = isRedemption(card) ? FROM_REDEMPTION : card.hq ? FROM_HQ : FROM_PLAYER; const senderType = isRedemption(card) ? FROM_REDEMPTION : card.hq ? FROM_HQ : FROM_PLAYER;
const name = card.secret ? "" : senderType === FROM_HQ ? HQ_NAME_STRING : card.hq ? HQ_NAME : card.from; const name = card.secret ? "" : senderType === FROM_HQ ? HQ_NAME_STRING : card.hq ? HQ_NAME : card.from;
const gift = card.gift && giftUsable(card.gift) ? card.gift : null;
return [ return [
card.id, name, card.card, card.stamp, card.read ? 1 : 0, card.msg, card.gift ? card.gift.type : TYPE_PLAIN, card.id, name, card.card, card.stamp, card.read ? 1 : 0, card.msg, gift ? gift.type : TYPE_PLAIN,
card.gift ? giftId(card.gift) : 0, card.gift ? card.gift.color : 0, card.gift ? card.gift.name : 0, gift ? giftId(gift) : 0, gift ? gift.color : 0, gift ? gift.name : 0,
card.hq || card.secret ? MEMBER : sender ? sender.accountType : 0, card.hq || card.secret ? MEMBER : sender ? sender.accountType : 0,
0, // name bar data 0, // name bar data
0, // secondary type 0, // secondary type
@@ -102,7 +126,7 @@ module.exports = ({findOnline, blocks}) => {
// patched client (ECardInbox) can show a custom item as itself (its // patched client (ECardInbox) can show a custom item as itself (its
// own picture and name) and not as the art it was made from. (the // own picture and name) and not as the art it was made from. (the
// "|" keeps the game from taking it for an HQ gift's own message.) // "|" keeps the game from taking it for an HQ gift's own message.)
card.gift && card.gift.type === TYPE_CLOTHING ? `item|${card.gift.def}` : "", gift && gift.type === TYPE_CLOTHING ? `item|${gift.def}` : "",
card.secret ? SECRET_VALENTINE : 0, card.secret ? SECRET_VALENTINE : 0,
]; ];
}; };
@@ -155,7 +179,11 @@ module.exports = ({findOnline, blocks}) => {
} }
else { else {
// for these the card's "gift id" and "gift name" are both the amount. // for these the card's "gift id" and "gift name" are both the amount.
attached = {type: gift.kind === "gems" ? TYPE_GEMS : TYPE_DIAMONDS, def: gift.amount, color: 0, name: gift.amount}; const amount = Number(gift.amount);
if (!Number.isInteger(amount) || amount < 1 || amount > MAX_GIFT_AMOUNT) {
return "An amount from 1 to 10,000,000";
}
attached = {type: gift.kind === "gems" ? TYPE_GEMS : TYPE_DIAMONDS, def: amount, color: 0, name: amount};
} }
// the gift popup takes a message that starts with a number for the id of // the gift popup takes a message that starts with a number for the id of
// a localization string (StartupPopups.setupGiftPopup). // a localization string (StartupPopups.setupGiftPopup).
@@ -218,8 +246,8 @@ module.exports = ({findOnline, blocks}) => {
} }
else if (Object.hasOwn(CURRENCY_OF, gift.type)) { else if (Object.hasOwn(CURRENCY_OF, gift.type)) {
const currency = CURRENCIES[CURRENCY_OF[gift.type]]; const currency = CURRENCIES[CURRENCY_OF[gift.type]];
account.currency[currency] = (account.currency[currency] || 0) + gift.def; account.currency[currency] = (account.currency[currency] || 0) + Number(gift.def);
achievements.currencyChanged(account, currency, gift.def); achievements.currencyChanged(account, currency, Number(gift.def));
// ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason] // ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason]
session.sendXt("cu", -1, CURRENCY_OF[gift.type], account.currency[currency], 0); session.sendXt("cu", -1, CURRENCY_OF[gift.type], account.currency[currency], 0);
} }
@@ -251,7 +279,8 @@ module.exports = ({findOnline, blocks}) => {
// silenced: no words of their own reach anyone, in a card either. // silenced: no words of their own reach anyone, in a card either.
if (!to || to === account || !art.cards.includes(Number(card)) || !art.stamps.includes(Number(stamp)) if (!to || to === account || !art.cards.includes(Number(card)) || !art.stamps.includes(Number(stamp))
|| !accounts.featureOn(account, "jamagrams") || (isSilenced(account) && clean(message || "") !== "") || !accounts.featureOn(account, "jamagrams") || (isSilenced(account) && clean(message || "") !== "")
|| !sendsPerTenMinutes.allow(account.id)) { // The client also skips its per-recipient cap for moderators.
|| (!account.isModerator && !sendsPerTenMinutes.allow(account.id))) {
reply(FAILED); reply(FAILED);
return; return;
} }
@@ -324,6 +353,13 @@ module.exports = ({findOnline, blocks}) => {
return; return;
} }
const {gift} = card; const {gift} = card;
// a gift that cannot be had (above): gone, and the window let go
if (!giftUsable(gift)) {
card.gift = null;
accounts.save(session.account);
session.sendXt("eg", -1, msgId, 1);
return;
}
// no room for it: it stays in the card until there is. // no room for it: it stays in the card until there is.
if (accept === "1" && ((gift.type === TYPE_CLOTHING && !hasRoom(session.account, "items")) if (accept === "1" && ((gift.type === TYPE_CLOTHING && !hasRoom(session.account, "items"))
|| (gift.type === TYPE_DEN_ITEM && !hasRoom(session.account, "denItems")))) { || (gift.type === TYPE_DEN_ITEM && !hasRoom(session.account, "denItems")))) {
@@ -344,7 +380,7 @@ module.exports = ({findOnline, blocks}) => {
// [setting] -> eCardIsolationHandler: [success] // [setting] -> eCardIsolationHandler: [success]
ei(session, roomId, [setting]) { ei(session, roomId, [setting]) {
const value = Number(setting); const value = turnedOver(Number(setting));
const valid = [FROM_EVERYONE, FROM_BUDDIES, FROM_NOBODY].includes(value); const valid = [FROM_EVERYONE, FROM_BUDDIES, FROM_NOBODY].includes(value);
if (valid) { if (valid) {
session.account.ecardPrivacy = value; session.account.ecardPrivacy = value;
@@ -373,5 +409,7 @@ module.exports = ({findOnline, blocks}) => {
return card ? senderOf(card) : null; return card ? senderOf(card) : null;
}; };
return {handlers, list, unread, redemptions, sendFromHq, noteFromHq, secretSender, SECRET_NAME: "Secret Valentine"}; // the setting as the inbox's settings popup shows it (above)
const privacyShown = account => turnedOver(account.ecardPrivacy || FROM_EVERYONE);
return {handlers, list, unread, redemptions, privacyShown, sendFromHq, noteFromHq, secretSender, SECRET_NAME: "Secret Valentine"};
}; };
+227
View File
@@ -0,0 +1,227 @@
"use strict";
const accounts = require("./accounts.js");
const achievements = require("./achievements.js");
const config = require("../config.js");
const defpacks = require("./defpacks.js");
// the eco den items: producers (special type 6, the Eco Solar Panel and
// Eco Wind Turbine) and consumers (7, the eco lamps and fan), sold for eco
// credits in the Eco Shop (list 778). client side: gui.EcoScorePopup (a
// producer clicked), gui.EcoPointsPopup (a consumer clicked),
// DenItemHolder.updateConsumers. the official server's rules were never
// recorded; these are this server's:
//
// - a den's generation is the eco power of the producers placed in its
// owner's den in use; consumers switched on take theirs from it, in
// inventory order, and one that no longer fits is "offline" (state 2)
// until there is power for it again. its switch stays on.
// - generation turns into credits, config.ecoCreditsPerPointHour a point
// an hour, waiting to be collected ("Get Your Credits") up to the
// meter's full 240. an account's first look (an eco window, or the
// Eco Shop) gets it config.ecoStartCredits, enough for its first producer.
// - the eco score (generation less use) earns the three eco plaques, one
// at a time, through user var 465 (a bit each).
const SPECIAL_PRODUCER = "6";
const SPECIAL_CONSUMER = "7";
const WIND_TURBINE = 4541;
const SOLAR_PANEL = 4540;
const CURRENCY_ECO = 11;
const ECO_SHOP_LIST = 778;
const MAX_WAITING = 240; // EcoScorePopup.updateCreditProgressMeter: the meter is full at 240
const USER_VAR_REWARDS = 465;
const REWARDS = [
{bit: 0, score: 5, def: 4611}, // Wood Eco Plaque
{bit: 1, score: 15, def: 4610}, // Silver Eco Plaque
{bit: 2, score: 30, def: 4609}, // Gold Eco Plaque
];
const HOUR_MS = 3600000;
const OFF = 0;
const ON = 1;
const OFFLINE = 2;
const special = item => {
const def = defpacks.denItemDef(item.def);
return def ? String(def.specialType) : "";
};
const power = item => Number((defpacks.denItemDef(item.def) || {}).ecoPower) || 0;
const placedInUse = account => account.denItems.filter(item => item.spots && item.spots[account.activeDen]);
// the den in use as the eco windows see it: {generation, consumption,
// turbines, panels, consumers: [item], states: Map(inv -> 0 off, 1 on, 2 offline)}
const stateOf = account => {
const placed = placedInUse(account);
const producers = placed.filter(item => special(item) === SPECIAL_PRODUCER);
const consumers = placed.filter(item => special(item) === SPECIAL_CONSUMER).sort((one, other) => one.inv - other.inv);
const generation = producers.reduce((sum, item) => sum + power(item), 0);
let consumption = 0;
const states = new Map();
for (const item of consumers) {
if (!item.ecoOn) {
states.set(item.inv, OFF);
}
else if (consumption + power(item) <= generation) {
consumption += power(item);
states.set(item.inv, ON);
}
else {
states.set(item.inv, OFFLINE);
}
}
return {
generation,
consumption,
turbines: producers.filter(item => item.def === WIND_TURBINE).length,
panels: producers.filter(item => item.def === SOLAR_PANEL).length,
consumers,
states,
};
};
// a den item's eco field in the den's state (DenStateItem's last): 0 for
// all but consumers
const consumerState = (account, item) => (special(item) === SPECIAL_CONSUMER ? stateOf(account).states.get(item.inv) || OFF : OFF);
const perHour = generation => generation * (Number(config.ecoCreditsPerPointHour) || 0);
// brings the waiting credits up to now, at the rate the den has now. the
// caller saves.
const accrue = account => {
const now = Date.now();
if (!account.eco) {
account.eco = {waiting: 0, at: now};
const start = Math.max(0, Math.floor(Number(config.ecoStartCredits) || 0));
account.currency.ecoCredits = (account.currency.ecoCredits || 0) + start;
return;
}
const rate = perHour(stateOf(account).generation);
const hours = Math.max(0, now - account.eco.at) / HOUR_MS;
account.eco.waiting = Math.min(MAX_WAITING, (Number(account.eco.waiting) || 0) + rate * hours);
account.eco.at = now;
};
// seconds until one more whole credit waits, 0 when none will
const secondsToNext = account => {
const rate = perHour(stateOf(account).generation);
if (rate <= 0 || account.eco.waiting >= MAX_WAITING) {
return 0;
}
const short = 1 - (account.eco.waiting % 1);
return Math.max(1, Math.ceil(short / rate * 3600));
};
const nextReward = account => {
const bits = Number(account.userVars[USER_VAR_REWARDS]) || 0;
return REWARDS.find(reward => !(bits & (1 << reward.bit))) || null;
};
module.exports = ({others, ecards}) => {
const sendCredits = session => session.sendXt("cu", -1, CURRENCY_ECO, session.account.currency.ecoCredits || 0, 0);
// the consumers' states to the owner and, when they are in it, everyone
// else in the den: DenXtCommManager.denEcoConsumerResponse [consumption,
// generation, count, (invIdx, state)...].
const sendConsumers = session => {
const {account} = session;
const state = stateOf(account);
const fields = [state.consumption, state.generation, state.consumers.length,
...state.consumers.flatMap(item => [item.inv, state.states.get(item.inv)])];
session.sendXt("dEc", -1, ...fields);
if (session.room && session.room.denOwner === account) {
for (const other of others(session)) {
other.sendXt("dEc", -1, ...fields);
}
}
};
const handlers = {
// requestDenEcoCreditRefresh -> EcoStateResponse: [turbines, panels,
// consumers, generation, consumption, score required, next reward bit,
// credits waiting, seconds to the next].
dEf(session) {
const {account} = session;
const firstLook = !account.eco;
accrue(account);
accounts.save(account);
if (firstLook) {
sendCredits(session);
}
const state = stateOf(account);
const reward = nextReward(account);
session.sendXt("dEf", -1, state.turbines, state.panels, state.consumers.length, state.generation, state.consumption,
reward ? reward.score : REWARDS[REWARDS.length - 1].score, reward ? reward.bit : -1,
Math.floor(account.eco.waiting), secondsToNext(account));
},
// requestDenEcoCreditRedeem: the waiting credits collected -> [success,
// seconds to the next].
dEr(session) {
const {account} = session;
accrue(account);
const credits = Math.floor(account.eco.waiting);
if (credits < 1) {
accounts.save(account);
session.sendXt("dEr", -1, 0, secondsToNext(account));
return;
}
account.eco.waiting -= credits;
account.currency.ecoCredits = (account.currency.ecoCredits || 0) + credits;
achievements.currencyChanged(account, "ecoCredits", credits);
accounts.save(account);
sendCredits(session);
session.sendXt("dEr", -1, 1, secondsToNext(account));
},
// requestDenEcoConsumer: [invIdx, "1" on | "0" off]
dEc(session, roomId, [invIdx, on]) {
const {account} = session;
const item = account.denItems.find(candidate => candidate.inv === Number(invIdx));
if (item && special(item) === SPECIAL_CONSUMER) {
accrue(account);
item.ecoOn = on === "1";
accounts.save(account);
}
sendConsumers(session);
},
};
// user var 465, set by the eco score window's gift: the value is the bit
// of the reward asked for. given when it is the next one and the score is
// there; the plaque comes as a gift from HQ. true when the var was this.
const userVar = (session, id, bit) => {
if (Number(id) !== USER_VAR_REWARDS) {
return false;
}
const {account} = session;
const reward = nextReward(account);
const state = stateOf(account);
if (reward && reward.bit === Number(bit) && state.generation - state.consumption >= reward.score
&& !ecards.sendFromHq(account, "Eco Reward", {kind: "den", id: reward.def})) {
account.userVars[USER_VAR_REWARDS] = (Number(account.userVars[USER_VAR_REWARDS]) || 0) | (1 << reward.bit);
accounts.save(account);
}
if (account.userVars[USER_VAR_REWARDS] === undefined) {
account.userVars[USER_VAR_REWARDS] = 0;
}
achievements.sendVar(session, USER_VAR_REWARDS);
return true;
};
// the Eco Shop opened: an account that never had eco credits is given
// its first, to buy its first producer with.
const shopOpened = session => {
if (!session.account.eco) {
accrue(session.account);
accounts.save(session.account);
sendCredits(session);
}
};
return {handlers, userVar, shopOpened, SHOP_LIST: ECO_SHOP_LIST};
};
module.exports.accrue = accrue;
module.exports.consumerState = consumerState;
module.exports.SPECIAL_TYPES = [SPECIAL_PRODUCER, SPECIAL_CONSUMER];
+53 -2
View File
@@ -1,5 +1,7 @@
"use strict"; "use strict";
const fs = require("fs");
const path = require("path");
const zlib = require("zlib"); const zlib = require("zlib");
const amf3 = require("./amf3.js"); const amf3 = require("./amf3.js");
const cdn = require("./cdn.js"); const cdn = require("./cdn.js");
@@ -13,15 +15,57 @@ const cdn = require("./cdn.js");
// (DenItemHolder), and the CDN has no such files for these. each one's // (DenItemHolder), and the CDN has no such files for these. each one's
// sound sits inside a media file or a room file as an MP3 (a DefineSound // sound sits inside a media file or a room file as an MP3 (a DefineSound
// tag of a zlib-compressed SWF), so the file is cut out of there when a // tag of a zlib-compressed SWF), so the file is cut out of there when a
// client first asks for it. nothing of it is kept in this repository. // client first asks for it. nothing of it is kept in this repository,
// except the tracks that are files of their own (`mp3`, in public/music/).
const FIRST_ID = 6001; // the official den items end at 5925 const FIRST_ID = 6001; // the official den items end at 5925
const STRING_BASE = 9000100; const STRING_BASE = 9000100;
const VOLUME = "40"; // the def's `flag`, as the official tracks have it const VOLUME = "40"; // the def's `flag`, as the official tracks have it
const TEMPLATE = 614; // "Jam On": each new row starts as a copy of this track's const TEMPLATE = 614; // "Jam On": each new row starts as a copy of this track's
// music files from the game's development CDN that no den item plays,
// kept in public/music/ and titled with their file names. tracks that
// already are den items there under another name (the same audio, or the
// same track by its name and length) were left out.
const DEV_MUSIC = [
"aj_BD_newTheme.mp3", "AJ_cinema_lobby.mp3", "AJ_CS_mus_over_flow.mp3", "aj_dr_musIntro.mp3", "aj_dr_musOutro.mp3",
"aj_eat_em_up.mp3", "aj_fallingPhantoms.mp3", "aj_mus_BD_FullSpectrum.mp3", "aj_mus_BD_muffled.mp3",
"aj_mus_BD_OceanFullSpectrum.mp3", "aj_mus_Best_Dressed1.mp3", "aj_mus_bestDressedOcean1.mp3",
"aj_mus_bestDressedOceanMuffled.mp3", "aj_mus_carnival.mp3", "aj_mus_club.mp3", "AJ_mus_den_sitar.mp3",
"aj_mus_dolphin.mp3", "AJ_mus_double_up.mp3", "aj_mus_flag_room.mp3", "AJ_mus_gem_ball.mp3",
"aj_mus_gem_breaker.mp3", "aj_mus_hassel_hoff.mp3", "aj_mus_hedgehog.mp3", "aj_mus_horseRaceLP.mp3",
"AJ_mus_jamaa_township.mp3", "aj_mus_oceans_shop.mp3", "AJ_Mus_Phantom_Fighter.mp3", "aj_mus_phantoms_treasure.mp3",
"aj_mus_pillBug.mp3", "aj_mus_rare_item_shop.mp3", "aj_mus_shiveer_tent.mp3", "aj_mus_sorting_game.mp3",
"AJ_Mus_spider_shooter.mp3", "aj_mus_Thierrys_aquarium.mp3", "aj_mus_touchPool.mp3", "AJ_mus_twister.mp3",
"aj_mus_wolfParty.mp3", "aj_musBackToSchoolParty.mp3", "aj_musBestGuess.mp3", "aj_musChineseNewYear.mp3",
"aj_musEagleLP.mp3", "aj_musHospital.mp3", "aj_musNewJammaIntro.mp3", "aj_musNPEintro.mp3", "aj_musOutback.mp3",
"aj_musOutbackShop.mp3", "aj_musPhntmKingIntro.mp3", "aj_musSpotOn.mp3", "aj_musStingerRaceIntro.mp3",
"aj_musStingerRaceOver.mp3", "aj_musTelescopeRoom.mp3", "aj_musVolcanoGreely.mp3", "AJ_Native_American.mp3",
"aj_petshop_mus.mp3", "AJ_reggaeton.mp3", "AJ_Shopping_music.mp3", "ajm_musBossBattle25.mp3", "ajm_musCloud.mp3",
"ajm_musFFFruitShack.mp3", "ajm_musFFSplash.mp3", "ajm_musFFTheater.mp3", "ajm_tugOfWar.mp3", "ajmusMasterp.mp3",
"ajq_forbodingTheme.mp3", "ajq_MiraThemeFinal.mp3", "ajq_mus2PhntmKings.mp3", "ajq_musAdvent20Hub.mp3",
"ajq_musBattleoftheForrest.mp3", "ajq_musbunnyBurrow.mp3", "ajq_musCave.mp3", "ajq_musCaveBossBattle.mp3",
"ajq_musCaveSlides.mp3", "ajq_musCharge.mp3", "ajq_musCombat.mp3", "ajq_musCraftingVillage.mp3",
"ajq_musDungeon.mp3", "ajq_musEerieGreelyCave.mp3", "ajq_musFactoryBossLp.mp3", "ajq_musFroggyMarsh.mp3",
"ajq_musGraveyard.mp3", "ajq_musHauntedForest.mp3", "ajq_musInToDeep.mp3", "ajq_musIntotheCaves.mp3",
"ajq_musMadGreely.mp3", "ajq_musMiraTomb.mp3", "ajq_musOceanQuest9.mp3", "ajq_musOuterLimits.mp3",
"ajq_musPeckSafe.mp3", "ajq_musPecksSecret.mp3", "ajq_musPhntmCreepy.mp3", "ajq_musPhntmDiguise.mp3",
"ajq_musPhntmInvasion.mp3", "ajq_musPhntmKingIntro.mp3", "ajq_musPhntmRetreat.mp3", "ajq_musPumpkinPatch.mp3",
"ajq_musQ22FinalRoom.mp3", "ajq_musQuest.mp3", "ajq_musQuest19Cave.mp3", "ajq_musQuest22.mp3",
"ajq_musQuest22B.mp3", "ajq_MusQuest23.mp3", "ajq_MusQuest23Intro.mp3", "ajq_musQuestStealth.mp3",
"ajq_musRoofTop.mp3", "ajq_musSafeLP.mp3", "ajq_musScienceLab.mp3", "ajq_musSearch4GreelyLP.mp3",
"ajq_musSirGilbertsCastle.mp3", "ajq_musSpooky.mp3", "ajq_musSpotted.mp3", "ajq_musSuspicious.mp3",
"ajq_musTrainingForrest.mp3", "ajq_musTreeHutPlayful.mp3", "ajq_musTugOfWarIdleLP.mp3", "ajq_musTurningTheTide.mp3",
"ajq_musTutorial.mp3", "ajq_musVolcanoFreeze.mp3", "ajq_musVolIn.mp3", "ajq_musVolOut.mp3", "ajq_musWinterFun.mp3",
"ajw_musWildExplorers.mp3", "ajw_musWildExplorersTent.mp3", "astronomy_mus_think.mp3", "fs_mus_intro.mp3",
"Mus_AP_Interface.mp3", "Mus_Art_Studio_theme.mp3", "MusAppondaleMuseum.mp3", "MusBirdsOfParadise.mp3",
"MusDenDef.mp3", "TD_mus_120bpm_lp.mp3", "TD_mus_80bpm_lp.mp3", "TD_mus_80bpm_nw.mp3", "TD_mus_80bpm_we.mp3",
];
// {file, title, sound: the sound's exported name ("" for the only, unnamed // {file, title, sound: the sound's exported name ("" for the only, unnamed
// one), and where it is: a media id, or a room file and the asset in it} // one), and where it is: a media id, or a room file and the asset in it, or
// an MP3 of this server's own in public/music/ (`mp3`)}. new tracks go at the
// end: a track's item id is its place in the list.
const TRACKS = [ const TRACKS = [
{file: "XtraNarration", title: "Narration", media: 1904, sound: "Narration"}, {file: "XtraNarration", title: "Narration", media: 1904, sound: "Narration"},
{file: "XtraUnnamed", title: "Unnamed Sound", media: 46, sound: ""}, {file: "XtraUnnamed", title: "Unnamed Sound", media: 46, sound: ""},
@@ -32,6 +76,8 @@ const TRACKS = [
{file: "XtraVolcano", title: "Volcano", media: 2507, sound: "aj_musVolcanoFull"}, {file: "XtraVolcano", title: "Volcano", media: 2507, sound: "aj_musVolcanoFull"},
...[1, 2, 3, 4].map(layer => ({file: `XtraConcert${layer}`, title: `Concert Layer ${layer}`, ...[1, 2, 3, 4].map(layer => ({file: `XtraConcert${layer}`, title: `Concert Layer ${layer}`,
room: "party/venue_concert", asset: "Concert\\Concert_Party_Front_Lights.swf", sound: `layer${layer}`})), room: "party/venue_concert", asset: "Concert\\Concert_Party_Front_Lights.swf", sound: `layer${layer}`})),
{file: "XtraDebugMusic", title: "AJ_Debug_Music.mp3", mp3: "AJ_Debug_Music.mp3"},
...DEV_MUSIC.map(mp3 => ({file: `Xtra_${mp3.slice(0, -4)}`, title: mp3, mp3})),
].map((track, index) => ({...track, id: FIRST_ID + index, stringId: STRING_BASE + index})); ].map((track, index) => ({...track, id: FIRST_ID + index, stringId: STRING_BASE + index}));
const ids = TRACKS.map(track => track.id); const ids = TRACKS.map(track => track.id);
@@ -87,7 +133,12 @@ const soundIn = (swf, name) => {
return null; return null;
}; };
const MUSIC_DIR = path.join(__dirname, "..", "public", "music");
const extract = async track => { const extract = async track => {
if (track.mp3) {
return fs.promises.readFile(path.join(MUSIC_DIR, track.mp3));
}
if (track.media) { if (track.media) {
const swf = await cdn.get(cdn.hashedPath(`media/${track.media}`)); const swf = await cdn.get(cdn.hashedPath(`media/${track.media}`));
return swf ? soundIn(swf, track.sound) : null; return swf ? soundIn(swf, track.sound) : null;
+101 -70
View File
@@ -1,84 +1,118 @@
[ [
{"id": 4, "swf": "Pachinko", "title": "Gem Ball", "type": 1, "vars": [16, 17, 0], "icon": 4295}, {"id": 1, "swf": "PVP_TicTacToe", "title": "Tic Tac Toe", "type": 0, "vars": [63,0,0], "icon": 5063, "card": 5055, "buddy": true},
{"id": 5, "swf": "MiniGame_Memory", "title": "Double Up", "type": 1, "vars": [6, 7, 83], "icon": 4291}, {"id": 4, "swf": "Pachinko", "title": "Gem Ball", "type": 1, "vars": [16,17,0], "icon": 4295, "card": 58},
{"id": 6, "swf": "MoatMadness", "title": "Overflow", "type": 1, "vars": [8, 9, 80], "icon": 4300}, {"id": 5, "swf": "MiniGame_Memory", "title": "Double Up", "type": 1, "vars": [6,7,0], "icon": 4291, "card": 61},
{"id": 10, "swf": "ParachuteGlider", "title": "Wind Rider", "type": 1, "vars": [12, 13, 79], "start": "seed", "icon": 4311}, {"id": 6, "swf": "MoatMadness", "title": "Overflow", "type": 1, "vars": [8,9,9], "icon": 4300, "card": 59},
{"id": 11, "swf": "Trivia", "title": "Temple of Trivia", "type": 1, "vars": [10, 11, 0], "ready": false, "icon": 4309}, {"id": 10, "swf": "ParachuteGlider", "title": "Wind Rider", "type": 1, "vars": [12,13,0], "start": "seedAndCrosshairs", "icon": 4311, "card": 65},
{"id": 12, "swf": "RiverRace", "title": "River Race", "type": 1, "vars": [22, 23, 0], "start": "seed"}, {"id": 11, "swf": "Trivia", "title": "Temple of Trivia", "type": 1, "vars": [10,11,0], "icon": 4309, "card": 64, "ready": false},
{"id": 13, "swf": "PhantomFighter", "title": "Phantom Fighter", "type": 1, "vars": [14, 15, 84], "icon": 4312}, {"id": 12, "swf": "RiverRace", "title": "River Race", "type": 1, "vars": [22,23,0], "start": "seed", "card": 62},
{"id": 14, "swf": "SpiderShooter", "title": "Spider Zapper", "type": 1, "vars": [18, 19, 82], "start": "seed", "icon": 4305}, {"id": 13, "swf": "PhantomFighter", "title": "Phantom Fighter", "type": 1, "vars": [14,15,0], "icon": 4312, "card": 60},
{"id": 14, "swf": "SpiderShooter", "title": "Spider Zapper", "type": 1, "vars": [18,19,0], "start": "seedAndCrosshairs", "icon": 4305, "card": 63},
{"id": 15, "swf": "MicroPopcorn", "title": "Popcorn Machine", "type": 0}, {"id": 15, "swf": "MicroPopcorn", "title": "Popcorn Machine", "type": 0},
{"id": 16, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 16, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 17, "swf": "MicroSmoothie", "title": "Smoothie Machine", "type": 0}, {"id": 17, "swf": "MicroSmoothie", "title": "Smoothie Machine", "type": 0},
{"id": 19, "swf": "WindRider", "title": "Sky High", "type": 1, "vars": [26, 27, 0], "icon": 4304}, {"id": 18, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 20, "swf": "Twister", "title": "Twister", "type": 1, "vars": [24, 25, 81], "icon": 4310}, {"id": 19, "swf": "WindRider", "title": "Sky High", "type": 1, "vars": [26,27,0], "icon": 4304, "card": 78},
{"id": 22, "swf": "DistanceChallenge", "title": "Long Shot", "type": 1, "vars": [20, 21, 0], "icon": 4298}, {"id": 20, "swf": "Twister", "title": "Twister", "type": 1, "vars": [24,25,0], "icon": 4310, "card": 79},
{"id": 23, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1}, {"id": 21, "swf": "FrogFlyer", "title": "Long Shot", "type": 1, "ready": false},
{"id": 26, "swf": "ArtStudioPottery", "title": "Pottery", "type": 1}, {"id": 22, "swf": "DistanceChallenge", "title": "Long Shot", "type": 1, "vars": [20,21,21], "icon": 4298, "card": 80},
{"id": 27, "swf": "MicroPhantom", "title": "Phantom Vortex", "type": 0}, {"id": 23, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1, "card": 58},
{"id": 28, "swf": "TowerDefense", "title": "Pest Control", "type": 1, "vars": [130, 131, 132], "icon": 4301}, {"id": 24, "swf": "ArtStudioColor", "title": "Coloring", "type": 1, "card": 58, "ready": false},
{"id": 30, "swf": "GemBreaker", "title": "Gem Breaker", "type": 1, "vars": [91, 93, 92], "start": "seedAndPlayers", "icon": 4313}, {"id": 25, "swf": "ParachuteGliderTest", "title": "Wind Rider", "type": 1, "card": 65, "ready": false},
{"id": 34, "swf": "MicroMiraSays", "title": "Mira Says", "type": 1, "vars": [77, 76, 0], "icon": 4299}, {"id": 26, "swf": "ArtStudioPottery", "title": "Pottery", "type": 1, "card": 58},
{"id": 35, "swf": "FortSmasher", "title": "Fruit Slinger", "type": 1, "vars": [143, 144, 145], "ready": false, "icon": 4294}, {"id": 27, "swf": "MicroPhantom", "title": "Phantom Vortex", "type": 0, "card": 69},
{"id": 36, "swf": "MicroHotCocoa", "title": "Hot Cocoa Machine", "type": 0}, {"id": 28, "swf": "TowerDefense", "title": "Pest Control", "type": 1, "vars": [130,131,132], "icon": 4301, "card": 456},
{"id": 37, "swf": "SuperSort", "title": "Super Sort", "type": 1, "vars": [31, 32, 37], "icon": 4307}, {"id": 29, "swf": "GemBreaker", "title": "Gem Breaker", "type": 1, "start": "seedAndPlayers", "card": 58},
{"id": 39, "swf": "PillBugs", "title": "Pill Bugs", "type": 1, "vars": [277, 278, 279], "icon": 4303}, {"id": 30, "swf": "GemBreaker", "title": "Gem Breaker", "type": 1, "vars": [91,32,0], "start": "seedAndPlayers", "icon": 4313, "card": 354},
{"id": 40, "swf": "BradyExpeditions", "title": "Brady Expeditions", "type": 1}, {"id": 31, "swf": "PVP_ConnectFour", "title": "Four Gems", "type": 0, "icon": 5057, "card": 5049, "buddy": true},
{"id": 41, "swf": "PhantomsTreasure", "title": "Phantom's Treasure", "type": 1, "vars": [281, 283, 282], "icon": 4302}, {"id": 32, "swf": "PVP_RockPaperScissor", "title": "Rock Paper Scissors", "type": 0, "icon": 5060, "card": 5052, "buddy": true},
{"id": 42, "swf": "FeedingFrenzy", "title": "Eat 'Em Up", "type": 1, "vars": [284, 285, 0], "icon": 4292}, {"id": 34, "swf": "MicroMiraSays", "title": "Mira Says", "type": 1, "vars": [77,76,0], "icon": 4299, "card": 288},
{"id": 43, "swf": "MicroPetWash", "title": "Pet Wash", "type": 0}, {"id": 35, "swf": "FortSmasher", "title": "Fruit Slinger", "type": 1, "vars": [74,75,0], "icon": 4294, "card": 541, "ready": false},
{"id": 48, "swf": "FashionShow", "title": "Best Dressed", "type": 1, "vars": [292, 293, 294], "ready": false, "icon": 4288}, {"id": 36, "swf": "MicroHotCocoa", "title": "Hot Cocoa Machine", "type": 0, "vars": [95,0,0]},
{"id": 51, "swf": "ArtStudioPainting", "title": "Painting", "type": 1}, {"id": 37, "swf": "SuperSort", "title": "Super Sort", "type": 1, "vars": [31,32,37], "icon": 4307, "card": 353},
{"id": 52, "swf": "MicroPetSalon", "title": "Pet Stop", "type": 0}, {"id": 38, "swf": "PVP_ShellGame", "title": "Shell Game", "type": 0, "icon": 5062, "card": 5054, "buddy": true},
{"id": 55, "swf": "MicroGameInvasion", "title": "Phantom Invasion", "type": 0}, {"id": 39, "swf": "PillBugs", "title": "Pill Bugs", "type": 1, "vars": [277,278,279], "icon": 4303, "card": 1098},
{"id": 40, "swf": "BradyChemistrySet", "title": "Brady's Lab", "type": 0, "vars": [115,0,0]},
{"id": 41, "swf": "PhantomsTreasure", "title": "Phantom's Treasure", "type": 1, "vars": [281,283,282], "icon": 4302, "card": 1140},
{"id": 42, "swf": "FeedingFrenzy", "title": "Eat 'Em Up", "type": 1, "vars": [284,0,0], "icon": 4292, "card": 1170},
{"id": 43, "swf": "MicroPetWash", "title": "Pet Wash", "type": 0, "vars": [51,0,0]},
{"id": 45, "swf": "PVP_Marbles", "title": "Marbles", "type": 0, "icon": 5058, "card": 5050, "buddy": true},
{"id": 46, "swf": "OffTheHook", "title": "Off the Hook", "type": 1, "card": 79, "ready": false},
{"id": 47, "swf": "Pinball", "title": "Double Up", "type": 1, "card": 61, "ready": false},
{"id": 48, "swf": "FashionShow", "title": "Best Dressed", "type": 1, "vars": [292,293,294], "icon": 4288, "card": 1205, "ready": false},
{"id": 49, "swf": "Geography", "title": "Geography", "type": 1, "card": 79, "ready": false},
{"id": 51, "swf": "ArtStudioPainting", "title": "Painting", "type": 1, "vars": [78,0,0], "card": 4849},
{"id": 52, "swf": "MicroPetSalon", "title": "Pet Stop", "type": 0, "vars": [280,0,0], "card": 1205},
{"id": 53, "swf": "PVP_Scooped", "title": "Scooped", "type": 0, "icon": 5061, "card": 5053, "buddy": true},
{"id": 54, "swf": "Glide", "title": "Glide", "type": 1, "card": 79, "ready": false},
{"id": 55, "swf": "MicroGameInvasion", "title": "Phantom Invasion", "type": 0, "card": 1205},
{"id": 56, "swf": "ActivityGeography", "title": "Eat 'Em Up", "type": 1, "card": 1205, "ready": false},
{"id": 57, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 57, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 58, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 59, "swf": "MicroCrane", "title": "The Claw", "type": 0, "icon": 4290}, {"id": 59, "swf": "MicroCrane", "title": "The Claw", "type": 0, "icon": 4290},
{"id": 60, "swf": "TouchPool", "title": "Touch Pool", "type": 1, "vars": [310, 308, 309], "icon": 5229}, {"id": 60, "swf": "TouchPool", "title": "Touch Pool", "type": 1, "vars": [310,308,309], "icon": 5229, "card": 5228},
{"id": 61, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 61, "swf": "MicroCrane", "title": "The Claw", "type": 0, "card": 65},
{"id": 62, "swf": "HorseRace", "title": "Jamaa Derby", "type": 1, "vars": [327, 328, 330], "ready": false, "icon": 4297}, {"id": 62, "swf": "HorseRace", "title": "Jamaa Derby", "type": 1, "vars": [327,328,330], "icon": 4297, "card": 1510, "ready": false},
{"id": 63, "swf": "MicroPuppy", "title": "Disc Toss", "type": 0, "vars": [313, 314, 315], "pet": 4}, {"id": 63, "swf": "MicroPuppy", "title": "Disc Toss", "type": 0, "vars": [313,314,315], "pet": 4},
{"id": 64, "swf": "MicroDucky", "title": "Ducky Dash", "type": 0, "vars": [316, 317, 318], "pet": 3}, {"id": 64, "swf": "MicroDucky", "title": "Ducky Dash", "type": 0, "vars": [316,317,318], "pet": 3},
{"id": 65, "swf": "MicroSnake", "title": "Sssssnake", "type": 0, "vars": [321, 322, 323], "pet": 11}, {"id": 65, "swf": "MicroSnake", "title": "Sssssnake", "type": 0, "vars": [321,322,323], "pet": 11},
{"id": 66, "swf": "FashionShow", "title": "Best Dressed", "type": 1, "vars": [292, 293, 294], "ready": false, "icon": 4289}, {"id": 66, "swf": "FashionShow", "title": "Best Dressed", "type": 1, "vars": [292,293,294], "icon": 4289, "card": 1482, "ready": false},
{"id": 68, "swf": "Skeeball", "title": "Phantom Ball", "type": 1, "tickets": 10}, {"id": 67, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 69, "swf": "WhackPhantom", "title": "Whack-A-Phantom", "type": 1, "tickets": 10}, {"id": 68, "swf": "Skeeball", "title": "Phantom Ball", "type": 0, "tickets": 10},
{"id": 70, "swf": "CandyCatcher", "title": "Candy Catch", "type": 1, "tickets": 10}, {"id": 69, "swf": "WhackPhantom", "title": "Whack-A-Phantom", "type": 0, "vars": [78,0,0], "tickets": 10, "card": 300},
{"id": 70, "swf": "CandyCatcher", "title": "Candy Catch", "type": 0, "tickets": 10, "card": 300},
{"id": 71, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 71, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 72, "swf": "MicroGameInvasion", "title": "Phantom Invasion", "type": 0}, {"id": 72, "swf": "MicroGameInvasion", "title": "Phantom Invasion", "type": 0, "card": 259},
{"id": 73, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 1}, {"id": 73, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 1, "vars": [78,0,0], "card": 1205},
{"id": 74, "swf": "CottonCandy", "title": "Cotton Candy Machine", "type": 0}, {"id": 74, "swf": "CottonCandy", "title": "Cotton Candy Machine", "type": 0, "vars": [78,0,0]},
{"id": 75, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 75, "swf": "MicroCrane", "title": "The Claw", "type": 0, "card": 300},
{"id": 76, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1}, {"id": 76, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 77, "swf": "FallingPhantoms", "title": "Falling Phantoms", "type": 1, "vars": [344, 345, 346], "ready": false, "icon": 4293}, {"id": 77, "swf": "FallingPhantoms", "title": "Falling Phantoms", "type": 1, "vars": [344,345,346], "icon": 4293, "card": 1622, "ready": false},
{"id": 78, "swf": "DolphinRace", "title": "Splash and Dash", "type": 1, "vars": [357, 358, 360], "ready": false, "icon": 4306}, {"id": 78, "swf": "DolphinRace", "title": "Splash and Dash", "type": 1, "vars": [357,358,360], "icon": 4306, "card": 1804, "ready": false},
{"id": 80, "swf": "ShootingGallery", "title": "Carnival Darts", "type": 1, "tickets": 100}, {"id": 80, "swf": "ShootingGallery", "title": "Carnival Darts", "type": 0, "tickets": 100},
{"id": 81, "swf": "MicroPetSalon", "title": "Pet Stop", "type": 0}, {"id": 81, "swf": "MicroPetSalon", "title": "Pet Stop", "type": 0, "vars": [57,0,0], "card": 259},
{"id": 82, "swf": "FastFoodies", "title": "Fast Foodies", "type": 1, "vars": [445, 444, 446], "icon": 5727}, {"id": 82, "swf": "FastFoodies", "title": "Fast Foodies", "type": 1, "vars": [445,444,446], "icon": 5727},
{"id": 83, "swf": "HedgeHog", "title": "Hedge Hog", "type": 1, "vars": [349, 350, 351], "icon": 4296}, {"id": 83, "swf": "HedgeHog", "title": "Hedge Hog", "type": 1, "vars": [349,350,351], "icon": 4296, "card": 1713},
{"id": 85, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 85, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 86, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1}, {"id": 86, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 87, "swf": "BradyChemistrySet", "title": "Brady's Lab", "type": 0}, {"id": 87, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 88, "swf": "SafetyQuiz", "title": "Safety Quiz", "type": 0}, {"id": 88, "swf": "SafetyQuiz", "title": "Safety Quiz", "type": 0},
{"id": 94, "swf": "EagleFlap", "title": "Swoopy Eagle", "type": 1, "vars": [378, 377, 0], "icon": 4308}, {"id": 89, "swf": "ArtStudioPrint", "title": "Coloring", "type": 0},
{"id": 96, "swf": "DunkAPhantom", "title": "Dunk-A-Phantom", "type": 1, "tickets": 10}, {"id": 90, "swf": "BradyExpeditions", "title": "Brady Expeditions", "type": 1},
{"id": 97, "swf": "SpotOn", "title": "Spot On", "type": 1, "vars": [386, 387, 388], "icon": 4321}, {"id": 91, "swf": "MicroSmoothie", "title": "Smoothie Machine", "type": 0},
{"id": 92, "swf": "ParachuteGlider2", "title": "Wind Rider", "type": 1, "card": 65, "ready": false},
{"id": 93, "swf": "QuestParachuteGlider", "title": "Wind Rider", "type": 1, "vars": [12,13,0], "card": 65, "ready": false},
{"id": 94, "swf": "EagleFlap", "title": "Swoopy Eagle", "type": 1, "vars": [378,377,0], "icon": 4308, "card": 2647},
{"id": 95, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 96, "swf": "DunkAPhantom", "title": "Dunk-A-Phantom", "type": 0, "tickets": 10, "card": 300},
{"id": 97, "swf": "SpotOn", "title": "Spot On", "type": 1, "vars": [386,387,388], "icon": 4321, "card": 3561},
{"id": 98, "swf": "MicroCrane", "title": "The Claw", "type": 0, "vars": [5,0,0]},
{"id": 99, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 99, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 100, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 100, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 102, "swf": "TrueFalse", "title": "Best Guess", "type": 1, "vars": [403, 405, 0], "ready": false}, {"id": 101, "swf": "PVP_Memory", "title": "Pairs", "type": 0, "icon": 5059, "card": 5051, "buddy": true},
{"id": 102, "swf": "TrueFalse", "title": "Best Guess", "type": 1, "vars": [403,0,0], "card": 3748, "ready": false},
{"id": 103, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 103, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 104, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 104, "swf": "MicroCrane", "title": "The Claw", "type": 0, "card": 300},
{"id": 105, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 105, "swf": "MicroCrane", "title": "The Claw", "type": 0, "card": 61},
{"id": 106, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 106, "swf": "MicroCrane", "title": "The Claw", "type": 0, "card": 61},
{"id": 107, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 107, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 108, "swf": "PVP_Bowling", "title": "Bowling", "type": 0, "icon": 5056, "card": 5048, "buddy": true},
{"id": 109, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 109, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 110, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 110, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 111, "swf": "MicroGoldPanning", "title": "Long Shot", "type": 0, "vars": [415,0,0], "ready": false},
{"id": 112, "swf": "MicroOatHarvest", "title": "Slingshot", "type": 0, "vars": [415,0,0], "ready": false},
{"id": 113, "swf": "MicroWoodGather", "title": "Slingshot", "type": 0, "vars": [415,0,0], "ready": false},
{"id": 114, "swf": "MicroStoneMining", "title": "Slingshot", "type": 0, "vars": [415,0,0], "ready": false},
{"id": 115, "swf": "MicroBambooHarvest", "title": "Slingshot", "type": 0, "vars": [415,0,0], "ready": false},
{"id": 116, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 116, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 117, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 117, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 118, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 118, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 119, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 119, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 120, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 120, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 121, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 121, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 122, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 123, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 123, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 124, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 125, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 125, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 126, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 126, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 127, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 127, "swf": "MicroCrane", "title": "The Claw", "type": 0},
@@ -89,9 +123,11 @@
{"id": 132, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 132, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 133, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 133, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 134, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 134, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 136, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1}, {"id": 135, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 138, "swf": "FastFoodies", "title": "Fast Foodies", "type": 1, "vars": [445, 444, 446]}, {"id": 136, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 139, "swf": "ArtStudioGridDrawing", "title": "Pixel Painting", "type": 1}, {"id": 137, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 138, "swf": "FastFoodies", "title": "Fast Foodies", "type": 1, "vars": [445,444,446], "icon": 5727, "card": 5723},
{"id": 139, "swf": "ArtStudioGridDrawing", "title": "Pixel Painting", "type": 1, "card": 5958},
{"id": 140, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 140, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 141, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 141, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 142, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 142, "swf": "MicroCrane", "title": "The Claw", "type": 0},
@@ -103,16 +139,11 @@
{"id": 148, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 148, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 149, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 149, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 150, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 150, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 151, "swf": "ArtStudioGridDrawing", "title": "Pixel Painting", "type": 1, "vars": [78,0,0], "card": 5958},
{"id": 152, "swf": "ArtStudioPrint", "title": "Coloring", "type": 0},
{"id": 153, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 153, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 154, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 154, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 155, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 155, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 156, "swf": "MicroCrane", "title": "The Claw", "type": 0}, {"id": 156, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 89, "swf": "PVP_TicTacToe", "title": "Tic Tac Toe", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5063}, {"id": 158, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 1, "vars": [78,0,0], "card": 1205}
{"id": 90, "swf": "PVP_ConnectFour", "title": "Four Gems", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5057},
{"id": 91, "swf": "PVP_RockPaperScissor", "title": "Rock Paper Scissors", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5060},
{"id": 92, "swf": "PVP_ShellGame", "title": "Shell Game", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5062},
{"id": 93, "swf": "PVP_Memory", "title": "Pairs", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5059},
{"id": 95, "swf": "PVP_Scooped", "title": "Scooped", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5061},
{"id": 98, "swf": "PVP_Bowling", "title": "Bowling", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5056},
{"id": 101, "swf": "PVP_Marbles", "title": "Marbles", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5058}
] ]
+214 -19
View File
@@ -22,9 +22,13 @@ const defpacks = require("./defpacks.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const manage = require("./manage.js"); const manage = require("./manage.js");
const modpanel = require("./modpanel.js"); const modpanel = require("./modpanel.js");
const discordBot = require("./discordbot.js");
const badges = require("./badges.js"); const badges = require("./badges.js");
const extraMusic = require("./extramusic.js"); const extraMusic = require("./extramusic.js");
const customMusic = require("./custommusic.js");
const itemControl = require("./itemcontrol.js");
const masterpieces = require("./masterpieces.js"); const masterpieces = require("./masterpieces.js");
const themeRooms = require("./themerooms.js");
const panel = require("./panel.js"); const panel = require("./panel.js");
const totp = require("./totp.js"); const totp = require("./totp.js");
const world = require("./world.js"); const world = require("./world.js");
@@ -50,6 +54,19 @@ const MIME = {
".otf": "font/otf", ".otf": "font/otf",
}; };
// The desktop webview caches the SWF aggressively. Include the local SWF's
// timestamp in its URL so a freshly built client is actually picked up after
// the server restarts, without making an operator remember to bump a config
// value by hand.
const clientRevision = () => {
try {
return Math.floor(fs.statSync(config.clientSwf).mtimeMs).toString(36);
}
catch (_) {
return "unknown";
}
};
const flashVars = () => ({ const flashVars = () => ({
content: config.baseUrl, content: config.baseUrl,
// the game's own server to the SWF, whatever its name: it loads the card // the game's own server to the SWF, whatever its name: it loads the card
@@ -69,10 +86,14 @@ const flashVars = () => ({
// member or not may be chosen on any server (lib/accounts.js) // member or not may be chosen on any server (lib/accounts.js)
membershipChoice: true, membershipChoice: true,
smoke_version: config.deployVersion, smoke_version: config.deployVersion,
clientURL: `${config.baseUrl}${config.deployVersion}/ajclient.swf?v=${config.buildVersion}`, clientURL: `${config.baseUrl}${config.deployVersion}/ajclient.swf?v=${config.buildVersion}-${clientRevision()}`,
startupRoom: config.startupRoom, startupRoom: config.startupRoom,
// "-1" turns the client's stats socket off. // "-1" turns the client's stats socket off.
sbStatTrackerIp: "-1", sbStatTrackerIp: "-1",
// the client's Discord rich presence (its app/discord.js): the Discord
// application it shows as, "" for none, and where its button goes.
discordAppId: config.discord.clientId,
presenceUrl: `${config.siteUrl}download`,
sbStatModulator: "0", sbStatModulator: "0",
currentTimestamp: Math.floor(Date.now() / 1000), currentTimestamp: Math.floor(Date.now() / 1000),
country: "US", country: "US",
@@ -213,6 +234,75 @@ const itemArtUpload = async (req, res, url, from, signedIn = null, adminSignedIn
send(res, 200, result); 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: // 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. // to its maker (the account page) and to staff who review or make items.
const itemArtView = (req, res, url, signedIn, adminSignedIn) => { const itemArtView = (req, res, url, signedIn, adminSignedIn) => {
@@ -289,7 +379,7 @@ const repeatedError = text => {
const THEMED_ROOM = /^(\d+)\/roomDefs\/theme_(\d+)\/(.+)$/; const THEMED_ROOM = /^(\d+)\/roomDefs\/theme_(\d+)\/(.+)$/;
// the web pages, as against what the game and the client load // the web pages, as against what the game and the client load
const SITE_PAGES = /^\/(?:register|terms|privacy|commands|shop|account|mod|download)?\/?$/; const SITE_PAGES = /^\/(?:register|terms|privacy|commands|shop|account|mod|admin|dashboard|download)?\/?$/;
// the installers /download offers, those of them config.downloadsDir has // the installers /download offers, those of them config.downloadsDir has
const DOWNLOADS = [ const DOWNLOADS = [
@@ -344,6 +434,7 @@ const CAPTCHA_PAGE_HEADERS = {...PAGE_HEADERS, "Content-Security-Policy": captch
// write, from config.js. // write, from config.js.
const LEGAL_VALUES = {legalEmail: config.legalEmail, adminEmail: config.adminEmail, operator: config.operator, hostedIn: config.hostedIn, const LEGAL_VALUES = {legalEmail: config.legalEmail, adminEmail: config.adminEmail, operator: config.operator, hostedIn: config.hostedIn,
version: config.termsVersion, site: new URL(config.siteUrl).host}; version: config.termsVersion, site: new URL(config.siteUrl).host};
const MAX_RULES_LENGTH = 65536; // characters of data/rules.txt the game is sent
const escapeHtml = text => String(text).replace(/[&<>"]/g, sign => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;"})[sign]); const escapeHtml = text => String(text).replace(/[&<>"]/g, sign => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;"})[sign]);
const sendLegalPage = async (res, file) => { const sendLegalPage = async (res, file) => {
for (const [name, value] of Object.entries(PAGE_HEADERS)) { for (const [name, value] of Object.entries(PAGE_HEADERS)) {
@@ -469,6 +560,7 @@ const renameAndSignIn = (res, body, from) => {
console.log(`[accounts] a rejected username was replaced by "${logText(account.username)}"`); console.log(`[accounts] a rejected username was replaced by "${logText(account.username)}"`);
accounts.setLoginChoices(account, body.login_choices); accounts.setLoginChoices(account, body.login_choices);
const token = accounts.issueToken(account); const token = accounts.issueToken(account);
devices.noteLauncher(token, Boolean(devices.read(body.device)));
send(res, 200, {auth_token: token, refresh_token: token, device_token: entry.deviceToken}); send(res, 200, {auth_token: token, refresh_token: token, device_token: entry.deviceToken});
}; };
@@ -479,13 +571,11 @@ const authenticate = async (req, res, from) => {
return; return;
} }
// the computer it is on (lib/devices.js): a client that does not say is // the computer it is on (lib/devices.js): a client that does not say is
// out of date (before 1.3.0) or not ours. 1.2 shows "The server refused // out of date (before 1.3.0) or not ours. it is signed in all the same,
// the login (426)", and still offers its update. // and its token noted (signInChecked): with config.requireDevice the game
// then loads and its login popup says to update (lib/world.js), where a
// refusal here only ever showed "The server refused the login (426)".
const device = devices.read(body.device); const device = devices.read(body.device);
if (!device && config.requireDevice) {
send(res, 426, {error_code: 101, error: "client_outdated"});
return;
}
const accountKey = String(body.username).trim().toLowerCase(); const accountKey = String(body.username).trim().toLowerCase();
if (!from.local && failuresByAddress.blocked(from.key)) { if (!from.local && failuresByAddress.blocked(from.key)) {
send(res, 429, {error_code: 429, error: "too_many_attempts"}); send(res, 429, {error_code: 429, error: "too_many_attempts"});
@@ -609,6 +699,7 @@ const signInChecked = async (res, body, from, account, saved, device) => {
// the custom client's advanced settings; the official launcher sends none. // the custom client's advanced settings; the official launcher sends none.
accounts.setLoginChoices(account, body.login_choices); accounts.setLoginChoices(account, body.login_choices);
const token = byRefresh ? body.refresh_token : accounts.issueToken(account); const token = byRefresh ? body.refresh_token : accounts.issueToken(account);
devices.noteLauncher(token, Boolean(device));
send(res, 200, {auth_token: token, refresh_token: token, device_token: deviceToken}); send(res, 200, {auth_token: token, refresh_token: token, device_token: deviceToken});
}; };
@@ -648,22 +739,60 @@ const handle = async (req, res) => {
return; return;
} }
const isAdmin = url.pathname === "/admin" || url.pathname.startsWith("/admin/"); const dashboardAdmin = url.pathname === "/dashboard/admin" || url.pathname.startsWith("/dashboard/admin/")
|| url.pathname === "/dashboard/api/admin" || url.pathname.startsWith("/dashboard/api/admin/");
const dashboardStaff = url.pathname === "/dashboard/staff" || url.pathname.startsWith("/dashboard/staff/")
|| url.pathname === "/dashboard/api/staff" || url.pathname.startsWith("/dashboard/api/staff/");
const isDashboard = url.pathname === "/dashboard" || dashboardAdmin || dashboardStaff;
const isAdmin = url.pathname === "/admin" || url.pathname.startsWith("/admin/") || dashboardAdmin;
const isAccount = url.pathname === "/account" || url.pathname.startsWith("/account/"); const isAccount = url.pathname === "/account" || url.pathname.startsWith("/account/");
const isMod = url.pathname === "/mod" || url.pathname.startsWith("/mod/"); const isMod = url.pathname === "/mod" || url.pathname.startsWith("/mod/") || dashboardStaff;
// the pages that keep a cookie answer only under this server's own names: // the pages that keep a cookie answer only under this server's own names:
// a request sent here by a page of another name (one whose name was made // a request sent here by a page of another name (one whose name was made
// to point at this machine, say) is not theirs to make. nor is such a // to point at this machine, say) is not theirs to make. nor is such a
// request ever this machine's own, wherever it came from. // request ever this machine's own, wherever it came from.
if (!limits.hostAllowed(req)) { if (!limits.hostAllowed(req)) {
if (isAdmin || isAccount || isMod) { if (isDashboard || isAdmin || isAccount || isMod) {
send(res, 421, {error: "wrong_host"}); send(res, 421, {error: "wrong_host"});
return; return;
} }
from.local = false; from.local = false;
} }
// GitHub sends signed push events here for optional Discord update cards.
if (url.pathname === "/discord/github") {
await discordBot.handleGithubWebhook(req, res);
return;
}
// One entry point for the owner and staff dashboards. The old addresses
// stay as bookmark-friendly redirects; their APIs remain available for
// installed tools and are not redirected.
if (req.method === "GET" && url.pathname === "/dashboard/") {
res.writeHead(302, {Location: `/dashboard${url.search}`, "Content-Length": 0});
res.end();
return;
}
if (req.method === "GET" && url.pathname === "/dashboard") {
res.setHeader("Cache-Control", "no-store");
res.setHeader("X-Frame-Options", "DENY");
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("Referrer-Policy", "no-referrer");
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "dashboard.html")), "text/html; charset=utf-8");
return;
}
if (req.method === "GET" && url.pathname === "/admin") {
res.writeHead(302, {Location: "/dashboard/admin", "Content-Length": 0});
res.end();
return;
}
if (req.method === "GET" && url.pathname === "/mod") {
res.writeHead(302, {Location: "/dashboard/staff", "Content-Length": 0});
res.end();
return;
}
// the admin panel sets its own, stricter headers: none of the cross-origin // the admin panel sets its own, stricter headers: none of the cross-origin
// allowances below apply to it. on a public server it is not there at all // allowances below apply to it. on a public server it is not there at all
// for anyone but this machine and the addresses named (config.adminAllow). // for anyone but this machine and the addresses named (config.adminAllow).
@@ -672,11 +801,20 @@ const handle = async (req, res) => {
send(res, 404, "Not found", "text/plain"); send(res, 404, "Not found", "text/plain");
return; return;
} }
if (dashboardAdmin) {
url.pathname = url.pathname.startsWith("/dashboard/api/admin")
? url.pathname.replace("/dashboard/api/admin", "/admin/api")
: url.pathname.replace("/dashboard/admin", "/admin");
}
if (url.pathname === "/admin/api/itemart") { if (url.pathname === "/admin/api/itemart") {
res.setHeader("Cache-Control", "no-store"); res.setHeader("Cache-Control", "no-store");
await itemArtUpload(req, res, url, from, null, panel.signedIn); await itemArtUpload(req, res, url, from, null, panel.signedIn);
return; return;
} }
if (url.pathname === "/admin/api/music") {
await musicRoute(req, res, url, from, null, panel.signedIn);
return;
}
await panel.handle(req, res, url, from, {send, readJson}); await panel.handle(req, res, url, from, {send, readJson});
return; return;
} }
@@ -693,11 +831,20 @@ const handle = async (req, res) => {
// and the moderator panel (lib/modpanel.js), which is there for anyone to // and the moderator panel (lib/modpanel.js), which is there for anyone to
// reach: its moderators are players, wherever they are. // reach: its moderators are players, wherever they are.
if (dashboardStaff) {
url.pathname = url.pathname.startsWith("/dashboard/api/staff")
? url.pathname.replace("/dashboard/api/staff", "/mod/api")
: url.pathname.replace("/dashboard/staff", "/mod");
}
if (isMod && url.pathname === "/mod/api/itemart") { if (isMod && url.pathname === "/mod/api/itemart") {
res.setHeader("Cache-Control", "no-store"); res.setHeader("Cache-Control", "no-store");
await itemArtUpload(req, res, url, from, modpanel.signedInAs); await itemArtUpload(req, res, url, from, modpanel.signedInAs);
return; return;
} }
if (isMod && url.pathname === "/mod/api/music") {
await musicRoute(req, res, url, from, modpanel.signedInAs);
return;
}
if (isMod) { if (isMod) {
await modpanel.handle(req, res, url, from, {send, readJson}); await modpanel.handle(req, res, url, from, {send, readJson});
return; return;
@@ -862,6 +1009,10 @@ const handle = async (req, res) => {
res.setHeader("Cache-Control", "public, max-age=86400"); res.setHeader("Cache-Control", "public, max-age=86400");
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "ban-icon.png")), MIME[".png"]); send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "ban-icon.png")), MIME[".png"]);
return; return;
case "GET /burrow-status-banner.png": // public banner used by the Discord status card
res.setHeader("Cache-Control", "public, max-age=86400");
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "burrow-status-banner.png")), MIME[".png"]);
return;
case "GET /bio-icon.png": // the button of the card's Bio tab case "GET /bio-icon.png": // the button of the card's Bio tab
res.setHeader("Cache-Control", "public, max-age=86400"); res.setHeader("Cache-Control", "public, max-age=86400");
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "bio-icon.png")), MIME[".png"]); send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "bio-icon.png")), MIME[".png"]);
@@ -922,18 +1073,45 @@ const handle = async (req, res) => {
return; return;
} }
const parts = formParts(req.headers["content-type"], await readBody(req, masterpieces.MAX_IMAGE_BYTES + 16 * 1024)); const parts = formParts(req.headers["content-type"], await readBody(req, masterpieces.MAX_IMAGE_BYTES + 16 * 1024));
const uuid = 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}); send(res, 200, uuid ? {success: true, uuid} : {success: false});
return; return;
} }
case "GET /crossdomain.xml": case "GET /crossdomain.xml":
send(res, 200, CROSS_DOMAIN, "text/xml"); send(res, 200, CROSS_DOMAIN, "text/xml");
return; return;
// the game's rules window (AJClient.showRules) shows this file, read
// again on every ask so it can be changed on a running server; made
// with a placeholder when there is none.
case "GET /rules.txt": {
const file = path.join(config.dataDir, "rules.txt");
let text;
try {
text = await fs.promises.readFile(file, "utf8");
}
catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
text = "Example\n";
await fs.promises.writeFile(file, text, {flag: "wx"}).catch(() => {});
}
res.setHeader("Cache-Control", "no-cache");
res.setHeader("X-Content-Type-Options", "nosniff");
send(res, 200, text.slice(0, MAX_RULES_LENGTH), "text/plain; charset=utf-8");
return;
}
case "GET /gameClient/game/index.html": case "GET /gameClient/game/index.html":
// not to be put in a frame of anyone's; the client shows it in a view of its own. // not to be put in a frame of anyone's; the client shows it in a view of its own.
res.setHeader("X-Frame-Options", "DENY"); res.setHeader("X-Frame-Options", "DENY");
res.setHeader("Referrer-Policy", "no-referrer"); res.setHeader("Referrer-Policy", "no-referrer");
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "game.html")), MIME[".html"]); // the admin's switch for the theatre browser (lib/panel.js), for the page to read
send(res, 200, String(await fs.promises.readFile(path.join(config.publicDir, "game.html")))
.replace("<html>", panel.theatreBrowserOn() ? '<html data-theatre-browser="on">' : "<html>"), MIME[".html"]);
return; return;
} }
@@ -968,7 +1146,15 @@ const handle = async (req, res) => {
return session ? limits.key(session.address) : null; return session ? limits.key(session.address) : null;
}; };
const picture = masterpieces.mayView(painting[1], from.key, playingFrom) || from.local ? masterpieces.image(painting[1]) : null; const picture = masterpieces.mayView(painting[1], from.key, playingFrom) || from.local ? masterpieces.image(painting[1]) : null;
send(res, picture ? 200 : 404, picture || "Not found", picture ? MIME[".jpg"] : "text/plain"); if (picture) {
send(res, 200, picture, MIME[".jpg"]);
return;
}
// one that cannot be shown (waiting to be looked at, seen from an
// address not its maker's game's, or its file gone) is the Burrow logo:
// given nothing, the game waited for it for good, behind its spinner.
res.setHeader("Cache-Control", "no-store");
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "logo-square.png")), MIME[".png"]);
return; return;
} }
@@ -984,15 +1170,21 @@ const handle = async (req, res) => {
send(res, body ? 200 : 404, body || "Not found", body ? MIME[".swf"] : "text/plain"); send(res, body ? 200 : 404, body || "Not found", body ? MIME[".swf"] : "text/plain");
return; return;
} }
// the extra den music tracks, which the CDN does not have as files. // the extra den music tracks, which the CDN does not have as files, and
const extra = await extraMusic.asset(relPath); // those uploaded by staff.
const extra = await extraMusic.asset(relPath) || await customMusic.asset(relPath);
if (extra) { if (extra) {
send(res, extra.body ? 200 : 404, extra.body || "Not found", extra.body ? extra.type : "text/plain"); send(res, extra.body ? 200 : 404, extra.body || "Not found", extra.body ? extra.type : "text/plain");
return; return;
} }
const clientPack = await defpacks.clientPack(relPath); const clientPack = await defpacks.clientPack(relPath);
if (clientPack) { if (clientPack) {
send(res, 200, clientPack, "application/octet-stream"); // what custom items this game has from its packs (customItems.sendAll)
const packKind = defpacks.customPackKind(relPath);
if (packKind) {
customItems.sawPack(from.key, packKind, clientPack.version);
}
send(res, 200, clientPack.body, "application/octet-stream");
return; return;
} }
// A room file in a seasonal theme ("<build>/roomDefs/theme_<other // A room file in a seasonal theme ("<build>/roomDefs/theme_<other
@@ -1000,8 +1192,11 @@ const handle = async (req, res) => {
// or from the current one when the room did not exist yet back then. // or from the current one when the room did not exist yet back then.
const themed = THEMED_ROOM.exec(relPath); const themed = THEMED_ROOM.exec(relPath);
const mayFetch = () => from.local || cacheMisses.allow(from.key); const mayFetch = () => from.local || cacheMisses.allow(from.key);
const body = (themed && Object.values(config.themes).some(theme => theme.build === Number(themed[2])) && await cdn.get(`${themed[2]}/roomDefs/${themed[3]}`, mayFetch)) const currentPath = themed ? `${themed[1]}/roomDefs/${themed[3]}` : relPath;
|| await cdn.get(themed ? `${themed[1]}/roomDefs/${themed[3]}` : relPath, mayFetch); const oldBody = themed && themed[2] !== themed[1] && Object.values(config.themes).some(theme => theme.build === Number(themed[2]))
&& await cdn.get(`${themed[2]}/roomDefs/${themed[3]}`, mayFetch);
// its shops and other spots as today's room has them (lib/themerooms.js)
const body = oldBody ? await themeRooms.fix(relPath, oldBody, () => cdn.get(currentPath, mayFetch)) : await cdn.get(currentPath, mayFetch);
if (!body) { if (!body) {
// one the CDN does not have is asked for again and again (the same few // one the CDN does not have is asked for again and again (the same few
// hundred, by every client that meets them): its client may keep the // hundred, by every client that meets them): its client may keep the
+2 -2
View File
@@ -22,9 +22,9 @@ const imageModeration = require("./image-moderation.js");
// kept as data/itemart/<kind>-<id>.<png|jpg|gif>; its version, a hash, is on // kept as data/itemart/<kind>-<id>.<png|jpg|gif>; its version, a hash, is on
// the item (customItems.setArt), so a new picture is a new address. // the item (customItems.setArt), so a new picture is a new address.
const MAX_BYTES = 300 * 1024; // a picture kept const MAX_BYTES = 100 * 1024; // a picture kept: every player who sees the item downloads it
const MAX_UPLOAD = 2 * 1024 * 1024; // one sent (a BMP is bigger than the PNG it becomes) const MAX_UPLOAD = 2 * 1024 * 1024; // one sent (a BMP is bigger than the PNG it becomes)
const MAX_SIDE = 512; const MAX_SIDE = 256; // drawn fitted to the item anyway (a den item's place is 160)
const MIN_SIDE = 8; const MIN_SIDE = 8;
const DIR = path.join(config.dataDir, "itemart"); const DIR = path.join(config.dataDir, "itemart");
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]); const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
+93 -1
View File
@@ -3,6 +3,7 @@
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const customItems = require("./customitems.js"); const customItems = require("./customitems.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const wearRules = require("./wearrules.js");
// what staff who make items (items.create: admins and developers) may do // what staff who make items (items.create: admins and developers) may do
// about who has them: // about who has them:
@@ -83,6 +84,94 @@ const lockedList = () => [...lockSet()].map(entry => {
return {kind, id: Number(id), name: nameOf(kind, id)}; return {kind, id: Number(id), name: nameOf(kind, id)};
}); });
// The animals a moderator can select in the dashboard. Avatar types, rather
// than a hand-written list of species, keep this correct for packs added in
// a later game build.
const wearAnimals = () => defpacks.avatarTypes().sort((one, two) => one - two).map(type => {
const def = defpacks.avatarDef(type) || {};
return {id: Number(type), name: defpacks.string(def.titleStrRef || def.nameStrId) || def.abbrName || `Animal ${type}`};
});
const wearRuleList = () => wearRules.all().flatMap(rule => {
const found = item("clothing", rule.id);
return found.error ? [] : [{id: found.id, name: nameOf(found.kind, found.id), blockedTypes: rule.blocked}];
});
// Remove a new restriction from every possible display of an item. A clothing
// association has an avatar slot; a mannequin keeps the inventory ids in
// five den-item slots. Both must be cleaned or a rule can be bypassed by
// switching animals or visiting a den.
const removeBlockedUses = (account, itemId, blocked) => {
const disallowedAvatarSlots = new Set(account.avatars.filter(avatar => blocked.has(Number(avatar.type))).map(avatar => avatar.avInvId));
const matchingInventory = new Set(account.items.filter(piece => piece.def === itemId).map(piece => piece.inv));
let removed = 0;
let clothingChanged = false;
let mannequinChanged = false;
for (const piece of account.items) {
if (piece.def !== itemId || !Array.isArray(piece.on)) {
continue;
}
const kept = piece.on.filter(avInvId => !disallowedAvatarSlots.has(avInvId));
if (kept.length !== piece.on.length) {
removed += piece.on.length - kept.length;
piece.on = kept;
clothingChanged = true;
}
}
for (const denItem of account.denItems) {
const mannequinType = Number((defpacks.denItemDef(denItem.def) || {}).mannequinAvatarDefId);
if (!blocked.has(mannequinType) || !denItem.mannequin || !Array.isArray(denItem.mannequin.worn)) {
continue;
}
const kept = denItem.mannequin.worn.map(inv => (matchingInventory.has(Number(inv)) ? 0 : inv));
if (kept.some((inv, index) => inv !== denItem.mannequin.worn[index])) {
removed += kept.filter(inv => inv === 0).length - denItem.mannequin.worn.filter(inv => inv === 0).length;
denItem.mannequin.worn = kept;
mannequinChanged = true;
}
}
return {changed: clothingChanged || mannequinChanged, mannequinChanged, removed};
};
// Make a clothing item unavailable to the selected animal types. `world`
// refreshes games and den visitors after the persistent state is cleaned.
const setWearRule = (id, blockedTypes, world) => {
const found = item("clothing", id);
if (found.error) {
return found;
}
const animals = wearAnimals();
const allowed = new Set(animals.map(animal => animal.id));
if (!Array.isArray(blockedTypes) || blockedTypes.length > allowed.size || !blockedTypes.every(Number.isInteger)
|| blockedTypes.some(type => !allowed.has(type))) {
return {error: "Choose only animals from the list."};
}
const blocked = [...new Set(blockedTypes)].sort((one, two) => one - two);
const changedRule = wearRules.setBlockedTypes(found.id, blocked).changed;
let accountsChanged = 0;
let removed = 0;
const blockedSet = new Set(blocked);
for (const account of accounts.all()) {
const cleaned = removeBlockedUses(account, found.id, blockedSet);
if (!cleaned.changed) {
continue;
}
accountsChanged++;
removed += cleaned.removed;
accounts.save(account);
world.wearRulesChanged(account, cleaned.mannequinChanged);
}
// Packs downloaded after this moment, and games already open, use the
// same rule-to-flag transformation. Server checks above remain authority.
defpacks.invalidateClientItemPack();
customItems.sendClothingDefs([found.id]);
const animalNames = blocked.map(type => animals.find(animal => animal.id === type).name);
const subject = describe(found.kind, found.id);
const suffix = blocked.length ? `cannot be worn by ${animalNames.join(", ")}.` : "can be worn by every animal again.";
return {ok: `${subject} ${suffix}${removed ? ` Took it off ${removed} existing use${removed === 1 ? "" : "s"}.` : ""}`,
detail: `clothing ${found.id}; blocked types ${blocked.join(",") || "none"}; ${accountsChanged} account${accountsChanged === 1 ? "" : "s"} changed`, changed: changedRule};
};
// every one of an item an account has, out of its inventory (and its trade // every one of an item an account has, out of its inventory (and its trade
// list). `world` tells a game playing (lib/world.js itemsTaken). returns how // list). `world` tells a game playing (lib/world.js itemsTaken). returns how
// many went. // many went.
@@ -135,7 +224,10 @@ const deleteCustom = (kind, id, world) => {
if (lockSet().delete(key(kind, entry.id))) { if (lockSet().delete(key(kind, entry.id))) {
saveLocks(); saveLocks();
} }
if (kind === "clothing") {
wearRules.forget(entry.id);
}
return {ok: `Deleted ${entry.name} (${kind === "den" ? "den item" : "clothing"} ${entry.id})${count ? `, and took ${count} from players` : ""}.`}; return {ok: `Deleted ${entry.name} (${kind === "den" ? "den item" : "clothing"} ${entry.id})${count ? `, and took ${count} from players` : ""}.`};
}; };
module.exports = {isLocked, setLocked, lockedList, take, deleteCustom}; module.exports = {isLocked, setLocked, lockedList, wearAnimals, wearRuleList, setWearRule, take, deleteCustom};
+76
View File
@@ -0,0 +1,76 @@
"use strict";
// pictures of items for the web item giver (public/items.html), from the
// game's own files on the CDN:
//
// - clothing: the icon the game shows in a closet (item.SimpleIcon), a
// paletted bitmap the page colours itself as the game does
// (LayerBitmap.paintFrame), so any four colours show without asking again.
// - den items: their art, a SWF, which public/item-preview.html plays with
// Ruffle through public/item-preview.swf (tools/preview-host).
//
// both are the same for everyone, so no sign-in is asked for them.
const zlib = require("zlib");
const amf3 = require("./amf3.js");
const cdn = require("./cdn.js");
const customItems = require("./customitems.js");
const defpacks = require("./defpacks.js");
const ICON_AVATAR = 1; // the avatar every closet icon is drawn for (Item.makeSmallIcon)
const ICON_LARGE = 25; // SimpleIcon.AN_ICON_L
const ICON_SMALL = 26; // SimpleIcon.AN_ICON_S
const IMAGE_VERSION = 0x7080900; // what ImageServerURL accepts
// DenItem.getIconId: which of an item's pictures the den shows, by its sort category.
const iconId = sortCat => ([0, 99, 6, 5].includes(sortCat) ? 1 : sortCat === 1 ? 2 : [2, 3, 4].includes(sortCat) ? 3 : sortCat + 1);
// a custom item is drawn as the game's item it was made from.
const baseIdOf = (kind, id) => {
const entry = customItems.get(kind, id);
return entry ? entry.base : Number(id);
};
// a clothing item's closet icon, large if there is one: {w, h, b} with b the
// first frame's run-length bytes, base64 (LayerBitmap.paintFrame reads them).
// null when it has none.
const clothingIcon = async id => {
const def = defpacks.itemDef(id);
if (!def || !Number.isInteger(Number(def.layerDefId))) {
return null;
}
for (const size of [ICON_LARGE, ICON_SMALL]) {
const file = await cdn.get(cdn.hashedPath(`imageArrays/${((ICON_AVATAR << 24) | (size << 16) | Number(def.layerDefId)) >>> 0}`));
try {
const image = file && amf3.decode(zlib.inflateSync(file));
const frame = image && image.v === IMAGE_VERSION && Array.isArray(image.f) && image.f[0];
if (frame && Buffer.isBuffer(frame.b) && frame.w > 0 && frame.h > 0) {
return {w: frame.w, h: frame.h, b: frame.b.toString("base64")};
}
}
catch (err) {
// not an icon this can read: the next size, or none.
}
}
return null;
};
// a den item's art as the SWF it holds, or null.
const denArt = async id => {
const def = defpacks.denItemDef(id);
const baseId = baseIdOf("den", id);
const baseDef = defpacks.denItemDef(baseId);
if (!def || !baseDef) {
return null;
}
const file = await cdn.get(cdn.hashedPath(`items/${((baseId << 16) | iconId(Number(baseDef.sortCat))) >>> 0}`));
try {
const wrapped = file && amf3.decode(file);
return wrapped && wrapped.ba ? Buffer.from(wrapped.ba) : null;
}
catch (err) {
return null;
}
};
module.exports = {clothingIcon, denArt};
+47
View File
@@ -3,6 +3,7 @@
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const achievements = require("./achievements.js"); const achievements = require("./achievements.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const wearRules = require("./wearrules.js");
const {CURRENCIES, MAX_ITEMS, MAX_WORN, activeAvatar, addClothing, sendClothingAdded, sendClothingRemoved, resolvePurchase} = require("./player.js"); const {CURRENCIES, MAX_ITEMS, MAX_WORN, activeAvatar, addClothing, sendClothingAdded, sendClothingRemoved, resolvePurchase} = require("./player.js");
// clothing: buying, wearing and recycling (client side: ItemXtCommManager). // clothing: buying, wearing and recycling (client side: ItemXtCommManager).
@@ -18,6 +19,8 @@ const LAYER_EYES = "3";
const MAX_RECYCLED_AT_ONCE = 500; const MAX_RECYCLED_AT_ONCE = 500;
const MAX_USED_AT_ONCE = 200; // pieces put on or taken off in one message const MAX_USED_AT_ONCE = 200; // pieces put on or taken off in one message
const RECYCLE_FRACTION = 0.3; // matches recyclePercentage sent at login const RECYCLE_FRACTION = 0.3; // matches recyclePercentage sent at login
const CURRENCY_GEMS = 0; // ItemXtCommManager.currencyUpdateResponse's currency type
const PHOTO_GEMS = 50; // what the photo booth says a picture costs (string 14789)
module.exports = ({others, sendItemList}) => { module.exports = ({others, sendItemList}) => {
// ItemXtCommManager.itemBuyResponse: [status, shopId, newAmount, currencyType] // ItemXtCommManager.itemBuyResponse: [status, shopId, newAmount, currencyType]
@@ -82,6 +85,13 @@ module.exports = ({others, sendItemList}) => {
} }
const item = account.items.find(candidate => candidate.inv === invIdx); const item = account.items.find(candidate => candidate.inv === invIdx);
if (item) { if (item) {
// The client flag only makes the control gray. Never trust it: a
// crafted iu packet or a stale client must not bypass a staff rule.
// Check before changing `on`, so a refused request cannot take off
// an otherwise valid item as a side effect.
if (worn && !wearRules.mayWear(item.def, avatar.type)) {
return null;
}
item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId); item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId);
// no more than MAX_WORN on one animal: what is over stays off. // no more than MAX_WORN on one animal: what is over stays off.
if (worn && account.items.filter(candidate => candidate.on.includes(avatar.avInvId)).length >= MAX_WORN) { if (worn && account.items.filter(candidate => candidate.on.includes(avatar.avInvId)).length >= MAX_WORN) {
@@ -133,6 +143,43 @@ module.exports = ({others, sendItemList}) => {
session.sendXt("ce", -1, 1, account.currency[paid]); session.sendXt("ce", -1, 1, account.currency[paid]);
}, },
// gui.MuseumDonation: [amount], gems given to the museum's causes. the
// reply (currencyDonationResponse) is [1] or [0]; the gems go, and the
// account keeps count of what it has given.
cd(session, roomId, [amount]) {
const {account} = session;
const gems = /^\d{1,9}$/.test(String(amount)) ? Number(amount) : 0;
if (gems < 1 || (account.currency.gems || 0) < gems) {
session.sendXt("cd", -1, 0);
return;
}
account.currency.gems -= gems;
account.gemsDonated = (account.gemsDonated || 0) + gems;
achievements.currencyChanged(account, "gems", -gems);
accounts.save(account);
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
session.sendXt("cd", -1, 1);
},
// the photo booth's picture (gui.PhotoBooth), PHOTO_GEMS gems. "apc"
// asks first: [gems after, or -1 for too few]; "apb", once the player
// keeps the picture, pays: [gem total]. neither was answered, and the
// booth waited behind its spinner for good.
apc(session) {
const gems = session.account.currency.gems || 0;
session.sendXt("apc", -1, gems >= PHOTO_GEMS ? gems - PHOTO_GEMS : -1);
},
apb(session) {
const {account} = session;
if ((account.currency.gems || 0) >= PHOTO_GEMS) {
account.currency.gems -= PHOTO_GEMS;
achievements.currencyChanged(account, "gems", -PHOTO_GEMS);
accounts.save(account);
}
session.sendXt("apb", -1, account.currency.gems || 0);
},
// ItemXtCommManager.requestItemRecycle: [invIdx, ...]. the reply // ItemXtCommManager.requestItemRecycle: [invIdx, ...]. the reply
// (itemRecycleResponse) is [count, newGemTotal, ...recycledInvIdx], and // (itemRecycleResponse) is [count, newGemTotal, ...recycledInvIdx], and
// the recycling window then waits, behind its spinner, for the item // the recycling window then waits, behind its spinner, for the item
+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};
+31 -1
View File
@@ -1,5 +1,6 @@
"use strict"; "use strict";
const net = require("net");
const config = require("../config.js"); const config = require("../config.js");
// small in-memory rate limits for the parts of the server that strangers can // small in-memory rate limits for the parts of the server that strangers can
@@ -28,6 +29,25 @@ const key = address => {
const isLoopback = address => LOOPBACK.includes(String(address || "").replace(/^::ffff:/i, "")); const isLoopback = address => LOOPBACK.includes(String(address || "").replace(/^::ffff:/i, ""));
// the addresses Cloudflare's edge connects from, as it publishes them at
// https://www.cloudflare.com/ips/ (they seldom change; add any new range here).
const CLOUDFLARE = new net.BlockList();
for (const range of ["173.245.48.0/20", "103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22", "141.101.64.0/18",
"108.162.192.0/18", "190.93.240.0/20", "188.114.96.0/20", "197.234.240.0/22", "198.41.128.0/17", "162.158.0.0/15",
"104.16.0.0/13", "104.24.0.0/14", "172.64.0.0/13", "131.0.72.0/22"]) {
const [prefix, bits] = range.split("/");
CLOUDFLARE.addSubnet(prefix, Number(bits), "ipv4");
}
for (const range of ["2400:cb00::/32", "2606:4700::/32", "2803:f800::/32", "2405:b500::/32", "2405:8100::/32",
"2a06:98c0::/29", "2c0f:f248::/32"]) {
const [prefix, bits] = range.split("/");
CLOUDFLARE.addSubnet(prefix, Number(bits), "ipv6");
}
const fromCloudflare = address => {
const family = net.isIP(address);
return family !== 0 && CLOUDFLARE.check(address, family === 4 ? "ipv4" : "ipv6");
};
// is this address the server's own machine, and does that count for // is this address the server's own machine, and does that count for
// anything here? (It must not when a local reverse proxy forwards everyone.) // anything here? (It must not when a local reverse proxy forwards everyone.)
const isTrustedLocal = address => config.trustLocalRequests && isLoopback(address); const isTrustedLocal = address => config.trustLocalRequests && isLoopback(address);
@@ -45,7 +65,17 @@ const clientOf = req => {
const own = String(req.socket.remoteAddress || "").replace(/^::ffff:/i, ""); const own = String(req.socket.remoteAddress || "").replace(/^::ffff:/i, "");
const forwarded = req.headers["x-forwarded-for"] || req.headers.forwarded || req.headers["cf-connecting-ip"] || req.headers["x-real-ip"]; const forwarded = req.headers["x-forwarded-for"] || req.headers.forwarded || req.headers["cf-connecting-ip"] || req.headers["x-real-ip"];
const hops = String(req.headers["x-forwarded-for"] || "").split(",").map(hop => hop.trim()).filter(Boolean); const hops = String(req.headers["x-forwarded-for"] || "").split(",").map(hop => hop.trim()).filter(Boolean);
const address = config.trustedProxy && isLoopback(own) && hops.length ? hops[hops.length - 1].replace(/^::ffff:/i, "").slice(0, 60) : own; // the last X-Forwarded-For entry is the one the local proxy appended: who
// connected to it (the first is whatever the visitor sent, so it is never
// used). Behind Cloudflare that is Cloudflare's own edge, which made every
// visitor one address (and left remoteip out of the Turnstile check), so
// then CF-Connecting-IP is the visitor. Only when that hop is Cloudflare:
// anyone who reaches the server directly can send the header too. Neither
// header counts unless the local reverse proxy has been trusted.
const lastHop = (hops.at(-1) || "").replace(/^::ffff:/i, "");
const cloudflareAddress = String(req.headers["cf-connecting-ip"] || "").trim().replace(/^::ffff:/i, "");
const reported = net.isIP(cloudflareAddress) && fromCloudflare(lastHop) ? cloudflareAddress : lastHop;
const address = config.trustedProxy && isLoopback(own) && reported ? reported.replace(/^::ffff:/i, "").slice(0, 60) : own;
const direct = isLoopback(own) && !forwarded; const direct = isLoopback(own) && !forwarded;
return {address, key: key(address), direct, local: direct && config.trustLocalRequests}; return {address, key: key(address), direct, local: direct && config.trustLocalRequests};
}; };
+343 -8
View File
@@ -12,6 +12,7 @@ const config = require("../config.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const achievements = require("./achievements.js"); const achievements = require("./achievements.js");
const badges = require("./badges.js"); const badges = require("./badges.js");
const discord = require("./discord.js");
const bans = require("./bans.js"); const bans = require("./bans.js");
const captcha = require("./captcha.js"); const captcha = require("./captcha.js");
const chatlog = require("./chatlog.js"); const chatlog = require("./chatlog.js");
@@ -21,7 +22,12 @@ const masterpieces = require("./masterpieces.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const support = require("./support.js"); const support = require("./support.js");
const totp = require("./totp.js"); const totp = require("./totp.js");
const recoveryMail = require("./recoverymail.js");
const world = require("./world.js"); const world = require("./world.js");
const chatStyles = require("./chatstyles.js");
const roles = require("./roles.js");
const admin = require("./admin.js");
const itemPreview = require("./itempreview.js");
// the account page at /account: what a player can do about their own // the account page at /account: what a player can do about their own
// account from a browser. they sign in with the game's username and // account from a browser. they sign in with the game's username and
@@ -40,9 +46,40 @@ const world = require("./world.js");
const COOKIE = "ajc_account"; const COOKIE = "ajc_account";
// A device that gave its two-step code keeps this for 30 days (lib/totp.js). // A device that gave its two-step code keeps this for 30 days (lib/totp.js).
const DEVICE_COOKIE = "ajc_device"; const DEVICE_COOKIE = "ajc_device";
// a Discord link under way (lib/discord.js): the browser that started it
// must be the one that comes back. Lax, as Discord's redirect back is from
// another site, which the page's own (Strict) cookie is not sent from.
const DISCORD_COOKIE = "ajc_dlink";
const discordCookie = (value, maxAgeSeconds) =>
`${DISCORD_COOKIE}=${value}; Path=/account/discord; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const SESSION_HOURS = 12; const SESSION_HOURS = 12;
const TEN_MINUTES_MS = 600000; const TEN_MINUTES_MS = 600000;
// "Sign in with the Burrow client": the page starts it, and keeps this
// cookie; the link it opens (burrow://account?n=<nonce>) has the client ask
// for a ticket with its own login token, which it then opens in the
// browser at /account/client. the ticket signs in only the browser that
// holds the nonce it was asked for, so a burrow:// link from anywhere else
// signs nobody in, and a ticket sent to someone else opens nothing for them.
const CLIENT_COOKIE = "ajc_clink";
const clientCookie = (value, maxAgeSeconds) =>
`${CLIENT_COOKIE}=${value}; Path=/account/client; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const CLIENT_START_MS = 5 * 60 * 1000;
const CLIENT_TICKET_MS = 2 * 60 * 1000;
const MAX_CLIENT_STARTS = 10000;
const clientStarts = new Map(); // SHA-256 of a nonce -> expiry (ms)
const clientTickets = new Map(); // SHA-256 of a ticket -> {id: account id, nonce: SHA-256 of its nonce, expiry: ms}
const clientStartsByAddress = limits.limiter(20, TEN_MINUTES_MS);
const clientTicketsByAccount = limits.limiter(10, TEN_MINUTES_MS);
const dropExpired = map => {
for (const [hash, entry] of map) {
if ((typeof entry === "number" ? entry : entry.expiry) < Date.now()) {
map.delete(hash);
}
}
};
const MAX_NOTE = 120; const MAX_NOTE = 120;
const RECOVERY_TOKEN_MS = 30 * 60 * 1000;
const recoveryHash = token => crypto.createHash("sha256").update(token).digest("hex");
// wrong passwords before further tries from an address are refused for a // wrong passwords before further tries from an address are refused for a
// while, as for the launcher's sign-in (lib/http.js). // while, as for the launcher's sign-in (lib/http.js).
@@ -52,6 +89,21 @@ const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_M
// at it and is then signed out. // at it and is then signed out.
const WRONG_PASSWORDS_ALLOWED = 5; const WRONG_PASSWORDS_ALLOWED = 5;
const wrongPasswords = limits.limiter(WRONG_PASSWORDS_ALLOWED, TEN_MINUTES_MS); const wrongPasswords = limits.limiter(WRONG_PASSWORDS_ALLOWED, TEN_MINUTES_MS);
const recoveryRequests = limits.limiter(5, TEN_MINUTES_MS);
// recovery mail sent for one account, from any address: a few an hour.
const recoveryMailsPerAccount = limits.limiter(3, 3600000);
// a 2FA reset by email waits this long after a password reset by email, so
// that someone who has only the mailbox cannot do one after the other.
const EMAIL_RESET_GAP_MS = 7 * 24 * 3600000;
// why a 2FA reset by email cannot be done for this account now, or null.
// it also needs the account's password (recover/complete). staff ask the
// admin (lib/panel.js), whose 2FA reset ends their role's use until they
// turn it on again: a mailbox must not make someone staff.
const twoStepResetProblem = account => roles.roleOf(account)
? "Staff accounts cannot remove 2FA by email. Ask the admin."
: account.emailPasswordResetAt && Date.now() - account.emailPasswordResetAt < EMAIL_RESET_GAP_MS
? "2FA cannot be removed by email within 7 days of a password reset by email."
: null;
// what may be done from the page of a ban (above). // what may be done from the page of a ban (above).
const BANNED_MAY = ["password", "twoStepStart", "twoStepConfirm", "twoStepOff", "forgetDevices", "delete", "appeal"]; const BANNED_MAY = ["password", "twoStepStart", "twoStepConfirm", "twoStepOff", "forgetDevices", "delete", "appeal"];
// and from the page of a rejected username: the same, with a new name in // and from the page of a rejected username: the same, with a new name in
@@ -104,6 +156,13 @@ const signOutOthers = (account, req) => {
} }
}; };
// ends the account's sessions in the moderator panel (lib/modpanel.js, which
// needs this file, so it is asked for when used): with the others when the
// password changes or the owner signs out everywhere, and when the account
// locks or turns 2FA off, so that a session from before does not come back
// with it.
const endStaffSessions = account => require("./modpanel.js").forget(account);
const twoStepOf = account => ({on: totp.isOn(account), since: account.totp ? account.totp.since : null, const twoStepOf = account => ({on: totp.isOn(account), since: account.totp ? account.totp.since : null,
recoveryLeft: account.totp ? account.totp.recovery.length : 0, devices: totp.freshDevices(account).length, deviceDays: totp.DEVICE_DAYS}); recoveryLeft: account.totp ? account.totp.recovery.length : 0, devices: totp.freshDevices(account).length, deviceDays: totp.DEVICE_DAYS});
@@ -128,6 +187,7 @@ const bannedProfile = (account, ban) => {
appeal: appeal && {createdAt: appeal.createdAt, text: appeal.text, status: appeal.status, reply: appeal.reply, handledAt: appeal.handledAt}, appeal: appeal && {createdAt: appeal.createdAt, text: appeal.text, status: appeal.status, reply: appeal.reply, handledAt: appeal.handledAt},
appealLimit: bans.MAX_APPEAL, appealLimit: bans.MAX_APPEAL,
twoStep: twoStepOf(account), twoStep: twoStepOf(account),
recoveryEmail: account.recoveryEmail ? `${account.recoveryEmail.slice(0, 2)}…${account.recoveryEmail.slice(account.recoveryEmail.lastIndexOf("@"))}` : "",
}; };
}; };
@@ -149,6 +209,7 @@ const profile = (account, from) => {
logins: account.numLogins || 0, logins: account.numLogins || 0,
playtime: account.playtime, playtime: account.playtime,
playtimePublic: account.playtimePublic, playtimePublic: account.playtimePublic,
chatStyle: chatStyles.normalize(account.chatStyle),
animals: account.avatars.length, animals: account.avatars.length,
animalType: avatar ? avatar.type : null, animalType: avatar ? avatar.type : null,
items: account.items.length, items: account.items.length,
@@ -163,7 +224,10 @@ const profile = (account, from) => {
banned: null, banned: null,
locked: account.locked, locked: account.locked,
twoStep: twoStepOf(account), twoStep: twoStepOf(account),
recoveryEmail: account.recoveryEmail ? `${account.recoveryEmail.slice(0, 2)}…${account.recoveryEmail.slice(account.recoveryEmail.lastIndexOf("@"))}` : "",
discord: account.discord, discord: account.discord,
discordLinked: Boolean(account.discordId),
discordLinking: discord.linking(),
bio: account.bio, bio: account.bio,
bioLimit: badges.MAX_BIO, bioLimit: badges.MAX_BIO,
badges: badges.of(account).map(badge => badge.label), badges: badges.of(account).map(badge => badge.label),
@@ -188,7 +252,7 @@ const profile = (account, from) => {
// hash, the 2FA secret, device passes), and what other tables hold of it. // hash, the 2FA secret, device passes), and what other tables hold of it.
// what others wrote about it (reports, a moderator's notes) is not theirs // what others wrote about it (reports, a moderator's notes) is not theirs
// to be handed, and is not here. // to be handed, and is not here.
const SECRET_FIELDS = ["salt", "hash", "totp", "totpSetup", "devices", "modNotes"]; const SECRET_FIELDS = ["salt", "hash", "totp", "totpSetup", "devices", "modNotes", "recoveryTokens"];
const dataOf = account => ({ const dataOf = account => ({
exportedAt: new Date().toISOString(), exportedAt: new Date().toISOString(),
server: config.baseUrl, server: config.baseUrl,
@@ -283,6 +347,7 @@ const act = (account, body, req, from, res) => {
} }
world.moderation.actions.kick(account); world.moderation.actions.kick(account);
signOutOthers(account, req); signOutOthers(account, req);
endStaffSessions(account);
console.log(`[account] "${logText(account.username)}" changed their password from ${logText(from.address)}`); console.log(`[account] "${logText(account.username)}" changed their password from ${logText(from.address)}`);
return {ok: "Password changed."}; return {ok: "Password changed."};
} }
@@ -302,6 +367,7 @@ const act = (account, body, req, from, res) => {
// out of the game now, and no saved sign-in gets back in. // out of the game now, and no saved sign-in gets back in.
accounts.revokeTokens(account); accounts.revokeTokens(account);
world.moderation.actions.kick(account); world.moderation.actions.kick(account);
endStaffSessions(account);
} }
accounts.save(account); accounts.save(account);
console.log(`[account] "${logText(account.username)}" ${logText(account.locked ? "locked" : "unlocked")} from ${logText(from.address)}`); console.log(`[account] "${logText(account.username)}" ${logText(account.locked ? "locked" : "unlocked")} from ${logText(from.address)}`);
@@ -355,6 +421,7 @@ const act = (account, body, req, from, res) => {
} }
totp.turnOff(account); totp.turnOff(account);
accounts.save(account); accounts.save(account);
endStaffSessions(account);
res.setHeader("Set-Cookie", cookieHeader("", 0, DEVICE_COOKIE)); res.setHeader("Set-Cookie", cookieHeader("", 0, DEVICE_COOKIE));
console.log(`[account] "${logText(account.username)}" turned two-step sign-in off from ${logText(from.address)}`); console.log(`[account] "${logText(account.username)}" turned two-step sign-in off from ${logText(from.address)}`);
return {ok: "2FA is off."}; return {ok: "2FA is off."};
@@ -403,16 +470,26 @@ const act = (account, body, req, from, res) => {
account.playtimePublic = body.on === true; account.playtimePublic = body.on === true;
accounts.save(account); accounts.save(account);
return {ok: account.playtimePublic ? "Others can see your playtime on your card." : "Your playtime is private."}; return {ok: account.playtimePublic ? "Others can see your playtime on your card." : "Your playtime is private."};
// their Discord username, for their card in the game. empty takes it off. // A player can choose every colour, opacity, animation and animation
case "discord": { // speed. Validation is deliberately here as well as in the page: saved
const name = badges.discordName(body.name); // state is not trusted just because it came from our own browser UI.
if (name === null) { case "chatStyle": {
return {error: "Not a Discord username."}; if (!chatStyles.valid(body.style)) {
return {error: "Choose valid chat colours and animation settings."};
} }
account.discord = name; account.chatStyle = chatStyles.normalize(body.style);
accounts.save(account); accounts.save(account);
return {ok: name ? "Saved." : "Removed."}; return {ok: "Chat style saved. Your next message will use it."};
} }
// their Discord account, for their card in the game: it is linked by
// signing in to Discord (GET /account/discord/link), and only taken off
// here, with the booster badge it brought.
case "discord":
if (String(body.name || "") !== "") {
return {error: "Link your Discord account instead."};
}
discord.unlink(account);
return {ok: "Removed."};
// the player's own words about a buddy; only they see them. // the player's own words about a buddy; only they see them.
case "buddyNote": { case "buddyNote": {
const key = String(body.name || "").toLowerCase(); const key = String(body.name || "").toLowerCase();
@@ -459,6 +536,7 @@ const act = (account, body, req, from, res) => {
accounts.save(account); accounts.save(account);
world.moderation.actions.kick(account); world.moderation.actions.kick(account);
signOutOthers(account, req); signOutOthers(account, req);
endStaffSessions(account);
return {ok: "Signed out everywhere."}; return {ok: "Signed out everywhere."};
// for good: the password again, and the username typed out. // for good: the password again, and the username typed out.
case "delete": { case "delete": {
@@ -471,6 +549,7 @@ const act = (account, body, req, from, res) => {
const name = account.username; const name = account.username;
world.disconnect(account); world.disconnect(account);
signOutOthers(account, null); signOutOthers(account, null);
endStaffSessions(account);
erase(account); erase(account);
console.log(`[account] "${logText(name)}" deleted their account from ${logText(from.address)}`); console.log(`[account] "${logText(name)}" deleted their account from ${logText(from.address)}`);
return {ok: "Account deleted.", deleted: true}; return {ok: "Account deleted.", deleted: true};
@@ -489,6 +568,16 @@ const PAGE_HEADERS = {
+ "form-action 'none'; frame-ancestors 'none'; base-uri 'none'"), + "form-action 'none'; frame-ancestors 'none'; base-uri 'none'"),
}; };
// the web item giver shows den items in frames of public/item-preview.html,
// which plays them with Ruffle (a Flash player, from jsDelivr).
const ITEMS_PAGE_POLICY = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; "
+ "frame-src 'self'; form-action 'none'; frame-ancestors 'none'; base-uri 'none'";
const RUFFLE = "https://cdn.jsdelivr.net/npm/@ruffle-rs/[email protected]/";
const PREVIEW_POLICY = `default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval' ${RUFFLE}; connect-src 'self' ${RUFFLE}; `
+ "style-src 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' data: blob:; worker-src blob:; "
+ "form-action 'none'; frame-ancestors 'self'; base-uri 'none'; sandbox allow-scripts";
const artFetches = limits.limiter(600, 600000); // item pictures for the web item giver, per address in ten minutes
// A request that changes something must come from this server's own page. // A request that changes something must come from this server's own page.
const sameOrigin = limits.originAllowed; const sameOrigin = limits.originAllowed;
@@ -504,6 +593,45 @@ const handle = async (req, res, url, from, web) => {
web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "account.html"))), "text/html; charset=utf-8"); web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "account.html"))), "text/html; charset=utf-8");
return; return;
} }
// the item giver on the web (public/items.html), with this page's sign-in.
if (route === "GET /account/items") {
res.setHeader("Content-Security-Policy", ITEMS_PAGE_POLICY);
web.send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "items.html")), "text/html; charset=utf-8");
return;
}
// its den item previews (lib/itempreview.js): a page of their own in a
// frame, sandboxed, as they run a Flash player from elsewhere (Ruffle).
if (route === "GET /account/item-preview") {
res.setHeader("Content-Security-Policy", PREVIEW_POLICY);
res.setHeader("X-Frame-Options", "SAMEORIGIN");
web.send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "item-preview.html")), "text/html; charset=utf-8");
return;
}
const art = /^GET \/account\/(item-preview\.swf|art\/(clothing|den)\/(\d{1,9}))$/.exec(route);
if (art) {
// fetched from the preview's sandbox, which has no origin of its own
res.setHeader("Access-Control-Allow-Origin", "*");
if (art[1] === "item-preview.swf") {
web.send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "item-preview.swf")), "application/x-shockwave-flash");
return;
}
if (!artFetches.allow(from.address)) {
reply(429, {error: "Too many at once. Try again in a minute."});
return;
}
const found = art[2] === "den" ? await itemPreview.denArt(Number(art[3])) : await itemPreview.clothingIcon(Number(art[3]));
if (!found) {
reply(404, {error: "No picture."});
return;
}
res.setHeader("Cache-Control", "public, max-age=3600");
web.send(res, 200, found, art[2] === "den" ? "application/x-shockwave-flash" : "application/json");
return;
}
if (route === "GET /account/recover") {
web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "recover.html"))), "text/html; charset=utf-8");
return;
}
if (req.method === "POST" && !sameOrigin(req)) { if (req.method === "POST" && !sameOrigin(req)) {
reply(403, {error: "forbidden"}); reply(403, {error: "forbidden"});
return; return;
@@ -511,6 +639,87 @@ const handle = async (req, res, url, from, web) => {
const body = req.method === "POST" ? await web.readJson(req) : {}; const body = req.method === "POST" ? await web.readJson(req) : {};
switch (route) { switch (route) {
case "POST /account/api/recover/request": {
// Always give the same reply: neither account names nor email addresses
// can be discovered from this endpoint.
if (!from.local && !recoveryRequests.allow(from.key)) {
reply(429, {ok: "If the account and recovery email match, we sent a recovery link."});
return;
}
const account = accounts.byName(String(body.username || ""));
const email = String(body.email || "").trim().toLowerCase();
const kind = body.kind === "twoStep" ? "twoStep" : "password";
if (account && account.recoveryEmail && account.recoveryEmail === email && recoveryMail.available()
&& recoveryMailsPerAccount.allow(account.id)) {
const token = crypto.randomBytes(32).toString("hex");
account.recoveryTokens = (account.recoveryTokens || []).filter(entry => entry.expires > Date.now());
account.recoveryTokens.push({hash: recoveryHash(token), kind, expires: Date.now() + RECOVERY_TOKEN_MS});
accounts.save(account);
const link = new URL(`/account/recover?token=${token}`, config.siteUrl).href;
const sent = await recoveryMail.send({to: account.recoveryEmail, subject: "Burrow account recovery",
text: `A ${kind === "twoStep" ? "2FA reset" : "password reset"} was requested for ${account.username}. Open this link within 30 minutes:\n${link}\n\nIf this was not you, ignore this email.`});
if (!sent) {
account.recoveryTokens = account.recoveryTokens.filter(entry => entry.hash !== recoveryHash(token));
accounts.save(account);
}
}
reply(200, {ok: "If the account and recovery email match, we sent a recovery link."});
return;
}
case "POST /account/api/recover/check": {
const token = String(body.token || "");
const account = [...accounts.all()].find(candidate => (candidate.recoveryTokens || []).some(entry => entry.hash === recoveryHash(token) && entry.expires > Date.now()));
const entry = account && account.recoveryTokens.find(candidate => candidate.hash === recoveryHash(token) && candidate.expires > Date.now());
const refused = entry && entry.kind === "twoStep" ? twoStepResetProblem(account) : null;
reply(entry && !refused ? 200 : 400, entry && !refused ? {kind: entry.kind} : {error: refused || "This recovery link is invalid or expired."});
return;
}
case "POST /account/api/recover/complete": {
const token = String(body.token || "");
const account = [...accounts.all()].find(candidate => (candidate.recoveryTokens || []).some(entry => entry.hash === recoveryHash(token) && entry.expires > Date.now()));
const entry = account && account.recoveryTokens.find(candidate => candidate.hash === recoveryHash(token) && candidate.expires > Date.now());
if (!entry) {
reply(400, {error: "This recovery link is invalid or expired."});
return;
}
if (entry.kind === "password") {
const problem = accounts.setPassword(account, body.password);
if (problem) {
reply(400, {error: problem === "weak_password" ? "That password is too easy to guess." : "Use 10+ characters with an uppercase letter, lowercase letter and digit."});
return;
}
account.emailPasswordResetAt = Date.now();
}
else {
const refused = twoStepResetProblem(account);
if (refused) {
reply(400, {error: refused});
return;
}
// the mailbox and the password: the link alone does not remove 2FA.
if (!from.local && failuresByAddress.blocked(from.key)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
if (await accounts.authenticateAsync(account.username, body.password) !== account) {
failuresByAddress.record(from.key);
reply(401, {error: "Wrong password."});
return;
}
if (totp.isOn(account)) {
totp.turnOff(account);
accounts.revokeTokens(account);
}
}
account.recoveryTokens = [];
accounts.save(account);
signOutOthers(account, null);
endStaffSessions(account);
world.moderation.actions.kick(account);
console.log(`[recovery] ${logText(entry.kind)} reset for "${logText(account.username)}" after email verification from ${logText(from.address)}`);
reply(200, {ok: entry.kind === "password" ? "Password reset. You can sign in now." : "2FA reset. You can sign in now."});
return;
}
case "POST /account/api/login": { case "POST /account/api/login": {
const key = String(body.username || "").trim().toLowerCase(); const key = String(body.username || "").trim().toLowerCase();
if (!from.local && failuresByAddress.blocked(from.key)) { if (!from.local && failuresByAddress.blocked(from.key)) {
@@ -568,6 +777,96 @@ const handle = async (req, res, url, from, web) => {
reply(200, {ok: true}); reply(200, {ok: true});
return; return;
} }
// "Sign in with the Burrow client" (above), from the page: the nonce for
// the burrow:// link, which this browser keeps as a cookie too.
case "POST /account/api/client-start": {
if (!from.local && !clientStartsByAddress.allow(from.key)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
dropExpired(clientStarts);
if (clientStarts.size >= MAX_CLIENT_STARTS) {
reply(503, {error: "Try again in a few minutes."});
return;
}
const nonce = crypto.randomBytes(24).toString("hex");
clientStarts.set(sha256(nonce), Date.now() + CLIENT_START_MS);
res.setHeader("Set-Cookie", clientCookie(nonce, CLIENT_START_MS / 1000));
reply(200, {nonce});
return;
}
// ... from the client, with its login token (no Origin: the client's main
// process): where to send the browser, which signs in there. a token is
// only given after a whole sign-in, 2FA code included (lib/http.js).
case "POST /account/api/client-ticket": {
const nonce = typeof body.nonce === "string" && /^[0-9a-f]{48}$/.test(body.nonce) ? body.nonce : "";
const started = nonce && clientStarts.get(sha256(nonce));
if (!started || started < Date.now()) {
reply(400, {error: "Start again from the account page."});
return;
}
if (!from.local && failuresByAddress.blocked(from.key)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
const account = accounts.byToken(body.token);
if (!account) {
failuresByAddress.record(from.key);
reply(401, {error: "Log in to Burrow again first."});
return;
}
if (!clientTicketsByAccount.allow(account.id)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
dropExpired(clientTickets);
const ticket = crypto.randomBytes(24).toString("hex");
clientTickets.set(sha256(ticket), {id: account.id, nonce: sha256(nonce), expiry: Date.now() + CLIENT_TICKET_MS});
reply(200, {url: new URL(`/account/client?ticket=${ticket}`, config.siteUrl).href, username: account.username});
return;
}
}
// ... and the ticket, opened by the client in the browser: signed in when
// this browser started it (its cookie). a ticket is good once, whatever
// happens. the page that follows says how it went.
if (route === "GET /account/client") {
const given = String(url.searchParams.get("ticket") || "");
const ticket = /^[0-9a-f]{48}$/.test(given) ? clientTickets.get(sha256(given)) : null;
if (ticket) {
clientTickets.delete(sha256(given));
}
const nonce = (new RegExp(`(?:^|;\\s*)${CLIENT_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1];
const account = ticket && ticket.expiry > Date.now() ? accounts.byId(ticket.id) : null;
const result = !account ? "expired" : !nonce || sha256(nonce) !== ticket.nonce ? "elsewhere" : "ok";
const cookies = [clientCookie("", 0)];
if (result === "ok") {
clientStarts.delete(ticket.nonce);
accounts.recordLogin(account, "web", from.address);
accounts.save(account);
signIn(res, account, cookies);
}
else {
res.setHeader("Set-Cookie", cookies);
}
// a page of this site's own that goes on to the account page, rather than
// a redirect: the (SameSite=Strict) cookie then surely goes with it.
res.setHeader("Cache-Control", "no-store");
web.send(res, 200, `<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=/account?client=${result}"><title>Burrow</title>`,
"text/html; charset=utf-8");
return;
}
// back from Discord (lib/discord.js): the state and the nonce must be the
// ones the link began with. the page then says how it went.
if (route === "GET /account/discord/callback") {
const nonce = (new RegExp(`(?:^|;\\s*)${DISCORD_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1];
const result = url.searchParams.get("error") ? {error: "cancelled"}
: await discord.finish(url.searchParams.get("state"), nonce, url.searchParams.get("code"));
res.setHeader("Set-Cookie", discordCookie("", 0));
res.writeHead(302, {Location: `/account?discord=${result.ok ? "linked" : result.error}`});
res.end();
return;
} }
const account = signedInAs(req); const account = signedInAs(req);
@@ -576,6 +875,20 @@ const handle = async (req, res, url, from, web) => {
return; return;
} }
switch (route) { switch (route) {
// the page's "Link Discord": off to Discord's sign-in, which comes back
// to /account/discord/callback.
case "GET /account/discord/link": {
if (!discord.linking() || banFor(account, from)) {
res.writeHead(302, {Location: "/account?discord=off"});
res.end();
return;
}
const {url: to, nonce} = discord.start(account);
res.setHeader("Set-Cookie", discordCookie(nonce, 600));
res.writeHead(302, {Location: to});
res.end();
return;
}
// A copy of their data, as a file. also from the page of a ban. // A copy of their data, as a file. also from the page of a ban.
case "GET /account/api/export": case "GET /account/api/export":
if (!writesPerTenMinutes.allow(account.id)) { if (!writesPerTenMinutes.allow(account.id)) {
@@ -588,6 +901,28 @@ const handle = async (req, res, url, from, web) => {
case "GET /account/api/me": case "GET /account/api/me":
reply(200, profile(account, from)); reply(200, profile(account, from));
return; return;
// the item giver (above, and lib/admin.js): for the account signed in
// here only, as the in-game one is for the one playing; not while banned.
case "GET /account/api/giver":
case "GET /account/api/colour":
case "POST /account/api/give": {
if (banFor(account, from) || account.nameRejected) {
reply(403, {error: "Not now."});
return;
}
if (route === "GET /account/api/colour") {
const result = await admin.colourLookup(url.searchParams);
reply(result.status, result.body);
return;
}
if (req.method === "GET") {
reply(200, await admin.searchFor(account, url.searchParams));
return;
}
const result = admin.giveAs(account, body);
reply(result.status, result.body);
return;
}
// for the trade offer form: what the player could give, and what // for the trade offer form: what the player could give, and what
// another player has up for trade. // another player has up for trade.
case "GET /account/api/tradable": { case "GET /account/api/tradable": {
+239 -26
View File
@@ -7,6 +7,7 @@ const config = require("../config.js");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const imageModeration = require("./image-moderation.js"); const imageModeration = require("./image-moderation.js");
const jpegPrint = require("./jpegprint.js");
// masterpieces: paintings from the Art Studio, framed and hung in a den // masterpieces: paintings from the Art Studio, framed and hung in a den
// (client side: game.artStudioPainting.ArtStudioPainting, the same in // (client side: game.artStudioPainting.ArtStudioPainting, the same in
@@ -41,9 +42,27 @@ const SCHEMA = `
status INTEGER NOT NULL, status INTEGER NOT NULL,
frame INTEGER NOT NULL, frame INTEGER NOT NULL,
reviewed_at INTEGER, reviewed_at INTEGER,
reviewed_by TEXT,
likes TEXT NOT NULL, likes TEXT NOT NULL,
image BLOB NOT NULL image BLOB NOT NULL
); );
-- every picture taken in, for the daily limit (pictures thrown away
-- unframed count too)
CREATE TABLE IF NOT EXISTS masterpiece_uploads (
creator_id INTEGER NOT NULL,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS masterpiece_uploads_by ON masterpiece_uploads (creator_id, created_at);
-- pictures a moderator or the admin approved once: the same picture
-- again, the same file (SHA-256) or the same painting saved and painted
-- again (its fingerprint, lib/jpegprint.js), is approved as it is framed
CREATE TABLE IF NOT EXISTS masterpiece_approved_pictures (
hash TEXT PRIMARY KEY,
approved_at INTEGER NOT NULL,
approved_by TEXT NOT NULL,
fingerprint BLOB,
thumb BLOB
);
`; `;
const UPLOADED = 0; // posted, not made into an item yet const UPLOADED = 0; // posted, not made into an item yet
@@ -78,14 +97,35 @@ const fileOf = id => path.join(folder(), `${id}.jpg`);
const GALLERY_SPOTS = 12; // PartyManager.setupMasterpiecesInRoom const GALLERY_SPOTS = 12; // PartyManager.setupMasterpiecesInRoom
const uploadsPerHour = limits.limiter(30, 3600000); const uploadsPerHour = limits.limiter(30, 3600000);
const DAY = 86400;
const AUTO_APPROVER = "auto"; // reviewedBy of a painting approved for a picture approved before
const now = () => Math.floor(Date.now() / 1000); const now = () => Math.floor(Date.now() / 1000);
const db = () => accounts.database(); const db = () => accounts.database();
const known = new Map(); // id -> {id, creator, createdAt, status, frame, likes: [account ids]} const known = new Map(); // id -> {id, creator, createdAt, status, frame, reviewedAt, reviewedBy, likes: [account ids], hash}
const approvedPictures = new Map(); // hash -> thumbnail of its fingerprint, or null: masterpiece_approved_pictures
const tokens = new Map(); // upload token -> {account id, expires (ms)} const tokens = new Map(); // upload token -> {account id, expires (ms)}
const load = () => { const load = () => {
db().exec(SCHEMA); db().exec(SCHEMA);
// who approved it: a moderator's username, "admin", or null when nobody
// looked (review was off, or it was approved before this was kept).
const columns = db().prepare("PRAGMA table_info(masterpieces)").all().map(column => column.name);
if (!columns.includes("reviewed_by")) {
db().exec("ALTER TABLE masterpieces ADD COLUMN reviewed_by TEXT");
}
// the picture's SHA-256 (hashOf) and fingerprint (lib/jpegprint.js), to know it again
if (!columns.includes("hash")) {
db().exec("ALTER TABLE masterpieces ADD COLUMN hash TEXT");
}
if (!columns.includes("fingerprint")) {
db().exec("ALTER TABLE masterpieces ADD COLUMN fingerprint BLOB");
}
const pictureColumns = db().prepare("PRAGMA table_info(masterpiece_approved_pictures)").all().map(column => column.name);
if (!pictureColumns.includes("fingerprint")) {
db().exec("ALTER TABLE masterpiece_approved_pictures ADD COLUMN fingerprint BLOB");
db().exec("ALTER TABLE masterpiece_approved_pictures ADD COLUMN thumb BLOB");
}
fs.mkdirSync(folder(), {recursive: true}); fs.mkdirSync(folder(), {recursive: true});
// pictures still in the table move out into files, once. // pictures still in the table move out into files, once.
for (const row of db().prepare("SELECT id FROM masterpieces WHERE length(image) > 0").all()) { for (const row of db().prepare("SELECT id FROM masterpieces WHERE length(image) > 0").all()) {
@@ -93,15 +133,138 @@ const load = () => {
fs.writeFileSync(fileOf(row.id), Buffer.from(picture)); fs.writeFileSync(fileOf(row.id), Buffer.from(picture));
db().prepare("UPDATE masterpieces SET image = ? WHERE id = ?").run(NO_IMAGE, row.id); db().prepare("UPDATE masterpieces SET image = ? WHERE id = ?").run(NO_IMAGE, row.id);
} }
for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, likes FROM masterpieces").all()) { for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, reviewed_at, reviewed_by, likes, hash FROM masterpieces").all()) {
known.set(row.id, {id: row.id, creator: row.creator_id, createdAt: row.created_at, status: row.status, frame: row.frame, likes: JSON.parse(row.likes)}); known.set(row.id, {id: row.id, creator: row.creator_id, createdAt: row.created_at, status: row.status, frame: row.frame,
reviewedAt: row.reviewed_at, reviewedBy: row.reviewed_by, likes: JSON.parse(row.likes), hash: row.hash || null});
} }
for (const row of db().prepare("SELECT hash, thumb FROM masterpiece_approved_pictures").all()) {
approvedPictures.set(row.hash, row.thumb ? Buffer.from(row.thumb) : null);
}
backfill();
};
const hashOf = image => crypto.createHash("sha256").update(image).digest("hex");
const printOf = painting => {
const row = db().prepare("SELECT fingerprint FROM masterpieces WHERE id = ?").get(painting.id);
return row && row.fingerprint ? Buffer.from(row.fingerprint) : null;
};
// the approved pictures (their hashes) that this picture is: the same file,
// or the same painting by its fingerprint.
const approvedMatches = (hash, print) => {
const found = approvedPictures.has(hash) ? [hash] : [];
if (print) {
const thumb = jpegPrint.thumbnail(print);
for (const [other, otherThumb] of approvedPictures) {
if (other !== hash && otherThumb && jpegPrint.thumbnailsClose(thumb, otherThumb)) {
const row = db().prepare("SELECT fingerprint FROM masterpiece_approved_pictures WHERE hash = ?").get(other);
if (row && row.fingerprint && jpegPrint.samePicture(print, Buffer.from(row.fingerprint))) {
found.push(other);
}
}
}
}
return found;
};
const pictureApproved = (hash, print) => Boolean(hash) && approvedMatches(hash, print).length > 0;
const notePictureApproved = (painting, print) => {
const thumb = print ? jpegPrint.thumbnail(print) : null;
db().prepare("INSERT OR IGNORE INTO masterpiece_approved_pictures (hash, approved_at, approved_by, fingerprint, thumb) VALUES (?, ?, ?, ?, ?)")
.run(painting.hash, painting.reviewedAt || now(), painting.reviewedBy, print, thumb);
if (!approvedPictures.has(painting.hash)) {
approvedPictures.set(painting.hash, thumb);
}
};
// paintings from before pictures were known again get their hash and
// fingerprint, a few at a time after start (each is a file read and some
// milliseconds of decoding, on the thread the game shares); those a person
// approved make their pictures approved ones.
const BACKFILL_BATCH = 20;
const backfill = () => {
const missing = db().prepare("SELECT id FROM masterpieces WHERE fingerprint IS NULL OR hash IS NULL").all().map(row => row.id);
const notedAgain = db().prepare("SELECT hash FROM masterpiece_approved_pictures WHERE fingerprint IS NULL").all().map(row => row.hash);
const step = () => {
for (const id of missing.splice(0, BACKFILL_BATCH)) {
const painting = known.get(id);
let image = null;
try {
image = painting ? fs.readFileSync(fileOf(id)) : null;
}
catch (err) {
image = null;
}
if (!image) {
continue;
}
painting.hash = hashOf(image);
const print = jpegPrint.fingerprint(image);
db().prepare("UPDATE masterpieces SET hash = ?, fingerprint = ? WHERE id = ?").run(painting.hash, print, id);
if (painting.status === APPROVED && painting.reviewedBy && painting.reviewedBy !== AUTO_APPROVER) {
notePictureApproved(painting, print);
}
}
// pictures approved before fingerprints were kept: from a painting of
// theirs, once every painting has its own
for (const hash of missing.length ? [] : notedAgain.splice(0, BACKFILL_BATCH)) {
const row = db().prepare("SELECT fingerprint FROM masterpieces WHERE hash = ? AND fingerprint IS NOT NULL").get(hash);
if (row) {
const print = Buffer.from(row.fingerprint);
const thumb = jpegPrint.thumbnail(print);
db().prepare("UPDATE masterpiece_approved_pictures SET fingerprint = ?, thumb = ? WHERE hash = ?").run(print, thumb, hash);
approvedPictures.set(hash, thumb);
}
}
if (missing.length || notedAgain.length) {
setTimeout(step, 200).unref();
}
};
if (missing.length || notedAgain.length) {
setTimeout(step, 1000).unref();
}
};
// why this account may not paint for a frame now, as words for the player,
// or null when it may: too new an account (asked at the easel, step 1), or
// as many new pictures in the last 24 hours as a day allows (asked of a
// picture not approved before, step 2). `whenFree` speaks of the wait.
const whenFree = seconds => {
const hours = Math.ceil(seconds / 3600);
return hours > 1 ? `in ${hours} hours` : `in ${Math.max(1, Math.ceil(seconds / 60))} minutes`;
};
const tooNew = account => {
const age = now() - (Number(account.createdAt) || 0);
if (age < config.masterpieceMinAccountAge) {
return `Accounts can make Masterpieces once they are a day old. Try again ${whenFree(config.masterpieceMinAccountAge - age)}.`;
}
return null;
};
const tooMany = account => {
const recent = db().prepare("SELECT created_at FROM masterpiece_uploads WHERE creator_id = ? AND created_at > ? ORDER BY created_at")
.all(account.id, now() - DAY);
const perDay = config.masterpiecesPerDay;
if (recent.length >= perDay) {
return `You can make ${perDay} new Masterpieces a day. Try again ${whenFree(recent[recent.length - perDay].created_at + DAY - now())}.`;
}
return null;
}; };
const needsReview = () => accounts.setting(REVIEW_SETTING) !== "0"; const needsReview = () => accounts.setting(REVIEW_SETTING) !== "0";
const setNeedsReview = on => accounts.setSetting(REVIEW_SETTING, on ? "1" : "0"); const setNeedsReview = on => accounts.setSetting(REVIEW_SETTING, on ? "1" : "0");
const forget = id => { // `unapprove`: it was taken back by staff, so its picture is no longer one
// approved before (a painting thrown away unframed leaves it alone).
const forget = (id, unapprove = false) => {
const painting = known.get(id);
if (unapprove && painting && painting.hash) {
for (const hash of approvedMatches(painting.hash, printOf(painting))) {
db().prepare("DELETE FROM masterpiece_approved_pictures WHERE hash = ?").run(hash);
approvedPictures.delete(hash);
}
}
known.delete(id); known.delete(id);
db().prepare("DELETE FROM masterpieces WHERE id = ?").run(id); db().prepare("DELETE FROM masterpieces WHERE id = ?").run(id);
fs.rmSync(fileOf(id), {force: true}); fs.rmSync(fileOf(id), {force: true});
@@ -119,6 +282,7 @@ const sweep = () => {
forget(painting.id); forget(painting.id);
} }
} }
db().prepare("DELETE FROM masterpiece_uploads WHERE created_at <= ?").run(now() - DAY);
}; };
setInterval(() => { setInterval(() => {
try { try {
@@ -129,8 +293,12 @@ setInterval(() => {
} }
}, 600000).unref(); }, 600000).unref();
// A token for one upload by this account (step 1). // A token for one upload by this account (step 1), or null when it is
// `tooNew`, which says why.
const issueToken = account => { const issueToken = account => {
if (tooNew(account)) {
return null;
}
for (const [token, entry] of tokens) { for (const [token, entry] of tokens) {
if (entry.account === account.id) { if (entry.account === account.id) {
tokens.delete(token); tokens.delete(token);
@@ -182,20 +350,33 @@ const looksLikeJpeg = image => {
return false; return false;
}; };
// step 2. resolves to the new painting's id, or null when the token is not // step 2. resolves to {uuid}, the new painting's id, or {uuid: null} when
// good, the picture is not a JPEG of a sane size, or the account has posted // the token is not good, the picture is not a JPEG of a sane size, or the
// too many. // account has posted too many; with `refusal` and `maker` when the player
// should be told why.
const upload = async (token, image) => { const upload = async (token, image) => {
const entry = typeof token === "string" ? tokens.get(token) : null; const entry = typeof token === "string" ? tokens.get(token) : null;
tokens.delete(token); tokens.delete(token);
if (!entry || entry.expires < Date.now() || !Buffer.isBuffer(image) || image.length > MAX_IMAGE_BYTES || !looksLikeJpeg(image) if (!entry || entry.expires < Date.now() || !Buffer.isBuffer(image) || image.length > MAX_IMAGE_BYTES || !looksLikeJpeg(image)
|| !uploadsPerHour.allow(entry.account)) { || !uploadsPerHour.allow(entry.account)) {
return null; return {uuid: null};
}
// a picture approved before is not a new one and does not count
const hash = hashOf(image);
const print = jpegPrint.fingerprint(image);
const approvedBefore = pictureApproved(hash, print);
const maker = accounts.byId(entry.account);
const refusal = maker && !approvedBefore ? tooNew(maker) || tooMany(maker) : null;
if (!maker || refusal) {
return {uuid: null, refusal, maker};
} }
const safety = await imageModeration.scan(image); const safety = await imageModeration.scan(image);
if (safety.blocked) { if (safety.blocked) {
console.log(`[masterpieces] rejected unsafe upload from account ${entry.account}`); 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. // one painting at a time is between the easel and the frame.
for (const painting of [...known.values()]) { for (const painting of [...known.values()]) {
@@ -203,18 +384,21 @@ const upload = async (token, image) => {
forget(painting.id); forget(painting.id);
} }
} }
const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, likes: []}; const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, reviewedAt: null, reviewedBy: null, likes: [], hash};
fs.writeFileSync(fileOf(painting.id), image); fs.writeFileSync(fileOf(painting.id), image);
db().prepare("INSERT INTO masterpieces (id, creator_id, created_at, status, frame, likes, image) VALUES (?, ?, ?, ?, ?, '[]', ?)") db().prepare("INSERT INTO masterpieces (id, creator_id, created_at, status, frame, likes, image, hash, fingerprint) VALUES (?, ?, ?, ?, ?, '[]', ?, ?, ?)")
.run(painting.id, painting.creator, painting.createdAt, painting.status, painting.frame, NO_IMAGE); .run(painting.id, painting.creator, painting.createdAt, painting.status, painting.frame, NO_IMAGE, hash, print);
known.set(painting.id, painting); known.set(painting.id, painting);
return painting.id; return {uuid: painting.id};
}; };
const setStatus = (painting, status) => { // `by`: who approved it, when someone did.
const setStatus = (painting, status, by = null) => {
painting.status = status; painting.status = status;
db().prepare("UPDATE masterpieces SET status = ?, frame = ?, reviewed_at = ? WHERE id = ?") painting.reviewedAt = status === APPROVED ? now() : null;
.run(status, painting.frame, status === APPROVED ? now() : null, painting.id); painting.reviewedBy = status === APPROVED ? by : null;
db().prepare("UPDATE masterpieces SET status = ?, frame = ?, reviewed_at = ?, reviewed_by = ? WHERE id = ?")
.run(status, painting.frame, painting.reviewedAt, painting.reviewedBy, painting.id);
}; };
// may this account make an item of that painting, in that frame? (Step 3, // may this account make an item of that painting, in that frame? (Step 3,
@@ -229,11 +413,19 @@ const claimable = (account, id, frame) => {
}; };
// step 3, paid for: the painting is an item now. true when it is approved // step 3, paid for: the painting is an item now. true when it is approved
// on the spot. // on the spot: review is off, or its picture was approved before.
const claim = (id, frame) => { const claim = (id, frame) => {
const painting = known.get(String(id)); const painting = known.get(String(id));
painting.frame = frame; painting.frame = frame;
setStatus(painting, needsReview() ? PENDING : APPROVED); if (!needsReview()) {
setStatus(painting, APPROVED);
}
else if (pictureApproved(painting.hash, printOf(painting))) {
setStatus(painting, APPROVED, AUTO_APPROVER);
}
else {
setStatus(painting, PENDING);
}
return painting.status === APPROVED; return painting.status === APPROVED;
}; };
@@ -268,13 +460,26 @@ const mayView = (id, address, addressOf) => {
return painting.status === APPROVED || Boolean(maker && addressOf(maker) && addressOf(maker) === address); return painting.status === APPROVED || Boolean(maker && addressOf(maker) && addressOf(maker) === address);
}; };
const approve = id => { // `by`: the moderator's username, or "admin". its picture is approved from
// now on, and the same picture waiting in other paintings is approved with
// it. the paintings approved, none when `id` was not waiting.
const approve = (id, by) => {
const painting = get(id); const painting = get(id);
if (!painting || painting.status !== PENDING) { if (!painting || painting.status !== PENDING) {
return false; return [];
} }
setStatus(painting, APPROVED); setStatus(painting, APPROVED, by);
return true; if (!painting.hash) {
return [painting];
}
const print = printOf(painting);
notePictureApproved(painting, print);
const twins = [...known.values()].filter(other => other.status === PENDING
&& (other.hash === painting.hash || (print && jpegPrint.samePicture(print, printOf(other)))));
for (const twin of twins) {
setStatus(twin, APPROVED, AUTO_APPROVER);
}
return [painting, ...twins];
}; };
// is a den item fit to be shown, traded and recycled? anything that is not // is a den item fit to be shown, traded and recycled? anything that is not
@@ -318,11 +523,14 @@ const gallery = () => {
return {pool: hung.slice(0, GALLERY_SPOTS), pluspool: hung.slice(GALLERY_SPOTS)}; return {pool: hung.slice(0, GALLERY_SPOTS), pluspool: hung.slice(GALLERY_SPOTS)};
}; };
// newest first: the waiting ones by when they were made, the approved ones
// by when they were approved, so that one let in by mistake is near the top.
const list = status => [...known.values()].filter(painting => painting.status === status) const list = status => [...known.values()].filter(painting => painting.status === status)
.sort((one, other) => other.createdAt - one.createdAt) .sort((one, other) => (other.reviewedAt || other.createdAt) - (one.reviewedAt || one.createdAt))
.map(painting => { .map(painting => {
const maker = creatorOf(painting.id); const maker = creatorOf(painting.id);
return {id: painting.id, creator: maker ? maker.username : "(deleted account)", createdAt: painting.createdAt, frame: painting.frame, likes: painting.likes.length}; return {id: painting.id, creator: maker ? maker.username : "(deleted account)", createdAt: painting.createdAt, frame: painting.frame, likes: painting.likes.length,
approvedAt: painting.reviewedAt, approvedBy: painting.reviewedBy};
}); });
// both lists for the panels, narrowed to makers whose names have // both lists for the panels, narrowed to makers whose names have
@@ -335,6 +543,11 @@ const listsFor = creator => {
return {waiting: narrowed(list(PENDING)), approved: narrowed(list(APPROVED))}; return {waiting: narrowed(list(PENDING)), approved: narrowed(list(APPROVED))};
}; };
// the last `count` approved, the latest first, for the moderator panel to
// take one back from: only the ones `by` approved, when given.
const recentlyApproved = (count, by = "") => list(APPROVED)
.filter(painting => !by || String(painting.approvedBy || "").toLowerCase() === by.toLowerCase()).slice(0, count);
const madeBy = account => [...known.values()].filter(painting => painting.creator === account.id).map(painting => painting.id); const madeBy = account => [...known.values()].filter(painting => painting.creator === account.id).map(painting => painting.id);
// generic lists: (mediaId, name string id) pairs, or null when `listId` is // generic lists: (mediaId, name string id) pairs, or null when `listId` is
@@ -343,7 +556,7 @@ const frameList = listId =>
([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null); ([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null);
module.exports = { module.exports = {
load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, frameList, load, issueToken, tooNew, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, recentlyApproved, frameList,
needsReview, setNeedsReview, madeBy, needsReview, setNeedsReview, madeBy,
PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES, PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES,
}; };
+209 -19
View File
@@ -6,6 +6,7 @@ const defpacks = require("./defpacks.js");
const buddyGames = require("./buddygames.js"); const buddyGames = require("./buddygames.js");
const masterpieces = require("./masterpieces.js"); const masterpieces = require("./masterpieces.js");
const dens = require("./dens.js"); const dens = require("./dens.js");
const customItems = require("./customitems.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const {activeAvatar, addClothing, sendClothingAdded} = require("./player.js"); const {activeAvatar, addClothing, sendClothingAdded} = require("./player.js");
@@ -16,10 +17,14 @@ const {activeAvatar, addClothing, sendClothingAdded} = require("./player.js");
// game: the room it runs in, the start signal, gem awards, and for some // game: the room it runs in, the start signal, gem awards, and for some
// games a few messages of their own. // games a few messages of their own.
// //
// lib/games.json is that table, put back together from what still names the // lib/games.json is that table, as a recording of the official game has it
// ids: arcade-machine den items (gameDefId and a name), the room files (which // (its "mi" reply, made with tools/recorder.js): which class each id runs,
// id stands where), the names GameCardPopup has for each game class, and the // in a window or in the room's place, its user vars and its pictures. it
// achievement defs (which user vars a game counts in). entries: // was first put back together from what still names the ids (arcade-machine
// den items, the room files, GameCardPopup's names, the achievement defs),
// which had some ids wrong: the print kits, the carnival games (run in the
// room, not in its place), Brady's lab, and the buddy games, given ids of
// other games' as nothing then named theirs. entries:
// id game def id // id game def id
// swf the game's key in game.IncludeMinigames // swf the game's key in game.IncludeMinigames
// title its name; sent as the id of the localization string that says so // title its name; sent as the id of the localization string that says so
@@ -32,16 +37,16 @@ const {activeAvatar, addClothing, sendClothingAdded} = require("./player.js");
// icon media id of its picture in the HUD's Games window; the games with // icon media id of its picture in the HUD's Games window; the games with
// one are the ones that window lists // one are the ones that window lists
// buddy true: one of the eight games two players play from a player's // buddy true: one of the eight games two players play from a player's
// card (lib/buddygames.js). their ids are ours: nothing in the // card (lib/buddygames.js)
// client names them, and the official table is gone. // card the game's title picture on its "Play!" popup; a buddy game's
// card a buddy game's picture, on the card's game tab and in the // in the invitation
// invitation
// //
// every other game is played alone (minPlayers = maxPlayers = 1): the // every other game is played alone (minPlayers = maxPlayers = 1): the
// multiplayer ones each have a protocol of their own between the players. // multiplayer ones each have a protocol of their own between the players.
const games = new Map(require("./games.json").map(game => [game.id, game])); const games = new Map(require("./games.json").map(game => [game.id, game]));
const GAME_AFTERGLOW_MS = 15000; // how long a game's room id is still taken after leaving it (leave)
const IN_ROOM = 0; const IN_ROOM = 0;
const MAX_GEMS_PER_AWARD = 5000; const MAX_GEMS_PER_AWARD = 5000;
const MAX_MASTERY_PER_AWARD = 100; const MAX_MASTERY_PER_AWARD = 100;
@@ -63,6 +68,10 @@ const CARNIVAL_COST = 5; // gems a go
const MAX_TICKETS_PER_GO = 300; const MAX_TICKETS_PER_GO = 300;
const CURRENCY_TICKETS = 1; const CURRENCY_TICKETS = 1;
const INVASION_COST = 10; // gems a go, as the machine's own screen says const INVASION_COST = 10; // gems a go, as the machine's own screen says
const SMOOTHIE_COLOURS = new Set(["purple", "orange", "red", "yellow"]);
// The game's attachment state is client-defined (for example, the cocoa
// recipe). It is not an item id and must never become protocol markup.
const attachmentExtra = value => String(value ?? "").replace(/[\r\n%,]/g, "").slice(0, 128);
const awardsPerMinute = limits.limiter(120, 60000); const awardsPerMinute = limits.limiter(120, 60000);
const invitesPerMinute = limits.limiter(20, 60000); const invitesPerMinute = limits.limiter(20, 60000);
@@ -79,7 +88,16 @@ const START = {
// which player is its own by the id (GemBreakerPlayer.init), and only // which player is its own by the id (GemBreakerPlayer.init), and only
// that one aims and shoots. // that one aims and shoots.
seedAndPlayers: game => [serial(), game.players.length, ...game.players.flatMap(player => [player.id, 0])], seedAndPlayers: game => [serial(), game.players.length, ...game.players.flatMap(player => [player.id, 0])],
// Spider Zapper and Wind Rider (SpiderShooterPlayer.init,
// ParachuteGliderPlayer.init): each player's sfs id and where it starts.
// given only the seed they had no players, none of them their own:
// nothing could be shot, and nobody glided.
seedAndCrosshairs: game => [serial(), game.players.length,
...game.players.flatMap((player, at) => [player.id, CROSSHAIR_X + at * CROSSHAIR_GAP, CROSSHAIR_Y])],
}; };
const CROSSHAIR_X = 400;
const CROSSHAIR_GAP = 100;
const CROSSHAIR_Y = 300;
// the room games several players play together: "Multiplayer" on the // the room games several players play together: "Multiplayer" on the
// game's waiting list (MinigameManager.setupWaitListPopup), for players in // game's waiting list (MinigameManager.setupWaitListPopup), for players in
@@ -103,7 +121,7 @@ function serial() {
let nextGameRoomId = 500000; // well clear of the world's room ids let nextGameRoomId = 500000; // well clear of the world's room ids
module.exports = ({tell, leaveRoom, findOnline, blocks}) => { module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => {
// MinigameInfo.init, the 19 fields the "mi" reply carries for a game. // MinigameInfo.init, the 19 fields the "mi" reply carries for a game.
const info = game => [ const info = game => [
game.id, game.id,
@@ -117,8 +135,8 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
game.buddy ? 2 : MULTIPLAYER[game.swf] ? MULTIPLAYER[game.swf].max : 1, game.buddy ? 2 : MULTIPLAYER[game.swf] ? MULTIPLAYER[game.swf].max : 1,
0, // max spectators 0, // max spectators
game.type, game.type,
// the game card: the title picture on the "play" popup (not known), and // the game card: the title picture on the "play" popup, and for a buddy
// for a buddy game the picture in the invitation. // game the picture in the invitation.
game.card || 0, game.card || 0,
...(game.vars || [0, 0, 0]), ...(game.vars || [0, 0, 0]),
game.buddy ? 1 : 0, // ready for player-versus-player: listed on players' cards game.buddy ? 1 : 0, // ready for player-versus-player: listed on players' cards
@@ -145,6 +163,82 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
} }
}; };
// A buddy game's bubble over a player's head, which anyone else in the
// room can click to play them (UserCommXtCommManager.sendCustomPVPMessage:
// a chat line "on|off" of type 12 with the game's id after it). the client
// reads it back as "on|<gameDefId>" or "off", and its sender waits for
// their own before going on. `session.pvpBubble` is the game's id.
const BUBBLE = "12";
const bubbleLine = session => [`on|${session.pvpBubble}`, BUBBLE, 0];
const bubbleSeers = session => watchers(session).filter(other => !blocks.either(other.account, session.account));
// the bubble goes for everyone else. the player's own "off" waits, when
// they are in a game, till they are out of it: it would end the game the
// client has only just set up (MinigameManager.readySelfForPvpGame).
const dropBubble = session => {
if (!session.pvpBubble) {
return;
}
session.pvpBubble = null;
if (session.room) {
for (const other of bubbleSeers(session)) {
other.sendXt("uc", session.room.id, session.id, "off", BUBBLE);
}
}
};
const bubbleOff = session => {
if (session.game) {
session.bubbleOffOwed = true;
}
else if (session.room) {
session.bubbleOffOwed = false;
session.sendXt("uc", session.room.id, session.id, "off", BUBBLE);
}
};
const bubble = (session, word, gameDefId) => {
if (word !== "on") {
dropBubble(session);
bubbleOff(session);
return;
}
const def = games.get(Number(gameDefId));
if (!def || !def.buddy || !Object.hasOwn(buddyGames, def.swf) || !session.room || session.game || session.invite
|| session.invisible || !accounts.featureOn(session.account, "gameInvites")) {
if (session.room && !session.game) {
tell(session, session.invisible ? "Nobody can see you to play with you." : "You cannot ask for a game right now.");
}
dropBubble(session);
bubbleOff(session);
return;
}
session.pvpBubble = def.id;
for (const other of [session, ...bubbleSeers(session)]) {
other.sendXt("uc", session.room.id, session.id, ...bubbleLine(session));
}
};
// a bubble that is up, for a player who has just been shown its owner.
const showBubble = (to, owner) => {
if (owner.pvpBubble && owner.room && to !== owner && !blocks.either(to.account, owner.account)) {
to.sendXt("uc", owner.room.id, owner.id, ...bubbleLine(owner));
}
};
// Food-machine games reward a short-lived avatar attachment. Replying
// with "_a" is important: MinigameManager turns it into the same local
// attachment action used by den objects, which then sends the normal
// user-communication packet to the room. Sending that packet ourselves
// skips the local state and leaves the player with nothing visible.
const grantAttachment = (session, game, reply, emoticonDefId, extra = "") => {
if (game.attachmentGranted) {
return;
}
const state = attachmentExtra(extra);
if (!defpacks.emoticonMediaId(emoticonDefId)) {
return;
}
game.attachmentGranted = true;
reply("_a", emoticonDefId, state);
};
// takes the player out of the game they are in, if any, and out of an // takes the player out of the game they are in, if any, and out of an
// invitation. // invitation.
const leave = session => { const leave = session => {
@@ -154,6 +248,13 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
return; return;
} }
session.game = null; session.game = null;
// an in-room game may say it is done just before it hands over what it
// made (the Juice Bar's smoothie, the Cocoa Hut's drink: an attachment,
// lib/world.js pubMsg), labelled with the game's room
session.lastGame = {roomId: game.roomId, until: Date.now() + GAME_AFTERGLOW_MS};
if (session.bubbleOffOwed) {
bubbleOff(session);
}
game.players = game.players.filter(player => player !== session); game.players = game.players.filter(player => player !== session);
if (game.lobby) { if (game.lobby) {
if (game.players.length === 0) { if (game.players.length === 0) {
@@ -208,6 +309,11 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
// minigamePetMastery) and who is in the game (joinGameResponse). // minigamePetMastery) and who is in the game (joinGameResponse).
const seat = (session, game, music) => { const seat = (session, game, music) => {
const avatar = activeAvatar(session.account); const avatar = activeAvatar(session.account);
// off to a game: a bubble still up goes (and its owner is told after).
if (session.pvpBubble) {
dropBubble(session);
session.bubbleOffOwed = true;
}
session.game = game; session.game = game;
session.sendXt("rj", -1, 1, `game${game.def.id}_${game.roomId}`, game.roomId, game.players.length, game.players.length, 0, 0, session.sendXt("rj", -1, 1, `game${game.def.id}_${game.roomId}`, game.roomId, game.players.length, game.players.length, 0, 0,
0, 1, 0, 1, game.def.type === IN_ROOM ? 1 : 0, // isPrivate, isGame, isLimbo, isTemp, isSubRoom 0, 1, 0, 1, game.def.type === IN_ROOM ? 1 : 0, // isPrivate, isGame, isLimbo, isTemp, isSubRoom
@@ -320,8 +426,12 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
// den items a claw machine can drop: the plushies, of the machine's own // den items a claw machine can drop: the plushies, of the machine's own
// animal when it is named for one ("The Wolf Claw"). // animal when it is named for one ("The Wolf Claw").
let plushies = null; let plushies = null;
// the game's own den items only: a custom item (and a player's own, which
// is nobody else's to win) may be missing from the winner's game, whose
// prize popup then threw (DenItem.initShopItem) and left the game frozen.
const gameOwnDenItemIds = () => defpacks.denItemIds().filter(id => id < customItems.FIRST_ID);
const clawPrizes = game => { const clawPrizes = game => {
plushies = plushies || defpacks.denItemIds().filter(id => /plush/i.test(defpacks.denItemDef(id).abbrName)); plushies = plushies || gameOwnDenItemIds().filter(id => /plush/i.test(defpacks.denItemDef(id).abbrName));
const item = defpacks.denItemIds().map(id => defpacks.denItemDef(id)).find(def => Number(def.gameDefId) === game.id); const item = defpacks.denItemIds().map(id => defpacks.denItemDef(id)).find(def => Number(def.gameDefId) === game.id);
const animal = item ? /^ArcCraneGame(.+)$/.exec(item.abbrName) : null; const animal = item ? /^ArcCraneGame(.+)$/.exec(item.abbrName) : null;
const own = animal ? plushies.filter(id => defpacks.denItemDef(id).abbrName.toLowerCase().includes(animal[1].toLowerCase())) : []; const own = animal ? plushies.filter(id => defpacks.denItemDef(id).abbrName.toLowerCase().includes(animal[1].toLowerCase())) : [];
@@ -332,7 +442,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
// machines aside. // machines aside.
let phantomItems = null; let phantomItems = null;
const invasionPrizes = () => { const invasionPrizes = () => {
phantomItems = phantomItems || defpacks.denItemIds().filter(id => /phantom/i.test(defpacks.denItemDef(id).abbrName) phantomItems = phantomItems || gameOwnDenItemIds().filter(id => /phantom/i.test(defpacks.denItemDef(id).abbrName)
&& !/^Arc/.test(defpacks.denItemDef(id).abbrName) && defpacks.string(defpacks.denItemDef(id).nameStrId)); && !/^Arc/.test(defpacks.denItemDef(id).abbrName) && defpacks.string(defpacks.denItemDef(id).nameStrId));
return phantomItems.length ? phantomItems : defpacks.denItemIds().slice(0, 1); return phantomItems.length ? phantomItems : defpacks.denItemIds().slice(0, 1);
}; };
@@ -376,13 +486,59 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
}, },
}; };
// refused to an account under a day old: the game shows its "could not
// send" popup, and a plain message box ("xtl") says why.
const uploadToken = (session, game, [, purpose], reply) => { const uploadToken = (session, game, [, purpose], reply) => {
reply("tkn", 1, 0, masterpieces.issueToken(session.account), 0, purpose === undefined ? 1 : Number(purpose) || 1); const token = masterpieces.issueToken(session.account);
if (!token) {
const why = masterpieces.tooNew(session.account) || "Your Masterpiece could not be sent. Try again later.";
session.sendXt("xtl", -1, why.replace(/%/g, " percent"));
}
reply("tkn", token ? 1 : 0, 0, token || "", 0, purpose === undefined ? 1 : Number(purpose) || 1);
}; };
// what a game asks of the server while it runs, by game class and then by // what a game asks of the server while it runs, by game class and then by
// the message's first word. `reply` answers the asker as an "mm". // the message's first word. `reply` answers the asker as an "mm".
const MESSAGES = { const MESSAGES = {
// These machines do not give an inventory item. They award temporary
// Holdable Icons: popcorn (emoticon 1), smoothies (2), and hot cocoa
// (5). The final field carries the selected visual state.
MicroPopcorn: {
_a(session, game, [kind], reply) {
if (kind === "1") {
grantAttachment(session, game, reply, 1);
}
},
},
MicroSmoothie: {
_a(session, game, [kind, colour], reply) {
const selected = String(colour || "").toLowerCase();
if (kind === "2" && SMOOTHIE_COLOURS.has(selected)) {
grantAttachment(session, game, reply, 2, selected);
}
},
},
MicroHotCocoa: {
_a(session, game, [kind, cocoaInfo], reply) {
if (kind === "5") {
grantAttachment(session, game, reply, 5, cocoaInfo);
}
},
},
CottonCandy: {
_a(session, game, [kind, emoticonInfo], reply) {
if (kind === "30") {
grantAttachment(session, game, reply, 30, emoticonInfo);
}
},
},
BradyChemistrySet: {
_a(session, game, [kind, emoticonInfo], reply) {
if (kind === "6") {
grantAttachment(session, game, reply, 6, emoticonInfo);
}
},
},
// the claw machines: "cp" pays for a go and learns whether the claw // the claw machines: "cp" pays for a go and learns whether the claw
// will hold and what on ([won, isDenItem, defId, ?, version]; anything // will hold and what on ([won, isDenItem, defId, ?, version]; anything
// but 1 or 0 for `won` means "not enough gems"); "cd" keeps (1) or // but 1 or 0 for `won` means "not enough gems"); "cd" keeps (1) or
@@ -416,7 +572,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
WindRider: { WindRider: {
go() {}, go() {},
gw(session, game, params, reply) { gw(session, game, params, reply) {
const ids = defpacks.clothingIds(); const ids = defpacks.clothingIds().filter(id => id < customItems.FIRST_ID);
const def = Math.random() < SKY_HIGH_PRIZE_CHANCE ? defpacks.itemDef(ids[Math.floor(Math.random() * ids.length)]) : null; const def = Math.random() < SKY_HIGH_PRIZE_CHANCE ? defpacks.itemDef(ids[Math.floor(Math.random() * ids.length)]) : null;
session.gamePrize = def ? {def: Number(def.id), color: Number(String(def.colors).split(",")[0])} : null; session.gamePrize = def ? {def: Number(def.id), color: Number(String(def.colors).split(",")[0])} : null;
reply("gw", def ? "1" : "0", def ? def.id : 0, 0, def ? session.gamePrize.color : 0); reply("gw", def ? "1" : "0", def ? def.id : 0, 0, def ? session.gamePrize.color : 0);
@@ -454,6 +610,18 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
}, },
// the touch pool: the same again, with six prizes; which one is in the // the touch pool: the same again, with six prizes; which one is in the
// first number. // first number.
// Spider Zapper, after each wave: "wave" [1 if the player shot enough,
// else 0] -> "wavesuccess" (the next wave) or "wavefail" (the end), and
// "waveend" [spiders shot] -> "waveend" [spiders shot] (its results).
// they went unanswered and the game waited after the first wave.
SpiderShooter: {
wave(session, game, [passed], reply) {
reply(passed === "1" ? "wavesuccess" : "wavefail");
},
waveend(session, game, [shot], reply) {
reply("waveend", /^\d{1,4}$/.test(String(shot)) ? Number(shot) : 0);
},
},
TouchPool: { TouchPool: {
ts(session, game, params, reply) { ts(session, game, params, reply) {
session.prizeSerial = serial(); session.prizeSerial = serial();
@@ -683,13 +851,29 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
session.invite = target.invite = {def, sender: session, target}; session.invite = target.invite = {def, sender: session, target};
target.sendXt("mp", -1, def.id, 0, session.account.username, 1); target.sendXt("mp", -1, def.id, 0, session.account.username, 1);
}, },
// an open challenge to whoever walks up (UserCommXtCommManager.sendCustomPVPMessage); not offered. // a click on another player's game bubble (MinigameXtCommManager
mcp() {}, // .sendMinigameCustomPvpJoinMsg): [gameDefId, 0, their username]. the
// game starts at once, as an invitation said yes to; a bubble that is
// gone by now is answered as an invitation said no to
// (MinigameManager.pvpResponse), which puts the clicker back as they were.
mcp(session, roomId, [gameDefId, , username]) {
const def = games.get(Number(gameDefId));
const host = findOnline(String(username || ""));
const free = player => player && player.room && !player.game && !player.invite;
if (!def || !host || host === session || host.pvpBubble !== def.id || host.room !== session.room
|| !free(session) || !free(host) || blocks.either(session.account, host.account)
|| !accounts.featureOn(session.account, "gameInvites")) {
session.sendXt("mp", -1, def ? def.id : Number(gameDefId) || 0, 1);
return;
}
startMatch(def, host, session);
},
}; };
// the HUD's Games window (GameJoinPopup, generic list 341): the playable // the HUD's Games window (GameJoinPopup, generic list 341): the playable
// games that have a picture for it, by name. // games that have a picture for it, by name. A buddy game's card picture
const library = [...games.values()].filter(game => game.icon && game.ready !== false) // is drawn the same way, and picking one there puts its bubble up.
const library = [...games.values()].filter(game => (game.icon || (game.buddy && game.card)) && game.ready !== false)
.sort((one, other) => one.title.localeCompare(other.title)).map(game => game.id); .sort((one, other) => one.title.localeCompare(other.title)).map(game => game.id);
// the buddy games' descriptions, sent unasked when a player arrives: a // the buddy games' descriptions, sent unasked when a player arrives: a
@@ -704,6 +888,12 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
handlers, handlers,
leave, leave,
greet, greet,
bubble,
showBubble,
// out of the room: nobody there is left to see the bubble.
roomLeft: session => {
session.pvpBubble = null;
},
library: () => library, library: () => library,
// the room a player in a room-replacing game came from, for the panel. // the room a player in a room-replacing game came from, for the panel.
playing: session => (session.game ? session.game.def.title : null), playing: session => (session.game ? session.game.def.title : null),
+28
View File
@@ -183,6 +183,34 @@ module.exports = ({findOnline}) => {
return true; return true;
}, },
// every post they wrote on anyone's Jammer Wall (lib/walls.js), their
// own included, and the replies to those, as deleting a post in the game
// takes its replies. returns {posts, replies, walls}.
clearWallPosts(author) {
const changed = [];
let posts = 0;
let replies = 0;
for (const owner of accounts.all()) {
const {wall} = owner;
const gone = new Set(wall.posts.filter(post => post.uid === author.id).map(post => post.x));
if (!gone.size) {
continue;
}
const kept = wall.posts.filter(post => !gone.has(post.x) && !gone.has(post.pp));
posts += gone.size;
replies += wall.posts.length - kept.length - gone.size;
const left = new Set(kept.map(post => post.x));
wall.posts = kept;
wall.hidden = wall.hidden.filter(id => left.has(id));
wall.modified = Date.now();
changed.push(owner);
}
if (changed.length) {
accounts.save(...changed);
}
return {posts, replies, walls: changed.length};
},
grantGems(target, amount) { grantGems(target, amount) {
return actions.grantCurrency(target, CURRENCY_GEMS, amount, false); return actions.grantCurrency(target, CURRENCY_GEMS, amount, false);
}, },
+20 -2
View File
@@ -18,13 +18,23 @@ const SCHEMA = `
`; `;
const MAX_DETAIL = 400; const MAX_DETAIL = 400;
const SHOWN = 300; const SHOWN = 300;
const listeners = new Set();
const load = () => accounts.database().exec(SCHEMA); const load = () => accounts.database().exec(SCHEMA);
const record = (by, action, target = "", detail = "") => { const record = (by, action, target = "", detail = "") => {
const entry = {at: Math.floor(Date.now() / 1000), by: String(by), action: String(action), target: String(target), detail: String(detail).slice(0, MAX_DETAIL)};
accounts.database().prepare("INSERT INTO mod_log (at, by, action, target, detail) VALUES (?, ?, ?, ?, ?)") accounts.database().prepare("INSERT INTO mod_log (at, by, action, target, detail) VALUES (?, ?, ?, ?, ?)")
.run(Math.floor(Date.now() / 1000), by, action, String(target), String(detail).slice(0, MAX_DETAIL)); .run(entry.at, entry.by, entry.action, entry.target, entry.detail);
console.log(`[mod] ${logText(by)}: ${logText(action)}${logText(target ? ` "${target}"` : "")}`); console.log(`[mod] ${logText(by)}: ${logText(action)}${logText(target ? ` "${target}"` : "")}`);
for (const listener of listeners) {
try {
listener(entry);
}
catch (err) {
console.error(`[modlog] listener failed: ${logText(err.message)}`);
}
}
}; };
const recent = () => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log ORDER BY id DESC LIMIT ?").all(SHOWN); const recent = () => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log ORDER BY id DESC LIMIT ?").all(SHOWN);
@@ -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") 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)); .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};
+500 -18
View File
@@ -1,6 +1,7 @@
"use strict"; "use strict";
const crypto = require("crypto"); const crypto = require("crypto");
const {execFileSync} = require("child_process");
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
@@ -15,6 +16,7 @@ const itemArt = require("./itemart.js");
const playerItems = require("./playeritems.js"); const playerItems = require("./playeritems.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const devices = require("./devices.js"); const devices = require("./devices.js");
const discordLinks = require("./discord.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const manage = require("./manage.js"); const manage = require("./manage.js");
const masterpieces = require("./masterpieces.js"); const masterpieces = require("./masterpieces.js");
@@ -24,9 +26,11 @@ const reports = require("./reports.js");
const roles = require("./roles.js"); const roles = require("./roles.js");
const staff = require("./staff.js"); const staff = require("./staff.js");
const stats = require("./stats.js"); const stats = require("./stats.js");
const sfs = require("./sfs.js");
const support = require("./support.js"); const support = require("./support.js");
const totp = require("./totp.js"); const totp = require("./totp.js");
const world = require("./world.js"); const world = require("./world.js");
const {logText} = require("./logtext.js");
// the moderator panel at /mod: what a moderator needs to look after the // the moderator panel at /mod: what a moderator needs to look after the
// players, and no more. it is apart from the admin panel (lib/panel.js), // players, and no more. it is apart from the admin panel (lib/panel.js),
@@ -50,27 +54,108 @@ const world = require("./world.js");
// moderator's name, for the admin panel. // moderator's name, for the admin panel.
const COOKIE = "ajc_mod"; const COOKIE = "ajc_mod";
const DISCORD_COOKIE = "ajc_mod_discord";
const SESSION_HOURS = 12; const SESSION_HOURS = 12;
const TEN_MINUTES_MS = 600000; const TEN_MINUTES_MS = 600000;
const MAX_BAN_HOURS = 24 * 365 * 10; const MAX_BAN_HOURS = 24 * 365 * 10;
const MAX_MESSAGE_LENGTH = 200; const MAX_MESSAGE_LENGTH = 200;
const MAX_RECENT_NOTES = 15; const MAX_RECENT_NOTES = 15;
const RECENT_PAINTINGS = 12;
const GIT_STATUS_CACHE_MS = 10000;
const PROJECT_ROOT = path.resolve(__dirname, "..");
const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS); const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS);
const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator
const sessions = new Map(); // SHA-256 of a session token -> {id: account id, expiry: ms} // SHA-256 of a session token -> {id: account id, expiry: ms, code}. `code`:
// a 2FA code was given for it (the password sign-in, and Discord's with a
// code after it), which the Discord bot's commands need (discordCommandActor).
const sessions = new Map();
// a Discord sign-in waiting for its 2FA code: SHA-256 of the token in its
// cookie -> {id, expiry, tries}. Discord says who it is; the code says it is
// still them, as the password sign-in asks.
const pendingDiscord = new Map();
const PENDING_COOKIE = "ajc_mod_pending";
const PENDING_MINUTES = 5;
const PENDING_TRIES = 5;
const addressSearched = new Map(); // moderator's account id -> the address they last searched for const addressSearched = new Map(); // moderator's account id -> the address they last searched for
const sha256 = text => crypto.createHash("sha256").update(text).digest("hex"); const sha256 = text => crypto.createHash("sha256").update(text).digest("hex");
// This is read-only and intentionally never fetches, pulls or pushes. It
// gives staff a conspicuous reminder that the running checkout contains work
// which has not made it to its tracked remote yet.
let gitStatusCachedAt = 0;
let gitStatusCached = null;
const gitUpdateState = () => {
if (gitStatusCached && Date.now() - gitStatusCachedAt < GIT_STATUS_CACHE_MS) {
return gitStatusCached;
}
try {
const runGit = args => execFileSync("git", args, {cwd: PROJECT_ROOT, encoding: "utf8", timeout: 1500, maxBuffer: 128 * 1024}).trim();
const raw = runGit(["status", "--porcelain=v1", "-z"]);
const entries = raw ? raw.split("\0").filter(Boolean) : [];
const changed = [];
for (let index = 0; index < entries.length; index++) {
const entry = entries[index];
const status = entry.slice(0, 2);
changed.push({status: status.trim() || "?", path: entry.slice(3)});
// A rename/copy has another NUL-delimited source path. The destination
// is the useful file to show in the warning.
if (status[0] === "R" || status[0] === "C") {
index++;
}
}
let ahead = 0;
let behind = 0;
let remoteKnown = true;
try {
const [behindText, aheadText] = runGit(["rev-list", "--left-right", "--count", "@{upstream}...HEAD"]).split(/\s+/);
behind = Number(behindText) || 0;
ahead = Number(aheadText) || 0;
}
catch (_) {
remoteKnown = false;
}
gitStatusCached = {available: true, changed, ahead, behind, remoteKnown,
needsPublish: changed.length > 0 || ahead > 0};
}
catch (err) {
gitStatusCached = {available: false, changed: [], ahead: 0, behind: 0, remoteKnown: false,
needsPublish: false, error: "Git status could not be read."};
}
gitStatusCachedAt = Date.now();
return gitStatusCached;
};
const cookieToken = req => { const cookieToken = req => {
const match = new RegExp(`(?:^|;\\s*)${COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || ""); const match = new RegExp(`(?:^|;\\s*)${COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "");
return match ? match[1] : null; return match ? match[1] : null;
}; };
const cookieHeader = (token, maxAgeSeconds) => const cookieHeader = (token, maxAgeSeconds) =>
`${COOKIE}=${token}; Path=/mod; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`; `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const discordCookie = (value, maxAgeSeconds) =>
`${DISCORD_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const pendingCookieHeader = (token, maxAgeSeconds) =>
`${PENDING_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const pendingToken = req => (new RegExp(`(?:^|;\\s*)${PENDING_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1] || null;
// `extraCookies` go out with the session's own.
const beginSession = (account, res, address, detail = "", code = true, extraCookies = []) => {
accounts.recordLogin(account, "mod", address);
accounts.save(account);
for (const [hash, session] of sessions) {
if (session.expiry < Date.now()) {
sessions.delete(hash);
}
}
const token = crypto.randomBytes(24).toString("hex");
sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000, code});
res.setHeader("Set-Cookie", [cookieHeader(token, SESSION_HOURS * 3600), ...extraCookies]);
modlog.record(account.username, "signed in", "", detail);
};
// may this account use the panel (still)? // may this account use the panel (still)?
const mayModerate = account => Boolean(account && roles.isActiveStaff(account, world.moderation.banRemaining(account) !== 0)); const mayModerate = account => Boolean(account && roles.isActiveStaff(account, world.moderation.banRemaining(account) !== 0));
@@ -90,6 +175,11 @@ const forget = account => {
sessions.delete(hash); sessions.delete(hash);
} }
} }
for (const [hash, pending] of pendingDiscord) {
if (pending.id === account.id) {
pendingDiscord.delete(hash);
}
}
}; };
const playerRow = (account, playing) => { const playerRow = (account, playing) => {
@@ -116,10 +206,18 @@ const playerRow = (account, playing) => {
const playing = () => new Map(world.players().map(player => [player.username, player.room || "(between rooms)"])); const playing = () => new Map(world.players().map(player => [player.username, player.room || "(between rooms)"]));
// by name (lib/staff.js says in what order). // what the Players page's list can be narrowed to (lib/staff.js `keep`).
const findPlayers = query => { const ONLY = {
online: (account, online) => online.has(account.username),
banned: account => world.moderation.banRemaining(account) !== 0 || devices.bannedId(account) !== 0,
silenced: account => world.moderation.silenceRemaining(account) !== 0,
staff: account => Boolean(roles.roleOf(account)),
};
// by name (lib/staff.js says in what order), and `only` one of ONLY's.
const findPlayers = (query, only) => {
const online = playing(); const online = playing();
const {found, total} = staff.findAccounts(query); const {found, total} = staff.findAccounts(query, Object.hasOwn(ONLY, only) ? ONLY[only] : undefined);
return {players: found.map(account => playerRow(account, online)), total}; return {players: found.map(account => playerRow(account, online)), total};
}; };
@@ -153,13 +251,16 @@ const maskedAddress = ban => ({
const wholeNumber = (value, min, max) => (Number.isInteger(value) && value >= min && value <= max ? value : null); const wholeNumber = (value, min, max) => (Number.isInteger(value) && value >= min && value <= max ? value : null);
// the permission (lib/roles.js) each action needs. // the permission (lib/roles.js) each action needs. an action that is not
// here is refused (act), so that a new one cannot go unchecked.
const ACTION_PERMISSIONS = { const ACTION_PERMISSIONS = {
ban: "player.ban", banReason: "player.ban", unban: "player.ban", ban: "player.ban", banReason: "player.ban", unban: "player.ban",
silence: "chat.silence", unsilence: "chat.silence", silence: "chat.silence", unsilence: "chat.silence",
kick: "player.kick", message: "player.warn", warn: "player.warn", unwarn: "player.warn", kick: "player.kick", message: "player.warn", warn: "player.warn", unwarn: "player.warn",
rejectName: "player.names", acceptName: "player.names", clearBio: "player.names", rejectName: "player.names", acceptName: "player.names", clearBio: "player.names",
banAddress: "address.ban", clearWallPosts: "player.names", banAddress: "address.ban",
// a computer's ban, as an address's, keeps out everyone who uses it
banDevices: "address.ban", unbanDevices: "address.ban",
summon: "player.summon", goto: "player.goto", summon: "player.summon", goto: "player.goto",
note: "player.view", deleteNote: "player.view", note: "player.view", deleteNote: "player.view",
}; };
@@ -180,8 +281,11 @@ const act = (mod, target, body) => {
if (!roles.outranks(mod, target)) { if (!roles.outranks(mod, target)) {
return {error: "Staff of your rank or above are for someone higher up to deal with."}; return {error: "Staff of your rank or above are for someone higher up to deal with."};
} }
const permission = ACTION_PERMISSIONS[body.action]; const permission = Object.hasOwn(ACTION_PERMISSIONS, body.action) ? ACTION_PERMISSIONS[body.action] : null;
if (permission && !roles.can(mod, permission)) { if (!permission) {
return {error: "Unknown action."};
}
if (!roles.can(mod, permission)) {
return {error: "Your role cannot do that."}; return {error: "Your role cannot do that."};
} }
switch (body.action) { switch (body.action) {
@@ -256,6 +360,15 @@ const act = (mod, target, body) => {
target.bio = ""; target.bio = "";
accounts.save(target); accounts.save(target);
return {ok: "Bio cleared."}; return {ok: "Bio cleared."};
case "clearWallPosts": {
const {posts, replies, walls} = actions.clearWallPosts(target);
if (!posts) {
return {error: `${name} has no posts on any Jammer Wall.`};
}
const text = `${posts} wall ${posts === 1 ? "post" : "posts"} by ${name} removed from ${walls} ${walls === 1 ? "wall" : "walls"}`
+ `${replies ? ` (with ${replies} ${replies === 1 ? "reply" : "replies"} to them)` : ""}.`;
return {ok: text, detail: `${posts} posts, ${replies} replies, ${walls} walls`};
}
// a note for the other staff (lib/modnotes.js); the player never sees it. // a note for the other staff (lib/modnotes.js); the player never sees it.
case "note": { case "note": {
const result = modNotes.add(target, by, body.text); const result = modNotes.add(target, by, body.text);
@@ -303,7 +416,7 @@ const PAGE_HEADERS = {
"X-Frame-Options": "DENY", "X-Frame-Options": "DENY",
"X-Content-Type-Options": "nosniff", "X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer", "Referrer-Policy": "no-referrer",
"Content-Security-Policy": 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'"), + "form-action 'none'; frame-ancestors 'none'; base-uri 'none'"),
}; };
@@ -319,6 +432,47 @@ const handle = async (req, res, url, from, web) => {
web.send(res, 200, captcha.withScriptVersion(await stats.withView(await fs.promises.readFile(path.join(config.publicDir, "mod.html")))), "text/html; charset=utf-8"); web.send(res, 200, captcha.withScriptVersion(await stats.withView(await fs.promises.readFile(path.join(config.publicDir, "mod.html")))), "text/html; charset=utf-8");
return; return;
} }
// The nonce cookie is Lax only for Discord's cross-site return. The normal
// staff-session cookie remains Strict and is issued after the callback.
if (route === "GET /mod/discord/login") {
if (!discordLinks.linking()) {
res.writeHead(302, {Location: "/dashboard/staff?discord=off"});
res.end();
return;
}
const {url: to, nonce} = discordLinks.startStaff();
res.setHeader("Set-Cookie", discordCookie(nonce, 600));
res.writeHead(302, {Location: to});
res.end();
return;
}
if (route === "GET /mod/discord/callback") {
const nonce = (new RegExp(`(?:^|;\\s*)${DISCORD_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1];
const result = url.searchParams.get("error") ? {error: "cancelled"}
: await discordLinks.finishStaff(url.searchParams.get("state"), nonce, url.searchParams.get("code"));
if (result.ok && !mayModerate(result.account)) {
result.ok = false;
result.error = "denied";
}
// Discord has said who this is; the panel opens once their 2FA code is
// given too (POST /mod/api/discord/code), so a Discord account alone,
// taken over or linked by someone else, opens nothing.
const cookies = [discordCookie("", 0)];
if (result.ok) {
for (const [hash, pending] of pendingDiscord) {
if (pending.expiry < Date.now()) {
pendingDiscord.delete(hash);
}
}
const token = crypto.randomBytes(24).toString("hex");
pendingDiscord.set(sha256(token), {id: result.account.id, expiry: Date.now() + PENDING_MINUTES * 60000, tries: 0});
cookies.push(pendingCookieHeader(token, PENDING_MINUTES * 60));
}
res.setHeader("Set-Cookie", cookies);
res.writeHead(302, {Location: `/dashboard/staff?discord=${result.ok ? "code" : result.error}`});
res.end();
return;
}
if (req.method === "POST" && !limits.originAllowed(req)) { if (req.method === "POST" && !limits.originAllowed(req)) {
reply(403, {error: "forbidden"}); reply(403, {error: "forbidden"});
return; return;
@@ -328,7 +482,7 @@ const handle = async (req, res, url, from, web) => {
switch (route) { switch (route) {
case "GET /mod/api/state": { case "GET /mod/api/state": {
const mod = signedInAs(req); const mod = signedInAs(req);
reply(200, {signedIn: Boolean(mod), username: mod ? mod.username : ""}); reply(200, {signedIn: Boolean(mod), username: mod ? mod.username : "", discordLogin: discordLinks.linking()});
return; return;
} }
// username, password and a code, all three every time. // username, password and a code, all three every time.
@@ -379,12 +533,97 @@ const handle = async (req, res, url, from, web) => {
} }
} }
const token = crypto.randomBytes(24).toString("hex"); const token = crypto.randomBytes(24).toString("hex");
sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000}); sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000, code: true});
res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600)); res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600));
modlog.record(account.username, "signed in"); modlog.record(account.username, "signed in");
reply(200, {ok: true, username: account.username}); reply(200, {ok: true, username: account.username});
return; return;
} }
// the second half of a Discord sign-in (GET /mod/discord/callback): the
// account's 2FA code, from the browser Discord sent back here. a few
// wrong codes and the sign-in is gone; it must start again at Discord.
case "POST /mod/api/discord/code": {
if (!from.local && failuresByAddress.blocked(from.key)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
const token = pendingToken(req);
const hash = token ? sha256(token) : null;
const pending = hash ? pendingDiscord.get(hash) : null;
const account = pending && pending.expiry > Date.now() ? accounts.byId(pending.id) : null;
if (!account || !mayModerate(account)) {
if (hash) {
pendingDiscord.delete(hash);
}
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
reply(401, {error: "The Discord sign-in expired. Sign in with Discord again.", expired: true});
return;
}
if (!totp.verify(account, String(body.code || ""))) {
failuresByAddress.record(from.key);
accounts.recordLogin(account, "mod", from.address, false);
accounts.save(account);
pending.tries++;
if (pending.tries >= PENDING_TRIES) {
pendingDiscord.delete(hash);
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
reply(401, {error: "Too many wrong codes. Sign in with Discord again.", expired: true});
return;
}
reply(401, {error: "Wrong code."});
return;
}
pendingDiscord.delete(hash);
beginSession(account, res, from.address, "through Discord", true, [pendingCookieHeader("", 0)]);
console.log(`[mod] ${logText(account.username)} signed in with Discord and a code from ${logText(from.address)}`);
reply(200, {ok: true, username: account.username});
return;
}
// signed in through the game instead: a client the moderator is playing
// in hands over the game's login token, so they need not type their
// password and a code again. taken only for active staff with 2FA on
// (so the game's own sign-in took a code), who are in the game now, and
// asking from the address that game connected from: the token alone,
// copied elsewhere, opens nothing.
case "POST /mod/api/game-login": {
if (!from.local && failuresByAddress.blocked(from.key)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
const account = accounts.byToken(body.token);
const session = account ? world.findOnline(account.username) : null;
if (!account || !roles.roleOf(account)) {
failuresByAddress.record(from.key);
reply(401, {error: "Sign in with your password and code."});
return;
}
if (!totp.isOn(account)) {
reply(403, {error: "Turn on 2FA on your account page first."});
return;
}
if (!mayModerate(account)) {
reply(403, {error: "This account cannot sign in here now."});
return;
}
if (!session || limits.key(session.address) !== from.key) {
reply(401, {error: "Be in the game on this computer, or sign in with your password and code."});
return;
}
accounts.recordLogin(account, "mod", from.address);
accounts.save(account);
for (const [hash, kept] of sessions) {
if (kept.expiry < Date.now()) {
sessions.delete(hash);
}
}
const cookie = crypto.randomBytes(24).toString("hex");
// no code given here, so not one the Discord bot's commands count
sessions.set(sha256(cookie), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000, code: false});
res.setHeader("Set-Cookie", cookieHeader(cookie, SESSION_HOURS * 3600));
modlog.record(account.username, "signed in", "", "through the game");
reply(200, {ok: true, username: account.username});
return;
}
case "POST /mod/api/logout": { case "POST /mod/api/logout": {
const token = cookieToken(req); const token = cookieToken(req);
if (token) { if (token) {
@@ -412,6 +651,23 @@ const handle = async (req, res, url, from, web) => {
} }
reply(result.ok ? 200 : 400, result.ok ? {ok: result.ok} : {error: result.error}); reply(result.ok ? 200 : 400, result.ok ? {ok: result.ok} : {error: result.error});
}; };
// a route's permission (lib/roles.js), as act() checks an action's: a
// role without it is refused here, whatever its page shows.
const may = permission => {
if (roles.can(mod, permission)) {
return true;
}
reply(403, {error: "Your role cannot do that."});
return false;
};
// why the moderator may not act on `account`, as act() refuses: not on
// themselves, nor on staff of their rank or above. null when they may.
const refusalFor = account => {
if (!account || roles.outranks(mod, account)) {
return null;
}
return {error: account === mod ? "That is you." : "Staff of your rank or above are for someone higher up to deal with."};
};
switch (route) { switch (route) {
// who is signed in here, their role and what it allows: for a client to // who is signed in here, their role and what it allows: for a client to
@@ -430,6 +686,22 @@ const handle = async (req, res, url, from, web) => {
reviewRoutes(route.replace(" /mod/api/", " "), body, reply, done, mod.username, "/mod/api/itemart"); reviewRoutes(route.replace(" /mod/api/", " "), body, reply, done, mod.username, "/mod/api/itemart");
return; return;
} }
// This deliberately precedes the broad /items branch. Moderators may
// receive the narrow items.restrict permission without also being allowed
// to make, delete, lock or take items.
if (/^\/mod\/api\/items\/wear-rules\/?$/.test(url.pathname)) {
if (!roles.can(mod, "items.restrict")) {
reply(403, {error: "Your role does not allow that."});
return;
}
// Normalize the harmless trailing-slash spelling before dispatching it.
itemRoutes(`${req.method} items/wear-rules`, url, body, reply, done, {
username: mod.username,
artBase: "/mod/api/itemart",
mayTake: () => false,
});
return;
}
// custom items (lib/customitems.js), for whoever may make them. // custom items (lib/customitems.js), for whoever may make them.
if (url.pathname.startsWith("/mod/api/items")) { if (url.pathname.startsWith("/mod/api/items")) {
if (!roles.can(mod, "items.create")) { if (!roles.can(mod, "items.create")) {
@@ -443,6 +715,43 @@ const handle = async (req, res, url, from, web) => {
}); });
return; return;
} }
// Service health is intentionally separate from player data: every staff
// role may see it, including developers who have no player-view access.
if (route === "GET /mod/api/server") {
if (!roles.can(mod, "server.view")) {
reply(403, {error: "Your role does not allow that."});
return;
}
const memory = process.memoryUsage();
const players = world.players();
const rooms = new Set(players.map(player => player.room).filter(Boolean));
reply(200, {
uptimeSeconds: Math.floor(process.uptime()),
players: players.length,
rooms: rooms.size,
memory: {
rssMb: Math.round(memory.rss / 1048576),
heapUsedMb: Math.round(memory.heapUsed / 1048576),
heapTotalMb: Math.round(memory.heapTotal / 1048576),
},
sockets: sfs.health(),
update: gitUpdateState(),
now: Date.now(),
});
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 // everything else shows players and what they did: not for a role that
// only makes things. // only makes things.
if (!roles.can(mod, "player.view")) { if (!roles.can(mod, "player.view")) {
@@ -456,6 +765,7 @@ const handle = async (req, res, url, from, web) => {
paintings: masterpieces.list(masterpieces.PENDING).length}); paintings: masterpieces.list(masterpieces.PENDING).length});
return; return;
// other accounts the same person may have, and their story (lib/staff.js). // other accounts the same person may have, and their story (lib/staff.js).
case "GET /mod/api/alts": { case "GET /mod/api/alts": {
const account = accounts.byName(url.searchParams.get("username") || ""); const account = accounts.byName(url.searchParams.get("username") || "");
@@ -485,7 +795,7 @@ const handle = async (req, res, url, from, web) => {
return; return;
} }
if (searchBy !== "address") { if (searchBy !== "address") {
reply(200, findPlayers(url.searchParams.get("q"))); reply(200, findPlayers(url.searchParams.get("q"), url.searchParams.get("only")));
return; return;
} }
// by address: only the address typed, which is written down (once // by address: only the address typed, which is written down (once
@@ -555,7 +865,12 @@ const handle = async (req, res, url, from, web) => {
reply(200, {reports: reports.list(url.searchParams.get("handled") === "1"), open: reports.openCount()}); reply(200, {reports: reports.list(url.searchParams.get("handled") === "1"), open: reports.openCount()});
return; return;
// a report dealt with: for the roles that act on players (a warning is
// the least of it), not for one that only looks.
case "POST /mod/api/report": case "POST /mod/api/report":
if (!may("player.warn")) {
return;
}
done(reports.markHandled(Number(body.id)) ? {ok: "Marked as dealt with."} : {error: "No such report waiting."}, "report dealt with", "", `#${Number(body.id)}`); done(reports.markHandled(Number(body.id)) ? {ok: "Marked as dealt with."} : {error: "No such report waiting."}, "report dealt with", "", `#${Number(body.id)}`);
return; return;
@@ -567,10 +882,32 @@ const handle = async (req, res, url, from, web) => {
} }
case "POST /mod/api/request": { case "POST /mod/api/request": {
if (body.action === "appealApprove" || body.action === "appealDeny") { if (body.action === "appealApprove" || body.action === "appealDeny") {
// a ban decision: for the roles that ban, and one that also lifts the
// ban on an address only for those that ban addresses.
const appeal = bans.waitingAppeal(body.id);
const liftsAddress = body.action === "appealApprove" && appeal && appeal.addressKey && bans.addressBan(appeal.addressKey);
if (!may("player.ban") || (liftsAddress && !may("address.ban"))) {
return;
}
const refusal = appeal ? refusalFor(accounts.byId(appeal.accountId)) : null;
if (refusal) {
done(refusal);
return;
}
const result = staff.answerAppeal(body.id, body.action === "appealApprove", body.reply, mod.username); const result = staff.answerAppeal(body.id, body.action === "appealApprove", body.reply, mod.username);
done(result, body.action === "appealApprove" ? "appeal approved" : "appeal denied", result.username, bans.clean(body.reply, bans.MAX_REPLY)); done(result, body.action === "appealApprove" ? "appeal approved" : "appeal denied", result.username, bans.clean(body.reply, bans.MAX_REPLY));
} }
else if (body.action === "approve" || body.action === "deny") { else if (body.action === "approve" || body.action === "deny") {
// a new name: for the roles that judge names.
if (!may("player.names")) {
return;
}
const request = support.nameRequestById(body.id);
const refusal = request ? refusalFor(accounts.byId(request.accountId)) : null;
if (refusal) {
done(refusal);
return;
}
const result = staff.answerNameRequest(body.id, body.action === "approve"); const result = staff.answerNameRequest(body.id, body.action === "approve");
done(result, body.action === "approve" ? "name request approved" : "name request denied", result.username); done(result, body.action === "approve" ? "name request approved" : "name request denied", result.username);
} }
@@ -594,16 +931,29 @@ const handle = async (req, res, url, from, web) => {
return; return;
} }
// A device ban lifted (lib/devices.js). // A device ban lifted (lib/devices.js): for the roles that give them
// (act's unbanDevices), and not one made with staff of their rank or above.
case "POST /mod/api/device": { case "POST /mod/api/device": {
if (!may("address.ban")) {
return;
}
const ban = devices.banById(body.id);
const refusal = ban ? refusalFor(accounts.byId(ban.accountId)) : null;
if (refusal) {
done(refusal);
return;
}
const result = staff.unbanDevices(body.id, mod.username); const result = staff.unbanDevices(body.id, mod.username);
done(result, "hardware ban lifted", result.username || ""); done(result, "hardware ban lifted", result.username || "");
return; return;
} }
// paintings players framed (lib/masterpieces.js). // paintings players framed (lib/masterpieces.js), and the ones approved
// last, to take one back that should not have been (mine=1: only the
// ones this moderator approved).
case "GET /mod/api/masterpieces": case "GET /mod/api/masterpieces":
reply(200, {...masterpieces.listsFor(url.searchParams.get("creator")), waitingCount: masterpieces.list(masterpieces.PENDING).length}); reply(200, {...masterpieces.listsFor(url.searchParams.get("creator")), waitingCount: masterpieces.list(masterpieces.PENDING).length,
recent: masterpieces.recentlyApproved(RECENT_PAINTINGS, url.searchParams.get("mine") === "1" ? mod.username : "")});
return; return;
case "GET /mod/api/masterpiece": { case "GET /mod/api/masterpiece": {
@@ -617,11 +967,21 @@ const handle = async (req, res, url, from, web) => {
return; return;
} }
// a painting judged: for the roles that judge paintings, and never
// their own or one by staff of their rank or above.
case "POST /mod/api/masterpiece": { case "POST /mod/api/masterpiece": {
if (!may("masterpieces.approve")) {
return;
}
const id = String(body.id || ""); const id = String(body.id || "");
const maker = masterpieces.creatorOf(id); const maker = masterpieces.creatorOf(id);
const refusal = refusalFor(maker);
if (refusal) {
done(refusal);
return;
}
const result = body.action === "approve" const result = body.action === "approve"
? (world.approveMasterpiece(id) ? {ok: "Approved."} : {error: "No such painting waiting."}) ? (world.approveMasterpiece(id, mod.username) ? {ok: "Approved."} : {error: "No such painting waiting."})
: body.action === "reject" || body.action === "remove" : body.action === "reject" || body.action === "remove"
? (world.removeMasterpiece(id) ? {ok: "Removed for good. Its maker was told and given a Masterpiece Token."} : {error: "No such painting."}) ? (world.removeMasterpiece(id) ? {ok: "Removed for good. Its maker was told and given a Masterpiece Token."} : {error: "No such painting."})
: {error: "Unknown action."}; : {error: "Unknown action."};
@@ -644,6 +1004,8 @@ const handle = async (req, res, url, from, web) => {
// whether it is locked out of the finder: for the dashboards' lock. // whether it is locked out of the finder: for the dashboards' lock.
// GET items/base?kind=clothing|den&id=N: an item of the game's to // GET items/base?kind=clothing|den&id=N: an item of the game's to
// make one from (its name and colours), to check before making it. // make one from (its name and colours), to check before making it.
// GET items/wear-rules?q=WORDS: clothing search results, animal choices and
// current per-animal wear blocks. POST it with {id, blockedTypes} to set.
// POST items {action: "create", kind, base, name, cost, members, colors} // POST items {action: "create", kind, base, name, cost, members, colors}
// or {action: "update", kind, id, and any of name, cost, members, colors, inShop} // or {action: "update", kind, id, and any of name, cost, members, colors, inShop}
// or {action: "lock" | "unlock", kind, id}: kept out of the item finder // or {action: "lock" | "unlock", kind, id}: kept out of the item finder
@@ -651,6 +1013,21 @@ const handle = async (req, res, url, from, web) => {
// or {action: "delete", kind, id}: a custom item, out of the game and every inventory. // or {action: "delete", kind, id}: a custom item, out of the game and every inventory.
const itemRoutes = (route, url, body, reply, done, actor) => { const itemRoutes = (route, url, body, reply, done, actor) => {
switch (route) { switch (route) {
case "GET items/wear-rules": {
const search = new URLSearchParams({kind: "clothing", q: url.searchParams.get("q") || ""});
const found = admin.search(search, null, true);
const rules = itemControl.wearRuleList();
const blockedByItem = new Map(rules.map(rule => [rule.id, rule.blockedTypes]));
reply(200, {animals: itemControl.wearAnimals(), rules, total: found.total,
results: found.results.slice(0, 20).map(entry => ({id: entry.id, name: entry.locked ? entry.name.replace(/ \(locked\)$/, "") : entry.name,
custom: entry.id >= customItems.FIRST_ID, blockedTypes: blockedByItem.get(entry.id) || []}))});
return;
}
case "POST items/wear-rules": {
const result = itemControl.setWearRule(body.id, body.blockedTypes, world);
done(result, result.ok ? "item wear rule changed" : "", "", `clothing ${body.id}`);
return;
}
case "GET items": case "GET items":
reply(200, {items: customItems.list().map(entry => ({...entry, baseName: customItems.baseName(entry), locked: itemControl.isLocked(entry.kind, entry.id), reply(200, {items: customItems.list().map(entry => ({...entry, baseName: customItems.baseName(entry), locked: itemControl.isLocked(entry.kind, entry.id),
artUrl: itemArt.urlOf(entry, actor.artBase)})), artUrl: itemArt.urlOf(entry, actor.artBase)})),
@@ -778,4 +1155,109 @@ 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})) .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)); .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.
// whose Discord this is: the active staff member it is linked to, or null.
// it says who someone is (the bot leaves staff alone), not that they may act.
const discordActor = discordId => {
const account = accounts.all().find(candidate => candidate.discordId === String(discordId));
return mayModerate(account) ? account : null;
};
// who may use the bot's commands: the staff member above, while they are
// signed in to the panel with a code (a session above with `code`). a
// Discord account alone is not them, and a new password, signing out
// everywhere or 2FA turned off end those sessions (forget), and the bot's
// use with them.
const discordCommandActor = discordId => {
const account = discordActor(discordId);
if (!account) {
return null;
}
for (const session of sessions.values()) {
if (session.id === account.id && session.code && session.expiry > Date.now()) {
return account;
}
}
return null;
};
const discordError = (actor, permission) => !actor
? {error: "Link this Discord account to your active Burrow staff account, then sign in to the staff dashboard with your 2FA code. Discord commands work while that sign-in lasts (12 hours)."}
: !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 discordError(null);
}
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, commandActor: discordCommandActor, 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};
+1
View File
@@ -0,0 +1 @@
{"10":{"type":1033,"count":141,"entries":["9329","0","9326","0","9332","0","9330","0","9331","0","9327","0","9328","0","9167","0","9170","0","9172","0","9174","0","9175","0","9176","0","9013","0","9014","0","9015","0","9016","0","9017","0","4452","0","2702","0","4451","0","2706","0","4453","0","2762","0","2711","0","2716","0","2715","0","2723","0","2697","0","2717","0","4478","0","1250","0","1251","0","1354","0","1426","0","1627","0","5738","0","346","0","86","0","124","0","118","0","2805","0","2806","0","2807","0","2808","0","2809","0","2810","0","2811","0","2812","0","2813","0","2814","0","2815","0","2816","0","2817","0","2818","0","2819","0","2820","0","2821","0","2822","0","2823","0","2824","0","2825","0","2826","0","2827","0","2828","0","1","0","4547","0","4542","0","4544","0","4549","0","4540","0","4548","0","4538","0","4539","0","4541","0","4543","0","4545","0","4546","0","2708","0","4470","0","356","0","5077","0","5078","0","5079","0","2705","0","4457","0","4465","0","2703","0","2709","0","5092","0","5093","0","5094","0","5095","0","4856","0","2712","0","2713","0","2714","0","4477","0","6130","0","6138","0","4777","0","4778","0","4779","0","4780","0","4855","0","5980","0","5981","0","4435","0","4946","0","4460","0","4461","0","4462","0","2707","0","4454","0","5088","0","5089","0","5090","0","5091","0","4455","0","2700","0","1188","0","2704","0","4459","0","4467","0","4468","0","4469","0","4393","0","5073","0","5074","0","5075","0","5076","0","4410","0","5084","0","5085","0","5086","0","5087","0","4466","0","5080","0","5081","0","5082","0","5083","0"]},"16":{"type":1023,"count":50,"entries":["551","552","553","554","555","556","557","564","558","569","559","1831","573","560","578","561","576","562","563","579","565","1841","568","574","566","1845","567","570","577","575","1830","571","1844","1826","572","1835","1839","1832","1843","1829","1827","1842","1828","1846","1838","1833","1840","1836","1837","1834"]},"44":{"type":1033,"count":35,"entries":["13","0","11","0","2889","0","2896","0","1602","0","2886","0","1604","0","12","0","2877","0","2885","0","1603","0","2894","0","10","0","2899","0","2891","0","2876","0","376","0","2878","0","2879","0","2880","0","2881","0","2882","0","2884","0","2888","0","2898","0","2887","0","2890","0","377","0","2892","0","2893","0","2895","0","2900","0","378","0","2901","0","2902","0"]},"53":{"type":1033,"count":14,"entries":["1389","1603","1545","1600","1595","1601","1265","1604","1470","1599","1232","1790","2279","3726","2015","0","7061","18253","1185","912","1192","1571","1186","913","1187","914","6189","0"],"note":"not recorded: the Journey Book's pages, found among the media files by their jb_title parts, and each land's name"},"54":{"type":1035,"count":160,"entries":["634","7044","32198","32199","10","459","0","635","7045","32200","32201","10","459","1","636","7046","32202","32203","10","459","2","637","7047","32204","32205","10","459","3","638","7048","32206","32207","10","459","4","639","7049","32208","32209","10","459","5","640","7050","32210","32211","10","459","6","641","7051","32212","32213","10","459","7","642","7052","32214","32215","10","459","8","643","7053","32216","32217","10","459","9","606","6667","31309","31310","14","457","0","607","6666","31311","31312","14","457","1","608","6668","31313","31314","14","457","2","609","6670","31303","31304","14","457","3","610","6665","31307","31308","14","457","4","611","6669","31305","31306","14","457","5","578","6180","30096","30097","14","456","11","577","6181","30094","30095","14","456","10","576","6187","30092","30093","14","456","9","575","6186","30090","30091","14","456","8","574","6179","30088","30089","14","456","7","573","6178","30086","30087","14","456","6","572","6177","30084","30085","14","456","5","571","6176","30082","30083","14","456","4","570","6183","30080","30081","14","456","3","569","6182","30078","30079","14","456","2","568","6185","30076","30077","14","456","1","567","6184","30074","30075","14","456","0","140","775","812","848","10","289","0","141","777","814","850","10","289","1","142","780","817","853","10","289","2","143","125","808","844","10","289","3","144","776","813","849","10","289","4","145","772","809","845","10","289","5","146","774","811","847","10","289","6","147","778","815","851","10","289","7","148","781","818","854","10","289","8","149","779","816","852","10","289","9","150","773","810","846","10","289","10","151","815","832","868","10","291","0","152","821","840","876","10","291","1","153","817","834","871","10","291","2","154","824","843","883","10","291","3","155","820","839","875","10","291","4","156","819","838","873","10","291","5","157","818","835","872","10","291","6","158","822","841","879","10","291","7","159","823","842","880","10","291","8","160","816","833","869","10","291","9","161","784","821","857","10","290","0","162","786","823","859","10","290","1","163","813","830","866","10","290","2","164","788","825","861","10","290","3","165","783","820","856","10","Line truncated
+271 -35
View File
@@ -8,6 +8,8 @@ const accounts = require("./accounts.js");
const achievements = require("./achievements.js"); const achievements = require("./achievements.js");
const adopt = require("./adopt.js"); const adopt = require("./adopt.js");
const badges = require("./badges.js"); const badges = require("./badges.js");
const discordLinks = require("./discord.js");
const discordBot = require("./discordbot.js");
const bans = require("./bans.js"); const bans = require("./bans.js");
const colours = require("./colours.js"); const colours = require("./colours.js");
const chatlog = require("./chatlog.js"); const chatlog = require("./chatlog.js");
@@ -30,6 +32,7 @@ const support = require("./support.js");
const totp = require("./totp.js"); const totp = require("./totp.js");
const manage = require("./manage.js"); const manage = require("./manage.js");
const world = require("./world.js"); const world = require("./world.js");
const codes = require("./codes.js");
const {activeAvatar} = require("./player.js"); const {activeAvatar} = require("./player.js");
// the admin panel at /admin: the only place the server is administered from. // the admin panel at /admin: the only place the server is administered from.
@@ -42,6 +45,7 @@ const {activeAvatar} = require("./player.js");
const PASSWORD_SETTING = "admin_password"; // "salt:hash" const PASSWORD_SETTING = "admin_password"; // "salt:hash"
const COOKIE = "ajc_admin"; const COOKIE = "ajc_admin";
const DISCORD_COOKIE = "ajc_admin_discord";
const SESSION_HOURS = 12; const SESSION_HOURS = 12;
const MIN_PASSWORD_LENGTH = 8; const MIN_PASSWORD_LENGTH = 8;
const MAX_PASSWORD_LENGTH = 200; const MAX_PASSWORD_LENGTH = 200;
@@ -89,6 +93,11 @@ const passwordAcceptable = password =>
typeof password === "string" && password.length >= MIN_PASSWORD_LENGTH && password.length <= MAX_PASSWORD_LENGTH; typeof password === "string" && password.length >= MIN_PASSWORD_LENGTH && password.length <= MAX_PASSWORD_LENGTH;
const load = () => { const load = () => {
// the number of worlds the admin chose last (world.setWorldCount)
const worlds = accounts.setting(world.WORLD_COUNT_SETTING);
if (worlds !== null) {
world.setWorldCount(worlds, false);
}
if (!hasPassword()) { if (!hasPassword()) {
setupCode = crypto.randomBytes(5).toString("hex"); setupCode = crypto.randomBytes(5).toString("hex");
console.log(`[admin] no admin password yet: open ${logText(config.baseUrl)}admin to choose one` console.log(`[admin] no admin password yet: open ${logText(config.baseUrl)}admin to choose one`
@@ -111,9 +120,27 @@ const signedIn = req => {
}; };
const cookieHeader = (token, maxAgeSeconds) => const cookieHeader = (token, maxAgeSeconds) =>
`${COOKIE}=${token}; Path=/admin; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`; `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const signIn = res => { const discordCookie = (value, maxAgeSeconds) =>
`${DISCORD_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
// a Discord sign-in waiting for the 2FA code of the account it is linked
// to: SHA-256 of the token in its cookie -> {id, expiry, tries}. Discord
// alone does not open this panel, as the password alone does not open the
// moderator panel.
const pendingDiscord = new Map();
const PENDING_COOKIE = "ajc_admin_pending";
const PENDING_MINUTES = 5;
const PENDING_TRIES = 5;
const pendingCookieHeader = (token, maxAgeSeconds) =>
`${PENDING_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const pendingToken = req => (new RegExp(`(?:^|;\\s*)${PENDING_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1] || null;
// may this account still sign in here with Discord?
const discordAdmin = account => Boolean(account && account.adminDashboardAccess && account.discordId && totp.isOn(account) && !account.locked);
// `extraCookies` go out with the session's own.
const signIn = (res, extraCookies = []) => {
for (const [hash, expiry] of sessions) { for (const [hash, expiry] of sessions) {
if (expiry < Date.now()) { if (expiry < Date.now()) {
sessions.delete(hash); sessions.delete(hash);
@@ -121,7 +148,7 @@ const signIn = res => {
} }
const token = crypto.randomBytes(24).toString("hex"); const token = crypto.randomBytes(24).toString("hex");
sessions.set(sha256(token), Date.now() + SESSION_HOURS * 3600000); sessions.set(sha256(token), Date.now() + SESSION_HOURS * 3600000);
res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600)); res.setHeader("Set-Cookie", [cookieHeader(token, SESSION_HOURS * 3600), ...extraCookies]);
}; };
const signOut = (req, res) => { const signOut = (req, res) => {
@@ -143,6 +170,8 @@ const accountRow = (account, playing) => {
locked: account.locked, locked: account.locked,
twoStep: totp.isOn(account), twoStep: totp.isOn(account),
discord: account.discord, discord: account.discord,
adminDashboardAccess: Boolean(account.adminDashboardAccess),
guide: account.guideGiven === true,
bio: account.bio, bio: account.bio,
badges: account.badges, badges: account.badges,
featuresOff: accounts.FEATURES.filter(name => !accounts.featureOn(account, name)), featuresOff: accounts.FEATURES.filter(name => !accounts.featureOn(account, name)),
@@ -277,6 +306,12 @@ const ROOM_GROUP_NOTES = {
adventures: "adventure maps; nothing in them moves", adventures: "adventure maps; nothing in them moves",
}; };
// the theatre's browser (experimental; the server's game.html and client
// 1.3.3): off unless the admin turns it on. what players see in it never
// reaches the server; this only says whether the game offers it.
const THEATRE_BROWSER_SETTING = "theatreBrowser";
const theatreBrowserOn = () => accounts.setting(THEATRE_BROWSER_SETTING) === "on";
const debugState = () => ({ const debugState = () => ({
players: world.players().map(player => player.username).sort((a, b) => a.localeCompare(b)), players: world.players().map(player => player.username).sort((a, b) => a.localeCompare(b)),
rooms: defpacks.roomPaths().map(roomPath => { rooms: defpacks.roomPaths().map(roomPath => {
@@ -284,6 +319,9 @@ const debugState = () => ({
return {path: roomPath, group, note: ROOM_NOTES[roomPath] || ROOM_GROUP_NOTES[group] || ""}; return {path: roomPath, group, note: ROOM_NOTES[roomPath] || ROOM_GROUP_NOTES[group] || ""};
}).sort((a, b) => a.path.localeCompare(b.path)), }).sort((a, b) => a.path.localeCompare(b.path)),
everythingOnSale: sales.everythingOnSale(), everythingOnSale: sales.everythingOnSale(),
theatreBrowser: theatreBrowserOn(),
worlds: config.shards.length,
maxWorlds: config.worldNames.length,
}); });
const debugAct = body => { const debugAct = body => {
@@ -301,6 +339,17 @@ const debugAct = body => {
? "Sale dates are off: every item shows, for players who start the game from now on." ? "Sale dates are off: every item shows, for players who start the game from now on."
: "Sale dates are back on, for players who start the game from now on."}; : "Sale dates are back on, for players who start the game from now on."};
} }
if (body.action === "worlds") {
const count = world.setWorldCount(body.count);
return count ? {ok: `${count} ${count === 1 ? "world" : "worlds"}: ${config.shards.map(shard => shard.name).join(", ")}.`}
: {error: "A number of worlds, please."};
}
if (body.action === "theatreBrowser") {
accounts.setSetting(THEATRE_BROWSER_SETTING, body.on === true ? "on" : "off");
return {ok: body.on === true
? "The theatre browser is on, for players on client 1.3.3 or newer once their game page loads again."
: "The theatre browser is off, once players' game pages load again."};
}
return {error: "Unknown debug action."}; return {error: "Unknown debug action."};
}; };
@@ -376,6 +425,13 @@ const gift = (account, body) => {
const MAX_QUEST_LEVEL = 100; const MAX_QUEST_LEVEL = 100;
// a password for a player who lost theirs: read out or pasted to them, so
// nothing that looks like something else (0 O, 1 l I).
const TEMP_PASSWORD_LETTERS = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
const TEMP_PASSWORD_LENGTH = 12;
const randomPassword = () => Array.from({length: TEMP_PASSWORD_LENGTH},
() => TEMP_PASSWORD_LETTERS[crypto.randomInt(TEMP_PASSWORD_LETTERS.length)]).join("");
const wholeNumber = (value, min, max) => (Number.isInteger(value) && value >= min && value <= max ? value : null); const wholeNumber = (value, min, max) => (Number.isInteger(value) && value >= min && value <= max ? value : null);
// returns {ok: text} or {error: text}. // returns {ok: text} or {error: text}.
@@ -383,32 +439,12 @@ const act = (account, body) => {
const {actions, PERMANENT} = world.moderation; const {actions, PERMANENT} = world.moderation;
const name = account.username; const name = account.username;
switch (body.action) { switch (body.action) {
case "password": {
const passwordProblem = accounts.setPassword(account, body.password);
if (passwordProblem) {
return {error: passwordProblem === "weak_password" ? "That password is too easy to guess: it is a common one, or has your username in it."
: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."};
}
actions.kick(account);
manage.forget(account); // their account page too, whoever has it open
modpanel.forget(account);
return {ok: `${name} has a new password and was signed out.`};
}
// the owner locks and unlocks on the account page; this is for when // the owner locks and unlocks on the account page; this is for when
// they cannot. // they cannot.
case "unlock": case "unlock":
account.locked = false; account.locked = false;
accounts.save(account); accounts.save(account);
return {ok: `${name} is unlocked.`}; return {ok: `${name} is unlocked.`};
// for a player who lost their phone and their recovery codes: their
// password alone signs them in again.
case "twoStepOff":
if (!totp.isOn(account)) {
return {error: `${name} does not use 2FA.`};
}
totp.turnOff(account);
accounts.save(account);
return {ok: `2FA is off for ${name}.`};
case "rename": { case "rename": {
world.disconnect(account); world.disconnect(account);
manage.forget(account); manage.forget(account);
@@ -452,16 +488,13 @@ const act = (account, body) => {
world.checkNameTag(account); world.checkNameTag(account);
return {ok: account.badges.length ? `${name} has: ${badges.of(account).map(badge => badge.label).join(", ")}.` : `${name} has no badges.`}; return {ok: account.badges.length ? `${name} has: ${badges.of(account).map(badge => badge.label).join(", ")}.` : `${name} has no badges.`};
} }
// their Discord username, which they otherwise set on the account // their linked Discord account (lib/discord.js), taken off.
// page; empty takes it off.
case "discord": { case "discord": {
const discord = badges.discordName(body.name); // only taken off: a player links their own (lib/discord.js)
if (discord === null) { if (String(body.name || "") !== "") {
return {error: "Not a Discord username."}; return {error: "Players link their Discord themselves, on the account page."};
} }
account.discord = discord; return discordLinks.unlink(account) ? {ok: "Discord unlinked."} : {error: `${name} has no Discord linked.`};
accounts.save(account);
return {ok: discord ? `Discord set to "${discord}".` : "Discord cleared."};
} }
// their bio, which they otherwise write on the account page; empty // their bio, which they otherwise write on the account page; empty
// takes it off. // takes it off.
@@ -551,6 +584,46 @@ const act = (account, body) => {
`+${(account.permGrants || []).join(",") || "none"} -${(account.permDenies || []).join(",") || "none"}`); `+${(account.permGrants || []).join(",") || "none"} -${(account.permDenies || []).join(",") || "none"}`);
return {ok: `${name}'s permissions are saved.`}; return {ok: `${name}'s permissions are saved.`};
} }
// guide: lets the player log in as one (lib/accounts.js setLoginChoices).
// it shows from their next login.
// lost access: a new random password, shown here once. it signs them out
// everywhere (lib/accounts.js setPassword); with `twoStepOff` their 2FA
// goes as well, for a lost authenticator.
case "tempPassword": {
let password = randomPassword();
// the account rules want a capital, a small letter and a digit, and no
// common word or the username in it: draw again until it has them.
while (accounts.setPassword(account, password)) {
password = randomPassword();
}
const twoStepOff = body.twoStepOff === true && totp.isOn(account);
if (twoStepOff) {
totp.turnOff(account);
}
accounts.save(account);
world.disconnect(account);
manage.forget(account);
modpanel.forget(account);
modlog.record("admin", "temporary password set", account.username, twoStepOff ? "2FA turned off" : "");
return {ok: `${name}'s password is now ${password}${twoStepOff ? " and their 2FA is off" : ""}. Ask them to change it on their account page.`, password};
}
case "guide": {
const on = body.on === true;
account.guideGiven = on;
accounts.save(account);
modlog.record("admin", on ? "made a guide" : "no longer a guide", account.username, "");
return {ok: on ? `${name} is a guide from their next login.` : `${name} is no longer a guide from their next login.`};
}
case "adminDashboardAccess": {
const on = body.on === true;
if (on && !account.discordId) {
return {error: `${name} must link their Discord account before it can be allowed.`};
}
account.adminDashboardAccess = on;
accounts.save(account);
modlog.record("admin", on ? "admin dashboard access given" : "admin dashboard access removed", account.username, account.discord || "");
return {ok: on ? `${name} may now sign in to this dashboard with their linked Discord account.` : `${name}'s Discord dashboard access was removed.`};
}
case "rejectName": case "rejectName":
actions.rejectName(account, BY); actions.rejectName(account, BY);
manage.forget(account); manage.forget(account);
@@ -572,6 +645,15 @@ const act = (account, body) => {
case "clearDen": case "clearDen":
actions.clearDen(account); actions.clearDen(account);
return {ok: `Everything in ${name}'s den went back to their inventory.`}; return {ok: `Everything in ${name}'s den went back to their inventory.`};
case "clearWallPosts": {
const {posts, replies, walls} = actions.clearWallPosts(account);
if (!posts) {
return {error: `${name} has no posts on any Jammer Wall.`};
}
const text = `${posts} wall ${posts === 1 ? "post" : "posts"} by ${name} removed from ${walls} ${walls === 1 ? "wall" : "walls"}`
+ `${replies ? ` (with ${replies} ${replies === 1 ? "reply" : "replies"} to them)` : ""}.`;
return {ok: text, detail: `${posts} posts, ${replies} replies, ${walls} walls`};
}
case "gems": { case "gems": {
const amount = wholeNumber(body.amount, -MAX_GEMS, MAX_GEMS); const amount = wholeNumber(body.amount, -MAX_GEMS, MAX_GEMS);
if (amount === null) { if (amount === null) {
@@ -598,7 +680,7 @@ const PAGE_HEADERS = {
"X-Frame-Options": "DENY", "X-Frame-Options": "DENY",
"X-Content-Type-Options": "nosniff", "X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer", "Referrer-Policy": "no-referrer",
"Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; " "Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; media-src 'self'; font-src 'self'; "
+ "form-action 'none'; frame-ancestors 'none'; base-uri 'none'", + "form-action 'none'; frame-ancestors 'none'; base-uri 'none'",
}; };
@@ -620,6 +702,46 @@ const handle = async (req, res, url, from, web) => {
web.send(res, 200, await stats.withView(await fs.promises.readFile(path.join(config.publicDir, "admin.html"))), "text/html; charset=utf-8"); web.send(res, 200, await stats.withView(await fs.promises.readFile(path.join(config.publicDir, "admin.html"))), "text/html; charset=utf-8");
return; return;
} }
// Discord redirects do not carry the normal Strict admin cookie, so their
// own short-lived nonce cookie is Lax and scoped to this callback alone.
if (route === "GET /admin/discord/login") {
if (!hasPassword() || !discordLinks.linking()) {
res.writeHead(302, {Location: "/dashboard/admin?discord=off"});
res.end();
return;
}
const {url: to, nonce} = discordLinks.startAdmin();
res.setHeader("Set-Cookie", discordCookie(nonce, 600));
res.writeHead(302, {Location: to});
res.end();
return;
}
if (route === "GET /admin/discord/callback") {
const nonce = (new RegExp(`(?:^|;\\s*)${DISCORD_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1];
const result = url.searchParams.get("error") ? {error: "cancelled"}
: await discordLinks.finishAdmin(url.searchParams.get("state"), nonce, url.searchParams.get("code"));
// Discord has said who this is; the panel opens once that account's 2FA
// code is given too (POST /admin/api/discord/code).
if (result.ok && !discordAdmin(result.account)) {
result.ok = false;
result.error = totp.isOn(result.account) ? "denied" : "twostep";
}
const cookies = [discordCookie("", 0)];
if (result.ok) {
for (const [hash, pending] of pendingDiscord) {
if (pending.expiry < Date.now()) {
pendingDiscord.delete(hash);
}
}
const token = crypto.randomBytes(24).toString("hex");
pendingDiscord.set(sha256(token), {id: result.account.id, expiry: Date.now() + PENDING_MINUTES * 60000, tries: 0});
cookies.push(pendingCookieHeader(token, PENDING_MINUTES * 60));
}
res.setHeader("Set-Cookie", cookies);
res.writeHead(302, {Location: `/dashboard/admin?discord=${result.ok ? "code" : result.error}`});
res.end();
return;
}
if (req.method === "POST" && !sameOrigin(req)) { if (req.method === "POST" && !sameOrigin(req)) {
reply(403, {error: "forbidden"}); reply(403, {error: "forbidden"});
return; return;
@@ -628,7 +750,7 @@ const handle = async (req, res, url, from, web) => {
switch (route) { switch (route) {
case "GET /admin/api/state": case "GET /admin/api/state":
reply(200, {needsSetup: !hasPassword(), needsSetupCode: !from.local, signedIn: signedIn(req)}); reply(200, {needsSetup: !hasPassword(), needsSetupCode: !from.local, signedIn: signedIn(req), discordLogin: discordLinks.linking()});
return; return;
// choosing the first password. whoever is at the server's own machine may; // choosing the first password. whoever is at the server's own machine may;
@@ -678,6 +800,44 @@ const handle = async (req, res, url, from, web) => {
return; return;
} }
// the second half of a Discord sign-in: the linked account's 2FA code.
case "POST /admin/api/discord/code": {
if (tooManyFailures(from.key)) {
reply(429, {error: "Too many attempts. Try again in a few minutes."});
return;
}
const token = pendingToken(req);
const hash = token ? sha256(token) : null;
const pending = hash ? pendingDiscord.get(hash) : null;
const account = pending && pending.expiry > Date.now() ? accounts.byId(pending.id) : null;
if (!discordAdmin(account)) {
if (hash) {
pendingDiscord.delete(hash);
}
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
reply(401, {error: "The Discord sign-in expired. Sign in with Discord again.", expired: true});
return;
}
if (!totp.verify(account, String(body.code || ""))) {
recordFailure(from.key);
console.log(`[admin] wrong 2FA code after Discord for ${logText(account.username)} from ${logText(from.address)}`);
pending.tries++;
if (pending.tries >= PENDING_TRIES) {
pendingDiscord.delete(hash);
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
reply(401, {error: "Too many wrong codes. Sign in with Discord again.", expired: true});
return;
}
reply(401, {error: "Wrong code."});
return;
}
pendingDiscord.delete(hash);
signIn(res, [pendingCookieHeader("", 0)]);
console.log(`[admin] ${logText(account.username)} signed in with Discord and a code from ${logText(from.address)}`);
reply(200, {ok: true});
return;
}
case "POST /admin/api/logout": case "POST /admin/api/logout":
signOut(req, res); signOut(req, res);
reply(200, {ok: true}); reply(200, {ok: true});
@@ -727,6 +887,65 @@ const handle = async (req, res, url, from, web) => {
reply(200, overview()); reply(200, overview());
return; return;
case "GET /admin/api/discord":
reply(200, discordBot.dashboardStatus());
return;
case "POST /admin/api/discord/status": {
const statusCard = discordBot.setStatusSettings({title: body.title, note: body.note, banner: body.banner});
if (statusCard.error) {
reply(400, {error: statusCard.error});
return;
}
modlog.record("admin", "Discord public status card changed", "", `title: ${statusCard.title}, banner: ${statusCard.banner || "none"}`);
reply(200, {ok: "Status-card text saved. Use Publish now to update Discord.", statusCard});
return;
}
case "POST /admin/api/discord/status/publish": {
const result = await discordBot.publishStatus();
if (result.ok) {
modlog.record("admin", "Discord public status card published");
}
reply(result.ok ? 200 : 400, result);
return;
}
case "POST /admin/api/discord/config": {
const result = discordBot.updateDashboardConfig(body);
if (result.ok) {
modlog.record("admin", "Discord bot routing settings changed");
}
reply(result.ok ? 200 : 400, result);
return;
}
case "POST /admin/api/discord/security": {
const result = discordBot.updateSecuritySettings(body);
if (result.ok) {
modlog.record("admin", "Discord security settings changed");
}
reply(result.ok ? 200 : 400, result);
return;
}
case "POST /admin/api/discord/community": {
const result = discordBot.updateCommunitySettings(body);
if (result.ok) modlog.record("admin", "Discord community and ticket settings changed");
reply(result.ok ? 200 : 400, result);
return;
}
case "POST /admin/api/discord/control": {
const action = String(body.action || "");
const result = await discordBot.control(action);
if (result.ok) {
modlog.record("admin", `Discord bot ${action}`);
}
reply(result.ok ? 200 : 400, result);
return;
}
// a page of accounts by name (lib/staff.js says in what order), never // 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 // all of them: with thousands, sending every one every few seconds
// slowed the page and the game alike. // slowed the page and the game alike.
@@ -906,6 +1125,23 @@ const handle = async (req, res, url, from, web) => {
return; return;
} }
// codes for the game's Redeem Code window (lib/codes.js), each giving
// an item, gems or diamonds
case "GET /admin/api/codes":
reply(200, {codes: codes.list(), kinds: codes.KINDS});
return;
case "POST /admin/api/codes": {
const result = body.action === "remove"
? (codes.remove(body.code) ? {ok: "Code deleted."} : {error: "No such code."})
: codes.create(body);
if (result.ok) {
console.log(`[admin] redemption code ${logText(body.action === "remove" ? "deleted" : "made")}: ${logText(String(body.code || "").toUpperCase())}`);
}
reply(result.ok ? 200 : 400, result);
return;
}
// the message everyone is shown when they arrive; empty for none. // the message everyone is shown when they arrive; empty for none.
case "POST /admin/api/motd": case "POST /admin/api/motd":
world.setMotd(String(body.text || "")); world.setMotd(String(body.text || ""));
@@ -956,7 +1192,7 @@ const handle = async (req, res, url, from, web) => {
: "New masterpieces are approved as they are made. Ones already waiting still wait."}; : "New masterpieces are approved as they are made. Ones already waiting still wait."};
} }
else if (body.action === "approve") { else if (body.action === "approve") {
result = world.approveMasterpiece(id) ? {ok: "Approved. Its maker has been told and can hang it now."} : {error: "No such painting waiting."}; result = world.approveMasterpiece(id, "admin") ? {ok: "Approved. Its maker has been told and can hang it now."} : {error: "No such painting waiting."};
} }
else if (body.action === "reject" || body.action === "remove") { else if (body.action === "reject" || body.action === "remove") {
result = world.removeMasterpiece(id) result = world.removeMasterpiece(id)
@@ -1036,4 +1272,4 @@ const handle = async (req, res, url, from, web) => {
} }
}; };
module.exports = {load, handle, signedIn, PASSWORD_SETTING}; module.exports = {load, handle, signedIn, theatreBrowserOn, PASSWORD_SETTING};
+3 -1
View File
@@ -117,7 +117,9 @@ module.exports = ({enterRoom, findOnline, blocks}) => {
// PartyManager.customPartyJoinResponse: [success, reason] // PartyManager.customPartyJoinResponse: [success, reason]
const joinHosted = (session, host) => { const joinHosted = (session, host) => {
const party = host && partyOf(host); const party = host && partyOf(host);
if (!party || blocks.either(host, session.account)) { // A one-use staff teleport may inspect a hosted party despite a block;
// ordinary party joins retain the host's privacy rule.
if (!party || (!session.staffTravel && blocks.either(host, session.account))) {
session.sendXt("sjp", -1, 0, party ? "BLK" : "NPP"); session.sendXt("sjp", -1, 0, party ? "BLK" : "NPP");
return; return;
} }
+39 -3
View File
@@ -3,7 +3,7 @@
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const achievements = require("./achievements.js"); const achievements = require("./achievements.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const {activeAvatar, isUint} = require("./player.js"); const {activeAvatar, activePet, isUint} = require("./player.js");
// pets (client side: PetManager, PetXtCommManager). A pet's species and look // pets (client side: PetManager, PetXtCommManager). A pet's species and look
// are packed into three integers by PetManager.packPetBits; the species is // are packed into three integers by PetManager.packPetBits; the species is
@@ -30,6 +30,13 @@ const MASTERY_FULL = 100;
const MASTERY_PER_ROOM = 5; const MASTERY_PER_ROOM = 5;
const MASTERY_BITS = 0xF00; // the part of uBits PetInventory writes const MASTERY_BITS = 0xF00; // the part of uBits PetInventory writes
const SECONDS_TO_HATCH = 259200; // PetManager.hasHatched const SECONDS_TO_HATCH = 259200; // PetManager.hasHatched
// not one of the game's: the pet chooser's "play as your pet" switch
// (gui.PetInventory), kept with the user vars so it reaches the client at
// login. on, whichever pet is out stands in for the avatar, in any room, as
// at a Play-As-Your-Pet party.
const USER_VAR_PET_FORM = 9008;
const inPetForm = account => Number(account.userVars[USER_VAR_PET_FORM]) === 1 && Boolean(activePet(account));
const random = (min, max) => min + Math.floor(Math.random() * (max - min + 1)); const random = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
@@ -106,6 +113,24 @@ module.exports = ({others, findOnline, petFields}) => {
const ownPet = (account, invIdx) => account.pets.find(candidate => candidate.inv === Number(invIdx)); const ownPet = (account, invIdx) => account.pets.find(candidate => candidate.inv === Number(invIdx));
// tells the player and everyone who sees them whether the pet stands in
// for the avatar (UserCommXtCommManager, user communication type 13).
const sendPetForm = session => {
if (session.pos) {
const state = inPetForm(session.account) ? "on" : "off";
for (const other of [session, ...others(session)]) {
other.sendXt("uc", session.room.id, session.id, state, "13");
}
}
};
// the pet chooser's switch. on with no pet out is kept for the next pet.
const setPetForm = (session, on) => {
achievements.set(session.account, USER_VAR_PET_FORM, on ? 1 : 0);
accounts.save(session.account);
sendPetForm(session);
};
const handlers = { const handlers = {
// PetManager.onPetListResponse: [found, username, count, (invIdx, // PetManager.onPetListResponse: [found, username, count, (invIdx,
// createdTs, name, lBits, uBits, eBits, mastery, personality, toy, food, // createdTs, name, lBits, uBits, eBits, mastery, personality, toy, food,
@@ -146,6 +171,7 @@ module.exports = ({others, findOnline, petFields}) => {
session.sendXt("ps", -1, 0); session.sendXt("ps", -1, 0);
return; return;
} }
const wasPetForm = inPetForm(account);
activeAvatar(account).petInvId = pet ? pet.inv : 0; activeAvatar(account).petInvId = pet ? pet.inv : 0;
accounts.save(account); accounts.save(account);
const messageRoom = session.room ? session.room.id : -1; const messageRoom = session.room ? session.room.id : -1;
@@ -155,6 +181,11 @@ module.exports = ({others, findOnline, petFields}) => {
other.sendXt("ps", messageRoom, 1, session.id, ...petFields(pet)); other.sendXt("ps", messageRoom, 1, session.id, ...petFields(pet));
} }
} }
// with no pet out the avatar comes back; the next pet out takes its
// place again while the switch is on.
if (wasPetForm !== inPetForm(account)) {
sendPetForm(session);
}
}, },
// PetManager.onPetDismissResponse: [success, invIdx] // PetManager.onPetDismissResponse: [success, invIdx]
@@ -165,7 +196,11 @@ module.exports = ({others, findOnline, petFields}) => {
session.sendXt("pd", -1, 0, invIdx); session.sendXt("pd", -1, 0, invIdx);
return; return;
} }
const wasPetForm = inPetForm(account);
account.pets = account.pets.filter(candidate => candidate !== pet); account.pets = account.pets.filter(candidate => candidate !== pet);
if (wasPetForm && !inPetForm(account)) {
sendPetForm(session);
}
for (const avatar of account.avatars) { for (const avatar of account.avatars) {
if (avatar.petInvId === pet.inv) { if (avatar.petInvId === pet.inv) {
avatar.petInvId = 0; avatar.petInvId = 0;
@@ -199,7 +234,8 @@ module.exports = ({others, findOnline, petFields}) => {
// EggPetHatchedPopup: [petInvIdx, nameId1, nameId2] names a pet hatched // EggPetHatchedPopup: [petInvIdx, nameId1, nameId2] names a pet hatched
// from an egg. PetManager.onPetEggNameResponse: [success, invIdx, name]. // from an egg. PetManager.onPetEggNameResponse: [success, invIdx, name].
pn(session, roomId, [invIdx, name1, name2]) { pn(session, roomId, [invIdx, name1, name2]) {
const pet = ownPet(session.account, invIdx); const {account} = session;
const pet = ownPet(account, invIdx);
const def = pet && defpacks.petDef(pet.lBits & 0xFF); const def = pet && defpacks.petDef(pet.lBits & 0xFF);
if (!pet || ![name1, name2].every(isUint) || pet.name || !def || def.isEgg !== "1" if (!pet || ![name1, name2].every(isUint) || pet.name || !def || def.isEgg !== "1"
|| pet.createdAt + SECONDS_TO_HATCH > Math.floor(Date.now() / 1000)) { || pet.createdAt + SECONDS_TO_HATCH > Math.floor(Date.now() / 1000)) {
@@ -234,5 +270,5 @@ module.exports = ({others, findOnline, petFields}) => {
}, },
}; };
return {handlers, walked, giveCharacter, favouritesList, personalityList, PERSONALITY_LIST}; return {handlers, walked, giveCharacter, favouritesList, personalityList, PERSONALITY_LIST, inPetForm, setPetForm};
}; };
+15 -3
View File
@@ -1,6 +1,7 @@
"use strict"; "use strict";
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const wearRules = require("./wearrules.js");
// accessors over an account's animals, pets and items (shape: accounts.js). // accessors over an account's animals, pets and items (shape: accounts.js).
// SbiConstants.CURRENCY_NAMES; an item's currencyType indexes into this. // SbiConstants.CURRENCY_NAMES; an item's currencyType indexes into this.
@@ -32,13 +33,24 @@ const avatarById = (account, perUserAvId) =>
const activePet = account => account.pets.find(pet => pet.inv === activeAvatar(account).petInvId) || null; const activePet = account => account.pets.find(pet => pet.inv === activeAvatar(account).petInvId) || null;
const wornItems = (account, avatar) => account.items.filter(item => item.on.includes(avatar.avInvId)); // The persisted state is also filtered here, not only where a player tries
// to put an item on. That keeps an old/corrupt pairing from reaching player
// cards or other people in a room while a dashboard rule is being applied.
const wornItems = (account, avatar) => account.items.filter(item => item.on.includes(avatar.avInvId)
&& wearRules.mayWear(item.def, avatar.type));
// item.EquippedAvatars: comma-separated 32-bit words, one bit per avInvId of // item.EquippedAvatars: comma-separated 32-bit words, one bit per avInvId of
// an animal wearing the item. // an animal wearing the item.
const equippedBits = item => { // With an account, omit stale pairings that are no longer allowed. The full
// inventory protocol otherwise exposes those bits and a later avatar switch
// can appear to revive a prohibited item.
const equippedBits = (item, account = null) => {
const words = [0]; const words = [0];
for (const avInvId of item.on) { const wornBy = account ? item.on.filter(avInvId => {
const avatar = account.avatars.find(candidate => candidate.avInvId === avInvId);
return avatar && wearRules.mayWear(item.def, avatar.type);
}) : item.on;
for (const avInvId of wornBy) {
const word = avInvId >>> 5; const word = avInvId >>> 5;
while (words.length <= word) { while (words.length <= word) {
words.push(0); words.push(0);
+21
View File
@@ -0,0 +1,21 @@
"use strict";
const config = require("../config.js");
const send = async ({to, subject, text}) => {
if (!config.recoveryMail) {
return false;
}
try {
const response = await fetch(config.recoveryMail.url, {method: "POST", headers: {
"Content-Type": "application/json", "Authorization": `Bearer ${config.recoveryMail.token}`,
}, body: JSON.stringify({to, subject, text})});
return response.ok;
}
catch (err) {
console.error("[recovery] email delivery failed");
return false;
}
};
module.exports = {available: () => Boolean(config.recoveryMail), send};
+19 -2
View File
@@ -45,6 +45,7 @@ const MERGE_SECONDS = 10;
const perTenMinutes = limits.limiter(10, 600000); const perTenMinutes = limits.limiter(10, 600000);
const now = () => Math.floor(Date.now() / 1000); const now = () => Math.floor(Date.now() / 1000);
const clean = (text, max) => String(text === undefined ? "" : text).replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, " ").trim().slice(0, max); const clean = (text, max) => String(text === undefined ? "" : text).replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, " ").trim().slice(0, max);
const listeners = new Set();
const load = () => accounts.database().exec(SCHEMA); const load = () => accounts.database().exec(SCHEMA);
@@ -68,9 +69,18 @@ const file = ({reporter, target, reason, detail = "", context = "", room = ""})
if (!perTenMinutes.allow(reporter.toLowerCase()) || openCount() >= MAX_OPEN) { if (!perTenMinutes.allow(reporter.toLowerCase()) || openCount() >= MAX_OPEN) {
return false; return false;
} }
db.prepare("INSERT INTO reports (created_at, reporter, target, reason, detail, context, room) VALUES (?, ?, ?, ?, ?, ?, ?)") const inserted = db.prepare("INSERT INTO reports (created_at, reporter, target, reason, detail, context, room) VALUES (?, ?, ?, ?, ?, ?, ?)")
.run(now(), reporter, target, Number.isInteger(reason) ? reason : 0, clean(detail, MAX_DETAIL), clean(context, MAX_CONTEXT), clean(room, 100)); .run(now(), reporter, target, Number.isInteger(reason) ? reason : 0, clean(detail, MAX_DETAIL), clean(context, MAX_CONTEXT), clean(room, 100));
console.log(`[world] ${logText(reporter)} reported "${logText(target)}" (${logText(REASONS[reason] || `reason ${reason}`)})`); console.log(`[world] ${logText(reporter)} reported "${logText(target)}" (${logText(REASONS[reason] || `reason ${reason}`)})`);
const report = row(db.prepare("SELECT * FROM reports WHERE id = ?").get(Number(inserted.lastInsertRowid)));
for (const listener of listeners) {
try {
listener(report);
}
catch (err) {
console.error(`[reports] listener failed: ${logText(err.message)}`);
}
}
return true; return true;
}; };
@@ -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; 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. // 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") const about = username => accounts.database().prepare("SELECT * FROM reports WHERE target = ? COLLATE NOCASE ORDER BY id DESC LIMIT 100")
.all(String(username)).map(row); .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};
+47 -9
View File
@@ -15,26 +15,34 @@ const totp = require("./totp.js");
// higher up, and for the admin in the end. // higher up, and for the admin in the end.
const PERMISSIONS = { 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)", "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)", "staff.list": "see which staff are online (!staff)",
"player.warn": "warn a player, take a warning back and send them a message (!warn, !unwarn, !warnings, !message)", "player.warn": "warn a player, take a warning back, send them a message and mark a report dealt with (!warn, !unwarn, !warnings, !message)",
"player.goto": "go to the room a player is in (!goto)", "player.goto": "go to the room a player is in (!goto)",
"chat.silence": "silence and unsilence a player (!silence)", "chat.silence": "silence and unsilence a player (!silence)",
"player.kick": "disconnect a player (!kick)", "player.kick": "disconnect a player (!kick)",
"player.summon": "bring a player to the room you are in (!summon)", "player.summon": "bring a player to the room you are in (!summon)",
"staff.invisible": "go unseen in rooms, as the game's moderators could (!invisible)", "staff.invisible": "go unseen in rooms, as the game's moderators could (!invisible)",
"player.ban": "ban, unban and change a ban's reason", "player.ban": "ban, unban, change a ban's reason and answer ban appeals",
"player.names": "reject or accept a name, clear a bio", "player.names": "reject or accept a name, answer requests for a new one, clear a bio, remove a player's Jammer Wall posts",
"address.ban": "ban the address a player last signed in from", "address.ban": "ban the address a player last signed in from, or the computers they use, and lift those bans",
"items.approve": "approve or turn away the items and pictures players make, when the admin has asked for that", "items.approve": "approve or turn away the items and pictures players make, when the admin has asked for that",
"masterpieces.approve": "approve or remove the paintings players frame as masterpieces (the Masterpieces page)",
"items.restrict": "stop a clothing item from being worn by selected animal types",
"items.create": "make new items from the game's art, change and delete them, lock items out of the item finder and take items from players (!item, !lock, !unlock, !locked, !take)", "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 = ["player.view", "staff.list", "player.warn", "player.goto", "chat.silence"]; 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"]; const MODERATOR = [...HELPER, "player.kick", "player.summon", "staff.invisible", "player.ban", "player.names", "address.ban", "items.approve", "masterpieces.approve", "items.restrict", "theater.control", "staff.log"];
const ADMIN = [...MODERATOR, "items.create"]; const ADMIN = [...MODERATOR, "server.announce", "items.create", "room.effects", "music.upload"];
// a developer makes things, and moderates nobody. // a developer makes things, and moderates nobody.
const DEVELOPER = ["staff.list", "items.create"]; const DEVELOPER = ["server.view", "staff.list", "items.create", "room.effects", "theater.control"];
const ROLES = { const ROLES = {
developer: {rank: 1, label: "Developer", permissions: DEVELOPER}, developer: {rank: 1, label: "Developer", permissions: DEVELOPER},
@@ -112,6 +120,36 @@ const setRolePermissions = (role, list) => {
return true; return true;
}; };
// masterpieces.approve was split from items.approve (2026-10-21), which
// judged paintings before. once: a role list the admin changed, and a staff
// member's own grants and denies, that held items.approve hold this too.
const SPLIT_SETTING = "permissionSplitMasterpieces";
const load = () => {
if (accounts.setting(SPLIT_SETTING)) {
return;
}
const withSplit = list => (Array.isArray(list) && list.includes("items.approve") && !list.includes("masterpieces.approve")
? [...list, "masterpieces.approve"] : list);
const changed = {...overrides()};
for (const role of Object.keys(changed)) {
changed[role] = withSplit(changed[role]);
}
accounts.setSetting(ROLE_SETTING, JSON.stringify(changed));
roleOverrides = changed;
for (const account of accounts.all()) {
if (account.permGrants || account.permDenies) {
const grants = withSplit(account.permGrants);
const denies = withSplit(account.permDenies);
if (grants !== account.permGrants || denies !== account.permDenies) {
if (grants) account.permGrants = grants;
if (denies) account.permDenies = denies;
accounts.save(account);
}
}
}
accounts.setSetting(SPLIT_SETTING, "1");
};
const permissionsOf = account => { const permissionsOf = account => {
const role = roleOf(account); const role = roleOf(account);
if (!role) { if (!role) {
@@ -163,5 +201,5 @@ const setRole = (account, role) => {
return true; return true;
}; };
module.exports = {PERMISSIONS, ROLES, roleOf, rankOf, isActiveStaff, permissionsOf, rolePermissions, roleChanged, setRolePermissions, module.exports = {load, PERMISSIONS, ROLES, roleOf, rankOf, isActiveStaff, permissionsOf, rolePermissions, roleChanged, setRolePermissions,
setAccountPermissions, can, outranks, setRole}; setAccountPermissions, can, outranks, setRole};
+7 -3
View File
@@ -14,8 +14,9 @@ const defpacks = require("./defpacks.js");
// then AMF3), so reading it here costs no extra download once anyone has // then AMF3), so reading it here costs no extra download once anyone has
// been in the room. // been in the room.
// what the room editor left in files nobody named. // what the room editor left in files nobody named ("default": the museum's
const UNNAMED = "Display Name"; // theatre).
const UNNAMED = ["display name", "default"];
// rooms whose file has no name and whose path does not spell it either. // rooms whose file has no name and whose path does not spell it either.
const NAMES = new Map([ const NAMES = new Map([
["jamaa_township.room_diamonds", "Diamond Shop"], ["jamaa_township.room_diamonds", "Diamond Shop"],
@@ -24,6 +25,9 @@ const NAMES = new Map([
["aussie.room_main", "Kimbara Outback"], ["aussie.room_main", "Kimbara Outback"],
["aussie.room_aushop", "Outback Imports"], ["aussie.room_aushop", "Outback Imports"],
["aussie.room_hos", "Medical Center"], ["aussie.room_hos", "Medical Center"],
["appondale.room_museumtheater", "Museum Theater"],
["crystal_sands.room_tiertheater", "Tierney's Theater"],
["lost_temple_of_zios.bb_theater", "Temple Theater"],
]); ]);
const VOLUME_SHOP = 12; // ActorVolume.type: clicking it opens generic list `typeDefId` const VOLUME_SHOP = 12; // ActorVolume.type: clicking it opens generic list `typeDefId`
@@ -37,7 +41,7 @@ const parse = body => {
const settings = (room.actors.ActorSettings || [])[0] || {}; const settings = (room.actors.ActorSettings || [])[0] || {};
const volumes = room.actors.ActorVolume || []; const volumes = room.actors.ActorVolume || [];
return { return {
name: typeof settings.name === "string" && settings.name.trim() !== UNNAMED ? settings.name.trim() : "", name: typeof settings.name === "string" && !UNNAMED.includes(settings.name.trim().toLowerCase()) ? settings.name.trim() : "",
shops: new Set(volumes.filter(volume => Number(volume.type) === VOLUME_SHOP).map(volume => Number(volume.typeDefId))), shops: new Set(volumes.filter(volume => Number(volume.type) === VOLUME_SHOP).map(volume => Number(volume.typeDefId))),
}; };
}; };
+32 -4
View File
@@ -18,7 +18,10 @@ const limits = require("./limits.js");
const POLICY = '<cross-domain-policy><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>'; const POLICY = '<cross-domain-policy><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>';
const MAX_MESSAGE = 64 * 1024; const MAX_MESSAGE = 64 * 1024;
const RATE_WINDOW_MS = 10000; const RATE_WINDOW_MS = 10000;
const MAX_BACKLOG = 4 * 1024 * 1024; // above what login writes in one go before the client reads any of it: every
// custom colour and custom item def (~4.2 MB on 2026-10-19, at the caps of
// 20000 colours and 5000 clothing), which a 4 MB limit cut off for everyone.
const MAX_BACKLOG = 16 * 1024 * 1024;
const MAX_ERRORS_PER_WINDOW = 20; const MAX_ERRORS_PER_WINDOW = 20;
// the Create Account screens are done in a few minutes; a guest connection // the Create Account screens are done in a few minutes; a guest connection
// does not get to stay for as long as it keeps sending something. // does not get to stay for as long as it keeps sending something.
@@ -28,6 +31,8 @@ const SIGNUP_LIFETIME_MS = 5 * 60000;
const forLog = message => message.replace(/(<pword><!\[CDATA\[)[\s\S]*?(\]\]>)/, "$1(hidden)$2"); const forLog = message => message.replace(/(<pword><!\[CDATA\[)[\s\S]*?(\]\]>)/, "$1(hidden)$2");
const connections = new Map(); // remote address -> open sockets const connections = new Map(); // remote address -> open sockets
let connectionCount = 0;
const metrics = {accepted: 0, rejected: 0, floodDisconnects: 0, handlerErrors: 0};
let nextUserId = 1; let nextUserId = 1;
@@ -139,13 +144,18 @@ const start = handlers => new Promise((resolve, reject) => {
const onConnection = socket => { const onConnection = socket => {
const address = limits.key(socket.remoteAddress); const address = limits.key(socket.remoteAddress);
const open = connections.get(address) || 0; const open = connections.get(address) || 0;
const total = [...connections.values()].reduce((sum, count) => sum + count, 0); // Kept as a counter instead of summing every address on every new socket.
// Under a burst of logins the old O(addresses) work delayed everyone else.
const total = connectionCount;
socket.on("error", () => {}); socket.on("error", () => {});
if (open >= config.maxConnectionsPerAddress || total >= config.maxConnections) { if (open >= config.maxConnectionsPerAddress || total >= config.maxConnections) {
metrics.rejected++;
socket.destroy(); socket.destroy();
return; return;
} }
connections.set(address, open + 1); connections.set(address, open + 1);
connectionCount++;
metrics.accepted++;
const session = new Session(socket); const session = new Session(socket);
let buffer = Buffer.alloc(0); let buffer = Buffer.alloc(0);
@@ -179,11 +189,15 @@ const start = handlers => new Promise((resolve, reject) => {
} }
bytesInWindow += chunk.length; bytesInWindow += chunk.length;
if (bytesInWindow > config.maxBytesPerTenSeconds) { if (bytesInWindow > config.maxBytesPerTenSeconds) {
metrics.floodDisconnects++;
console.log(`[game] ${logText(session.name)} disconnected for flooding`); console.log(`[game] ${logText(session.name)} disconnected for flooding`);
socket.destroy(); socket.destroy();
return; return;
} }
buffer = Buffer.concat([buffer, chunk]); // Node normally gives complete SmartFox packets in one chunk. Avoiding
// Buffer.concat in that common case reduces allocation and GC during
// busy logins; fragments still retain the exact old behaviour.
buffer = buffer.length === 0 ? chunk : Buffer.concat([buffer, chunk]);
let end; let end;
while ((end = buffer.indexOf(0)) !== -1) { while ((end = buffer.indexOf(0)) !== -1) {
if (end > MAX_MESSAGE) { if (end > MAX_MESSAGE) {
@@ -191,6 +205,7 @@ const start = handlers => new Promise((resolve, reject) => {
return; return;
} }
if (++messagesInWindow > config.maxMessagesPerTenSeconds) { if (++messagesInWindow > config.maxMessagesPerTenSeconds) {
metrics.floodDisconnects++;
console.log(`[game] ${logText(session.name)} disconnected for flooding`); console.log(`[game] ${logText(session.name)} disconnected for flooding`);
socket.destroy(); socket.destroy();
return; return;
@@ -201,6 +216,7 @@ const start = handlers => new Promise((resolve, reject) => {
dispatch(session, message); dispatch(session, message);
} }
catch (err) { catch (err) {
metrics.handlerErrors++;
// one line a failure, and an end to them: a client that sends // one line a failure, and an end to them: a client that sends
// nonsense in a loop is not to fill the log. // nonsense in a loop is not to fill the log.
const where = String(err.stack || "").split("\n")[1] || ""; const where = String(err.stack || "").split("\n")[1] || "";
@@ -229,6 +245,7 @@ const start = handlers => new Promise((resolve, reject) => {
else { else {
connections.delete(address); connections.delete(address);
} }
connectionCount = Math.max(0, connectionCount - 1);
console.log(`[game] ${logText(session.name)} disconnected`); console.log(`[game] ${logText(session.name)} disconnected`);
// nothing thrown while a player is seen off may take the server down. // nothing thrown while a player is seen off may take the server down.
try { try {
@@ -277,4 +294,15 @@ const start = handlers => new Promise((resolve, reject) => {
}); });
}); });
module.exports = {start}; // This intentionally exposes counts only: staff can see whether the service
// is healthy without receiving player addresses or packet contents.
const health = () => ({
openConnections: connectionCount,
connectedAddresses: connections.size,
accepted: metrics.accepted,
rejected: metrics.rejected,
floodDisconnects: metrics.floodDisconnects,
handlerErrors: metrics.handlerErrors,
});
module.exports = {start, health};
+4 -4
View File
@@ -141,19 +141,19 @@ const byDevice = query => {
// other accounts the same person may have: those that used one of its // other accounts the same person may have: those that used one of its
// computers (lib/devices.js), and those that signed in from one of its // computers (lib/devices.js), and those that signed in from one of its
// addresses in the last 90 days. [{username, devices: [kind], weak, // addresses in the last 90 days. [{username, devices: [kind],
// addresses: count, online, banned}], the likeliest first. the addresses // addresses: count, online, banned}], the likeliest first. the addresses
// themselves are not given: moderators do not see them. // themselves are not given: moderators do not see them.
const altsOf = account => { const altsOf = account => {
const found = new Map(); const found = new Map();
const entry = username => { const entry = username => {
if (!found.has(username)) { if (!found.has(username)) {
found.set(username, {username, devices: [], weak: false, addresses: 0}); found.set(username, {username, devices: [], addresses: 0});
} }
return found.get(username); return found.get(username);
}; };
for (const alt of devices.alts(account)) { for (const alt of devices.alts(account)) {
Object.assign(entry(alt.username), {devices: alt.kinds, weak: alt.weak}); Object.assign(entry(alt.username), {devices: alt.kinds});
} }
const mine = new Set(account.logins.filter(login => login.ok && login.address && !limits.isLoopback(login.address)).map(login => login.address)); const mine = new Set(account.logins.filter(login => login.ok && login.address && !limits.isLoopback(login.address)).map(login => login.address));
if (mine.size) { if (mine.size) {
@@ -170,7 +170,7 @@ const altsOf = account => {
const other = accounts.byName(alt.username); const other = accounts.byName(alt.username);
return {...alt, online: Boolean(world.findOnline(alt.username)), banned: other ? world.moderation.banRemaining(other) : 0, return {...alt, online: Boolean(world.findOnline(alt.username)), banned: other ? world.moderation.banRemaining(other) : 0,
deviceBanned: other ? devices.bannedId(other) !== 0 : false}; deviceBanned: other ? devices.bannedId(other) !== 0 : false};
}).sort((one, other) => Number(other.devices.length > 0 && !other.weak) - Number(one.devices.length > 0 && !one.weak) }).sort((one, other) => Number(other.devices.length > 0) - Number(one.devices.length > 0)
|| other.devices.length - one.devices.length || other.addresses - one.addresses || one.username.localeCompare(other.username)).slice(0, 100); || other.devices.length - one.devices.length || other.addresses - one.addresses || one.username.localeCompare(other.username)).slice(0, 100);
}; };
+67
View File
@@ -0,0 +1,67 @@
"use strict";
const zlib = require("zlib");
const amf3 = require("./amf3.js");
// a room file of a seasonal theme comes from an older build (lib/http.js,
// roomAsSeenBy in lib/world.js), and so do its clickable spots: a shop there
// names the generic list it had then, which today's lists may have as
// something else or as nothing, so one theme's shops worked and another's
// did not. each spot the room has today too (by its name) is given today's
// list, kind and message; what only the old room has stays as it was.
// the volume fields that say what a click does (RoomManagerWorld: type 1 a
// minigame by typeDefId, 7 a message, 12 a generic list)
const ACTION_FIELDS = ["type", "typeDefId", "message"];
const MAX_KEPT = 40; // rooms remembered, made once each (files of up to a few MB)
const kept = new Map(); // old file's path -> the file with today's spots, or null for "as it was"
const volumes = room => (room && room.actors && Array.isArray(room.actors.ActorVolume) ? room.actors.ActorVolume : []);
const withTodaysSpots = (oldBody, currentBody) => {
const old = amf3.decode(zlib.inflateSync(oldBody));
const today = new Map(volumes(amf3.decode(zlib.inflateSync(currentBody))).filter(volume => volume && volume.name).map(volume => [volume.name, volume]));
let changed = false;
for (const volume of volumes(old)) {
const now = volume && today.get(volume.name);
if (now && ACTION_FIELDS.some(field => volume[field] !== now[field])) {
for (const field of ACTION_FIELDS) {
if (now[field] === undefined) {
delete volume[field];
}
else {
volume[field] = now[field];
}
}
changed = true;
}
}
return changed ? zlib.deflateSync(amf3.encode(old)) : oldBody;
};
// `oldBody` with today's spots, `current` giving today's file (or null);
// the old one as it was when that cannot be had or read.
const fix = async (key, oldBody, current) => {
if (kept.has(key)) {
return kept.get(key) || oldBody;
}
let body = oldBody;
try {
const currentBody = await current();
if (currentBody) {
body = withTodaysSpots(oldBody, currentBody);
}
}
catch (err) {
console.log(`[themes] ${key}: ${err.message}`);
body = oldBody;
}
if (kept.size >= MAX_KEPT) {
kept.delete(kept.keys().next().value);
}
kept.set(key, body === oldBody ? null : body);
return body;
};
module.exports = {fix};
+17 -7
View File
@@ -15,7 +15,7 @@ const TYPE_CLOTHING = 0;
const TYPE_DEN_ITEM = 1; const TYPE_DEN_ITEM = 1;
const TYPE_PET = 3; const TYPE_PET = 3;
const MAX_TRADE_ITEMS = 50; const MAX_TRADE_ITEMS = 200; // on a trade list (the game sets no end to it; past this the rest were dropped)
const MAX_PETS = 1000; // as in lib/pets.js const MAX_PETS = 1000; // as in lib/pets.js
// "ti" request steps (first parameter from the client) // "ti" request steps (first parameter from the client)
@@ -53,8 +53,11 @@ module.exports = ({findOnline, blocks}) => {
// createdTs, lBits, uBits, eBits, name, personality, toy, food)...] // createdTs, lBits, uBits, eBits, name, personality, toy, food)...]
const sendTradeList = (to, account) => { const sendTradeList = (to, account) => {
const listed = type => account.tradeList.filter(entry => entry.type === type).map(entry => entry.inv); const listed = type => account.tradeList.filter(entry => entry.type === type).map(entry => entry.inv);
const clothing = account.items.filter(item => listed(TYPE_CLOTHING).includes(item.inv)); // one whose def is gone (a custom item deleted) is left out: the client
const denItems = account.denItems.filter(item => listed(TYPE_DEN_ITEM).includes(item.inv) && masterpieces.itemApproved(item)); // cannot make an item of it, and the list stopped there.
const clothing = account.items.filter(item => listed(TYPE_CLOTHING).includes(item.inv) && defpacks.itemDef(item.def));
const denItems = account.denItems.filter(item => listed(TYPE_DEN_ITEM).includes(item.inv) && masterpieces.itemApproved(item)
&& defpacks.denItemDef(item.def));
const pets = account.pets.filter(pet => listed(TYPE_PET).includes(pet.inv)); const pets = account.pets.filter(pet => listed(TYPE_PET).includes(pet.inv));
to.sendXt("tl", -1, account.username, to.sendXt("tl", -1, account.username,
clothing.length, ...clothing.flatMap(item => [item.def, item.inv, item.color]), clothing.length, ...clothing.flatMap(item => [item.def, item.inv, item.color]),
@@ -71,8 +74,10 @@ module.exports = ({findOnline, blocks}) => {
(type === TYPE_CLOTHING ? account.items : type === TYPE_DEN_ITEM ? account.denItems : type === TYPE_PET ? account.pets : []); (type === TYPE_CLOTHING ? account.items : type === TYPE_DEN_ITEM ? account.denItems : type === TYPE_PET ? account.pets : []);
// A masterpiece still waiting for review is nobody's to trade. // A masterpiece still waiting for review is nobody's to trade.
// nor one whose def is gone.
const find = (account, type, inv) => collectionOf(account, type) const find = (account, type, inv) => collectionOf(account, type)
.find(entry => entry.inv === inv && (type !== TYPE_DEN_ITEM || masterpieces.itemApproved(entry))); .find(entry => entry.inv === inv && (type !== TYPE_DEN_ITEM || masterpieces.itemApproved(entry))
&& (type === TYPE_CLOTHING ? Boolean(defpacks.itemDef(entry.def)) : type === TYPE_DEN_ITEM ? Boolean(defpacks.denItemDef(entry.def)) : true));
// the field layouts differ between the offer the owner is shown (no // the field layouts differ between the offer the owner is shown (no
// inventory ids for clothing and den items) and the completed trade. // inventory ids for clothing and den items) and the completed trade.
@@ -129,6 +134,10 @@ module.exports = ({findOnline, blocks}) => {
return coming === 0 || collectionOf(account, type).length + coming - gives.filter(item => item.type === type).length <= max; return coming === 0 || collectionOf(account, type).length + coming - gives.filter(item => item.type === type).length <= max;
}); });
const endTrade = trade => {
trade.requester.trade = trade.owner.trade = null;
};
// ends the trade `session` is part of, telling the other side with `status`. // ends the trade `session` is part of, telling the other side with `status`.
const abandon = (session, status) => { const abandon = (session, status) => {
const {trade} = session; const {trade} = session;
@@ -136,7 +145,7 @@ module.exports = ({findOnline, blocks}) => {
return; return;
} }
const other = trade.requester === session ? trade.owner : trade.requester; const other = trade.requester === session ? trade.owner : trade.requester;
trade.requester.trade = trade.owner.trade = null; endTrade(trade);
other.sendXt("ti", -1, status, session.account.username, USERNAME_SHOWN); other.sendXt("ti", -1, status, session.account.username, USERNAME_SHOWN);
}; };
@@ -250,7 +259,7 @@ module.exports = ({findOnline, blocks}) => {
return; return;
} }
const {requester, owner, wantedType, wanted, offered} = trade; const {requester, owner, wantedType, wanted, offered} = trade;
requester.trade = owner.trade = null; endTrade(trade);
// either side may have recycled or re-traded something while deciding. // either side may have recycled or re-traded something while deciding.
const stillThere = collectionOf(owner.account, wantedType).includes(wanted) const stillThere = collectionOf(owner.account, wantedType).includes(wanted)
&& offered.every(item => collectionOf(requester.account, item.type).includes(item.entry)) && offered.every(item => collectionOf(requester.account, item.type).includes(item.entry))
@@ -312,7 +321,8 @@ module.exports = ({findOnline, blocks}) => {
sendTradeList(session, account); sendTradeList(session, account);
}, },
// ["1"/"0"]: busy flag while the trade window is open; nothing to answer. // ["1"/"0"]: busy flag while the trade window is open; nothing to
// answer.
tb() {}, tb() {},
ti(session, roomId, params) { ti(session, roomId, params) {
+3 -2
View File
@@ -77,10 +77,11 @@ const whole = value => (Number.isInteger(Number(value)) ? Number(value) : 0);
// the photo booth picture ("pb", PlayerWallGui): one level deeper than the // the photo booth picture ("pb", PlayerWallGui): one level deeper than the
// rest, {avatar: {id, color1.., eyes, pattern}, bgid, pet: {ts, lbits, ..} | // rest, {avatar: {id, color1.., eyes, pattern}, bgid, pet: {ts, lbits, ..} |
// null, items: [{id, color}, ..]}. it was turned away as too deep, and the // null, items: [{id, color}, ..]}. it was turned away as too deep, and the
// owner's whole change with it: the photo never stayed. // owner's whole change with it: the photo never stayed. an animal wearing
// nothing has no items list at all (null), which was turned away too.
const MAX_PHOTO_ITEMS = 30; const MAX_PHOTO_ITEMS = 30;
const photoParam = value => value === null || (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length <= 6 const photoParam = value => value === null || (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length <= 6
&& Object.entries(value).every(([key, part]) => (key === "items" ? Array.isArray(part) && part.length <= MAX_PHOTO_ITEMS && part.every(flat) && Object.entries(value).every(([key, part]) => (key === "items" ? part === null || (Array.isArray(part) && part.length <= MAX_PHOTO_ITEMS && part.every(flat))
: key === "avatar" || key === "pet" ? part === null || flat(part) : scalar(part)))); : key === "avatar" || key === "pet" ? part === null || flat(part) : scalar(part))));
module.exports = ({blocks, findOnline}) => { module.exports = ({blocks, findOnline}) => {
+91
View File
@@ -0,0 +1,91 @@
"use strict";
// Loaded only when a rule is read or saved. defpacks.js is imported while
// accounts.js is still defining its exports, so a top-level require here
// would retain that partial `{}` forever.
const accounts = () => require("./accounts.js");
// Clothing that staff have said must not be worn by certain animal types.
// This is deliberately its own small module: game code, def packs and the
// dashboards all ask the same source of truth, while itemcontrol.js owns
// validating dashboard input and removing existing uses.
const SETTING = "clothingWearRules";
let rules = null; // Map<clothing def id, Set<avatar type>>
const positiveInteger = value => Number.isSafeInteger(value) && value > 0;
const ruleMap = () => {
if (rules) {
return rules;
}
let saved = {};
try {
const parsed = JSON.parse(accounts().setting(SETTING) || "{}");
saved = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
}
catch {
saved = {};
}
rules = new Map();
for (const [id, types] of Object.entries(saved)) {
const itemId = Number(id);
if (!positiveInteger(itemId) || !Array.isArray(types)) {
continue;
}
const blocked = new Set(types.map(Number).filter(positiveInteger));
if (blocked.size) {
rules.set(itemId, blocked);
}
}
return rules;
};
const save = () => {
const stored = {};
for (const [id, types] of [...ruleMap()].sort(([one], [two]) => one - two)) {
stored[id] = [...types].sort((one, two) => one - two);
}
accounts().setSetting(SETTING, JSON.stringify(stored));
};
const blockedTypes = itemId => [...(ruleMap().get(Number(itemId)) || [])].sort((one, two) => one - two);
const all = () => [...ruleMap()].map(([id]) => ({id, blocked: blockedTypes(id)})).sort((one, two) => one.id - two.id);
const mayWear = (itemId, avatarType) => !ruleMap().get(Number(itemId))?.has(Number(avatarType));
// `types` has already been checked against the avatar definitions by
// itemcontrol.js. Keeping this module generic lets it also be used while a
// def pack is being made, without a defpacks <-> wearrules dependency cycle.
const setBlockedTypes = (itemId, types) => {
const id = Number(itemId);
if (!positiveInteger(id)) {
return {changed: false, blocked: []};
}
const next = new Set((Array.isArray(types) ? types : []).map(Number).filter(positiveInteger));
const before = blockedTypes(id);
if (next.size) {
ruleMap().set(id, next);
}
else {
ruleMap().delete(id);
}
const after = blockedTypes(id);
const changed = before.length !== after.length || before.some((type, index) => type !== after[index]);
if (changed) {
save();
}
return {changed, blocked: after};
};
// Custom clothing ids are never reused, but clearing their rule at deletion
// keeps the setting accurate and avoids showing a stale dashboard entry.
const forget = itemId => {
if (ruleMap().delete(Number(itemId))) {
save();
}
};
module.exports = {blockedTypes, all, mayWear, setBlockedTypes, forget};
+505 -44
View File
@@ -19,12 +19,16 @@ const badges = require("./badges.js");
const bans = require("./bans.js"); const bans = require("./bans.js");
const devices = require("./devices.js"); const devices = require("./devices.js");
const chatlog = require("./chatlog.js"); const chatlog = require("./chatlog.js");
const support = require("./support.js");
const codes = require("./codes.js");
const chatFilter = require("./chatfilter.js"); const chatFilter = require("./chatfilter.js");
const chatSpam = require("./chatspam.js"); const chatSpam = require("./chatspam.js");
const chatStyles = require("./chatstyles.js");
const buddyModule = require("./buddies.js"); const buddyModule = require("./buddies.js");
const dens = require("./dens.js"); const dens = require("./dens.js");
const disguises = require("./disguises.js"); const disguises = require("./disguises.js");
const ecardModule = require("./ecards.js"); const ecardModule = require("./ecards.js");
const ecoModule = require("./eco.js");
const epicDens = require("./epicdens.js"); const epicDens = require("./epicdens.js");
const itemHandlers = require("./items.js"); const itemHandlers = require("./items.js");
const minigameModule = require("./minigames.js"); const minigameModule = require("./minigames.js");
@@ -48,6 +52,8 @@ const {CURRENCIES, DIAMOND_TYPES, activeAvatar, avatarById, activePet, equippedB
const GENERIC_LIST_AVATARS = 64; const GENERIC_LIST_AVATARS = 64;
const GENERIC_LIST_NEWSPAPER = 627; const GENERIC_LIST_NEWSPAPER = 627;
const GENERIC_LIST_WHATS_NEW = 369;
const WHATS_NEW_PAGES = 6;
// the worlds' names (ServerSelector.getShardName): localization ids, the // the worlds' names (ServerSelector.getShardName): localization ids, the
// game's own river names, world N being the Nth. // game's own river names, world N being the Nth.
const GENERIC_LIST_WORLD_NAMES = 16; const GENERIC_LIST_WORLD_NAMES = 16;
@@ -127,30 +133,89 @@ const DEF_COMBINED_LIST = 1060;
const DEF_DEN_ROOM = 1040; const DEF_DEN_ROOM = 1040;
const DEF_CURRENCY_EXCHANGE = 1051; const DEF_CURRENCY_EXCHANGE = 1051;
const DEF_DIAMOND = 1054; const DEF_DIAMOND = 1054;
// generic lists as the official server answered them (gl), recorded with
// tools/recorder.js: used where this server has none of its own. one was
// not recorded and is made up the same way: the Journey Book's pages (53),
// found among the media files (each has a "jb_title_<land>" part) with the
// name of each land, which opens the book at the page of the land the
// player is in (GuiManager.onJourneyBookMediaListReceived). likewise the
// books of the Chamber of Knowledge (EBookChooser, lists 353-356) and their
// pages, for the four whose pages could be found.
const OFFICIAL_LISTS = require("./official-lists.json");
const SHOP_LIST_TYPES = [DEF_ITEM, DEF_DEN_ITEM, DEF_DEN_ROOM, DEF_COMBINED_LIST, DEF_CURRENCY_EXCHANGE, DEF_DIAMOND]; const SHOP_LIST_TYPES = [DEF_ITEM, DEF_DEN_ITEM, DEF_DEN_ROOM, DEF_COMBINED_LIST, DEF_CURRENCY_EXCHANGE, DEF_DIAMOND];
// a shop's title when its room gives it none (a shop in a land's main room,
// or one opened from elsewhere): what it sells (strings in lib/defpacks.js).
// with no title the shop window's banner was blank.
// shops opened from a window rather than a room, by their list: the Eco Shop.
const SHOP_LIST_TITLES = new Map([[778, 35727]]);
const SHOP_KIND_TITLES = new Map([[DEF_ITEM, 9000010], [DEF_DEN_ITEM, 9000011], [DEF_DEN_ROOM, 9000012],
[DEF_COMBINED_LIST, 9000013], [DEF_CURRENCY_EXCHANGE, 9000014], [DEF_DIAMOND, 9000015]]);
// diamond lists the client reads at login to learn which animals and pets // diamond lists the client reads at login to learn which animals and pets
// cost diamonds. they stay empty: animals and pets are free here. // cost diamonds. they stay empty: animals and pets are free here.
const DIAMOND_ANIMAL_AND_PET_LISTS = [166, 214, 293]; const DIAMOND_ANIMAL_AND_PET_LISTS = [166, 214, 293];
// the Diamond Shop's two den displays ("one" and "two" in its room file). // the Diamond Shop's two den displays ("one" and "two" in its room file).
// taken for the dens sold for diamonds: nothing else in the room is. // taken for the dens sold for diamonds: nothing else in the room is.
const DIAMOND_DEN_LIST = 196; const DIAMOND_DEN_LIST = 196;
// the egg the egg stands sell (pet.EggPetGuiManager, list 624): one at
// random of these, the diamond shop's eggs. empty, the stand threw.
const DIAMOND_EGG_LIST = 624;
const LANG_ENG = 0; const LANG_ENG = 0;
const IDLE_ANIM_LAND = 14; const IDLE_ANIM_LAND = 14;
const IDLE_ANIM_OCEAN = 29; const IDLE_ANIM_OCEAN = 29;
const MAX_PATH_POINTS = 12; const MAX_PATH_POINTS = 12;
// Action messages are client-side animation names (":dance:", ":sitNW:",
// etc.). Keep the currently playing one only while the avatar is standing
// still, so someone who enters the room can see it once their client has
// created that avatar.
const ACTION_NAME = /^:[A-Za-z][A-Za-z0-9]*:$/;
const TYPED_NAME = /^[A-Za-z0-9][A-Za-z0-9 '.-]{0,19}$/; // an animal's or pet's name typed by its owner const TYPED_NAME = /^[A-Za-z0-9][A-Za-z0-9 '.-]{0,19}$/; // an animal's or pet's name typed by its owner
// a typed name the server's filter (lib/chat-filter.txt) stops. the game's
// own names are word ids ("123|456"), which it never does.
const nameFiltered = name => !String(name).includes("|") && Boolean(chatFilter.broken(String(name)));
const MAX_BLOCKED = 1000; // from the account page; the game's own button has no limit const MAX_BLOCKED = 1000; // from the account page; the game's own button has no limit
const TYPED_CHAT_TYPES = ["0", "9"]; const TYPED_CHAT_TYPES = ["0", "9"];
// UserCommXtCommManager's safe chat phrase (1), emote (2), action (3),
// attachment (4), slide (6) and pet action (7)
const MOMENTARY_TYPES = ["1", "2", "3", "4", "6", "7"];
const MAX_CHAT_EXTRA = 100; // the field after a chat line's type const MAX_CHAT_EXTRA = 100; // the field after a chat line's type
const MAX_USER_VARS = 2000; const MAX_USER_VARS = 2000;
const MAX_FILTER_WORDS = 100; // a player's own words for their chat filter const MAX_FILTER_WORDS = 100; // a player's own words for their chat filter
const MAX_FILTER_WORD = 30; const MAX_FILTER_WORD = 30;
const LOGIN_BANNED = -15; // MainFrame.MSG_ID_LOGIN_BANNED const LOGIN_BANNED = -15; // MainFrame.MSG_ID_LOGIN_BANNED
// MainFrame.MSG_ID_LOGIN_ACCT_MAINT: its popup (GamePlay.onWorldLogIn) shows
// localization string 11198, which lib/defpacks.js makes the "update your
// client" message. the official servers' account maintenance never happens
// here.
const LOGIN_OUTDATED = -12;
const THEME_PATH_PREFIX = "theme_"; // lib/http.js looks for this const THEME_PATH_PREFIX = "theme_"; // lib/http.js looks for this
const chatLines = limits.limiter(config.chatLinesPerWindow, config.chatWindowMs); const chatLines = limits.limiter(config.chatLinesPerWindow, config.chatWindowMs);
const codeTries = limits.limiter(10, 60000); // codes typed, per account a minute
// emotes, actions, attachments: each goes to everyone in the room, so a
// player pressing one over and over slowed a busy room for all of them.
const roomActions = limits.limiter(config.roomActionsPerWindow, config.roomActionWindowMs);
const online = new Map(); // lowercased username -> session const online = new Map(); // lowercased username -> session
const rooms = new Map(); // "path.name#shard" -> room 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, // 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 // parties and adventures have none and belong to no world. each player has
@@ -181,7 +246,33 @@ const sees = (viewer, subject) => (!subject.invisible || roles.isActiveStaff(vie
&& !(viewer.account.hideBlocked && blocks.has(viewer.account, subject.account)); && !(viewer.account.hideBlocked && blocks.has(viewer.account, subject.account));
// everyone else in the room who should hear about this player's animal. // everyone else in the room who should hear about this player's animal.
const watchers = session => others(session).filter(other => sees(other, session)); const watchers = session => others(session).filter(other => sees(other, session));
// the game's feedback windows by type (FeedbackManager.frameLabelForType;
// the titles are the feedback defs' own), for the panel to say where a
// message came from
const FEEDBACK_KINDS = new Map([[1, "Theatre feedback"], [3, "Feedback"], [4, "Jamaa Journal feedback"], [5, "Feedback"],
[11, "Theatre feedback"], [18, "Jammer Wall feedback"], [19, "Chat feedback"], [21, "Theatre feedback"], [22, "Theatre feedback"]]);
const TYPING_EVERY_MS = 2000; // "typing" passed on at most this often per player (xty) const TYPING_EVERY_MS = 2000; // "typing" passed on at most this often per player (xty)
const WORLD_COUNT_SETTING = "worldCount"; // how many worlds the admin chose (setWorldCount)
// tags ("@name") in chat and on Jammer Walls (xmn): the longest player's
// name that the text after an "@" starts with, ending where a word does
// ("@John Smith hi" is John Smith if there is one, else John; "@Bobby" is
// never Bob). {length, name} or null.
const MAX_MENTION_TEXT = 40;
const MAX_MENTIONS = 10; // per question
const mentionLookups = limits.limiter(120, 60000); // questions a minute, per player
const mentionOf = text => {
for (let length = Math.min(text.length, MAX_MENTION_TEXT); length > 0; length--) {
if (length < text.length && /[A-Za-z0-9]/.test(text[length])) {
continue;
}
const name = accounts.nameOf(text.slice(0, length));
if (name) {
return {length, name};
}
}
return null;
};
const decodeEntities = text => text const decodeEntities = text => text
.replace(/&lt;/g, "<") .replace(/&lt;/g, "<")
@@ -236,7 +327,7 @@ const loginParams = session => {
playerWallSettings: account.wall.privacy, playerWallSettings: account.wall.privacy,
// not 0: PlayerWallManager only opens walls for accounts with them on. // not 0: PlayerWallManager only opens walls for accounts with them on.
webWallStatus: 1, webWallStatus: 1,
eCardPrivacySettings: account.ecardPrivacy, eCardPrivacySettings: ecards.privacyShown(account),
// not empty: with neither address set, every fifth login opens a // not empty: with neither address set, every fifth login opens a
// "parent's email" window (GuiManager.showAjEmailBtn). accounts here // "parent's email" window (GuiManager.showAjEmailBtn). accounts here
// have no email. // have no email.
@@ -304,9 +395,12 @@ const login = (session, msg) => {
loginFailed(session, LOGIN_BANNED, "Banned"); loginFailed(session, LOGIN_BANNED, "Banned");
return; return;
} }
if (config.requireDevice && devices.knownFor(account).lastAt < Math.floor(Date.now() / 1000) - 90 * 86400) { // a launcher that sent no device ids (before 1.3.0): signed in at
console.log(`[world] login rejected for "${logText(account.username)}": no device ids`); // /authenticate, refused here, where the game's popup can say why.
loginFailed(session, 0, "Update the client"); if (config.requireDevice && (devices.launcherOutdated(msg.cdata("pword"))
|| devices.knownFor(account).lastAt < Math.floor(Date.now() / 1000) - 90 * 86400)) {
console.log(`[world] login rejected for "${logText(account.username)}": client outdated (no device ids)`);
loginFailed(session, LOGIN_OUTDATED, "Client outdated");
return; return;
} }
// its username was rejected (lib/moderation.js): a new one first, which // its username was rejected (lib/moderation.js): a new one first, which
@@ -328,6 +422,17 @@ const login = (session, msg) => {
existing.close(); existing.close();
leaveWorld(existing); leaveWorld(existing);
} }
// a name typed before the filter covered names, or one a newer rule
// catches: the animal takes the username, the pet is "Pet".
const filteredNames = [...account.avatars.filter(avatar => nameFiltered(avatar.name)),
...account.pets.filter(pet => nameFiltered(pet.name))];
if (filteredNames.length) {
for (const thing of filteredNames) {
console.log(`[filter] ${logText(account.username)}'s name "${logText(thing.name)}" cleared`);
thing.name = account.avatars.includes(thing) ? account.username : "Pet";
}
accounts.save(account);
}
session.account = account; session.account = account;
accounts.hold(account); accounts.hold(account);
account.numLogins++; account.numLogins++;
@@ -351,6 +456,7 @@ const login = (session, msg) => {
accounts.save(account); accounts.save(account);
online.set(key, session); online.set(key, session);
console.log(`[world] ${logText(account.username)} logged in as sfs user ${logText(session.id)}`); 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)}); session.sendXtJson(-1, {_cmd: "login", status: "1", params: loginParams(session)});
// every custom colour, before anything that might be drawn with one // every custom colour, before anything that might be drawn with one
// (XtReplyDemuxer -> PaletteHelper.handleCustomColors in the patched SWF). // (XtReplyDemuxer -> PaletteHelper.handleCustomColors in the patched SWF).
@@ -376,7 +482,7 @@ const sendItemList = (to, target, full, perUserAvId) => {
const {account} = target; const {account} = target;
const avatar = avatarById(account, perUserAvId); const avatar = avatarById(account, perUserAvId);
const items = full const items = full
? account.items.flatMap(item => [item.def, item.inv, item.color, equippedBits(item), 0]) ? account.items.flatMap(item => [item.def, item.inv, item.color, equippedBits(item, account), 0])
: wornItems(account, avatar).flatMap(item => [item.def, item.inv, item.color]); : wornItems(account, avatar).flatMap(item => [item.def, item.inv, item.color]);
const count = full ? account.items.length : wornItems(account, avatar).length; const count = full ? account.items.length : wornItems(account, avatar).length;
to.sendXt("il", -1, full ? "0" : "1", 0, avatar.perUserAvId, account.username, avatar.eyes, avatar.pattern, count, ...items); to.sendXt("il", -1, full ? "0" : "1", 0, avatar.perUserAvId, account.username, avatar.eyes, avatar.pattern, count, ...items);
@@ -426,16 +532,29 @@ const sendAvatarCreate = (to, target) => {
avatar.questLevel || 0, avatar.questLevel || 0,
1, // userNameModeratedFlag 1, // userNameModeratedFlag
lastSeenField(account, Boolean(findOnline(account.username))), // daysSinceLastLogin: see lib/player.js lastSeenField(account, Boolean(findOnline(account.username))), // daysSinceLastLogin: see lib/player.js
// optional-field flags: bit 0 accountType, bit 1 nameBarData, bit 2 pet // optional-field flags: bit 0 accountType, bit 1 nameBarData, bit 2 pet,
pet ? 7 : 3, // 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.accountType,
account.nameBarData, account.nameBarData,
...(pet ? petFields(pet) : [])); ...(pet ? petFields(pet) : []),
...(account.isGuide ? [0, 1] : []));
sendItemList(to, target, false); sendItemList(to, target, false);
disguises.show(to, target); disguises.show(to, target);
if (target.invisible) { if (target.invisible) {
to.sendXt("xiv", -1, target.id, 1); to.sendXt("xiv", -1, target.id, 1);
} }
if (pets.inPetForm(account)) {
to.sendXt("uc", room.id, target.id, "on", "13");
}
// `ac` only creates the avatar. Actions normally travel as live `uc`
// type-3 packets, so replay a standing player's current action after `ac`
// for a player who has just entered (or reloaded) the room.
if (target.activeAction) {
to.sendXt("uc", room.id, target.id, target.activeAction.name, "3", target.activeAction.extra);
}
minigames.showBubble(to, target);
}; };
// redraws `session`'s animal for everyone else in the room, for changes the // redraws `session`'s animal for everyone else in the room, for changes the
@@ -475,8 +594,10 @@ const sortStock = () => {
// two out-of-the-way shops keep what was never in one: the shop in the // two out-of-the-way shops keep what was never in one: the shop in the
// Chamber of Knowledge's base (reached from a hidden spot on the world map) // Chamber of Knowledge's base (reached from a hidden spot on the world map)
// has the den items, the one in the Zios archives the clothing. see // has the den items, the one in the Zios archives the clothing. see
// oddDenItemIds in lib/defpacks.js. // oddDenItemIds in lib/defpacks.js. of the clothing only the Founder's Hat
const ODDITY_SHOPS = new Map([[396, () => defpacks.oddDenItemIds()], [666, () => defpacks.oddClothingIds()]]); // (oddClothingIds' first): the rest, nameless pieces never finished, made the
// Forgotten Archive a heap of broken items.
const ODDITY_SHOPS = new Map([[396, () => defpacks.oddDenItemIds()], [666, () => defpacks.oddClothingIds().slice(0, 1)]]);
// the items staff have made (lib/customitems.js) are sold there too, first. // the items staff have made (lib/customitems.js) are sold there too, first.
const CUSTOM_ITEM_SHOPS = new Map([[396, "den"], [666, "clothing"]]); const CUSTOM_ITEM_SHOPS = new Map([[396, "den"], [666, "clothing"]]);
const ticketStock = kind => sortStock()[kind]; const ticketStock = kind => sortStock()[kind];
@@ -509,7 +630,7 @@ const sendUserVars = session => {
}; };
const findOnline = username => online.get(String(username).toLowerCase()); const findOnline = username => online.get(String(username).toLowerCase());
const STAFF_WINDOW_COMMANDS = ["warn", "unwarn", "message", "silence", "kick", "summon", "goto", "warnings"]; const STAFF_WINDOW_COMMANDS = ["warn", "unwarn", "message", "silence", "kick", "summon", "goto", "warnings", "reject"];
const MAX_STAFF_WINDOW_WORDS = 3; // username, then a reason, hours or the message (each one field) const MAX_STAFF_WINDOW_WORDS = 3; // username, then a reason, hours or the message (each one field)
// a custom colour (lib/colours.js) for these four RGB values, made if it is // a custom colour (lib/colours.js) for these four RGB values, made if it is
@@ -546,6 +667,10 @@ const sendFilter = session => {
session.sendXt("xfl", -1, filter.chosen ? 1 : 0, filter.level, filter.mode, filter.words); session.sendXt("xfl", -1, filter.chosen ? 1 : 0, filter.level, filter.mode, filter.words);
}; };
// The in-game editor asks for this on demand too. It receives only canonical
// values, so the Flash client never has to guess at a missing account field.
const sendChatStyle = session => session.sendXt("xcs", -1, ...chatStyles.fields(session.account.chatStyle));
// the player called `username` as the senders above take one: their session // the player called `username` as the senders above take one: their session
// when they are playing, else just their account. A player's card can be // when they are playing, else just their account. A player's card can be
// opened for anybody (the buddy list, the player search), and it asks for // opened for anybody (the buddy list, the player search), and it asks for
@@ -572,6 +697,25 @@ const handlers = {
sendFilter(session); sendFilter(session);
}, },
// The Settings > Chat Bubble popup. An empty request just reloads the
// saved setting; a complete twelve-field request replaces it. Older custom
// clients remain accepted and receive a two-stop gradient automatically.
xcs(session, roomId, params) {
if (params.length === 0) {
sendChatStyle(session);
return;
}
if (![7, 10, 11, 12].includes(params.length)) return;
const [background, accent, text, border, opacity, animation, speed, gradient = "linear", angle = 45, strength = 100, outline = 1,
stops = `${background}:0;${accent}:100`] = params;
const style = {background, accent, text, border, opacity: Number(opacity), animation, speed: Number(speed),
gradient, angle: Number(angle), strength: Number(strength), outline: Number(outline), stops};
if (!chatStyles.valid(style)) return;
session.account.chatStyle = style;
accounts.save(session.account);
sendChatStyle(session);
},
// the patched client's hex colour picker (gui.ColorTable): [rgb1, rgb2, // the patched client's hex colour picker (gui.ColorTable): [rgb1, rgb2,
// rgb3, rgb4], the four colours of one layer. everyone online is told the // rgb3, rgb4], the four colours of one layer. everyone online is told the
// entry's id, the asker included, who then uses it as that layer's colour. // entry's id, the asker included, who then uses it as that layer's colour.
@@ -639,6 +783,9 @@ const handlers = {
const teleport = params[params.length - 1] === "1" ? 1 : 0; const teleport = params[params.length - 1] === "1" ? 1 : 0;
const firstUpdate = !session.pos; const firstUpdate = !session.pos;
session.pos = {x: coords[coords.length - 2], y: coords[coords.length - 1]}; session.pos = {x: coords[coords.length - 2], y: coords[coords.length - 1]};
// Walking, swimming, or a teleport replaces a looping action on every
// client. Do not replay it to somebody entering later.
delete session.activeAction;
if (!session.greeted) { if (!session.greeted) {
// the first room has loaded: the client can show a popup now. // the first room has loaded: the client can show a popup now.
session.greeted = true; session.greeted = true;
@@ -646,6 +793,9 @@ const handlers = {
if (motd) { if (motd) {
tell(session, 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); buddies.greet(session);
minigames.greet(session); minigames.greet(session);
moderation.greet(session); moderation.greet(session);
@@ -710,6 +860,9 @@ const handlers = {
} }
let entries = []; let entries = [];
let count; let count;
if (Number(listId) === eco.SHOP_LIST) {
eco.shopOpened(session);
}
if (Number(listId) === GENERIC_LIST_AVATARS) { if (Number(listId) === GENERIC_LIST_AVATARS) {
entries = defpacks.avatarTypes(); entries = defpacks.avatarTypes();
} }
@@ -779,6 +932,12 @@ const handlers = {
const real = shopStock.list(listId, type); const real = shopStock.list(listId, type);
entries = [...new Set([...defpacks.customShopIds(CUSTOM_ITEM_SHOPS.get(Number(listId))), ...(real ? real.entries : []), ...ODDITY_SHOPS.get(Number(listId))()])]; entries = [...new Set([...defpacks.customShopIds(CUSTOM_ITEM_SHOPS.get(Number(listId))), ...(real ? real.entries : []), ...ODDITY_SHOPS.get(Number(listId))()])];
} }
else if (Number(listId) === DIAMOND_EGG_LIST) {
entries = defpacks.diamondIds().filter(id => {
const def = defpacks.diamondDef(id);
return def.type === DIAMOND_TYPES.pet && (defpacks.petDef(Number(def.refId)) || {}).isEgg === "1";
});
}
else if (Number(listId) === DIAMOND_DEN_LIST) { else if (Number(listId) === DIAMOND_DEN_LIST) {
entries = defpacks.diamondIds().filter(id => { entries = defpacks.diamondIds().filter(id => {
const def = defpacks.diamondDef(id); const def = defpacks.diamondDef(id);
@@ -811,9 +970,27 @@ const handlers = {
count = defpacks.petIds().length; count = defpacks.petIds().length;
entries = defpacks.petIds().flatMap(id => [id, 1]); entries = defpacks.petIds().flatMap(id => [id, 1]);
} }
// Jammer Central's "What's New" pictures (gui.BulletinBoard, list 369):
// the newest pages of the Jamaa Journal. empty, the window waited on
// its spinner.
if (Number(listId) === GENERIC_LIST_WHATS_NEW && (count === undefined ? entries.length : count) === 0) {
entries = defpacks.newestJournalPages(WHATS_NEW_PAGES).flatMap(id => [id, 0]);
count = entries.length / 2;
}
// what the official server answered, where this one has nothing of its
// own (lib/official-lists.json, from recordings of the official game:
// the Journey Book's facts and pictures among them)
if ((count === undefined ? entries.length : count) === 0 && Object.hasOwn(OFFICIAL_LISTS, String(Number(listId)))) {
const official = OFFICIAL_LISTS[String(Number(listId))];
if (official.type === type) {
entries = official.entries;
count = official.count;
}
}
// for shops the first unused field is the title's string id; left empty // for shops the first unused field is the title's string id; left empty
// it keeps the shop window's own title (Shop.gotItemListCallback). // it keeps the shop window's own title (Shop.gotItemListCallback).
const title = SHOP_LIST_TYPES.includes(type) ? (session.room ? roomInfo.shopTitle(session.room.base, listId) : "") : 0; const title = SHOP_LIST_TYPES.includes(type)
? (session.room && roomInfo.shopTitle(session.room.base, listId)) || SHOP_LIST_TITLES.get(Number(listId)) || SHOP_KIND_TITLES.get(type) : 0;
session.sendXt("gl", -1, listId, type, title, 0, 0, 0, count === undefined ? entries.length : count, ...entries); session.sendXt("gl", -1, listId, type, title, 0, 0, 0, count === undefined ? entries.length : count, ...entries);
}, },
@@ -835,6 +1012,10 @@ const handlers = {
if (vars[id] === undefined && Object.keys(vars).length >= MAX_USER_VARS) { if (vars[id] === undefined && Object.keys(vars).length >= MAX_USER_VARS) {
return; return;
} }
// the eco plaques (lib/eco.js) are given, not set
if (eco.userVar(session, id, value)) {
return;
}
if (Number(id) === USER_VAR_HIDE_BLOCKED) { if (Number(id) === USER_VAR_HIDE_BLOCKED) {
setHideBlocked(session, Number(value) === 1); setHideBlocked(session, Number(value) === 1);
} }
@@ -894,6 +1075,47 @@ const handlers = {
} }
}, },
// The host/event overlay only sends one of these fixed room effects. Its
// permission check lives here as well, so a forged client packet cannot
// change a room.
xrc(session, roomId, [effect]) {
const choice = String(effect || "").toLowerCase();
if (roles.isActiveStaff(session.account) && roles.can(session.account, "room.effects")
&& ["small", "normal", "big", "rainbow", "clear"].includes(choice)) {
commands.run(session, `!roomfx ${choice}`);
}
},
// The browser host renders the YouTube iframe; the game receives only a
// validated video id and keeps it shared by the people in this theatre.
xtv(session, roomId, [action, value = ""]) {
const {room} = session;
// Some theatre maps report an internal room path which has no "theatre"
// in it (the visible room title does). Staff permission is the boundary;
// restricting by that unreliable path made Play for room silently fail.
if (!roles.isActiveStaff(session.account) || !roles.can(session.account, "theater.control") || !room) {
return;
}
let videoId = "";
if (action === "play") {
const text = String(value).trim();
const match = text.match(/^(?:[A-Za-z0-9_-]{11}|(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([A-Za-z0-9_-]{11})(?:[?&#].*)?)$/i);
videoId = match ? (match[1] || text) : "";
if (!videoId) {
session.sendXt("xtl", -1, "Paste a YouTube watch, share, or embed link.");
return;
}
}
else if (action !== "stop") {
return;
}
room.theatreVideo = videoId;
for (const viewer of room.sessions) {
viewer.sendXt("xtv", room.id, videoId);
}
modlog.record(session.account.username, videoId ? "played theatre video" : "stopped theatre video", "", room.name);
},
// the patched client's chat box: whether its player is typing, for a // the patched client's chat box: whether its player is typing, for a
// "..." over their animal in everyone else's game (gui.ChatHistory): // "..." over their animal in everyone else's game (gui.ChatHistory):
// xty [1 | 0], passed on as "xty" [.., .., sfsId, 1 | 0]. a client says // xty [1 | 0], passed on as "xty" [.., .., sfsId, 1 | 0]. a client says
@@ -911,6 +1133,76 @@ const handlers = {
} }
}, },
// the game's feedback windows (the purple Help and Feedback buttons, the
// orbs in rooms, the newspaper's and the theatre's: the patched
// gui.FeedbackManager): xfb [the window's feedback type, the text]. it
// goes to the staff panels' feedback (lib/support.js), named by where it
// was written.
xfb(session, roomId, [type, ...text]) {
const where = FEEDBACK_KINDS.get(Number(type)) || "Feedback";
const said = text.join("%").trim();
if (!said) {
return;
}
const result = support.sendFeedback(session.account, "feedback", `${where} (in ${session.room ? session.room.displayName : "the game"}): ${said}`);
// the window has thanked them already; said only when it did not go
if (!result.ok) {
tell(session, result.error === "too_many" ? "You have sent a lot of feedback today. Try again tomorrow." : "That feedback could not be sent.");
}
},
// the game's Redeem Code window (GameRedemptionXtCommManager.requestRedeemCode):
// [code, captcha question, answer], a code made in the admin panel
// (lib/codes.js). the reply (CodeRedemptionPopup.onCodeRedeemResponse) is
// "1" redeemed: the gift comes as a card from HQ, or for gems and diamonds
// as a gift popup, whose card says so itself (lib/ecards.js deliver);
// "-4" not now (used already, and an HQ popup says so); else "that code
// didn't work". it was not answered at all, and the window spun.
grc(session, roomId, [code]) {
const {account} = session;
if (!codeTries.allow(account.id)) {
session.sendXt("grc", -1, "-4", "", 0);
return;
}
const result = codes.redeem(account, code);
if (result.error === "used" || result.error === "spent") {
tell(session, result.error === "used" ? "You have used that code already." : "That code has been used up.");
session.sendXt("grc", -1, "-4", "", 0);
return;
}
if (result.error) {
session.sendXt("grc", -1, "0", "", 0);
return;
}
const problem = ecards.sendFromHq(account, `Code ${result.code} redeemed!`, result.gift);
if (problem) {
codes.unredeem(account, result.code);
tell(session, `${problem}. The code can be used once there is room.`);
session.sendXt("grc", -1, "-4", "", 0);
return;
}
if (result.gift.kind === "clothing" || result.gift.kind === "den") {
session.sendXt("grc", -1, "1", "", 0);
tell(session, "Code redeemed! Your gift is in your Jam-A-Grams.");
}
},
// the patched client's tags (AJClient.resolveMentions): xmn [id, the text
// after each "@", ...] -> "xmn" [.., .., id, then for each text: how many
// of its characters are a player's name (0 for none), the name as it is
// spelled, 1 if they are online]. what a text is not a name of stays text.
xmn(session, roomId, [id, ...texts]) {
if (!mentionLookups.allow(session.account.id)) {
return;
}
const reply = [];
for (const text of texts.slice(0, MAX_MENTIONS)) {
const found = mentionOf(String(text));
reply.push(found ? found.length : 0, found ? found.name : "", found && findOnline(found.name) ? 1 : 0);
}
session.sendXt("xmn", -1, Number.isInteger(Number(id)) ? Number(id) : 0, ...reply);
},
// the patched client's staff window: going invisible, or being seen again. // the patched client's staff window: going invisible, or being seen again.
xiv(session) { xiv(session) {
if (session.invisible || roles.can(session.account, "staff.invisible")) { if (session.invisible || roles.can(session.account, "staff.invisible")) {
@@ -943,7 +1235,12 @@ const handlers = {
const thing = kind === "a" ? account.avatars.find(avatar => avatar.perUserAvId === Number(id)) const thing = kind === "a" ? account.avatars.find(avatar => avatar.perUserAvId === Number(id))
: kind === "p" ? account.pets.find(pet => pet.inv === Number(id)) : null; : kind === "p" ? account.pets.find(pet => pet.inv === Number(id)) : null;
// typed words others read: not while silenced. // typed words others read: not while silenced.
const ok = Boolean(thing) && TYPED_NAME.test(wanted) && !moderation.isSilenced(account); const filtered = Boolean(thing) && TYPED_NAME.test(wanted) && nameFiltered(wanted);
const ok = Boolean(thing) && TYPED_NAME.test(wanted) && !filtered && !moderation.isSilenced(account);
if (filtered) {
console.log(`[filter] ${logText(session.name)} named ${kind === "a" ? "an animal" : "a pet"}: "${logText(wanted)}" (${logText(chatFilter.broken(wanted))})`);
chatFilter.warn(session);
}
if (ok) { if (ok) {
thing.name = wanted; thing.name = wanted;
accounts.save(account); accounts.save(account);
@@ -975,11 +1272,28 @@ const handlers = {
// VolumeSelector.handleRoomCountResponse: the head-count shown on each land // VolumeSelector.handleRoomCountResponse: the head-count shown on each land
// of the world map, as [count, (roomName, players)...]. // of the world map, as [count, (roomName, players)...].
// the map's buddy counts (VolumeSelector.handleRoomCountResponse): how
// many of the player's buddies are in each land of the player's world.
// the map takes a land from the room's name (an ocean's from its room)
// and keeps the last number it gets for it, so each land comes once,
// its rooms added up. it counted everyone in every room of every world.
// dens, parties and adventures are left out, whose names are nobody
// else's business.
rc(session) { rc(session) {
// the lands and their shops, as the map shows them: not dens, parties, const counts = new Map(); // a name the map reads its land from -> buddies there
// or anybody's adventure, whose names are nobody else's business. const world = session.worldId || config.shards[0].id;
const counts = [...rooms.values()].filter(room => !room.denOwner && room.roomType === 0).flatMap(room => [room.name, room.sessions.size]); for (const other of online.values()) {
session.sendXt("rc", -1, counts.length / 2, ...counts); const {room} = other;
if (other === session || !room || room.denOwner || room.roomType !== 0 || worldOf(room.name) !== world
|| !session.account.buddies.includes(other.account.username.toLowerCase()) || !sees(session, other)
|| blocks.either(session.account, other.account)) {
continue;
}
const [land, place = ""] = room.base.split(".");
const key = land === "oceans" ? `oceans.${place}#${world}` : `${land}.room_main#${world}`;
counts.set(key, (counts.get(key) || 0) + 1);
}
session.sendXt("rc", -1, counts.size, ...[...counts].flat());
}, },
// RoomXtCommManager.sendRoomJoinRequestFull: [nameOrId, confirmLanguage, invisible, joinType] // RoomXtCommManager.sendRoomJoinRequestFull: [nameOrId, confirmLanguage, invisible, joinType]
@@ -1093,10 +1407,31 @@ const itemsTaken = (account, kind, invs, worn) => {
} }
}; };
// A dashboard clothing rule can affect several animals and mannequins at
// once. Their persisted references have already been removed by
// itemcontrol.js; refresh both the owner's full inventory and anyone seeing
// their animal or den so an open game cannot keep displaying the old outfit.
const wearRulesChanged = (account, mannequinChanged = false) => {
const session = findOnline(account.username);
if (session) {
sendItemList(session, session, true);
refreshForOthers(session);
if (mannequinChanged) {
dens.sendDenItems(session);
}
}
if (mannequinChanged) {
const den = rooms.get(`den${account.username}`);
for (const visitor of den ? den.sessions : []) {
dens.sendDenState(visitor, den, false);
}
}
};
// staff moving a player: `whoName` to the room `toName` is in (summon is // staff moving a player: `whoName` to the room `toName` is in (summon is
// the player to the staff member, goto the staff member to the player). both // the player to the staff member, goto the staff member to the player). both
// online, `toName` in a room. the room's own rules still apply: a full room // online, `toName` in a room. This privileged movement deliberately bypasses
// or a locked den keeps them out. // a full room, locked den, or hosted-party block; regular joins do not.
// they land where `toName` stands (the patched client's "xgt": [x, y, // they land where `toName` stands (the patched client's "xgt": [x, y,
// "1" same room, teleported now | "0" the spot to spawn on in the next // "1" same room, teleported now | "0" the spot to spawn on in the next
// room], or [] to forget a spot not used). with nobody's spot known yet, // room], or [] to forget a spot not used). with nobody's spot known yet,
@@ -1120,13 +1455,15 @@ const staffMove = (whoName, toName) => {
who.sendXt("xgt", -1, ...spot, 1); who.sendXt("xgt", -1, ...spot, 1);
return {ok: true, room: shown}; return {ok: true, room: shown};
} }
if (room.sessions.size >= config.maxUsersPerRoom) {
return {error: `${shown} is full.`};
}
if (spot) { if (spot) {
who.sendXt("xgt", -1, ...spot, 0); who.sendXt("xgt", -1, ...spot, 0);
} }
// staffMove is only reached through permission-checked commands. The flag
// is consumed by enterRoom/joinDen, preserving normal rules for all other
// joins.
who.staffTravel = true;
joinRoom(who, room.name); joinRoom(who, room.name);
delete who.staffTravel;
if (who.room !== room) { if (who.room !== room) {
if (spot) { if (spot) {
who.sendXt("xgt", -1); who.sendXt("xgt", -1);
@@ -1170,6 +1507,7 @@ const pets = petModule(context);
const parties = partyModule(context); const parties = partyModule(context);
const ecards = ecardModule(context); const ecards = ecardModule(context);
const walls = wallModule(context); const walls = wallModule(context);
const eco = ecoModule({others, ecards});
const commands = commandModule(context); const commands = commandModule(context);
const minigames = minigameModule(context); const minigames = minigameModule(context);
const adventures = adventureModule(context); const adventures = adventureModule(context);
@@ -1179,9 +1517,22 @@ const trades = tradeHandlers(context);
achievements.setFinder(findOnline); achievements.setFinder(findOnline);
Object.assign(handlers, avatarHandlers(context), itemHandlers(context), pets.handlers, dens.handlers({...context, others}), Object.assign(handlers, avatarHandlers(context), itemHandlers(context), pets.handlers, dens.handlers({...context, others}),
buddies.handlers, moderation.handlers, trades.handlers, achievements.handlers, adopt.handlers, worldItems.handlers, buddies.handlers, moderation.handlers, trades.handlers, achievements.handlers, adopt.handlers, worldItems.handlers,
parties.handlers, ecards.handlers, walls.handlers, minigames.handlers, adventures.handlers, stubHandlers, parties.handlers, ecards.handlers, eco.handlers, walls.handlers, minigames.handlers, adventures.handlers, stubHandlers,
playerItems.handlers({itemsTaken: (...args) => itemsTaken(...args)})); playerItems.handlers({itemsTaken: (...args) => itemsTaken(...args)}));
// a den's owner, wherever they are, is told how many are in it: the HUD's
// den count, with the doorbell when it goes up (DenXtCommManager.denRoomCount,
// GuiManager.updateDenRoomCount: [count, 1 if they are among them, owner]).
// someone they cannot see is not counted.
const tellDenCount = room => {
const owner = room && room.denOwner ? findOnline(room.denOwner.username) : null;
if (!owner) {
return;
}
const inside = [...room.sessions].filter(other => other === owner || sees(owner, other));
owner.sendXt("drc", -1, inside.length, inside.includes(owner) ? 1 : 0, room.denOwner.username);
};
const leaveRoom = session => { const leaveRoom = session => {
const {room} = session; const {room} = session;
if (!room) { if (!room) {
@@ -1190,6 +1541,8 @@ const leaveRoom = session => {
room.sessions.delete(session); room.sessions.delete(session);
session.room = null; session.room = null;
session.pos = null; session.pos = null;
delete session.activeAction;
minigames.roomLeft(session);
for (const other of room.sessions) { for (const other of room.sessions) {
// AvatarManager.avatarRemoveResponse // AvatarManager.avatarRemoveResponse
if (sees(other, session)) { if (sees(other, session)) {
@@ -1199,6 +1552,7 @@ const leaveRoom = session => {
if (room.sessions.size === 0) { if (room.sessions.size === 0) {
rooms.delete(room.name); rooms.delete(room.name);
} }
tellDenCount(room);
}; };
// the Bio tab's words: the bio, under the time played when the player // the Bio tab's words: the bio, under the time played when the player
@@ -1245,6 +1599,8 @@ setInterval(() => {
}, 60000).unref(); }, 60000).unref();
const leaveWorld = session => { 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); minigames.leave(session);
trades.forget(session); trades.forget(session);
leaveRoom(session); leaveRoom(session);
@@ -1256,6 +1612,7 @@ const leaveWorld = session => {
accounts.release(session.account); accounts.release(session.account);
accounts.save(session.account); accounts.save(session.account);
buddies.announce(session.account); buddies.announce(session.account);
gameActivity({type: "logout", username, at: Math.floor(Date.now() / 1000), playedSeconds});
} }
}; };
@@ -1339,11 +1696,13 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
if (room && room === session.room) { if (room && room === session.room) {
return; return;
} }
// moderators (marked so in the admin panel) are let into a full room, and // Moderators, a one-use staff teleport, and a player arriving when every
// so is a player arriving when every spawn room is full (spawnRoom). // spawn room is full (spawnRoom) may enter a full room.
const overflow = session.spawnOverflow; const overflow = session.spawnOverflow;
const staffTravel = session.staffTravel === true;
session.spawnOverflow = false; session.spawnOverflow = false;
if (room && room.sessions.size >= config.maxUsersPerRoom && !roles.isActiveStaff(session.account) && !overflow) { delete session.staffTravel;
if (room && room.sessions.size >= config.maxUsersPerRoom && !roles.isActiveStaff(session.account) && !staffTravel && !overflow) {
joinFailed(session, "This room is currently full"); joinFailed(session, "This room is currently full");
return; return;
} }
@@ -1366,6 +1725,7 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
if (props.denOwner && props.denOwner !== session.account) { if (props.denOwner && props.denOwner !== session.account) {
noteDenVisit(props.denOwner, session.account); noteDenVisit(props.denOwner, session.account);
} }
tellDenCount(room);
roomInfo.ensure(base); roomInfo.ensure(base);
const avatar = activeAvatar(session.account); const avatar = activeAvatar(session.account);
pets.walked(session.account); pets.walked(session.account);
@@ -1386,6 +1746,9 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
room.customMusicDef, room.customMusicDef,
worldId); worldId);
dens.sendRoomProperties(session, roomAsSeenBy(session, room)); dens.sendRoomProperties(session, roomAsSeenBy(session, room));
if (room.theatreVideo !== undefined) {
session.sendXt("xtv", room.id, room.theatreVideo);
}
for (const other of others(session)) { for (const other of others(session)) {
if (other.pos && sees(session, other)) { if (other.pos && sees(session, other)) {
@@ -1546,7 +1909,7 @@ const joinRoom = (session, requested) => {
let shard = config.shards.find(s => s.id === Number(shardText)) || config.shards.find(s => s.id === session.worldId) || config.shards[0]; let shard = config.shards.find(s => s.id === Number(shardText)) || config.shards.find(s => s.id === session.worldId) || config.shards[0];
// full there: with "Find Open World" on, the same room in a world that // full there: with "Find Open World" on, the same room in a world that
// has space (moderators get into a full room anyway). // has space (moderators get into a full room anyway).
if (roomFull(`${base}#${shard.id}`) && !session.account.moderator && findOpenWorld(session.account)) { if (roomFull(`${base}#${shard.id}`) && !roles.isActiveStaff(session.account) && findOpenWorld(session.account)) {
shard = config.shards.find(other => !roomFull(`${base}#${other.id}`)) || shard; shard = config.shards.find(other => !roomFull(`${base}#${other.id}`)) || shard;
} }
enterRoom(session, `${base}#${shard.id}`, base, roomInfo.name(base), shard.id); enterRoom(session, `${base}#${shard.id}`, base, roomInfo.name(base), shard.id);
@@ -1568,7 +1931,8 @@ const joinDen = (session, requested) => {
joinFailed(session, `Den "${requested}" does not exist`); joinFailed(session, `Den "${requested}" does not exist`);
return; return;
} }
if (!dens.canEnter(owner, session.account) || blocks.has(owner, session.account)) { const staffTravel = session.staffTravel === true;
if ((!dens.canEnter(owner, session.account) || blocks.has(owner, session.account)) && !staffTravel) {
joinFailed(session, "This den is locked"); joinFailed(session, "This den is locked");
return; return;
} }
@@ -1615,7 +1979,13 @@ module.exports = {
case "pubMsg": { case "pubMsg": {
// UserCommXtCommManager sends "<text>%<type>[%<extra>]" and reads it // UserCommXtCommManager sends "<text>%<type>[%<extra>]" and reads it
// back in userCommChatResponse as [sfsUserId, text, type, extra]. // back in userCommChatResponse as [sfsUserId, text, type, extra].
if (session.room && session.room.id === msg.roomId) { // An in-room minigame keeps the player in their world room, but its
// embedded SWF labels outgoing user messages with the minigame's
// temporary sub-room id. Accept that id as well so its attachment
// reward can make the normal round trip back to the avatar.
const fromGame = (session.game && session.game.roomId === Number(msg.roomId))
|| (session.lastGame && session.lastGame.roomId === Number(msg.roomId) && Date.now() < session.lastGame.until);
if (session.room && (session.room.id === msg.roomId || fromGame)) {
// at most text, type and one extra field, and no essays. // at most text, type and one extra field, and no essays.
const fields = decodeEntities(msg.cdata("txt") || "").split("%").slice(0, 3); const fields = decodeEntities(msg.cdata("txt") || "").split("%").slice(0, 3);
if (fields[0].length > config.maxChatLength || (fields[2] || "").length > MAX_CHAT_EXTRA) { if (fields[0].length > config.maxChatLength || (fields[2] || "").length > MAX_CHAT_EXTRA) {
@@ -1629,10 +1999,58 @@ module.exports = {
return; return;
} }
fields[1] = String(Number(fields[1])); fields[1] = String(Number(fields[1]));
// A buddy game's bubble over the player's head (lib/minigames.js).
if (fields[1] === "12") {
minigames.bubble(session, fields[0], fields[2]);
return;
}
// 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") {
pets.setPetForm(session, fields[0] === "on");
return;
}
// Type 3 is the action packet. It used to be sent only to people
// already in the room, leaving late arrivals with an idle avatar
// until the player performed the action again. Save the safe action
// name and its mirror marker for the next avatar-create packet.
if (fields[1] === "3") {
if (!ACTION_NAME.test(fields[0])) {
return;
}
session.activeAction = {name: fields[0], extra: fields[2] || ""};
}
// Attachment messages carry an emoticon *definition* id from the
// sender, while the recipient's avatar view needs that definition's
// media id. This is the normal path used by den attachments and
// the food-machine minigames.
if (fields[1] === "4") {
const [defId, ...extra] = fields[0].split(",");
if (defId === "0") {
fields[0] = "0,";
}
else {
const mediaId = defpacks.emoticonMediaId(defId);
if (!mediaId) {
return;
}
fields[0] = `${mediaId},${extra.join(",").replace(/[\r\n%,]/g, "").slice(0, 128)}`;
}
}
// typed chat shows as "..." over the sender until the server sends // typed chat shows as "..." over the sender until the server sends
// it back (UserCommXtCommManager.sendChatMessage); everything else // it back (UserCommXtCommManager.sendChatMessage); everything else
// the sender has already shown themselves. // the sender has already shown themselves.
const echo = TYPED_CHAT_TYPES.includes(fields[1]); const echo = TYPED_CHAT_TYPES.includes(fields[1]);
// An attachment is only drawn after the server sends it back. The
// local client deliberately does not draw it optimistically, unlike
// typed chat and normal emotes.
const attachmentEcho = fields[1] === "4";
// A phrase from the phrase menus is drawn from the echo too (the
// patched UserCommXtCommManager.sendAvatarSafeChat), so that it
// comes in the sender's chat bubble style, as typed chat does.
const phrase = fields[1] === "1";
// silenced, or chat switched off on the account page: the line // silenced, or chat switched off on the account page: the line
// goes nowhere. // goes nowhere.
if (echo && (moderation.isSilenced(session.account) || !accounts.featureOn(session.account, "chat"))) { if (echo && (moderation.isSilenced(session.account) || !accounts.featureOn(session.account, "chat"))) {
@@ -1645,6 +2063,14 @@ module.exports = {
session.sendXt("uc", session.room.id, session.id, -1, 5); session.sendXt("uc", session.room.id, session.id, -1, 5);
return; return;
} }
// the momentary ones (a phrase, an emote, an action, an attachment,
// a slide, a pet's trick), past a few in a few seconds, reach
// nobody: the sender has shown their own already. what sets a
// state (a colour, see-through, a lasting emote) always goes, or
// others would be left seeing the wrong one.
if (MOMENTARY_TYPES.includes(fields[1]) && !limits.isTrustedLocal(session.address) && !roomActions.allow(session.account.id)) {
return;
}
if (echo) { if (echo) {
// "!help" and the like (lib/commands.js). A command's line is // "!help" and the like (lib/commands.js). A command's line is
// still echoed to its sender, whose chat bubble waits for it. // still echoed to its sender, whose chat bubble waits for it.
@@ -1686,12 +2112,18 @@ module.exports = {
// nobody hears a player they have blocked, and with chat switched // nobody hears a player they have blocked, and with chat switched
// off nobody's typed lines arrive at all. // off nobody's typed lines arrive at all.
// an invisible staff member's emotes and the like reach staff only. // an invisible staff member's emotes and the like reach staff only.
for (const recipient of echo ? session.room.sessions : others(session)) { // Typed chat always gets a third (stock "extra") field, followed by
// its style. Keeping message and type at their original indexes is
// what clears the local "..." bubble; carrying the style on the
// same packet prevents it being lost or applied to a later line.
const style = echo || phrase ? chatStyles.packet(session.account.chatStyle) : "";
for (const recipient of (echo || attachmentEcho || phrase) ? session.room.sessions : others(session)) {
if (session.invisible && recipient !== session && !roles.isActiveStaff(recipient.account)) { if (session.invisible && recipient !== session && !roles.isActiveStaff(recipient.account)) {
continue; continue;
} }
if (recipient === session || (!blocks.has(recipient.account, session.account) && (!echo || accounts.featureOn(recipient.account, "chat")))) { if (recipient === session || (!blocks.has(recipient.account, session.account) && (!echo || accounts.featureOn(recipient.account, "chat")))) {
recipient.sendXt("uc", session.room.id, session.id, ...fields); recipient.sendXt("uc", session.room.id, session.id,
...((echo || phrase) && style ? [fields[0], fields[1], fields[2] || "", style] : fields));
} }
} }
} }
@@ -1729,6 +2161,7 @@ module.exports = {
findOnline, findOnline,
makeColour, makeColour,
sendItemList, sendItemList,
wearRulesChanged,
setTheme, setTheme,
// offers left on the account page (lib/trades.js); `refresh` shows a // offers left on the account page (lib/trades.js); `refresh` shows a
// playing account its inventories as they are now. // playing account its inventories as they are now.
@@ -1829,20 +2262,22 @@ module.exports = {
// the panel's Masterpieces page. A painting waiting for review is an // 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 // 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. // Jam-A-Gram from Animal Jam HQ and at once if they are playing. `by`
approveMasterpiece(id) { // is who approved it: a moderator's username, or "admin". the same
const maker = masterpieces.creatorOf(id); // picture waiting elsewhere is approved with it, and its makers told too.
if (!masterpieces.approve(id)) { approveMasterpiece(id, by) {
return false; const approved = masterpieces.approve(id, by);
} for (const painting of approved) {
if (maker) { const maker = masterpieces.creatorOf(painting.id);
ecards.noteFromHq(maker, "Your Masterpiece has been approved! It is with your den items."); if (maker) {
const session = findOnline(maker.username); ecards.noteFromHq(maker, "Your Masterpiece has been approved! It is with your den items.");
if (session) { const session = findOnline(maker.username);
dens.sendDenItems(session); 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 // 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 // was not approved, or one that should not have been. its maker gets a
@@ -1867,7 +2302,7 @@ module.exports = {
account.denItems = account.denItems.filter(item => item.image !== painting.id); 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))); 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) { if (maker) {
dens.giveDenItem(maker, masterpieces.TOKEN_DEN_ITEM); 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."); ecards.noteFromHq(maker, "Your Masterpiece was not approved. Here is a Masterpiece Token to frame another one with.");
@@ -1887,6 +2322,31 @@ module.exports = {
return true; return true;
}, },
// how many worlds there are (the admin panel), from 1 to 10, kept as a
// setting. the list is changed where it is (config.shards: everything
// reads it from there), so the world picker shows the new ones at once;
// whoever is in a world that is gone is moved to the first.
WORLD_COUNT_SETTING,
setWorldCount(count, keep = true) {
const wanted = Math.min(config.worldNames.length, Math.max(1, Math.floor(Number(count))));
if (!Number.isFinite(wanted)) {
return null;
}
config.shards.splice(0, config.shards.length, ...config.worldNames.slice(0, wanted).map((name, i) => ({id: i + 1, name})));
if (keep) {
accounts.setSetting(WORLD_COUNT_SETTING, String(wanted));
}
for (const session of online.values()) {
if (session.worldId > wanted) {
session.worldId = config.shards[0].id;
if (session.room && worldOf(session.room.name) === 0 && /#\d+$/.test(session.room.name)) {
sendHome(session);
}
}
}
return wanted;
},
// the panel's Debug page: puts a playing account into any room of the room // the panel's Debug page: puts a playing account into any room of the room
// list, as that room and nothing more (a den's file without its owner, a // list, as that room and nothing more (a den's file without its owner, a
// party's without the party). returns what is wrong, or null. // party's without the party). returns what is wrong, or null.
@@ -1943,4 +2403,5 @@ module.exports = {
room: session.room ? session.room.name.replace(/#(\d+)$/, (whole, id) => (worldOf(whole) ? ` (${worldName(Number(id))})` : whole)) : null, room: session.room ? session.room.name.replace(/#(\d+)$/, (whole, id) => (worldOf(whole) ? ` (${worldName(Number(id))})` : whole)) : null,
address: session.address, 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": { "engines": {
"node": ">=22.5" "node": ">=22.5"
},
"dependencies": {
"discord.js": "14.26.4"
} }
} }
+329 -24
View File
@@ -94,6 +94,8 @@
transition: background 0.12s, border-color 0.12s, color 0.12s; transition: background 0.12s, border-color 0.12s, color 0.12s;
} }
button:hover { background: var(--raised); border-color: #555; } button:hover { background: var(--raised); border-color: #555; }
a.button { border: 1px solid var(--line); border-radius: 999px; padding: 7px 16px 8px; white-space: nowrap; text-decoration: none; }
a.button:hover { background: var(--raised); border-color: #555; }
button:disabled { opacity: 0.45; cursor: default; } button:disabled { opacity: 0.45; cursor: default; }
button:focus-visible, a:focus-visible, input[type="checkbox"]:focus-visible { outline: 2px solid var(--text); outline-offset: 2px; } button:focus-visible, a:focus-visible, input[type="checkbox"]:focus-visible { outline: 2px solid var(--text); outline-offset: 2px; }
button.primary { font-weight: 700; color: #000; background: var(--text); border-color: var(--text); } button.primary { font-weight: 700; color: #000; background: var(--text); border-color: var(--text); }
@@ -116,7 +118,7 @@
line-height: 17px; line-height: 17px;
text-align: center; text-align: center;
} }
@media (prefers-reduced-motion: reduce) { * { transition: none !important; } } @media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } }
.wrap { max-width: 760px; margin: 0 auto; } .wrap { max-width: 760px; margin: 0 auto; }
label.check { display: flex; align-items: center; color: var(--text); font-size: 14px; cursor: pointer; } label.check { display: flex; align-items: center; color: var(--text); font-size: 14px; cursor: pointer; }
/* dark on white whatever the page: that is what a phone's camera reads. */ /* dark on white whatever the page: that is what a phone's camera reads. */
@@ -175,6 +177,26 @@
.ban-head { display: flex; align-items: center; gap: 12px; margin-bottom: 4px; } .ban-head { display: flex; align-items: center; gap: 12px; margin-bottom: 4px; }
.ban-head img { width: 44px; height: 44px; flex: none; } .ban-head img { width: 44px; height: 44px; flex: none; }
.ban-head h2 { margin: 0; font-size: 22px; } .ban-head h2 { margin: 0; font-size: 22px; }
.chat-style-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 12px; }
.chat-style-grid input[type="color"] { width: 100%; height: 42px; padding: 3px; cursor: pointer; }
.gradient-editor { margin: 14px 0; padding: 12px; border: 1px solid var(--line); border-radius: 12px; }
.gradient-editor-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; }
.gradient-stops { display: grid; gap: 8px; }
.gradient-ramp { height: 22px; margin-bottom: 10px; border: 1px solid var(--line); border-radius: 999px; }
.gradient-stop { display: grid; grid-template-columns: 50px minmax(100px, 1fr) 72px auto; align-items: center; gap: 8px; }
.gradient-stop input[type="color"] { width: 50px; height: 36px; padding: 2px; cursor: pointer; }
.gradient-stop input[type="range"] { margin: 0; }
.gradient-stop output { color: var(--muted); font-size: 12px; text-align: right; }
.chat-preview { min-height: 74px; display: grid; place-items: center; margin-top: 14px; padding: 12px 18px; border: 1px solid var(--line); border-radius: 18px; text-align: center; font-weight: 700; background: linear-gradient(120deg, #fff, #dfe8ff); color: #445559; }
.chat-preview.pulse { animation: chatPulse 1.5s ease-in-out infinite alternate; }
.chat-preview.shimmer { background-size: 250% 100%; animation: chatShimmer 1.5s linear infinite; }
.chat-preview.flow { background-size: 220% 220%; animation: chatFlow 1.5s linear infinite alternate; }
.chat-preview.rainbow { animation: chatRainbow 2s linear infinite; }
@keyframes chatPulse { to { opacity: .55; } }
@keyframes chatShimmer { to { background-position: 100% 0; } }
@keyframes chatFlow { to { background-position: 100% 100%; } }
@keyframes chatRainbow { to { filter: hue-rotate(360deg); } }
@media (max-width: 440px) { .chat-style-grid { grid-template-columns: 1fr; } }
#ban-section pre { margin: 0 0 12px; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; } #ban-section pre { margin: 0 0 12px; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; }
#ban-section h3 { margin: 18px 0 0; } #ban-section h3 { margin: 18px 0 0; }
</style> </style>
@@ -195,16 +217,17 @@
<label class="check" style="margin-top:12px"><input id="remember-device" type="checkbox"> Trust this device for 30 days</label> <label class="check" style="margin-top:12px"><input id="remember-device" type="checkbox"> Trust this device for 30 days</label>
</div> </div>
<div class="captcha" id="captcha"></div> <div class="captcha" id="captcha"></div>
<div class="row"><button class="primary" type="submit">Sign in</button></div> <div class="row"><button class="primary" type="submit">Sign in</button><button id="client-sign-in" type="button">Sign in with the Burrow client</button></div>
</form> </form>
<p class="status" id="gate-status" role="status"></p> <p class="status" id="gate-status" role="status"></p>
<p class="hint" style="margin:10px 0 0">No account yet? <a href="/register">Create one</a></p> <p class="hint" style="margin:10px 0 0">No account yet? <a href="/register">Create one</a> · <a href="/account/recover">Forgot password or 2FA?</a></p>
</div> </div>
<div id="page" hidden> <div id="page" hidden>
<header> <header>
<img class="mark" src="/logo.png" alt=""> <img class="mark" src="/logo.png" alt="">
<h1 id="title"></h1> <h1 id="title"></h1>
<a class="button" id="item-giver" href="/account/items">Item giver</a>
<button id="sign-out" type="button">Sign out</button> <button id="sign-out" type="button">Sign out</button>
</header> </header>
@@ -242,7 +265,11 @@
<section> <section>
<h2>Buddies</h2> <h2>Buddies</h2>
<div id="buddies"></div> <!-- closed at first: a long list made the page slow to scroll -->
<details id="buddies-box" hidden>
<summary id="buddies-summary">Buddies</summary>
<div id="buddies"></div>
</details>
<p class="hint" id="no-buddies" hidden>No buddies yet.</p> <p class="hint" id="no-buddies" hidden>No buddies yet.</p>
<p class="status" id="buddy-status" role="status"></p> <p class="status" id="buddy-status" role="status"></p>
</section> </section>
@@ -293,7 +320,10 @@
<section> <section>
<h2>Den visitors</h2> <h2>Den visitors</h2>
<div id="visits"></div> <details id="visits-box" hidden>
<summary id="visits-summary">Visitors</summary>
<div id="visits"></div>
</details>
<p class="hint" id="no-visits" hidden>No visitors yet.</p> <p class="hint" id="no-visits" hidden>No visitors yet.</p>
</section> </section>
@@ -354,6 +384,35 @@
<p class="status" id="bio-status" role="status"></p> <p class="status" id="bio-status" role="status"></p>
</section> </section>
<section id="chat-bubble">
<h2>Chat bubble</h2>
<p>Choose how your spoken chat bubbles look for everyone using Burrow's current client.</p>
<form id="chat-style-form">
<div class="gradient-editor">
<div class="gradient-editor-head"><b>Gradient colours</b><button id="chat-stop-add" type="button">Add colour</button></div>
<div class="gradient-ramp" id="chat-ramp"></div>
<div class="gradient-stops" id="chat-stops"></div>
</div>
<div class="chat-style-grid">
<div hidden><input id="chat-background" type="color" value="#ffffff"></div>
<div hidden><input id="chat-accent" type="color" value="#dfe8ff"></div>
<div><label for="chat-text-colour">Text colour</label><input id="chat-text-colour" type="color" value="#445559"></div>
<div><label for="chat-border">Border</label><input id="chat-border" type="color" value="#9aabb0"></div>
<div><label for="chat-opacity">Opacity <span class="hint" id="chat-opacity-value"></span></label><input id="chat-opacity" type="range" min="25" max="100" value="75"></div>
<div><label for="chat-gradient">Gradient</label><select id="chat-gradient"><option value="linear">Linear</option><option value="radial">Radial</option><option value="solid">Solid</option></select></div>
<div><label for="chat-angle">Direction</label><select id="chat-angle"><option value="0">0°</option><option value="45">45°</option><option value="90">90°</option><option value="135">135°</option><option value="180">180°</option><option value="225">225°</option><option value="270">270°</option><option value="315">315°</option></select></div>
<div><label for="chat-strength">Gradient strength <span class="hint" id="chat-strength-value"></span></label><input id="chat-strength" type="range" min="0" max="100" value="100"></div>
<div><label for="chat-outline">Outline thickness <span class="hint" id="chat-outline-value"></span></label><input id="chat-outline" type="range" min="0" max="4" step="1" value="1"></div>
<div><label for="chat-animation">Animation</label><select id="chat-animation"><option value="none">Still</option><option value="pulse">Pulse</option><option value="shimmer">Shimmer</option><option value="flow">Flow</option><option value="rainbow">Rainbow</option></select></div>
<div><label for="chat-speed">Animation speed <span class="hint" id="chat-speed-value"></span></label><input id="chat-speed" type="range" min="40" max="300" value="100"></div>
</div>
<div class="chat-preview" id="chat-preview">Your chat bubble preview</div>
<div class="row"><button id="chat-style-swap" type="button">Swap gradient</button><button id="chat-style-random" type="button">Random gradient</button></div>
<div class="row"><button class="primary" type="submit">Save chat style</button><button id="chat-style-reset" type="button">Use original bubble</button></div>
</form>
<p class="status" id="chat-style-status" role="status"></p>
</section>
<section> <section>
<h2>Playtime</h2> <h2>Playtime</h2>
<p id="playtime-text"></p> <p id="playtime-text"></p>
@@ -367,12 +426,10 @@
<section> <section>
<h2>Discord</h2> <h2>Discord</h2>
<p id="badges" hidden></p> <p id="badges" hidden></p>
<form id="discord-form"> <p id="discord-shown"></p>
<label for="discord-name">Username</label> <p class="hint" id="discord-about">Shown on your card in the game. Sign in to Discord to link your account; boosting Burrow's Discord server gives you the Server Booster badge while you boost.</p>
<input id="discord-name" maxlength="33" autocomplete="off" spellcheck="false"> <div class="row"><button class="primary" id="discord-link" type="button">Link Discord</button>
<div class="row"><button class="primary" type="submit">Save</button> <button id="discord-remove" type="button">Unlink</button></div>
<button id="discord-remove" type="button">Remove</button></div>
</form>
<p class="status" id="discord-status" role="status"></p> <p class="status" id="discord-status" role="status"></p>
</section> </section>
@@ -506,8 +563,12 @@
]; ];
const VIA = {game: "Game", launcher: "Client", web: "This page", mod: "Moderator panel"}; const VIA = {game: "Game", launcher: "Client", web: "This page", mod: "Moderator panel"};
const ANIMALS = {1: "Tiger", 4: "Wolf", 5: "Koala", 6: "Panda", 7: "Monkey", 8: "Bunny", 13: "Rhino", 18: "Seal", 24: "Penguin"}; const ANIMALS = {1: "Tiger", 4: "Wolf", 5: "Koala", 6: "Panda", 7: "Monkey", 8: "Bunny", 13: "Rhino", 18: "Seal", 24: "Penguin"};
const DEFAULT_CHAT_STYLE = {background: "ffffff", accent: "dfe8ff", text: "445559", border: "9aabb0", opacity: 75,
animation: "none", speed: 100, gradient: "linear", angle: 45, strength: 100, outline: 1,
stops: "ffffff:0;dfe8ff:100"};
let account = null; let account = null;
let chatStops = [];
let twoStepSetup = null; // {secret, uri} while two-step sign-in is being turned on let twoStepSetup = null; // {secret, uri} while two-step sign-in is being turned on
let twoStepCodes = null; // the recovery codes, until the player says they kept them let twoStepCodes = null; // the recovery codes, until the player says they kept them
@@ -529,6 +590,126 @@
$(id).classList.toggle("bad", bad); $(id).classList.toggle("bad", bad);
}; };
const parseChatStops = style => {
const parsed = String(style.stops || "").split(";").map(value => {
const match = /^([0-9a-f]{6}):(100|[1-9]?\d)$/i.exec(value);
return match ? {color: match[1].toLowerCase(), position: Number(match[2])} : null;
});
return parsed.length >= 2 && parsed.length <= 5 && parsed.every(Boolean)
? parsed : [{color: style.background, position: 0}, {color: style.accent, position: 100}];
};
const styleValue = () => {
if (chatStops.length < 2) chatStops = parseChatStops(DEFAULT_CHAT_STYLE);
chatStops.sort((one, two) => one.position - two.position);
chatStops[0].position = 0;
chatStops.at(-1).position = 100;
const background = chatStops[0].color;
const accent = chatStops.at(-1).color;
$("chat-background").value = `#${background}`;
$("chat-accent").value = `#${accent}`;
return {
background, accent,
text: $("chat-text-colour").value.slice(1).toLowerCase(),
border: $("chat-border").value.slice(1).toLowerCase(),
opacity: Number($("chat-opacity").value),
animation: $("chat-animation").value,
speed: Number($("chat-speed").value),
gradient: $("chat-gradient").value,
angle: Number($("chat-angle").value),
strength: Number($("chat-strength").value),
outline: Number($("chat-outline").value),
stops: chatStops.map(stop => `${stop.color}:${stop.position}`).join(";"),
};
};
const paintChatPreview = () => {
const style = styleValue();
const preview = $("chat-preview");
preview.className = `chat-preview ${style.animation}`;
const mix = (one, two, amount) => one.map((part, index) => Math.round(part + (two[index] - part) * amount));
const rgb = hex => [0, 2, 4].map(at => parseInt(hex.slice(at, at + 2), 16));
const stops = parseChatStops(style).map((stop, index) => {
const colour = index ? mix(rgb(style.background), rgb(stop.color), style.strength / 100) : rgb(stop.color);
return `#${colour.map(part => part.toString(16).padStart(2, "0")).join("")} ${stop.position}%`;
}).join(", ");
preview.style.background = style.gradient === "solid" ? `#${style.background}` : style.gradient === "radial"
? `radial-gradient(circle, ${stops})`
: `linear-gradient(${style.angle}deg, ${stops})`;
preview.style.color = `#${style.text}`;
preview.style.borderColor = `#${style.border}`;
preview.style.borderWidth = `${style.outline}px`;
preview.style.opacity = String(style.opacity / 100);
preview.style.animationDuration = `${Math.max(.25, 1.5 * 100 / style.speed)}s`;
$("chat-opacity-value").textContent = `${style.opacity}%`;
$("chat-speed-value").textContent = `${style.speed}%`;
$("chat-strength-value").textContent = `${style.strength}%`;
$("chat-outline-value").textContent = `${style.outline}px`;
};
const renderChatStops = () => {
chatStops.sort((one, two) => one.position - two.position);
const holder = $("chat-stops");
holder.replaceChildren();
$("chat-ramp").style.background = `linear-gradient(90deg, ${chatStops.map(stop => `#${stop.color} ${stop.position}%`).join(", ")})`;
chatStops.forEach((stop, index) => {
const row = el("div", undefined, "gradient-stop");
const colour = document.createElement("input");
colour.type = "color";
colour.value = `#${stop.color}`;
colour.setAttribute("aria-label", `Gradient colour ${index + 1}`);
const position = document.createElement("input");
position.type = "range";
position.min = String(index ? chatStops[index - 1].position + 1 : 0);
position.max = String(index < chatStops.length - 1 ? chatStops[index + 1].position - 1 : 100);
position.value = String(stop.position);
position.disabled = index === 0 || index === chatStops.length - 1;
const value = document.createElement("output");
value.textContent = index === 0 ? "Start" : index === chatStops.length - 1 ? "End" : `${stop.position}%`;
const remove = document.createElement("button");
remove.type = "button";
remove.textContent = "Remove";
remove.disabled = chatStops.length <= 2;
colour.addEventListener("input", () => {
stop.color = colour.value.slice(1).toLowerCase();
renderChatStops();
paintChatPreview();
});
position.addEventListener("input", () => {
stop.position = Number(position.value);
value.textContent = `${stop.position}%`;
$("chat-ramp").style.background = `linear-gradient(90deg, ${chatStops.map(item => `#${item.color} ${item.position}%`).join(", ")})`;
paintChatPreview();
});
remove.addEventListener("click", () => {
chatStops.splice(index, 1);
renderChatStops();
paintChatPreview();
});
row.append(colour, position, value, remove);
holder.append(row);
});
$("chat-stop-add").disabled = chatStops.length >= 5;
};
const fillChatStyle = style => {
style = {...DEFAULT_CHAT_STYLE, ...style};
chatStops = parseChatStops(style);
$("chat-background").value = `#${style.background}`;
$("chat-accent").value = `#${style.accent}`;
$("chat-text-colour").value = `#${style.text}`;
$("chat-border").value = `#${style.border}`;
$("chat-opacity").value = String(style.opacity);
$("chat-animation").value = style.animation;
$("chat-speed").value = String(style.speed);
$("chat-gradient").value = style.gradient;
$("chat-angle").value = String(style.angle);
$("chat-strength").value = String(style.strength);
$("chat-outline").value = String(style.outline);
renderChatStops();
paintChatPreview();
};
const api = async (path, body) => { const api = async (path, body) => {
try { try {
const response = await fetch(`/account/api/${path}`, body === undefined ? {} : { const response = await fetch(`/account/api/${path}`, body === undefined ? {} : {
@@ -689,8 +870,8 @@
// moving), else drawn into a PNG that fits, smaller until it is small // moving), else drawn into a PNG that fits, smaller until it is small
// enough. any picture this browser can open will do (WebP, AVIF, BMP...). // enough. any picture this browser can open will do (WebP, AVIF, BMP...).
// null when it cannot be read at all. // null when it cannot be read at all.
const PICTURE_SIDE = 512; const PICTURE_SIDE = 256;
const PICTURE_BYTES = 300 * 1024; const PICTURE_BYTES = 100 * 1024;
const preparePicture = async file => { const preparePicture = async file => {
const kept = ["image/png", "image/jpeg", "image/gif"].includes(file.type); const kept = ["image/png", "image/jpeg", "image/gif"].includes(file.type);
let image = null; let image = null;
@@ -704,7 +885,7 @@
image.close(); image.close();
return file; return file;
} }
for (const side of [PICTURE_SIDE, 384, 256, 128]) { for (const side of [PICTURE_SIDE, 192, 128, 96]) {
const scale = Math.min(1, side / image.width, side / image.height); const scale = Math.min(1, side / image.width, side / image.height);
const canvas = document.createElement("canvas"); const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.round(image.width * scale)); canvas.width = Math.max(1, Math.round(image.width * scale));
@@ -759,6 +940,9 @@
} }
renderMyItems(); renderMyItems();
$("lock-notice").hidden = !account.locked; $("lock-notice").hidden = !account.locked;
if (!$("chat-style-form").contains(document.activeElement)) {
fillChatStyle(account.chatStyle);
}
const tiles = [ const tiles = [
[account.online ? "Playing now" : account.lastSeen ? when(account.lastSeen) : "Not played yet", "Last seen"], [account.online ? "Playing now" : account.lastSeen ? when(account.lastSeen) : "Not played yet", "Last seen"],
@@ -805,11 +989,11 @@
$("bio-text").maxLength = account.bioLimit + 20; // room for the line ends a browser counts double $("bio-text").maxLength = account.bioLimit + 20; // room for the line ends a browser counts double
$("bio-remove").hidden = !account.bio; $("bio-remove").hidden = !account.bio;
bioCount(); bioCount();
// not while it is being typed in: every answer from the server draws the page again. // linked by signing in to Discord (lib/discord.js), not typed in
if (document.activeElement !== $("discord-name")) { $("discord-shown").textContent = account.discordLinked ? `Linked: ${account.discord}` : "Not linked.";
$("discord-name").value = account.discord; $("discord-link").textContent = account.discordLinked ? "Link another" : "Link Discord";
} $("discord-link").hidden = !account.discordLinking;
$("discord-remove").hidden = !account.discord; $("discord-remove").hidden = !account.discordLinked;
$("badges").hidden = account.badges.length === 0; $("badges").hidden = account.badges.length === 0;
$("badges").textContent = `Badges: ${account.badges.join(", ")}`; $("badges").textContent = `Badges: ${account.badges.join(", ")}`;
@@ -845,6 +1029,8 @@
})); }));
} }
$("no-buddies").hidden = account.buddyList.length > 0; $("no-buddies").hidden = account.buddyList.length > 0;
$("buddies-box").hidden = account.buddyList.length === 0;
$("buddies-summary").textContent = `Show ${account.buddyList.length.toLocaleString()} ${account.buddyList.length === 1 ? "buddy" : "buddies"}`;
$("blocked").replaceChildren(...account.blocked.map(name => { $("blocked").replaceChildren(...account.blocked.map(name => {
const row = el("div", undefined, "switch"); const row = el("div", undefined, "switch");
@@ -890,6 +1076,8 @@
return entry; return entry;
})); }));
$("no-visits").hidden = account.denVisits.length > 0; $("no-visits").hidden = account.denVisits.length > 0;
$("visits-box").hidden = account.denVisits.length === 0;
$("visits-summary").textContent = `Show ${account.denVisits.length.toLocaleString()} ${account.denVisits.length === 1 ? "visit" : "visits"}`;
$("achievement-summary").textContent = `${account.achievements.earned} of ${account.achievements.of} earned.`; $("achievement-summary").textContent = `${account.achievements.earned} of ${account.achievements.of} earned.`;
$("achievements").replaceChildren(...account.achievements.counted.map(counted => { $("achievements").replaceChildren(...account.achievements.counted.map(counted => {
@@ -938,12 +1126,79 @@
if (result.ok) { if (result.ok) {
account = result.data; account = result.data;
render(); render();
// back from linking Discord: how it went, once
if (discordResult && Object.hasOwn(DISCORD_RESULTS, discordResult)) {
setStatus("discord-status", DISCORD_RESULTS[discordResult], discordResult !== "linked");
history.replaceState(null, "", location.pathname + location.hash);
}
} }
else { else {
showGate(result.status === 0 ? result.data.error : ""); showGate(result.status === 0 ? result.data.error : "");
if (Object.hasOwn(CLIENT_RESULTS, clientResult || "")) {
setStatus("gate-status", CLIENT_RESULTS[clientResult], true);
}
// never by itself on the way back from it: a browser that would
// not keep the sign-in would open tab after tab.
else if (!clientResult && clientRemembered()) {
signInWithClient();
}
}
if (clientResult) {
if (result.ok && clientResult === "ok") {
try {
localStorage.setItem(CLIENT_KEY, "1");
}
catch (err) {
// not kept: the button stays the way in.
}
}
history.replaceState(null, "", location.pathname + location.hash);
} }
}; };
// "Sign in with the Burrow client" (lib/manage.js): the browser asks
// whether to open Burrow, which opens this page again signed in (in a
// new tab: this one follows). once that has worked in this browser, the
// page asks by itself each time it opens signed out.
const CLIENT_KEY = "burrow-client-sign-in";
const CLIENT_RESULTS = {
ok: "Burrow signed you in, but this browser did not keep it. Sign in with your password.",
expired: "That sign-in took too long. Try again.",
elsewhere: "Burrow opened the page in another browser than the one you started in. Start from this browser again, or sign in with your password.",
};
const clientResult = new URLSearchParams(location.search).get("client");
const clientRemembered = () => {
try {
return localStorage.getItem(CLIENT_KEY) === "1";
}
catch (err) {
return false;
}
};
let clientWait = null;
const signInWithClient = async () => {
const started = await api("client-start", {});
if (!started.ok) {
setStatus("gate-status", started.data.error || "That did not work.", true);
return;
}
setStatus("gate-status", "Opening Burrow… Allow it if your browser asks. Burrow must be logged in, or remember you.");
location.href = `burrow://account?n=${started.data.nonce}`;
clearInterval(clientWait);
const until = Date.now() + 120000;
clientWait = setInterval(async () => {
if (account || Date.now() > until) {
clearInterval(clientWait);
return;
}
if ((await api("me")).ok) {
clearInterval(clientWait);
await load();
}
}, 2000);
};
$("client-sign-in").addEventListener("click", signInWithClient);
$("sign-in").addEventListener("submit", async event => { $("sign-in").addEventListener("submit", async event => {
event.preventDefault(); event.preventDefault();
const answer = captchaPass ? undefined : await check.answer(); const answer = captchaPass ? undefined : await check.answer();
@@ -1340,12 +1595,62 @@
}); });
$("bio-remove").addEventListener("click", () => act({action: "bio", text: ""}, "bio-status")); $("bio-remove").addEventListener("click", () => act({action: "bio", text: ""}, "bio-status"));
$("discord-form").addEventListener("submit", async event => { ["chat-background", "chat-accent", "chat-text-colour", "chat-border", "chat-opacity", "chat-gradient", "chat-angle", "chat-strength", "chat-outline", "chat-animation", "chat-speed"].forEach(id => {
event.preventDefault(); $(id).addEventListener("input", paintChatPreview);
$("discord-name").blur(); $(id).addEventListener("change", paintChatPreview);
await act({action: "discord", name: $("discord-name").value}, "discord-status");
}); });
$("discord-remove").addEventListener("click", () => act({action: "discord", name: ""}, "discord-status")); $("chat-style-form").addEventListener("submit", async event => {
event.preventDefault();
await act({action: "chatStyle", style: styleValue()}, "chat-style-status");
});
$("chat-stop-add").addEventListener("click", () => {
if (chatStops.length >= 5) return;
let gapAt = 0;
for (let index = 1; index < chatStops.length - 1; index++) {
if (chatStops[index + 1].position - chatStops[index].position > chatStops[gapAt + 1].position - chatStops[gapAt].position) gapAt = index;
}
const before = chatStops[gapAt];
const after = chatStops[gapAt + 1];
const rgb = hex => [0, 2, 4].map(at => parseInt(hex.slice(at, at + 2), 16));
const mixed = rgb(before.color).map((part, index) => Math.round((part + rgb(after.color)[index]) / 2).toString(16).padStart(2, "0")).join("");
chatStops.splice(gapAt + 1, 0, {color: mixed, position: Math.round((before.position + after.position) / 2)});
renderChatStops();
paintChatPreview();
});
$("chat-style-swap").addEventListener("click", () => {
chatStops = chatStops.slice().reverse().map(stop => ({color: stop.color, position: 100 - stop.position}));
renderChatStops();
paintChatPreview();
});
$("chat-style-random").addEventListener("click", () => {
const randomColour = () => Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, "0");
chatStops.forEach(stop => { stop.color = randomColour(); });
renderChatStops();
paintChatPreview();
});
$("chat-style-reset").addEventListener("click", async () => {
fillChatStyle(DEFAULT_CHAT_STYLE);
await act({action: "chatStyle", style: DEFAULT_CHAT_STYLE}, "chat-style-status");
});
// off to Discord's sign-in; it comes back to /account?discord=<how it went>
$("discord-link").addEventListener("click", () => {
location.href = "/account/discord/link";
});
$("discord-remove").addEventListener("click", () => {
if (confirm("Unlink your Discord account? It comes off your card, and so does the Server Booster badge.")) {
act({action: "discord", name: ""}, "discord-status");
}
});
const DISCORD_RESULTS = {
linked: "Discord linked.",
cancelled: "Linking was cancelled.",
expired: "That took too long, or was started in another browser. Try again.",
taken: "That Discord account is linked to another Burrow account.",
discord: "Discord did not answer. Try again later.",
off: "Linking Discord is not available right now.",
};
const discordResult = new URLSearchParams(location.search).get("discord");
$("lock").addEventListener("click", () => { $("lock").addEventListener("click", () => {
if (!account.locked && !window.confirm("Lock the account? Nobody gets in until you unlock it here.")) { if (!account.locked && !window.confirm("Lock the account? Nobody gets in until you unlock it here.")) {
+800 -26
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

+7 -1
View File
@@ -25,17 +25,21 @@
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
} }
#status { margin: 0; text-align: center; } #status { margin: 0; text-align: center; }
button { display: none; border: 1px solid #8c8c8c; border-radius: 5px; padding: 6px 12px; background: transparent; color: #ddd; font: inherit; cursor: pointer; }
button.show { display: block; }
</style> </style>
</head> </head>
<body> <body>
<div id="widget"></div> <div id="widget"></div>
<p id="status" role="status">Checking…</p> <p id="status" role="status">Checking…</p>
<button id="retry" type="button">Try again</button>
<script src="/captcha.js"></script> <script src="/captcha.js"></script>
<script> <script>
"use strict"; "use strict";
const action = new URLSearchParams(location.search).get("action") === "signup" ? "signup" : "login"; const action = new URLSearchParams(location.search).get("action") === "signup" ? "signup" : "login";
const status = document.getElementById("status"); const status = document.getElementById("status");
const retry = document.getElementById("retry");
const done = token => { const done = token => {
if (window.burrowCaptcha) { if (window.burrowCaptcha) {
window.burrowCaptcha.done(token); window.burrowCaptcha.done(token);
@@ -53,10 +57,12 @@
}}); }});
check.answer().then(token => { check.answer().then(token => {
if (!token) { if (!token) {
status.textContent = "Captcha failed. Close this and try again."; status.textContent = "Captcha could not load. Check your connection or content blocker.";
retry.classList.add("show");
} }
}); });
} }
retry.addEventListener("click", () => location.reload());
</script> </script>
</body> </body>
</html> </html>
+72 -23
View File
@@ -10,14 +10,29 @@
// captcha.FAILED then), and check.reset() after it: an answer is good once. // captcha.FAILED then), and check.reset() after it: an answer is good once.
window.captcha = (() => { window.captcha = (() => {
const siteKey = "{{siteKey}}"; const siteKey = "{{siteKey}}";
const LOAD_TIMEOUT_MS = 15000;
let loading = null; let loading = null;
const load = () => { const load = () => {
loading = loading || new Promise((resolve, reject) => { loading = loading || new Promise((resolve, reject) => {
const script = document.createElement("script"); const script = document.createElement("script");
script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"; script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
script.onload = () => resolve(window.turnstile); const timer = setTimeout(() => {
loading = null;
reject(new Error("the captcha took too long to load"));
}, LOAD_TIMEOUT_MS);
script.onload = () => {
clearTimeout(timer);
if (window.turnstile && typeof window.turnstile.render === "function") {
resolve(window.turnstile);
}
else {
loading = null;
reject(new Error("the captcha did not start"));
}
};
script.onerror = () => { script.onerror = () => {
clearTimeout(timer);
loading = null; loading = null;
reject(new Error("the captcha did not load")); reject(new Error("the captcha did not load"));
}; };
@@ -26,12 +41,15 @@ window.captcha = (() => {
return loading; return loading;
}; };
// `options`: {appearance} ("interaction-only" by default: seen only when // `options`: {appearance} ("always" by default: hidden till cloudflare
// cloudflare wants a click), {onAnswer(token)}. // wanted a click, it was taken for one that never showed), {onAnswer(token)}.
const MAX_RETRIES = 2; // a widget that errs is started again this often first
const mount = (element, action, options = {}) => { const mount = (element, action, options = {}) => {
let widget = null; let widget = null;
let answer = null; // a token, "" when none could be had, null while waiting let answer = null; // a token, "" when none could be had, null while waiting
let waiting = []; let waiting = [];
let retries = 0;
let starting = false;
const settle = value => { const settle = value => {
answer = value; answer = value;
if (value && options.onAnswer) { if (value && options.onAnswer) {
@@ -42,42 +60,73 @@ window.captcha = (() => {
} }
waiting = []; waiting = [];
}; };
if (siteKey) { const start = () => {
if (!siteKey || starting || widget !== null) {
return;
}
starting = true;
load().then(turnstile => { load().then(turnstile => {
widget = turnstile.render(element, { starting = false;
sitekey: siteKey, try {
action, widget = turnstile.render(element, {
theme: "dark", sitekey: siteKey,
appearance: options.appearance || "interaction-only", action,
callback: settle, theme: "dark",
"expired-callback": () => { appearance: options.appearance || "always",
answer = null; callback: value => {
}, retries = 0;
// its code is cloudflare's (110200: this site's name is not on the widget) settle(value);
"error-callback": code => { },
console.log(`captcha error ${code}`); "expired-callback": () => {
settle(""); answer = null;
}, },
}); // its code is cloudflare's (110200: this site's name is not on
}, () => settle("")); // the widget). many pass with a second go: it is had first.
} "error-callback": code => {
console.log(`captcha error ${code}`);
if (retries < MAX_RETRIES) {
retries++;
answer = null;
setTimeout(() => window.turnstile.reset(widget), 1000 * retries);
return true;
}
settle("");
return true;
},
});
}
catch (err) {
console.log(`captcha could not start: ${err.message}`);
settle("");
}
}, () => {
starting = false;
settle("");
});
};
start();
return { return {
on: Boolean(siteKey), on: Boolean(siteKey),
answer: () => { answer: () => {
if (!siteKey) { if (!siteKey) {
return Promise.resolve(undefined); return Promise.resolve(undefined);
} }
// one that could not load is tried again when an answer is wanted
if (answer === "" && widget === null) {
answer = null;
start();
}
return answer !== null ? Promise.resolve(answer) : new Promise(resolve => waiting.push(resolve)); return answer !== null ? Promise.resolve(answer) : new Promise(resolve => waiting.push(resolve));
}, },
// (a widget that never loaded keeps its "" so nothing waits on it)
reset: () => { reset: () => {
if (widget !== null) { if (widget !== null) {
answer = null; answer = null;
retries = 0;
window.turnstile.reset(widget); window.turnstile.reset(widget);
} }
}, },
}; };
}; };
return {on: Boolean(siteKey), mount, FAILED: "Captcha could not load. Reload the page."}; return {on: Boolean(siteKey), mount, FAILED: "Captcha could not load. Check your connection or content blocker, then reload."};
})(); })();
+28
View File
@@ -0,0 +1,28 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Burrow dashboard</title>
<link rel="icon" type="image/png" href="/logo-square.png">
<style>
@font-face { font-family: DigitalDelivery; src: url("/fonts/CCDigitalDelivery-Regular.otf") format("opentype"); }
@font-face { font-family: DigitalDelivery; font-weight: 700; src: url("/fonts/CCDigitalDelivery-Bold.otf") format("opentype"); }
:root { color-scheme: dark; } * { box-sizing: border-box; }
body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px; background: #000; color: #fff; font: 16px/1.45 DigitalDelivery, system-ui, sans-serif; }
main { width: min(720px, 100%); padding: clamp(24px, 6vw, 48px); border: 1px solid #333; border-radius: 22px; background: #0d0d0d; }
header { display: flex; align-items: center; gap: 15px; margin-bottom: 28px; } header img { width: 54px; height: 54px; object-fit: contain; } h1 { margin: 0; font-size: 30px; } p { color: #aaa; margin: 5px 0 0; }
.choices { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 14px; } a { display: block; padding: 20px; color: inherit; text-decoration: none; border: 1px solid #3a3a3a; border-radius: 15px; background: #151515; } a:hover, a:focus-visible { background: #222; border-color: #fff; outline: none; } strong { display: block; font-size: 19px; margin-bottom: 5px; } .hint { font-size: 13px; color: #aaa; } footer { margin-top: 24px; font-size: 12px; color: #777; }
</style>
</head>
<body>
<main>
<header><img src="/logo.png" alt=""><div><h1>Burrow dashboard</h1><p>One place for running and moderating your server.</p></div></header>
<div class="choices">
<a href="/dashboard/admin"><strong>Owner dashboard</strong><span class="hint">Server settings, accounts, logs, items, roles, and all administration.</span></a>
<a href="/dashboard/staff"><strong>Staff dashboard</strong><span class="hint">Player care, reports, moderation, review, and server health.</span></a>
</div>
<footer>Access remains role-based. Staff never receive owner controls.</footer>
</main>
</body>
</html>
+1022 -3
View File
File diff suppressed because it is too large. Load diff
+67
View File
@@ -0,0 +1,67 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Item preview</title>
<style>
html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: #1a1a1a; }
ruffle-player, ruffle-object, ruffle-embed { display: block; width: 100%; height: 100%; }
</style>
<script>
// ruffle's own settings: no menus, overlays or sound.
window.RufflePlayer = {config: {
publicPath: "https://cdn.jsdelivr.net/npm/@ruffle-rs/[email protected]/",
polyfills: false,
autoplay: "on",
unmuteOverlay: "hidden",
splashScreen: false,
contextMenu: "off",
letterbox: "off",
backgroundColor: "#1A1A1A", // the giver page's
volume: 0,
openUrlMode: "deny",
allowScriptAccess: false,
showSwfDownload: false,
warnOnUnsupportedContent: false,
logLevel: "error",
}};
</script>
<script src="https://cdn.jsdelivr.net/npm/@ruffle-rs/[email protected]/ruffle.js" integrity="sha256-JgNqlFZwiN+z3oinWejtEKTOoHspUArzbzRe70JCAJg=" crossorigin="anonymous"></script>
</head>
<body>
<script>
"use strict";
// one den item for the web item giver (public/items.html), in a frame of
// its own: #id=&v=&tint=rrggbb&s=, as Give would give it. its art plays
// in public/item-preview.swf (tools/preview-host), which sets the
// variant and tint as a den does. served sandboxed (lib/manage.js): this
// page has no origin, so no sign-in, of its own.
let player = null;
const show = () => {
const wanted = new URLSearchParams(location.hash.slice(1));
const id = /^\d{1,9}$/.test(wanted.get("id") || "") ? wanted.get("id") : null;
if (player) {
player.remove();
player = null;
}
if (!id || !window.RufflePlayer || !window.RufflePlayer.newest) {
return;
}
player = window.RufflePlayer.newest().createPlayer();
document.body.append(player);
const parameters = {art: new URL(`/account/art/den/${id}`, location.href).href, version: String(Number(wanted.get("v")) || 0)};
if (/^[0-9a-f]{6}$/i.test(wanted.get("tint") || "")) {
parameters.tint = wanted.get("tint");
parameters.strength = String(Number(wanted.get("s")) || 100);
}
const movie = {url: new URL("/account/item-preview.swf", location.href).href, parameters};
(player.ruffle ? player.ruffle().load(movie) : player.load(movie)).catch(() => {});
};
window.addEventListener("hashchange", show);
show();
</script>
</body>
</html>
Binary file not shown.
+786
View File
@@ -0,0 +1,786 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Item giver</title>
<link rel="icon" type="image/png" href="/logo-square.png">
<style>
/* the account page's look (public/account.html): black and white, in
the game's own text font. the only colours are the items' own. */
@font-face { font-family: "DigitalDelivery"; font-weight: 400; src: url("/fonts/CCDigitalDelivery-Regular.otf") format("opentype"); }
@font-face { font-family: "DigitalDelivery"; font-weight: 700; src: url("/fonts/CCDigitalDelivery-Bold.otf") format("opentype"); }
:root {
color-scheme: dark;
--bg: #000;
--panel: #0d0d0d;
--raised: #1a1a1a;
--line: #2e2e2e;
--text: #fff;
--muted: #8c8c8c;
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
::selection { background: #fff; color: #000; }
body {
margin: 0;
padding: 32px 16px 48px;
background: var(--bg);
color: var(--text);
font: 15px/1.4 "DigitalDelivery", system-ui, "Segoe UI", sans-serif;
-webkit-font-smoothing: antialiased;
}
a { color: inherit; text-underline-offset: 3px; }
h1 { margin: 0; font-size: 26px; font-weight: 700; flex: 1; }
h2 { margin: 0 0 6px; font-size: 17px; font-weight: 700; }
h3 { margin: 16px 0 8px; font-size: 14px; font-weight: 700; }
p { margin: 0 0 12px; color: var(--muted); }
.wrap { max-width: 760px; margin: 0 auto; }
header { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }
header img { width: 40px; height: 40px; }
section {
padding: 20px;
margin-bottom: 16px;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 18px;
}
input, select {
font: inherit;
color: var(--text);
background: var(--bg);
border: 1px solid var(--line);
border-radius: 14px;
padding: 9px 14px 10px;
}
input:hover, select:hover { border-color: #555; }
input:focus, select:focus { outline: none; border-color: var(--text); }
input:disabled { opacity: 0.4; }
button, a.button {
font: inherit;
color: var(--text);
background: none;
border: 1px solid var(--line);
border-radius: 999px;
padding: 7px 16px 8px;
cursor: pointer;
white-space: nowrap;
text-decoration: none;
}
button:hover, a.button:hover { background: var(--raised); border-color: #555; }
button:disabled { opacity: 0.45; cursor: default; }
button:focus-visible, a:focus-visible, input:focus-visible { outline: 2px solid var(--text); outline-offset: 2px; }
button.primary { font-weight: 700; color: #000; background: var(--text); border-color: var(--text); }
button.primary:hover { background: #d9d9d9; border-color: #d9d9d9; }
button[aria-pressed="true"] { border-color: var(--text); background: var(--raised); }
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
#search-row input { flex: 1; min-width: 180px; }
.status { min-height: 20px; margin: 10px 0 0; font-size: 13px; color: var(--muted); }
.status.bad { color: var(--text); }
.status.bad::before { content: "! "; font-weight: 700; }
#results { list-style: none; margin: 12px 0 0; padding: 0; display: grid; gap: 6px; }
#results button {
display: flex; width: 100%; gap: 10px; align-items: baseline;
border-radius: 14px; padding: 9px 14px 10px; text-align: left; white-space: normal;
}
#results .name { flex: 1; overflow-wrap: anywhere; }
.meta { font-size: 12px; color: var(--muted); white-space: nowrap; }
.swatches { display: inline-flex; gap: 3px; vertical-align: middle; }
.swatch { width: 16px; height: 16px; border-radius: 5px; border: 1px solid rgba(255, 255, 255, 0.25); }
#presets, #variants { display: flex; flex-wrap: wrap; gap: 6px; }
#presets button, #variants button { padding: 6px 10px 7px; border-radius: 12px; }
.slot { display: grid; grid-template-columns: 74px 44px 1fr; gap: 8px; align-items: center; margin-bottom: 8px; }
.slot span { color: var(--muted); font-size: 13px; }
.colour-slot { grid-template-columns: 74px 44px minmax(0, 160px) 96px; }
input.aj { width: 100%; min-width: 0; font-variant-numeric: tabular-nums; }
#whole-row { margin-top: 4px; }
#whole-row > span:first-child { width: 74px; color: var(--muted); font-size: 13px; }
#whole { width: 190px; }
#whole-note { white-space: normal; }
input[type="color"] { width: 44px; height: 38px; padding: 3px; border-radius: 10px; cursor: pointer; }
input.hex { width: 100%; max-width: 160px; font-variant-numeric: tabular-nums; text-transform: lowercase; }
input[type="range"] { flex: 1; padding: 0; border: none; accent-color: #fff; }
label.check { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; }
#give-row { margin-top: 16px; }
#item-head { display: flex; gap: 16px; align-items: center; }
#item-head > div:first-child { flex: 1; min-width: 0; }
#preview {
position: relative; flex: none; width: 160px; height: 160px;
display: grid; place-items: center;
background: var(--raised); border: 1px solid var(--line); border-radius: 14px; overflow: hidden;
}
#preview canvas, #preview img { max-width: 144px; max-height: 144px; }
#preview iframe { width: 100%; height: 100%; border: 0; }
#preview-note { position: absolute; inset: auto 8px 6px; font-size: 11px; text-align: center; color: var(--muted); }
@media (max-width: 480px) {
.slot { grid-template-columns: 64px 44px 1fr; }
.colour-slot { grid-template-columns: 64px 44px minmax(0, 1fr) 56px; }
.colour-slot span { white-space: nowrap; }
#whole-row > span:first-child { width: auto; }
#whole { width: 100%; }
#item-head { flex-direction: column-reverse; align-items: flex-start; }
}
</style>
</head>
<body>
<div class="wrap">
<header>
<img src="/logo.png" alt="">
<h1>Item giver</h1>
<a class="button" href="/account">Your account</a>
</header>
<section id="gate" hidden>
<h2 id="gate-title">Sign in first</h2>
<p id="gate-text">The item giver uses your account page's sign-in.</p>
<a class="button" href="/account">Go to your account page</a>
</section>
<section id="finder" hidden>
<p id="who"></p>
<div class="row" id="search-row">
<input id="query" type="search" placeholder="Name or id" maxlength="60" autocomplete="off" spellcheck="false" aria-label="Search items">
<select id="kind" aria-label="Kind of item">
<option value="all">Everything</option>
<option value="clothing">Clothing</option>
<option value="den">Den items</option>
</select>
</div>
<p class="status" id="search-status" role="status"></p>
<ul id="results"></ul>
</section>
<section id="detail" hidden>
<div id="item-head">
<div>
<h2 id="item-name"></h2>
<p class="meta" id="item-meta"></p>
</div>
<div id="preview" aria-label="How it looks">
<canvas id="preview-icon" hidden></canvas>
<img id="preview-art" alt="" hidden>
<iframe id="preview-den" title="How it looks" sandbox="allow-scripts" hidden></iframe>
<span id="preview-note"></span>
</div>
</div>
<div id="clothing-part">
<h3>The item's own colours</h3>
<div id="presets"></div>
<h3>Your own colours</h3>
<div id="slots"></div>
<div class="row" id="whole-row">
<span>Whole item</span>
<input class="aj" id="whole" inputmode="numeric" maxlength="11" spellcheck="false" autocomplete="off" placeholder="AJ colour" aria-label="The whole item's colour as the game writes it">
<span class="meta" id="whole-note"></span>
</div>
</div>
<div id="den-part">
<h3>Variant</h3>
<div id="variants"></div>
<p id="no-variants" hidden>This item has no other variants.</p>
<h3>Tint</h3>
<p id="tint-off" hidden>Mannequins cannot be tinted.</p>
<div id="tint-on">
<label class="check"><input id="tint" type="checkbox"> The whole item in shades of a colour</label>
<div class="slot" style="margin-top:10px">
<span>Colour</span>
<input type="color" id="tint-picker" value="#4ab3f4" aria-label="Tint colour">
<input class="hex" id="tint-hex" value="#4ab3f4" maxlength="7" spellcheck="false" aria-label="Tint colour as #RRGGBB">
</div>
<div class="row">
<span class="meta">Strength</span>
<input type="range" id="tint-strength" min="1" max="100" value="70" aria-label="Tint strength">
<span class="meta" id="tint-strength-text">70%</span>
</div>
</div>
</div>
<div class="row" id="give-row">
<button class="primary" id="give" type="button">Give</button>
<span class="meta" id="give-what"></span>
</div>
<p class="status" id="give-status" role="status"></p>
</section>
</div>
<script>
"use strict";
// the item giver on the web (lib/admin.js searchFor and giveAs, by way
// of lib/manage.js), signed in as on the account page: items go to that
// account, as the in-game giver's go to the one playing.
const $ = id => document.getElementById(id);
const KINDS = {clothing: "Clothing", den: "Den item"};
let chosen = null; // the result picked
let preset = 0; // the item's own colour picked, or null for the slots' own
let variant = 0;
const setStatus = (id, text, bad = false) => {
$(id).textContent = text;
$(id).classList.toggle("bad", bad);
};
const api = async (path, body) => {
try {
const response = await fetch(`/account/api/${path}`, body === undefined ? {} : {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body),
});
return {ok: response.ok, status: response.status, data: await response.json().catch(() => ({}))};
}
catch (err) {
return {ok: false, status: 0, data: {error: "The server did not answer."}};
}
};
// "#abc", "abc", "#aabbcc" or "aabbcc" as "#aabbcc"; null for anything else.
const readHex = text => {
const match = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(text).trim());
if (!match) {
return null;
}
const digits = match[1].length === 3 ? match[1].replace(/./g, digit => digit + digit) : match[1];
return `#${digits.toLowerCase()}`;
};
const swatches = colours => {
const box = document.createElement("span");
box.className = "swatches";
for (const colour of colours) {
const swatch = document.createElement("span");
swatch.className = "swatch";
swatch.style.background = `#${colour}`;
box.append(swatch);
}
return box;
};
// a colour picker and a #RRGGBB box that follow each other; `onChange`
// is told of each colour taken.
const pairUp = (picker, box, onChange) => {
picker.addEventListener("input", () => {
box.value = picker.value;
onChange();
});
box.addEventListener("input", () => {
const hex = readHex(box.value);
box.setCustomValidity(hex ? "" : "#RRGGBB");
if (hex) {
picker.value = hex;
onChange();
}
});
box.addEventListener("change", () => {
const hex = readHex(box.value);
box.value = hex || picker.value;
box.setCustomValidity("");
});
};
// the game's way of writing colours: one number for the whole item, its
// four colours' places in the game's palette of 256, colour 1 the top
// byte; written unsigned, or signed as lists of the game's colours often
// have them. top byte 0xFD: a custom colour, four RGB values of the
// server's own (lib/colours.js), not palette places.
let palette = null; // the game's 256 colours, "#rrggbb", once the server says
let customId = null; // the custom colour the four make, when one is known
const CUSTOM_TOP = 0xFD;
const isCustom = value => value >>> 24 === CUSTOM_TOP;
const readWhole = text => {
const value = /^-?\d{1,10}$/.test(String(text).trim()) ? Number(String(text).trim()) : NaN;
return value >= -0x80000000 && value <= 0xFFFFFFFF ? value >>> 0 : null;
};
// one colour's place, 0 to 255; -128 to -1 are 128 to 255 written signed
const readIndex = text => {
const value = /^-?\d{1,3}$/.test(String(text).trim()) ? Number(String(text).trim()) : NaN;
return value >= -128 && value <= 255 ? (value + 256) % 256 : null;
};
const pack = indexes => indexes.reduce((value, index) => value * 256 + index, 0);
// a slot set: its colour, and its place in the palette or null. `from`
// is the box typed in, left as typed.
const setSlot = (slot, hex, index, from = null) => {
slot.index = index;
if (from !== "hex") {
slot.picker.value = hex;
slot.box.value = hex;
}
if (from !== "aj") {
slot.aj.value = index === null ? "" : String(index);
slot.aj.setCustomValidity("");
}
slot.aj.placeholder = index === null && palette ? "custom" : "AJ";
};
// what Give gives: a colour id, or null for a custom colour still to make.
const wholeValue = () => {
if (preset !== null && chosen && chosen.presets[preset]) {
return chosen.presets[preset].id;
}
if (customId !== null) {
return customId;
}
return slots.every(slot => slot.index !== null) ? pack(slots.map(slot => slot.index)) : null;
};
let lookupTimer = null;
const showWhole = () => {
const value = wholeValue();
if (document.activeElement !== $("whole")) {
$("whole").value = value === null ? "" : String(value);
$("whole").setCustomValidity("");
}
$("whole-note").textContent = value === null ? "A new custom colour, made when you give it."
: `${value} unsigned · ${value | 0} signed${isCustom(value) ? " · a custom colour" : ""}`;
// four colours not all the palette's: a custom colour they make already?
clearTimeout(lookupTimer);
if (value === null) {
const asked = slots.map(slot => slot.picker.value.slice(1)).join(",");
lookupTimer = setTimeout(async () => {
const result = await api(`colour?rgbs=${asked}`);
if (result.ok && result.data.id !== null && preset === null && customId === null
&& slots.map(slot => slot.picker.value.slice(1)).join(",") === asked) {
customId = result.data.id;
showWhole();
showChoice();
}
}, 200);
}
};
// a whole item's colour taken: from the whole box (`from`) or one of the item's own.
const applyWhole = async (value, from = null, own = null) => {
if (isCustom(value)) {
const colours = own || await api(`colour?id=${value}`).then(result => (result.ok ? result.data.colours : null));
if (!colours) {
$("whole-note").textContent = "No such custom colour.";
return;
}
if (from === "whole" && readWhole($("whole").value) !== value) {
return; // typed on since
}
colours.forEach((colour, index) => setSlot(slots[index], `#${colour}`, null));
customId = value;
}
else {
[24, 16, 8, 0].forEach((shift, index) => {
const place = value >>> shift & 255;
setSlot(slots[index], palette ? palette[place] : own ? `#${own[index]}` : slots[index].picker.value, place);
});
customId = null;
}
showChoice();
};
const slots = [];
for (let slot = 0; slot < 4; slot++) {
const row = document.createElement("div");
row.className = "slot colour-slot";
const name = document.createElement("span");
name.textContent = `Colour ${slot + 1}`;
const picker = document.createElement("input");
picker.type = "color";
picker.value = "#ffffff";
picker.setAttribute("aria-label", `Colour ${slot + 1}`);
const box = document.createElement("input");
box.className = "hex";
box.maxLength = 7;
box.spellcheck = false;
box.value = "#ffffff";
box.setAttribute("aria-label", `Colour ${slot + 1} as #RRGGBB`);
const aj = document.createElement("input");
aj.className = "aj";
aj.inputMode = "numeric";
aj.maxLength = 4;
aj.spellcheck = false;
aj.autocomplete = "off";
aj.placeholder = "AJ";
aj.title = "Its place in the game's palette: 0 to 255 (-128 to -1 written signed)";
aj.setAttribute("aria-label", `Colour ${slot + 1} as the game writes it, 0 to 255`);
const own = {picker, box, aj, index: null};
pairUp(picker, box, () => {
const place = palette ? palette.indexOf(picker.value) : -1;
setSlot(own, picker.value, place < 0 ? null : place, "hex");
preset = null;
customId = null;
showChoice();
});
aj.addEventListener("input", () => {
const place = readIndex(aj.value);
aj.setCustomValidity(place === null || !palette ? "0 to 255" : "");
if (place !== null && palette) {
setSlot(own, palette[place], place, "aj");
preset = null;
customId = null;
showChoice();
}
});
aj.addEventListener("change", () => setSlot(own, own.picker.value, own.index));
row.append(name, picker, box, aj);
$("slots").append(row);
slots.push(own);
}
$("whole").addEventListener("input", () => {
const value = readWhole($("whole").value);
$("whole").setCustomValidity(value === null ? "A colour id, signed or not" : "");
if (value !== null) {
preset = null;
applyWhole(value, "whole");
}
else if ($("whole").value.trim()) {
$("whole-note").textContent = "A whole number: -2147483648 to 4294967295.";
}
});
$("whole").addEventListener("change", showChoice);
pairUp($("tint-picker"), $("tint-hex"), () => {
$("tint").checked = true;
showChoice();
});
$("tint").addEventListener("change", showChoice);
$("tint-strength").addEventListener("input", () => {
$("tint-strength-text").textContent = `${$("tint-strength").value}%`;
$("tint").checked = true;
showChoice();
});
// the item as it would be given (lib/itempreview.js). clothing: its
// closet icon, coloured here as the game colours it
// (PaletteHelper.BuildAnimalPalette, LayerBitmap.paintFrame). den items:
// their art played in a frame of public/item-preview.html. a custom
// item with a picture of its own: that picture.
const icons = new Map(); // clothing id: its icon, {w, h, bytes}, or null
const rgbOf = hex => parseInt(hex.slice(1), 16);
const gradient = (palette, rgb, start, count) => {
let [red, green, blue] = [rgb >> 16 & 255, rgb >> 8 & 255, rgb & 255];
const [stepRed, stepGreen, stepBlue] = [red, green, blue].map(value => Math.floor(value / (count + 2)));
for (let at = start + count - 1, left = count; left > 0; left--, at--) {
[255, 192, 128, 64].forEach((alpha, shade) => {
palette[at + 25 * shade] = [red, green, blue, alpha];
});
red -= stepRed;
green -= stepGreen;
blue -= stepBlue;
}
};
const mix = (one, other) => [16, 8, 0].reduce((sum, shift) => sum | (((one >> shift & 255) + (other >> shift & 255)) >> 1) << shift, 0);
const paletteOf = ([one, two, three, four]) => {
const palette = [];
[[one, 1, 3], [two, 4, 3], [three, 7, 3], [four, 10, 3], [mix(one, two), 13, 2], [mix(two, three), 15, 2],
[mix(one, three), 17, 2], [mix(one, four), 19, 2], [mix(two, four), 21, 2], [mix(three, four), 23, 2]]
.forEach(([rgb, start, count]) => gradient(palette, rgb, start, count));
return palette;
};
const paintIcon = (icon, colours) => {
const canvas = $("preview-icon");
canvas.width = icon.w;
canvas.height = icon.h;
const context = canvas.getContext("2d");
const image = context.createImageData(icon.w, icon.h);
const palette = paletteOf(colours.map(rgbOf));
const bytes = icon.bytes;
let [x, y, at] = [0, 0, 0];
while (at < bytes.length) {
let index = bytes[at++];
let run = 1;
if (index & 0x80) {
index &= 0x7F;
run = bytes[at++] + 1;
}
if (index === 0) {
x += run;
if (x >= icon.w) {
const over = x - icon.w;
x = over % icon.w;
y += Math.floor(over / icon.w) + 1;
}
continue;
}
const colour = palette[index];
for (; run > 0; run--) {
if (colour && y < icon.h) {
image.data.set(colour, (y * icon.w + x) * 4);
}
if (++x === icon.w) {
x = 0;
y++;
}
}
}
context.putImageData(image, 0, 0);
};
let previewShown = null; // what the preview shows, to change only what changed
let denTimer = null;
const showPreview = () => {
const entry = chosen;
const note = text => {
$("preview-note").textContent = text;
};
const only = id => {
for (const one of ["preview-icon", "preview-art", "preview-den"]) {
$(one).hidden = one !== id;
}
};
if (entry.art) {
if (previewShown !== entry.art) {
previewShown = entry.art;
only("preview-art");
note("");
$("preview-art").src = entry.art;
}
return;
}
if (entry.kind === "clothing") {
const colours = slots.map(slot => slot.picker.value);
const icon = icons.get(entry.id);
if (icon === undefined) {
only(null);
note("Loading…");
icons.set(entry.id, false);
fetch(`/account/art/clothing/${entry.id}`).then(response => (response.ok ? response.json() : null)).catch(() => null).then(found => {
icons.set(entry.id, found ? {w: found.w, h: found.h, bytes: Uint8Array.from(atob(found.b), letter => letter.charCodeAt(0))} : null);
if (chosen === entry) {
showPreview();
}
});
return;
}
if (icon) {
only("preview-icon");
note("");
paintIcon(icon, colours);
}
else if (icon === null) {
only(null);
note("No picture");
}
previewShown = null;
return;
}
const wanted = new URLSearchParams({id: entry.id, v: variant});
if (entry.tintable && $("tint").checked) {
wanted.set("tint", $("tint-picker").value.slice(1));
wanted.set("s", $("tint-strength").value);
}
const address = `/account/item-preview#${wanted}`;
if (previewShown === address) {
return;
}
previewShown = address;
only("preview-den");
note("");
// a new player each time: a slider dragged waits for it to stop
clearTimeout(denTimer);
denTimer = setTimeout(() => {
$("preview-den").src = address;
}, $("preview-den").src ? 250 : 0);
};
// what Give would give, said beside it.
function showChoice() {
for (const [index, button] of [...$("presets").children].entries()) {
button.setAttribute("aria-pressed", String(index === preset));
}
for (const button of $("variants").children) {
button.setAttribute("aria-pressed", String(Number(button.dataset.variant) === variant));
}
if (!chosen) {
return;
}
showPreview();
if (chosen.kind === "clothing") {
showWhole();
const value = wholeValue();
$("give-what").textContent = preset !== null ? `Its own colour ${preset + 1} (${value})`
: value !== null ? `Colour ${value}` : `A new colour of ${slots.map(slot => slot.picker.value).join(" ")}`;
}
else {
const parts = [chosen.variants.length ? `Variant ${chosen.variants.indexOf(variant) + 1}` : "As it is"];
if (chosen.tintable && $("tint").checked) {
parts.push(`tinted ${$("tint-picker").value} at ${$("tint-strength").value}%`);
}
$("give-what").textContent = parts.join(", ");
}
}
const choosePreset = index => {
preset = index;
applyWhole(chosen.presets[index].id, null, chosen.presets[index].colours);
};
const choose = entry => {
chosen = entry;
$("detail").hidden = false;
$("item-name").textContent = entry.name;
$("item-meta").textContent = `${KINDS[entry.kind]} · id ${entry.id}${entry.cost ? ` · ${entry.cost} gems in shops` : ""}`;
$("clothing-part").hidden = entry.kind !== "clothing";
$("den-part").hidden = entry.kind !== "den";
setStatus("give-status", "");
if (entry.kind === "clothing") {
$("presets").textContent = "";
entry.presets.forEach((option, index) => {
const button = document.createElement("button");
button.type = "button";
button.title = `Colour ${index + 1} (${option.id})`;
button.append(option.colours ? swatches(option.colours) : String(index + 1));
button.addEventListener("click", () => choosePreset(index));
$("presets").append(button);
});
if (entry.presets.length) {
choosePreset(0);
}
else {
preset = null;
}
}
else {
$("variants").textContent = "";
variant = entry.variants.length ? entry.variants[0] : 0;
entry.variants.forEach((version, index) => {
const button = document.createElement("button");
button.type = "button";
button.dataset.variant = String(version);
button.title = `Variant ${index + 1}`;
button.append(entry.variantColours ? swatches(entry.variantColours[index]) : String(index + 1));
button.addEventListener("click", () => {
variant = version;
showChoice();
});
$("variants").append(button);
});
$("no-variants").hidden = entry.variants.length > 0;
$("tint-on").hidden = !entry.tintable;
$("tint-off").hidden = entry.tintable;
$("tint").checked = false;
}
showChoice();
$("detail").scrollIntoView({behavior: "smooth", block: "nearest"});
};
const showResults = found => {
const list = $("results");
list.textContent = "";
for (const entry of found.results) {
const row = document.createElement("li");
const button = document.createElement("button");
button.type = "button";
const name = document.createElement("span");
name.className = "name";
name.textContent = entry.name;
const meta = document.createElement("span");
meta.className = "meta";
meta.textContent = `${KINDS[entry.kind]} · ${entry.id}`;
button.append(name, meta);
button.addEventListener("click", () => choose(entry));
row.append(button);
list.append(row);
}
setStatus("search-status", found.total === 0 ? "Nothing found." : found.total > found.results.length
? `${found.total} found; the first ${found.results.length} shown. Type more to narrow it down.` : `${found.total} found.`);
};
const showGate = (title, text) => {
$("gate").hidden = false;
$("finder").hidden = true;
$("detail").hidden = true;
$("gate-title").textContent = title;
$("gate-text").textContent = text;
};
let asked = 0;
const search = async () => {
const mine = ++asked;
const result = await api(`giver?q=${encodeURIComponent($("query").value.trim())}&kind=${encodeURIComponent($("kind").value)}`);
if (mine !== asked) {
return;
}
if (result.status === 401) {
showGate("Sign in first", "The item giver uses your account page's sign-in.");
}
else if (result.status === 403) {
showGate("Not now", "The item giver is not open to this account at the moment. Your account page says why.");
}
else if (!result.ok) {
setStatus("search-status", result.data.error || "That did not work.", true);
}
else {
$("gate").hidden = true;
$("finder").hidden = false;
showResults(result.data);
}
};
let typing = null;
$("query").addEventListener("input", () => {
clearTimeout(typing);
typing = setTimeout(search, 250);
});
$("kind").addEventListener("change", search);
$("give").addEventListener("click", async () => {
if (!chosen) {
return;
}
const body = {kind: chosen.kind, id: chosen.id};
if (chosen.kind === "clothing") {
const value = wholeValue();
if (preset !== null) {
body.colorIndex = preset;
}
else if (value !== null) {
body.color = String(value);
}
else {
body.color = slots.map(slot => slot.picker.value).join(" ");
}
}
else {
body.version = variant;
if (chosen.tintable && $("tint").checked) {
body.tint = $("tint-picker").value;
body.tintStrength = Number($("tint-strength").value);
}
}
$("give").disabled = true;
const result = await api("give", body);
$("give").disabled = false;
if (result.status === 401) {
showGate("Sign in again", "Your account page's sign-in ended.");
return;
}
if (!result.ok) {
setStatus("give-status", result.data.error || "That did not work.", true);
return;
}
const as = result.data.color !== undefined ? ` Its colour in the game: ${result.data.color}.` : result.data.version ? ` Its version in the game: ${result.data.version}.` : "";
setStatus("give-status", `${chosen.name}: given. ${result.data.online ? "It is in your inventory in the game now." : "It is in your inventory next time you play."}${as}`);
});
api("colour").then(result => {
if (result.ok && result.data.palette) {
palette = result.data.palette.map(colour => `#${colour}`);
for (const slot of slots) {
const place = palette.indexOf(slot.picker.value);
setSlot(slot, slot.picker.value, slot.index !== null ? slot.index : place < 0 ? null : place);
}
showChoice();
}
else {
for (const slot of slots) {
slot.aj.disabled = true;
}
}
});
api("me").then(result => {
if (result.ok) {
$("who").textContent = `Items go to ${result.data.username}.`;
}
});
search();
</script>
</body>
</html>
+1347 -262
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 284 files, more files were not shown because too many files have changed in this diff. Show more