Compare commits

..
109 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
Snipz 783feb7788 Merge pull request #5 from burrow-dev/moderator-tools
Moderator tools etc
2026-10-17 22:02:15 -04:00
SnipzilandClaude Opus 5.5 ee06e8ca77 fix(ci): pass the security invariants and clear the code-scanning alerts
- Remove package-lock.json: the server uses no npm packages, which the
  invariants check enforces (no supply chain to attack).
- Allow the two hosts the server really calls in .github/allowed-hosts.json:
  cdn.jsdelivr.net (Twemoji pictures, lib/emoji.js) and vision.googleapis.com
  (the optional SafeSearch check, lib/image-moderation.js). The github.com
  mention in lib/emoji.js was only a comment, now reworded.
- logText strips line feeds with .replace(/\n/g, ""), the form CodeQL's
  js/log-injection recognises as a sanitiser. The old [\r\n]+ to a space was
  just as safe, but not recognised, so every log line using it was flagged
  (34 alerts on main, 35 on this branch).
- /authenticate: the saved sign-in is decided by what the server finds for
  the refresh token, not by whether the request has one
  (js/user-controlled-bypass). A token that is not good is still refused
  with error_code 100.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 21:55:48 -04:00
Snipzil d8a9c1f881 feat(package): add package-lock.json for dependency management 2026-10-17 21:46:43 -04:00
SnipzilandClaude Opus 5.5 59d9d7e5fa feat(client): item maker, worn pictures, emoji, sitting, typing, AFK, staff window
Rebuilt swf/ajclient.swf from swf-src (tools/build-client.sh). New patched
classes: KeepAlive, AvatarView, AvatarUtility, Item, DenItemHelper,
SitForwardAction.

Custom items
- The Item Maker in Settings, in the game's own style: make an item from one
  of the game's, name it, upload a picture (PNG encoded in the client and
  shrunk when too big), choose sticker or texture, rename, delete.
- Pictures stand in for the item's icon and, for den items, the placed item.
- Worn pictures: LayerBitmap paints a sticker or a texture. Fixed it showing
  only until the player moved:
  - AvatarView rebuilt the worn layers on every new animation without the
    item id, so walking drew the base item. It now carries the id ("d").
  - Frames painted while the picture loaded stayed cached as the base item.
    They are all painted again when it arrives (LayerBitmap.artArrived).
- The picture loader checks the server's crossdomain policy before its pixels
  are read.

Chat
- Windows emoji and the AJ emotes inline with text in chat bubbles; emoji are
  sent as \{hex} tags. An emoji picker and :shortcodes:.
- Chat box limit 200 characters; the box shows emoji in the system font.
- Clicking an emote while typing puts its code in the chat box.
- Two new base emotes: 💀 and 😭 (HUDAssets.swf, EmoticonUtility).
- Typing bubble: a "..." over a player's animal while they type ("xty").
  It goes on a new line, when they stop, or after 8 seconds.
- loadArt shares pictures by address: emoji and icons load and decode once.

Actions
- Sit Front and Sit Back between the sit arrows, plus Mirror for any action
  (from the other session). Front now plays animation 5 (facing the camera)
  and Back animation 1 (facing away); both had played animation 1.

Staff
- The Moderate window from a player card's Report button for staff: warn
  (custom text too), kick, silence, ban, summon, goto, notes.
- Invisible staff drawn half see-through; staff land on the exact spot on
  goto and summon ("xgt").

Other
- AFK sign-out after 75 minutes instead of 7, with a 60-second warning
  (com.sbi.client.KeepAlive).
- Jam-a-Grams show custom items and colours; Jammer Wall avatar photos fixed.
- The Item Maker row in the settings menu and the item window toggle.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 21:44:11 -04:00
SnipzilandClaude Opus 5.5 331c3e6025 feat(panels): redesigned admin and moderator panels, item review, account items
Both panels keep the black and white theme and the game's font, with a new
sidebar layout.

Moderator panel (public/mod.html)
- Dashboard: tiles for players online, open reports, requests and paintings;
  find a player; recent mod notes; a Restrict Items card for roles that may
  lock items.
- Player page: mod notes, the items the player made with their pictures,
  "Take picture off" (counts as a strike), and stop/allow picture uploads.
- Items tab: make items, change their look, lock and unlock, take from a
  player, delete.
- Review tab (items.approve): approve or turn away new items and pictures.
  Pictures are blurred until clicked, and each card shows how many of the
  maker's pictures were turned away before. Lists whose uploads are stopped.
- Emoji shown as pictures in chat logs.

Admin panel (public/admin.html)
- Overview: a Restrict Items card that searches any item by name or id and
  locks or unlocks it in place, with the count of locked items.
- Items page: the same tools as the moderator panel, plus the Item Maker
  switches (players can make items; new items wait; every picture waits).
- Role permission matrix on the Moderators page, and per-account permission
  grants and denies.
- Main's Chat tab added to the sidebar.

Account page (public/account.html)
- My Items: rename, add or change a picture (converted and shrunk in the
  browser when needed), sticker or texture, delete. Shows when a picture is
  waiting for a moderator and when uploads are stopped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 21:44:10 -04:00
SnipzilandClaude Opus 5.5 e05565787f feat(server): staff tools, player-made items, picture safety, chat, multiplayer games
Staff and moderation
- Invisible staff (!invisible, "xiv"): hidden from players, half see-through
  to other staff, cannot chat while hidden. New permission staff.invisible.
- Summon and goto land on the player's exact spot ("xgt" before the move).
- Custom warnings (!warn PLAYER custom TEXT), shown in the warning popup.
- Mod notes (!note, !notes; lib/modnotes.js), on the player page and the
  dashboard.
- Granular permissions: per-role overrides (setting rolePermissions) and
  per-account grants and denies, applied live to staff who are playing
  (refreshStaff re-sends "xsp").
- Item control (lib/itemcontrol.js): lock items out of the item finder
  (!lock, !unlock, !locked), take an item from a player (!take), delete a
  custom item from the game and every inventory.
- GET items/find: search any item by name or id, marked locked, for the
  dashboards' quick lock.

Player-made items (lib/playeritems.js, "xcm")
- The Item Maker: make, rename, set the worn look, delete. 5 a day, 20 in all;
  names go through the name filter.
- Admin switches: Item Maker on/off, new items wait for approval, and a
  separate switch (on by default) that holds every player-uploaded picture
  for a moderator. Review queue for items.approve (moderator and up).
- Pictures (lib/itemart.js): PNG, JPEG and GIF cleaned of metadata, BMP
  converted to PNG; 512px and 300KB at most once cleaned.
- Worn as the maker chooses: a sticker (the picture) or a texture (the
  item's shape painted with the picture).

Picture safety
- A picture waiting for approval is never served publicly: /itemart/ 404s it,
  and it is only shown through /account|/mod|/admin/api/itemart to its maker
  and to staff who review or make items.
- A picture turned away or taken off is remembered by SHA-256 and cannot be
  uploaded again.
- Three strikes: three pictures turned away stops a player's uploads until a
  moderator lets them again. Staff can stop or allow uploads by hand.
- Accounts under 24 hours old cannot upload pictures (AJ_ITEM_ART_MIN_HOURS);
  uploads capped at 10 a day.
- Optional Google Cloud Vision SafeSearch (lib/image-moderation.js) for item
  pictures and Art Studio paintings when AJ_GOOGLE_VISION_API_KEY is set;
  fails closed when the scanner is unreachable.

Chat
- Emoji: Twemoji pictures served at /emoji/<codepoints>.png and cached in
  data/emoji (lib/emoji.js).
- Smart spam filtering before the word filter (lib/chatspam.js): long runs of
  one character, repeated words and lines, huge words and emoji floods are
  tidied, and repeats within 20 seconds are dropped.
- Typing indicator: "xty" is passed on to everyone in the room who can see
  the player, at most every 2 seconds.

Games (lib/minigames.js)
- Room games can be played together: a MULTIPLAYER table gives a game a
  waiting list (Single Player / Multiplayer). Players in the same room are
  matched, taken into the game together, and each one's moves are relayed to
  the others. Gem Breaker is the first: two players, "pos", "shoot" and
  "playerLost" relayed.
- Gem Breaker's start message now lists each player's id. Without it no
  player counted as local, so even single player could not aim.

Other
- Players stay connected through the client's new 75-minute AFK limit
  (idleTimeoutMs 80 minutes).
- Jam-a-Grams carry custom items and colours; Jammer Wall avatar photos are
  validated (walls.js photoParam).
- Weak passwords refused (common words, or containing the username).
- Code-scanning fixes: every logged value goes through logText
  (lib/logtext.js) against log injection, HSTS, path-only error logs, a
  single file read in lib/names.js.

Tests: items (pictures, approval, strikes, re-upload refusal, the hidden
waiting picture, the dashboard search), staff (invisibility, goto and summon
spots, custom warnings, notes), buddygames (two-player Gem Breaker, the
typing relay), and updates for main's verified badge and spawn rooms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 21:44:10 -04:00
SnipzilandClaude Opus 5.5 da7eb9af58 Merge origin/main into moderator-tools
Hardware bans, panel search and logs, two worlds and the verified badge,
with the branch's staff roles kept: full rooms let in active staff, and
address search stays with the roles that may ban addresses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 17:58:28 -04:00
Burrowdev 13c2f04d52 fix: device ids optional until players update to client 1.3.0
A sign-in without device ids is let in unless AJ_REQUIRE_DEVICE=1. An
account seen on banned hardware is still refused, with the ban's reason,
when its client sends no ids. The privacy policy no longer says the
client cannot sign in without them.
2026-10-17 23:54:46 +03:00
Burrowdev 31cbd87ff8 feat: two worlds, rooms of 40, random spawn with space
- rooms hold 40 players. a player not starting in their den arrives in
  a random room of config.spawnRooms that has space (AJ_SPAWN_ROOMS
  overrides); with every one full, the emptiest, over the cap.
- two worlds, Aldan and Congo (AJ_WORLDS sets how many): each its own
  copy of every land, dens and parties shared. a player arrives in a
  random world with space and keeps it through dens and parties.
- the settings menu's World row is back: the server sends the worlds'
  names (generic list 16) and the world list (rm), and the client asks
  for the names once at login. a buddy's "go to" leads into their
  world, whose name the buddy card shows. "Find Open World" (on by
  default) joins a full room in a world with space.
- the panels show the world with the room. the test harness pins one
  world and the township. buildVersion 60.
2026-10-17 23:54:46 +03:00
Burrowdev b813d89cfa feat: animals use the actions they have art for in any room
A land animal underwater is shown the land actions (sit, sleep, hop,
dance, play) and an ocean animal on land the ocean ones; animals of
land and ocean both get a "Swim moves" / "Land moves" button above the
actions window to swap sets. gui.ActionManager joins swf-src. The other
set's dance and play go by names of their own (:danceLand:,
:danceSwim:, :playLand:, :playSwim:), and AvatarWorldView plays each
action from the set the animal has art for.
2026-10-17 23:54:46 +03:00
Burrowdev cf729d52dc feat: hardware bans, panel search and logs, jam-a-gram and wall post logs
- the client (1.3.0) sends one-way hashes of the device's ids at
  sign-in; the server keys them again with a secret of its own
  (data/device-key) and keeps them per account (lib/devices.js). a
  sign-in without them is refused with 426 (AJ_REQUIRE_DEVICE=0 lets it
  in), so 1.2 clients cannot sign in.
- hardware bans: every device an account used in the last 90 days.
  any id but a network card blocks sign-in, sign-up and the game, on
  any account. a network card match, ids that look altered, or a device
  shared with a banned player raise hardware alerts instead.
- both panels: hardware ban and lift, the account's hardware ids,
  search by hardware id, other accounts by device or address, a
  timeline (bans, staff actions, reports, alerts), and hardware bans
  and alerts in the bans tab.
- jam-a-grams and wall posts go into the chat log, the filtered ones
  marked not sent. chat search filters by kind, by what the filter
  stopped, and from a time back; each player's page lists their
  jam-a-grams and wall posts, sent and received.
- account search runs on the server and ranks exact names first, then
  names starting with the search; the admin panel no longer downloads
  every account. hidden tabs only refresh the waiting counts in the
  title. masterpieces can be searched by maker, approved ones too.
  reports can show the reported player's chat at the time. links follow
  the open tab and player.
- admin actions on accounts go into the moderator log.
- privacy policy covers hardware hashes and the new logs.
2026-10-17 23:54:46 +03:00
Burrowdev 0e86592d40 feat: verified badge
A blue scalloped seal with a tick, listed first so it sits straight
after the name. tools/make-badges.py draws it (verified.png and
verified.swf).
2026-10-17 23:54:46 +03:00
SnipzilandClaude Opus 5.5 d09ee94e16 Merge origin/main into moderator-tools
The built client is main's here; it is rebuilt from the merged sources.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 16:33:14 -04:00
Snipzil bcefbc2d8a docs(readme): add twemoji credits 2026-10-17 16:25:09 -04:00
burrow-dev 555360aa1b Merge pull request #3 from burrow-dev/docs/security-audit
docs: link the independent security audit in the readme
2026-10-17 15:25:29 +03:00
Burrowdev 80383e8dec feat: chat filters cover bios
The server refuses a bio that breaks its filter and hides one saved before.
The client filter now runs on your own card too.
2026-10-17 14:35:29 +03:00
Burrowdev 89fe4d2a28 feat: server chat filter for slurs and sexual talk, no secret valentines
- lib/chatfilter.js reads its rules from lib/chat-filter.txt (reloaded
  when it changes) and applies them to typed chat, jam-a-gram messages
  and jammer wall posts. players cannot turn it off. a blocked message
  reaches nobody, its sender sees the game's "inappropriate behavior"
  warning, and blocked chat is kept in the chat log marked not sent.
- rules match words, prefixes and phrases, in order or anywhere, with
  "?" for any word and "!" for exceptions, and see through stand-in
  letters, drawn-out letters and spaced-out spelling. the example rules
  block sexual talk aimed at someone while letting plain swearing
  through; the slur section is left for the owner to fill in.
- secret valentine jam-a-grams are off: the client sends a normal card
  without asking (buildVersion 56), and the server refuses a card asked
  for as a secret valentine.
2026-10-17 12:50:14 +03:00
Burrowdev aa455f52d0 perf: save only changed accounts, cache missing assets, lighter logging and backup
Ping on prod jumped to seconds because node's main thread was busy most
of every second.

- accounts.save(account, ...) names the changed accounts, which are
  written within a second; the rest are looked at a few at a time
  (10 ms a save for those in play, 5 ms for the others). One save under
  prod-like load: 289 ms before, 16 ms after.
- an asset the CDN does not have gets a cacheable 404 and is logged once
- the proxy's own connections no longer count against the web cap, which
  had node reset requests nginx had already let in
- a repeated client error is written once in ten minutes; the panel's
  log buffer trims in batches
- the daily backup uses sqlite's online backup off the main thread
2026-10-17 11:57:40 +03:00
SnipzilandClaude Opus 5.5 3611e566be Client: the staff window takes a warning back; rebuilt
- "Take back warning" beside "Warnings" in the staff window ("xmd" unwarn)
- swf/ajclient.swf rebuilt with the staff window and custom items on top
  of the 17 October client

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 22:59:00 -04:00
SnipzilandClaude Opus 5.5 57abc8746d test: catch up with the 17 October update
- the buddy list and last-seen times ("bl", "xls") come unasked at login
- the den owner is sent the den's items on a switch
- a clothing gift goes by its picture's id; the shop page is the Item giver

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 22:50:47 -04:00
SnipzilandClaude Opus 5.5 ceda20ffc8 Staff roles for the 17 October panel: address search, full rooms
- searching players by address and lifting an address ban need
  address.ban (moderators and above), not only the panel itself
- entering a full room goes by the staff role

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 22:50:47 -04:00
SnipzilandClaude Opus 5.5 f3983fcf67 Warnings: shown at the next visit, taken back, and a silence for many
- a warning given while the player is away is kept and shown with the
  game's popup once they are next in a room (the latest one)
- unwarn: "Take back latest" in the moderator panel, !unwarn in game and
  from the staff window ("xmd")
- config.warningSilence: the Nth warning within some days also silences
  (3rd: an hour, 5th: a day, by default)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 22:43:28 -04:00
SnipzilandClaude Opus 5.5 627e6f9180 A staff window in the game, from the report button of a player's card
For staff, the report button of a player's card opens a window for that
player instead (AJClient.openModerate): warn with a reason, send a
message, silence for an hour or a day or lift it, bring them here, go to
them, disconnect, and their warnings. Only what the role allows is shown.

The window sends "xmd" [command, username, ...], which the server runs as
the staff command typed in chat (lib/commands.js), so the permission check
and the moderators' log are the same; the answer comes as a message box.
Only active staff, and only these commands. Staff are sent their role and
permissions at login ("xsp"); nobody else is sent anything.

test/staff.js covers xsp and xmd, and that a player's xmd does nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 22:43:27 -04:00
SnipzilandClaude Opus 5.5 6563d5de99 Custom items made while the server runs, and a Developer role
Staff with the new items.create permission (admins, and the new Developer
role) make clothing and den items from the game's own art: an existing
item under a new id (50000 on), name, price, members-only flag and choice
of its colours. No restart of the server or of anyone's game:

- lib/customitems.js keeps them (custom_items table) and puts them into
  the server's tables and the packs new games fetch (defpacks.setCustomItem)
- games already playing get the def rows in "xdi"; so does every game at
  login. The client adds them (ItemXtCommManager.addItemDefs,
  DenXtCommManager.addDenItemDefs, both now in swf-src; rebuild with
  tools/build-client.sh)
- they are sold first in the two shops of oddities and found by the item
  finder; an item can be renamed, repriced, recoloured and taken off sale,
  never deleted (players may own it)
- the moderator panel has an Items page; in game, "!item clothing|den ID
  NAME" and "!item list"
- the Developer role holds only staff.list and items.create. The panel's
  pages that show players (players, chat, reports, requests, bans,
  paintings) now need player.view, which helpers and up have

test/items.js covers it end to end, including a restart (withServer can
keep its database for that).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 22:43:27 -04:00
SnipzilandClaude Opus 5.5 2fba9f1612 Staff roles with permissions, warnings, in-game staff commands
Moderators were one flag on the account. Now an account can hold a staff
role (lib/roles.js): helper, moderator or admin, each a list of named
permissions, with a higher role holding everything below it. An account
only marked `moderator` still counts as a moderator.

Every staff action checks the permission it needs, and staff never act
on staff of their own rank or above:

- warnings: kept on the account (who, when, the reason, a note for
  staff), and shown to the player with the game's own warning popup for
  the reason ("fw": inappropriate behavior, bullying, personal
  information, scamming), which this server's strings already word as the
  Burrow Rules.
- moderator panel: each action is checked against the role; new actions
  "warn" (with a reason and note), "summon" (bring a player to the room you
  are in) and "goto"; the player's page shows their warnings; GET
  /mod/api/me returns your role and permissions, and the page hides the
  buttons yours does not allow.
- in the game: !staff, !summon, !goto, !kick, !silence (HOURS, 0, or
  off), !warn PLAYER [reason] [note], !warnings PLAYER and !message, for
  staff whose role allows each, written to the moderators' log like the
  panel's actions, marked "(in game)". To anyone else they are plain chat.
  Usernames with spaces work.
- the login reply carries the player's own staffRole and
  staffPermissions (empty for everyone else), so a client can show staff
  tools only to staff.
- admin panel: a role picker on the account, "role" on POST
  /admin/api/account, and GET /admin/api/roles listing what each allows.
  The old moderator switch still works.

Also: the moderators' message box showed "--Message From Moderator--\n\n"
with the "\n" as written (strings 11134 and 11135 keep it as two
characters); they get real line breaks.

Staff powers need 2FA turned on, as the moderator panel already did. In
the game they come with the game session, which a trusted device opens
without a code; requiring a recent code there is left for later.

test/staff.js covers all of the above end to end.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 22:42:46 -04:00
SnipzilandClaude Opus 5.5 63dc43ebb3 test: bring the test suite up to date, and let it run on Windows
The smoke, features, account and qol tests had fallen behind the server
and failed before reaching their end. Each now checks what the server
does on purpose today:

- harness: the chat filter messages the server sends unasked ("xfl"
  after every login, "xfa" on the first room) are set aside like "zs".
- smoke: a banned account's sign-in is refused with "account_banned", so
  the login-choices check uses a fresh account instead of the banned Carol.
- features: a shop's name comes from its room file, read the first time
  anyone goes in (the first visitor sees a name made from the path). A
  scout goes in first until the file is read, so the check no longer
  depends on what an earlier run left in cache/.
- account: a deleted account's name is held for NAME_HELD_DAYS, so taking
  it again right away is "username_taken".
- qol: the commands page sets what to type in italics.

And on Windows: withServer waits for the server process to exit before
removing its data directory, and retries; the database stays locked until
the process is gone, and the cleanup's EPERM hid the test's own result.

All seven test files pass (smoke, features, account, qol, buddygames,
restored, and staff in the next commit).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 22:42:36 -04:00
SnipzilandClaude Opus 5.5 f96a0e1e6a docs: credit a Strawberry Jam contributor for the audit
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 20:58:07 -04:00
SnipzilandClaude Opus 5.5 5dd56d6333 docs: link the independent security audit in the readme
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 20:55:04 -04:00
Burrowdev edca7bf790 ci: allow the item giver's colour picker link in the client swf 2026-10-17 02:01:34 +03:00
Burrowdev 04f468af2c feat: stats graphs, playtime, ip search against ban evasion, 150-char chat
- stats graphs for the admin and moderator panels (lib/stats.js, public/stats-view.html)
- playtime, private unless shown on the card's bio tab; set on the account page
- search accounts by ip address, only against ban evasion; mods see no addresses and each search is logged
- privacy policy for the above (terms version 2026-10-17)
- the per-second save looks only at accounts in play, with a slow sweep of the rest
- items in several dens at once; chat filter hides slurs and threats by default
- sexual usernames refused; moderators may enter full rooms; guide login allowed
- 150-character chat box (client build 55)
- fixes: gifts, trades, dens, pets in dens, den recycling, special animals' colours,
  jammer walls, settings switches; the buddy list sent at login
- the item giver, the rules screen and the art studio rework
2026-10-17 02:00:57 +03:00
Snipz 8400d2f928 Merge pull request #2 from burrow-dev/ci/security-checks
ci: add security checks and commitlint on every push
2026-10-16 18:53:20 -04:00
SnipzilandClaude Opus 5.5 dc38a49749 ci: add security checks and commitlint on every push
Security workflow, on every push, pull request and weekly:
- invariants: no npm packages, no child_process/vm/eval in the server,
  no web address outside .github/allowed-hosts.json in the server or in
  the SWFs players load, no committed keys, all JavaScript parses
- secrets: TruffleHog over the pushed commits
- codeql: security-extended queries for the JavaScript and the workflows

Commit messages are checked against Conventional Commits; the commits
publish-public.sh makes are exempt. Actions are pinned to commit SHAs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 18:18:27 -04:00
344 changed files with 74792 additions and 1605 deletions

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
{
"server": [
"ajcontent.akamaized.net",
"burrow.moe",
"cdn.jsdelivr.net",
"challenges.cloudflare.com",
"discord.com",
"duckduckgo.com",
"play.burrow.moe",
"player.vimeo.com",
"vision.googleapis.com",
"www.cloudflare.com",
"www.w3.org",
"www.youtube-nocookie.com"
],
"swf": [
"academy.animaljam.com",
"adobe.com",
"aj-color-picker.carrd.co",
"buddy.animaljam.com",
"crypto.hurlant.com",
"dailyexplorer.animaljam.com",
"dev-content.animaljam.com",
"jump.animaljam.com",
"ns.adobe.com",
"purl.org",
"shop.animaljam.com",
"ssl.google-analytics.com",
"wac.6a16.edgecastcdn.net",
"www.adobe.com",
"www.animaljam.com",
"www.google-analytics.com",
"www.osmf.org",
"www.w3.org"
]
}
+15
View File
@@ -0,0 +1,15 @@
// commit messages follow Conventional Commits ("fix(trades): keep offers
// after a rename"), checked by .github/workflows/commitlint.yml.
//
// the commits the private repository's tools/publish-public.sh makes ("Brought
// up to date with the private repository (abc1234)") are left alone: they are
// written by a script and carry no change of their own to describe.
export default {
extends: ["@commitlint/config-conventional"],
ignores: [message => /^Brought up to date with the private repository \([0-9a-f]+\)/.test(message)],
rules: {
// long links and file paths in a body or footer are fine
"body-max-line-length": [0],
"footer-max-line-length": [0],
},
};
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env node
"use strict";
// what the security audit of 2026-10-16 found true of this server, checked on
// every push so that it stays true (or is changed on purpose):
//
// - it has only the one pinned Discord gateway dependency needed by the
// optional staff bot; additions are refused to keep the supply chain small
// - the server code starts no other programs and runs no generated code
// - the server code names no web address outside .github/allowed-hosts.json
// - no private key, certificate key or .env file is committed
// - every JavaScript file parses
//
// a check that fails says what to do. run it from the repository's root:
//
// node .github/scripts/invariants.js
const fs = require("fs");
const path = require("path");
const {execFileSync} = require("child_process");
const tracked = execFileSync("git", ["ls-files", "-z"], {encoding: "utf8"}).split("\0").filter(Boolean);
const problems = [];
const fail = (file, message) => problems.push({file, message});
// The server stayed dependency-free until the optional Discord staff bot. Its
// maintained gateway/components implementation is pinned exactly and captured
// in package-lock.json; no other package is permitted without deliberately
// extending this allowlist and its review surface.
const pkg = JSON.parse(fs.readFileSync("package.json", "utf8"));
const ALLOWED_DEPENDENCIES = {dependencies: {"discord.js": "14.26.4"}};
for (const field of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies", "bundledDependencies"]) {
const actual = pkg[field] || {};
const allowedDependencies = ALLOWED_DEPENDENCIES[field] || {};
if (JSON.stringify(Object.keys(actual).sort().map(name => [name, actual[name]])) !== JSON.stringify(Object.keys(allowedDependencies).sort().map(name => [name, allowedDependencies[name]]))) {
fail("package.json", `${field} differs from its approved dependency allowlist. Keep dependencies empty except for the pinned Discord staff-bot gateway, or deliberately update this check and explain why.`);
}
}
for (const lock of ["yarn.lock", "pnpm-lock.yaml"]) {
if (tracked.includes(lock)) fail(lock, "use the reviewed package-lock.json; alternate package-manager lockfiles are not allowed.");
}
if (fs.existsSync("package-lock.json")) {
try {
const lock = JSON.parse(fs.readFileSync("package-lock.json", "utf8"));
if (lock.lockfileVersion !== 3 || lock.packages?.[""]?.dependencies?.["discord.js"] !== "14.26.4") {
fail("package-lock.json", "must be the npm v3 lockfile for the pinned [email protected] dependency.");
}
}
catch {
fail("package-lock.json", "is not a readable npm lockfile.");
}
}
else {
fail("package-lock.json", "is required to review the pinned Discord bot dependency.");
}
// the server's own code: what the game server runs
const serverCode = tracked.filter(file => /^(server|config)\.js$/.test(file) || /^lib\/.*\.js$/.test(file));
const FORBIDDEN = [
[/require\(\s*["'](?:node:)?child_process["']\s*\)/, "starts other programs (child_process)"],
[/require\(\s*["'](?:node:)?vm["']\s*\)/, "runs generated code (vm)"],
[/(?<![\w.$])eval\s*\(/, "runs generated code (eval)"],
[/\bnew\s+Function\s*\(/, "runs generated code (new Function)"],
[/\bprocess\.binding\s*\(/, "reaches into Node's internals (process.binding)"],
];
const allowed = JSON.parse(fs.readFileSync(".github/allowed-hosts.json", "utf8"));
const HOST = /https?:\/\/([A-Za-z0-9.-]+)/g;
for (const file of serverCode) {
const text = fs.readFileSync(file, "utf8");
for (const [pattern, what] of FORBIDDEN) {
if (pattern.test(text)) {
fail(file, `${what}. The server code never did; if this is meant, change this check in the same pull request and say why.`);
}
}
}
// web addresses in the server code and the pages it serves
for (const file of tracked.filter(name => /^(server\.js|config\.js|lib\/.*\.(js|json)|public\/.*\.(html|js))$/.test(name))) {
for (const [, host] of fs.readFileSync(file, "utf8").matchAll(HOST)) {
const name = host.toLowerCase();
if (!allowed.server.includes(name)) {
fail(file, `names ${name}, which is not in .github/allowed-hosts.json ("server"). Add it there if it is meant.`);
}
}
}
// keys and secrets
for (const file of tracked) {
const base = path.basename(file);
if (/\.(pem|key|p12|pfx)$/i.test(base) || /^\.env(\..*)?$/.test(base) || /^id_(rsa|ed25519|ecdsa)$/.test(base)) {
fail(file, "looks like a key or a secrets file. Remove it from the repository (and from its history), and replace the key.");
}
}
// every JavaScript file parses
for (const file of tracked.filter(name => /\.(c|m)?js$/.test(name) && !name.startsWith("tools/decompiled/"))) {
try {
execFileSync(process.execPath, ["--check", file], {stdio: "pipe"});
}
catch (err) {
fail(file, `does not parse: ${String(err.stderr).trim().split("\n").slice(0, 4).join(" ")}`);
}
}
if (problems.length) {
for (const {file, message} of problems) {
console.log(`::error file=${file}::${file} ${message}`);
}
process.exit(1);
}
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`);
+66
View File
@@ -0,0 +1,66 @@
# every web address a SWF players load could reach out to, checked against
# .github/allowed-hosts.json ("swf"). the game files are what the client runs,
# so a host that shows up in one of them for the first time fails the check
# until somebody looks at it and adds it to the list.
#
# python3 .github/scripts/swf-hosts.py [--list] <file.swf> ...
#
# --list prints the hosts found instead of checking them.
import json
import lzma
import re
import sys
import zlib
from pathlib import Path
HOST = re.compile(rb"https?://([A-Za-z0-9.-]+)")
def body(data):
"""the SWF's bytes after the 8-byte header, uncompressed."""
kind = data[:3]
if kind == b"FWS":
return data[8:]
if kind == b"CWS":
return zlib.decompress(data[8:])
if kind == b"ZWS":
# sig(3) version(1) length(4) lzma length(4) props(5) data: rebuilt as
# an .lzma stream of unknown size
return lzma.LZMADecompressor(lzma.FORMAT_ALONE).decompress(data[12:17] + bytes([0xFF] * 8) + data[17:])
raise ValueError("not a SWF")
def hosts(path):
found = set()
for match in HOST.finditer(body(path.read_bytes())):
host = match.group(1).decode("ascii").lower().strip(".-")
if "." in host:
found.add(host)
return found
def main(args):
listing = "--list" in args
files = [Path(arg) for arg in args if arg != "--list"]
allowed = set(json.loads(Path(".github/allowed-hosts.json").read_text())["swf"]) if not listing else set()
failed = False
for path in files:
try:
found = hosts(path)
except (ValueError, lzma.LZMAError, zlib.error) as err:
print(f"::error file={path}::cannot read {path}: {err}")
failed = True
continue
if listing:
print(f"{path}: {', '.join(sorted(found)) or '(none)'}")
continue
for host in sorted(found - allowed):
print(f"::error file={path}::{path} names {host}, which is not in .github/allowed-hosts.json")
failed = True
if not listing and not failed:
print(f"{len(files)} SWFs checked: every web address in them is on the list")
return 1 if failed else 0
sys.exit(main(sys.argv[1:]))
+49
View File
@@ -0,0 +1,49 @@
name: Commit messages
# every commit pushed, and every commit in a pull request, is checked against
# .github/commitlint.config.mjs (Conventional Commits).
on:
push:
pull_request:
permissions:
contents: read
jobs:
commitlint:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
fetch-depth: 0
persist-credentials: false
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 22
# installed for this run only: the server itself has no npm packages
- name: Install commitlint
run: npm install --no-save --no-package-lock --ignore-scripts @commitlint/[email protected] @commitlint/[email protected]
- name: Check the commits
env:
EVENT: ${{ github.event_name }}
PR_BASE: ${{ github.event.pull_request.base.sha }}
PR_HEAD: ${{ github.event.pull_request.head.sha }}
PUSH_BEFORE: ${{ github.event.before }}
PUSH_AFTER: ${{ github.sha }}
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
run: |
if [ "$EVENT" = pull_request ]; then
from=$PR_BASE to=$PR_HEAD
elif [ -n "$PUSH_BEFORE" ] && [ "$PUSH_BEFORE" != 0000000000000000000000000000000000000000 ] && git cat-file -e "$PUSH_BEFORE^{commit}" 2>/dev/null; then
from=$PUSH_BEFORE to=$PUSH_AFTER
else
# a new branch (or a force push): what it has that the default branch has not,
# or else the last commit alone
from=$(git merge-base "origin/$DEFAULT_BRANCH" "$PUSH_AFTER" 2>/dev/null || true)
[ -n "$from" ] && [ "$from" != "$PUSH_AFTER" ] || from=$PUSH_AFTER~1
to=$PUSH_AFTER
fi
git cat-file -e "$from^{commit}" 2>/dev/null || { npx --no-install commitlint --config .github/commitlint.config.mjs --last --verbose; exit; }
npx --no-install commitlint --config .github/commitlint.config.mjs --from "$from" --to "$to" --verbose
+79
View File
@@ -0,0 +1,79 @@
name: Security
# on every push and pull request, and once a week for newly published CodeQL
# queries:
# - invariants: what the 2026-10-16 security audit found true stays true
# (no npm packages, no program starts or eval in the server, no unlisted
# web addresses in the server or in the SWFs players load, no keys, all
# JavaScript parses). see .github/scripts/.
# - secrets: TruffleHog over the commits pushed
# - codeql: GitHub's code scanning of the JavaScript and of these workflows
on:
push:
pull_request:
schedule:
- cron: "17 4 * * 1"
workflow_dispatch:
permissions:
contents: read
jobs:
invariants:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 22
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
with:
python-version: "3.12"
- name: Server code
run: node .github/scripts/invariants.js
- name: Game files players load
run: git ls-files -z 'swf/*.swf' | xargs -0 python3 -I .github/scripts/swf-hosts.py
secrets:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
fetch-depth: 0
persist-credentials: false
- uses: trufflesecurity/trufflehog@4dd8831c5f12599465d4d45c3c447b4018a34c85 # v3.97.9
with:
version: 3.97.9
extra_args: --results=verified,unknown
codeql:
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: read
security-events: write
actions: read
strategy:
fail-fast: false
matrix:
language: [javascript-typescript, actions]
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- uses: github/codeql-action/init@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
with:
languages: ${{ matrix.language }}
queries: security-extended
config: |
paths-ignore:
- tools/decompiled
- swf-src
- uses: github/codeql-action/analyze@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
with:
category: /language:${{ matrix.language }}
+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.
+24
View File
@@ -1,7 +1,31 @@
# 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
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.
**[Read the audit](https://snipzil.github.io/burrow-server/)**
Every push to this repository is checked automatically (`.github/workflows/security.yml`) for new outside web addresses in the server or game files, code that starts programs, committed keys and leaked credentials.
# Disclaimer # Disclaimer
Burrow is an unofficial fan project. It is not affiliated with, endorsed by or connected to WildWorks, Inc. or Animal Jam. Animal Jam and Animal Jam Classic are trademarks of WildWorks, Inc. Burrow is an unofficial fan project. It is not affiliated with, endorsed by or connected to WildWorks, Inc. or Animal Jam. Animal Jam and Animal Jam Classic are trademarks of WildWorks, Inc.
**Takedown procedure: WildWorks, Inc. or its authorized representatives may request the removal of content, or of Burrow as a whole, by writing to [email protected]. Upon verification of authority, the request will be carried out promptly.** **Takedown procedure: WildWorks, Inc. or its authorized representatives may request the removal of content, or of Burrow as a whole, by writing to [email protected]. Upon verification of authority, the request will be carried out promptly.**
# Credits
Emoji in chat are drawn with [Twemoji](https://github.com/jdecked/twemoji), © Twitter, Inc. and other contributors, under [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/).
+110 -6
View File
@@ -3,6 +3,7 @@
const path = require("path"); const path = require("path");
const env = process.env; const env = process.env;
const googleVisionApiKey = env.AJ_GOOGLE_VISION_API_KEY;
const LOOPBACK_NAMES = ["127.0.0.1", "::1", "localhost"]; const LOOPBACK_NAMES = ["127.0.0.1", "::1", "localhost"];
const bindAddress = env.AJ_BIND || "127.0.0.1"; const bindAddress = env.AJ_BIND || "127.0.0.1";
const httpPort = Number(env.AJ_HTTP_PORT || 8080); const httpPort = Number(env.AJ_HTTP_PORT || 8080);
@@ -84,6 +85,13 @@ module.exports = {
// cookies are only sent back over an encrypted connection when players // cookies are only sent back over an encrypted connection when players
// have one, whoever does the encrypting. // have one, whoever does the encrypting.
secureCookies: baseUrl.startsWith("https:"), secureCookies: baseUrl.startsWith("https:"),
// Google Cloud Vision SafeSearch, used for player-uploaded custom item art
// and masterpieces. Off when no key is configured (useful for local work).
// When on, a Google outage rejects uploads rather than letting unscanned
// images through.
googleVision: googleVisionApiKey ? {
endpoint: `https://vision.googleapis.com/v1/images:annotate?key=${encodeURIComponent(googleVisionApiKey)}`,
} : null,
// the admin panel answers this machine alone on a public server (reach it // the admin panel answers this machine alone on a public server (reach it
// through an SSH tunnel), plus the addresses listed in AJ_ADMIN_ALLOW, // through an SSH tunnel), plus the addresses listed in AJ_ADMIN_ALLOW,
// separated by commas. on a local server it answers whoever can reach it. // separated by commas. on a local server it answers whoever can reach it.
@@ -93,11 +101,57 @@ module.exports = {
// tried or an account is made, with both set. off without them. // tried or an account is made, with both set. off without them.
turnstile: env.AJ_TURNSTILE_SITE_KEY && env.AJ_TURNSTILE_SECRET turnstile: env.AJ_TURNSTILE_SITE_KEY && env.AJ_TURNSTILE_SECRET
? {siteKey: env.AJ_TURNSTILE_SITE_KEY, secret: env.AJ_TURNSTILE_SECRET} : null, ? {siteKey: env.AJ_TURNSTILE_SITE_KEY, secret: env.AJ_TURNSTILE_SECRET} : null,
// A stalled CAPTCHA provider must not consume all of the VPS's outbound
// sockets. This only limits simultaneous verification requests; normal
// players use one, and a rejected request can safely be retried.
maxConcurrentCaptchaChecks: Math.max(1, Math.min(100, Number(env.AJ_CAPTCHA_MAX_CONCURRENT) || 24)),
// Account-recovery mail is delivered to this HTTPS webhook. It receives
// {to, subject, text}; point it at the transactional-mail provider or
// small mail relay you use. Recovery is deliberately unavailable until
// both values are set, rather than ever exposing a reset link in a page.
recoveryMail: env.AJ_RECOVERY_MAIL_URL && env.AJ_RECOVERY_MAIL_TOKEN
? {url: env.AJ_RECOVERY_MAIL_URL, token: env.AJ_RECOVERY_MAIL_TOKEN} : null,
// asset mirror: anything not served locally is fetched once from here and // asset mirror: anything not served locally is fetched once from here and
// cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only. // cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only.
upstreamContent: env.AJ_UPSTREAM || "https://ajcontent.akamaized.net/", upstreamContent: env.AJ_UPSTREAM || "https://ajcontent.akamaized.net/",
// emoji pictures for chat (lib/emoji.js): Twemoji's, at one version
emojiUpstream: env.AJ_EMOJI_UPSTREAM || "https://cdn.jsdelivr.net/gh/jdecked/[email protected]/assets/72x72/",
offline: env.AJ_OFFLINE === "1", offline: env.AJ_OFFLINE === "1",
// the client's device ids (lib/devices.js): a game whose launcher sent none
// (a client from before 1.3.0, the official launcher, or one that left
// them out) is turned away at its login, its popup saying to update.
// AJ_REQUIRE_DEVICE=0 lets them in (an account seen on banned hardware
// before is still kept out).
requireDevice: env.AJ_REQUIRE_DEVICE !== "0",
// Discord (lib/discord.js): an application's id and secret for linking a
// player's Discord account on the account page and for allowed accounts to
// sign in to /dashboard/admin (OAuth2 redirects:
// <siteUrl>account/discord/callback,
// <siteUrl>dashboard/admin/discord/callback, and
// <siteUrl>dashboard/staff/discord/callback), and a bot in Burrow's Discord
// server for the booster badge. linking is off without the first two, the
// booster badge left alone without the last two.
discord: {
clientId: env.AJ_DISCORD_CLIENT_ID || "",
clientSecret: env.AJ_DISCORD_CLIENT_SECRET || "",
botToken: env.AJ_DISCORD_BOT_TOKEN || "",
guildId: env.AJ_DISCORD_GUILD_ID || "",
// Optional Components V2 notification channels. Leave any empty to
// disable that stream: reports, public status, game joins/leaves, the
// moderation audit trail, and Discord bot command/audit events.
reportsChannelId: env.AJ_DISCORD_REPORTS_CHANNEL_ID || "",
statusChannelId: env.AJ_DISCORD_STATUS_CHANNEL_ID || "",
gameLogsChannelId: env.AJ_DISCORD_GAME_LOGS_CHANNEL_ID || "",
moderationLogsChannelId: env.AJ_DISCORD_MOD_LOGS_CHANNEL_ID || "",
botLogsChannelId: env.AJ_DISCORD_BOT_LOGS_CHANNEL_ID || "",
// A signed GitHub push webhook at /discord/github can turn commits into
// a Components V2 update card. All three values are needed to enable it.
githubRepository: env.AJ_GITHUB_REPOSITORY || "", // owner/repository
githubWebhookSecret: env.AJ_GITHUB_WEBHOOK_SECRET || "",
updatesChannelId: env.AJ_DISCORD_UPDATES_CHANNEL_ID || "",
},
deployVersion: env.AJ_DEPLOY_VERSION || "1830", deployVersion: env.AJ_DEPLOY_VERSION || "1830",
// older builds the CDN still serves, asked in turn for a room file the // older builds the CDN still serves, asked in turn for a room file the
// current build has dropped. 1828 is the last with the Summer Carnival. // current build has dropped. 1828 is the last with the Summer Carnival.
@@ -114,7 +168,13 @@ module.exports = {
// game no longer open to SWFs from other addresses. // game no longer open to SWFs from other addresses.
// 40: the chat filter's window laid out again. // 40: the chat filter's window laid out again.
// 41: the game's text says "Burrow" where it said Animal Jam. // 41: the game's text says "Burrow" where it said Animal Jam.
buildVersion: env.AJ_BUILD_VERSION || "41", // 48: the item giver (the item finder renamed) with previews and hex colours;
// 49 and 50: its link to a colour picker.
// 61: the Owner, Moderator, 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",
@@ -147,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-13", 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",
@@ -244,8 +304,24 @@ module.exports = {
{room: "appondale.room_museum", shown: "appondale.room_museum_ant", months: [2, 4, 6, 8, 10, 12]}, {room: "appondale.room_museum", shown: "appondale.room_museum_ant", months: [2, 4, 6, 8, 10, 12]},
], ],
startupRoom: "jamaa_township.room_main", startupRoom: "jamaa_township.room_main",
shards: [{id: 1, name: "Aldan"}], // where a player who does not start in their den arrives: one of these at
maxUsersPerRoom: 80, // random, of those that are not full (lib/world.js). AJ_SPAWN_ROOMS: a
// list of its own, comma-separated (the tests' is the township alone).
spawnRooms: env.AJ_SPAWN_ROOMS ? env.AJ_SPAWN_ROOMS.split(",").map(room => room.trim()).filter(Boolean)
: ["jamaa_township.room_main", "sarepia.room_main", "crystal_sands.room_main", "coral_canyons.room_main",
"mountains_of_shivveer.room_main", "appondale.room_main", "lost_temple_of_zios.room_main", "aussie.room_main", "balloosh.room_main"],
// the worlds, each its own copy of every land (rooms are "path#world";
// dens and parties are everyone's). a player arrives in one at random and
// can switch in the settings menu (gui.ServerSelector). the game names
// world N after the Nth name of its own list (551 Aldan, 552 Congo...,
// generic list 16), so the names here are only for the panels and logs.
// AJ_WORLDS: how many (the tests' is one).
// the admin panel can change how many while the server runs (lib/world.js
// setWorldCount), which then outlasts a restart.
worldNames: ["Aldan", "Congo", "Draa", "Grande", "Kama", "Nile", "Pecos", "Ramu", "Tigris", "Zambezi"],
shards: ["Aldan", "Congo", "Draa", "Grande", "Kama", "Nile", "Pecos", "Ramu", "Tigris", "Zambezi"]
.slice(0, Math.min(10, Math.max(1, Number(env.AJ_WORLDS) || 2))).map((name, i) => ({id: i + 1, name})),
maxUsersPerRoom: 40,
// everything in every shop for nothing (AJ_FREE_SHOPS=1). off unless // everything in every shop for nothing (AJ_FREE_SHOPS=1). off unless
// asked for: what the game's shops make of a price of 0 has not been seen. // asked for: what the game's shops make of a price of 0 has not been seen.
freeShops: env.AJ_FREE_SHOPS === "1", freeShops: env.AJ_FREE_SHOPS === "1",
@@ -273,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
@@ -280,14 +364,34 @@ module.exports = {
tlsHandshakeTimeoutMs: 10000, tlsHandshakeTimeoutMs: 10000,
maxMessagesPerTenSeconds: 400, // per game socket; walking sends a few a second maxMessagesPerTenSeconds: 400, // per game socket; walking sends a few a second
loginTimeoutMs: 30000, // a game socket must log in within this loginTimeoutMs: 30000, // a game socket must log in within this
idleTimeoutMs: 15 * 60000, // the client sends a keep-alive far more often // a client sends nothing while its player is away, and signs itself out
// after 75 minutes of that (com.sbi.client.KeepAlive): the socket waits longer.
idleTimeoutMs: 80 * 60000,
tokenLifetimeDays: 30, // login tokens kept by the launcher's "remember me" tokenLifetimeDays: 30, // login tokens kept by the launcher's "remember me"
maxChatLength: 300, // a line as sent: the client's chat box takes 200 (gui.ChatHistory), and
// each emoji goes as a tag of 8 or more ("\{1f600}"). lib/chatspam.js
// cuts down what is long for no good reason.
maxChatLength: 600,
// how old an account must be before it may give its items pictures
// (lib/playeritems.js), so a picture turned away is not simply sent again
// from a new account. not for this machine's own requests (AJ_ITEM_ART_MIN_HOURS).
itemArtMinAccountHours: Number(env.AJ_ITEM_ART_MIN_HOURS || 24),
// warnings (lib/moderation.js warn): the Nth one within `days` also
// silences the player for that many minutes, [[N, minutes], ...]. a
// longer silence already on them stays. steps [] turns it off.
warningSilence: {days: 30, steps: [[3, 60], [5, 24 * 60]]},
// days typed chat and whispers are kept for the moderator panel's chat // days typed chat and whispers are kept for the moderator panel's chat
// history (lib/chatlog.js); 0 keeps none. // history (lib/chatlog.js); 0 keeps none.
chatLogDays: env.AJ_CHAT_LOG_DAYS === undefined ? 30 : Math.max(0, Number(env.AJ_CHAT_LOG_DAYS) || 0), chatLogDays: env.AJ_CHAT_LOG_DAYS === undefined ? 30 : Math.max(0, Number(env.AJ_CHAT_LOG_DAYS) || 0),
chatLinesPerWindow: 5, // typed chat lines one player may send ... chatLinesPerWindow: 5, // typed chat lines one player may send ...
chatWindowMs: 3000, // ... in this long chatWindowMs: 3000, // ... in this long
roomActionsPerWindow: 6, // emotes, actions and the like one player may send a room ...
roomActionWindowMs: 3000, // ... in this long (the rest reach nobody)
// eco den items (lib/eco.js): credits an hour for each point of eco power
// placed in a den, and what an account is given the first time it looks
// (an Eco Solar Panel's price)
ecoCreditsPerPointHour: 1,
ecoStartCredits: 1500,
maxBytesPerTenSeconds: 512 * 1024, // per game socket; saving a full den is about 40 KB maxBytesPerTenSeconds: 512 * 1024, // per game socket; saving a full den is about 40 KB
// custom colours (lib/colours.js). every one ever made is sent to every // custom colours (lib/colours.js). every one ever made is sent to every
// player at every login and is never taken out again, so there is an end // player at every login and is never taken out again, so there is an end
+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"
+368 -77
View File
@@ -1,9 +1,10 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto"); const crypto = require("crypto");
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const {DatabaseSync} = require("node:sqlite"); const {DatabaseSync, backup: copyDatabase} = require("node:sqlite");
const config = require("../config.js"); const config = require("../config.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const names = require("./names.js"); const names = require("./names.js");
@@ -13,9 +14,9 @@ const names = require("./names.js");
// JSON document per account in `state`. // JSON document per account in `state`.
// //
// every account is held in memory while the server runs. game code changes // every account is held in memory while the server runs. game code changes
// those objects directly and then calls save(), which has every account // those objects directly and then calls save(account, ...), which has the
// whose state changed written back, a moment later: however many times it // accounts named written back a moment later, and the others looked at a
// is called in that moment, the accounts are gone through once (flush). // few at a time (flush, below).
const SCHEMA = ` const SCHEMA = `
CREATE TABLE IF NOT EXISTS accounts ( CREATE TABLE IF NOT EXISTS accounts (
@@ -45,7 +46,7 @@ const SCHEMA = `
// fields stored in their own columns rather than in `state`. // fields stored in their own columns rather than in `state`.
const COLUMN_FIELDS = ["id", "username", "salt", "hash", "createdAt"]; const COLUMN_FIELDS = ["id", "username", "salt", "hash", "createdAt"];
// how the game treats the account this session; set again at every login. // how the game treats the account this session; set again at every login.
const SESSION_FIELDS = ["accountType", "isGuide", "isModerator", "membershipDays", "startInDen", "startRoom"]; const SESSION_FIELDS = ["accountType", "isGuide", "guideRefused", "isModerator", "membershipDays", "startInDen", "startRoom"];
const DEFAULT_MEMBERSHIP_DAYS = 9999; const DEFAULT_MEMBERSHIP_DAYS = 9999;
const MAX_ACCOUNT_TYPE = 5; const MAX_ACCOUNT_TYPE = 5;
const MEMBERSHIP_TYPES = [0, 2]; // non-member, member const MEMBERSHIP_TYPES = [0, 2]; // non-member, member
@@ -56,7 +57,13 @@ const MIN_LETTERS = 3; // the client's own rule (SbiConstants.USERNAME_REGEX)
const MIN_PASSWORD_LENGTH = 10; const MIN_PASSWORD_LENGTH = 10;
const MAX_DEN_SLOTS = 200; // DenSwitch.nextFreeSlotIdx const MAX_DEN_SLOTS = 200; // DenSwitch.nextFreeSlotIdx
const DEN_OPEN = 2; // den privacy: 0 locked, 1 buddies only, 2 everyone const DEN_OPEN = 2; // den privacy: 0 locked, 1 buddies only, 2 everyone
const USER_VAR_SETTINGS = 363; // the settings menu's switches, a bit each (gui.MySettings)
// the chat filter an account starts with: level 1 slurs and threats, mode 1
// the whole message left out (see account.filter below).
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
@@ -72,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;
@@ -109,7 +119,7 @@ const newAvatar = (ids, name, type, customAvId) => {
customAvId: custom ? Number(customAvId) : -1, customAvId: custom ? Number(customAvId) : -1,
colors: [def.colorLayer1, Number(custom && custom.overrideColorLayer2) || def.colorLayer2, def.colorLayer3].map(Number), colors: [def.colorLayer1, Number(custom && custom.overrideColorLayer2) || def.colorLayer2, def.colorLayer3].map(Number),
eyes: Number(def.baseEyesId) || 0, eyes: Number(def.baseEyesId) || 0,
pattern: Number(custom ? custom.patternRefId : def.basePatternId) || 0, pattern: Number(custom ? defpacks.customPattern(customAvId) : def.basePatternId) || 0,
petInvId: 0, petInvId: 0,
}; };
}; };
@@ -153,6 +163,10 @@ const normalize = account => {
account.outfitUndo.avInvId = avatar.avInvId; account.outfitUndo.avInvId = avatar.avInvId;
} }
} }
// custom animals made while their pattern list was a 0 (lib/defpacks.js)
for (const avatar of account.avatars.filter(candidate => candidate.customAvId !== -1 && !candidate.pattern)) {
avatar.pattern = defpacks.customPattern(avatar.customAvId);
}
account.pets = account.pets || []; // {inv, lBits, uBits, eBits, name, createdAt} account.pets = account.pets || []; // {inv, lBits, uBits, eBits, name, createdAt}
account.dens = account.dens || [{inv: 0, def: config.denDefId}]; // den rooms owned account.dens = account.dens || [{inv: 0, def: config.denDefId}]; // den rooms owned
account.activeDen = account.activeDen || 0; // inv of the den in use account.activeDen = account.activeDen || 0; // inv of the den in use
@@ -174,19 +188,42 @@ const normalize = account => {
account.activeDen = moved.has(account.activeDen) ? moved.get(account.activeDen) : account.activeDen; account.activeDen = moved.has(account.activeDen) ? moved.get(account.activeDen) : account.activeDen;
for (const item of account.denItems || []) { for (const item of account.denItems || []) {
item.den = moved.has(item.den) ? moved.get(item.den) : item.den; item.den = moved.has(item.den) ? moved.get(item.den) : item.den;
if (item.spots) {
item.spots = Object.fromEntries(Object.entries(item.spots).map(([den, spot]) => [moved.has(Number(den)) ? moved.get(Number(den)) : den, spot]));
}
} }
} }
account.denPrivacy = account.denPrivacy === undefined ? DEN_OPEN : account.denPrivacy; account.denPrivacy = account.denPrivacy === undefined ? DEN_OPEN : account.denPrivacy;
account.denItems = account.denItems || []; // {inv, def, version, placed, den, x, y, flip, mannequin?, image?}: lib/dens.js // {inv, def, version, spots, mannequin?, image?}: lib/dens.js. spots: where
// it stands, {den inventory id: {cat, x, y, flip}}, as many dens as it is in.
account.denItems = account.denItems || [];
for (const item of account.denItems) { for (const item of account.denItems) {
item.den = item.den === undefined ? account.activeDen : item.den; // which den it is placed in // from when an item stood in one den at most: {placed, den, x, y, flip, cat}.
if (!item.spots) {
const den = item.den === undefined ? account.activeDen : item.den;
item.spots = item.placed ? {[den]: {cat: item.cat || 1, x: item.x || 0, y: item.y || 0, flip: item.flip || 0}} : {};
}
for (const old of ["placed", "den", "x", "y", "flip", "cat"]) {
delete item[old];
}
} }
account.userVars = account.userVars || {}; account.userVars = account.userVars || {};
// the settings menu's switches (user var 363) were once stored as the
// number of the last switch touched rather than as bits: such a value
// cannot be told from a real one, so every account starts again from the
// game's defaults, once.
if (!account.settingsBitsFixed) {
delete account.userVars[USER_VAR_SETTINGS];
account.settingsBitsFixed = true;
}
account.theme = account.theme || ""; // seasonal look of the lands, see themes in config.js account.theme = account.theme || ""; // seasonal look of the lands, see themes in config.js
account.lastSeen = account.lastSeen || 0; // when they last left the game, in seconds; 0 = never recorded account.lastSeen = account.lastSeen || 0; // when they last left the game, in seconds; 0 = never recorded
// what the player set on the account page (lib/manage.js). // 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
@@ -214,21 +251,45 @@ 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
// their card shows it to others: theirs to choose on the account page.
account.playtime = Number.isFinite(account.playtime) && account.playtime > 0 ? Math.floor(account.playtime) : 0;
account.playtimePublic = account.playtimePublic === true;
// the chat filter, which the player's own game applies (AJClient in the // the chat filter, which the player's own game applies (AJClient in the
// patched SWF; "xfl" in lib/world.js): {level: 1 slurs and threats, 2 // patched SWF; "xfl" in lib/world.js): {level: 1 slurs and threats, 2
// swearing too, 0 off; mode: 0 stars over the words, 1 the message left // swearing too, 0 off; mode: 0 stars over the words, 1 the message left
// out; words: their own, commas between; chosen: have they been asked}. // out; words: their own, commas between; chosen: have they been asked}.
// an account that has not chosen has no filter: that is the start. // an account starts with slurs and threats hidden, and may turn it off.
account.filter = account.filter && typeof account.filter === "object" && account.filter.chosen ? account.filter : {level: 0, mode: 0, words: "", chosen: false}; account.filter = account.filter && typeof account.filter === "object" && account.filter.chosen ? account.filter : {...DEFAULT_FILTER, chosen: false};
// that default came after accounts that had none, or had turned it off:
// they get it too, once. a stricter level, and the way it is shown when
// they had one, stay as they were.
if (!account.filterDefaultApplied) {
if (!(account.filter.level >= DEFAULT_FILTER.level)) {
Object.assign(account.filter, {level: DEFAULT_FILTER.level, mode: DEFAULT_FILTER.mode});
}
account.filterDefaultApplied = true;
}
// two-step sign-in: lib/totp.js. // two-step sign-in: lib/totp.js.
account.totp = account.totp || null; account.totp = account.totp || null;
account.totpSetup = account.totpSetup || null; account.totpSetup = account.totpSetup || null;
account.devices = Array.isArray(account.devices) ? account.devices : []; account.devices = Array.isArray(account.devices) ? account.devices : [];
// the computers it signed in from, keyed (lib/devices.js): [{kind, id, first, last}].
account.hwids = Array.isArray(account.hwids) ? account.hwids : [];
account.nextInv = account.nextInv || 2; account.nextInv = account.nextInv || 2;
account.numLogins = account.numLogins || 0; account.numLogins = account.numLogins || 0;
account.uuid = account.uuid || crypto.randomUUID(); account.uuid = account.uuid || crypto.randomUUID();
@@ -245,11 +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 is the player's own choice on any server, the rest only // member or not is the player's own choice on any server; the rest only
// with config.loginChoices: another account type shows to everyone. // with config.loginChoices: another account type shows to everyone.
const type = choices && typeof choices === "object" && MEMBERSHIP_TYPES.includes(choices.accountType) ? choices.accountType : asked.accountType; const own = choices && typeof choices === "object" ? choices : {};
const type = MEMBERSHIP_TYPES.includes(own.accountType) ? own.accountType : asked.accountType;
account.accountType = whole(type, MAX_ACCOUNT_TYPE) ? type : config.defaultAccountType; account.accountType = whole(type, MAX_ACCOUNT_TYPE) ? type : config.defaultAccountType;
account.isGuide = asked.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
@@ -275,8 +342,9 @@ 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);
return account; return account;
}; };
@@ -302,15 +370,18 @@ const importLegacyFile = () => {
} }
db.exec("COMMIT"); db.exec("COMMIT");
fs.renameSync(file, `${file}.imported`); fs.renameSync(file, `${file}.imported`);
console.log(`[accounts] imported ${byKey.size} accounts from accounts.json`); console.log(`[accounts] imported ${logText(byKey.size)} accounts from accounts.json`);
}; };
const load = () => { const load = () => {
fs.mkdirSync(config.dataDir, {recursive: true}); fs.mkdirSync(config.dataDir, {recursive: true});
db = new DatabaseSync(path.join(config.dataDir, "game.sqlite")); db = new DatabaseSync(path.join(config.dataDir, "game.sqlite"));
// busy_timeout: something else writing to the file for a moment (a tool, // busy_timeout: something else writing to the file for a moment (a tool,
// a copy being made) is waited for, not an error. // a copy being made) is waited for, not an error. synchronous NORMAL: with
db.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;"); // WAL the disk is synced at checkpoints, not after every commit, which
// held the game up on each chat line and save; a crash of the server
// loses nothing, a power cut at most the last moment's writes.
db.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;");
db.exec(SCHEMA); db.exec(SCHEMA);
for (const row of db.prepare("SELECT * FROM accounts").all()) { for (const row of db.prepare("SELECT * FROM accounts").all()) {
const account = normalize({ const account = normalize({
@@ -321,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();
@@ -345,7 +416,7 @@ const load = () => {
// runs the server is told which, to rename by hand if they see fit. // runs the server is told which, to rename by hand if they see fit.
const unusual = [...byId.values()].filter(account => names.refused(account.username)).map(account => account.username); const unusual = [...byId.values()].filter(account => names.refused(account.username)).map(account => account.username);
if (unusual.length) { if (unusual.length) {
console.log(`[accounts] usernames that could not be chosen today: ${unusual.slice(0, 50).join(", ")}${unusual.length > 50 ? ", ..." : ""}`); console.log(`[accounts] usernames that could not be chosen today: ${logText(unusual.slice(0, 50).join(", "))}${logText(unusual.length > 50 ? ", ..." : "")}`);
} }
// once: the Early Member badge for the accounts that were there before // once: the Early Member badge for the accounts that were there before
// it existed, the oldest hundred of them. // it existed, the oldest hundred of them.
@@ -368,23 +439,143 @@ const load = () => {
for (const row of db.prepare("SELECT token, account_id, created_at FROM tokens").all()) { for (const row of db.prepare("SELECT token, account_id, created_at FROM tokens").all()) {
tokens.set(row.token, {id: row.account_id, createdAt: row.created_at}); tokens.set(row.token, {id: row.account_id, createdAt: row.created_at});
} }
console.log(`[accounts] ${byKey.size} accounts in ${path.join(config.dataDir, "game.sqlite")}`); console.log(`[accounts] ${logText(byKey.size)} accounts in ${logText(path.join(config.dataDir, "game.sqlite"))}`);
};
// Which accounts a save looks at. turning an account into JSON to see
// whether it changed costs (up to a millisecond for a big one), and doing it
// a second after nearly every message for every account in play (online
// ones, and the buddies, dens and cards they had looked up lately) held the
// whole server up for most of every second once there were enough players.
// so game code says which accounts it changed, save(account, ...), and those
// are written within SAVE_DELAY_MS. behind them, for whatever changed an
// account without saying so, the accounts in play are looked at a few at a
// time (PLAY_BUDGET_MS a save), round and round: online ones (hold, from
// lib/world.js) and ones looked up lately (by name, id, token, password: how
// the admin panel, buddies and the like get at an offline account), for
// WARM_MS. behind those every other account is looked at the same way
// (SWEEP_BUDGET_MS), for what reached an account some other way
// (accounts.all()). a stop of the server, and every flush() called by name,
// looks at all of them.
const WARM_MS = 10 * 60 * 1000;
const PLAY_BUDGET_MS = 10;
const SWEEP_BUDGET_MS = 5;
const held = new Set(); // accounts online
const warm = new Map(); // account -> when last looked up
const dirty = new Set(); // accounts said to have changed since the last save
let playOrder = [];
let playAt = 0;
let playLeft = 0; // accounts in play still to be looked at since the last save()
let sweepOrder = [];
let sweepAt = 0;
let sweepLeft = 0; // accounts the sweep still has to look at since the last save()
const touch = account => {
if (account) {
warm.set(account, Date.now());
}
return account;
};
const hold = account => {
held.add(account);
touch(account);
};
const release = account => {
held.delete(account);
touch(account);
};
const changedState = (account, changed) => {
const json = stateJson(account);
if (savedState.get(account.id) !== stateDigest(json)) {
changed.push([account.id, json]);
return true;
}
return false;
};
const elapsedMs = started => Number(process.hrtime.bigint() - started) / 1e6;
// the next accounts in play, while there is time: the ones online and the
// ones looked up lately. one looked up longer ago than WARM_MS is looked at
// once more, then left to the sweep.
const lookAtPlay = (changed, looked) => {
const started = process.hrtime.bigint();
while (playLeft > 0 && elapsedMs(started) < PLAY_BUDGET_MS) {
if (playAt >= playOrder.length) {
const now = Date.now();
playOrder = [...new Set([...held, ...warm.keys()])];
playAt = 0;
for (const [account, at] of warm) {
if (now - at > WARM_MS && !held.has(account)) {
warm.delete(account);
}
}
if (playOrder.length === 0) {
playLeft = 0;
break;
}
}
const account = playOrder[playAt++];
playLeft--;
if (!looked.has(account) && byId.get(account.id) === account) {
looked.add(account);
changedState(account, changed);
}
}
};
const lookAtRest = (changed, looked) => {
const started = process.hrtime.bigint();
while (sweepLeft > 0 && elapsedMs(started) < SWEEP_BUDGET_MS) {
if (sweepAt >= sweepOrder.length) {
sweepOrder = [...byId.values()];
sweepAt = 0;
if (sweepOrder.length === 0) {
sweepLeft = 0;
break;
}
}
const account = sweepOrder[sweepAt++];
sweepLeft--;
if (!looked.has(account) && byId.get(account.id) === account) {
looked.add(account);
changedState(account, changed);
}
}
}; };
// writes every account whose state changed since it was last written, in // writes every account whose state changed since it was last written, in
// one transaction. // one transaction; with {some: true}, of the accounts said to have changed
const flush = () => { // and the next few of the others (above).
const flush = ({some = false} = {}) => {
clearTimeout(saveTimer); clearTimeout(saveTimer);
saveTimer = null; saveTimer = null;
if (!db) { if (!db) {
return; return;
} }
const changed = []; const changed = [];
for (const account of byId.values()) { const named = [...dirty];
const json = stateJson(account); dirty.clear();
if (savedState.get(account.id) !== json) { if (some) {
changed.push([account.id, json]); const looked = new Set();
for (const account of named) {
if (byId.get(account.id) === account) {
looked.add(account);
changedState(account, changed);
}
} }
lookAtPlay(changed, looked);
lookAtRest(changed, looked);
}
else {
for (const account of byId.values()) {
changedState(account, changed);
}
playLeft = 0;
sweepLeft = 0;
}
if (playLeft > 0 || sweepLeft > 0) {
later(CONTINUE_MS); // the looking goes on in a moment
} }
if (changed.length === 0) { if (changed.length === 0) {
return; return;
@@ -399,64 +590,86 @@ const flush = () => {
} }
catch (err) { catch (err) {
db.exec("ROLLBACK"); db.exec("ROLLBACK");
named.forEach(account => dirty.add(account));
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));
} }
}; };
// "Something changed": the accounts are written within SAVE_DELAY_MS. going // "Something changed": the accounts named are written within SAVE_DELAY_MS,
// through every account costs more the more there are, and game code calls // and the looking-through above starts again. game code calls this after
// this after nearly every message (and some of it a hundred times in a // nearly every message (and some of it a hundred times in a row), so it is
// row), so the going-through is done once for all the calls of a moment. // done once for all the calls of a moment. what a crash can lose is that
// what a crash can lose is that moment; a stop of the server writes first // moment, for an account named, and the time a round of the looking takes,
// for one changed without saying so; a stop of the server writes first
// (server.js). // (server.js).
const SAVE_DELAY_MS = 1000; const SAVE_DELAY_MS = 1000;
const CONTINUE_MS = 250;
let saveTimer = null; let saveTimer = null;
const save = () => { const later = delay => {
if (saveTimer === null) { if (saveTimer === null) {
saveTimer = setTimeout(() => { saveTimer = setTimeout(() => {
try { try {
flush(); flush({some: true});
} }
catch (err) { catch (err) {
console.error(`[accounts] could not save: ${err.message}`); console.error(`[accounts] could not save: ${err.message}`);
save(); // tried again in a moment: nothing is lost while the server runs save(); // tried again in a moment: nothing is lost while the server runs
} }
}, SAVE_DELAY_MS); }, delay);
} }
}; };
const save = (...changedAccounts) => {
for (const account of changedAccounts) {
if (account) {
dirty.add(account);
}
}
playLeft = held.size + warm.size;
sweepLeft = byId.size;
later(SAVE_DELAY_MS);
};
// A copy of the whole database, made once a day into data/backups/ and the // A copy of the whole database, made once a day into data/backups/ and the
// latest BACKUPS_KEPT kept. it is a whole file of its own (VACUUM INTO), to // latest BACKUPS_KEPT kept. it is a whole file of its own, to be copied
// be copied somewhere else by whoever runs the server: a copy on the same // somewhere else by whoever runs the server: a copy on the same disk is no
// disk is no help when the disk goes. // help when the disk goes. it is copied a batch of pages at a time off the
// main thread (sqlite's online backup): made in one go (VACUUM INTO, after
// writing every account) it held the game up for seconds.
const BACKUPS_KEPT = 14; const BACKUPS_KEPT = 14;
const backup = () => { let backingUp = false;
const backup = async () => {
const folder = path.join(config.dataDir, "backups"); const folder = path.join(config.dataDir, "backups");
const file = path.join(folder, `game-${new Date().toISOString().slice(0, 10)}.sqlite`); const file = path.join(folder, `game-${new Date().toISOString().slice(0, 10)}.sqlite`);
if (fs.existsSync(file)) { if (backingUp || fs.existsSync(file)) {
return; return;
} }
fs.mkdirSync(folder, {recursive: true, mode: 0o700}); backingUp = true;
flush(); const part = `${file}.part`;
db.prepare("VACUUM INTO ?").run(file); try {
fs.chmodSync(file, 0o600); fs.mkdirSync(folder, {recursive: true, mode: 0o700});
fs.rmSync(part, {force: true});
await copyDatabase(db, part);
fs.chmodSync(part, 0o600);
fs.renameSync(part, file); // only a whole copy has the day's name
}
finally {
backingUp = false;
fs.rmSync(part, {force: true});
}
const old = fs.readdirSync(folder).filter(name => /^game-\d{4}-\d{2}-\d{2}\.sqlite$/.test(name)).sort().slice(0, -BACKUPS_KEPT); const old = fs.readdirSync(folder).filter(name => /^game-\d{4}-\d{2}-\d{2}\.sqlite$/.test(name)).sort().slice(0, -BACKUPS_KEPT);
for (const name of old) { for (const name of old) {
fs.unlinkSync(path.join(folder, name)); fs.unlinkSync(path.join(folder, name));
} }
console.log(`[accounts] backup written: ${file}`); console.log(`[accounts] backup written: ${logText(file)}`);
}; };
const startBackups = () => { const startBackups = () => {
const attempt = () => { const attempt = () => {
try { backup().catch(err => {
backup();
}
catch (err) {
console.error(`[accounts] backup failed: ${err.message}`); console.error(`[accounts] backup failed: ${err.message}`);
} });
}; };
attempt(); attempt();
setInterval(attempt, 3600000).unref(); setInterval(attempt, 3600000).unref();
@@ -483,9 +696,26 @@ const retire = key => {
// A new password: ten characters or more, with a capital letter, a small // A new password: ten characters or more, with a capital letter, a small
// one and a digit among them. passwords chosen before this rule still sign // one and a digit among them. passwords chosen before this rule still sign
// in; it is asked of the next one. // in; it is asked of the next one.
const passwordProblem = password => // the words most often under a password that meets the rules ("Password123",
(typeof password !== "string" || password.length < MIN_PASSWORD_LENGTH || password.length > MAX_PASSWORD_LENGTH // "Sunshine2024"): with its digits and signs taken off, a password that is
|| !/[A-Z]/.test(password) || !/[a-z]/.test(password) || !/[0-9]/.test(password) ? "invalid_password" : null); // one of these is refused, as is one with the username in it.
const COMMON_PASSWORD_WORDS = new Set(["password", "passw", "pass", "qwerty", "qwertyuiop", "asdfgh", "asdfghjkl", "zxcvbn", "abcdef", "abcdefg",
"abcdefgh", "abcdefghij", "welcome", "letmein", "iloveyou", "admin", "administrator", "monkey", "dragon", "football", "baseball", "soccer",
"sunshine", "princess", "starwars", "superman", "batman", "master", "shadow", "michael", "jennifer", "charlie", "freedom", "whatever",
"trustno", "hello", "secret", "login", "changeme", "animaljam", "animal", "jamaa", "jammer", "wildworks", "burrow", "summer", "winter",
"spring", "autumn", "january", "minecraft", "roblox", "fortnite", "pokemon", "computer", "internet", "cookie", "chocolate", "butterfly"]);
const passwordProblem = (password, username = "") => {
if (typeof password !== "string" || password.length < MIN_PASSWORD_LENGTH || password.length > MAX_PASSWORD_LENGTH
|| !/[A-Z]/.test(password) || !/[a-z]/.test(password) || !/[0-9]/.test(password)) {
return "invalid_password";
}
const lower = password.toLowerCase();
const name = String(username || "").toLowerCase().replace(/[^a-z0-9]/g, "");
if (COMMON_PASSWORD_WORDS.has(lower.replace(/[^a-z]/g, "")) || (name.length >= 3 && lower.replace(/[^a-z0-9]/g, "").includes(name))) {
return "weak_password";
}
return null;
};
// creates an account. `avatar` gives the first animal's {type, name}; the // creates an account. `avatar` gives the first animal's {type, name}; the
// name may be left out, and is then the player's. there is no default // name may be left out, and is then the player's. there is no default
@@ -494,7 +724,7 @@ const passwordProblem = password =>
// "invalid_password" | "choose_animal"}. // "invalid_password" | "choose_animal"}.
const register = (username, password, avatar = {}) => { const register = (username, password, avatar = {}) => {
username = typeof username === "string" ? username.trim() : username; username = typeof username === "string" ? username.trim() : username;
const error = usernameProblem(username) || passwordProblem(password) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal"); const error = usernameProblem(username) || passwordProblem(password, username) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal");
if (error) { if (error) {
return {error}; return {error};
} }
@@ -505,14 +735,43 @@ const register = (username, password, avatar = {}) => {
activeAvatar: 1, activeAvatar: 1,
// early Member, for an account made while there are no more than a hundred. // early Member, for an account made while there are no more than a hundred.
badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [], badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [],
recoveryEmail: typeof avatar.email === "string" && EMAIL_PATTERN.test(avatar.email.trim()) ? avatar.email.trim().toLowerCase() : "",
}); });
console.log(`[accounts] registered "${username}" (id ${account.id})`); console.log(`[accounts] registered "${logText(username)}" (id ${logText(account.id)})`);
return {account};
};
// Public sign-ups can arrive in a burst. scryptSync is fine for the local,
// legacy Create Account socket but it would freeze all players while each web
// registration is derived. Keep the same validation and database insert on
// the main thread, but derive its password on libuv's worker pool. Check the
// username again after awaiting: another request may have claimed it first.
const registerAsync = async (username, password, avatar = {}) => {
username = typeof username === "string" ? username.trim() : username;
let error = usernameProblem(username) || passwordProblem(password, username) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal");
if (error) {
return {error};
}
const salt = crypto.randomBytes(16).toString("hex");
const hash = await hashPasswordAsync(password, salt);
error = usernameProblem(username) || passwordProblem(password, username) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal");
if (error) {
return {error};
}
const type = Number(avatar.type);
const account = insert(username, salt, hash, now(), {
avatars: [newAvatar({perUserAvId: 1, avInvId: 1}, avatar.name || username, type, -1)],
activeAvatar: 1,
badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [],
recoveryEmail: typeof avatar.email === "string" && EMAIL_PATTERN.test(avatar.email.trim()) ? avatar.email.trim().toLowerCase() : "",
});
console.log(`[accounts] registered "${logText(username)}" (id ${logText(account.id)})`);
return {account}; return {account};
}; };
const authenticate = (username, password) => { const authenticate = (username, password) => {
// "name" and "name " are the same account. // "name" and "name " are the same account.
const account = typeof username === "string" ? byKey.get(username.trim().toLowerCase()) : null; const account = typeof username === "string" ? touch(byKey.get(username.trim().toLowerCase())) : null;
if (typeof password !== "string" || !password) { if (typeof password !== "string" || !password) {
return null; return null;
} }
@@ -534,7 +793,7 @@ const authenticate = (username, password) => {
// the same, with the password worked out off the main thread (above). // the same, with the password worked out off the main thread (above).
const authenticateAsync = async (username, password) => { const authenticateAsync = async (username, password) => {
const account = typeof username === "string" ? byKey.get(username.trim().toLowerCase()) : null; const account = typeof username === "string" ? touch(byKey.get(username.trim().toLowerCase())) : null;
if (typeof password !== "string" || !password || password.length > MAX_PASSWORD_LENGTH) { if (typeof password !== "string" || !password || password.length > MAX_PASSWORD_LENGTH) {
return null; return null;
} }
@@ -552,9 +811,10 @@ const authenticateAsync = async (username, password) => {
}; };
// gives the account a new password and signs it out everywhere. returns // gives the account a new password and signs it out everywhere. returns
// "invalid_password" when the password is not acceptable, else null. // "invalid_password" (the rules) or "weak_password" (a common one, or the
// username in it) when the password is not acceptable, else null.
const setPassword = (account, password) => { const setPassword = (account, password) => {
const problem = passwordProblem(password); const problem = passwordProblem(password, account.username);
if (problem) { if (problem) {
return problem; return problem;
} }
@@ -582,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.
@@ -603,16 +866,32 @@ const rename = (account, username, anyName = false) => {
db.prepare("DELETE FROM retired_names WHERE name_key = ?").run(newKey); db.prepare("DELETE FROM retired_names WHERE name_key = ?").run(newKey);
} }
db.prepare("UPDATE accounts SET username = ?, username_key = ? WHERE id = ?").run(username, newKey, account.id); db.prepare("UPDATE accounts SET username = ?, username_key = ? WHERE id = ?").run(username, newKey, account.id);
console.log(`[accounts] renamed "${account.username}" to "${username}" (id ${account.id})`); console.log(`[accounts] renamed "${logText(account.username)}" to "${logText(username)}" (id ${logText(account.id)})`);
for (const [table, column] of [
["reports", "reporter"], ["reports", "target"], ["feedback", "username"],
["chat_log", "username"], ["chat_log", "to_name"], ["appeals", "username"],
["ban_log", "username"], ["mod_log", "by"], ["mod_log", "target"],
]) {
// A few lean unit tests load the account store without every dashboard
// module. The tables are present in the actual server, but keep rename
// usable in that smaller setup too.
if (db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table)) {
db.prepare(`UPDATE ${table} SET ${column} = ? WHERE ${column} = ? COLLATE NOCASE`).run(username, account.username);
}
}
byKey.delete(oldKey); byKey.delete(oldKey);
account.username = username; account.username = username;
byKey.set(newKey, account); byKey.set(newKey, account);
const named = [account];
for (const other of byId.values()) { for (const other of byId.values()) {
other.buddies = other.buddies.map(name => (name === oldKey ? newKey : name)); if ([other.buddies, other.blocked, other.buddyRequests].some(list => list.includes(oldKey))) {
other.blocked = other.blocked.map(name => (name === oldKey ? newKey : name)); other.buddies = other.buddies.map(name => (name === oldKey ? newKey : name));
other.buddyRequests = other.buddyRequests.map(name => (name === oldKey ? newKey : name)); other.blocked = other.blocked.map(name => (name === oldKey ? newKey : name));
other.buddyRequests = other.buddyRequests.map(name => (name === oldKey ? newKey : name));
named.push(other);
}
} }
save(); save(...named);
return null; return null;
}; };
@@ -646,14 +925,19 @@ const remove = account => {
byId.delete(account.id); byId.delete(account.id);
savedState.delete(account.id); savedState.delete(account.id);
retire(key); retire(key);
const named = [];
for (const other of byId.values()) { for (const other of byId.values()) {
other.tradeOffers = other.tradeOffers.filter(offer => offer.fromId !== account.id); if (other.tradeOffers.some(offer => offer.fromId === account.id)
other.buddies = other.buddies.filter(name => name !== key); || [other.buddies, other.blocked, other.buddyRequests].some(list => list.includes(key))) {
other.blocked = other.blocked.filter(name => name !== key); other.tradeOffers = other.tradeOffers.filter(offer => offer.fromId !== account.id);
other.buddyRequests = other.buddyRequests.filter(name => name !== key); other.buddies = other.buddies.filter(name => name !== key);
other.blocked = other.blocked.filter(name => name !== key);
other.buddyRequests = other.buddyRequests.filter(name => name !== key);
named.push(other);
}
} }
save(); save(...named);
console.log(`[accounts] deleted "${account.username}" (id ${account.id})`); console.log(`[accounts] deleted "${logText(account.username)}" (id ${logText(account.id)})`);
}; };
// small server-wide values kept in the database (the admin panel's password). // small server-wide values kept in the database (the admin panel's password).
@@ -684,15 +968,22 @@ const issueToken = account => {
const byToken = token => { const byToken = token => {
const entry = typeof token === "string" && token.length === TOKEN_HEX_LENGTH ? tokens.get(tokenHash(token)) : null; const entry = typeof token === "string" && token.length === TOKEN_HEX_LENGTH ? tokens.get(tokenHash(token)) : null;
return entry && !tokenExpired(entry.createdAt) ? byId.get(entry.id) || null : null; return entry && !tokenExpired(entry.createdAt) ? touch(byId.get(entry.id)) || null : null;
}; };
const byName = username => byKey.get(String(username).toLowerCase()) || null; const byName = username => touch(byKey.get(String(username).toLowerCase())) || null;
const accountById = id => byId.get(Number(id)) || 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 all = () => [...byId.values()]; const all = () => [...byId.values()];
const database = () => db; const database = () => db;
module.exports = {FEATURES, featureOn, recordLogin, revokeTokens, load, save, flush, startBackups, database, setLoginChoices, setPassword, rename, remove, setting, setSetting, hashPassword, register, usernameProblem, authenticate, authenticateAsync, issueToken, byToken, byName, byId: accountById, newAvatar, freeAvatarSlot, all}; 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};
+1 -1
View File
@@ -105,7 +105,7 @@ const grant = (account, defId) => {
} }
const achievement = {inv: account.nextInv++, def: def.id}; const achievement = {inv: account.nextInv++, def: def.id};
account.achievements.push(achievement); account.achievements.push(achievement);
accounts.save(); accounts.save(account);
const session = findOnline(account.username); const session = findOnline(account.username);
if (session) { if (session) {
if (account.userVars[def.userVarRef] === undefined) { if (account.userVars[def.userVarRef] === undefined) {
+227 -23
View File
@@ -2,10 +2,17 @@
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const bans = require("./bans.js"); const bans = require("./bans.js");
const cdn = require("./cdn.js");
const colours = require("./colours.js");
const captcha = require("./captcha.js"); const captcha = require("./captcha.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const devices = require("./devices.js");
const config = require("../config.js"); const config = require("../config.js");
const roles = require("./roles.js");
const dens = require("./dens.js"); const dens = require("./dens.js");
const itemControl = require("./itemcontrol.js");
const customItems = require("./customitems.js");
const itemArt = require("./itemart.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const world = require("./world.js"); const world = require("./world.js");
const {addClothing, sendClothingAdded, isUint} = require("./player.js"); const {addClothing, sendClothingAdded, isUint} = require("./player.js");
@@ -21,6 +28,7 @@ const MAX_FAVOURITES = 200; // finder items remembered per account
const STARTER_ANIMALS = [1, 4, 5, 6, 7, 8, 13, 18, 24]; const STARTER_ANIMALS = [1, 4, 5, 6, 7, 8, 13, 18, 24];
let catalog = null; let catalog = null;
let catalogVersion = -1; // defpacks.customVersion() it was built at: staff add items as the server runs
const buildCatalog = () => [ const buildCatalog = () => [
...defpacks.clothingIds().map(id => { ...defpacks.clothingIds().map(id => {
@@ -35,13 +43,23 @@ const buildCatalog = () => [
// `favourites` is an account's finderGiven, or null: with nothing typed, the // `favourites` is an account's finderGiven, or null: with nothing typed, the
// items that account took most often come first, the latest first among // items that account took most often come first, the latest first among
// equals. (The in-game finder says whose search it is.) // equals. (The in-game finder says whose search it is.) items locked out of
const search = (params, favourites = null) => { // the finder (lib/itemcontrol.js) are left out, unless `seesLocked`: then
catalog = catalog || buildCatalog(); // they are marked. an item a player made (lib/playeritems.js) is found by
// its maker only (`askerId`), and by those who see locked ones. with
// "base=1", only the game's own items that can be made into a new one.
const search = (params, favourites = null, seesLocked = false, askerId = null) => {
if (!catalog || catalogVersion !== defpacks.customVersion()) {
catalog = buildCatalog();
catalogVersion = defpacks.customVersion();
}
const kind = params.get("kind") || "all"; const kind = params.get("kind") || "all";
const words = (params.get("q") || "").toLowerCase().split(/\s+/).filter(Boolean); const words = (params.get("q") || "").toLowerCase().split(/\s+/).filter(Boolean);
const matches = catalog.filter(entry => (kind === "all" || entry.kind === kind) const matches = catalog.filter(entry => (kind === "all" || entry.kind === kind)
&& words.every(word => entry.search.includes(word) || String(entry.id) === word)); && words.every(word => entry.search.includes(word) || String(entry.id) === word)
&& (seesLocked || !itemControl.isLocked(entry.kind, entry.id))
&& (seesLocked || [null, askerId].includes(customItems.ownerOf(entry.kind, entry.id)))
&& (params.get("base") !== "1" || customItems.copyable(entry.kind, entry.id)));
matches.sort((a, b) => words.includes(String(b.id)) - words.includes(String(a.id))); matches.sort((a, b) => words.includes(String(b.id)) - words.includes(String(a.id)));
if (words.length === 0 && favourites) { if (words.length === 0 && favourites) {
const taken = entry => favourites[`${entry.kind}:${entry.id}`] || {count: 0, at: 0}; const taken = entry => favourites[`${entry.kind}:${entry.id}`] || {count: 0, at: 0};
@@ -49,26 +67,84 @@ const search = (params, favourites = null) => {
} }
return { return {
total: matches.length, total: matches.length,
results: matches.slice(0, MAX_RESULTS).map(({kind: entryKind, id, name, cost, colors}) => ({kind: entryKind, id, name, cost, colors})), results: matches.slice(0, MAX_RESULTS).map(({kind: entryKind, id, name, cost, colors}) => {
const locked = seesLocked && itemControl.isLocked(entryKind, id);
return {kind: entryKind, id, name: locked ? `${name} (locked)` : name, cost, colors, ...(locked ? {locked} : {})};
}),
}; };
}; };
const give = body => { // 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
// digits alone are a colour id
const HEX_COLOURS = /^#[0-9a-f]{6}([\s,]+#[0-9a-f]{6}){0,3}$/i;
// `seesLocked`: who asks may take items locked out of the finder.
const give = (body, seesLocked = false) => {
const account = accounts.byName(body.username); const account = accounts.byName(body.username);
if (!account) { if (!account) {
return {status: 404, body: {error: "No such account"}}; return {status: 404, body: {error: "No such account"}};
} }
const maker = customItems.ownerOf(body.kind, body.id);
if (!seesLocked && maker !== null && maker !== account.id) {
return {status: 403, body: {error: "That item is another player's own."}};
}
if (!seesLocked && itemControl.isLocked(body.kind, body.id)) {
return {status: 403, body: {error: "That item is locked out of the item finder."}};
}
const session = world.findOnline(account.username); const session = world.findOnline(account.username);
const given = {}; // what the item was given as: its colour, or its version
if (body.kind === "clothing") { if (body.kind === "clothing") {
const def = defpacks.itemDef(body.id); const def = defpacks.itemDef(body.id);
const colors = def ? String(def.colors).split(",") : []; const colors = def ? String(def.colors).split(",") : [];
// `color` is a raw colour id of the caller's choosing; otherwise one of // `color` is a raw colour id of the caller's choosing, or one to four hex
// the item's own colours is picked by `colorIndex`. // colours ("#FF8800", "#FF0000 #FFFFFF") for the item's four colour bands
const custom = body.color !== undefined && body.color !== ""; // in order, the last filling the rest: a custom colour (lib/colours.js),
if (custom && !isUint(String(body.color))) { // made as the animal editor's hex box makes one. otherwise one of the
return {status: 400, body: {error: "The colour id must be a whole number from 0 to 4294967295"}}; // item's own colours is picked by `colorIndex`.
let custom = body.color !== undefined && body.color !== "" ? String(body.color).trim() : "";
const hexes = custom.match(HEX_COLOURS) ? custom.split(/[\s,]+/).filter(Boolean) : null;
if (hexes) {
const rgbs = [0, 1, 2, 3].map(slot => parseInt(hexes[Math.min(slot, hexes.length - 1)].replace("#", ""), 16));
const entry = world.makeColour(account, rgbs, 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."}};
}
custom = String(entry.id);
} }
const color = custom ? String(body.color) : colors[Number(body.colorIndex) || 0]; // 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)) {
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];
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"}};
} }
@@ -76,7 +152,8 @@ const give = body => {
if (!item) { if (!item) {
return {status: 409, body: {error: "That inventory is full"}}; return {status: 409, body: {error: "That inventory is full"}};
} }
accounts.save(); given.color = Number(color);
accounts.save(account);
if (session) { if (session) {
sendClothingAdded(session, item); sendClothingAdded(session, item);
} }
@@ -85,12 +162,48 @@ const give = body => {
if (!defpacks.denItemIds().includes(Number(body.id))) { if (!defpacks.denItemIds().includes(Number(body.id))) {
return {status: 400, body: {error: "No such den item"}}; return {status: 400, body: {error: "No such den item"}};
} }
if (!dens.giveDenItem(account, body.id)) { // `version`: one of the variants its art has (above), 0 by default.
// `tint` ("#RRGGBB") and `tintStrength` (1-100, 100 by default): the
// whole item in shades of that colour, which the patched client draws
// (DenItemHelper.applyTint). the tint is a custom colour entry
// (lib/colours.js, [rgb, strength, 0, 0]), and 1 + its number goes in
// the version above the variant's 8 bits, so it goes wherever the item
// goes: dens, trades, gifts.
const variants = variantsOf(body.id);
const variant = body.version === undefined || body.version === "" ? 0 : Number(body.version);
if (!Number.isInteger(variant) || (variant !== 0 && !(variants && variants.versions.includes(variant)))) {
return {status: 400, body: {error: "That item has no such variant"}};
}
let version = variant;
const tint = typeof body.tint === "string" ? body.tint.trim() : "";
if (tint) {
const strength = body.tintStrength === undefined || body.tintStrength === "" ? 100 : Number(body.tintStrength);
if (!/^#[0-9a-f]{6}$/i.test(tint) || !Number.isInteger(strength) || strength < 1 || strength > 100) {
return {status: 400, body: {error: "Tint: #RRGGBB, strength 1 to 100"}};
}
if ((defpacks.denItemDef(body.id) || {}).specialType === SPECIAL_MANNEQUIN) {
return {status: 400, body: {error: "Mannequins cannot be tinted"}};
}
const entry = world.makeColour(account, [parseInt(tint.slice(1), 16), strength, 0, 0], session);
if (!entry) {
return {status: 400, body: {error: "Bad colour"}};
}
if (entry.full) {
return {status: 429, body: {error: "No more new colours today. Colours made before can still be used."}};
}
const slot = entry.id - colours.CUSTOM_BASE + 1;
if (slot > MAX_TINT_SLOT) {
return {status: 503, body: {error: "No more tints can be made"}};
}
version |= slot << 8;
}
if (!dens.giveDenItem(account, body.id, version)) {
return {status: 409, body: {error: "That inventory is full"}}; return {status: 409, body: {error: "That inventory is full"}};
} }
if (session) { if (session) {
dens.sendDenItems(session); dens.sendDenItems(session);
} }
given.version = version;
} }
else { else {
return {status: 400, body: {error: "Unknown item kind"}}; return {status: 400, body: {error: "Unknown item kind"}};
@@ -100,12 +213,91 @@ const give = body => {
account.finderGiven[key] = {count: ((account.finderGiven[key] || {}).count || 0) + 1, at: Math.floor(Date.now() / 1000)}; account.finderGiven[key] = {count: ((account.finderGiven[key] || {}).count || 0) + 1, at: Math.floor(Date.now() / 1000)};
const kept = Object.entries(account.finderGiven).sort((one, other) => other[1].at - one[1].at).slice(0, MAX_FAVOURITES); 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(); accounts.save(account);
return {status: 200, body: {ok: true, online: Boolean(session)}}; return {status: 200, body: {ok: true, online: Boolean(session), ...given}};
};
// the game's 256 colours (the CDN's paletteData; PaletteHelper.setGamePalette),
// as "rrggbb", once read. null while the file cannot be had.
let palette = null;
const loadPalette = async () => {
if (!palette) {
const file = await cdn.get(cdn.hashedPath("paletteData"));
if (file && file.length >= 4 && file.readInt32BE(0) === 1024) {
palette = Array.from({length: 256}, (unused, index) => (file.readUInt32BE(4 + index * 4) & 0xFFFFFF).toString(16).padStart(6, "0"));
}
}
return palette;
};
// a packed colour's four, as "rrggbb" (a custom colour's own, or the
// palette's at each of its four bytes, colour 1 the top one).
const coloursOf = id => {
const custom = colours.rgbsOf(id);
if (custom) {
return custom.map(rgb => rgb.toString(16).padStart(6, "0"));
}
return palette ? [24, 16, 8, 0].map(shift => palette[(id >>> shift) & 0xFF]) : null;
};
// the web item giver (/account/items, lib/manage.js): a search as the
// in-game one, with what each item may be given as: a clothing item's own
// colours, a den item's variants and whether it takes a tint.
const searchFor = async (account, params) => {
await loadPalette();
const found = search(params, account.finderGiven, roles.can(account, "items.create"), account.id);
return {...found, results: found.results.map(result => {
// a custom item's own picture, which the game shows in place of its art
const custom = customItems.get(result.kind, result.id);
const entry = {...result, art: custom ? itemArt.urlOf(custom, "/account/api/itemart") : null};
if (entry.kind === "clothing") {
const def = defpacks.itemDef(entry.id);
const ids = def ? String(def.colors).split(",").map(Number).filter(Number.isInteger).slice(0, MAX_PRESETS) : [];
return {...entry, presets: ids.map(id => ({id: id >>> 0, colours: coloursOf(id >>> 0)}))};
}
const variants = variantsOf(entry.id);
return {...entry, variants: variants ? variants.versions : [], variantColours: variants && variants.colours ? variants.colours : null,
tintable: (defpacks.denItemDef(entry.id) || {}).specialType !== SPECIAL_MANNEQUIN};
})};
};
// ... and its colour boxes, which turn colours to the game's numbers and
// back as they are typed: with `id`, a custom colour's four ("rrggbb"); with
// `rgbs` (four "rrggbb", commas between), the custom colour already made of
// those four, or null (Give would make it); with neither, the game's 256.
const colourLookup = async params => {
if (params.has("id")) {
const text = params.get("id");
const id = /^-?\d{1,10}$/.test(text) && Number(text) >= -0x80000000 && Number(text) <= 0xFFFFFFFF ? Number(text) >>> 0 : null;
const rgbs = id === null ? null : colours.rgbsOf(id);
return rgbs ? {status: 200, body: {id, colours: rgbs.map(rgb => rgb.toString(16).padStart(6, "0"))}}
: {status: 404, body: {error: "No such custom colour"}};
}
if (params.has("rgbs")) {
const rgbs = params.get("rgbs").split(",").map(hex => (/^[0-9a-f]{6}$/i.test(hex) ? parseInt(hex, 16) : NaN));
const entry = colours.allocate(rgbs, false);
if (!entry) {
return {status: 400, body: {error: "Four colours: rrggbb,rrggbb,rrggbb,rrggbb"}};
}
return {status: 200, body: {id: entry.full ? null : entry.id}};
}
return {status: 200, body: {palette: await loadPalette()}};
};
// ... and its Give, for the account signed in on that page.
const giveAs = (account, body) => {
if (!givesPerMinute.allow(account.id)) {
return {status: 429, body: {error: "Too many at once. Try again in a minute."}};
}
return give({...body, username: account.username}, roles.can(account, "items.create"));
}; };
const FORBIDDEN = {status: 403, body: {error: "forbidden"}}; const FORBIDDEN = {status: 403, body: {error: "forbidden"}};
// may whoever asks see and take items locked out of the finder? staff who
// may lock them (admins and developers) do; so does the owner, on this
// machine, asking with no account's token (the /shop page).
const seesLocked = (account, from) => (account ? roles.can(account, "items.create") : from.local);
// the account a login token is for, while it may play. A ban leaves the // the account a login token is for, while it may play. A ban leaves the
// token alone (so that the client can ask about the ban with it, below), // token alone (so that the client can ask about the ban with it, below),
// and it is good for nothing else until the ban is over. // and it is good for nothing else until the ban is over.
@@ -123,7 +315,8 @@ const handle = async (route, params, body, from) => {
case "GET /api/search": { case "GET /api/search": {
const asking = accounts.byName(params.get("username") || ""); const asking = accounts.byName(params.get("username") || "");
const known = asking && (from.local || holderOf(params.get("token")) === asking); const known = asking && (from.local || holderOf(params.get("token")) === asking);
return {status: 200, body: search(params, known ? asking.finderGiven : null)}; return {status: 200, body: search(params, known ? asking.finderGiven : null, seesLocked(params.get("token") ? holderOf(params.get("token")) : null, from),
known ? asking.id : null)};
} }
case "GET /api/accounts": case "GET /api/accounts":
if (!from.local) { if (!from.local) {
@@ -138,7 +331,7 @@ const handle = async (route, params, body, from) => {
if (!from.local && !givesPerMinute.allow(owner.id)) { if (!from.local && !givesPerMinute.allow(owner.id)) {
return {status: 429, body: {error: "Too many at once. Try again in a minute."}}; return {status: 429, body: {error: "Too many at once. Try again in a minute."}};
} }
return give(body || {}); return give(body || {}, seesLocked((body || {}).token ? owner : null, from));
} }
case "POST /api/theme": { case "POST /api/theme": {
const account = accounts.byName((body || {}).username); const account = accounts.byName((body || {}).username);
@@ -185,14 +378,25 @@ const handle = async (route, params, body, from) => {
} }
const ban = world.moderation.banOf(account); const ban = world.moderation.banOf(account);
const addressBan = ban ? null : bans.addressBan(from.address); const addressBan = ban ? null : bans.addressBan(from.address);
const deviceBan = ban || addressBan ? null : devices.banOfAccount(account);
return {status: 200, body: ban ? {banned: "account", banned_seconds: ban.seconds, ban_reason: ban.reason} return {status: 200, body: ban ? {banned: "account", banned_seconds: ban.seconds, ban_reason: ban.reason}
: addressBan ? {banned: "address", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason} : {banned: null}}; : addressBan ? {banned: "address", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason}
: deviceBan ? {banned: "device", banned_seconds: world.moderation.PERMANENT, ban_reason: deviceBan.reason} : {banned: null}};
} }
case "POST /api/register": { case "POST /api/register": {
if (bans.addressBan(from.address)) { if (bans.addressBan(from.address)) {
return {status: 403, body: {error: "address_banned"}}; return {status: 403, body: {error: "address_banned"}};
} }
const {username, password, avatarType} = body || {}; // the client says which computer it is on (lib/devices.js); the sign-up
// page cannot, and an account made there still signs in through the client.
const device = devices.read((body || {}).device);
if (device && devices.banOf(device)) {
return {status: 403, body: {error: "device_banned"}};
}
const {username, password, avatarType, email} = body || {};
if (config.recoveryMail && (typeof email !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim()))) {
return {status: 400, body: {error: "invalid_email"}};
}
// the terms and the privacy policy, and old enough to agree to them: // the terms and the privacy policy, and old enough to agree to them:
// said by the one signing up, on the page or in the client. // said by the one signing up, on the page or in the client.
if ((body || {}).agreed !== true) { if ((body || {}).agreed !== true) {
@@ -214,10 +418,10 @@ 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(); accounts.save(result.account);
} }
// the client signs in straight after, and is not asked again. // the client signs in straight after, and is not asked again.
return result.error ? {status: 400, body: {error: result.error}} return result.error ? {status: 400, body: {error: result.error}}
@@ -228,4 +432,4 @@ const handle = async (route, params, body, from) => {
} }
}; };
module.exports = {handle}; module.exports = {handle, search, searchFor, colourLookup, giveAs};
+1 -1
View File
@@ -59,7 +59,7 @@ const handlers = {
for (const found of session.account.adoptAPets) { for (const found of session.account.adoptAPets) {
found.seen = found.seen || seen.has(found.def); found.seen = found.seen || seen.has(found.def);
} }
accounts.save(); accounts.save(session.account);
}, },
}; };
+4 -3
View File
@@ -1,5 +1,6 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
// adventures. the engine is in the client (quest/QuestManager): it places // adventures. the engine is in the client (quest/QuestManager): it places
// the actors named in the room file and plays them. what happens when was // the actors named in the room file and plays them. what happens when was
// decided by scripts on the official server, which no file holds, so each // decided by scripts on the official server, which no file holds, so each
@@ -82,7 +83,7 @@ module.exports = ({enterRoom, joinRoom, tell}) => {
avatar.questXp = before + amount; avatar.questXp = before + amount;
avatar.questLevel = levelFor(avatar.questXp); avatar.questLevel = levelFor(avatar.questXp);
if (amount > 0) { if (amount > 0) {
accounts.save(); accounts.save(session.account);
} }
q.send("quxp", amount, avatar.questXp, level, avatar.questLevel, percent(avatar.questXp), actor); q.send("quxp", amount, avatar.questXp, level, avatar.questLevel, percent(avatar.questXp), actor);
if (avatar.questLevel > level) { if (avatar.questLevel > level) {
@@ -121,7 +122,7 @@ module.exports = ({enterRoom, joinRoom, tell}) => {
const {account} = session; const {account} = session;
account.currency.gems = (account.currency.gems || 0) + amount; account.currency.gems = (account.currency.gems || 0) + amount;
achievements.currencyChanged(account, "gems", amount); achievements.currencyChanged(account, "gems", amount);
accounts.save(); accounts.save(account);
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0); session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
}, },
}; };
@@ -145,7 +146,7 @@ module.exports = ({enterRoom, joinRoom, tell}) => {
family[1](tools(session, quest), key, ...args); family[1](tools(session, quest), key, ...args);
} }
else if (key !== null && kind !== "pickedUp") { else if (key !== null && kind !== "pickedUp") {
console.log(`[adventure] ${quest.script.title}: nothing written for "${kind} ${key}"`); console.log(`[adventure] ${logText(quest.script.title)}: nothing written for "${logText(kind)} ${logText(key)}"`);
} }
}; };
+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);
}, },
}; };
+15 -7
View File
@@ -78,7 +78,7 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
// (accounts.freeAvatarSlot). // (accounts.freeAvatarSlot).
const avatar = accounts.newAvatar({perUserAvId: account.nextInv++, avInvId: accounts.freeAvatarSlot(account)}, `${name1}|${name2}|${name3}`, type, customAvId); const avatar = accounts.newAvatar({perUserAvId: account.nextInv++, avInvId: accounts.freeAvatarSlot(account)}, `${name1}|${name2}|${name3}`, type, customAvId);
account.avatars.push(avatar); account.avatars.push(avatar);
accounts.save(); accounts.save(account);
session.sendXt("aa", -1, 1, avatar.perUserAvId, avatar.avInvId); session.sendXt("aa", -1, 1, avatar.perUserAvId, avatar.avInvId);
}, },
@@ -93,10 +93,16 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
return; return;
} }
account.activeAvatar = avatar.perUserAvId; account.activeAvatar = avatar.perUserAvId;
accounts.save(); accounts.save(account);
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,20 +110,22 @@ 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);
for (const item of account.items) { for (const item of account.items) {
item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId); item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId);
} }
accounts.save(); 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]
@@ -134,7 +142,7 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
if (tagChanged) { if (tagChanged) {
session.account.nameBarData = nameBarData; session.account.nameBarData = nameBarData;
} }
accounts.save(); accounts.save(session.account);
session.sendXt("ap", -1, 1); session.sendXt("ap", -1, 1);
refreshForOthers(session); refreshForOthers(session);
if (tagChanged) { if (tagChanged) {
+6 -2
View File
@@ -33,8 +33,12 @@ const cdn = require("./cdn.js");
// there are no more than a hundred (lib/accounts.js); the admin may give // there are no more than a hundred (lib/accounts.js); the admin may give
// it and take it away like any other. // it and take it away like any other.
// in the order they are listed and drawn. // in the order they are listed and drawn. the Verified, Owner, Moderator and
// Developer name tags show their badge to everyone, not only to buddies:
// their def ids are in PUBLIC_BADGE_IDS of swf-src/AvatarWorldView.as.
const BADGES = [ const BADGES = [
// first, so its tick comes straight after the name, as on other sites.
{id: "verified", label: "Verified", tag: {def: 76, media: 20014, bit: 21}},
{id: "owner", label: "Owner", tag: {def: 63, media: 20001, bit: 8}}, {id: "owner", label: "Owner", tag: {def: 63, media: 20001, bit: 8}},
{id: "moderator", label: "Moderator", tag: {def: 64, media: 20002, bit: 9}}, {id: "moderator", label: "Moderator", tag: {def: 64, media: 20002, bit: 9}},
{id: "contributor", label: "Contributor", tag: {def: 65, media: 20003, bit: 10}}, {id: "contributor", label: "Contributor", tag: {def: 65, media: 20003, bit: 10}},
@@ -61,7 +65,7 @@ const set = (account, ids) => {
}; };
// A Discord username as Discord has them now: 2 to 32 of a-z, 0-9, "_" and // A Discord username as Discord has them now: 2 to 32 of a-z, 0-9, "_" and
// ".", with no two dots in a row. nobody checks that it is theirs. // ".", with no two dots in a row. players link theirs (lib/discord.js).
const DISCORD_NAME = /^(?!.*\.\.)[a-z0-9_.]{2,32}$/; const DISCORD_NAME = /^(?!.*\.\.)[a-z0-9_.]{2,32}$/;
// returns the username as it will be kept ("" for none), or null when it // returns the username as it will be kept ("" for none), or null when it
+2 -1
View File
@@ -1,5 +1,6 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const net = require("net"); const net = require("net");
@@ -158,7 +159,7 @@ const appeal = (account, text, addressKey = "") => {
} }
db().prepare("INSERT INTO appeals (account_id, created_at, username, text, address_key) VALUES (?, ?, ?, ?, ?)").run(account.id, now(), account.username, body, addressKey); db().prepare("INSERT INTO appeals (account_id, created_at, username, text, address_key) VALUES (?, ?, ?, ?, ?)").run(account.id, now(), account.username, body, addressKey);
record({account, address: addressKey, action: "appeal"}); record({account, address: addressKey, action: "appeal"});
console.log(`[bans] "${account.username}" appealed`); console.log(`[bans] "${logText(account.username)}" appealed`);
return {appeal: appealOf(account)}; return {appeal: appealOf(account)};
}; };
+14 -9
View File
@@ -40,7 +40,7 @@ const requestsPerTenMinutes = limits.limiter(20, 600000);
// and reads a hosted party's name as three string ids. // and reads a hosted party's name as three string ids.
const roomTitle = room => room.displayName; const roomTitle = room => room.displayName;
module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => { module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft, worldOf, worldName}) => {
// BuddyXtCommManager.buddyStatusResponse: [1, username, uuid, moderatedFlag, // BuddyXtCommManager.buddyStatusResponse: [1, username, uuid, moderatedFlag,
// online, accountType, buddyFlag, avatarName, perUserAvId, partyTimeLeft] // online, accountType, buddyFlag, avatarName, perUserAvId, partyTimeLeft]
const sendStatus = (to, account, buddyFlag) => { const sendStatus = (to, account, buddyFlag) => {
@@ -105,7 +105,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
else if (!account.buddies.includes(key(target))) { else if (!account.buddies.includes(key(target))) {
if (!target.buddyRequests.includes(key(account))) { if (!target.buddyRequests.includes(key(account))) {
target.buddyRequests.push(key(account)); target.buddyRequests.push(key(account));
accounts.save(); accounts.save(account, target);
} }
if (targetSession) { if (targetSession) {
targetSession.sendXt("ba", -1, REQUEST_INCOMING, account.username, USERNAME_SHOWN); targetSession.sendXt("ba", -1, REQUEST_INCOMING, account.username, USERNAME_SHOWN);
@@ -122,7 +122,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
return; return;
} }
account.buddyRequests = account.buddyRequests.filter(name => name !== key(requester)); account.buddyRequests = account.buddyRequests.filter(name => name !== key(requester));
accounts.save(); accounts.save(account);
const requesterSession = findOnline(requester.username); const requesterSession = findOnline(requester.username);
if (accept !== "1" || account.buddies.includes(key(requester)) if (accept !== "1" || account.buddies.includes(key(requester))
|| account.buddies.length >= MAX_BUDDIES || requester.buddies.length >= MAX_BUDDIES) { || account.buddies.length >= MAX_BUDDIES || requester.buddies.length >= MAX_BUDDIES) {
@@ -135,7 +135,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
requester.buddies.push(key(account)); requester.buddies.push(key(account));
achievements.add(account, achievements.VARS.buddiesAdded); achievements.add(account, achievements.VARS.buddiesAdded);
achievements.add(requester, achievements.VARS.buddiesAdded); achievements.add(requester, achievements.VARS.buddiesAdded);
accounts.save(); accounts.save(account, requester);
sendStatus(session, requester, STATUS_UPDATE); sendStatus(session, requester, STATUS_UPDATE);
if (requesterSession) { if (requesterSession) {
sendStatus(requesterSession, account, STATUS_ACCEPTED_YOUR_REQUEST); sendStatus(requesterSession, account, STATUS_ACCEPTED_YOUR_REQUEST);
@@ -149,7 +149,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
if (other) { if (other) {
account.buddies = account.buddies.filter(name => name !== key(other)); account.buddies = account.buddies.filter(name => name !== key(other));
other.buddies = other.buddies.filter(name => name !== key(account)); other.buddies = other.buddies.filter(name => name !== key(account));
accounts.save(); accounts.save(account, other);
const otherSession = findOnline(other.username); const otherSession = findOnline(other.username);
if (otherSession) { if (otherSession) {
otherSession.sendXt("bd", -1, account.username); otherSession.sendXt("bd", -1, account.username);
@@ -165,7 +165,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
const added = other && other !== account && !account.blocked.includes(key(other)) && account.blocked.length < MAX_BLOCKED; const added = other && other !== account && !account.blocked.includes(key(other)) && account.blocked.length < MAX_BLOCKED;
if (added) { if (added) {
account.blocked.push(key(other)); account.blocked.push(key(other));
accounts.save(); accounts.save(account);
} }
session.sendXt("bb", -1, username, other && other !== account && account.blocked.includes(key(other)) ? 1 : 0); session.sendXt("bb", -1, username, other && other !== account && account.blocked.includes(key(other)) ? 1 : 0);
if (added) { if (added) {
@@ -178,7 +178,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
const other = accounts.byName(username); const other = accounts.byName(username);
const removed = other && account.blocked.includes(key(other)); const removed = other && account.blocked.includes(key(other));
account.blocked = account.blocked.filter(name => name !== String(username).toLowerCase()); account.blocked = account.blocked.filter(name => name !== String(username).toLowerCase());
accounts.save(); accounts.save(account);
session.sendXt("bu", -1, username, 1); session.sendXt("bu", -1, username, 1);
if (removed) { if (removed) {
onUnblocked(session, other); onUnblocked(session, other);
@@ -195,11 +195,16 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
// gets [roomName, displayName, displayNameStringId, cannotGoThere]; an // gets [roomName, displayName, displayNameStringId, cannotGoThere]; an
// empty room means offline. the last field greys out the card's "go to" // empty room means offline. the last field greys out the card's "go to"
// button (BuddyCard.checkBuddyRoomAgainstMine), so it is 0: every room // button (BuddyCard.checkBuddyRoomAgainstMine), so it is 0: every room
// here can be walked into. someone who blocked the asker looks offline. // here can be walked into. the room's name carries its world, and "go
// to" joins it by that name, so it leads into the buddy's world, which
// is named after the room when it is not the asker's. someone who
// blocked the asker looks offline.
br(session, roomId, [username]) { br(session, roomId, [username]) {
const target = findOnline(username); const target = findOnline(username);
if (target && target.room && !target.account.blocked.includes(key(session.account))) { if (target && target.room && !target.account.blocked.includes(key(session.account))) {
session.sendXt("br", -1, target.room.name, roomTitle(target.room), 0, 0); const world = worldOf(target.room.name);
const elsewhere = world !== 0 && world !== session.worldId;
session.sendXt("br", -1, target.room.name, `${roomTitle(target.room)}${elsewhere ? ` (${worldName(world)})` : ""}`, 0, 0);
} }
else { else {
session.sendXt("br", -1, "", "", 0, 0); session.sendXt("br", -1, "", "", 0, 0);
+19 -3
View File
@@ -1,5 +1,6 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto"); const crypto = require("crypto");
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
@@ -25,10 +26,12 @@ const MAX_ANSWER_LENGTH = 2048;
const PASS_MS = 600000; const PASS_MS = 600000;
const PASS_USES = 5; const PASS_USES = 5;
const MAX_PASSES = 10000; const MAX_PASSES = 10000;
const MAX_VERIFYING = config.maxConcurrentCaptchaChecks;
const on = Boolean(config.turnstile); const on = Boolean(config.turnstile);
const passes = new Map(); // SHA-256 of a pass -> {id: account id, key: address key, expiry, uses} const passes = new Map(); // SHA-256 of a pass -> {id: account id, key: address key, expiry, uses}
const sha256 = text => crypto.createHash("sha256").update(String(text)).digest("hex"); const sha256 = text => crypto.createHash("sha256").update(String(text)).digest("hex");
let verifying = 0;
// for the pages: what each answer means // for the pages: what each answer means
const MESSAGES = { const MESSAGES = {
@@ -69,6 +72,13 @@ const verify = async (answer, from, action) => {
if (typeof answer !== "string" || !answer || answer.length > MAX_ANSWER_LENGTH) { if (typeof answer !== "string" || !answer || answer.length > MAX_ANSWER_LENGTH) {
return "captcha_required"; return "captcha_required";
} }
// A burst of valid-looking tokens should not turn an upstream Turnstile
// slowdown into thousands of open fetches on this VPS. Refuse quickly;
// the browser can reset its widget and retry after the short outage.
if (verifying >= MAX_VERIFYING) {
return "captcha_unavailable";
}
verifying++;
const form = new URLSearchParams({secret: config.turnstile.secret, response: answer}); const form = new URLSearchParams({secret: config.turnstile.secret, response: answer});
if (!limits.isLoopback(from.address)) { if (!limits.isLoopback(from.address)) {
form.set("remoteip", from.address); form.set("remoteip", from.address);
@@ -79,9 +89,12 @@ const verify = async (answer, from, action) => {
result = await response.json(); result = await response.json();
} }
catch (err) { catch (err) {
console.log(`[captcha] cloudflare did not answer: ${err.message}`); console.log(`[captcha] cloudflare did not answer: ${logText(err.message)}`);
return "captcha_unavailable"; return "captcha_unavailable";
} }
finally {
verifying--;
}
// an answer made for another form is no answer for this one. cloudflare's // an answer made for another form is no answer for this one. cloudflare's
// test keys give none. // test keys give none.
if (!result || result.success !== true || (result.action && result.action !== action)) { if (!result || result.success !== true || (result.action && result.action !== action)) {
@@ -103,8 +116,11 @@ const check = async (body, from, action, account) => {
return verify(body.captcha, from, action); return verify(body.captcha, from, action);
}; };
// a page's security policy, letting the widget in when it is on. // a page's security policy: public/captcha.js always (the page calls it even
const policy = csp => (on ? `${csp.replace("script-src ", `script-src 'self' ${ORIGIN} `)}; frame-src ${ORIGIN}` : csp); // when off), and the widget too when it is on.
const policy = csp => (on
? `${csp.replace("script-src ", `script-src 'self' ${ORIGIN} `).replace("connect-src ", `connect-src 'self' ${ORIGIN} `)}; frame-src ${ORIGIN}`
: csp.replace("script-src ", "script-src 'self' "));
// a page with public/captcha.js asked for under a name that changes with the // a page with public/captcha.js asked for under a name that changes with the
// script and the key: cloudflare keeps .js files for hours, whatever the // script and the key: cloudflare keeps .js files for hours, whatever the
+11 -6
View File
@@ -1,5 +1,6 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto"); const crypto = require("crypto");
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
@@ -69,7 +70,7 @@ const measure = async folder => {
}; };
measure(config.cacheDir).then(() => { measure(config.cacheDir).then(() => {
if (cacheBytes > config.maxCacheBytes) { if (cacheBytes > config.maxCacheBytes) {
console.log(`[cdn] the cache holds ${Math.round(cacheBytes / 1048576)} MB, over its limit: new files are served but not kept (AJ_MAX_CACHE_MB)`); console.log(`[cdn] the cache holds ${logText(Math.round(cacheBytes / 1048576))} MB, over its limit: new files are served but not kept (AJ_MAX_CACHE_MB)`);
} }
}); });
@@ -84,7 +85,7 @@ const download = async (relPath, file) => {
} }
missing.add(relPath); missing.add(relPath);
} }
console.log(`[cdn] ${res.status} ${relPath}`); console.log(`[cdn] ${logText(res.status)} ${logText(relPath)}`);
return null; return null;
} }
const body = Buffer.from(await res.arrayBuffer()); const body = Buffer.from(await res.arrayBuffer());
@@ -99,10 +100,10 @@ const download = async (relPath, file) => {
const tmp = `${file}.${process.pid}.tmp`; const tmp = `${file}.${process.pid}.tmp`;
await fs.promises.writeFile(tmp, body); await fs.promises.writeFile(tmp, body);
await fs.promises.rename(tmp, file); await fs.promises.rename(tmp, file);
console.log(`[cdn] cached ${relPath} (${body.length} bytes)`); console.log(`[cdn] cached ${logText(relPath)} (${logText(body.length)} bytes)`);
} }
catch (err) { catch (err) {
console.log(`[cdn] could not cache ${relPath}: ${err.message}`); console.log(`[cdn] could not cache ${logText(relPath)}: ${logText(err.message)}`);
} }
return body; return body;
}; };
@@ -134,7 +135,7 @@ const getExact = async (asked, mayFetch = () => true) => {
// A download that fails (the CDN not answering in time) is "not there" // A download that fails (the CDN not answering in time) is "not there"
// for now, and is tried again the next time the file is asked for. // for now, and is tried again the next time the file is asked for.
inFlight.set(relPath, download(relPath, file).catch(err => { inFlight.set(relPath, download(relPath, file).catch(err => {
console.log(`[cdn] could not fetch ${relPath}: ${err.message}`); console.log(`[cdn] could not fetch ${logText(relPath)}: ${logText(err.message)}`);
return null; return null;
}).finally(() => inFlight.delete(relPath))); }).finally(() => inFlight.delete(relPath)));
} }
@@ -171,4 +172,8 @@ const cached = async asked => {
} }
}; };
module.exports = {get, cached, hashName, hashedPath}; // whether the official CDN said it has no such file (a 404 or 403 when it
// was asked), as against one not asked for yet or not fetched just now.
const knownMissing = asked => missing.has(clean(asked));
module.exports = {get, cached, knownMissing, hashName, hashedPath};
+74
View File
@@ -0,0 +1,74 @@
# The server's chat filter (lib/chatfilter.js): typed chat, Jam-a-Gram
# messages, Jammer Wall posts and bios. A message that breaks a rule here
# reaches nobody, and its sender is told it was not sent (a bio is not
# saved, and one saved before is not shown). Players cannot turn this
# off (unlike the client's own filter). It is read again when this file
# changes: no restart needed.
#
# One rule to a line; lines starting with # are comments. Capitals do not
# matter. Messages are read the way people dodge filters: digits and signs
# standing in for letters (4ss, a$$, n00b), letters drawn out (fuuuck), and
# words spelled out a letter at a time (f u c k, f.u.c.k).
#
# word that word on its own ("ass", not "class" or "assume")
# word* any word starting with it ("fuck*": fucking, fucker)
# *word* any word with it anywhere inside (for words that never
# turn up inside innocent ones)
# two words those words one after the other
# a|b|c any one of them
# a + b a, then b as the very next word
# a .. b a, then b at most 4 words later ("send .. nudes" catches
# "send me some nudes", but not "nudes, send")
# a & b both somewhere in the same message, in any order
# ? any one word (a name: "fuck + ? + ass" catches
# "fuck johns ass")
# !word in a | list: but not this word ("?|!it" is any word
# but "it"). A slot of only these takes up no word:
# "a + !up" is a, not followed by "up" (or ending there)
#
# These combine: "fuck|screw + you|u + in|up + the|your + ass" is one rule.
# Apostrophes are dropped before matching, so write "ill" for "i'll".
# Prefer + over .. and & : the looser the rule, the more ordinary messages it
# catches by accident ("fuck .. you" would also catch "i dont give a fuck
# about you").
# --- Slurs -------------------------------------------------------------------
*nigger*
*faggot*
# --- Sexual talk aimed at someone ---------------------------------------------
# Aimed at anyone: these use ? for the person, so names are caught too.
# "Not a person" words (it, this, up, off...) are left out with !, so
# "gonna fuck this up" and "fuck it" go through.
# "fuck you in the ass", "ill fuck john in the ass", "bang her up the butt".
fuck*|screw|bang|rape*|hump*|pound|breed .. in|up|on + the|your|ur|his|her|their|my|ma|yo|that + ass|butt|booty|pussy|dick|cock|hole|asshole|mouth|throat|vagina
# "fuck johns ass", "fuck your pussy", "eat her pussy".
fuck*|screw|bang|rape*|hump*|pound|breed|eat + ?|!the|!a|!this|!that + ass|butt|booty|pussy|dick|cock|tits|titties|boobs|hole|asshole|vagina|penis|clit
# "fuck pussy", "suck dick", "eat pussy".
fuck*|eat|suck*|lick* + pussy|dick|cock|tits|titties|boobs|clit|penis|vagina|nipples|dih
# "fuck you hard", "ill bang john raw". Plain "fuck you" is an insult and stays.
fuck*|screw|bang|rape*|hump*|pound|breed + ?|!this|!that|!it|!the|!a|!up|!off + hard|harder|raw|deep|senseless
# Saying what you'll do to someone: "ill fuck you", "im gonna fuck john",
# "i wanna bang her". Not "ill fuck him up" (a threat, not sex) or "gonna
# fuck this level up".
ill|imma|ima|gonna|gunna|wanna|lemme|let me|tryna|finna|want to|going to|i will|i want to|i would|id|lets + fuck|screw|bang|rape|hump|breed + ?|!up|!off|!around|!it|!this|!that|!with|!over|!everything|!everyone|!something|!shit|!myself|!yourself|!themselves|!the|!a|!all|!things|!stuff + !up|!off|!over|!shit
# Asking to: "wanna fuck?", "lets bang". Not "wanna fuck around".
wanna|want to|lets|can we|do you want to + fuck|bang|screw + !up|!off|!around|!with|!this|!that|!it|!over|!shit|!things|!everything
# Asking for or offering sex acts: "suck my dick", "lick johns pussy",
# "grab her ass".
suck*|lick*|blow|ride|touch|rub|finger*|jerk|stroke|grab|squeeze + ?|!the|!a|!some|!these|!those|!all + dick|cock|pussy|tits|titties|boobs|balls|ass|butt|booty|nipples|clit|penis|vagina|dih
# Asking for pictures: "send me some nudes", "show me ur tits".
send|show|see|sending|post .. nudes|noods|nude|naked|tits|titties|boobs|pussy|dick|cock|nipples|penis|vagina
# Asking for sex: "wanna have sex", "lets cyber", "sex with john".
wanna|want to|lets|can we|have|having|do you want to + sex|cyber|cybersex|seks|secks
sex|cyber|cybersex + with + ?
sext|sexting|cybersex
# "cum on you", "cum inside her", "nut in ur mouth".
cum|cumming|jizz + on|in|inside|all over + ?
nut|nutting + on|in|inside|all over + you|u|ur|your|my|me|her|his|him|them
# Sex acts and porn words that have no everyday use in this game.
blowjob*|handjob*|rimjob*|deepthroat*|cumshot*|creampie*|gangbang*|threesome*|orgasm*|masturbat*|jerk off|jack off|jerking off|jacking off
porn*|hentai|rule34|r34|onlyfans|nudes|noods|dildo*|vibrator*|horny|hornie|erection|boner
# Roleplay asks: "wanna erp", "dm me for erp".
erp & wanna|want|lets|dm|pm|anyone
+175
View File
@@ -0,0 +1,175 @@
"use strict";
const {logText} = require("./logtext.js");
const fs = require("fs");
const path = require("path");
// the server's own filter for what players write to each other: typed chat,
// Jam-a-Gram messages, Jammer Wall posts and bios. unlike the chat filter in
// the client (the player's to set, or turn off), this one cannot be turned off,
// and what it catches reaches nobody. it is meant to be narrow: slurs, and
// sexual talk aimed at someone, never swearing as such ("fuck" is fine,
// "i'll fuck you in the ass" is not). the rules are lib/chat-filter.txt,
// read again when it changes; the file says how they are written.
const RULES_FILE = path.join(__dirname, "chat-filter.txt");
// for "a .. b": how many words may come between the two ("a + b": none)
const MAX_GAP = 4;
// letters written as digits or signs, as the client's filter reads them
// (AJClient.filterText), plus "@" and "$".
const STAND_INS = {0: "o", 1: "i", 3: "e", 4: "a", 5: "s", 7: "t", "@": "a", $: "s"};
// A letter drawn out three times or more ("fuuuck") is read as the word
// with every run of letters made one, and compared that way: a word written
// plainly is compared as it is ("ass" is not "as").
const squash = word => word.replace(/(.)\1+/g, "$1");
const stretched = word => /(.)\1\1/.test(word);
// the words of a message as compared: small letters, apostrophes dropped
// ("i'll" is "ill"), stand-ins read as the letters they are, split at
// anything else. a word that is only digits is a number and goes. three or
// more single letters in a row ("f u c k", "f.u.c.k") are read as one word.
const wordsOf = text => {
const words = String(text).toLowerCase().replace(/['\u2019`]/g, "")
.split(/[^a-z0-9@$]+/).filter(word => word && !/^\d+$/.test(word))
.map(word => word.replace(/[0-9@$]/g, sign => STAND_INS[sign] || "")).filter(Boolean);
const joined = [];
for (let i = 0; i < words.length;) {
let end = i;
while (end < words.length && words[end].length === 1) {
end++;
}
if (end - i >= 3) {
joined.push(words.slice(i, end).join(""));
i = end;
}
else {
joined.push(words[i]);
i++;
}
}
return joined;
};
// one word of a rule: {text, start, inside, any}. "word" is that word,
// "word*" any word starting with it, "*word*" any word with it anywhere
// inside, "?" any word at all.
const patternOf = token => {
if (token === "?") {
return {any: true};
}
const inside = token.length > 2 && token.startsWith("*") && token.endsWith("*");
const start = !inside && token.endsWith("*");
const text = token.replace(/^\*|\*$/g, "").toLowerCase().replace(/[0-9@$]/g, sign => STAND_INS[sign] || "").replace(/[^a-z]/g, "");
return text ? {text, start, inside} : null;
};
const fits = (word, pattern) => {
if (pattern.any) {
return true;
}
const forms = stretched(word) ? [word, squash(word)] : [word];
const wanted = form => (form === word ? pattern.text : squash(pattern.text));
return forms.some(form => (pattern.inside ? form.includes(wanted(form))
: pattern.start ? form.startsWith(wanted(form)) : form === wanted(form)));
};
// A rule: clauses joined by " & ", all of which must be found in the
// message; a clause: slots in order, joined by " + " (the next word) or
// " .. " (at most MAX_GAP words later), each slot {choices, gap}, its gap
// being how far after the one before it may start; a slot's choices are
// joined by "|", and a choice is one word, or words that follow each other.
// a choice written "!word" is one the slot must not be: "?|!it" is any word
// but "it". A slot of only those takes up no word: "a + !up" is "a", not
// followed by "up" (or at the end of the message).
const parse = line => line.split(/\s+&\s+/).map(clause => {
const parts = clause.split(/\s+(\.\.|\+)\s+/);
const slots = [];
for (let i = 0; i < parts.length; i += 2) {
const written = parts[i].split("|").map(choice => choice.trim());
const wordsIn = list => list.map(choice => choice.split(/\s+/).map(patternOf)).filter(choice => choice.length > 0 && choice.every(Boolean));
const choices = wordsIn(written.filter(choice => !choice.startsWith("!")));
const not = wordsIn(written.filter(choice => choice.startsWith("!")).map(choice => choice.slice(1)));
slots.push({choices, not, gap: parts[i - 1] === "+" ? 0 : MAX_GAP});
}
return slots;
});
// where in `words` a slot's choice starts at `at`: the index after it, or -1.
const startsWith = (words, at, choice) => at + choice.length <= words.length && choice.every((pattern, i) => fits(words[at + i], pattern));
const slotAt = (words, at, slot) => {
if (slot.not.some(choice => startsWith(words, at, choice))) {
return -1;
}
for (const choice of slot.choices) {
if (startsWith(words, at, choice)) {
return at + choice.length;
}
}
return -1;
};
const clauseFrom = (words, slots, from, to) => {
if (slots.length === 0) {
return true;
}
if (slots[0].choices.length === 0) {
return !slots[0].not.some(choice => startsWith(words, from, choice)) && clauseFrom(words, slots.slice(1), from, from + (slots.length > 1 ? slots[1].gap : 0));
}
for (let at = from; at <= Math.min(to, words.length - 1); at++) {
const end = slotAt(words, at, slots[0]);
if (end !== -1 && clauseFrom(words, slots.slice(1), end, end + (slots.length > 1 ? slots[1].gap : 0))) {
return true;
}
}
return false;
};
let kept = {mtime: -1, rules: []};
const rules = () => {
let mtime = 0;
try {
mtime = fs.statSync(RULES_FILE).mtimeMs;
}
catch (err) {
return [];
}
if (kept.mtime !== mtime) {
const lines = fs.readFileSync(RULES_FILE, "utf8").split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith("#"));
const parsed = [];
for (const line of lines) {
const clauses = parse(line);
if (clauses.every(clause => clause.length > 0 && clause.every(slot => slot.choices.length > 0 || slot.not.length > 0) && clause[0].choices.length > 0)) {
parsed.push({line, clauses});
}
else {
console.log(`[filter] lib/chat-filter.txt: a rule that could not be read was left out: ${logText(line)}`);
}
}
kept = {mtime, rules: parsed};
console.log(`[filter] ${logText(parsed.length)} rules`);
}
return kept.rules;
};
// the rule a message breaks (its line in the file), or null.
const broken = text => {
const words = wordsOf(text);
if (words.length === 0) {
return null;
}
const rule = rules().find(candidate => candidate.clauses.every(clause => clauseFrom(words, clause, 0, words.length - 1)));
return rule ? rule.line : null;
};
// the game's own warning screen, over the game, for ten seconds
// (FacilitatorXtCommManager, "fw" of facilitatorDisciplineResponse). its
// kind picks the picture and the words: 3 "Personal Information", 5
// "Bullying", 11 "Scamming", 0 a short "Inappropriate Chat", and this one
// "Inappropriate Behavior" with the game's own text ("It looks like the
// conversation you're having isn't appropriate..."). it also lets go of
// the sender's chat bubble that waits for the line.
const WARNING_BEHAVIOR = 4;
const warn = session => session.sendXt("fd", -1, "fw", WARNING_BEHAVIOR);
module.exports = {broken, warn, wordsOf};
+68 -11
View File
@@ -3,7 +3,8 @@
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const config = require("../config.js"); const config = require("../config.js");
// what players typed: chat in a room, and whispers. kept for the moderator // what players typed: chat in a room, whispers, Jam-a-Grams and posts on
// each other's Jammer Walls. kept for the moderator
// panel (lib/modpanel.js), which is where a moderator reads what was said // panel (lib/modpanel.js), which is where a moderator reads what was said
// before deciding anything; nothing else reads it. lines older than // before deciding anything; nothing else reads it. lines older than
// config.chatLogDays are deleted, and an account's lines go when the // config.chatLogDays are deleted, and an account's lines go when the
@@ -26,6 +27,11 @@ const SCHEMA = `
const CHAT = "chat"; const CHAT = "chat";
const WHISPER = "whisper"; const WHISPER = "whisper";
const JAMAGRAM = "jamagram";
const WALL = "wall";
const KINDS = [CHAT, WHISPER, JAMAGRAM, WALL];
// what the server's filter kept from being sent is kept with this in front.
const NOT_SENT = "(not sent) ";
const DAY_SECONDS = 86400; const DAY_SECONDS = 86400;
const MAX_TEXT = 600; const MAX_TEXT = 600;
const PAGE = 100; const PAGE = 100;
@@ -40,28 +46,69 @@ const prune = () => {
const load = () => { const load = () => {
db().exec(SCHEMA); db().exec(SCHEMA);
// lines the filter stopped are marked, and found by a small index of their own.
if (!db().prepare("PRAGMA table_info(chat_log)").all().some(column => column.name === "stopped")) {
db().exec("ALTER TABLE chat_log ADD COLUMN stopped INTEGER NOT NULL DEFAULT 0");
db().prepare("UPDATE chat_log SET stopped = 1 WHERE substr(text, 1, ?) = ?").run(NOT_SENT.length, NOT_SENT);
}
db().exec("CREATE INDEX IF NOT EXISTS chat_log_stopped ON chat_log (at) WHERE stopped = 1");
prune(); prune();
setInterval(prune, DAY_SECONDS * 1000 / 4).unref(); setInterval(prune, DAY_SECONDS * 1000 / 4).unref();
}; };
const stoppedFlag = text => (String(text).startsWith(NOT_SENT) ? 1 : 0);
// A line said in `room` (its name as the world knows it), or with `to` a // A line said in `room` (its name as the world knows it), or with `to` a
// whisper to that player. // whisper to that player.
const record = (account, room, text, to = "") => { const record = (account, room, text, to = "") => {
if (config.chatLogDays <= 0) { if (config.chatLogDays <= 0) {
return; return;
} }
db().prepare("INSERT INTO chat_log (at, account_id, username, room, kind, to_name, text) VALUES (?, ?, ?, ?, ?, ?, ?)") db().prepare("INSERT INTO chat_log (at, account_id, username, room, kind, to_name, text, stopped) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
.run(now(), account.id, account.username, String(room || ""), to ? WHISPER : CHAT, to, String(text).slice(0, MAX_TEXT)); .run(now(), account.id, account.username, String(room || ""), to ? WHISPER : CHAT, to, String(text).slice(0, MAX_TEXT), stoppedFlag(text));
}; };
const row = line => ({id: line.id, at: line.at, username: line.username, room: line.room, whisperTo: line.kind === WHISPER ? line.to_name : "", text: line.text}); // A Jam-a-Gram's words (`kind` JAMAGRAM), or a post on a Jammer Wall
// (WALL): `to` is who it was sent to, or whose wall it is.
const recordTo = (account, kind, to, text) => {
if (config.chatLogDays <= 0 || !KINDS.includes(kind)) {
return;
}
db().prepare("INSERT INTO chat_log (at, account_id, username, room, kind, to_name, text, stopped) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
.run(now(), account.id, account.username, "", kind, String(to || ""), String(text).slice(0, MAX_TEXT), stoppedFlag(text));
};
const row = line => ({id: line.id, at: line.at, username: line.username, room: line.room, kind: line.kind, to: line.to_name,
whisperTo: line.kind === WHISPER ? line.to_name : "", text: line.text});
// lines newest first, a page at a time: by who said them (or was whispered // lines newest first, a page at a time: by who said them (or was whispered
// to), by room, by words in them, and `before` an id for the next page. // to, or sent to), by room, by words in them, by kind (one of KINDS, or
const search = ({username = "", room = "", text = "", before = 0}) => { // "notsent" for what the filter stopped), from `until` (seconds) back, and
// `before` an id for the next page. `direction` narrows the username to
// what they sent ("sent") or what was sent to them ("received").
const search = ({username = "", room = "", text = "", kind = "", direction = "", until = 0, before = 0}) => {
const where = []; const where = [];
const values = []; const values = [];
if (username) { if (KINDS.includes(kind)) {
where.push("kind = ?");
values.push(kind);
}
else if (kind === "notsent") {
where.push("stopped = 1");
}
if (until > 0) {
where.push("at <= ?");
values.push(Math.floor(until));
}
if (username && direction === "sent") {
where.push("username = ? COLLATE NOCASE");
values.push(username);
}
else if (username && direction === "received") {
where.push("to_name = ? COLLATE NOCASE");
values.push(username);
}
else if (username) {
where.push("(username = ? COLLATE NOCASE OR to_name = ? COLLATE NOCASE)"); where.push("(username = ? COLLATE NOCASE OR to_name = ? COLLATE NOCASE)");
values.push(username, username); values.push(username, username);
} }
@@ -87,9 +134,9 @@ const around = id => {
if (!line) { if (!line) {
return null; return null;
} }
const [same, values] = line.kind === WHISPER const [same, values] = line.kind === CHAT
? ["kind = ? AND ((username = ? AND to_name = ?) OR (username = ? AND to_name = ?))", [WHISPER, line.username, line.to_name, line.to_name, line.username]] ? ["kind = ? AND room = ?", [CHAT, line.room]]
: ["kind = ? AND room = ?", [CHAT, line.room]]; : ["kind = ? AND ((username = ? AND to_name = ?) OR (username = ? AND to_name = ?))", [line.kind, line.username, line.to_name, line.to_name, line.username]];
const earlier = db().prepare(`SELECT * FROM chat_log WHERE ${same} AND id < ? ORDER BY id DESC LIMIT ?`).all(...values, line.id, AROUND).reverse(); const earlier = db().prepare(`SELECT * FROM chat_log WHERE ${same} AND id < ? ORDER BY id DESC LIMIT ?`).all(...values, line.id, AROUND).reverse();
const later = db().prepare(`SELECT * FROM chat_log WHERE ${same} AND id > ? ORDER BY id LIMIT ?`).all(...values, line.id, AROUND); const later = db().prepare(`SELECT * FROM chat_log WHERE ${same} AND id > ? ORDER BY id LIMIT ?`).all(...values, line.id, AROUND);
return {line: row(line), lines: [...earlier, line, ...later].map(row)}; return {line: row(line), lines: [...earlier, line, ...later].map(row)};
@@ -99,9 +146,19 @@ const around = id => {
// of their data a player may ask for (lib/manage.js). // of their data a player may ask for (lib/manage.js).
const saidBy = account => db().prepare("SELECT * FROM chat_log WHERE account_id = ? ORDER BY id").all(account.id).map(row); const saidBy = account => db().prepare("SELECT * FROM chat_log WHERE account_id = ? ORDER BY id").all(account.id).map(row);
// how many of an account's lines the server's filter stopped, in the last
// `days` days.
const notSentCount = (account, days) => db().prepare("SELECT COUNT(*) AS n FROM chat_log WHERE account_id = ? AND at > ? AND stopped = 1")
.get(account.id, now() - days * DAY_SECONDS).n;
// those the filter stopped most often in the last `days` days: [{username, count, last}].
const mostStopped = (days, limit) => db().prepare(`SELECT username, COUNT(*) AS count, MAX(at) AS last FROM chat_log
WHERE stopped = 1 AND at > ? GROUP BY account_id ORDER BY count DESC LIMIT ?`)
.all(now() - days * DAY_SECONDS, limit).map(entry => ({username: entry.username, count: entry.count, last: entry.last}));
// an account being deleted: what it said goes with it. // an account being deleted: what it said goes with it.
const forget = account => { const forget = account => {
db().prepare("DELETE FROM chat_log WHERE account_id = ?").run(account.id); db().prepare("DELETE FROM chat_log WHERE account_id = ?").run(account.id);
}; };
module.exports = {load, record, search, around, saidBy, forget, PAGE}; module.exports = {load, record, recordTo, search, around, saidBy, notSentCount, mostStopped, forget, PAGE, JAMAGRAM, WALL, NOT_SENT};
+61
View File
@@ -0,0 +1,61 @@
"use strict";
// typed chat made fit to read before anyone sees it (lib/world.js, pubMsg):
// not a filter of what is said (that is lib/chatfilter.js) but of how much
// of it there is. a key held down ("aaaaaaaaaa..."), a word said over and
// over, one long run of letters with no space, a line all in capitals, a
// wall of emoji: each is cut down, and the line still goes. the same line
// said again and again in a short while does not.
const MAX_RUN = 5; // the same character this many times at most ("nooooo")
const MAX_REPEAT = 4; // the same word or emoji this many times in a row
const MAX_WORD = 32; // letters with no space between
const MAX_EMOJI = 12; // emoji in a line ("\{1f600}", as the client sends them)
const SHOUT_LENGTH = 12; // a line this long or more ...
const SHOUT_SHARE = 0.7; // ... with this share of its letters capitals is lowered
const REPEAT_LINES = 3; // the last few lines a player said ...
const REPEAT_MS = 20000; // ... within this long: one of those again is not sent
const EMOJI = /\\\{[0-9a-f]{2,6}(?:-[0-9a-f]{2,6}){0,9}\}/g;
// the line made tidy. emoji tags count as one character each here.
const tidy = text => {
// every emoji as one character for now (a private-use one), so that the
// rules below see it as one: put back at the end
const emoji = [];
let line = String(text).replace(EMOJI, tag => {
emoji.push(tag);
return String.fromCharCode(0xE000);
});
// a character held down (not a digit: "1000000" is a number)
line = line.replace(new RegExp(`(.)\\1{${MAX_RUN},}`, "gu"), (run, char) => (/\d/.test(char) ? run : char.repeat(MAX_RUN)));
// one long run with no space
line = line.split(" ").map(word => (word.length > MAX_WORD ? word.slice(0, MAX_WORD) : word)).join(" ");
// the same word (or emoji) over and over: in a row, with or without spaces
line = line.replace(new RegExp(`((?:\\S+?)\\s*)\\1{${MAX_REPEAT},}`, "giu"), (run, once) => (/\d/.test(once) ? run : once.repeat(MAX_REPEAT)));
// shouting
const letters = line.replace(/[^A-Za-z]/g, "");
if (letters.length >= SHOUT_LENGTH && letters.replace(/[^A-Z]/g, "").length / letters.length >= SHOUT_SHARE) {
line = line.toLowerCase();
}
// the emoji back, no more than MAX_EMOJI of them
let kept = 0;
let at = 0;
line = line.replace(new RegExp(String.fromCharCode(0xE000), "g"), () => {
const tag = emoji[at++];
return kept++ < MAX_EMOJI ? tag : "";
});
return line.replace(/\s{2,}/g, " ").trim();
};
// was this line said by them just now (one of their last few, a short while
// ago)? kept on the session, as recentChat is.
const repeated = (session, line) => {
const now = Date.now();
const said = (session.saidLately || []).filter(entry => now - entry.at < REPEAT_MS);
const again = said.some(entry => entry.line.toLowerCase() === line.toLowerCase());
session.saidLately = [...said, {line, at: now}].slice(-REPEAT_LINES);
return again;
};
module.exports = {tidy, repeated};
+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};
+6 -2
View File
@@ -1,5 +1,6 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
// custom colours. the game stores a colour as four palette indexes packed in // custom colours. the game stores a colour as four palette indexes packed in
@@ -29,7 +30,7 @@ const load = () => {
entries.set(row.id, row.rgb.split(",").map(Number)); entries.set(row.id, row.rgb.split(",").map(Number));
nextId = Math.max(nextId, row.id + 1); nextId = Math.max(nextId, row.id + 1);
} }
console.log(`[colours] ${entries.size} custom colours`); console.log(`[colours] ${logText(entries.size)} custom colours`);
}; };
const valid = rgbs => rgbs.length === 4 && rgbs.every(value => Number.isInteger(value) && value >= 0 && value <= MAX_RGB); const valid = rgbs => rgbs.length === 4 && rgbs.every(value => Number.isInteger(value) && value >= 0 && value <= MAX_RGB);
@@ -70,4 +71,7 @@ const chunks = (size = 200) => {
// the custom range), or an entry of the table? // the custom range), or an entry of the table?
const known = id => id < CUSTOM_BASE || id > MAX_ID || entries.has(id); const known = id => id < CUSTOM_BASE || id > MAX_ID || entries.has(id);
module.exports = {load, allocate, chunks, known, count: () => entries.size}; // the four RGB values of an entry, or null.
const rgbsOf = id => entries.get(id) || null;
module.exports = {CUSTOM_BASE, load, allocate, chunks, known, rgbsOf, count: () => entries.size};
+523 -24
View File
@@ -2,10 +2,16 @@
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const chatlog = require("./chatlog.js"); const chatlog = require("./chatlog.js");
const customItems = require("./customitems.js");
const itemControl = require("./itemcontrol.js");
const wearRules = require("./wearrules.js");
const modNotes = require("./modnotes.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const disguises = require("./disguises.js"); const disguises = require("./disguises.js");
const dens = require("./dens.js"); const dens = require("./dens.js");
const {isSilenced} = require("./moderation.js"); const {isSilenced} = require("./moderation.js");
const modlog = require("./modlog.js");
const roles = require("./roles.js");
const {MAX_DEN_ITEMS, MAX_WORN, activeAvatar, wornItems} = require("./player.js"); const {MAX_DEN_ITEMS, MAX_WORN, activeAvatar, wornItems} = require("./player.js");
// things players can do by typing "!something" in the chat box, for what // things players can do by typing "!something" in the chat box, for what
@@ -47,7 +53,7 @@ const MAX_AGAIN = 100;
// A hosted party's own name is three string ids, no use outside the game. // A hosted party's own name is three string ids, no use outside the game.
const roomTitle = room => (room.partyHost ? `${room.partyHost.username}'s party` : room.displayName); const roomTitle = room => (room.partyHost ? `${room.partyHost.username}'s party` : room.displayName);
module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideBlocked, refreshForOthers, travel, reloadRoom, buyAgain, ask}) => { module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideBlocked, refreshForOthers, travel, reloadRoom, buyAgain, ask, staffMove, setInvisible, staffModeration}) => {
// A plain message box with an OK button. // A plain message box with an OK button.
const tell = (session, text) => session.sendXt("xtl", -1, String(text).replace(/%/g, " percent")); const tell = (session, text) => session.sendXt("xtl", -1, String(text).replace(/%/g, " percent"));
@@ -68,7 +74,10 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
const {account} = session; const {account} = session;
const avatar = activeAvatar(account); const avatar = activeAvatar(account);
const before = wornItems(account, avatar); const before = wornItems(account, avatar);
const wanted = account.items.filter(item => invs.includes(item.inv)).slice(0, MAX_WORN); // Saved outfits are a second equip route, so they obey the same rule as
// the item editor. A saved id remains in the outfit in case staff later
// remove the rule; it simply cannot be put on while blocked.
const wanted = account.items.filter(item => invs.includes(item.inv) && wearRules.mayWear(item.def, avatar.type)).slice(0, MAX_WORN);
const takenOff = before.filter(item => !wanted.includes(item)); const takenOff = before.filter(item => !wanted.includes(item));
account.outfitUndo = {avInvId: avatar.avInvId, items: before.map(item => item.inv)}; account.outfitUndo = {avInvId: avatar.avInvId, items: before.map(item => item.inv)};
for (const item of takenOff) { for (const item of takenOff) {
@@ -79,7 +88,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
item.on.push(avatar.avInvId); item.on.push(avatar.avInvId);
} }
} }
accounts.save(); accounts.save(account);
// ItemXtCommManager.itemsChangedListResponse, "3" = what is worn // ItemXtCommManager.itemsChangedListResponse, "3" = what is worn
// changed: [3, inUse, perUserAvId, username, colour, onCount, // changed: [3, inUse, perUserAvId, username, colour, onCount,
// offCount, (invIdx, defId)..., offInvIdx...] // offCount, (invIdx, defId)..., offInvIdx...]
@@ -131,7 +140,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
} }
const items = wornItems(account, avatar).map(item => item.inv); const items = wornItems(account, avatar).map(item => item.inv);
account.outfits = [...account.outfits.filter(entry => entry !== existing), {name, items}]; account.outfits = [...account.outfits.filter(entry => entry !== existing), {name, items}];
accounts.save(); accounts.save(account);
tell(session, `Outfit ${name} saved (${items.length} items).`); tell(session, `Outfit ${name} saved (${items.length} items).`);
return; return;
} }
@@ -152,7 +161,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
return; return;
} }
account.outfits = account.outfits.filter(entry => entry.name !== name); account.outfits = account.outfits.filter(entry => entry.name !== name);
accounts.save(); accounts.save(account);
tell(session, `Outfit ${name} deleted.`); tell(session, `Outfit ${name} deleted.`);
return; return;
case "list": case "list":
@@ -166,22 +175,22 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
const activeDenDef = account => (account.dens.find(den => den.inv === account.activeDen) || account.dens[0]).def; const activeDenDef = account => (account.dens.find(den => den.inv === account.activeDen) || account.dens[0]).def;
const layoutOf = owner => owner.denItems const layoutOf = owner => owner.denItems
.filter(item => item.placed && item.den === owner.activeDen) .filter(item => dens.spotOf(item, owner.activeDen))
.map(item => ({def: item.def, version: item.version, x: item.x, y: item.y, flip: item.flip})); .map(item => ({def: item.def, version: item.version, ...dens.spotOf(item, owner.activeDen)}));
// lays the account's den in use out as `layout` says, with its own items. // lays the account's den in use out as `layout` says, with its own items
// with `giveMissing`, items it lacks are added to its inventory first. // (whether or not they stand in other dens too). with `giveMissing`, items
// returns how many of the layout's items could not be placed. // it lacks are added to its inventory first. returns how many of the
// layout's items could not be placed.
const applyLayout = (session, layout, giveMissing) => { const applyLayout = (session, layout, giveMissing) => {
const {account} = session; const {account} = session;
for (const item of account.denItems.filter(candidate => candidate.den === account.activeDen)) { for (const item of account.denItems.filter(candidate => dens.spotOf(candidate, account.activeDen))) {
item.placed = false; delete item.spots[account.activeDen];
item.x = item.y = item.flip = 0;
} }
const used = new Set(); const used = new Set();
let missing = 0; let missing = 0;
for (const spot of layout) { for (const spot of layout) {
let item = account.denItems.find(candidate => !used.has(candidate) && !candidate.placed let item = account.denItems.find(candidate => !used.has(candidate)
&& candidate.def === spot.def && candidate.version === spot.version); && candidate.def === spot.def && candidate.version === spot.version);
if (!item && giveMissing && account.denItems.length < MAX_DEN_ITEMS && defpacks.denItemIds().includes(spot.def)) { if (!item && giveMissing && account.denItems.length < MAX_DEN_ITEMS && defpacks.denItemIds().includes(spot.def)) {
item = dens.giveDenItem(account, spot.def, spot.version); item = dens.giveDenItem(account, spot.def, spot.version);
@@ -191,9 +200,10 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
continue; continue;
} }
used.add(item); used.add(item);
Object.assign(item, {placed: true, den: account.activeDen, x: spot.x, y: spot.y, flip: spot.flip}); item.spots = item.spots || {};
item.spots[account.activeDen] = {cat: spot.cat || 1, x: spot.x, y: spot.y, flip: spot.flip};
} }
accounts.save(); accounts.save(account);
dens.sendDenItems(session); dens.sendDenItems(session);
const room = session.room && session.room.denOwner === account ? session.room : null; const room = session.room && session.room.denOwner === account ? session.room : null;
for (const occupant of room ? room.sessions : []) { for (const occupant of room ? room.sessions : []) {
@@ -216,7 +226,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
} }
const items = layoutOf(account); const items = layoutOf(account);
account.denLayouts = [...account.denLayouts.filter(entry => entry !== existing), {name, den: activeDenDef(account), items}]; account.denLayouts = [...account.denLayouts.filter(entry => entry !== existing), {name, den: activeDenDef(account), items}];
accounts.save(); accounts.save(account);
tell(session, `Den layout ${name} saved (${items.length} items).`); tell(session, `Den layout ${name} saved (${items.length} items).`);
return; return;
} }
@@ -265,7 +275,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
} }
const missing = applyLayout(session, undo.items, false); const missing = applyLayout(session, undo.items, false);
account.denUndo = null; account.denUndo = null;
accounts.save(); accounts.save(account);
tell(session, missing ? `Your den is back as it was, apart from ${missing} items that are no longer yours.` : "Your den is back as it was."); tell(session, missing ? `Your den is back as it was, apart from ${missing} items that are no longer yours.` : "Your den is back as it was.");
return; return;
} }
@@ -275,7 +285,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
return; return;
} }
account.denLayouts = account.denLayouts.filter(entry => entry.name !== name); account.denLayouts = account.denLayouts.filter(entry => entry.name !== name);
accounts.save(); accounts.save(account);
tell(session, `Den layout ${name} deleted.`); tell(session, `Den layout ${name} deleted.`);
return; return;
case "list": case "list":
@@ -372,7 +382,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
const themes = require("../config.js").themes; const themes = require("../config.js").themes;
if (action === "random" && (choice === "on" || choice === "off")) { if (action === "random" && (choice === "on" || choice === "off")) {
account.randomTheme = choice === "on"; account.randomTheme = choice === "on";
accounts.save(); accounts.save(account);
tell(session, account.randomTheme ? "The lands get a look picked at random each time you log in." : "The lands keep the look you choose."); tell(session, account.randomTheme ? "The lands get a look picked at random each time you log in." : "The lands keep the look you choose.");
} }
else if (action === "here" && session.room && !session.room.denOwner && (choice === "off" || Object.hasOwn(themes, choice))) { else if (action === "here" && session.room && !session.room.denOwner && (choice === "off" || Object.hasOwn(themes, choice))) {
@@ -382,7 +392,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
else { else {
account.roomThemes[session.room.base] = choice; account.roomThemes[session.room.base] = choice;
} }
accounts.save(); accounts.save(account);
reloadRoom(session); reloadRoom(session);
} }
else if (action === "list") { else if (action === "list") {
@@ -402,7 +412,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
} }
const before = account.ecards.length; const before = account.ecards.length;
account.ecards = account.ecards.filter(card => !card.read || card.gift); account.ecards = account.ecards.filter(card => !card.read || card.gift);
accounts.save(); accounts.save(account);
tell(session, `${before - account.ecards.length} read Jam-A-Grams deleted. Open your mail again to see.`); tell(session, `${before - account.ecards.length} read Jam-A-Grams deleted. Open your mail again to see.`);
}, },
@@ -481,7 +491,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
} }
else if (wanted.toLowerCase() === "off") { else if (wanted.toLowerCase() === "off") {
delete account.denNames[account.activeDen]; delete account.denNames[account.activeDen];
accounts.save(); accounts.save(account);
tell(session, "This den has its usual name again."); tell(session, "This den has its usual name again.");
} }
else if (isSilenced(account)) { else if (isSilenced(account)) {
@@ -492,13 +502,498 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
} }
else { else {
account.denNames[account.activeDen] = wanted; account.denNames[account.activeDen] = wanted;
accounts.save(); accounts.save(account);
tell(session, `This den is now called ${wanted}. It shows the next time someone walks in.`); tell(session, `This den is now called ${wanted}. It shows the next time someone walks in.`);
} }
}, },
}; };
// ---- staff commands (lib/roles.js). each checks the role's permission on
// every use, and what is done is written down under the staff member's
// name, as in the moderator panel. to anyone without the permission they
// are plain chat, like any other "!word" the server does not know.
const MAX_STAFF_HOURS = 24 * 365 * 10;
const MAX_WARNING = 200;
const MAX_WARNINGS_SHOWN = 5;
const MAX_ITEMS_LISTED = 8;
const MAX_NOTES_SHOWN = 5; // "!notes": the latest, in one message box
const staffMay = (session, permission) => {
const moderation = staffModeration();
return roles.can(session.account, permission, moderation.banRemaining(session.account) !== 0);
};
// the longest run of leading words naming an online player, and the words
// after it: usernames may have spaces in them.
const splitName = words => {
for (let count = words.length; count > 0; count--) {
const target = findOnline(words.slice(0, count).join(" "));
if (target) {
return {target, rest: words.slice(count)};
}
}
return {target: null, rest: words};
};
// the same for any account, online or not.
const splitAccount = words => {
for (let count = words.length; count > 0; count--) {
const account = accounts.byName(words.slice(0, count).join(" "));
if (account) {
return account;
}
}
return null;
};
// finds the player the command is about, and checks the staff member may
// act on them (`onStaff`: also on staff below their rank).
const withTarget = (session, words, usage, onStaff, run) => {
const {target, rest} = splitName(words);
if (!words.length) {
tell(session, usage);
}
else if (!target) {
tell(session, `${words.join(" ")} is not online.`);
}
else if (target === session) {
tell(session, "That is you.");
}
else if (onStaff && !roles.outranks(session.account, target.account)) {
tell(session, "Staff of your rank or above are for someone higher up to deal with.");
}
else {
run(target, rest);
}
};
const logged = (session, action, target, detail = "") =>
modlog.record(session.account.username, `${action} (in game)`, target.account.username, detail);
// what lib/itemcontrol.js tells about items taken.
const worldForItems = {itemsTaken: (...args) => require("./world.js").itemsTaken(...args)};
const lockCommand = (session, words, locked) => {
const [kind, id] = [(words[0] || "").toLowerCase(), words[1]];
if (words.length !== 2) {
tell(session, `Use: !${locked ? "lock" : "unlock"} clothing|den ID`);
return;
}
const result = itemControl.setLocked(kind, id, locked);
tell(session, result.error || result.ok);
if (result.ok) {
modlog.record(session.account.username, locked ? "item locked (in game)" : "item unlocked (in game)", "", `${kind} ${id}`);
}
};
// an account named by the first words (a name may have spaces: the longest
// that is one), and the words after it.
const accountAndRest = words => {
for (let count = words.length; count > 0; count--) {
const account = accounts.byName(words.slice(0, count).join(" "));
if (account) {
return {account, rest: words.slice(count)};
}
}
return {account: null, rest: words};
};
const staffCommands = {
// A short-lived room control for owners, admins and developers. It uses
// the avatar protocol rather than persisting any player appearance.
roomfx: {
permission: "room.effects",
run(session, words) {
const room = session.room;
const effect = (words[0] || "").toLowerCase();
if (!room || !["small", "normal", "big", "rainbow", "clear"].includes(effect)) {
tell(session, "Use: !roomfx small, !roomfx normal, !roomfx big, !roomfx rainbow, or !roomfx clear");
return;
}
const send = (type, value) => {
for (const target of room.sessions) {
for (const viewer of room.sessions) {
viewer.sendXt("uc", room.id, target.id, String(value), type);
}
}
};
const stopRainbow = () => {
if (room.roomEffectTimer) {
clearInterval(room.roomEffectTimer);
delete room.roomEffectTimer;
}
};
if (effect === "rainbow") {
stopRainbow();
let hue = 0;
room.roomEffectTimer = setInterval(() => {
if (room.sessions.size === 0) {
stopRainbow();
return;
}
const colour = [0xFF4040, 0xFFB340, 0xF8FF40, 0x50E860, 0x40CFFF, 0x7560FF, 0xDC55FF][hue++ % 7];
send(8, colour);
}, 350);
room.roomEffectTimer.unref();
tell(session, "Rainbow effect started for everyone in this room. !roomfx clear stops it.");
}
else {
stopRainbow();
if (effect === "small" || effect === "big" || effect === "normal") {
send(14, effect === "small" ? 0.7 : effect === "big" ? 1.35 : 1);
tell(session, `Everyone in this room is now ${effect === "normal" ? "normal size" : effect}.`);
}
else {
send(8, 0);
send(14, 1);
tell(session, "Room effects cleared.");
}
}
modlog.record(session.account.username, "room effect (in game)", "", `${effect}: ${roomTitle(room)}`);
},
},
// "!item clothing|den ID NAME": a new item made from the game's item ID
// (lib/customitems.js), free, every colour of the one it is made from;
// everyone has it at once. the moderator panel's Items page does more.
// "!item list": the latest made.
item: {
permission: "items.create",
run(session, words) {
const usage = "Use: !item clothing|den ID NAME, or !item list";
if ((words[0] || "").toLowerCase() === "list") {
const latest = customItems.list().slice(0, MAX_ITEMS_LISTED)
.map(entry => `${entry.id} ${entry.name} (${entry.kind === "den" ? "den" : "clothing"}${entry.inShop ? "" : ", off sale"})`);
tell(session, latest.length ? `Latest items made: ${latest.join("; ")}` : "No items made yet.");
return;
}
const kind = (words[0] || "").toLowerCase();
if (!customItems.KINDS.includes(kind) || !/^\d+$/.test(words[1] || "") || words.length < 3) {
tell(session, usage);
return;
}
const result = customItems.create(kind, {base: words[1], name: words.slice(2).join(" ")}, session.account.username);
if (result.error) {
tell(session, result.error);
return;
}
const {item} = result;
tell(session, `Made ${item.name}, ${kind === "den" ? "den item" : "clothing"} ${item.id}. It is in the item finder now.`);
modlog.record(session.account.username, "item made (in game)", "", `${kind} ${item.id} ${item.name}`);
},
},
staff: {
permission: "staff.list",
run(session) {
const on = players().filter(other => roles.isActiveStaff(other.account))
.map(other => `${other.account.username} (${roles.ROLES[roles.roleOf(other.account)].label})`);
tell(session, on.length ? `Staff online: ${on.join(", ")}` : "No staff online.");
},
},
// Opens the same in-game moderation window as a player's card. This is
// useful when a moderator already knows the name and does not need to
// hunt through search results first.
mod: {
permission: "player.view",
run(session, words) {
const target = words.length ? findOnline(words.join(" ")) : null;
if (!target) {
tell(session, words.length ? `${words.join(" ")} is not online.` : "Use: !mod PLAYER");
return;
}
if (target.account !== session.account && roles.roleOf(target.account) && !roles.outranks(session.account, target.account)) {
tell(session, "Staff of your rank or above are for someone higher up to deal with.");
return;
}
session.sendXt("xui", -1, "moderate", target.account.username);
},
},
// Owners, admins and developers get the room-effects panel from chat.
// `host` is an intuitive alias for event hosts.
event: {
permission: "room.effects",
run(session) {
session.sendXt("xui", -1, "event");
},
},
host: {
permission: "room.effects",
run(session) {
session.sendXt("xui", -1, "event");
},
},
// "!note PLAYER text": a note for the other staff (lib/modnotes.js),
// never shown to the player. "!notes PLAYER": the latest few.
note: {
permission: "player.view",
run(session, words) {
const {account, rest} = accountAndRest(words);
if (!account || !rest.length) {
tell(session, account || !words.length ? "Use: !note PLAYER text" : `No player called ${words[0]}.`);
return;
}
if (account === session.account) {
tell(session, "That is you.");
return;
}
if (roles.roleOf(account) && !roles.outranks(session.account, account)) {
tell(session, "Staff of your rank or above are for someone higher up to deal with.");
return;
}
const result = modNotes.add(account, session.account.username, rest.join(" "));
if (result.error) {
tell(session, result.error);
return;
}
tell(session, `Note on ${account.username} added.`);
modlog.record(session.account.username, "note (in game)", account.username, result.note.text);
},
},
notes: {
permission: "player.view",
run(session, words) {
const account = words.length ? accounts.byName(words.join(" ")) : null;
if (!account) {
tell(session, words.length ? `No player called ${words.join(" ")}.` : "Use: !notes PLAYER");
return;
}
const latest = modNotes.list(account).slice(0, MAX_NOTES_SHOWN)
.map(note => `${new Date(note.at * 1000).toISOString().slice(0, 10)} ${note.by}: ${note.text}`);
tell(session, latest.length ? `Notes on ${account.username}: ${latest.join(" | ")}` : `No notes on ${account.username}.`);
},
},
// "!invisible": unseen by players in every room until said again (staff
// still see them), as the game's own moderators could be.
invisible: {
permission: "staff.invisible",
run(session) {
setInvisible(session, !session.invisible);
},
},
reject: {
permission: "player.names",
run(session, words) {
withTarget(session, words, "Use: !reject PLAYER", true, target => {
if (target.account.nameRejected) {
tell(session, `${target.account.username}'s name is already rejected.`);
return;
}
staffModeration().actions.rejectName(target.account, session.account.username);
tell(session, `${target.account.username} was signed out and must choose a new name.`);
logged(session, "rejected username", target);
});
},
},
// "!lock clothing|den ID", "!unlock clothing|den ID", "!locked": items
// kept out of the item finder for players (lib/itemcontrol.js).
lock: {
permission: "items.create",
run(session, words) {
lockCommand(session, words, true);
},
},
unlock: {
permission: "items.create",
run(session, words) {
lockCommand(session, words, false);
},
},
locked: {
permission: "items.create",
run(session) {
const list = itemControl.lockedList().slice(0, MAX_ITEMS_LISTED)
.map(entry => `${entry.kind} ${entry.id} ${entry.name || "(no name)"}`);
tell(session, list.length ? `Locked out of the item finder: ${list.join("; ")}` : "Nothing is locked out of the item finder.");
},
},
// "!take PLAYER clothing|den ID": every one of that item, out of their
// inventory, online or not.
take: {
permission: "items.create",
run(session, words) {
const usage = "Use: !take PLAYER clothing|den ID";
// the name may have spaces: the kind and the id are the last two words.
const [kind, id] = words.slice(-2).map(word => word.toLowerCase());
const account = words.length >= 3 ? accounts.byName(words.slice(0, -2).join(" ")) : null;
if (words.length < 3 || !/^\d+$/.test(id)) {
tell(session, usage);
return;
}
if (!account) {
tell(session, `No player called ${words.slice(0, -2).join(" ")}.`);
return;
}
if (account !== session.account && !roles.outranks(session.account, account) && roles.roleOf(account)) {
tell(session, "Staff of your rank or above are for someone higher up to deal with.");
return;
}
const result = itemControl.take(account.username, kind, id, worldForItems);
tell(session, result.error || result.ok);
if (result.ok) {
modlog.record(session.account.username, "item taken (in game)", account.username, `${kind} ${id} x${result.count}`);
}
},
},
summon: {
permission: "player.summon",
run(session, words) {
withTarget(session, words, "Use: !summon PLAYER", true, target => {
const result = staffMove(target.account.username, session.account.username);
if (!result.ok) {
tell(session, result.error);
return;
}
tell(session, `${target.account.username} was brought here.`);
logged(session, "summon", target, result.room);
});
},
},
goto: {
permission: "player.goto",
run(session, words) {
withTarget(session, words, "Use: !goto PLAYER", false, target => {
const result = staffMove(session.account.username, target.account.username);
if (!result.ok) {
tell(session, result.error);
return;
}
logged(session, "goto", target, result.room);
});
},
},
kick: {
permission: "player.kick",
run(session, words) {
withTarget(session, words, "Use: !kick PLAYER", true, target => {
const name = target.account.username;
if (staffModeration().actions.kick(target.account)) {
tell(session, `${name} was disconnected.`);
logged(session, "kick", target);
}
else {
tell(session, `${name} is not online.`);
}
});
},
},
// "!silence PLAYER HOURS" (0: until lifted), "!silence PLAYER off".
silence: {
permission: "chat.silence",
run(session, words) {
withTarget(session, words, "Use: !silence PLAYER HOURS (0 until lifted), or !silence PLAYER off", true, (target, rest) => {
const {actions, PERMANENT} = staffModeration();
const name = target.account.username;
const amount = (rest[0] || "").toLowerCase();
if (amount === "off") {
actions.silence(target.account, 0);
tell(session, `${name} can chat again.`);
logged(session, "unsilence", target);
return;
}
const hours = /^\d{1,6}$/.test(amount) ? Number(amount) : NaN;
if (!(hours >= 0 && hours <= MAX_STAFF_HOURS)) {
tell(session, "Use: !silence PLAYER HOURS (0 until lifted), or !silence PLAYER off");
return;
}
actions.silence(target.account, hours === 0 ? PERMANENT : hours * 3600);
tell(session, hours === 0 ? `${name} cannot chat until it is lifted.` : `${name} cannot chat for ${hours} hours.`);
logged(session, "silence", target, String(hours || "until lifted"));
});
},
},
// "!warn PLAYER [REASON] [note]": a warning, kept on the account and
// shown with the game's own warning popup. REASON is behavior (the
// default), bullying, personal or scamming; the note is for staff.
// "!warn PLAYER custom TEXT": a warning in the staff member's own
// words, which is what the player is shown.
warn: {
permission: "player.warn",
run(session, words) {
const usage = `Use: !warn PLAYER [${staffModeration().WARNINGS.join("|")}] [note], or !warn PLAYER custom TEXT`;
withTarget(session, words, usage, true, (target, rest) => {
const {WARNINGS, actions} = staffModeration();
const asked = (rest[0] || "").toLowerCase();
const reason = WARNINGS.includes(asked) ? asked : "behavior";
const note = (WARNINGS.includes(asked) ? rest.slice(1) : rest).join(" ").trim().slice(0, MAX_WARNING);
if (reason === "custom" && !note) {
tell(session, "Use: !warn PLAYER custom TEXT (the text is what they are shown)");
return;
}
const result = actions.warn(target.account, reason, session.account.username, note);
tell(session, `${target.account.username} warned (${reason}): warning ${result.count}.`
+ (result.silencedMinutes ? ` Silenced for ${result.silencedMinutes} minutes, for that many warnings.` : ""));
logged(session, "warn", target, note ? `${reason} · ${note}` : reason);
});
},
},
// "!message PLAYER text": a message box from the moderators.
message: {
permission: "player.warn",
run(session, words) {
withTarget(session, words, "Use: !message PLAYER text", true, (target, rest) => {
const text = rest.join(" ").trim().slice(0, MAX_WARNING);
if (!text) {
tell(session, "Use: !message PLAYER text");
return;
}
if (staffModeration().actions.message(target.account, text)) {
tell(session, `Shown to ${target.account.username}.`);
logged(session, "message", target, text);
}
else {
tell(session, `${target.account.username} is not online.`);
}
});
},
},
// "!unwarn PLAYER": takes back their latest warning (one given by
// mistake), online or not.
unwarn: {
permission: "player.warn",
run(session, words) {
const account = splitAccount(words);
if (!account) {
tell(session, words.length ? `No player called ${words.join(" ")}.` : "Use: !unwarn PLAYER");
return;
}
if (account === session.account) {
tell(session, "That is you.");
return;
}
if (!roles.outranks(session.account, account)) {
tell(session, "Staff of your rank or above are for someone higher up to deal with.");
return;
}
const removed = staffModeration().actions.unwarn(account);
if (!removed) {
tell(session, `${account.username} has no warnings.`);
return;
}
tell(session, `Took back ${account.username}'s latest warning (${removed.reason}).`);
modlog.record(session.account.username, "unwarn (in game)", account.username, removed.reason);
},
},
// "!warnings PLAYER": their latest warnings, online or not.
warnings: {
permission: "player.warn",
run(session, words) {
const account = splitAccount(words);
if (!account) {
tell(session, words.length ? `No player called ${words.join(" ")}.` : "Use: !warnings PLAYER");
return;
}
const list = account.warnings || [];
if (!list.length) {
tell(session, `${account.username} has no warnings.`);
return;
}
const latest = list.slice(-MAX_WARNINGS_SHOWN).reverse()
.map(entry => `${new Date(entry.at * 1000).toISOString().slice(0, 10)} ${entry.reason} by ${entry.by}${entry.note ? ` (${entry.note})` : ""}`);
tell(session, `${account.username} has ${list.length} warning${list.length === 1 ? "" : "s"}. Latest: ${latest.join("; ")}`);
},
},
};
return { return {
// runs `text` if it is a command. returns what to do with the chat line: // runs `text` if it is a command. returns what to do with the chat line:
// null to swallow it, or the text everyone should see in its place. // null to swallow it, or the text everyone should see in its place.
@@ -508,6 +1003,10 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
} }
const typed = text.slice(PREFIX.length).trim().split(/\s+/); const typed = text.slice(PREFIX.length).trim().split(/\s+/);
const [name, ...words] = typed.map(word => word.toLowerCase()); const [name, ...words] = typed.map(word => word.toLowerCase());
if (Object.hasOwn(staffCommands, name) && staffMay(session, staffCommands[name].permission)) {
staffCommands[name].run(session, typed.slice(1));
return null;
}
if (Object.hasOwn(asTyped, name) && (name !== "den" || typed.length > 1)) { if (Object.hasOwn(asTyped, name) && (name !== "den" || typed.length > 1)) {
asTyped[name](session, typed.slice(1)); asTyped[name](session, typed.slice(1));
return null; return null;
+465
View File
@@ -0,0 +1,465 @@
"use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js");
const defpacks = require("./defpacks.js");
const limits = require("./limits.js");
// items the staff make while the server runs, with no restart of the server
// or of anybody's game. each is an existing item's art (the clothing piece
// or den item it is made from) under an id, name, price and colours of its
// own. the server's tables and the packs new games fetch have it at once
// (defpacks.setCustomItem); games already playing are sent its def row
// ("xdi", which the patched client adds to its tables), and so is a game at
// login if its packs may be older than the item (sendAll).
//
// an item can be taken out of the shop, renamed and repriced, or deleted:
// then it goes from every inventory too (lib/itemcontrol.js).
// ids far above the game's own (clothing to about 4,600, den items to about
// 6,000), one range per pack; names go under localization ids above the
// server's other added strings (lib/defpacks.js ADDED_STRINGS, 9000001 on).
const FIRST_ID = 50000;
const STRING_BASE = {clothing: 9100000, den: 9200000};
const KINDS = ["clothing", "den"];
const MAX_NAME = 40;
const MAX_COST = 1000000;
const MAX_COLOURS = 16;
const MAX_ITEMS = 5000; // per kind
const CHUNK = 40; // def rows per "xdi" message
const TYPE_CLOTHING = "1";
const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items that can be copied: plain, mannequin
const CURRENCY_GEMS = "0";
// the fields of a def row the patched client reads from "xdi"
// (ItemXtCommManager.addItemDef, DenXtCommManager.addDenItemDef): the rest of
// the base's row is only weight, ~600 bytes a row and 5000 rows at login.
const CLIENT_FIELDS = {
clothing: ["id", "layerDefId", "layerId", "type", "value", "titleStrId", "isGiftable", "membersOnly", "itemStatus", "enviroType",
"avatarUseFlags", "recycleValue", "currencyType", "defense", "attack", "attackMediaRefId", "combatType", "modifierType",
"modifierValue", "criticalHit", "combinedCost", "colors", "availabilityStartTime", "availabilityEndTime"],
den: ["id", "abbrName", "combinedCost", "cost", "currencyType", "enviroType", "flag", "gameDefId", "itemStatus", "layer",
"mannequinAvatarDefId", "mannequinCatId", "membersOnly", "nameStrId", "parentArrayId", "promoType", "recycleValue",
"scalePercent", "sortCat", "specialType", "typeCat", "availabilityStartTime", "availabilityEndTime", "ecoPower"],
};
// how long a fetch of the packs is taken to describe a game of that address
// that logs in (sendAll). a game logs in minutes after it fetched them.
const PACKS_SEEN_MS = 2 * 3600000;
const MAX_PACKS_SEEN = 100000; // addresses
const SCHEMA = `CREATE TABLE IF NOT EXISTS custom_items (
kind TEXT NOT NULL, id INTEGER NOT NULL, base INTEGER NOT NULL, name TEXT NOT NULL,
cost INTEGER NOT NULL, members INTEGER NOT NULL, colors TEXT NOT NULL, in_shop INTEGER NOT NULL,
created_by TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (kind, id))`;
const items = new Map(KINDS.map(kind => [kind, new Map()])); // kind -> id -> entry
let made = 0; // entries in the order they were made (`seq`), for lists
let broadcast = () => {}; // (cmd, ...params) to every game playing; set by lib/world.js
// address key -> {at, clothing, den, names}: the version (defpacks
// customVersion) of the packs with custom items in that address last
// fetched, the oldest within PACKS_SEEN_MS (players behind one address
// fetch at different times). an entry's `changed` is the version of its last change.
const packsSeen = new Map();
const db = () => accounts.database();
const now = () => Math.floor(Date.now() / 1000);
const baseDef = (kind, id) => (kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id));
// the file name an uploaded music track is asked for by (lib/custommusic.js):
// a new upload is a new name, so no game plays an old copy from its cache.
const audioName = entry => `CustomMusic${entry.id}_${entry.audio}`;
let audioGone = () => {}; // (entry): an uploaded track's item was deleted; set by lib/custommusic.js
// the def row of an entry: its base's row with its own id, name, price and
// colours, always on sale and marked new.
const rowOf = entry => {
const base = baseDef(entry.kind, entry.base);
const own = {
id: String(entry.id),
membersOnly: entry.members ? "1" : "0",
itemStatus: "1",
availabilityStartTime: "0",
availabilityEndTime: "0",
currencyType: CURRENCY_GEMS,
recycleValue: "0",
combinedCost: "",
};
if (entry.kind === "den") {
// a music track uploaded by staff (lib/custommusic.js): the game plays
// "audio/<abbrName>.mp3", which the server answers with its file
if (entry.audio) {
own.abbrName = audioName(entry);
}
return {...base, ...own, nameStrId: String(STRING_BASE.den + entry.id - FIRST_ID), cost: String(entry.cost)};
}
return {...base, ...own, titleStrId: String(STRING_BASE.clothing + entry.id - FIRST_ID), value: String(entry.cost), colors: entry.colors.join(","), isGiftable: "1"};
};
const apply = entry => {
defpacks.setCustomItem(entry.kind, rowOf(entry), entry.name, entry.inShop);
entry.changed = defpacks.customVersion();
};
// what "xdi" carries of an entry: the fields the client reads, its name and
// picture. clothing goes through the clients' pack transform, so the wear
// rules reach custom items too.
const clientRow = entry => {
const row = entry.kind === "clothing" ? defpacks.clientItemRow(rowOf(entry)) : rowOf(entry);
const out = {};
for (const field of CLIENT_FIELDS[entry.kind]) {
if (row[field] !== undefined) {
out[field] = row[field];
}
}
return {...out, name: entry.name, art: entry.artPending ? "" : entry.art || "", artMode: entry.artMode || "sticker"};
};
// "xdi" [.., .., kind, json]: def rows with their names, as JSON. a field
// may not hold "%" (lib/sfs.js drops it), so a "%" in a name is written as
// JSON's %.
const xtRows = rows => JSON.stringify(rows).replace(/%/g, "\\u0025");
const messages = entries => {
const out = [];
for (const kind of KINDS) {
// a picture waiting for a moderator is not shown yet
const rows = entries.filter(entry => entry.kind === kind && !entry.pending).map(clientRow);
for (let at = 0; at < rows.length; at += CHUNK) {
out.push([kind, xtRows(rows.slice(at, at + CHUNK))]);
}
}
return out;
};
// The patched client accepts ordinary clothing rows through xdi as well as
// newly made ones. That lets a moderation rule take effect in an already
// open editor instead of waiting for its next def-pack download.
const sendClothingDefs = ids => {
const rows = [...new Set(ids.map(Number))].map(id => {
const entry = items.get("clothing").get(id);
// A refreshed custom row must retain the extra xdi-only fields. Omitting
// them makes a live client lose its custom name or picture while its
// avatar-use flag is being updated.
return entry ? {...defpacks.clientItemRow(rowOf(entry)), name: entry.name, art: entry.artPending ? "" : entry.art || "",
artMode: entry.artMode || "sticker"} : defpacks.clientItemDef(id);
}).filter(row => row && row.type === TYPE_CLOTHING);
for (let at = 0; at < rows.length; at += CHUNK) {
broadcast("xdi", "clothing", xtRows(rows.slice(at, at + CHUNK)));
}
};
const announce = entry => {
if (entry.pending) {
return;
}
for (const params of messages([entry])) {
broadcast("xdi", ...params);
}
};
const fromRow = row => ({
kind: row.kind, id: row.id, base: row.base, name: row.name, cost: row.cost, members: row.members === 1,
colors: row.colors ? row.colors.split(",").map(Number) : [], inShop: row.in_shop === 1, createdBy: row.created_by, createdAt: row.created_at,
ownerId: row.owner_id ?? null,
art: row.art || null,
artMode: LOOKS.includes(row.art_mode) ? row.art_mode : "sticker",
pending: row.pending === 1,
artPending: row.art_pending === 1,
audio: /^[0-9a-f]{8,64}$/.test(row.audio || "") ? row.audio : null,
});
// a player-made item (lib/playeritems.js) has the maker's account id;
// staff-made ones none. an item with a picture of its own (lib/itemart.js)
// has its version. the columns came later than the table.
const addOwnerColumn = () => {
const columns = db().prepare("PRAGMA table_info(custom_items)").all().map(column => column.name);
if (!columns.includes("owner_id")) {
db().exec("ALTER TABLE custom_items ADD COLUMN owner_id INTEGER");
}
if (!columns.includes("art")) {
db().exec("ALTER TABLE custom_items ADD COLUMN art TEXT");
}
if (!columns.includes("art_mode")) {
db().exec("ALTER TABLE custom_items ADD COLUMN art_mode TEXT");
}
// waiting for a moderator (lib/playeritems.js, when the admin asks for it):
// the item itself, or only its newest picture
if (!columns.includes("pending")) {
db().exec("ALTER TABLE custom_items ADD COLUMN pending INTEGER");
}
if (!columns.includes("art_pending")) {
db().exec("ALTER TABLE custom_items ADD COLUMN art_pending INTEGER");
}
// a music track uploaded by staff (lib/custommusic.js): its file's version
if (!columns.includes("audio")) {
db().exec("ALTER TABLE custom_items ADD COLUMN audio TEXT");
}
};
const load = () => {
db().exec(SCHEMA);
addOwnerColumn();
for (const row of db().prepare("SELECT * FROM custom_items ORDER BY rowid").all()) {
const entry = {...fromRow(row), seq: made++};
if (!baseDef(entry.kind, entry.base)) {
console.log(`[custom items] ${logText(entry.kind)} ${logText(entry.id)} is made from ${logText(entry.base)}, which is not in the packs; left out`);
continue;
}
items.get(entry.kind).set(entry.id, entry);
if (!entry.pending) {
apply(entry);
}
}
console.log(`[custom items] ${logText(items.get("clothing").size)} clothing, ${logText(items.get("den").size)} den items`);
};
// checks what staff typed. returns {error} or the cleaned values.
const NAME_PATTERN = /^[\p{L}\p{N} '&!?.,:()#+\-]+$/u;
const clean = (kind, fields, current = null) => {
const out = {};
if (fields.name !== undefined || !current) {
const name = String(fields.name || "").trim().replace(/\s+/g, " ");
if (!name || name.length > MAX_NAME || !NAME_PATTERN.test(name)) {
return {error: `A name of 1 to ${MAX_NAME} letters, numbers, spaces and simple punctuation, please.`};
}
out.name = name;
}
if (fields.cost !== undefined || !current) {
const cost = Number(fields.cost === undefined || fields.cost === "" ? 0 : fields.cost);
if (!Number.isInteger(cost) || cost < 0 || cost > MAX_COST) {
return {error: `A price from 0 to ${MAX_COST} gems, please.`};
}
out.cost = cost;
}
if (fields.members !== undefined || !current) {
out.members = fields.members === true || fields.members === "1" || fields.members === 1;
}
if (fields.inShop !== undefined || !current) {
out.inShop = fields.inShop === undefined ? true : fields.inShop === true || fields.inShop === "1" || fields.inShop === 1;
}
if (kind === "clothing" && (fields.colors !== undefined || !current)) {
const base = baseDef(kind, current ? current.base : fields.base);
const baseColours = String(base.colors).split(",").map(Number);
let colors = fields.colors;
if (colors === undefined || colors === null || colors === "") {
colors = baseColours;
}
else {
colors = (Array.isArray(colors) ? colors : String(colors).split(",")).map(value => Number(String(value).trim()));
}
// a colour is a packed palette number, as in the packs (or a custom colour
// id, lib/colours.js).
if (colors.length === 0 || colors.length > MAX_COLOURS || !colors.every(value => Number.isInteger(value) && value >= 0 && value <= 0xFFFFFFFF)) {
return {error: `1 to ${MAX_COLOURS} colours, each a number as the packs have them.`};
}
out.colors = colors;
}
return out;
};
// makes an item from `base`, an existing clothing piece or den item.
// `ownerId`: the player who made it (lib/playeritems.js), or null for staff.
// `pending`: it waits for a moderator (approve), out of the game till then.
// returns {item} or {error}.
const create = (kind, fields, by, ownerId = null, pending = false) => {
if (!KINDS.includes(kind)) {
return {error: "The kind is clothing or den."};
}
const baseId = Number(fields.base);
const base = Number.isInteger(baseId) ? baseDef(kind, baseId) : null;
if (!base || baseId >= FIRST_ID) {
return {error: `No ${kind === "den" ? "den item" : "clothing"} with the id ${fields.base} to make it from (it must be one of the game's own).`};
}
if (kind === "clothing" && base.type !== TYPE_CLOTHING) {
return {error: `${baseId} is a body part, not clothing.`};
}
if (kind === "den" && !OFFERED_SPECIAL_TYPES.includes(base.specialType)) {
return {error: `Den item ${baseId} does something of its own (a portal, a game, ...) and cannot be copied.`};
}
if (items.get(kind).size >= MAX_ITEMS) {
return {error: "There are as many custom items of that kind as there can be."};
}
const values = clean(kind, {...fields, base: baseId});
if (values.error) {
return values;
}
const id = Math.max(FIRST_ID - 1, ...items.get(kind).keys()) + 1;
// `fields.audio`: an uploaded music track's version (lib/custommusic.js)
const audio = kind === "den" && /^[0-9a-f]{8,64}$/.test(String(fields.audio || "")) ? String(fields.audio) : null;
const entry = {kind, id, base: baseId, colors: [], ...values, createdBy: String(by), createdAt: now(), ownerId, artMode: "sticker", pending, artPending: false,
audio, seq: made++};
db().prepare("INSERT INTO custom_items (kind, id, base, name, cost, members, colors, in_shop, created_by, created_at, owner_id, pending, audio) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
.run(kind, id, baseId, entry.name, entry.cost, entry.members ? 1 : 0, entry.colors.join(","), entry.inShop ? 1 : 0, entry.createdBy, entry.createdAt, ownerId, pending ? 1 : 0, audio);
items.get(kind).set(id, entry);
if (!pending) {
apply(entry);
announce(entry);
}
return {item: entry};
};
// changes the name, price, members-only, colours or whether it is on sale.
const update = (kind, id, fields) => {
const entry = items.has(kind) && items.get(kind).get(Number(id));
if (!entry) {
return {error: "No such custom item."};
}
const values = clean(kind, fields, entry);
if (values.error) {
return values;
}
Object.assign(entry, values);
db().prepare("UPDATE custom_items SET name = ?, cost = ?, members = ?, colors = ?, in_shop = ? WHERE kind = ? AND id = ?")
.run(entry.name, entry.cost, entry.members ? 1 : 0, entry.colors.join(","), entry.inShop ? 1 : 0, kind, entry.id);
if (!entry.pending) {
apply(entry);
announce(entry);
}
return {item: entry};
};
// how a clothing item with a picture of its own is worn: "sticker" (the
// picture where the item would be) or "texture" (the item's shape, painted
// with the picture). the patched client draws it (LayerBitmap.paintLayer).
const LOOKS = ["sticker", "texture"];
// returns {item} or {error}; every game is told.
const setArtMode = (kind, id, mode) => {
const entry = items.has(kind) && items.get(kind).get(Number(id));
if (!entry) {
return {error: "No such custom item."};
}
if (!LOOKS.includes(mode)) {
return {error: "The look is sticker or texture."};
}
entry.artMode = mode;
db().prepare("UPDATE custom_items SET art_mode = ? WHERE kind = ? AND id = ?").run(mode, kind, entry.id);
entry.changed = defpacks.customChanged();
announce(entry);
return {item: entry};
};
// its picture's version (lib/itemart.js), or null for none; every game is told.
// `pending`: the picture waits for a moderator, and is not shown till then.
const setArt = (kind, id, art, pending = false) => {
const entry = items.has(kind) && items.get(kind).get(Number(id));
if (!entry) {
return;
}
entry.art = art || null;
entry.artPending = Boolean(art && pending);
db().prepare("UPDATE custom_items SET art = ?, art_pending = ? WHERE kind = ? AND id = ?").run(entry.art, entry.artPending ? 1 : 0, kind, entry.id);
entry.changed = defpacks.customChanged();
announce(entry);
};
// a moderator lets an item, or its picture, in (lib/playeritems.js approve).
// returns the entry, or null when there was nothing waiting.
const approve = (kind, id) => {
const entry = items.has(kind) && items.get(kind).get(Number(id));
if (!entry || (!entry.pending && !entry.artPending)) {
return null;
}
entry.pending = false;
entry.artPending = false;
db().prepare("UPDATE custom_items SET pending = 0, art_pending = 0 WHERE kind = ? AND id = ?").run(kind, entry.id);
apply(entry);
announce(entry);
return entry;
};
// deletes it from the tables (games playing keep its def row, which nothing
// uses now). taking it from the players who have it is the caller's.
// returns {item} or {error}.
const remove = (kind, id) => {
const entry = items.has(kind) && items.get(kind).get(Number(id));
if (!entry) {
return {error: "No such custom item."};
}
db().prepare("DELETE FROM custom_items WHERE kind = ? AND id = ?").run(kind, entry.id);
items.get(kind).delete(entry.id);
defpacks.unsetCustomItem(kind, entry.id);
if (entry.audio) {
audioGone(entry);
}
return {item: entry};
};
const list = () => KINDS.flatMap(kind => [...items.get(kind).values()])
.sort((one, other) => other.seq - one.seq);
module.exports = {
KINDS,
FIRST_ID,
audioName,
onAudioGone: callback => {
audioGone = callback;
},
load,
create,
update,
remove,
setArt,
setArtMode,
approve,
// what waits for a moderator: items, and pictures, the oldest first
waiting: () => list().filter(entry => entry.pending || entry.artPending).reverse(),
LOOKS,
list,
get: (kind, id) => (items.has(kind) && items.get(kind).get(Number(id))) || null,
// the account id of the player who made an item, or null (staff's, or
// one of the game's own).
ownerOf: (kind, id) => {
const entry = items.has(kind) && items.get(kind).get(Number(id));
return entry ? entry.ownerId : null;
},
// can this base be made into an item? (the checks of create, for a list
// to offer only those.)
copyable: (kind, id) => {
const def = baseDef(kind, id);
return Boolean(def) && Number(id) < FIRST_ID && (kind === "clothing" ? def.type === TYPE_CLOTHING : OFFERED_SPECIAL_TYPES.includes(def.specialType));
},
// the base an item's art is from, for a list showing what each is.
baseName: entry => {
const def = baseDef(entry.kind, entry.base);
return def ? defpacks.string(entry.kind === "den" ? def.nameStrId : def.titleStrId) || String(def.abbrName || entry.base) : String(entry.base);
},
// an address was sent a pack with custom items in: "clothing", "den" or
// "names" (lib/defpacks.js customPackKind), made at `version`.
sawPack(key, packKind, version) {
const time = Date.now();
const seen = packsSeen.get(key);
if (seen && time - seen.at < PACKS_SEEN_MS) {
if (seen[packKind] === undefined) {
seen[packKind] = version;
}
return;
}
packsSeen.delete(key);
packsSeen.set(key, {at: time, [packKind]: version});
// the oldest are first
for (const [oldKey, old] of packsSeen) {
if (packsSeen.size <= MAX_PACKS_SEEN && time - old.at < PACKS_SEEN_MS) {
break;
}
packsSeen.delete(oldKey);
}
},
// the custom items a game logging in may not have: those changed since its
// address fetched the packs, and those with a picture (which the packs do
// not carry); every one when the address fetched none lately.
sendAll(session) {
const seen = packsSeen.get(limits.key(session.address));
const fresh = seen && Date.now() - seen.at < PACKS_SEEN_MS && seen.names !== undefined ? seen : null;
const since = kind => (fresh && fresh[kind] !== undefined ? Math.min(fresh[kind], fresh.names) : -1);
const needed = entry => !entry.pending && (entry.changed > since(entry.kind) || (entry.art && !entry.artPending));
for (const params of messages(list().reverse().filter(needed))) {
session.sendXt("xdi", -1, ...params);
}
},
sendClothingDefs,
// lib/world.js says how to reach every game playing.
connect(broadcastXt) {
broadcast = broadcastXt;
},
};
+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};
+248 -21
View File
@@ -1,5 +1,6 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const zlib = require("zlib"); const zlib = require("zlib");
const amf3 = require("./amf3.js"); const amf3 = require("./amf3.js");
const cdn = require("./cdn.js"); const cdn = require("./cdn.js");
@@ -7,6 +8,7 @@ const config = require("../config.js");
const sales = require("./sales.js"); const sales = require("./sales.js");
const badges = require("./badges.js"); const badges = require("./badges.js");
const extraMusic = require("./extramusic.js"); const extraMusic = require("./extramusic.js");
const wearRules = require("./wearrules.js");
// defPack ids, from loader.DefPacksDefHelper in the client. // defPack ids, from loader.DefPacksDefHelper in the client.
const DEF_ITEM = 1000; const DEF_ITEM = 1000;
@@ -19,6 +21,19 @@ const DEF_DEN_ROOM = 1040;
const DEF_DIAMOND = 1054; const DEF_DIAMOND = 1054;
const DEF_PET = 1046; const DEF_PET = 1046;
const DEF_AVATAR_CUSTOM = 1057; const DEF_AVATAR_CUSTOM = 1057;
// custom animals whose def has no pattern (patternRefId 0): their patterns
// were only in the generic list the official server sent. these are the
// pattern items locked to a special animal (bLockAvatarFlags) made after
// the last def that names its own, in release order; 2121 starts with the
// raccoon's overrideColorLayer2. a list of 0 made the avatar editor throw
// (#1009 in AvatarEditor.setCustomPatternColorIdx) and never open.
const CUSTOM_PATTERNS = new Map([
[8, [1963, 1964, 1965, 1966]], // Legendary Eagle
[9, [1976]], // Fearsome Falcon
[10, [1981]], // Royal Red Panda
[11, [2073]], // Frolicking Fox
[12, [2121]], // Rainbow Raccoon
]);
const DEF_ACHIEVEMENTS = 1042; const DEF_ACHIEVEMENTS = 1042;
const DEF_PARTY = 1047; const DEF_PARTY = 1047;
const DEF_CURRENCY_EXCHANGE = 1051; const DEF_CURRENCY_EXCHANGE = 1051;
@@ -28,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();
@@ -56,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.
@@ -130,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
@@ -162,7 +215,64 @@ const withOurName = pack => {
return pack; return pack;
}; };
const withAddedStrings = pack => withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings())); // the moderators' message boxes (FacilitatorXtCommManager "fp") keep
// "\n" as two characters, which the client shows just as written
// ("--Message From Moderator--\n\nhello"). real line breaks in their place.
const LITERAL_LINE_BREAKS = ["11134", "11135"];
const withLineBreaks = pack => {
for (const id of LITERAL_LINE_BREAKS) {
if (typeof pack[id] === "string") {
pack[id] = pack[id].replace(/\\n/g, "\n");
}
}
return pack;
};
// items the staff make while the server runs (lib/customitems.js): an
// existing item's art under a new id, name and price. their rows and names
// are kept here, and go into the packs like the rows above, after the
// renaming (a name staff chose is left as they wrote it).
const customRows = new Map([[DEF_ITEM, new Map()], [DEF_DEN_ITEM, new Map()]]); // pack -> id -> row
const customStrings = {}; // localization id -> name
const customInShop = {clothing: new Set(), den: new Set()}; // ids on sale
let customVersion = 0; // goes up with every change, for anything that keeps a list of items
const withCustomRows = id => pack => {
const at = new Map(Object.entries(pack).map(([key, def]) => [String(def.id), key]));
let next = Math.max(-1, ...Object.keys(pack).map(Number).filter(Number.isInteger)) + 1;
for (const row of customRows.get(id).values()) {
// a changed row replaces the one the pack was made with.
pack[at.has(row.id) ? at.get(row.id) : next++] = {...row};
}
return pack;
};
// colours of clothing items from a dump of a beta-era inventory (art id,
// then the colour as 4 bytes, little-endian), added after each item's own
// so the colours already given keep their place. the shop shows a list's
// first 8 only, so these are had from the item givers.
const DUMP_COLOURS = new Map([
[231, [0x6929C069]], // Rare Eyeball Hat (Beta EyeBall; tried in the game)
[224, [0x67520169]], // Creature Mask (Beta Creature Mask)
[136, [0x2C083069, 0x55153131]], // Tiara (Beta Tiara, Milky Tiara)
[135, [0x83550505]], // Arctic Hood (Beta Hood)
[169, [0x937FF63B]], // Elf Helmet (Beta Elf)
[714, [0x00000069]], // Furry Hat (Real Magenta Furry Hat)
[649, [0x2E2D1906]], // Turquoise Ring (1st Glitched Ring)
]);
const withDumpColours = pack => {
for (const def of Object.values(pack)) {
const added = def && DUMP_COLOURS.get(Number(def.id));
if (added) {
const colours = String(def.colors).split(",").filter(Boolean);
def.colors = [...colours, ...added.map(String).filter(colour => !colours.includes(colour))].join(",");
}
}
return pack;
};
const withAddedStrings = pack => Object.assign(withLineBreaks(withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings()))), customStrings);
// the extra music tracks (lib/extramusic.js), as den items like the // the extra music tracks (lib/extramusic.js), as den items like the
// official tracks. // official tracks.
@@ -223,8 +333,8 @@ const SHARED_CHANGES = new Map([
[DEF_ROOM, withRestoredRooms], [DEF_ROOM, withRestoredRooms],
[DEF_PARTY, withRestoredParties], [DEF_PARTY, withRestoredParties],
[DEF_DEN_ROOM, withoutPrices(DEF_DEN_ROOM, withAddedDens)], [DEF_DEN_ROOM, withoutPrices(DEF_DEN_ROOM, withAddedDens)],
[DEF_DEN_ITEM, withoutPrices(DEF_DEN_ITEM, withExtraMusic)], [DEF_DEN_ITEM, withoutPrices(DEF_DEN_ITEM, pack => withCustomRows(DEF_DEN_ITEM)(withExtraMusic(pack)))],
[DEF_ITEM, withoutPrices(DEF_ITEM)], [DEF_ITEM, withoutPrices(DEF_ITEM, pack => withCustomRows(DEF_ITEM)(withDumpColours(pack)))],
[DEF_DIAMOND, withoutPrices(DEF_DIAMOND)], [DEF_DIAMOND, withoutPrices(DEF_DIAMOND)],
[DEF_PET, withoutPrices(DEF_PET)], [DEF_PET, withoutPrices(DEF_PET)],
[DEF_LOCALIZATION_EN, withAddedStrings], [DEF_LOCALIZATION_EN, withAddedStrings],
@@ -268,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);
@@ -293,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.
@@ -348,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.
@@ -356,7 +497,7 @@ const loadOptional = async id => {
return await load(id); return await load(id);
} }
catch (err) { catch (err) {
console.log(`[defs] ${err.message}; the feature that uses it is off`); console.log(`[defs] ${logText(err.message)}; the feature that uses it is off`);
return []; return [];
} }
}; };
@@ -377,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);
@@ -398,7 +540,8 @@ const init = async () => {
customAvatarDefs = new Map((await load(DEF_AVATAR_CUSTOM)).map(def => [Number(def.id), def])); customAvatarDefs = new Map((await load(DEF_AVATAR_CUSTOM)).map(def => [Number(def.id), def]));
for (const def of await load(DEF_AVATAR_CUSTOM)) { for (const def of await load(DEF_AVATAR_CUSTOM)) {
const listId = Number(def.patternListRefId); const listId = Number(def.patternListRefId);
patternLists.set(listId, [...(patternLists.get(listId) || []), Number(def.patternRefId)]); const patterns = Number(def.patternRefId) ? [Number(def.patternRefId)] : CUSTOM_PATTERNS.get(Number(def.id)) || [];
patternLists.set(listId, [...(patternLists.get(listId) || []), ...patterns]);
} }
roomDefsById = new Map((await load(DEF_ROOM)).map(def => [Number(def.id), def])); roomDefsById = new Map((await load(DEF_ROOM)).map(def => [Number(def.id), def]));
// typeCat 4 is music (the jukebox tracks; also what a hosted party plays) // typeCat 4 is music (the jukebox tracks; also what a hosted party plays)
@@ -413,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), {
@@ -425,11 +571,75 @@ const init = async () => {
isGame: def.isGame === "1", isGame: def.isGame === "1",
}]; }];
})); }));
console.log(`[defs] ${avatarDefs.size} avatars, ${roomDefsByPath.size} rooms, ${clothingIds.length} clothing items, ${denItemIds.length} den items, ${petIds.length} pets`); console.log(`[defs] ${logText(avatarDefs.size)} avatars, ${logText(roomDefsByPath.size)} rooms, ${logText(clothingIds.length)} clothing items, ${logText(denItemIds.length)} den items, ${logText(petIds.length)} pets`);
};
// puts a custom item (lib/customitems.js) in, or changes one already in:
// `kind` "clothing" or "den", `row` its full def row (strings, as in the
// packs), `name` its English name under the row's string id. the server's
// tables have it at once, and the packs clients fetch are made again.
// `inShop` false takes it out of the shop (the ones players have still draw).
const setCustomItem = (kind, row, name, inShop = true) => {
const pack = kind === "den" ? DEF_DEN_ITEM : DEF_ITEM;
const id = Number(row.id);
const stringId = kind === "den" ? row.nameStrId : row.titleStrId;
customRows.get(pack).set(id, row);
customStrings[stringId] = name;
strings[stringId] = name;
stringIds = null;
if (packs.has(pack)) {
packs.set(pack, [...packs.get(pack).filter(def => Number(def.id) !== id), row]);
}
if (kind === "den") {
denItemDefs.set(id, row);
denItemIds = denItemIds.includes(id) ? denItemIds : [...denItemIds, id];
}
else {
itemDefs.set(id, row);
clothingIds = clothingIds.includes(id) ? clothingIds : [...clothingIds, id];
}
customInShop[kind][inShop ? "add" : "delete"](id);
clientPacksChanged.add(pack);
clientPacksChanged.add(DEF_LOCALIZATION_EN);
customVersion++;
};
// a custom item deleted (lib/customitems.js): out of the tables and the
// packs new games fetch. its name stays under its string id, unused.
const unsetCustomItem = (kind, id) => {
const pack = kind === "den" ? DEF_DEN_ITEM : DEF_ITEM;
const number = Number(id);
customRows.get(pack).delete(number);
if (packs.has(pack)) {
packs.set(pack, packs.get(pack).filter(def => Number(def.id) !== number));
}
if (kind === "den") {
denItemDefs.delete(number);
denItemIds = denItemIds.filter(one => one !== number);
}
else {
itemDefs.delete(number);
clothingIds = clothingIds.filter(one => one !== number);
}
customInShop[kind].delete(number);
clientPacksChanged.add(pack);
customVersion++;
}; };
module.exports = { module.exports = {
init, init,
setCustomItem,
unsetCustomItem,
// the custom items on sale, the newest first.
customShopIds: kind => [...customInShop[kind]].reverse(),
customVersion: () => customVersion,
// a change of a custom item that is not in the packs (its picture): one
// more version, for a game logging in to be told of it
customChanged: () => ++customVersion,
// the avatarUseFlags every clothing row has in the clients' pack (any animal)
EVERY_AVATAR,
// "clothing", "den" or "names" for a pack path with custom items in (lib/customitems.js sawPack), else null.
customPackKind: relPath => CUSTOM_PACK_KINDS.get(clientPackPaths.get(relPath)) || null,
load, load,
itemDef: id => itemDefs.get(Number(id)), itemDef: id => itemDefs.get(Number(id)),
clothingIds: () => clothingIds, clothingIds: () => clothingIds,
@@ -437,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) {
@@ -451,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,
@@ -487,6 +709,11 @@ module.exports = {
extraMusicIds: () => extraMusic.ids, extraMusicIds: () => extraMusic.ids,
roomDefById: id => roomDefsById.get(Number(id)), roomDefById: id => roomDefsById.get(Number(id)),
patternList: listId => patternLists.get(Number(listId)), patternList: listId => patternLists.get(Number(listId)),
// the pattern a custom animal starts with
customPattern: id => {
const def = customAvatarDefs.get(Number(id));
return def ? (patternLists.get(Number(def.patternListRefId)) || [0])[0] : 0;
},
avatarTypes: () => [...avatarDefs.keys()], avatarTypes: () => [...avatarDefs.keys()],
// first non-member land animal, falling back to whatever the pack lists // first non-member land animal, falling back to whatever the pack lists
// first. // first.
+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
+165 -46
View File
@@ -1,11 +1,14 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const achievements = require("./achievements.js"); const achievements = require("./achievements.js");
const config = require("../config.js"); const config = require("../config.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const wearRules = require("./wearrules.js");
const epicDens = require("./epicdens.js"); const epicDens = require("./epicdens.js");
const masterpieces = require("./masterpieces.js"); const masterpieces = require("./masterpieces.js");
const eco = require("./eco.js");
const {CURRENCIES, MAX_DEN_ITEMS, hasRoom, activeAvatar, resolvePurchase, isUint} = require("./player.js"); const {CURRENCIES, MAX_DEN_ITEMS, hasRoom, activeAvatar, resolvePurchase, isUint} = require("./player.js");
// den items: owning, placing and recycling furniture (client side: // den items: owning, placing and recycling furniture (client side:
@@ -30,7 +33,10 @@ const canEnter = (owner, visitor) => owner === visitor || owner.denPrivacy === D
|| (owner.denPrivacy === DEN_BUDDIES_ONLY && owner.buddies.includes(visitor.username.toLowerCase())); || (owner.denPrivacy === DEN_BUDDIES_ONLY && owner.buddies.includes(visitor.username.toLowerCase()));
const RECYCLE_FRACTION = 0.3; // matches recyclePercentage sent at login const RECYCLE_FRACTION = 0.3; // matches recyclePercentage sent at login
const FIELDS_PER_SAVED_ITEM = 17; const FIELDS_PER_SAVED_ITEM = 17;
const REF_DEN_ITEM = "0"; // "1" would be a pet placed in the den const REF_DEN_ITEM = "0";
const REF_PET = "1";
const PET_CATEGORY = 1; // DenItem.getInWorldId for pets (sort category 99)
const MAX_CATEGORY = 1000;
const CURRENCY_DIAMONDS = 3; const CURRENCY_DIAMONDS = 3;
// mannequins: den items (special type 4) that stand as an animal in clothes // mannequins: den items (special type 4) that stand as an animal in clothes
@@ -48,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.
@@ -70,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),
@@ -83,33 +98,67 @@ 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;
}), }),
}; };
}; };
// DenXtCommManager.denItemsResponse: [activeDenIdx, count, ?, (invIdx, defId, // where an item stands: `spots` has a place for each den it is in, by the
// placed, version, approved, imageId, creatorDbId, creatorUuid, [mannequin], // den's inventory id ({cat, x, y, flip}), so one item can be in several dens
// denStoreInvId)...]. the three after "approved" are a masterpiece's // at once. the client is only ever told about the den in use.
const spotOf = (item, den) => (item.spots ? item.spots[den] : undefined);
const isPlaced = item => Boolean(item.spots) && Object.keys(item.spots).length > 0;
const itemsInDen = account => account.denItems.filter(item => spotOf(item, account.activeDen));
// the pets standing in the owner's den in use: `inDen` is {den, x, y, flip}.
const petsInDen = account => account.pets.filter(pet => pet.inDen && pet.inDen.den === account.activeDen);
// DenXtCommManager.denItemsResponse: [activeDenIdx, count, petCount, (invIdx,
// defId, placed, version, approved, imageId, creatorDbId, creatorUuid,
// [mannequin], denStoreInvId)..., petInvIdx...]. "placed" is the category the
// den editor gave the item (DenItem.getInWorldId) in the den in use, 0 when
// 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);
session.sendXt("di", -1, account.activeDen, denItems.length, 0, const pets = petsInDen(account);
...denItems.flatMap(item => [item.inv, item.def, item.placed ? 1 : 0, item.version, masterpieces.itemApproved(item), ...masterpieces.itemFields(item), session.sendXt("di", -1, account.activeDen, denItems.length, pets.length,
...mannequinOwnFields(account, item), 0])); ...denItems.flatMap(item => {
const spot = spotOf(item, account.activeDen);
return [item.inv, item.def, spot ? spot.cat || 1 : 0, item.version, masterpieces.itemApproved(item), ...masterpieces.itemFields(item),
...mannequinOwnFields(account, item), 0];
}),
...pets.map(pet => pet.inv));
}; };
// 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], ?)...]. forceReload makes the client finish a // creatorDbId, creatorUuid, [mannequin], eco state)..., (invIdx, lBits, uBits, eBits,
// pending room change, so it is set when the den has just been entered. // category, x, y, flipped, createdTs, personality, toy, food, name)...].
// forceReload makes the client finish a pending room change, so it is set
// when the den has just been entered.
const sendDenState = (session, room, forceReload = true) => { const sendDenState = (session, room, forceReload = true) => {
const placed = room.denOwner.denItems.filter(item => item.placed && item.den === room.denOwner.activeDen && masterpieces.itemApproved(item)); const owner = room.denOwner;
session.sendXt("ds", room.id, placed.length, 0, forceReload ? 1 : 0, const placed = itemsInDen(owner).filter(item => known(item) && masterpieces.itemApproved(item));
...placed.flatMap(item => [item.inv, item.def, 1, item.x, item.y, item.version, item.flip, "", ...masterpieces.itemFields(item), const pets = petsInDen(owner);
...mannequinShownFields(room.denOwner, item), 0])); session.sendXt("ds", room.id, placed.length, pets.length, forceReload ? 1 : 0,
...placed.flatMap(item => {
const spot = spotOf(item, owner.activeDen);
// Keep the editor's real placement category. Sending every placed
// 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,
pet.createdAt, pet.personality || 0, pet.toy || 0, pet.food || 0, pet.name]));
}; };
// adds a den item to an account; used by purchases, prizes and the item // adds a den item to an account; used by purchases, prizes and the item
@@ -118,9 +167,9 @@ const giveDenItem = (account, defId, version = 0) => {
if (!hasRoom(account, "denItems")) { if (!hasRoom(account, "denItems")) {
return null; return null;
} }
const item = {inv: account.nextInv++, def: Number(defId), version: Number(version) || 0, placed: false, den: account.activeDen, x: 0, y: 0, flip: 0}; const item = {inv: account.nextInv++, def: Number(defId), version: Number(version) || 0, spots: {}};
account.denItems.push(item); account.denItems.push(item);
accounts.save(); accounts.save(account);
return item; return item;
}; };
@@ -128,15 +177,17 @@ const giveDenItem = (account, defId, version = 0) => {
// on the screens of everyone inside it (DenXtCommManager.denEmptyResponse). // on the screens of everyone inside it (DenXtCommManager.denEmptyResponse).
const clearDen = (owner, findOnline) => { const clearDen = (owner, findOnline) => {
// kept so that "!den undo" can put it back (lib/commands.js). // kept so that "!den undo" can put it back (lib/commands.js).
const placed = owner.denItems.filter(item => item.placed && item.den === owner.activeDen); const placed = itemsInDen(owner);
if (placed.length) { if (placed.length) {
owner.denUndo = {den: owner.activeDen, items: placed.map(item => ({def: item.def, version: item.version, x: item.x, y: item.y, flip: item.flip}))}; owner.denUndo = {den: owner.activeDen, items: placed.map(item => ({def: item.def, version: item.version, ...spotOf(item, owner.activeDen)}))};
} }
for (const item of owner.denItems.filter(candidate => candidate.den === owner.activeDen)) { for (const item of placed) {
item.placed = false; delete item.spots[owner.activeDen];
item.x = item.y = item.flip = 0;
} }
accounts.save(); for (const pet of petsInDen(owner)) {
delete pet.inDen;
}
accounts.save(owner);
const ownerSession = findOnline(owner.username); const ownerSession = findOnline(owner.username);
const room = ownerSession && ownerSession.room && ownerSession.room.denOwner === owner ? ownerSession.room : null; const room = ownerSession && ownerSession.room && ownerSession.room.denOwner === owner ? ownerSession.room : null;
for (const session of room ? room.sessions : []) { for (const session of room ? room.sessions : []) {
@@ -200,7 +251,7 @@ const handlers = ({others, findOnline}) => {
account.currency[currency] -= purchase.cost; account.currency[currency] -= purchase.cost;
achievements.currencyChanged(account, currency, -purchase.cost); achievements.currencyChanged(account, currency, -purchase.cost);
account.dens.push({inv: freeSlot(account, /^\d{1,3}$/.test(String(slot)) ? Number(slot) : NaN), def: purchase.defId}); account.dens.push({inv: freeSlot(account, /^\d{1,3}$/.test(String(slot)) ? Number(slot) : NaN), def: purchase.defId});
accounts.save(); accounts.save(account);
session.sendXt("db", -1, 1, account.currency[currency], 0, purchase.currencyType, 0); session.sendXt("db", -1, 1, account.currency[currency], 0, purchase.currencyType, 0);
sendDenList(session); sendDenList(session);
}; };
@@ -228,12 +279,45 @@ const handlers = ({others, findOnline}) => {
masterpieces.claim(paintingId, frame); masterpieces.claim(paintingId, frame);
const item = giveDenItem(account, masterpieces.DEN_ITEM, frame); const item = giveDenItem(account, masterpieces.DEN_ITEM, frame);
item.image = String(paintingId); item.image = String(paintingId);
accounts.save(); accounts.save(account);
console.log(`[world] ${account.username} made masterpiece ${item.image}${masterpieces.itemApproved(item) ? "" : " (waiting for review in the admin panel)"}`); console.log(`[world] ${logText(account.username)} made masterpiece ${logText(item.image)}${logText(masterpieces.itemApproved(item) ? "" : " (waiting for review in the admin panel)")}`);
session.sendXt("db", -1, 1, account.currency.diamonds || 0, 0, CURRENCY_DIAMONDS, item.inv); session.sendXt("db", -1, 1, account.currency.diamonds || 0, 0, CURRENCY_DIAMONDS, item.inv);
sendDenItems(session); sendDenItems(session);
}; };
// den rooms recycled from the den switcher (DenSwitch.removeDen): never the
// den in use, nor slot 0. what stood in one goes back to the inventory,
// and a den bought for gems gives back the share den items do. the reply
// is the same as for items.
const recycleDens = (session, invList) => {
const {account} = session;
const recycled = [];
for (const invIdx of new Set(String(invList).split(",", MAX_DENS).map(Number))) {
const den = account.dens.find(candidate => candidate.inv === invIdx);
if (!den || den.inv === 0 || den.inv === account.activeDen || account.dens.length <= 1) {
continue;
}
account.dens.splice(account.dens.indexOf(den), 1);
for (const item of account.denItems.filter(candidate => spotOf(candidate, den.inv))) {
delete item.spots[den.inv];
}
for (const pet of account.pets.filter(candidate => candidate.inDen && candidate.inDen.den === den.inv)) {
delete pet.inDen;
}
const refund = Math.floor(Number((defpacks.denRoomDef(den.def) || {}).cost || 0) * RECYCLE_FRACTION);
account.currency.gems += refund;
achievements.currencyChanged(account, "gems", refund);
recycled.push(den.inv);
}
accounts.save(account);
session.sendXt("dr", -1, recycled.length, account.currency.gems, ...recycled);
// the switcher empties the slot itself; the items that come back need
// the inventory's list.
if (recycled.length) {
sendDenItems(session);
}
};
return { return {
di(session) { di(session) {
sendDenItems(session); sendDenItems(session);
@@ -289,9 +373,12 @@ const handlers = ({others, findOnline}) => {
sendDenItems(session); sendDenItems(session);
}, },
// DenXtCommManager.requestDenStateChange: [count, (refType, invIdx, placed, // DenXtCommManager.requestDenStateChange: [count, (refType, invIdx,
// x, y, flipped, userNameLink, 10 mannequin fields)...]. the reply // category, x, y, flipped, userNameLink, 10 mannequin fields)...]. the
// (DenEditor.onDenSaveSet) lists the inventory ids that were applied. // category is DenItem.getInWorldId: 1 furniture, toys, plants and pets,
// 2 wall items, 3 music, the room's denCatId floors and wallpapers; 0 not
// placed. the reply (DenEditor.onDenSaveSet) lists the inventory ids
// that were applied.
ds(session, roomId, params) { ds(session, roomId, params) {
const {account} = session; const {account} = session;
const count = Number(params[0]); const count = Number(params[0]);
@@ -299,22 +386,48 @@ 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);
const activePet = activeAvatar(account).petInvId;
for (let i = 0; i < count; i++) { for (let i = 0; i < count; i++) {
const [refType, invIdx, placed, x, y, flip, , ...outfit] = params.slice(1 + i * FIELDS_PER_SAVED_ITEM, 1 + (i + 1) * FIELDS_PER_SAVED_ITEM); const [refType, invIdx, category, x, y, flip, , ...outfit] = params.slice(1 + i * FIELDS_PER_SAVED_ITEM, 1 + (i + 1) * FIELDS_PER_SAVED_ITEM);
const item = byInv.get(Number(invIdx)); const cat = Number(category);
if (refType !== REF_DEN_ITEM || !item || ![x, y, flip].every(value => Number.isInteger(Number(value))) if (![x, y, flip].every(value => Number.isInteger(Number(value))) || !Number.isInteger(cat) || Math.abs(cat) > MAX_CATEGORY) {
|| (placed === "1" && !masterpieces.itemApproved(item))) {
continue; continue;
} }
item.placed = placed === "1"; const placed = cat !== 0;
item.den = account.activeDen; if (refType === REF_PET) {
item.x = item.placed ? Number(x) : 0; // the pet that follows its owner about is not put down (DenEditor says so).
item.y = item.placed ? Number(y) : 0; const pet = account.pets.find(candidate => candidate.inv === Number(invIdx));
item.flip = item.placed ? Number(flip) : 0; if (pet && !(placed && pet.inv === activePet)) {
const mannequin = isMannequin(item) && readMannequin(account, outfit); if (placed) {
pet.inDen = {den: account.activeDen, x: Number(x), y: Number(y), flip: Number(flip)};
}
else if (pet.inDen && pet.inDen.den === account.activeDen) {
delete pet.inDen;
}
applied.push(pet.inv);
}
continue;
}
const item = byInv.get(Number(invIdx));
if (refType !== REF_DEN_ITEM || !item || (placed && !masterpieces.itemApproved(item))) {
continue;
}
// only the den in use changes: the item stays wherever else it stands.
item.spots = item.spots || {};
if (placed) {
item.spots[account.activeDen] = {cat, x: Number(x), y: Number(y), flip: Number(flip)};
}
else {
delete item.spots[account.activeDen];
}
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) {
@@ -329,7 +442,7 @@ const handlers = ({others, findOnline}) => {
} }
applied.push(item.inv); applied.push(item.inv);
} }
accounts.save(); accounts.save(account);
session.sendXt("dss", -1, ...applied); session.sendXt("dss", -1, ...applied);
if (inOwnDen(session)) { if (inOwnDen(session)) {
for (const other of others(session)) { for (const other of others(session)) {
@@ -344,6 +457,10 @@ const handlers = ({others, findOnline}) => {
// recycleDiCallback) before it lets go of its spinner. // recycleDiCallback) before it lets go of its spinner.
dr(session, roomId, [kind, invList]) { dr(session, roomId, [kind, invList]) {
const {account} = session; const {account} = session;
if (kind === "-1") {
recycleDens(session, invList);
return;
}
const recycled = []; const recycled = [];
for (const invIdx of kind === "0" ? new Set(String(invList).split(",", MAX_RECYCLED_AT_ONCE).map(Number)) : []) { for (const invIdx of kind === "0" ? new Set(String(invList).split(",", MAX_RECYCLED_AT_ONCE).map(Number)) : []) {
const index = account.denItems.findIndex(item => item.inv === invIdx); const index = account.denItems.findIndex(item => item.inv === invIdx);
@@ -359,7 +476,7 @@ const handlers = ({others, findOnline}) => {
account.denItems.splice(index, 1); account.denItems.splice(index, 1);
recycled.push(invIdx); recycled.push(invIdx);
} }
accounts.save(); accounts.save(account);
session.sendXt("dr", -1, recycled.length, account.currency.gems, ...recycled); session.sendXt("dr", -1, recycled.length, account.currency.gems, ...recycled);
if (recycled.length) { if (recycled.length) {
sendDenItems(session); sendDenItems(session);
@@ -393,9 +510,11 @@ const handlers = ({others, findOnline}) => {
return; return;
} }
account.activeDen = den.inv; account.activeDen = den.inv;
accounts.save(); accounts.save(account);
const avatar = activeAvatar(account); const avatar = activeAvatar(account);
session.sendXt("dc", -1, den.def, avatar.perUserAvId, avatar.petInvId); session.sendXt("dc", -1, den.def, avatar.perUserAvId, avatar.petInvId);
// what is free and what is placed differs from den to den.
sendDenItems(session);
if (inOwnDen(session)) { if (inOwnDen(session)) {
const {room} = session; const {room} = session;
Object.assign(room, denRoom(account)); Object.assign(room, denRoom(account));
@@ -425,10 +544,10 @@ const handlers = ({others, findOnline}) => {
} }
else if ([DEN_LOCKED, DEN_BUDDIES_ONLY, DEN_OPEN].includes(Number(value))) { else if ([DEN_LOCKED, DEN_BUDDIES_ONLY, DEN_OPEN].includes(Number(value))) {
session.account.denPrivacy = Number(value); session.account.denPrivacy = Number(value);
accounts.save(); accounts.save(session.account);
} }
}, },
}; };
}; };
module.exports = {handlers, sendDenState, sendDenItems, sendRoomProperties, giveDenItem, clearDen, denRoom, canEnter, DEF_DEN_ROOM}; module.exports = {handlers, sendDenState, sendDenItems, sendRoomProperties, giveDenItem, clearDen, denRoom, canEnter, spotOf, isPlaced, DEF_DEN_ROOM};
+443
View File
@@ -0,0 +1,443 @@
"use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const accounts = require("./accounts.js");
const config = require("../config.js");
// the computers players sign in from, for telling alts apart and keeping a
// banned player's computer out (the "device ban" of the panels).
//
// the client (1.3.0 and on) sends, with every sign-in, hashes of what it
// can read about the computer: the system's own id (MachineGuid on Windows,
// IOPlatformUUID on macOS, /etc/machine-id on Linux), the board's id or
// serial, the disks' serials, the network cards' addresses, and an id of
// its own it keeps in two or three places. none of them is sent as it is:
// each is SHA-256 of "burrow-device:<kind>:<value>", and here that is keyed
// again with a secret of this server's (data/device-key), so what is kept
// is of no use anywhere else.
//
// two computers are taken for one when they share at least MIN_MATCHING of
// these (owner, 2026-10-23: one or two in common was too often someone
// else's), for a ban and for an alt alike: someone who edits
// /etc/machine-id or deletes MachineGuid still has the same board, disks
// and the client's own id. the network card's address (MAC_KIND) does not
// count towards them: it is easily changed and sometimes shared, so it bans
// nothing; it is written down for the moderators instead. values every cheap board or VM has ("To be filled by
// O.E.M.", all zeros) are left out here, so that no ban falls on everyone
// who has one. what the client noticed was wrong (the system id missing, or
// not shaped as it always is) comes as notes, and is written down too.
//
// the client is open source, so a player who builds their own can send
// anything; this keeps out the usual ban evader (a VPN, a new account),
// not a determined one. the moderators see the alerts and decide.
const SCHEMA = `
CREATE TABLE IF NOT EXISTS device_bans (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ids TEXT NOT NULL,
reason TEXT NOT NULL,
by TEXT NOT NULL,
created_at INTEGER NOT NULL,
account_id INTEGER,
username TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS device_alerts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
at INTEGER NOT NULL,
account_id INTEGER NOT NULL,
username TEXT NOT NULL,
kind TEXT NOT NULL,
detail TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS device_alerts_account ON device_alerts (account_id, id);
`;
const KINDS = ["os", "board", "disk", "install", "mac"];
const STRONG = ["os", "board", "disk", "install"];
const MAC_KIND = "mac";
const MIN_MATCHING = 3; // ids but a network card's two computers share to be taken for one
const LISTS = ["disk", "mac"]; // sent as lists; the rest one each
const MAX_IN_LIST = 8;
const MAX_KEPT = 60; // ids an account keeps, the latest
const DAYS_KEPT = 90; // what a ban by account takes, and alts look at
const ALERT_EVERY_SECONDS = 86400; // one alert of a kind for an account a day
const MAX_ALERTS_SHOWN = 200;
const MAX_REASON = 300;
const HASH = /^[0-9a-f]{64}$/;
const NOTE = /^[a-z_]{1,24}$/;
// notes from the client that mean someone has been at the computer's ids.
const TAMPER_NOTES = {
os_missing: "the system id is missing",
os_odd: "the system id is not shaped like one",
install_mismatch: "the client's own ids disagree",
};
// values that are everyone's: on cheap boards, in VMs, or where the maker
// wrote nothing. the client sends them hashed like any other, so they are
// hashed here the same way to be known.
const JUNK = {
os: ["00000000-0000-0000-0000-000000000000", "ffffffff-ffff-ffff-ffff-ffffffffffff", "00000000000000000000000000000000",
"ffffffffffffffffffffffffffffffff"],
board: ["00000000-0000-0000-0000-000000000000", "ffffffff-ffff-ffff-ffff-ffffffffffff", "03000200-0400-0500-0006-000700080009",
"12345678-1234-5678-90ab-cddeefaabbcc", "to be filled by o.e.m.", "default string", "system serial number", "chassis serial number",
"not applicable", "not specified", "none", "n/a", "0", "0123456789", "123456789", "1234567890", "serial", "invalid"],
disk: ["0", "none", "0000_0000_0000_0000", "default string", "to be filled by o.e.m.", "not specified"],
mac: ["00:00:00:00:00:00", "ff:ff:ff:ff:ff:ff"],
};
const clientHash = (kind, value) => crypto.createHash("sha256").update(`burrow-device:${kind}:${value}`).digest("hex");
const JUNK_HASHES = new Set(Object.entries(JUNK).flatMap(([kind, values]) => values.map(value => clientHash(kind, value))));
const now = () => Math.floor(Date.now() / 1000);
const db = () => accounts.database();
const clean = (text, max) => String(text === undefined || text === null ? "" : text).replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, max);
const NO_REASON = "Not provided";
let key = null; // this server's secret for keying the ids
const banned = new Map(); // "kind:id" -> ban {id, ids, reason, by, createdAt, accountId, username}
const holders = new Map(); // "kind:id" -> Set of account ids that used it
const keyFile = () => path.join(config.dataDir, "device-key");
// the account's ids: [{kind, id, first, last}], the latest first.
const idsOf = account => {
if (!Array.isArray(account.hwids)) {
account.hwids = [];
}
return account.hwids;
};
const tag = entry => `${entry.kind}:${entry.id}`;
const isStrong = id => STRONG.includes(id.split(":")[0]);
const banRow = row => ({id: row.id, ids: JSON.parse(row.ids), reason: row.reason, by: row.by, createdAt: row.created_at,
accountId: row.account_id, username: row.username});
const load = () => {
try {
key = fs.readFileSync(keyFile());
}
catch (err) {
key = crypto.randomBytes(32);
fs.writeFileSync(keyFile(), key, {mode: 0o600});
}
db().exec(SCHEMA);
for (const row of db().prepare("SELECT * FROM device_bans").all()) {
const ban = banRow(row);
for (const id of ban.ids) {
banned.set(id, ban);
}
}
for (const account of accounts.all()) {
for (const entry of idsOf(account)) {
remember(account, tag(entry));
}
}
};
const remember = (account, id) => {
if (!holders.has(id)) {
holders.set(id, new Set());
}
holders.get(id).add(account.id);
};
// what a sign-in said about its computer (`device` from its body), keyed:
// {ids: [{kind, id}], notes: [..]}, or null when it said nothing usable.
const read = device => {
if (!device || typeof device !== "object" || device.v !== 1 || !device.ids || typeof device.ids !== "object") {
return null;
}
const ids = [];
for (const kind of KINDS) {
const given = device.ids[kind];
const values = LISTS.includes(kind) ? (Array.isArray(given) ? given.slice(0, MAX_IN_LIST) : []) : [given];
for (const value of values) {
const hash = String(value || "").toLowerCase();
if (HASH.test(hash) && !JUNK_HASHES.has(hash)) {
ids.push({kind, id: crypto.createHmac("sha256", key).update(`${kind}:${hash}`).digest("hex").slice(0, 32)});
}
}
}
const notes = Array.isArray(device.notes) ? device.notes.slice(0, 8).map(String).filter(note => NOTE.test(note)) : [];
// something to tell one computer by, beyond a network card.
return ids.some(entry => STRONG.includes(entry.kind)) ? {ids, notes} : null;
};
// the ban that has at least MIN_MATCHING of these "kind:id" in it, or
// null. network cards' addresses are not counted (see the top).
const banMatching = ids => {
const strong = new Set(ids.filter(isStrong));
const looked = new Set();
for (const id of strong) {
const ban = banned.get(id);
if (ban && !looked.has(ban.id)) {
looked.add(ban.id);
if (ban.ids.filter(one => strong.has(one)).length >= MIN_MATCHING) {
return ban;
}
}
}
return null;
};
// the ban that keeps this computer out, or null.
const banOf = device => banMatching(device.ids.map(tag));
// the ban on any computer the account signed in from lately, or null: for
// the client asking why its game was stopped.
const banOfAccount = account => banMatching(idsOf(account).filter(entry => entry.last > now() - DAYS_KEPT * 86400).map(tag));
const alert = (account, kind, detail) => {
const last = db().prepare("SELECT at FROM device_alerts WHERE account_id = ? AND kind = ? ORDER BY id DESC LIMIT 1").get(account.id, kind);
if (last && last.at > now() - ALERT_EVERY_SECONDS) {
return;
}
db().prepare("INSERT INTO device_alerts (at, account_id, username, kind, detail) VALUES (?, ?, ?, ?, ?)").run(now(), account.id, account.username, kind, detail);
console.log(`[devices] ${logText(account.username)}: ${logText(kind)} (${logText(detail)})`);
};
// an account signed in from this computer: its ids are kept, and what looks
// wrong is written down. `isBanned(account)` says whether another account is
// banned now (lib/moderation.js), for "shares a computer with a banned one".
const seen = (account, device, isBanned) => {
const list = idsOf(account);
const at = now();
for (const entry of device.ids) {
const kept = list.find(other => other.kind === entry.kind && other.id === entry.id);
if (kept) {
kept.last = at;
}
else {
list.push({kind: entry.kind, id: entry.id, first: at, last: at});
}
remember(account, tag(entry));
}
list.sort((one, other) => other.last - one.last);
for (const dropped of list.splice(MAX_KEPT)) {
const set = holders.get(tag(dropped));
if (set) {
set.delete(account.id);
}
}
const tampered = device.notes.filter(note => TAMPER_NOTES[note]).map(note => TAMPER_NOTES[note]);
if (tampered.length) {
alert(account, "tampered", tampered.join(", "));
}
const nearBan = device.ids.find(entry => entry.kind === MAC_KIND && banned.has(tag(entry)));
if (nearBan) {
alert(account, "near_ban", `same network card as a hardware ban (${banned.get(tag(nearBan)).username || "no account"})`);
}
const shared = new Map(); // account id -> ids in common
for (const entry of device.ids.filter(one => STRONG.includes(one.kind))) {
for (const id of holders.get(tag(entry)) || []) {
if (id !== account.id) {
shared.set(id, (shared.get(id) || 0) + 1);
}
}
}
const sharers = new Set();
for (const [id, count] of shared) {
const other = count >= MIN_MATCHING ? accounts.byId(id) : null;
if (other && isBanned(other)) {
sharers.add(other.username);
}
}
if (sharers.size) {
alert(account, "shares_banned", `same hardware as banned ${[...sharers].slice(0, 5).join(", ")}`);
}
};
// the other accounts that used one of this one's computers, sharing at
// least MIN_MATCHING of its ids: [{username, kinds: [kind]}], most in
// common first.
const alts = account => {
const found = new Map(); // account id -> {kinds: Set, strong: ids in common but network cards}
for (const entry of idsOf(account)) {
for (const id of holders.get(tag(entry)) || []) {
if (id !== account.id) {
if (!found.has(id)) {
found.set(id, {kinds: new Set(), strong: 0});
}
found.get(id).kinds.add(entry.kind);
found.get(id).strong += STRONG.includes(entry.kind) ? 1 : 0;
}
}
}
return [...found].filter(([, shared]) => shared.strong >= MIN_MATCHING)
.map(([id, shared]) => ({account: accounts.byId(id), kinds: [...shared.kinds], strong: shared.strong}))
.filter(entry => entry.account)
.sort((one, other) => other.strong - one.strong || other.kinds.length - one.kinds.length || one.account.username.localeCompare(other.account.username))
.map(entry => ({username: entry.account.username, kinds: entry.kinds}));
};
// how many computers' worth of ids an account has, for the panels.
const knownFor = account => ({ids: idsOf(account).length, lastAt: idsOf(account).reduce((latest, entry) => Math.max(latest, entry.last), 0)});
// bans every computer the account signed in from in the last DAYS_KEPT
// days. returns {ban} or {error}. `out(ban)` puts out whoever plays from
// one of them.
const banAccount = (account, reason, by) => {
const ids = [...new Set(idsOf(account).filter(entry => entry.last > now() - DAYS_KEPT * 86400).map(tag))];
if (ids.filter(isStrong).length < MIN_MATCHING) {
return {error: `Fewer than ${MIN_MATCHING} hardware IDs known for them.`};
}
if (ids.filter(isStrong).every(id => banned.has(id))) {
return {error: "Their hardware is banned already."};
}
const text = clean(reason, MAX_REASON) || NO_REASON;
const result = db().prepare("INSERT INTO device_bans (ids, reason, by, created_at, account_id, username) VALUES (?, ?, ?, ?, ?, ?)")
.run(JSON.stringify(ids), text, by, now(), account.id, account.username);
const ban = {id: Number(result.lastInsertRowid), ids, reason: text, by, createdAt: now(), accountId: account.id, username: account.username};
for (const id of ids) {
banned.set(id, ban);
}
return {ban};
};
// the accounts playing from one of a ban's computers, by their latest ids:
// those with at least MIN_MATCHING of its ids.
const accountsUnder = ban => {
const found = new Map(); // account id -> ids in common
for (const id of new Set(ban.ids.filter(isStrong))) {
for (const accountId of holders.get(id) || []) {
found.set(accountId, (found.get(accountId) || 0) + 1);
}
}
return [...found].filter(([, count]) => count >= MIN_MATCHING).map(([id]) => accounts.byId(id)).filter(Boolean);
};
const unban = id => {
const row = db().prepare("SELECT * FROM device_bans WHERE id = ?").get(Number(id));
if (!row) {
return null;
}
const ban = banRow(row);
db().prepare("DELETE FROM device_bans WHERE id = ?").run(ban.id);
for (const one of ban.ids) {
if (banned.get(one) && banned.get(one).id === ban.id) {
banned.delete(one);
}
}
return ban;
};
// one ban as kept, with the account it was made with (accountId), or null:
// for the moderator panel to see whose it is before lifting it.
const banById = id => {
const row = db().prepare("SELECT * FROM device_bans WHERE id = ?").get(Number(id));
return row ? banRow(row) : null;
};
// the bans, newest first: their ids, and the accounts that used them.
const MAX_LISTED_ACCOUNTS = 20;
const list = () => db().prepare("SELECT * FROM device_bans ORDER BY id DESC").all().map(banRow)
.map(ban => ({id: ban.id, username: ban.username, reason: ban.reason, by: ban.by, createdAt: ban.createdAt,
ids: ban.ids.map(one => ({kind: one.split(":")[0], id: one.split(":")[1]})),
accounts: accountsUnder(ban).map(account => account.username).sort().slice(0, MAX_LISTED_ACCOUNTS)}));
// the account's ids for the panels, the latest first: [{kind, id, first,
// last, banned: the ban's id or 0, others: how many other accounts used it}].
const idsFor = account => idsOf(account).map(entry => {
const ban = banned.get(tag(entry));
const set = holders.get(tag(entry));
return {kind: entry.kind, id: entry.id, first: entry.first, last: entry.last, banned: ban ? ban.id : 0,
others: set ? [...set].filter(id => id !== account.id).length : 0};
});
// the bans that keep the account's computers out (by any of its ids but a
// network card's, however old), and those made with it: what "unban
// computers" on its page lifts.
const bansOfAccount = account => {
const found = new Map();
for (const entry of idsOf(account)) {
const ban = banned.get(tag(entry));
if (ban && STRONG.includes(entry.kind)) {
found.set(ban.id, ban);
}
}
for (const ban of banned.values()) {
if (ban.accountId === account.id) {
found.set(ban.id, ban);
}
}
return [...found.values()];
};
// the accounts that used an id, or any id starting with what was typed (a
// "kind:" in front is let be): {error} or {players: [{account, kinds,
// lastAt}]}, the latest first.
const MIN_ID_QUERY = 6;
const MAX_ID_FOUND = 100;
const search = query => {
const wanted = String(query || "").trim().toLowerCase().replace(/^[a-z]+:/, "").slice(0, 32);
if (wanted.length < MIN_ID_QUERY || !/^[0-9a-f]+$/.test(wanted)) {
return {error: `Type at least ${MIN_ID_QUERY} characters of a hardware ID.`};
}
const found = new Map(); // account id -> {kinds, lastAt}
for (const [key, set] of holders) {
const [kind, id] = key.split(":");
if (!id.startsWith(wanted)) {
continue;
}
for (const accountId of set) {
const account = accounts.byId(accountId);
const entry = account && idsOf(account).find(one => one.kind === kind && one.id === id);
if (entry) {
const kept = found.get(accountId) || {account, kinds: new Set(), lastAt: 0};
kept.kinds.add(kind);
kept.lastAt = Math.max(kept.lastAt, entry.last);
found.set(accountId, kept);
}
}
}
return {players: [...found.values()].map(entry => ({...entry, kinds: [...entry.kinds]}))
.sort((one, other) => other.lastAt - one.lastAt).slice(0, MAX_ID_FOUND)};
};
// is any of the account's computers banned? the ban's id, or 0.
const bannedId = account => {
const ban = banOfAccount(account);
return ban ? ban.id : 0;
};
const ALERT_NAMES = {tampered: "Hardware IDs tampered with", near_ban: "Network card of a hardware ban", shares_banned: "Same hardware as a banned player"};
const alertRow = row => ({id: row.id, at: row.at, username: row.username, kind: row.kind, name: ALERT_NAMES[row.kind] || row.kind, detail: row.detail});
const alerts = () => db().prepare("SELECT * FROM device_alerts ORDER BY id DESC LIMIT ?").all(MAX_ALERTS_SHOWN).map(alertRow);
const alertsOf = account => db().prepare("SELECT * FROM device_alerts WHERE account_id = ? ORDER BY id DESC LIMIT 50").all(account.id).map(alertRow);
// an account being deleted: its ids and alerts go. bans stay: they are of
// computers, not of the account.
const forget = account => {
for (const entry of idsOf(account)) {
const set = holders.get(tag(entry));
if (set) {
set.delete(account.id);
}
}
db().prepare("DELETE FROM device_alerts WHERE account_id = ?").run(account.id);
};
// sign-in tokens last given to (or brought back by) a launcher that sent no
// device ids: one from before 1.3.0, or not ours. with config.requireDevice
// its sign-in still goes through, so that the game loads and its own login
// popup can say to update (lib/world.js), which a refused sign-in cannot.
// kept by hash, in memory: such a launcher signs in again each time it starts.
const MAX_OUTDATED = 20000;
const outdatedTokens = new Set();
const tokenKey = token => crypto.createHash("sha256").update(String(token)).digest("hex");
const noteLauncher = (token, hasIds) => {
const key = tokenKey(token);
if (hasIds) {
outdatedTokens.delete(key);
return;
}
if (outdatedTokens.size >= MAX_OUTDATED) {
outdatedTokens.delete(outdatedTokens.values().next().value);
}
outdatedTokens.add(key);
};
const launcherOutdated = token => outdatedTokens.has(tokenKey(token));
module.exports = {noteLauncher, launcherOutdated, load, read, banOf, banOfAccount, seen, alts, knownFor, banAccount, accountsUnder, unban, banById, list, idsFor, bansOfAccount, search, bannedId, alerts, alertsOf, forget, clientHash};
+295
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
@@ -70,7 +70,7 @@ const show = (to, subject) => {
// afresh, which brings the disguise with it (`show`). // afresh, which brings the disguise with it (`show`).
const set = (session, id, redraw) => { const set = (session, id, redraw) => {
session.account.disguise = id; session.account.disguise = id;
accounts.save(); accounts.save(session.account);
session.sendXt("dph", -1, 1, session.id, id ? 1 : 0, id || NPC_PHANTOM); session.sendXt("dph", -1, 1, session.id, id ? 1 : 0, id || NPC_PHANTOM);
redraw(session); redraw(session);
}; };
+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]
} }
+92 -22
View File
@@ -1,9 +1,12 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const achievements = require("./achievements.js"); const achievements = require("./achievements.js");
const chatFilter = require("./chatfilter.js");
const chatlog = require("./chatlog.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const dens = require("./dens.js"); const dens = require("./dens.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
@@ -14,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;
@@ -48,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;
@@ -66,28 +77,56 @@ 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.
const senderOf = card => (card.fromId ? accounts.byId(card.fromId) : accounts.byName(card.from)); const senderOf = card => (card.fromId ? accounts.byId(card.fromId) : accounts.byName(card.from));
// the card's gift id: for clothing the id of its picture (ECardInbox hands
// it to SimpleIcon as an accId, which is the def's layerDefId), for the
// rest the def id or the amount.
const giftId = gift => {
const def = gift.type === TYPE_CLOTHING && defpacks.itemDef(gift.def);
return def ? Number(def.layerDefId) : gift.def;
};
// the 17 fields ECard.init takes, for one card. A secret valentine's // the 17 fields ECard.init takes, for one card. A secret valentine's
// sender is known here (reports about it reach them) but not sent. // sender is known here (reports about it reach them) but not sent.
const fields = card => { const fields = card => {
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 ? card.gift.def : 0, card.gift ? card.gift.color : 0, card.gift ? card.gift.name : 0, gift ? giftId(gift) : 0, gift ? gift.color : 0, gift ? gift.name : 0,
card.hq || card.secret ? MEMBER : sender ? sender.accountType : 0, card.hq || card.secret ? MEMBER : sender ? sender.accountType : 0,
0, // name bar data 0, // name bar data
0, // secondary type 0, // secondary type
senderType, senderType,
USERNAME_SHOWN, USERNAME_SHOWN,
"", // additional gift data // additional gift data: for clothing, "item|<def id>", so that the
// patched client (ECardInbox) can show a custom item as itself (its
// own picture and name) and not as the art it was made from. (the
// "|" keeps the game from taking it for an HQ gift's own message.)
gift && gift.type === TYPE_CLOTHING ? `item|${gift.def}` : "",
card.secret ? SECRET_VALENTINE : 0, card.secret ? SECRET_VALENTINE : 0,
]; ];
}; };
@@ -140,13 +179,17 @@ 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).
const message = clean(text).replace(/^(?=[\s+-]*\d)/, "Gift: "); const message = clean(text).replace(/^(?=[\s+-]*\d)/, "Gift: ");
deliver(to, {from: HQ_NAME, hq: true, card: art.cards[0], stamp: 0, msg: message, gift: attached}); deliver(to, {from: HQ_NAME, hq: true, card: art.cards[0], stamp: 0, msg: message, gift: attached});
accounts.save(); accounts.save(to);
return null; return null;
}; };
@@ -157,7 +200,7 @@ module.exports = ({findOnline, blocks}) => {
return false; return false;
} }
deliver(to, {from: HQ_NAME, hq: true, card: art.cards[0], stamp: 0, msg: clean(text).replace(/^(?=[\s+-]*\d)/, "Note: "), gift: null}); deliver(to, {from: HQ_NAME, hq: true, card: art.cards[0], stamp: 0, msg: clean(text).replace(/^(?=[\s+-]*\d)/, "Note: "), gift: null});
accounts.save(); accounts.save(to);
return true; return true;
}; };
@@ -203,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);
} }
@@ -236,7 +279,24 @@ 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);
return;
}
// secret valentines are off on this server: the patched client no
// longer offers them, and a card asked for as one from an older copy
// is not sent with its sender's name shown instead.
if (isValentine === "1") {
reply(FAILED);
return;
}
// the server's filter (lib/chatfilter.js).
const rule = chatFilter.broken(clean(message || ""));
if (rule) {
chatFilter.warn(session);
console.log(`[filter] ${logText(account.username)} in a Jam-a-Gram to ${logText(to.username)}: "${logText(clean(message || ""))}" (${logText(rule)})`);
chatlog.recordTo(account, chatlog.JAMAGRAM, to.username, chatlog.NOT_SENT + clean(message || ""));
reply(FAILED); reply(FAILED);
return; return;
} }
@@ -254,13 +314,14 @@ module.exports = ({findOnline, blocks}) => {
reply(FAILED); reply(FAILED);
return; return;
} }
deliver(to, {from: account.username, fromId: account.id, card: Number(card), stamp: Number(stamp), msg: clean(message || ""), gift, deliver(to, {from: account.username, fromId: account.id, card: Number(card), stamp: Number(stamp), msg: clean(message || ""), gift});
...(isValentine === "1" ? {secret: true} : {})}); // for the panels (lib/chatlog.js), as typed chat is.
chatlog.recordTo(account, chatlog.JAMAGRAM, to.username, clean(message || "") + (gift ? " [with a gift]" : ""));
achievements.add(account, achievements.VARS.jamAGramsSent); achievements.add(account, achievements.VARS.jamAGramsSent);
if (gift) { if (gift) {
achievements.add(account, achievements.VARS.giftsSent); achievements.add(account, achievements.VARS.giftsSent);
} }
accounts.save(); accounts.save(account, to);
reply(SENT); reply(SENT);
}, },
@@ -269,7 +330,7 @@ module.exports = ({findOnline, blocks}) => {
const card = session.account.ecards.find(candidate => candidate.id === Number(msgId)); const card = session.account.ecards.find(candidate => candidate.id === Number(msgId));
if (card) { if (card) {
card.read = true; card.read = true;
accounts.save(); accounts.save(session.account);
} }
session.sendXt("er", -1, msgId, card ? 1 : 0); session.sendXt("er", -1, msgId, card ? 1 : 0);
}, },
@@ -280,7 +341,7 @@ module.exports = ({findOnline, blocks}) => {
const {account} = session; const {account} = session;
const before = account.ecards.length; const before = account.ecards.length;
account.ecards = account.ecards.filter(card => card.id !== Number(msgId)); account.ecards = account.ecards.filter(card => card.id !== Number(msgId));
accounts.save(); accounts.save(account);
session.sendXt("ed", -1, 1, before - account.ecards.length, ...(before === account.ecards.length ? [] : [msgId])); session.sendXt("ed", -1, 1, before - account.ecards.length, ...(before === account.ecards.length ? [] : [msgId]));
}, },
@@ -292,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")))) {
@@ -306,17 +374,17 @@ module.exports = ({findOnline, blocks}) => {
if (accept === "1") { if (accept === "1") {
giveGift(session, gift); giveGift(session, gift);
} }
accounts.save(); accounts.save(session.account);
session.sendXt("eg", -1, msgId, 1); session.sendXt("eg", -1, msgId, 1);
}, },
// [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;
accounts.save(); accounts.save(session.account);
} }
session.sendXt("ei", -1, valid ? 1 : 0); session.sendXt("ei", -1, valid ? 1 : 0);
}, },
@@ -341,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];
+80
View File
@@ -0,0 +1,80 @@
"use strict";
const fs = require("fs");
const path = require("path");
const config = require("../config.js");
const {logText} = require("./logtext.js");
// pictures of emoji, for the patched client's chat bubbles (gui.ChatBalloon):
// the game's font has none, so an emoji typed in chat (with Windows' emoji
// panel, say) is drawn as one of these. they are Twemoji's (CC-BY 4.0,
// jdecked/twemoji on GitHub), asked of config.emojiUpstream once
// each and kept in data/emoji. a name is the emoji's code points in hex,
// joined by "-", as Twemoji names its files ("1f600", "1f468-200d-1f469").
const NAME = /^[0-9a-f]{2,6}(?:-[0-9a-f]{2,6}){0,9}$/;
const MAX_BYTES = 64 * 1024;
const MAX_MISSING = 5000;
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
const DIR = path.join(config.dataDir, "emoji");
const missing = new Set(); // names the upstream does not have
const pending = new Map(); // name -> promise, so that one is asked for once
const isName = name => typeof name === "string" && NAME.test(name);
const fileOf = name => path.join(DIR, `${name}.png`);
const fetchUpstream = async name => {
const res = await fetch(`${config.emojiUpstream}${name}.png`, {signal: AbortSignal.timeout(config.upstreamTimeoutMs)});
if (!res.ok) {
if (res.status === 404 || res.status === 403) {
if (missing.size >= MAX_MISSING) {
missing.clear();
}
missing.add(name);
}
return null;
}
const body = Buffer.from(await res.arrayBuffer());
// a PNG, and a small one, or nothing is kept
if (body.length > MAX_BYTES || !body.subarray(0, 8).equals(PNG_SIGNATURE)) {
console.log(`[emoji] not a picture: ${logText(name)}`);
return null;
}
try {
fs.mkdirSync(DIR, {recursive: true});
const tmp = `${fileOf(name)}.${process.pid}.tmp`;
fs.writeFileSync(tmp, body);
fs.renameSync(tmp, fileOf(name));
}
catch (err) {
console.log(`[emoji] could not keep ${logText(name)}: ${logText(err.message)}`);
}
return body;
};
// the picture for `name`: a Buffer, or null. `mayFetch()`: whether one not
// kept yet may be asked of the upstream for this request (asked only then).
const get = async (name, mayFetch) => {
if (!isName(name) || missing.has(name)) {
return null;
}
try {
return await fs.promises.readFile(fileOf(name));
}
catch (err) {
if (err.code !== "ENOENT") {
return null;
}
}
if (!mayFetch()) {
return null;
}
if (!pending.has(name)) {
pending.set(name, fetchUpstream(name).catch(() => null).finally(() => pending.delete(name)));
}
return pending.get(name);
};
module.exports = {get, isName};
+4 -1
View File
@@ -3,13 +3,15 @@
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const bans = require("./bans.js"); const bans = require("./bans.js");
const chatlog = require("./chatlog.js"); const chatlog = require("./chatlog.js");
const devices = require("./devices.js");
const masterpieces = require("./masterpieces.js"); const masterpieces = require("./masterpieces.js");
const support = require("./support.js"); const support = require("./support.js");
const world = require("./world.js"); const world = require("./world.js");
// an account deleted for good, by its owner (lib/manage.js) or by the admin // an account deleted for good, by its owner (lib/manage.js) or by the admin
// (lib/panel.js), and what was kept about it elsewhere with it: its chat // (lib/panel.js), and what was kept about it elsewhere with it: its chat
// lines, its appeal, its feedback and username requests, and the paintings // lines, its appeal, its feedback and username requests, the computers it
// was used from (lib/devices.js), and the paintings
// it made (from whoever holds one by now). what stays is said in the // it made (from whoever holds one by now). what stays is said in the
// privacy policy (public/privacy.html): the record of bans and of what // privacy policy (public/privacy.html): the record of bans and of what
// moderators did, under the name it had, until lib/retention.js ends it. // moderators did, under the name it had, until lib/retention.js ends it.
@@ -20,6 +22,7 @@ module.exports = account => {
} }
bans.forget(account); bans.forget(account);
chatlog.forget(account); chatlog.forget(account);
devices.forget(account);
support.forget(account); support.forget(account);
accounts.remove(account); accounts.remove(account);
}; };
+53 -2
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}
] ]
+465 -43
View File
@@ -1,23 +1,34 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto"); const crypto = require("crypto");
const fs = require("fs"); const fs = require("fs");
const http = require("http"); const http = require("http");
const https = require("https"); const https = require("https");
const path = require("path"); const path = require("path");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const customItems = require("./customitems.js");
const itemArt = require("./itemart.js");
const emoji = require("./emoji.js");
const modlog = require("./modlog.js");
const roles = require("./roles.js");
const admin = require("./admin.js"); const admin = require("./admin.js");
const bans = require("./bans.js"); const bans = require("./bans.js");
const captcha = require("./captcha.js"); const captcha = require("./captcha.js");
const cdn = require("./cdn.js"); const cdn = require("./cdn.js");
const config = require("../config.js"); const config = require("../config.js");
const devices = require("./devices.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const manage = require("./manage.js"); const manage = require("./manage.js");
const modpanel = require("./modpanel.js"); const modpanel = require("./modpanel.js");
const discordBot = require("./discordbot.js");
const badges = require("./badges.js"); const badges = require("./badges.js");
const extraMusic = require("./extramusic.js"); const extraMusic = require("./extramusic.js");
const customMusic = require("./custommusic.js");
const itemControl = require("./itemcontrol.js");
const masterpieces = require("./masterpieces.js"); const masterpieces = require("./masterpieces.js");
const themeRooms = require("./themerooms.js");
const panel = require("./panel.js"); const panel = require("./panel.js");
const totp = require("./totp.js"); const totp = require("./totp.js");
const world = require("./world.js"); const world = require("./world.js");
@@ -43,6 +54,19 @@ const MIME = {
".otf": "font/otf", ".otf": "font/otf",
}; };
// The desktop webview caches the SWF aggressively. Include the local SWF's
// timestamp in its URL so a freshly built client is actually picked up after
// the server restarts, without making an operator remember to bump a config
// value by hand.
const clientRevision = () => {
try {
return Math.floor(fs.statSync(config.clientSwf).mtimeMs).toString(36);
}
catch (_) {
return "unknown";
}
};
const flashVars = () => ({ const flashVars = () => ({
content: config.baseUrl, content: config.baseUrl,
// the game's own server to the SWF, whatever its name: it loads the card // the game's own server to the SWF, whatever its name: it loads the card
@@ -62,10 +86,14 @@ const flashVars = () => ({
// member or not may be chosen on any server (lib/accounts.js) // member or not may be chosen on any server (lib/accounts.js)
membershipChoice: true, membershipChoice: true,
smoke_version: config.deployVersion, smoke_version: config.deployVersion,
clientURL: `${config.baseUrl}${config.deployVersion}/ajclient.swf?v=${config.buildVersion}`, clientURL: `${config.baseUrl}${config.deployVersion}/ajclient.swf?v=${config.buildVersion}-${clientRevision()}`,
startupRoom: config.startupRoom, startupRoom: config.startupRoom,
// "-1" turns the client's stats socket off. // "-1" turns the client's stats socket off.
sbStatTrackerIp: "-1", sbStatTrackerIp: "-1",
// the client's Discord rich presence (its app/discord.js): the Discord
// application it shows as, "" for none, and where its button goes.
discordAppId: config.discord.clientId,
presenceUrl: `${config.siteUrl}download`,
sbStatModulator: "0", sbStatModulator: "0",
currentTimestamp: Math.floor(Date.now() / 1000), currentTimestamp: Math.floor(Date.now() / 1000),
country: "US", country: "US",
@@ -138,6 +166,161 @@ const formParts = (contentType, body) => {
return parts; return parts;
}; };
// a custom item's picture set or taken away (?kind=&id=[&remove=1], the
// picture as the body): by its maker, or by staff who make items. who asks
// is the holder of a game's token (/api/itemart?token=, the client's Item
// Maker), or `signedIn` (req) -> account: the account page's or the
// moderator panel's session, whose cookies only go to their own paths
// (/account/api/itemart, /mod/api/itemart), from this server's own pages.
// every answer is 200, with {ok} or {error}: the game's Flash cannot read
// the body of any other.
// `adminSignedIn` (req) -> boolean: the admin panel's session, which acts as
// staff who make items, and is written down as "admin".
const itemArtUpload = async (req, res, url, from, signedIn = null, adminSignedIn = null) => {
if ((req.method === "GET" || req.method === "HEAD") && (signedIn || adminSignedIn)) {
itemArtView(req, res, url, signedIn, adminSignedIn);
return;
}
if (req.method !== "POST" || !limits.originAllowed(req)) {
send(res, 200, {error: "forbidden"});
return;
}
const token = url.searchParams.get("token");
const holder = token ? accounts.byToken(token) : null;
const asAdmin = Boolean(adminSignedIn && adminSignedIn(req));
const account = asAdmin ? null : signedIn ? signedIn(req) : holder && world.moderation.banRemaining(holder) === 0 ? holder : null;
if (!account && !asAdmin) {
send(res, 200, {error: "Sign in first."});
return;
}
const kind = url.searchParams.get("kind");
const entry = customItems.get(kind, url.searchParams.get("id"));
if (!entry) {
send(res, 200, {error: "No such custom item."});
return;
}
const staffMay = asAdmin || roles.can(account, "items.create");
if (!staffMay && entry.ownerId !== account.id) {
send(res, 200, {error: "That is not one of your items."});
return;
}
const playerItems = require("./playeritems.js");
const refusal = staffMay || url.searchParams.get("remove") === "1" ? null : playerItems.uploadRefusal(account, from.local);
if (refusal) {
send(res, 200, refusal);
return;
}
if (!from.local && !asAdmin && !artUploads.allow(account.id)) {
send(res, 200, {error: "Too many pictures today. Try again tomorrow."});
return;
}
let result;
if (url.searchParams.get("remove") === "1") {
result = itemArt.remove(kind, entry.id);
}
else {
const data = await readBody(req, itemArt.MAX_UPLOAD + 1).catch(() => null);
// a player's own picture waits for a moderator unless the admin says not;
// one turned away before may not come back.
const waits = !staffMay && playerItems.pictureWaits();
result = data ? await itemArt.set(kind, entry.id, data, waits, staffMay ? null : playerItems.pictureRefused)
: {error: `That picture is too big: ${Math.round(itemArt.MAX_UPLOAD / 1024 / 1024)} MB at most.`};
}
if (result.ok) {
const owner = entry.ownerId === null ? null : accounts.byId(entry.ownerId);
modlog.record(asAdmin ? "admin" : account.username, url.searchParams.get("remove") === "1" ? "item picture removed" : "item picture set",
owner && owner !== account ? owner.username : "", `${kind} ${entry.id} ${entry.name}`);
}
send(res, 200, result);
};
// music tracks uploaded in the panels (lib/custommusic.js), at
// /mod/api/music (staff with "music.upload") and /admin/api/music:
// GET: the tracks; GET ?play=<id>: one's file, to listen to;
// POST ?name=&cost=&inShop=1, the MP3 as the body: a new track;
// POST ?delete=<id>: the track deleted, and taken from every player.
// `signedIn` (req) -> account: the moderator panel's session;
// `adminSignedIn` (req) -> boolean: the admin panel's, written down as "admin".
const musicUploads = limits.limiter(30, 3600000); // tracks an hour, per staff member
const musicRoute = async (req, res, url, from, signedIn = null, adminSignedIn = null) => {
res.setHeader("Cache-Control", "no-store");
const asAdmin = Boolean(adminSignedIn && adminSignedIn(req));
const account = asAdmin ? null : signedIn ? signedIn(req) : null;
if (!asAdmin && !(account && roles.can(account, "music.upload"))) {
send(res, 403, {error: "Your role cannot upload music."});
return;
}
const by = asAdmin ? "admin" : account.username;
if (req.method === "GET" || req.method === "HEAD") {
if (url.searchParams.has("play")) {
const track = customMusic.file(url.searchParams.get("play"));
if (!track) {
send(res, 404, "Not found", "text/plain");
return;
}
res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox");
res.setHeader("X-Content-Type-Options", "nosniff");
send(res, 200, track.data, "audio/mpeg");
return;
}
send(res, 200, {tracks: customMusic.list(), maxBytes: customMusic.MAX_BYTES});
return;
}
if (req.method !== "POST" || !limits.originAllowed(req)) {
send(res, 403, {error: "forbidden"});
return;
}
if (url.searchParams.has("delete")) {
const entry = customItems.get("den", url.searchParams.get("delete"));
if (!entry || !entry.audio) {
send(res, 404, {error: "No such uploaded track."});
return;
}
const result = itemControl.deleteCustom("den", entry.id, world);
if (result.ok) {
modlog.record(by, "music deleted", "", `den ${entry.id} ${entry.name}`);
}
send(res, result.ok ? 200 : 400, result);
return;
}
if (!asAdmin && !musicUploads.allow(account.id)) {
send(res, 429, {error: "Too many uploads. Try again later."});
return;
}
const data = await readBody(req, customMusic.MAX_BYTES + 1).catch(() => null);
if (!data) {
send(res, 413, {error: `That file is too big: ${customMusic.MAX_BYTES / 1024 / 1024} MB at most.`});
return;
}
const result = customMusic.add(data, {name: url.searchParams.get("name"), cost: url.searchParams.get("cost") || 0,
inShop: url.searchParams.get("inShop") === "1"}, by);
if (result.error) {
send(res, 400, result);
return;
}
modlog.record(by, "music uploaded", "", `den ${result.item.id} ${result.item.name}`);
send(res, 200, {ok: `"${result.item.name}" is den item ${result.item.id}. Players can get it from the item finder now${result.item.inShop ? ", and the shop" : ""}.`,
item: {id: result.item.id, name: result.item.name}});
};
// a picture still waiting for a moderator, which /itemart/ does not serve:
// to its maker (the account page) and to staff who review or make items.
const itemArtView = (req, res, url, signedIn, adminSignedIn) => {
res.setHeader("Cache-Control", "private, no-store");
const asAdmin = Boolean(adminSignedIn && adminSignedIn(req));
const account = asAdmin ? null : signedIn ? signedIn(req) : null;
const entry = customItems.get(url.searchParams.get("kind"), url.searchParams.get("id"));
const allowed = entry && (asAdmin || (account && (entry.ownerId === account.id || roles.can(account, "items.approve") || roles.can(account, "items.create"))));
const picture = allowed ? itemArt.file(entry.kind, entry.id, true) : null;
if (!picture) {
send(res, 404, "Not found", "text/plain");
return;
}
res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox");
res.setHeader("X-Content-Type-Options", "nosniff");
send(res, 200, picture.data, `image/${picture.type}`);
};
const send = (res, status, body, type = "application/json") => { const send = (res, status, body, type = "application/json") => {
const data = Buffer.isBuffer(body) ? body : Buffer.from(typeof body === "string" ? body : JSON.stringify(body)); const data = Buffer.isBuffer(body) ? body : Buffer.from(typeof body === "string" ? body : JSON.stringify(body));
res.writeHead(status, {"Content-Type": type, "Content-Length": data.length}); res.writeHead(status, {"Content-Type": type, "Content-Length": data.length});
@@ -151,9 +334,12 @@ const send = (res, status, body, type = "application/json") => {
const TEN_MINUTES_MS = 600000; const TEN_MINUTES_MS = 600000;
const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS); const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS);
const searches = limits.limiter(120, 60000); // item finder searches, per address const searches = limits.limiter(120, 60000); // item finder searches, per address
const MISSING_ASSET_SECONDS = 600; // how long a client may keep the CDN's "no such file"
const cacheMisses = limits.limiter(config.cacheMissesPerTenMinutes, TEN_MINUTES_MS); // files fetched from the official CDN for one address const cacheMisses = limits.limiter(config.cacheMissesPerTenMinutes, TEN_MINUTES_MS); // files fetched from the official CDN for one address
const errorReports = limits.limiter(config.errorReportsPerMinute, 60000); const errorReports = limits.limiter(config.errorReportsPerMinute, 60000);
const paintingPosts = limits.limiter(60, TEN_MINUTES_MS); // per address; each also needs a token from the game const paintingPosts = limits.limiter(60, TEN_MINUTES_MS); // per address; each also needs a token from the game
const artUploads = limits.limiter(10, 24 * 3600000); // custom items' pictures, per account a day
const emojiFetches = limits.limiter(600, TEN_MINUTES_MS); // emoji pictures not kept yet, asked of the upstream, per address
const PAINTING_PATH = /^\/masterpieces\/([0-9a-f-]{36})$/; const PAINTING_PATH = /^\/masterpieces\/([0-9a-f-]{36})$/;
// where clients ask for the HUD artwork; ours is a changed copy. // where clients ask for the HUD artwork; ours is a changed copy.
@@ -169,10 +355,31 @@ const keepClientError = text => {
.then(size => (size < MAX_CLIENT_ERROR_FILE ? fs.promises.appendFile(CLIENT_ERROR_FILE, text) : null)) .then(size => (size < MAX_CLIENT_ERROR_FILE ? fs.promises.appendFile(CLIENT_ERROR_FILE, text) : null))
.catch(() => {}); .catch(() => {});
}; };
// the same error from many clients (one broken item, met by everyone who
// sees it) is written once in REPEAT_WINDOW_MS, and the next time after that
// with how many there were between: a log, and a thread that waits for it,
// had a stack of twenty lines several times a second. null for one to leave
// out; else what to add to its line.
const REPEAT_WINDOW_MS = 600000;
const MAX_REMEMBERED_ERRORS = 1000;
const recentErrors = new Map(); // section and message -> {at, more}
const repeatedError = text => {
const seen = recentErrors.get(text);
if (seen && Date.now() - seen.at < REPEAT_WINDOW_MS) {
seen.more++;
return null;
}
recentErrors.delete(text);
if (recentErrors.size >= MAX_REMEMBERED_ERRORS) {
recentErrors.delete(recentErrors.keys().next().value);
}
recentErrors.set(text, {at: Date.now(), more: 0});
return seen && seen.more > 0 ? `\n\t(and ${seen.more} more like it in the ${Math.round(REPEAT_WINDOW_MS / 60000)} minutes before)` : "";
};
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 = [
@@ -227,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)) {
@@ -348,10 +556,11 @@ const renameAndSignIn = (res, body, from) => {
delete account.nameRejected; delete account.nameRejected;
manage.forget(account); manage.forget(account);
accounts.recordLogin(account, "launcher", from.address); accounts.recordLogin(account, "launcher", from.address);
accounts.save(); accounts.save(account);
console.log(`[accounts] a rejected username was replaced by "${account.username}"`); console.log(`[accounts] a rejected username was replaced by "${logText(account.username)}"`);
accounts.setLoginChoices(account, body.login_choices); accounts.setLoginChoices(account, body.login_choices);
const token = accounts.issueToken(account); const token = accounts.issueToken(account);
devices.noteLauncher(token, Boolean(devices.read(body.device)));
send(res, 200, {auth_token: token, refresh_token: token, device_token: entry.deviceToken}); send(res, 200, {auth_token: token, refresh_token: token, device_token: entry.deviceToken});
}; };
@@ -361,36 +570,63 @@ const authenticate = async (req, res, from) => {
renameAndSignIn(res, body, from); renameAndSignIn(res, body, from);
return; return;
} }
const byRefresh = body.refresh_token !== undefined; // the computer it is on (lib/devices.js): a client that does not say is
// out of date (before 1.3.0) or not ours. it is signed in all the same,
// and its token noted (signInChecked): with config.requireDevice the game
// then loads and its login popup says to update (lib/world.js), where a
// refusal here only ever showed "The server refused the login (426)".
const device = devices.read(body.device);
const accountKey = String(body.username).trim().toLowerCase(); const accountKey = String(body.username).trim().toLowerCase();
if (!from.local && failuresByAddress.blocked(from.key)) { if (!from.local && failuresByAddress.blocked(from.key)) {
send(res, 429, {error_code: 429, error: "too_many_attempts"}); send(res, 429, {error_code: 429, error: "too_many_attempts"});
return; return;
} }
// A saved sign-in ("remember me"): the account its token is good for,
// which is what the rest goes by. a token is only ever given after a
// whole sign-in (password, captcha and 2FA code), so one that is good
// stands in for them; one that is not is refused here, whatever else
// the request says. (Whether the request offers a token is not what
// decides: only the server's own answer for it.)
const saved = accounts.byToken(body.refresh_token); // null for none, or for one that is not good
if (saved) {
await signInChecked(res, body, from, saved, true, device);
return;
}
if (body.refresh_token !== undefined) {
failuresByAddress.record(from.key);
// error_code 100 = expired refresh token
send(res, 401, {error_code: 100});
return;
}
// a password is not looked at before the captcha. the custom client // a password is not looked at before the captcha. the custom client
// knows these errors; the official launcher shows them as a wrong password. // knows these errors; the official launcher shows them as a wrong password.
const captchaProblem = byRefresh ? null : await captcha.check(body, from, "login", accounts.byName(accountKey)); const captchaProblem = await captcha.check(body, from, "login", accounts.byName(accountKey));
if (captchaProblem) { if (captchaProblem) {
send(res, captchaProblem === "captcha_unavailable" ? 503 : 401, {error_code: 101, error: captchaProblem}); send(res, captchaProblem === "captcha_unavailable" ? 503 : 401, {error_code: 101, error: captchaProblem});
return; return;
} }
const account = byRefresh const account = await accounts.authenticateAsync(body.username, body.password);
? accounts.byToken(body.refresh_token)
: await accounts.authenticateAsync(body.username, body.password);
if (!account) { if (!account) {
failuresByAddress.record(from.key); failuresByAddress.record(from.key);
if (!byRefresh) { // A wrong password shows in the account's own login history.
// A wrong password shows in the account's own login history. const tried = accounts.byName(accountKey);
const tried = accounts.byName(accountKey); if (tried) {
if (tried) { accounts.recordLogin(tried, "launcher", from.address, false);
accounts.recordLogin(tried, "launcher", from.address, false); accounts.save(tried);
accounts.save();
}
} }
// error_code 100 = expired refresh token, 101 = wrong credentials // error_code 101 = wrong credentials
send(res, 401, {error_code: byRefresh ? 100 : 101}); send(res, 401, {error_code: 101});
return; return;
} }
await signInChecked(res, body, from, account, false, device);
};
// the rest of a sign-in, for an account whose password was right (`saved`
// false) or whose saved sign-in's token was good (`saved` true; then it is
// not asked for a 2FA code again, and the token it has is the one it keeps).
// `device`: the computer it is on (lib/devices.js), or null for a client that does not say.
const signInChecked = async (res, body, from, account, saved, device) => {
const byRefresh = saved === true;
// banned: said here, with how long is left (-1 for good), where a client // banned: said here, with how long is left (-1 for good), where a client
// can show it. the game itself would only be refused at its socket with // can show it. the game itself would only be refused at its socket with
// the one line it has for that, which says neither. the password (or the // the one line it has for that, which says neither. the password (or the
@@ -408,6 +644,15 @@ const authenticate = async (req, res, from) => {
send(res, 401, {error_code: 101, error: "address_banned", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason}); send(res, 401, {error_code: 101, error: "address_banned", banned_seconds: world.moderation.PERMANENT, ban_reason: addressBan.reason});
return; return;
} }
// A banned computer (lib/devices.js): for good, whichever account. a
// client that sent no ids (before 1.3.0) is judged by the hardware the
// account was seen on.
const deviceBan = device ? devices.banOf(device) : devices.banOfAccount(account);
if (deviceBan) {
console.log(`[devices] "${logText(account.username)}" refused: hardware banned (ban ${logText(deviceBan.id)})`);
send(res, 401, {error_code: 101, error: "device_banned", banned_seconds: world.moderation.PERMANENT, ban_reason: deviceBan.reason});
return;
}
// locked by its owner on the account page: the password is right, and // locked by its owner on the account page: the password is right, and
// still nobody gets in. the launcher shows this as a failed sign-in. // still nobody gets in. the launcher shows this as a failed sign-in.
if (account.locked) { if (account.locked) {
@@ -429,7 +674,7 @@ const authenticate = async (req, res, from) => {
if (!totp.verify(account, String(body.totp))) { if (!totp.verify(account, String(body.totp))) {
failuresByAddress.record(from.key); failuresByAddress.record(from.key);
accounts.recordLogin(account, "launcher", from.address, false); accounts.recordLogin(account, "launcher", from.address, false);
accounts.save(); accounts.save(account);
send(res, 401, {error_code: 101, error: "totp_wrong", captcha_pass: captcha.issuePass(account, from)}); send(res, 401, {error_code: 101, error: "totp_wrong", captcha_pass: captcha.issuePass(account, from)});
return; return;
} }
@@ -440,17 +685,21 @@ const authenticate = async (req, res, from) => {
// its username was rejected: a new one first (above). the official // its username was rejected: a new one first (above). the official
// launcher shows this as a wrong password; the account page asks too. // launcher shows this as a wrong password; the account page asks too.
if (account.nameRejected) { if (account.nameRejected) {
accounts.save(); // a two-step code just used stays used accounts.save(account); // a two-step code just used stays used
send(res, 401, {error_code: 101, error: "name_rejected", rename_ticket: renameTicket(account, deviceToken)}); send(res, 401, {error_code: 101, error: "name_rejected", rename_ticket: renameTicket(account, deviceToken)});
return; return;
} }
if (device) {
devices.seen(account, device, other => world.moderation.banRemaining(other) !== 0);
}
if (!byRefresh) { if (!byRefresh) {
accounts.recordLogin(account, "launcher", from.address); accounts.recordLogin(account, "launcher", from.address);
accounts.save();
} }
accounts.save(account);
// the custom client's advanced settings; the official launcher sends none. // the custom client's advanced settings; the official launcher sends none.
accounts.setLoginChoices(account, body.login_choices); accounts.setLoginChoices(account, body.login_choices);
const token = byRefresh ? body.refresh_token : accounts.issueToken(account); const token = byRefresh ? body.refresh_token : accounts.issueToken(account);
devices.noteLauncher(token, Boolean(device));
send(res, 200, {auth_token: token, refresh_token: token, device_token: deviceToken}); send(res, 200, {auth_token: token, refresh_token: token, device_token: deviceToken});
}; };
@@ -471,6 +720,10 @@ const player = (req, res) => {
}; };
const handle = async (req, res) => { const handle = async (req, res) => {
// over https, browsers are told to keep to it (a year)
if (config.secureCookies) {
res.setHeader("Strict-Transport-Security", "max-age=31536000");
}
const url = new URL(req.url, config.baseUrl); const url = new URL(req.url, config.baseUrl);
const route = `${req.method} ${url.pathname}`; const route = `${req.method} ${url.pathname}`;
@@ -486,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).
@@ -510,10 +801,29 @@ const handle = async (req, res) => {
send(res, 404, "Not found", "text/plain"); send(res, 404, "Not found", "text/plain");
return; return;
} }
if (dashboardAdmin) {
url.pathname = url.pathname.startsWith("/dashboard/api/admin")
? url.pathname.replace("/dashboard/api/admin", "/admin/api")
: url.pathname.replace("/dashboard/admin", "/admin");
}
if (url.pathname === "/admin/api/itemart") {
res.setHeader("Cache-Control", "no-store");
await itemArtUpload(req, res, url, from, null, panel.signedIn);
return;
}
if (url.pathname === "/admin/api/music") {
await musicRoute(req, res, url, from, null, panel.signedIn);
return;
}
await panel.handle(req, res, url, from, {send, readJson}); await panel.handle(req, res, url, from, {send, readJson});
return; return;
} }
if (isAccount && url.pathname === "/account/api/itemart") {
res.setHeader("Cache-Control", "no-store");
await itemArtUpload(req, res, url, from, manage.signedInAs);
return;
}
if (isAccount) { if (isAccount) {
await manage.handle(req, res, url, from, {send, readJson}); await manage.handle(req, res, url, from, {send, readJson});
return; return;
@@ -521,6 +831,20 @@ const handle = async (req, res) => {
// and the moderator panel (lib/modpanel.js), which is there for anyone to // and the moderator panel (lib/modpanel.js), which is there for anyone to
// reach: its moderators are players, wherever they are. // reach: its moderators are players, wherever they are.
if (dashboardStaff) {
url.pathname = url.pathname.startsWith("/dashboard/api/staff")
? url.pathname.replace("/dashboard/api/staff", "/mod/api")
: url.pathname.replace("/dashboard/staff", "/mod");
}
if (isMod && url.pathname === "/mod/api/itemart") {
res.setHeader("Cache-Control", "no-store");
await itemArtUpload(req, res, url, from, modpanel.signedInAs);
return;
}
if (isMod && url.pathname === "/mod/api/music") {
await musicRoute(req, res, url, from, modpanel.signedInAs);
return;
}
if (isMod) { if (isMod) {
await modpanel.handle(req, res, url, from, {send, readJson}); await modpanel.handle(req, res, url, from, {send, readJson});
return; return;
@@ -546,6 +870,39 @@ const handle = async (req, res) => {
return; return;
} }
// custom items' own pictures (lib/itemart.js): served as the picture
// they are and nothing else.
const artPath = /^\/itemart\/(clothing|den)\/(\d{1,9})\.png$/.exec(url.pathname);
if (artPath && (req.method === "GET" || req.method === "HEAD")) {
const picture = itemArt.file(artPath[1], artPath[2]);
if (!picture) {
send(res, 404, "Not found", "text/plain");
return;
}
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox");
res.setHeader("Content-Disposition", "inline");
send(res, 200, picture.data, `image/${picture.type}`);
return;
}
// emoji pictures for chat bubbles (lib/emoji.js)
const emojiPath = /^\/emoji\/([0-9a-f-]{2,80})\.png$/.exec(url.pathname);
if (emojiPath && (req.method === "GET" || req.method === "HEAD")) {
const picture = await emoji.get(emojiPath[1], () => from.local || emojiFetches.allow(from.key));
if (!picture) {
send(res, 404, "Not found", "text/plain");
return;
}
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox");
send(res, 200, picture, "image/png");
return;
}
if (url.pathname === "/api/itemart") {
await itemArtUpload(req, res, url, from);
return;
}
if (url.pathname.startsWith("/api/")) { if (url.pathname.startsWith("/api/")) {
// the item finder's API changes accounts, so other sites open in a // the item finder's API changes accounts, so other sites open in a
// browser on this machine must not be able to call it. // browser on this machine must not be able to call it.
@@ -652,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"]);
@@ -687,9 +1048,12 @@ const handle = async (req, res) => {
const section = String(report.section).slice(0, 20).replace(/[^\w-]/g, "?"); const section = String(report.section).slice(0, 20).replace(/[^\w-]/g, "?");
const trace = message.startsWith("media "); const trace = message.startsWith("media ");
if (trace ? config.logPackets : from.local || errorReports.allow(from.key)) { if (trace ? config.logPackets : from.local || errorReports.allow(from.key)) {
console.log(`[${trace ? "client-trace" : "client-error"}] (${section}) ${message}`); const again = trace ? "" : repeatedError(`${section} ${message}`);
if (!trace) { if (again !== null) {
keepClientError(`${new Date().toISOString()} (${section}) ${message}\n`); console.log(`[${logText(trace ? "client-trace" : "client-error")}] (${logText(section)}) ${logText(message)}${logText(again)}`);
if (!trace) {
keepClientError(`${new Date().toISOString()} (${section}) ${message}${again}\n`);
}
} }
} }
send(res, 200, {}); send(res, 200, {});
@@ -709,29 +1073,56 @@ const handle = async (req, res) => {
return; return;
} }
const parts = formParts(req.headers["content-type"], await readBody(req, masterpieces.MAX_IMAGE_BYTES + 16 * 1024)); const parts = formParts(req.headers["content-type"], await readBody(req, masterpieces.MAX_IMAGE_BYTES + 16 * 1024));
const uuid = masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image")); const {uuid, refusal, maker} = await masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image"));
// the game only says it could not be sent: HQ says why
if (refusal && maker) {
world.tellAccount(maker, refusal);
}
send(res, 200, uuid ? {success: true, uuid} : {success: false}); send(res, 200, uuid ? {success: true, uuid} : {success: false});
return; return;
} }
case "GET /crossdomain.xml": case "GET /crossdomain.xml":
send(res, 200, CROSS_DOMAIN, "text/xml"); send(res, 200, CROSS_DOMAIN, "text/xml");
return; return;
// the game's rules window (AJClient.showRules) shows this file, read
// again on every ask so it can be changed on a running server; made
// with a placeholder when there is none.
case "GET /rules.txt": {
const file = path.join(config.dataDir, "rules.txt");
let text;
try {
text = await fs.promises.readFile(file, "utf8");
}
catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
text = "Example\n";
await fs.promises.writeFile(file, text, {flag: "wx"}).catch(() => {});
}
res.setHeader("Cache-Control", "no-cache");
res.setHeader("X-Content-Type-Options", "nosniff");
send(res, 200, text.slice(0, MAX_RULES_LENGTH), "text/plain; charset=utf-8");
return;
}
case "GET /gameClient/game/index.html": case "GET /gameClient/game/index.html":
// not to be put in a frame of anyone's; the client shows it in a view of its own. // not to be put in a frame of anyone's; the client shows it in a view of its own.
res.setHeader("X-Frame-Options", "DENY"); res.setHeader("X-Frame-Options", "DENY");
res.setHeader("Referrer-Policy", "no-referrer"); res.setHeader("Referrer-Policy", "no-referrer");
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "game.html")), MIME[".html"]); // the admin's switch for the theatre browser (lib/panel.js), for the page to read
send(res, 200, String(await fs.promises.readFile(path.join(config.publicDir, "game.html")))
.replace("<html>", panel.theatreBrowserOn() ? '<html data-theatre-browser="on">' : "<html>"), MIME[".html"]);
return; return;
} }
if (req.method !== "GET" && req.method !== "HEAD") { if (req.method !== "GET" && req.method !== "HEAD") {
console.log(`[http] unhandled ${route}`); console.log(`[http] unhandled ${logText(route)}`);
send(res, 404, {error: "not_found"}); send(res, 404, {error: "not_found"});
return; return;
} }
if (config.logPackets) { if (config.logPackets) {
console.log(`[http] GET ${url.pathname}`); console.log(`[http] GET ${logText(url.pathname)}`);
} }
// asset SWFs import their fonts from this fixed path next to the game page; // asset SWFs import their fonts from this fixed path next to the game page;
@@ -755,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;
} }
@@ -771,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
@@ -787,10 +1192,21 @@ 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) {
console.log(`[http] 404 ${url.pathname}`); // 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
// answer a while, and it was logged when the CDN said so ([cdn] 404).
if (cdn.knownMissing(themed ? `${themed[1]}/roomDefs/${themed[3]}` : relPath)) {
res.setHeader("Cache-Control", `public, max-age=${MISSING_ASSET_SECONDS}`);
}
else {
console.log(`[http] 404 ${logText(url.pathname)}`);
}
send(res, 404, "Not found", "text/plain"); send(res, 404, "Not found", "text/plain");
return; return;
} }
@@ -801,7 +1217,8 @@ const handle = async (req, res) => {
const start = () => new Promise((resolve, reject) => { const start = () => new Promise((resolve, reject) => {
const onRequest = (req, res) => { const onRequest = (req, res) => {
handle(req, res).catch(err => { handle(req, res).catch(err => {
console.log(`[http] ${req.method} ${req.url} failed: ${err.message}`); // the path only: a query may hold a login token (the item finder's, the Item Maker's)
console.log(`[http] ${logText(req.method)} ${logText(String(req.url).split("?")[0])} failed: ${logText(err.message)}`);
if (!res.headersSent) { if (!res.headersSent) {
send(res, 500, {error: "server_error"}); send(res, 500, {error: "server_error"});
} }
@@ -815,12 +1232,15 @@ const start = () => new Promise((resolve, reject) => {
: http.createServer(onRequest); : http.createServer(onRequest);
// nobody gets to hold a request open by trickling it in, nor a reply by // nobody gets to hold a request open by trickling it in, nor a reply by
// never reading it; and there is an end to how many connections there // never reading it; and there is an end to how many connections there
// may be, in all and from one address. // may be, in all and from one address. a proxy in front (nginx) keeps
// its own count of those; its connections here are not counted, since
// turning them away only had it fail the requests of players it had
// already let in, who then asked again.
server.requestTimeout = 30000; server.requestTimeout = 30000;
server.headersTimeout = 15000; server.headersTimeout = 15000;
server.timeout = config.httpSocketTimeoutMs; server.timeout = config.httpSocketTimeoutMs;
server.maxConnections = config.maxHttpConnections;
const open = new Map(); // address, as limits count it -> connections const open = new Map(); // address, as limits count it -> connections
let openInAll = 0;
server.on("connection", socket => { server.on("connection", socket => {
const address = limits.key(socket.remoteAddress); const address = limits.key(socket.remoteAddress);
// behind a proxy every connection is the proxy's own. // behind a proxy every connection is the proxy's own.
@@ -828,12 +1248,14 @@ const start = () => new Promise((resolve, reject) => {
return; return;
} }
const count = (open.get(address) || 0) + 1; const count = (open.get(address) || 0) + 1;
if (count > config.maxHttpConnectionsPerAddress) { if (count > config.maxHttpConnectionsPerAddress || openInAll >= config.maxHttpConnections) {
socket.destroy(); socket.destroy();
return; return;
} }
open.set(address, count); open.set(address, count);
openInAll++;
socket.once("close", () => { socket.once("close", () => {
openInAll--;
const left = open.get(address) - 1; const left = open.get(address) - 1;
if (left > 0) { if (left > 0) {
open.set(address, left); open.set(address, left);
@@ -845,7 +1267,7 @@ const start = () => new Promise((resolve, reject) => {
}); });
server.once("error", reject); server.once("error", reject);
server.listen(config.httpPort, config.bindAddress, () => { server.listen(config.httpPort, config.bindAddress, () => {
console.log(`[http] listening on ${config.bindAddress}:${config.httpPort}${config.webTls ? " (TLS)" : ""}`); console.log(`[http] listening on ${logText(config.bindAddress)}:${logText(config.httpPort)}${logText(config.webTls ? " (TLS)" : "")}`);
resolve(server); resolve(server);
}); });
}); });
+52
View File
@@ -0,0 +1,52 @@
"use strict";
const config = require("../config.js");
// Google Cloud Vision SafeSearch detects adult and racy material. We keep
// this dependency-free and use its REST API so deploying the server needs no
// service-account files or Google SDK in node_modules.
const UNSAFE = new Set(["LIKELY", "VERY_LIKELY"]);
const TIMEOUT_MS = 10000;
// {blocked, error}; `error` deliberately fails closed when the scanner is
// enabled: accepting an image while the safety service is unavailable would
// make this protection easy to bypass.
const scan = async image => {
if (!config.googleVision) {
return {blocked: false};
}
if (!Buffer.isBuffer(image) || image.length === 0) {
return {blocked: true, error: "That picture could not be checked for safety."};
}
const abort = new AbortController();
const timer = setTimeout(() => abort.abort(), TIMEOUT_MS);
try {
const response = await fetch(config.googleVision.endpoint, {
method: "POST",
headers: {"Content-Type": "application/json"},
signal: abort.signal,
body: JSON.stringify({
requests: [{image: {content: image.toString("base64")}, features: [{type: "SAFE_SEARCH_DETECTION"}]}],
}),
});
const result = await response.json().catch(() => null);
const safeSearch = result && result.responses && result.responses[0] && result.responses[0].safeSearchAnnotation;
if (!response.ok || !safeSearch) {
console.error(`[image-moderation] Google Vision request failed (${response.status})`);
return {blocked: true, error: "Picture safety checking is temporarily unavailable. Please try again."};
}
if (UNSAFE.has(safeSearch.adult) || UNSAFE.has(safeSearch.racy)) {
return {blocked: true, error: "That picture was blocked because it may contain nudity or other NSFW content."};
}
return {blocked: false};
}
catch (err) {
console.error(`[image-moderation] Google Vision request failed: ${err.message}`);
return {blocked: true, error: "Picture safety checking is temporarily unavailable. Please try again."};
}
finally {
clearTimeout(timer);
}
};
module.exports = {scan};
+403
View File
@@ -0,0 +1,403 @@
"use strict";
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const zlib = require("zlib");
const config = require("../config.js");
const customItems = require("./customitems.js");
const imageModeration = require("./image-moderation.js");
// custom items' own pictures: uploaded by the item's maker (or staff), shown
// by the patched client in place of the item's icon, and for a den item in
// place of the item standing in a den (AJClient.customArtUrl). worn
// clothing keeps the art it was made from: that is drawn for every animal
// and pose, which one picture cannot be.
//
// a picture is checked before it is kept: a PNG, a JPEG or a GIF by its own
// bytes (whatever it is called), of a sensible size, and kept without what
// else such files carry (a photo's EXIF, with where it was taken; PNG text;
// GIF comments). a BMP is made a PNG. (the pages and the game turn other
// kinds, and pictures too big, into a PNG before they send them.)
// kept as data/itemart/<kind>-<id>.<png|jpg|gif>; its version, a hash, is on
// the item (customItems.setArt), so a new picture is a new address.
const MAX_BYTES = 100 * 1024; // a picture kept: every player who sees the item downloads it
const MAX_UPLOAD = 2 * 1024 * 1024; // one sent (a BMP is bigger than the PNG it becomes)
const MAX_SIDE = 256; // drawn fitted to the item anyway (a den item's place is 160)
const MIN_SIDE = 8;
const DIR = path.join(config.dataDir, "itemart");
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
// the PNG chunks a picture needs; text, times, EXIF and the like are dropped
const PNG_KEPT = new Set(["IHDR", "PLTE", "IDAT", "IEND", "tRNS", "gAMA", "cHRM", "sRGB", "iCCP", "sBIT", "pHYs"]);
const TYPES = ["png", "jpeg", "gif"];
const EXTENSION = {png: "png", jpeg: "jpg", gif: "gif"};
const VERSION_MARK = {png: "p", jpeg: "j", gif: "g"};
const fileOf = (kind, id, type) => path.join(DIR, `${kind}-${Number(id)}.${EXTENSION[type]}`);
// a GIF's blocks, without comments, plain text and any application block but
// the one that says it loops; null when it is not a whole GIF. kept animated.
const cleanGif = data => {
const head = data.toString("latin1", 0, 6);
if (data.length < 14 || (head !== "GIF87a" && head !== "GIF89a")) {
return null;
}
const width = data.readUInt16LE(6);
const height = data.readUInt16LE(8);
const packed = data[10];
let at = 13 + (packed & 0x80 ? 3 * (2 << (packed & 7)) : 0);
if (at > data.length) {
return null;
}
const kept = [data.subarray(0, at)];
// sub-blocks from `from`: where they end (after the 0 that ends them)
const subBlocksEnd = from => {
let i = from;
while (i < data.length && data[i] !== 0) {
i += data[i] + 1;
}
return i < data.length ? i + 1 : -1;
};
let images = 0;
while (at < data.length) {
const block = data[at];
if (block === 0x3B) {
kept.push(data.subarray(at, at + 1));
return images ? {data: Buffer.concat(kept), width, height, type: "gif"} : null;
}
if (block === 0x2C) {
if (at + 10 > data.length) {
return null;
}
const local = data[at + 9];
const start = at;
at += 10 + (local & 0x80 ? 3 * (2 << (local & 7)) : 0) + 1; // the descriptor, its colours, the LZW code size
const end = subBlocksEnd(at);
if (end === -1) {
return null;
}
kept.push(data.subarray(start, end));
at = end;
images++;
continue;
}
if (block === 0x21 && at + 2 <= data.length) {
const label = data[at + 1];
const end = subBlocksEnd(at + 2);
if (end === -1) {
return null;
}
const loops = label === 0xFF && data.toString("latin1", at + 3, at + 14) === "NETSCAPE2.0";
if (label === 0xF9 || loops) {
kept.push(data.subarray(at, end));
}
at = end;
continue;
}
return null;
}
return null;
};
// a PNG of RGBA pixels (`pixels`, width * height * 4 bytes, rows top down).
const CRC_TABLE = Array.from({length: 256}, (unused, n) => {
let c = n;
for (let k = 0; k < 8; k++) {
c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1;
}
return c >>> 0;
});
const crc32 = buffer => {
let c = 0xFFFFFFFF;
for (const byte of buffer) {
c = CRC_TABLE[(c ^ byte) & 0xFF] ^ (c >>> 8);
}
return (c ^ 0xFFFFFFFF) >>> 0;
};
const pngChunk = (type, body) => {
const length = Buffer.alloc(4);
length.writeUInt32BE(body.length);
const typed = Buffer.concat([Buffer.from(type, "latin1"), body]);
const crc = Buffer.alloc(4);
crc.writeUInt32BE(crc32(typed));
return Buffer.concat([length, typed, crc]);
};
const encodePng = (width, height, pixels) => {
const header = Buffer.alloc(13);
header.writeUInt32BE(width, 0);
header.writeUInt32BE(height, 4);
header[8] = 8; // bits a channel
header[9] = 6; // RGBA
const rows = Buffer.alloc((width * 4 + 1) * height);
for (let y = 0; y < height; y++) {
pixels.copy(rows, y * (width * 4 + 1) + 1, y * width * 4, (y + 1) * width * 4);
}
return Buffer.concat([PNG_SIGNATURE, pngChunk("IHDR", header), pngChunk("IDAT", zlib.deflateSync(rows)), pngChunk("IEND", Buffer.alloc(0))]);
};
// RGBA pixels shrunk to fit `side` (each new pixel the mean of those it covers).
const shrink = (width, height, pixels, side) => {
const scale = Math.min(1, side / width, side / height);
if (scale === 1) {
return {width, height, pixels};
}
const w = Math.max(1, Math.round(width * scale));
const h = Math.max(1, Math.round(height * scale));
const out = Buffer.alloc(w * h * 4);
for (let y = 0; y < h; y++) {
const y0 = Math.floor(y / scale);
const y1 = Math.min(height, Math.max(y0 + 1, Math.floor((y + 1) / scale)));
for (let x = 0; x < w; x++) {
const x0 = Math.floor(x / scale);
const x1 = Math.min(width, Math.max(x0 + 1, Math.floor((x + 1) / scale)));
const sum = [0, 0, 0, 0];
for (let sy = y0; sy < y1; sy++) {
for (let sx = x0; sx < x1; sx++) {
for (let c = 0; c < 4; c++) {
sum[c] += pixels[(sy * width + sx) * 4 + c];
}
}
}
const count = (y1 - y0) * (x1 - x0);
for (let c = 0; c < 4; c++) {
out[(y * w + x) * 4 + c] = Math.round(sum[c] / count);
}
}
}
return {width: w, height: h, pixels: out};
};
// a BMP (uncompressed, or bit fields: 1, 4, 8, 24 or 32 bits a pixel) as a
// PNG, shrunk to fit; null when it is not one this can read.
const MAX_BMP_SIDE = 4096;
const bmpToPng = data => {
if (data.length < 54 || data.toString("latin1", 0, 2) !== "BM") {
return null;
}
const offset = data.readUInt32LE(10);
const headerSize = data.readUInt32LE(14);
if (headerSize < 40) {
return null;
}
const width = data.readInt32LE(18);
const rawHeight = data.readInt32LE(22);
const height = Math.abs(rawHeight);
const bits = data.readUInt16LE(28);
const compression = data.readUInt32LE(30);
if (width < 1 || height < 1 || width > MAX_BMP_SIDE || height > MAX_BMP_SIDE || ![1, 4, 8, 24, 32].includes(bits) || ![0, 3].includes(compression)) {
return null;
}
const stride = Math.ceil(width * bits / 32) * 4;
if (offset + stride * height > data.length) {
return null;
}
const paletteAt = 14 + headerSize;
const pixels = Buffer.alloc(width * height * 4);
const hasAlpha = bits === 32 && (headerSize >= 56 || compression === 3);
for (let y = 0; y < height; y++) {
const row = offset + (rawHeight > 0 ? height - 1 - y : y) * stride;
for (let x = 0; x < width; x++) {
const o = (y * width + x) * 4;
let b;
let g;
let r;
let a = 255;
if (bits >= 24) {
const p = row + x * (bits / 8);
[b, g, r] = [data[p], data[p + 1], data[p + 2]];
if (hasAlpha) {
a = data[p + 3];
}
}
else {
const perByte = 8 / bits;
const byte = data[row + Math.floor(x / perByte)];
const index = (byte >> ((perByte - 1 - (x % perByte)) * bits)) & ((1 << bits) - 1);
const entry = paletteAt + index * 4;
if (entry + 3 > data.length) {
return null;
}
[b, g, r] = [data[entry], data[entry + 1], data[entry + 2]];
}
pixels[o] = r;
pixels[o + 1] = g;
pixels[o + 2] = b;
pixels[o + 3] = a;
}
}
const small = shrink(width, height, pixels, MAX_SIDE);
return {data: encodePng(small.width, small.height, small.pixels), width: small.width, height: small.height, type: "png"};
};
// a PNG's chunks, without the ones not kept; null when it is not a whole PNG.
const cleanPng = data => {
if (data.length < 33 || !data.subarray(0, 8).equals(PNG_SIGNATURE)) {
return null;
}
const kept = [PNG_SIGNATURE];
let at = 8;
let width = 0;
let height = 0;
let ended = false;
while (at + 12 <= data.length) {
const length = data.readUInt32BE(at);
const type = data.toString("latin1", at + 4, at + 8);
if (at + 12 + length > data.length) {
return null;
}
if (type === "IHDR") {
width = data.readUInt32BE(at + 8);
height = data.readUInt32BE(at + 12);
}
if (PNG_KEPT.has(type)) {
kept.push(data.subarray(at, at + 12 + length));
}
at += 12 + length;
if (type === "IEND") {
ended = true;
break;
}
}
return ended && width && height ? {data: Buffer.concat(kept), width, height, type: "png"} : null;
};
// a JPEG without its APP1..APP15 (EXIF, XMP, ...) and comment segments;
// null when it is not one. its size is read from the frame header.
const cleanJpeg = data => {
if (data.length < 4 || data[0] !== 0xFF || data[1] !== 0xD8) {
return null;
}
const kept = [data.subarray(0, 2)];
let at = 2;
let width = 0;
let height = 0;
while (at + 4 <= data.length) {
if (data[at] !== 0xFF) {
return null;
}
const marker = data[at + 1];
if (marker === 0xD9) {
kept.push(data.subarray(at, at + 2));
break;
}
const length = data.readUInt16BE(at + 2);
if (length < 2 || at + 2 + length > data.length) {
return null;
}
const segment = data.subarray(at, at + 2 + length);
// start of frame (not DHT, JPG or DAC): the size
if (marker >= 0xC0 && marker <= 0xCF && ![0xC4, 0xC8, 0xCC].includes(marker)) {
height = data.readUInt16BE(at + 5);
width = data.readUInt16BE(at + 7);
}
const dropped = (marker >= 0xE1 && marker <= 0xEF) || marker === 0xFE;
if (!dropped) {
kept.push(segment);
}
at += 2 + length;
// start of scan: the compressed data runs to the end
if (marker === 0xDA) {
kept.push(data.subarray(at));
break;
}
}
return width && height ? {data: Buffer.concat(kept), width, height, type: "jpeg"} : null;
};
// checks and cleans an upload: {data, type} or {error}.
const check = data => {
if (!Buffer.isBuffer(data) || data.length === 0) {
return {error: "Choose a picture first."};
}
if (data.length > MAX_UPLOAD) {
return {error: `That picture is too big: ${Math.round(MAX_UPLOAD / 1024 / 1024)} MB at most.`};
}
const image = cleanPng(data) || cleanJpeg(data) || cleanGif(data) || bmpToPng(data);
if (!image) {
return {error: "That is not a PNG, JPEG, GIF or BMP picture."};
}
if (image.data.length > MAX_BYTES) {
return {error: `That picture is too big: ${Math.round(MAX_BYTES / 1024)} KB at most once cleaned. A smaller one, please.`};
}
if (image.width > MAX_SIDE || image.height > MAX_SIDE || image.width < MIN_SIDE || image.height < MIN_SIDE) {
return {error: `A picture from ${MIN_SIDE} to ${MAX_SIDE} pixels on each side, please.`};
}
return image;
};
const digest = data => crypto.createHash("sha256").update(data).digest("hex");
// sets an item's picture. resolves to {ok, art} or {error}.
// `pending`: it waits for a moderator before anyone is shown it (lib/playeritems.js).
// `refused(hash)`: whether a picture of that SHA-256 (once cleaned) was
// turned away before, and may not be sent again.
const set = async (kind, id, data, pending = false, refused = null) => {
const entry = customItems.get(kind, id);
if (!entry) {
return {error: "No such custom item."};
}
const image = check(data);
if (image.error) {
return image;
}
if (refused && refused(digest(image.data))) {
return {error: "A moderator turned that picture away before. Choose another one."};
}
const safety = await imageModeration.scan(image.data);
if (safety.blocked) {
return {error: safety.error};
}
fs.mkdirSync(DIR, {recursive: true});
for (const type of TYPES) {
fs.rmSync(fileOf(kind, entry.id, type), {force: true});
}
fs.writeFileSync(fileOf(kind, entry.id, image.type), image.data);
const art = `${VERSION_MARK[image.type]}${crypto.createHash("sha256").update(image.data).digest("hex").slice(0, 12)}`;
customItems.setArt(kind, entry.id, art, pending);
return {ok: pending ? `${entry.name}'s new picture is waiting for a moderator to approve it.` : `${entry.name} has a new picture.`, art};
};
// takes an item's picture away (its maker's choice, or staff's).
const remove = (kind, id) => {
const entry = customItems.get(kind, id);
if (!entry || !entry.art) {
return {error: "That item has no picture of its own."};
}
for (const type of TYPES) {
fs.rmSync(fileOf(kind, entry.id, type), {force: true});
}
customItems.setArt(kind, entry.id, null);
return {ok: `${entry.name}'s picture was taken away.`};
};
// the picture to serve: {data, type} or null. one waiting for a moderator
// only `withPending`: for the maker and the moderators (lib/http.js).
const file = (kind, id, withPending = false) => {
const entry = customItems.get(kind, id);
if (!entry || !entry.art || (entry.artPending && !withPending)) {
return null;
}
const type = TYPES.find(one => entry.art.startsWith(VERSION_MARK[one])) || "png";
try {
return {data: fs.readFileSync(fileOf(kind, entry.id, type)), type};
}
catch {
return null;
}
};
// the SHA-256 of an item's picture as kept, waiting or not: null for none.
const digestOf = (kind, id) => {
const picture = file(kind, id, true);
return picture ? digest(picture.data) : null;
};
// where a page shows an item's picture: the public address once anyone may
// see it; while it waits, `base` (the page's own /…/api/itemart, which asks
// who it is first).
const urlOf = (entry, base) => (!entry.art ? null : entry.artPending
? `${base}?kind=${entry.kind}&id=${entry.id}&v=${entry.art}` : `/itemart/${entry.kind}/${entry.id}.png?v=${entry.art}`);
module.exports = {set, remove, file, check, digestOf, urlOf, MAX_BYTES, MAX_UPLOAD};
+233
View File
@@ -0,0 +1,233 @@
"use strict";
const accounts = require("./accounts.js");
const customItems = require("./customitems.js");
const defpacks = require("./defpacks.js");
const wearRules = require("./wearrules.js");
// what staff who make items (items.create: admins and developers) may do
// about who has them:
//
// - lock an item out of the item finder (lib/admin.js): players no longer
// find it there or take it from it. staff who may lock still do, with the
// item marked locked. it stays wherever else it is (a shop, a trade).
// - take an item from one player: every one of it they have.
// - delete a custom item (lib/customitems.js): out of the game, and out of
// every inventory.
const LOCKS_SETTING = "finderLocks";
const KINDS = ["clothing", "den"];
let locks = null; // Set of "kind:id"
const key = (kind, id) => `${kind}:${Number(id)}`;
const lockSet = () => {
if (!locks) {
let saved = [];
try {
saved = JSON.parse(accounts.setting(LOCKS_SETTING) || "[]");
}
catch {
saved = [];
}
locks = new Set(Array.isArray(saved) ? saved.map(String) : []);
}
return locks;
};
const saveLocks = () => accounts.setSetting(LOCKS_SETTING, JSON.stringify([...lockSet()]));
const defOf = (kind, id) => (kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id));
const nameOf = (kind, id) => {
const def = defOf(kind, id);
if (!def) {
return "";
}
return kind === "den" ? defpacks.string(def.nameStrId) || def.abbrName || "" : defpacks.string(def.titleStrId);
};
const describe = (kind, id) => `${nameOf(kind, id) || "(no name)"} (${kind === "den" ? "den item" : "clothing"} ${Number(id)})`;
// checks a kind and id typed by staff: {kind, id} of an item that exists, or {error}.
const item = (kind, id) => {
const number = Number(id);
if (!KINDS.includes(kind)) {
return {error: "The kind is clothing or den."};
}
if (!Number.isInteger(number) || !defOf(kind, number) || (kind === "clothing" && !defpacks.clothingIds().includes(number))) {
return {error: `No ${kind === "den" ? "den item" : "clothing"} with the id ${id}.`};
}
return {kind, id: number};
};
const isLocked = (kind, id) => lockSet().has(key(kind, id));
// returns {ok} or {error}.
const setLocked = (kind, id, locked) => {
const found = item(kind, id);
if (found.error) {
return found;
}
const was = isLocked(found.kind, found.id);
if (was === locked) {
return {error: `${describe(found.kind, found.id)} is ${locked ? "already" : "not"} locked.`};
}
lockSet()[locked ? "add" : "delete"](key(found.kind, found.id));
saveLocks();
return {ok: `${describe(found.kind, found.id)} is ${locked ? "locked out of" : "back in"} the item finder.`};
};
const lockedList = () => [...lockSet()].map(entry => {
const [kind, id] = entry.split(":");
return {kind, id: Number(id), name: nameOf(kind, id)};
});
// The animals a moderator can select in the dashboard. Avatar types, rather
// than a hand-written list of species, keep this correct for packs added in
// a later game build.
const wearAnimals = () => defpacks.avatarTypes().sort((one, two) => one - two).map(type => {
const def = defpacks.avatarDef(type) || {};
return {id: Number(type), name: defpacks.string(def.titleStrRef || def.nameStrId) || def.abbrName || `Animal ${type}`};
});
const wearRuleList = () => wearRules.all().flatMap(rule => {
const found = item("clothing", rule.id);
return found.error ? [] : [{id: found.id, name: nameOf(found.kind, found.id), blockedTypes: rule.blocked}];
});
// Remove a new restriction from every possible display of an item. A clothing
// association has an avatar slot; a mannequin keeps the inventory ids in
// five den-item slots. Both must be cleaned or a rule can be bypassed by
// switching animals or visiting a den.
const removeBlockedUses = (account, itemId, blocked) => {
const disallowedAvatarSlots = new Set(account.avatars.filter(avatar => blocked.has(Number(avatar.type))).map(avatar => avatar.avInvId));
const matchingInventory = new Set(account.items.filter(piece => piece.def === itemId).map(piece => piece.inv));
let removed = 0;
let clothingChanged = false;
let mannequinChanged = false;
for (const piece of account.items) {
if (piece.def !== itemId || !Array.isArray(piece.on)) {
continue;
}
const kept = piece.on.filter(avInvId => !disallowedAvatarSlots.has(avInvId));
if (kept.length !== piece.on.length) {
removed += piece.on.length - kept.length;
piece.on = kept;
clothingChanged = true;
}
}
for (const denItem of account.denItems) {
const mannequinType = Number((defpacks.denItemDef(denItem.def) || {}).mannequinAvatarDefId);
if (!blocked.has(mannequinType) || !denItem.mannequin || !Array.isArray(denItem.mannequin.worn)) {
continue;
}
const kept = denItem.mannequin.worn.map(inv => (matchingInventory.has(Number(inv)) ? 0 : inv));
if (kept.some((inv, index) => inv !== denItem.mannequin.worn[index])) {
removed += kept.filter(inv => inv === 0).length - denItem.mannequin.worn.filter(inv => inv === 0).length;
denItem.mannequin.worn = kept;
mannequinChanged = true;
}
}
return {changed: clothingChanged || mannequinChanged, mannequinChanged, removed};
};
// Make a clothing item unavailable to the selected animal types. `world`
// refreshes games and den visitors after the persistent state is cleaned.
const setWearRule = (id, blockedTypes, world) => {
const found = item("clothing", id);
if (found.error) {
return found;
}
const animals = wearAnimals();
const allowed = new Set(animals.map(animal => animal.id));
if (!Array.isArray(blockedTypes) || blockedTypes.length > allowed.size || !blockedTypes.every(Number.isInteger)
|| blockedTypes.some(type => !allowed.has(type))) {
return {error: "Choose only animals from the list."};
}
const blocked = [...new Set(blockedTypes)].sort((one, two) => one - two);
const changedRule = wearRules.setBlockedTypes(found.id, blocked).changed;
let accountsChanged = 0;
let removed = 0;
const blockedSet = new Set(blocked);
for (const account of accounts.all()) {
const cleaned = removeBlockedUses(account, found.id, blockedSet);
if (!cleaned.changed) {
continue;
}
accountsChanged++;
removed += cleaned.removed;
accounts.save(account);
world.wearRulesChanged(account, cleaned.mannequinChanged);
}
// Packs downloaded after this moment, and games already open, use the
// same rule-to-flag transformation. Server checks above remain authority.
defpacks.invalidateClientItemPack();
customItems.sendClothingDefs([found.id]);
const animalNames = blocked.map(type => animals.find(animal => animal.id === type).name);
const subject = describe(found.kind, found.id);
const suffix = blocked.length ? `cannot be worn by ${animalNames.join(", ")}.` : "can be worn by every animal again.";
return {ok: `${subject} ${suffix}${removed ? ` Took it off ${removed} existing use${removed === 1 ? "" : "s"}.` : ""}`,
detail: `clothing ${found.id}; blocked types ${blocked.join(",") || "none"}; ${accountsChanged} account${accountsChanged === 1 ? "" : "s"} changed`, changed: changedRule};
};
// every one of an item an account has, out of its inventory (and its trade
// list). `world` tells a game playing (lib/world.js itemsTaken). returns how
// many went.
const takeFromAccount = (account, kind, id, world) => {
const number = Number(id);
const collection = kind === "den" ? "denItems" : "items";
const gone = account[collection].filter(entry => entry.def === number);
if (!gone.length) {
return 0;
}
const invs = new Set(gone.map(entry => entry.inv));
account[collection] = account[collection].filter(entry => !invs.has(entry.inv));
account.tradeList = account.tradeList.filter(entry => !invs.has(entry.inv));
accounts.save();
world.itemsTaken(account, kind, [...invs], kind === "clothing" && gone.some(entry => entry.on.length > 0));
return gone.length;
};
// from one player, by username. returns {ok, count} or {error}.
const take = (username, kind, id, world) => {
const account = accounts.byName(username);
if (!account) {
return {error: `No player called ${username}.`};
}
// a deleted custom item can be gone from the tables and still be owned:
// the id is taken as it is then.
const found = item(kind, id);
if (found.error && !(KINDS.includes(kind) && Number.isInteger(Number(id)))) {
return found;
}
const count = takeFromAccount(account, kind, id, world);
return count ? {ok: `Took ${count} of ${describe(kind, id)} from ${account.username}.`, count}
: {error: `${account.username} has no ${describe(kind, id)}.`};
};
// a custom item out of the game, and out of everyone's inventory. returns {ok} or {error}.
const deleteCustom = (kind, id, world) => {
const entry = customItems.get(kind, id);
if (!entry) {
return {error: "No such custom item."};
}
let count = 0;
for (const account of accounts.all()) {
count += takeFromAccount(account, kind, entry.id, world);
}
if (entry.art) {
require("./itemart.js").remove(kind, entry.id);
}
customItems.remove(kind, entry.id);
if (lockSet().delete(key(kind, entry.id))) {
saveLocks();
}
if (kind === "clothing") {
wearRules.forget(entry.id);
}
return {ok: `Deleted ${entry.name} (${kind === "den" ? "den item" : "clothing"} ${entry.id})${count ? `, and took ${count} from players` : ""}.`};
};
module.exports = {isLocked, setLocked, lockedList, wearAnimals, wearRuleList, setWearRule, take, deleteCustom};
+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};
+51 -4
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]
@@ -48,7 +51,7 @@ module.exports = ({others, sendItemList}) => {
achievements.currencyChanged(account, currency, -purchase.cost); achievements.currencyChanged(account, currency, -purchase.cost);
achievements.add(account, achievements.VARS.clothesBought); achievements.add(account, achievements.VARS.clothesBought);
const item = addClothing(account, def.id, colors[colorIndex]); const item = addClothing(account, def.id, colors[colorIndex]);
accounts.save(); accounts.save(account);
sendClothingAdded(session, item); sendClothingAdded(session, item);
session.sendXt("ib", -1, 1, shopId, account.currency[currency], purchase.currencyType); session.sendXt("ib", -1, 1, shopId, account.currency[currency], purchase.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) {
@@ -95,7 +105,7 @@ module.exports = ({others, sendItemList}) => {
}; };
const off = ids.slice(onCount).filter(invIdx => setWorn(invIdx, false) !== null); const off = ids.slice(onCount).filter(invIdx => setWorn(invIdx, false) !== null);
const on = ids.slice(0, onCount).map(invIdx => [invIdx, setWorn(invIdx, true)]).filter(([, def]) => def !== null); const on = ids.slice(0, onCount).map(invIdx => [invIdx, setWorn(invIdx, true)]).filter(([, def]) => def !== null);
accounts.save(); accounts.save(account);
// ItemXtCommManager.itemUseResponse // ItemXtCommManager.itemUseResponse
session.sendXt("iu", -1, 1); session.sendXt("iu", -1, 1);
// the reply only closes the editor. the animal in the room is redrawn // the reply only closes the editor. the animal in the room is redrawn
@@ -127,12 +137,49 @@ module.exports = ({others, sendItemList}) => {
account.currency[received] = (account.currency[received] || 0) + def.result; account.currency[received] = (account.currency[received] || 0) + def.result;
achievements.currencyChanged(account, paid, -def.cost); achievements.currencyChanged(account, paid, -def.cost);
achievements.currencyChanged(account, received, def.result); achievements.currencyChanged(account, received, def.result);
accounts.save(); accounts.save(account);
// ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason] // ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason]
session.sendXt("cu", -1, def.resultType, account.currency[received], 0); session.sendXt("cu", -1, def.resultType, account.currency[received], 0);
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
@@ -154,7 +201,7 @@ module.exports = ({others, sendItemList}) => {
account.items.splice(index, 1); account.items.splice(index, 1);
recycled.push(invIdx); recycled.push(invIdx);
} }
accounts.save(); accounts.save(account);
session.sendXt("ir", -1, recycled.length, account.currency.gems || 0, ...recycled); session.sendXt("ir", -1, recycled.length, account.currency.gems || 0, ...recycled);
if (recycled.length) { if (recycled.length) {
sendClothingRemoved(session, recycled); sendClothingRemoved(session, recycled);
+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};
}; };
+4 -1
View File
@@ -5,6 +5,7 @@
const MAX_LINES = 5000; const MAX_LINES = 5000;
const MAX_LINE_LENGTH = 2000; const MAX_LINE_LENGTH = 2000;
const TRIM_BATCH = 1000;
const lines = []; // {id, time, text} const lines = []; // {id, time, text}
let nextId = 1; let nextId = 1;
@@ -15,7 +16,9 @@ const capture = original => (...args) => {
for (const line of text.split("\n")) { for (const line of text.split("\n")) {
lines.push({id: nextId++, time: Date.now(), text: line.slice(0, MAX_LINE_LENGTH)}); lines.push({id: nextId++, time: Date.now(), text: line.slice(0, MAX_LINE_LENGTH)});
} }
if (lines.length > MAX_LINES) { // trimmed a batch at a time: trimming a line at a time moved all the
// others along for every line printed.
if (lines.length > MAX_LINES + TRIM_BATCH) {
lines.splice(0, lines.length - MAX_LINES); lines.splice(0, lines.length - MAX_LINES);
} }
}; };
+17
View File
@@ -0,0 +1,17 @@
"use strict";
// a value from outside (a username, an address, what a client sent) as it
// may go into a line of the server's log: on one line, and with no control
// characters, so that it cannot pass for a line of the server's own (a name
// with a line break in it, "...\n[admin] signed in") or move the terminal's
// cursor about. (U+2028 and U+2029, which end a line too, are in the second.)
const OTHER_BREAKS_AND_CONTROLS = new RegExp("[\x00-\x1f\x7f-\x9f\u2028\u2029]", "g");
// (line feeds go first, and to nothing: the form code scanning knows as a
// log's sanitiser. carriage returns, and the rest, are then replaced.)
const logText = value => String(value)
.replace(/\n/g, "")
.replace(/\r/g, " ")
.replace(OTHER_BREAKS_AND_CONTROLS, "?");
module.exports = {logText};
+410 -34
View File
@@ -1,5 +1,9 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const customItems = require("./customitems.js");
const itemControl = require("./itemcontrol.js");
const playerItems = require("./playeritems.js");
const crypto = require("crypto"); const crypto = require("crypto");
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
@@ -8,15 +12,22 @@ 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");
const chatFilter = require("./chatfilter.js");
const erase = require("./erase.js"); const erase = require("./erase.js");
const masterpieces = require("./masterpieces.js"); 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
@@ -35,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).
@@ -47,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
@@ -99,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});
@@ -123,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("@"))}` : "",
}; };
}; };
@@ -142,16 +207,27 @@ const profile = (account, from) => {
lastSeen: account.lastSeen || account.lastLogin || null, lastSeen: account.lastSeen || account.lastLogin || null,
online: Boolean(world.findOnline(account.username)), online: Boolean(world.findOnline(account.username)),
logins: account.numLogins || 0, logins: account.numLogins || 0,
playtime: account.playtime,
playtimePublic: account.playtimePublic,
chatStyle: chatStyles.normalize(account.chatStyle),
animals: account.avatars.length, animals: account.avatars.length,
animalType: avatar ? avatar.type : null, animalType: avatar ? avatar.type : null,
items: account.items.length, items: account.items.length,
denItems: account.denItems.length, denItems: account.denItems.length,
// what they made in the game's Item Maker (lib/playeritems.js)
customItems: playerItems.madeBy(account).map(entry => ({kind: entry.kind, id: entry.id, name: entry.name,
art: require("./itemart.js").urlOf(entry, "/account/api/itemart"), artWaiting: Boolean(entry.artPending), look: entry.artMode || "sticker"})),
picturesStopped: Boolean(account.artBlocked),
customItemLimits: {perDay: playerItems.PER_DAY, inAll: playerItems.IN_ALL},
pets: account.pets.length, pets: account.pets.length,
buddies: account.buddies.length, buddies: account.buddies.length,
banned: null, banned: null,
locked: account.locked, locked: account.locked,
twoStep: twoStepOf(account), twoStep: twoStepOf(account),
recoveryEmail: account.recoveryEmail ? `${account.recoveryEmail.slice(0, 2)}…${account.recoveryEmail.slice(account.recoveryEmail.lastIndexOf("@"))}` : "",
discord: account.discord, discord: account.discord,
discordLinked: Boolean(account.discordId),
discordLinking: discord.linking(),
bio: account.bio, bio: account.bio,
bioLimit: badges.MAX_BIO, bioLimit: badges.MAX_BIO,
badges: badges.of(account).map(badge => badge.label), badges: badges.of(account).map(badge => badge.label),
@@ -176,7 +252,7 @@ const profile = (account, from) => {
// hash, the 2FA secret, device passes), and what other tables hold of it. // hash, the 2FA secret, device passes), and what other tables hold of it.
// what others wrote about it (reports, a moderator's notes) is not theirs // what others wrote about it (reports, a moderator's notes) is not theirs
// to be handed, and is not here. // to be handed, and is not here.
const SECRET_FIELDS = ["salt", "hash", "totp", "totpSetup", "devices"]; const SECRET_FIELDS = ["salt", "hash", "totp", "totpSetup", "devices", "modNotes", "recoveryTokens"];
const dataOf = account => ({ const dataOf = account => ({
exportedAt: new Date().toISOString(), exportedAt: new Date().toISOString(),
server: config.baseUrl, server: config.baseUrl,
@@ -246,8 +322,8 @@ const act = (account, body, req, from, res) => {
return {error: NAME_ERRORS[problem] || NAME_ERRORS.invalid_username}; return {error: NAME_ERRORS[problem] || NAME_ERRORS.invalid_username};
} }
delete account.nameRejected; delete account.nameRejected;
accounts.save(); accounts.save(account);
console.log(`[account] a rejected username was replaced by "${account.username}" from ${from.address}`); console.log(`[account] a rejected username was replaced by "${logText(account.username)}" from ${logText(from.address)}`);
return {ok: "Saved."}; return {ok: "Saved."};
} }
// one for each account, ever: an answer that wants a follow-up says // one for each account, ever: an answer that wants a follow-up says
@@ -264,12 +340,15 @@ const act = (account, body, req, from, res) => {
if (!passwordAgain(account, body.current)) { if (!passwordAgain(account, body.current)) {
return {error: "Wrong password."}; return {error: "Wrong password."};
} }
if (accounts.setPassword(account, body.password)) { const passwordProblem = accounts.setPassword(account, body.password);
return {error: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."}; if (passwordProblem) {
return {error: passwordProblem === "weak_password" ? "That password is too easy to guess: it is a common one, or has your username in it."
: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."};
} }
world.moderation.actions.kick(account); world.moderation.actions.kick(account);
signOutOthers(account, req); signOutOthers(account, req);
console.log(`[account] "${account.username}" changed their password from ${from.address}`); endStaffSessions(account);
console.log(`[account] "${logText(account.username)}" changed their password from ${logText(from.address)}`);
return {ok: "Password changed."}; return {ok: "Password changed."};
} }
case "requestName": { case "requestName": {
@@ -288,9 +367,10 @@ const act = (account, body, req, from, res) => {
// out of the game now, and no saved sign-in gets back in. // out of the game now, and no saved sign-in gets back in.
accounts.revokeTokens(account); accounts.revokeTokens(account);
world.moderation.actions.kick(account); world.moderation.actions.kick(account);
endStaffSessions(account);
} }
accounts.save(); accounts.save(account);
console.log(`[account] "${account.username}" ${account.locked ? "locked" : "unlocked"} from ${from.address}`); console.log(`[account] "${logText(account.username)}" ${logText(account.locked ? "locked" : "unlocked")} from ${logText(from.address)}`);
return {ok: account.locked ? "Locked." : "Unlocked."}; return {ok: account.locked ? "Locked." : "Unlocked."};
} }
case "feature": { case "feature": {
@@ -298,7 +378,7 @@ const act = (account, body, req, from, res) => {
return {error: "Unknown setting."}; return {error: "Unknown setting."};
} }
account.features[body.feature] = body.on; account.features[body.feature] = body.on;
accounts.save(); accounts.save(account);
return {ok: "Saved."}; return {ok: "Saved."};
} }
// two-step sign-in (lib/totp.js). turning it on: the password again, // two-step sign-in (lib/totp.js). turning it on: the password again,
@@ -312,18 +392,19 @@ const act = (account, body, req, from, res) => {
return {error: "Wrong password."}; return {error: "Wrong password."};
} }
const setup = totp.begin(account); const setup = totp.begin(account);
accounts.save(); accounts.save(account);
return {ok: "Scan the code.", setup}; return {ok: "Scan the code.", setup};
} }
case "twoStepConfirm": { case "twoStepConfirm": {
const recovery = totp.confirm(account, body.code); const recovery = totp.confirm(account, body.code);
if (!recovery) { if (!recovery) {
accounts.save(); accounts.save(account);
return {error: "Wrong code."}; // confirm() drops a setup older than 15 minutes: no code can match it now.
return {error: account.totpSetup ? "Wrong code." : "Setup timed out. Turn 2FA on again and scan the new QR code."};
} }
accounts.revokeTokens(account); accounts.revokeTokens(account);
accounts.save(); accounts.save(account);
console.log(`[account] "${account.username}" turned two-step sign-in on from ${from.address}`); console.log(`[account] "${logText(account.username)}" turned two-step sign-in on from ${logText(from.address)}`);
return {ok: "2FA is on.", recovery}; return {ok: "2FA is on.", recovery};
} }
// turning it off: the password and a code (or a recovery code). // turning it off: the password and a code (or a recovery code).
@@ -335,20 +416,35 @@ const act = (account, body, req, from, res) => {
return {error: "Wrong password."}; return {error: "Wrong password."};
} }
if (!totp.verify(account, String(body.code || ""))) { if (!totp.verify(account, String(body.code || ""))) {
accounts.save(); accounts.save(account);
return {error: "Wrong code."}; return {error: "Wrong code."};
} }
totp.turnOff(account); totp.turnOff(account);
accounts.save(); accounts.save(account);
endStaffSessions(account);
res.setHeader("Set-Cookie", cookieHeader("", 0, DEVICE_COOKIE)); res.setHeader("Set-Cookie", cookieHeader("", 0, DEVICE_COOKIE));
console.log(`[account] "${account.username}" turned two-step sign-in off from ${from.address}`); console.log(`[account] "${logText(account.username)}" turned two-step sign-in off from ${logText(from.address)}`);
return {ok: "2FA is off."}; return {ok: "2FA is off."};
} }
case "forgetDevices": case "forgetDevices":
totp.forgetDevices(account); totp.forgetDevices(account);
accounts.save(); accounts.save(account);
return {ok: "Trusted devices forgotten."}; return {ok: "Trusted devices forgotten."};
// their bio, for the Bio tab of their card in the game. empty takes it off. // their bio, for the Bio tab of their card in the game. empty takes it off.
// their own custom items: a new name, or gone (from everyone who has
// one). a picture is sent to /api/itemart.
case "itemLook":
return playerItems.setLook(account, String(body.kind), body.id, String(body.look));
case "itemRename":
return playerItems.rename(account, String(body.kind), body.id, body.name);
case "itemDelete": {
const entry = customItems.get(String(body.kind), body.id);
if (!entry || entry.ownerId !== account.id) {
return {error: "That is not one of your items."};
}
const result = itemControl.deleteCustom(entry.kind, entry.id, world);
return result.error ? result : {ok: `Deleted ${entry.name}.`};
}
case "bio": { case "bio": {
// typed words others read: not while they cannot chat. // typed words others read: not while they cannot chat.
if (world.moderation.isSilenced(account)) { if (world.moderation.isSilenced(account)) {
@@ -358,20 +454,42 @@ const act = (account, body, req, from, res) => {
if (bio === null) { if (bio === null) {
return {error: `At most ${badges.MAX_BIO} characters on ${badges.MAX_BIO_LINES} lines.`}; return {error: `At most ${badges.MAX_BIO} characters on ${badges.MAX_BIO_LINES} lines.`};
} }
// the server's chat filter, as for anything else players write to
// each other (lib/chat-filter.txt).
const rule = chatFilter.broken(bio);
if (rule) {
console.log(`[filter] "${logText(account.username)}" bio not saved (${logText(rule)}): ${logText(JSON.stringify(bio))}`);
return {error: "Your bio has words that are not allowed here."};
}
account.bio = bio; account.bio = bio;
accounts.save(); accounts.save(account);
return {ok: bio ? "Saved." : "Removed."}; return {ok: bio ? "Saved." : "Removed."};
} }
// their Discord username, for their card in the game. empty takes it off. // whether their card in the game shows how long they have played.
case "discord": { case "playtimePublic":
const name = badges.discordName(body.name); account.playtimePublic = body.on === true;
if (name === null) { accounts.save(account);
return {error: "Not a Discord username."}; return {ok: account.playtimePublic ? "Others can see your playtime on your card." : "Your playtime is private."};
// A player can choose every colour, opacity, animation and animation
// speed. Validation is deliberately here as well as in the page: saved
// state is not trusted just because it came from our own browser UI.
case "chatStyle": {
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(); 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();
@@ -385,7 +503,7 @@ const act = (account, body, req, from, res) => {
else { else {
delete account.buddyNotes[key]; delete account.buddyNotes[key];
} }
accounts.save(); accounts.save(account);
return {ok: "Saved."}; return {ok: "Saved."};
} }
// blocking and unblocking, as the game's own buttons do it. // blocking and unblocking, as the game's own buttons do it.
@@ -415,9 +533,10 @@ const act = (account, body, req, from, res) => {
case "signOutEverywhere": case "signOutEverywhere":
accounts.revokeTokens(account); accounts.revokeTokens(account);
totp.forgetDevices(account); totp.forgetDevices(account);
accounts.save(); 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": {
@@ -430,8 +549,9 @@ const act = (account, body, req, from, res) => {
const name = account.username; const name = account.username;
world.disconnect(account); world.disconnect(account);
signOutOthers(account, null); signOutOthers(account, null);
endStaffSessions(account);
erase(account); erase(account);
console.log(`[account] "${name}" deleted their account from ${from.address}`); console.log(`[account] "${logText(name)}" deleted their account from ${logText(from.address)}`);
return {ok: "Account deleted.", deleted: true}; return {ok: "Account deleted.", deleted: true};
} }
default: default:
@@ -448,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;
@@ -463,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;
@@ -470,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)) {
@@ -488,7 +738,7 @@ const handle = async (req, res, url, from, web) => {
failuresByAddress.record(from.key); failuresByAddress.record(from.key);
if (known) { if (known) {
accounts.recordLogin(known, "web", from.address, false); accounts.recordLogin(known, "web", from.address, false);
accounts.save(); accounts.save(known);
} }
reply(401, {error: "Wrong username or password."}); reply(401, {error: "Wrong username or password."});
return; return;
@@ -504,7 +754,7 @@ const handle = async (req, res, url, from, web) => {
if (!totp.verify(account, String(body.code))) { if (!totp.verify(account, String(body.code))) {
failuresByAddress.record(from.key); failuresByAddress.record(from.key);
accounts.recordLogin(account, "web", from.address, false); accounts.recordLogin(account, "web", from.address, false);
accounts.save(); accounts.save(account);
reply(401, {error: "Wrong code.", twoStep: true, captchaPass: captcha.issuePass(account, from)}); reply(401, {error: "Wrong code.", twoStep: true, captchaPass: captcha.issuePass(account, from)});
return; return;
} }
@@ -513,7 +763,7 @@ const handle = async (req, res, url, from, web) => {
} }
} }
accounts.recordLogin(account, "web", from.address); accounts.recordLogin(account, "web", from.address);
accounts.save(); accounts.save(account);
signIn(res, account, cookies); signIn(res, account, cookies);
reply(200, {ok: true}); reply(200, {ok: true});
return; return;
@@ -527,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);
@@ -535,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)) {
@@ -547,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": {
@@ -586,4 +962,4 @@ const handle = async (req, res, url, from, web) => {
// called when an account's name changes or it is deleted: its page sessions end. // called when an account's name changes or it is deleted: its page sessions end.
const forget = account => signOutOthers(account, null); const forget = account => signOutOthers(account, null);
module.exports = {handle, forget}; module.exports = {handle, forget, signedInAs};
+255 -26
View File
@@ -6,6 +6,8 @@ const path = require("path");
const config = require("../config.js"); const config = require("../config.js");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const imageModeration = require("./image-moderation.js");
const jpegPrint = require("./jpegprint.js");
// masterpieces: paintings from the Art Studio, framed and hung in a den // masterpieces: paintings from the Art Studio, framed and hung in a den
// (client side: game.artStudioPainting.ArtStudioPainting, the same in // (client side: game.artStudioPainting.ArtStudioPainting, the same in
@@ -40,9 +42,27 @@ const SCHEMA = `
status INTEGER NOT NULL, status INTEGER NOT NULL,
frame INTEGER NOT NULL, frame INTEGER NOT NULL,
reviewed_at INTEGER, reviewed_at INTEGER,
reviewed_by TEXT,
likes TEXT NOT NULL, likes TEXT NOT NULL,
image BLOB NOT NULL image BLOB NOT NULL
); );
-- every picture taken in, for the daily limit (pictures thrown away
-- unframed count too)
CREATE TABLE IF NOT EXISTS masterpiece_uploads (
creator_id INTEGER NOT NULL,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS masterpiece_uploads_by ON masterpiece_uploads (creator_id, created_at);
-- pictures a moderator or the admin approved once: the same picture
-- again, the same file (SHA-256) or the same painting saved and painted
-- again (its fingerprint, lib/jpegprint.js), is approved as it is framed
CREATE TABLE IF NOT EXISTS masterpiece_approved_pictures (
hash TEXT PRIMARY KEY,
approved_at INTEGER NOT NULL,
approved_by TEXT NOT NULL,
fingerprint BLOB,
thumb BLOB
);
`; `;
const UPLOADED = 0; // posted, not made into an item yet const UPLOADED = 0; // posted, not made into an item yet
@@ -77,14 +97,35 @@ const fileOf = id => path.join(folder(), `${id}.jpg`);
const GALLERY_SPOTS = 12; // PartyManager.setupMasterpiecesInRoom const GALLERY_SPOTS = 12; // PartyManager.setupMasterpiecesInRoom
const uploadsPerHour = limits.limiter(30, 3600000); const uploadsPerHour = limits.limiter(30, 3600000);
const DAY = 86400;
const AUTO_APPROVER = "auto"; // reviewedBy of a painting approved for a picture approved before
const now = () => Math.floor(Date.now() / 1000); const now = () => Math.floor(Date.now() / 1000);
const db = () => accounts.database(); const db = () => accounts.database();
const known = new Map(); // id -> {id, creator, createdAt, status, frame, likes: [account ids]} const known = new Map(); // id -> {id, creator, createdAt, status, frame, reviewedAt, reviewedBy, likes: [account ids], hash}
const approvedPictures = new Map(); // hash -> thumbnail of its fingerprint, or null: masterpiece_approved_pictures
const tokens = new Map(); // upload token -> {account id, expires (ms)} const tokens = new Map(); // upload token -> {account id, expires (ms)}
const load = () => { const load = () => {
db().exec(SCHEMA); db().exec(SCHEMA);
// who approved it: a moderator's username, "admin", or null when nobody
// looked (review was off, or it was approved before this was kept).
const columns = db().prepare("PRAGMA table_info(masterpieces)").all().map(column => column.name);
if (!columns.includes("reviewed_by")) {
db().exec("ALTER TABLE masterpieces ADD COLUMN reviewed_by TEXT");
}
// the picture's SHA-256 (hashOf) and fingerprint (lib/jpegprint.js), to know it again
if (!columns.includes("hash")) {
db().exec("ALTER TABLE masterpieces ADD COLUMN hash TEXT");
}
if (!columns.includes("fingerprint")) {
db().exec("ALTER TABLE masterpieces ADD COLUMN fingerprint BLOB");
}
const pictureColumns = db().prepare("PRAGMA table_info(masterpiece_approved_pictures)").all().map(column => column.name);
if (!pictureColumns.includes("fingerprint")) {
db().exec("ALTER TABLE masterpiece_approved_pictures ADD COLUMN fingerprint BLOB");
db().exec("ALTER TABLE masterpiece_approved_pictures ADD COLUMN thumb BLOB");
}
fs.mkdirSync(folder(), {recursive: true}); fs.mkdirSync(folder(), {recursive: true});
// pictures still in the table move out into files, once. // pictures still in the table move out into files, once.
for (const row of db().prepare("SELECT id FROM masterpieces WHERE length(image) > 0").all()) { for (const row of db().prepare("SELECT id FROM masterpieces WHERE length(image) > 0").all()) {
@@ -92,15 +133,138 @@ const load = () => {
fs.writeFileSync(fileOf(row.id), Buffer.from(picture)); fs.writeFileSync(fileOf(row.id), Buffer.from(picture));
db().prepare("UPDATE masterpieces SET image = ? WHERE id = ?").run(NO_IMAGE, row.id); db().prepare("UPDATE masterpieces SET image = ? WHERE id = ?").run(NO_IMAGE, row.id);
} }
for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, likes FROM masterpieces").all()) { for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, reviewed_at, reviewed_by, likes, hash FROM masterpieces").all()) {
known.set(row.id, {id: row.id, creator: row.creator_id, createdAt: row.created_at, status: row.status, frame: row.frame, likes: JSON.parse(row.likes)}); known.set(row.id, {id: row.id, creator: row.creator_id, createdAt: row.created_at, status: row.status, frame: row.frame,
reviewedAt: row.reviewed_at, reviewedBy: row.reviewed_by, likes: JSON.parse(row.likes), hash: row.hash || null});
} }
for (const row of db().prepare("SELECT hash, thumb FROM masterpiece_approved_pictures").all()) {
approvedPictures.set(row.hash, row.thumb ? Buffer.from(row.thumb) : null);
}
backfill();
};
const hashOf = image => crypto.createHash("sha256").update(image).digest("hex");
const printOf = painting => {
const row = db().prepare("SELECT fingerprint FROM masterpieces WHERE id = ?").get(painting.id);
return row && row.fingerprint ? Buffer.from(row.fingerprint) : null;
};
// the approved pictures (their hashes) that this picture is: the same file,
// or the same painting by its fingerprint.
const approvedMatches = (hash, print) => {
const found = approvedPictures.has(hash) ? [hash] : [];
if (print) {
const thumb = jpegPrint.thumbnail(print);
for (const [other, otherThumb] of approvedPictures) {
if (other !== hash && otherThumb && jpegPrint.thumbnailsClose(thumb, otherThumb)) {
const row = db().prepare("SELECT fingerprint FROM masterpiece_approved_pictures WHERE hash = ?").get(other);
if (row && row.fingerprint && jpegPrint.samePicture(print, Buffer.from(row.fingerprint))) {
found.push(other);
}
}
}
}
return found;
};
const pictureApproved = (hash, print) => Boolean(hash) && approvedMatches(hash, print).length > 0;
const notePictureApproved = (painting, print) => {
const thumb = print ? jpegPrint.thumbnail(print) : null;
db().prepare("INSERT OR IGNORE INTO masterpiece_approved_pictures (hash, approved_at, approved_by, fingerprint, thumb) VALUES (?, ?, ?, ?, ?)")
.run(painting.hash, painting.reviewedAt || now(), painting.reviewedBy, print, thumb);
if (!approvedPictures.has(painting.hash)) {
approvedPictures.set(painting.hash, thumb);
}
};
// paintings from before pictures were known again get their hash and
// fingerprint, a few at a time after start (each is a file read and some
// milliseconds of decoding, on the thread the game shares); those a person
// approved make their pictures approved ones.
const BACKFILL_BATCH = 20;
const backfill = () => {
const missing = db().prepare("SELECT id FROM masterpieces WHERE fingerprint IS NULL OR hash IS NULL").all().map(row => row.id);
const notedAgain = db().prepare("SELECT hash FROM masterpiece_approved_pictures WHERE fingerprint IS NULL").all().map(row => row.hash);
const step = () => {
for (const id of missing.splice(0, BACKFILL_BATCH)) {
const painting = known.get(id);
let image = null;
try {
image = painting ? fs.readFileSync(fileOf(id)) : null;
}
catch (err) {
image = null;
}
if (!image) {
continue;
}
painting.hash = hashOf(image);
const print = jpegPrint.fingerprint(image);
db().prepare("UPDATE masterpieces SET hash = ?, fingerprint = ? WHERE id = ?").run(painting.hash, print, id);
if (painting.status === APPROVED && painting.reviewedBy && painting.reviewedBy !== AUTO_APPROVER) {
notePictureApproved(painting, print);
}
}
// pictures approved before fingerprints were kept: from a painting of
// theirs, once every painting has its own
for (const hash of missing.length ? [] : notedAgain.splice(0, BACKFILL_BATCH)) {
const row = db().prepare("SELECT fingerprint FROM masterpieces WHERE hash = ? AND fingerprint IS NOT NULL").get(hash);
if (row) {
const print = Buffer.from(row.fingerprint);
const thumb = jpegPrint.thumbnail(print);
db().prepare("UPDATE masterpiece_approved_pictures SET fingerprint = ?, thumb = ? WHERE hash = ?").run(print, thumb, hash);
approvedPictures.set(hash, thumb);
}
}
if (missing.length || notedAgain.length) {
setTimeout(step, 200).unref();
}
};
if (missing.length || notedAgain.length) {
setTimeout(step, 1000).unref();
}
};
// why this account may not paint for a frame now, as words for the player,
// or null when it may: too new an account (asked at the easel, step 1), or
// as many new pictures in the last 24 hours as a day allows (asked of a
// picture not approved before, step 2). `whenFree` speaks of the wait.
const whenFree = seconds => {
const hours = Math.ceil(seconds / 3600);
return hours > 1 ? `in ${hours} hours` : `in ${Math.max(1, Math.ceil(seconds / 60))} minutes`;
};
const tooNew = account => {
const age = now() - (Number(account.createdAt) || 0);
if (age < config.masterpieceMinAccountAge) {
return `Accounts can make Masterpieces once they are a day old. Try again ${whenFree(config.masterpieceMinAccountAge - age)}.`;
}
return null;
};
const tooMany = account => {
const recent = db().prepare("SELECT created_at FROM masterpiece_uploads WHERE creator_id = ? AND created_at > ? ORDER BY created_at")
.all(account.id, now() - DAY);
const perDay = config.masterpiecesPerDay;
if (recent.length >= perDay) {
return `You can make ${perDay} new Masterpieces a day. Try again ${whenFree(recent[recent.length - perDay].created_at + DAY - now())}.`;
}
return null;
}; };
const needsReview = () => accounts.setting(REVIEW_SETTING) !== "0"; const needsReview = () => accounts.setting(REVIEW_SETTING) !== "0";
const setNeedsReview = on => accounts.setSetting(REVIEW_SETTING, on ? "1" : "0"); const setNeedsReview = on => accounts.setSetting(REVIEW_SETTING, on ? "1" : "0");
const forget = id => { // `unapprove`: it was taken back by staff, so its picture is no longer one
// approved before (a painting thrown away unframed leaves it alone).
const forget = (id, unapprove = false) => {
const painting = known.get(id);
if (unapprove && painting && painting.hash) {
for (const hash of approvedMatches(painting.hash, printOf(painting))) {
db().prepare("DELETE FROM masterpiece_approved_pictures WHERE hash = ?").run(hash);
approvedPictures.delete(hash);
}
}
known.delete(id); known.delete(id);
db().prepare("DELETE FROM masterpieces WHERE id = ?").run(id); db().prepare("DELETE FROM masterpieces WHERE id = ?").run(id);
fs.rmSync(fileOf(id), {force: true}); fs.rmSync(fileOf(id), {force: true});
@@ -118,6 +282,7 @@ const sweep = () => {
forget(painting.id); forget(painting.id);
} }
} }
db().prepare("DELETE FROM masterpiece_uploads WHERE created_at <= ?").run(now() - DAY);
}; };
setInterval(() => { setInterval(() => {
try { try {
@@ -128,8 +293,12 @@ setInterval(() => {
} }
}, 600000).unref(); }, 600000).unref();
// A token for one upload by this account (step 1). // A token for one upload by this account (step 1), or null when it is
// `tooNew`, which says why.
const issueToken = account => { const issueToken = account => {
if (tooNew(account)) {
return null;
}
for (const [token, entry] of tokens) { for (const [token, entry] of tokens) {
if (entry.account === account.id) { if (entry.account === account.id) {
tokens.delete(token); tokens.delete(token);
@@ -181,15 +350,33 @@ const looksLikeJpeg = image => {
return false; return false;
}; };
// step 2. returns the new painting's id, or null when the token is not // step 2. resolves to {uuid}, the new painting's id, or {uuid: null} when
// good, the picture is not a JPEG of a sane size, or the account has posted // the token is not good, the picture is not a JPEG of a sane size, or the
// too many. // account has posted too many; with `refusal` and `maker` when the player
const upload = (token, image) => { // should be told why.
const upload = async (token, image) => {
const entry = typeof token === "string" ? tokens.get(token) : null; const entry = typeof token === "string" ? tokens.get(token) : null;
tokens.delete(token); tokens.delete(token);
if (!entry || entry.expires < Date.now() || !Buffer.isBuffer(image) || image.length > MAX_IMAGE_BYTES || !looksLikeJpeg(image) if (!entry || entry.expires < Date.now() || !Buffer.isBuffer(image) || image.length > MAX_IMAGE_BYTES || !looksLikeJpeg(image)
|| !uploadsPerHour.allow(entry.account)) { || !uploadsPerHour.allow(entry.account)) {
return null; return {uuid: null};
}
// a picture approved before is not a new one and does not count
const hash = hashOf(image);
const print = jpegPrint.fingerprint(image);
const approvedBefore = pictureApproved(hash, print);
const maker = accounts.byId(entry.account);
const refusal = maker && !approvedBefore ? tooNew(maker) || tooMany(maker) : null;
if (!maker || refusal) {
return {uuid: null, refusal, maker};
}
const safety = await imageModeration.scan(image);
if (safety.blocked) {
console.log(`[masterpieces] rejected unsafe upload from account ${entry.account}`);
return {uuid: null};
}
if (!approvedBefore) {
db().prepare("INSERT INTO masterpiece_uploads (creator_id, created_at) VALUES (?, ?)").run(entry.account, now());
} }
// one painting at a time is between the easel and the frame. // one painting at a time is between the easel and the frame.
for (const painting of [...known.values()]) { for (const painting of [...known.values()]) {
@@ -197,18 +384,21 @@ const upload = (token, image) => {
forget(painting.id); forget(painting.id);
} }
} }
const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, likes: []}; const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, reviewedAt: null, reviewedBy: null, likes: [], hash};
fs.writeFileSync(fileOf(painting.id), image); fs.writeFileSync(fileOf(painting.id), image);
db().prepare("INSERT INTO masterpieces (id, creator_id, created_at, status, frame, likes, image) VALUES (?, ?, ?, ?, ?, '[]', ?)") db().prepare("INSERT INTO masterpieces (id, creator_id, created_at, status, frame, likes, image, hash, fingerprint) VALUES (?, ?, ?, ?, ?, '[]', ?, ?, ?)")
.run(painting.id, painting.creator, painting.createdAt, painting.status, painting.frame, NO_IMAGE); .run(painting.id, painting.creator, painting.createdAt, painting.status, painting.frame, NO_IMAGE, hash, print);
known.set(painting.id, painting); known.set(painting.id, painting);
return painting.id; return {uuid: painting.id};
}; };
const setStatus = (painting, status) => { // `by`: who approved it, when someone did.
const setStatus = (painting, status, by = null) => {
painting.status = status; painting.status = status;
db().prepare("UPDATE masterpieces SET status = ?, frame = ?, reviewed_at = ? WHERE id = ?") painting.reviewedAt = status === APPROVED ? now() : null;
.run(status, painting.frame, status === APPROVED ? now() : null, painting.id); painting.reviewedBy = status === APPROVED ? by : null;
db().prepare("UPDATE masterpieces SET status = ?, frame = ?, reviewed_at = ?, reviewed_by = ? WHERE id = ?")
.run(status, painting.frame, painting.reviewedAt, painting.reviewedBy, painting.id);
}; };
// may this account make an item of that painting, in that frame? (Step 3, // may this account make an item of that painting, in that frame? (Step 3,
@@ -223,11 +413,19 @@ const claimable = (account, id, frame) => {
}; };
// step 3, paid for: the painting is an item now. true when it is approved // step 3, paid for: the painting is an item now. true when it is approved
// on the spot. // on the spot: review is off, or its picture was approved before.
const claim = (id, frame) => { const claim = (id, frame) => {
const painting = known.get(String(id)); const painting = known.get(String(id));
painting.frame = frame; painting.frame = frame;
setStatus(painting, needsReview() ? PENDING : APPROVED); if (!needsReview()) {
setStatus(painting, APPROVED);
}
else if (pictureApproved(painting.hash, printOf(painting))) {
setStatus(painting, APPROVED, AUTO_APPROVER);
}
else {
setStatus(painting, PENDING);
}
return painting.status === APPROVED; return painting.status === APPROVED;
}; };
@@ -262,13 +460,26 @@ const mayView = (id, address, addressOf) => {
return painting.status === APPROVED || Boolean(maker && addressOf(maker) && addressOf(maker) === address); return painting.status === APPROVED || Boolean(maker && addressOf(maker) && addressOf(maker) === address);
}; };
const approve = id => { // `by`: the moderator's username, or "admin". its picture is approved from
// now on, and the same picture waiting in other paintings is approved with
// it. the paintings approved, none when `id` was not waiting.
const approve = (id, by) => {
const painting = get(id); const painting = get(id);
if (!painting || painting.status !== PENDING) { if (!painting || painting.status !== PENDING) {
return false; return [];
} }
setStatus(painting, APPROVED); setStatus(painting, APPROVED, by);
return true; if (!painting.hash) {
return [painting];
}
const print = printOf(painting);
notePictureApproved(painting, print);
const twins = [...known.values()].filter(other => other.status === PENDING
&& (other.hash === painting.hash || (print && jpegPrint.samePicture(print, printOf(other)))));
for (const twin of twins) {
setStatus(twin, APPROVED, AUTO_APPROVER);
}
return [painting, ...twins];
}; };
// is a den item fit to be shown, traded and recycled? anything that is not // is a den item fit to be shown, traded and recycled? anything that is not
@@ -312,13 +523,31 @@ const gallery = () => {
return {pool: hung.slice(0, GALLERY_SPOTS), pluspool: hung.slice(GALLERY_SPOTS)}; return {pool: hung.slice(0, GALLERY_SPOTS), pluspool: hung.slice(GALLERY_SPOTS)};
}; };
// newest first: the waiting ones by when they were made, the approved ones
// by when they were approved, so that one let in by mistake is near the top.
const list = status => [...known.values()].filter(painting => painting.status === status) const list = status => [...known.values()].filter(painting => painting.status === status)
.sort((one, other) => other.createdAt - one.createdAt) .sort((one, other) => (other.reviewedAt || other.createdAt) - (one.reviewedAt || one.createdAt))
.map(painting => { .map(painting => {
const maker = creatorOf(painting.id); const maker = creatorOf(painting.id);
return {id: painting.id, creator: maker ? maker.username : "(deleted account)", createdAt: painting.createdAt, frame: painting.frame, likes: painting.likes.length}; return {id: painting.id, creator: maker ? maker.username : "(deleted account)", createdAt: painting.createdAt, frame: painting.frame, likes: painting.likes.length,
approvedAt: painting.reviewedAt, approvedBy: painting.reviewedBy};
}); });
// both lists for the panels, narrowed to makers whose names have
// `creator` in them (the one of exactly that name first): {waiting,
// approved}, newest first.
const listsFor = creator => {
const wanted = String(creator || "").trim().toLowerCase().slice(0, 100);
const narrowed = paintings => (wanted ? paintings.filter(painting => painting.creator.toLowerCase().includes(wanted))
.sort((one, other) => Number(other.creator.toLowerCase() === wanted) - Number(one.creator.toLowerCase() === wanted)) : paintings);
return {waiting: narrowed(list(PENDING)), approved: narrowed(list(APPROVED))};
};
// the last `count` approved, the latest first, for the moderator panel to
// take one back from: only the ones `by` approved, when given.
const recentlyApproved = (count, by = "") => list(APPROVED)
.filter(painting => !by || String(painting.approvedBy || "").toLowerCase() === by.toLowerCase()).slice(0, count);
const madeBy = account => [...known.values()].filter(painting => painting.creator === account.id).map(painting => painting.id); const madeBy = account => [...known.values()].filter(painting => painting.creator === account.id).map(painting => painting.id);
// generic lists: (mediaId, name string id) pairs, or null when `listId` is // generic lists: (mediaId, name string id) pairs, or null when `listId` is
@@ -327,7 +556,7 @@ const frameList = listId =>
([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null); ([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null);
module.exports = { module.exports = {
load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, frameList, load, issueToken, tooNew, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, recentlyApproved, frameList,
needsReview, setNeedsReview, madeBy, needsReview, setNeedsReview, madeBy,
PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES, PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES,
}; };
+308 -29
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);
@@ -75,8 +84,35 @@ const messagesPerMinute = limits.limiter(900, 60000);
// the "start" message a game waits for once it has said it is ready. // the "start" message a game waits for once it has said it is ready.
const START = { const START = {
seed: () => [serial()], seed: () => [serial()],
seedAndPlayers: game => [serial(), game.players.length], // then each player's sfs id and a field the game skips: a game knows
// which player is its own by the id (GemBreakerPlayer.init), and only
// that one aims and shoots.
seedAndPlayers: game => [serial(), game.players.length, ...game.players.flatMap(player => [player.id, 0])],
// Spider Zapper and Wind Rider (SpiderShooterPlayer.init,
// ParachuteGliderPlayer.init): each player's sfs id and where it starts.
// given only the seed they had no players, none of them their own:
// nothing could be shot, and nobody glided.
seedAndCrosshairs: game => [serial(), game.players.length,
...game.players.flatMap((player, at) => [player.id, CROSSHAIR_X + at * CROSSHAIR_GAP, CROSSHAIR_Y])],
}; };
const CROSSHAIR_X = 400;
const CROSSHAIR_GAP = 100;
const CROSSHAIR_Y = 300;
// the room games several players play together: "Multiplayer" on the
// game's waiting list (MinigameManager.setupWaitListPopup), for players in
// the same room. each client plays the same game from the same start, and
// the server passes each player's moves on to the others: `relay` names
// the messages passed on, true for those that go with the sender's sfs id
// first. a full list starts the game.
const MULTIPLAYER = {
// GemBreaker.message: "pos" [sfsUserId, cannon angle], "shoot" [the shot's
// nine numbers], "playerLost" [the next round's seed]. two players, a
// field each, first to win two rounds.
GemBreaker: {max: 2, relay: {pos: true, shoot: false, playerLost: false}},
};
const MAX_RELAYED_FIELDS = 12;
const RELAYED_FIELD = /^[-0-9a-zA-Z.]{1,32}$/;
// serial numbers the client mixes into its award messages; any number will do. // serial numbers the client mixes into its award messages; any number will do.
function serial() { function serial() {
@@ -85,7 +121,7 @@ function serial() {
let nextGameRoomId = 500000; // well clear of the world's room ids let nextGameRoomId = 500000; // well clear of the world's room ids
module.exports = ({tell, leaveRoom, findOnline, blocks}) => { module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => {
// MinigameInfo.init, the 19 fields the "mi" reply carries for a game. // MinigameInfo.init, the 19 fields the "mi" reply carries for a game.
const info = game => [ const info = game => [
game.id, game.id,
@@ -93,11 +129,14 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
defpacks.stringId(game.title) || defpacks.stringId(FALLBACK_TITLE), defpacks.stringId(game.title) || defpacks.stringId(FALLBACK_TITLE),
game.swf, // extName game.swf, // extName
game.swf, // swfName game.swf, // swfName
game.buddy ? 2 : 1, game.buddy ? 2 : 1, // min and max players // min and max players: more than one gives the game a waiting list
// with "Single Player" and "Multiplayer" (lib/minigames.js MULTIPLAYER).
game.buddy ? 2 : MULTIPLAYER[game.swf] ? MULTIPLAYER[game.swf].max : 1,
game.buddy ? 2 : MULTIPLAYER[game.swf] ? MULTIPLAYER[game.swf].max : 1,
0, // max spectators 0, // max spectators
game.type, game.type,
// the game card: the title picture on the "play" popup (not known), and // the game card: the title picture on the "play" popup, and for a buddy
// for a buddy game the picture in the invitation. // game the picture in the invitation.
game.card || 0, game.card || 0,
...(game.vars || [0, 0, 0]), ...(game.vars || [0, 0, 0]),
game.buddy ? 1 : 0, // ready for player-versus-player: listed on players' cards game.buddy ? 1 : 0, // ready for player-versus-player: listed on players' cards
@@ -124,6 +163,82 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
} }
}; };
// A buddy game's bubble over a player's head, which anyone else in the
// room can click to play them (UserCommXtCommManager.sendCustomPVPMessage:
// a chat line "on|off" of type 12 with the game's id after it). the client
// reads it back as "on|<gameDefId>" or "off", and its sender waits for
// their own before going on. `session.pvpBubble` is the game's id.
const BUBBLE = "12";
const bubbleLine = session => [`on|${session.pvpBubble}`, BUBBLE, 0];
const bubbleSeers = session => watchers(session).filter(other => !blocks.either(other.account, session.account));
// the bubble goes for everyone else. the player's own "off" waits, when
// they are in a game, till they are out of it: it would end the game the
// client has only just set up (MinigameManager.readySelfForPvpGame).
const dropBubble = session => {
if (!session.pvpBubble) {
return;
}
session.pvpBubble = null;
if (session.room) {
for (const other of bubbleSeers(session)) {
other.sendXt("uc", session.room.id, session.id, "off", BUBBLE);
}
}
};
const bubbleOff = session => {
if (session.game) {
session.bubbleOffOwed = true;
}
else if (session.room) {
session.bubbleOffOwed = false;
session.sendXt("uc", session.room.id, session.id, "off", BUBBLE);
}
};
const bubble = (session, word, gameDefId) => {
if (word !== "on") {
dropBubble(session);
bubbleOff(session);
return;
}
const def = games.get(Number(gameDefId));
if (!def || !def.buddy || !Object.hasOwn(buddyGames, def.swf) || !session.room || session.game || session.invite
|| session.invisible || !accounts.featureOn(session.account, "gameInvites")) {
if (session.room && !session.game) {
tell(session, session.invisible ? "Nobody can see you to play with you." : "You cannot ask for a game right now.");
}
dropBubble(session);
bubbleOff(session);
return;
}
session.pvpBubble = def.id;
for (const other of [session, ...bubbleSeers(session)]) {
other.sendXt("uc", session.room.id, session.id, ...bubbleLine(session));
}
};
// a bubble that is up, for a player who has just been shown its owner.
const showBubble = (to, owner) => {
if (owner.pvpBubble && owner.room && to !== owner && !blocks.either(to.account, owner.account)) {
to.sendXt("uc", owner.room.id, owner.id, ...bubbleLine(owner));
}
};
// Food-machine games reward a short-lived avatar attachment. Replying
// with "_a" is important: MinigameManager turns it into the same local
// attachment action used by den objects, which then sends the normal
// user-communication packet to the room. Sending that packet ourselves
// skips the local state and leaves the player with nothing visible.
const grantAttachment = (session, game, reply, emoticonDefId, extra = "") => {
if (game.attachmentGranted) {
return;
}
const state = attachmentExtra(extra);
if (!defpacks.emoticonMediaId(emoticonDefId)) {
return;
}
game.attachmentGranted = true;
reply("_a", emoticonDefId, state);
};
// takes the player out of the game they are in, if any, and out of an // takes the player out of the game they are in, if any, and out of an
// invitation. // invitation.
const leave = session => { const leave = session => {
@@ -133,7 +248,21 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
return; return;
} }
session.game = null; session.game = null;
// an in-room game may say it is done just before it hands over what it
// made (the Juice Bar's smoothie, the Cocoa Hut's drink: an attachment,
// lib/world.js pubMsg), labelled with the game's room
session.lastGame = {roomId: game.roomId, until: Date.now() + GAME_AFTERGLOW_MS};
if (session.bubbleOffOwed) {
bubbleOff(session);
}
game.players = game.players.filter(player => player !== session); game.players = game.players.filter(player => player !== session);
if (game.lobby) {
if (game.players.length === 0) {
lobbies.delete(game.lobby);
}
tellLobby(game);
return;
}
// the games' own "player left": [sfsUserId]. A buddy game takes it for // the games' own "player left": [sfsUserId]. A buddy game takes it for
// a win, so the one still looking at the result of a game that has been // a win, so the one still looking at the result of a game that has been
// decided is not told. three of them only the clients know the end of // decided is not told. three of them only the clients know the end of
@@ -180,6 +309,11 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
// minigamePetMastery) and who is in the game (joinGameResponse). // minigamePetMastery) and who is in the game (joinGameResponse).
const seat = (session, game, music) => { const seat = (session, game, music) => {
const avatar = activeAvatar(session.account); const avatar = activeAvatar(session.account);
// off to a game: a bubble still up goes (and its owner is told after).
if (session.pvpBubble) {
dropBubble(session);
session.bubbleOffOwed = true;
}
session.game = game; session.game = game;
session.sendXt("rj", -1, 1, `game${game.def.id}_${game.roomId}`, game.roomId, game.players.length, game.players.length, 0, 0, session.sendXt("rj", -1, 1, `game${game.def.id}_${game.roomId}`, game.roomId, game.players.length, game.players.length, 0, 0,
0, 1, 0, 1, game.def.type === IN_ROOM ? 1 : 0, // isPrivate, isGame, isLimbo, isTemp, isSubRoom 0, 1, 0, 1, game.def.type === IN_ROOM ? 1 : 0, // isPrivate, isGame, isLimbo, isTemp, isSubRoom
@@ -191,6 +325,59 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
session.sendXt("mj", game.roomId, ...game.players.map(player => player.id)); session.sendXt("mj", game.roomId, ...game.players.map(player => player.id));
}; };
// the waiting lists of multiplayer room games: "<gameDefId> <room>" -> a
// game not started yet. one is answered "mj" from the room the players
// wait in, with who waits: the client draws them from that room, so they
// stay in it till the list is full.
const lobbies = new Map();
const tellLobby = game => {
for (const player of game.players) {
player.sendXt("mj", game.waitRoom.id, ...game.players.map(other => other.id));
}
};
const joinLobby = (session, def, multi) => {
const key = `${def.id} ${session.room.name}`;
let game = lobbies.get(key);
if (game && game.players.some(player => blocks.either(player.account, session.account))) {
session.sendXt("mj", -1, "as", 0);
tell(session, "Someone already waiting for that game is not someone you play with. Try again later.");
return;
}
if (!game) {
game = {roomId: nextGameRoomId++, def, multi, players: [], started: false, ready: new Set(), lobby: key, waitRoom: session.room};
lobbies.set(key, game);
}
game.players.push(session);
session.game = game;
tellLobby(game);
if (game.players.length >= multi.max) {
lobbies.delete(key);
game.lobby = null;
for (const player of game.players) {
const music = player.room ? player.room.customMusicDef : 0;
if (def.type !== IN_ROOM) {
leaveRoom(player);
}
seat(player, game, music);
}
start(game);
}
};
// a move in a multiplayer room game, passed on to the other players.
const relay = (session, game, word, params) => {
const withId = game.multi.relay[word];
if (!game.started || params.length > MAX_RELAYED_FIELDS || !params.every(field => RELAYED_FIELD.test(String(field)))
|| !messagesPerMinute.allow(session.account.id)) {
return;
}
for (const other of game.players) {
if (other !== session) {
other.sendXt("mm", game.roomId, word, ...(withId ? [session.id] : []), ...params);
}
}
};
// starts a buddy game between two players (lib/buddygames.js says what // starts a buddy game between two players (lib/buddygames.js says what
// `match` is). it runs in a window over whatever room each is in. // `match` is). it runs in a window over whatever room each is in.
const startMatch = (def, sender, target) => { const startMatch = (def, sender, target) => {
@@ -239,8 +426,12 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
// den items a claw machine can drop: the plushies, of the machine's own // den items a claw machine can drop: the plushies, of the machine's own
// animal when it is named for one ("The Wolf Claw"). // animal when it is named for one ("The Wolf Claw").
let plushies = null; let plushies = null;
// the game's own den items only: a custom item (and a player's own, which
// is nobody else's to win) may be missing from the winner's game, whose
// prize popup then threw (DenItem.initShopItem) and left the game frozen.
const gameOwnDenItemIds = () => defpacks.denItemIds().filter(id => id < customItems.FIRST_ID);
const clawPrizes = game => { const clawPrizes = game => {
plushies = plushies || defpacks.denItemIds().filter(id => /plush/i.test(defpacks.denItemDef(id).abbrName)); plushies = plushies || gameOwnDenItemIds().filter(id => /plush/i.test(defpacks.denItemDef(id).abbrName));
const item = defpacks.denItemIds().map(id => defpacks.denItemDef(id)).find(def => Number(def.gameDefId) === game.id); const item = defpacks.denItemIds().map(id => defpacks.denItemDef(id)).find(def => Number(def.gameDefId) === game.id);
const animal = item ? /^ArcCraneGame(.+)$/.exec(item.abbrName) : null; const animal = item ? /^ArcCraneGame(.+)$/.exec(item.abbrName) : null;
const own = animal ? plushies.filter(id => defpacks.denItemDef(id).abbrName.toLowerCase().includes(animal[1].toLowerCase())) : []; const own = animal ? plushies.filter(id => defpacks.denItemDef(id).abbrName.toLowerCase().includes(animal[1].toLowerCase())) : [];
@@ -251,7 +442,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
// machines aside. // machines aside.
let phantomItems = null; let phantomItems = null;
const invasionPrizes = () => { const invasionPrizes = () => {
phantomItems = phantomItems || defpacks.denItemIds().filter(id => /phantom/i.test(defpacks.denItemDef(id).abbrName) phantomItems = phantomItems || gameOwnDenItemIds().filter(id => /phantom/i.test(defpacks.denItemDef(id).abbrName)
&& !/^Arc/.test(defpacks.denItemDef(id).abbrName) && defpacks.string(defpacks.denItemDef(id).nameStrId)); && !/^Arc/.test(defpacks.denItemDef(id).abbrName) && defpacks.string(defpacks.denItemDef(id).nameStrId));
return phantomItems.length ? phantomItems : defpacks.denItemIds().slice(0, 1); return phantomItems.length ? phantomItems : defpacks.denItemIds().slice(0, 1);
}; };
@@ -271,7 +462,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
} }
account.currency.gems -= CARNIVAL_COST; account.currency.gems -= CARNIVAL_COST;
achievements.currencyChanged(account, "gems", -CARNIVAL_COST); achievements.currencyChanged(account, "gems", -CARNIVAL_COST);
accounts.save(); accounts.save(account);
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0); session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
game.serial2 = serial(); game.serial2 = serial();
reply("pg", "1", hideSerial(game.serial2)); reply("pg", "1", hideSerial(game.serial2));
@@ -288,20 +479,66 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
if (tickets > 0) { if (tickets > 0) {
account.currency.tickets = (account.currency.tickets || 0) + tickets; account.currency.tickets = (account.currency.tickets || 0) + tickets;
achievements.currencyChanged(account, "tickets", tickets); achievements.currencyChanged(account, "tickets", tickets);
accounts.save(); accounts.save(account);
session.sendXt("cu", -1, CURRENCY_TICKETS, account.currency.tickets, 0); session.sendXt("cu", -1, CURRENCY_TICKETS, account.currency.tickets, 0);
} }
reply("gr", tickets); reply("gr", tickets);
}, },
}; };
// 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
@@ -315,7 +552,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
} }
account.currency.gems -= CLAW_COST; account.currency.gems -= CLAW_COST;
achievements.currencyChanged(account, "gems", -CLAW_COST); achievements.currencyChanged(account, "gems", -CLAW_COST);
accounts.save(); accounts.save(account);
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0); session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
const prizes = clawPrizes(game.def); const prizes = clawPrizes(game.def);
const won = prizes.length > 0 && Math.random() < CLAW_WIN_CHANCE; const won = prizes.length > 0 && Math.random() < CLAW_WIN_CHANCE;
@@ -335,7 +572,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
WindRider: { WindRider: {
go() {}, go() {},
gw(session, game, params, reply) { gw(session, game, params, reply) {
const ids = defpacks.clothingIds(); const ids = defpacks.clothingIds().filter(id => id < customItems.FIRST_ID);
const def = Math.random() < SKY_HIGH_PRIZE_CHANCE ? defpacks.itemDef(ids[Math.floor(Math.random() * ids.length)]) : null; const def = Math.random() < SKY_HIGH_PRIZE_CHANCE ? defpacks.itemDef(ids[Math.floor(Math.random() * ids.length)]) : null;
session.gamePrize = def ? {def: Number(def.id), color: Number(String(def.colors).split(",")[0])} : null; session.gamePrize = def ? {def: Number(def.id), color: Number(String(def.colors).split(",")[0])} : null;
reply("gw", def ? "1" : "0", def ? def.id : 0, 0, def ? session.gamePrize.color : 0); reply("gw", def ? "1" : "0", def ? def.id : 0, 0, def ? session.gamePrize.color : 0);
@@ -343,7 +580,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
gd(session, game, [keep]) { gd(session, game, [keep]) {
if (keep === "1" && session.gamePrize) { if (keep === "1" && session.gamePrize) {
sendClothingAdded(session, addClothing(session.account, session.gamePrize.def, session.gamePrize.color)); sendClothingAdded(session, addClothing(session.account, session.gamePrize.def, session.gamePrize.color));
accounts.save(); accounts.save(session.account);
} }
session.gamePrize = null; session.gamePrize = null;
}, },
@@ -373,6 +610,18 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
}, },
// the touch pool: the same again, with six prizes; which one is in the // the touch pool: the same again, with six prizes; which one is in the
// first number. // first number.
// Spider Zapper, after each wave: "wave" [1 if the player shot enough,
// else 0] -> "wavesuccess" (the next wave) or "wavefail" (the end), and
// "waveend" [spiders shot] -> "waveend" [spiders shot] (its results).
// they went unanswered and the game waited after the first wave.
SpiderShooter: {
wave(session, game, [passed], reply) {
reply(passed === "1" ? "wavesuccess" : "wavefail");
},
waveend(session, game, [shot], reply) {
reply("waveend", /^\d{1,4}$/.test(String(shot)) ? Number(shot) : 0);
},
},
TouchPool: { TouchPool: {
ts(session, game, params, reply) { ts(session, game, params, reply) {
session.prizeSerial = serial(); session.prizeSerial = serial();
@@ -401,7 +650,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
} }
account.currency.gems -= INVASION_COST; account.currency.gems -= INVASION_COST;
achievements.currencyChanged(account, "gems", -INVASION_COST); achievements.currencyChanged(account, "gems", -INVASION_COST);
accounts.save(); accounts.save(account);
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0); session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
const prizes = invasionPrizes(); const prizes = invasionPrizes();
session.prizeSerial = serial(); session.prizeSerial = serial();
@@ -451,7 +700,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
}, },
// MinigameManager.launchGame: [gameDefId, multiplayer, proModeId, ?]. // MinigameManager.launchGame: [gameDefId, multiplayer, proModeId, ?].
mj(session, roomId, [gameDefId]) { mj(session, roomId, [gameDefId, multiplayer]) {
leave(session); // a game left without a word, if any leave(session); // a game left without a word, if any
const def = games.get(Number(gameDefId)); const def = games.get(Number(gameDefId));
if (!def || def.ready === false || def.buddy || !session.room) { if (!def || def.ready === false || def.buddy || !session.room) {
@@ -461,6 +710,10 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
tell(session, "That game is not ready on this server yet."); tell(session, "That game is not ready on this server yet.");
return; return;
} }
if (multiplayer === "1" && Object.hasOwn(MULTIPLAYER, def.swf)) {
joinLobby(session, def, MULTIPLAYER[def.swf]);
return;
}
const game = {roomId: nextGameRoomId++, def, players: [session], started: false, ready: new Set()}; const game = {roomId: nextGameRoomId++, def, players: [session], started: false, ready: new Set()};
const music = session.room.customMusicDef; // the client takes this from every room join const music = session.room.customMusicDef; // the client takes this from every room join
if (def.type !== IN_ROOM) { if (def.type !== IN_ROOM) {
@@ -490,6 +743,10 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
matchMessage(session, game, String(word), params); matchMessage(session, game, String(word), params);
return; return;
} }
if (game.multi && Object.hasOwn(game.multi.relay, String(word))) {
relay(session, game, String(word), params);
return;
}
const reply = (...fields) => session.sendXt("mm", game.roomId, ...fields); const reply = (...fields) => session.sendXt("mm", game.roomId, ...fields);
const own = game.def.tickets ? carnival : MESSAGES[game.def.swf]; const own = game.def.tickets ? carnival : MESSAGES[game.def.swf];
if (own && Object.hasOwn(own, word)) { if (own && Object.hasOwn(own, word)) {
@@ -528,7 +785,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
if (valid) { if (valid) {
account.currency.gems = (account.currency.gems || 0) + amount; account.currency.gems = (account.currency.gems || 0) + amount;
achievements.currencyChanged(account, "gems", amount); achievements.currencyChanged(account, "gems", amount);
accounts.save(); accounts.save(account);
} }
session.gemSerial = serial(); session.gemSerial = serial();
session.sendXt("mg", -1, session.gemSerial, 0); session.sendXt("mg", -1, session.gemSerial, 0);
@@ -547,7 +804,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
if (valid && (pet.mastery || 0) < MASTERY_FULL) { if (valid && (pet.mastery || 0) < MASTERY_FULL) {
pet.mastery = Math.min(MASTERY_FULL, (pet.mastery || 0) + amount); pet.mastery = Math.min(MASTERY_FULL, (pet.mastery || 0) + amount);
nowFull = pet.mastery === MASTERY_FULL; nowFull = pet.mastery === MASTERY_FULL;
accounts.save(); accounts.save(account);
} }
session.masterySerial = serial(); session.masterySerial = serial();
session.sendXt("ma", -1, session.masterySerial, nowFull ? 1 : 0); session.sendXt("ma", -1, session.masterySerial, nowFull ? 1 : 0);
@@ -594,13 +851,29 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
session.invite = target.invite = {def, sender: session, target}; session.invite = target.invite = {def, sender: session, target};
target.sendXt("mp", -1, def.id, 0, session.account.username, 1); target.sendXt("mp", -1, def.id, 0, session.account.username, 1);
}, },
// an open challenge to whoever walks up (UserCommXtCommManager.sendCustomPVPMessage); not offered. // a click on another player's game bubble (MinigameXtCommManager
mcp() {}, // .sendMinigameCustomPvpJoinMsg): [gameDefId, 0, their username]. the
// game starts at once, as an invitation said yes to; a bubble that is
// gone by now is answered as an invitation said no to
// (MinigameManager.pvpResponse), which puts the clicker back as they were.
mcp(session, roomId, [gameDefId, , username]) {
const def = games.get(Number(gameDefId));
const host = findOnline(String(username || ""));
const free = player => player && player.room && !player.game && !player.invite;
if (!def || !host || host === session || host.pvpBubble !== def.id || host.room !== session.room
|| !free(session) || !free(host) || blocks.either(session.account, host.account)
|| !accounts.featureOn(session.account, "gameInvites")) {
session.sendXt("mp", -1, def ? def.id : Number(gameDefId) || 0, 1);
return;
}
startMatch(def, host, session);
},
}; };
// the HUD's Games window (GameJoinPopup, generic list 341): the playable // the HUD's Games window (GameJoinPopup, generic list 341): the playable
// games that have a picture for it, by name. // games that have a picture for it, by name. A buddy game's card picture
const library = [...games.values()].filter(game => game.icon && game.ready !== false) // is drawn the same way, and picking one there puts its bubble up.
const library = [...games.values()].filter(game => (game.icon || (game.buddy && game.card)) && game.ready !== false)
.sort((one, other) => one.title.localeCompare(other.title)).map(game => game.id); .sort((one, other) => one.title.localeCompare(other.title)).map(game => game.id);
// the buddy games' descriptions, sent unasked when a player arrives: a // the buddy games' descriptions, sent unasked when a player arrives: a
@@ -615,6 +888,12 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
handlers, handlers,
leave, leave,
greet, greet,
bubble,
showBubble,
// out of the room: nobody there is left to see the bubble.
roomLeft: session => {
session.pvpBubble = null;
},
library: () => library, library: () => library,
// the room a player in a room-replacing game came from, for the panel. // the room a player in a room-replacing game came from, for the panel.
playing: session => (session.game ? session.game.def.title : null), playing: session => (session.game ? session.game.def.title : null),
+137 -8
View File
@@ -4,6 +4,7 @@ const accounts = require("./accounts.js");
const achievements = require("./achievements.js"); const achievements = require("./achievements.js");
const bans = require("./bans.js"); const bans = require("./bans.js");
const dens = require("./dens.js"); const dens = require("./dens.js");
const config = require("../config.js");
const {CURRENCIES} = require("./player.js"); const {CURRENCIES} = require("./player.js");
// moderation: kick, ban, silence, clear a den, grant gems, message a player. // moderation: kick, ban, silence, clear a den, grant gems, message a player.
@@ -18,6 +19,23 @@ const CURRENCY_GEMS = 0;
// client says "You earned N ..." in a popup when the amount went up. // client says "You earned N ..." in a popup when the amount went up.
const REASON_ANNOUNCE = 3; const REASON_ANNOUNCE = 3;
// a warning's reason, and the client's own warning popup for it
// (FacilitatorXtCommManager.showContextualWarningPopup, "fw"): its artwork
// and its words, which this server's strings already say in its own name.
const WARNINGS = {
behavior: 4, // "Inappropriate Behavior"
bullying: 1, // "Bullying"
personal: 3, // "Personal Information"
scamming: 9, // "Scamming"
// in the staff member's own words: its note is what the player is shown,
// in a message box (there is no popup for it), and it cannot be left out.
custom: null,
};
const CUSTOM_WARNING = "custom";
const MAX_WARNINGS_KEPT = 100;
const MAX_WARNING_NOTE = 200;
const SECONDS_PER_DAY = 86400;
const now = () => Math.floor(Date.now() / 1000); const now = () => Math.floor(Date.now() / 1000);
// seconds of ban left, PERMANENT, or 0 when not banned. // seconds of ban left, PERMANENT, or 0 when not banned.
@@ -35,6 +53,21 @@ const banOf = account => {
return seconds === 0 ? null : {seconds, reason: account.banReason || bans.NO_REASON, by: account.bannedBy || "", since: account.bannedAt || null}; return seconds === 0 ? null : {seconds, reason: account.banReason || bans.NO_REASON, by: account.bannedBy || "", since: account.bannedAt || null};
}; };
// the warnings an account has had in the last config.warningSilence.days
// (all of them when that is 0).
const recentWarnings = account => {
const days = (config.warningSilence || {}).days || 0;
const since = now() - days * SECONDS_PER_DAY;
return (account.warnings || []).filter(entry => !days || entry.at >= since).length;
};
// the minutes of silence a warning brings when it is the Nth recent one
// (config.warningSilence.steps, [[N, minutes], ...]); 0 for none.
const silenceForWarning = count => {
const step = ((config.warningSilence || {}).steps || []).find(([warnings]) => warnings === count);
return step ? step[1] : 0;
};
const isSilenced = account => account.silencedUntil === PERMANENT || (account.silencedUntil || 0) > now(); const isSilenced = account => account.silencedUntil === PERMANENT || (account.silencedUntil || 0) > now();
// seconds of silence left, PERMANENT, or 0 when the account may chat. // seconds of silence left, PERMANENT, or 0 when the account may chat.
@@ -52,6 +85,16 @@ module.exports = ({findOnline}) => {
// A "message from moderator" popup; also used to answer chat commands. // A "message from moderator" popup; also used to answer chat commands.
const notify = (session, text) => discipline(session, "fp", text, 0); const notify = (session, text) => discipline(session, "fp", text, 0);
// a warning as the player sees it: the game's popup for its reason, or a
// custom one's words.
const showWarning = (session, entry) => {
if (entry.reason === CUSTOM_WARNING && entry.note) {
notify(session, `Warning: ${entry.note}`);
}
else {
discipline(session, "fw", WARNINGS[entry.reason] ?? WARNINGS.behavior);
}
};
const actions = { const actions = {
kick(target) { kick(target) {
@@ -71,7 +114,7 @@ module.exports = ({findOnline}) => {
target.banReason = bans.reasonText(reason); target.banReason = bans.reasonText(reason);
target.bannedBy = by; target.bannedBy = by;
target.bannedAt = now(); target.bannedAt = now();
accounts.save(); accounts.save(target);
bans.record({account: target, action: "ban", seconds: duration, reason: target.banReason, by}); bans.record({account: target, action: "ban", seconds: duration, reason: target.banReason, by});
const session = findOnline(target.username); const session = findOnline(target.username);
if (session) { if (session) {
@@ -87,7 +130,7 @@ module.exports = ({findOnline}) => {
delete target.banReason; delete target.banReason;
delete target.bannedBy; delete target.bannedBy;
delete target.bannedAt; delete target.bannedAt;
accounts.save(); accounts.save(target);
if (was) { if (was) {
bans.record({account: target, action: "unban", by}); bans.record({account: target, action: "unban", by});
} }
@@ -100,7 +143,7 @@ module.exports = ({findOnline}) => {
return false; return false;
} }
target.banReason = bans.reasonText(reason); target.banReason = bans.reasonText(reason);
accounts.save(); accounts.save(target);
bans.record({account: target, action: "reason", reason: target.banReason, by}); bans.record({account: target, action: "reason", reason: target.banReason, by});
return true; return true;
}, },
@@ -108,7 +151,7 @@ module.exports = ({findOnline}) => {
// duration in seconds, PERMANENT, or 0 to lift // duration in seconds, PERMANENT, or 0 to lift
silence(target, duration) { silence(target, duration) {
target.silencedUntil = duration === PERMANENT ? PERMANENT : (duration > 0 ? now() + duration : 0); target.silencedUntil = duration === PERMANENT ? PERMANENT : (duration > 0 ? now() + duration : 0);
accounts.save(); accounts.save(target);
const session = findOnline(target.username); const session = findOnline(target.username);
if (session) { if (session) {
// minutes, negative for "until further notice", 0 for "you may type again" // minutes, negative for "until further notice", 0 for "you may type again"
@@ -123,7 +166,7 @@ module.exports = ({findOnline}) => {
rejectName(target, by = "") { rejectName(target, by = "") {
target.nameRejected = {by, at: now()}; target.nameRejected = {by, at: now()};
accounts.revokeTokens(target); accounts.revokeTokens(target);
accounts.save(); accounts.save(target);
actions.kick(target); actions.kick(target);
return true; return true;
}, },
@@ -131,7 +174,7 @@ module.exports = ({findOnline}) => {
// taken back: the name will do after all. // taken back: the name will do after all.
acceptName(target) { acceptName(target) {
delete target.nameRejected; delete target.nameRejected;
accounts.save(); accounts.save(target);
return true; return true;
}, },
@@ -140,6 +183,34 @@ module.exports = ({findOnline}) => {
return true; return true;
}, },
// every post they wrote on anyone's Jammer Wall (lib/walls.js), their
// own included, and the replies to those, as deleting a post in the game
// takes its replies. returns {posts, replies, walls}.
clearWallPosts(author) {
const changed = [];
let posts = 0;
let replies = 0;
for (const owner of accounts.all()) {
const {wall} = owner;
const gone = new Set(wall.posts.filter(post => post.uid === author.id).map(post => post.x));
if (!gone.size) {
continue;
}
const kept = wall.posts.filter(post => !gone.has(post.x) && !gone.has(post.pp));
posts += gone.size;
replies += wall.posts.length - kept.length - gone.size;
const left = new Set(kept.map(post => post.x));
wall.posts = kept;
wall.hidden = wall.hidden.filter(id => left.has(id));
wall.modified = Date.now();
changed.push(owner);
}
if (changed.length) {
accounts.save(...changed);
}
return {posts, replies, walls: changed.length};
},
grantGems(target, amount) { grantGems(target, amount) {
return actions.grantCurrency(target, CURRENCY_GEMS, amount, false); return actions.grantCurrency(target, CURRENCY_GEMS, amount, false);
}, },
@@ -154,7 +225,7 @@ module.exports = ({findOnline}) => {
const before = target.currency[name] || 0; const before = target.currency[name] || 0;
target.currency[name] = Math.max(0, before + amount); target.currency[name] = Math.max(0, before + amount);
achievements.currencyChanged(target, name, target.currency[name] - before); achievements.currencyChanged(target, name, target.currency[name] - before);
accounts.save(); accounts.save(target);
const session = findOnline(target.username); const session = findOnline(target.username);
if (session) { if (session) {
// ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason] // ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason]
@@ -171,6 +242,51 @@ module.exports = ({findOnline}) => {
notify(session, text); notify(session, text);
return true; return true;
}, },
// a warning: kept on the account (who, when, why and a note for staff),
// and shown with the game's own warning popup: now if they are in a
// room, else once they are next (greet). the Nth warning within
// config.warningSilence.days may also silence them for a while; a
// longer silence already on them is left alone.
// returns {count, online, silencedMinutes}, or null for a reason that
// is not one (or a custom warning with nothing to say).
warn(target, reason, by, note = "") {
const text = String(note).trim().slice(0, MAX_WARNING_NOTE);
if (!Object.hasOwn(WARNINGS, reason) || (reason === CUSTOM_WARNING && !text)) {
return null;
}
const session = findOnline(target.username);
const seen = Boolean(session && session.greeted);
const entry = {at: now(), by, reason, note: text, seen};
target.warnings = [...(target.warnings || []), entry].slice(-MAX_WARNINGS_KEPT);
accounts.save();
if (seen) {
showWarning(session, entry);
}
let silencedMinutes = silenceForWarning(recentWarnings(target));
const left = silenceRemaining(target);
if (silencedMinutes && left !== PERMANENT && left < silencedMinutes * SECONDS_PER_MINUTE) {
actions.silence(target, silencedMinutes * SECONDS_PER_MINUTE);
}
else {
silencedMinutes = 0;
}
return {count: target.warnings.length, online: Boolean(session), silencedMinutes};
},
// takes back their latest warning (one given by mistake). a silence it
// brought stays; that is lifted on its own (silence 0). returns the
// warning taken back, or null when there is none.
unwarn(target) {
const list = target.warnings || [];
if (!list.length) {
return null;
}
const removed = list[list.length - 1];
target.warnings = list.slice(0, -1);
accounts.save();
return removed;
},
}; };
// the client's moderator requests, refused whoever sends them. each // the client's moderator requests, refused whoever sends them. each
@@ -178,7 +294,20 @@ module.exports = ({findOnline}) => {
const refuse = reply => session => session.sendXt(reply, -1, 0); const refuse = reply => session => session.sendXt(reply, -1, 0);
const handlers = {fk: refuse("fk"), fb: refuse("fb"), fs: refuse("fs"), fm: refuse("fm"), fg: refuse("fg"), fp: refuse("fp"), fc() {}}; const handlers = {fk: refuse("fk"), fb: refuse("fb"), fs: refuse("fs"), fm: refuse("fm"), fg: refuse("fg"), fp: refuse("fp"), fc() {}};
return {handlers, actions, banRemaining, banOf, isSilenced, silenceRemaining, PERMANENT}; // the first room has loaded (lib/world.js): a warning given while they
// were away is shown now, the latest only (the game has one warning
// popup), and all of them count as seen.
const greet = session => {
const unseen = (session.account.warnings || []).filter(entry => entry.seen === false);
if (!unseen.length) {
return;
}
unseen.forEach(entry => { entry.seen = true; });
accounts.save();
showWarning(session, unseen[unseen.length - 1]);
};
return {handlers, actions, greet, banRemaining, banOf, isSilenced, silenceRemaining, PERMANENT, WARNINGS: Object.keys(WARNINGS)};
}; };
Object.assign(module.exports, {isSilenced, banRemaining, banOf}); Object.assign(module.exports, {isSilenced, banRemaining, banOf});
+26 -3
View File
@@ -1,5 +1,6 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
// what each moderator did in the moderator panel (lib/modpanel.js), for // what each moderator did in the moderator panel (lib/modpanel.js), for
@@ -17,15 +18,37 @@ const SCHEMA = `
`; `;
const MAX_DETAIL = 400; const MAX_DETAIL = 400;
const SHOWN = 300; const SHOWN = 300;
const listeners = new Set();
const load = () => accounts.database().exec(SCHEMA); const load = () => accounts.database().exec(SCHEMA);
const record = (by, action, target = "", detail = "") => { const record = (by, action, target = "", detail = "") => {
const entry = {at: Math.floor(Date.now() / 1000), by: String(by), action: String(action), target: String(target), detail: String(detail).slice(0, MAX_DETAIL)};
accounts.database().prepare("INSERT INTO mod_log (at, by, action, target, detail) VALUES (?, ?, ?, ?, ?)") accounts.database().prepare("INSERT INTO mod_log (at, by, action, target, detail) VALUES (?, ?, ?, ?, ?)")
.run(Math.floor(Date.now() / 1000), by, action, String(target), String(detail).slice(0, MAX_DETAIL)); .run(entry.at, entry.by, entry.action, entry.target, entry.detail);
console.log(`[mod] ${by}: ${action}${target ? ` "${target}"` : ""}`); console.log(`[mod] ${logText(by)}: ${logText(action)}${logText(target ? ` "${target}"` : "")}`);
for (const listener of listeners) {
try {
listener(entry);
}
catch (err) {
console.error(`[modlog] listener failed: ${logText(err.message)}`);
}
}
}; };
const recent = () => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log ORDER BY id DESC LIMIT ?").all(SHOWN); const recent = () => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log ORDER BY id DESC LIMIT ?").all(SHOWN);
module.exports = {load, record, recent}; // what staff did to one player, newest first, for their timeline.
const about = username => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log WHERE target = ? COLLATE NOCASE ORDER BY id DESC LIMIT 100")
.all(String(username));
// Optional integrations subscribe here rather than wrapping record(), so an
// unavailable Discord channel can never stop a moderation action or its DB
// audit record from being written.
const onRecord = listener => {
listeners.add(listener);
return () => listeners.delete(listener);
};
module.exports = {load, record, recent, about, onRecord};
+53
View File
@@ -0,0 +1,53 @@
"use strict";
const crypto = require("crypto");
const accounts = require("./accounts.js");
// moderators' notes on a player: what staff want one another to know about
// them ("talked to them about trading, seemed fine"), on the player's page
// of the moderator panel and with "!notes" in the game. the player is never
// shown them (lib/manage.js leaves them out of their data).
//
// on an account: modNotes [{id, at, by, text}], the oldest first.
const MAX_NOTES = 100;
const MAX_TEXT = 500;
const now = () => Math.floor(Date.now() / 1000);
const list = account => [...(account.modNotes || [])].reverse();
// returns {note} or {error}.
const add = (account, by, text) => {
const clean = String(text || "").replace(/\s+/g, " ").trim().slice(0, MAX_TEXT);
if (!clean) {
return {error: "Write the note first."};
}
const note = {id: crypto.randomBytes(6).toString("hex"), at: now(), by: String(by), text: clean};
account.modNotes = [...(account.modNotes || []), note].slice(-MAX_NOTES);
accounts.save();
return {note};
};
// a note taken away by whoever wrote it, or by someone who may remove anyone's
// (`anyone`). returns {note} or {error}.
const remove = (account, id, by, anyone) => {
const note = (account.modNotes || []).find(entry => entry.id === String(id));
if (!note) {
return {error: "No such note."};
}
if (!anyone && note.by.toLowerCase() !== String(by).toLowerCase()) {
return {error: "Only whoever wrote a note, or an admin, can remove it."};
}
account.modNotes = account.modNotes.filter(entry => entry !== note);
accounts.save();
return {note};
};
// the newest notes on anybody, with whom they are about.
const recent = count => accounts.all()
.flatMap(account => (account.modNotes || []).map(note => ({...note, about: account.username})))
.sort((one, other) => other.at - one.at)
.slice(0, count);
module.exports = {list, add, remove, recent, MAX_TEXT};
+856 -40
View File
File diff suppressed because it is too large. Load diff
+29 -11
View File
@@ -12,10 +12,13 @@ const config = require("../config.js");
// the admin panel). the lists are files, read again when they change: // the admin panel). the lists are files, read again when they change:
// lib/reserved-names.txt staff-like names // lib/reserved-names.txt staff-like names
// public/filter/level1.txt the chat filter's first level: slurs, threats // public/filter/level1.txt the chat filter's first level: slurs, threats
// lib/sexual-names.txt sexual words, refused anywhere in a name
// (bar the short ones marked "=", see the file)
// and the names of the Epic Dens, which are how a showcase den is asked for. // and the names of the Epic Dens, which are how a showcase den is asked for.
const RESERVED_FILE = path.join(__dirname, "reserved-names.txt"); const RESERVED_FILE = path.join(__dirname, "reserved-names.txt");
const SLURS_FILE = path.join(config.publicDir, "filter", "level1.txt"); const SLURS_FILE = path.join(config.publicDir, "filter", "level1.txt");
const SEXUAL_FILE = path.join(__dirname, "sexual-names.txt");
const DIGITS = {0: "o", 1: "i", 3: "e", 4: "a", 5: "s", 7: "t"}; const DIGITS = {0: "o", 1: "i", 3: "e", 4: "a", 5: "s", 7: "t"};
// A word as it is compared: small letters, digits at either end dropped // A word as it is compared: small letters, digits at either end dropped
@@ -28,24 +31,35 @@ const plain = word => word.toLowerCase().replace(/^\d+|\d+$/g, "").replace(/\d/g
const squash = word => word.replace(/(.)\1+/g, "$1"); const squash = word => word.replace(/(.)\1+/g, "$1");
const stretched = word => /(.)\1\1/.test(word); const stretched = word => /(.)\1\1/.test(word);
// the entries of a list file: [{text, prefix}], text made plain as above. // the entries of a list file: [{text, prefix, word}], text made plain as
// above. "word" is for a line marked "=": in lib/sexual-names.txt the rest
// are matched anywhere in a name.
const lists = new Map(); // file -> {mtime, entries} const lists = new Map(); // file -> {mtime, entries}
// the file is opened once, and its time and its words are both of what was
// opened: a list changed in between cannot be read under the old one's time.
const read = file => { const read = file => {
let mtime = 0; let fd;
try { try {
mtime = fs.statSync(file).mtimeMs; fd = fs.openSync(file, "r");
} }
catch (err) { catch (err) {
return []; return [];
} }
const kept = lists.get(file); try {
if (kept && kept.mtime === mtime) { const mtime = fs.fstatSync(fd).mtimeMs;
return kept.entries; const kept = lists.get(file);
if (kept && kept.mtime === mtime) {
return kept.entries;
}
const entries = fs.readFileSync(fd, "utf8").split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith("#"))
.map(line => ({text: line.replace(/^=/, "").replace(/\*$/, "").split(/\s+/).map(plain).join(""), prefix: line.endsWith("*"), word: line.startsWith("=")}))
.filter(entry => entry.text.length >= 2);
lists.set(file, {mtime, entries});
return entries;
}
finally {
fs.closeSync(fd);
} }
const entries = fs.readFileSync(file, "utf8").split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith("#"))
.map(line => ({text: line.replace(/\*$/, "").split(/\s+/).map(plain).join(""), prefix: line.endsWith("*")})).filter(entry => entry.text.length >= 2);
lists.set(file, {mtime, entries});
return entries;
}; };
let epicDens = null; let epicDens = null;
@@ -71,7 +85,11 @@ const refused = username => {
const same = (word, entry) => word === entry.text || (entry.prefix && word.startsWith(entry.text)) const same = (word, entry) => word === entry.text || (entry.prefix && word.startsWith(entry.text))
|| (stretched(word) && (squash(word) === squash(entry.text) || (entry.prefix && squash(word).startsWith(squash(entry.text))))); || (stretched(word) && (squash(word) === squash(entry.text) || (entry.prefix && squash(word).startsWith(squash(entry.text)))));
const hit = entry => same(whole, entry) || words.some(word => same(word, entry)); const hit = entry => same(whole, entry) || words.some(word => same(word, entry));
return read(RESERVED_FILE).some(hit) || read(SLURS_FILE).some(hit) || denNames().includes(whole); // anywhere in the name, with a letter drawn out three times or more read
// as two and as one ("booooobs"; "Bobbby" is not "boob").
const drawnOut = [whole, whole.replace(/(.)\1{2,}/g, "$1$1"), whole.replace(/(.)\1{2,}/g, "$1")];
const inside = entry => (entry.word ? hit(entry) : drawnOut.some(form => form.includes(entry.text)));
return read(RESERVED_FILE).some(hit) || read(SLURS_FILE).some(hit) || read(SEXUAL_FILE).some(inside) || denNames().includes(whole);
}; };
module.exports = {refused, plain}; module.exports = {refused, plain};
+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
+489 -60
View File
@@ -1,5 +1,6 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto"); const crypto = require("crypto");
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
@@ -7,23 +8,31 @@ const accounts = require("./accounts.js");
const achievements = require("./achievements.js"); const achievements = require("./achievements.js");
const adopt = require("./adopt.js"); const adopt = require("./adopt.js");
const badges = require("./badges.js"); const badges = require("./badges.js");
const discordLinks = require("./discord.js");
const discordBot = require("./discordbot.js");
const bans = require("./bans.js"); const bans = require("./bans.js");
const colours = require("./colours.js"); const colours = require("./colours.js");
const chatlog = require("./chatlog.js");
const config = require("../config.js"); const config = require("../config.js");
const devices = require("./devices.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const log = require("./log.js"); const log = require("./log.js");
const masterpieces = require("./masterpieces.js"); const masterpieces = require("./masterpieces.js");
const modlog = require("./modlog.js"); const modlog = require("./modlog.js");
const modpanel = require("./modpanel.js"); const modpanel = require("./modpanel.js");
const playerItems = require("./playeritems.js");
const erase = require("./erase.js"); const erase = require("./erase.js");
const reports = require("./reports.js"); const reports = require("./reports.js");
const roles = require("./roles.js");
const sales = require("./sales.js"); const sales = require("./sales.js");
const stats = require("./stats.js");
const staff = require("./staff.js"); const staff = require("./staff.js");
const support = require("./support.js"); 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.
@@ -36,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;
@@ -46,6 +56,7 @@ const TEN_MINUTES_MS = 600000;
const DAY_SECONDS = 86400; const DAY_SECONDS = 86400;
const MAX_ANNOUNCEMENT = 300; const MAX_ANNOUNCEMENT = 300;
const MAX_OWNED_LISTED = 300; const MAX_OWNED_LISTED = 300;
const MAX_LISTED = 100; // accounts in one search of the Accounts page
// currencies the panel can hand out, as indexes into CURRENCIES. // currencies the panel can hand out, as indexes into CURRENCIES.
const GIFT_CURRENCIES = {gems: 0, tickets: 1, diamonds: 3}; const GIFT_CURRENCIES = {gems: 0, tickets: 1, diamonds: 3};
// who a ban is written down as given by. the panel has one password and so // who a ban is written down as given by. the panel has one password and so
@@ -82,9 +93,14 @@ const passwordAcceptable = password =>
typeof password === "string" && password.length >= MIN_PASSWORD_LENGTH && password.length <= MAX_PASSWORD_LENGTH; typeof password === "string" && password.length >= MIN_PASSWORD_LENGTH && password.length <= MAX_PASSWORD_LENGTH;
const load = () => { const load = () => {
// the number of worlds the admin chose last (world.setWorldCount)
const worlds = accounts.setting(world.WORLD_COUNT_SETTING);
if (worlds !== null) {
world.setWorldCount(worlds, false);
}
if (!hasPassword()) { if (!hasPassword()) {
setupCode = crypto.randomBytes(5).toString("hex"); setupCode = crypto.randomBytes(5).toString("hex");
console.log(`[admin] no admin password yet: open ${config.baseUrl}admin to choose one` console.log(`[admin] no admin password yet: open ${logText(config.baseUrl)}admin to choose one`
+ ` (from another machine it will ask for this setup code: ${setupCode})`); + ` (from another machine it will ask for this setup code: ${setupCode})`);
} }
}; };
@@ -104,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);
@@ -114,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) => {
@@ -136,22 +170,35 @@ 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)),
logins: account.numLogins, logins: account.numLogins,
playtime: account.playtime,
playtimePublic: account.playtimePublic,
online: playing.has(account.username), online: playing.has(account.username),
room: playing.get(account.username) || null, room: playing.get(account.username) || null,
// seconds left, -1 for permanent, 0 for not banned // seconds left, -1 for permanent, 0 for not banned
banned: ban, banned: ban,
banReason: ban === 0 ? "" : account.banReason || bans.NO_REASON, banReason: ban === 0 ? "" : account.banReason || bans.NO_REASON,
moderator: Boolean(account.moderator), moderator: Boolean(roles.roleOf(account)),
role: roles.roleOf(account),
// what they may do (their role's, with their own grants and denies)
permissions: roles.permissionsOf(account),
permGrants: account.permGrants || [],
permDenies: account.permDenies || [],
nameRejected: Boolean(account.nameRejected), nameRejected: Boolean(account.nameRejected),
silenced: world.moderation.isSilenced(account), silenced: world.moderation.isSilenced(account),
animals: account.avatars.length, animals: account.avatars.length,
level: activeAvatar(account).questLevel || 0, level: activeAvatar(account).questLevel || 0,
items: account.items.length + account.denItems.length, items: account.items.length + account.denItems.length,
gems: account.currency.gems || 0, gems: account.currency.gems || 0,
deviceBanned: devices.bannedId(account) !== 0,
devicesKnown: devices.knownFor(account).ids,
stoppedThisWeek: chatlog.notSentCount(account, 7),
paintings: masterpieces.madeBy(account).length,
}; };
}; };
@@ -259,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 => {
@@ -266,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 => {
@@ -283,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."};
}; };
@@ -345,7 +412,7 @@ const gift = (account, body) => {
if (body.kind === "adopt") { if (body.kind === "adopt") {
const ids = body.id === "all" ? defpacks.adoptAPetIds() : [body.id]; const ids = body.id === "all" ? defpacks.adoptAPetIds() : [body.id];
const given = ids.filter(id => adopt.give(account, id)).length; const given = ids.filter(id => adopt.give(account, id)).length;
accounts.save(); accounts.save(account);
return given ? {ok: `${name} has ${given} more on their Adopt-A-Pet checklist (it shows after their next login).`} return given ? {ok: `${name} has ${given} more on their Adopt-A-Pet checklist (it shows after their next login).`}
: {error: "No such Adopt-A-Pet, or they already have it."}; : {error: "No such Adopt-A-Pet, or they already have it."};
} }
@@ -358,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}.
@@ -365,30 +439,12 @@ const act = (account, body) => {
const {actions, PERMANENT} = world.moderation; const {actions, PERMANENT} = world.moderation;
const name = account.username; const name = account.username;
switch (body.action) { switch (body.action) {
case "password": {
if (accounts.setPassword(account, body.password)) {
return {error: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."};
}
actions.kick(account);
manage.forget(account); // their account page too, whoever has it open
modpanel.forget(account);
return {ok: `${name} has a new password and was signed out.`};
}
// the owner locks and unlocks on the account page; this is for when // the owner locks and unlocks on the account page; this is for when
// they cannot. // they cannot.
case "unlock": case "unlock":
account.locked = false; account.locked = false;
accounts.save(); 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();
return {ok: `2FA is off for ${name}.`};
case "rename": { case "rename": {
world.disconnect(account); world.disconnect(account);
manage.forget(account); manage.forget(account);
@@ -410,7 +466,7 @@ const act = (account, body) => {
return {error: "Pick a date and time in the past."}; return {error: "Pick a date and time in the past."};
} }
account.lastSeen = when; account.lastSeen = when;
accounts.save(); accounts.save(account);
return {ok: `${name} was last seen ${new Date(when * 1000).toISOString().replace("T", " ").slice(0, 16)} UTC, as far as the game knows.`}; return {ok: `${name} was last seen ${new Date(when * 1000).toISOString().replace("T", " ").slice(0, 16)} UTC, as far as the game knows.`};
} }
// the adventure level of the animal they are using. // the adventure level of the animal they are using.
@@ -428,20 +484,17 @@ const act = (account, body) => {
return {error: "Unknown badge."}; return {error: "Unknown badge."};
} }
badges.set(account, body.badges); badges.set(account, body.badges);
accounts.save(); accounts.save(account);
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();
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.
@@ -451,7 +504,7 @@ const act = (account, body) => {
return {error: `At most ${badges.MAX_BIO} characters on ${badges.MAX_BIO_LINES} lines.`}; return {error: `At most ${badges.MAX_BIO} characters on ${badges.MAX_BIO_LINES} lines.`};
} }
account.bio = bio; account.bio = bio;
accounts.save(); accounts.save(account);
return {ok: bio ? "Bio set." : "Bio cleared."}; return {ok: bio ? "Bio set." : "Bio cleared."};
} }
case "ban": { case "ban": {
@@ -474,6 +527,11 @@ const act = (account, body) => {
return {ok: `${name} is no longer banned.`}; return {ok: `${name} is no longer banned.`};
case "kick": case "kick":
return actions.kick(account) ? {ok: `${name} was disconnected.`} : {error: `${name} is not online.`}; return actions.kick(account) ? {ok: `${name} was disconnected.`} : {error: `${name} is not online.`};
// every computer they signed in from lately (lib/devices.js).
case "banDevices":
return staff.banDevices(account, body.reason, BY);
case "unbanDevices":
return staff.unbanDevicesOf(account, BY);
// counted in hours; the game's own notice counts minutes. // counted in hours; the game's own notice counts minutes.
case "silence": { case "silence": {
const hours = wholeNumber(body.hours, 0, MAX_BAN_HOURS); const hours = wholeNumber(body.hours, 0, MAX_BAN_HOURS);
@@ -485,18 +543,87 @@ const act = (account, body) => {
} }
// A moderator may use the moderator panel (lib/modpanel.js), with this // A moderator may use the moderator panel (lib/modpanel.js), with this
// account's password and its 2FA, which it has to have. // account's password and its 2FA, which it has to have.
// (the older on/off switch; "role" below is the full one.)
case "moderator": case "moderator":
if (body.on === true) { roles.setRole(account, body.on === true ? "moderator" : null);
account.moderator = true; if (body.on !== true) {
}
else {
delete account.moderator;
modpanel.forget(account); modpanel.forget(account);
} }
accounts.save(); accounts.save(account);
return {ok: body.on === true return {ok: body.on === true
? `${name} is a moderator.${totp.isOn(account) ? "" : " They have no 2FA yet and cannot sign in to the moderator panel until they turn it on."}` ? `${name} is a moderator.${totp.isOn(account) ? "" : " They have no 2FA yet and cannot sign in to the moderator panel until they turn it on."}`
: `${name} is no longer a moderator.`}; : `${name} is no longer a moderator.`};
// A staff role (lib/roles.js): helper, moderator, admin, or none. What
// each allows is listed under "GET /admin/api/roles".
case "role": {
const role = body.role === null || body.role === "" || body.role === "none" ? null : String(body.role);
if (!roles.setRole(account, role)) {
return {error: `No such role. Roles: ${Object.keys(roles.ROLES).join(", ")}, or none.`};
}
if (role === null) {
modpanel.forget(account);
}
accounts.save();
world.refreshStaff(account);
if (role === null) {
return {ok: `${name} has no staff role.`};
}
const label = roles.ROLES[role].label.toLowerCase();
return {ok: `${name} is now ${/^[aeiou]/.test(label) ? "an" : "a"} ${label}.${totp.isOn(account) ? "" : " They have no 2FA yet, so their role does nothing until they turn it on."}`};
}
// one staff member's own permissions, beyond their role's or taken from
// it ({grants: [...], denies: [...]}).
case "permissions": {
if (!roles.roleOf(account)) {
return {error: `${name} has no staff role: give them one first.`};
}
roles.setAccountPermissions(account, body.grants, body.denies);
accounts.save();
world.refreshStaff(account);
modlog.record("admin", "permissions changed", account.username,
`+${(account.permGrants || []).join(",") || "none"} -${(account.permDenies || []).join(",") || "none"}`);
return {ok: `${name}'s permissions are saved.`};
}
// guide: lets the player log in as one (lib/accounts.js setLoginChoices).
// it shows from their next login.
// lost access: a new random password, shown here once. it signs them out
// everywhere (lib/accounts.js setPassword); with `twoStepOff` their 2FA
// goes as well, for a lost authenticator.
case "tempPassword": {
let password = randomPassword();
// the account rules want a capital, a small letter and a digit, and no
// common word or the username in it: draw again until it has them.
while (accounts.setPassword(account, password)) {
password = randomPassword();
}
const twoStepOff = body.twoStepOff === true && totp.isOn(account);
if (twoStepOff) {
totp.turnOff(account);
}
accounts.save(account);
world.disconnect(account);
manage.forget(account);
modpanel.forget(account);
modlog.record("admin", "temporary password set", account.username, twoStepOff ? "2FA turned off" : "");
return {ok: `${name}'s password is now ${password}${twoStepOff ? " and their 2FA is off" : ""}. Ask them to change it on their account page.`, password};
}
case "guide": {
const on = body.on === true;
account.guideGiven = on;
accounts.save(account);
modlog.record("admin", on ? "made a guide" : "no longer a guide", account.username, "");
return {ok: on ? `${name} is a guide from their next login.` : `${name} is no longer a guide from their next login.`};
}
case "adminDashboardAccess": {
const on = body.on === true;
if (on && !account.discordId) {
return {error: `${name} must link their Discord account before it can be allowed.`};
}
account.adminDashboardAccess = on;
accounts.save(account);
modlog.record("admin", on ? "admin dashboard access given" : "admin dashboard access removed", account.username, account.discord || "");
return {ok: on ? `${name} may now sign in to this dashboard with their linked Discord account.` : `${name}'s Discord dashboard access was removed.`};
}
case "rejectName": case "rejectName":
actions.rejectName(account, BY); actions.rejectName(account, BY);
manage.forget(account); manage.forget(account);
@@ -518,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) {
@@ -544,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'",
}; };
@@ -563,7 +699,47 @@ const handle = async (req, res, url, from, web) => {
const route = `${req.method} ${url.pathname.replace(/\/$/, "") || "/admin"}`; const route = `${req.method} ${url.pathname.replace(/\/$/, "") || "/admin"}`;
if (route === "GET /admin") { if (route === "GET /admin") {
web.send(res, 200, 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;
}
// 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; return;
} }
if (req.method === "POST" && !sameOrigin(req)) { if (req.method === "POST" && !sameOrigin(req)) {
@@ -574,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;
@@ -601,7 +777,7 @@ const handle = async (req, res, url, from, web) => {
} }
storePassword(body.password); storePassword(body.password);
setupCode = null; setupCode = null;
console.log(`[admin] admin password chosen from ${from.address}`); console.log(`[admin] admin password chosen from ${logText(from.address)}`);
signIn(res); signIn(res);
reply(200, {ok: true}); reply(200, {ok: true});
return; return;
@@ -614,16 +790,54 @@ const handle = async (req, res, url, from, web) => {
} }
if (!hasPassword() || !passwordMatches(body.password)) { if (!hasPassword() || !passwordMatches(body.password)) {
recordFailure(from.key); recordFailure(from.key);
console.log(`[admin] failed sign-in from ${from.address}`); console.log(`[admin] failed sign-in from ${logText(from.address)}`);
reply(401, {error: "Wrong password."}); reply(401, {error: "Wrong password."});
return; return;
} }
console.log(`[admin] signed in from ${from.address}`); console.log(`[admin] signed in from ${logText(from.address)}`);
signIn(res); signIn(res);
reply(200, {ok: true}); reply(200, {ok: true});
return; return;
} }
// the second half of a Discord sign-in: the linked account's 2FA code.
case "POST /admin/api/discord/code": {
if (tooManyFailures(from.key)) {
reply(429, {error: "Too many attempts. Try again in a few minutes."});
return;
}
const token = pendingToken(req);
const hash = token ? sha256(token) : null;
const pending = hash ? pendingDiscord.get(hash) : null;
const account = pending && pending.expiry > Date.now() ? accounts.byId(pending.id) : null;
if (!discordAdmin(account)) {
if (hash) {
pendingDiscord.delete(hash);
}
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
reply(401, {error: "The Discord sign-in expired. Sign in with Discord again.", expired: true});
return;
}
if (!totp.verify(account, String(body.code || ""))) {
recordFailure(from.key);
console.log(`[admin] wrong 2FA code after Discord for ${logText(account.username)} from ${logText(from.address)}`);
pending.tries++;
if (pending.tries >= PENDING_TRIES) {
pendingDiscord.delete(hash);
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
reply(401, {error: "Too many wrong codes. Sign in with Discord again.", expired: true});
return;
}
reply(401, {error: "Wrong code."});
return;
}
pendingDiscord.delete(hash);
signIn(res, [pendingCookieHeader("", 0)]);
console.log(`[admin] ${logText(account.username)} signed in with Discord and a code from ${logText(from.address)}`);
reply(200, {ok: true});
return;
}
case "POST /admin/api/logout": case "POST /admin/api/logout":
signOut(req, res); signOut(req, res);
reply(200, {ok: true}); reply(200, {ok: true});
@@ -635,14 +849,155 @@ const handle = async (req, res, url, from, web) => {
return; return;
} }
// what players made that waits (the moderator panel's Review), and the
// admin's switches for the Item Maker: {enabled, approval}.
if (url.pathname === "/admin/api/review" || url.pathname === "/admin/api/item-switches") {
const done = (result, action, target = "", detail = "") => {
if (result.ok) {
modlog.record("admin", action, target, result.detail || detail);
}
reply(result.ok ? 200 : 400, result.ok ? {ok: result.ok} : {error: result.error});
};
if (route === "POST /admin/api/item-switches") {
const flag = value => (value === undefined ? undefined : value === true);
playerItems.setSwitches({enabled: flag(body.enabled), approval: flag(body.approval), artApproval: flag(body.artApproval)});
const pictures = playerItems.pictureWaits() ? "pictures wait for a moderator" : "pictures are shown at once";
done({ok: `The Item Maker is ${playerItems.enabled() ? "on" : "off"}; new items ${playerItems.approvalOn() ? "wait for a moderator first" : "are in the game at once"}; ${pictures}.`},
"item maker settings", "", `${playerItems.enabled() ? "on" : "off"}, approval ${playerItems.approvalOn() ? "on" : "off"}, pictures ${playerItems.pictureWaits() ? "wait" : "at once"}`);
return;
}
modpanel.reviewRoutes(route.replace(" /admin/api/", " "), body, reply, done, "admin", "/admin/api/itemart");
return;
}
// custom items (lib/customitems.js): the moderator panel's pages, the
// admin written down as "admin", and free to take from anyone.
if (url.pathname.startsWith("/admin/api/items")) {
const done = (result, action, target = "", detail = "") => {
if (result.ok) {
modlog.record("admin", action, target, result.detail || detail);
}
reply(result.ok ? 200 : 400, result.ok ? {ok: result.ok} : {error: result.error});
};
modpanel.itemRoutes(route.replace(" /admin/api/", " "), url, body, reply, done, {username: "admin", artBase: "/admin/api/itemart", mayTake: () => true});
return;
}
switch (route) { switch (route) {
case "GET /admin/api/overview": case "GET /admin/api/overview":
reply(200, overview()); reply(200, overview());
return; return;
case "GET /admin/api/discord":
reply(200, discordBot.dashboardStatus());
return;
case "POST /admin/api/discord/status": {
const statusCard = discordBot.setStatusSettings({title: body.title, note: body.note, banner: body.banner});
if (statusCard.error) {
reply(400, {error: statusCard.error});
return;
}
modlog.record("admin", "Discord public status card changed", "", `title: ${statusCard.title}, banner: ${statusCard.banner || "none"}`);
reply(200, {ok: "Status-card text saved. Use Publish now to update Discord.", statusCard});
return;
}
case "POST /admin/api/discord/status/publish": {
const result = await discordBot.publishStatus();
if (result.ok) {
modlog.record("admin", "Discord public status card published");
}
reply(result.ok ? 200 : 400, result);
return;
}
case "POST /admin/api/discord/config": {
const result = discordBot.updateDashboardConfig(body);
if (result.ok) {
modlog.record("admin", "Discord bot routing settings changed");
}
reply(result.ok ? 200 : 400, result);
return;
}
case "POST /admin/api/discord/security": {
const result = discordBot.updateSecuritySettings(body);
if (result.ok) {
modlog.record("admin", "Discord security settings changed");
}
reply(result.ok ? 200 : 400, result);
return;
}
case "POST /admin/api/discord/community": {
const result = discordBot.updateCommunitySettings(body);
if (result.ok) modlog.record("admin", "Discord community and ticket settings changed");
reply(result.ok ? 200 : 400, result);
return;
}
case "POST /admin/api/discord/control": {
const action = String(body.action || "");
const result = await discordBot.control(action);
if (result.ok) {
modlog.record("admin", `Discord bot ${action}`);
}
reply(result.ok ? 200 : 400, result);
return;
}
// a page of accounts by name (lib/staff.js says in what order), never
// all of them: with thousands, sending every one every few seconds
// slowed the page and the game alike.
case "GET /admin/api/accounts": { case "GET /admin/api/accounts": {
const playing = new Map(world.players().map(player => [player.username, player.room || "(between rooms)"])); const playing = new Map(world.players().map(player => [player.username, player.room || "(between rooms)"]));
reply(200, {accounts: accounts.all().map(account => accountRow(account, playing)), badges: badges.BADGES}); const filter = url.searchParams.get("filter");
const keep = filter === "online" ? (account, online) => online.has(account.username)
: filter === "banned" ? account => world.moderation.banRemaining(account) !== 0 : () => true;
const {found, total} = staff.findAccounts(url.searchParams.get("q"), keep, MAX_LISTED);
reply(200, {accounts: found.map(account => accountRow(account, playing)), total, badges: badges.BADGES});
return;
}
// one account's row, for the one that is open whatever the list shows.
case "GET /admin/api/account": {
const account = accounts.byName(url.searchParams.get("username") || "");
const playing = new Map(world.players().map(player => [player.username, player.room || "(between rooms)"]));
reply(account ? 200 : 404, account ? {account: accountRow(account, playing), badges: badges.BADGES} : {error: "No such account."});
return;
}
// the graphs (lib/stats.js): the last `days` days, by the viewer's clock.
case "GET /admin/api/stats":
reply(200, stats.report(Number(url.searchParams.get("days")), Number(url.searchParams.get("offset"))));
return;
// who signed in from an address, or from addresses starting so.
case "GET /admin/api/address-search": {
const found = staff.byAddress(url.searchParams.get("q"));
reply(found.error ? 400 : 200, found);
return;
}
// who signed in from a computer, by one of its ids or the start of one.
case "GET /admin/api/device-search": {
const found = staff.byDevice(url.searchParams.get("q"));
reply(found.error ? 400 : 200, found.error ? found : {players: found.players.map(entry => ({...entry,
online: Boolean(world.findOnline(entry.username))}))});
return;
}
// what players typed, sent and posted (lib/chatlog.js), as the moderators see it.
case "GET /admin/api/chat": {
const params = url.searchParams;
const lines = chatlog.search({username: (params.get("username") || "").trim().slice(0, 100), room: (params.get("room") || "").trim().slice(0, 100),
text: (params.get("text") || "").trim().slice(0, 100), kind: params.get("kind") || "", direction: params.get("direction") || "", until: Number(params.get("until")) || 0,
before: Number(params.get("before")) || 0});
reply(200, {lines, more: lines.length === chatlog.PAGE, days: config.chatLogDays});
return;
}
case "GET /admin/api/chat/around": {
const found = chatlog.around(url.searchParams.get("id"));
reply(found ? 200 : 404, found || {error: "No such line."});
return; return;
} }
@@ -660,7 +1015,11 @@ const handle = async (req, res, url, from, web) => {
} }
const result = act(account, body); const result = act(account, body);
if (result.ok) { if (result.ok) {
console.log(`[admin] ${body.action} on "${account.username}"`); console.log(`[admin] ${logText(body.action)} on "${logText(account.username)}"`);
// in the record beside the moderators', for the player's timeline.
if (!["password", "lastSeen", "level"].includes(body.action)) {
modlog.record(BY, body.action, account.username, result.detail || "");
}
} }
reply(result.ok ? 200 : 400, result); reply(result.ok ? 200 : 400, result);
return; return;
@@ -673,10 +1032,63 @@ const handle = async (req, res, url, from, web) => {
} }
case "GET /admin/api/bans": case "GET /admin/api/bans":
reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans()}); reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans(), devices: devices.list(), alerts: devices.alerts()});
return;
// A device ban lifted (lib/devices.js).
case "POST /admin/api/device": {
const result = staff.unbanDevices(body.id, BY);
if (result.ok) {
console.log(`[admin] device ban ${logText(Number(body.id))} lifted`);
modlog.record(BY, "hardware ban lifted", result.username || "");
}
reply(result.ok ? 200 : 400, result);
return;
}
// other accounts the same person may have, their story, and who the
// chat filter stopped most this week (lib/staff.js, lib/chatlog.js).
case "GET /admin/api/alts": {
const account = accounts.byName(url.searchParams.get("username") || "");
reply(account ? 200 : 404, account ? {alts: staff.altsOf(account), ids: devices.idsFor(account)} : {error: "No such account."});
return;
}
case "GET /admin/api/timeline": {
const account = accounts.byName(url.searchParams.get("username") || "");
reply(account ? 200 : 404, account ? {events: staff.timelineOf(account)} : {error: "No such account."});
return;
}
case "GET /admin/api/filterhits":
reply(200, {players: chatlog.mostStopped(7, 50)});
return;
// what waits, for the tabs and the page's title, on every page.
case "GET /admin/api/counts":
reply(200, {reports: reports.openCount(), support: support.openCount() + bans.openAppeals(), masterpieces: masterpieces.list(masterpieces.PENDING).length});
return; return;
// who may use the moderator panel, and what each did there. // who may use the moderator panel, and what each did there.
// the staff roles and what each may do.
case "GET /admin/api/roles":
reply(200, {roles: Object.entries(roles.ROLES).map(([id, role]) => ({id, label: role.label, rank: role.rank, permissions: roles.rolePermissions(id),
defaults: role.permissions, changed: roles.roleChanged(id)})), permissions: roles.PERMISSIONS});
return;
// a role's permissions changed ({role, permissions: [...]}), or back to
// its defaults ({role, reset: true}). its staff who are playing are told.
case "POST /admin/api/roles": {
const role = String(body.role || "");
if (!roles.setRolePermissions(role, body.reset === true ? null : Array.isArray(body.permissions) ? body.permissions : [])) {
reply(400, {error: "No such role."});
return;
}
for (const player of accounts.all().filter(account => roles.roleOf(account) === role)) {
world.refreshStaff(player);
}
console.log(`[admin] permissions of the ${logText(role)} role ${logText(body.reset === true ? "reset" : "changed")}`);
modlog.record("admin", body.reset === true ? "role permissions reset" : "role permissions changed", "", `${role}: ${roles.rolePermissions(role).join(", ")}`);
reply(200, {ok: `${roles.ROLES[role].label}: ${body.reset === true ? "back to its defaults" : "saved"}.`});
return;
}
case "GET /admin/api/moderators": case "GET /admin/api/moderators":
reply(200, {moderators: modpanel.moderators(), log: modlog.recent()}); reply(200, {moderators: modpanel.moderators(), log: modlog.recent()});
return; return;
@@ -690,7 +1102,7 @@ const handle = async (req, res, url, from, web) => {
case "POST /admin/api/address": { case "POST /admin/api/address": {
const result = addressAct(body); const result = addressAct(body);
if (result.ok) { if (result.ok) {
console.log(`[admin] address ${body.action}: ${limits.key(body.address)}`); console.log(`[admin] address ${logText(body.action)}: ${logText(limits.key(body.address))}`);
} }
reply(result.ok ? 200 : 400, result); reply(result.ok ? 200 : 400, result);
return; return;
@@ -707,7 +1119,24 @@ const handle = async (req, res, url, from, web) => {
case "POST /admin/api/debug": { case "POST /admin/api/debug": {
const result = debugAct(body); const result = debugAct(body);
if (result.ok) { if (result.ok) {
console.log(`[admin] debug: ${body.action} ${body.action === "teleport" ? `${body.username} -> ${body.room}` : body.on === true}`); console.log(`[admin] debug: ${logText(body.action)} ${logText(body.action === "teleport" ? `${body.username} -> ${body.room}` : body.on === true)}`);
}
reply(result.ok ? 200 : 400, result);
return;
}
// codes for the game's Redeem Code window (lib/codes.js), each giving
// an item, gems or diamonds
case "GET /admin/api/codes":
reply(200, {codes: codes.list(), kinds: codes.KINDS});
return;
case "POST /admin/api/codes": {
const result = body.action === "remove"
? (codes.remove(body.code) ? {ok: "Code deleted."} : {error: "No such code."})
: codes.create(body);
if (result.ok) {
console.log(`[admin] redemption code ${logText(body.action === "remove" ? "deleted" : "made")}: ${logText(String(body.code || "").toUpperCase())}`);
} }
reply(result.ok ? 200 : 400, result); reply(result.ok ? 200 : 400, result);
return; return;
@@ -728,7 +1157,7 @@ const handle = async (req, res, url, from, web) => {
return; return;
} }
const reached = world.announce(text, body.room ? String(body.room) : null); const reached = world.announce(text, body.room ? String(body.room) : null);
console.log(`[admin] announcement to ${body.room ? `room ${body.room}` : "everyone"} (${reached} players)`); console.log(`[admin] announcement to ${logText(body.room ? `room ${body.room}` : "everyone")} (${logText(reached)} players)`);
reply(200, {ok: reached === 1 ? "Shown to 1 player." : `Shown to ${reached} players.`}); reply(200, {ok: reached === 1 ? "Shown to 1 player." : `Shown to ${reached} players.`});
return; return;
} }
@@ -738,8 +1167,8 @@ const handle = async (req, res, url, from, web) => {
case "GET /admin/api/masterpieces": case "GET /admin/api/masterpieces":
reply(200, { reply(200, {
review: masterpieces.needsReview(), review: masterpieces.needsReview(),
waiting: masterpieces.list(masterpieces.PENDING), ...masterpieces.listsFor(url.searchParams.get("creator")),
approved: masterpieces.list(masterpieces.APPROVED), waitingCount: masterpieces.list(masterpieces.PENDING).length,
}); });
return; return;
@@ -763,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)
@@ -773,7 +1202,7 @@ const handle = async (req, res, url, from, web) => {
result = {error: "Unknown action."}; result = {error: "Unknown action."};
} }
if (result.ok) { if (result.ok) {
console.log(`[admin] masterpiece ${body.action} ${id || body.on === true}`); console.log(`[admin] masterpiece ${logText(body.action)} ${logText(id || body.on === true)}`);
} }
reply(result.ok ? 200 : 400, result); reply(result.ok ? 200 : 400, result);
return; return;
@@ -815,7 +1244,7 @@ const handle = async (req, res, url, from, web) => {
result = {error: "Unknown action."}; result = {error: "Unknown action."};
} }
if (result.ok) { if (result.ok) {
console.log(`[admin] support: ${body.action} ${Number(body.id)}`); console.log(`[admin] support: ${logText(body.action)} ${logText(Number(body.id))}`);
} }
reply(result.ok ? 200 : 400, result); reply(result.ok ? 200 : 400, result);
return; return;
@@ -843,4 +1272,4 @@ const handle = async (req, res, url, from, web) => {
} }
}; };
module.exports = {load, handle, PASSWORD_SETTING}; module.exports = {load, handle, signedIn, theatreBrowserOn, PASSWORD_SETTING};
+6 -3
View File
@@ -1,5 +1,6 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const config = require("../config.js"); const config = require("../config.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
@@ -116,7 +117,9 @@ module.exports = ({enterRoom, findOnline, blocks}) => {
// PartyManager.customPartyJoinResponse: [success, reason] // PartyManager.customPartyJoinResponse: [success, reason]
const joinHosted = (session, host) => { const joinHosted = (session, host) => {
const party = host && partyOf(host); const party = host && partyOf(host);
if (!party || blocks.either(host, session.account)) { // A one-use staff teleport may inspect a hosted party despite a block;
// ordinary party joins retain the host's privacy rule.
if (!party || (!session.staffTravel && blocks.either(host, session.account))) {
session.sendXt("sjp", -1, 0, party ? "BLK" : "NPP"); session.sendXt("sjp", -1, 0, party ? "BLK" : "NPP");
return; return;
} }
@@ -187,10 +190,10 @@ module.exports = ({enterRoom, findOnline, blocks}) => {
return; return;
} }
account.currency.diamonds -= HOST_COST; account.currency.diamonds -= HOST_COST;
accounts.save(); accounts.save(account);
const party = {host: account, defId: def.id, name: `${name1}|${name2}|${name3}`, music: Number(music), endsAt: now() + config.partyMinutes * 60}; const party = {host: account, defId: def.id, name: `${name1}|${name2}|${name3}`, music: Number(music), endsAt: now() + config.partyMinutes * 60};
hosted.set(account.username.toLowerCase(), party); hosted.set(account.username.toLowerCase(), party);
console.log(`[world] ${account.username} is hosting a party (def ${def.id})`); console.log(`[world] ${logText(account.username)} is hosting a party (def ${logText(def.id)})`);
session.sendXt("cu", -1, CURRENCY_DIAMONDS, account.currency.diamonds, 0); session.sendXt("cu", -1, CURRENCY_DIAMONDS, account.currency.diamonds, 0);
session.sendXt("scp", -1, 1, 1, party.endsAt - now()); session.sendXt("scp", -1, 1, 1, party.endsAt - now());
joinHosted(session, account); joinHosted(session, account);
+45 -9
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));
@@ -100,12 +107,30 @@ module.exports = ({others, findOnline, petFields}) => {
giveCharacter(pet); giveCharacter(pet);
account.pets.push(pet); account.pets.push(pet);
achievements.set(account, achievements.VARS.pets, Math.max(Number(account.userVars[achievements.VARS.pets]) || 0, account.pets.length)); achievements.set(account, achievements.VARS.pets, Math.max(Number(account.userVars[achievements.VARS.pets]) || 0, account.pets.length));
accounts.save(); accounts.save(account);
session.sendXt("pc", -1, 1, account.currency.gems || 0, 0, pet.inv, ...petFields(pet), 0); session.sendXt("pc", -1, 1, account.currency.gems || 0, 0, pet.inv, ...petFields(pet), 0);
}; };
const ownPet = (account, invIdx) => account.pets.find(candidate => candidate.inv === Number(invIdx)); const 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,8 +171,9 @@ 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(); accounts.save(account);
const messageRoom = session.room ? session.room.id : -1; const messageRoom = session.room ? session.room.id : -1;
session.sendXt("ps", messageRoom, 1, session.id, pet ? pet.inv : 0); session.sendXt("ps", messageRoom, 1, session.id, pet ? pet.inv : 0);
if (session.pos) { if (session.pos) {
@@ -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,13 +196,17 @@ 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;
} }
} }
accounts.save(); accounts.save(account);
session.sendXt("pd", -1, 1, pet.inv); session.sendXt("pd", -1, 1, pet.inv);
}, },
@@ -187,7 +222,7 @@ module.exports = ({others, findOnline, petFields}) => {
return; return;
} }
pet.uBits = ((pet.uBits & ~MASTERY_BITS) | (item << 8)) >>> 0; pet.uBits = ((pet.uBits & ~MASTERY_BITS) | (item << 8)) >>> 0;
accounts.save(); accounts.save(account);
session.sendXt("pm", -1, 1, pet.inv, pet.lBits, pet.uBits, pet.eBits); session.sendXt("pm", -1, 1, pet.inv, pet.lBits, pet.uBits, pet.eBits);
if (pet.inv === activeAvatar(account).petInvId && session.pos) { if (pet.inv === activeAvatar(account).petInvId && session.pos) {
for (const other of others(session)) { for (const other of others(session)) {
@@ -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)) {
@@ -207,7 +243,7 @@ module.exports = ({others, findOnline, petFields}) => {
return; return;
} }
pet.name = `${name1}|${name2}`; pet.name = `${name1}|${name2}`;
accounts.save(); accounts.save(account);
session.sendXt("pn", -1, 1, pet.inv, pet.name); session.sendXt("pn", -1, 1, pet.inv, pet.name);
}, },
@@ -224,7 +260,7 @@ module.exports = ({others, findOnline, petFields}) => {
return; return;
} }
pet.uBits = ((pet.uBits & 0xFFF) | (parts[0] << 12) | (parts[1] << 16) | (parts[2] << 20)) >>> 0; pet.uBits = ((pet.uBits & 0xFFF) | (parts[0] << 12) | (parts[1] << 16) | (parts[2] << 20)) >>> 0;
accounts.save(); accounts.save(account);
session.sendXt("pi", -1, 1, account.currency.gems || 0, pet.inv, pet.lBits, pet.uBits, pet.eBits); session.sendXt("pi", -1, 1, account.currency.gems || 0, pet.inv, pet.lBits, pet.uBits, pet.eBits);
if (session.pos) { if (session.pos) {
for (const other of others(session)) { for (const other of others(session)) {
@@ -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);
+303
View File
@@ -0,0 +1,303 @@
"use strict";
const accounts = require("./accounts.js");
const config = require("../config.js");
const customItems = require("./customitems.js");
const dens = require("./dens.js");
const itemControl = require("./itemcontrol.js");
const modlog = require("./modlog.js");
const names = require("./names.js");
const {addClothing, sendClothingAdded} = require("./player.js");
// items players make for themselves (the patched client's Item Maker, in the
// settings menu): one of the game's clothing pieces or den items under a
// name of their own, as staff make them (lib/customitems.js), but free, never
// in a shop, and in the item finder for its maker only. the maker is given
// one at once; it can be worn, placed and traded like any other. a maker
// may delete their own; staff may delete anyone's (the moderator panel).
//
// "xcm" from the client: ["info"], ["make", kind, baseId, name],
// ["rename", kind, id, name], ["look", kind, id, "sticker" | "texture"]
// (how one with a picture is worn) or ["delete", kind, id]. its picture is
// uploaded over HTTP (lib/itemart.js, POST /api/itemart). the answer is always "xcm" [ok 1 | 0, what to say,
// left today, left in all, the maker's items as JSON]
// the admin's two switches (the admin panel's Items page): whether players
// may make items at all, and whether what they make (an item, or a new
// picture for one) waits for a moderator first (items.approve: the
// moderator panel's Review page), out of the game till then.
const ENABLED_SETTING = "playerItems";
const APPROVAL_SETTING = "playerItemApproval";
const enabled = () => accounts.setting(ENABLED_SETTING) !== "off";
const approvalOn = () => accounts.setting(APPROVAL_SETTING) === "on";
// pictures are seen by everyone who meets the item, so a player's waits for
// a moderator even when items do not: unless the admin turns this off too.
const ART_APPROVAL_SETTING = "playerArtApproval";
const artApprovalOn = () => accounts.setting(ART_APPROVAL_SETTING) !== "off";
const pictureWaits = () => approvalOn() || artApprovalOn();
const setSwitches = ({enabled: on, approval, artApproval}) => {
if (on !== undefined) {
accounts.setSetting(ENABLED_SETTING, on ? "on" : "off");
}
if (approval !== undefined) {
accounts.setSetting(APPROVAL_SETTING, approval ? "on" : "off");
}
if (artApproval !== undefined) {
accounts.setSetting(ART_APPROVAL_SETTING, artApproval ? "on" : "off");
}
};
// ---- what keeps pictures players upload decent
//
// - a picture turned away (or taken off by a moderator) is remembered by
// its SHA-256, and the same picture cannot be sent again;
// - each counts against its maker: at ART_STRIKES their uploads stop,
// till a moderator lets them again (account.artBlocked);
// - an account younger than config.itemArtMinAccountHours may not upload.
const ART_STRIKES = 3;
const REFUSED_SETTING = "refusedArt";
const MAX_REFUSED = 5000;
let refused = null; // Set of SHA-256 hex
const refusedSet = () => {
if (!refused) {
let saved = [];
try {
saved = JSON.parse(accounts.setting(REFUSED_SETTING) || "[]");
}
catch {
saved = [];
}
refused = new Set(Array.isArray(saved) ? saved.map(String) : []);
}
return refused;
};
const pictureRefused = hash => refusedSet().has(hash);
// {error} when `account` may not upload a picture now, else null. `local`:
// the request is from this machine (no wait for a new account).
const uploadRefusal = (account, local = false) => {
if (account.artBlocked) {
return {error: "A moderator has turned off picture uploads for your account."};
}
const hours = config.itemArtMinAccountHours;
if (!local && hours > 0 && Math.floor(Date.now() / 1000) - (account.createdAt || 0) < hours * 3600) {
return {error: `New accounts can add pictures after ${hours} hours. Try again later.`};
}
return null;
};
// stops or lets again one player's uploads; letting them again clears the
// pictures counted against them.
const setUploadsBlocked = (account, blocked) => {
account.artBlocked = Boolean(blocked);
if (!blocked) {
account.artRefusals = 0;
}
accounts.save(account);
return {ok: blocked ? `${account.username} can no longer upload pictures.` : `${account.username} can upload pictures again.`};
};
// a picture turned away or taken off: never again, and counted against its
// maker (not against staff, whose items have no maker). before it is removed.
// returns what to add to what the moderator is told.
const strike = entry => {
const hash = require("./itemart.js").digestOf(entry.kind, entry.id);
if (hash) {
const set = refusedSet();
set.add(hash);
const kept = [...set].slice(-MAX_REFUSED);
refused = new Set(kept);
accounts.setSetting(REFUSED_SETTING, JSON.stringify(kept));
}
const maker = entry.ownerId === null ? null : accounts.byId(entry.ownerId);
if (!maker) {
return "";
}
maker.artRefusals = (maker.artRefusals || 0) + 1;
if (maker.artRefusals >= ART_STRIKES && !maker.artBlocked) {
maker.artBlocked = true;
accounts.save(maker);
modlog.record("system", "picture uploads stopped", maker.username, `${maker.artRefusals} pictures turned away`);
return ` That is ${maker.artRefusals} for ${maker.username}: their picture uploads are stopped.`;
}
accounts.save(maker);
return ` ${maker.username} has had ${maker.artRefusals} of ${ART_STRIKES} pictures turned away.`;
};
// a moderator takes an item's picture off, shown or waiting (after a report).
const takePicture = (kind, id) => {
const entry = customItems.get(kind, id);
if (!entry || !entry.art) {
return {error: "That item has no picture of its own."};
}
const said = strike(entry);
const result = require("./itemart.js").remove(kind, entry.id);
return result.error ? result : {ok: `${result.ok}${said}`};
};
const PER_DAY = 5;
const IN_ALL = 20;
const DAY = 86400;
const RENAMES_PER_HOUR = 10;
const now = () => Math.floor(Date.now() / 1000);
const renames = require("./limits.js").limiter(RENAMES_PER_HOUR, 3600000); // per account: each is sent to every game
const madeBy = account => customItems.list().filter(entry => entry.ownerId === account.id);
const left = account => {
const mine = madeBy(account);
const today = mine.filter(entry => entry.createdAt > now() - DAY).length;
return {today: Math.max(0, Math.min(PER_DAY - today, IN_ALL - mine.length)), inAll: Math.max(0, IN_ALL - mine.length)};
};
// returns {ok} or {error}.
const make = (session, kind, baseId, name) => {
const {account} = session;
if (!enabled()) {
return {error: "The Item Maker is turned off on this server for now."};
}
if (!customItems.KINDS.includes(kind) || !/^\d+$/.test(String(baseId))) {
return {error: "Choose an item to make yours from."};
}
if (!customItems.copyable(kind, Number(baseId))) {
return {error: "That item cannot be made into one of your own. Choose another."};
}
const room = left(account);
if (room.inAll === 0) {
return {error: `You have made ${IN_ALL} items, as many as there can be. Delete one to make another.`};
}
if (room.today === 0) {
return {error: `You have made ${PER_DAY} items today. Try again tomorrow.`};
}
const clean = String(name || "").trim().replace(/\s+/g, " ");
if (clean && names.refused(clean)) {
return {error: "That name is not allowed."};
}
const waits = approvalOn();
const result = customItems.create(kind, {base: Number(baseId), name: clean, cost: 0, members: false, inShop: false}, account.username, account.id, waits);
if (result.error) {
return result;
}
const {item} = result;
if (waits) {
modlog.record(account.username, "item made by a player, waiting for approval", "", `${kind} ${item.id} ${item.name}`);
return {ok: `${item.name} is waiting for a moderator to approve it. It is yours as soon as they do.`};
}
giveTo(account, item, session);
modlog.record(account.username, "item made by a player", "", `${kind} ${item.id} ${item.name}`);
return {ok: `Made ${item.name}. It is in your ${kind === "den" ? "den items" : "clothing"} now.`};
};
// one of the item, to its maker: now in their game if `session` is it
const giveTo = (account, item, session) => {
if (item.kind === "den") {
if (dens.giveDenItem(account, item.id) && session) {
dens.sendDenItems(session);
}
}
else {
const given = addClothing(account, item.id, item.colors[0]);
accounts.save(account);
if (session) {
sendClothingAdded(session, given);
}
}
};
// a moderator's answer about what waits (lib/modpanel.js, lib/panel.js): an
// item let in is given to its maker; one turned away is deleted, or only
// its picture taken away. `world` finds whether its maker is playing, and
// tells games about items taken. returns {ok} or {error}.
const review = (kind, id, approve, by, world) => {
const entry = customItems.get(kind, id);
if (!entry || (!entry.pending && !entry.artPending)) {
return {error: "That is not waiting for approval."};
}
const maker = entry.ownerId === null ? null : accounts.byId(entry.ownerId);
const wasNew = entry.pending;
if (approve) {
customItems.approve(kind, entry.id);
if (wasNew && maker) {
giveTo(maker, entry, world.findOnline(maker.username));
}
return {ok: wasNew ? `${entry.name} is in the game, and ${maker ? maker.username : "its maker"} has one.` : `${entry.name}'s picture is shown now.`};
}
if (wasNew) {
itemControl.deleteCustom(kind, entry.id, world);
return {ok: `${entry.name} was turned away and deleted.`};
}
const said = strike(entry);
require("./itemart.js").remove(kind, entry.id);
return {ok: `${entry.name}'s new picture was turned away.${said}`};
};
// a new name for one of their own (every game is told: customItems.update).
const rename = (account, kind, id, name) => {
const entry = customItems.get(kind, id);
if (!entry || entry.ownerId !== account.id) {
return {error: "That is not one of your items."};
}
if (!renames.allow(account.id)) {
return {error: "Too many renames. Try again in an hour."};
}
const clean = String(name || "").trim().replace(/\s+/g, " ");
if (clean && names.refused(clean)) {
return {error: "That name is not allowed."};
}
const result = customItems.update(kind, entry.id, {name: clean});
return result.error ? result : {ok: `Renamed it ${result.item.name}.`};
};
// how one of their own is worn ("sticker" or "texture")
const setLook = (account, kind, id, mode) => {
const entry = customItems.get(kind, id);
if (!entry || entry.ownerId !== account.id) {
return {error: "That is not one of your items."};
}
const result = customItems.setArtMode(kind, entry.id, String(mode));
return result.error ? result : {ok: `${entry.name} is worn as ${mode === "texture" ? "its shape, with your picture in it" : "your picture"}.`};
};
const remove = (session, kind, id, world) => {
const entry = customItems.get(kind, id);
if (!entry || entry.ownerId !== session.account.id) {
return {error: "That is not one of your items."};
}
const result = itemControl.deleteCustom(kind, entry.id, world);
return result.error ? result : {ok: `Deleted ${entry.name}.`};
};
const reply = (session, result) => {
const room = left(session.account);
const mine = madeBy(session.account).map(entry => ({kind: entry.kind, id: entry.id, name: entry.name, base: entry.base, art: entry.artPending ? "" : entry.art || "",
artMode: entry.artMode || "sticker", waiting: entry.pending ? "item" : entry.artPending ? "picture" : ""}));
session.sendXt("xcm", -1, result.error ? 0 : 1, String(result.error || result.ok || "").replace(/%/g, " percent"), room.today, room.inAll,
JSON.stringify(mine).replace(/%/g, "\\u0025"));
};
// `world` tells games about items taken (lib/world.js itemsTaken).
const handlers = world => ({
xcm(session, roomId, [action, kind, id, ...words]) {
if (action === "make") {
reply(session, make(session, kind, id, words.join(" ")));
}
else if (action === "look") {
reply(session, setLook(session.account, kind, id, words[0]));
}
else if (action === "rename") {
reply(session, rename(session.account, kind, id, words.join(" ")));
}
else if (action === "delete") {
reply(session, remove(session, kind, id, world));
}
else {
reply(session, enabled() ? {ok: ""} : {error: "The Item Maker is turned off on this server for now."});
}
},
});
module.exports = {handlers, madeBy, rename, setLook, review, enabled, approvalOn, artApprovalOn, pictureWaits, setSwitches,
pictureRefused, uploadRefusal, setUploadsBlocked, takePicture, ART_STRIKES, PER_DAY, IN_ALL};
+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};
+25 -3
View File
@@ -1,5 +1,6 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
@@ -44,6 +45,7 @@ const MERGE_SECONDS = 10;
const perTenMinutes = limits.limiter(10, 600000); const perTenMinutes = limits.limiter(10, 600000);
const now = () => Math.floor(Date.now() / 1000); const now = () => Math.floor(Date.now() / 1000);
const clean = (text, max) => String(text === undefined ? "" : text).replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, " ").trim().slice(0, max); const clean = (text, max) => String(text === undefined ? "" : text).replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, " ").trim().slice(0, max);
const listeners = new Set();
const load = () => accounts.database().exec(SCHEMA); const load = () => accounts.database().exec(SCHEMA);
@@ -67,9 +69,18 @@ const file = ({reporter, target, reason, detail = "", context = "", room = ""})
if (!perTenMinutes.allow(reporter.toLowerCase()) || openCount() >= MAX_OPEN) { if (!perTenMinutes.allow(reporter.toLowerCase()) || openCount() >= MAX_OPEN) {
return false; return false;
} }
db.prepare("INSERT INTO reports (created_at, reporter, target, reason, detail, context, room) VALUES (?, ?, ?, ?, ?, ?, ?)") const inserted = db.prepare("INSERT INTO reports (created_at, reporter, target, reason, detail, context, room) VALUES (?, ?, ?, ?, ?, ?, ?)")
.run(now(), reporter, target, Number.isInteger(reason) ? reason : 0, clean(detail, MAX_DETAIL), clean(context, MAX_CONTEXT), clean(room, 100)); .run(now(), reporter, target, Number.isInteger(reason) ? reason : 0, clean(detail, MAX_DETAIL), clean(context, MAX_CONTEXT), clean(room, 100));
console.log(`[world] ${reporter} reported "${target}" (${REASONS[reason] || `reason ${reason}`})`); console.log(`[world] ${logText(reporter)} reported "${logText(target)}" (${logText(REASONS[reason] || `reason ${reason}`)})`);
const report = row(db.prepare("SELECT * FROM reports WHERE id = ?").get(Number(inserted.lastInsertRowid)));
for (const listener of listeners) {
try {
listener(report);
}
catch (err) {
console.error(`[reports] listener failed: ${logText(err.message)}`);
}
}
return true; return true;
}; };
@@ -94,4 +105,15 @@ const list = (handled = false) => accounts.database()
const markHandled = id => accounts.database().prepare("UPDATE reports SET handled_at = ? WHERE id = ? AND handled_at IS NULL").run(now(), id).changes > 0; const markHandled = id => accounts.database().prepare("UPDATE reports SET handled_at = ? WHERE id = ? AND handled_at IS NULL").run(now(), id).changes > 0;
module.exports = {load, file, list, markHandled, openCount, MAX_DETAIL}; // Lets optional integrations (the Discord bot) receive a newly filed report
// without making a report depend on an external service being available.
const onFile = listener => {
listeners.add(listener);
return () => listeners.delete(listener);
};
// the reports about one player, newest first, for their timeline.
const about = username => accounts.database().prepare("SELECT * FROM reports WHERE target = ? COLLATE NOCASE ORDER BY id DESC LIMIT 100")
.all(String(username)).map(row);
module.exports = {load, file, list, about, markHandled, onFile, openCount, MAX_DETAIL};
+205
View File
@@ -0,0 +1,205 @@
"use strict";
const accounts = require("./accounts.js");
const totp = require("./totp.js");
// staff roles, and what each may do. an account holds at most one role
// (`role` on the account), set by the admin. an account from before roles
// that is only marked `moderator` counts as a moderator, so nothing that
// worked before stops working.
//
// a role is a list of permissions, and every staff action checks the one it
// needs, in the moderator panel (lib/modpanel.js) and in the game
// (lib/commands.js) alike. a higher role holds everything a lower one does.
// staff never act on staff of their own rank or above: that is for someone
// higher up, and for the admin in the end.
const PERMISSIONS = {
"server.view": "see read-only server health in the moderator panel",
"server.announce": "send an announcement to everyone playing",
"player.view": "see players, chat, reports, requests, bans and paintings in the moderator panel, and keep notes on players (!note, !notes)",
"staff.list": "see which staff are online (!staff)",
"player.warn": "warn a player, take a warning back, send them a message and mark a report dealt with (!warn, !unwarn, !warnings, !message)",
"player.goto": "go to the room a player is in (!goto)",
"chat.silence": "silence and unsilence a player (!silence)",
"player.kick": "disconnect a player (!kick)",
"player.summon": "bring a player to the room you are in (!summon)",
"staff.invisible": "go unseen in rooms, as the game's moderators could (!invisible)",
"player.ban": "ban, unban, change a ban's reason and answer ban appeals",
"player.names": "reject or accept a name, answer requests for a new one, clear a bio, remove a player's Jammer Wall posts",
"address.ban": "ban the address a player last signed in from, or the computers they use, and lift those bans",
"items.approve": "approve or turn away the items and pictures players make, when the admin has asked for that",
"masterpieces.approve": "approve or remove the paintings players frame as masterpieces (the Masterpieces page)",
"items.restrict": "stop a clothing item from being worn by selected animal types",
"items.create": "make new items from the game's art, change and delete them, lock items out of the item finder and take items from players (!item, !lock, !unlock, !locked, !take)",
"room.effects": "run temporary room-wide size and colour effects (!roomfx)",
"theater.control": "play or stop a YouTube video for everyone in the theatre",
"music.upload": "upload MP3s as den music tracks, and delete those uploaded (the Music page)",
"staff.log": "read the mod log: what staff did, in the panels and the game (the Mod log page)",
};
const HELPER = ["server.view", "player.view", "staff.list", "player.warn", "player.goto", "chat.silence"];
const MODERATOR = [...HELPER, "player.kick", "player.summon", "staff.invisible", "player.ban", "player.names", "address.ban", "items.approve", "masterpieces.approve", "items.restrict", "theater.control", "staff.log"];
const ADMIN = [...MODERATOR, "server.announce", "items.create", "room.effects", "music.upload"];
// a developer makes things, and moderates nobody.
const DEVELOPER = ["server.view", "staff.list", "items.create", "room.effects", "theater.control"];
const ROLES = {
developer: {rank: 1, label: "Developer", permissions: DEVELOPER},
helper: {rank: 1, label: "Helper", permissions: HELPER},
moderator: {rank: 2, label: "Moderator", permissions: MODERATOR},
admin: {rank: 3, label: "Admin", permissions: ADMIN},
};
// the role an account holds, or null.
const roleOf = account => {
if (!account) {
return null;
}
if (Object.hasOwn(ROLES, account.role)) {
return account.role;
}
return account.moderator ? "moderator" : null;
};
const rankOf = account => {
const role = roleOf(account);
return role ? ROLES[role].rank : 0;
};
// may this account act as staff at all right now? as for the moderator
// panel: a role, 2FA turned on, not locked and not banned. `banned` says
// whether the account is banned (passed in, so that this file needs nothing
// of the world's).
const isActiveStaff = (account, banned = false) =>
Boolean(roleOf(account) && totp.isOn(account) && !account.locked && !banned);
// what each role may do can be changed by the admin (the admin panel's
// Moderators page): kept as a setting, {role: [permission, ...]}, a role
// not in it holding its defaults above. one staff member can be given more
// than their role, or less (`permGrants`, `permDenies` on the account, from
// their page in the admin panel). a role and 2FA are still what makes
// someone staff at all (isActiveStaff).
const ROLE_SETTING = "rolePermissions";
let roleOverrides = null;
const overrides = () => {
if (!roleOverrides) {
try {
const saved = JSON.parse(accounts.setting(ROLE_SETTING) || "{}");
roleOverrides = saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
}
catch {
roleOverrides = {};
}
}
return roleOverrides;
};
// the permissions in a list that are ones, each once
const known = list => [...new Set(Array.isArray(list) ? list.map(String) : [])].filter(permission => Object.hasOwn(PERMISSIONS, permission));
const rolePermissions = role => (Object.hasOwn(overrides(), role) ? known(overrides()[role]) : [...ROLES[role].permissions]);
const roleChanged = role => Object.hasOwn(overrides(), role);
// a role's permissions, or its defaults again (`list` null). false for no such role.
const setRolePermissions = (role, list) => {
if (!Object.hasOwn(ROLES, role)) {
return false;
}
const changed = {...overrides()};
if (list === null) {
delete changed[role];
}
else {
changed[role] = known(list);
}
accounts.setSetting(ROLE_SETTING, JSON.stringify(changed));
roleOverrides = changed;
return true;
};
// masterpieces.approve was split from items.approve (2026-10-21), which
// judged paintings before. once: a role list the admin changed, and a staff
// member's own grants and denies, that held items.approve hold this too.
const SPLIT_SETTING = "permissionSplitMasterpieces";
const load = () => {
if (accounts.setting(SPLIT_SETTING)) {
return;
}
const withSplit = list => (Array.isArray(list) && list.includes("items.approve") && !list.includes("masterpieces.approve")
? [...list, "masterpieces.approve"] : list);
const changed = {...overrides()};
for (const role of Object.keys(changed)) {
changed[role] = withSplit(changed[role]);
}
accounts.setSetting(ROLE_SETTING, JSON.stringify(changed));
roleOverrides = changed;
for (const account of accounts.all()) {
if (account.permGrants || account.permDenies) {
const grants = withSplit(account.permGrants);
const denies = withSplit(account.permDenies);
if (grants !== account.permGrants || denies !== account.permDenies) {
if (grants) account.permGrants = grants;
if (denies) account.permDenies = denies;
accounts.save(account);
}
}
}
accounts.setSetting(SPLIT_SETTING, "1");
};
const permissionsOf = account => {
const role = roleOf(account);
if (!role) {
return [];
}
const denied = new Set(known(account.permDenies));
return [...new Set([...rolePermissions(role), ...known(account.permGrants)])].filter(permission => !denied.has(permission));
};
// one staff member's own: given beyond their role, and taken from it. a
// permission in both is given. the caller saves the account.
const setAccountPermissions = (account, grants, denies) => {
const given = known(grants);
const taken = known(denies).filter(permission => !given.includes(permission));
if (given.length) {
account.permGrants = given;
}
else {
delete account.permGrants;
}
if (taken.length) {
account.permDenies = taken;
}
else {
delete account.permDenies;
}
};
const can = (account, permission, banned = false) =>
isActiveStaff(account, banned) && permissionsOf(account).includes(permission);
// may `actor` act on `target`? never on themselves, nor on staff of their
// own rank or above.
const outranks = (actor, target) => actor !== target && rankOf(actor) > rankOf(target);
// sets the role (one of ROLES, or null for none). `moderator` is kept in
// step for anything that still reads it.
const setRole = (account, role) => {
if (role === null || role === "" || role === "none") {
delete account.role;
delete account.moderator;
return true;
}
if (!Object.hasOwn(ROLES, role)) {
return false;
}
account.role = role;
account.moderator = true;
return true;
};
module.exports = {load, PERMISSIONS, ROLES, roleOf, rankOf, isActiveStaff, permissionsOf, rolePermissions, roleChanged, setRolePermissions,
setAccountPermissions, can, outranks, setRole};
+9 -4
View File
@@ -1,5 +1,6 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const zlib = require("zlib"); const zlib = require("zlib");
const amf3 = require("./amf3.js"); const amf3 = require("./amf3.js");
const cdn = require("./cdn.js"); const cdn = require("./cdn.js");
@@ -13,8 +14,9 @@ const defpacks = require("./defpacks.js");
// then AMF3), so reading it here costs no extra download once anyone has // then AMF3), so reading it here costs no extra download once anyone has
// been in the room. // been in the room.
// what the room editor left in files nobody named. // what the room editor left in files nobody named ("default": the museum's
const UNNAMED = "Display Name"; // theatre).
const UNNAMED = ["display name", "default"];
// rooms whose file has no name and whose path does not spell it either. // rooms whose file has no name and whose path does not spell it either.
const NAMES = new Map([ const NAMES = new Map([
["jamaa_township.room_diamonds", "Diamond Shop"], ["jamaa_township.room_diamonds", "Diamond Shop"],
@@ -23,6 +25,9 @@ const NAMES = new Map([
["aussie.room_main", "Kimbara Outback"], ["aussie.room_main", "Kimbara Outback"],
["aussie.room_aushop", "Outback Imports"], ["aussie.room_aushop", "Outback Imports"],
["aussie.room_hos", "Medical Center"], ["aussie.room_hos", "Medical Center"],
["appondale.room_museumtheater", "Museum Theater"],
["crystal_sands.room_tiertheater", "Tierney's Theater"],
["lost_temple_of_zios.bb_theater", "Temple Theater"],
]); ]);
const VOLUME_SHOP = 12; // ActorVolume.type: clicking it opens generic list `typeDefId` const VOLUME_SHOP = 12; // ActorVolume.type: clicking it opens generic list `typeDefId`
@@ -36,7 +41,7 @@ const parse = body => {
const settings = (room.actors.ActorSettings || [])[0] || {}; const settings = (room.actors.ActorSettings || [])[0] || {};
const volumes = room.actors.ActorVolume || []; const volumes = room.actors.ActorVolume || [];
return { return {
name: typeof settings.name === "string" && settings.name.trim() !== UNNAMED ? settings.name.trim() : "", name: typeof settings.name === "string" && !UNNAMED.includes(settings.name.trim().toLowerCase()) ? settings.name.trim() : "",
shops: new Set(volumes.filter(volume => Number(volume.type) === VOLUME_SHOP).map(volume => Number(volume.typeDefId))), shops: new Set(volumes.filter(volume => Number(volume.type) === VOLUME_SHOP).map(volume => Number(volume.typeDefId))),
}; };
}; };
@@ -71,7 +76,7 @@ const preload = async () => {
remember(base, body); remember(base, body);
} }
} }
console.log(`[rooms] names of ${rooms.size} rooms read from the cache`); console.log(`[rooms] names of ${logText(rooms.size)} rooms read from the cache`);
}; };
// A name made from the path, for a room not read yet or left unnamed: // A name made from the path, for a room not read yet or left unnamed:
+59
View File
@@ -0,0 +1,59 @@
porn
boob
dick
penis
vagina
pussy
clit
cunt
dildo
vibrator
hentai
horny
slut
whore
milf
blowjob
handjob
orgasm
orgy
fetish
bdsm
nsfw
onlyfans
nude
naked
nipple
erotic
semen
sperm
jizz
titty
titties
tits
boner
sexy
ejaculat
masturbat
condom
genital
testicle
scrotum
=sex*
=cock
=cocks
=cum*
=anal
=anus
=ass
=asses
=butt
=butts
=xxx
=thot
=tit
=rape*
=rapist
=pedo*
=loli
=shota
+43 -14
View File
@@ -1,5 +1,6 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto"); const crypto = require("crypto");
const fs = require("fs"); const fs = require("fs");
const net = require("net"); const net = require("net");
@@ -17,7 +18,10 @@ const limits = require("./limits.js");
const POLICY = '<cross-domain-policy><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>'; const POLICY = '<cross-domain-policy><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>';
const MAX_MESSAGE = 64 * 1024; const MAX_MESSAGE = 64 * 1024;
const RATE_WINDOW_MS = 10000; const RATE_WINDOW_MS = 10000;
const MAX_BACKLOG = 4 * 1024 * 1024; // above what login writes in one go before the client reads any of it: every
// custom colour and custom item def (~4.2 MB on 2026-10-19, at the caps of
// 20000 colours and 5000 clothing), which a 4 MB limit cut off for everyone.
const MAX_BACKLOG = 16 * 1024 * 1024;
const MAX_ERRORS_PER_WINDOW = 20; const MAX_ERRORS_PER_WINDOW = 20;
// the Create Account screens are done in a few minutes; a guest connection // the Create Account screens are done in a few minutes; a guest connection
// does not get to stay for as long as it keeps sending something. // does not get to stay for as long as it keeps sending something.
@@ -27,6 +31,8 @@ const SIGNUP_LIFETIME_MS = 5 * 60000;
const forLog = message => message.replace(/(<pword><!\[CDATA\[)[\s\S]*?(\]\]>)/, "$1(hidden)$2"); const forLog = message => message.replace(/(<pword><!\[CDATA\[)[\s\S]*?(\]\]>)/, "$1(hidden)$2");
const connections = new Map(); // remote address -> open sockets const connections = new Map(); // remote address -> open sockets
let connectionCount = 0;
const metrics = {accepted: 0, rejected: 0, floodDisconnects: 0, handlerErrors: 0};
let nextUserId = 1; let nextUserId = 1;
@@ -49,7 +55,7 @@ class Session {
write(message) { write(message) {
if (this.socket.writable) { if (this.socket.writable) {
if (config.logPackets) { if (config.logPackets) {
console.log(`[game] -> ${this.name} ${message}`); console.log(`[game] -> ${logText(this.name)} ${logText(message)}`);
} }
this.socket.write(message + "\0"); this.socket.write(message + "\0");
// A client that stopped reading must not pile up messages here forever. // A client that stopped reading must not pile up messages here forever.
@@ -96,7 +102,7 @@ const parseSys = message => {
const start = handlers => new Promise((resolve, reject) => { const start = handlers => new Promise((resolve, reject) => {
const dispatch = (session, message) => { const dispatch = (session, message) => {
if (config.logPackets) { if (config.logPackets) {
console.log(`[game] <- ${session.name} ${forLog(message)}`); console.log(`[game] <- ${logText(session.name)} ${logText(forLog(message))}`);
} }
if (message.startsWith("<policy-file-request")) { if (message.startsWith("<policy-file-request")) {
session.socket.end(POLICY + "\0"); session.socket.end(POLICY + "\0");
@@ -138,13 +144,18 @@ const start = handlers => new Promise((resolve, reject) => {
const onConnection = socket => { const onConnection = socket => {
const address = limits.key(socket.remoteAddress); const address = limits.key(socket.remoteAddress);
const open = connections.get(address) || 0; const open = connections.get(address) || 0;
const total = [...connections.values()].reduce((sum, count) => sum + count, 0); // Kept as a counter instead of summing every address on every new socket.
// Under a burst of logins the old O(addresses) work delayed everyone else.
const total = connectionCount;
socket.on("error", () => {}); socket.on("error", () => {});
if (open >= config.maxConnectionsPerAddress || total >= config.maxConnections) { if (open >= config.maxConnectionsPerAddress || total >= config.maxConnections) {
metrics.rejected++;
socket.destroy(); socket.destroy();
return; return;
} }
connections.set(address, open + 1); connections.set(address, open + 1);
connectionCount++;
metrics.accepted++;
const session = new Session(socket); const session = new Session(socket);
let buffer = Buffer.alloc(0); let buffer = Buffer.alloc(0);
@@ -153,7 +164,7 @@ const start = handlers => new Promise((resolve, reject) => {
let bytesInWindow = 0; let bytesInWindow = 0;
let errorsInWindow = 0; let errorsInWindow = 0;
socket.setNoDelay(true); socket.setNoDelay(true);
console.log(`[game] ${session.remote} connected as #${session.id}`); console.log(`[game] ${logText(session.remote)} connected as #${logText(session.id)}`);
// whoever connects has to log in (or start signing up) promptly, and // whoever connects has to log in (or start signing up) promptly, and
// nobody may sit silent for long: the client sends keep-alives. // nobody may sit silent for long: the client sends keep-alives.
@@ -178,11 +189,15 @@ const start = handlers => new Promise((resolve, reject) => {
} }
bytesInWindow += chunk.length; bytesInWindow += chunk.length;
if (bytesInWindow > config.maxBytesPerTenSeconds) { if (bytesInWindow > config.maxBytesPerTenSeconds) {
console.log(`[game] ${session.name} disconnected for flooding`); metrics.floodDisconnects++;
console.log(`[game] ${logText(session.name)} disconnected for flooding`);
socket.destroy(); socket.destroy();
return; return;
} }
buffer = Buffer.concat([buffer, chunk]); // Node normally gives complete SmartFox packets in one chunk. Avoiding
// Buffer.concat in that common case reduces allocation and GC during
// busy logins; fragments still retain the exact old behaviour.
buffer = buffer.length === 0 ? chunk : Buffer.concat([buffer, chunk]);
let end; let end;
while ((end = buffer.indexOf(0)) !== -1) { while ((end = buffer.indexOf(0)) !== -1) {
if (end > MAX_MESSAGE) { if (end > MAX_MESSAGE) {
@@ -190,7 +205,8 @@ const start = handlers => new Promise((resolve, reject) => {
return; return;
} }
if (++messagesInWindow > config.maxMessagesPerTenSeconds) { if (++messagesInWindow > config.maxMessagesPerTenSeconds) {
console.log(`[game] ${session.name} disconnected for flooding`); metrics.floodDisconnects++;
console.log(`[game] ${logText(session.name)} disconnected for flooding`);
socket.destroy(); socket.destroy();
return; return;
} }
@@ -200,12 +216,13 @@ const start = handlers => new Promise((resolve, reject) => {
dispatch(session, message); dispatch(session, message);
} }
catch (err) { catch (err) {
metrics.handlerErrors++;
// one line a failure, and an end to them: a client that sends // one line a failure, and an end to them: a client that sends
// nonsense in a loop is not to fill the log. // nonsense in a loop is not to fill the log.
const where = String(err.stack || "").split("\n")[1] || ""; const where = String(err.stack || "").split("\n")[1] || "";
console.log(`[game] error handling message from ${session.name}: ${err.message}${where ? ` (${where.trim()})` : ""}`); console.log(`[game] error handling message from ${logText(session.name)}: ${logText(err.message)}${logText(where ? ` (${where.trim()})` : "")}`);
if (++errorsInWindow > MAX_ERRORS_PER_WINDOW) { if (++errorsInWindow > MAX_ERRORS_PER_WINDOW) {
console.log(`[game] ${session.name} disconnected: too many messages that could not be handled`); console.log(`[game] ${logText(session.name)} disconnected: too many messages that could not be handled`);
socket.destroy(); socket.destroy();
return; return;
} }
@@ -228,13 +245,14 @@ const start = handlers => new Promise((resolve, reject) => {
else { else {
connections.delete(address); connections.delete(address);
} }
console.log(`[game] ${session.name} disconnected`); connectionCount = Math.max(0, connectionCount - 1);
console.log(`[game] ${logText(session.name)} disconnected`);
// nothing thrown while a player is seen off may take the server down. // nothing thrown while a player is seen off may take the server down.
try { try {
handlers.close(session); handlers.close(session);
} }
catch (err) { catch (err) {
console.log(`[game] error while ${session.name} left: ${err.stack}`); console.log(`[game] error while ${logText(session.name)} left: ${logText(err.stack)}`);
} }
}); });
}; };
@@ -271,9 +289,20 @@ const start = handlers => new Promise((resolve, reject) => {
} }
server.once("error", reject); server.once("error", reject);
server.listen(config.gamePort, config.gameBindAddress, () => { server.listen(config.gamePort, config.gameBindAddress, () => {
console.log(`[game] listening on ${config.gameBindAddress}:${config.gamePort}${config.tls ? " (TLS)" : ""}`); console.log(`[game] listening on ${logText(config.gameBindAddress)}:${logText(config.gamePort)}${logText(config.tls ? " (TLS)" : "")}`);
resolve(server); resolve(server);
}); });
}); });
module.exports = {start}; // This intentionally exposes counts only: staff can see whether the service
// is healthy without receiving player addresses or packet contents.
const health = () => ({
openConnections: connectionCount,
connectedAddresses: connections.size,
accepted: metrics.accepted,
rejected: metrics.rejected,
floodDisconnects: metrics.floodDisconnects,
handlerErrors: metrics.handlerErrors,
});
module.exports = {start, health};
+3 -1
View File
@@ -1,5 +1,6 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto"); const crypto = require("crypto");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const bans = require("./bans.js"); const bans = require("./bans.js");
@@ -24,6 +25,7 @@ const STATUS = {
username_taken: USERNAME_TAKEN, username_taken: USERNAME_TAKEN,
invalid_username: USERNAME_INVALID, invalid_username: USERNAME_INVALID,
invalid_password: PASSWORD_INVALID, invalid_password: PASSWORD_INVALID,
weak_password: PASSWORD_INVALID, // the game's screens have one word for both
name_not_allowed: USERNAME_INVALID, name_not_allowed: USERNAME_INVALID,
}; };
// names asked about on one guest connection: the screens ask once or twice. // names asked about on one guest connection: the screens ask once or twice.
@@ -88,7 +90,7 @@ const handlers = {
return; return;
} }
if (!limits.registrationAllowed(session.address, limits.isTrustedLocal(session.address))) { if (!limits.registrationAllowed(session.address, limits.isTrustedLocal(session.address))) {
console.log(`[signup] too many sign-ups from ${session.address}`); console.log(`[signup] too many sign-ups from ${logText(session.address)}`);
session.sendXt("lc", -1, FAILED, 0); session.sendXt("lc", -1, FAILED, 0);
return; return;
} }
+160 -1
View File
@@ -2,7 +2,11 @@
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const bans = require("./bans.js"); const bans = require("./bans.js");
const devices = require("./devices.js");
const limits = require("./limits.js");
const manage = require("./manage.js"); const manage = require("./manage.js");
const modlog = require("./modlog.js");
const reports = require("./reports.js");
const support = require("./support.js"); const support = require("./support.js");
const world = require("./world.js"); const world = require("./world.js");
@@ -25,6 +29,57 @@ const disciplined = () => accounts.all()
.filter(entry => entry.banned !== 0 || entry.silenced !== 0) .filter(entry => entry.banned !== 0 || entry.silenced !== 0)
.sort((a, b) => a.username.localeCompare(b.username)); .sort((a, b) => a.username.localeCompare(b.username));
// accounts by name, for both panels' search: at most `limit`, those named
// exactly what was typed first, then those whose names start with it, then
// those with it anywhere, online players first within each and then by
// name. so "John" is never lost among John123 and Johnathan. with nothing
// typed: online players, then the ones seen last. `keep` narrows it
// (online, banned...). returns {found, total}: total is how many matched.
const MAX_FOUND = 50;
const findAccounts = (query, keep = () => true, limit = MAX_FOUND) => {
const wanted = String(query || "").trim().toLowerCase().slice(0, 100);
const online = new Set(world.players().map(player => player.username));
const rank = name => {
const low = name.toLowerCase();
return low === wanted ? 0 : low.startsWith(wanted) ? 1 : 2;
};
const matched = accounts.all().filter(account => account.username.toLowerCase().includes(wanted) && keep(account, online));
const sorted = wanted
? matched.sort((a, b) => rank(a.username) - rank(b.username) || Number(online.has(b.username)) - Number(online.has(a.username))
|| a.username.localeCompare(b.username))
: matched.sort((a, b) => Number(online.has(b.username)) - Number(online.has(a.username))
|| (b.lastSeen || b.lastLogin || 0) - (a.lastSeen || a.lastLogin || 0));
return {found: sorted.slice(0, limit), total: matched.length};
};
// the accounts that signed in from an address, or from any address that
// starts with what was typed ("203.0.113." for the lot): from the sign-in
// histories, which hold the last 90 days (lib/accounts.js). failed tries
// are left out, being anyone's. returns {error} or {players: [{username,
// online, addresses: [{address, at}], lastAt}]}, the latest first.
const MIN_ADDRESS_QUERY = 3;
const MAX_ADDRESS_FOUND = 100;
const byAddress = query => {
const wanted = String(query || "").trim().toLowerCase().replace(/^::ffff:/, "").slice(0, 60);
if (wanted.length < MIN_ADDRESS_QUERY || !/^[0-9a-f.:]+$/.test(wanted) || !/[.:]/.test(wanted)) {
return {error: "Type at least the start of an IP address, like 203.0.113."};
}
const players = [];
for (const account of accounts.all()) {
const seen = new Map();
for (const login of account.logins) {
if (login.ok && login.address && login.address.toLowerCase().startsWith(wanted)) {
seen.set(login.address, Math.max(seen.get(login.address) || 0, login.at));
}
}
if (seen.size > 0) {
const addresses = [...seen].map(([address, at]) => ({address, at})).sort((one, other) => other.at - one.at);
players.push({username: account.username, online: Boolean(world.findOnline(account.username)), addresses, lastAt: addresses[0].at});
}
}
return {players: players.sort((one, other) => other.lastAt - one.lastAt).slice(0, MAX_ADDRESS_FOUND)};
};
const ADDRESS_ERRORS = { const ADDRESS_ERRORS = {
not_an_address: "Not an IP address.", not_an_address: "Not an IP address.",
own_address: "That is this machine's own address: with a proxy or a tunnel in front, everyone's.", own_address: "That is this machine's own address: with a proxy or a tunnel in front, everyone's.",
@@ -39,6 +94,110 @@ const banAddress = (address, reason, by) => {
return result.error ? {error: ADDRESS_ERRORS[result.error]} : {ban: result.ban, out: world.disconnectAddress(result.ban.address)}; return result.error ? {error: ADDRESS_ERRORS[result.error]} : {ban: result.ban, out: world.disconnectAddress(result.ban.address)};
}; };
// bans every computer the account signed in from lately (lib/devices.js),
// and puts out whoever plays from one of them, whichever account. their
// sign-ins stay, as with an address ban: the client asks with one why its
// game stopped, and the account page stays open to them for an appeal; the
// game itself turns them away (lib/world.js). returns {ok, detail} or {error}.
const banDevices = (account, reason, by) => {
const result = devices.banAccount(account, reason, by);
if (result.error) {
return result;
}
const under = devices.accountsUnder(result.ban);
const out = world.disconnectBanned(under);
bans.record({account, action: "device_ban", seconds: -1, reason: result.ban.reason, by});
const others = under.filter(one => one !== account).map(one => one.username);
return {ok: `${account.username} is hardware banned (${result.ban.ids.length} IDs).${out ? ` ${out} playing from them ${out === 1 ? "was" : "were"} put out.` : ""}`
+ `${others.length ? ` Also used by: ${others.slice(0, 10).join(", ")}${others.length > 10 ? "…" : ""}.` : ""}`, detail: result.ban.reason};
};
const unbanDevices = (id, by) => {
const ban = devices.unban(id);
if (!ban) {
return {error: "No such hardware ban."};
}
bans.record({account: accounts.byId(ban.accountId), action: "device_unban", by});
return {ok: `The hardware ban made with ${ban.username || "that account"} is lifted.`, username: ban.username};
};
// every computer ban that keeps the account out, or was made with it, lifted.
const unbanDevicesOf = (account, by) => {
const lifted = devices.bansOfAccount(account).map(ban => unbanDevices(ban.id, by)).filter(result => result.ok);
if (!lifted.length) {
return {error: "None of their hardware is banned."};
}
const names = [...new Set(lifted.map(result => result.username).filter(Boolean))];
return {ok: `${lifted.length === 1 ? "1 hardware ban was" : `${lifted.length} hardware bans were`} lifted${names.length ? ` (made with ${names.join(", ")})` : ""}.`,
detail: names.join(", ")};
};
// the accounts that used a computer id, or one starting with what was
// typed (lib/devices.js): {error} or {players: [{username, kinds, lastAt}]}.
const byDevice = query => {
const found = devices.search(query);
return found.error ? found : {players: found.players.map(entry => ({username: entry.account.username, kinds: entry.kinds, lastAt: entry.lastAt}))};
};
// other accounts the same person may have: those that used one of its
// computers (lib/devices.js), and those that signed in from one of its
// addresses in the last 90 days. [{username, devices: [kind],
// addresses: count, online, banned}], the likeliest first. the addresses
// themselves are not given: moderators do not see them.
const altsOf = account => {
const found = new Map();
const entry = username => {
if (!found.has(username)) {
found.set(username, {username, devices: [], addresses: 0});
}
return found.get(username);
};
for (const alt of devices.alts(account)) {
Object.assign(entry(alt.username), {devices: alt.kinds});
}
const mine = new Set(account.logins.filter(login => login.ok && login.address && !limits.isLoopback(login.address)).map(login => login.address));
if (mine.size) {
for (const other of accounts.all()) {
if (other !== account) {
const shared = new Set(other.logins.filter(login => login.ok && mine.has(login.address)).map(login => login.address));
if (shared.size) {
entry(other.username).addresses = shared.size;
}
}
}
}
return [...found.values()].map(alt => {
const other = accounts.byName(alt.username);
return {...alt, online: Boolean(world.findOnline(alt.username)), banned: other ? world.moderation.banRemaining(other) : 0,
deviceBanned: other ? devices.bannedId(other) !== 0 : false};
}).sort((one, other) => Number(other.devices.length > 0) - Number(one.devices.length > 0)
|| other.devices.length - one.devices.length || other.addresses - one.addresses || one.username.localeCompare(other.username)).slice(0, 100);
};
// one player's story, newest first: bans given and lifted, what staff did
// to them, the reports about them, and what their computers gave away
// (lib/devices.js). [{at, kind, text, by}].
const BAN_WORDS = {ban: "Banned", unban: "Ban lifted", reason: "Ban reason changed", appeal: "Appealed", appeal_approved: "Appeal approved",
appeal_denied: "Appeal denied", device_ban: "Hardware banned", device_unban: "Hardware ban lifted"};
const timelineOf = account => {
const events = [];
for (const entry of bans.historyOf(account)) {
const length = entry.action === "ban" ? (entry.seconds === -1 ? "for good" : `${Math.round(entry.seconds / 3600)} h`) : "";
events.push({at: entry.at, kind: "ban", text: [BAN_WORDS[entry.action] || entry.action, length, entry.reason].filter(Boolean).join(" · "), by: entry.by});
}
for (const entry of modlog.about(account.username)) {
events.push({at: entry.at, kind: "staff", text: [entry.action, entry.detail].filter(Boolean).join(" · "), by: entry.by});
}
for (const report of reports.about(account.username)) {
events.push({at: report.createdAt, kind: "report", text: `Reported: ${report.reason}${report.detail ? ` · ${report.detail}` : ""}${report.handledAt ? "" : " (waiting)"}`,
by: report.reporter});
}
for (const entry of devices.alertsOf(account)) {
events.push({at: entry.at, kind: "alert", text: `${entry.name} · ${entry.detail}`, by: ""});
}
return events.sort((one, other) => other.at - one.at).slice(0, 200);
};
// appeals with what each is against, as it stands now. // appeals with what each is against, as it stands now.
const appealsFor = handled => bans.appeals(handled).map(appeal => { const appealsFor = handled => bans.appeals(handled).map(appeal => {
const account = accounts.byId(appeal.accountId); const account = accounts.byId(appeal.accountId);
@@ -94,4 +253,4 @@ const answerNameRequest = (id, approve) => {
return {ok: `${oldName} is now called ${account.username}. They log in with the new name and the same password.`, username: account.username}; return {ok: `${oldName} is now called ${account.username}. They log in with the new name and the same password.`, username: account.username};
}; };
module.exports = {disciplined, banAddress, appealsFor, answerAppeal, answerNameRequest}; module.exports = {disciplined, findAccounts, byAddress, banAddress, banDevices, unbanDevices, unbanDevicesOf, byDevice, altsOf, timelineOf, appealsFor, answerAppeal, answerNameRequest};
+209
View File
@@ -0,0 +1,209 @@
"use strict";
const fs = require("fs");
const path = require("path");
const accounts = require("./accounts.js");
const config = require("../config.js");
// the game's numbers over time, for the graphs on the admin and moderator
// panels: how many were playing (a sample a minute, written as one row per
// five minutes with its average and its most), every login to the game, and
// every stretch of play when it ends. the logins and the stretches name the
// account, so they go after a year (as the privacy policy says of the
// records kept about players); the head-counts name nobody and stay.
const DAY_SECONDS = 86400;
const SAMPLE_MS = 60000;
const ROW_SECONDS = 300;
const KEPT_DAYS = 365;
const RANGES = [1, 7, 30, 90, 365]; // days a graph can cover
const TOP_PLAYERS = 10;
const SCHEMA = `
CREATE TABLE IF NOT EXISTS stats_online (at INTEGER PRIMARY KEY, average REAL NOT NULL, most INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS stats_logins (at INTEGER NOT NULL, account_id INTEGER NOT NULL, first INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS stats_logins_at ON stats_logins (at);
CREATE TABLE IF NOT EXISTS stats_sessions (ended INTEGER NOT NULL, account_id INTEGER NOT NULL, seconds INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS stats_sessions_ended ON stats_sessions (ended);
`;
const now = () => Math.floor(Date.now() / 1000);
const db = () => accounts.database();
let countOnline = () => 0;
let row = null; // the five minutes being counted: {at, sum, samples, most}
const writeRow = () => {
if (row && row.samples > 0) {
db().prepare("INSERT INTO stats_online (at, average, most) VALUES (?, ?, ?) ON CONFLICT(at) DO UPDATE SET average = excluded.average, most = excluded.most")
.run(row.at, row.sum / row.samples, row.most);
}
};
const sample = () => {
const count = countOnline();
const at = Math.floor(now() / ROW_SECONDS) * ROW_SECONDS;
if (row && row.at !== at) {
writeRow();
row = null;
}
row = row || {at, sum: 0, samples: 0, most: 0};
row.sum += count;
row.samples++;
row.most = Math.max(row.most, count);
};
const prune = () => {
const before = now() - KEPT_DAYS * DAY_SECONDS;
db().prepare("DELETE FROM stats_logins WHERE at < ?").run(before);
db().prepare("DELETE FROM stats_sessions WHERE ended < ?").run(before);
};
// `online` counts the players in the game now (lib/world.js).
const load = online => {
db().exec(SCHEMA);
countOnline = online;
prune();
sample();
setInterval(() => {
try {
sample();
}
catch (err) {
console.error(`[stats] could not count: ${err.message}`);
}
}, SAMPLE_MS).unref();
setInterval(prune, DAY_SECONDS * 1000).unref();
};
// the row being counted is written before the server stops (server.js).
const flush = () => {
try {
writeRow();
}
catch (err) {
// the database is closing
}
};
const login = (account, first) => {
db().prepare("INSERT INTO stats_logins (at, account_id, first) VALUES (?, ?, ?)").run(now(), account.id, first ? 1 : 0);
};
const session = (account, seconds) => {
if (seconds > 0) {
db().prepare("INSERT INTO stats_sessions (ended, account_id, seconds) VALUES (?, ?, ?)").run(now(), account.id, Math.round(seconds));
}
};
// the numbers for the last `days` days, in buckets of an hour (a day or
// two) or of a day, the days as the viewer's clock has them: `offset` is
// their minutes ahead of UTC. the hours of the day and the days of the week
// are theirs too.
const report = (days, offset) => {
days = RANGES.includes(days) ? days : 7;
offset = Number.isInteger(offset) && Math.abs(offset) <= 14 * 60 ? offset * 60 : 0;
const end = now();
const start = end - days * DAY_SECONDS;
const size = days <= 2 ? 3600 : DAY_SECONDS;
// the bucket a moment falls in, by the viewer's clock.
const bucketOf = at => Math.floor((at + offset) / size) * size - offset;
const first = bucketOf(start);
const buckets = new Map();
for (let at = first; at <= end; at += size) {
buckets.set(at, {at, average: 0, most: 0, logins: 0, players: 0, newAccounts: 0, samples: 0, sum: 0, who: new Set()});
}
const hours = Array.from({length: 24}, () => ({sum: 0, samples: 0, logins: 0}));
const week = Array.from({length: 7}, () => Array.from({length: 24}, () => ({sum: 0, samples: 0})));
const local = at => new Date((at + offset) * 1000);
let most = {count: 0, at: null};
for (const sampled of db().prepare("SELECT at, average, most FROM stats_online WHERE at >= ? ORDER BY at").all(start)) {
const bucket = buckets.get(bucketOf(sampled.at));
if (bucket) {
bucket.sum += sampled.average;
bucket.samples++;
bucket.most = Math.max(bucket.most, sampled.most);
}
const when = local(sampled.at);
hours[when.getUTCHours()].sum += sampled.average;
hours[when.getUTCHours()].samples++;
week[when.getUTCDay()][when.getUTCHours()].sum += sampled.average;
week[when.getUTCDay()][when.getUTCHours()].samples++;
if (sampled.most > most.count) {
most = {count: sampled.most, at: sampled.at};
}
}
if (row && row.at >= start && row.most > most.count) {
most = {count: row.most, at: row.at};
}
const everyone = new Set();
let logins = 0;
let firstLogins = 0;
for (const entry of db().prepare("SELECT at, account_id, first FROM stats_logins WHERE at >= ?").all(start)) {
const bucket = buckets.get(bucketOf(entry.at));
if (bucket) {
bucket.logins++;
bucket.who.add(entry.account_id);
}
hours[local(entry.at).getUTCHours()].logins++;
everyone.add(entry.account_id);
logins++;
firstLogins += entry.first;
}
const all = accounts.all();
let newAccounts = 0;
for (const account of all) {
if (account.createdAt >= start) {
newAccounts++;
const bucket = buckets.get(bucketOf(account.createdAt));
if (bucket) {
bucket.newAccounts++;
}
}
}
const played = db().prepare("SELECT COUNT(*) AS count, COALESCE(SUM(seconds), 0) AS total FROM stats_sessions WHERE ended >= ?").get(start);
const ever = db().prepare("SELECT at, most FROM stats_online ORDER BY most DESC, at DESC LIMIT 1").get();
return {
days,
bucketSeconds: size,
summary: {
online: countOnline(),
accounts: all.length,
newAccounts,
logins,
players: everyone.size,
firstLogins,
peak: most,
peakEver: ever && (!row || ever.most >= row.most) ? {count: ever.most, at: ever.at} : row ? {count: row.most, at: row.at} : {count: 0, at: null},
sessions: played.count,
averageSessionSeconds: played.count ? Math.round(played.total / played.count) : 0,
playedSeconds: played.total,
},
series: [...buckets.values()].map(bucket => ({
at: bucket.at,
average: bucket.samples ? Math.round(bucket.sum / bucket.samples * 10) / 10 : null,
most: bucket.samples ? bucket.most : null,
logins: bucket.logins,
players: bucket.who.size,
newAccounts: bucket.newAccounts,
})),
hours: hours.map(hour => ({average: hour.samples ? Math.round(hour.sum / hour.samples * 10) / 10 : null, logins: hour.logins})),
week: week.map(day => day.map(hour => (hour.samples ? Math.round(hour.sum / hour.samples * 10) / 10 : null))),
topPlaytime: all.filter(account => account.playtime > 0).sort((one, other) => other.playtime - one.playtime).slice(0, TOP_PLAYERS)
.map(account => ({username: account.username, seconds: account.playtime})),
};
};
// A panel's page with the Stats tab (public/stats-view.html) where it says
// <!--stats-view-->: the admin and the moderator panels show the same one.
const withView = async page => {
const view = await fs.promises.readFile(path.join(config.publicDir, "stats-view.html"), "utf8");
return Buffer.from(String(page).replace("<!--stats-view-->", () => view));
};
module.exports = {load, flush, login, session, report, withView, RANGES};
+3 -2
View File
@@ -1,5 +1,6 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
// what players send from the account page (/account, lib/manage.js) for // what players send from the account page (/account, lib/manage.js) for
@@ -79,7 +80,7 @@ const requestName = (account, newName, reason) => {
db().prepare("UPDATE name_requests SET status = ?, handled_at = ? WHERE account_id = ? AND status = ?").run(WITHDRAWN, now(), account.id, WAITING); db().prepare("UPDATE name_requests SET status = ?, handled_at = ? WHERE account_id = ? AND status = ?").run(WITHDRAWN, now(), account.id, WAITING);
db().prepare("INSERT INTO name_requests (created_at, account_id, old_name, new_name, reason) VALUES (?, ?, ?, ?, ?)") db().prepare("INSERT INTO name_requests (created_at, account_id, old_name, new_name, reason) VALUES (?, ?, ?, ?, ?)")
.run(now(), account.id, account.username, newName, clean(reason, MAX_REASON)); .run(now(), account.id, account.username, newName, clean(reason, MAX_REASON));
console.log(`[support] "${account.username}" asked to be called "${newName}"`); console.log(`[support] "${logText(account.username)}" asked to be called "${logText(newName)}"`);
return {request: waitingNameRequest(account)}; return {request: waitingNameRequest(account)};
}; };
@@ -127,7 +128,7 @@ const sendFeedback = (account, kind, text) => {
return {error: "too_many"}; return {error: "too_many"};
} }
db().prepare("INSERT INTO feedback (created_at, account_id, username, kind, text) VALUES (?, ?, ?, ?, ?)").run(now(), account.id, account.username, kind, body); db().prepare("INSERT INTO feedback (created_at, account_id, username, kind, text) VALUES (?, ?, ?, ?, ?)").run(now(), account.id, account.username, kind, body);
console.log(`[support] ${kind === "bug" ? "bug report" : "feedback"} from "${account.username}"`); console.log(`[support] ${logText(kind === "bug" ? "bug report" : "feedback")} from "${logText(account.username)}"`);
return {ok: true}; return {ok: true};
}; };
+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};
+30 -16
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.
@@ -91,7 +96,8 @@ module.exports = ({findOnline, blocks}) => {
return [DONE_CLOTHING, entry.def, entry.inv, entry.color]; return [DONE_CLOTHING, entry.def, entry.inv, entry.color];
} }
if (type === TYPE_DEN_ITEM) { if (type === TYPE_DEN_ITEM) {
return [DONE_DEN_ITEM, entry.def, entry.inv, entry.version, "true", ...masterpieces.itemFields(entry)]; // the inventory id first here, unlike clothing (TradeManager.displayTradeDone).
return [DONE_DEN_ITEM, entry.inv, entry.def, entry.version, "true", ...masterpieces.itemFields(entry)];
} }
return [DONE_PET, entry.createdAt, entry.inv, entry.lBits & 0xFF, entry.lBits, entry.uBits, entry.eBits, 0, 0, 0, entry.name]; return [DONE_PET, entry.createdAt, entry.inv, entry.lBits & 0xFF, entry.lBits, entry.uBits, entry.eBits, 0, 0, 0, entry.name];
}; };
@@ -128,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;
@@ -135,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);
}; };
@@ -154,8 +164,11 @@ module.exports = ({findOnline, blocks}) => {
if (type === TYPE_CLOTHING) { if (type === TYPE_CLOTHING) {
moved.on = []; moved.on = [];
} }
else if (type === TYPE_PET) {
delete moved.inDen; // it was standing in the giver's den
}
else if (type === TYPE_DEN_ITEM) { else if (type === TYPE_DEN_ITEM) {
Object.assign(moved, {placed: false, x: 0, y: 0, flip: 0}); moved.spots = {}; // it stood in the giver's dens
delete moved.mannequin; // a mannequin changes hands bare delete moved.mannequin; // a mannequin changes hands bare
} }
collectionOf(to, type).push(moved); collectionOf(to, type).push(moved);
@@ -246,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))
@@ -263,7 +276,7 @@ module.exports = ({findOnline, blocks}) => {
const offeredNames = toOwner.map(item => nameOf(item.type, item.entry)); const offeredNames = toOwner.map(item => nameOf(item.type, item.entry));
note(requester.account, owner.account, wantedName, offeredNames); note(requester.account, owner.account, wantedName, offeredNames);
note(owner.account, requester.account, offeredNames, wantedName); note(owner.account, requester.account, offeredNames, wantedName);
accounts.save(); accounts.save(requester.account, owner.account);
requester.sendXt("ti", -1, TRADE_PROGRESS, COMPLETED, 1, ...doneFields(wantedType, toRequester), requester.sendXt("ti", -1, TRADE_PROGRESS, COMPLETED, 1, ...doneFields(wantedType, toRequester),
offered.length, ...offered.flatMap(item => [doneType(item.type), item.entry.inv])); offered.length, ...offered.flatMap(item => [doneType(item.type), item.entry.inv]));
owner.sendXt("ti", -1, TRADE_PROGRESS, COMPLETED, toOwner.length, ...toOwner.flatMap(item => doneFields(item.type, item.entry)), owner.sendXt("ti", -1, TRADE_PROGRESS, COMPLETED, toOwner.length, ...toOwner.flatMap(item => doneFields(item.type, item.entry)),
@@ -304,11 +317,12 @@ module.exports = ({findOnline, blocks}) => {
account.tradeList.push({type, inv}); account.tradeList.push({type, inv});
} }
} }
accounts.save(); accounts.save(account);
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) {
@@ -346,7 +360,7 @@ module.exports = ({findOnline, blocks}) => {
const offers = { const offers = {
// what `account` could give: its clothing and den items, by name. // what `account` could give: its clothing and den items, by name.
owned: account => [TYPE_CLOTHING, TYPE_DEN_ITEM].flatMap(type => collectionOf(account, type) owned: account => [TYPE_CLOTHING, TYPE_DEN_ITEM].flatMap(type => collectionOf(account, type)
.filter(entry => type !== TYPE_DEN_ITEM || (masterpieces.itemApproved(entry) && !entry.placed)) .filter(entry => type !== TYPE_DEN_ITEM || (masterpieces.itemApproved(entry) && Object.keys(entry.spots || {}).length === 0))
.map(entry => ({type, inv: entry.inv, name: nameOf(type, entry)}))) .map(entry => ({type, inv: entry.inv, name: nameOf(type, entry)})))
.sort((one, other) => one.name.localeCompare(other.name)), .sort((one, other) => one.name.localeCompare(other.name)),
@@ -384,7 +398,7 @@ module.exports = ({findOnline, blocks}) => {
return "too_many"; return "too_many";
} }
to.tradeOffers.push({id: to.nextInv++, fromId: from.id, at: Math.floor(Date.now() / 1000), wanted: want, offered: give}); to.tradeOffers.push({id: to.nextInv++, fromId: from.id, at: Math.floor(Date.now() / 1000), wanted: want, offered: give});
accounts.save(); accounts.save(to);
return null; return null;
}, },
@@ -402,7 +416,7 @@ module.exports = ({findOnline, blocks}) => {
const given = from ? offer.offered.map(item => ({type: item.type, entry: find(from, item.type, item.inv)})) : []; const given = from ? offer.offered.map(item => ({type: item.type, entry: find(from, item.type, item.inv)})) : [];
if (accept && (!from || !wanted || given.some(item => !item.entry) || blocks.either(from, account) if (accept && (!from || !wanted || given.some(item => !item.entry) || blocks.either(from, account)
|| !fits(from, [offer.wanted], given) || !fits(account, given, [offer.wanted]))) { || !fits(from, [offer.wanted], given) || !fits(account, given, [offer.wanted]))) {
accounts.save(); accounts.save(account);
return "gone"; return "gone";
} }
if (accept) { if (accept) {
@@ -415,7 +429,7 @@ module.exports = ({findOnline, blocks}) => {
// whoever is in the game sees their inventories change. // whoever is in the game sees their inventories change.
[account, from].forEach(refresh); [account, from].forEach(refresh);
} }
accounts.save(); accounts.save(account, from);
return null; return null;
}, },
@@ -424,7 +438,7 @@ module.exports = ({findOnline, blocks}) => {
const before = to ? to.tradeOffers.length : 0; const before = to ? to.tradeOffers.length : 0;
if (to) { if (to) {
to.tradeOffers = to.tradeOffers.filter(offer => !(offer.id === Number(id) && offer.fromId === from.id)); to.tradeOffers = to.tradeOffers.filter(offer => !(offer.id === Number(id) && offer.fromId === from.id));
accounts.save(); accounts.save(to);
} }
return Boolean(to) && to.tradeOffers.length < before; return Boolean(to) && to.tradeOffers.length < before;
}, },
+35 -11
View File
@@ -1,9 +1,12 @@
"use strict"; "use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto"); const crypto = require("crypto");
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const accounts = require("./accounts.js"); const accounts = require("./accounts.js");
const chatFilter = require("./chatfilter.js");
const chatlog = require("./chatlog.js");
const masterpieces = require("./masterpieces.js"); const masterpieces = require("./masterpieces.js");
const limits = require("./limits.js"); const limits = require("./limits.js");
const {isUint} = require("./player.js"); const {isUint} = require("./player.js");
@@ -71,8 +74,17 @@ const flat = value => scalar(value) || (typeof value === "object" && !Array.isAr
&& Object.keys(value).length <= 12 && Object.values(value).every(scalar)); && Object.keys(value).length <= 12 && Object.values(value).every(scalar));
const plainParam = value => flat(value) || (Array.isArray(value) && value.length <= MAX_PARAM_ENTRIES && value.every(flat)); const plainParam = value => flat(value) || (Array.isArray(value) && value.length <= MAX_PARAM_ENTRIES && value.every(flat));
const whole = value => (Number.isInteger(Number(value)) ? Number(value) : 0); const whole = value => (Number.isInteger(Number(value)) ? Number(value) : 0);
// the photo booth picture ("pb", PlayerWallGui): one level deeper than the
// rest, {avatar: {id, color1.., eyes, pattern}, bgid, pet: {ts, lbits, ..} |
// null, items: [{id, color}, ..]}. it was turned away as too deep, and the
// owner's whole change with it: the photo never stayed. an animal wearing
// nothing has no items list at all (null), which was turned away too.
const MAX_PHOTO_ITEMS = 30;
const photoParam = value => value === null || (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length <= 6
&& Object.entries(value).every(([key, part]) => (key === "items" ? part === null || (Array.isArray(part) && part.length <= MAX_PHOTO_ITEMS && part.every(flat))
: key === "avatar" || key === "pet" ? part === null || flat(part) : scalar(part))));
module.exports = ({blocks}) => { module.exports = ({blocks, findOnline}) => {
const tokens = new Map(); // token -> {viewer: account id, owner: account id, expires} const tokens = new Map(); // token -> {viewer: account id, owner: account id, expires}
const mayOpen = (owner, viewer) => { const mayOpen = (owner, viewer) => {
@@ -150,7 +162,17 @@ module.exports = ({blocks}) => {
const put = (owner, viewer, body) => { const put = (owner, viewer, body) => {
const colours = Array.isArray(body.ac) ? body.ac.slice(0, 3).map(String) : []; const colours = Array.isArray(body.ac) ? body.ac.slice(0, 3).map(String) : [];
const message = clean(body.m === undefined ? "" : body.m); const message = clean(body.m === undefined ? "" : body.m);
if (!message || isSilenced(viewer) || !colours.every(isUint) || !postsPerTenMinutes.allow(viewer.id)) { // the server's filter (lib/chatfilter.js) too.
const rule = message ? chatFilter.broken(message) : null;
if (rule) {
console.log(`[filter] ${logText(viewer.username)} on ${logText(owner.username)}'s wall: "${logText(message)}" (${logText(rule)})`);
chatlog.recordTo(viewer, chatlog.WALL, owner.username, chatlog.NOT_SENT + message);
const session = findOnline(viewer.username);
if (session) {
chatFilter.warn(session);
}
}
if (!message || rule || isSilenced(viewer) || !colours.every(isUint) || !postsPerTenMinutes.allow(viewer.id)) {
// PlayerWallGui.onMessageSent: cs -1 = "could not be posted" // PlayerWallGui.onMessageSent: cs -1 = "could not be posted"
return {PUT: {s: false, cs: -1}}; return {PUT: {s: false, cs: -1}};
} }
@@ -174,10 +196,12 @@ module.exports = ({blocks}) => {
if (typeof body.pp === "string" && owner.wall.posts.some(other => other.x === body.pp)) { if (typeof body.pp === "string" && owner.wall.posts.some(other => other.x === body.pp)) {
post.pp = body.pp; // a reply to that post post.pp = body.pp; // a reply to that post
} }
// for the panels (lib/chatlog.js), as typed chat is.
chatlog.recordTo(viewer, chatlog.WALL, owner.username, message);
owner.wall.posts.push(post); owner.wall.posts.push(post);
owner.wall.posts = owner.wall.posts.slice(-MAX_POSTS); owner.wall.posts = owner.wall.posts.slice(-MAX_POSTS);
owner.wall.modified = post.t; owner.wall.modified = post.t;
accounts.save(); accounts.save(owner);
return {PUT: {s: true}, x: post.x, t: post.t, GET: getReply(owner, viewer)}; return {PUT: {s: true}, x: post.x, t: post.t, GET: getReply(owner, viewer)};
}; };
@@ -207,7 +231,7 @@ module.exports = ({blocks}) => {
} }
wall.posts = wall.posts.filter(candidate => candidate !== post && candidate.pp !== post.x); wall.posts = wall.posts.filter(candidate => candidate !== post && candidate.pp !== post.x);
wall.modified = Date.now(); wall.modified = Date.now();
accounts.save(); accounts.save(owner);
return {s: true}; return {s: true};
} }
case "GMB": // posts the owner chose to hide case "GMB": // posts the owner chose to hide
@@ -217,7 +241,7 @@ module.exports = ({blocks}) => {
return {s: false}; return {s: false};
} }
wall.hidden = [...new Set([...wall.hidden, body.x])].slice(-MAX_HIDDEN); wall.hidden = [...new Set([...wall.hidden, body.x])].slice(-MAX_HIDDEN);
accounts.save(); accounts.save(owner);
return {s: true}; return {s: true};
case "CLW": case "CLW":
if (!mine) { if (!mine) {
@@ -226,7 +250,7 @@ module.exports = ({blocks}) => {
wall.posts = []; wall.posts = [];
wall.hidden = []; wall.hidden = [];
wall.modified = Date.now(); wall.modified = Date.now();
accounts.save(); accounts.save(owner);
return {s: true}; return {s: true};
case "RMP": // masterpieces taken off the wall; there are none case "RMP": // masterpieces taken off the wall; there are none
case "ACK": // notifications marked as read; there are none case "ACK": // notifications marked as read; there are none
@@ -264,7 +288,7 @@ module.exports = ({blocks}) => {
&& mayOpen(owner, session.account) === TOKEN_OK; && mayOpen(owner, session.account) === TOKEN_OK;
if (allowed) { if (allowed) {
owner.wall.likes = [...likes(owner), session.account.id]; owner.wall.likes = [...likes(owner), session.account.id];
accounts.save(); accounts.save(owner);
} }
session.sendXt("crp", -1, allowed ? 1 : 0); session.sendXt("crp", -1, allowed ? 1 : 0);
}, },
@@ -286,7 +310,7 @@ module.exports = ({blocks}) => {
const valid = [NOBODY, BUDDIES, EVERYONE].includes(value); const valid = [NOBODY, BUDDIES, EVERYONE].includes(value);
if (valid) { if (valid) {
session.account.wall.privacy = value; session.account.wall.privacy = value;
accounts.save(); accounts.save(session.account);
} }
session.sendXt("wss", -1, valid ? 1 : 0); session.sendXt("wss", -1, valid ? 1 : 0);
}, },
@@ -311,7 +335,7 @@ module.exports = ({blocks}) => {
const merged = changes && typeof changes === "object" && !Array.isArray(changes) ? {...wall.params} : null; const merged = changes && typeof changes === "object" && !Array.isArray(changes) ? {...wall.params} : null;
for (const key of merged ? OWNER_PARAMS : []) { for (const key of merged ? OWNER_PARAMS : []) {
if (changes[key] !== undefined) { if (changes[key] !== undefined) {
if (!plainParam(changes[key])) { if (!(key === "pb" ? photoParam(changes[key]) : plainParam(changes[key]))) {
session.sendXt("wps", -1, 0); session.sendXt("wps", -1, 0);
return; return;
} }
@@ -324,7 +348,7 @@ module.exports = ({blocks}) => {
} }
wall.params = merged; wall.params = merged;
wall.modified = Date.now(); wall.modified = Date.now();
accounts.save(); accounts.save(session.account);
session.sendXt("wps", -1, 1); session.sendXt("wps", -1, 1);
}, },
@@ -333,7 +357,7 @@ module.exports = ({blocks}) => {
const owner = accounts.byName(username); const owner = accounts.byName(username);
if (owner && owner !== session.account && mayOpen(owner, session.account) === TOKEN_OK) { if (owner && owner !== session.account && mayOpen(owner, session.account) === TOKEN_OK) {
owner.wall.visits++; owner.wall.visits++;
accounts.save(); accounts.save(owner);
} }
session.sendXt("wci", -1, owner ? 1 : 0); session.sendXt("wci", -1, owner ? 1 : 0);
}, },
+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};
+980 -91
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -67,7 +67,7 @@ const handlers = {
} }
// the client reads the bit straight from its copy of the user var. // the client reads the bit straight from its copy of the user var.
achievements.set(account, def.userVarRefId, ((Number(account.userVars[def.userVarRefId]) || 0) | (1 << Number(def.uvIndex))) >>> 0); achievements.set(account, def.userVarRefId, ((Number(account.userVars[def.userVarRefId]) || 0) | (1 << Number(def.uvIndex))) >>> 0);
accounts.save(); accounts.save(account);
session.sendXt("wig", -1, 1, amount); session.sendXt("wig", -1, 1, amount);
}, },
}; };
+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"
} }
} }
+507 -21
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. */
@@ -136,6 +138,14 @@
input:not([type="checkbox"]), textarea { width: 100%; } input:not([type="checkbox"]), textarea { width: 100%; }
textarea { min-height: 110px; resize: vertical; } textarea { min-height: 110px; resize: vertical; }
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-top: 12px; } .row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-top: 12px; }
/* their own custom items: a card each, its picture on the left */
.my-items { display: grid; gap: 10px; margin-top: 10px; }
.my-item { display: grid; grid-template-columns: 72px 1fr; gap: 12px; align-items: center; padding: 10px; border: 1px solid var(--line); border-radius: 14px; }
.my-item .art { width: 72px; height: 72px; border-radius: 10px; background: var(--raised, #1a1a1a); display: grid; place-items: center; overflow: hidden; color: var(--muted); font-size: 11px; text-align: center; }
.my-item .art img { max-width: 100%; max-height: 100%; image-rendering: auto; }
.my-item .row { margin-top: 6px; }
.my-item input[type="text"] { flex: 1; min-width: 140px; }
.my-item input[type="file"] { display: none; }
.captcha { margin-top: 12px; } .captcha { margin-top: 12px; }
.tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; } .tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; }
.tile { padding: 12px 14px 11px; border: 1px solid var(--line); border-radius: 18px; } .tile { padding: 12px 14px 11px; border: 1px solid var(--line); border-radius: 18px; }
@@ -167,6 +177,26 @@
.ban-head { display: flex; align-items: center; gap: 12px; margin-bottom: 4px; } .ban-head { display: flex; align-items: center; gap: 12px; margin-bottom: 4px; }
.ban-head img { width: 44px; height: 44px; flex: none; } .ban-head img { width: 44px; height: 44px; flex: none; }
.ban-head h2 { margin: 0; font-size: 22px; } .ban-head h2 { margin: 0; font-size: 22px; }
.chat-style-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 12px; }
.chat-style-grid input[type="color"] { width: 100%; height: 42px; padding: 3px; cursor: pointer; }
.gradient-editor { margin: 14px 0; padding: 12px; border: 1px solid var(--line); border-radius: 12px; }
.gradient-editor-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; }
.gradient-stops { display: grid; gap: 8px; }
.gradient-ramp { height: 22px; margin-bottom: 10px; border: 1px solid var(--line); border-radius: 999px; }
.gradient-stop { display: grid; grid-template-columns: 50px minmax(100px, 1fr) 72px auto; align-items: center; gap: 8px; }
.gradient-stop input[type="color"] { width: 50px; height: 36px; padding: 2px; cursor: pointer; }
.gradient-stop input[type="range"] { margin: 0; }
.gradient-stop output { color: var(--muted); font-size: 12px; text-align: right; }
.chat-preview { min-height: 74px; display: grid; place-items: center; margin-top: 14px; padding: 12px 18px; border: 1px solid var(--line); border-radius: 18px; text-align: center; font-weight: 700; background: linear-gradient(120deg, #fff, #dfe8ff); color: #445559; }
.chat-preview.pulse { animation: chatPulse 1.5s ease-in-out infinite alternate; }
.chat-preview.shimmer { background-size: 250% 100%; animation: chatShimmer 1.5s linear infinite; }
.chat-preview.flow { background-size: 220% 220%; animation: chatFlow 1.5s linear infinite alternate; }
.chat-preview.rainbow { animation: chatRainbow 2s linear infinite; }
@keyframes chatPulse { to { opacity: .55; } }
@keyframes chatShimmer { to { background-position: 100% 0; } }
@keyframes chatFlow { to { background-position: 100% 100%; } }
@keyframes chatRainbow { to { filter: hue-rotate(360deg); } }
@media (max-width: 440px) { .chat-style-grid { grid-template-columns: 1fr; } }
#ban-section pre { margin: 0 0 12px; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; } #ban-section pre { margin: 0 0 12px; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; }
#ban-section h3 { margin: 18px 0 0; } #ban-section h3 { margin: 18px 0 0; }
</style> </style>
@@ -187,16 +217,17 @@
<label class="check" style="margin-top:12px"><input id="remember-device" type="checkbox"> Trust this device for 30 days</label> <label class="check" style="margin-top:12px"><input id="remember-device" type="checkbox"> Trust this device for 30 days</label>
</div> </div>
<div class="captcha" id="captcha"></div> <div class="captcha" id="captcha"></div>
<div class="row"><button class="primary" type="submit">Sign in</button></div> <div class="row"><button class="primary" type="submit">Sign in</button><button id="client-sign-in" type="button">Sign in with the Burrow client</button></div>
</form> </form>
<p class="status" id="gate-status" role="status"></p> <p class="status" id="gate-status" role="status"></p>
<p class="hint" style="margin:10px 0 0">No account yet? <a href="/register">Create one</a></p> <p class="hint" style="margin:10px 0 0">No account yet? <a href="/register">Create one</a> · <a href="/account/recover">Forgot password or 2FA?</a></p>
</div> </div>
<div id="page" hidden> <div id="page" hidden>
<header> <header>
<img class="mark" src="/logo.png" alt=""> <img class="mark" src="/logo.png" alt="">
<h1 id="title"></h1> <h1 id="title"></h1>
<a class="button" id="item-giver" href="/account/items">Item giver</a>
<button id="sign-out" type="button">Sign out</button> <button id="sign-out" type="button">Sign out</button>
</header> </header>
@@ -234,7 +265,11 @@
<section> <section>
<h2>Buddies</h2> <h2>Buddies</h2>
<div id="buddies"></div> <!-- closed at first: a long list made the page slow to scroll -->
<details id="buddies-box" hidden>
<summary id="buddies-summary">Buddies</summary>
<div id="buddies"></div>
</details>
<p class="hint" id="no-buddies" hidden>No buddies yet.</p> <p class="hint" id="no-buddies" hidden>No buddies yet.</p>
<p class="status" id="buddy-status" role="status"></p> <p class="status" id="buddy-status" role="status"></p>
</section> </section>
@@ -285,7 +320,10 @@
<section> <section>
<h2>Den visitors</h2> <h2>Den visitors</h2>
<div id="visits"></div> <details id="visits-box" hidden>
<summary id="visits-summary">Visitors</summary>
<div id="visits"></div>
</details>
<p class="hint" id="no-visits" hidden>No visitors yet.</p> <p class="hint" id="no-visits" hidden>No visitors yet.</p>
</section> </section>
@@ -303,6 +341,14 @@
</details> </details>
</section> </section>
<section>
<h2>My items</h2>
<p class="hint" id="my-items-hint"></p>
<div class="my-items" id="my-items"></div>
<p class="hint" id="no-my-items" hidden>You have not made any items yet. Make one in the game: Settings, then Item Maker.</p>
<p class="status" id="my-items-status" role="status"></p>
</section>
<section class="kept" id="rename-section" hidden> <section class="kept" id="rename-section" hidden>
<h2>Username rejected</h2> <h2>Username rejected</h2>
<form id="rename-form"> <form id="rename-form">
@@ -338,15 +384,52 @@
<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>
<h2>Playtime</h2>
<p id="playtime-text"></p>
<div class="switch">
<div class="what"><b>Show on my card</b><span class="hint">At the top of the Bio tab, for anyone who opens your card in the game.</span></div>
<button id="playtime-public" type="button" aria-pressed="false">Private</button>
</div>
<p class="status" id="playtime-status" role="status"></p>
</section>
<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>
@@ -480,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
@@ -503,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 ? {} : {
@@ -586,6 +793,133 @@
} }
}; };
// their own custom items (lib/playeritems.js): rename, a picture of its
// own (sent as it is to /api/itemart, which checks and cleans it), delete.
const renderMyItems = () => {
const items = account.customItems || [];
const limits = account.customItemLimits || {perDay: 0, inAll: 0};
$("my-items-hint").textContent = `Items you made in the game's Item Maker: ${items.length} of ${limits.inAll}, up to ${limits.perDay} a day. `
+ "A picture (any kind: one too big is made smaller) is shown as the item's icon, and for a den item in the den, once a moderator has checked it. "
+ (account.picturesStopped ? "A moderator has turned off picture uploads for your account." : "Pictures must suit everyone: one turned away counts against you.");
$("no-my-items").hidden = items.length > 0;
$("my-items").replaceChildren(...items.map(item => {
const card = el("div", undefined, "my-item");
const art = el("div", item.art ? undefined : "No picture", "art");
if (item.art) {
const picture = el("img");
picture.src = item.art;
picture.alt = "";
art.append(picture);
}
const body = el("div");
body.append(el("strong", `${item.name}`), el("span", ` · ${item.kind === "den" ? "den item" : "clothing"} ${item.id}${item.artWaiting ? " · picture waiting for a moderator" : ""}`, "hint"));
const nameRow = el("div", undefined, "row");
const name = el("input");
name.type = "text";
name.maxLength = 40;
name.value = item.name;
name.setAttribute("aria-label", `New name for ${item.name}`);
const rename = el("button", "Rename");
rename.type = "button";
rename.addEventListener("click", () => act({action: "itemRename", kind: item.kind, id: item.id, name: name.value}, "my-items-status"));
nameRow.append(name, rename);
const artRow = el("div", undefined, "row");
const file = el("input");
file.type = "file";
file.accept = "image/*";
const choose = el("button", item.art ? "New picture" : "Add picture");
choose.type = "button";
choose.addEventListener("click", () => file.click());
file.addEventListener("change", () => file.files[0] && sendPicture(item, file.files[0]));
artRow.append(file, choose);
if (item.art && item.kind === "clothing") {
// how it is worn: the picture itself, or the item's shape painted with it
const look = el("select");
look.setAttribute("aria-label", `How ${item.name} is worn`);
for (const [value, text] of [["sticker", "Worn as the picture"], ["texture", "Worn as its shape, with the picture in it"]]) {
const option = el("option", text);
option.value = value;
look.append(option);
}
look.value = item.look || "sticker";
look.addEventListener("change", () => act({action: "itemLook", kind: item.kind, id: item.id, look: look.value}, "my-items-status"));
artRow.append(look);
}
if (item.art) {
const remove = el("button", "Remove picture");
remove.type = "button";
remove.addEventListener("click", () => sendPicture(item, null));
artRow.append(remove);
}
const del = el("button", "Delete", "danger");
del.type = "button";
del.addEventListener("click", () => {
if (confirm(`Delete ${item.name}? It goes from everyone who has it, and cannot be undone.`)) {
act({action: "itemDelete", kind: item.kind, id: item.id}, "my-items-status");
}
});
artRow.append(del);
body.append(nameRow, artRow);
card.append(art, body);
return card;
}));
};
// a picture made ready to send (lib/itemart.js): as it is when the
// server takes it as it is (a PNG, JPEG or GIF small enough: a GIF keeps
// moving), else drawn into a PNG that fits, smaller until it is small
// enough. any picture this browser can open will do (WebP, AVIF, BMP...).
// null when it cannot be read at all.
const PICTURE_SIDE = 256;
const PICTURE_BYTES = 100 * 1024;
const preparePicture = async file => {
const kept = ["image/png", "image/jpeg", "image/gif"].includes(file.type);
let image = null;
try {
image = await createImageBitmap(file);
}
catch (err) {
return kept ? file : null;
}
if (kept && file.size <= PICTURE_BYTES && image.width <= PICTURE_SIDE && image.height <= PICTURE_SIDE) {
image.close();
return file;
}
for (const side of [PICTURE_SIDE, 192, 128, 96]) {
const scale = Math.min(1, side / image.width, side / image.height);
const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.round(image.width * scale));
canvas.height = Math.max(1, Math.round(image.height * scale));
canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
const blob = await new Promise(resolve => canvas.toBlob(resolve, "image/png"));
if (blob && blob.size <= PICTURE_BYTES) {
image.close();
return blob;
}
}
image.close();
return null;
};
const sendPicture = async (item, chosen) => {
const file = chosen ? await preparePicture(chosen) : null;
if (chosen && !file) {
setStatus("my-items-status", "That picture could not be read. Try a PNG, JPEG or GIF.", true);
return;
}
setStatus("my-items-status", file ? "Sending the picture..." : "Taking the picture away...");
try {
const response = await fetch(`/account/api/itemart?kind=${encodeURIComponent(item.kind)}&id=${encodeURIComponent(item.id)}${file ? "" : "&remove=1"}`,
{method: "POST", headers: {"Content-Type": "application/octet-stream"}, body: file || new Uint8Array(0)});
const data = await response.json().catch(() => ({}));
setStatus("my-items-status", data.ok || data.error || "That did not work.", !data.ok);
await load();
}
catch (err) {
setStatus("my-items-status", "The server did not answer.", true);
}
};
const render = () => { const render = () => {
$("gate").hidden = true; $("gate").hidden = true;
$("page").hidden = false; $("page").hidden = false;
@@ -604,12 +938,17 @@
if (account.nameRejected) { if (account.nameRejected) {
return; return;
} }
renderMyItems();
$("lock-notice").hidden = !account.locked; $("lock-notice").hidden = !account.locked;
if (!$("chat-style-form").contains(document.activeElement)) {
fillChatStyle(account.chatStyle);
}
const tiles = [ const tiles = [
[account.online ? "Playing now" : account.lastSeen ? when(account.lastSeen) : "Not played yet", "Last seen"], [account.online ? "Playing now" : account.lastSeen ? when(account.lastSeen) : "Not played yet", "Last seen"],
[when(account.createdAt), "Created"], [when(account.createdAt), "Created"],
[account.logins.toLocaleString(), "Logins"], [account.logins.toLocaleString(), "Logins"],
[played(account.playtime), "Playtime"],
[`${account.animals}${ANIMALS[account.animalType] ? ` · ${ANIMALS[account.animalType]} in use` : ""}`, "Animals"], [`${account.animals}${ANIMALS[account.animalType] ? ` · ${ANIMALS[account.animalType]} in use` : ""}`, "Animals"],
[account.pets.toLocaleString(), "Pets"], [account.pets.toLocaleString(), "Pets"],
[account.items.toLocaleString(), "Clothing"], [account.items.toLocaleString(), "Clothing"],
@@ -638,17 +977,23 @@
return row; return row;
})); }));
$("playtime-text").textContent = `You have played for ${played(account.playtime)}.`;
$("playtime-public").textContent = account.playtimePublic ? "Public" : "Private";
$("playtime-public").setAttribute("aria-pressed", String(account.playtimePublic));
$("playtime-public").setAttribute("aria-label", `Show playtime on my card: ${account.playtimePublic ? "public" : "private"}`);
$("playtime-public").disabled = false;
if (document.activeElement !== $("bio-text")) { if (document.activeElement !== $("bio-text")) {
$("bio-text").value = account.bio; $("bio-text").value = account.bio;
} }
$("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(", ")}`;
@@ -684,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");
@@ -729,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 => {
@@ -777,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();
@@ -1148,6 +1564,26 @@
}); });
$("forget-devices").addEventListener("click", () => act({action: "forgetDevices"}, "two-step-status")); $("forget-devices").addEventListener("click", () => act({action: "forgetDevices"}, "two-step-status"));
// time played, in the largest units that say it: "3 days 4 hours".
const played = seconds => {
const days = Math.floor(seconds / 86400);
const hours = Math.floor(seconds % 86400 / 3600);
const minutes = Math.floor(seconds % 3600 / 60);
const unit = (count, name) => `${count.toLocaleString()} ${name}${count === 1 ? "" : "s"}`;
if (days > 0) {
return hours > 0 ? `${unit(days, "day")} ${unit(hours, "hour")}` : unit(days, "day");
}
if (hours > 0) {
return minutes > 0 ? `${unit(hours, "hour")} ${unit(minutes, "minute")}` : unit(hours, "hour");
}
return unit(minutes, "minute");
};
$("playtime-public").addEventListener("click", async () => {
$("playtime-public").disabled = true;
await act({action: "playtimePublic", on: !account.playtimePublic}, "playtime-status");
$("playtime-public").disabled = false;
});
const bioCount = () => { const bioCount = () => {
$("bio-count").textContent = `${[...$("bio-text").value.trim()].length} / ${account ? account.bioLimit : 200}`; $("bio-count").textContent = `${[...$("bio-text").value.trim()].length} / ${account ? account.bioLimit : 200}`;
}; };
@@ -1159,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.")) {
+2320 -148
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 945 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

+7 -1
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."};
})(); })();
Loaded 100 of 344 files, more files were not shown because too many files have changed in this diff. Show more