Compare commits

..
22 Commits
Author SHA1 Message Date
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
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
97 changed files with 18846 additions and 663 deletions

No files matched your search

+2
View File
@@ -2,8 +2,10 @@
"server": [
"ajcontent.akamaized.net",
"burrow.moe",
"cdn.jsdelivr.net",
"challenges.cloudflare.com",
"play.burrow.moe",
"vision.googleapis.com",
"www.cloudflare.com",
"www.w3.org"
],
+3
View File
@@ -12,3 +12,6 @@ Every push to this repository is checked automatically (`.github/workflows/secur
Burrow is an unofficial fan project. It is not affiliated with, endorsed by or connected to WildWorks, Inc. or Animal Jam. Animal Jam and Animal Jam Classic are trademarks of WildWorks, Inc.
**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/).
+49 -5
View File
@@ -3,6 +3,7 @@
const path = require("path");
const env = process.env;
const googleVisionApiKey = env.AJ_GOOGLE_VISION_API_KEY;
const LOOPBACK_NAMES = ["127.0.0.1", "::1", "localhost"];
const bindAddress = env.AJ_BIND || "127.0.0.1";
const httpPort = Number(env.AJ_HTTP_PORT || 8080);
@@ -84,6 +85,13 @@ module.exports = {
// cookies are only sent back over an encrypted connection when players
// have one, whoever does the encrypting.
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
// 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.
@@ -97,7 +105,15 @@ module.exports = {
// asset mirror: anything not served locally is fetched once from here and
// cached in cacheDir. set AJ_OFFLINE=1 to serve from the cache only.
upstreamContent: env.AJ_UPSTREAM || "https://ajcontent.akamaized.net/",
// 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",
// the client's device ids (lib/devices.js): with AJ_REQUIRE_DEVICE=1, a
// sign-in without them (a client from before 1.3.0, the official
// launcher, or one that left them out) is refused. off for now, while
// players update to 1.3.0: they are let in, and an account seen on banned
// hardware before is still kept out.
requireDevice: env.AJ_REQUIRE_DEVICE === "1",
deployVersion: env.AJ_DEPLOY_VERSION || "1830",
// older builds the CDN still serves, asked in turn for a room file the
// current build has dropped. 1828 is the last with the Summer Carnival.
@@ -116,7 +132,7 @@ module.exports = {
// 41: the game's text says "Burrow" where it said Animal Jam.
// 48: the item giver (the item finder renamed) with previews and hex colours;
// 49 and 50: its link to a colour picker.
buildVersion: env.AJ_BUILD_VERSION || "57",
buildVersion: env.AJ_BUILD_VERSION || "60",
// what the official CDN is asked for; not ours to change.
upstreamBuildVersion: "3",
@@ -246,8 +262,23 @@ module.exports = {
{room: "appondale.room_museum", shown: "appondale.room_museum_ant", months: [2, 4, 6, 8, 10, 12]},
],
startupRoom: "jamaa_township.room_main",
shards: [{id: 1, name: "Aldan"}],
maxUsersPerRoom: 80,
// where a player who does not start in their den arrives: one of these at
// 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. A local server starts with one shared world so two
// players in the same land can always see one another; set AJ_WORLDS=2 or
// more to opt into separate copies of every land.
shards: ["Aldan", "Congo", "Draa", "Grande", "Kama", "Nile", "Pecos", "Ramu", "Tigris", "Zambezi"]
.slice(0, Math.min(10, Math.max(1, Number(env.AJ_WORLDS) || 1))).map((name, i) => ({id: i + 1, name})),
maxUsersPerRoom: 40,
// everything in every shop for nothing (AJ_FREE_SHOPS=1). off unless
// asked for: what the game's shops make of a price of 0 has not been seen.
freeShops: env.AJ_FREE_SHOPS === "1",
@@ -282,9 +313,22 @@ module.exports = {
tlsHandshakeTimeoutMs: 10000,
maxMessagesPerTenSeconds: 400, // per game socket; walking sends a few a second
loginTimeoutMs: 30000, // a game socket must log in within this
idleTimeoutMs: 15 * 60000, // the client sends a keep-alive far more often
// 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"
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
// 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),
+34 -13
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
@@ -270,6 +271,8 @@ const normalize = account => {
account.totp = account.totp || null;
account.totpSetup = account.totpSetup || null;
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.numLogins = account.numLogins || 0;
account.uuid = account.uuid || crypto.randomUUID();
@@ -346,7 +349,7 @@ const importLegacyFile = () => {
}
db.exec("COMMIT");
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 = () => {
@@ -389,7 +392,7 @@ const load = () => {
// runs the server is told which, to rename by hand if they see fit.
const unusual = [...byId.values()].filter(account => names.refused(account.username)).map(account => account.username);
if (unusual.length) {
console.log(`[accounts] usernames that could not be chosen today: ${unusual.slice(0, 50).join(", ")}${unusual.length > 50 ? ", ..." : ""}`);
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
// it existed, the oldest hundred of them.
@@ -412,7 +415,7 @@ const load = () => {
for (const row of db.prepare("SELECT token, account_id, created_at FROM tokens").all()) {
tokens.set(row.token, {id: row.account_id, createdAt: row.created_at});
}
console.log(`[accounts] ${byKey.size} accounts in ${path.join(config.dataDir, "game.sqlite")}`);
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
@@ -636,7 +639,7 @@ const backup = async () => {
for (const name of old) {
fs.unlinkSync(path.join(folder, name));
}
console.log(`[accounts] backup written: ${file}`);
console.log(`[accounts] backup written: ${logText(file)}`);
};
const startBackups = () => {
const attempt = () => {
@@ -669,9 +672,26 @@ const retire = key => {
// A new password: ten characters or more, with a capital letter, a small
// one and a digit among them. passwords chosen before this rule still sign
// in; it is asked of the next one.
const passwordProblem = password =>
(typeof password !== "string" || password.length < MIN_PASSWORD_LENGTH || password.length > MAX_PASSWORD_LENGTH
|| !/[A-Z]/.test(password) || !/[a-z]/.test(password) || !/[0-9]/.test(password) ? "invalid_password" : null);
// the words most often under a password that meets the rules ("Password123",
// "Sunshine2024"): with its digits and signs taken off, a password that is
// 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
// name may be left out, and is then the player's. there is no default
@@ -680,7 +700,7 @@ const passwordProblem = password =>
// "invalid_password" | "choose_animal"}.
const register = (username, password, avatar = {}) => {
username = typeof username === "string" ? username.trim() : username;
const error = usernameProblem(username) || passwordProblem(password) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal");
const error = usernameProblem(username) || passwordProblem(password, username) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal");
if (error) {
return {error};
}
@@ -692,7 +712,7 @@ const register = (username, password, avatar = {}) => {
// early Member, for an account made while there are no more than a hundred.
badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [],
});
console.log(`[accounts] registered "${username}" (id ${account.id})`);
console.log(`[accounts] registered "${logText(username)}" (id ${logText(account.id)})`);
return {account};
};
@@ -738,9 +758,10 @@ const authenticateAsync = async (username, password) => {
};
// 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 problem = passwordProblem(password);
const problem = passwordProblem(password, account.username);
if (problem) {
return problem;
}
@@ -789,7 +810,7 @@ const rename = (account, username, anyName = false) => {
db.prepare("DELETE FROM retired_names WHERE name_key = ?").run(newKey);
}
db.prepare("UPDATE accounts SET username = ?, username_key = ? WHERE id = ?").run(username, newKey, account.id);
console.log(`[accounts] renamed "${account.username}" to "${username}" (id ${account.id})`);
console.log(`[accounts] renamed "${logText(account.username)}" to "${logText(username)}" (id ${logText(account.id)})`);
byKey.delete(oldKey);
account.username = username;
byKey.set(newKey, account);
@@ -848,7 +869,7 @@ const remove = account => {
}
}
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).
+50 -10
View File
@@ -4,8 +4,12 @@ const accounts = require("./accounts.js");
const bans = require("./bans.js");
const captcha = require("./captcha.js");
const defpacks = require("./defpacks.js");
const devices = require("./devices.js");
const config = require("../config.js");
const roles = require("./roles.js");
const dens = require("./dens.js");
const itemControl = require("./itemcontrol.js");
const customItems = require("./customitems.js");
const limits = require("./limits.js");
const world = require("./world.js");
const {addClothing, sendClothingAdded, isUint} = require("./player.js");
@@ -21,6 +25,7 @@ const MAX_FAVOURITES = 200; // finder items remembered per account
const STARTER_ANIMALS = [1, 4, 5, 6, 7, 8, 13, 18, 24];
let catalog = null;
let catalogVersion = -1; // defpacks.customVersion() it was built at: staff add items as the server runs
const buildCatalog = () => [
...defpacks.clothingIds().map(id => {
@@ -35,13 +40,23 @@ const buildCatalog = () => [
// `favourites` is an account's finderGiven, or null: with nothing typed, the
// items that account took most often come first, the latest first among
// equals. (The in-game finder says whose search it is.)
const search = (params, favourites = null) => {
catalog = catalog || buildCatalog();
// equals. (The in-game finder says whose search it is.) items locked out of
// the finder (lib/itemcontrol.js) are left out, unless `seesLocked`: then
// 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 words = (params.get("q") || "").toLowerCase().split(/\s+/).filter(Boolean);
const matches = catalog.filter(entry => (kind === "all" || entry.kind === kind)
&& words.every(word => entry.search.includes(word) || String(entry.id) === word));
&& 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)));
if (words.length === 0 && favourites) {
const taken = entry => favourites[`${entry.kind}:${entry.id}`] || {count: 0, at: 0};
@@ -49,7 +64,10 @@ const search = (params, favourites = null) => {
}
return {
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} : {})};
}),
};
};
@@ -57,11 +75,19 @@ const search = (params, favourites = null) => {
// digits alone are a colour id
const HEX_COLOURS = /^#[0-9a-f]{6}([\s,]+#[0-9a-f]{6}){0,3}$/i;
const give = body => {
// `seesLocked`: who asks may take items locked out of the finder.
const give = (body, seesLocked = false) => {
const account = accounts.byName(body.username);
if (!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);
if (body.kind === "clothing") {
const def = defpacks.itemDef(body.id);
@@ -125,6 +151,11 @@ const give = body => {
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
// 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.
@@ -142,7 +173,8 @@ const handle = async (route, params, body, from) => {
case "GET /api/search": {
const asking = accounts.byName(params.get("username") || "");
const known = asking && (from.local || holderOf(params.get("token")) === asking);
return {status: 200, body: search(params, known ? asking.finderGiven : null)};
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":
if (!from.local) {
@@ -157,7 +189,7 @@ const handle = async (route, params, body, from) => {
if (!from.local && !givesPerMinute.allow(owner.id)) {
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": {
const account = accounts.byName((body || {}).username);
@@ -204,13 +236,21 @@ const handle = async (route, params, body, from) => {
}
const ban = world.moderation.banOf(account);
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}
: 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": {
if (bans.addressBan(from.address)) {
return {status: 403, body: {error: "address_banned"}};
}
// 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} = body || {};
// the terms and the privacy policy, and old enough to agree to them:
// said by the one signing up, on the page or in the client.
@@ -247,4 +287,4 @@ const handle = async (route, params, body, from) => {
}
};
module.exports = {handle};
module.exports = {handle, search};
+2 -1
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
// adventures. the engine is in the client (quest/QuestManager): it places
// the actors named in the room file and plays them. what happens when was
// decided by scripts on the official server, which no file holds, so each
@@ -145,7 +146,7 @@ module.exports = ({enterRoom, joinRoom, tell}) => {
family[1](tools(session, quest), key, ...args);
}
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)}"`);
}
};
+2
View File
@@ -35,6 +35,8 @@ const cdn = require("./cdn.js");
// in the order they are listed and drawn.
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: "moderator", label: "Moderator", tag: {def: 64, media: 20002, bit: 9}},
{id: "contributor", label: "Contributor", tag: {def: 65, media: 20003, bit: 10}},
+2 -1
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js");
const limits = require("./limits.js");
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);
record({account, address: addressKey, action: "appeal"});
console.log(`[bans] "${account.username}" appealed`);
console.log(`[bans] "${logText(account.username)}" appealed`);
return {appeal: appealOf(account)};
};
+8 -3
View File
@@ -40,7 +40,7 @@ const requestsPerTenMinutes = limits.limiter(20, 600000);
// and reads a hosted party's name as three string ids.
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,
// online, accountType, buddyFlag, avatarName, perUserAvId, partyTimeLeft]
const sendStatus = (to, account, buddyFlag) => {
@@ -195,11 +195,16 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
// gets [roomName, displayName, displayNameStringId, cannotGoThere]; an
// empty room means offline. the last field greys out the card's "go to"
// button (BuddyCard.checkBuddyRoomAgainstMine), so it is 0: every room
// here can be walked into. someone who blocked the asker looks offline.
// 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]) {
const target = findOnline(username);
if (target && target.room && !target.account.blocked.includes(key(session.account))) {
session.sendXt("br", -1, target.room.name, roomTitle(target.room), 0, 0);
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 {
session.sendXt("br", -1, "", "", 0, 0);
+7 -3
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
@@ -79,7 +80,7 @@ const verify = async (answer, from, action) => {
result = await response.json();
}
catch (err) {
console.log(`[captcha] cloudflare did not answer: ${err.message}`);
console.log(`[captcha] cloudflare did not answer: ${logText(err.message)}`);
return "captcha_unavailable";
}
// an answer made for another form is no answer for this one. cloudflare's
@@ -103,8 +104,11 @@ const check = async (body, from, action, account) => {
return verify(body.captcha, from, action);
};
// a page's security policy, letting the widget in when it is on.
const policy = csp => (on ? `${csp.replace("script-src ", `script-src 'self' ${ORIGIN} `)}; frame-src ${ORIGIN}` : csp);
// a page's security policy: public/captcha.js always (the page calls it even
// when off), and the widget too when it is on.
const policy = csp => (on
? `${csp.replace("script-src ", `script-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
// script and the key: cloudflare keeps .js files for hours, whatever the
+6 -5
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
@@ -69,7 +70,7 @@ const measure = async folder => {
};
measure(config.cacheDir).then(() => {
if (cacheBytes > config.maxCacheBytes) {
console.log(`[cdn] the cache holds ${Math.round(cacheBytes / 1048576)} MB, over its limit: new files are served but not kept (AJ_MAX_CACHE_MB)`);
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);
}
console.log(`[cdn] ${res.status} ${relPath}`);
console.log(`[cdn] ${logText(res.status)} ${logText(relPath)}`);
return null;
}
const body = Buffer.from(await res.arrayBuffer());
@@ -99,10 +100,10 @@ const download = async (relPath, file) => {
const tmp = `${file}.${process.pid}.tmp`;
await fs.promises.writeFile(tmp, body);
await fs.promises.rename(tmp, file);
console.log(`[cdn] cached ${relPath} (${body.length} bytes)`);
console.log(`[cdn] cached ${logText(relPath)} (${logText(body.length)} bytes)`);
}
catch (err) {
console.log(`[cdn] could not cache ${relPath}: ${err.message}`);
console.log(`[cdn] could not cache ${logText(relPath)}: ${logText(err.message)}`);
}
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"
// for now, and is tried again the next time the file is asked for.
inFlight.set(relPath, download(relPath, file).catch(err => {
console.log(`[cdn] could not fetch ${relPath}: ${err.message}`);
console.log(`[cdn] could not fetch ${logText(relPath)}: ${logText(err.message)}`);
return null;
}).finally(() => inFlight.delete(relPath)));
}
+3 -2
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const fs = require("fs");
const path = require("path");
@@ -142,11 +143,11 @@ const rules = () => {
parsed.push({line, clauses});
}
else {
console.log(`[filter] lib/chat-filter.txt: a rule that could not be read was left out: ${line}`);
console.log(`[filter] lib/chat-filter.txt: a rule that could not be read was left out: ${logText(line)}`);
}
}
kept = {mtime, rules: parsed};
console.log(`[filter] ${parsed.length} rules`);
console.log(`[filter] ${logText(parsed.length)} rules`);
}
return kept.rules;
};
+68 -11
View File
@@ -3,7 +3,8 @@
const accounts = require("./accounts.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
// before deciding anything; nothing else reads it. lines older than
// config.chatLogDays are deleted, and an account's lines go when the
@@ -26,6 +27,11 @@ const SCHEMA = `
const CHAT = "chat";
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 MAX_TEXT = 600;
const PAGE = 100;
@@ -40,28 +46,69 @@ const prune = () => {
const load = () => {
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();
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
// whisper to that player.
const record = (account, room, text, to = "") => {
if (config.chatLogDays <= 0) {
return;
}
db().prepare("INSERT INTO chat_log (at, account_id, username, room, kind, to_name, text) VALUES (?, ?, ?, ?, ?, ?, ?)")
.run(now(), account.id, account.username, String(room || ""), to ? WHISPER : CHAT, to, String(text).slice(0, MAX_TEXT));
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), 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
// to), by room, by words in them, and `before` an id for the next page.
const search = ({username = "", room = "", text = "", before = 0}) => {
// to, or sent to), by room, by words in them, by kind (one of KINDS, or
// "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 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)");
values.push(username, username);
}
@@ -87,9 +134,9 @@ const around = id => {
if (!line) {
return null;
}
const [same, values] = line.kind === WHISPER
? ["kind = ? AND ((username = ? AND to_name = ?) OR (username = ? AND to_name = ?))", [WHISPER, line.username, line.to_name, line.to_name, line.username]]
: ["kind = ? AND room = ?", [CHAT, line.room]];
const [same, values] = line.kind === CHAT
? ["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 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)};
@@ -99,9 +146,19 @@ const around = id => {
// 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);
// 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.
const forget = account => {
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};
+2 -1
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js");
// 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));
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);
+396 -1
View File
@@ -2,10 +2,15 @@
const accounts = require("./accounts.js");
const chatlog = require("./chatlog.js");
const customItems = require("./customitems.js");
const itemControl = require("./itemcontrol.js");
const modNotes = require("./modnotes.js");
const defpacks = require("./defpacks.js");
const disguises = require("./disguises.js");
const dens = require("./dens.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");
// things players can do by typing "!something" in the chat box, for what
@@ -47,7 +52,7 @@ const MAX_AGAIN = 100;
// A hosted party's own name is three string ids, no use outside the game.
const roomTitle = room => (room.partyHost ? `${room.partyHost.username}'s party` : room.displayName);
module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideBlocked, refreshForOthers, travel, reloadRoom, buyAgain, ask}) => {
module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideBlocked, refreshForOthers, travel, reloadRoom, buyAgain, ask, staffMove, setInvisible, staffModeration}) => {
// A plain message box with an OK button.
const tell = (session, text) => session.sendXt("xtl", -1, String(text).replace(/%/g, " percent"));
@@ -500,6 +505,392 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
};
// ---- staff commands (lib/roles.js). each checks the role's permission on
// every use, and what is done is written down under the staff member's
// name, as in the moderator panel. to anyone without the permission they
// are plain chat, like any other "!word" the server does not know.
const MAX_STAFF_HOURS = 24 * 365 * 10;
const MAX_WARNING = 200;
const MAX_WARNINGS_SHOWN = 5;
const MAX_ITEMS_LISTED = 8;
const MAX_NOTES_SHOWN = 5; // "!notes": the latest, in one message box
const staffMay = (session, permission) => {
const moderation = staffModeration();
return roles.can(session.account, permission, moderation.banRemaining(session.account) !== 0);
};
// the longest run of leading words naming an online player, and the words
// after it: usernames may have spaces in them.
const splitName = words => {
for (let count = words.length; count > 0; count--) {
const target = findOnline(words.slice(0, count).join(" "));
if (target) {
return {target, rest: words.slice(count)};
}
}
return {target: null, rest: words};
};
// the same for any account, online or not.
const splitAccount = words => {
for (let count = words.length; count > 0; count--) {
const account = accounts.byName(words.slice(0, count).join(" "));
if (account) {
return account;
}
}
return null;
};
// finds the player the command is about, and checks the staff member may
// act on them (`onStaff`: also on staff below their rank).
const withTarget = (session, words, usage, onStaff, run) => {
const {target, rest} = splitName(words);
if (!words.length) {
tell(session, usage);
}
else if (!target) {
tell(session, `${words.join(" ")} is not online.`);
}
else if (target === session) {
tell(session, "That is you.");
}
else if (onStaff && !roles.outranks(session.account, target.account)) {
tell(session, "Staff of your rank or above are for someone higher up to deal with.");
}
else {
run(target, rest);
}
};
const logged = (session, action, target, detail = "") =>
modlog.record(session.account.username, `${action} (in game)`, target.account.username, detail);
// what lib/itemcontrol.js tells about items taken.
const worldForItems = {itemsTaken: (...args) => require("./world.js").itemsTaken(...args)};
const lockCommand = (session, words, locked) => {
const [kind, id] = [(words[0] || "").toLowerCase(), words[1]];
if (words.length !== 2) {
tell(session, `Use: !${locked ? "lock" : "unlock"} clothing|den ID`);
return;
}
const result = itemControl.setLocked(kind, id, locked);
tell(session, result.error || result.ok);
if (result.ok) {
modlog.record(session.account.username, locked ? "item locked (in game)" : "item unlocked (in game)", "", `${kind} ${id}`);
}
};
// an account named by the first words (a name may have spaces: the longest
// that is one), and the words after it.
const accountAndRest = words => {
for (let count = words.length; count > 0; count--) {
const account = accounts.byName(words.slice(0, count).join(" "));
if (account) {
return {account, rest: words.slice(count)};
}
}
return {account: null, rest: words};
};
const staffCommands = {
// "!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.");
},
},
// "!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);
},
},
// "!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 {
// 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.
@@ -509,6 +900,10 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
}
const typed = text.slice(PREFIX.length).trim().split(/\s+/);
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)) {
asTyped[name](session, typed.slice(1));
return null;
+355
View File
@@ -0,0 +1,355 @@
"use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js");
const defpacks = require("./defpacks.js");
// items the staff make while the server runs, with no restart of the server
// or of anybody's game. each is an existing item's art (the clothing piece
// or den item it is made from) under an id, name, price and colours of its
// own. the server's tables and the packs new games fetch have it at once
// (defpacks.setCustomItem); games already playing are sent its def row
// ("xdi", which the patched client adds to its tables), and so is every game
// at login, in case it was started before the item was made.
//
// 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";
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
const db = () => accounts.database();
const now = () => Math.floor(Date.now() / 1000);
const baseDef = (kind, id) => (kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id));
// 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") {
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);
// "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 messages = entries => {
const out = [];
for (const kind of KINDS) {
// a picture waiting for a moderator is not shown yet
const rows = entries.filter(entry => entry.kind === kind && !entry.pending)
.map(entry => ({...rowOf(entry), name: entry.name, art: entry.artPending ? "" : entry.art || "", artMode: entry.artMode || "sticker"}));
for (let at = 0; at < rows.length; at += CHUNK) {
out.push([kind, JSON.stringify(rows.slice(at, at + CHUNK)).replace(/%/g, "\\u0025")]);
}
}
return out;
};
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,
});
// 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");
}
};
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;
const entry = {kind, id, base: baseId, colors: [], ...values, createdBy: String(by), createdAt: now(), ownerId, artMode: "sticker", pending, artPending: false,
seq: made++};
db().prepare("INSERT INTO custom_items (kind, id, base, name, cost, members, colors, in_shop, created_by, created_at, owner_id, pending) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
.run(kind, id, baseId, entry.name, entry.cost, entry.members ? 1 : 0, entry.colors.join(","), entry.inShop ? 1 : 0, entry.createdBy, entry.createdAt, ownerId, pending ? 1 : 0);
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);
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);
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);
return {item: entry};
};
const list = () => KINDS.flatMap(kind => [...items.get(kind).values()])
.sort((one, other) => other.seq - one.seq);
module.exports = {
KINDS,
FIRST_ID,
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);
},
// every custom item, for a game logging in.
sendAll(session) {
for (const params of messages(list().reverse().filter(entry => !entry.pending))) {
session.sendXt("xdi", -1, ...params);
}
},
// lib/world.js says how to reach every game playing.
connect(broadcastXt) {
broadcast = broadcastXt;
},
};
+95 -5
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const zlib = require("zlib");
const amf3 = require("./amf3.js");
const cdn = require("./cdn.js");
@@ -175,7 +176,39 @@ const withOurName = 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;
};
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
// official tracks.
@@ -236,8 +269,8 @@ const SHARED_CHANGES = new Map([
[DEF_ROOM, withRestoredRooms],
[DEF_PARTY, withRestoredParties],
[DEF_DEN_ROOM, withoutPrices(DEF_DEN_ROOM, withAddedDens)],
[DEF_DEN_ITEM, withoutPrices(DEF_DEN_ITEM, withExtraMusic)],
[DEF_ITEM, withoutPrices(DEF_ITEM)],
[DEF_DEN_ITEM, withoutPrices(DEF_DEN_ITEM, pack => withCustomRows(DEF_DEN_ITEM)(withExtraMusic(pack)))],
[DEF_ITEM, withoutPrices(DEF_ITEM, withCustomRows(DEF_ITEM))],
[DEF_DIAMOND, withoutPrices(DEF_DIAMOND)],
[DEF_PET, withoutPrices(DEF_PET)],
[DEF_LOCALIZATION_EN, withAddedStrings],
@@ -369,7 +402,7 @@ const loadOptional = async id => {
return await load(id);
}
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 [];
}
};
@@ -439,11 +472,68 @@ const init = async () => {
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);
clientPackBodies.delete(pack);
clientPackBodies.delete(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);
clientPackBodies.delete(pack);
customVersion++;
};
module.exports = {
init,
setCustomItem,
unsetCustomItem,
// the custom items on sale, the newest first.
customShopIds: kind => [...customInShop[kind]].reverse(),
customVersion: () => customVersion,
load,
itemDef: id => itemDefs.get(Number(id)),
clothingIds: () => clothingIds,
+2 -1
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js");
const achievements = require("./achievements.js");
const config = require("../config.js");
@@ -260,7 +261,7 @@ const handlers = ({others, findOnline}) => {
const item = giveDenItem(account, masterpieces.DEN_ITEM, frame);
item.image = String(paintingId);
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);
sendDenItems(session);
};
+400
View File
@@ -0,0 +1,400 @@
"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.
//
// any one of them is a match: someone who edits /etc/machine-id or deletes
// MachineGuid still has the same disks and the client's own id. the network
// card's address alone (MAC_KIND) is a weak match: 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 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 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 keeps this computer out, or null. a network card's address
// alone keeps nobody out (see the top).
const banOf = device => {
for (const entry of device.ids) {
if (STRONG.includes(entry.kind) && banned.has(tag(entry))) {
return banned.get(tag(entry));
}
}
return null;
};
// 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 => {
for (const entry of idsOf(account)) {
if (STRONG.includes(entry.kind) && entry.last > now() - DAYS_KEPT * 86400 && banned.has(tag(entry))) {
return banned.get(tag(entry));
}
}
return null;
};
const alert = (account, kind, detail) => {
const 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 sharers = new Set();
for (const entry of device.ids.filter(one => STRONG.includes(one.kind))) {
for (const id of holders.get(tag(entry)) || []) {
const other = id === account.id ? null : accounts.byId(id);
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 any of this one's computers: [{username,
// kinds: [kind], weak: true when only a network card}], most in common first.
const alts = account => {
const found = new Map(); // account id -> Set of kinds
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, new Set());
}
found.get(id).add(entry.kind);
}
}
}
return [...found].map(([id, kinds]) => ({account: accounts.byId(id), kinds: [...kinds]}))
.filter(entry => entry.account)
.map(entry => ({username: entry.account.username, kinds: entry.kinds, weak: entry.kinds.every(kind => kind === MAC_KIND)}))
.sort((one, other) => Number(one.weak) - Number(other.weak) || other.kinds.length - one.kinds.length || one.username.localeCompare(other.username));
};
// 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.some(id => STRONG.includes(id.split(":")[0]))) {
return {error: "No hardware IDs known for them."};
}
if (ids.filter(id => STRONG.includes(id.split(":")[0])).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.
const accountsUnder = ban => {
const ids = new Set(ban.ids.filter(id => STRONG.includes(id.split(":")[0])));
const found = new Set();
for (const id of ids) {
for (const accountId of holders.get(id) || []) {
found.add(accountId);
}
}
return [...found].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;
};
// 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);
};
module.exports = {load, read, banOf, banOfAccount, seen, alts, knownFor, banAccount, accountsUnder, unban, list, idsFor, bansOfAccount, search, bannedId, alerts, alertsOf, forget, clientHash};
+11 -2
View File
@@ -1,10 +1,12 @@
"use strict";
const {logText} = require("./logtext.js");
const fs = require("fs");
const path = require("path");
const accounts = require("./accounts.js");
const achievements = require("./achievements.js");
const chatFilter = require("./chatfilter.js");
const chatlog = require("./chatlog.js");
const defpacks = require("./defpacks.js");
const dens = require("./dens.js");
const limits = require("./limits.js");
@@ -96,7 +98,11 @@ module.exports = ({findOnline, blocks}) => {
0, // secondary type
senderType,
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.)
card.gift && card.gift.type === TYPE_CLOTHING ? `item|${card.gift.def}` : "",
card.secret ? SECRET_VALENTINE : 0,
];
};
@@ -260,7 +266,8 @@ module.exports = ({findOnline, blocks}) => {
const rule = chatFilter.broken(clean(message || ""));
if (rule) {
chatFilter.warn(session);
console.log(`[filter] ${account.username} in a Jam-a-Gram to ${to.username}: "${clean(message || "")}" (${rule})`);
console.log(`[filter] ${logText(account.username)} in a Jam-a-Gram to ${logText(to.username)}: "${logText(clean(message || ""))}" (${logText(rule)})`);
chatlog.recordTo(account, chatlog.JAMAGRAM, to.username, chatlog.NOT_SENT + clean(message || ""));
reply(FAILED);
return;
}
@@ -279,6 +286,8 @@ module.exports = ({findOnline, blocks}) => {
return;
}
deliver(to, {from: account.username, fromId: account.id, card: Number(card), stamp: Number(stamp), msg: clean(message || ""), gift});
// for the panels (lib/chatlog.js), as typed chat is.
chatlog.recordTo(account, chatlog.JAMAGRAM, to.username, clean(message || "") + (gift ? " [with a gift]" : ""));
achievements.add(account, achievements.VARS.jamAGramsSent);
if (gift) {
achievements.add(account, achievements.VARS.giftsSent);
+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 bans = require("./bans.js");
const chatlog = require("./chatlog.js");
const devices = require("./devices.js");
const masterpieces = require("./masterpieces.js");
const support = require("./support.js");
const world = require("./world.js");
// an account deleted for good, by its owner (lib/manage.js) or by the admin
// (lib/panel.js), and what was kept about it elsewhere with it: its chat
// lines, its appeal, its feedback and username requests, and the paintings
// 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
// 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.
@@ -20,6 +22,7 @@ module.exports = account => {
}
bans.forget(account);
chatlog.forget(account);
devices.forget(account);
support.forget(account);
accounts.remove(account);
};
+212 -23
View File
@@ -1,16 +1,23 @@
"use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto");
const fs = require("fs");
const http = require("http");
const https = require("https");
const path = require("path");
const accounts = require("./accounts.js");
const 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 bans = require("./bans.js");
const captcha = require("./captcha.js");
const cdn = require("./cdn.js");
const config = require("../config.js");
const devices = require("./devices.js");
const defpacks = require("./defpacks.js");
const limits = require("./limits.js");
const manage = require("./manage.js");
@@ -138,6 +145,92 @@ const formParts = (contentType, body) => {
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);
};
// 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 data = Buffer.isBuffer(body) ? body : Buffer.from(typeof body === "string" ? body : JSON.stringify(body));
res.writeHead(status, {"Content-Type": type, "Content-Length": data.length});
@@ -155,6 +248,8 @@ const MISSING_ASSET_SECONDS = 600; // how long a client may keep the CDN's "no s
const cacheMisses = limits.limiter(config.cacheMissesPerTenMinutes, TEN_MINUTES_MS); // files fetched from the official CDN for one address
const 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 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})$/;
// where clients ask for the HUD artwork; ours is a changed copy.
@@ -371,7 +466,7 @@ const renameAndSignIn = (res, body, from) => {
manage.forget(account);
accounts.recordLogin(account, "launcher", from.address);
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);
const token = accounts.issueToken(account);
send(res, 200, {auth_token: token, refresh_token: token, device_token: entry.deviceToken});
@@ -383,36 +478,65 @@ const authenticate = async (req, res, from) => {
renameAndSignIn(res, body, from);
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. 1.2 shows "The server refused
// the login (426)", and still offers its update.
const device = devices.read(body.device);
if (!device && config.requireDevice) {
send(res, 426, {error_code: 101, error: "client_outdated"});
return;
}
const accountKey = String(body.username).trim().toLowerCase();
if (!from.local && failuresByAddress.blocked(from.key)) {
send(res, 429, {error_code: 429, error: "too_many_attempts"});
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
// 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) {
send(res, captchaProblem === "captcha_unavailable" ? 503 : 401, {error_code: 101, error: captchaProblem});
return;
}
const account = byRefresh
? accounts.byToken(body.refresh_token)
: await accounts.authenticateAsync(body.username, body.password);
const account = await accounts.authenticateAsync(body.username, body.password);
if (!account) {
failuresByAddress.record(from.key);
if (!byRefresh) {
// A wrong password shows in the account's own login history.
const tried = accounts.byName(accountKey);
if (tried) {
accounts.recordLogin(tried, "launcher", from.address, false);
accounts.save(tried);
}
// A wrong password shows in the account's own login history.
const tried = accounts.byName(accountKey);
if (tried) {
accounts.recordLogin(tried, "launcher", from.address, false);
accounts.save(tried);
}
// error_code 100 = expired refresh token, 101 = wrong credentials
send(res, 401, {error_code: byRefresh ? 100 : 101});
// error_code 101 = wrong credentials
send(res, 401, {error_code: 101});
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
// 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
@@ -430,6 +554,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});
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
// still nobody gets in. the launcher shows this as a failed sign-in.
if (account.locked) {
@@ -466,10 +599,13 @@ const authenticate = async (req, res, from) => {
send(res, 401, {error_code: 101, error: "name_rejected", rename_ticket: renameTicket(account, deviceToken)});
return;
}
if (device) {
devices.seen(account, device, other => world.moderation.banRemaining(other) !== 0);
}
if (!byRefresh) {
accounts.recordLogin(account, "launcher", from.address);
accounts.save(account);
}
accounts.save(account);
// the custom client's advanced settings; the official launcher sends none.
accounts.setLoginChoices(account, body.login_choices);
const token = byRefresh ? body.refresh_token : accounts.issueToken(account);
@@ -493,6 +629,10 @@ const player = (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 route = `${req.method} ${url.pathname}`;
@@ -532,10 +672,20 @@ const handle = async (req, res) => {
send(res, 404, "Not found", "text/plain");
return;
}
if (url.pathname === "/admin/api/itemart") {
res.setHeader("Cache-Control", "no-store");
await itemArtUpload(req, res, url, from, null, panel.signedIn);
return;
}
await panel.handle(req, res, url, from, {send, readJson});
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) {
await manage.handle(req, res, url, from, {send, readJson});
return;
@@ -543,6 +693,11 @@ const handle = async (req, res) => {
// and the moderator panel (lib/modpanel.js), which is there for anyone to
// reach: its moderators are players, wherever they are.
if (isMod && url.pathname === "/mod/api/itemart") {
res.setHeader("Cache-Control", "no-store");
await itemArtUpload(req, res, url, from, modpanel.signedInAs);
return;
}
if (isMod) {
await modpanel.handle(req, res, url, from, {send, readJson});
return;
@@ -568,6 +723,39 @@ const handle = async (req, res) => {
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/")) {
// the item finder's API changes accounts, so other sites open in a
// browser on this machine must not be able to call it.
@@ -711,7 +899,7 @@ const handle = async (req, res) => {
if (trace ? config.logPackets : from.local || errorReports.allow(from.key)) {
const again = trace ? "" : repeatedError(`${section} ${message}`);
if (again !== null) {
console.log(`[${trace ? "client-trace" : "client-error"}] (${section}) ${message}${again}`);
console.log(`[${logText(trace ? "client-trace" : "client-error")}] (${logText(section)}) ${logText(message)}${logText(again)}`);
if (!trace) {
keepClientError(`${new Date().toISOString()} (${section}) ${message}${again}\n`);
}
@@ -734,7 +922,7 @@ const handle = async (req, res) => {
return;
}
const parts = formParts(req.headers["content-type"], await readBody(req, masterpieces.MAX_IMAGE_BYTES + 16 * 1024));
const uuid = masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image"));
const uuid = await masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image"));
send(res, 200, uuid ? {success: true, uuid} : {success: false});
return;
}
@@ -750,13 +938,13 @@ const handle = async (req, res) => {
}
if (req.method !== "GET" && req.method !== "HEAD") {
console.log(`[http] unhandled ${route}`);
console.log(`[http] unhandled ${logText(route)}`);
send(res, 404, {error: "not_found"});
return;
}
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;
@@ -822,7 +1010,7 @@ const handle = async (req, res) => {
res.setHeader("Cache-Control", `public, max-age=${MISSING_ASSET_SECONDS}`);
}
else {
console.log(`[http] 404 ${url.pathname}`);
console.log(`[http] 404 ${logText(url.pathname)}`);
}
send(res, 404, "Not found", "text/plain");
return;
@@ -834,7 +1022,8 @@ const handle = async (req, res) => {
const start = () => new Promise((resolve, reject) => {
const onRequest = (req, res) => {
handle(req, res).catch(err => {
console.log(`[http] ${req.method} ${req.url} failed: ${err.message}`);
// 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) {
send(res, 500, {error: "server_error"});
}
@@ -883,7 +1072,7 @@ const start = () => new Promise((resolve, reject) => {
});
server.once("error", reject);
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);
});
});
+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 = 300 * 1024; // a picture kept
const MAX_UPLOAD = 2 * 1024 * 1024; // one sent (a BMP is bigger than the PNG it becomes)
const MAX_SIDE = 512;
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};
+141
View File
@@ -0,0 +1,141 @@
"use strict";
const accounts = require("./accounts.js");
const customItems = require("./customitems.js");
const defpacks = require("./defpacks.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)};
});
// 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();
}
return {ok: `Deleted ${entry.name} (${kind === "den" ? "den item" : "clothing"} ${entry.id})${count ? `, and took ${count} from players` : ""}.`};
};
module.exports = {isLocked, setLocked, lockedList, take, deleteCustom};
+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};
+38 -12
View File
@@ -1,5 +1,9 @@
"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 fs = require("fs");
const path = require("path");
@@ -149,6 +153,11 @@ const profile = (account, from) => {
animalType: avatar ? avatar.type : null,
items: account.items.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,
buddies: account.buddies.length,
banned: null,
@@ -179,7 +188,7 @@ const profile = (account, from) => {
// hash, the 2FA secret, device passes), and what other tables hold of it.
// what others wrote about it (reports, a moderator's notes) is not theirs
// to be handed, and is not here.
const SECRET_FIELDS = ["salt", "hash", "totp", "totpSetup", "devices"];
const SECRET_FIELDS = ["salt", "hash", "totp", "totpSetup", "devices", "modNotes"];
const dataOf = account => ({
exportedAt: new Date().toISOString(),
server: config.baseUrl,
@@ -250,7 +259,7 @@ const act = (account, body, req, from, res) => {
}
delete account.nameRejected;
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."};
}
// one for each account, ever: an answer that wants a follow-up says
@@ -267,12 +276,14 @@ const act = (account, body, req, from, res) => {
if (!passwordAgain(account, body.current)) {
return {error: "Wrong password."};
}
if (accounts.setPassword(account, body.password)) {
return {error: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."};
const passwordProblem = accounts.setPassword(account, body.password);
if (passwordProblem) {
return {error: passwordProblem === "weak_password" ? "That password is too easy to guess: it is a common one, or has your username in it."
: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."};
}
world.moderation.actions.kick(account);
signOutOthers(account, req);
console.log(`[account] "${account.username}" changed their password from ${from.address}`);
console.log(`[account] "${logText(account.username)}" changed their password from ${logText(from.address)}`);
return {ok: "Password changed."};
}
case "requestName": {
@@ -293,7 +304,7 @@ const act = (account, body, req, from, res) => {
world.moderation.actions.kick(account);
}
accounts.save(account);
console.log(`[account] "${account.username}" ${account.locked ? "locked" : "unlocked"} from ${from.address}`);
console.log(`[account] "${logText(account.username)}" ${logText(account.locked ? "locked" : "unlocked")} from ${logText(from.address)}`);
return {ok: account.locked ? "Locked." : "Unlocked."};
}
case "feature": {
@@ -322,11 +333,12 @@ const act = (account, body, req, from, res) => {
const recovery = totp.confirm(account, body.code);
if (!recovery) {
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.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};
}
// turning it off: the password and a code (or a recovery code).
@@ -344,7 +356,7 @@ const act = (account, body, req, from, res) => {
totp.turnOff(account);
accounts.save(account);
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."};
}
case "forgetDevices":
@@ -352,6 +364,20 @@ const act = (account, body, req, from, res) => {
accounts.save(account);
return {ok: "Trusted devices forgotten."};
// 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": {
// typed words others read: not while they cannot chat.
if (world.moderation.isSilenced(account)) {
@@ -365,7 +391,7 @@ const act = (account, body, req, from, res) => {
// each other (lib/chat-filter.txt).
const rule = chatFilter.broken(bio);
if (rule) {
console.log(`[filter] "${account.username}" bio not saved (${rule}): ${JSON.stringify(bio)}`);
console.log(`[filter] "${logText(account.username)}" bio not saved (${logText(rule)}): ${logText(JSON.stringify(bio))}`);
return {error: "Your bio has words that are not allowed here."};
}
account.bio = bio;
@@ -446,7 +472,7 @@ const act = (account, body, req, from, res) => {
world.disconnect(account);
signOutOthers(account, null);
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};
}
default:
@@ -601,4 +627,4 @@ const handle = async (req, res, url, from, web) => {
// called when an account's name changes or it is deleted: its page sessions end.
const forget = account => signOutOthers(account, null);
module.exports = {handle, forget};
module.exports = {handle, forget, signedInAs};
+19 -3
View File
@@ -6,6 +6,7 @@ const path = require("path");
const config = require("../config.js");
const accounts = require("./accounts.js");
const limits = require("./limits.js");
const imageModeration = require("./image-moderation.js");
// masterpieces: paintings from the Art Studio, framed and hung in a den
// (client side: game.artStudioPainting.ArtStudioPainting, the same in
@@ -181,16 +182,21 @@ const looksLikeJpeg = image => {
return false;
};
// step 2. returns the new painting's id, or null when the token is not
// step 2. resolves to the new painting's id, or null when the token is not
// good, the picture is not a JPEG of a sane size, or the account has posted
// too many.
const upload = (token, image) => {
const upload = async (token, image) => {
const entry = typeof token === "string" ? tokens.get(token) : null;
tokens.delete(token);
if (!entry || entry.expires < Date.now() || !Buffer.isBuffer(image) || image.length > MAX_IMAGE_BYTES || !looksLikeJpeg(image)
|| !uploadsPerHour.allow(entry.account)) {
return null;
}
const safety = await imageModeration.scan(image);
if (safety.blocked) {
console.log(`[masterpieces] rejected unsafe upload from account ${entry.account}`);
return null;
}
// one painting at a time is between the easel and the frame.
for (const painting of [...known.values()]) {
if (painting.creator === entry.account && painting.status === UPLOADED) {
@@ -319,6 +325,16 @@ const list = status => [...known.values()].filter(painting => painting.status ==
return {id: painting.id, creator: maker ? maker.username : "(deleted account)", createdAt: painting.createdAt, frame: painting.frame, likes: painting.likes.length};
});
// 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))};
};
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
@@ -327,7 +343,7 @@ const frameList = listId =>
([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null);
module.exports = {
load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, frameList,
load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, frameList,
needsReview, setNeedsReview, madeBy,
PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES,
};
+92 -3
View File
@@ -75,9 +75,27 @@ const messagesPerMinute = limits.limiter(900, 60000);
// the "start" message a game waits for once it has said it is ready.
const START = {
seed: () => [serial()],
seedAndPlayers: game => [serial(), game.players.length],
// 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])],
};
// 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.
function serial() {
return 1 + Math.floor(Math.random() * 1000000);
@@ -93,7 +111,10 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
defpacks.stringId(game.title) || defpacks.stringId(FALLBACK_TITLE),
game.swf, // extName
game.swf, // swfName
game.buddy ? 2 : 1, game.buddy ? 2 : 1, // min and max players
// 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
game.type,
// the game card: the title picture on the "play" popup (not known), and
@@ -134,6 +155,13 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
}
session.game = null;
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
// 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
@@ -191,6 +219,59 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
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
// `match` is). it runs in a window over whatever room each is in.
const startMatch = (def, sender, target) => {
@@ -451,7 +532,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
},
// MinigameManager.launchGame: [gameDefId, multiplayer, proModeId, ?].
mj(session, roomId, [gameDefId]) {
mj(session, roomId, [gameDefId, multiplayer]) {
leave(session); // a game left without a word, if any
const def = games.get(Number(gameDefId));
if (!def || def.ready === false || def.buddy || !session.room) {
@@ -461,6 +542,10 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
tell(session, "That game is not ready on this server yet.");
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 music = session.room.customMusicDef; // the client takes this from every room join
if (def.type !== IN_ROOM) {
@@ -490,6 +575,10 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
matchMessage(session, game, String(word), params);
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 own = game.def.tickets ? carnival : MESSAGES[game.def.swf];
if (own && Object.hasOwn(own, word)) {
+102 -1
View File
@@ -4,6 +4,7 @@ const accounts = require("./accounts.js");
const achievements = require("./achievements.js");
const bans = require("./bans.js");
const dens = require("./dens.js");
const config = require("../config.js");
const {CURRENCIES} = require("./player.js");
// 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.
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);
// 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};
};
// 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();
// 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.
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 = {
kick(target) {
@@ -171,6 +214,51 @@ module.exports = ({findOnline}) => {
notify(session, text);
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
@@ -178,7 +266,20 @@ module.exports = ({findOnline}) => {
const refuse = reply => session => session.sendXt(reply, -1, 0);
const handlers = {fk: refuse("fk"), fb: refuse("fb"), fs: refuse("fs"), fm: refuse("fm"), fg: refuse("fg"), fp: refuse("fp"), fc() {}};
return {handlers, actions, banRemaining, banOf, isSilenced, silenceRemaining, PERMANENT};
// 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});
+7 -2
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js");
// what each moderator did in the moderator panel (lib/modpanel.js), for
@@ -23,9 +24,13 @@ const load = () => accounts.database().exec(SCHEMA);
const record = (by, action, target = "", detail = "") => {
accounts.database().prepare("INSERT INTO mod_log (at, by, action, target, detail) VALUES (?, ?, ?, ?, ?)")
.run(Math.floor(Date.now() / 1000), by, action, String(target), String(detail).slice(0, MAX_DETAIL));
console.log(`[mod] ${by}: ${action}${target ? ` "${target}"` : ""}`);
console.log(`[mod] ${logText(by)}: ${logText(action)}${logText(target ? ` "${target}"` : "")}`);
};
const recent = () => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log ORDER BY id DESC LIMIT ?").all(SHOWN);
module.exports = {load, record, recent};
// 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));
module.exports = {load, record, recent, about};
+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};
+329 -23
View File
@@ -4,15 +4,24 @@ const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const accounts = require("./accounts.js");
const admin = require("./admin.js");
const bans = require("./bans.js");
const captcha = require("./captcha.js");
const chatlog = require("./chatlog.js");
const config = require("../config.js");
const customItems = require("./customitems.js");
const itemControl = require("./itemcontrol.js");
const itemArt = require("./itemart.js");
const playerItems = require("./playeritems.js");
const defpacks = require("./defpacks.js");
const devices = require("./devices.js");
const limits = require("./limits.js");
const manage = require("./manage.js");
const masterpieces = require("./masterpieces.js");
const modlog = require("./modlog.js");
const modNotes = require("./modnotes.js");
const reports = require("./reports.js");
const roles = require("./roles.js");
const staff = require("./staff.js");
const stats = require("./stats.js");
const support = require("./support.js");
@@ -23,8 +32,9 @@ const world = require("./world.js");
// players, and no more. it is apart from the admin panel (lib/panel.js),
// which stays whoever runs the server's alone.
//
// A moderator is a game account the admin marked as one (`moderator` on the
// account). they sign in here with that account's username and password and
// A moderator is a game account the admin gave a staff role (lib/roles.js:
// helper, moderator or admin; `moderator` on an older account counts as a
// moderator), and what they may do here is what their role allows. they sign in here with that account's username and password and
// a code from their authenticator app, every time: an account without 2FA
// cannot sign in at all, and a trusted device is not taken for a code.
// being a moderator gives the account nothing in the game itself.
@@ -44,7 +54,7 @@ const SESSION_HOURS = 12;
const TEN_MINUTES_MS = 600000;
const MAX_BAN_HOURS = 24 * 365 * 10;
const MAX_MESSAGE_LENGTH = 200;
const MAX_FOUND = 50;
const MAX_RECENT_NOTES = 15;
const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS);
const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator
@@ -63,8 +73,7 @@ const cookieHeader = (token, maxAgeSeconds) =>
`${COOKIE}=${token}; Path=/mod; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
// may this account use the panel (still)?
const mayModerate = account => Boolean(account && account.moderator && totp.isOn(account) && !account.locked
&& world.moderation.banRemaining(account) === 0);
const mayModerate = account => Boolean(account && roles.isActiveStaff(account, world.moderation.banRemaining(account) !== 0));
const signedInAs = req => {
const token = cookieToken(req);
@@ -95,23 +104,23 @@ const playerRow = (account, playing) => {
banReason: ban ? ban.reason : "",
silenced: world.moderation.silenceRemaining(account),
nameRejected: Boolean(account.nameRejected),
moderator: Boolean(account.moderator),
moderator: Boolean(roles.roleOf(account)),
role: roles.roleOf(account),
warnings: (account.warnings || []).length,
playtime: account.playtime,
bio: account.bio,
discord: account.discord,
deviceBanned: devices.bannedId(account) !== 0,
};
};
const playing = () => new Map(world.players().map(player => [player.username, player.room || "(between rooms)"]));
// by name (lib/staff.js says in what order).
const findPlayers = query => {
const wanted = String(query || "").trim().toLowerCase().slice(0, 100);
const online = playing();
return accounts.all()
.filter(account => account.username.toLowerCase().includes(wanted))
.sort((a, b) => Number(online.has(b.username)) - Number(online.has(a.username)) || a.username.localeCompare(b.username))
.slice(0, MAX_FOUND)
.map(account => playerRow(account, online));
const {found, total} = staff.findAccounts(query);
return {players: found.map(account => playerRow(account, online)), total};
};
// one player: the row, what was done about their bans (without addresses),
@@ -120,7 +129,17 @@ const playerDetail = account => ({
...playerRow(account, playing()),
history: bans.historyOf(account).map(({at, action, seconds, reason, by}) => ({at, action, seconds, reason, by})),
appeal: bans.appealOf(account),
warningList: (account.warnings || []).slice(-20).reverse(),
notes: modNotes.list(account),
openReports: reports.list(false).filter(report => report.target.toLowerCase() === account.username.toLowerCase()).length,
devicesKnown: devices.knownFor(account).ids,
stoppedThisWeek: chatlog.notSentCount(account, 7),
paintings: masterpieces.madeBy(account).length,
// what they made in the Item Maker, with its pictures, for a report about one
madeItems: playerItems.madeBy(account).map(entry => ({kind: entry.kind, id: entry.id, name: entry.name,
artUrl: itemArt.urlOf(entry, "/mod/api/itemart"), artWaiting: Boolean(entry.artPending)})),
picturesStopped: Boolean(account.artBlocked),
pictureStrikes: account.artRefusals || 0,
});
// an address with its end left out, and a name to lift its ban by.
@@ -134,6 +153,23 @@ const maskedAddress = ban => ({
const wholeNumber = (value, min, max) => (Number.isInteger(value) && value >= min && value <= max ? value : null);
// the permission (lib/roles.js) each action needs.
const ACTION_PERMISSIONS = {
ban: "player.ban", banReason: "player.ban", unban: "player.ban",
silence: "chat.silence", unsilence: "chat.silence",
kick: "player.kick", message: "player.warn", warn: "player.warn", unwarn: "player.warn",
rejectName: "player.names", acceptName: "player.names", clearBio: "player.names",
banAddress: "address.ban",
summon: "player.summon", goto: "player.goto",
note: "player.view", deleteNote: "player.view",
};
// minutes as a person would say them: "1 hour", "1 day", "90 minutes".
const silenceText = minutes => {
const [count, unit] = minutes % 1440 === 0 ? [minutes / 1440, "day"] : minutes % 60 === 0 ? [minutes / 60, "hour"] : [minutes, "minute"];
return `${count} ${unit}${count === 1 ? "" : "s"}`;
};
const act = (mod, target, body) => {
const {actions, PERMANENT} = world.moderation;
const name = target.username;
@@ -141,8 +177,12 @@ const act = (mod, target, body) => {
if (target === mod) {
return {error: "That is you."};
}
if (target.moderator) {
return {error: "Another moderator is the admin's to deal with."};
if (!roles.outranks(mod, target)) {
return {error: "Staff of your rank or above are for someone higher up to deal with."};
}
const permission = ACTION_PERMISSIONS[body.action];
if (permission && !roles.can(mod, permission)) {
return {error: "Your role cannot do that."};
}
switch (body.action) {
case "ban": {
@@ -183,6 +223,22 @@ const act = (mod, target, body) => {
}
return actions.message(target, text) ? {ok: `Shown to ${name}.`, detail: text} : {error: `${name} is not online.`};
}
case "warn": {
const reason = String(body.reason || "behavior");
const result = actions.warn(target, reason, by, body.note);
if (!result) {
return {error: reason === "custom" ? "A custom warning needs its words in the note: they are what the player is shown."
: `A warning's reason: ${world.moderation.WARNINGS.join(", ")}.`};
}
return {ok: `${name} warned (${reason}): warning ${result.count}.${result.online ? "" : " They are offline: they will see it when they next play."}`
+ (result.silencedMinutes ? ` That many warnings also silenced them for ${silenceText(result.silencedMinutes)}.` : ""),
detail: `${reason}${body.note ? ` · ${String(body.note).slice(0, 200)}` : ""}`};
}
case "unwarn": {
const removed = actions.unwarn(target);
return removed ? {ok: `Took back ${name}'s latest warning (${removed.reason}).`, detail: removed.reason}
: {error: `${name} has no warnings.`};
}
case "rejectName":
if (target.nameRejected) {
return {error: "Already rejected."};
@@ -200,6 +256,15 @@ const act = (mod, target, body) => {
target.bio = "";
accounts.save(target);
return {ok: "Bio cleared."};
// a note for the other staff (lib/modnotes.js); the player never sees it.
case "note": {
const result = modNotes.add(target, by, body.text);
return result.error ? result : {ok: "Note added.", detail: result.note.text};
}
case "deleteNote": {
const result = modNotes.remove(target, body.id, by, roles.roleOf(mod) === "admin");
return result.error ? result : {ok: "Note removed.", detail: `${result.note.by}: ${result.note.text}`};
}
// the address they last signed in from, for good. which address that
// is, the moderator is not told.
case "banAddress": {
@@ -213,6 +278,21 @@ const act = (mod, target, body) => {
}
return {ok: "Their address is banned.", detail: result.ban.reason};
}
// the moderator's own animal and the player's, in the game: both have
// to be online, the moderator in a room.
case "summon": {
const result = world.staffMove(target.username, mod.username);
return result.ok ? {ok: `${name} was brought to ${result.room}.`, detail: result.room} : {error: result.error};
}
case "goto": {
const result = world.staffMove(mod.username, target.username);
return result.ok ? {ok: `You went to ${name} (${result.room}).`, detail: result.room} : {error: result.error};
}
// every computer they signed in from lately (lib/devices.js).
case "banDevices":
return staff.banDevices(target, body.reason, by);
case "unbanDevices":
return staff.unbanDevicesOf(target, by);
default:
return {error: "Unknown action."};
}
@@ -267,7 +347,7 @@ const handle = async (req, res, url, from, web) => {
const account = known && await accounts.authenticateAsync(known.username, body.password) === known ? known : null;
// one answer for a wrong password and for an account that is no
// moderator: who the moderators are is nobody's to find out here.
if (!account || !account.moderator) {
if (!account || !roles.roleOf(account)) {
failuresByAddress.record(from.key);
if (known && !account) {
accounts.recordLogin(known, "mod", from.address, false);
@@ -333,19 +413,88 @@ const handle = async (req, res, url, from, web) => {
reply(result.ok ? 200 : 400, result.ok ? {ok: result.ok} : {error: result.error});
};
switch (route) {
// who is signed in here, their role and what it allows: for a client to
// show only the buttons that will work.
case "GET /mod/api/me":
reply(200, {username: mod.username, role: roles.roleOf(mod), permissions: roles.permissionsOf(mod)});
return;
}
// what players made that waits for approval (lib/playeritems.js)
if (url.pathname === "/mod/api/review") {
if (!roles.can(mod, "items.approve")) {
reply(403, {error: "Your role does not allow that."});
return;
}
reviewRoutes(route.replace(" /mod/api/", " "), body, reply, done, mod.username, "/mod/api/itemart");
return;
}
// custom items (lib/customitems.js), for whoever may make them.
if (url.pathname.startsWith("/mod/api/items")) {
if (!roles.can(mod, "items.create")) {
reply(403, {error: "Your role does not allow that."});
return;
}
itemRoutes(route.replace(" /mod/api/", " "), url, body, reply, done, {
username: mod.username,
artBase: "/mod/api/itemart",
mayTake: target => target === mod || !roles.roleOf(target) || roles.outranks(mod, target),
});
return;
}
// everything else shows players and what they did: not for a role that
// only makes things.
if (!roles.can(mod, "player.view")) {
reply(403, {error: "Your role does not allow that."});
return;
}
switch (route) {
case "GET /mod/api/overview":
reply(200, {online: world.players().length, reports: reports.openCount(), requests: support.nameRequests(false).length + bans.openAppeals(),
paintings: masterpieces.list(masterpieces.PENDING).length});
return;
// other accounts the same person may have, and their story (lib/staff.js).
case "GET /mod/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 player."});
return;
}
case "GET /mod/api/timeline": {
const account = accounts.byName(url.searchParams.get("username") || "");
reply(account ? 200 : 404, account ? {events: staff.timelineOf(account)} : {error: "No such player."});
return;
}
// who the server's chat filter stopped most this week.
case "GET /mod/api/filterhits":
reply(200, {players: chatlog.mostStopped(7, 50)});
return;
case "GET /mod/api/players": {
if (url.searchParams.get("by") !== "address") {
reply(200, {players: findPlayers(url.searchParams.get("q"))});
const searchBy = url.searchParams.get("by");
if (searchBy === "device") {
const found = staff.byDevice(url.searchParams.get("q"));
if (found.error) {
reply(400, found);
return;
}
const online = playing();
reply(200, {players: found.players.map(entry => ({...playerRow(accounts.byName(entry.username), online), matchedAt: entry.lastAt}))});
return;
}
if (searchBy !== "address") {
reply(200, findPlayers(url.searchParams.get("q")));
return;
}
// by address: only the address typed, which is written down (once
// for each address, though the page asks again every few seconds).
// for the roles that ban addresses (lib/roles.js), not every staff member.
if (!roles.can(mod, "address.ban")) {
reply(403, {error: "Your role cannot do that."});
return;
}
const query = String(url.searchParams.get("q") || "").trim().toLowerCase();
const found = staff.byAddress(query);
if (found.error) {
@@ -361,6 +510,11 @@ const handle = async (req, res, url, from, web) => {
return;
}
// the latest mod notes on anybody (lib/modnotes.js), for the dashboard.
case "GET /mod/api/notes":
reply(200, {notes: modNotes.recent(MAX_RECENT_NOTES)});
return;
case "GET /mod/api/stats":
reply(200, stats.report(Number(url.searchParams.get("days")), Number(url.searchParams.get("offset"))));
return;
@@ -386,7 +540,8 @@ const handle = async (req, res, url, from, web) => {
case "GET /mod/api/chat": {
const params = url.searchParams;
const lines = chatlog.search({username: (params.get("username") || "").trim().slice(0, 100), room: (params.get("room") || "").trim().slice(0, 100),
text: (params.get("text") || "").trim().slice(0, 100), before: Number(params.get("before")) || 0});
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;
}
@@ -426,18 +581,29 @@ const handle = async (req, res, url, from, web) => {
}
case "GET /mod/api/bans":
reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans().map(maskedAddress)});
reply(200, {accounts: staff.disciplined(), addresses: bans.addressBans().map(maskedAddress), devices: devices.list(), alerts: devices.alerts()});
return;
case "POST /mod/api/address": {
if (!roles.can(mod, "address.ban")) {
reply(403, {error: "Your role cannot do that."});
return;
}
const ban = bans.addressBans().find(entry => sha256(entry.key).slice(0, 16) === String(body.id));
done(ban && bans.unbanAddress(ban.key, mod.username) ? {ok: "No longer banned."} : {error: "Not banned."}, "address unbanned", "", ban ? ban.reason : "");
return;
}
// A device ban lifted (lib/devices.js).
case "POST /mod/api/device": {
const result = staff.unbanDevices(body.id, mod.username);
done(result, "hardware ban lifted", result.username || "");
return;
}
// paintings players framed (lib/masterpieces.js).
case "GET /mod/api/masterpieces":
reply(200, {waiting: masterpieces.list(masterpieces.PENDING), approved: masterpieces.list(masterpieces.APPROVED)});
reply(200, {...masterpieces.listsFor(url.searchParams.get("creator")), waitingCount: masterpieces.list(masterpieces.PENDING).length});
return;
case "GET /mod/api/masterpiece": {
@@ -468,8 +634,148 @@ const handle = async (req, res, url, from, web) => {
}
};
const moderators = () => accounts.all().filter(account => account.moderator)
.map(account => ({username: account.username, twoStep: totp.isOn(account), lastSeen: account.lastSeen || null}))
// the custom items' pages, for the moderator panel (/mod/api/...) and the
// admin panel (/admin/api/..., lib/panel.js): `route` is without that
// ("GET items"), and `actor` is {username, mayTake(account)}: who it is
// written down as, and whether they may take items from that player.
// GET items: the custom items, the newest first.
// GET items/find?q=WORDS&kind=all|clothing|den: any item (the game's or a
// custom one), by name or id, as the item finder finds it, each marked
// whether it is locked out of the finder: for the dashboards' lock.
// GET items/base?kind=clothing|den&id=N: an item of the game's to
// make one from (its name and colours), to check before making it.
// POST items {action: "create", kind, base, name, cost, members, colors}
// or {action: "update", kind, id, and any of name, cost, members, colors, inShop}
// or {action: "lock" | "unlock", kind, id}: kept out of the item finder
// or {action: "take", username, kind, id}: every one of it, from one player
// or {action: "delete", kind, id}: a custom item, out of the game and every inventory.
const itemRoutes = (route, url, body, reply, done, actor) => {
switch (route) {
case "GET items":
reply(200, {items: customItems.list().map(entry => ({...entry, baseName: customItems.baseName(entry), locked: itemControl.isLocked(entry.kind, entry.id),
artUrl: itemArt.urlOf(entry, actor.artBase)})),
firstId: customItems.FIRST_ID, locked: itemControl.lockedList()});
return;
case "GET items/find": {
const found = admin.search(url.searchParams, null, true);
reply(200, {total: found.total, results: found.results.slice(0, 20).map(entry => ({
kind: entry.kind, id: entry.id, cost: entry.cost,
name: entry.locked ? entry.name.replace(/ \(locked\)$/, "") : entry.name,
locked: Boolean(entry.locked),
custom: entry.id >= customItems.FIRST_ID,
})), lockedCount: itemControl.lockedList().length});
return;
}
case "GET items/base": {
const kind = url.searchParams.get("kind") === "den" ? "den" : "clothing";
const id = Number(url.searchParams.get("id"));
const def = kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id);
if (!def || id >= customItems.FIRST_ID || (kind === "clothing" && def.type !== "1")) {
reply(404, {error: `No ${kind === "den" ? "den item" : "clothing"} with that id.`});
return;
}
reply(200, kind === "den"
? {kind, id, name: defpacks.string(def.nameStrId) || def.abbrName, art: def.abbrName, cost: Number(def.cost)}
: {kind, id, name: defpacks.string(def.titleStrId), art: Number(def.layerDefId), cost: Number(def.value), colors: String(def.colors).split(",").map(Number)});
return;
}
case "POST items": {
const kind = String(body.kind || "");
if (body.action === "lock" || body.action === "unlock") {
const result = itemControl.setLocked(kind, body.id, body.action === "lock");
done(result, result.ok ? `item ${body.action}ed` : "", "", `${kind} ${body.id}`);
return;
}
if (body.action === "take") {
const target = accounts.byName(String(body.username || "").trim());
if (target && !actor.mayTake(target)) {
done({error: "Staff of your rank or above are for someone higher up to deal with."});
return;
}
const result = itemControl.take(String(body.username || "").trim(), kind, body.id, world);
done(result, result.ok ? "item taken" : "", target ? target.username : "", `${kind} ${body.id}${result.count ? ` x${result.count}` : ""}`);
return;
}
if (body.action === "look") {
const result = customItems.setArtMode(kind, body.id, String(body.look));
done(result.error ? result : {ok: `${result.item.name} is worn as ${body.look === "texture" ? "a texture" : "a sticker"}.`},
"item look changed", "", `${kind} ${body.id} ${body.look}`);
return;
}
if (body.action === "delete") {
const result = itemControl.deleteCustom(kind, body.id, world);
done(result, result.ok ? "item deleted" : "", "", `${kind} ${body.id}`);
return;
}
const result = body.action === "update"
? customItems.update(kind, body.id, body)
: body.action === "create" ? customItems.create(kind, body, actor.username) : {error: "Unknown action."};
if (result.error) {
done(result);
return;
}
const {item} = result;
done({ok: `${item.name} (${item.kind === "den" ? "den item" : "clothing"} ${item.id}) ${body.action === "update" ? "changed" : "made"}.`},
body.action === "update" ? "item changed" : "item made", "", `${item.kind} ${item.id} ${item.name}`);
return;
}
default:
reply(404, {error: "not_found"});
}
};
// GET review: what waits, the oldest first; POST review {kind, id, approve: true | false}.
// for the moderator panel and the admin panel (lib/panel.js) alike.
// POST review {action: "takePicture", kind, id}: a picture off an item,
// counted against its maker; {action: "uploads", username, blocked}:
// stops, or lets again, one player's picture uploads.
// `artBase`: the panel's /…/api/itemart, where pictures that wait are shown.
const reviewRoutes = (route, body, reply, done, by, artBase) => {
if (route === "GET review") {
reply(200, {
waiting: customItems.waiting().map(entry => {
const maker = entry.ownerId === null ? null : accounts.byId(entry.ownerId);
return {kind: entry.kind, id: entry.id, name: entry.name, baseName: customItems.baseName(entry), base: entry.base, maker: maker ? maker.username : entry.createdBy,
createdAt: entry.createdAt, waiting: entry.pending ? "item" : "picture", artUrl: itemArt.urlOf(entry, artBase),
makerStrikes: maker ? maker.artRefusals || 0 : 0};
}),
enabled: playerItems.enabled(),
approval: playerItems.approvalOn(),
artApproval: playerItems.artApprovalOn(),
strikes: playerItems.ART_STRIKES,
stopped: accounts.all().filter(account => account.artBlocked).map(account => account.username).sort(),
});
return;
}
if (route === "POST review" && body.action === "takePicture") {
const kind = String(body.kind || "");
const entry = customItems.get(kind, body.id);
const maker = entry && entry.ownerId !== null ? accounts.byId(entry.ownerId) : null;
const result = playerItems.takePicture(kind, body.id);
done(result, result.ok ? "item picture taken off" : "", maker ? maker.username : "", `${kind} ${body.id}`);
return;
}
if (route === "POST review" && body.action === "uploads") {
const target = accounts.byName(String(body.username || "").trim());
if (!target) {
done({error: "No such player."});
return;
}
const result = playerItems.setUploadsBlocked(target, body.blocked === true);
done(result, body.blocked === true ? "picture uploads stopped" : "picture uploads allowed", target.username);
return;
}
if (route === "POST review") {
const kind = String(body.kind || "");
const result = playerItems.review(kind, body.id, body.approve === true, by, world);
done(result, result.ok ? (body.approve === true ? "item approved" : "item turned away") : "", "", `${kind} ${body.id}`);
return;
}
reply(404, {error: "not_found"});
};
const moderators = () => accounts.all().filter(account => roles.roleOf(account))
.map(account => ({username: account.username, role: roles.roleOf(account), twoStep: totp.isOn(account), lastSeen: account.lastSeen || null}))
.sort((a, b) => a.username.localeCompare(b.username));
module.exports = {handle, forget, moderators};
module.exports = {handle, forget, moderators, signedInAs, itemRoutes, reviewRoutes};
+18 -10
View File
@@ -35,23 +35,31 @@ const stretched = word => /(.)\1\1/.test(word);
// above. "word" is for a line marked "=": in lib/sexual-names.txt the rest
// are matched anywhere in a name.
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 => {
let mtime = 0;
let fd;
try {
mtime = fs.statSync(file).mtimeMs;
fd = fs.openSync(file, "r");
}
catch (err) {
return [];
}
const kept = lists.get(file);
if (kept && kept.mtime === mtime) {
return kept.entries;
try {
const mtime = fs.fstatSync(fd).mtimeMs;
const kept = lists.get(file);
if (kept && kept.mtime === mtime) {
return kept.entries;
}
const entries = fs.readFileSync(fd, "utf8").split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith("#"))
.map(line => ({text: line.replace(/^=/, "").replace(/\*$/, "").split(/\s+/).map(plain).join(""), prefix: line.endsWith("*"), word: line.startsWith("=")}))
.filter(entry => entry.text.length >= 2);
lists.set(file, {mtime, entries});
return entries;
}
finally {
fs.closeSync(fd);
}
const entries = fs.readFileSync(file, "utf8").split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith("#"))
.map(line => ({text: line.replace(/^=/, "").replace(/\*$/, "").split(/\s+/).map(plain).join(""), prefix: line.endsWith("*"), word: line.startsWith("=")}))
.filter(entry => entry.text.length >= 2);
lists.set(file, {mtime, entries});
return entries;
};
let epicDens = null;
+201 -23
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
@@ -9,15 +10,19 @@ const adopt = require("./adopt.js");
const badges = require("./badges.js");
const bans = require("./bans.js");
const colours = require("./colours.js");
const chatlog = require("./chatlog.js");
const config = require("../config.js");
const devices = require("./devices.js");
const defpacks = require("./defpacks.js");
const limits = require("./limits.js");
const log = require("./log.js");
const masterpieces = require("./masterpieces.js");
const modlog = require("./modlog.js");
const modpanel = require("./modpanel.js");
const playerItems = require("./playeritems.js");
const erase = require("./erase.js");
const reports = require("./reports.js");
const roles = require("./roles.js");
const sales = require("./sales.js");
const stats = require("./stats.js");
const staff = require("./staff.js");
@@ -47,6 +52,7 @@ const TEN_MINUTES_MS = 600000;
const DAY_SECONDS = 86400;
const MAX_ANNOUNCEMENT = 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.
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
@@ -85,7 +91,7 @@ const passwordAcceptable = password =>
const load = () => {
if (!hasPassword()) {
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})`);
}
};
@@ -148,13 +154,22 @@ const accountRow = (account, playing) => {
// seconds left, -1 for permanent, 0 for not banned
banned: ban,
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),
silenced: world.moderation.isSilenced(account),
animals: account.avatars.length,
level: activeAvatar(account).questLevel || 0,
items: account.items.length + account.denItems.length,
gems: account.currency.gems || 0,
deviceBanned: devices.bannedId(account) !== 0,
devicesKnown: devices.knownFor(account).ids,
stoppedThisWeek: chatlog.notSentCount(account, 7),
paintings: masterpieces.madeBy(account).length,
};
};
@@ -369,8 +384,10 @@ const act = (account, body) => {
const name = account.username;
switch (body.action) {
case "password": {
if (accounts.setPassword(account, body.password)) {
return {error: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."};
const passwordProblem = accounts.setPassword(account, body.password);
if (passwordProblem) {
return {error: passwordProblem === "weak_password" ? "That password is too easy to guess: it is a common one, or has your username in it."
: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit."};
}
actions.kick(account);
manage.forget(account); // their account page too, whoever has it open
@@ -477,6 +494,11 @@ const act = (account, body) => {
return {ok: `${name} is no longer banned.`};
case "kick":
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.
case "silence": {
const hours = wholeNumber(body.hours, 0, MAX_BAN_HOURS);
@@ -488,18 +510,47 @@ const act = (account, body) => {
}
// A moderator may use the moderator panel (lib/modpanel.js), with this
// account's password and its 2FA, which it has to have.
// (the older on/off switch; "role" below is the full one.)
case "moderator":
if (body.on === true) {
account.moderator = true;
}
else {
delete account.moderator;
roles.setRole(account, body.on === true ? "moderator" : null);
if (body.on !== true) {
modpanel.forget(account);
}
accounts.save(account);
return {ok: body.on === true
? `${name} is a moderator.${totp.isOn(account) ? "" : " They have no 2FA yet and cannot sign in to the moderator panel until they turn it on."}`
: `${name} is no longer a moderator.`};
// 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.`};
}
case "rejectName":
actions.rejectName(account, BY);
manage.forget(account);
@@ -604,7 +655,7 @@ const handle = async (req, res, url, from, web) => {
}
storePassword(body.password);
setupCode = null;
console.log(`[admin] admin password chosen from ${from.address}`);
console.log(`[admin] admin password chosen from ${logText(from.address)}`);
signIn(res);
reply(200, {ok: true});
return;
@@ -617,11 +668,11 @@ const handle = async (req, res, url, from, web) => {
}
if (!hasPassword() || !passwordMatches(body.password)) {
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."});
return;
}
console.log(`[admin] signed in from ${from.address}`);
console.log(`[admin] signed in from ${logText(from.address)}`);
signIn(res);
reply(200, {ok: true});
return;
@@ -638,14 +689,62 @@ const handle = async (req, res, url, from, web) => {
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) {
case "GET /admin/api/overview":
reply(200, overview());
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": {
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;
}
@@ -660,6 +759,28 @@ const handle = async (req, res, url, from, web) => {
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;
}
case "GET /admin/api/logs": {
const lines = log.recent(Number(url.searchParams.get("after")) || 0, (url.searchParams.get("filter") || "").slice(0, 100));
@@ -675,7 +796,11 @@ const handle = async (req, res, url, from, web) => {
}
const result = act(account, body);
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);
return;
@@ -688,10 +813,63 @@ const handle = async (req, res, url, from, web) => {
}
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;
// 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":
reply(200, {moderators: modpanel.moderators(), log: modlog.recent()});
return;
@@ -705,7 +883,7 @@ const handle = async (req, res, url, from, web) => {
case "POST /admin/api/address": {
const result = addressAct(body);
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);
return;
@@ -722,7 +900,7 @@ const handle = async (req, res, url, from, web) => {
case "POST /admin/api/debug": {
const result = debugAct(body);
if (result.ok) {
console.log(`[admin] debug: ${body.action} ${body.action === "teleport" ? `${body.username} -> ${body.room}` : body.on === true}`);
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;
@@ -743,7 +921,7 @@ const handle = async (req, res, url, from, web) => {
return;
}
const reached = world.announce(text, body.room ? String(body.room) : null);
console.log(`[admin] announcement to ${body.room ? `room ${body.room}` : "everyone"} (${reached} players)`);
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.`});
return;
}
@@ -753,8 +931,8 @@ const handle = async (req, res, url, from, web) => {
case "GET /admin/api/masterpieces":
reply(200, {
review: masterpieces.needsReview(),
waiting: masterpieces.list(masterpieces.PENDING),
approved: masterpieces.list(masterpieces.APPROVED),
...masterpieces.listsFor(url.searchParams.get("creator")),
waitingCount: masterpieces.list(masterpieces.PENDING).length,
});
return;
@@ -788,7 +966,7 @@ const handle = async (req, res, url, from, web) => {
result = {error: "Unknown action."};
}
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);
return;
@@ -830,7 +1008,7 @@ const handle = async (req, res, url, from, web) => {
result = {error: "Unknown action."};
}
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);
return;
@@ -858,4 +1036,4 @@ const handle = async (req, res, url, from, web) => {
}
};
module.exports = {load, handle, PASSWORD_SETTING};
module.exports = {load, handle, signedIn, PASSWORD_SETTING};
+2 -1
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js");
const config = require("../config.js");
const defpacks = require("./defpacks.js");
@@ -190,7 +191,7 @@ module.exports = ({enterRoom, findOnline, blocks}) => {
accounts.save(account);
const party = {host: account, defId: def.id, name: `${name1}|${name2}|${name3}`, music: Number(music), endsAt: now() + config.partyMinutes * 60};
hosted.set(account.username.toLowerCase(), party);
console.log(`[world] ${account.username} is hosting a party (def ${def.id})`);
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("scp", -1, 1, 1, party.endsAt - now());
joinHosted(session, account);
+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};
+7 -2
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js");
const limits = require("./limits.js");
@@ -69,7 +70,7 @@ const file = ({reporter, target, reason, detail = "", context = "", room = ""})
}
db.prepare("INSERT INTO reports (created_at, reporter, target, reason, detail, context, room) VALUES (?, ?, ?, ?, ?, ?, ?)")
.run(now(), reporter, target, Number.isInteger(reason) ? reason : 0, clean(detail, MAX_DETAIL), clean(context, MAX_CONTEXT), clean(room, 100));
console.log(`[world] ${reporter} reported "${target}" (${REASONS[reason] || `reason ${reason}`})`);
console.log(`[world] ${logText(reporter)} reported "${logText(target)}" (${logText(REASONS[reason] || `reason ${reason}`)})`);
return true;
};
@@ -94,4 +95,8 @@ 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;
module.exports = {load, file, list, markHandled, openCount, MAX_DETAIL};
// the reports about one player, newest first, for their timeline.
const about = username => accounts.database().prepare("SELECT * FROM reports WHERE target = ? COLLATE NOCASE ORDER BY id DESC LIMIT 100")
.all(String(username)).map(row);
module.exports = {load, file, list, about, markHandled, openCount, MAX_DETAIL};
+167
View File
@@ -0,0 +1,167 @@
"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 = {
"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 and send them a message (!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 and change a ban's reason",
"player.names": "reject or accept a name, clear a bio",
"address.ban": "ban the address a player last signed in from",
"items.approve": "approve or turn away the items and pictures players make, when the admin has asked for that",
"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)",
};
const HELPER = ["player.view", "staff.list", "player.warn", "player.goto", "chat.silence"];
const MODERATOR = [...HELPER, "player.kick", "player.summon", "staff.invisible", "player.ban", "player.names", "address.ban", "items.approve"];
const ADMIN = [...MODERATOR, "items.create"];
// a developer makes things, and moderates nobody.
const DEVELOPER = ["staff.list", "items.create"];
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;
};
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 = {PERMISSIONS, ROLES, roleOf, rankOf, isActiveStaff, permissionsOf, rolePermissions, roleChanged, setRolePermissions,
setAccountPermissions, can, outranks, setRole};
+2 -1
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const zlib = require("zlib");
const amf3 = require("./amf3.js");
const cdn = require("./cdn.js");
@@ -71,7 +72,7 @@ const preload = async () => {
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:
+11 -10
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto");
const fs = require("fs");
const net = require("net");
@@ -49,7 +50,7 @@ class Session {
write(message) {
if (this.socket.writable) {
if (config.logPackets) {
console.log(`[game] -> ${this.name} ${message}`);
console.log(`[game] -> ${logText(this.name)} ${logText(message)}`);
}
this.socket.write(message + "\0");
// A client that stopped reading must not pile up messages here forever.
@@ -96,7 +97,7 @@ const parseSys = message => {
const start = handlers => new Promise((resolve, reject) => {
const dispatch = (session, message) => {
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")) {
session.socket.end(POLICY + "\0");
@@ -153,7 +154,7 @@ const start = handlers => new Promise((resolve, reject) => {
let bytesInWindow = 0;
let errorsInWindow = 0;
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
// nobody may sit silent for long: the client sends keep-alives.
@@ -178,7 +179,7 @@ const start = handlers => new Promise((resolve, reject) => {
}
bytesInWindow += chunk.length;
if (bytesInWindow > config.maxBytesPerTenSeconds) {
console.log(`[game] ${session.name} disconnected for flooding`);
console.log(`[game] ${logText(session.name)} disconnected for flooding`);
socket.destroy();
return;
}
@@ -190,7 +191,7 @@ const start = handlers => new Promise((resolve, reject) => {
return;
}
if (++messagesInWindow > config.maxMessagesPerTenSeconds) {
console.log(`[game] ${session.name} disconnected for flooding`);
console.log(`[game] ${logText(session.name)} disconnected for flooding`);
socket.destroy();
return;
}
@@ -203,9 +204,9 @@ const start = handlers => new Promise((resolve, reject) => {
// one line a failure, and an end to them: a client that sends
// nonsense in a loop is not to fill the log.
const where = String(err.stack || "").split("\n")[1] || "";
console.log(`[game] error handling message from ${session.name}: ${err.message}${where ? ` (${where.trim()})` : ""}`);
console.log(`[game] error handling message from ${logText(session.name)}: ${logText(err.message)}${logText(where ? ` (${where.trim()})` : "")}`);
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();
return;
}
@@ -228,13 +229,13 @@ const start = handlers => new Promise((resolve, reject) => {
else {
connections.delete(address);
}
console.log(`[game] ${session.name} disconnected`);
console.log(`[game] ${logText(session.name)} disconnected`);
// nothing thrown while a player is seen off may take the server down.
try {
handlers.close(session);
}
catch (err) {
console.log(`[game] error while ${session.name} left: ${err.stack}`);
console.log(`[game] error while ${logText(session.name)} left: ${logText(err.stack)}`);
}
});
};
@@ -271,7 +272,7 @@ const start = handlers => new Promise((resolve, reject) => {
}
server.once("error", reject);
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);
});
});
+3 -1
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const crypto = require("crypto");
const accounts = require("./accounts.js");
const bans = require("./bans.js");
@@ -24,6 +25,7 @@ const STATUS = {
username_taken: USERNAME_TAKEN,
invalid_username: USERNAME_INVALID,
invalid_password: PASSWORD_INVALID,
weak_password: PASSWORD_INVALID, // the game's screens have one word for both
name_not_allowed: USERNAME_INVALID,
};
// names asked about on one guest connection: the screens ask once or twice.
@@ -88,7 +90,7 @@ const handlers = {
return;
}
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);
return;
}
+132 -1
View File
@@ -2,7 +2,11 @@
const accounts = require("./accounts.js");
const bans = require("./bans.js");
const devices = require("./devices.js");
const limits = require("./limits.js");
const manage = require("./manage.js");
const modlog = require("./modlog.js");
const reports = require("./reports.js");
const support = require("./support.js");
const world = require("./world.js");
@@ -25,6 +29,29 @@ const disciplined = () => accounts.all()
.filter(entry => entry.banned !== 0 || entry.silenced !== 0)
.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
@@ -67,6 +94,110 @@ const banAddress = (address, reason, by) => {
return result.error ? {error: ADDRESS_ERRORS[result.error]} : {ban: result.ban, out: world.disconnectAddress(result.ban.address)};
};
// 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], weak,
// 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: [], weak: false, addresses: 0});
}
return found.get(username);
};
for (const alt of devices.alts(account)) {
Object.assign(entry(alt.username), {devices: alt.kinds, weak: alt.weak});
}
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 && !other.weak) - Number(one.devices.length > 0 && !one.weak)
|| 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.
const appealsFor = handled => bans.appeals(handled).map(appeal => {
const account = accounts.byId(appeal.accountId);
@@ -122,4 +253,4 @@ const answerNameRequest = (id, approve) => {
return {ok: `${oldName} is now called ${account.username}. They log in with the new name and the same password.`, username: account.username};
};
module.exports = {disciplined, byAddress, banAddress, appealsFor, answerAppeal, answerNameRequest};
module.exports = {disciplined, findAccounts, byAddress, banAddress, banDevices, unbanDevices, unbanDevicesOf, byDevice, altsOf, timelineOf, appealsFor, answerAppeal, answerNameRequest};
+3 -2
View File
@@ -1,5 +1,6 @@
"use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js");
// 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("INSERT INTO name_requests (created_at, account_id, old_name, new_name, reason) VALUES (?, ?, ?, ?, ?)")
.run(now(), account.id, account.username, newName, clean(reason, MAX_REASON));
console.log(`[support] "${account.username}" asked to be called "${newName}"`);
console.log(`[support] "${logText(account.username)}" asked to be called "${logText(newName)}"`);
return {request: waitingNameRequest(account)};
};
@@ -127,7 +128,7 @@ const sendFeedback = (account, kind, text) => {
return {error: "too_many"};
}
db().prepare("INSERT INTO feedback (created_at, account_id, username, kind, text) VALUES (?, ?, ?, ?, ?)").run(now(), account.id, account.username, kind, body);
console.log(`[support] ${kind === "bug" ? "bug report" : "feedback"} from "${account.username}"`);
console.log(`[support] ${logText(kind === "bug" ? "bug report" : "feedback")} from "${logText(account.username)}"`);
return {ok: true};
};
+15 -2
View File
@@ -1,10 +1,12 @@
"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 chatFilter = require("./chatfilter.js");
const chatlog = require("./chatlog.js");
const masterpieces = require("./masterpieces.js");
const limits = require("./limits.js");
const {isUint} = require("./player.js");
@@ -72,6 +74,14 @@ const flat = value => scalar(value) || (typeof value === "object" && !Array.isAr
&& Object.keys(value).length <= 12 && Object.values(value).every(scalar));
const plainParam = value => flat(value) || (Array.isArray(value) && value.length <= MAX_PARAM_ENTRIES && value.every(flat));
const whole = value => (Number.isInteger(Number(value)) ? Number(value) : 0);
// 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.
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" ? Array.isArray(part) && part.length <= MAX_PHOTO_ITEMS && part.every(flat)
: key === "avatar" || key === "pet" ? part === null || flat(part) : scalar(part))));
module.exports = ({blocks, findOnline}) => {
const tokens = new Map(); // token -> {viewer: account id, owner: account id, expires}
@@ -154,7 +164,8 @@ module.exports = ({blocks, findOnline}) => {
// the server's filter (lib/chatfilter.js) too.
const rule = message ? chatFilter.broken(message) : null;
if (rule) {
console.log(`[filter] ${viewer.username} on ${owner.username}'s wall: "${message}" (${rule})`);
console.log(`[filter] ${logText(viewer.username)} on ${logText(owner.username)}'s wall: "${logText(message)}" (${logText(rule)})`);
chatlog.recordTo(viewer, chatlog.WALL, owner.username, chatlog.NOT_SENT + message);
const session = findOnline(viewer.username);
if (session) {
chatFilter.warn(session);
@@ -184,6 +195,8 @@ module.exports = ({blocks, findOnline}) => {
if (typeof body.pp === "string" && owner.wall.posts.some(other => other.x === body.pp)) {
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 = owner.wall.posts.slice(-MAX_POSTS);
owner.wall.modified = post.t;
@@ -321,7 +334,7 @@ module.exports = ({blocks, findOnline}) => {
const merged = changes && typeof changes === "object" && !Array.isArray(changes) ? {...wall.params} : null;
for (const key of merged ? OWNER_PARAMS : []) {
if (changes[key] !== undefined) {
if (!plainParam(changes[key])) {
if (!(key === "pb" ? photoParam(changes[key]) : plainParam(changes[key]))) {
session.sendXt("wps", -1, 0);
return;
}
+375 -35
View File
@@ -1,10 +1,15 @@
"use strict";
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js");
const achievements = require("./achievements.js");
const adopt = require("./adopt.js");
const config = require("../config.js");
const colours = require("./colours.js");
const customItems = require("./customitems.js");
const roles = require("./roles.js");
const modlog = require("./modlog.js");
const playerItems = require("./playeritems.js");
const commandModule = require("./commands.js");
const limits = require("./limits.js");
const masterpieces = require("./masterpieces.js");
@@ -12,8 +17,10 @@ const defpacks = require("./defpacks.js");
const avatarHandlers = require("./avatars.js");
const badges = require("./badges.js");
const bans = require("./bans.js");
const devices = require("./devices.js");
const chatlog = require("./chatlog.js");
const chatFilter = require("./chatfilter.js");
const chatSpam = require("./chatspam.js");
const buddyModule = require("./buddies.js");
const dens = require("./dens.js");
const disguises = require("./disguises.js");
@@ -34,13 +41,21 @@ const stubHandlers = require("./stubs.js");
const wallModule = require("./walls.js");
const worldItems = require("./worlditems.js");
const stats = require("./stats.js");
const {CURRENCIES, DIAMOND_TYPES, activeAvatar, avatarById, activePet, equippedBits, wornItems, lastSeenField} = require("./player.js");
const {CURRENCIES, DIAMOND_TYPES, activeAvatar, avatarById, activePet, equippedBits, wornItems, lastSeenField, sendClothingRemoved} = require("./player.js");
// game logic behind the socket. field orders below mirror the client's
// parsers; the class that reads each message is named next to it.
const GENERIC_LIST_AVATARS = 64;
const GENERIC_LIST_NEWSPAPER = 627;
// the worlds' names (ServerSelector.getShardName): localization ids, the
// game's own river names, world N being the Nth.
const GENERIC_LIST_WORLD_NAMES = 16;
const WORLD_NAME_IDS = Array.from({length: 29}, (_, i) => 551 + i);
// the settings menu's "Find Open World" switch (gui.MySettings
// SETTINGS_AUTO_SERVER_TRAVEL): a set bit is off. on, a room that is full in
// the player's world is joined in another world that has space.
const SETTING_FIND_OPEN_WORLD = 3;
const USER_VAR_NEWSPAPER_READ = 455;
const USER_VAR_GEM_BONUS = 214;
// not one of the game's: the patched client's "hide blocked players" setting
@@ -136,6 +151,19 @@ const THEME_PATH_PREFIX = "theme_"; // lib/http.js looks for this
const chatLines = limits.limiter(config.chatLinesPerWindow, config.chatWindowMs);
const online = new Map(); // lowercased username -> session
const rooms = new Map(); // "path.name#shard" -> room
// worlds (config.shards): a land room's name ends in "#<world>"; dens,
// parties and adventures have none and belong to no world. each player has
// a world (session.worldId), picked when they arrive and changed by walking
// into a room of another.
const worldOf = name => {
const found = /#(\d+)$/.exec(name || "");
return found && config.shards.some(shard => shard.id === Number(found[1])) ? Number(found[1]) : 0;
};
const worldName = id => (config.shards.find(shard => shard.id === id) || {name: `World ${id}`}).name;
const inWorld = id => [...online.values()].filter(session => session.worldId === id);
const findOpenWorld = account => !((Number((account.userVars || {})[USER_VAR_SETTINGS]) >> SETTING_FIND_OPEN_WORLD) & 1)
|| Number((account.userVars || {})[USER_VAR_SETTINGS]) < 0;
let nextRoomId = 100;
const others = session => session.room ? [...session.room.sessions].filter(s => s !== session) : [];
@@ -148,9 +176,12 @@ const blocks = {
has: (blocker, target) => blocker.blocked.includes(nameKey(target)),
either: (a, b) => a.blocked.includes(nameKey(b)) || b.blocked.includes(nameKey(a)),
};
const sees = (viewer, subject) => !(viewer.account.hideBlocked && blocks.has(viewer.account, subject.account));
// staff gone invisible (setInvisible, below) are drawn for staff only.
const sees = (viewer, subject) => (!subject.invisible || roles.isActiveStaff(viewer.account))
&& !(viewer.account.hideBlocked && blocks.has(viewer.account, subject.account));
// everyone else in the room who should hear about this player's animal.
const watchers = session => others(session).filter(other => sees(other, session));
const TYPING_EVERY_MS = 2000; // "typing" passed on at most this often per player (xty)
const decodeEntities = text => text
.replace(/&lt;/g, "<")
@@ -186,6 +217,11 @@ const loginParams = session => {
// from bit 8 up: the name tag badges the admin gave this account
// (lib/badges.js).
pendingFlags: 7 | badges.loginFlags(account),
// this account's own staff role and what it allows (lib/roles.js), for a
// client to show staff tools only to staff. empty for everyone else, and
// only ever about the account logging in.
staffRole: roles.isActiveStaff(account) ? roles.roleOf(account) : "",
staffPermissions: roles.isActiveStaff(account) ? roles.permissionsOf(account).join(",") : "",
dailyGiftIndex: -1,
hasOnlineBuddies: buddies.hasOnlineBuddies(account),
// one bit per kind of interaction (Utility.canBuddy, canTrade, canGift,
@@ -245,32 +281,44 @@ const login = (session, msg) => {
const username = (msg.cdata("nick") || "").split("%")[0];
const account = accounts.byToken(msg.cdata("pword"));
if (!account || account.username.toLowerCase() !== username.toLowerCase()) {
console.log(`[world] login rejected for "${username}"`);
console.log(`[world] login rejected for "${logText(username)}"`);
loginFailed(session, 0, "Invalid login");
return;
}
if (moderation.banRemaining(account) !== 0) {
console.log(`[world] login rejected for banned account "${account.username}"`);
console.log(`[world] login rejected for banned account "${logText(account.username)}"`);
loginFailed(session, LOGIN_BANNED, "Banned");
return;
}
// A banned address (lib/bans.js). the client is told at /authenticate,
// with the reason; this is for a game that got here another way.
if (bans.addressBan(session.address)) {
console.log(`[world] login rejected for "${account.username}" from a banned address`);
console.log(`[world] login rejected for "${logText(account.username)}" from a banned address`);
loginFailed(session, LOGIN_BANNED, "Banned");
return;
}
// a banned computer (lib/devices.js), and a game that never said which
// computer it is on: told at /authenticate too, which is the way in.
if (devices.banOfAccount(account)) {
console.log(`[world] login rejected for "${logText(account.username)}": hardware banned`);
loginFailed(session, LOGIN_BANNED, "Banned");
return;
}
if (config.requireDevice && devices.knownFor(account).lastAt < Math.floor(Date.now() / 1000) - 90 * 86400) {
console.log(`[world] login rejected for "${logText(account.username)}": no device ids`);
loginFailed(session, 0, "Update the client");
return;
}
// its username was rejected (lib/moderation.js): a new one first, which
// the client or the account page asks for.
if (account.nameRejected) {
console.log(`[world] login rejected for "${account.username}": the name was rejected`);
console.log(`[world] login rejected for "${logText(account.username)}": the name was rejected`);
loginFailed(session, 0, "Username rejected");
return;
}
// locked by its owner on the account page (lib/manage.js).
if (account.locked) {
console.log(`[world] login rejected for locked account "${account.username}"`);
console.log(`[world] login rejected for locked account "${logText(account.username)}"`);
loginFailed(session, 0, "Account locked");
return;
}
@@ -302,13 +350,21 @@ const login = (session, msg) => {
achievements.refresh(account);
accounts.save(account);
online.set(key, session);
console.log(`[world] ${account.username} logged in as sfs user ${session.id}`);
console.log(`[world] ${logText(account.username)} logged in as sfs user ${logText(session.id)}`);
session.sendXtJson(-1, {_cmd: "login", status: "1", params: loginParams(session)});
// every custom colour, before anything that might be drawn with one
// (XtReplyDemuxer -> PaletteHelper.handleCustomColors in the patched SWF).
for (const chunk of colours.chunks()) {
session.sendXt("xcc", -1, chunk.length, ...chunk.flat());
}
// and the items staff have made (lib/customitems.js), for a game started
// before they were.
customItems.sendAll(session);
// staff: their role and what it allows, for the patched client's staff
// window (AJClient.onStaff). nobody else is sent anything.
if (roles.isActiveStaff(account)) {
session.sendXt("xsp", -1, roles.roleOf(account), roles.permissionsOf(account).join(","));
}
sendFilter(session);
buddies.announce(account);
};
@@ -377,6 +433,9 @@ const sendAvatarCreate = (to, target) => {
...(pet ? petFields(pet) : []));
sendItemList(to, target, false);
disguises.show(to, target);
if (target.invisible) {
to.sendXt("xiv", -1, target.id, 1);
}
};
// redraws `session`'s animal for everyone else in the room, for changes the
@@ -418,6 +477,8 @@ const sortStock = () => {
// has the den items, the one in the Zios archives the clothing. see
// oddDenItemIds in lib/defpacks.js.
const ODDITY_SHOPS = new Map([[396, () => defpacks.oddDenItemIds()], [666, () => defpacks.oddClothingIds()]]);
// the items staff have made (lib/customitems.js) are sold there too, first.
const CUSTOM_ITEM_SHOPS = new Map([[396, "den"], [666, "clothing"]]);
const ticketStock = kind => sortStock()[kind];
// the den shops of the lands (Coral Canyons, Deep Blue) and the one inside
// a den: lists that mix kinds, selling den rooms.
@@ -448,6 +509,8 @@ const sendUserVars = session => {
};
const findOnline = username => online.get(String(username).toLowerCase());
const STAFF_WINDOW_COMMANDS = ["warn", "unwarn", "message", "silence", "kick", "summon", "goto", "warnings"];
const MAX_STAFF_WINDOW_WORDS = 3; // username, then a reason, hours or the message (each one field)
// a custom colour (lib/colours.js) for these four RGB values, made if it is
// new and the account has not made its day's worth; everyone online is told
@@ -470,6 +533,13 @@ const makeColour = (account, rgbs, asker = null) => {
return entry;
};
// a message for every game playing (custom items, lib/customitems.js).
customItems.connect((cmd, ...params) => {
for (const session of online.values()) {
session.sendXt(cmd, -1, ...params);
}
});
// the account's chat filter, for its game to apply: [chosen, level, mode, own words].
const sendFilter = session => {
const {filter} = session.account;
@@ -578,6 +648,7 @@ const handlers = {
}
buddies.greet(session);
minigames.greet(session);
moderation.greet(session);
// never asked what chat they want filtered: the window is put to
// them, this once (the patched client's "xfa").
if (!session.account.filter.chosen) {
@@ -585,8 +656,12 @@ const handlers = {
}
}
if (firstUpdate) {
// the player's own animal is on their screen now: its disguise, if any.
// the player's own animal is on their screen now: its disguise, if any,
// and see-through if they are invisible.
disguises.show(session, session);
if (session.invisible) {
session.sendXt("xiv", -1, session.id, 1);
}
}
for (const other of watchers(session)) {
if (firstUpdate) {
@@ -594,7 +669,6 @@ const handlers = {
sendAvatarCreate(other, session);
}
else {
// AvatarManager.avatarUpdateResponse
other.sendXt("au", session.room.id, 1, session.id, count, ...coords, teleport);
}
}
@@ -605,6 +679,23 @@ const handlers = {
// defPack. list contents live on the official servers, so apart from the two
// kinds that can be rebuilt from defPacks every list is answered empty; that
// still releases whatever the client had waiting on it.
// the settings menu's world list (ServerSelector, GamePlay.showServerSelectorMore):
// a node's name, then each world as id, language, how full (0 to 4, 4
// being full) and how many of the player's buddies are in it. the game
// leaves out the world the player is in.
rm(session) {
const fields = [];
const capacity = config.spawnRooms.length * config.maxUsersPerRoom;
for (const shard of config.shards) {
const here = inWorld(shard.id);
const full = config.spawnRooms.every(base => roomFull(`${base}#${shard.id}`));
const bars = full ? 4 : Math.min(3, Math.ceil(4 * here.length / capacity));
const buddyCount = here.filter(other => session.account.buddies.includes(other.account.username.toLowerCase())).length;
fields.push(shard.id, LANG_ENG, bars, buddyCount);
}
session.sendXt("rm", -1, "burrow", ...fields);
},
gl(session, roomId, [listId]) {
if (Number(listId) === GENERIC_LIST_NEWSPAPER) {
// the client decides whether to pop the newspaper open when this list
@@ -622,6 +713,9 @@ const handlers = {
if (Number(listId) === GENERIC_LIST_AVATARS) {
entries = defpacks.avatarTypes();
}
else if (Number(listId) === GENERIC_LIST_WORLD_NAMES) {
entries = WORLD_NAME_IDS;
}
else if (defpacks.patternList(listId)) {
entries = defpacks.patternList(listId);
}
@@ -683,7 +777,7 @@ const handlers = {
else if (ODDITY_SHOPS.has(Number(listId))) {
// what the shop really sold comes first.
const real = shopStock.list(listId, type);
entries = [...new Set([...(real ? real.entries : []), ...ODDITY_SHOPS.get(Number(listId))()])];
entries = [...new Set([...defpacks.customShopIds(CUSTOM_ITEM_SHOPS.get(Number(listId))), ...(real ? real.entries : []), ...ODDITY_SHOPS.get(Number(listId))()])];
}
else if (Number(listId) === DIAMOND_DEN_LIST) {
entries = defpacks.diamondIds().filter(id => {
@@ -791,6 +885,39 @@ const handlers = {
session.sendXt("fra", -1, fileReport(session, username, reason, "", about) ? 1 : 0);
},
// the staff's window of the patched client (AJClient.openModerate):
// [command, username, ...words], one of the staff commands about a player,
// run as if typed (lib/commands.js checks the permission and logs it).
xmd(session, roomId, [command, ...words]) {
if (roles.isActiveStaff(session.account) && STAFF_WINDOW_COMMANDS.includes(command) && words.length > 0 && words.length <= MAX_STAFF_WINDOW_WORDS) {
commands.run(session, `!${command} ${words.join(" ")}`);
}
},
// the patched client's chat box: whether its player is typing, for a
// "..." over their animal in everyone else's game (gui.ChatHistory):
// xty [1 | 0], passed on as "xty" [.., .., sfsId, 1 | 0]. a client says
// it again every few seconds while typing; more often is not passed on.
xty(session, roomId, [on]) {
const typing = on === "1";
const now = Date.now();
if (!session.room || session.invisible || (typing && session.typingAt && now - session.typingAt < TYPING_EVERY_MS)
|| (!typing && !session.typingAt)) {
return;
}
session.typingAt = typing ? now : 0;
for (const other of watchers(session)) {
other.sendXt("xty", -1, session.id, typing ? 1 : 0);
}
},
// the patched client's staff window: going invisible, or being seen again.
xiv(session) {
if (session.invisible || roles.can(session.account, "staff.invisible")) {
setInvisible(session, !session.invisible);
}
},
// the patched report window (gui.ReportAPlayer), just before its "fr" or
// "fra": [username, reasonId, what the reporter typed].
xrd(session, roomId, [username, reason, ...text]) {
@@ -897,6 +1024,118 @@ const fileReport = (session, username, reason, detail = "", about = "") => {
// what the modules below may use of this one. `others` here is everyone who
// should see the player's animal change; dens get everyone in the room.
// invisible staff (the "staff.invisible" permission): their animal is drawn
// for staff only, half see-through ("xiv" [.., .., sfsId, 1 | 0], for the
// patched client), on their own screen too. the game's own invisible mode
// ("fi") is not used: with it the client stops sending where it walks, and
// staff could not see them move. they say nothing while invisible (pubMsg).
const setInvisible = (session, invisible) => {
if (Boolean(session.invisible) === invisible) {
return;
}
const {room} = session;
const shown = Boolean(room && session.pos);
const before = shown ? watchers(session) : [];
session.invisible = invisible;
const after = shown ? watchers(session) : [];
for (const other of before.filter(other => !after.includes(other))) {
other.sendXt("ar", room.id, session.id);
}
for (const other of after) {
if (before.includes(other)) {
other.sendXt("xiv", -1, session.id, invisible ? 1 : 0);
}
else {
sendAvatarCreate(other, session);
}
}
if (shown) {
session.sendXt("xiv", -1, session.id, invisible ? 1 : 0);
}
// the patched client's message box, as the staff commands answer in
session.sendXt("xtl", -1, invisible ? "You are invisible: only staff see you, and you cannot chat. Say !invisible again to be seen."
: "You can be seen again.");
modlog.record(session.account.username, invisible ? "went invisible (in game)" : "became visible (in game)", "", room ? room.name : "");
};
// what an account's game knows of its staff role ("xsp", AJClient.onStaff),
// sent again when the admin changed it: nothing for one no longer staff.
// one that may no longer go invisible is seen again.
const refreshStaff = account => {
const session = findOnline(account.username);
if (!session) {
return;
}
const active = roles.isActiveStaff(account);
session.sendXt("xsp", -1, active ? roles.roleOf(account) : "", active ? roles.permissionsOf(account).join(",") : "");
if (session.invisible && !roles.can(account, "staff.invisible")) {
setInvisible(session, false);
}
};
// items taken from an account (lib/itemcontrol.js): its game, if playing,
// and anybody in its den are told. `worn`: clothing it had on went too.
const itemsTaken = (account, kind, invs, worn) => {
const session = findOnline(account.username);
if (session && kind === "den") {
dens.sendDenItems(session);
}
else if (session) {
sendClothingRemoved(session, invs);
if (worn) {
sendItemList(session, session, false);
refreshForOthers(session);
}
}
const den = kind === "den" ? rooms.get(`den${account.username}`) : null;
for (const other of den ? den.sessions : []) {
dens.sendDenState(other, den, false);
}
};
// staff moving a player: `whoName` to the room `toName` is in (summon is
// the player to the staff member, goto the staff member to the player). both
// online, `toName` in a room. the room's own rules still apply: a full room
// or a locked den keeps them out.
// they land where `toName` stands (the patched client's "xgt": [x, y,
// "1" same room, teleported now | "0" the spot to spawn on in the next
// room], or [] to forget a spot not used). with nobody's spot known yet,
// it is the room's usual spawn.
const staffMove = (whoName, toName) => {
const who = findOnline(whoName);
const to = findOnline(toName);
if (!who) {
return {error: `${whoName} is not online.`};
}
if (!to || !to.room) {
return {error: `${toName} is not in a room.`};
}
const room = to.room;
const shown = room.displayName || room.name;
const spot = to.pos ? [to.pos.x, to.pos.y] : null;
if (who.room === room) {
if (!spot) {
return {error: "Already in the same room."};
}
who.sendXt("xgt", -1, ...spot, 1);
return {ok: true, room: shown};
}
if (room.sessions.size >= config.maxUsersPerRoom) {
return {error: `${shown} is full.`};
}
if (spot) {
who.sendXt("xgt", -1, ...spot, 0);
}
joinRoom(who, room.name);
if (who.room !== room) {
if (spot) {
who.sendXt("xgt", -1);
}
return {error: `Could not get into ${shown}.`};
}
return {ok: true, room: shown};
};
const context = {
others: watchers,
watchers,
@@ -916,8 +1155,14 @@ const context = {
tell: (...args) => tell(...args),
leaveRoom: (...args) => leaveRoom(...args),
ask: (...args) => ask(...args),
travel: (session, base) => joinRoom(session, `${base}#${config.shards[0].id}`),
travel: (session, base) => joinRoom(session, `${base}#${session.worldId || config.shards[0].id}`),
worldOf,
worldName,
joinRoom: (...args) => joinRoom(...args),
staffMove: (...args) => staffMove(...args),
setInvisible: (...args) => setInvisible(...args),
// the moderation module, made after this context (lib/commands.js uses it)
staffModeration: () => moderation,
reloadRoom: session => reloadRoom(session),
buyAgain: session => handlers[session.lastPurchase.cmd](session, session.lastPurchase.roomId, session.lastPurchase.params),
};
@@ -934,7 +1179,8 @@ const trades = tradeHandlers(context);
achievements.setFinder(findOnline);
Object.assign(handlers, avatarHandlers(context), itemHandlers(context), pets.handlers, dens.handlers({...context, others}),
buddies.handlers, moderation.handlers, trades.handlers, achievements.handlers, adopt.handlers, worldItems.handlers,
parties.handlers, ecards.handlers, walls.handlers, minigames.handlers, adventures.handlers, stubHandlers);
parties.handlers, ecards.handlers, walls.handlers, minigames.handlers, adventures.handlers, stubHandlers,
playerItems.handlers({itemsTaken: (...args) => itemsTaken(...args)}));
const leaveRoom = session => {
const {room} = session;
@@ -1069,7 +1315,7 @@ const setTheme = (account, theme) => {
// RoomXtCommManager.roomJoinResponse failure branch
const joinFailed = (session, reason) => {
console.log(`[world] ${session.name} could not join: ${reason}`);
console.log(`[world] ${logText(session.name)} could not join: ${logText(reason)}`);
session.sendXt("rj", -1, 0, reason);
};
@@ -1093,8 +1339,11 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
if (room && room === session.room) {
return;
}
// moderators (marked so in the admin panel) are let into a full room.
if (room && room.sessions.size >= config.maxUsersPerRoom && !session.account.moderator) {
// moderators (marked so in the admin panel) are let into a full room, and
// so is a player arriving when every spawn room is full (spawnRoom).
const overflow = session.spawnOverflow;
session.spawnOverflow = false;
if (room && room.sessions.size >= config.maxUsersPerRoom && !roles.isActiveStaff(session.account) && !overflow) {
joinFailed(session, "This room is currently full");
return;
}
@@ -1107,6 +1356,13 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
}
room.sessions.add(session);
session.room = room;
// a land room is in a world, which is the player's now; a den or a party
// is in none, and the game is told the world the player was in, which it
// goes back to when they walk out (RoomManagerWorld.shardId).
if (worldOf(name)) {
session.worldId = worldOf(name);
}
const worldId = session.worldId || shardId;
if (props.denOwner && props.denOwner !== session.account) {
noteDenVisit(props.denOwner, session.account);
}
@@ -1128,7 +1384,7 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
avatar.petInvId,
LANG_ENG,
room.customMusicDef,
shardId);
worldId);
dens.sendRoomProperties(session, roomAsSeenBy(session, room));
for (const other of others(session)) {
@@ -1140,8 +1396,8 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
};
const sendHome = session => {
const shard = config.shards[0];
enterRoom(session, `${config.startupRoom}#${shard.id}`, config.startupRoom, roomInfo.name(config.startupRoom), shard.id);
const shard = session.worldId || config.shards[0].id;
enterRoom(session, `${config.startupRoom}#${shard}`, config.startupRoom, roomInfo.name(config.startupRoom), shard);
};
const emptyRoom = name => {
@@ -1203,6 +1459,37 @@ const onUnblocked = (session, target) => {
}
};
// a world for a player arriving: one at random of those whose spawn rooms
// are not all full; with every one full, the emptiest.
const pickWorld = () => {
const open = config.shards.filter(shard => config.spawnRooms.some(base => !roomFull(`${base}#${shard.id}`)));
if (open.length > 0) {
return open[Math.floor(Math.random() * open.length)].id;
}
return config.shards.reduce((emptiest, shard) => (inWorld(shard.id).length < inWorld(emptiest.id).length ? shard : emptiest)).id;
};
const roomFull = name => {
const room = rooms.get(name);
return Boolean(room) && room.sessions.size >= config.maxUsersPerRoom;
};
// a spawn room (config.spawnRooms) at random, of those with space; with
// all of them full, the emptiest, which lets this player in over the cap.
const spawnRoom = (session, shardId) => {
const known = config.spawnRooms.filter(base => defpacks.roomDef(base));
if (known.length === 0) {
return config.startupRoom;
}
const open = known.filter(base => !roomFull(`${base}#${shardId}`));
if (open.length > 0) {
return open[Math.floor(Math.random() * open.length)];
}
const size = base => (rooms.get(`${base}#${shardId}`) || {sessions: new Set()}).sessions.size;
session.spawnOverflow = true;
return known.reduce((emptiest, base) => (size(base) < size(emptiest) ? base : emptiest));
};
const joinRoom = (session, requested) => {
// "jamaa_township.room_main#-1": path, then shard (-1 = pick one for me).
let [base, shardText] = requested.split("@")[0].split("#");
@@ -1227,23 +1514,41 @@ const joinRoom = (session, requested) => {
// non-buddy's until then: it is sent ahead of the first room, as the
// client takes it unasked (BuddyManager.buddyListResponseHandler).
handlers.bl(session);
// the game asks for world -1 ("pick one for me") unless it is going back
// to one (after a reconnect, say).
session.worldId = worldOf(`#${shardText}`) || pickWorld();
const {startInDen, startRoom, username} = session.account;
const den = startInDen ? username : /^den/i.test(startRoom || "") ? startRoom.slice(3) : null;
if (den !== null && accounts.byName(den)) {
joinDen(session, `den${den}`);
return;
}
// any other name asked for that is a room here; else the usual one.
// any other name asked for that is a room here and has space; else one
// of the spawn rooms that has, so nobody's login ends at "room is full".
const asked = (startRoom || "").split("#")[0].toLowerCase();
if (!startInDen && defpacks.roomDef(asked) && !asked.startsWith("den")) {
base = asked;
}
const shardId = session.worldId;
base = !startInDen && defpacks.roomDef(asked) && !asked.startsWith("den") && !roomFull(`${asked}#${shardId}`)
? asked : spawnRoom(session, shardId);
shardText = String(shardId);
}
// switching worlds (the settings menu's world list asks for the township of
// the one picked): a full room there is swapped for one with space.
else if (worldOf(`#${shardText}`) && session.worldId && worldOf(`#${shardText}`) !== session.worldId
&& roomFull(`${base}#${shardText}`) && config.spawnRooms.includes(base)) {
base = spawnRoom(session, Number(shardText));
}
if (!defpacks.roomDef(base) || base.startsWith("den")) {
joinFailed(session, `Room "${requested}" is not supported by this server`);
return;
}
const shard = config.shards.find(s => s.id === Number(shardText)) || config.shards[0];
// a world that is not one here (-1, or one the game made up because every
// world was full) is the player's own.
let shard = config.shards.find(s => s.id === Number(shardText)) || config.shards.find(s => s.id === session.worldId) || config.shards[0];
// full there: with "Find Open World" on, the same room in a world that
// has space (moderators get into a full room anyway).
if (roomFull(`${base}#${shard.id}`) && !session.account.moderator && findOpenWorld(session.account)) {
shard = config.shards.find(other => !roomFull(`${base}#${other.id}`)) || shard;
}
enterRoom(session, `${base}#${shard.id}`, base, roomInfo.name(base), shard.id);
};
@@ -1255,7 +1560,7 @@ const joinDen = (session, requested) => {
// room like any other (lib/epicdens.js). A player of that name comes first.
const showcase = owner ? null : epicDens.byName(requested.slice(3));
if (showcase) {
const shard = config.shards[0].id;
const shard = session.worldId || config.shards[0].id;
enterRoom(session, `${showcase.base}#${shard}`, showcase.base, showcase.name, shard);
return;
}
@@ -1283,7 +1588,7 @@ const unhandled = (cmd, params) => {
const key = cmd === "gl" ? `gl ${params[0]}` : cmd;
if (!seenUnhandled.has(key) && seenUnhandled.size < 500) {
seenUnhandled.add(key);
console.log(`[world] no handler for xt "${key}" (params: ${JSON.stringify(params).slice(0, 200)}) - the client gets no reply`);
console.log(`[world] no handler for xt "${logText(key)}" (params: ${logText(JSON.stringify(params).slice(0, 200))}) - the client gets no reply`);
}
};
@@ -1348,25 +1653,43 @@ module.exports = {
session.sendXt("uc", session.room.id, session.id, ...fields);
return;
}
fields[0] = said;
// invisible staff give commands and say nothing: the bubble
// waiting goes, as for a silenced player.
if (session.invisible) {
session.sendXt("uc", session.room.id, session.id, -1, 5);
return;
}
// how much there is of it (lib/chatspam.js): a key held down, a
// word over and over, shouting, a wall of emoji are cut down; the
// same line again and again is not sent.
const line = chatSpam.tidy(said);
if (!line || chatSpam.repeated(session, line)) {
session.sendXt("uc", session.room.id, session.id, -1, 5);
return;
}
fields[0] = line;
// the server's filter (lib/chatfilter.js): the line reaches
// nobody, the sender sees the game's warning screen, and it is
// kept in the chat log for the moderators, marked as not sent.
const rule = chatFilter.broken(said);
const rule = chatFilter.broken(line);
if (rule) {
session.sendXt("uc", session.room.id, session.id, -1, 5);
chatFilter.warn(session);
chatlog.record(session.account, session.room.name, `(not sent) ${said}`);
console.log(`[filter] ${session.name} in ${session.room.name}: "${said}" (${rule})`);
chatlog.record(session.account, session.room.name, `(not sent) ${line}`);
console.log(`[filter] ${logText(session.name)} in ${logText(session.room.name)}: "${logText(line)}" (${logText(rule)})`);
return;
}
session.recentChat.push(`${new Date().toISOString().slice(11, 19)} ${said}`);
session.recentChat.push(`${new Date().toISOString().slice(11, 19)} ${line}`);
session.recentChat = session.recentChat.slice(-RECENT_CHAT_LINES);
chatlog.record(session.account, session.room.name, said);
chatlog.record(session.account, session.room.name, line);
}
// nobody hears a player they have blocked, and with chat switched
// off nobody's typed lines arrive at all.
// an invisible staff member's emotes and the like reach staff only.
for (const recipient of echo ? session.room.sessions : others(session)) {
if (session.invisible && recipient !== session && !roles.isActiveStaff(recipient.account)) {
continue;
}
if (recipient === session || (!blocks.has(recipient.account, session.account) && (!echo || accounts.featureOn(recipient.account, "chat")))) {
recipient.sendXt("uc", session.room.id, session.id, ...fields);
}
@@ -1378,7 +1701,7 @@ module.exports = {
session.close();
return;
default:
console.log(`[world] unhandled sys "${msg.action}" from ${session.name}`);
console.log(`[world] unhandled sys "${logText(msg.action)}" from ${logText(session.name)}`);
}
},
@@ -1444,6 +1767,9 @@ module.exports = {
return true;
},
moderation,
staffMove,
itemsTaken,
refreshStaff,
walls,
ecards,
// called when the admin changed an account's badges: a name tag showing
@@ -1574,7 +1900,7 @@ module.exports = {
return "There is no such room";
}
minigames.leave(session);
const shard = config.shards[0].id;
const shard = session.worldId || config.shards[0].id;
enterRoom(session, `${base}#${shard}`, base, roomInfo.name(base), shard);
return null;
},
@@ -1588,6 +1914,20 @@ module.exports = {
}
return there.length;
},
// puts out these accounts, if playing, with the game's banned notice:
// their computer was banned (lib/devices.js). returns how many were.
disconnectBanned(list) {
let out = 0;
for (const account of list) {
const session = findOnline(account.username);
if (session) {
session.sendXt("fd", -1, "fb", 1, moderation.PERMANENT);
session.close();
out++;
}
}
return out;
},
// takes the account out of the world at once (not when its socket gets
// round to closing), so the caller can go on to rename or delete it.
disconnect(account) {
@@ -1600,7 +1940,7 @@ module.exports = {
},
players: () => [...online.values()].map(session => ({
username: session.account.username,
room: session.room ? session.room.name : null,
room: session.room ? session.room.name.replace(/#(\d+)$/, (whole, id) => (worldOf(whole) ? ` (${worldName(Number(id))})` : whole)) : null,
address: session.address,
})),
};
+144
View File
@@ -136,6 +136,14 @@
input:not([type="checkbox"]), textarea { width: 100%; }
textarea { min-height: 110px; resize: vertical; }
.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; }
.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; }
@@ -303,6 +311,14 @@
</details>
</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>
<h2>Username rejected</h2>
<form id="rename-form">
@@ -596,6 +612,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 = 512;
const PICTURE_BYTES = 300 * 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, 384, 256, 128]) {
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 = () => {
$("gate").hidden = true;
$("page").hidden = false;
@@ -614,6 +757,7 @@
if (account.nameRejected) {
return;
}
renderMyItems();
$("lock-notice").hidden = !account.locked;
const tiles = [
+1451 -147
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 945 B

+1292 -135
View File
File diff suppressed because it is too large. Load diff
+8 -5
View File
@@ -172,8 +172,9 @@
<tr><td>Username, password (stored only as a salted hash), and the date and version of the terms you accepted</td><td>To give you an account</td></tr>
<tr><td>Your game data: animals, items, dens, pets, buddies, block list, trades, achievements, settings</td><td>To run the game for you</td></tr>
<tr><td>What you choose to write or make: bio, Discord username (optional), Jam-A-Grams, wall posts, paintings, feedback</td><td>To show or deliver it as you asked</td></tr>
<tr><td>Typed chat and whispers, with the room and time</td><td>Moderation: reviewing reports and deciding on bans</td></tr>
<tr><td>Typed chat and whispers, with the room and time, and the words of Jam-A-Grams and wall posts, with who they went to</td><td>Moderation: reviewing reports and deciding on bans</td></tr>
<tr><td>IP address at each sign-in, and sign-in times</td><td>Security: your sign-in history, limiting abuse, address bans, and finding accounts made to get around a ban</td></tr>
<tr><td>Hardware hashes, sent by the Burrow client at each sign-in. The client reads a few identifiers of your device (its system id, hardware serial numbers, network card addresses, and a random id the client makes for itself) and turns each into a one-way hash before sending it; we hash them again with a secret key of our own. The identifiers themselves never leave your device, and the hashes cannot be turned back into them: they do not tell us who you are, what your device is, or anything else about it, and mean nothing outside this server. We also note if the identifiers look missing or altered</td><td>Only to prevent ban evasion: hardware bans, and finding accounts made to get around a ban. They are not used for tracking or advertising and are never shared</td></tr>
<tr><td>When you log in to the game, how long each visit lasts, and your total playtime</td><td>To show you your playtime, and for overall activity figures (how many people play and when) that staff use to run the server</td></tr>
<tr><td>The number of players online, counted every minute</td><td>Overall activity figures. This count is not linked to anyone</td></tr>
<tr><td>Reports, bans and their reasons, appeals, username rejections</td><td>Moderation and preventing ban evasion</td></tr>
@@ -188,7 +189,7 @@
<h2>3. Who can see it</h2>
<ul>
<li><b>Other players</b> see your username, animals, den, bio, Discord username if you add one, badges, when you joined and were last seen, your chat in the room you are in, whether you are currently banned, and your total playtime if you make it public on your account page (it is private unless you choose otherwise).</li>
<li><b>Moderators</b> can also read stored chat and whispers, reports, and ban history, and see your total playtime and the overall activity figures. They cannot see your IP address, sign-in history, password or inventory.</li>
<li><b>Moderators</b> can also read stored chat, whispers, Jam-A-Grams and wall posts, reports, and ban history, see which other accounts used the same device or signed in from the same IP addresses (never the addresses themselves; for devices, only the hashes described in section 2), and see your total playtime and the overall activity figures. They cannot see your IP address, sign-in history, password or inventory.</li>
<li><b>Moderators</b> can look up which accounts signed in from an IP address they already have, only to stop ban evasion: finding new accounts made by someone who is banned. The search shows only account names and when they signed in from that address, never the address itself or any other address. Every search is recorded under the moderator's name and reviewed by the administrator.</li>
<li><b>The administrator</b> can see everything listed in section 2, and can search accounts by IP address for the same purpose.</li>
<li><b>Our hosting provider</b> stores the data on our behalf, in {{hostedIn}}. If that is outside your country, your data is transferred there to provide the service.</li>
@@ -211,7 +212,9 @@
<thead><tr><th>Data</th><th>Kept</th></tr></thead>
<tbody>
<tr><td>Account and game data</td><td>Until you delete your account</td></tr>
<tr><td>Chat and whispers</td><td>30 days</td></tr>
<tr><td>Chat, whispers, and the words of Jam-A-Grams and wall posts</td><td>30 days</td></tr>
<tr><td>Hardware hashes</td><td>Until you delete your account (the latest 60)</td></tr>
<tr><td>Hardware bans (hashes only)</td><td>Until the ban is lifted</td></tr>
<tr><td>Sign-in history with IP addresses</td><td>Your last 40 sign-ins, and none older than 90 days</td></tr>
<tr><td>Error reports and server logs</td><td>Up to 30 days</td></tr>
<tr><td>Handled reports, feedback and username requests</td><td>12 months</td></tr>
@@ -222,7 +225,7 @@
<tr><td>Backups</td><td>14 days</td></tr>
</tbody>
</table></div>
<p style="margin-top:12px">When you delete your account we delete your game data, chat, appeal, feedback, username requests and paintings straight away, and your total playtime. Your past logins stay in the overall activity figures for up to 12 months and are not shown to anyone by name. Your username is held for 30 days so nobody can pass as you, and ban records are kept as shown above. Copies in backups disappear within 14 days.</p>
<p style="margin-top:12px">When you delete your account we delete your game data, chat, hardware hashes, appeal, feedback, username requests and paintings straight away, and your total playtime. Your past logins stay in the overall activity figures for up to 12 months and are not shown to anyone by name. Your username is held for 30 days so nobody can pass as you, and ban records are kept as shown above. Copies in backups disappear within 14 days.</p>
</section>
<section>
@@ -243,7 +246,7 @@
<section>
<h2>8. Cookies and your device</h2>
<p>The website sets only cookies that are needed to keep you signed in: a session cookie on your account page (12 hours) and, if you choose "Trust this device", a 2FA cookie (30 days). The client keeps your saved sign-in on your own computer if you tick "Remember me". Cloudflare may add a security cookie of its own (section 4). There are no advertising or tracking cookies.</p>
<p>The website sets only cookies that are needed to keep you signed in: a session cookie on your account page (12 hours) and, if you choose "Trust this device", a 2FA cookie (30 days). The client keeps your saved sign-in on your own device if you tick "Remember me". Cloudflare may add a security cookie of its own (section 4). There are no advertising or tracking cookies.</p>
</section>
<section>
+1
View File
@@ -234,6 +234,7 @@
username_taken: "That username is already taken.",
name_not_allowed: "That username is not allowed.",
invalid_password: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit.",
weak_password: "That password is too easy to guess: it is a common one, or has your username in it.",
choose_animal: "Choose an animal first.",
too_many_registrations: "Too many accounts were created from your address. Try again in an hour.",
address_banned: "Your address is banned.",
+4
View File
@@ -5,10 +5,12 @@ require("./lib/log.js"); // first, so everything printed reaches the admin panel
const fs = require("fs");
const accounts = require("./lib/accounts.js");
const bans = require("./lib/bans.js");
const devices = require("./lib/devices.js");
const chatlog = require("./lib/chatlog.js");
const modlog = require("./lib/modlog.js");
const retention = require("./lib/retention.js");
const colours = require("./lib/colours.js");
const customItems = require("./lib/customitems.js");
const config = require("./config.js");
const defpacks = require("./lib/defpacks.js");
const http = require("./lib/http.js");
@@ -37,9 +39,11 @@ const main = async () => {
fs.chmodSync(config.dataDir, 0o700);
accounts.startBackups();
colours.load();
customItems.load();
reports.load();
support.load();
bans.load();
devices.load();
chatlog.load();
modlog.load();
masterpieces.load();
+1751 -1
View File
File diff suppressed because it is too large. Load diff
+716
View File
@@ -0,0 +1,716 @@
package gui
{
import avatar.Avatar;
import avatar.AvatarManager;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import flash.utils.Dictionary;
import game.ArtStudioKit;
import pet.WorldPet;
// the actions window. an animal has the art for its own set of actions
// only (a land animal's sitting, sleeping, hopping; an ocean animal's
// diving, swirling, posing), so it is shown its own set in any room: a
// land animal underwater still sits and hops. an animal of land and ocean
// both (seal, otter...) has both, and a button above the window swaps the
// set shown ("Swim moves" on land, "Land moves" underwater).
//
// the sets share buttons, and ":dance:" and ":play:" are the same name in
// both (the room picks the animation, AvatarWorldView.setAction): the
// other set's dance and play go by names of their own (OTHER_SET_NAMES).
// the other names (":dive:", ":sitNW:"...) are one set's already.
public class ActionManager
{
private static const OTHER_SET_NAMES:Object = {
"danceAnim_btnCont":[":danceLand:",":danceSwim:"],
"playAnim_btnCont":[":playLand:",":playSwim:"]
};
private static const OTHER_SET_BUTTONS:Object = {
":danceLand:":"danceAnim_btnCont",
":danceSwim:":"danceAnim_btnCont",
":playLand:":"playAnim_btnCont",
":playSwim:":"playAnim_btnCont"
};
private static const SWAP_W:int = 150;
private static const SWAP_H:int = 26;
// the set the window shows: the room's, unless swapped
private var _oceanShown:Boolean;
// action sprites made from a name (matchActionString), and that name
private var _names:Dictionary = new Dictionary(true);
private var _swapBtn:MovieClip;
// Whether the next (and currently selected) action is horizontally
// mirrored. The state is sent with the action to other players.
public var mirrorActions:Boolean = false;
private var _lastAction:Sprite;
// sitting facing forward (":sitS:", AvatarWorldView's animation 1): the
// "Forward" in the middle of the four arrows. its action sprite is a
// class of the client's own (SitForwardAction), not of the HUD's art.
private static const SIT_FORWARD:String = "SitForwardAction";
private const ACTIONWINDOW_DIM_ALPHA:Number = 0.5;
private const ACTIONWINDOW_BRIGHT_ALPHA:Number = 1;
public var actionBtn:MovieClip;
public var actionWindow:MovieClip;
public var emoteBtn:MovieClip;
public var emoteWindow:Sprite;
public var safeChatBtn:MovieClip;
public var safeChatTree:MovieClip;
public var setActionCallback:Function;
public var actionSprites:Array = ["sit1BtnCont","sit2BtnCont","sit3BtnCont","sit4BtnCont","danceAnim_btnCont","sleepAnim_btnCont","hopAnim_btnCont","playAnim_btnCont","pose1BtnCont","pose2BtnCont","diveAnim_btnCont","swirlAnim_btnCont"];
public var actionStrings:Object;
private var _actions:MovieClip;
private var _petActions:MovieClip;
private var _views:Array;
private var _titleBanner:Sprite;
public function ActionManager(param1:Function, param2:MovieClip, param3:MovieClip, param4:MovieClip, param5:Sprite, param6:MovieClip, param7:MovieClip)
{
super();
if(setActionCallback != null)
{
throw new Error("ERROR: Singleton ActionManager did not expect to be created twice!");
}
setActionCallback = param1;
actionBtn = param2;
actionBtn.addEventListener("mouseDown",actionBtnDownHandler,false,0,true);
actionWindow = param3;
addAllActions();
addSwapButton();
actionWindow.addChild(_actions);
actionWindow.addChild(_petActions);
_petActions.visible = false;
actionWindow.poseBtns = _actions.poseBtns;
actionWindow.diveBtn = _actions.diveBtn;
actionWindow.swirlBtn = _actions.swirlBtn;
actionWindow.sitBtns = _actions.sitBtns;
actionWindow.visible = false;
emoteBtn = param4;
emoteWindow = param5;
safeChatBtn = param6;
safeChatTree = param7;
setupTitleBanner();
}
// a room joined: its set is shown, if the animal has it.
public function turnOnOceanActions(param1:Boolean) : void
{
_oceanShown = ownSet(param1);
showSet();
}
// the set to show in a room (true: the ocean's): the room's, unless the
// player's animal has the art of the other only.
private static function ownSet(param1:Boolean) : Boolean
{
var _loc2_:Avatar = AvatarManager.playerAvatar;
if(_loc2_ == null)
{
return param1;
}
var _loc3_:Boolean = Utility.isLand(_loc2_.enviroTypeFlag);
var _loc4_:Boolean = Utility.isOcean(_loc2_.enviroTypeFlag);
return _loc3_ == _loc4_ ? param1 : _loc4_;
}
// whether the player's animal has the art of a set (true: the ocean's)
private static function playerHasSet(param1:Boolean) : Boolean
{
var _loc2_:Avatar = AvatarManager.playerAvatar;
if(_loc2_ == null)
{
return false;
}
return param1 ? Utility.isOcean(_loc2_.enviroTypeFlag) : Utility.isLand(_loc2_.enviroTypeFlag);
}
private function showSet() : void
{
actionWindow.poseBtns.visible = _oceanShown;
actionWindow.diveBtn.visible = _oceanShown;
actionWindow.swirlBtn.visible = _oceanShown;
actionWindow.sitBtns.visible = !_oceanShown;
if(_swapBtn)
{
ArtStudioKit.setLabel(_swapBtn,_oceanShown ? "Land moves" : "Swim moves");
}
}
private function addSwapButton() : void
{
_swapBtn = ArtStudioKit.button(null,null,SWAP_W,SWAP_H,onSwapBtn,"Swim moves");
// the window closes on a press anywhere else
_swapBtn.addEventListener("mouseDown",stopPress,false,0,true);
_swapBtn.visible = false;
_actions.addChild(_swapBtn);
}
private function stopPress(param1:MouseEvent) : void
{
param1.stopPropagation();
}
private function onSwapBtn(param1:MouseEvent) : void
{
_oceanShown = !_oceanShown;
showSet();
}
private static function roomIsOcean() : Boolean
{
return AvatarManager.roomEnviroType == 1;
}
// whether the player's animal has the art of both sets
private static function playerHasBothSets() : Boolean
{
var _loc1_:Avatar = AvatarManager.playerAvatar;
return _loc1_ != null && Utility.isLand(_loc1_.enviroTypeFlag) && Utility.isOcean(_loc1_.enviroTypeFlag);
}
// the swap button, for an animal of both sets, above the window; any
// other is shown its own set (the player may have changed animals
// since the room was joined).
private function updateSwapButton() : void
{
var _loc1_:Boolean = playerHasBothSets();
var _loc2_:Rectangle = null;
if(!_loc1_ && _oceanShown != ownSet(roomIsOcean()))
{
_oceanShown = ownSet(roomIsOcean());
showSet();
}
_swapBtn.visible = _loc1_;
if(_loc1_)
{
_loc2_ = actionWindow.ba.getBounds(actionWindow);
if(_titleBanner && actionWindow.contains(_titleBanner))
{
_loc2_ = _loc2_.union(_titleBanner.getBounds(actionWindow));
}
_swapBtn.x = int(_loc2_.x + (_loc2_.width - SWAP_W) / 2);
_swapBtn.y = int(_loc2_.top - SWAP_H - 4);
}
}
public function turnOnPetActions(param1:Boolean) : void
{
if(param1)
{
_petActions.visible = true;
_actions.visible = false;
}
else
{
_petActions.visible = false;
_actions.visible = true;
}
}
public function reload(param1:MovieClip, param2:MovieClip, param3:MovieClip, param4:Sprite, param5:MovieClip, param6:MovieClip, param7:Function) : void
{
setActionCallback = param7;
if(actionBtn)
{
actionBtn.removeEventListener("mouseDown",actionBtnDownHandler);
}
actionBtn = param1;
actionBtn.addEventListener("mouseDown",actionBtnDownHandler,false,0,true);
while(actionWindow.numChildren > 2)
{
actionWindow.removeChildAt(actionWindow.numChildren - 1);
}
actionWindow = param2;
addAllActions();
addSwapButton();
actionWindow.addChild(_actions);
actionWindow.addChild(_petActions);
_petActions.visible = false;
actionWindow.poseBtns = _actions.poseBtns;
actionWindow.diveBtn = _actions.diveBtn;
actionWindow.swirlBtn = _actions.swirlBtn;
actionWindow.sitBtns = _actions.sitBtns;
actionWindow.visible = false;
emoteBtn = param3;
emoteWindow = param4;
actionWindow = param2;
safeChatBtn = param5;
safeChatTree = param6;
actionBtn.downToUpState();
setupTitleBanner();
}
private function addAllActions() : void
{
var _loc14_:* = 0;
_loc14_ = 10;
var _loc11_:* = 0;
_loc11_ = 25;
var _loc13_:* = 0;
_loc13_ = 40;
var _loc5_:* = 0;
_loc5_ = 91;
var _loc2_:* = 0;
_loc2_ = 2;
var _loc1_:Number = NaN;
_loc1_ = -72;
var _loc4_:Number = NaN;
_loc4_ = -50;
var _loc10_:Number = NaN;
_loc10_ = -88;
var _loc15_:int = 0;
_loc15_ = 4;
var _loc16_:int = 0;
_loc16_ = 2;
var _loc7_:int = 0;
_loc7_ = 8;
var _loc6_:* = 0;
var _loc3_:Sprite = null;
var _loc12_:Sprite = null;
var _loc8_:int = 0;
var _loc9_:int = 0;
_actions = new MovieClip();
_petActions = new MovieClip();
_loc6_ = 0;
while(_loc6_ < actionSprites.length)
{
if(_loc6_ < 8)
{
_loc3_ = GETDEFINITIONBYNAME(_loc6_ < 4 ? "sitBtns" : actionSprites[_loc6_]);
if(_loc6_ == 0)
{
_loc3_.x = actionWindow.ba.width * 0.5 + -72 - 25 - 5;
_loc3_.y = 10 + Math.floor(_loc6_ / 2) * 40 + -50;
_actions.addChild(_loc3_);
_actions.sitBtns = _loc3_;
_loc8_ = 1;
while(_loc8_ <= 4)
{
_loc12_ = _loc3_["sit" + _loc8_ + "Btn"];
_loc12_.buttonMode = true;
_loc12_.useHandCursor = true;
_loc12_.tabEnabled = true;
_loc12_.tabChildren = false;
_loc12_.addEventListener("mouseDown",actionClickHandler,false,0,true);
_loc8_++;
}
addSitDirectionButtons(_loc3_);
}
else if(_loc6_ >= 4)
{
_loc3_.x = 25 + (_loc6_ % 2 * 91 + -72);
_loc3_.y = 10 + Math.floor(_loc6_ / 2) * 40 + -88;
_actions.addChild(_loc3_);
_loc3_.buttonMode = true;
_loc3_.useHandCursor = true;
_loc3_.tabEnabled = true;
_loc3_.tabChildren = false;
_loc3_.addEventListener("mouseDown",actionClickHandler,false,0,true);
}
}
else
{
_loc3_ = GETDEFINITIONBYNAME(_loc6_ == 8 ? "poseBtns" : actionSprites[_loc6_]);
if(_loc6_ == 8)
{
_loc3_.visible = false;
_actions.poseBtns = _loc3_;
_loc3_.x = actionWindow.ba.width * 0.5 + -72 - 25 - 5;
_loc3_.y = 10 + Math.floor((_loc6_ - 8) / 2) * 40 + -50;
_actions.addChild(_loc3_);
_loc9_ = 1;
while(_loc9_ <= 2)
{
_loc12_ = _loc3_["pose" + _loc9_ + "Btn"];
_loc12_.buttonMode = true;
_loc12_.useHandCursor = true;
_loc12_.tabEnabled = true;
_loc12_.tabChildren = false;
_loc12_.addEventListener("mouseDown",actionClickHandler,false,0,true);
_loc9_++;
}
}
else if(_loc6_ >= 8 + 2)
{
_loc3_.visible = false;
if(_loc6_ == actionSprites.length - 1)
{
_actions.diveBtn = _loc3_;
}
else
{
_actions.swirlBtn = _loc3_;
}
_loc3_.x = 25 + ((_loc6_ - 5) % 2 * 91 + -72);
_loc3_.y = 10 + Math.floor((_loc6_ - 5) / 2) * 40 + -88;
_actions.addChild(_loc3_);
_loc3_.buttonMode = true;
_loc3_.useHandCursor = true;
_loc3_.tabEnabled = true;
_loc3_.tabChildren = false;
_loc3_.addEventListener("mouseDown",actionClickHandler,false,0,true);
}
}
_loc6_++;
}
_loc3_ = GETDEFINITIONBYNAME("playPetAnim_btnCont");
_loc3_.y = -31;
_loc3_.buttonMode = true;
_loc3_.useHandCursor = true;
_loc3_.tabEnabled = true;
_loc3_.tabChildren = false;
_loc3_.addEventListener("mouseDown",onPetPlayBtn,false,0,true);
_petActions.addChild(_loc3_);
_loc3_ = GETDEFINITIONBYNAME("dancePetAnim_btnCont");
_petActions.danceBtn = _loc3_;
_loc3_.y = 31;
_loc3_.buttonMode = true;
_loc3_.useHandCursor = true;
_loc3_.tabEnabled = true;
_loc3_.tabChildren = false;
_loc3_.addEventListener("mouseDown",actionClickHandler,false,0,true);
_petActions.addChild(_loc3_);
actionStrings = {};
actionStrings["sit1BtnCont"] = actionStrings["pose1BtnCont"] = [":sitNW:",":poseLeft:"];
actionStrings["sit2BtnCont"] = [":sitNE:"];
actionStrings["sit3BtnCont"] = [":sitSE:"];
actionStrings["sit4BtnCont"] = actionStrings["pose2BtnCont"] = [":sitSW:",":poseRight:"];
actionStrings["danceAnim_btnCont"] = actionStrings["dancePetAnim_btnCont"] = [":dance:"];
actionStrings["sleepAnim_btnCont"] = actionStrings["diveAnim_btnCont"] = [":sleep:",":dive:"];
actionStrings["hopAnim_btnCont"] = actionStrings["swirlAnim_btnCont"] = [":hop:",":swirl:"];
actionStrings["playAnim_btnCont"] = [":play:"];
actionStrings[SIT_FORWARD] = [":sitS:"];
}
private function setupTitleBanner() : void
{
if(emoteWindow.name.indexOf("Quest") == -1)
{
if(_titleBanner)
{
if(!actionWindow.contains(_titleBanner))
{
actionWindow.addChild(_titleBanner);
}
}
else
{
_titleBanner = GETDEFINITIONBYNAME("AnimsTitleBanner");
_titleBanner.x = -91.75;
_titleBanner.y = -91.25;
actionWindow.addChild(_titleBanner);
}
}
}
public function destroy() : void
{
setActionCallback = null;
actionBtn.removeEventListener("mouseDown",actionBtnDownHandler);
actionBtn = null;
actionWindow.visible = false;
actionWindow = null;
emoteBtn = null;
emoteWindow = null;
safeChatBtn = null;
safeChatTree = null;
}
// the name a button sends: the set shown's, and for dance and play the
// other set's own name when the set shown is not the room's.
private function nameFor(param1:String) : String
{
var _loc2_:Array = actionStrings[param1];
if(!_loc2_)
{
return null;
}
if(OTHER_SET_NAMES[param1] && _oceanShown != roomIsOcean())
{
return OTHER_SET_NAMES[param1][_oceanShown ? 1 : 0];
}
return _loc2_.length > 1 ? _loc2_[_oceanShown ? 1 : 0] : _loc2_[0];
}
// Front and Back sit facing straight forward and straight away. Mirror
// replays whichever action was picked most recently in the other
// horizontal direction (including dance, sleep, hop and play).
private function addSitDirectionButtons(param1:MovieClip) : void
{
var _loc2_:Rectangle = param1.getBounds(param1);
var _loc3_:Number = _loc2_.x + _loc2_.width * 0.5;
var _loc4_:Number = _loc2_.y + _loc2_.height * 0.5;
var _loc5_:Sprite = addDirectionButton(param1,"Front",0,0,false);
var _loc6_:Sprite = addDirectionButton(param1,"Back",0,0,true);
var _loc7_:Number = _loc3_ - (_loc5_.width + 3 + _loc6_.width) * 0.5;
_loc5_.x = _loc7_;
_loc6_.x = _loc7_ + _loc5_.width + 3;
_loc5_.y = _loc6_.y = _loc4_ - 13;
var _loc8_:Sprite = actionPill("Mirror");
var _loc9_:Sprite = actionHitTarget(_loc8_);
_loc9_.x = _loc3_ - _loc9_.width * 0.5;
_loc9_.y = _loc4_ + 3;
_loc9_.addEventListener("mouseDown",mirrorClickHandler,false,0,true);
_loc9_.addEventListener("mouseOver",function(param1:MouseEvent):void
{
_loc9_.alpha = 0.8;
},false,0,true);
_loc9_.addEventListener("mouseOut",function(param1:MouseEvent):void
{
_loc9_.alpha = 1;
},false,0,true);
param1.addChild(_loc9_);
}
private function addDirectionButton(param1:MovieClip, param2:String, param3:Number, param4:Number, param5:Boolean) : Sprite
{
var _loc6_:Sprite = actionPill(param2);
var _loc7_:Sprite = actionHitTarget(_loc6_);
_loc7_.x = param3;
_loc7_.y = param4;
_loc7_.name = param5 ? "sitBackHit" : "sitFrontHit";
_loc7_.addEventListener("mouseDown",sitDirectionClickHandler,false,0,true);
param1.addChild(_loc7_);
return _loc7_;
}
// Keep the generated controls visually uniform. Invisible trailing
// spaces reserve the same room without changing the labels players see.
private function actionPill(param1:String) : Sprite
{
var _loc2_:String = param1 == "Front" ? "Front " : (param1 == "Back" ? "Back " : param1);
return AJClient.makePill(_loc2_,0x5CB82E,0x2C6E16,false,10);
}
private function sitDirectionClickHandler(param1:MouseEvent) : void
{
param1.stopPropagation();
// one sprite class for both; each sprite is named for the way it faces
var _loc2_:Sprite = new SitForwardAction();
_names[_loc2_] = param1.currentTarget.name == "sitBackHit" ? ":sitN:" : ":sitS:";
selectAction(_loc2_);
}
// The sit artwork is itself a MovieClip with mouse children. A separate
// transparent hit target above it keeps our generated labels clickable.
private function actionHitTarget(param1:Sprite) : Sprite
{
var _loc2_:Sprite = new Sprite();
_loc2_.graphics.beginFill(0,0);
_loc2_.graphics.drawRect(0,0,param1.width,param1.height);
_loc2_.graphics.endFill();
_loc2_.addChild(param1);
_loc2_.buttonMode = true;
_loc2_.useHandCursor = true;
_loc2_.mouseEnabled = true;
_loc2_.mouseChildren = false;
return _loc2_;
}
private function selectAction(param1:Sprite, param2:Boolean = false) : void
{
if(!actionBtn.isGray)
{
mirrorActions = param2;
_lastAction = param1;
setActionCallback(param1);
actionBtn.dispatchEvent(new MouseEvent("mouseDown"));
}
}
private function mirrorClickHandler(param1:MouseEvent) : void
{
param1.stopPropagation();
if(!actionBtn.isGray)
{
mirrorActions = !mirrorActions;
if(_lastAction)
{
setActionCallback(_lastAction);
}
}
}
public function rememberAction(param1:Sprite) : void
{
_lastAction = param1;
}
public function getActionString(param1:Sprite) : String
{
if(_names[param1] != undefined)
{
return _names[param1];
}
var _loc2_:String = param1["constructor"].toString();
return nameFor(_loc2_.slice(7,_loc2_.length - 1));
}
// the button for an action's name, which it then stands for. `typed`:
// the player's own, typed in chat, which is held to the sets their
// animal has art for; another player's is taken as it came
// (AvatarWorldView.setAction plays what their animal has art for).
public function matchActionString(param1:String, param2:Boolean = false) : Sprite
{
var _loc3_:int = 0;
if(param1 == ":sitS:" || param1 == ":sitN:")
{
var _loc9_:Sprite = new SitForwardAction();
_names[_loc9_] = param1;
return _loc9_;
}
var _loc4_:String = OTHER_SET_BUTTONS[param1];
var _loc5_:Sprite = null;
if(_loc4_ && param2 && !playerHasSet(param1.indexOf("Swim") != -1))
{
return null;
}
if(!_loc4_)
{
for each(var _loc2_:String in actionSprites)
{
_loc3_ = int(actionStrings[_loc2_].indexOf(param1));
if(_loc3_ != -1)
{
if(actionStrings[_loc2_].length <= 1 || !param2 || playerHasSet(_loc3_ == 1))
{
_loc4_ = _loc2_;
break;
}
}
}
}
if(!_loc4_)
{
return null;
}
_loc5_ = GETDEFINITIONBYNAME(_loc4_);
_names[_loc5_] = param1;
return _loc5_;
}
public function openActions() : void
{
if(!actionWindow.visible)
{
updateSwapButton();
actionWindow.visible = true;
brightenActions();
}
}
public function dimActions() : void
{
if(actionWindow.visible && actionWindow.alpha != 0.5)
{
actionWindow.alpha = 0.5;
}
}
public function brightenActions() : void
{
if(actionWindow.alpha != 1)
{
actionWindow.alpha = 1;
}
}
public function closeActions() : void
{
if(actionWindow.visible)
{
actionWindow.visible = false;
brightenActions();
actionBtn.downToUpState();
}
}
public function grayOutPetDanceBtn(param1:Boolean) : void
{
if(_petActions)
{
_petActions.danceBtn.activateGrayState(param1);
}
}
private function actionBtnDownHandler(param1:MouseEvent) : void
{
param1.stopPropagation();
if(!param1.currentTarget.isGray)
{
if(actionWindow.visible)
{
closeActions();
}
else
{
if(safeChatTree.visible)
{
safeChatBtn.dispatchEvent(param1);
}
if(emoteWindow.visible)
{
emoteBtn.dispatchEvent(param1);
}
openActions();
}
}
}
private function actionClickHandler(param1:MouseEvent) : void
{
param1.stopPropagation();
if(!actionBtn.isGray && !param1.currentTarget.isGray)
{
_lastAction = new param1.currentTarget.constructor();
setActionCallback(_lastAction);
actionBtn.dispatchEvent(new MouseEvent("mouseDown"));
param1.currentTarget.downToUpState();
}
}
private function onPetPlayBtn(param1:MouseEvent) : void
{
var _loc2_:WorldPet = null;
param1.stopPropagation();
if(AvatarManager.playerAvatarWorldView)
{
_loc2_ = AvatarManager.playerAvatarWorldView.getActivePet();
if(_loc2_)
{
AvatarManager.playerAvatarWorldView.faceAnim(0,0,false);
_loc2_.onClick(param1);
}
}
actionBtn.dispatchEvent(new MouseEvent("mouseDown"));
param1.currentTarget.downToUpState();
}
}
}
File diff suppressed because it is too large. Load diff
+380
View File
@@ -0,0 +1,380 @@
package avatar
{
import collection.AccItemCollection;
import com.sbi.graphics.LayerAnim;
import flash.display.Sprite;
import flash.filters.ColorMatrixFilter;
import item.Item;
public class AvatarView extends Sprite
{
protected var _layerAnim:LayerAnim;
protected var _avatar:Avatar;
protected var _skipAnimEnviroCheck:Boolean;
public var avTypeChangedCallback:Function;
public var onAvatarChangedCallback:Function;
private var _isOffScreen:Boolean;
private var _holdAnimId:int;
private var _lastAnimToHappen:int;
public function AvatarView()
{
super();
}
public function set lastAnimToHappen(param1:int) : void
{
_lastAnimToHappen = param1;
}
public function get lastAnimToHappen() : int
{
return _lastAnimToHappen;
}
public function set holdAnimId(param1:int) : void
{
_holdAnimId = param1;
}
public function init(param1:Avatar, param2:Function = null, param3:Function = null, param4:Boolean = false, param5:Boolean = false) : void
{
_holdAnimId = 0;
_avatar = param1;
_avatar.addEventListener("OnAvatarChanged",avatarChanged,false,0,true);
avTypeChangedCallback = param2;
onAvatarChangedCallback = param3;
_skipAnimEnviroCheck = param5;
_layerAnim = LayerAnim.getNew(param4);
_layerAnim.avDefId = _avatar.avTypeId;
if(_avatar.colors)
{
_layerAnim.layers = setLayerHelper();
}
this.addChild(_layerAnim.bitmap);
}
public function destroy(param1:Boolean = false) : void
{
if(param1 && _avatar)
{
_avatar.removeEventListener("OnAvatarChanged",avatarChanged);
_avatar.destroy();
_avatar = null;
}
avTypeChangedCallback = null;
onAvatarChangedCallback = null;
LayerAnim.destroy(_layerAnim);
_layerAnim = null;
}
public function resetAvatar(param1:Avatar) : void
{
if(_avatar && _avatar.hasEventListener("OnAvatarChanged"))
{
_avatar.removeEventListener("OnAvatarChanged",avatarChanged);
}
_avatar = param1;
_avatar.addEventListener("OnAvatarChanged",avatarChanged,false,0,true);
if(_layerAnim)
{
_layerAnim.avDefId = _avatar.avTypeId;
if(_avatar.colors)
{
_layerAnim.layers = setLayerHelper();
}
}
}
public function isValid() : Boolean
{
return _layerAnim != null;
}
public function hideAvatar() : void
{
if(_layerAnim != null)
{
_layerAnim.visible = false;
}
}
public function showAvatar() : void
{
if(_layerAnim != null)
{
_layerAnim.visible = true;
}
}
public function set isOffScreen(param1:Boolean) : void
{
_isOffScreen = param1;
}
public function get isOffScreen() : Boolean
{
return _isOffScreen;
}
public function pauseAnim(param1:Boolean) : void
{
_layerAnim.pause = param1;
}
public function advanceFrame() : void
{
_layerAnim.frame++;
}
public function get frame() : int
{
return _layerAnim.frame;
}
public function set frame(param1:int) : void
{
_layerAnim.frame = param1;
}
public function get flip() : Boolean
{
return _layerAnim.hFlip;
}
public function get animId() : int
{
return _layerAnim.animId;
}
protected function avatarChanged(param1:AvatarEvent) : void
{
if(_layerAnim)
{
if(_layerAnim.avDefId != _avatar.avTypeId)
{
_layerAnim.avDefId = _avatar.avTypeId;
if(avTypeChangedCallback != null)
{
avTypeChangedCallback(this);
}
}
_layerAnim.layers = setLayerHelper();
if(onAvatarChangedCallback != null)
{
onAvatarChangedCallback(this);
}
}
}
protected function setLayerHelper() : Array
{
var _loc1_:AvatarInfo = null;
var _loc2_:AccItemCollection = null;
var _loc3_:* = null;
if(_avatar.inventoryBodyMod && _avatar.inventoryBodyMod.itemCollection && _avatar.inventoryBodyMod.itemCollection.length >= 1)
{
_loc3_ = new AccItemCollection(_avatar.inventoryBodyMod.itemCollection.concatCollection(_avatar.inventoryClothing.itemCollection));
}
else
{
_loc1_ = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(_avatar.userName,_avatar.perUserAvId);
if(_loc1_)
{
_loc2_ = _skipAnimEnviroCheck ? _loc1_.getFullItems(true) : _loc1_.getItems(true);
if(_loc2_)
{
_loc3_ = _loc2_;
}
}
}
return AvatarUtility.layerArrayForItemsAndColors(_loc3_,_avatar.colors,_avatar.avInvId,_avatar.roomType,_skipAnimEnviroCheck);
}
public function playAnim(param1:int, param2:Boolean = false, param3:int = 0, param4:Function = null, param5:Boolean = false) : void
{
var _loc14_:Boolean = false;
var _loc13_:AccItemCollection = null;
var _loc6_:int = 0;
var _loc15_:int = 0;
var _loc11_:Array = null;
var _loc8_:* = null;
var _loc10_:Object = null;
var _loc9_:Array = null;
var _loc7_:* = 0;
if(_layerAnim && _layerAnim.visible && (_holdAnimId == 0 || param1 == _holdAnimId))
{
if(!_isOffScreen)
{
_loc14_ = false;
_loc13_ = _avatar.accShownItems;
if(!_layerAnim.layers)
{
_loc14_ = true;
}
else if(_layerAnim.layers.length != _loc13_.length)
{
_loc14_ = true;
}
else
{
_loc6_ = int(_loc13_.length);
_loc15_ = 0;
while(_loc15_ < _loc6_)
{
if(_layerAnim.layers.indexOf(_loc13_.getAccItem(_loc15_).accId) == -1)
{
_loc14_ = true;
break;
}
_loc15_++;
}
}
if(_loc14_)
{
_loc11_ = [];
_loc8_ = _loc13_;
_loc9_ = _avatar.colors;
for each(var _loc12_ in _loc8_.getCoreArray())
{
if((_loc12_.layerId <= 3 || (_skipAnimEnviroCheck || _loc12_.enviroType == _avatar.roomType || _loc12_.isLandAndOcean)) && _loc12_.getInUse(_avatar.avInvId))
{
if(_loc12_.layerId == 1)
{
_loc7_ = uint(_loc9_[0]);
}
else if(_loc12_.layerId == 2)
{
_loc7_ = uint(_loc9_[1]);
}
else if(_loc12_.layerId == 3)
{
_loc7_ = uint(_loc9_[2]);
}
else
{
if(param5)
{
continue;
}
_loc7_ = _loc12_.color;
}
// "d": the item, as AvatarUtility.layerArrayForItemsAndColors
// gives it: a custom one's own picture goes by it
// (LayerAnim, LayerBitmap). without it every new
// animation (walking) was painted as the item's base.
_loc10_ = {
"l":_loc12_.accId,
"c":_loc7_,
"d":_loc12_.defId
};
_loc11_.push(_loc10_);
}
}
_layerAnim.layers = _loc11_;
}
_layerAnim.hFlip = param2;
_layerAnim.playAnim(param1,param3,param4);
}
else
{
_lastAnimToHappen = param1;
}
}
}
public function reloadItemsFromCache() : void
{
var _loc1_:AccItemCollection = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(_avatar.userName,_avatar.perUserAvId).getItems(true);
_avatar.itemResponseIntegrate(_loc1_,_skipAnimEnviroCheck);
}
public function preloadAnims(param1:Array, param2:Function = null) : void
{
_layerAnim.preload(param1,param2);
}
public function blackOut() : void
{
var _loc1_:Array = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0];
_layerAnim.bitmap.filters = [new ColorMatrixFilter(_loc1_)];
}
public function get avatarData() : Avatar
{
return _avatar;
}
public function get userName() : String
{
if(_avatar != null)
{
return _avatar.userName;
}
return null;
}
public function get userId() : int
{
if(_avatar == null)
{
return -1;
}
return _avatar.sfsUserId;
}
public function get avTypeId() : int
{
return _avatar.avTypeId;
}
public function get customAvId() : int
{
return _avatar.customAvId;
}
public function get perUserAvId() : int
{
return _avatar.perUserAvId;
}
public function get avInvId() : int
{
return _avatar.avInvId;
}
public function get inventoryBodyModItems() : AccItemCollection
{
return _avatar.inventoryBodyMod.itemCollection;
}
public function get inventoryClothingItems() : AccItemCollection
{
return _avatar.inventoryClothing.itemCollection;
}
public function setAvtColors(param1:Array) : void
{
_avatar.colors = param1;
}
public function get avName() : String
{
return _avatar.avName;
}
public function get accShownItems() : AccItemCollection
{
return _avatar.accShownItems;
}
}
}
+203 -2
View File
@@ -90,65 +90,120 @@ package avatar
private static const STATE_LAND:int = 6;
// the actions' animations, `land` and `water`. an animal has the art of
// its own set only (land or ocean animals) or of both: an action of a
// set (`set`) plays as that set's when the animal has it, and otherwise
// as the animal's own set's, so a land animal underwater still sits
// (gui.ActionManager). ":dance:" and ":play:" are both sets' and go by
// the room for an animal of both; the other set's dance and play have
// names of their own.
public static var _actionLookup:Array = [{
"name":":dance:",
"land":23,
"water":38,
"flip":false
},{
"name":":danceLand:",
"land":23,
"water":38,
"set":"land",
"flip":false
},{
"name":":danceSwim:",
"land":23,
"water":38,
"set":"water",
"flip":false
},{
"name":":sleep:",
"land":22,
"water":41,
"set":"land",
"flip":false
},{
"name":":dive:",
"land":22,
"water":41,
"set":"water",
"flip":false
},{
"name":":hop:",
"land":17,
"water":33,
"set":"land",
"flip":false
},{
"name":":swirl:",
"land":17,
"water":33,
"set":"water",
"flip":false
},{
"name":":play:",
"land":6,
"water":39,
"flip":false
},{
"name":":playLand:",
"land":6,
"water":39,
"set":"land",
"flip":false
},{
"name":":playSwim:",
"land":6,
"water":39,
"set":"water",
"flip":false
},{
"name":":sitNW:",
"land":2,
"water":40,
"set":"land",
"flip":true
},{
"name":":poseLeft:",
"land":2,
"water":40,
"set":"water",
"flip":true
},{
"name":":sitNE:",
"land":2,
"water":40,
"set":"land",
"flip":false
},{
"name":":sitSE:",
"land":4,
"water":40,
"set":"land",
"flip":true
},{
"name":":poseRight:",
"land":2,
"water":40,
"set":"water",
"flip":false
},{
"name":":sitSW:",
"land":4,
"water":40,
"set":"land",
"flip":false
},{
// sitting facing straight forward, and straight away (the "Front"
// and "Back" between the arrows): animations 5 and 1, the ends of
// the sitting turn 1-5 (2 the back corners, 4 the front ones; the
// slide's spin plays them in turn). the game's own buttons never did.
"name":":sitS:",
"land":5,
"water":40,
"flip":false
},{
"name":":sitN:",
"land":1,
"water":40,
"flip":false
}];
@@ -168,6 +223,21 @@ package avatar
private var _platformingCurVel:Number = 0;
private var _chatBalloon:ChatBalloon;
// "..." where the chat bubble goes, while the player is typing
// (AJClient.onTyping). gone when a line arrives, when they stop, or
// TYPING_SHOWN ms after they last said they were, if a "stopped" is lost.
private static const TYPING_SHOWN:int = 8000;
private var _typing:Sprite;
private var _typingDots:Array;
private var _typingTimer:Timer;
private var _typingStep:int;
private var _typingUntil:int;
private var _namebar:NameBar;
@@ -587,6 +657,14 @@ package avatar
{
_chatLayer.removeChild(_chatBalloon);
}
hideTyping();
if(_typingTimer)
{
_typingTimer.removeEventListener("timer",onTypingTimer);
_typingTimer = null;
}
_typing = null;
_typingDots = null;
removeChild(_namebar);
if(_secondaryEmot && _chatLayer.contains(_secondaryEmot))
{
@@ -982,9 +1060,108 @@ package avatar
return false;
}
public function setTyping(param1:Boolean) : void
{
var _loc2_:Sprite = null;
var _loc3_:int = 0;
if(!param1 || _chatLayer == null)
{
hideTyping();
return;
}
if(_typing == null)
{
_typing = new Sprite();
_typing.mouseEnabled = false;
_typing.mouseChildren = false;
_typing.graphics.lineStyle(2,0x8C6A3C);
_typing.graphics.beginFill(0xFFFFFF);
_typing.graphics.drawRoundRect(-22,-26,44,22,20,20);
_typing.graphics.endFill();
_typing.graphics.lineStyle();
_typing.graphics.beginFill(0xFFFFFF);
_typing.graphics.moveTo(-5,-5);
_typing.graphics.lineTo(0,2);
_typing.graphics.lineTo(5,-5);
_typing.graphics.endFill();
_typingDots = [];
_loc3_ = 0;
while(_loc3_ < 3)
{
_loc2_ = new Sprite();
_loc2_.graphics.beginFill(0x6B5034);
_loc2_.graphics.drawCircle(0,0,3);
_loc2_.graphics.endFill();
_loc2_.x = -10 + _loc3_ * 10;
_loc2_.y = -15;
_typing.addChild(_loc2_);
_typingDots.push(_loc2_);
_loc3_++;
}
_typingTimer = new Timer(300);
_typingTimer.addEventListener("timer",onTypingTimer,false,0,true);
}
_typingUntil = getTimer() + TYPING_SHOWN;
if(_typing.parent != _chatLayer)
{
_chatLayer.addChild(_typing);
}
placeTyping();
_typing.visible = !(_chatBalloon && _chatBalloon.visible);
if(!_typingTimer.running)
{
_typingTimer.start();
}
}
private function hideTyping() : void
{
if(_typingTimer)
{
_typingTimer.stop();
}
if(_typing && _typing.parent)
{
_typing.parent.removeChild(_typing);
}
}
private function placeTyping() : void
{
if(_typing && _chatBalloon)
{
_typing.x = _chatBalloon.x;
_typing.y = _chatBalloon.y;
}
}
private function onTypingTimer(param1:TimerEvent) : void
{
var _loc2_:int = 0;
if(_typing == null || getTimer() > _typingUntil)
{
hideTyping();
return;
}
placeTyping();
_typing.visible = !(_chatBalloon && _chatBalloon.visible);
_typingStep = (_typingStep + 1) % 3;
_loc2_ = 0;
while(_loc2_ < _typingDots.length)
{
_typingDots[_loc2_].alpha = _loc2_ == _typingStep ? 1 : 0.35;
_typingDots[_loc2_].y = _loc2_ == _typingStep ? -17 : -15;
_loc2_++;
}
}
public function setMessage(param1:String, param2:int) : void
{
var _loc3_:Boolean = false;
if(param1 != "...")
{
hideTyping();
}
if(param2 > 1)
{
if(param2 == 2)
@@ -1148,11 +1325,22 @@ package avatar
_lastIdleAnim = getBaseIdle();
_lastIdleFlip = false;
var _loc2_:String = _actionMgr.getActionString(param1);
// the sets this animal has art for
var _loc5_:Boolean = _avatar == null || Utility.isLand(_avatar.enviroTypeFlag);
var _loc6_:Boolean = _avatar == null || Utility.isOcean(_avatar.enviroTypeFlag);
var _loc7_:String = null;
for each(var _loc4_:Object in _actionLookup)
{
if(_loc4_.name == _loc2_)
{
_loc3_ = int(_roomType == 0 ? _loc4_.land : _loc4_.water);
// the action's own set, if the animal has it; otherwise its
// only set, or with both (or neither known) the room's
_loc7_ = _loc4_.set;
if(!_loc7_ || (_loc7_ == "water" ? !_loc6_ : !_loc5_))
{
_loc7_ = _loc5_ == _loc6_ ? (_roomType == 0 ? "land" : "water") : (_loc5_ ? "land" : "water");
}
_loc3_ = int(_loc7_ == "water" ? _loc4_.water : _loc4_.land);
if(_loc3_ > 0)
{
_lastIdleAnim = _loc3_;
@@ -1164,7 +1352,20 @@ package avatar
}
if(_pet && _loc2_)
{
_pet.setActionByName(_loc2_);
// pets know ":dance:" and ":play:", not the other set's names
_pet.setActionByName(_loc2_.replace(/(Land|Swim):$/,":"));
}
}
// The base action definitions supply their normal orientation. A local
// Mirror selection is applied after that, so it works for every action
// without changing the original sit/dance/etc. mappings.
public function setActionMirrored(param1:Boolean) : void
{
if(_lastIdleAnim > 0 && param1)
{
_lastIdleFlip = !_lastIdleFlip;
playAnim(_lastIdleAnim,_lastIdleFlip);
}
}
+7 -1
View File
@@ -3325,6 +3325,12 @@ package buddy
private function reportDownHandler(param1:MouseEvent) : void
{
param1.stopPropagation();
// staff get their window for this player instead (AJClient.openModerate).
if(!param1.currentTarget.isGray && AJClient.canModerate())
{
AJClient.openModerate(_currUserName);
return;
}
if(!param1.currentTarget.isGray)
{
if(_reportAPlayer)
@@ -3344,7 +3350,7 @@ package buddy
param1.stopPropagation();
if(!param1.currentTarget.isGray)
{
GuiManager.toolTip.init(_popupLayer,LocalizationManager.translateIdOnly(14633),845,210);
GuiManager.toolTip.init(_popupLayer,AJClient.canModerate() ? "Moderate" : LocalizationManager.translateIdOnly(14633),845,210);
GuiManager.toolTip.startTimer(param1);
}
}
+191 -33
View File
@@ -63,9 +63,12 @@ package gui
private var _emoteBGOffsetFunc:Function;
// emotes drawn inside a line of chat: "\" and an emote's code
// ("\:)", "\:fever:") is shown as that emote, small, where it was
// typed. each is {at, clip}: where its gap starts in the text shown.
// emotes drawn inside a line of chat, small, where they were typed: an
// emote's code standing as a word of its own ("hi :) there", ":fever:"),
// or anywhere after a "\" ("yay\:)"). and emoji (typed with Windows'
// emoji panel, say), which the game's font has none of: each is drawn
// as a picture of it, from the server (/emoji/<code points>.png,
// Twemoji's). each is {at, clip}: where its gap starts in the text shown.
private static const INLINE_GAP:String = " ";
private static const LONGEST_EMOTE_CODE:int = 16;
@@ -130,7 +133,7 @@ package gui
this.visible = true;
}
clearInline();
_msgTxt.text = param1.indexOf("\\") == -1 ? param1 : inlineEmotes(param1);
_msgTxt.text = inlineEmotes(param1);
_msgTxt.height;
// AJClient.whisperNext is set by the server's "xw" just ahead of a
// whispered line.
@@ -178,50 +181,63 @@ package gui
}
}
// the text with each "\<emote code>" replaced by a gap, the emote for
// it kept in _inline. A code that is no emote stays as typed.
// the text with each emote code and emoji (above) replaced by a gap, the
// picture for it kept in _inline. what is neither stays as typed.
private function inlineEmotes(param1:String) : String
{
var _loc2_:String = "";
var _loc3_:int = 0;
var _loc4_:int = 0;
var _loc5_:String = null;
var _loc6_:String = null;
var _loc7_:MovieClip = null;
var _loc7_:Sprite = null;
var _loc8_:int = 0;
while(_loc3_ < param1.length)
{
_loc5_ = null;
if(param1.charAt(_loc3_) == "\\")
_loc8_ = emojiLength(param1,_loc3_);
if(_loc8_ > 0)
{
_loc4_ = Math.min(LONGEST_EMOTE_CODE,param1.length - _loc3_ - 1);
while(_loc4_ >= 2 && _loc5_ == null)
{
_loc6_ = param1.substr(_loc3_ + 1,_loc4_);
if(EmoticonUtility.doesStringMatchAnEmote(_loc6_))
{
_loc5_ = _loc6_;
}
_loc4_--;
}
_inline.push({
"at":_loc2_.length,
"clip":emojiClip(param1.substr(_loc3_,_loc8_))
});
_loc2_ += INLINE_GAP;
_loc3_ += _loc8_;
continue;
}
if(_loc5_ != null)
_loc5_ = null;
// an emoji as it is sent: "\{1f600}" (AJClient.emojiToTokens)
if(param1.substr(_loc3_,2) == "\\{")
{
_loc7_ = EmoticonUtility.getSmallSmileyMCForEmoteString(_loc5_);
if(_loc7_ != null)
var _loc9_:Array = /^\\\{([0-9a-f]{2,6}(?:-[0-9a-f]{2,6}){0,9})\}/.exec(param1.substr(_loc3_,90));
if(_loc9_ != null)
{
_loc7_.mouseEnabled = false;
_loc7_.mouseChildren = false;
_inline.push({
"at":_loc2_.length,
"clip":_loc7_
"clip":emojiClipNamed(_loc9_[1])
});
_loc2_ += INLINE_GAP;
_loc3_ += String(_loc9_[0]).length;
continue;
}
else
{
_loc2_ += _loc5_;
}
_loc3_ += 1 + _loc5_.length;
}
if(param1.charAt(_loc3_) == "\\")
{
_loc5_ = emoteCodeAt(param1,_loc3_ + 1,false);
}
else if(_loc3_ == 0 || param1.charAt(_loc3_ - 1) == " ")
{
_loc5_ = emoteCodeAt(param1,_loc3_,true);
}
_loc7_ = _loc5_ == null ? null : EmoticonUtility.getSmallSmileyMCForEmoteString(_loc5_);
if(_loc7_ != null)
{
_loc7_.mouseEnabled = false;
_loc7_.mouseChildren = false;
_inline.push({
"at":_loc2_.length,
"clip":_loc7_
});
_loc2_ += INLINE_GAP;
_loc3_ += (param1.charAt(_loc3_) == "\\" ? 1 : 0) + _loc5_.length;
}
else
{
@@ -231,7 +247,149 @@ package gui
}
return _loc2_;
}
// the longest emote code at `param2`, or null. `param3`: as a word of its
// own, so it must end the text or come before a space or a stop.
private static function emoteCodeAt(param1:String, param2:int, param3:Boolean) : String
{
var _loc4_:int = Math.min(LONGEST_EMOTE_CODE,param1.length - param2);
var _loc5_:String = null;
var _loc6_:String = null;
while(_loc4_ >= 2)
{
_loc5_ = param1.substr(param2,_loc4_);
_loc6_ = param1.charAt(param2 + _loc4_);
if((!param3 || _loc6_ == "" || " .,!?".indexOf(_loc6_) != -1) && EmoticonUtility.doesStringMatchAnEmote(_loc5_))
{
return _loc5_;
}
_loc4_--;
}
return null;
}
// how many UTF-16 units the emoji at `param2` takes (with its skin tone,
// its variation selector, a keycap, a second flag letter, and whatever
// it is joined to with a zero-width joiner), or 0 when there is none.
public static function emojiLength(param1:String, param2:int) : int
{
var _loc3_:int = param1.charCodeAt(param2);
var _loc4_:int = 0;
var _loc5_:int = 0;
var _loc6_:int = 0;
var _loc7_:Boolean = false;
if(_loc3_ >= 0xD800 && _loc3_ <= 0xDBFF)
{
_loc5_ = codePointAt(param1,param2);
if(_loc5_ < 0x1F000 || _loc5_ > 0x1FAFF)
{
return 0;
}
_loc4_ = 2;
_loc7_ = _loc5_ >= 0x1F1E6 && _loc5_ <= 0x1F1FF;
// a flag is two letters
if(_loc7_)
{
_loc6_ = codePointAt(param1,param2 + 2);
if(_loc6_ >= 0x1F1E6 && _loc6_ <= 0x1F1FF)
{
_loc4_ = 4;
}
}
}
else if(_loc3_ >= 0x2600 && _loc3_ <= 0x27BF || _loc3_ >= 0x2300 && _loc3_ <= 0x23FF || _loc3_ >= 0x2B00 && _loc3_ <= 0x2BFF
|| _loc3_ >= 0x2194 && _loc3_ <= 0x21AA || _loc3_ >= 0x25AA && _loc3_ <= 0x25FE
|| [0x203C,0x2049,0x2122,0x2139,0x24C2,0x2934,0x2935,0x3030,0x303D,0x3297,0x3299,0xA9,0xAE].indexOf(_loc3_) != -1 && param1.charCodeAt(param2 + 1) == 0xFE0F)
{
_loc4_ = 1;
}
else if("0123456789#*".indexOf(param1.charAt(param2)) != -1 && param1.charCodeAt(param2 + 1) == 0xFE0F && param1.charCodeAt(param2 + 2) == 0x20E3)
{
return 3;
}
else
{
return 0;
}
while(param2 + _loc4_ < param1.length)
{
_loc3_ = param1.charCodeAt(param2 + _loc4_);
if(_loc3_ == 0xFE0F || _loc3_ == 0x20E3)
{
_loc4_++;
}
else if(_loc3_ == 0xD83C && param1.charCodeAt(param2 + _loc4_ + 1) >= 0xDFFB && param1.charCodeAt(param2 + _loc4_ + 1) <= 0xDFFF)
{
_loc4_ += 2;
}
else if(_loc3_ == 0x200D && param2 + _loc4_ + 1 < param1.length)
{
_loc5_ = emojiLength(param1,param2 + _loc4_ + 1);
if(_loc5_ == 0)
{
break;
}
_loc4_ += 1 + _loc5_;
break;
}
else
{
break;
}
}
return _loc4_;
}
private static function codePointAt(param1:String, param2:int) : int
{
var _loc3_:int = param1.charCodeAt(param2);
var _loc4_:int = param1.charCodeAt(param2 + 1);
if(_loc3_ >= 0xD800 && _loc3_ <= 0xDBFF && _loc4_ >= 0xDC00 && _loc4_ <= 0xDFFF)
{
return (_loc3_ - 0xD800) * 0x400 + (_loc4_ - 0xDC00) + 0x10000;
}
return _loc3_;
}
// its picture's name, as Twemoji names its files: the code points in
// hex, "-" between, without U+FE0F unless it is joined (U+200D).
public static function emojiName(param1:String) : String
{
var _loc2_:Array = [];
var _loc3_:int = 0;
var _loc4_:int = 0;
var _loc5_:Boolean = param1.indexOf(String.fromCharCode(0x200D)) != -1;
while(_loc3_ < param1.length)
{
_loc4_ = codePointAt(param1,_loc3_);
_loc3_ += _loc4_ > 0xFFFF ? 2 : 1;
if(_loc4_ != 0xFE0F || _loc5_)
{
_loc2_.push(_loc4_.toString(16));
}
}
return _loc2_.join("-");
}
// the picture of an emoji: a 72-square, its middle on the origin (as
// the game's small emotes are), filled when the picture has loaded.
private static function emojiClip(param1:String) : Sprite
{
return emojiClipNamed(emojiName(param1));
}
private static function emojiClipNamed(param1:String) : Sprite
{
var _loc2_:Sprite = new Sprite();
_loc2_.graphics.beginFill(0,0);
_loc2_.graphics.drawRect(-36,-36,72,72);
_loc2_.graphics.endFill();
_loc2_.mouseEnabled = false;
_loc2_.mouseChildren = false;
AJClient.loadArt(gMainFrame.clientInfo.websiteURL + "emoji/" + param1 + ".png",_loc2_,72,false);
return _loc2_;
}
// puts each inline emote over its gap, as tall as the line.
private function placeInline() : void
{
+52 -3
View File
@@ -14,6 +14,7 @@ package gui
import flash.events.TextEvent;
import flash.text.StyleSheet;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.ui.Mouse;
import gui.itemWindows.ItemWindowTextNode;
import localization.LocalizationManager;
@@ -211,6 +212,8 @@ package gui
public function addMessage(param1:String, param2:String, param3:String, param4:String) : void
{
// emoji as their names here: this list has no pictures (AJClient.emojiAsNames)
param4 = AJClient.emojiAsNames(param4);
var _loc5_:Boolean = false;
var _loc6_:* = 0;
var _loc7_:int = 0;
@@ -479,9 +482,10 @@ package gui
}
else
{
// 150 here, where the original stopped at 70. the server takes
// up to config.maxChatLength.
chatMsgText.maxChars = 150;
// 200 here, where the original stopped at 70. the server takes
// up to config.maxChatLength (more: an emoji goes as a tag of 8
// or more), and makes long lines shorter (lib/chatspam.js).
chatMsgText.maxChars = 200;
}
}
@@ -753,6 +757,51 @@ package gui
{
_predictiveTextManager.onTextFieldChanged(param1);
}
showEmojiInInput();
AJClient.noteTyping(chatMsgText.text);
}
// the chat box while it holds an emoji (Windows' emoji panel, say): the
// game's font has none, so the box is drawn in the computer's own emoji
// font until there are none again. the bubble shows them as pictures
// (gui.ChatBalloon).
private var _inputShowsEmoji:Boolean = false;
private var _inputFormat:TextFormat;
private var _inputEmbedded:Boolean = true;
public function showEmojiInInput() : void
{
var _loc1_:Boolean = false;
var _loc2_:int = 0;
var _loc3_:String = chatMsgText == null ? "" : chatMsgText.text;
var _loc4_:TextFormat = null;
while(_loc2_ < _loc3_.length && !_loc1_)
{
_loc1_ = ChatBalloon.emojiLength(_loc3_,_loc2_) > 0;
_loc2_++;
}
if(chatMsgText == null || _loc1_ == _inputShowsEmoji)
{
return;
}
if(_loc1_)
{
_inputFormat = chatMsgText.defaultTextFormat;
_inputEmbedded = chatMsgText.embedFonts;
_loc4_ = new TextFormat("Segoe UI Emoji",_inputFormat.size,_inputFormat.color,_inputFormat.bold);
chatMsgText.embedFonts = false;
chatMsgText.defaultTextFormat = _loc4_;
chatMsgText.setTextFormat(_loc4_);
}
else
{
chatMsgText.embedFonts = _inputEmbedded;
chatMsgText.defaultTextFormat = _inputFormat;
chatMsgText.setTextFormat(_inputFormat);
}
_inputShowsEmoji = _loc1_;
}
private function keyDownListener(param1:KeyboardEvent) : void
+665
View File
@@ -0,0 +1,665 @@
package loader
{
import Enums.DenItemDef;
import avatar.AvatarManager;
import avatar.MannequinData;
import com.sbi.loader.FileServerEvent;
import den.DenItem;
import den.DenStateItem;
import den.DenXtCommManager;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import pet.PetItem;
import pet.PetManager;
public class DenItemHelper
{
private var _denItem:DenItem;
private var _denStateItem:DenStateItem;
private var _defId:int;
private var _id:uint;
private var _callback:Function;
private var _loader:Loader;
private var _sprite:Sprite;
private var _portalSprite:Sprite;
private var _sortOffset:int;
private var _minigameDefId:int;
private var _nameStrId:int;
private var _listLauncherId:int;
private var _version:int;
private var _version2:int;
private var _version3:int;
private var _petItem:PetItem;
private var _bFlipLabel:Boolean;
private var _isUniqueImageItem:Boolean;
private var _uniqueImageId:String;
private var _uniqueImageCreator:String;
private var _uniqueImageCreatorDbId:int;
private var _uniqueImageCreatorUUID:String;
private var _isMannequin:Boolean;
private var _isDenStore:Boolean;
private var _masterpieceDefHelper:MasterpieceDefHelper;
private var _mannequinData:MannequinData;
private var _onMouseDownCallback:Function;
private var _onMouseOverCallback:Function;
private var _onMouseOutCallback:Function;
private var _uniqueImage:Sprite;
public function DenItemHelper()
{
super();
}
public function get displayObject() : Sprite
{
return _sprite;
}
public function get content() : DisplayObject
{
return _loader.content;
}
public function get sortOffset() : int
{
return _sortOffset;
}
public function get id() : int
{
return _id;
}
public function get minigameDefId() : int
{
return _minigameDefId;
}
public function get bFlipLabel() : Boolean
{
return _bFlipLabel;
}
public function get isUniqueImageItem() : Boolean
{
return _isUniqueImageItem;
}
public function get listLauncherId() : int
{
return _listLauncherId;
}
public function get nameStrId() : int
{
return _nameStrId;
}
public function get uniqueImage() : Sprite
{
return _uniqueImage;
}
public function get uniqueImageId() : String
{
return _uniqueImageId;
}
public function set uniqueImageId(param1:String) : void
{
_uniqueImageId = param1;
}
public function get uniqueImageCreator() : String
{
return _uniqueImageCreator;
}
public function set uniqueImageCreator(param1:String) : void
{
_uniqueImageCreator = param1;
}
public function get uniqueImageCreatorDbId() : int
{
return _uniqueImageCreatorDbId;
}
public function get uniqueImageCreatorUUID() : String
{
return _uniqueImageCreatorUUID;
}
public function get denStateItem() : DenStateItem
{
return _denStateItem;
}
public function get defId() : int
{
return _defId;
}
public function get version() : int
{
return _version;
}
public function get mannequin() : MannequinData
{
return _mannequinData;
}
public function get isMannequin() : Boolean
{
return _isMannequin;
}
public function get isDenStore() : Boolean
{
return _isDenStore;
}
public function get contentWidth() : int
{
if(_loader != null && _loader.content != null)
{
if(_loader.content.hasOwnProperty("sizeCont"))
{
return _loader.content["sizeCont"].width;
}
return _loader.content.width;
}
return 0;
}
public function get contentHeight() : int
{
if(_loader != null && _loader.content != null)
{
if(_loader.content.hasOwnProperty("sizeCont"))
{
return _loader.content["sizeCont"].height;
}
return _loader.content.height;
}
return 0;
}
public function get currDenItem() : DenItem
{
return _denItem;
}
public function init(param1:DenItem, param2:Function, param3:PetItem = null, param4:int = 0, param5:int = 0, param6:MannequinData = null) : void
{
_denItem = param1;
_defId = param1.defId;
_id = uint(_defId << 16 | DenItem.getIconId(param1.sortId));
_callback = param2;
_minigameDefId = param1.minigameDefId;
_nameStrId = param5;
_listLauncherId = param4;
_bFlipLabel = false;
_isUniqueImageItem = false;
_petItem = param3;
_version = param1.sortId == 99 ? _petItem.petBits[0] : param1.version;
_version2 = param1.sortId == 99 ? _petItem.petBits[1] : 0;
_version3 = param1.sortId == 99 ? _petItem.petBits[2] : 0;
_loader = new Loader();
_sprite = new Sprite();
_portalSprite = new Sprite();
_uniqueImage = new Sprite();
_uniqueImageId = param1.uniqueImageId;
_uniqueImageCreator = param1.uniqueImageCreator;
_uniqueImageCreatorDbId = param1.uniqueImageCreatorDbId;
_uniqueImageCreatorUUID = param1.uniqueImageCreatorUUID;
_mannequinData = param6;
if(loadCustomArt())
{
return;
}
DenItemServer.instance.addEventListener("OnNewData",handleData,false,0,true);
DenItemServer.instance.requestFile(_id);
}
public function initDS(param1:DenStateItem, param2:Function) : void
{
_denStateItem = param1;
_defId = param1.defId;
_id = uint(_defId << 16 | param1.catId);
_callback = param2;
_minigameDefId = param1.minigameDefId;
_nameStrId = param1.nameStrId;
_listLauncherId = param1.listLauncherId;
_bFlipLabel = false;
_isUniqueImageItem = false;
_petItem = param1.petItem;
_version = param1.sortCatId == 99 ? _petItem.petBits[0] : param1.version;
_version2 = param1.sortCatId == 99 ? _petItem.petBits[1] : 0;
_version3 = param1.sortCatId == 99 ? _petItem.petBits[2] : 0;
_loader = new Loader();
_sprite = new Sprite();
_portalSprite = new Sprite();
_uniqueImage = new Sprite();
_uniqueImageId = param1.uniqueImageId;
_uniqueImageCreator = param1.uniqueImageCreator;
_uniqueImageCreatorDbId = param1.uniqueImageCreatorDbId;
_uniqueImageCreatorUUID = param1.uniqueImageCreatorUUID;
_mannequinData = param1.mannequinData;
if(loadCustomArt())
{
return;
}
DenItemServer.instance.addEventListener("OnNewData",handleData,false,0,true);
DenItemServer.instance.requestFile(_id);
}
public function initGeneric(param1:DenItemDef, param2:Function, param3:int = 0, param4:int = 0, param5:int = 0, param6:String = "", param7:int = -1, param8:String = "", param9:PetItem = null, param10:MannequinData = null) : void
{
_defId = param1.id;
_id = uint(_defId << 16 | DenItem.getIconId(param1.sortCat));
_callback = param2;
_minigameDefId = param1.gameDefId;
_nameStrId = param5;
_listLauncherId = param4;
_bFlipLabel = false;
_isUniqueImageItem = false;
_petItem = param9;
_version = param1.sortCat == 99 ? _petItem.petBits[0] : param3;
_version2 = param1.sortCat == 99 ? _petItem.petBits[1] : 0;
_version3 = param1.sortCat == 99 ? _petItem.petBits[2] : 0;
_loader = new Loader();
_sprite = new Sprite();
_portalSprite = new Sprite();
_uniqueImage = new Sprite();
_uniqueImageId = param6;
_uniqueImageCreator = "";
_uniqueImageCreatorDbId = param7;
_uniqueImageCreatorUUID = param8;
_mannequinData = param10;
if(loadCustomArt())
{
return;
}
DenItemServer.instance.addEventListener("OnNewData",handleData,false,0,true);
DenItemServer.instance.requestFile(_id);
}
public function destroy() : void
{
DenItemServer.instance.removeEventListener("OnNewData",handleData);
if(_loader)
{
if(_loader.parent)
{
_loader.parent.removeChild(_loader);
}
_loader.unloadAndStop(true);
}
_callback = null;
_sprite = null;
}
public function loadUniqueImage() : void
{
if(_loader && _loader.content.hasOwnProperty("setUniqueImage"))
{
_isUniqueImageItem = true;
if(_uniqueImageId != "")
{
_masterpieceDefHelper = new MasterpieceDefHelper();
_masterpieceDefHelper.init(_uniqueImageId,onUniqueImageIdLoaded);
}
}
}
public function setupItemWithEmotes(param1:DenStateItem) : void
{
_denStateItem = param1;
}
public function addPortalListeners(param1:DenStateItem, param2:Function, param3:Function = null, param4:Function = null) : void
{
_denStateItem = param1;
_onMouseDownCallback = param2;
_portalSprite.addEventListener("mouseDown",onMouseDown,false,0,true);
if(param3 != null)
{
_onMouseOverCallback = param3;
_portalSprite.addEventListener("mouseOver",onMouseOver,false,0,true);
}
if(param4 != null)
{
_onMouseOutCallback = param4;
_portalSprite.addEventListener("mouseOut",onMouseOut,false,0,true);
}
}
public function addMouseListeners(param1:DenStateItem, param2:Function, param3:Function = null, param4:Function = null) : void
{
_denStateItem = param1;
_onMouseDownCallback = param2;
_sprite.addEventListener("mouseDown",onMouseDown,false,0,true);
if(param3 != null)
{
_onMouseOverCallback = param3;
_sprite.addEventListener("mouseOver",onMouseOver,false,0,true);
}
if(param4 != null)
{
_onMouseOutCallback = param4;
_sprite.addEventListener("mouseOut",onMouseOut,false,0,true);
}
}
public function removeMouseListeners() : void
{
_denStateItem = null;
_onMouseDownCallback = null;
_sprite.removeEventListener("mouseDown",onMouseDown);
if(_onMouseOverCallback != null)
{
_onMouseOverCallback = null;
_sprite.removeEventListener("mouseOver",onMouseOver);
}
if(_onMouseOutCallback != null)
{
_onMouseOutCallback = null;
_sprite.removeEventListener("mouseOut",onMouseOut);
}
}
public function removePortalListeners() : void
{
_denStateItem = null;
_onMouseDownCallback = null;
_portalSprite.removeEventListener("mouseDown",onMouseDown);
if(_onMouseOverCallback != null)
{
_onMouseOverCallback = null;
_portalSprite.removeEventListener("mouseOver",onMouseOver);
}
if(_onMouseOutCallback != null)
{
_onMouseOutCallback = null;
_portalSprite.removeEventListener("mouseOut",onMouseOut);
}
}
public function getVersions() : Array
{
if(_loader && _loader.content && _loader.content.hasOwnProperty("getVersions"))
{
return _loader.content["getVersions"]();
}
return null;
}
public function setVersion(param1:int, param2:int = 0, param3:int = 0) : void
{
var _loc5_:MovieClip = null;
var _loc4_:int = 0;
_version = param1;
if(param2 > 0)
{
_version2 = param2;
}
if(param3 > 0)
{
_version3 = param3;
}
if(_loader && _loader.content)
{
if(_loader.content.hasOwnProperty("setVersion"))
{
if(_version == -1)
{
_version = getVersions()[0];
}
_loader.content["setVersion"](param1);
}
else if(_loader.content.hasOwnProperty("pet"))
{
_loc5_ = MovieClip(_loader.content);
PetManager.setPetState(_loc5_,_version,_version2,_version3);
if(_petItem && _petItem.isEgg)
{
if(_loc5_.pet.hasOwnProperty("setEggDayInt"))
{
_loc4_ = _petItem.createdTs > 0 ? Math.floor((Utility.getInitialEpochTime() - _petItem.createdTs) / 86400) : 0;
_loc5_.pet.setEggDayInt(_loc4_);
}
}
}
}
}
public function rebuildMannequinView() : void
{
var _loc1_:DenItemDef = DenXtCommManager.getDenItemDef(_defId);
if(_loc1_ != null && _loc1_.mannequinAvatarDefId > 0)
{
_isMannequin = true;
_mannequinData.setupMannequinAvatarView(_loc1_,MovieClip(_loader.content));
}
}
// a custom den item's own picture (AJClient.customArtUrl): in place of
// the game's art, as its icon and in a den, standing on its spot.
private function loadCustomArt() : Boolean
{
var _loc1_:String = AJClient.customArtUrl("den",_defId);
if(_loc1_ == null)
{
return false;
}
var _loc2_:DenItemHelper = this;
_sortOffset = 0;
AJClient.loadArt(_loc1_,_sprite,160,true,function():void
{
_sprite.addChild(_portalSprite);
if(_callback != null)
{
_callback(_loc2_);
_callback = null;
}
});
return true;
}
private function handleData(param1:FileServerEvent) : void
{
var _loc2_:Object = null;
if(param1.id == _id && param1.success)
{
DenItemServer.instance.removeEventListener("OnNewData",handleData);
_loader.contentLoaderInfo.addEventListener("complete",onBytesLoaded);
param1.data.position = 0;
_loc2_ = param1.data.readObject();
_sortOffset = _loc2_.so;
_loader.loadBytes(_loc2_.ba);
}
}
private function onBytesLoaded(param1:Event) : void
{
var _loc3_:MovieClip = null;
var _loc2_:int = 0;
var _loc4_:DenItemDef = null;
_loader.contentLoaderInfo.removeEventListener("complete",onBytesLoaded);
var _loc5_:Array = _loader.content["currentLabels"];
if(_loc5_.length >= 0)
{
for each(var _loc6_:Object in _loc5_)
{
if(_loc6_.name == "flip")
{
_bFlipLabel = true;
break;
}
}
if(!Utility.doesItAnimate(_loader.content))
{
_loader.cacheAsBitmap = true;
}
}
if(_version == -1)
{
if(_loader.content.hasOwnProperty("getVersions"))
{
_version = getVersions()[0];
}
else
{
_version = 0;
}
}
if(_loader.content.hasOwnProperty("setVersion") && _version >= 0)
{
MovieClip(_loader.content).setVersion(_version);
}
else if(_loader.content.hasOwnProperty("pet"))
{
_loc3_ = MovieClip(_loader.content);
PetManager.setPetState(_loc3_,_version,_version2,_version3);
if(_petItem && _petItem.isEgg)
{
if(_loc3_.pet.hasOwnProperty("setEggDayInt"))
{
_loc2_ = _petItem.createdTs > 0 ? Math.floor((Utility.getInitialEpochTime() - _petItem.createdTs) / 86400) : 0;
_loc3_.pet.setEggDayInt(_loc2_);
}
}
}
if(MovieClip(_loader.content).isMoveToDisabled)
{
_loader.name = "moveToDisabled";
}
if(_mannequinData != null)
{
_loc4_ = DenXtCommManager.getDenItemDef(_defId);
if(_loc4_ != null && _loc4_.mannequinAvatarDefId > 0)
{
_isMannequin = true;
_mannequinData.setupMannequinAvatarView(_loc4_,MovieClip(_loader.content));
}
}
if(_denStateItem != null)
{
if(_denStateItem.specialType == 1)
{
_portalSprite.addChild(MovieClip(_loader.content).clickObject);
}
else if(_denStateItem.specialType == 2 && _loader.content.hasOwnProperty("setEmoteCallback"))
{
MovieClip(_loader.content).setEmoteCallback(onEmoteItemClicked);
}
else if(_denStateItem.specialType == 5)
{
_isDenStore = true;
}
}
if(_loader.content.hasOwnProperty("setUniqueImage"))
{
_isUniqueImageItem = true;
if(_uniqueImageId != "")
{
_masterpieceDefHelper = new MasterpieceDefHelper();
_masterpieceDefHelper.init(_uniqueImageId,onUniqueImageIdLoaded);
}
}
_sprite.addChild(_loader);
_sprite.addChild(_portalSprite);
if(_callback != null)
{
_callback(this);
_callback = null;
}
}
private function onUniqueImageIdLoaded(param1:Sprite) : void
{
if(_masterpieceDefHelper)
{
_masterpieceDefHelper.destroy();
_masterpieceDefHelper = null;
}
if(_uniqueImage)
{
_uniqueImage.addChild(param1);
if(_loader && _loader.content && "setUniqueImage" in _loader.content)
{
MovieClip(_loader.content).setUniqueImage(_uniqueImage);
}
}
}
private function onEmoteItemClicked(param1:int) : void
{
if(AvatarManager.playerAvatarWorldView && !AvatarManager.playerAvatarWorldView.isThisAttachmentOn(param1))
{
AvatarManager.setPlayerAttachmentEmot(param1);
}
}
private function onMouseDown(param1:MouseEvent) : void
{
if(_onMouseDownCallback != null)
{
_onMouseDownCallback(param1,this);
}
}
private function onMouseOver(param1:MouseEvent) : void
{
if(_onMouseOverCallback != null)
{
_onMouseOverCallback(param1,this);
}
}
private function onMouseOut(param1:MouseEvent) : void
{
if(_onMouseOutCallback != null)
{
_onMouseOutCallback(param1);
}
}
}
}
File diff suppressed because it is too large. Load diff
+46
View File
@@ -33,6 +33,7 @@ package gui
import flash.net.navigateToURL;
import giftPopup.GiftPopup;
import gui.itemWindows.ItemWindowECard;
import item.ItemXtCommManager;
import item.SimpleIcon;
import loader.DenItemHelper;
import loader.MediaHelper;
@@ -698,6 +699,16 @@ package gui
switch(_loc6_.type)
{
case 1:
// a custom item's own picture, when it has one (AJClient.customArtUrl)
if(AJClient.customArtUrl("clothing",giftItemDefId(_loc6_)) != null)
{
var _loc8_:Sprite = new Sprite();
AJClient.loadArt(AJClient.customArtUrl("clothing",giftItemDefId(_loc6_)),_loc8_,100,false,function():void
{
setupGiftPopup(_loc8_);
});
break;
}
_clothingIconHelper = new SimpleIcon();
_clothingIconHelper.init(_loc6_.giftColor,_loc6_.giftId,1,true,false,clothingIconReceived);
break;
@@ -802,10 +813,45 @@ package gui
setupGiftPopup(_guiPet);
}
// a clothing gift's item id, which the server sends as "item|<id>" in
// the card's additional gift data (its gift id is the art's), or 0
private static function giftItemDefId(param1:ECard) : int
{
var _loc2_:String = param1.additionalGiftData == null ? "" : param1.additionalGiftData;
return _loc2_.indexOf("item|") == 0 ? int(_loc2_.substr(5)) : 0;
}
// a custom item's name as it is now (the server sends it with the
// item, "xdi"): the game's strings have none for one made since this
// game started, nor a name it was given since.
private static function giftItemName(param1:ECard) : String
{
var _loc2_:Object = null;
var _loc3_:int = param1.type == 1 ? giftItemDefId(param1) : param1.giftId;
if(_loc3_ < 50000)
{
return null;
}
if(param1.type == 1)
{
_loc2_ = ItemXtCommManager.getItemDef(_loc3_);
}
else if(param1.type == 3 || param1.type == 99)
{
_loc2_ = DenXtCommManager.getDenItemDef(_loc3_);
}
return _loc2_ != null && _loc2_.name ? String(_loc2_.name) : null;
}
private function setupGiftPopup(param1:Sprite) : void
{
DarkenManager.showLoadingSpiral(false);
var _loc2_:ECard = _inbox[_currCardIdx];
var _loc4_:String = giftItemName(_loc2_);
if(_loc4_ != null)
{
_loc2_.giftName = _loc4_;
}
var _loc3_:Boolean = _loc2_.isFromVoice && _loc2_.additionalGiftData.length > 0 && _loc2_.additionalGiftData.indexOf("|") == -1;
_giftPopup = new GiftPopup();
_giftPopup.init(_guiLayer,param1,_loc2_.giftName,_loc2_.giftId,_loc2_.isFromVoice ? 6 : 0,GiftPopup.giftTypeForECardType(_loc2_.type),keepGiftCallback,rejectGiftCallback,destroyGiftPopup,!_loc2_.isFromVoice,GiftPopup.buttonsTypeForECardType(_loc2_.type),_loc2_.secondaryType,null,_loc3_ ? _loc2_.modifiedMsg : null,_petBits);
+27 -3
View File
@@ -3,7 +3,7 @@
returns null
body
maxstack 43
maxstack 45
localcount 1
initscopedepth 0
maxscopedepth 1
@@ -54,7 +54,9 @@
pushstring "emo_star2_sml"
pushstring "emo_star3_sml"
pushstring "emo_temp_sml"
newarray 43
pushstring "emo_skull_sml"
pushstring "emo_sob_sml"
newarray 45
findproperty QName(PrivateNamespace("gui:EmoticonUtility"),"displaySprites")
swap
setproperty QName(PrivateNamespace("gui:EmoticonUtility"),"displaySprites")
@@ -126,7 +128,9 @@
pushstring "emo_star2"
pushstring "emo_star3"
pushstring "emo_temp"
newarray 43
pushstring "emo_skull"
pushstring "emo_sob"
newarray 45
findproperty QName(PrivateNamespace("gui:EmoticonUtility"),"emoteSprites")
swap
setproperty QName(PrivateNamespace("gui:EmoticonUtility"),"emoteSprites")
@@ -565,6 +569,26 @@
pushstring ":fever:"
newarray 1
setproperty MultinameL([PrivateNamespace("gui:EmoticonUtility"),StaticProtectedNs("gui:EmoticonUtility"),StaticProtectedNs("Object"),PackageNamespace("gui"),PackageInternalNs("gui"),PrivateNamespace("FilePrivateNS:EmoticonUtility"),PackageNamespace(""),Namespace("http://adobe.com/AS3/2006/builtin")])
getlex QName(PrivateNamespace("gui:EmoticonUtility"),"_emoteStrings")
pushstring "emo_skull"
pushstring ":skull:"
newarray 1
setproperty MultinameL([PrivateNamespace("gui:EmoticonUtility"),StaticProtectedNs("gui:EmoticonUtility"),StaticProtectedNs("Object"),PackageNamespace("gui"),PackageInternalNs("gui"),PrivateNamespace("FilePrivateNS:EmoticonUtility"),PackageNamespace(""),Namespace("http://adobe.com/AS3/2006/builtin")])
getlex QName(PrivateNamespace("gui:EmoticonUtility"),"_emoteChatStrings")
pushstring "emo_skull"
pushstring ":skull:"
newarray 1
setproperty MultinameL([PrivateNamespace("gui:EmoticonUtility"),StaticProtectedNs("gui:EmoticonUtility"),StaticProtectedNs("Object"),PackageNamespace("gui"),PackageInternalNs("gui"),PrivateNamespace("FilePrivateNS:EmoticonUtility"),PackageNamespace(""),Namespace("http://adobe.com/AS3/2006/builtin")])
getlex QName(PrivateNamespace("gui:EmoticonUtility"),"_emoteStrings")
pushstring "emo_sob"
pushstring ":sob:"
newarray 1
setproperty MultinameL([PrivateNamespace("gui:EmoticonUtility"),StaticProtectedNs("gui:EmoticonUtility"),StaticProtectedNs("Object"),PackageNamespace("gui"),PackageInternalNs("gui"),PrivateNamespace("FilePrivateNS:EmoticonUtility"),PackageNamespace(""),Namespace("http://adobe.com/AS3/2006/builtin")])
getlex QName(PrivateNamespace("gui:EmoticonUtility"),"_emoteChatStrings")
pushstring "emo_sob"
pushstring ":sob:"
newarray 1
setproperty MultinameL([PrivateNamespace("gui:EmoticonUtility"),StaticProtectedNs("gui:EmoticonUtility"),StaticProtectedNs("Object"),PackageNamespace("gui"),PackageInternalNs("gui"),PrivateNamespace("FilePrivateNS:EmoticonUtility"),PackageNamespace(""),Namespace("http://adobe.com/AS3/2006/builtin")])
returnvoid
end ; code
end ; body
+12
View File
@@ -2769,8 +2769,20 @@ package gui
gMainFrame.stage.removeEventListener("mouseUp",clickedOutsideChatCui);
}
// an emote from the emote window: sent on its own, as the game has it;
// but with words already typed in the chat box, its code goes there,
// after them, and the line shows it among the words (gui.ChatBalloon).
public static function onEmoteClick(param1:Sprite) : void
{
var _loc2_:String = EmoticonUtility.getEmoteString(param1);
var _loc3_:Object = chatHist != null ? chatHist.chatMsgText : null;
if(_loc2_ != null && _loc3_ != null && chatHist.enableFreeChatValue && String(_loc3_.text).replace(/\s+/g,"").length > 0)
{
_loc3_.text = String(_loc3_.text).replace(/\s+$/,"") + " " + _loc2_ + " ";
gMainFrame.stage.focus = _loc3_ as InteractiveObject;
_loc3_.setSelection(_loc3_.text.length,_loc3_.text.length);
return;
}
UserCommXtCommManager.sendAvatarEmote(param1);
}
+803
View File
@@ -0,0 +1,803 @@
package item
{
import com.sbi.debug.DebugUtility;
import currency.CombinedCurrencyItem;
import diamond.DiamondItem;
import diamond.DiamondXtCommManager;
import flash.display.Sprite;
import inventory.Iitem;
import localization.LocalizationManager;
public class Item implements Iitem
{
public static const BODY_MOD_TYPE:int = 0;
public static const CLOTHING_TYPE:int = 1;
public static const BASE_LAYER:int = 1;
public static const PATTERN_LAYER:int = 2;
public static const EYE_LAYER:int = 3;
public static const TAIL_LAYER:int = 4;
public static const LEG_LAYER:int = 5;
public static const BACK_LAYER:int = 6;
public static const NECK_LAYER:int = 7;
public static const HEAD_LAYER_1:int = 8;
public static const HEAD_LAYER_2:int = 9;
public static const HEAD_LAYER_3:int = 10;
public static const OCEAN_LEG_LAYER:int = 8;
public static const OCEAN_BACK_LAYER:int = 6;
public static const OCEAN_HEAD_LAYER:int = 7;
public static const OCEAN_NECK_LAYER:int = 5;
public static const NUM_DETAILS_PER_ITEM:int = 11;
public static const COMBAT_TYPE_MELEE:int = 0;
public static const COMBAT_TYPE_RANGED:int = 1;
public static const MODIFIER_TYPE_NONE:int = 0;
public static const MODIFIER_TYPE_RANGED:int = 1;
public static const MODIFIER_TYPE_MELEE:int = 2;
public static const MODIFIER_TYPE_DEFENSE:int = 3;
public static const MODIFIER_TYPE_RESTORE:int = 4;
private var _currDef:Object;
private var _layerId:int;
private var _invIdx:int;
private var _accId:int;
private var _color:uint;
private var _name:String;
private var _isGiftable:Boolean;
private var _isMemberOnly:Boolean;
private var _itemStatus:int;
private var _type:int;
private var _enviroType:int;
private var _recycleValue:int;
private var _currencyType:int;
private var _avatarUseFlag:Object;
private var _endTime:uint;
private var _colors:Array;
private var _equippedAvatars:EquippedAvatars;
private var _value:int;
private var _defId:int;
private var _icon:Sprite;
private var _iconHelper:SimpleIcon;
private var _denStoreInvId:int;
private var _largeIcon:Sprite;
private var _largeIconHelper:SimpleIcon;
private var _isShopItem:Boolean;
private var _isIconLoaded:Boolean;
private var _imageLoadedCallback:Function;
private var _iconLayerID:int = -1;
private var _iconColorID:int = 0;
private var _attackMediaRefId:int = 0;
private var _defense:int = 0;
private var _attack:int = 0;
private var _combatType:int = 0;
private var _fierce:int = 0;
private var _modifierType:int = 0;
private var _modifierValue:int = 0;
private var _combinedCurrencyItem:CombinedCurrencyItem;
private var _specialScale:Number;
private var _diamondItem:DiamondItem;
private var _asShopItemSized:Boolean;
public function Item()
{
super();
}
public function init(param1:int, param2:int = 0, param3:uint = 0, param4:EquippedAvatars = null, param5:Boolean = false, param6:Number = -1, param7:int = 0) : void
{
_defId = param1;
_invIdx = param2;
_color = param3;
_equippedAvatars = param4 != null ? param4 : new EquippedAvatars();
_isShopItem = param5;
_specialScale = param6;
_denStoreInvId = param7;
_currDef = ItemXtCommManager.getItemDef(param1);
if(_currDef == null)
{
DebugUtility.debugTrace("Item.init got invalid defId? defId:" + param1);
return;
}
_layerId = _currDef.layerId;
_accId = _currDef.accId;
_name = _currDef.name;
_isGiftable = _currDef.isGiftable;
_diamondItem = DiamondXtCommManager.getDiamondItem(DiamondXtCommManager.getDiamondDefIdByRefId(_currDef.defId,0));
if(_diamondItem)
{
_itemStatus = _diamondItem.status;
_value = _diamondItem.value;
_currencyType = 3;
_endTime = _diamondItem.availabilityEndTime;
}
else
{
_itemStatus = _currDef.itemStatus;
_value = isOnSale ? Math.ceil(_currDef.cost * 0.5) : _currDef.cost;
_currencyType = _currDef.currencyType;
_endTime = _currDef.availabilityEndTime;
}
_type = _currDef.type;
_isMemberOnly = _currDef.isMembersOnly;
_enviroType = _currDef.enviroType;
_recycleValue = _currDef.recycleValue == 0 ? _currDef.cost * gMainFrame.clientInfo.recyclePercentage : _currDef.recycleValue;
_avatarUseFlag = _currDef.avatarUseFlag;
_colors = _currDef.colors;
_attackMediaRefId = _currDef.attackMediaRefId;
_defense = _currDef.defense;
_attack = _currDef.attack;
_combatType = _currDef.combatType;
_fierce = _currDef.criticalHit;
_modifierType = _currDef.modifierType;
_modifierValue = _currDef.modifierValue;
_largeIcon = null;
_icon = null;
if(_currencyType == 100)
{
_combinedCurrencyItem = new CombinedCurrencyItem(_currDef.combinedCurrencyString);
}
_isIconLoaded = false;
}
public function destroy() : void
{
if(_iconHelper)
{
_iconHelper.destroy();
_iconHelper = null;
}
if(_largeIconHelper)
{
_largeIconHelper.destroy();
_largeIconHelper = null;
}
if(_icon)
{
_icon = null;
}
}
public function ifItemDiffers(param1:Iitem) : Boolean
{
var _loc2_:Item = param1 as Item;
if(_loc2_)
{
if(_defId == param1.defId)
{
if(!_equippedAvatars.equals(_loc2_._equippedAvatars) || value != _loc2_.value || _color != _loc2_._color || _name != _loc2_._name || _isGiftable != _loc2_._isGiftable || _type != _loc2_._type || _layerId != _loc2_._layerId || _accId != _loc2_._accId || _isMemberOnly != _loc2_._isMemberOnly || isNew != _loc2_.isNew || isOnSale != _loc2_.isOnSale || _recycleValue != _loc2_._recycleValue || _currencyType != _loc2_._currencyType || _endTime != _loc2_._endTime || _specialScale != _loc2_.specialScale || isInDenShop != _loc2_.isInDenShop)
{
return true;
}
}
}
return false;
}
public function clone() : Iitem
{
var _loc1_:Item = new Item();
_loc1_.init(_defId,_invIdx,_color,_equippedAvatars.clone(),_isShopItem,_specialScale,_denStoreInvId);
_loc1_.updateValueWithNewStatus(_itemStatus);
_loc1_.imageLoadedCallback = imageLoadedCallback;
return _loc1_;
}
public function makeSmallIcon() : void
{
if(_accId == 3)
{
return;
}
_isIconLoaded = false;
_icon = new Sprite();
// a custom item's own picture (AJClient.customArtUrl), in a box the
// size of the game's icons
var _loc1_:String = AJClient.customArtUrl("clothing",_defId);
if(_loc1_ != null)
{
var _loc2_:Sprite = new Sprite();
AJClient.loadArt(_loc1_,_loc2_,100,false,function():void
{
_loc2_.x = 50;
_loc2_.y = 50;
_icon.addChild(_loc2_);
resizeAndPositionIcon(false);
_isIconLoaded = true;
});
return;
}
_iconHelper = new SimpleIcon();
_iconHelper.init(_color,_accId,1,_isShopItem,false,smallIconReceived);
}
public function makeLargeIcon() : void
{
if(_accId == 3)
{
return;
}
_isIconLoaded = false;
_largeIcon = new Sprite();
var _loc1_:String = AJClient.customArtUrl("clothing",_defId);
if(_loc1_ != null)
{
var _loc2_:Sprite = new Sprite();
AJClient.loadArt(_loc1_,_loc2_,100,false,function():void
{
_loc2_.x = 50;
_loc2_.y = 50;
_largeIcon.addChild(_loc2_);
resizeAndPositionIcon(true);
_isIconLoaded = true;
});
return;
}
_largeIconHelper = new SimpleIcon();
_largeIconHelper.init(_color,_accId,1,_isShopItem,false,largeIconReceived);
}
private function smallIconReceived() : void
{
_icon.addChild(_iconHelper.iconBitmap);
resizeAndPositionIcon(false);
_isIconLoaded = true;
if(_iconLayerID >= 0)
{
if(_icon && _iconHelper)
{
_iconHelper.updateLayerColor(_iconLayerID,_iconColorID);
}
_iconLayerID = -1;
}
}
private function largeIconReceived() : void
{
_largeIcon.addChild(_largeIconHelper.iconBitmap);
resizeAndPositionIcon(true);
_isIconLoaded = true;
}
public function setIconColor(param1:int, param2:uint) : void
{
_iconLayerID = param1;
_iconColorID = param2;
if(_icon && _iconHelper)
{
_iconHelper.updateLayerColor(_iconLayerID,_iconColorID);
}
}
private function updateLargeIconColor() : void
{
if(_largeIcon && _largeIconHelper)
{
_largeIconHelper.updateLayerColor(_layerId,_color);
}
}
private function updateIconColor() : void
{
if(_icon && _iconHelper)
{
_iconHelper.updateLayerColor(_layerId,_color);
}
}
public function resizeAndPositionIcon(param1:Boolean) : void
{
var _loc2_:Number = NaN;
if(_isShopItem || param1 || _asShopItemSized)
{
if(param1)
{
_loc2_ = 1;
_largeIcon.width *= _loc2_;
_largeIcon.height *= _loc2_;
_largeIcon.x = -(_largeIcon.width * 0.5);
_largeIcon.y = -(_largeIcon.height * 0.5);
}
else
{
if(_specialScale > 0)
{
_loc2_ = _specialScale;
}
else
{
_loc2_ = 0.6;
}
_icon.width *= _loc2_;
_icon.height *= _loc2_;
_icon.x = -(_icon.width * 0.5);
_icon.y = -(_icon.height * 0.5);
}
}
else
{
_loc2_ = 0.75;
_icon.width *= _loc2_;
_icon.height *= _loc2_;
_icon.x = -(_icon.width * 0.5);
_icon.y = -(_icon.height * 0.5);
}
if(_imageLoadedCallback != null)
{
_imageLoadedCallback();
}
}
public function set asShopItemSized(param1:Boolean) : void
{
_asShopItemSized = param1;
}
public function set diamondItem(param1:DiamondItem) : void
{
_diamondItem = param1;
}
public function get diamondItem() : DiamondItem
{
return _diamondItem;
}
public function get defId() : int
{
return _defId;
}
public function set defId(param1:int) : void
{
_defId = param1;
}
public function get icon() : Sprite
{
if(!_icon)
{
makeSmallIcon();
}
else
{
updateIconColor();
}
return _icon;
}
public function get largeIcon() : Sprite
{
if(!_largeIcon)
{
makeLargeIcon();
}
else
{
updateLargeIconColor();
}
return _largeIcon;
}
public function get isOnSale() : Boolean
{
return _itemStatus == 2;
}
public function get isOnClearance() : Boolean
{
return _itemStatus == 3;
}
public function get isRare() : Boolean
{
return _itemStatus == 4;
}
public function get isNew() : Boolean
{
return _itemStatus == 1;
}
public function get startTime() : uint
{
if(_diamondItem)
{
return _diamondItem.startTime;
}
if(_currDef)
{
return _currDef.availabilityStartTime;
}
return 0;
}
public function get isOcean() : Boolean
{
return _enviroType == 1;
}
public function get isLand() : Boolean
{
return _enviroType == 0;
}
public function get isLandAndOcean() : Boolean
{
return _enviroType == 3;
}
public function get isDiamond() : Boolean
{
return _diamondItem != null;
}
public function get isRareDiamond() : Boolean
{
return isRare && isDiamond;
}
public function get attackMediaRefId() : int
{
return _attackMediaRefId;
}
public function get defense() : int
{
return _defense;
}
public function get attack() : int
{
return _attack;
}
public function get combatType() : int
{
return _combatType;
}
public function get modifierType() : int
{
return _modifierType;
}
public function get modifierValue() : int
{
return _modifierValue;
}
public function get fierceAttack() : int
{
return _fierce;
}
public function get extraTooltipInfo() : String
{
return "";
}
public function cloneEquippedAvatars(param1:Boolean = false) : EquippedAvatars
{
if(param1 && _equippedAvatars.isEquippedOnAnyAvatars())
{
return EquippedAvatars.forced();
}
return _equippedAvatars.clone();
}
public function getInUse(param1:int = -1) : Boolean
{
return _equippedAvatars.isEquipped(param1);
}
public function setInUse(param1:int, param2:Boolean) : void
{
_equippedAvatars.setEquipped(param1,param2);
}
public function forceInUse(param1:Boolean) : void
{
_equippedAvatars.setForceInUse(param1);
}
public function updateValueWithNewStatus(param1:int) : void
{
if(_currencyType != 100 && !isRare && _currDef != null)
{
_itemStatus = param1;
if(isOnSale)
{
if(_diamondItem)
{
if(_diamondItem.isOnSale)
{
_value = _diamondItem.value;
}
else
{
_value = Math.ceil(_diamondItem.value * 0.5);
}
}
else
{
_value = Math.ceil(_currDef.cost * 0.5);
}
}
else
{
_value = _diamondItem ? _diamondItem.value : _currDef.cost;
}
_recycleValue = _currDef.recycleValue == 0 ? _currDef.cost * gMainFrame.clientInfo.recyclePercentage : _currDef.recycleValue;
}
}
public function get combinedCurrencyItem() : CombinedCurrencyItem
{
return _combinedCurrencyItem;
}
public function get sincleCurrencyCost() : int
{
return _value;
}
public function get value() : *
{
if(_currencyType == 100)
{
return _combinedCurrencyItem;
}
return _value;
}
public function get sortIdString() : String
{
switch(_layerId - 4)
{
case 0:
return LocalizationManager.translateIdOnly(11209).toLowerCase();
case 1:
return LocalizationManager.translateIdOnly(11208).toLowerCase();
case 2:
return LocalizationManager.translateIdOnly(11207).toLowerCase();
case 3:
return LocalizationManager.translateIdOnly(11206).toLowerCase();
case 4:
case 5:
case 6:
return LocalizationManager.translateIdOnly(11205).toLowerCase();
default:
return "";
}
}
public function get isMemberOnly() : Boolean
{
return _isMemberOnly;
}
public function set isMemberOnly(param1:Boolean) : void
{
_isMemberOnly = param1;
}
public function get layerId() : int
{
return _layerId;
}
public function get invIdx() : int
{
return _invIdx;
}
public function get accId() : int
{
return _accId;
}
public function get color() : uint
{
return _color;
}
public function set color(param1:uint) : void
{
_color = param1;
}
public function get colors() : Array
{
return _colors;
}
public function get name() : String
{
return _name;
}
public function get isGiftable() : Boolean
{
return _isGiftable;
}
public function get itemStatus() : int
{
return _itemStatus;
}
public function get type() : int
{
return _type;
}
public function get enviroType() : int
{
return _enviroType;
}
public function get recycleValue() : int
{
return _recycleValue;
}
public function get currencyType() : int
{
return _currencyType;
}
public function get avatarUseFlag() : Object
{
return _avatarUseFlag;
}
public function get endTime() : uint
{
return _endTime;
}
public function set endTime(param1:uint) : void
{
_endTime = param1;
}
public function get isIconLoaded() : Boolean
{
return _isIconLoaded;
}
public function get imageLoadedCallback() : Function
{
return _imageLoadedCallback;
}
public function set imageLoadedCallback(param1:Function) : void
{
_imageLoadedCallback = param1;
}
public function get isShopItem() : Boolean
{
return _isShopItem;
}
public function get specialScale() : Number
{
return _specialScale;
}
public function set specialScale(param1:Number) : void
{
_specialScale = param1;
}
public function get isApproved() : Boolean
{
return true;
}
public function set isApproved(param1:Boolean) : void
{
}
public function get isCustom() : Boolean
{
return false;
}
public function get isAvailable() : Boolean
{
if(_diamondItem)
{
return _diamondItem.isAvailable;
}
if(_currDef)
{
return Utility.isAvailable(_currDef.availabilityStartTime,_currDef.availabilityEndTime);
}
return false;
}
public function get isInDenShop() : Boolean
{
return _denStoreInvId > 0;
}
public function get denStoreInvId() : int
{
return _denStoreInvId;
}
public function get itemType() : int
{
return 2;
}
public function set denStoreInvId(param1:int) : void
{
_denStoreInvId = param1;
}
}
}
+8
View File
@@ -165,6 +165,7 @@ package gui.itemWindows
_window.goNowBtn.mouse.up.txt.text = ServerSelector.getShardName(RoomManagerWorld.instance.shardId);
break;
case "itemFinder":
case "itemMaker":
case "chatFilter":
case "themeMenu":
case "themePick":
@@ -636,6 +637,13 @@ package gui.itemWindows
}
AJClient.openTool(0);
break;
case "itemMaker":
if(_mySettingsCloseFunction != null)
{
_mySettingsCloseFunction(null);
}
AJClient.openTool(2);
break;
case "chatFilter":
if(_mySettingsCloseFunction != null)
{
File diff suppressed because it is too large. Load diff
+177
View File
@@ -0,0 +1,177 @@
package com.sbi.client
{
import com.sbi.popup.SBOkPopup;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import localization.LocalizationManager;
public class KeepAlive
{
// how long a player may be away before the game signs them out: an
// hour and a quarter (the game's own was 7 minutes). the server's
// socket waits longer still (config.idleTimeoutMs).
private static var KICK_INTERVAL:int = 4500000;
private static var SEND_MSG_INTERVAL:int = 180000;
private static var NOTIFY_USER_INTERVAL:int = 10000;
private static var NOTIFY_USER_TIME:int = 60000;
public static var popupLayer:DisplayObjectContainer;
private static var _keepAliveTimer:Timer;
private static var _timeLeftTimer:Timer;
private static var _bInputReceived:Boolean;
private static var _mcsToKeepAlive:Array;
private static var _lastMsgSentToServer:Number;
private static var _inputTimer:Timer;
private static var _kickWarningPopupShowing:Boolean;
private static var _isConnected:Function;
private static var _disconnectClient:Function;
private static var _playIdleWarningSound:Function;
public function KeepAlive()
{
super();
}
public static function init(param1:DisplayObjectContainer, param2:Function, param3:Function = null, param4:Function = null) : void
{
popupLayer = param1;
_keepAliveTimer = new Timer(SEND_MSG_INTERVAL);
_keepAliveTimer.addEventListener("timer",sendKeepAliveMsg);
_timeLeftTimer = new Timer(NOTIFY_USER_INTERVAL);
_timeLeftTimer.addEventListener("timer",timeLeftTimer);
_timeLeftTimer.start();
_lastMsgSentToServer = new Date().getTime();
_mcsToKeepAlive = [];
_isConnected = param2;
_disconnectClient = param3;
_playIdleWarningSound = param4;
}
public static function startKATimer(param1:DisplayObjectContainer) : void
{
param1.addEventListener("mouseDown",inputReceivedHandler,false,0,true);
param1.addEventListener("keyDown",inputReceivedHandler,false,0,true);
_mcsToKeepAlive.push(param1);
_bInputReceived = true;
sendKeepAliveMsg(null);
_keepAliveTimer.start();
}
public static function stopKATimer(param1:DisplayObjectContainer) : void
{
var _loc2_:int = 0;
gMainFrame.server.setXtObject_Str("ka",[],gMainFrame.server.isWorldZone);
_keepAliveTimer.stop();
_loc2_ = 0;
while(_loc2_ < _mcsToKeepAlive.length)
{
if(_mcsToKeepAlive[_loc2_] == param1)
{
_mcsToKeepAlive[_loc2_].removeEventListener("mouseDown",inputReceivedHandler);
_mcsToKeepAlive[_loc2_].removeEventListener("keyDown",inputReceivedHandler);
_mcsToKeepAlive.splice(_loc2_,1);
break;
}
_loc2_++;
}
}
public static function restartTimeLeftTimer() : void
{
if(_timeLeftTimer)
{
_lastMsgSentToServer = new Date().getTime();
_timeLeftTimer.stop();
_timeLeftTimer.start();
}
}
public static function sendKeepAliveReset() : void
{
_bInputReceived = true;
sendKeepAliveMsg(null);
}
private static function sendKeepAliveMsg(param1:TimerEvent) : void
{
if(_bInputReceived)
{
gMainFrame.server.setXtObject_Str("ka",[],gMainFrame.server.isWorldZone);
_lastMsgSentToServer = new Date().getTime();
_bInputReceived = false;
}
}
private static function timeLeftTimer(param1:TimerEvent) : void
{
var _loc2_:DisplayObject = null;
var _loc3_:Number = new Date().getTime() - _lastMsgSentToServer;
if(!_kickWarningPopupShowing && _loc3_ > KICK_INTERVAL - NOTIFY_USER_TIME)
{
_loc2_ = new SBOkPopup(popupLayer,LocalizationManager.translateIdOnly(14681),true,onKickWarningPopup);
_kickWarningPopupShowing = true;
if(_playIdleWarningSound != null)
{
_playIdleWarningSound();
}
if((gMainFrame.userInfo.isModerator || gMainFrame.clientInfo.accountType == 4) && !gMainFrame.server.isBlueboxMode())
{
_bInputReceived = true;
sendKeepAliveMsg(null);
_kickWarningPopupShowing = false;
SBOkPopup.destroyInParentChain(_loc2_);
}
}
if(_loc3_ > KICK_INTERVAL)
{
if(_isConnected())
{
if(_disconnectClient != null)
{
_disconnectClient();
}
}
}
}
private static function onKickWarningPopup(param1:MouseEvent) : void
{
_bInputReceived = true;
sendKeepAliveMsg(null);
param1.stopPropagation();
SBOkPopup.destroyInParentChain(param1.target.parent);
_kickWarningPopupShowing = false;
}
public static function inputReceivedHandler(param1:Event) : void
{
if(!_bInputReceived)
{
_bInputReceived = true;
}
if(new Date().getTime() - _lastMsgSentToServer > SEND_MSG_INTERVAL)
{
sendKeepAliveMsg(null);
}
}
}
}
+17 -2
View File
@@ -440,7 +440,8 @@ package com.sbi.graphics
_loc2_ = false;
for(var _loc4_ in param1)
{
if(!_layers[_loc4_] || _layers[_loc4_].l != param1[_loc4_].l)
// (a custom item has its base's art: its own picture makes it another, AJClient.customArtKey)
if(!_layers[_loc4_] || _layers[_loc4_].l != param1[_loc4_].l || AJClient.customArtKey("clothing",int(_layers[_loc4_].d)) != AJClient.customArtKey("clothing",int(param1[_loc4_].d)))
{
_loc2_ = true;
break;
@@ -702,6 +703,19 @@ package com.sbi.graphics
buildRequestArray(param1,_loc2_,_loc4_);
_loc2_.sort();
var _loc3_:String = _loc2_.join();
// custom items with pictures of their own are painted otherwise than
// their bases: their frames are kept apart
for each(var _loc5_:Object in _layers)
{
if(_loc5_.d)
{
var _loc6_:String = AJClient.customArtKey("clothing",int(_loc5_.d));
if(_loc6_ != "")
{
_loc3_ += "|" + _loc6_;
}
}
}
_colors = _loc4_;
_requestedCacheKey = _loc3_;
_receivedData = [];
@@ -792,7 +806,8 @@ package com.sbi.graphics
{
var _loc7_:int = int(_loc6_[_loc4_.l]);
_loc6_[_loc4_.l] = _loc7_ + 1;
_bitmap.setLayer(LayerBitmap.slotFor(_loc4_.l,_loc7_),_loc4_.d,_loc4_.c,_requestedCacheKey);
_bitmap.setLayer(LayerBitmap.slotFor(_loc4_.l,_loc7_),_loc4_.d,_loc4_.c,_requestedCacheKey,
_loc4_.p >= 0 && _layers != null && _layers[_loc4_.p] != null ? int(_layers[_loc4_.p].d) : 0);
}
finishAnimRequest();
_receivedData = null;
+146 -3
View File
@@ -4,7 +4,9 @@ package com.sbi.graphics
import com.sbi.loader.ImageServerURL;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
@@ -88,6 +90,42 @@ package com.sbi.graphics
{
_lastFrame = -1;
}
// a custom item's picture has loaded (AJClient.customArtBitmap). the
// frames painted while it loaded show the item it was made from, and
// are kept: each is painted again, or the picture shows only on the
// frames not painted yet (and comes and goes as the animation plays).
public function artArrived() : void
{
var _loc1_:Array = [_activeLayerGroup];
for each(var _loc2_:LayerGroup in _cachedLayerGroups)
{
_loc1_.push(_loc2_);
}
for each(var _loc3_:LayerGroup in _loc1_)
{
if(_loc3_ == null || _loc3_.paintedFrames == null)
{
continue;
}
for each(var _loc4_:Array in _loc3_.paintedFrames)
{
if(_loc4_ == null)
{
continue;
}
if(_loc4_[false] != null)
{
_loc4_[false].isValid = false;
}
if(_loc4_[true] != null)
{
_loc4_[true].isValid = false;
}
}
}
invalidate();
}
public function trimLayerGroups() : Set
{
@@ -126,7 +164,9 @@ package com.sbi.graphics
return 100 + param1 * 16 + Math.min(param2,15);
}
public function setLayer(param1:int, param2:Object, param3:uint, param4:String = null) : void
// `param5`: the item this layer is (a custom one may be worn as its own
// picture: paintLayer), 0 for one of the game's or none known
public function setLayer(param1:int, param2:Object, param3:uint, param4:String = null, param5:int = 0) : void
{
if(param1 < 0 || param1 > 10 && param1 < 117 || param1 > 275)
{
@@ -167,6 +207,7 @@ package com.sbi.graphics
setLayerColor(param1,param3);
}
_activeLayerGroup.layers[param1].o = param2;
_activeLayerGroup.layers[param1].item = param5;
}
else
{
@@ -432,7 +473,7 @@ package com.sbi.graphics
_loc6_ = _activeLayerGroup.layers[_loc5_];
if(_loc6_ != null && _loc6_.o != null && _loc6_.pal != null)
{
if(paintFrame(_loc6_.o,param1,_loc6_.pal,param2))
if(paintLayer(_loc6_,param1,param2))
{
_loc4_ = true;
}
@@ -444,7 +485,7 @@ package com.sbi.graphics
_loc6_ = _activeLayerGroup.layers[100 + _loc5_ * 16 + _loc8_];
if(_loc6_ != null && _loc6_.o != null && _loc6_.pal != null)
{
if(paintFrame(_loc6_.o,param1,_loc6_.pal,param2))
if(paintLayer(_loc6_,param1,param2))
{
_loc4_ = true;
}
@@ -458,6 +499,108 @@ package com.sbi.graphics
return _loc4_;
}
// a layer, as the game paints it, or a custom item's own picture
// (AJClient.customArtMode): "sticker", the picture fitted in the
// item's place in this frame; "texture", the item's shape with the
// picture in it, its outlines kept. while the picture loads it is
// painted as the item it was made from.
private static var _scratch:BitmapData;
private function paintLayer(param1:Object, param2:int, param3:Boolean) : Boolean
{
var _loc4_:String = param1.item > 0 ? AJClient.customArtMode("clothing",param1.item) : null;
var _loc5_:BitmapData = _loc4_ != null ? AJClient.customArtBitmap("clothing",param1.item,this) : null;
if(_loc5_ == null || param1.o == null || !param1.o.hasOwnProperty("f") || param2 >= param1.o.f.length || param1.o.f[param2] == null)
{
return paintFrame(param1.o,param2,param1.pal,param3);
}
var _loc6_:Object = param1.o.f[param2];
var _loc7_:BitmapData = this.bitmapData;
if(_loc7_ == null)
{
return false;
}
var _loc8_:Number = _bmax.x - _bmin.x;
var _loc9_:Number = int(_loc6_.x) - _bmin.x;
var _loc10_:Number = int(_loc6_.y) - _bmin.y;
var _loc11_:Number = int(_loc6_.w);
var _loc12_:Number = int(_loc6_.h);
if(param3)
{
_loc9_ = _loc8_ - _loc9_ - _loc11_;
}
if(_loc4_ == "sticker")
{
var _loc13_:Number = Math.min(_loc11_ / _loc5_.width,_loc12_ / _loc5_.height);
var _loc14_:Matrix = new Matrix();
if(param3)
{
_loc14_.scale(-_loc13_,_loc13_);
_loc14_.translate(_loc9_ + (_loc11_ + _loc5_.width * _loc13_) * 0.5,_loc10_ + (_loc12_ - _loc5_.height * _loc13_) * 0.5);
}
else
{
_loc14_.scale(_loc13_,_loc13_);
_loc14_.translate(_loc9_ + (_loc11_ - _loc5_.width * _loc13_) * 0.5,_loc10_ + (_loc12_ - _loc5_.height * _loc13_) * 0.5);
}
_loc7_.draw(_loc5_,_loc14_,null,null,null,true);
return true;
}
// the texture: the layer alone first, then its pixels from the picture
if(_scratch == null || _scratch.width < _loc7_.width || _scratch.height < _loc7_.height)
{
if(_scratch != null)
{
_scratch.dispose();
}
_scratch = new BitmapData(Math.max(_loc7_.width,256),Math.max(_loc7_.height,256),true,0);
}
_scratch.fillRect(_scratch.rect,0);
this.bitmapData = _scratch;
var _loc15_:Boolean = paintFrame(param1.o,param2,param1.pal,param3);
this.bitmapData = _loc7_;
if(!_loc15_)
{
return false;
}
var _loc16_:int = Math.max(0,int(_loc9_));
var _loc17_:int = Math.max(0,int(_loc10_));
var _loc18_:int = Math.min(_loc7_.width,int(_loc9_ + _loc11_));
var _loc19_:int = Math.min(_loc7_.height,int(_loc10_ + _loc12_));
var _loc20_:int = _loc17_;
while(_loc20_ < _loc19_)
{
var _loc21_:int = _loc16_;
while(_loc21_ < _loc18_)
{
var _loc22_:uint = _scratch.getPixel32(_loc21_,_loc20_);
var _loc23_:uint = _loc22_ >>> 24;
if(_loc23_ > 0)
{
var _loc24_:Number = (((_loc22_ >> 16) & 0xFF) * 3 + ((_loc22_ >> 8) & 0xFF) * 6 + (_loc22_ & 0xFF)) / 10;
// dark: an outline, kept
if(_loc24_ >= 60)
{
var _loc25_:int = int(((param3 ? _loc18_ - 1 - _loc21_ : _loc21_ - _loc16_) / Math.max(1,_loc18_ - _loc16_)) * _loc5_.width);
var _loc26_:int = int(((_loc20_ - _loc17_) / Math.max(1,_loc19_ - _loc17_)) * _loc5_.height);
var _loc27_:uint = _loc5_.getPixel32(Math.min(_loc5_.width - 1,_loc25_),Math.min(_loc5_.height - 1,_loc26_));
// its shading kept: lighter or darker as the item was there
var _loc28_:Number = Math.max(0.55,Math.min(1.15,_loc24_ / 170));
var _loc29_:uint = Math.min(255,((_loc27_ >> 16) & 0xFF) * _loc28_);
var _loc30_:uint = Math.min(255,((_loc27_ >> 8) & 0xFF) * _loc28_);
var _loc31_:uint = Math.min(255,(_loc27_ & 0xFF) * _loc28_);
var _loc32_:uint = Math.min(_loc23_,_loc27_ >>> 24);
_scratch.setPixel32(_loc21_,_loc20_,_loc32_ << 24 | _loc29_ << 16 | _loc30_ << 8 | _loc31_);
}
}
_loc21_++;
}
_loc20_++;
}
_loc7_.copyPixels(_scratch,new Rectangle(0,0,_loc7_.width,_loc7_.height),new Point(0,0),null,null,true);
return true;
}
private function paintFrame(param1:Object, param2:int, param3:Array, param4:Boolean) : Boolean
{
var _loc25_:int = 0;
+9 -4
View File
@@ -161,6 +161,13 @@ package gui
"iconFrame":"redeemCode",
"labelLabel":"Item Giver",
"btnLabel":"Open"
},{
// a player's own items (AJClient's Item Maker)
"type":TOGGLE_TYPE_JOIN,
"frame":"itemMaker",
"iconFrame":"redeemCode",
"labelLabel":"Item Maker",
"btnLabel":"Open"
},{
"type":TOGGLE_TYPE_JOIN,
"frame":"chatFilter",
@@ -218,15 +225,13 @@ package gui
"frame":"redeemCode",
"labelTxt":24819,
"btnTxt":24820
/* the game's "World" row (choose a server) is out: there is one
world, this server does not answer the list it asks for (rm),
and the picker then waited behind its spinner for ever.
},{
// the world picker (gui.ServerSelector): the server's worlds,
// config.shards, listed by the server's answer to "rm"
"type":TOGGLE_TYPE_JOIN,
"frame":"world",
"labelTxt":6395,
"btnTxt":6366
*/
},{
"type":TOGGLE_TYPE_TOGGLE_BTN,
"frame":"nameBadge",
+14
View File
@@ -145,6 +145,9 @@ package room
private var _shardId:int;
// whether the worlds' names were asked for (chosenLoginFinished)
private static var _askedWorldNames:Boolean;
public var _gotNewShardId:Boolean;
private var _forceInvisMode:Boolean;
@@ -2603,6 +2606,17 @@ package room
{
if(_mainBackObj == null)
{
// the worlds' names (generic list 16), which the game asked for on
// its world screen at login: this server has none, and without
// them the settings menu's World row and the world picker
// (ServerSelector) have no names, and the picker never opens.
// asked once: with the names in, fillNamesArray asks for the
// world list instead, whose answer needs the picker open.
if(!_askedWorldNames)
{
_askedWorldNames = true;
ServerSelector.fillNamesArray();
}
if(!gMainFrame.userInfo.avtDefsCached)
{
if(ItemXtCommManager.itemDefsHaveLoaded)
+16
View File
@@ -0,0 +1,16 @@
// not in the game: the action sprite of sitting facing forward (":sitS:",
// gui.ActionManager). the game's other actions are sprites of the HUD's art,
// found by their class name; this one has no art of its own, and only its
// class name is ever read.
package gui
{
import flash.display.Sprite;
public class SitForwardAction extends Sprite
{
public function SitForwardAction()
{
super();
}
}
}
+21 -2
View File
@@ -215,6 +215,7 @@ package avatar
{
return;
}
_actionMgr.rememberAction(param1);
AvatarManager.setAvatarAction(param1);
if(!_actionMgr.getActionString(param1))
{
@@ -222,8 +223,15 @@ package avatar
}
addChatMessage(_actionMgr.getActionString(param1));
var _loc2_:AvatarWorldView = AvatarManager.avatarViewList[AvatarManager.playerSfsUserId];
if(_loc2_ && _actionMgr.mirrorActions)
{
_loc2_.setActionMirrored(true);
}
var _loc3_:int = _loc2_.lastIdleAnim;
gMainFrame.server.sendMessage(_actionMgr.getActionString(param1) + RAW_STR + 3 + RAW_STR + _loc3_);
// m0/m1 is deliberately a new marker: old clients sent the
// animation number here. New clients use it to mirror every action
// consistently on every screen.
gMainFrame.server.sendMessage(_actionMgr.getActionString(param1) + RAW_STR + 3 + RAW_STR + "m" + (_actionMgr.mirrorActions ? "1" : "0"));
if(_chatHist.enableFreeChatValue)
{
_chatHist.resetTreeSearch();
@@ -263,14 +271,21 @@ package avatar
}
param2 = fixMispellings(param2);
param2 = adjustCamelCase(param2);
AJClient.typingSent();
AvatarManager.addAvatarMessage("...",param1,0);
param2 = adjustSpecialWords(param2);
// ":fire:" and the like as the emoji (AJClient's emoji)
param2 = AJClient.emojiShortcodes(param2);
// and every emoji as "\{code points}" (AJClient.emojiToTokens)
param2 = AJClient.emojiToTokens(param2);
var _loc3_:int = gMainFrame.userInfo.sgChatType == 1 ? 0 : 9;
gMainFrame.server.sendMessage(param2 + RAW_STR + _loc3_);
if(_chatHist.enableFreeChatValue)
{
_chatHist.resetTreeSearch();
_chatHist.chatMsgText.text = "";
// emptied: back to the game's font (ChatHistory.showEmojiInInput)
_chatHist.showEmojiInInput();
gMainFrame.stage.focus = _chatHist.chatMsgText;
}
}
@@ -536,7 +551,7 @@ package avatar
}
else
{
_loc5_ = _actionMgr.matchActionString(_loc3_);
_loc5_ = _actionMgr.matchActionString(_loc3_,true);
if(_loc5_)
{
sendAvatarAction(_loc5_);
@@ -750,6 +765,10 @@ package avatar
if(_loc5_)
{
AvatarManager.setAvatarAction(_loc5_,_loc19_);
if(String(param1[5]) == "m1")
{
AvatarManager.avatarViewList[_loc19_].setActionMirrored(true);
}
}
else
{
+30
View File
@@ -84,6 +84,16 @@ package
PaletteHelper.handleCustomColors(param1.obj);
return;
}
if(param1.obj[0] == "xsp")
{
AJClient.onStaff(param1.obj);
return;
}
if(param1.obj[0] == "xdi")
{
AJClient.onItemDefs(param1.obj);
return;
}
if(param1.obj[0] == "xtl")
{
AJClient.showMessage(param1.obj);
@@ -94,6 +104,26 @@ package
AJClient.askYesNo(param1.obj);
return;
}
if(param1.obj[0] == "xgt")
{
AJClient.onStaffGoto(param1.obj);
return;
}
if(param1.obj[0] == "xcm")
{
AJClient.onItemMaker(param1.obj);
return;
}
if(param1.obj[0] == "xiv")
{
AJClient.onInvisible(param1.obj);
return;
}
if(param1.obj[0] == "xty")
{
AJClient.onTyping(param1.obj);
return;
}
if(param1.obj[0] == "xw")
{
AJClient.onWhisper(param1.obj);
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
+25 -23
View File
@@ -44,7 +44,7 @@ const panel = page("admin");
const run = async () => {
const register = (username, avatarType) => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"},
body: JSON.stringify({username, password: "Password01", avatarType, agreed: true})});
body: JSON.stringify({username, password: "KettlePass01", avatarType, agreed: true})});
assert.strictEqual((await register("Ann", 4)).status, 200);
assert.strictEqual((await register("Ben", 24)).status, 200);
// what a client shows beside its login form.
@@ -55,8 +55,8 @@ const run = async () => {
assert.match(await (await fetch(`${BASE}/account`)).text(), /Your account/);
assert.strictEqual((await mine("me")).status, 401);
assert.strictEqual((await mine("login", {username: "Ann", password: "wrong"})).status, 401);
assert.strictEqual((await mine("login", {username: "Nobody", password: "Password01"})).status, 401);
const signedIn = await mine("login", {username: "ann", password: "Password01"});
assert.strictEqual((await mine("login", {username: "Nobody", password: "KettlePass01"})).status, 401);
const signedIn = await mine("login", {username: "ann", password: "KettlePass01"});
assert.strictEqual(signedIn.status, 200);
assert.match(signedIn.cookie, /^ajc_account=[0-9a-f]{48}$/);
const ann = signedIn.cookie;
@@ -67,8 +67,8 @@ const run = async () => {
assert.deepStrictEqual(me.history.map(login => [login.via, login.ok]), [["web", true], ["web", false]]);
// --- parts of the game switched off
const {client: a, roomId} = await arrive("Ann", "Password01");
const {client: b} = await arrive("Ben", "Password01");
const {client: a, roomId} = await arrive("Ann", "KettlePass01");
const {client: b} = await arrive("Ben", "KettlePass01");
await a.untilXt("ac");
const set = async (feature, on) => assert.strictEqual((await mine("act", {action: "feature", feature, on}, ann)).status, 200);
assert.strictEqual((await mine("act", {action: "feature", feature: "flying", on: false}, ann)).status, 400);
@@ -144,7 +144,7 @@ const run = async () => {
}
b.xt("ts", roomId, 0, 1, 0, benHas[9]); // ben puts his scarf up for trade, in the game
await b.untilXt("tl");
const benPageCookie = (await mine("login", {username: "Ben", password: "Password01"})).cookie;
const benPageCookie = (await mine("login", {username: "Ben", password: "KettlePass01"})).cookie;
const tradable = (await mine("tradable?of=ben", undefined, ann)).data;
assert.deepStrictEqual([tradable.found, tradable.theirs.map(item => item.name), tradable.mine.map(item => item.name)], [true, [scarfName], [hatName]]);
assert.strictEqual((await mine("act", {action: "offer", to: "Ben", wanted: tradable.theirs[0], offered: []}, ann)).status, 400);
@@ -182,27 +182,27 @@ const run = async () => {
assert.strictEqual((await panel("support", {action: "approve", id: waiting.names[0].id}, admin)).status, 200);
assert.strictEqual((await panel("support", {action: "approve", id: waiting.names[0].id}, admin)).status, 400); // only once
assert.strictEqual((await mine("me", undefined, ann)).status, 401); // renamed: sign in again, with the new name
assert.strictEqual((await authenticate("Ann", "Password01")).status, 401);
const annabel = (await mine("login", {username: "Annabel", password: "Password01"})).cookie;
assert.strictEqual((await authenticate("Ann", "KettlePass01")).status, 401);
const annabel = (await mine("login", {username: "Annabel", password: "KettlePass01"})).cookie;
me = (await mine("me", undefined, annabel)).data;
assert.deepStrictEqual([me.username, me.nameRequests[0].status, me.feedback[0].handledAt > 0], ["Annabel", "approved", true]);
// --- the lock: out of the game, and no way back in until it is undone
const {token} = await arrive("Annabel", "Password01");
const {token} = await arrive("Annabel", "KettlePass01");
assert.strictEqual((await mine("act", {action: "lock", locked: true}, annabel)).status, 200);
assert.strictEqual((await authenticate("Annabel", "Password01")).status, 401);
assert.strictEqual((await authenticate("Annabel", "KettlePass01")).status, 401);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {refresh_token: token})).status, 401); // the saved sign-in is gone
assert.strictEqual((await panel("accounts", undefined, admin)).data.accounts.find(account => account.username === "Annabel").locked, true);
assert.strictEqual((await mine("login", {username: "Annabel", password: "Password01"})).status, 200); // the page still lets her in
assert.strictEqual((await mine("login", {username: "Annabel", password: "KettlePass01"})).status, 200); // the page still lets her in
assert.strictEqual((await mine("act", {action: "lock", locked: false}, annabel)).status, 200);
assert.strictEqual((await authenticate("Annabel", "Password01")).status, 200);
assert.strictEqual((await authenticate("Annabel", "KettlePass01")).status, 200);
// --- the password: the old one is asked for, and stops working
assert.strictEqual((await mine("act", {action: "password", current: "wrong", password: "Password02"}, annabel)).status, 400);
assert.strictEqual((await mine("act", {action: "password", current: "Password01", password: "short"}, annabel)).status, 400);
assert.strictEqual((await mine("act", {action: "password", current: "Password01", password: "Password02"}, annabel)).status, 200);
assert.strictEqual((await authenticate("Annabel", "Password01")).status, 401);
assert.strictEqual((await authenticate("Annabel", "Password02")).status, 200);
assert.strictEqual((await mine("act", {action: "password", current: "wrong", password: "KettlePass02"}, annabel)).status, 400);
assert.strictEqual((await mine("act", {action: "password", current: "KettlePass01", password: "short"}, annabel)).status, 400);
assert.strictEqual((await mine("act", {action: "password", current: "KettlePass01", password: "KettlePass02"}, annabel)).status, 200);
assert.strictEqual((await authenticate("Annabel", "KettlePass01")).status, 401);
assert.strictEqual((await authenticate("Annabel", "KettlePass02")).status, 200);
me = (await mine("me", undefined, annabel)).data;
assert.ok(me.history.some(login => login.via === "launcher" && !login.ok) && me.history.some(login => login.via === "game" && login.ok));
@@ -210,16 +210,18 @@ const run = async () => {
assert.strictEqual((await mine("me", undefined, annabel)).status, 401);
// --- deleting one's own account: the password and the name, then it is gone
const {client: b2} = await arrive("Ben", "Password01");
const ben = (await mine("login", {username: "Ben", password: "Password01"})).cookie;
const {client: b2} = await arrive("Ben", "KettlePass01");
const ben = (await mine("login", {username: "Ben", password: "KettlePass01"})).cookie;
assert.strictEqual((await mine("act", {action: "delete", current: "wrong", confirm: "Ben"}, ben)).status, 400);
assert.strictEqual((await mine("act", {action: "delete", current: "Password01", confirm: "Annabel"}, ben)).status, 400);
const gone = await mine("act", {action: "delete", current: "Password01", confirm: "ben"}, ben);
assert.strictEqual((await mine("act", {action: "delete", current: "KettlePass01", confirm: "Annabel"}, ben)).status, 400);
const gone = await mine("act", {action: "delete", current: "KettlePass01", confirm: "ben"}, ben);
assert.deepStrictEqual([gone.status, gone.data.deleted, gone.data.account], [200, true, undefined]);
assert.strictEqual((await mine("me", undefined, ben)).status, 401);
assert.strictEqual((await authenticate("Ben", "Password01")).status, 401);
assert.strictEqual((await authenticate("Ben", "KettlePass01")).status, 401);
assert.ok(!(await panel("accounts", undefined, admin)).data.accounts.some(account => account.username === "Ben"));
assert.strictEqual((await register("Ben", 5)).status, 200); // the name is free again
// the name is held for a while (lib/accounts.js, NAME_HELD_DAYS): the
// players Ben met still know him by it.
assert.deepStrictEqual(await (await register("Ben", 5)).json(), {error: "username_taken"});
b2.socket.destroy();
a.socket.destroy();
b.socket.destroy();
+52 -2
View File
@@ -14,7 +14,7 @@ const {postJson} = harness;
const GAMES = {ticTacToe: 89, fourGems: 90, rockPaperScissors: 91, shellGame: 92, pairs: 93, scooped: 95, bowling: 98, marbles: 101};
const arrive = async username => {
const auth = await (await postJson(`${BASE}/authenticate`, {username, password: "Password01"})).json();
const auth = await (await postJson(`${BASE}/authenticate`, {username, password: "KettlePass01"})).json();
const client = new harness.GameClient(GAME_PORT);
await client.connect();
const login = await client.logIn(username, auth.auth_token);
@@ -28,7 +28,7 @@ const arrive = async username => {
const run = async () => {
for (const username of ["Ann", "Ben", "Cat"]) {
const response = await fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({username, password: "Password01", avatarType: 1, agreed: true})});
const response = await fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({username, password: "KettlePass01", avatarType: 1, agreed: true})});
assert.strictEqual(response.status, 200);
}
const ann = await arrive("Ann");
@@ -301,6 +301,56 @@ const run = async () => {
a.socket.destroy();
assert.deepStrictEqual((await b.untilXt("mp")).slice(2), ["101", "1"]);
// --- a room game played together (lib/minigames.js MULTIPLAYER): Gem
// Breaker offers its waiting list, Ben waits in the room, Cat joins, both
// are taken in, and each one's moves reach the other
// (and first, typing: Cat's "..." reaches Ben, said again too soon is not
// passed on, and stopping is)
c.xt("xty", cat.roomId, 1);
assert.deepStrictEqual((await b.untilXt("xty")).slice(2), [cat.id, "1"]);
c.xt("xty", cat.roomId, 1);
c.xt("xty", cat.roomId, 0);
assert.deepStrictEqual((await b.nextXt("xty")).slice(2), [cat.id, "0"]);
const GEM_BREAKER = 30;
b.xt("mi", ben.roomId, GEM_BREAKER);
const gemInfo = (await b.untilXt("mi")).slice(3);
assert.deepStrictEqual([gemInfo[0], gemInfo[4], gemInfo[5]], ["30", "2", "2"]);
b.xt("mj", ben.roomId, GEM_BREAKER, 1, 0, -1);
assert.deepStrictEqual((await b.untilXt("mj")).slice(1), [ben.roomId, ben.id]);
c.xt("mj", cat.roomId, GEM_BREAKER, 1, 0, -1);
for (const client of [b, c]) {
assert.deepStrictEqual((await client.untilXt("mj")).slice(1), [ben.roomId, ben.id, cat.id]);
}
const gemRoom = (await b.untilXt("rj"))[4];
for (const client of [b, c]) {
assert.deepStrictEqual((await client.untilXt("mj")).slice(1), [gemRoom, ben.id, cat.id]);
assert.deepStrictEqual((await client.untilXt("ms")).slice(2, 5), ["2", ben.id, cat.id]);
}
b.xt("mm", gemRoom, GEM_BREAKER, "ready");
c.xt("mm", gemRoom, GEM_BREAKER, "ready");
for (const client of [b, c]) {
const go = await client.untilXt("mm");
assert.deepStrictEqual([go[2], ...go.slice(4)], ["start", "2", ben.id, "0", cat.id, "0"]);
}
b.xt("mm", gemRoom, GEM_BREAKER, "pos", "-45");
assert.deepStrictEqual((await c.nextXt("mm")).slice(2), ["pos", ben.id, "-45"]);
c.xt("mm", gemRoom, GEM_BREAKER, "shoot", "0.5", "-0.8", "210", "40", "3", "1", "300", "0", "5");
assert.deepStrictEqual((await b.nextXt("mm")).slice(2), ["shoot", "0.5", "-0.8", "210", "40", "3", "1", "300", "0", "5"]);
c.xt("mm", gemRoom, GEM_BREAKER, "pos", "<b>");
c.xt("mm", gemRoom, GEM_BREAKER, "playerLost", "12345");
assert.deepStrictEqual((await b.nextXt("mm")).slice(2), ["playerLost", "12345"]); // and not the one with markup
// one leaving: the other is told, as the game expects
c.xt("ml", gemRoom);
assert.deepStrictEqual((await b.untilXt("ml")).slice(1), [gemRoom, cat.id]);
// alone, the start names its one player, whose cannon it is
b.xt("rj", gemRoom, TOWNSHIP, 1, 0, 0);
const back = (await b.untilXt("rj"))[4];
b.xt("mj", back, GEM_BREAKER, 0, 0, -1);
const soloRoom = (await b.untilXt("mj"))[1];
b.xt("mm", soloRoom, GEM_BREAKER, "ready");
assert.deepStrictEqual((await b.untilXt("mm")).slice(4), ["1", ben.id, "0"]);
b.socket.destroy();
c.socket.destroy();
};
+44 -18
View File
@@ -45,8 +45,8 @@ const wall = async body => (await postJson(`${BASE}/wall`, body)).json();
const run = async () => {
const registerJson = body => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({avatarType: 1, agreed: true, ...body})});
for (const username of ["Ann", "Ben", "Cat"]) {
assert.strictEqual((await registerJson({username, password: "Password01"})).status, 200);
for (const username of ["Ann", "Ben", "Cat", "Scout"]) {
assert.strictEqual((await registerJson({username, password: "KettlePass01"})).status, 200);
}
// --- the admin panel's message of the day reaches a player once their first room has loaded
@@ -62,7 +62,7 @@ const run = async () => {
assert.strictEqual((await panel("motd", {text: "Welcome to the test server"}, admin)).status, 200);
assert.strictEqual((await panel("messages", undefined, admin)).data.motd, "Welcome to the test server");
const {client: a, login: annLogin, roomId} = await arrive("Ann", "Password01");
const {client: a, login: annLogin, roomId} = await arrive("Ann", "KettlePass01");
// "ua": the text sits where a room id usually does, then 1 = system message.
assert.deepStrictEqual((await a.untilXt("ua")).slice(1), ["Welcome to the test server", "1"]);
assert.strictEqual((await panel("motd", {text: ""}, admin)).status, 200);
@@ -81,10 +81,34 @@ const run = async () => {
a.xt("pad", roomId, "Ann");
assert.deepStrictEqual((await a.nextXt("pad")).slice(2), ["1", "1", String(annLogin.params.usableAdoptAPetDefs[0].defId), String(annLogin.params.usableAdoptAPetDefs[0].invId)]);
const {client: b, login: benLogin} = await arrive("Ben", "Password01");
const {client: b, login: benLogin} = await arrive("Ben", "KettlePass01");
await a.untilXt("ac");
await a.nextXt("il");
// the shop's name and stalls come from its room file (lib/roominfo.js),
// read the first time anyone goes in; until then the name is made from its
// path. a scout goes in first and comes back until the file has been read,
// so that what follows does not depend on what an earlier run left in the
// cache. (the scout never enters the township, so a and b see nothing.)
const scoutAuth = await (await postJson(`${BASE}/authenticate`, {username: "Scout", password: "KettlePass01"})).json();
const scout = new harness.GameClient(GAME_PORT);
await scout.connect();
assert.strictEqual((await scout.logIn("Scout", scoutAuth.auth_token)).status, "1");
let scoutRoom = 1;
for (let tries = 0; ; tries++) {
scout.xt("rj", scoutRoom, "jamaa_township.clothes_shop#1", 1, 0, 0);
const there = await scout.untilXt("rj");
if (there[14] === "Jam Mart Clothing") {
break;
}
assert.ok(tries < 40, `the shop's room file was never read (still "${there[14]}")`);
await new Promise(resolve => setTimeout(resolve, 500));
scout.xt("rj", there[4], "sarepia.room_main#1", 1, 0, 0);
scoutRoom = (await scout.untilXt("rj"))[4];
}
scout.socket.destroy();
await new Promise(resolve => setTimeout(resolve, 300)); // gone before Ben walks in
// --- a shop's title is its room's name, as the id of the string that says so
b.xt("rj", roomId, "jamaa_township.clothes_shop#1", 1, 0, 0);
const shopRoom = await b.untilXt("rj");
@@ -176,7 +200,7 @@ const run = async () => {
// --- name tags: the colour and badge go with a colour change, reach the room, and stay
a.xt("gl", roomId, 110);
const badges = await a.nextXt("gl");
assert.deepStrictEqual([badges[3], badges[8], badges[9], badges[70]], ["1049", "75", "1", "62"]); // every badge, in id order: the game's 62 and the thirteen the admin gives
assert.deepStrictEqual([badges[3], badges[8], badges[9], badges[70]], ["1049", "76", "1", "62"]); // every badge, in id order: the game's 62 and the fourteen the admin gives (verified among them)
const tag = 6 | 11 << 8; // colour 6, the twelfth badge
a.xt("ap", roomId, 1, 2, 3, tag);
assert.deepStrictEqual((await a.nextXt("ap")).slice(2), ["1"]);
@@ -389,7 +413,10 @@ const run = async () => {
assert.deepStrictEqual([sent[2], sent[7], sent[8], sent[9]], ["2", "0", "1", hat]);
assert.deepStrictEqual((await a.nextXt("es")).slice(2), ["1"]);
const pushed = await b.untilXt("ep");
assert.deepStrictEqual(pushed.slice(3, 10), ["Ann", cards[9], stamps[9], "0", "A hat for you!", "1", shop[9]]);
// a clothing gift goes by the id of its picture (the def's layerDefId,
// lib/ecards.js giftId), not the item's
assert.deepStrictEqual(pushed.slice(3, 9), ["Ann", cards[9], stamps[9], "0", "A hat for you!", "1"]);
assert.ok(Number(pushed[9]) > 0);
b.xt("el", own[4], 0);
const inbox = await b.nextXt("el");
assert.deepStrictEqual([inbox[2], inbox.length], ["1", 3 + 17]);
@@ -408,18 +435,9 @@ const run = async () => {
b.xt("ei", own[4], 0);
await b.nextXt("ei");
// A secret valentine: the receiver is not told who sent it, the server knows.
// secret valentines are off (lib/ecards.js): one asked for is refused
a.xt("es", own[4], "Ben", cards[9], stamps[9], 2, "GUESS WHO", 0, 0, 1);
assert.deepStrictEqual((await a.nextXt("es")).slice(2), ["1"]);
const valentine = await b.nextXt("ep");
assert.deepStrictEqual([valentine[3], valentine[7], valentine[18]], ["", "GUESS WHO", "1"]); // no name; special type 1
b.xt("fr", own[4], "Secret Valentine", 14); // reported under the name the game shows
assert.deepStrictEqual((await b.nextXt("fr")).slice(2), ["1"]);
const aboutValentine = (await panel("reports", undefined, admin)).data.reports;
assert.deepStrictEqual([aboutValentine[0].reporter, aboutValentine[0].target, aboutValentine[0].reason], ["Ben", "Ann", "Inappropriate Jam-A-Gram"]);
await panel("report", {id: aboutValentine[0].id}, admin);
b.xt("ed", own[4], valentine[2]);
await b.nextXt("ed");
assert.deepStrictEqual((await a.nextXt("es")).slice(2), ["0"]);
// --- Jammer Walls: the wallpapers a wall cannot be drawn without, and their buttons
a.xt("gl", own[4], 314);
@@ -461,6 +479,14 @@ const run = async () => {
assert.deepStrictEqual((await b.nextXt("wps")).slice(2), ["1"]);
const mine = await wall({cmd: "GET", t: ownToken});
assert.deepStrictEqual([mine.p.bg, mine.p.tag, mine.p.visits, mine.r.length], ["7", "hello there", 1, 1]); // visits are not the owner's to set
// the photo booth picture: its animal, its pet and what it wears, kept
const photo = {avatar: {id: 4, color1: 1463028479, color2: 603979776, color3: 83885823, eyes: 4, pattern: 25}, bgid: 3,
pet: {ts: 1792133948, lbits: 25, uBits: 0, eBits: 0}, items: [{id: 101, color: 1463028479}, {id: 202, color: 0}]};
b.xt("wps", own[4], JSON.stringify({pb: photo}));
assert.deepStrictEqual((await b.nextXt("wps")).slice(2), ["1"]);
assert.deepStrictEqual((await wall({cmd: "GET", t: ownToken})).p.pb, photo);
b.xt("wps", own[4], JSON.stringify({pb: {avatar: {deep: {deeper: 1}}}})); // but no deeper than that
assert.deepStrictEqual((await b.nextXt("wps")).slice(2), ["0"]);
assert.deepStrictEqual(await wall({cmd: "CLW", t: token[3]}), {s: false}); // only the owner clears a wall
assert.deepStrictEqual(await wall({cmd: "DEL", t: ownToken, x: put.x}), {s: true});
assert.strictEqual((await wall({cmd: "GET", t: ownToken})).r.length, 0);
@@ -488,7 +514,7 @@ const run = async () => {
assert.strictEqual((await panel("overview", undefined, admin)).data.stats.reports, 1);
assert.strictEqual((await panel("report", {id: waiting.reports[0].id}, admin)).status, 200);
assert.strictEqual((await panel("reports", undefined, admin)).data.open, 0);
assert.strictEqual((await panel("reports?handled=1", undefined, admin)).data.reports.length, 2); // this one and the valentine
assert.strictEqual((await panel("reports?handled=1", undefined, admin)).data.reports.length, 1); // this one (secret valentines, reported before, are off)
// --- blocking: no chat from them, out of my party and my den, and out of sight if I say so
a.xt("bb", own[4], "Ben");
+32 -6
View File
@@ -6,6 +6,7 @@
const assert = require("assert");
const {spawn} = require("child_process");
const crypto = require("crypto");
const fs = require("fs");
const net = require("net");
const os = require("os");
@@ -100,6 +101,12 @@ class GameClient {
this.varUpdates.push(fields);
continue;
}
// the chat filter settings ("xfl", after every login), the one-time
// question which filter to use ("xfa", on the first room) and the
// buddy list with when each was last seen ("bl", "xls": at login) come unasked.
if ((fields[0] === "xfl" || fields[0] === "xfa" || fields[0] === "bl" || fields[0] === "xls") && cmd !== fields[0]) {
continue;
}
if (this.unasked(fields)) {
continue;
}
@@ -132,18 +139,31 @@ class GameClient {
}
}
// what the client 1.3.0 sends about its computer (lib/devices.js), made up:
// one computer for each username, unless a test gives its own.
const deviceFor = name => {
const hash = kind => crypto.createHash("sha256").update(`test-device:${kind}:${String(name).toLowerCase()}`).digest("hex");
return {v: 1, ids: {os: hash("os"), install: hash("install"), disk: [hash("disk")], mac: [hash("mac")]}, notes: []};
};
const postJson = (url, body) => fetch(url, {
method: "POST",
headers: {"Content-Type": "application/json", "Origin": "null"},
body: JSON.stringify(body),
body: JSON.stringify(/\/authenticate$/.test(url) && body && body.device === undefined ? {...body, device: deviceFor(body.username || "")} : body),
});
// starts a server on the given ports with an empty database, runs `run`
// against it, and prints `name` passed or the server's output on failure.
const withServer = async (name, httpPort, gamePort, run) => {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "aj-test-"));
// with `dataDir` it uses that database instead, and leaves it there (for a
// test of what is still there after a restart).
const withServer = async (name, httpPort, gamePort, run, {dataDir: keptDir = null} = {}) => {
const dataDir = keptDir || fs.mkdtempSync(path.join(os.tmpdir(), "aj-test-"));
const server = spawn(process.execPath, [path.join(__dirname, "..", "server.js")], {
env: {...process.env, AJ_HTTP_PORT: httpPort, AJ_GAME_PORT: gamePort, AJ_DATA_DIR: dataDir, AJ_QUIET: "1"},
env: {...process.env, AJ_HTTP_PORT: httpPort, AJ_GAME_PORT: gamePort, AJ_DATA_DIR: dataDir, AJ_QUIET: "1",
// everyone arrives in the township, as the tests expect
AJ_SPAWN_ROOMS: process.env.AJ_SPAWN_ROOMS || "jamaa_township.room_main",
// and in the one world
AJ_WORLDS: process.env.AJ_WORLDS || "1"},
stdio: ["ignore", "pipe", "inherit"],
});
let output = "";
@@ -165,9 +185,15 @@ const withServer = async (name, httpPort, gamePort, run) => {
throw err;
}
finally {
// on Windows the database stays locked until the process has gone, so
// wait for it before throwing its files away.
const exited = server.exitCode !== null ? Promise.resolve() : new Promise(resolve => server.once("exit", resolve));
server.kill();
fs.rmSync(dataDir, {recursive: true, force: true});
await exited;
if (!keptDir) {
fs.rmSync(dataDir, {recursive: true, force: true, maxRetries: 10, retryDelay: 200});
}
}
};
module.exports = {GameClient, postJson, withServer};
module.exports = {deviceFor, GameClient, postJson, withServer};
+509
View File
@@ -0,0 +1,509 @@
"use strict";
// end to end: items the staff make while the server runs
// (lib/customitems.js), from the moderator panel and in the game: games
// already playing are sent them, the packs have them, the shop sells them,
// and they are still there after a restart.
const assert = require("assert");
const crypto = require("crypto");
const fs = require("fs");
const os = require("os");
const path = require("path");
const zlib = require("zlib");
const harness = require("./harness.js");
const {decode} = require("../lib/amf3.js");
const cdn = require("../lib/cdn.js");
const HTTP_PORT = 18093;
const GAME_PORT = 19352;
const BASE = `http://127.0.0.1:${HTTP_PORT}`;
const TOWNSHIP = "jamaa_township.room_main#1";
const ODD_CLOTHING_SHOP = 666;
const ODD_DEN_SHOP = 396;
const {postJson} = harness;
// the authenticator app's side of 2FA (lib/totp.js), as in test/staff.js.
const STEP = 30;
const base32Decode = text => {
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
const bits = text.replace(/=+$/, "").toUpperCase().split("").map(c => alphabet.indexOf(c).toString(2).padStart(5, "0")).join("");
const bytes = [];
for (let i = 0; i + 8 <= bits.length; i += 8) {
bytes.push(parseInt(bits.slice(i, i + 8), 2));
}
return Buffer.from(bytes);
};
const codeAt = (secret, step) => {
const counter = Buffer.alloc(8);
counter.writeBigUInt64BE(BigInt(step));
const mac = crypto.createHmac("sha1", base32Decode(secret)).update(counter).digest();
const offset = mac[mac.length - 1] & 0x0F;
return String((mac.readUInt32BE(offset) & 0x7FFFFFFF) % 1000000).padStart(6, "0");
};
const stepNow = () => Math.floor(Date.now() / 1000 / STEP);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const waitForStep = async step => {
while (stepNow() < step) {
await sleep(250);
}
};
const webSession = () => {
let cookie = "";
return async (urlPath, body) => {
const headers = {cookie};
const options = body === undefined ? {headers} : {method: "POST", headers: {...headers, "Content-Type": "application/json"}, body: JSON.stringify(body)};
const res = await fetch(`${BASE}${urlPath}`, options);
const set = res.headers.get("set-cookie");
if (set) {
cookie = set.split(";")[0];
}
return {status: res.status, data: await res.json().catch(() => ({}))};
};
};
const say = (client, roomId, text) =>
client.send(`<msg t='sys'><body action='pubMsg' r='${roomId}'><txt><![CDATA[${text}%0]]></txt></body></msg>`);
// `onLogin(client)` runs before the room is joined, for what the server
// sends with the login (joining skips everything else on the way).
const arrive = async (username, password, totp, onLogin = async () => {}) => {
const res = await postJson(`${BASE}/authenticate`, {username, password, ...(totp ? {totp} : {})});
const auth = await res.json();
assert.strictEqual(res.status, 200, `${username} could not sign in: ${JSON.stringify(auth)}`);
const client = new harness.GameClient(GAME_PORT);
await client.connect();
const login = await client.logIn(username, auth.auth_token);
assert.strictEqual(login.status, "1");
await onLogin(client);
client.xt("rj", 1, TOWNSHIP, 1, 0, 0);
const rj = await client.untilXt("rj");
await client.untilXt("rp");
return {client, roomId: rj[4], token: auth.auth_token};
};
// a pack as the clients get it.
const pack = async id => Object.values(decode(zlib.inflateRawSync(Buffer.from(await (await fetch(`${BASE}/${cdn.hashedPath(`defPacks/${id}`)}`)).arrayBuffer()))));
const strings = async () => decode(zlib.inflateRawSync(Buffer.from(await (await fetch(`${BASE}/${cdn.hashedPath("defPacks/10230")}`)).arrayBuffer())));
const byId = (rows, id) => rows.find(row => String(row.id) === String(id));
// "xdi" [.., .., kind, rows as JSON], the next one of `kind`.
const untilDefs = async (client, kind) => {
for (;;) {
const fields = await client.untilXt("xdi");
if (fields[2] === kind) {
return JSON.parse(fields[3]);
}
}
};
const nextBox = async client => (await client.untilXt("xtl"))[2];
const shopList = async (client, roomId, shop) => {
client.xt("gl", roomId, shop);
return (await client.untilXt("gl")).slice(9);
};
const people = {Dev: "KettlePass21", Hal: "KettlePass22", Pat: "KettlePass23", Lou: "KettlePass24"};
const secret = {};
let usedStep = 0;
let made = {};
const first = async () => {
const registerJson = body => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({avatarType: 1, agreed: true, ...body})});
for (const [username, password] of Object.entries(people)) {
assert.strictEqual((await registerJson({username, password})).status, 200);
}
const admin = webSession();
assert.strictEqual((await admin("/admin/api/setup", {password: "AdminPass99!"})).status, 200);
assert.strictEqual((await admin("/admin/api/login", {password: "AdminPass99!"})).status, 200);
for (const username of ["Dev", "Hal"]) {
const page = webSession();
assert.strictEqual((await page("/account/api/login", {username, password: people[username]})).status, 200);
secret[username] = (await page("/account/api/act", {action: "twoStepStart", current: people[username]})).data.setup.secret;
usedStep = Math.max(usedStep, stepNow());
assert.ok((await page("/account/api/act", {action: "twoStepConfirm", code: codeAt(secret[username], stepNow())})).data.ok);
}
assert.match((await admin("/admin/api/account", {username: "Dev", action: "role", role: "developer"})).data.ok, /developer/);
assert.match((await admin("/admin/api/account", {username: "Hal", action: "role", role: "helper"})).data.ok, /helper/);
// a game started before anything is made
const pat = await arrive("Pat", people.Pat);
// --- the panel: a developer makes items, and sees no players
usedStep++;
await waitForStep(usedStep);
const dev = webSession();
assert.strictEqual((await dev("/mod/api/login", {username: "Dev", password: people.Dev, code: codeAt(secret.Dev, usedStep)})).status, 200);
const me = (await dev("/mod/api/me")).data;
assert.strictEqual(me.role, "developer");
assert.ok(me.permissions.includes("items.create") && !me.permissions.includes("player.view"));
for (const page of ["/mod/api/players", "/mod/api/chat", "/mod/api/reports", "/mod/api/overview"]) {
assert.strictEqual((await dev(page)).status, 403, page);
}
assert.deepStrictEqual((await dev("/mod/api/items")).data.items, []);
// something to make them from: a clothing piece with several colours, and the bean bag chair
const clothing = await pack(1000);
const base = clothing.find(row => row.type === "1" && String(row.colors).split(",").length >= 3);
const looked = (await dev(`/mod/api/items/base?kind=clothing&id=${base.id}`)).data;
assert.strictEqual(looked.art, Number(base.layerDefId));
assert.strictEqual(looked.colors.length, String(base.colors).split(",").length);
const bodyPart = clothing.find(row => row.type === "0");
assert.strictEqual((await dev(`/mod/api/items/base?kind=clothing&id=${bodyPart.id}`)).status, 404);
// bad requests
const make = fields => dev("/mod/api/items", {action: "create", kind: "clothing", base: base.id, name: "Test Crown", cost: 25, ...fields});
assert.match((await make({name: ""})).data.error, /name/);
assert.match((await make({name: "<b>hi</b>"})).data.error, /name/);
assert.match((await make({cost: -1})).data.error, /price/);
assert.match((await make({base: bodyPart.id})).data.error, /body part/);
assert.match((await make({base: 999999})).data.error, /No clothing/);
assert.match((await make({colors: []})).data.error, /colours/);
// made: Pat's game is told at once
const colours = looked.colors.slice(0, 2);
const crown = await make({colors: colours});
assert.match(crown.data.ok, /^Test Crown \(clothing 50000\) made\.$/);
const [row] = await untilDefs(pat.client, "clothing");
assert.deepStrictEqual([row.id, row.name, row.layerDefId, row.layerId, row.colors, row.titleStrId],
["50000", "Test Crown", base.layerDefId, base.layerId, colours.join(","), "9100000"]);
// the packs a new game fetches have it, and its name
const crownRow = byId(await pack(1000), 50000);
assert.strictEqual(crownRow.layerDefId, base.layerDefId);
assert.strictEqual(crownRow.avatarUseFlags, "9007199254740991"); // any animal, like all clothing here
assert.strictEqual((await strings())[9100000], "Test Crown");
// first in the shop of oddities, and Pat can buy it in a colour it has
assert.strictEqual((await shopList(pat.client, pat.roomId, ODD_CLOTHING_SHOP))[0], "50000");
pat.client.xt("ib", pat.roomId, ODD_CLOTHING_SHOP, 1, 50000, 2, 0);
assert.strictEqual((await pat.client.untilXt("ib"))[2], "0"); // a third colour it was not given
pat.client.xt("ib", pat.roomId, ODD_CLOTHING_SHOP, 1, 50000, 1, 0);
const bought = await pat.client.untilXt("il");
assert.ok(bought.includes("50000"));
assert.strictEqual((await pat.client.untilXt("ib"))[2], "1");
// a den item, from the bean bag chair
const chair = await dev("/mod/api/items", {action: "create", kind: "den", base: 1, name: "Test Chair", cost: 10});
assert.match(chair.data.ok, /^Test Chair \(den item 50000\) made\.$/);
const [chairRow] = await untilDefs(pat.client, "den");
assert.deepStrictEqual([chairRow.id, chairRow.abbrName, chairRow.name, chairRow.nameStrId], ["50000", "BeanBagChair", "Test Chair", "9200000"]);
assert.strictEqual((await shopList(pat.client, pat.roomId, ODD_DEN_SHOP))[0], "50000");
assert.strictEqual(byId(await pack(1030), 50000).abbrName, "BeanBagChair");
// the item finder has them
const found = await (await fetch(`${BASE}/api/search?kind=all&q=50000`)).json();
assert.deepStrictEqual(found.results.filter(entry => entry.id === 50000).map(entry => `${entry.kind} ${entry.name}`).sort(), ["clothing Test Crown", "den Test Chair"]);
// changed: renamed and taken off sale, and Pat is told the new name
assert.match((await dev("/mod/api/items", {action: "update", kind: "clothing", id: 50000, name: "Gold Crown", inShop: false})).data.ok, /Gold Crown .* changed/);
assert.strictEqual((await untilDefs(pat.client, "clothing"))[0].name, "Gold Crown");
assert.ok(!(await shopList(pat.client, pat.roomId, ODD_CLOTHING_SHOP)).includes("50000"));
assert.strictEqual((await strings())[9100000], "Gold Crown");
// --- in the game: !item, for whoever may make items
usedStep++;
await waitForStep(usedStep);
// a game logging in is sent every item made so far
let atLogin = null;
const devGame = await arrive("Dev", people.Dev, codeAt(secret.Dev, usedStep), async client => {
atLogin = await untilDefs(client, "clothing");
});
assert.deepStrictEqual(atLogin.map(entry => entry.name), ["Gold Crown"]);
say(devGame.client, devGame.roomId, `!item clothing ${base.id} Quick Hat`);
assert.strictEqual(await nextBox(devGame.client), "Made Quick Hat, clothing 50001. It is in the item finder now.");
assert.strictEqual((await untilDefs(pat.client, "clothing"))[0].name, "Quick Hat");
say(devGame.client, devGame.roomId, "!item list");
assert.match(await nextBox(devGame.client), /^Latest items made: 50001 Quick Hat \(clothing\); 50000 Test Chair \(den\); 50000 Gold Crown \(clothing, off sale\)$/);
say(devGame.client, devGame.roomId, "!item hat 12 x");
assert.match(await nextBox(devGame.client), /^Use: !item/);
// a helper may not: it is chat (another account: the same step will do)
const hal = await arrive("Hal", people.Hal, codeAt(secret.Hal, usedStep));
say(hal.client, hal.roomId, `!item clothing ${base.id} Nope`);
for (;;) {
const line = await pat.client.untilXt("uc");
if (line[3] === `!item clothing ${base.id} Nope`) {
break;
}
}
assert.strictEqual((await dev("/mod/api/items")).data.items.length, 3);
// --- locked out of the item finder (lib/itemcontrol.js): players do not
// find it or take it; the owner here, and staff who may lock, still do
const searchAs = async (q, who) => (await (await fetch(`${BASE}/api/search?kind=clothing&q=${q}${who ? `&username=${who.name}&token=${who.token}` : ""}`)).json()).results;
// (as the item finder page and the client send it: no Origin of another site)
const giveAs = (body, token) => fetch(`${BASE}/api/give`, {method: "POST", headers: {"Content-Type": "application/json"},
body: JSON.stringify({...body, ...(token ? {token} : {})})});
const patAs = {name: "Pat", token: pat.token};
assert.ok((await searchAs(50001, patAs)).some(entry => entry.id === 50001));
assert.match((await dev("/mod/api/items", {action: "lock", kind: "clothing", id: 50001})).data.ok, /^Quick Hat \(clothing 50001\) is locked out of the item finder\.$/);
assert.match((await dev("/mod/api/items", {action: "lock", kind: "clothing", id: 50001})).data.error, /already locked/);
assert.ok(!(await searchAs(50001, patAs)).some(entry => entry.id === 50001));
const refused = await giveAs({username: "Pat", kind: "clothing", id: 50001}, pat.token);
assert.deepStrictEqual([refused.status, (await refused.json()).error], [403, "That item is locked out of the item finder."]);
assert.deepStrictEqual((await searchAs(50001)).filter(entry => entry.id === 50001).map(entry => [entry.name, entry.locked]), [["Quick Hat (locked)", true]]);
assert.strictEqual((await searchAs(50001, {name: "Dev", token: devGame.token})).find(entry => entry.id === 50001).name, "Quick Hat (locked)");
assert.deepStrictEqual((await dev("/mod/api/items")).data.locked, [{kind: "clothing", id: 50001, name: "Quick Hat"}]);
// the dashboards' lock finds it by name, marked locked, with the count
const findLock = (await dev("/mod/api/items/find?q=quick%20hat&kind=clothing")).data;
assert.deepStrictEqual([findLock.lockedCount, findLock.results.find(entry => entry.id === 50001)],
[1, {kind: "clothing", id: 50001, cost: findLock.results.find(entry => entry.id === 50001).cost, name: "Quick Hat", locked: true, custom: true}]);
say(devGame.client, devGame.roomId, "!locked");
assert.strictEqual(await nextBox(devGame.client), "Locked out of the item finder: clothing 50001 Quick Hat");
// --- taken from a player: every one of it, their game told
assert.strictEqual((await giveAs({username: "Pat", kind: "clothing", id: 50001, colorIndex: 0})).status, 200); // the owner, here
assert.strictEqual((await giveAs({username: "Pat", kind: "clothing", id: 50001, colorIndex: 0})).status, 200);
say(devGame.client, devGame.roomId, "!take Pat clothing 50001");
assert.strictEqual(await nextBox(devGame.client), "Took 2 of Quick Hat (clothing 50001) from Pat.");
for (;;) {
const changed = await pat.client.untilXt("il");
if (changed[2] === "2" && changed[8] === "2") { // two removed
break;
}
}
say(devGame.client, devGame.roomId, "!take Pat clothing 50001");
assert.strictEqual(await nextBox(devGame.client), "Pat has no Quick Hat (clothing 50001).");
assert.strictEqual((await giveAs({username: "Pat", kind: "den", id: 50000})).status, 200);
assert.match((await dev("/mod/api/items", {action: "take", username: "Pat", kind: "den", id: 50000})).data.ok, /^Took 1 of Test Chair \(den item 50000\) from Pat\.$/);
assert.match((await dev("/mod/api/items", {action: "unlock", kind: "clothing", id: 50001})).data.ok, /back in the item finder/);
assert.ok((await searchAs(50001, patAs)).some(entry => entry.id === 50001));
// --- a custom item deleted: out of the game and every inventory
say(devGame.client, devGame.roomId, `!item clothing ${base.id} Doomed Hat`);
assert.strictEqual(await nextBox(devGame.client), "Made Doomed Hat, clothing 50002. It is in the item finder now.");
assert.strictEqual((await giveAs({username: "Pat", kind: "clothing", id: 50002, colorIndex: 0})).status, 200);
assert.match((await dev("/mod/api/items", {action: "delete", kind: "clothing", id: 50002})).data.ok, /^Deleted Doomed Hat \(clothing 50002\), and took 1 from players\.$/);
assert.ok(!(await searchAs(50002)).some(entry => entry.id === 50002));
assert.strictEqual((await giveAs({username: "Pat", kind: "clothing", id: 50002, colorIndex: 0})).status, 400);
assert.ok(!byId(await pack(1000), 50002));
assert.strictEqual((await dev("/mod/api/items")).data.items.length, 3);
// --- a player's own items (lib/playeritems.js, the client's Item Maker):
// free, given to them, found by them only, at most five a day
const maker = async (...params) => {
pat.client.xt("xcm", pat.roomId, ...params);
const answer = await pat.client.untilXt("xcm");
return {ok: answer[2] === "1", said: answer[3], today: Number(answer[4]), inAll: Number(answer[5]), mine: JSON.parse(answer[6])};
};
assert.deepStrictEqual(await maker("info"), {ok: true, said: "", today: 5, inAll: 20, mine: []});
const own = await maker("make", "clothing", base.id, "Pat Hat");
assert.deepStrictEqual([own.ok, own.said, own.today, own.inAll], [true, "Made Pat Hat. It is in your clothing now.", 4, 19]);
const patHat = own.mine[0];
assert.deepStrictEqual([patHat.kind, patHat.name, patHat.base], ["clothing", "Pat Hat", Number(base.id)]);
assert.ok((await searchAs(patHat.id, patAs)).some(entry => entry.id === patHat.id));
const halAs = {name: "Hal", token: hal.token};
assert.ok(!(await searchAs(patHat.id, halAs)).some(entry => entry.id === patHat.id));
assert.strictEqual((await giveAs({username: "Hal", kind: "clothing", id: patHat.id, colorIndex: 0}, hal.token)).status, 403);
assert.ok((await searchAs(patHat.id, {name: "Dev", token: devGame.token})).some(entry => entry.id === patHat.id)); // staff who make items
assert.match((await maker("make", "clothing", base.id, "Admin Hat")).said, /not allowed/);
assert.match((await maker("make", "clothing", bodyPart.id, "Body")).said, /cannot be made into one of your own/);
// the base list offers only what can be copied
assert.ok(!(await (await fetch(`${BASE}/api/search?base=1&kind=clothing&q=${bodyPart.id}`)).json()).results.some(entry => entry.id === bodyPart.id));
for (let count = 2; count <= 5; count++) {
assert.ok((await maker("make", "den", 1, `Pat Chair ${count}`)).ok);
}
const full = await maker("make", "den", 1, "One Too Many");
assert.deepStrictEqual([full.ok, full.today], [false, 0]);
assert.match(full.said, /made 5 items today/);
// --- its own picture (lib/itemart.js): checked and cleaned, served, and
// every game told; only by its maker or staff who make items
const crc32 = buf => {
let c = ~0;
for (const byte of buf) {
c ^= byte;
for (let k = 0; k < 8; k++) {
c = (c >>> 1) ^ (0xEDB88320 & -(c & 1));
}
}
return (~c) >>> 0;
};
const chunk = (type, data) => {
const head = Buffer.alloc(8);
head.writeUInt32BE(data.length);
head.write(type, 4, "latin1");
const crc = Buffer.alloc(4);
crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data])));
return Buffer.concat([head, data, crc]);
};
const png = (side, extra = []) => {
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(side, 0);
ihdr.writeUInt32BE(side, 4);
ihdr[8] = 8;
ihdr[9] = 2;
const raw = Buffer.alloc((side * 3 + 1) * side, 0x7F);
return Buffer.concat([Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]), chunk("IHDR", ihdr), ...extra,
chunk("IDAT", zlib.deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);
};
const upload = (who, entry, body, extra = "") => fetch(`${BASE}/api/itemart?kind=${entry.kind}&id=${entry.id}&token=${who.token}${extra}`,
{method: "POST", headers: {"Content-Type": "application/octet-stream"}, body}).then(response => response.json());
const hatEntry = (await maker("info")).mine.find(entry => entry.name === "Pat Hat");
// by default a player's picture waits for a moderator, even with items
// let in at once: nobody else is shown it, not even by its address
assert.match((await upload(pat, hatEntry, png(30))).ok, /waiting for a moderator/);
assert.strictEqual((await maker("info")).mine.find(entry => entry.kind === hatEntry.kind && entry.id === hatEntry.id).art, "");
assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png`)).status, 404);
const pendingUrl = (await admin("/admin/api/review")).data.waiting.find(entry => entry.id === hatEntry.id).artUrl;
assert.match(pendingUrl, /^\/admin\/api\/itemart\?kind=clothing&id=\d+&v=p[0-9a-f]{12}$/);
assert.strictEqual((await admin(pendingUrl)).status, 200);
assert.strictEqual((await fetch(`${BASE}${pendingUrl}`)).status, 404); // signed in to nothing
assert.match((await admin("/admin/api/review", {kind: "clothing", id: hatEntry.id, approve: true})).data.ok, /picture is shown now/);
assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png`)).status, 200);
while (!(await untilDefs(pat.client, "clothing")).some(row => row.art)) {
// every game is told of it waiting (no picture), then of it shown
}
// the rest of these, shown at once (the admin's switch)
assert.strictEqual((await admin("/admin/api/item-switches", {artApproval: false})).status, 200);
assert.strictEqual((await admin("/admin/api/review")).data.artApproval, false);
assert.match((await upload(pat, hatEntry, png(32, [chunk("tEXt", Buffer.from("Author\x00Pat at home"))]))).ok, /new picture/);
const told = (await untilDefs(pat.client, "clothing")).map(row => [row.id, row.art]);
const sameItem = entry => entry.kind === hatEntry.kind && entry.id === hatEntry.id;
const withArt = (await maker("info")).mine.find(sameItem);
assert.match(withArt.art, /^p[0-9a-f]{12}$/);
assert.deepStrictEqual(told, [[String(hatEntry.id), withArt.art]]);
const served = await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png?v=${withArt.art}`);
assert.deepStrictEqual([served.status, served.headers.get("content-type"), served.headers.get("x-content-type-options")], [200, "image/png", "nosniff"]);
const bytes = Buffer.from(await served.arrayBuffer());
assert.ok(!bytes.includes(Buffer.from("tEXt")) && !bytes.includes(Buffer.from("Pat at home")), "the text chunk was left in");
assert.match((await upload(pat, hatEntry, Buffer.from("<html><script>alert(1)</script></html>"))).error, /not a PNG, JPEG, GIF or BMP/);
// a GIF is kept a GIF (without its comment); a BMP is made a PNG
const gif = Buffer.concat([Buffer.from("GIF89a"), Buffer.from([16, 0, 16, 0, 0x80, 0, 0]), Buffer.alloc(6, 0x55),
Buffer.from([0x21, 0xFE, 4]), Buffer.from("Bob!"), Buffer.from([0]), Buffer.from([0x2C, 0, 0, 0, 0, 16, 0, 16, 0, 0, 2, 3, 1, 2, 3, 0, 0x3B])]);
assert.match((await upload(pat, hatEntry, gif)).ok, /new picture/);
const gifArt = (await maker("info")).mine.find(entry => entry.kind === hatEntry.kind && entry.id === hatEntry.id).art;
const gifServed = await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png?v=${gifArt}`);
assert.strictEqual(gifServed.headers.get("content-type"), "image/gif");
assert.ok(!Buffer.from(await gifServed.arrayBuffer()).includes(Buffer.from("Bob!")), "the GIF comment was left in");
const bmp = Buffer.alloc(54 + 32 * 3 * 32);
bmp.write("BM");
bmp.writeUInt32LE(bmp.length, 2);
bmp.writeUInt32LE(54, 10);
bmp.writeUInt32LE(40, 14);
bmp.writeInt32LE(32, 18);
bmp.writeInt32LE(32, 22);
bmp.writeUInt16LE(1, 26);
bmp.writeUInt16LE(24, 28);
assert.match((await upload(pat, hatEntry, bmp)).ok, /new picture/);
const bmpArt = (await maker("info")).mine.find(entry => entry.kind === hatEntry.kind && entry.id === hatEntry.id).art;
assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png?v=${bmpArt}`)).headers.get("content-type"), "image/png");
assert.match((await upload(pat, hatEntry, png(600))).error, /512 pixels/);
assert.match((await upload(hal, hatEntry, png(16))).error, /not one of your items/);
assert.match((await fetch(`${BASE}/api/itemart?kind=clothing&id=${hatEntry.id}`, {method: "POST", body: png(16)}).then(r => r.json())).error, /Sign in/);
// a JPEG keeps its picture and loses its EXIF (where a photo was taken)
const segment = (marker, data) => Buffer.concat([Buffer.from([0xFF, marker, (data.length + 2) >> 8, (data.length + 2) & 0xFF]), data]);
const jpeg = Buffer.concat([Buffer.from([0xFF, 0xD8]), segment(0xE0, Buffer.from("JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00", "latin1")),
segment(0xE1, Buffer.from("Exif\x00\x00GPS 51.5N 0.12W", "latin1")), segment(0xC0, Buffer.from([8, 0, 20, 0, 30, 1, 1, 0x11, 0])),
segment(0xDA, Buffer.from([1, 1, 0, 0, 0x3F, 0])), Buffer.from([0x12, 0x34, 0xFF, 0xD9])]);
assert.match((await upload(pat, hatEntry, jpeg)).ok, /new picture/);
const jpegArt = (await maker("info")).mine.find(sameItem).art;
const jpegBytes = Buffer.from(await (await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png?v=${jpegArt}`)).arrayBuffer());
assert.ok(jpegBytes.includes(Buffer.from("JFIF")) && !jpegBytes.includes(Buffer.from("GPS")), "the EXIF was left in");
assert.match((await upload(pat, hatEntry, Buffer.alloc(0), "&remove=1")).ok, /taken away/);
assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png`)).status, 404);
assert.match((await upload(pat, hatEntry, png(24))).ok, /new picture/); // deleted with the item, below
assert.match((await maker("rename", "clothing", hatEntry.id, "Party Hat")).said, /^Renamed it Party Hat\.$/);
// how it is worn: a sticker by default, a texture when its maker says so, every game told
pat.client.xt("xcm", pat.roomId, "look", "clothing", hatEntry.id, "texture");
assert.strictEqual((await untilDefs(pat.client, "clothing"))[0].artMode, "texture");
assert.strictEqual((await pat.client.untilXt("xcm"))[2], "1"); // its own answer, after every game was told
const wornAs = await maker("info");
assert.strictEqual(wornAs.mine.find(entry => entry.kind === "clothing" && entry.id === hatEntry.id).artMode, "texture");
assert.match((await maker("look", "clothing", hatEntry.id, "melted")).said, /sticker or texture/);
// deleting: their own only, and gone from everyone
assert.match((await maker("delete", "clothing", 50001)).said, /not one of your items/);
for (const entry of full.mine) {
assert.match((await maker("delete", entry.kind, entry.id)).said, /^Deleted /);
}
assert.deepStrictEqual((await maker("info")).mine, []);
assert.strictEqual((await fetch(`${BASE}/itemart/clothing/${hatEntry.id}.png`)).status, 404);
assert.strictEqual((await dev("/mod/api/items")).data.items.length, 3);
// --- the admin's switches: what players make waits for a moderator first,
// out of the game till then; or the Item Maker is off
assert.strictEqual((await admin("/admin/api/item-switches", {enabled: true, approval: true})).status, 200);
const asked = await maker("make", "clothing", base.id, "Waiting Hat");
assert.match(asked.said, /waiting for a moderator/);
const waitingHat = asked.mine.find(entry => entry.name === "Waiting Hat");
assert.strictEqual(waitingHat.waiting, "item");
assert.ok(!(await searchAs(waitingHat.id)).some(entry => entry.id === waitingHat.id)); // not in the game yet
const queue = (await admin("/admin/api/review")).data;
assert.deepStrictEqual([queue.enabled, queue.approval, queue.waiting.map(entry => `${entry.name} ${entry.waiting} ${entry.maker}`)],
[true, true, ["Waiting Hat item Pat"]]);
assert.strictEqual((await dev("/mod/api/review")).status, 403); // a developer approves nothing
assert.match((await admin("/admin/api/review", {kind: "clothing", id: waitingHat.id, approve: true})).data.ok, /in the game, and Pat has one/);
for (;;) {
const changed = await pat.client.untilXt("il");
if (changed[2] === "2" && changed[10] === String(waitingHat.id)) { // given to Pat
break;
}
}
assert.ok((await searchAs(waitingHat.id, patAs)).some(entry => entry.id === waitingHat.id));
// a new picture waits too, and is not shown till then
assert.match((await upload(pat, waitingHat, png(20))).ok, /waiting for a moderator/);
assert.strictEqual((await maker("info")).mine.find(entry => entry.id === waitingHat.id && entry.kind === "clothing").waiting, "picture");
assert.match((await admin("/admin/api/review", {kind: "clothing", id: waitingHat.id, approve: false})).data.ok,
/picture was turned away\. Pat has had 1 of 3 pictures turned away\.$/);
assert.strictEqual((await admin("/admin/api/review")).data.waiting.length, 0);
// the same picture cannot come back; after three turned away, uploads stop
assert.match((await upload(pat, waitingHat, png(20))).error, /turned that picture away before/);
assert.match((await upload(pat, waitingHat, png(21))).ok, /waiting/);
assert.match((await admin("/admin/api/review", {kind: "clothing", id: waitingHat.id, approve: false})).data.ok, /2 of 3/);
assert.match((await upload(pat, waitingHat, png(22))).ok, /waiting/);
assert.match((await admin("/admin/api/review", {action: "takePicture", kind: "clothing", id: waitingHat.id})).data.ok,
/taken away\. That is 3 for Pat: their picture uploads are stopped\.$/);
assert.match((await upload(pat, waitingHat, png(23))).error, /turned off picture uploads/);
assert.deepStrictEqual((await admin("/admin/api/review")).data.stopped, ["Pat"]);
assert.match((await admin("/admin/api/review", {action: "uploads", username: "Pat", blocked: false})).data.ok, /Pat can upload pictures again/);
assert.match((await upload(pat, waitingHat, png(23))).ok, /waiting/);
assert.match((await admin("/admin/api/review", {kind: "clothing", id: waitingHat.id, approve: true})).data.ok, /shown now/);
// off: nothing is made
assert.strictEqual((await admin("/admin/api/item-switches", {enabled: false, approval: false})).status, 200);
assert.match((await maker("make", "clothing", base.id, "No Hat")).said, /turned off/);
assert.strictEqual((await admin("/admin/api/item-switches", {enabled: true})).status, 200);
assert.match((await maker("delete", "clothing", waitingHat.id)).said, /^Deleted /);
// written down under the maker's name
const log = (await admin("/admin/api/moderators")).data.log.map(entry => `${entry.by} ${entry.action} ${entry.detail}`);
for (const line of ["Dev item made clothing 50000 Test Crown", "Dev item made den 50000 Test Chair", "Dev item changed clothing 50000 Gold Crown",
"Dev item made (in game) clothing 50001 Quick Hat", "Dev item locked clothing 50001", "Dev item taken (in game) clothing 50001 x2",
"Dev item taken den 50000 x1", "Dev item deleted clothing 50002"]) {
assert.ok(log.includes(line), `missing from the log: ${line}\n${log.join("\n")}`);
}
made = {base};
for (const {client} of [pat, devGame, hal]) {
client.socket.destroy();
}
};
// the same database, a new server: everything is still there.
const second = async () => {
const atLogin = {};
const lou = await arrive("Lou", people.Lou, null, async client => {
atLogin.clothing = await untilDefs(client, "clothing");
atLogin.den = await untilDefs(client, "den");
});
assert.deepStrictEqual(atLogin.clothing.map(entry => `${entry.id} ${entry.name}`), ["50000 Gold Crown", "50001 Quick Hat"]);
assert.deepStrictEqual(atLogin.den.map(entry => entry.name), ["Test Chair"]);
assert.strictEqual(byId(await pack(1000), 50001).layerDefId, made.base.layerDefId);
assert.strictEqual((await strings())[9100001], "Quick Hat");
const shop = await shopList(lou.client, lou.roomId, ODD_CLOTHING_SHOP);
assert.ok(shop.includes("50001") && !shop.includes("50000"));
lou.client.socket.destroy();
};
(async () => {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "aj-test-"));
try {
await harness.withServer("items test", HTTP_PORT, GAME_PORT, first, {dataDir});
await harness.withServer("items test (after a restart)", HTTP_PORT, GAME_PORT, second, {dataDir});
}
finally {
fs.rmSync(dataDir, {recursive: true, force: true, maxRetries: 10, retryDelay: 200});
}
})().catch(err => {
console.error(err);
process.exit(1);
});
+4 -4
View File
@@ -21,7 +21,7 @@ const told = async client => (await client.untilXt("xtl"))[2];
// logs in and asks for the township, as the game always does first.
// returns where the server put them.
const arrive = async username => {
const auth = await (await postJson(`${BASE}/authenticate`, {username, password: "Password01"})).json();
const auth = await (await postJson(`${BASE}/authenticate`, {username, password: "KettlePass01"})).json();
const client = new harness.GameClient(GAME_PORT);
await client.connect();
const login = await client.logIn(username, auth.auth_token);
@@ -36,7 +36,7 @@ const arrive = async username => {
const run = async () => {
for (const username of ["Ann", "Ben"]) {
const response = await fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"},
body: JSON.stringify({username, password: "Password01", avatarType: 1, agreed: true})});
body: JSON.stringify({username, password: "KettlePass01", avatarType: 1, agreed: true})});
assert.strictEqual(response.status, 200);
}
let {client: a, login, roomId, room} = await arrive("Ann");
@@ -149,7 +149,7 @@ const run = async () => {
assert.strictEqual(await owned(), before + 3);
say(a, roomId, "!help"); // gone: the list is at /commands
assert.strictEqual((await a.untilXt("uc"))[3], "!help");
assert.match(await (await fetch(`${BASE}/commands`)).text(), /!outfit save NAME/);
assert.match(await (await fetch(`${BASE}/commands`)).text(), /!outfit save <i>NAME<\/i>/); // the page sets what to type in italics
// --- den undo, mail, music
say(a, roomId, "!den undo");
@@ -190,7 +190,7 @@ const run = async () => {
await new Promise(resolve => setTimeout(resolve, 200));
// --- "start in your own den" (asked for at sign-in): the game asks for the township and is put in the den
const denAuth = await (await postJson(`${BASE}/authenticate`, {username: "Ann", password: "Password01", login_choices: {startInDen: true}})).json();
const denAuth = await (await postJson(`${BASE}/authenticate`, {username: "Ann", password: "KettlePass01", login_choices: {startInDen: true}})).json();
const home = new harness.GameClient(GAME_PORT);
await home.connect();
await home.logIn("Ann", denAuth.auth_token);
+6 -6
View File
@@ -38,9 +38,9 @@ const byId = (rows, id) => rows.find(row => String(row.id) === String(id));
const run = async () => {
const registerJson = body => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({avatarType: 1, agreed: true, ...body})});
for (const username of ["Ann", "Ben"]) {
assert.strictEqual((await registerJson({username, password: "Password01"})).status, 200);
assert.strictEqual((await registerJson({username, password: "KettlePass01"})).status, 200);
}
const {client: a, roomId} = await arrive("Ann", "Password01");
const {client: a, roomId} = await arrive("Ann", "KettlePass01");
// --- Epic Dens: twenty names; asking for the den of one leads into its room
a.xt("dh", roomId);
@@ -147,7 +147,7 @@ const run = async () => {
a.xt("di", den);
assert.deepStrictEqual((await a.nextXt("di")).slice(13, 24), ["111", "222", "0", "333", "0", "0", "0", "0", "0", hat, "0"]);
// A visitor is told what the hat is: its def and colour, then its id.
const {client: b, roomId: benRoom} = await arrive("Ben", "Password01");
const {client: b, roomId: benRoom} = await arrive("Ben", "KettlePass01");
b.xt("dj", benRoom, "denAnn", 1, -1);
const seen = await b.untilXt("ds");
assert.deepStrictEqual(seen.slice(5), [mannequin, "3433", "1", "300", "400", "0", "0", "", "", "-1", "",
@@ -177,8 +177,8 @@ const run = async () => {
assert.strictEqual((await a.nextXt("di"))[22], "0");
// --- a player who is not in the game: their card still shows who they are
assert.strictEqual((await registerJson({username: "Cat", password: "Password01"})).status, 200);
const {client: c, roomId: catRoom} = await arrive("Cat", "Password01");
assert.strictEqual((await registerJson({username: "Cat", password: "KettlePass01"})).status, 200);
const {client: c, roomId: catRoom} = await arrive("Cat", "KettlePass01");
c.xt("pc", catRoom, 312, 1, 0, 0, 15386, 15428, 0); // a pet, so there is one to list
await c.untilXt("pc");
c.socket.destroy();
@@ -204,7 +204,7 @@ const run = async () => {
const stamps = (await b.nextXt("gl")).slice(9);
b.xt("es", benRoom, "Cat", cards[0], stamps[0], 0, "see you soon", 0, 0, 0);
assert.strictEqual((await b.untilXt("es"))[2], "1");
const {client: c2, login: catLogin, roomId: catRoom2} = await arrive("Cat", "Password01");
const {client: c2, login: catLogin, roomId: catRoom2} = await arrive("Cat", "KettlePass01");
assert.strictEqual(catLogin.params.numUnreadECards, 1);
assert.deepStrictEqual((await c2.untilXt("ba")).slice(2), ["0", "Ben", "1"]); // asked, now that Cat is here
c2.xt("bc", catRoom2, "Ben", 1);
+36 -29
View File
@@ -28,29 +28,29 @@ const run = async () => {
// --- registration: the web form's API, and no accounts made by logging in
assert.match(await (await fetch(`${BASE}/register`)).text(), /Create an account/);
const registerJson = body => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({avatarType: 1, agreed: true, ...body})});
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Alice", password: "Password01"})).status, 401);
assert.strictEqual((await registerJson({username: "Alice", password: "Password01"})).status, 200);
assert.deepStrictEqual(await (await registerJson({username: "alice", password: "Password01"})).json(), {error: "username_taken"});
assert.deepStrictEqual(await (await registerJson({username: "a!", password: "Password01"})).json(), {error: "invalid_username"});
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Alice", password: "KettlePass01"})).status, 401);
assert.strictEqual((await registerJson({username: "Alice", password: "KettlePass01"})).status, 200);
assert.deepStrictEqual(await (await registerJson({username: "alice", password: "KettlePass01"})).json(), {error: "username_taken"});
assert.deepStrictEqual(await (await registerJson({username: "a!", password: "KettlePass01"})).json(), {error: "invalid_username"});
assert.deepStrictEqual(await (await registerJson({username: "Shorty", password: "pw"})).json(), {error: "invalid_password"});
// no default animal: whoever signs up picks one of the nine on the page.
assert.deepStrictEqual(await (await registerJson({username: "Noanimal", password: "Password01", avatarType: undefined})).json(), {error: "choose_animal"});
assert.deepStrictEqual(await (await registerJson({username: "Noanimal", password: "Password01", avatarType: 2})).json(), {error: "choose_animal"});
assert.deepStrictEqual(await (await registerJson({username: "Noanimal", password: "KettlePass01", avatarType: undefined})).json(), {error: "choose_animal"});
assert.deepStrictEqual(await (await registerJson({username: "Noanimal", password: "KettlePass01", avatarType: 2})).json(), {error: "choose_animal"});
assert.match(await (await fetch(`${BASE}/register`)).text(), /Choose an animal/);
assert.strictEqual((await fetch(`${BASE}/signup/thumb_wolf.svg`)).headers.get("content-type"), "image/svg+xml");
assert.strictEqual((await fetch(`${BASE}/signup/..%2Faccount.html`)).status, 404);
for (const [username, password] of [["Bob", "Password02"], ["Carol", "Password03"], ["foo", "Password04"]]) {
for (const [username, password] of [["Bob", "KettlePass02"], ["Carol", "KettlePass03"], ["foo", "KettlePass04"]]) {
assert.strictEqual((await registerJson({username, password})).status, 200);
}
let res = await postJson(`${BASE}/authenticate`, {username: "Alice", password: "Password01", domain: "flash", df: "x"});
let res = await postJson(`${BASE}/authenticate`, {username: "Alice", password: "KettlePass01", domain: "flash", df: "x"});
assert.strictEqual(res.status, 200);
assert.strictEqual(res.headers.get("access-control-allow-origin"), "null");
const alice = await res.json();
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "alice", password: "wrong"})).status, 401);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "constructor", password: "Password01"})).status, 401);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "constructor", password: "KettlePass01"})).status, 401);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {refresh_token: alice.refresh_token})).status, 200);
const bob = await (await postJson(`${BASE}/authenticate`, {username: "Bob", password: "Password02"})).json();
const bob = await (await postJson(`${BASE}/authenticate`, {username: "Bob", password: "KettlePass02"})).json();
res = await fetch(`${BASE}/player?domain=flash&client_version=1830`, {headers: {Authorization: `Bearer ${alice.auth_token}`}});
assert.strictEqual((await res.json()).screen_name, "Alice");
@@ -83,11 +83,11 @@ const run = async () => {
assert.deepStrictEqual((await guest.nextXt("la")).slice(2), ["1"]);
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv("aes-256-cbc", crypto.createHash("sha256").update(guestKey).digest(), iv);
const encrypted = Buffer.concat([iv, cipher.update("DavePass01"), cipher.final()]).toString("base64");
const encrypted = Buffer.concat([iv, cipher.update("TulipKettle01"), cipher.final()]).toString("base64");
guest.xt("lc", 1, "Dave", encrypted, "2000-01-01", 0, "", 15136, 15224, 15299, 4, 0, "US", 1830);
assert.deepStrictEqual((await guest.nextXt("lc")).slice(2, 3), ["1"]);
guest.socket.destroy();
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Dave", password: "DavePass01"})).status, 200);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Dave", password: "TulipKettle01"})).status, 200);
// --- first player: login and world entry
const a = new GameClient();
@@ -158,6 +158,10 @@ const run = async () => {
assert.deepStrictEqual((await b.nextXt("uc")).slice(1), [roomId, String(bobId), "hi & bye", "0"]);
b.send(`<msg t='sys'><body action='pubMsg' r='${roomId}'><txt><![CDATA[7%2]]></txt></body></msg>`); // emote: not echoed
assert.deepStrictEqual((await a.nextXt("uc")).slice(3), ["7", "2"]);
// Actions are sent to every other player in the room. The sender has
// already applied the action locally, so it is not echoed back to them.
b.send(`<msg t='sys'><body action='pubMsg' r='${roomId}'><txt><![CDATA[:sitS:%3%m1]]></txt></body></msg>`);
assert.deepStrictEqual((await a.nextXt("uc")).slice(3), [":sitS:", "3", "m1"]);
// --- player cards
a.xt("ag", roomId, "bob", 1);
@@ -234,7 +238,7 @@ const run = async () => {
assert.deepStrictEqual((await a.nextXt("ds")).slice(2), ["0", "0", "1"]);
// --- shops, clothing, animals and pets (Carol watches from the same den)
const carol = await (await postJson(`${BASE}/authenticate`, {username: "Carol", password: "Password03"})).json();
const carol = await (await postJson(`${BASE}/authenticate`, {username: "Carol", password: "KettlePass03"})).json();
const c = new GameClient();
await c.connect();
await c.logIn("Carol", carol.auth_token);
@@ -383,17 +387,18 @@ const run = async () => {
const moved = await c.nextXt("rp");
assert.deepStrictEqual([moved[4], moved[5]], ["2", newDenDef]); // room type 2 = den, then the den type
assert.deepStrictEqual((await c.nextXt("ds")).slice(2, 3), ["0"]); // the furniture stayed in the first den
assert.deepStrictEqual((await a.nextXt("ds")).slice(2, 3), ["0"]);
// the owner is also sent the den's items ("di") on a switch
assert.deepStrictEqual((await a.untilXt("ds")).slice(2, 3), ["0"]);
a.xt("dc", denId, 0);
await a.nextXt("dc");
await c.nextXt("rp");
assert.deepStrictEqual((await c.nextXt("ds")).slice(2, 3), ["1"]);
await a.nextXt("ds");
await a.untilXt("ds");
a.xt("dp", denId, 0, 0);
{
const stranger = new GameClient();
await stranger.connect();
await stranger.logIn("Dave", (await (await postJson(`${BASE}/authenticate`, {username: "Dave", password: "DavePass01"})).json()).auth_token);
await stranger.logIn("Dave", (await (await postJson(`${BASE}/authenticate`, {username: "Dave", password: "TulipKettle01"})).json()).auth_token);
stranger.xt("dj", 1, "denAlice", 1, -1);
assert.strictEqual((await stranger.nextXt("rj"))[2], "0");
stranger.socket.destroy();
@@ -411,7 +416,7 @@ const run = async () => {
assert.deepStrictEqual([gone[2], gone[5], ...gone.slice(7)], ["2", "Alice", "0", "1", tradedInv]);
// --- item finder: search by name and id, give to a connected player
assert.match(await (await fetch(`${BASE}/shop`)).text(), /Item finder/);
assert.match(await (await fetch(`${BASE}/shop`)).text(), /Item giver/);
const found = await (await fetch(`${BASE}/api/search?q=top+hat&kind=clothing`)).json();
assert.ok(found.total > 0 && found.results.every(item => /top/i.test(item.name) && /hat/i.test(item.name)));
const hat = found.results[0];
@@ -428,7 +433,7 @@ const run = async () => {
assert.deepStrictEqual((await a.nextXt("di")).slice(3, 4), ["1"]);
// --- no game account has admin powers: "foo" is an ordinary player now
const foo = await (await postJson(`${BASE}/authenticate`, {username: "foo", password: "Password04"})).json();
const foo = await (await postJson(`${BASE}/authenticate`, {username: "foo", password: "KettlePass04"})).json();
const f = new GameClient();
await f.connect();
const fooLogin = await f.logIn("foo", foo.auth_token);
@@ -520,14 +525,14 @@ const run = async () => {
// names sign-up would refuse are fine from the panel, and can log in.
for (const odd of ["x", "~*Bob*~ <3", "Ünïcødé 名前", "a name well past twenty characters"]) {
assert.strictEqual((await panel("account", {username: "Bob", action: "rename", newName: odd}, admin)).status, 200);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: odd, password: "Password02"})).status, 200);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: odd, password: "KettlePass02"})).status, 200);
assert.strictEqual((await panel("account", {username: odd, action: "rename", newName: "Bob"}, admin)).status, 200);
}
assert.strictEqual((await registerJson({username: "x", password: "Password09"})).status, 400); // sign-up rules unchanged
assert.strictEqual((await registerJson({username: "x", password: "KettlePass09"})).status, 400); // sign-up rules unchanged
const renamed = await panel("account", {username: "Bob", action: "rename", newName: "Robert"}, admin);
assert.deepStrictEqual([renamed.status, renamed.data.username], [200, "Robert"]);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Bob", password: "Password02"})).status, 401);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "robert", password: "Password02"})).status, 200);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "Bob", password: "KettlePass02"})).status, 401);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "robert", password: "KettlePass02"})).status, 200);
assert.ok(!(await panel("accounts", undefined, admin)).data.accounts.some(account => account.username === "Bob"));
assert.strictEqual((await panel("account", {username: "Robert", action: "rename", newName: "ROBERT"}, admin)).status, 200);
assert.strictEqual((await panel("account", {username: "robert", action: "rename", newName: "Bob"}, admin)).status, 200);
@@ -535,7 +540,7 @@ const run = async () => {
// A new password for a player: the old one and old tokens stop working.
assert.strictEqual((await panel("account", {username: "foo", action: "password", password: "short"}, admin)).status, 400);
assert.strictEqual((await panel("account", {username: "foo", action: "password", password: "New-password-4"}, admin)).status, 200);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "foo", password: "Password04"})).status, 401);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "foo", password: "KettlePass04"})).status, 401);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {refresh_token: foo.refresh_token})).status, 401);
assert.strictEqual((await postJson(`${BASE}/authenticate`, {username: "foo", password: "New-password-4"})).status, 200);
assert.strictEqual((await panel("account", {username: "foo", action: "delete"}, admin)).status, 200);
@@ -621,14 +626,16 @@ const run = async () => {
// --- the custom client's login choices: honoured for that session only
assert.strictEqual((await (await fetch(`${BASE}/flashvars`)).json()).loginChoices, true);
const chosen = await (await postJson(`${BASE}/authenticate`, {username: "Carol", password: "Password03",
// (a fresh account: Carol is banned by now, and a banned account's
// sign-in is refused with "account_banned", so it gets no token.)
assert.strictEqual((await registerJson({username: "Erin", password: "KettlePass05"})).status, 200);
const chosen = await (await postJson(`${BASE}/authenticate`, {username: "Erin", password: "KettlePass05",
login_choices: {accountType: 0, isGuide: true, membershipDays: 12, isModerator: "yes"}})).json();
// (Carol is banned from the game by now, so only the web side is checked.)
assert.strictEqual((await (await fetch(`${BASE}/player`, {headers: {Authorization: `Bearer ${chosen.auth_token}`}})).json()).game_account_type, 0);
a.xt("ag", denId, "Carol", 0);
a.xt("ag", denId, "Erin", 0);
assert.deepStrictEqual((await a.untilXt("ag")).slice(5, 7), ["0", "1"]); // account type, guide
await postJson(`${BASE}/authenticate`, {username: "Carol", password: "Password03"}); // and back to normal
a.xt("ag", denId, "Carol", 0);
await postJson(`${BASE}/authenticate`, {username: "Erin", password: "KettlePass05"}); // and back to normal
a.xt("ag", denId, "Erin", 0);
assert.deepStrictEqual((await a.untilXt("ag")).slice(5, 7), ["2", "0"]);
// --- custom colours: an id for four RGB values, announced to everyone
@@ -642,7 +649,7 @@ const run = async () => {
assert.strictEqual((await a.untilXt("ap"))[2], "1");
const late = new GameClient();
await late.connect();
const dev = await (await postJson(`${BASE}/authenticate`, {username: "Alice", password: "Password01", login_choices: {accountType: 4, membershipDays: 7}})).json();
const dev = await (await postJson(`${BASE}/authenticate`, {username: "Alice", password: "KettlePass01", login_choices: {accountType: 4, membershipDays: 7}})).json();
const devLogin = await late.logIn("Alice", dev.auth_token);
assert.deepStrictEqual([devLogin.params.accountType, devLogin.params.numDaysLeftOnSubscription, devLogin.params.isGuide, devLogin.params.isModerator], [4, 7, false, false]);
assert.deepStrictEqual((await late.untilXt("xcc")).slice(2, 4), ["1", String(0xFD000000)]); // the table at login
+376
View File
@@ -0,0 +1,376 @@
"use strict";
// end to end: staff roles (lib/roles.js), the staff chat commands
// (lib/commands.js) and the moderator panel's role checks
// (lib/modpanel.js), against a real server with a database of its own.
const assert = require("assert");
const crypto = require("crypto");
const harness = require("./harness.js");
const HTTP_PORT = 18091;
const GAME_PORT = 19350;
const BASE = `http://127.0.0.1:${HTTP_PORT}`;
const TOWNSHIP = "jamaa_township.room_main#1";
const SAREPIA = "sarepia.room_main#1";
const {postJson} = harness;
// the authenticator app's side of 2FA (lib/totp.js): a base32 secret,
// HMAC-SHA1, 30-second steps, six digits.
const STEP = 30;
const base32Decode = text => {
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
const bits = text.replace(/=+$/, "").toUpperCase().split("").map(c => alphabet.indexOf(c).toString(2).padStart(5, "0")).join("");
const bytes = [];
for (let i = 0; i + 8 <= bits.length; i += 8) {
bytes.push(parseInt(bits.slice(i, i + 8), 2));
}
return Buffer.from(bytes);
};
const codeAt = (secret, step) => {
const counter = Buffer.alloc(8);
counter.writeBigUInt64BE(BigInt(step));
const mac = crypto.createHmac("sha1", base32Decode(secret)).update(counter).digest();
const offset = mac[mac.length - 1] & 0x0F;
return String((mac.readUInt32BE(offset) & 0x7FFFFFFF) % 1000000).padStart(6, "0");
};
const stepNow = () => Math.floor(Date.now() / 1000 / STEP);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
// a code is taken once: each use needs a later step than the last.
const waitForStep = async step => {
while (stepNow() < step) {
await sleep(250);
}
};
// a web panel's session: keeps the cookie it is given.
const webSession = () => {
let cookie = "";
return async (path, body) => {
const headers = {cookie};
const options = body === undefined ? {headers} : {method: "POST", headers: {...headers, "Content-Type": "application/json"}, body: JSON.stringify(body)};
const res = await fetch(`${BASE}${path}`, options);
const set = res.headers.get("set-cookie");
if (set) {
cookie = set.split(";")[0];
}
return {status: res.status, data: await res.json().catch(() => ({}))};
};
};
const say = (client, roomId, text) =>
client.send(`<msg t='sys'><body action='pubMsg' r='${roomId}'><txt><![CDATA[${text}%0]]></txt></body></msg>`);
// logs in (with a 2FA code when given) and walks into `room`. `onLogin`
// sees what comes with the login, before joining skips past it.
const arrive = async (username, password, room, totp, onLogin = async () => {}) => {
const res = await postJson(`${BASE}/authenticate`, {username, password, ...(totp ? {totp} : {})});
const auth = await res.json();
assert.strictEqual(res.status, 200, `${username} could not sign in: ${JSON.stringify(auth)}`);
const client = new harness.GameClient(GAME_PORT);
await client.connect();
const login = await client.logIn(username, auth.auth_token);
assert.strictEqual(login.status, "1");
await onLogin(client);
client.xt("rj", 1, room, 1, 0, 0);
let rj = await client.untilXt("rj");
await client.untilXt("rp");
// a session's first room is always a spawn room (lib/world.js joinRoom)
if (rj[3] !== room) {
client.xt("rj", rj[4], room, 1, 0, 0);
rj = await client.untilXt("rj");
await client.untilXt("rp");
}
client.xt("au", rj[4], 1, 400, 400, 14, 1);
return {client, login, roomId: rj[4], room: rj[3]};
};
// the next moderator popup ("fd") of this kind, skipping earlier ones (a
// silence notice, say) still waiting.
const untilPopup = async (client, kind) => {
for (;;) {
const fields = await client.untilXt("fd");
if (fields[2] === kind) {
return fields;
}
}
};
// the next message box ("xtl") the server shows this client.
const nextBox = async client => (await client.untilXt("xtl"))[2];
// the chat line `text` coming back (every typed line, a command too, is
// shown to its sender, so skip those before it).
const untilChat = async (client, text) => {
for (;;) {
const line = await client.untilXt("uc");
if (line[3] === text) {
return line;
}
}
};
const run = async () => {
const registerJson = body => fetch(`${BASE}/api/register`, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({avatarType: 1, agreed: true, ...body})});
const people = {Mira: "KettlePass11", Hal: "KettlePass12", Pip: "KettlePass13", Ann: "KettlePass14"};
for (const [username, password] of Object.entries(people)) {
assert.strictEqual((await registerJson({username, password})).status, 200);
}
// --- the admin gives roles
const admin = webSession();
assert.strictEqual((await admin("/admin/api/setup", {password: "AdminPass99!"})).status, 200);
assert.strictEqual((await admin("/admin/api/login", {password: "AdminPass99!"})).status, 200);
const roleList = await admin("/admin/api/roles");
assert.deepStrictEqual(roleList.data.roles.map(role => role.id), ["developer", "helper", "moderator", "admin"]);
assert.match((await admin("/admin/api/account", {username: "Mira", action: "role", role: "boss"})).data.error, /No such role/);
// staff need 2FA: turned on from the account page.
const secrets = {};
const usedStep = {};
for (const username of ["Mira", "Hal"]) {
const page = webSession();
assert.strictEqual((await page("/account/api/login", {username, password: people[username]})).status, 200);
const begun = await page("/account/api/act", {action: "twoStepStart", current: people[username]});
secrets[username] = begun.data.setup.secret;
usedStep[username] = stepNow();
const confirmed = await page("/account/api/act", {action: "twoStepConfirm", code: codeAt(secrets[username], usedStep[username])});
assert.ok(confirmed.data.ok, JSON.stringify(confirmed.data));
}
assert.match((await admin("/admin/api/account", {username: "Mira", action: "role", role: "moderator"})).data.ok, /moderator/);
assert.match((await admin("/admin/api/account", {username: "Hal", action: "role", role: "helper"})).data.ok, /helper/);
// --- the game: the login reply carries your own role, and nobody else's
usedStep.Mira++;
// and the patched client's staff window is told the same ("xsp")
let staffSaid = null;
const mira = await arrive("Mira", people.Mira, TOWNSHIP, codeAt(secrets.Mira, usedStep.Mira), async client => {
staffSaid = await client.untilXt("xsp");
});
assert.strictEqual(staffSaid[2], "moderator");
assert.ok(staffSaid[3].split(",").includes("player.summon"));
assert.strictEqual(mira.login.params.staffRole, "moderator");
assert.ok(mira.login.params.staffPermissions.split(",").includes("player.summon"));
usedStep.Hal++;
const hal = await arrive("Hal", people.Hal, TOWNSHIP, codeAt(secrets.Hal, usedStep.Hal));
assert.strictEqual(hal.login.params.staffRole, "helper");
const pip = await arrive("Pip", people.Pip, SAREPIA);
assert.strictEqual(pip.login.params.staffRole, "");
const ann = await arrive("Ann", people.Ann, SAREPIA);
// a staff command from a player is plain chat
say(pip.client, pip.roomId, "!kick Mira");
await untilChat(pip.client, "!kick Mira");
say(mira.client, mira.roomId, "!staff");
const staffBox = await nextBox(mira.client);
assert.match(staffBox, /Mira \(Moderator\)/);
assert.match(staffBox, /Hal \(Helper\)/);
// summon: Pip is brought from Sarepia to Mira in the township
say(mira.client, mira.roomId, "!summon Pip");
// ... onto the spot where Mira stands, when the room has loaded ("xgt")
assert.deepStrictEqual((await pip.client.untilXt("xgt")).slice(2), ["400", "400", "0"]);
assert.strictEqual((await pip.client.untilXt("rj"))[3], TOWNSHIP);
assert.strictEqual(await nextBox(mira.client), "Pip was brought here.");
// a helper may silence a player, but not kick, nor act on a moderator
say(hal.client, hal.roomId, "!silence Pip 1");
assert.strictEqual(await nextBox(hal.client), "Pip cannot chat for 1 hours.");
say(hal.client, hal.roomId, "!silence Pip off");
assert.strictEqual(await nextBox(hal.client), "Pip can chat again.");
say(hal.client, hal.roomId, "!silence Mira 1");
assert.match(await nextBox(hal.client), /your rank or above/);
say(hal.client, hal.roomId, "!kick Pip");
// no permission: just chat, seen by the room (Mira, in the township)
await untilChat(mira.client, "!kick Pip");
// goto: Mira goes to Ann in Sarepia
say(mira.client, mira.roomId, "!goto Ann");
assert.deepStrictEqual((await mira.client.untilXt("xgt")).slice(2), ["400", "400", "0"]);
assert.strictEqual((await mira.client.untilXt("rj"))[3], SAREPIA);
// in the same room already: straight onto her
say(mira.client, ann.roomId, "!goto Ann");
assert.deepStrictEqual((await mira.client.untilXt("xgt")).slice(2), ["400", "400", "1"]);
// a warning: the game's own popup for the reason ("fw", 1 = bullying),
// kept on the account; a message box; the count; then kick disconnects
say(mira.client, ann.roomId, "!warn Ann bullying called names");
assert.deepStrictEqual((await ann.client.untilXt("fd")).slice(2, 4), ["fw", "1"]);
assert.strictEqual(await nextBox(mira.client), "Ann warned (bullying): warning 1.");
say(mira.client, ann.roomId, "!warn Ann");
assert.deepStrictEqual((await ann.client.untilXt("fd")).slice(2, 4), ["fw", "4"]); // behavior, the default
assert.strictEqual(await nextBox(mira.client), "Ann warned (behavior): warning 2.");
say(mira.client, ann.roomId, "!message Ann please be kind");
assert.deepStrictEqual((await ann.client.untilXt("fd")).slice(2, 4), ["fp", "please be kind"]);
assert.strictEqual(await nextBox(mira.client), "Shown to Ann.");
say(mira.client, ann.roomId, "!warnings Ann");
assert.match(await nextBox(mira.client), /^Ann has 2 warnings\. Latest: \S+ behavior by Mira; \S+ bullying by Mira \(called names\)$/);
// the client's staff window ("xmd"): the same commands, one field each
// the third warning in 30 days also silences for an hour (config.warningSilence)
mira.client.xt("xmd", ann.roomId, "warn", "Ann", "personal");
assert.deepStrictEqual((await ann.client.untilXt("fd")).slice(2, 4), ["fw", "3"]);
assert.deepStrictEqual((await ann.client.untilXt("fd")).slice(2, 4), ["fs", "60"]);
assert.strictEqual(await nextBox(mira.client), "Ann warned (personal): warning 3. Silenced for 60 minutes, for that many warnings.");
mira.client.xt("xmd", ann.roomId, "message", "Ann", "hello there");
assert.deepStrictEqual((await untilPopup(ann.client, "fp")).slice(2, 4), ["fp", "hello there"]);
assert.strictEqual(await nextBox(mira.client), "Shown to Ann.");
mira.client.xt("xmd", ann.roomId, "ban", "Ann"); // not one the window has: nothing
// and from a player, nothing at all: Ann warns Mira
ann.client.xt("xmd", ann.roomId, "warn", "Mira", "bullying");
mira.client.xt("xmd", ann.roomId, "warnings", "Ann");
assert.match(await nextBox(mira.client), /^Ann has 3 warnings\. /);
say(mira.client, ann.roomId, "!warnings Mira");
assert.strictEqual(await nextBox(mira.client), "Mira has no warnings.");
say(mira.client, ann.roomId, "!kick Ann");
assert.strictEqual((await ann.client.untilXt("fd"))[2], "fk");
assert.strictEqual(await nextBox(mira.client), "Ann was disconnected.");
// --- the moderator panel: what the role allows, checked by the server
for (const username of ["Mira", "Hal"]) {
usedStep[username]++;
}
await waitForStep(Math.max(usedStep.Mira, usedStep.Hal) - 1);
const modPage = webSession();
assert.strictEqual((await modPage("/mod/api/login", {username: "Mira", password: people.Mira, code: codeAt(secrets.Mira, usedStep.Mira)})).status, 200);
const miraMe = (await modPage("/mod/api/me")).data;
assert.strictEqual(miraMe.role, "moderator");
assert.ok(miraMe.permissions.includes("player.ban"));
const halPage = webSession();
assert.strictEqual((await halPage("/mod/api/login", {username: "Hal", password: people.Hal, code: codeAt(secrets.Hal, usedStep.Hal)})).status, 200);
const halMe = (await halPage("/mod/api/me")).data;
assert.strictEqual(halMe.role, "helper");
assert.ok(!halMe.permissions.includes("player.ban"));
assert.strictEqual((await halPage("/mod/api/act", {username: "Pip", action: "ban", hours: 1, reason: "x"})).data.error, "Your role cannot do that.");
assert.match((await halPage("/mod/api/act", {username: "Mira", action: "silence", hours: 1})).data.error, /your rank or above/);
// searching by address (against ban evasion) is for the roles that ban addresses
assert.strictEqual((await halPage("/mod/api/players?by=address&q=127.0.0.")).status, 403);
assert.ok(Array.isArray((await modPage("/mod/api/players?by=address&q=127.0.0.")).data.players));
// a warning from the panel, and on the player's page
assert.match((await modPage("/mod/api/act", {username: "Pip", action: "warn", reason: "scamming", note: "fake trade"})).data.ok, /^Pip warned \(scamming\): warning 1\./);
assert.match((await modPage("/mod/api/act", {username: "Pip", action: "warn", reason: "nonsense"})).data.error, /reason/);
assert.deepStrictEqual((await untilPopup(pip.client, "fw")).slice(2, 4), ["fw", "9"]);
const pipPage = (await modPage("/mod/api/player?username=Pip")).data;
assert.strictEqual(pipPage.warnings, 1);
assert.deepStrictEqual([pipPage.warningList[0].reason, pipPage.warningList[0].note, pipPage.warningList[0].by], ["scamming", "fake trade", "Mira"]);
assert.strictEqual(pipPage.warningList[0].seen, true);
// mod notes: for staff, never the player; removed by their writer or an admin
assert.strictEqual((await modPage("/mod/api/act", {username: "Pip", action: "note", text: " talked about trading, seemed fine "})).data.ok, "Note added.");
assert.match((await modPage("/mod/api/act", {username: "Pip", action: "note", text: " "})).data.error, /Write the note first/);
assert.strictEqual((await halPage("/mod/api/act", {username: "Pip", action: "note", text: "keeps asking for free items"})).data.ok, "Note added.");
const notes = (await modPage("/mod/api/player?username=Pip")).data.notes;
assert.deepStrictEqual(notes.map(note => `${note.by}: ${note.text}`), ["Hal: keeps asking for free items", "Mira: talked about trading, seemed fine"]);
assert.match((await modPage("/mod/api/act", {username: "Pip", action: "deleteNote", id: notes[0].id})).data.error, /Only whoever wrote a note/);
assert.strictEqual((await halPage("/mod/api/act", {username: "Pip", action: "deleteNote", id: notes[0].id})).data.ok, "Note removed.");
assert.match((await halPage("/mod/api/act", {username: "Mira", action: "note", text: "x"})).data.error, /your rank or above/);
say(mira.client, ann.roomId, "!note Pip asked about the rules");
assert.strictEqual(await nextBox(mira.client), "Note on Pip added.");
say(mira.client, ann.roomId, "!notes Pip");
assert.match(await nextBox(mira.client), /^Notes on Pip: \S+ Mira: asked about the rules \| \S+ Mira: talked about trading, seemed fine$/);
say(mira.client, ann.roomId, "!notes Nobody");
assert.strictEqual(await nextBox(mira.client), "No player called Nobody.");
// warnings while away (Ann was disconnected): kept for her next visit;
// the fifth in 30 days silences for a day; one is taken back
assert.match((await modPage("/mod/api/act", {username: "Ann", action: "warn", reason: "bullying"})).data.ok,
/^Ann warned \(bullying\): warning 4\. They are offline: they will see it when they next play\.$/);
assert.match((await modPage("/mod/api/act", {username: "Ann", action: "warn", reason: "behavior"})).data.ok,
/warning 5\. .*silenced them for 1 day\.$/);
assert.strictEqual((await modPage("/mod/api/act", {username: "Ann", action: "unwarn"})).data.ok, "Took back Ann's latest warning (behavior).");
const annAway = (await modPage("/mod/api/player?username=Ann")).data;
assert.strictEqual(annAway.warnings, 4);
assert.strictEqual(annAway.warningList[0].seen, false);
const annBack = await arrive("Ann", people.Ann, SAREPIA);
assert.deepStrictEqual((await untilPopup(annBack.client, "fw")).slice(2, 4), ["fw", "1"]); // the bullying one
assert.strictEqual((await modPage("/mod/api/player?username=Ann")).data.warningList[0].seen, true);
say(mira.client, ann.roomId, "!unwarn Ann");
assert.strictEqual(await nextBox(mira.client), "Took back Ann's latest warning (bullying).");
say(mira.client, ann.roomId, "!unwarn Mira");
assert.strictEqual(await nextBox(mira.client), "That is you.");
// the panel's summon brings Pip to Mira (now in Sarepia)
assert.match((await modPage("/mod/api/act", {username: "Pip", action: "summon"})).data.ok || "", /^Pip was brought to /);
assert.strictEqual((await pip.client.untilXt("rj"))[3], SAREPIA);
// a custom warning: the staff member's words are what the player sees
mira.client.xt("xmd", ann.roomId, "warn", "Pip", "custom", "no spamming please");
assert.deepStrictEqual((await untilPopup(pip.client, "fp")).slice(2, 4), ["fp", "Warning: no spamming please"]);
assert.strictEqual(await nextBox(mira.client), "Pip warned (custom): warning 2.");
say(mira.client, ann.roomId, "!warn Pip custom");
assert.match(await nextBox(mira.client), /^Use: !warn PLAYER custom TEXT/);
assert.match((await modPage("/mod/api/act", {username: "Pip", action: "warn", reason: "custom", note: " "})).data.error, /custom warning needs its words/);
// invisible: gone from players' screens, still seen by staff (half
// see-through: "xiv"), and seen moving by them; not for a helper
// ("ac": [.., room, id, x, y, anim, username, ...]; others' may be waiting)
const untilDrawn = async (client, username, x) => {
for (;;) {
const fields = await client.untilXt("ac");
if (fields[6] === username && fields[3] === x) {
return fields;
}
}
};
const untilRemoved = async (client, id) => {
for (;;) {
if ((await client.untilXt("ar"))[2] === id) {
return;
}
}
};
mira.client.xt("au", ann.roomId, 1, 300, 300, 14, 1);
const miraId = (await untilDrawn(pip.client, "Mira", "300"))[2];
hal.client.xt("rj", 1, SAREPIA, 1, 0, 0);
const halRj = await hal.client.untilXt("rj");
await hal.client.untilXt("rp");
hal.client.xt("au", halRj[4], 1, 410, 410, 14, 1);
await untilDrawn(hal.client, "Mira", "300");
say(mira.client, ann.roomId, "!invisible");
await untilRemoved(pip.client, miraId);
assert.deepStrictEqual((await hal.client.untilXt("xiv")).slice(2), [miraId, "1"]);
assert.deepStrictEqual((await mira.client.untilXt("xiv")).slice(2), [miraId, "1"]);
assert.match(await nextBox(mira.client), /^You are invisible: only staff see you/);
mira.client.xt("au", ann.roomId, 1, 350, 350, 14, 0);
for (;;) {
const moved = await hal.client.untilXt("au");
if (moved[3] === miraId) {
break;
}
}
// a helper may not: the window's request does nothing, the command is chat
hal.client.xt("xiv", halRj[4]);
say(hal.client, halRj[4], "!invisible");
await untilChat(pip.client, "!invisible");
// back again, where she walked to
mira.client.xt("xiv", ann.roomId);
assert.deepStrictEqual((await untilDrawn(pip.client, "Mira", "350")).slice(2, 5), [miraId, "350", "350"]);
assert.deepStrictEqual((await hal.client.untilXt("xiv")).slice(2), [miraId, "0"]);
assert.strictEqual(await nextBox(mira.client), "You can be seen again.");
// everything above is in the moderators' log, the in-game ones marked so
const log = (await admin("/admin/api/moderators")).data.log.map(entry => `${entry.by} ${entry.action} ${entry.target}`);
for (const line of ["Mira summon (in game) Pip", "Hal silence (in game) Pip", "Mira goto (in game) Ann", "Mira warn (in game) Ann",
"Mira message (in game) Ann", "Mira kick (in game) Ann", "Mira warn Pip", "Mira summon Pip", "Mira warn Ann", "Mira unwarn Ann",
"Mira unwarn (in game) Ann", "Mira went invisible (in game) ", "Mira became visible (in game) ", "Mira note Pip", "Hal deleteNote Pip",
"Mira note (in game) Pip"]) {
assert.ok(log.includes(line), `missing from the log: ${line}\n${log.join("\n")}`);
}
// the moderators' message box header has real line breaks, not "\\n"
const zlib = require("zlib");
const {decode} = require("../lib/amf3.js");
const stringsPath = require("../lib/cdn.js").hashedPath("defPacks/10230");
const strings = decode(zlib.inflateRawSync(Buffer.from(await (await fetch(`${BASE}/${stringsPath}`)).arrayBuffer())));
assert.strictEqual(strings[11134], "--Message From Moderator--\n\n");
assert.ok(!strings[11135].includes("\\n"));
for (const {client} of [mira, hal, pip, annBack]) {
client.socket.destroy();
}
};
harness.withServer("staff test", HTTP_PORT, GAME_PORT, run).catch(err => {
console.error(err);
process.exit(1);
});
+14 -3
View File
@@ -23,6 +23,7 @@ cd "$(dirname "$(readlink -f "$0")")/.."
out=${1:-swf/ajclient.swf}
set -- \
AJClient AJClient.as \
com.sbi.client.KeepAlive KeepAlive.as \
GlobalErrorCatch GlobalErrorCatch.as \
XtReplyDemuxer XtReplyDemuxer.as \
loader.MediaHelper MediaHelper.as \
@@ -33,6 +34,7 @@ set -- \
gui.ReportAPlayer ReportAPlayer.as \
gui.ECardCreation ECardCreation.as \
gui.GuiManager GuiManager.as \
gui.ActionManager ActionManager.as \
gui.PlayerSearch PlayerSearch.as \
avatar.NPCView NPCView.as \
gui.ChatHistory ChatHistory.as \
@@ -55,6 +57,7 @@ set -- \
gui.PetInventory PetInventory.as \
gui.DenEditor DenEditor.as \
gui.TradeManager TradeManager.as \
avatar.AvatarView AvatarView.as \
avatar.AvatarWorldView AvatarWorldView.as \
room.RoomManagerWorld RoomManagerWorld.as \
gskinner.motion.GTween GTween.as \
@@ -74,10 +77,18 @@ set -- \
ecard.ECard ECard.as \
game.ArtStudioKit ArtStudioKit.as \
game.artStudioPainting.ArtStudioPainting ArtStudioPainting.as \
game.artStudioGridDrawing.ArtStudioGridDrawing ArtStudioGridDrawing.as
game.artStudioGridDrawing.ArtStudioGridDrawing ArtStudioGridDrawing.as \
item.ItemXtCommManager ItemXtCommManager.as \
den.DenXtCommManager DenXtCommManager.as \
gui.ActionManager ActionManager.as \
gui.SitForwardAction SitForwardAction.as \
avatar.AvatarUtility AvatarUtility.as \
item.Item Item.as \
loader.DenItemHelper DenItemHelper.as
# not in the game: added before the replace (game.ArtStudioKit is Strawberry
# Jam's, shared by its two art studio painters)
NEW_CLASSES="game.ArtStudioKit"
# Jam's, shared by its two art studio painters; gui.SitForwardAction is the
# action of sitting facing forward)
NEW_CLASSES="game.ArtStudioKit gui.SitForwardAction"
args=""
while [ $# -gt 0 ]; do
args="$args $1 swf-src/$2"
Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

+55 -1
View File
@@ -178,8 +178,29 @@ def sprout():
return [(stem, False), (small, False), (large, False)]
# id, outline, and the card disc's colours: top, bottom, rim.
def seal_points():
"""A round seal with eight soft scallops, as verified accounts have."""
steps = 96
return [(7.5 * (1 + 0.075 * math.cos(math.radians(8 * angle))) * math.cos(math.radians(angle)),
7.5 * (1 + 0.075 * math.cos(math.radians(8 * angle))) * math.sin(math.radians(angle)))
for angle in (360 * step / steps - 90 for step in range(steps))]
def seal_tick():
return [(x * 0.52, y * 0.52 + 0.3) for x, y in tick()[0][0]]
def verified():
# the seal with the tick cut out of it, so the name tag's colour shows
# the seal and the tag behind shows through the tick.
return [(seal_points(), False), (seal_tick(), True)]
# id, outline, and the card disc's colours: top, bottom, rim. a badge whose
# rim is None has no disc: its outline's solid pieces are shaded instead,
# and its holes are white (the verified seal, blue with a white tick).
BADGES = [
("verified", verified, "#4cb3ff", "#1478e6", None),
("owner", crown, "#ffd95a", "#f0a11c", "#96600a"),
("moderator", shield, "#5cb2ff", "#1f6fd6", "#12458a"),
("contributor", wrench, "#6fd878", "#2f9e3a", "#19621f"),
@@ -262,6 +283,8 @@ def card_pixels(paths, top, bottom, rim):
"""CARD_SIZE square of (r, g, b, a): a disc shaded from `top` to
`bottom` with a `rim`, the outline in white on it. Sixteen samples to a
pixel."""
if rim is None:
return shape_pixels(paths, top, bottom)
paths = fitted(paths, CARD_HALF)
top, bottom, rim = rgb(top), rgb(bottom), rgb(rim)
middle, fill_radius, rim_radius = CARD_SIZE / 2, 20.0, 23.0
@@ -291,6 +314,37 @@ def card_pixels(paths, top, bottom, rim):
return rows
def shape_pixels(paths, top, bottom):
"""CARD_SIZE square of (r, g, b, a): the outline's solid pieces, as big
as the disc, shaded from `top` to `bottom`, and its holes in white."""
paths = fitted(paths, 23.0)
solid = [(points, False) for points, hole in paths if not hole]
holes = [(points, False) for points, hole in paths if hole]
top, bottom = rgb(top), rgb(bottom)
middle = CARD_SIZE / 2
rows = []
for py in range(CARD_SIZE):
row = []
for px in range(CARD_SIZE):
total = [0.0, 0.0, 0.0, 0.0]
for sy in range(4):
for sx in range(4):
x, y = px + (sx + 0.5) / 4 - middle, py + (sy + 0.5) / 4 - middle
if not inside(solid, x, y):
continue
if inside(holes, x, y):
colour = (255, 255, 255)
else:
shade = (y + 23.0) / 46.0
colour = tuple(a + (b - a) * shade for a, b in zip(top, bottom))
for channel in range(3):
total[channel] += colour[channel]
total[3] += 1
row.append(tuple(round(total[c] / total[3]) if total[3] else 0 for c in range(3)) + (round(total[3] / 16 * 255),))
rows.append(row)
return rows
def png(rows):
raw = b"".join(b"\x00" + bytes(value for pixel in row for value in pixel) for row in rows)
+13 -6
View File
@@ -1,4 +1,4 @@
"""make-emote.py <picture.png> [name] [--black-background]
"""make-emote.py <picture.png> [name] [--slot=N] [--black-background]
Adds an emote of our own to swf/HUDAssets.swf, from a picture: the classes
"<name>" (the emote over an animal's head and in a chat bubble) and
@@ -10,7 +10,9 @@ The game makes an emote by its class name (gui.EmoticonUtility), so the
name also has to be in that class's lists: swf-src/EmoticonUtility.cinit.pcode,
which tools/build-client.sh puts into the client.
Running it again replaces what an earlier run added. The picture must be an
Each emote of ours has a slot (--slot=N, 0 by default: emo_temp's), its
own character ids and its own code: running it again for a slot replaces
what an earlier run put there, and leaves the other slots as they are. The picture must be an
8-bit RGBA PNG, not interlaced; --black-background is for one that came on
black where it should be see-through. Needs nothing but Python.
"""
@@ -267,18 +269,23 @@ def main():
sys.exit(__doc__)
words = [word for word in sys.argv[1:] if not word.startswith("--")]
name = words[1] if len(words) > 1 else "emo_temp"
slots = [word for word in sys.argv[1:] if word.startswith("--slot=")]
slot = int(slots[0].split("=", 1)[1]) if slots else 0
first_id = FIRST_ID + slot * 5
# slot 0 keeps the name it always had, so that a run for it replaces it
abc_name = ABC_NAME if slot == 0 else ABC_NAME + b"_" + str(slot).encode()
picture = read_png(Path(words[0]))
if "--black-background" in sys.argv:
picture = without_background(*picture)
width, height, pixels = shrunk(*picture, SHRINK)
bitmap, large_shape, small_shape, large, small = range(FIRST_ID, FIRST_ID + 5)
bitmap, large_shape, small_shape, large, small = range(first_id, first_id + 5)
ours = [
tag(36, struct.pack("<HBHH", bitmap, 5, width, height) + zlib.compress(pixels, 9)),
picture_shape(large_shape, bitmap, width, height, LARGE_WIDTH),
picture_shape(small_shape, bitmap, width, height, SMALL_WIDTH),
clip(large, large_shape),
clip(small, small_shape),
tag(82, struct.pack("<I", 1) + ABC_NAME + b"\0" + abc([name, f"{name}_sml"])),
tag(82, struct.pack("<I", 1) + abc_name + b"\0" + abc([name, f"{name}_sml"])),
tag(76, struct.pack("<H", 2) + struct.pack("<H", large) + name.encode() + b"\0" + struct.pack("<H", small) + f"{name}_sml".encode() + b"\0"),
]
@@ -295,9 +302,9 @@ def main():
def is_ours(code, whole, inner):
if code in (2, 36, 39):
return FIRST_ID <= struct.unpack_from("<H", inner)[0] < FIRST_ID + 5
return first_id <= struct.unpack_from("<H", inner)[0] < first_id + 5
if code == 82:
return inner[4:4 + len(ABC_NAME) + 1] == ABC_NAME + b"\0"
return inner[4:4 + len(abc_name) + 1] == abc_name + b"\0"
return code == 76 and struct.unpack_from("<H", inner, 2)[0] == large
kept = [entry for entry in tags if not is_ours(*entry)]
first_frame = next(index for index, (code, _, _) in enumerate(kept) if code == 1)
+24 -4
View File
@@ -59,7 +59,16 @@ const day = time => new Date(time).toISOString().slice(0, 10);
fs.mkdirSync(filesDir, {recursive: true});
// {builds: {build: newest sale start}, rooms: {room: {build: hash of its file}}}
let index = fs.existsSync(indexFile) ? JSON.parse(fs.readFileSync(indexFile)) : null;
// read if it is there: no separate look first, which the file could change after
let index = null;
try {
index = JSON.parse(fs.readFileSync(indexFile));
}
catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
}
if (!index) {
index = {builds: {}, rooms: {}};
const jobs = [];
@@ -83,14 +92,25 @@ const day = time => new Date(time).toISOString().slice(0, 10);
const [build, room] = jobs.pop();
const body = await download(build, `roomDefs/${room}.xroom`);
const hash = body ? crypto.createHash("sha1").update(body).digest("hex").slice(0, 12) : null;
if (body && !fs.existsSync(path.join(filesDir, hash))) {
fs.writeFileSync(path.join(filesDir, hash), body);
// named by its own hash, so one already there is this same file: "wx"
// writes only a new one, in the one step.
if (body) {
try {
fs.writeFileSync(path.join(filesDir, hash), body, {flag: "wx"});
}
catch (err) {
if (err.code !== "EEXIST") {
throw err;
}
}
}
(index.rooms[room] = index.rooms[room] || {})[build] = hash;
}
};
await Promise.all(Array.from({length: WORKERS}, worker));
fs.writeFileSync(indexFile, JSON.stringify(index));
// written whole under another name, then put in its place
fs.writeFileSync(`${indexFile}.tmp`, JSON.stringify(index));
fs.renameSync(`${indexFile}.tmp`, indexFile);
}
console.log("Builds, by the newest sale start in each:");