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]>
This commit is contained in:
SnipzilandClaude Opus 5.5 committed 2026-10-17 16:33:14 -04:00
commit d09ee94e16
33 files changed
+649 -230

No files matched your search

+7
View File
@@ -1,6 +1,13 @@
# Burrow
Burrow is a private server for AJ Classic.
# Security
An independent security audit by a Strawberry Jam contributor, who is not part of the Burrow team, found no malware in the Burrow client or server (client v1.2.0, server as of 17 October 2026). Every file in every installer was checked against its source and against the official Electron, NSIS and Adobe Flash releases. The report also lists the weaknesses found, with fixes, and every check can be repeated by anyone.
**[Read the audit](https://snipzil.github.io/burrow-server/)**
Every push to this repository is checked automatically (`.github/workflows/security.yml`) for new outside web addresses in the server or game files, code that starts programs, committed keys and leaked credentials.
# Disclaimer
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.
+1 -1
View File
@@ -116,7 +116,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 || "55",
buildVersion: env.AJ_BUILD_VERSION || "57",
// what the official CDN is asked for; not ours to change.
upstreamBuildVersion: "3",
+148 -79
View File
@@ -3,7 +3,7 @@
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const {DatabaseSync} = require("node:sqlite");
const {DatabaseSync, backup: copyDatabase} = require("node:sqlite");
const config = require("../config.js");
const defpacks = require("./defpacks.js");
const names = require("./names.js");
@@ -13,9 +13,9 @@ const names = require("./names.js");
// JSON document per account in `state`.
//
// every account is held in memory while the server runs. game code changes
// those objects directly and then calls save(), which has every account
// whose state changed written back, a moment later: however many times it
// is called in that moment, the accounts are gone through once (flush).
// those objects directly and then calls save(account, ...), which has the
// accounts named written back a moment later, and the others looked at a
// few at a time (flush, below).
const SCHEMA = `
CREATE TABLE IF NOT EXISTS accounts (
@@ -415,21 +415,30 @@ const load = () => {
console.log(`[accounts] ${byKey.size} accounts in ${path.join(config.dataDir, "game.sqlite")}`);
};
// Which accounts the save after a message looks at. turning an account into
// JSON to see whether it changed costs, and doing it for every account there
// is, a second after nearly every message, held the whole server up for
// longer the more accounts there were: a second and more, for everyone. so
// it looks at the accounts in play: online ones (hold, from lib/world.js),
// and ones looked up lately (by name, id, token, password: how the admin
// panel, buddies and the like get at an offline account), until a save
// finds them written and WARM_MS has gone by. the rest are looked at a few
// at a time behind those (SWEEP_BUDGET_MS a save), round and round, for
// what reached an account some other way (accounts.all()). a stop of the
// server, and every flush() called by name, looks at all of them.
// Which accounts a save looks at. turning an account into JSON to see
// whether it changed costs (up to a millisecond for a big one), and doing it
// a second after nearly every message for every account in play (online
// ones, and the buddies, dens and cards they had looked up lately) held the
// whole server up for most of every second once there were enough players.
// so game code says which accounts it changed, save(account, ...), and those
// are written within SAVE_DELAY_MS. behind them, for whatever changed an
// account without saying so, the accounts in play are looked at a few at a
// time (PLAY_BUDGET_MS a save), round and round: online ones (hold, from
// lib/world.js) and ones looked up lately (by name, id, token, password: how
// the admin panel, buddies and the like get at an offline account), for
// WARM_MS. behind those every other account is looked at the same way
// (SWEEP_BUDGET_MS), for what reached an account some other way
// (accounts.all()). a stop of the server, and every flush() called by name,
// looks at all of them.
const WARM_MS = 10 * 60 * 1000;
const PLAY_BUDGET_MS = 10;
const SWEEP_BUDGET_MS = 5;
const held = new Set(); // accounts online
const warm = new Map(); // account -> when last looked up
const dirty = new Set(); // accounts said to have changed since the last save
let playOrder = [];
let playAt = 0;
let playLeft = 0; // accounts in play still to be looked at since the last save()
let sweepOrder = [];
let sweepAt = 0;
let sweepLeft = 0; // accounts the sweep still has to look at since the last save()
@@ -457,9 +466,60 @@ const changedState = (account, changed) => {
return false;
};
const elapsedMs = started => Number(process.hrtime.bigint() - started) / 1e6;
// the next accounts in play, while there is time: the ones online and the
// ones looked up lately. one looked up longer ago than WARM_MS is looked at
// once more, then left to the sweep.
const lookAtPlay = (changed, looked) => {
const started = process.hrtime.bigint();
while (playLeft > 0 && elapsedMs(started) < PLAY_BUDGET_MS) {
if (playAt >= playOrder.length) {
const now = Date.now();
playOrder = [...new Set([...held, ...warm.keys()])];
playAt = 0;
for (const [account, at] of warm) {
if (now - at > WARM_MS && !held.has(account)) {
warm.delete(account);
}
}
if (playOrder.length === 0) {
playLeft = 0;
break;
}
}
const account = playOrder[playAt++];
playLeft--;
if (!looked.has(account) && byId.get(account.id) === account) {
looked.add(account);
changedState(account, changed);
}
}
};
const lookAtRest = (changed, looked) => {
const started = process.hrtime.bigint();
while (sweepLeft > 0 && elapsedMs(started) < SWEEP_BUDGET_MS) {
if (sweepAt >= sweepOrder.length) {
sweepOrder = [...byId.values()];
sweepAt = 0;
if (sweepOrder.length === 0) {
sweepLeft = 0;
break;
}
}
const account = sweepOrder[sweepAt++];
sweepLeft--;
if (!looked.has(account) && byId.get(account.id) === account) {
looked.add(account);
changedState(account, changed);
}
}
};
// writes every account whose state changed since it was last written, in
// one transaction; with {some: true}, of the accounts in play and the
// sweep's next few (above).
// one transaction; with {some: true}, of the accounts said to have changed
// and the next few of the others (above).
const flush = ({some = false} = {}) => {
clearTimeout(saveTimer);
saveTimer = null;
@@ -467,49 +527,28 @@ const flush = ({some = false} = {}) => {
return;
}
const changed = [];
const named = [...dirty];
dirty.clear();
if (some) {
const now = Date.now();
const looked = new Set();
for (const account of held) {
looked.add(account);
changedState(account, changed);
}
for (const [account, at] of warm) {
if (looked.has(account)) {
continue;
}
looked.add(account);
if (byId.get(account.id) !== account) {
warm.delete(account); // removed
}
else if (!changedState(account, changed) && now - at > WARM_MS && !held.has(account)) {
warm.delete(account);
}
}
const started = process.hrtime.bigint();
while (sweepLeft > 0 && Number(process.hrtime.bigint() - started) / 1e6 < SWEEP_BUDGET_MS) {
if (sweepAt >= sweepOrder.length) {
sweepOrder = [...byId.values()];
sweepAt = 0;
if (sweepOrder.length === 0) {
break;
}
}
const account = sweepOrder[sweepAt++];
sweepLeft--;
if (!looked.has(account) && byId.get(account.id) === account) {
for (const account of named) {
if (byId.get(account.id) === account) {
looked.add(account);
changedState(account, changed);
}
}
lookAtPlay(changed, looked);
lookAtRest(changed, looked);
}
else {
for (const account of byId.values()) {
changedState(account, changed);
}
playLeft = 0;
sweepLeft = 0;
}
if (sweepLeft > 0) {
save(); // the sweep goes on in a moment
if (playLeft > 0 || sweepLeft > 0) {
later(CONTINUE_MS); // the looking goes on in a moment
}
if (changed.length === 0) {
return;
@@ -524,6 +563,7 @@ const flush = ({some = false} = {}) => {
}
catch (err) {
db.exec("ROLLBACK");
named.forEach(account => dirty.add(account));
throw err;
}
for (const [id, json] of changed) {
@@ -531,16 +571,17 @@ const flush = ({some = false} = {}) => {
}
};
// "Something changed": the accounts are written within SAVE_DELAY_MS. going
// through every account costs more the more there are, and game code calls
// this after nearly every message (and some of it a hundred times in a
// row), so the going-through is done once for all the calls of a moment.
// what a crash can lose is that moment; a stop of the server writes first
// "Something changed": the accounts named are written within SAVE_DELAY_MS,
// and the looking-through above starts again. game code calls this after
// nearly every message (and some of it a hundred times in a row), so it is
// done once for all the calls of a moment. what a crash can lose is that
// moment, for an account named, and the time a round of the looking takes,
// for one changed without saying so; a stop of the server writes first
// (server.js).
const SAVE_DELAY_MS = 1000;
const CONTINUE_MS = 250;
let saveTimer = null;
const save = () => {
sweepLeft = byId.size;
const later = delay => {
if (saveTimer === null) {
saveTimer = setTimeout(() => {
try {
@@ -550,25 +591,47 @@ const save = () => {
console.error(`[accounts] could not save: ${err.message}`);
save(); // tried again in a moment: nothing is lost while the server runs
}
}, SAVE_DELAY_MS);
}, delay);
}
};
const save = (...changedAccounts) => {
for (const account of changedAccounts) {
if (account) {
dirty.add(account);
}
}
playLeft = held.size + warm.size;
sweepLeft = byId.size;
later(SAVE_DELAY_MS);
};
// A copy of the whole database, made once a day into data/backups/ and the
// latest BACKUPS_KEPT kept. it is a whole file of its own (VACUUM INTO), to
// be copied somewhere else by whoever runs the server: a copy on the same
// disk is no help when the disk goes.
// latest BACKUPS_KEPT kept. it is a whole file of its own, to be copied
// somewhere else by whoever runs the server: a copy on the same disk is no
// help when the disk goes. it is copied a batch of pages at a time off the
// main thread (sqlite's online backup): made in one go (VACUUM INTO, after
// writing every account) it held the game up for seconds.
const BACKUPS_KEPT = 14;
const backup = () => {
let backingUp = false;
const backup = async () => {
const folder = path.join(config.dataDir, "backups");
const file = path.join(folder, `game-${new Date().toISOString().slice(0, 10)}.sqlite`);
if (fs.existsSync(file)) {
if (backingUp || fs.existsSync(file)) {
return;
}
fs.mkdirSync(folder, {recursive: true, mode: 0o700});
flush();
db.prepare("VACUUM INTO ?").run(file);
fs.chmodSync(file, 0o600);
backingUp = true;
const part = `${file}.part`;
try {
fs.mkdirSync(folder, {recursive: true, mode: 0o700});
fs.rmSync(part, {force: true});
await copyDatabase(db, part);
fs.chmodSync(part, 0o600);
fs.renameSync(part, file); // only a whole copy has the day's name
}
finally {
backingUp = false;
fs.rmSync(part, {force: true});
}
const old = fs.readdirSync(folder).filter(name => /^game-\d{4}-\d{2}-\d{2}\.sqlite$/.test(name)).sort().slice(0, -BACKUPS_KEPT);
for (const name of old) {
fs.unlinkSync(path.join(folder, name));
@@ -577,12 +640,9 @@ const backup = () => {
};
const startBackups = () => {
const attempt = () => {
try {
backup();
}
catch (err) {
backup().catch(err => {
console.error(`[accounts] backup failed: ${err.message}`);
}
});
};
attempt();
setInterval(attempt, 3600000).unref();
@@ -733,12 +793,16 @@ const rename = (account, username, anyName = false) => {
byKey.delete(oldKey);
account.username = username;
byKey.set(newKey, account);
const named = [account];
for (const other of byId.values()) {
other.buddies = other.buddies.map(name => (name === oldKey ? newKey : name));
other.blocked = other.blocked.map(name => (name === oldKey ? newKey : name));
other.buddyRequests = other.buddyRequests.map(name => (name === oldKey ? newKey : name));
if ([other.buddies, other.blocked, other.buddyRequests].some(list => list.includes(oldKey))) {
other.buddies = other.buddies.map(name => (name === oldKey ? newKey : name));
other.blocked = other.blocked.map(name => (name === oldKey ? newKey : name));
other.buddyRequests = other.buddyRequests.map(name => (name === oldKey ? newKey : name));
named.push(other);
}
}
save();
save(...named);
return null;
};
@@ -772,13 +836,18 @@ const remove = account => {
byId.delete(account.id);
savedState.delete(account.id);
retire(key);
const named = [];
for (const other of byId.values()) {
other.tradeOffers = other.tradeOffers.filter(offer => offer.fromId !== account.id);
other.buddies = other.buddies.filter(name => name !== key);
other.blocked = other.blocked.filter(name => name !== key);
other.buddyRequests = other.buddyRequests.filter(name => name !== key);
if (other.tradeOffers.some(offer => offer.fromId === account.id)
|| [other.buddies, other.blocked, other.buddyRequests].some(list => list.includes(key))) {
other.tradeOffers = other.tradeOffers.filter(offer => offer.fromId !== account.id);
other.buddies = other.buddies.filter(name => name !== key);
other.blocked = other.blocked.filter(name => name !== key);
other.buddyRequests = other.buddyRequests.filter(name => name !== key);
named.push(other);
}
}
save();
save(...named);
console.log(`[accounts] deleted "${account.username}" (id ${account.id})`);
};
+1 -1
View File
@@ -105,7 +105,7 @@ const grant = (account, defId) => {
}
const achievement = {inv: account.nextInv++, def: def.id};
account.achievements.push(achievement);
accounts.save();
accounts.save(account);
const session = findOnline(account.username);
if (session) {
if (account.userVars[def.userVarRef] === undefined) {
+3 -3
View File
@@ -99,7 +99,7 @@ const give = body => {
if (!item) {
return {status: 409, body: {error: "That inventory is full"}};
}
accounts.save();
accounts.save(account);
if (session) {
sendClothingAdded(session, item);
}
@@ -123,7 +123,7 @@ const give = body => {
account.finderGiven[key] = {count: ((account.finderGiven[key] || {}).count || 0) + 1, at: Math.floor(Date.now() / 1000)};
const kept = Object.entries(account.finderGiven).sort((one, other) => other[1].at - one[1].at).slice(0, MAX_FAVOURITES);
account.finderGiven = Object.fromEntries(kept);
accounts.save();
accounts.save(account);
return {status: 200, body: {ok: true, online: Boolean(session)}};
};
@@ -240,7 +240,7 @@ const handle = async (route, params, body, from) => {
const result = accounts.register(username, password, {type: avatarType});
if (result.account) {
result.account.agreed = {version: config.termsVersion, at: Math.floor(Date.now() / 1000)};
accounts.save();
accounts.save(result.account);
}
// the client signs in straight after, and is not asked again.
return result.error ? {status: 400, body: {error: result.error}}
+1 -1
View File
@@ -59,7 +59,7 @@ const handlers = {
for (const found of session.account.adoptAPets) {
found.seen = found.seen || seen.has(found.def);
}
accounts.save();
accounts.save(session.account);
},
};
+2 -2
View File
@@ -82,7 +82,7 @@ module.exports = ({enterRoom, joinRoom, tell}) => {
avatar.questXp = before + amount;
avatar.questLevel = levelFor(avatar.questXp);
if (amount > 0) {
accounts.save();
accounts.save(session.account);
}
q.send("quxp", amount, avatar.questXp, level, avatar.questLevel, percent(avatar.questXp), actor);
if (avatar.questLevel > level) {
@@ -121,7 +121,7 @@ module.exports = ({enterRoom, joinRoom, tell}) => {
const {account} = session;
account.currency.gems = (account.currency.gems || 0) + amount;
achievements.currencyChanged(account, "gems", amount);
accounts.save();
accounts.save(account);
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
},
};
+4 -4
View File
@@ -78,7 +78,7 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
// (accounts.freeAvatarSlot).
const avatar = accounts.newAvatar({perUserAvId: account.nextInv++, avInvId: accounts.freeAvatarSlot(account)}, `${name1}|${name2}|${name3}`, type, customAvId);
account.avatars.push(avatar);
accounts.save();
accounts.save(account);
session.sendXt("aa", -1, 1, avatar.perUserAvId, avatar.avInvId);
},
@@ -93,7 +93,7 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
return;
}
account.activeAvatar = avatar.perUserAvId;
accounts.save();
accounts.save(account);
const messageRoom = session.room ? session.room.id : -1;
const common = [1, session.id, avatar.perUserAvId, avatar.avInvId, avatar.customAvId, avatar.type, ...avatar.colors, avatar.name];
session.sendXt("as", messageRoom, ...common, avatar.petInvId, avatar.questLevel || 0);
@@ -116,7 +116,7 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
for (const item of account.items) {
item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId);
}
accounts.save();
accounts.save(account);
session.sendXt("ak", -1, 1, 0);
},
@@ -134,7 +134,7 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
if (tagChanged) {
session.account.nameBarData = nameBarData;
}
accounts.save();
accounts.save(session.account);
session.sendXt("ap", -1, 1);
refreshForOthers(session);
if (tagChanged) {
+6 -6
View File
@@ -105,7 +105,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
else if (!account.buddies.includes(key(target))) {
if (!target.buddyRequests.includes(key(account))) {
target.buddyRequests.push(key(account));
accounts.save();
accounts.save(account, target);
}
if (targetSession) {
targetSession.sendXt("ba", -1, REQUEST_INCOMING, account.username, USERNAME_SHOWN);
@@ -122,7 +122,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
return;
}
account.buddyRequests = account.buddyRequests.filter(name => name !== key(requester));
accounts.save();
accounts.save(account);
const requesterSession = findOnline(requester.username);
if (accept !== "1" || account.buddies.includes(key(requester))
|| account.buddies.length >= MAX_BUDDIES || requester.buddies.length >= MAX_BUDDIES) {
@@ -135,7 +135,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
requester.buddies.push(key(account));
achievements.add(account, achievements.VARS.buddiesAdded);
achievements.add(requester, achievements.VARS.buddiesAdded);
accounts.save();
accounts.save(account, requester);
sendStatus(session, requester, STATUS_UPDATE);
if (requesterSession) {
sendStatus(requesterSession, account, STATUS_ACCEPTED_YOUR_REQUEST);
@@ -149,7 +149,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
if (other) {
account.buddies = account.buddies.filter(name => name !== key(other));
other.buddies = other.buddies.filter(name => name !== key(account));
accounts.save();
accounts.save(account, other);
const otherSession = findOnline(other.username);
if (otherSession) {
otherSession.sendXt("bd", -1, account.username);
@@ -165,7 +165,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
const added = other && other !== account && !account.blocked.includes(key(other)) && account.blocked.length < MAX_BLOCKED;
if (added) {
account.blocked.push(key(other));
accounts.save();
accounts.save(account);
}
session.sendXt("bb", -1, username, other && other !== account && account.blocked.includes(key(other)) ? 1 : 0);
if (added) {
@@ -178,7 +178,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
const other = accounts.byName(username);
const removed = other && account.blocked.includes(key(other));
account.blocked = account.blocked.filter(name => name !== String(username).toLowerCase());
accounts.save();
accounts.save(account);
session.sendXt("bu", -1, username, 1);
if (removed) {
onUnblocked(session, other);
+5 -1
View File
@@ -171,4 +171,8 @@ const cached = async asked => {
}
};
module.exports = {get, cached, hashName, hashedPath};
// whether the official CDN said it has no such file (a 404 or 403 when it
// was asked), as against one not asked for yet or not fetched just now.
const knownMissing = asked => missing.has(clean(asked));
module.exports = {get, cached, knownMissing, hashName, hashedPath};
+74
View File
@@ -0,0 +1,74 @@
# The server's chat filter (lib/chatfilter.js): typed chat, Jam-a-Gram
# messages, Jammer Wall posts and bios. A message that breaks a rule here
# reaches nobody, and its sender is told it was not sent (a bio is not
# saved, and one saved before is not shown). Players cannot turn this
# off (unlike the client's own filter). It is read again when this file
# changes: no restart needed.
#
# One rule to a line; lines starting with # are comments. Capitals do not
# matter. Messages are read the way people dodge filters: digits and signs
# standing in for letters (4ss, a$$, n00b), letters drawn out (fuuuck), and
# words spelled out a letter at a time (f u c k, f.u.c.k).
#
# word that word on its own ("ass", not "class" or "assume")
# word* any word starting with it ("fuck*": fucking, fucker)
# *word* any word with it anywhere inside (for words that never
# turn up inside innocent ones)
# two words those words one after the other
# a|b|c any one of them
# a + b a, then b as the very next word
# a .. b a, then b at most 4 words later ("send .. nudes" catches
# "send me some nudes", but not "nudes, send")
# a & b both somewhere in the same message, in any order
# ? any one word (a name: "fuck + ? + ass" catches
# "fuck johns ass")
# !word in a | list: but not this word ("?|!it" is any word
# but "it"). A slot of only these takes up no word:
# "a + !up" is a, not followed by "up" (or ending there)
#
# These combine: "fuck|screw + you|u + in|up + the|your + ass" is one rule.
# Apostrophes are dropped before matching, so write "ill" for "i'll".
# Prefer + over .. and & : the looser the rule, the more ordinary messages it
# catches by accident ("fuck .. you" would also catch "i dont give a fuck
# about you").
# --- Slurs -------------------------------------------------------------------
*nigger*
*faggot*
# --- Sexual talk aimed at someone ---------------------------------------------
# Aimed at anyone: these use ? for the person, so names are caught too.
# "Not a person" words (it, this, up, off...) are left out with !, so
# "gonna fuck this up" and "fuck it" go through.
# "fuck you in the ass", "ill fuck john in the ass", "bang her up the butt".
fuck*|screw|bang|rape*|hump*|pound|breed .. in|up|on + the|your|ur|his|her|their|my|ma|yo|that + ass|butt|booty|pussy|dick|cock|hole|asshole|mouth|throat|vagina
# "fuck johns ass", "fuck your pussy", "eat her pussy".
fuck*|screw|bang|rape*|hump*|pound|breed|eat + ?|!the|!a|!this|!that + ass|butt|booty|pussy|dick|cock|tits|titties|boobs|hole|asshole|vagina|penis|clit
# "fuck pussy", "suck dick", "eat pussy".
fuck*|eat|suck*|lick* + pussy|dick|cock|tits|titties|boobs|clit|penis|vagina|nipples|dih
# "fuck you hard", "ill bang john raw". Plain "fuck you" is an insult and stays.
fuck*|screw|bang|rape*|hump*|pound|breed + ?|!this|!that|!it|!the|!a|!up|!off + hard|harder|raw|deep|senseless
# Saying what you'll do to someone: "ill fuck you", "im gonna fuck john",
# "i wanna bang her". Not "ill fuck him up" (a threat, not sex) or "gonna
# fuck this level up".
ill|imma|ima|gonna|gunna|wanna|lemme|let me|tryna|finna|want to|going to|i will|i want to|i would|id|lets + fuck|screw|bang|rape|hump|breed + ?|!up|!off|!around|!it|!this|!that|!with|!over|!everything|!everyone|!something|!shit|!myself|!yourself|!themselves|!the|!a|!all|!things|!stuff + !up|!off|!over|!shit
# Asking to: "wanna fuck?", "lets bang". Not "wanna fuck around".
wanna|want to|lets|can we|do you want to + fuck|bang|screw + !up|!off|!around|!with|!this|!that|!it|!over|!shit|!things|!everything
# Asking for or offering sex acts: "suck my dick", "lick johns pussy",
# "grab her ass".
suck*|lick*|blow|ride|touch|rub|finger*|jerk|stroke|grab|squeeze + ?|!the|!a|!some|!these|!those|!all + dick|cock|pussy|tits|titties|boobs|balls|ass|butt|booty|nipples|clit|penis|vagina|dih
# Asking for pictures: "send me some nudes", "show me ur tits".
send|show|see|sending|post .. nudes|noods|nude|naked|tits|titties|boobs|pussy|dick|cock|nipples|penis|vagina
# Asking for sex: "wanna have sex", "lets cyber", "sex with john".
wanna|want to|lets|can we|have|having|do you want to + sex|cyber|cybersex|seks|secks
sex|cyber|cybersex + with + ?
sext|sexting|cybersex
# "cum on you", "cum inside her", "nut in ur mouth".
cum|cumming|jizz + on|in|inside|all over + ?
nut|nutting + on|in|inside|all over + you|u|ur|your|my|me|her|his|him|them
# Sex acts and porn words that have no everyday use in this game.
blowjob*|handjob*|rimjob*|deepthroat*|cumshot*|creampie*|gangbang*|threesome*|orgasm*|masturbat*|jerk off|jack off|jerking off|jacking off
porn*|hentai|rule34|r34|onlyfans|nudes|noods|dildo*|vibrator*|horny|hornie|erection|boner
# Roleplay asks: "wanna erp", "dm me for erp".
erp & wanna|want|lets|dm|pm|anyone
+174
View File
@@ -0,0 +1,174 @@
"use strict";
const fs = require("fs");
const path = require("path");
// the server's own filter for what players write to each other: typed chat,
// Jam-a-Gram messages, Jammer Wall posts and bios. unlike the chat filter in
// the client (the player's to set, or turn off), this one cannot be turned off,
// and what it catches reaches nobody. it is meant to be narrow: slurs, and
// sexual talk aimed at someone, never swearing as such ("fuck" is fine,
// "i'll fuck you in the ass" is not). the rules are lib/chat-filter.txt,
// read again when it changes; the file says how they are written.
const RULES_FILE = path.join(__dirname, "chat-filter.txt");
// for "a .. b": how many words may come between the two ("a + b": none)
const MAX_GAP = 4;
// letters written as digits or signs, as the client's filter reads them
// (AJClient.filterText), plus "@" and "$".
const STAND_INS = {0: "o", 1: "i", 3: "e", 4: "a", 5: "s", 7: "t", "@": "a", $: "s"};
// A letter drawn out three times or more ("fuuuck") is read as the word
// with every run of letters made one, and compared that way: a word written
// plainly is compared as it is ("ass" is not "as").
const squash = word => word.replace(/(.)\1+/g, "$1");
const stretched = word => /(.)\1\1/.test(word);
// the words of a message as compared: small letters, apostrophes dropped
// ("i'll" is "ill"), stand-ins read as the letters they are, split at
// anything else. a word that is only digits is a number and goes. three or
// more single letters in a row ("f u c k", "f.u.c.k") are read as one word.
const wordsOf = text => {
const words = String(text).toLowerCase().replace(/['\u2019`]/g, "")
.split(/[^a-z0-9@$]+/).filter(word => word && !/^\d+$/.test(word))
.map(word => word.replace(/[0-9@$]/g, sign => STAND_INS[sign] || "")).filter(Boolean);
const joined = [];
for (let i = 0; i < words.length;) {
let end = i;
while (end < words.length && words[end].length === 1) {
end++;
}
if (end - i >= 3) {
joined.push(words.slice(i, end).join(""));
i = end;
}
else {
joined.push(words[i]);
i++;
}
}
return joined;
};
// one word of a rule: {text, start, inside, any}. "word" is that word,
// "word*" any word starting with it, "*word*" any word with it anywhere
// inside, "?" any word at all.
const patternOf = token => {
if (token === "?") {
return {any: true};
}
const inside = token.length > 2 && token.startsWith("*") && token.endsWith("*");
const start = !inside && token.endsWith("*");
const text = token.replace(/^\*|\*$/g, "").toLowerCase().replace(/[0-9@$]/g, sign => STAND_INS[sign] || "").replace(/[^a-z]/g, "");
return text ? {text, start, inside} : null;
};
const fits = (word, pattern) => {
if (pattern.any) {
return true;
}
const forms = stretched(word) ? [word, squash(word)] : [word];
const wanted = form => (form === word ? pattern.text : squash(pattern.text));
return forms.some(form => (pattern.inside ? form.includes(wanted(form))
: pattern.start ? form.startsWith(wanted(form)) : form === wanted(form)));
};
// A rule: clauses joined by " & ", all of which must be found in the
// message; a clause: slots in order, joined by " + " (the next word) or
// " .. " (at most MAX_GAP words later), each slot {choices, gap}, its gap
// being how far after the one before it may start; a slot's choices are
// joined by "|", and a choice is one word, or words that follow each other.
// a choice written "!word" is one the slot must not be: "?|!it" is any word
// but "it". A slot of only those takes up no word: "a + !up" is "a", not
// followed by "up" (or at the end of the message).
const parse = line => line.split(/\s+&\s+/).map(clause => {
const parts = clause.split(/\s+(\.\.|\+)\s+/);
const slots = [];
for (let i = 0; i < parts.length; i += 2) {
const written = parts[i].split("|").map(choice => choice.trim());
const wordsIn = list => list.map(choice => choice.split(/\s+/).map(patternOf)).filter(choice => choice.length > 0 && choice.every(Boolean));
const choices = wordsIn(written.filter(choice => !choice.startsWith("!")));
const not = wordsIn(written.filter(choice => choice.startsWith("!")).map(choice => choice.slice(1)));
slots.push({choices, not, gap: parts[i - 1] === "+" ? 0 : MAX_GAP});
}
return slots;
});
// where in `words` a slot's choice starts at `at`: the index after it, or -1.
const startsWith = (words, at, choice) => at + choice.length <= words.length && choice.every((pattern, i) => fits(words[at + i], pattern));
const slotAt = (words, at, slot) => {
if (slot.not.some(choice => startsWith(words, at, choice))) {
return -1;
}
for (const choice of slot.choices) {
if (startsWith(words, at, choice)) {
return at + choice.length;
}
}
return -1;
};
const clauseFrom = (words, slots, from, to) => {
if (slots.length === 0) {
return true;
}
if (slots[0].choices.length === 0) {
return !slots[0].not.some(choice => startsWith(words, from, choice)) && clauseFrom(words, slots.slice(1), from, from + (slots.length > 1 ? slots[1].gap : 0));
}
for (let at = from; at <= Math.min(to, words.length - 1); at++) {
const end = slotAt(words, at, slots[0]);
if (end !== -1 && clauseFrom(words, slots.slice(1), end, end + (slots.length > 1 ? slots[1].gap : 0))) {
return true;
}
}
return false;
};
let kept = {mtime: -1, rules: []};
const rules = () => {
let mtime = 0;
try {
mtime = fs.statSync(RULES_FILE).mtimeMs;
}
catch (err) {
return [];
}
if (kept.mtime !== mtime) {
const lines = fs.readFileSync(RULES_FILE, "utf8").split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith("#"));
const parsed = [];
for (const line of lines) {
const clauses = parse(line);
if (clauses.every(clause => clause.length > 0 && clause.every(slot => slot.choices.length > 0 || slot.not.length > 0) && clause[0].choices.length > 0)) {
parsed.push({line, clauses});
}
else {
console.log(`[filter] lib/chat-filter.txt: a rule that could not be read was left out: ${line}`);
}
}
kept = {mtime, rules: parsed};
console.log(`[filter] ${parsed.length} rules`);
}
return kept.rules;
};
// the rule a message breaks (its line in the file), or null.
const broken = text => {
const words = wordsOf(text);
if (words.length === 0) {
return null;
}
const rule = rules().find(candidate => candidate.clauses.every(clause => clauseFrom(words, clause, 0, words.length - 1)));
return rule ? rule.line : null;
};
// the game's own warning screen, over the game, for ten seconds
// (FacilitatorXtCommManager, "fw" of facilitatorDisciplineResponse). its
// kind picks the picture and the words: 3 "Personal Information", 5
// "Bullying", 11 "Scamming", 0 a short "Inappropriate Chat", and this one
// "Inappropriate Behavior" with the game's own text ("It looks like the
// conversation you're having isn't appropriate..."). it also lets go of
// the sender's chat bubble that waits for the line.
const WARNING_BEHAVIOR = 4;
const warn = session => session.sendXt("fd", -1, "fw", WARNING_BEHAVIOR);
module.exports = {broken, warn, wordsOf};
+12 -12
View File
@@ -82,7 +82,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
item.on.push(avatar.avInvId);
}
}
accounts.save();
accounts.save(account);
// ItemXtCommManager.itemsChangedListResponse, "3" = what is worn
// changed: [3, inUse, perUserAvId, username, colour, onCount,
// offCount, (invIdx, defId)..., offInvIdx...]
@@ -134,7 +134,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
}
const items = wornItems(account, avatar).map(item => item.inv);
account.outfits = [...account.outfits.filter(entry => entry !== existing), {name, items}];
accounts.save();
accounts.save(account);
tell(session, `Outfit ${name} saved (${items.length} items).`);
return;
}
@@ -155,7 +155,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
return;
}
account.outfits = account.outfits.filter(entry => entry.name !== name);
accounts.save();
accounts.save(account);
tell(session, `Outfit ${name} deleted.`);
return;
case "list":
@@ -197,7 +197,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
item.spots = item.spots || {};
item.spots[account.activeDen] = {cat: spot.cat || 1, x: spot.x, y: spot.y, flip: spot.flip};
}
accounts.save();
accounts.save(account);
dens.sendDenItems(session);
const room = session.room && session.room.denOwner === account ? session.room : null;
for (const occupant of room ? room.sessions : []) {
@@ -220,7 +220,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
}
const items = layoutOf(account);
account.denLayouts = [...account.denLayouts.filter(entry => entry !== existing), {name, den: activeDenDef(account), items}];
accounts.save();
accounts.save(account);
tell(session, `Den layout ${name} saved (${items.length} items).`);
return;
}
@@ -269,7 +269,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
}
const missing = applyLayout(session, undo.items, false);
account.denUndo = null;
accounts.save();
accounts.save(account);
tell(session, missing ? `Your den is back as it was, apart from ${missing} items that are no longer yours.` : "Your den is back as it was.");
return;
}
@@ -279,7 +279,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
return;
}
account.denLayouts = account.denLayouts.filter(entry => entry.name !== name);
accounts.save();
accounts.save(account);
tell(session, `Den layout ${name} deleted.`);
return;
case "list":
@@ -376,7 +376,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
const themes = require("../config.js").themes;
if (action === "random" && (choice === "on" || choice === "off")) {
account.randomTheme = choice === "on";
accounts.save();
accounts.save(account);
tell(session, account.randomTheme ? "The lands get a look picked at random each time you log in." : "The lands keep the look you choose.");
}
else if (action === "here" && session.room && !session.room.denOwner && (choice === "off" || Object.hasOwn(themes, choice))) {
@@ -386,7 +386,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
else {
account.roomThemes[session.room.base] = choice;
}
accounts.save();
accounts.save(account);
reloadRoom(session);
}
else if (action === "list") {
@@ -406,7 +406,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
}
const before = account.ecards.length;
account.ecards = account.ecards.filter(card => !card.read || card.gift);
accounts.save();
accounts.save(account);
tell(session, `${before - account.ecards.length} read Jam-A-Grams deleted. Open your mail again to see.`);
},
@@ -485,7 +485,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
}
else if (wanted.toLowerCase() === "off") {
delete account.denNames[account.activeDen];
accounts.save();
accounts.save(account);
tell(session, "This den has its usual name again.");
}
else if (isSilenced(account)) {
@@ -496,7 +496,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
}
else {
account.denNames[account.activeDen] = wanted;
accounts.save();
accounts.save(account);
tell(session, `This den is now called ${wanted}. It shows the next time someone walks in.`);
}
},
+9 -9
View File
@@ -149,7 +149,7 @@ const giveDenItem = (account, defId, version = 0) => {
}
const item = {inv: account.nextInv++, def: Number(defId), version: Number(version) || 0, spots: {}};
account.denItems.push(item);
accounts.save();
accounts.save(account);
return item;
};
@@ -167,7 +167,7 @@ const clearDen = (owner, findOnline) => {
for (const pet of petsInDen(owner)) {
delete pet.inDen;
}
accounts.save();
accounts.save(owner);
const ownerSession = findOnline(owner.username);
const room = ownerSession && ownerSession.room && ownerSession.room.denOwner === owner ? ownerSession.room : null;
for (const session of room ? room.sessions : []) {
@@ -231,7 +231,7 @@ const handlers = ({others, findOnline}) => {
account.currency[currency] -= purchase.cost;
achievements.currencyChanged(account, currency, -purchase.cost);
account.dens.push({inv: freeSlot(account, /^\d{1,3}$/.test(String(slot)) ? Number(slot) : NaN), def: purchase.defId});
accounts.save();
accounts.save(account);
session.sendXt("db", -1, 1, account.currency[currency], 0, purchase.currencyType, 0);
sendDenList(session);
};
@@ -259,7 +259,7 @@ const handlers = ({others, findOnline}) => {
masterpieces.claim(paintingId, frame);
const item = giveDenItem(account, masterpieces.DEN_ITEM, frame);
item.image = String(paintingId);
accounts.save();
accounts.save(account);
console.log(`[world] ${account.username} made masterpiece ${item.image}${masterpieces.itemApproved(item) ? "" : " (waiting for review in the admin panel)"}`);
session.sendXt("db", -1, 1, account.currency.diamonds || 0, 0, CURRENCY_DIAMONDS, item.inv);
sendDenItems(session);
@@ -289,7 +289,7 @@ const handlers = ({others, findOnline}) => {
achievements.currencyChanged(account, "gems", refund);
recycled.push(den.inv);
}
accounts.save();
accounts.save(account);
session.sendXt("dr", -1, recycled.length, account.currency.gems, ...recycled);
// the switcher empties the slot itself; the items that come back need
// the inventory's list.
@@ -418,7 +418,7 @@ const handlers = ({others, findOnline}) => {
}
applied.push(item.inv);
}
accounts.save();
accounts.save(account);
session.sendXt("dss", -1, ...applied);
if (inOwnDen(session)) {
for (const other of others(session)) {
@@ -452,7 +452,7 @@ const handlers = ({others, findOnline}) => {
account.denItems.splice(index, 1);
recycled.push(invIdx);
}
accounts.save();
accounts.save(account);
session.sendXt("dr", -1, recycled.length, account.currency.gems, ...recycled);
if (recycled.length) {
sendDenItems(session);
@@ -486,7 +486,7 @@ const handlers = ({others, findOnline}) => {
return;
}
account.activeDen = den.inv;
accounts.save();
accounts.save(account);
const avatar = activeAvatar(account);
session.sendXt("dc", -1, den.def, avatar.perUserAvId, avatar.petInvId);
// what is free and what is placed differs from den to den.
@@ -520,7 +520,7 @@ const handlers = ({others, findOnline}) => {
}
else if ([DEN_LOCKED, DEN_BUDDIES_ONLY, DEN_OPEN].includes(Number(value))) {
session.account.denPrivacy = Number(value);
accounts.save();
accounts.save(session.account);
}
},
};
+1 -1
View File
@@ -70,7 +70,7 @@ const show = (to, subject) => {
// afresh, which brings the disguise with it (`show`).
const set = (session, id, redraw) => {
session.account.disguise = id;
accounts.save();
accounts.save(session.account);
session.sendXt("dph", -1, 1, session.id, id ? 1 : 0, id || NPC_PHANTOM);
redraw(session);
};
+24 -9
View File
@@ -4,6 +4,7 @@ const fs = require("fs");
const path = require("path");
const accounts = require("./accounts.js");
const achievements = require("./achievements.js");
const chatFilter = require("./chatfilter.js");
const defpacks = require("./defpacks.js");
const dens = require("./dens.js");
const limits = require("./limits.js");
@@ -154,7 +155,7 @@ module.exports = ({findOnline, blocks}) => {
// a localization string (StartupPopups.setupGiftPopup).
const message = clean(text).replace(/^(?=[\s+-]*\d)/, "Gift: ");
deliver(to, {from: HQ_NAME, hq: true, card: art.cards[0], stamp: 0, msg: message, gift: attached});
accounts.save();
accounts.save(to);
return null;
};
@@ -165,7 +166,7 @@ module.exports = ({findOnline, blocks}) => {
return false;
}
deliver(to, {from: HQ_NAME, hq: true, card: art.cards[0], stamp: 0, msg: clean(text).replace(/^(?=[\s+-]*\d)/, "Note: "), gift: null});
accounts.save();
accounts.save(to);
return true;
};
@@ -248,6 +249,21 @@ module.exports = ({findOnline, blocks}) => {
reply(FAILED);
return;
}
// secret valentines are off on this server: the patched client no
// longer offers them, and a card asked for as one from an older copy
// is not sent with its sender's name shown instead.
if (isValentine === "1") {
reply(FAILED);
return;
}
// the server's filter (lib/chatfilter.js).
const rule = chatFilter.broken(clean(message || ""));
if (rule) {
chatFilter.warn(session);
console.log(`[filter] ${account.username} in a Jam-a-Gram to ${to.username}: "${clean(message || "")}" (${rule})`);
reply(FAILED);
return;
}
if (!mayReceiveFrom(to, account)) {
reply(NOT_ACCEPTING);
return;
@@ -262,13 +278,12 @@ module.exports = ({findOnline, blocks}) => {
reply(FAILED);
return;
}
deliver(to, {from: account.username, fromId: account.id, card: Number(card), stamp: Number(stamp), msg: clean(message || ""), gift,
...(isValentine === "1" ? {secret: true} : {})});
deliver(to, {from: account.username, fromId: account.id, card: Number(card), stamp: Number(stamp), msg: clean(message || ""), gift});
achievements.add(account, achievements.VARS.jamAGramsSent);
if (gift) {
achievements.add(account, achievements.VARS.giftsSent);
}
accounts.save();
accounts.save(account, to);
reply(SENT);
},
@@ -277,7 +292,7 @@ module.exports = ({findOnline, blocks}) => {
const card = session.account.ecards.find(candidate => candidate.id === Number(msgId));
if (card) {
card.read = true;
accounts.save();
accounts.save(session.account);
}
session.sendXt("er", -1, msgId, card ? 1 : 0);
},
@@ -288,7 +303,7 @@ module.exports = ({findOnline, blocks}) => {
const {account} = session;
const before = account.ecards.length;
account.ecards = account.ecards.filter(card => card.id !== Number(msgId));
accounts.save();
accounts.save(account);
session.sendXt("ed", -1, 1, before - account.ecards.length, ...(before === account.ecards.length ? [] : [msgId]));
},
@@ -314,7 +329,7 @@ module.exports = ({findOnline, blocks}) => {
if (accept === "1") {
giveGift(session, gift);
}
accounts.save();
accounts.save(session.account);
session.sendXt("eg", -1, msgId, 1);
},
@@ -324,7 +339,7 @@ module.exports = ({findOnline, blocks}) => {
const valid = [FROM_EVERYONE, FROM_BUDDIES, FROM_NOBODY].includes(value);
if (valid) {
session.account.ecardPrivacy = value;
accounts.save();
accounts.save(session.account);
}
session.sendXt("ei", -1, valid ? 1 : 0);
},
+50 -12
View File
@@ -151,6 +151,7 @@ const send = (res, status, body, type = "application/json") => {
const TEN_MINUTES_MS = 600000;
const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS);
const searches = limits.limiter(120, 60000); // item finder searches, per address
const MISSING_ASSET_SECONDS = 600; // how long a client may keep the CDN's "no such file"
const cacheMisses = limits.limiter(config.cacheMissesPerTenMinutes, TEN_MINUTES_MS); // files fetched from the official CDN for one address
const errorReports = limits.limiter(config.errorReportsPerMinute, 60000);
const paintingPosts = limits.limiter(60, TEN_MINUTES_MS); // per address; each also needs a token from the game
@@ -169,6 +170,27 @@ const keepClientError = text => {
.then(size => (size < MAX_CLIENT_ERROR_FILE ? fs.promises.appendFile(CLIENT_ERROR_FILE, text) : null))
.catch(() => {});
};
// the same error from many clients (one broken item, met by everyone who
// sees it) is written once in REPEAT_WINDOW_MS, and the next time after that
// with how many there were between: a log, and a thread that waits for it,
// had a stack of twenty lines several times a second. null for one to leave
// out; else what to add to its line.
const REPEAT_WINDOW_MS = 600000;
const MAX_REMEMBERED_ERRORS = 1000;
const recentErrors = new Map(); // section and message -> {at, more}
const repeatedError = text => {
const seen = recentErrors.get(text);
if (seen && Date.now() - seen.at < REPEAT_WINDOW_MS) {
seen.more++;
return null;
}
recentErrors.delete(text);
if (recentErrors.size >= MAX_REMEMBERED_ERRORS) {
recentErrors.delete(recentErrors.keys().next().value);
}
recentErrors.set(text, {at: Date.now(), more: 0});
return seen && seen.more > 0 ? `\n\t(and ${seen.more} more like it in the ${Math.round(REPEAT_WINDOW_MS / 60000)} minutes before)` : "";
};
const THEMED_ROOM = /^(\d+)\/roomDefs\/theme_(\d+)\/(.+)$/;
// the web pages, as against what the game and the client load
@@ -348,7 +370,7 @@ const renameAndSignIn = (res, body, from) => {
delete account.nameRejected;
manage.forget(account);
accounts.recordLogin(account, "launcher", from.address);
accounts.save();
accounts.save(account);
console.log(`[accounts] a rejected username was replaced by "${account.username}"`);
accounts.setLoginChoices(account, body.login_choices);
const token = accounts.issueToken(account);
@@ -384,7 +406,7 @@ const authenticate = async (req, res, from) => {
const tried = accounts.byName(accountKey);
if (tried) {
accounts.recordLogin(tried, "launcher", from.address, false);
accounts.save();
accounts.save(tried);
}
}
// error_code 100 = expired refresh token, 101 = wrong credentials
@@ -429,7 +451,7 @@ const authenticate = async (req, res, from) => {
if (!totp.verify(account, String(body.totp))) {
failuresByAddress.record(from.key);
accounts.recordLogin(account, "launcher", from.address, false);
accounts.save();
accounts.save(account);
send(res, 401, {error_code: 101, error: "totp_wrong", captcha_pass: captcha.issuePass(account, from)});
return;
}
@@ -440,13 +462,13 @@ const authenticate = async (req, res, from) => {
// its username was rejected: a new one first (above). the official
// launcher shows this as a wrong password; the account page asks too.
if (account.nameRejected) {
accounts.save(); // a two-step code just used stays used
accounts.save(account); // a two-step code just used stays used
send(res, 401, {error_code: 101, error: "name_rejected", rename_ticket: renameTicket(account, deviceToken)});
return;
}
if (!byRefresh) {
accounts.recordLogin(account, "launcher", from.address);
accounts.save();
accounts.save(account);
}
// the custom client's advanced settings; the official launcher sends none.
accounts.setLoginChoices(account, body.login_choices);
@@ -687,9 +709,12 @@ const handle = async (req, res) => {
const section = String(report.section).slice(0, 20).replace(/[^\w-]/g, "?");
const trace = message.startsWith("media ");
if (trace ? config.logPackets : from.local || errorReports.allow(from.key)) {
console.log(`[${trace ? "client-trace" : "client-error"}] (${section}) ${message}`);
if (!trace) {
keepClientError(`${new Date().toISOString()} (${section}) ${message}\n`);
const again = trace ? "" : repeatedError(`${section} ${message}`);
if (again !== null) {
console.log(`[${trace ? "client-trace" : "client-error"}] (${section}) ${message}${again}`);
if (!trace) {
keepClientError(`${new Date().toISOString()} (${section}) ${message}${again}\n`);
}
}
}
send(res, 200, {});
@@ -790,7 +815,15 @@ const handle = async (req, res) => {
const body = (themed && Object.values(config.themes).some(theme => theme.build === Number(themed[2])) && await cdn.get(`${themed[2]}/roomDefs/${themed[3]}`, mayFetch))
|| await cdn.get(themed ? `${themed[1]}/roomDefs/${themed[3]}` : relPath, mayFetch);
if (!body) {
console.log(`[http] 404 ${url.pathname}`);
// one the CDN does not have is asked for again and again (the same few
// hundred, by every client that meets them): its client may keep the
// answer a while, and it was logged when the CDN said so ([cdn] 404).
if (cdn.knownMissing(themed ? `${themed[1]}/roomDefs/${themed[3]}` : relPath)) {
res.setHeader("Cache-Control", `public, max-age=${MISSING_ASSET_SECONDS}`);
}
else {
console.log(`[http] 404 ${url.pathname}`);
}
send(res, 404, "Not found", "text/plain");
return;
}
@@ -815,12 +848,15 @@ const start = () => new Promise((resolve, reject) => {
: http.createServer(onRequest);
// nobody gets to hold a request open by trickling it in, nor a reply by
// never reading it; and there is an end to how many connections there
// may be, in all and from one address.
// may be, in all and from one address. a proxy in front (nginx) keeps
// its own count of those; its connections here are not counted, since
// turning them away only had it fail the requests of players it had
// already let in, who then asked again.
server.requestTimeout = 30000;
server.headersTimeout = 15000;
server.timeout = config.httpSocketTimeoutMs;
server.maxConnections = config.maxHttpConnections;
const open = new Map(); // address, as limits count it -> connections
let openInAll = 0;
server.on("connection", socket => {
const address = limits.key(socket.remoteAddress);
// behind a proxy every connection is the proxy's own.
@@ -828,12 +864,14 @@ const start = () => new Promise((resolve, reject) => {
return;
}
const count = (open.get(address) || 0) + 1;
if (count > config.maxHttpConnectionsPerAddress) {
if (count > config.maxHttpConnectionsPerAddress || openInAll >= config.maxHttpConnections) {
socket.destroy();
return;
}
open.set(address, count);
openInAll++;
socket.once("close", () => {
openInAll--;
const left = open.get(address) - 1;
if (left > 0) {
open.set(address, left);
+4 -4
View File
@@ -48,7 +48,7 @@ module.exports = ({others, sendItemList}) => {
achievements.currencyChanged(account, currency, -purchase.cost);
achievements.add(account, achievements.VARS.clothesBought);
const item = addClothing(account, def.id, colors[colorIndex]);
accounts.save();
accounts.save(account);
sendClothingAdded(session, item);
session.sendXt("ib", -1, 1, shopId, account.currency[currency], purchase.currencyType);
},
@@ -95,7 +95,7 @@ module.exports = ({others, sendItemList}) => {
};
const off = ids.slice(onCount).filter(invIdx => setWorn(invIdx, false) !== null);
const on = ids.slice(0, onCount).map(invIdx => [invIdx, setWorn(invIdx, true)]).filter(([, def]) => def !== null);
accounts.save();
accounts.save(account);
// ItemXtCommManager.itemUseResponse
session.sendXt("iu", -1, 1);
// the reply only closes the editor. the animal in the room is redrawn
@@ -127,7 +127,7 @@ module.exports = ({others, sendItemList}) => {
account.currency[received] = (account.currency[received] || 0) + def.result;
achievements.currencyChanged(account, paid, -def.cost);
achievements.currencyChanged(account, received, def.result);
accounts.save();
accounts.save(account);
// ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason]
session.sendXt("cu", -1, def.resultType, account.currency[received], 0);
session.sendXt("ce", -1, 1, account.currency[paid]);
@@ -154,7 +154,7 @@ module.exports = ({others, sendItemList}) => {
account.items.splice(index, 1);
recycled.push(invIdx);
}
accounts.save();
accounts.save(account);
session.sendXt("ir", -1, recycled.length, account.currency.gems || 0, ...recycled);
if (recycled.length) {
sendClothingRemoved(session, recycled);
+4 -1
View File
@@ -5,6 +5,7 @@
const MAX_LINES = 5000;
const MAX_LINE_LENGTH = 2000;
const TRIM_BATCH = 1000;
const lines = []; // {id, time, text}
let nextId = 1;
@@ -15,7 +16,9 @@ const capture = original => (...args) => {
for (const line of text.split("\n")) {
lines.push({id: nextId++, time: Date.now(), text: line.slice(0, MAX_LINE_LENGTH)});
}
if (lines.length > MAX_LINES) {
// trimmed a batch at a time: trimming a line at a time moved all the
// others along for every line printed.
if (lines.length > MAX_LINES + TRIM_BATCH) {
lines.splice(0, lines.length - MAX_LINES);
}
};
+25 -17
View File
@@ -11,6 +11,7 @@ const badges = require("./badges.js");
const bans = require("./bans.js");
const captcha = require("./captcha.js");
const chatlog = require("./chatlog.js");
const chatFilter = require("./chatfilter.js");
const erase = require("./erase.js");
const masterpieces = require("./masterpieces.js");
const defpacks = require("./defpacks.js");
@@ -248,7 +249,7 @@ const act = (account, body, req, from, res) => {
return {error: NAME_ERRORS[problem] || NAME_ERRORS.invalid_username};
}
delete account.nameRejected;
accounts.save();
accounts.save(account);
console.log(`[account] a rejected username was replaced by "${account.username}" from ${from.address}`);
return {ok: "Saved."};
}
@@ -291,7 +292,7 @@ const act = (account, body, req, from, res) => {
accounts.revokeTokens(account);
world.moderation.actions.kick(account);
}
accounts.save();
accounts.save(account);
console.log(`[account] "${account.username}" ${account.locked ? "locked" : "unlocked"} from ${from.address}`);
return {ok: account.locked ? "Locked." : "Unlocked."};
}
@@ -300,7 +301,7 @@ const act = (account, body, req, from, res) => {
return {error: "Unknown setting."};
}
account.features[body.feature] = body.on;
accounts.save();
accounts.save(account);
return {ok: "Saved."};
}
// two-step sign-in (lib/totp.js). turning it on: the password again,
@@ -314,17 +315,17 @@ const act = (account, body, req, from, res) => {
return {error: "Wrong password."};
}
const setup = totp.begin(account);
accounts.save();
accounts.save(account);
return {ok: "Scan the code.", setup};
}
case "twoStepConfirm": {
const recovery = totp.confirm(account, body.code);
if (!recovery) {
accounts.save();
accounts.save(account);
return {error: "Wrong code."};
}
accounts.revokeTokens(account);
accounts.save();
accounts.save(account);
console.log(`[account] "${account.username}" turned two-step sign-in on from ${from.address}`);
return {ok: "2FA is on.", recovery};
}
@@ -337,18 +338,18 @@ const act = (account, body, req, from, res) => {
return {error: "Wrong password."};
}
if (!totp.verify(account, String(body.code || ""))) {
accounts.save();
accounts.save(account);
return {error: "Wrong code."};
}
totp.turnOff(account);
accounts.save();
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}`);
return {ok: "2FA is off."};
}
case "forgetDevices":
totp.forgetDevices(account);
accounts.save();
accounts.save(account);
return {ok: "Trusted devices forgotten."};
// their bio, for the Bio tab of their card in the game. empty takes it off.
case "bio": {
@@ -360,14 +361,21 @@ const act = (account, body, req, from, res) => {
if (bio === null) {
return {error: `At most ${badges.MAX_BIO} characters on ${badges.MAX_BIO_LINES} lines.`};
}
// the server's chat filter, as for anything else players write to
// each other (lib/chat-filter.txt).
const rule = chatFilter.broken(bio);
if (rule) {
console.log(`[filter] "${account.username}" bio not saved (${rule}): ${JSON.stringify(bio)}`);
return {error: "Your bio has words that are not allowed here."};
}
account.bio = bio;
accounts.save();
accounts.save(account);
return {ok: bio ? "Saved." : "Removed."};
}
// whether their card in the game shows how long they have played.
case "playtimePublic":
account.playtimePublic = body.on === true;
accounts.save();
accounts.save(account);
return {ok: account.playtimePublic ? "Others can see your playtime on your card." : "Your playtime is private."};
// their Discord username, for their card in the game. empty takes it off.
case "discord": {
@@ -376,7 +384,7 @@ const act = (account, body, req, from, res) => {
return {error: "Not a Discord username."};
}
account.discord = name;
accounts.save();
accounts.save(account);
return {ok: name ? "Saved." : "Removed."};
}
// the player's own words about a buddy; only they see them.
@@ -392,7 +400,7 @@ const act = (account, body, req, from, res) => {
else {
delete account.buddyNotes[key];
}
accounts.save();
accounts.save(account);
return {ok: "Saved."};
}
// blocking and unblocking, as the game's own buttons do it.
@@ -422,7 +430,7 @@ const act = (account, body, req, from, res) => {
case "signOutEverywhere":
accounts.revokeTokens(account);
totp.forgetDevices(account);
accounts.save();
accounts.save(account);
world.moderation.actions.kick(account);
signOutOthers(account, req);
return {ok: "Signed out everywhere."};
@@ -495,7 +503,7 @@ const handle = async (req, res, url, from, web) => {
failuresByAddress.record(from.key);
if (known) {
accounts.recordLogin(known, "web", from.address, false);
accounts.save();
accounts.save(known);
}
reply(401, {error: "Wrong username or password."});
return;
@@ -511,7 +519,7 @@ const handle = async (req, res, url, from, web) => {
if (!totp.verify(account, String(body.code))) {
failuresByAddress.record(from.key);
accounts.recordLogin(account, "web", from.address, false);
accounts.save();
accounts.save(account);
reply(401, {error: "Wrong code.", twoStep: true, captchaPass: captcha.issuePass(account, from)});
return;
}
@@ -520,7 +528,7 @@ const handle = async (req, res, url, from, web) => {
}
}
accounts.recordLogin(account, "web", from.address);
accounts.save();
accounts.save(account);
signIn(res, account, cookies);
reply(200, {ok: true});
return;
+7 -7
View File
@@ -271,7 +271,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
}
account.currency.gems -= CARNIVAL_COST;
achievements.currencyChanged(account, "gems", -CARNIVAL_COST);
accounts.save();
accounts.save(account);
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
game.serial2 = serial();
reply("pg", "1", hideSerial(game.serial2));
@@ -288,7 +288,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
if (tickets > 0) {
account.currency.tickets = (account.currency.tickets || 0) + tickets;
achievements.currencyChanged(account, "tickets", tickets);
accounts.save();
accounts.save(account);
session.sendXt("cu", -1, CURRENCY_TICKETS, account.currency.tickets, 0);
}
reply("gr", tickets);
@@ -315,7 +315,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
}
account.currency.gems -= CLAW_COST;
achievements.currencyChanged(account, "gems", -CLAW_COST);
accounts.save();
accounts.save(account);
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
const prizes = clawPrizes(game.def);
const won = prizes.length > 0 && Math.random() < CLAW_WIN_CHANCE;
@@ -343,7 +343,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
gd(session, game, [keep]) {
if (keep === "1" && session.gamePrize) {
sendClothingAdded(session, addClothing(session.account, session.gamePrize.def, session.gamePrize.color));
accounts.save();
accounts.save(session.account);
}
session.gamePrize = null;
},
@@ -401,7 +401,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
}
account.currency.gems -= INVASION_COST;
achievements.currencyChanged(account, "gems", -INVASION_COST);
accounts.save();
accounts.save(account);
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
const prizes = invasionPrizes();
session.prizeSerial = serial();
@@ -528,7 +528,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
if (valid) {
account.currency.gems = (account.currency.gems || 0) + amount;
achievements.currencyChanged(account, "gems", amount);
accounts.save();
accounts.save(account);
}
session.gemSerial = serial();
session.sendXt("mg", -1, session.gemSerial, 0);
@@ -547,7 +547,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
if (valid && (pet.mastery || 0) < MASTERY_FULL) {
pet.mastery = Math.min(MASTERY_FULL, (pet.mastery || 0) + amount);
nowFull = pet.mastery === MASTERY_FULL;
accounts.save();
accounts.save(account);
}
session.masterySerial = serial();
session.sendXt("ma", -1, session.masterySerial, nowFull ? 1 : 0);
+7 -7
View File
@@ -100,7 +100,7 @@ module.exports = ({findOnline}) => {
target.banReason = bans.reasonText(reason);
target.bannedBy = by;
target.bannedAt = now();
accounts.save();
accounts.save(target);
bans.record({account: target, action: "ban", seconds: duration, reason: target.banReason, by});
const session = findOnline(target.username);
if (session) {
@@ -116,7 +116,7 @@ module.exports = ({findOnline}) => {
delete target.banReason;
delete target.bannedBy;
delete target.bannedAt;
accounts.save();
accounts.save(target);
if (was) {
bans.record({account: target, action: "unban", by});
}
@@ -129,7 +129,7 @@ module.exports = ({findOnline}) => {
return false;
}
target.banReason = bans.reasonText(reason);
accounts.save();
accounts.save(target);
bans.record({account: target, action: "reason", reason: target.banReason, by});
return true;
},
@@ -137,7 +137,7 @@ module.exports = ({findOnline}) => {
// duration in seconds, PERMANENT, or 0 to lift
silence(target, duration) {
target.silencedUntil = duration === PERMANENT ? PERMANENT : (duration > 0 ? now() + duration : 0);
accounts.save();
accounts.save(target);
const session = findOnline(target.username);
if (session) {
// minutes, negative for "until further notice", 0 for "you may type again"
@@ -152,7 +152,7 @@ module.exports = ({findOnline}) => {
rejectName(target, by = "") {
target.nameRejected = {by, at: now()};
accounts.revokeTokens(target);
accounts.save();
accounts.save(target);
actions.kick(target);
return true;
},
@@ -160,7 +160,7 @@ module.exports = ({findOnline}) => {
// taken back: the name will do after all.
acceptName(target) {
delete target.nameRejected;
accounts.save();
accounts.save(target);
return true;
},
@@ -183,7 +183,7 @@ module.exports = ({findOnline}) => {
const before = target.currency[name] || 0;
target.currency[name] = Math.max(0, before + amount);
achievements.currencyChanged(target, name, target.currency[name] - before);
accounts.save();
accounts.save(target);
const session = findOnline(target.username);
if (session) {
// ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason]
+4 -4
View File
@@ -239,7 +239,7 @@ const act = (mod, target, body) => {
return {ok: `${name} keeps the name.`};
case "clearBio":
target.bio = "";
accounts.save();
accounts.save(target);
return {ok: "Bio cleared."};
// the address they last signed in from, for good. which address that
// is, the moderator is not told.
@@ -322,7 +322,7 @@ const handle = async (req, res, url, from, web) => {
failuresByAddress.record(from.key);
if (known && !account) {
accounts.recordLogin(known, "mod", from.address, false);
accounts.save();
accounts.save(known);
}
reply(401, {error: "Wrong username or password."});
return;
@@ -338,12 +338,12 @@ const handle = async (req, res, url, from, web) => {
if (!totp.verify(account, String(body.code || ""))) {
failuresByAddress.record(from.key);
accounts.recordLogin(account, "mod", from.address, false);
accounts.save();
accounts.save(account);
reply(401, {error: "Wrong code."});
return;
}
accounts.recordLogin(account, "mod", from.address);
accounts.save();
accounts.save(account);
for (const [hash, session] of sessions) {
if (session.expiry < Date.now()) {
sessions.delete(hash);
+8 -8
View File
@@ -350,7 +350,7 @@ const gift = (account, body) => {
if (body.kind === "adopt") {
const ids = body.id === "all" ? defpacks.adoptAPetIds() : [body.id];
const given = ids.filter(id => adopt.give(account, id)).length;
accounts.save();
accounts.save(account);
return given ? {ok: `${name} has ${given} more on their Adopt-A-Pet checklist (it shows after their next login).`}
: {error: "No such Adopt-A-Pet, or they already have it."};
}
@@ -383,7 +383,7 @@ const act = (account, body) => {
// they cannot.
case "unlock":
account.locked = false;
accounts.save();
accounts.save(account);
return {ok: `${name} is unlocked.`};
// for a player who lost their phone and their recovery codes: their
// password alone signs them in again.
@@ -392,7 +392,7 @@ const act = (account, body) => {
return {error: `${name} does not use 2FA.`};
}
totp.turnOff(account);
accounts.save();
accounts.save(account);
return {ok: `2FA is off for ${name}.`};
case "rename": {
world.disconnect(account);
@@ -415,7 +415,7 @@ const act = (account, body) => {
return {error: "Pick a date and time in the past."};
}
account.lastSeen = when;
accounts.save();
accounts.save(account);
return {ok: `${name} was last seen ${new Date(when * 1000).toISOString().replace("T", " ").slice(0, 16)} UTC, as far as the game knows.`};
}
// the adventure level of the animal they are using.
@@ -433,7 +433,7 @@ const act = (account, body) => {
return {error: "Unknown badge."};
}
badges.set(account, body.badges);
accounts.save();
accounts.save(account);
world.checkNameTag(account);
return {ok: account.badges.length ? `${name} has: ${badges.of(account).map(badge => badge.label).join(", ")}.` : `${name} has no badges.`};
}
@@ -445,7 +445,7 @@ const act = (account, body) => {
return {error: "Not a Discord username."};
}
account.discord = discord;
accounts.save();
accounts.save(account);
return {ok: discord ? `Discord set to "${discord}".` : "Discord cleared."};
}
// their bio, which they otherwise write on the account page; empty
@@ -456,7 +456,7 @@ const act = (account, body) => {
return {error: `At most ${badges.MAX_BIO} characters on ${badges.MAX_BIO_LINES} lines.`};
}
account.bio = bio;
accounts.save();
accounts.save(account);
return {ok: bio ? "Bio set." : "Bio cleared."};
}
case "ban": {
@@ -496,7 +496,7 @@ const act = (account, body) => {
if (body.on !== true) {
modpanel.forget(account);
}
accounts.save();
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.`};
+1 -1
View File
@@ -187,7 +187,7 @@ module.exports = ({enterRoom, findOnline, blocks}) => {
return;
}
account.currency.diamonds -= HOST_COST;
accounts.save();
accounts.save(account);
const party = {host: account, defId: def.id, name: `${name1}|${name2}|${name3}`, music: Number(music), endsAt: now() + config.partyMinutes * 60};
hosted.set(account.username.toLowerCase(), party);
console.log(`[world] ${account.username} is hosting a party (def ${def.id})`);
+6 -6
View File
@@ -100,7 +100,7 @@ module.exports = ({others, findOnline, petFields}) => {
giveCharacter(pet);
account.pets.push(pet);
achievements.set(account, achievements.VARS.pets, Math.max(Number(account.userVars[achievements.VARS.pets]) || 0, account.pets.length));
accounts.save();
accounts.save(account);
session.sendXt("pc", -1, 1, account.currency.gems || 0, 0, pet.inv, ...petFields(pet), 0);
};
@@ -147,7 +147,7 @@ module.exports = ({others, findOnline, petFields}) => {
return;
}
activeAvatar(account).petInvId = pet ? pet.inv : 0;
accounts.save();
accounts.save(account);
const messageRoom = session.room ? session.room.id : -1;
session.sendXt("ps", messageRoom, 1, session.id, pet ? pet.inv : 0);
if (session.pos) {
@@ -171,7 +171,7 @@ module.exports = ({others, findOnline, petFields}) => {
avatar.petInvId = 0;
}
}
accounts.save();
accounts.save(account);
session.sendXt("pd", -1, 1, pet.inv);
},
@@ -187,7 +187,7 @@ module.exports = ({others, findOnline, petFields}) => {
return;
}
pet.uBits = ((pet.uBits & ~MASTERY_BITS) | (item << 8)) >>> 0;
accounts.save();
accounts.save(account);
session.sendXt("pm", -1, 1, pet.inv, pet.lBits, pet.uBits, pet.eBits);
if (pet.inv === activeAvatar(account).petInvId && session.pos) {
for (const other of others(session)) {
@@ -207,7 +207,7 @@ module.exports = ({others, findOnline, petFields}) => {
return;
}
pet.name = `${name1}|${name2}`;
accounts.save();
accounts.save(account);
session.sendXt("pn", -1, 1, pet.inv, pet.name);
},
@@ -224,7 +224,7 @@ module.exports = ({others, findOnline, petFields}) => {
return;
}
pet.uBits = ((pet.uBits & 0xFFF) | (parts[0] << 12) | (parts[1] << 16) | (parts[2] << 20)) >>> 0;
accounts.save();
accounts.save(account);
session.sendXt("pi", -1, 1, account.currency.gems || 0, pet.inv, pet.lBits, pet.uBits, pet.eBits);
if (session.pos) {
for (const other of others(session)) {
+6 -6
View File
@@ -267,7 +267,7 @@ module.exports = ({findOnline, blocks}) => {
const offeredNames = toOwner.map(item => nameOf(item.type, item.entry));
note(requester.account, owner.account, wantedName, offeredNames);
note(owner.account, requester.account, offeredNames, wantedName);
accounts.save();
accounts.save(requester.account, owner.account);
requester.sendXt("ti", -1, TRADE_PROGRESS, COMPLETED, 1, ...doneFields(wantedType, toRequester),
offered.length, ...offered.flatMap(item => [doneType(item.type), item.entry.inv]));
owner.sendXt("ti", -1, TRADE_PROGRESS, COMPLETED, toOwner.length, ...toOwner.flatMap(item => doneFields(item.type, item.entry)),
@@ -308,7 +308,7 @@ module.exports = ({findOnline, blocks}) => {
account.tradeList.push({type, inv});
}
}
accounts.save();
accounts.save(account);
sendTradeList(session, account);
},
@@ -388,7 +388,7 @@ module.exports = ({findOnline, blocks}) => {
return "too_many";
}
to.tradeOffers.push({id: to.nextInv++, fromId: from.id, at: Math.floor(Date.now() / 1000), wanted: want, offered: give});
accounts.save();
accounts.save(to);
return null;
},
@@ -406,7 +406,7 @@ module.exports = ({findOnline, blocks}) => {
const given = from ? offer.offered.map(item => ({type: item.type, entry: find(from, item.type, item.inv)})) : [];
if (accept && (!from || !wanted || given.some(item => !item.entry) || blocks.either(from, account)
|| !fits(from, [offer.wanted], given) || !fits(account, given, [offer.wanted]))) {
accounts.save();
accounts.save(account);
return "gone";
}
if (accept) {
@@ -419,7 +419,7 @@ module.exports = ({findOnline, blocks}) => {
// whoever is in the game sees their inventories change.
[account, from].forEach(refresh);
}
accounts.save();
accounts.save(account, from);
return null;
},
@@ -428,7 +428,7 @@ module.exports = ({findOnline, blocks}) => {
const before = to ? to.tradeOffers.length : 0;
if (to) {
to.tradeOffers = to.tradeOffers.filter(offer => !(offer.id === Number(id) && offer.fromId === from.id));
accounts.save();
accounts.save(to);
}
return Boolean(to) && to.tradeOffers.length < before;
},
+20 -10
View File
@@ -4,6 +4,7 @@ const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const accounts = require("./accounts.js");
const chatFilter = require("./chatfilter.js");
const masterpieces = require("./masterpieces.js");
const limits = require("./limits.js");
const {isUint} = require("./player.js");
@@ -72,7 +73,7 @@ const flat = value => scalar(value) || (typeof value === "object" && !Array.isAr
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);
module.exports = ({blocks}) => {
module.exports = ({blocks, findOnline}) => {
const tokens = new Map(); // token -> {viewer: account id, owner: account id, expires}
const mayOpen = (owner, viewer) => {
@@ -150,7 +151,16 @@ module.exports = ({blocks}) => {
const put = (owner, viewer, body) => {
const colours = Array.isArray(body.ac) ? body.ac.slice(0, 3).map(String) : [];
const message = clean(body.m === undefined ? "" : body.m);
if (!message || isSilenced(viewer) || !colours.every(isUint) || !postsPerTenMinutes.allow(viewer.id)) {
// the server's filter (lib/chatfilter.js) too.
const rule = message ? chatFilter.broken(message) : null;
if (rule) {
console.log(`[filter] ${viewer.username} on ${owner.username}'s wall: "${message}" (${rule})`);
const session = findOnline(viewer.username);
if (session) {
chatFilter.warn(session);
}
}
if (!message || rule || isSilenced(viewer) || !colours.every(isUint) || !postsPerTenMinutes.allow(viewer.id)) {
// PlayerWallGui.onMessageSent: cs -1 = "could not be posted"
return {PUT: {s: false, cs: -1}};
}
@@ -177,7 +187,7 @@ module.exports = ({blocks}) => {
owner.wall.posts.push(post);
owner.wall.posts = owner.wall.posts.slice(-MAX_POSTS);
owner.wall.modified = post.t;
accounts.save();
accounts.save(owner);
return {PUT: {s: true}, x: post.x, t: post.t, GET: getReply(owner, viewer)};
};
@@ -207,7 +217,7 @@ module.exports = ({blocks}) => {
}
wall.posts = wall.posts.filter(candidate => candidate !== post && candidate.pp !== post.x);
wall.modified = Date.now();
accounts.save();
accounts.save(owner);
return {s: true};
}
case "GMB": // posts the owner chose to hide
@@ -217,7 +227,7 @@ module.exports = ({blocks}) => {
return {s: false};
}
wall.hidden = [...new Set([...wall.hidden, body.x])].slice(-MAX_HIDDEN);
accounts.save();
accounts.save(owner);
return {s: true};
case "CLW":
if (!mine) {
@@ -226,7 +236,7 @@ module.exports = ({blocks}) => {
wall.posts = [];
wall.hidden = [];
wall.modified = Date.now();
accounts.save();
accounts.save(owner);
return {s: true};
case "RMP": // masterpieces taken off the wall; there are none
case "ACK": // notifications marked as read; there are none
@@ -264,7 +274,7 @@ module.exports = ({blocks}) => {
&& mayOpen(owner, session.account) === TOKEN_OK;
if (allowed) {
owner.wall.likes = [...likes(owner), session.account.id];
accounts.save();
accounts.save(owner);
}
session.sendXt("crp", -1, allowed ? 1 : 0);
},
@@ -286,7 +296,7 @@ module.exports = ({blocks}) => {
const valid = [NOBODY, BUDDIES, EVERYONE].includes(value);
if (valid) {
session.account.wall.privacy = value;
accounts.save();
accounts.save(session.account);
}
session.sendXt("wss", -1, valid ? 1 : 0);
},
@@ -324,7 +334,7 @@ module.exports = ({blocks}) => {
}
wall.params = merged;
wall.modified = Date.now();
accounts.save();
accounts.save(session.account);
session.sendXt("wps", -1, 1);
},
@@ -333,7 +343,7 @@ module.exports = ({blocks}) => {
const owner = accounts.byName(username);
if (owner && owner !== session.account && mayOpen(owner, session.account) === TOKEN_OK) {
owner.wall.visits++;
accounts.save();
accounts.save(owner);
}
session.sendXt("wci", -1, owner ? 1 : 0);
},
+29 -14
View File
@@ -15,6 +15,7 @@ const avatarHandlers = require("./avatars.js");
const badges = require("./badges.js");
const bans = require("./bans.js");
const chatlog = require("./chatlog.js");
const chatFilter = require("./chatfilter.js");
const buddyModule = require("./buddies.js");
const dens = require("./dens.js");
const disguises = require("./disguises.js");
@@ -306,7 +307,7 @@ const login = (session, msg) => {
// before the session is findable, so that nothing is sent ahead of the
// login reply.
achievements.refresh(account);
accounts.save();
accounts.save(account);
online.set(key, session);
console.log(`[world] ${account.username} logged in as sfs user ${session.id}`);
session.sendXtJson(-1, {_cmd: "login", status: "1", params: loginParams(session)});
@@ -480,7 +481,7 @@ const makeColour = (account, rgbs, asker = null) => {
}
if (entry.created) {
account.coloursMade = {day: today, count: made + 1};
accounts.save();
accounts.save(account);
}
for (const recipient of entry.created ? online.values() : asker ? [asker] : []) {
recipient.sendXt("xcc", -1, 1, entry.id, ...entry.rgbs);
@@ -523,7 +524,7 @@ const handlers = {
.filter(Boolean).slice(0, MAX_FILTER_WORDS);
session.account.filter = {level: [0, 1, 2].includes(Number(level)) ? Number(level) : 0, mode: Number(mode) === 1 ? 1 : 0,
words: [...new Set(own)].join(","), chosen: true};
accounts.save();
accounts.save(session.account);
sendFilter(session);
},
@@ -796,7 +797,7 @@ const handlers = {
vars[id] = 0;
}
const earned = achievements.award(account, id);
accounts.save();
accounts.save(account);
achievements.sendVar(session, id, earned);
},
@@ -854,7 +855,7 @@ const handlers = {
const ok = Boolean(thing) && TYPED_NAME.test(wanted) && !moderation.isSilenced(account);
if (ok) {
thing.name = wanted;
accounts.save();
accounts.save(account);
if (kind === "a" && thing === activeAvatar(account)) {
sendAvatarData(session, session, thing.perUserAvId);
}
@@ -1029,14 +1030,17 @@ const playedText = seconds => {
return `Played ${minutes} minute${minutes === 1 ? "" : "s"}`;
};
const cardBio = account => {
// a bio from before the chat filter, or one a newer rule catches, is not
// shown (lib/chat-filter.txt).
const bio = account.bio && !chatFilter.broken(account.bio) ? account.bio : "";
if (!account.playtimePublic) {
return account.bio;
return bio;
}
const session = online.get(account.username.toLowerCase());
if (session) {
countPlaytime(session);
}
return account.bio ? `${playedText(account.playtime)}\n\n${account.bio}` : playedText(account.playtime);
return bio ? `${playedText(account.playtime)}\n\n${bio}` : playedText(account.playtime);
};
// the time since it was last counted, added to the account's playtime.
@@ -1068,7 +1072,7 @@ const leaveWorld = session => {
countPlaytime(session);
stats.session(session.account, (Date.now() - session.playStarted) / 1000);
accounts.release(session.account);
accounts.save();
accounts.save(session.account);
buddies.announce(session.account);
}
};
@@ -1119,7 +1123,7 @@ const setTheme = (account, theme) => {
return false;
}
account.theme = theme;
accounts.save();
accounts.save(account);
const session = findOnline(account.username);
if (session) {
reloadRoom(session);
@@ -1227,7 +1231,7 @@ const setHideBlocked = (session, hide) => {
}
account.hideBlocked = hide;
account.userVars[USER_VAR_HIDE_BLOCKED] = hide ? 1 : 0;
accounts.save();
accounts.save(account);
if (!hide) {
for (const other of blocked) {
sendAvatarCreate(session, other);
@@ -1409,6 +1413,17 @@ module.exports = {
return;
}
fields[0] = said;
// 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);
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})`);
return;
}
session.recentChat.push(`${new Date().toISOString().slice(11, 19)} ${said}`);
session.recentChat = session.recentChat.slice(-RECENT_CHAT_LINES);
chatlog.record(session.account, session.room.name, said);
@@ -1484,7 +1499,7 @@ module.exports = {
return false;
}
account.blocked = block ? [...account.blocked, key] : account.blocked.filter(name => name !== key);
accounts.save();
accounts.save(account);
const session = findOnline(account.username);
if (session) {
(block ? onBlocked : onUnblocked)(session, target);
@@ -1504,7 +1519,7 @@ module.exports = {
return;
}
account.nameBarData &= ~0xFF00;
accounts.save();
accounts.save(account);
const session = findOnline(account.username);
if (session && session.room) {
// AvatarXtCommManager "an": [sfsUserId, nameBarData]
@@ -1520,7 +1535,7 @@ module.exports = {
const avatar = activeAvatar(account);
avatar.questLevel = level;
avatar.questXp = adventureModule.levelXp(level);
accounts.save();
accounts.save(account);
const session = findOnline(account.username);
if (session && session.room) {
for (const viewer of session.room.sessions) {
@@ -1607,7 +1622,7 @@ module.exports = {
dens.sendDenState(visitor, room, false);
}
}
accounts.save();
accounts.save(...changed, maker);
return true;
},
+1 -1
View File
@@ -67,7 +67,7 @@ const handlers = {
}
// the client reads the bit straight from its copy of the user var.
achievements.set(account, def.userVarRefId, ((Number(account.userVars[def.userVarRefId]) || 0) | (1 << Number(def.uvIndex))) >>> 0);
accounts.save();
accounts.save(account);
session.sendXt("wig", -1, 1, amount);
},
};
+2 -1
View File
@@ -737,7 +737,8 @@ package gui
return;
}
gMainFrame.stage.focus = null;
loadValentinesPopup();
// Burrow: no secret valentines, so no popup asking which to send
sendECard(param1);
}
private function sendMailBtnOverHandler(param1:MouseEvent) : void
+3 -2
View File
@@ -165,8 +165,9 @@ package
_loc4_ += 17;
}
}
// A player's bio, the last field of what their card is told.
else if(param1.obj[0] == "xbn" && param1.obj.length > 7 && String(param1.obj[2]).toLowerCase() != String(gMainFrame.server.userName).toLowerCase())
// A player's bio, the last field of what their card is told:
// their own too, so they see it as others do.
else if(param1.obj[0] == "xbn" && param1.obj.length > 7)
{
param1.obj[7] = AJClient.filterOrNote(String(param1.obj[7]));
}
BIN
View File
Binary file not shown.