perf: save only changed accounts, cache missing assets, lighter logging and backup

Ping on prod jumped to seconds because node's main thread was busy most
of every second.

- accounts.save(account, ...) names the changed accounts, which are
  written within a second; the rest are looked at a few at a time
  (10 ms a save for those in play, 5 ms for the others). One save under
  prod-like load: 289 ms before, 16 ms after.
- an asset the CDN does not have gets a cacheable 404 and is logged once
- the proxy's own connections no longer count against the web cap, which
  had node reset requests nginx had already let in
- a repeated client error is written once in ten minutes; the panel's
  log buffer trims in batches
- the daily backup uses sqlite's online backup off the main thread
This commit is contained in:
Burrowdev committed 2026-10-17 11:57:40 +03:00
1 parent edca7bf790
commit aa455f52d0
26 files changed
+334 -220

No files matched your search

+148 -79
View File
@@ -3,7 +3,7 @@
const crypto = require("crypto"); const crypto = require("crypto");
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const {DatabaseSync} = require("node:sqlite"); const {DatabaseSync, backup: copyDatabase} = require("node:sqlite");
const config = require("../config.js"); const config = require("../config.js");
const defpacks = require("./defpacks.js"); const defpacks = require("./defpacks.js");
const names = require("./names.js"); const names = require("./names.js");
@@ -13,9 +13,9 @@ const names = require("./names.js");
// JSON document per account in `state`. // JSON document per account in `state`.
// //
// every account is held in memory while the server runs. game code changes // every account is held in memory while the server runs. game code changes
// those objects directly and then calls save(), which has every account // those objects directly and then calls save(account, ...), which has the
// whose state changed written back, a moment later: however many times it // accounts named written back a moment later, and the others looked at a
// is called in that moment, the accounts are gone through once (flush). // few at a time (flush, below).
const SCHEMA = ` const SCHEMA = `
CREATE TABLE IF NOT EXISTS accounts ( CREATE TABLE IF NOT EXISTS accounts (
@@ -415,21 +415,30 @@ const load = () => {
console.log(`[accounts] ${byKey.size} accounts in ${path.join(config.dataDir, "game.sqlite")}`); 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 // Which accounts a save looks at. turning an account into JSON to see
// JSON to see whether it changed costs, and doing it for every account there // whether it changed costs (up to a millisecond for a big one), and doing it
// is, a second after nearly every message, held the whole server up for // a second after nearly every message for every account in play (online
// longer the more accounts there were: a second and more, for everyone. so // ones, and the buddies, dens and cards they had looked up lately) held the
// it looks at the accounts in play: online ones (hold, from lib/world.js), // whole server up for most of every second once there were enough players.
// and ones looked up lately (by name, id, token, password: how the admin // so game code says which accounts it changed, save(account, ...), and those
// panel, buddies and the like get at an offline account), until a save // are written within SAVE_DELAY_MS. behind them, for whatever changed an
// finds them written and WARM_MS has gone by. the rest are looked at a few // account without saying so, the accounts in play are looked at a few at a
// at a time behind those (SWEEP_BUDGET_MS a save), round and round, for // time (PLAY_BUDGET_MS a save), round and round: online ones (hold, from
// what reached an account some other way (accounts.all()). a stop of the // lib/world.js) and ones looked up lately (by name, id, token, password: how
// server, and every flush() called by name, looks at all of them. // 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 WARM_MS = 10 * 60 * 1000;
const PLAY_BUDGET_MS = 10;
const SWEEP_BUDGET_MS = 5; const SWEEP_BUDGET_MS = 5;
const held = new Set(); // accounts online const held = new Set(); // accounts online
const warm = new Map(); // account -> when last looked up 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 sweepOrder = [];
let sweepAt = 0; let sweepAt = 0;
let sweepLeft = 0; // accounts the sweep still has to look at since the last save() 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; return false;
}; };
const elapsedMs = started => Number(process.hrtime.bigint() - started) / 1e6;
// the next accounts in play, while there is time: the ones online and the
// ones looked up lately. one looked up longer ago than WARM_MS is looked at
// once more, then left to the sweep.
const lookAtPlay = (changed, looked) => {
const started = process.hrtime.bigint();
while (playLeft > 0 && elapsedMs(started) < PLAY_BUDGET_MS) {
if (playAt >= playOrder.length) {
const now = Date.now();
playOrder = [...new Set([...held, ...warm.keys()])];
playAt = 0;
for (const [account, at] of warm) {
if (now - at > WARM_MS && !held.has(account)) {
warm.delete(account);
}
}
if (playOrder.length === 0) {
playLeft = 0;
break;
}
}
const account = playOrder[playAt++];
playLeft--;
if (!looked.has(account) && byId.get(account.id) === account) {
looked.add(account);
changedState(account, changed);
}
}
};
const lookAtRest = (changed, looked) => {
const started = process.hrtime.bigint();
while (sweepLeft > 0 && elapsedMs(started) < SWEEP_BUDGET_MS) {
if (sweepAt >= sweepOrder.length) {
sweepOrder = [...byId.values()];
sweepAt = 0;
if (sweepOrder.length === 0) {
sweepLeft = 0;
break;
}
}
const account = sweepOrder[sweepAt++];
sweepLeft--;
if (!looked.has(account) && byId.get(account.id) === account) {
looked.add(account);
changedState(account, changed);
}
}
};
// writes every account whose state changed since it was last written, in // writes every account whose state changed since it was last written, in
// one transaction; with {some: true}, of the accounts in play and the // one transaction; with {some: true}, of the accounts said to have changed
// sweep's next few (above). // and the next few of the others (above).
const flush = ({some = false} = {}) => { const flush = ({some = false} = {}) => {
clearTimeout(saveTimer); clearTimeout(saveTimer);
saveTimer = null; saveTimer = null;
@@ -467,49 +527,28 @@ const flush = ({some = false} = {}) => {
return; return;
} }
const changed = []; const changed = [];
const named = [...dirty];
dirty.clear();
if (some) { if (some) {
const now = Date.now();
const looked = new Set(); const looked = new Set();
for (const account of held) { for (const account of named) {
looked.add(account); if (byId.get(account.id) === account) {
changedState(account, changed); looked.add(account);
}
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) {
changedState(account, changed); changedState(account, changed);
} }
} }
lookAtPlay(changed, looked);
lookAtRest(changed, looked);
} }
else { else {
for (const account of byId.values()) { for (const account of byId.values()) {
changedState(account, changed); changedState(account, changed);
} }
playLeft = 0;
sweepLeft = 0; sweepLeft = 0;
} }
if (sweepLeft > 0) { if (playLeft > 0 || sweepLeft > 0) {
save(); // the sweep goes on in a moment later(CONTINUE_MS); // the looking goes on in a moment
} }
if (changed.length === 0) { if (changed.length === 0) {
return; return;
@@ -524,6 +563,7 @@ const flush = ({some = false} = {}) => {
} }
catch (err) { catch (err) {
db.exec("ROLLBACK"); db.exec("ROLLBACK");
named.forEach(account => dirty.add(account));
throw err; throw err;
} }
for (const [id, json] of changed) { for (const [id, json] of changed) {
@@ -531,16 +571,17 @@ const flush = ({some = false} = {}) => {
} }
}; };
// "Something changed": the accounts are written within SAVE_DELAY_MS. going // "Something changed": the accounts named are written within SAVE_DELAY_MS,
// through every account costs more the more there are, and game code calls // and the looking-through above starts again. game code calls this after
// this after nearly every message (and some of it a hundred times in a // nearly every message (and some of it a hundred times in a row), so it is
// row), so the going-through is done once for all the calls of a moment. // done once for all the calls of a moment. what a crash can lose is that
// what a crash can lose is that moment; a stop of the server writes first // moment, for an account named, and the time a round of the looking takes,
// for one changed without saying so; a stop of the server writes first
// (server.js). // (server.js).
const SAVE_DELAY_MS = 1000; const SAVE_DELAY_MS = 1000;
const CONTINUE_MS = 250;
let saveTimer = null; let saveTimer = null;
const save = () => { const later = delay => {
sweepLeft = byId.size;
if (saveTimer === null) { if (saveTimer === null) {
saveTimer = setTimeout(() => { saveTimer = setTimeout(() => {
try { try {
@@ -550,25 +591,47 @@ const save = () => {
console.error(`[accounts] could not save: ${err.message}`); console.error(`[accounts] could not save: ${err.message}`);
save(); // tried again in a moment: nothing is lost while the server runs save(); // tried again in a moment: nothing is lost while the server runs
} }
}, SAVE_DELAY_MS); }, delay);
} }
}; };
const save = (...changedAccounts) => {
for (const account of changedAccounts) {
if (account) {
dirty.add(account);
}
}
playLeft = held.size + warm.size;
sweepLeft = byId.size;
later(SAVE_DELAY_MS);
};
// A copy of the whole database, made once a day into data/backups/ and the // A copy of the whole database, made once a day into data/backups/ and the
// latest BACKUPS_KEPT kept. it is a whole file of its own (VACUUM INTO), to // latest BACKUPS_KEPT kept. it is a whole file of its own, to be copied
// be copied somewhere else by whoever runs the server: a copy on the same // somewhere else by whoever runs the server: a copy on the same disk is no
// disk is no help when the disk goes. // help when the disk goes. it is copied a batch of pages at a time off the
// main thread (sqlite's online backup): made in one go (VACUUM INTO, after
// writing every account) it held the game up for seconds.
const BACKUPS_KEPT = 14; const BACKUPS_KEPT = 14;
const backup = () => { let backingUp = false;
const backup = async () => {
const folder = path.join(config.dataDir, "backups"); const folder = path.join(config.dataDir, "backups");
const file = path.join(folder, `game-${new Date().toISOString().slice(0, 10)}.sqlite`); const file = path.join(folder, `game-${new Date().toISOString().slice(0, 10)}.sqlite`);
if (fs.existsSync(file)) { if (backingUp || fs.existsSync(file)) {
return; return;
} }
fs.mkdirSync(folder, {recursive: true, mode: 0o700}); backingUp = true;
flush(); const part = `${file}.part`;
db.prepare("VACUUM INTO ?").run(file); try {
fs.chmodSync(file, 0o600); fs.mkdirSync(folder, {recursive: true, mode: 0o700});
fs.rmSync(part, {force: true});
await copyDatabase(db, part);
fs.chmodSync(part, 0o600);
fs.renameSync(part, file); // only a whole copy has the day's name
}
finally {
backingUp = false;
fs.rmSync(part, {force: true});
}
const old = fs.readdirSync(folder).filter(name => /^game-\d{4}-\d{2}-\d{2}\.sqlite$/.test(name)).sort().slice(0, -BACKUPS_KEPT); const old = fs.readdirSync(folder).filter(name => /^game-\d{4}-\d{2}-\d{2}\.sqlite$/.test(name)).sort().slice(0, -BACKUPS_KEPT);
for (const name of old) { for (const name of old) {
fs.unlinkSync(path.join(folder, name)); fs.unlinkSync(path.join(folder, name));
@@ -577,12 +640,9 @@ const backup = () => {
}; };
const startBackups = () => { const startBackups = () => {
const attempt = () => { const attempt = () => {
try { backup().catch(err => {
backup();
}
catch (err) {
console.error(`[accounts] backup failed: ${err.message}`); console.error(`[accounts] backup failed: ${err.message}`);
} });
}; };
attempt(); attempt();
setInterval(attempt, 3600000).unref(); setInterval(attempt, 3600000).unref();
@@ -733,12 +793,16 @@ const rename = (account, username, anyName = false) => {
byKey.delete(oldKey); byKey.delete(oldKey);
account.username = username; account.username = username;
byKey.set(newKey, account); byKey.set(newKey, account);
const named = [account];
for (const other of byId.values()) { for (const other of byId.values()) {
other.buddies = other.buddies.map(name => (name === oldKey ? newKey : name)); if ([other.buddies, other.blocked, other.buddyRequests].some(list => list.includes(oldKey))) {
other.blocked = other.blocked.map(name => (name === oldKey ? newKey : name)); other.buddies = other.buddies.map(name => (name === oldKey ? newKey : name));
other.buddyRequests = other.buddyRequests.map(name => (name === oldKey ? newKey : name)); other.blocked = other.blocked.map(name => (name === oldKey ? newKey : name));
other.buddyRequests = other.buddyRequests.map(name => (name === oldKey ? newKey : name));
named.push(other);
}
} }
save(); save(...named);
return null; return null;
}; };
@@ -772,13 +836,18 @@ const remove = account => {
byId.delete(account.id); byId.delete(account.id);
savedState.delete(account.id); savedState.delete(account.id);
retire(key); retire(key);
const named = [];
for (const other of byId.values()) { for (const other of byId.values()) {
other.tradeOffers = other.tradeOffers.filter(offer => offer.fromId !== account.id); if (other.tradeOffers.some(offer => offer.fromId === account.id)
other.buddies = other.buddies.filter(name => name !== key); || [other.buddies, other.blocked, other.buddyRequests].some(list => list.includes(key))) {
other.blocked = other.blocked.filter(name => name !== key); other.tradeOffers = other.tradeOffers.filter(offer => offer.fromId !== account.id);
other.buddyRequests = other.buddyRequests.filter(name => name !== key); other.buddies = other.buddies.filter(name => name !== key);
other.blocked = other.blocked.filter(name => name !== key);
other.buddyRequests = other.buddyRequests.filter(name => name !== key);
named.push(other);
}
} }
save(); save(...named);
console.log(`[accounts] deleted "${account.username}" (id ${account.id})`); console.log(`[accounts] deleted "${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}; const achievement = {inv: account.nextInv++, def: def.id};
account.achievements.push(achievement); account.achievements.push(achievement);
accounts.save(); accounts.save(account);
const session = findOnline(account.username); const session = findOnline(account.username);
if (session) { if (session) {
if (account.userVars[def.userVarRef] === undefined) { if (account.userVars[def.userVarRef] === undefined) {
+3 -3
View File
@@ -95,7 +95,7 @@ const give = body => {
if (!item) { if (!item) {
return {status: 409, body: {error: "That inventory is full"}}; return {status: 409, body: {error: "That inventory is full"}};
} }
accounts.save(); accounts.save(account);
if (session) { if (session) {
sendClothingAdded(session, item); sendClothingAdded(session, item);
} }
@@ -119,7 +119,7 @@ const give = body => {
account.finderGiven[key] = {count: ((account.finderGiven[key] || {}).count || 0) + 1, at: Math.floor(Date.now() / 1000)}; account.finderGiven[key] = {count: ((account.finderGiven[key] || {}).count || 0) + 1, at: Math.floor(Date.now() / 1000)};
const kept = Object.entries(account.finderGiven).sort((one, other) => other[1].at - one[1].at).slice(0, MAX_FAVOURITES); const kept = Object.entries(account.finderGiven).sort((one, other) => other[1].at - one[1].at).slice(0, MAX_FAVOURITES);
account.finderGiven = Object.fromEntries(kept); account.finderGiven = Object.fromEntries(kept);
accounts.save(); accounts.save(account);
return {status: 200, body: {ok: true, online: Boolean(session)}}; return {status: 200, body: {ok: true, online: Boolean(session)}};
}; };
@@ -236,7 +236,7 @@ const handle = async (route, params, body, from) => {
const result = accounts.register(username, password, {type: avatarType}); const result = accounts.register(username, password, {type: avatarType});
if (result.account) { if (result.account) {
result.account.agreed = {version: config.termsVersion, at: Math.floor(Date.now() / 1000)}; result.account.agreed = {version: config.termsVersion, at: Math.floor(Date.now() / 1000)};
accounts.save(); accounts.save(result.account);
} }
// the client signs in straight after, and is not asked again. // the client signs in straight after, and is not asked again.
return result.error ? {status: 400, body: {error: result.error}} return result.error ? {status: 400, body: {error: result.error}}
+1 -1
View File
@@ -59,7 +59,7 @@ const handlers = {
for (const found of session.account.adoptAPets) { for (const found of session.account.adoptAPets) {
found.seen = found.seen || seen.has(found.def); found.seen = found.seen || seen.has(found.def);
} }
accounts.save(); accounts.save(session.account);
}, },
}; };
+2 -2
View File
@@ -82,7 +82,7 @@ module.exports = ({enterRoom, joinRoom, tell}) => {
avatar.questXp = before + amount; avatar.questXp = before + amount;
avatar.questLevel = levelFor(avatar.questXp); avatar.questLevel = levelFor(avatar.questXp);
if (amount > 0) { if (amount > 0) {
accounts.save(); accounts.save(session.account);
} }
q.send("quxp", amount, avatar.questXp, level, avatar.questLevel, percent(avatar.questXp), actor); q.send("quxp", amount, avatar.questXp, level, avatar.questLevel, percent(avatar.questXp), actor);
if (avatar.questLevel > level) { if (avatar.questLevel > level) {
@@ -121,7 +121,7 @@ module.exports = ({enterRoom, joinRoom, tell}) => {
const {account} = session; const {account} = session;
account.currency.gems = (account.currency.gems || 0) + amount; account.currency.gems = (account.currency.gems || 0) + amount;
achievements.currencyChanged(account, "gems", amount); achievements.currencyChanged(account, "gems", amount);
accounts.save(); accounts.save(account);
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0); session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
}, },
}; };
+4 -4
View File
@@ -78,7 +78,7 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
// (accounts.freeAvatarSlot). // (accounts.freeAvatarSlot).
const avatar = accounts.newAvatar({perUserAvId: account.nextInv++, avInvId: accounts.freeAvatarSlot(account)}, `${name1}|${name2}|${name3}`, type, customAvId); const avatar = accounts.newAvatar({perUserAvId: account.nextInv++, avInvId: accounts.freeAvatarSlot(account)}, `${name1}|${name2}|${name3}`, type, customAvId);
account.avatars.push(avatar); account.avatars.push(avatar);
accounts.save(); accounts.save(account);
session.sendXt("aa", -1, 1, avatar.perUserAvId, avatar.avInvId); session.sendXt("aa", -1, 1, avatar.perUserAvId, avatar.avInvId);
}, },
@@ -93,7 +93,7 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
return; return;
} }
account.activeAvatar = avatar.perUserAvId; account.activeAvatar = avatar.perUserAvId;
accounts.save(); accounts.save(account);
const messageRoom = session.room ? session.room.id : -1; const messageRoom = session.room ? session.room.id : -1;
const common = [1, session.id, avatar.perUserAvId, avatar.avInvId, avatar.customAvId, avatar.type, ...avatar.colors, avatar.name]; const common = [1, session.id, avatar.perUserAvId, avatar.avInvId, avatar.customAvId, avatar.type, ...avatar.colors, avatar.name];
session.sendXt("as", messageRoom, ...common, avatar.petInvId, avatar.questLevel || 0); session.sendXt("as", messageRoom, ...common, avatar.petInvId, avatar.questLevel || 0);
@@ -116,7 +116,7 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
for (const item of account.items) { for (const item of account.items) {
item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId); item.on = item.on.filter(avInvId => avInvId !== avatar.avInvId);
} }
accounts.save(); accounts.save(account);
session.sendXt("ak", -1, 1, 0); session.sendXt("ak", -1, 1, 0);
}, },
@@ -134,7 +134,7 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
if (tagChanged) { if (tagChanged) {
session.account.nameBarData = nameBarData; session.account.nameBarData = nameBarData;
} }
accounts.save(); accounts.save(session.account);
session.sendXt("ap", -1, 1); session.sendXt("ap", -1, 1);
refreshForOthers(session); refreshForOthers(session);
if (tagChanged) { if (tagChanged) {
+6 -6
View File
@@ -105,7 +105,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
else if (!account.buddies.includes(key(target))) { else if (!account.buddies.includes(key(target))) {
if (!target.buddyRequests.includes(key(account))) { if (!target.buddyRequests.includes(key(account))) {
target.buddyRequests.push(key(account)); target.buddyRequests.push(key(account));
accounts.save(); accounts.save(account, target);
} }
if (targetSession) { if (targetSession) {
targetSession.sendXt("ba", -1, REQUEST_INCOMING, account.username, USERNAME_SHOWN); targetSession.sendXt("ba", -1, REQUEST_INCOMING, account.username, USERNAME_SHOWN);
@@ -122,7 +122,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
return; return;
} }
account.buddyRequests = account.buddyRequests.filter(name => name !== key(requester)); account.buddyRequests = account.buddyRequests.filter(name => name !== key(requester));
accounts.save(); accounts.save(account);
const requesterSession = findOnline(requester.username); const requesterSession = findOnline(requester.username);
if (accept !== "1" || account.buddies.includes(key(requester)) if (accept !== "1" || account.buddies.includes(key(requester))
|| account.buddies.length >= MAX_BUDDIES || requester.buddies.length >= MAX_BUDDIES) { || account.buddies.length >= MAX_BUDDIES || requester.buddies.length >= MAX_BUDDIES) {
@@ -135,7 +135,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
requester.buddies.push(key(account)); requester.buddies.push(key(account));
achievements.add(account, achievements.VARS.buddiesAdded); achievements.add(account, achievements.VARS.buddiesAdded);
achievements.add(requester, achievements.VARS.buddiesAdded); achievements.add(requester, achievements.VARS.buddiesAdded);
accounts.save(); accounts.save(account, requester);
sendStatus(session, requester, STATUS_UPDATE); sendStatus(session, requester, STATUS_UPDATE);
if (requesterSession) { if (requesterSession) {
sendStatus(requesterSession, account, STATUS_ACCEPTED_YOUR_REQUEST); sendStatus(requesterSession, account, STATUS_ACCEPTED_YOUR_REQUEST);
@@ -149,7 +149,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
if (other) { if (other) {
account.buddies = account.buddies.filter(name => name !== key(other)); account.buddies = account.buddies.filter(name => name !== key(other));
other.buddies = other.buddies.filter(name => name !== key(account)); other.buddies = other.buddies.filter(name => name !== key(account));
accounts.save(); accounts.save(account, other);
const otherSession = findOnline(other.username); const otherSession = findOnline(other.username);
if (otherSession) { if (otherSession) {
otherSession.sendXt("bd", -1, account.username); otherSession.sendXt("bd", -1, account.username);
@@ -165,7 +165,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
const added = other && other !== account && !account.blocked.includes(key(other)) && account.blocked.length < MAX_BLOCKED; const added = other && other !== account && !account.blocked.includes(key(other)) && account.blocked.length < MAX_BLOCKED;
if (added) { if (added) {
account.blocked.push(key(other)); account.blocked.push(key(other));
accounts.save(); accounts.save(account);
} }
session.sendXt("bb", -1, username, other && other !== account && account.blocked.includes(key(other)) ? 1 : 0); session.sendXt("bb", -1, username, other && other !== account && account.blocked.includes(key(other)) ? 1 : 0);
if (added) { if (added) {
@@ -178,7 +178,7 @@ module.exports = ({findOnline, onBlocked, onUnblocked, partyTimeLeft}) => {
const other = accounts.byName(username); const other = accounts.byName(username);
const removed = other && account.blocked.includes(key(other)); const removed = other && account.blocked.includes(key(other));
account.blocked = account.blocked.filter(name => name !== String(username).toLowerCase()); account.blocked = account.blocked.filter(name => name !== String(username).toLowerCase());
accounts.save(); accounts.save(account);
session.sendXt("bu", -1, username, 1); session.sendXt("bu", -1, username, 1);
if (removed) { if (removed) {
onUnblocked(session, other); onUnblocked(session, other);
+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};
+12 -12
View File
@@ -79,7 +79,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
item.on.push(avatar.avInvId); item.on.push(avatar.avInvId);
} }
} }
accounts.save(); accounts.save(account);
// ItemXtCommManager.itemsChangedListResponse, "3" = what is worn // ItemXtCommManager.itemsChangedListResponse, "3" = what is worn
// changed: [3, inUse, perUserAvId, username, colour, onCount, // changed: [3, inUse, perUserAvId, username, colour, onCount,
// offCount, (invIdx, defId)..., offInvIdx...] // offCount, (invIdx, defId)..., offInvIdx...]
@@ -131,7 +131,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
} }
const items = wornItems(account, avatar).map(item => item.inv); const items = wornItems(account, avatar).map(item => item.inv);
account.outfits = [...account.outfits.filter(entry => entry !== existing), {name, items}]; account.outfits = [...account.outfits.filter(entry => entry !== existing), {name, items}];
accounts.save(); accounts.save(account);
tell(session, `Outfit ${name} saved (${items.length} items).`); tell(session, `Outfit ${name} saved (${items.length} items).`);
return; return;
} }
@@ -152,7 +152,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
return; return;
} }
account.outfits = account.outfits.filter(entry => entry.name !== name); account.outfits = account.outfits.filter(entry => entry.name !== name);
accounts.save(); accounts.save(account);
tell(session, `Outfit ${name} deleted.`); tell(session, `Outfit ${name} deleted.`);
return; return;
case "list": case "list":
@@ -194,7 +194,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
item.spots = item.spots || {}; item.spots = item.spots || {};
item.spots[account.activeDen] = {cat: spot.cat || 1, x: spot.x, y: spot.y, flip: spot.flip}; item.spots[account.activeDen] = {cat: spot.cat || 1, x: spot.x, y: spot.y, flip: spot.flip};
} }
accounts.save(); accounts.save(account);
dens.sendDenItems(session); dens.sendDenItems(session);
const room = session.room && session.room.denOwner === account ? session.room : null; const room = session.room && session.room.denOwner === account ? session.room : null;
for (const occupant of room ? room.sessions : []) { for (const occupant of room ? room.sessions : []) {
@@ -217,7 +217,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
} }
const items = layoutOf(account); const items = layoutOf(account);
account.denLayouts = [...account.denLayouts.filter(entry => entry !== existing), {name, den: activeDenDef(account), items}]; account.denLayouts = [...account.denLayouts.filter(entry => entry !== existing), {name, den: activeDenDef(account), items}];
accounts.save(); accounts.save(account);
tell(session, `Den layout ${name} saved (${items.length} items).`); tell(session, `Den layout ${name} saved (${items.length} items).`);
return; return;
} }
@@ -266,7 +266,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
} }
const missing = applyLayout(session, undo.items, false); const missing = applyLayout(session, undo.items, false);
account.denUndo = null; account.denUndo = null;
accounts.save(); accounts.save(account);
tell(session, missing ? `Your den is back as it was, apart from ${missing} items that are no longer yours.` : "Your den is back as it was."); tell(session, missing ? `Your den is back as it was, apart from ${missing} items that are no longer yours.` : "Your den is back as it was.");
return; return;
} }
@@ -276,7 +276,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
return; return;
} }
account.denLayouts = account.denLayouts.filter(entry => entry.name !== name); account.denLayouts = account.denLayouts.filter(entry => entry.name !== name);
accounts.save(); accounts.save(account);
tell(session, `Den layout ${name} deleted.`); tell(session, `Den layout ${name} deleted.`);
return; return;
case "list": case "list":
@@ -373,7 +373,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
const themes = require("../config.js").themes; const themes = require("../config.js").themes;
if (action === "random" && (choice === "on" || choice === "off")) { if (action === "random" && (choice === "on" || choice === "off")) {
account.randomTheme = choice === "on"; account.randomTheme = choice === "on";
accounts.save(); accounts.save(account);
tell(session, account.randomTheme ? "The lands get a look picked at random each time you log in." : "The lands keep the look you choose."); tell(session, account.randomTheme ? "The lands get a look picked at random each time you log in." : "The lands keep the look you choose.");
} }
else if (action === "here" && session.room && !session.room.denOwner && (choice === "off" || Object.hasOwn(themes, choice))) { else if (action === "here" && session.room && !session.room.denOwner && (choice === "off" || Object.hasOwn(themes, choice))) {
@@ -383,7 +383,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
else { else {
account.roomThemes[session.room.base] = choice; account.roomThemes[session.room.base] = choice;
} }
accounts.save(); accounts.save(account);
reloadRoom(session); reloadRoom(session);
} }
else if (action === "list") { else if (action === "list") {
@@ -403,7 +403,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
} }
const before = account.ecards.length; const before = account.ecards.length;
account.ecards = account.ecards.filter(card => !card.read || card.gift); account.ecards = account.ecards.filter(card => !card.read || card.gift);
accounts.save(); accounts.save(account);
tell(session, `${before - account.ecards.length} read Jam-A-Grams deleted. Open your mail again to see.`); tell(session, `${before - account.ecards.length} read Jam-A-Grams deleted. Open your mail again to see.`);
}, },
@@ -482,7 +482,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
} }
else if (wanted.toLowerCase() === "off") { else if (wanted.toLowerCase() === "off") {
delete account.denNames[account.activeDen]; delete account.denNames[account.activeDen];
accounts.save(); accounts.save(account);
tell(session, "This den has its usual name again."); tell(session, "This den has its usual name again.");
} }
else if (isSilenced(account)) { else if (isSilenced(account)) {
@@ -493,7 +493,7 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
} }
else { else {
account.denNames[account.activeDen] = wanted; account.denNames[account.activeDen] = wanted;
accounts.save(); accounts.save(account);
tell(session, `This den is now called ${wanted}. It shows the next time someone walks in.`); tell(session, `This den is now called ${wanted}. It shows the next time someone walks in.`);
} }
}, },
+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: {}}; const item = {inv: account.nextInv++, def: Number(defId), version: Number(version) || 0, spots: {}};
account.denItems.push(item); account.denItems.push(item);
accounts.save(); accounts.save(account);
return item; return item;
}; };
@@ -167,7 +167,7 @@ const clearDen = (owner, findOnline) => {
for (const pet of petsInDen(owner)) { for (const pet of petsInDen(owner)) {
delete pet.inDen; delete pet.inDen;
} }
accounts.save(); accounts.save(owner);
const ownerSession = findOnline(owner.username); const ownerSession = findOnline(owner.username);
const room = ownerSession && ownerSession.room && ownerSession.room.denOwner === owner ? ownerSession.room : null; const room = ownerSession && ownerSession.room && ownerSession.room.denOwner === owner ? ownerSession.room : null;
for (const session of room ? room.sessions : []) { for (const session of room ? room.sessions : []) {
@@ -231,7 +231,7 @@ const handlers = ({others, findOnline}) => {
account.currency[currency] -= purchase.cost; account.currency[currency] -= purchase.cost;
achievements.currencyChanged(account, currency, -purchase.cost); achievements.currencyChanged(account, currency, -purchase.cost);
account.dens.push({inv: freeSlot(account, /^\d{1,3}$/.test(String(slot)) ? Number(slot) : NaN), def: purchase.defId}); account.dens.push({inv: freeSlot(account, /^\d{1,3}$/.test(String(slot)) ? Number(slot) : NaN), def: purchase.defId});
accounts.save(); accounts.save(account);
session.sendXt("db", -1, 1, account.currency[currency], 0, purchase.currencyType, 0); session.sendXt("db", -1, 1, account.currency[currency], 0, purchase.currencyType, 0);
sendDenList(session); sendDenList(session);
}; };
@@ -259,7 +259,7 @@ const handlers = ({others, findOnline}) => {
masterpieces.claim(paintingId, frame); masterpieces.claim(paintingId, frame);
const item = giveDenItem(account, masterpieces.DEN_ITEM, frame); const item = giveDenItem(account, masterpieces.DEN_ITEM, frame);
item.image = String(paintingId); item.image = String(paintingId);
accounts.save(); accounts.save(account);
console.log(`[world] ${account.username} made masterpiece ${item.image}${masterpieces.itemApproved(item) ? "" : " (waiting for review in the admin panel)"}`); console.log(`[world] ${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); session.sendXt("db", -1, 1, account.currency.diamonds || 0, 0, CURRENCY_DIAMONDS, item.inv);
sendDenItems(session); sendDenItems(session);
@@ -289,7 +289,7 @@ const handlers = ({others, findOnline}) => {
achievements.currencyChanged(account, "gems", refund); achievements.currencyChanged(account, "gems", refund);
recycled.push(den.inv); recycled.push(den.inv);
} }
accounts.save(); accounts.save(account);
session.sendXt("dr", -1, recycled.length, account.currency.gems, ...recycled); session.sendXt("dr", -1, recycled.length, account.currency.gems, ...recycled);
// the switcher empties the slot itself; the items that come back need // the switcher empties the slot itself; the items that come back need
// the inventory's list. // the inventory's list.
@@ -418,7 +418,7 @@ const handlers = ({others, findOnline}) => {
} }
applied.push(item.inv); applied.push(item.inv);
} }
accounts.save(); accounts.save(account);
session.sendXt("dss", -1, ...applied); session.sendXt("dss", -1, ...applied);
if (inOwnDen(session)) { if (inOwnDen(session)) {
for (const other of others(session)) { for (const other of others(session)) {
@@ -452,7 +452,7 @@ const handlers = ({others, findOnline}) => {
account.denItems.splice(index, 1); account.denItems.splice(index, 1);
recycled.push(invIdx); recycled.push(invIdx);
} }
accounts.save(); accounts.save(account);
session.sendXt("dr", -1, recycled.length, account.currency.gems, ...recycled); session.sendXt("dr", -1, recycled.length, account.currency.gems, ...recycled);
if (recycled.length) { if (recycled.length) {
sendDenItems(session); sendDenItems(session);
@@ -486,7 +486,7 @@ const handlers = ({others, findOnline}) => {
return; return;
} }
account.activeDen = den.inv; account.activeDen = den.inv;
accounts.save(); accounts.save(account);
const avatar = activeAvatar(account); const avatar = activeAvatar(account);
session.sendXt("dc", -1, den.def, avatar.perUserAvId, avatar.petInvId); session.sendXt("dc", -1, den.def, avatar.perUserAvId, avatar.petInvId);
// what is free and what is placed differs from den to den. // 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))) { else if ([DEN_LOCKED, DEN_BUDDIES_ONLY, DEN_OPEN].includes(Number(value))) {
session.account.denPrivacy = Number(value); session.account.denPrivacy = Number(value);
accounts.save(); accounts.save(session.account);
} }
}, },
}; };
+1 -1
View File
@@ -70,7 +70,7 @@ const show = (to, subject) => {
// afresh, which brings the disguise with it (`show`). // afresh, which brings the disguise with it (`show`).
const set = (session, id, redraw) => { const set = (session, id, redraw) => {
session.account.disguise = id; session.account.disguise = id;
accounts.save(); accounts.save(session.account);
session.sendXt("dph", -1, 1, session.id, id ? 1 : 0, id || NPC_PHANTOM); session.sendXt("dph", -1, 1, session.id, id ? 1 : 0, id || NPC_PHANTOM);
redraw(session); redraw(session);
}; };
+7 -7
View File
@@ -154,7 +154,7 @@ module.exports = ({findOnline, blocks}) => {
// a localization string (StartupPopups.setupGiftPopup). // a localization string (StartupPopups.setupGiftPopup).
const message = clean(text).replace(/^(?=[\s+-]*\d)/, "Gift: "); const message = clean(text).replace(/^(?=[\s+-]*\d)/, "Gift: ");
deliver(to, {from: HQ_NAME, hq: true, card: art.cards[0], stamp: 0, msg: message, gift: attached}); deliver(to, {from: HQ_NAME, hq: true, card: art.cards[0], stamp: 0, msg: message, gift: attached});
accounts.save(); accounts.save(to);
return null; return null;
}; };
@@ -165,7 +165,7 @@ module.exports = ({findOnline, blocks}) => {
return false; return false;
} }
deliver(to, {from: HQ_NAME, hq: true, card: art.cards[0], stamp: 0, msg: clean(text).replace(/^(?=[\s+-]*\d)/, "Note: "), gift: null}); deliver(to, {from: HQ_NAME, hq: true, card: art.cards[0], stamp: 0, msg: clean(text).replace(/^(?=[\s+-]*\d)/, "Note: "), gift: null});
accounts.save(); accounts.save(to);
return true; return true;
}; };
@@ -268,7 +268,7 @@ module.exports = ({findOnline, blocks}) => {
if (gift) { if (gift) {
achievements.add(account, achievements.VARS.giftsSent); achievements.add(account, achievements.VARS.giftsSent);
} }
accounts.save(); accounts.save(account, to);
reply(SENT); reply(SENT);
}, },
@@ -277,7 +277,7 @@ module.exports = ({findOnline, blocks}) => {
const card = session.account.ecards.find(candidate => candidate.id === Number(msgId)); const card = session.account.ecards.find(candidate => candidate.id === Number(msgId));
if (card) { if (card) {
card.read = true; card.read = true;
accounts.save(); accounts.save(session.account);
} }
session.sendXt("er", -1, msgId, card ? 1 : 0); session.sendXt("er", -1, msgId, card ? 1 : 0);
}, },
@@ -288,7 +288,7 @@ module.exports = ({findOnline, blocks}) => {
const {account} = session; const {account} = session;
const before = account.ecards.length; const before = account.ecards.length;
account.ecards = account.ecards.filter(card => card.id !== Number(msgId)); account.ecards = account.ecards.filter(card => card.id !== Number(msgId));
accounts.save(); accounts.save(account);
session.sendXt("ed", -1, 1, before - account.ecards.length, ...(before === account.ecards.length ? [] : [msgId])); session.sendXt("ed", -1, 1, before - account.ecards.length, ...(before === account.ecards.length ? [] : [msgId]));
}, },
@@ -314,7 +314,7 @@ module.exports = ({findOnline, blocks}) => {
if (accept === "1") { if (accept === "1") {
giveGift(session, gift); giveGift(session, gift);
} }
accounts.save(); accounts.save(session.account);
session.sendXt("eg", -1, msgId, 1); session.sendXt("eg", -1, msgId, 1);
}, },
@@ -324,7 +324,7 @@ module.exports = ({findOnline, blocks}) => {
const valid = [FROM_EVERYONE, FROM_BUDDIES, FROM_NOBODY].includes(value); const valid = [FROM_EVERYONE, FROM_BUDDIES, FROM_NOBODY].includes(value);
if (valid) { if (valid) {
session.account.ecardPrivacy = value; session.account.ecardPrivacy = value;
accounts.save(); accounts.save(session.account);
} }
session.sendXt("ei", -1, valid ? 1 : 0); session.sendXt("ei", -1, valid ? 1 : 0);
}, },
+50 -12
View File
@@ -151,6 +151,7 @@ const send = (res, status, body, type = "application/json") => {
const TEN_MINUTES_MS = 600000; const TEN_MINUTES_MS = 600000;
const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS); const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS);
const searches = limits.limiter(120, 60000); // item finder searches, per address const searches = limits.limiter(120, 60000); // item finder searches, per address
const MISSING_ASSET_SECONDS = 600; // how long a client may keep the CDN's "no such file"
const cacheMisses = limits.limiter(config.cacheMissesPerTenMinutes, TEN_MINUTES_MS); // files fetched from the official CDN for one address const cacheMisses = limits.limiter(config.cacheMissesPerTenMinutes, TEN_MINUTES_MS); // files fetched from the official CDN for one address
const errorReports = limits.limiter(config.errorReportsPerMinute, 60000); const errorReports = limits.limiter(config.errorReportsPerMinute, 60000);
const paintingPosts = limits.limiter(60, TEN_MINUTES_MS); // per address; each also needs a token from the game const paintingPosts = limits.limiter(60, TEN_MINUTES_MS); // per address; each also needs a token from the game
@@ -169,6 +170,27 @@ const keepClientError = text => {
.then(size => (size < MAX_CLIENT_ERROR_FILE ? fs.promises.appendFile(CLIENT_ERROR_FILE, text) : null)) .then(size => (size < MAX_CLIENT_ERROR_FILE ? fs.promises.appendFile(CLIENT_ERROR_FILE, text) : null))
.catch(() => {}); .catch(() => {});
}; };
// the same error from many clients (one broken item, met by everyone who
// sees it) is written once in REPEAT_WINDOW_MS, and the next time after that
// with how many there were between: a log, and a thread that waits for it,
// had a stack of twenty lines several times a second. null for one to leave
// out; else what to add to its line.
const REPEAT_WINDOW_MS = 600000;
const MAX_REMEMBERED_ERRORS = 1000;
const recentErrors = new Map(); // section and message -> {at, more}
const repeatedError = text => {
const seen = recentErrors.get(text);
if (seen && Date.now() - seen.at < REPEAT_WINDOW_MS) {
seen.more++;
return null;
}
recentErrors.delete(text);
if (recentErrors.size >= MAX_REMEMBERED_ERRORS) {
recentErrors.delete(recentErrors.keys().next().value);
}
recentErrors.set(text, {at: Date.now(), more: 0});
return seen && seen.more > 0 ? `\n\t(and ${seen.more} more like it in the ${Math.round(REPEAT_WINDOW_MS / 60000)} minutes before)` : "";
};
const THEMED_ROOM = /^(\d+)\/roomDefs\/theme_(\d+)\/(.+)$/; const THEMED_ROOM = /^(\d+)\/roomDefs\/theme_(\d+)\/(.+)$/;
// the web pages, as against what the game and the client load // the web pages, as against what the game and the client load
@@ -348,7 +370,7 @@ const renameAndSignIn = (res, body, from) => {
delete account.nameRejected; delete account.nameRejected;
manage.forget(account); manage.forget(account);
accounts.recordLogin(account, "launcher", from.address); accounts.recordLogin(account, "launcher", from.address);
accounts.save(); accounts.save(account);
console.log(`[accounts] a rejected username was replaced by "${account.username}"`); console.log(`[accounts] a rejected username was replaced by "${account.username}"`);
accounts.setLoginChoices(account, body.login_choices); accounts.setLoginChoices(account, body.login_choices);
const token = accounts.issueToken(account); const token = accounts.issueToken(account);
@@ -384,7 +406,7 @@ const authenticate = async (req, res, from) => {
const tried = accounts.byName(accountKey); const tried = accounts.byName(accountKey);
if (tried) { if (tried) {
accounts.recordLogin(tried, "launcher", from.address, false); accounts.recordLogin(tried, "launcher", from.address, false);
accounts.save(); accounts.save(tried);
} }
} }
// error_code 100 = expired refresh token, 101 = wrong credentials // 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))) { if (!totp.verify(account, String(body.totp))) {
failuresByAddress.record(from.key); failuresByAddress.record(from.key);
accounts.recordLogin(account, "launcher", from.address, false); accounts.recordLogin(account, "launcher", from.address, false);
accounts.save(); accounts.save(account);
send(res, 401, {error_code: 101, error: "totp_wrong", captcha_pass: captcha.issuePass(account, from)}); send(res, 401, {error_code: 101, error: "totp_wrong", captcha_pass: captcha.issuePass(account, from)});
return; return;
} }
@@ -440,13 +462,13 @@ const authenticate = async (req, res, from) => {
// its username was rejected: a new one first (above). the official // its username was rejected: a new one first (above). the official
// launcher shows this as a wrong password; the account page asks too. // launcher shows this as a wrong password; the account page asks too.
if (account.nameRejected) { if (account.nameRejected) {
accounts.save(); // a two-step code just used stays used accounts.save(account); // a two-step code just used stays used
send(res, 401, {error_code: 101, error: "name_rejected", rename_ticket: renameTicket(account, deviceToken)}); send(res, 401, {error_code: 101, error: "name_rejected", rename_ticket: renameTicket(account, deviceToken)});
return; return;
} }
if (!byRefresh) { if (!byRefresh) {
accounts.recordLogin(account, "launcher", from.address); accounts.recordLogin(account, "launcher", from.address);
accounts.save(); accounts.save(account);
} }
// the custom client's advanced settings; the official launcher sends none. // the custom client's advanced settings; the official launcher sends none.
accounts.setLoginChoices(account, body.login_choices); accounts.setLoginChoices(account, body.login_choices);
@@ -687,9 +709,12 @@ const handle = async (req, res) => {
const section = String(report.section).slice(0, 20).replace(/[^\w-]/g, "?"); const section = String(report.section).slice(0, 20).replace(/[^\w-]/g, "?");
const trace = message.startsWith("media "); const trace = message.startsWith("media ");
if (trace ? config.logPackets : from.local || errorReports.allow(from.key)) { if (trace ? config.logPackets : from.local || errorReports.allow(from.key)) {
console.log(`[${trace ? "client-trace" : "client-error"}] (${section}) ${message}`); const again = trace ? "" : repeatedError(`${section} ${message}`);
if (!trace) { if (again !== null) {
keepClientError(`${new Date().toISOString()} (${section}) ${message}\n`); console.log(`[${trace ? "client-trace" : "client-error"}] (${section}) ${message}${again}`);
if (!trace) {
keepClientError(`${new Date().toISOString()} (${section}) ${message}${again}\n`);
}
} }
} }
send(res, 200, {}); 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)) 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); || await cdn.get(themed ? `${themed[1]}/roomDefs/${themed[3]}` : relPath, mayFetch);
if (!body) { if (!body) {
console.log(`[http] 404 ${url.pathname}`); // one the CDN does not have is asked for again and again (the same few
// hundred, by every client that meets them): its client may keep the
// answer a while, and it was logged when the CDN said so ([cdn] 404).
if (cdn.knownMissing(themed ? `${themed[1]}/roomDefs/${themed[3]}` : relPath)) {
res.setHeader("Cache-Control", `public, max-age=${MISSING_ASSET_SECONDS}`);
}
else {
console.log(`[http] 404 ${url.pathname}`);
}
send(res, 404, "Not found", "text/plain"); send(res, 404, "Not found", "text/plain");
return; return;
} }
@@ -815,12 +848,15 @@ const start = () => new Promise((resolve, reject) => {
: http.createServer(onRequest); : http.createServer(onRequest);
// nobody gets to hold a request open by trickling it in, nor a reply by // nobody gets to hold a request open by trickling it in, nor a reply by
// never reading it; and there is an end to how many connections there // never reading it; and there is an end to how many connections there
// may be, in all and from one address. // may be, in all and from one address. a proxy in front (nginx) keeps
// its own count of those; its connections here are not counted, since
// turning them away only had it fail the requests of players it had
// already let in, who then asked again.
server.requestTimeout = 30000; server.requestTimeout = 30000;
server.headersTimeout = 15000; server.headersTimeout = 15000;
server.timeout = config.httpSocketTimeoutMs; server.timeout = config.httpSocketTimeoutMs;
server.maxConnections = config.maxHttpConnections;
const open = new Map(); // address, as limits count it -> connections const open = new Map(); // address, as limits count it -> connections
let openInAll = 0;
server.on("connection", socket => { server.on("connection", socket => {
const address = limits.key(socket.remoteAddress); const address = limits.key(socket.remoteAddress);
// behind a proxy every connection is the proxy's own. // behind a proxy every connection is the proxy's own.
@@ -828,12 +864,14 @@ const start = () => new Promise((resolve, reject) => {
return; return;
} }
const count = (open.get(address) || 0) + 1; const count = (open.get(address) || 0) + 1;
if (count > config.maxHttpConnectionsPerAddress) { if (count > config.maxHttpConnectionsPerAddress || openInAll >= config.maxHttpConnections) {
socket.destroy(); socket.destroy();
return; return;
} }
open.set(address, count); open.set(address, count);
openInAll++;
socket.once("close", () => { socket.once("close", () => {
openInAll--;
const left = open.get(address) - 1; const left = open.get(address) - 1;
if (left > 0) { if (left > 0) {
open.set(address, left); open.set(address, left);
+4 -4
View File
@@ -48,7 +48,7 @@ module.exports = ({others, sendItemList}) => {
achievements.currencyChanged(account, currency, -purchase.cost); achievements.currencyChanged(account, currency, -purchase.cost);
achievements.add(account, achievements.VARS.clothesBought); achievements.add(account, achievements.VARS.clothesBought);
const item = addClothing(account, def.id, colors[colorIndex]); const item = addClothing(account, def.id, colors[colorIndex]);
accounts.save(); accounts.save(account);
sendClothingAdded(session, item); sendClothingAdded(session, item);
session.sendXt("ib", -1, 1, shopId, account.currency[currency], purchase.currencyType); session.sendXt("ib", -1, 1, shopId, account.currency[currency], purchase.currencyType);
}, },
@@ -95,7 +95,7 @@ module.exports = ({others, sendItemList}) => {
}; };
const off = ids.slice(onCount).filter(invIdx => setWorn(invIdx, false) !== null); const off = ids.slice(onCount).filter(invIdx => setWorn(invIdx, false) !== null);
const on = ids.slice(0, onCount).map(invIdx => [invIdx, setWorn(invIdx, true)]).filter(([, def]) => def !== null); const on = ids.slice(0, onCount).map(invIdx => [invIdx, setWorn(invIdx, true)]).filter(([, def]) => def !== null);
accounts.save(); accounts.save(account);
// ItemXtCommManager.itemUseResponse // ItemXtCommManager.itemUseResponse
session.sendXt("iu", -1, 1); session.sendXt("iu", -1, 1);
// the reply only closes the editor. the animal in the room is redrawn // the reply only closes the editor. the animal in the room is redrawn
@@ -127,7 +127,7 @@ module.exports = ({others, sendItemList}) => {
account.currency[received] = (account.currency[received] || 0) + def.result; account.currency[received] = (account.currency[received] || 0) + def.result;
achievements.currencyChanged(account, paid, -def.cost); achievements.currencyChanged(account, paid, -def.cost);
achievements.currencyChanged(account, received, def.result); achievements.currencyChanged(account, received, def.result);
accounts.save(); accounts.save(account);
// ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason] // ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason]
session.sendXt("cu", -1, def.resultType, account.currency[received], 0); session.sendXt("cu", -1, def.resultType, account.currency[received], 0);
session.sendXt("ce", -1, 1, account.currency[paid]); session.sendXt("ce", -1, 1, account.currency[paid]);
@@ -154,7 +154,7 @@ module.exports = ({others, sendItemList}) => {
account.items.splice(index, 1); account.items.splice(index, 1);
recycled.push(invIdx); recycled.push(invIdx);
} }
accounts.save(); accounts.save(account);
session.sendXt("ir", -1, recycled.length, account.currency.gems || 0, ...recycled); session.sendXt("ir", -1, recycled.length, account.currency.gems || 0, ...recycled);
if (recycled.length) { if (recycled.length) {
sendClothingRemoved(session, recycled); sendClothingRemoved(session, recycled);
+4 -1
View File
@@ -5,6 +5,7 @@
const MAX_LINES = 5000; const MAX_LINES = 5000;
const MAX_LINE_LENGTH = 2000; const MAX_LINE_LENGTH = 2000;
const TRIM_BATCH = 1000;
const lines = []; // {id, time, text} const lines = []; // {id, time, text}
let nextId = 1; let nextId = 1;
@@ -15,7 +16,9 @@ const capture = original => (...args) => {
for (const line of text.split("\n")) { for (const line of text.split("\n")) {
lines.push({id: nextId++, time: Date.now(), text: line.slice(0, MAX_LINE_LENGTH)}); lines.push({id: nextId++, time: Date.now(), text: line.slice(0, MAX_LINE_LENGTH)});
} }
if (lines.length > MAX_LINES) { // trimmed a batch at a time: trimming a line at a time moved all the
// others along for every line printed.
if (lines.length > MAX_LINES + TRIM_BATCH) {
lines.splice(0, lines.length - MAX_LINES); lines.splice(0, lines.length - MAX_LINES);
} }
}; };
+17 -17
View File
@@ -248,7 +248,7 @@ const act = (account, body, req, from, res) => {
return {error: NAME_ERRORS[problem] || NAME_ERRORS.invalid_username}; return {error: NAME_ERRORS[problem] || NAME_ERRORS.invalid_username};
} }
delete account.nameRejected; delete account.nameRejected;
accounts.save(); accounts.save(account);
console.log(`[account] a rejected username was replaced by "${account.username}" from ${from.address}`); console.log(`[account] a rejected username was replaced by "${account.username}" from ${from.address}`);
return {ok: "Saved."}; return {ok: "Saved."};
} }
@@ -291,7 +291,7 @@ const act = (account, body, req, from, res) => {
accounts.revokeTokens(account); accounts.revokeTokens(account);
world.moderation.actions.kick(account); world.moderation.actions.kick(account);
} }
accounts.save(); accounts.save(account);
console.log(`[account] "${account.username}" ${account.locked ? "locked" : "unlocked"} from ${from.address}`); console.log(`[account] "${account.username}" ${account.locked ? "locked" : "unlocked"} from ${from.address}`);
return {ok: account.locked ? "Locked." : "Unlocked."}; return {ok: account.locked ? "Locked." : "Unlocked."};
} }
@@ -300,7 +300,7 @@ const act = (account, body, req, from, res) => {
return {error: "Unknown setting."}; return {error: "Unknown setting."};
} }
account.features[body.feature] = body.on; account.features[body.feature] = body.on;
accounts.save(); accounts.save(account);
return {ok: "Saved."}; return {ok: "Saved."};
} }
// two-step sign-in (lib/totp.js). turning it on: the password again, // two-step sign-in (lib/totp.js). turning it on: the password again,
@@ -314,17 +314,17 @@ const act = (account, body, req, from, res) => {
return {error: "Wrong password."}; return {error: "Wrong password."};
} }
const setup = totp.begin(account); const setup = totp.begin(account);
accounts.save(); accounts.save(account);
return {ok: "Scan the code.", setup}; return {ok: "Scan the code.", setup};
} }
case "twoStepConfirm": { case "twoStepConfirm": {
const recovery = totp.confirm(account, body.code); const recovery = totp.confirm(account, body.code);
if (!recovery) { if (!recovery) {
accounts.save(); accounts.save(account);
return {error: "Wrong code."}; return {error: "Wrong code."};
} }
accounts.revokeTokens(account); accounts.revokeTokens(account);
accounts.save(); accounts.save(account);
console.log(`[account] "${account.username}" turned two-step sign-in on from ${from.address}`); console.log(`[account] "${account.username}" turned two-step sign-in on from ${from.address}`);
return {ok: "2FA is on.", recovery}; return {ok: "2FA is on.", recovery};
} }
@@ -337,18 +337,18 @@ const act = (account, body, req, from, res) => {
return {error: "Wrong password."}; return {error: "Wrong password."};
} }
if (!totp.verify(account, String(body.code || ""))) { if (!totp.verify(account, String(body.code || ""))) {
accounts.save(); accounts.save(account);
return {error: "Wrong code."}; return {error: "Wrong code."};
} }
totp.turnOff(account); totp.turnOff(account);
accounts.save(); accounts.save(account);
res.setHeader("Set-Cookie", cookieHeader("", 0, DEVICE_COOKIE)); res.setHeader("Set-Cookie", cookieHeader("", 0, DEVICE_COOKIE));
console.log(`[account] "${account.username}" turned two-step sign-in off from ${from.address}`); console.log(`[account] "${account.username}" turned two-step sign-in off from ${from.address}`);
return {ok: "2FA is off."}; return {ok: "2FA is off."};
} }
case "forgetDevices": case "forgetDevices":
totp.forgetDevices(account); totp.forgetDevices(account);
accounts.save(); accounts.save(account);
return {ok: "Trusted devices forgotten."}; return {ok: "Trusted devices forgotten."};
// their bio, for the Bio tab of their card in the game. empty takes it off. // their bio, for the Bio tab of their card in the game. empty takes it off.
case "bio": { case "bio": {
@@ -361,13 +361,13 @@ const act = (account, body, req, from, res) => {
return {error: `At most ${badges.MAX_BIO} characters on ${badges.MAX_BIO_LINES} lines.`}; return {error: `At most ${badges.MAX_BIO} characters on ${badges.MAX_BIO_LINES} lines.`};
} }
account.bio = bio; account.bio = bio;
accounts.save(); accounts.save(account);
return {ok: bio ? "Saved." : "Removed."}; return {ok: bio ? "Saved." : "Removed."};
} }
// whether their card in the game shows how long they have played. // whether their card in the game shows how long they have played.
case "playtimePublic": case "playtimePublic":
account.playtimePublic = body.on === true; 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."}; 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. // their Discord username, for their card in the game. empty takes it off.
case "discord": { case "discord": {
@@ -376,7 +376,7 @@ const act = (account, body, req, from, res) => {
return {error: "Not a Discord username."}; return {error: "Not a Discord username."};
} }
account.discord = name; account.discord = name;
accounts.save(); accounts.save(account);
return {ok: name ? "Saved." : "Removed."}; return {ok: name ? "Saved." : "Removed."};
} }
// the player's own words about a buddy; only they see them. // the player's own words about a buddy; only they see them.
@@ -392,7 +392,7 @@ const act = (account, body, req, from, res) => {
else { else {
delete account.buddyNotes[key]; delete account.buddyNotes[key];
} }
accounts.save(); accounts.save(account);
return {ok: "Saved."}; return {ok: "Saved."};
} }
// blocking and unblocking, as the game's own buttons do it. // blocking and unblocking, as the game's own buttons do it.
@@ -422,7 +422,7 @@ const act = (account, body, req, from, res) => {
case "signOutEverywhere": case "signOutEverywhere":
accounts.revokeTokens(account); accounts.revokeTokens(account);
totp.forgetDevices(account); totp.forgetDevices(account);
accounts.save(); accounts.save(account);
world.moderation.actions.kick(account); world.moderation.actions.kick(account);
signOutOthers(account, req); signOutOthers(account, req);
return {ok: "Signed out everywhere."}; return {ok: "Signed out everywhere."};
@@ -495,7 +495,7 @@ const handle = async (req, res, url, from, web) => {
failuresByAddress.record(from.key); failuresByAddress.record(from.key);
if (known) { if (known) {
accounts.recordLogin(known, "web", from.address, false); accounts.recordLogin(known, "web", from.address, false);
accounts.save(); accounts.save(known);
} }
reply(401, {error: "Wrong username or password."}); reply(401, {error: "Wrong username or password."});
return; return;
@@ -511,7 +511,7 @@ const handle = async (req, res, url, from, web) => {
if (!totp.verify(account, String(body.code))) { if (!totp.verify(account, String(body.code))) {
failuresByAddress.record(from.key); failuresByAddress.record(from.key);
accounts.recordLogin(account, "web", from.address, false); accounts.recordLogin(account, "web", from.address, false);
accounts.save(); accounts.save(account);
reply(401, {error: "Wrong code.", twoStep: true, captchaPass: captcha.issuePass(account, from)}); reply(401, {error: "Wrong code.", twoStep: true, captchaPass: captcha.issuePass(account, from)});
return; return;
} }
@@ -520,7 +520,7 @@ const handle = async (req, res, url, from, web) => {
} }
} }
accounts.recordLogin(account, "web", from.address); accounts.recordLogin(account, "web", from.address);
accounts.save(); accounts.save(account);
signIn(res, account, cookies); signIn(res, account, cookies);
reply(200, {ok: true}); reply(200, {ok: true});
return; return;
+7 -7
View File
@@ -271,7 +271,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
} }
account.currency.gems -= CARNIVAL_COST; account.currency.gems -= CARNIVAL_COST;
achievements.currencyChanged(account, "gems", -CARNIVAL_COST); achievements.currencyChanged(account, "gems", -CARNIVAL_COST);
accounts.save(); accounts.save(account);
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0); session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
game.serial2 = serial(); game.serial2 = serial();
reply("pg", "1", hideSerial(game.serial2)); reply("pg", "1", hideSerial(game.serial2));
@@ -288,7 +288,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
if (tickets > 0) { if (tickets > 0) {
account.currency.tickets = (account.currency.tickets || 0) + tickets; account.currency.tickets = (account.currency.tickets || 0) + tickets;
achievements.currencyChanged(account, "tickets", tickets); achievements.currencyChanged(account, "tickets", tickets);
accounts.save(); accounts.save(account);
session.sendXt("cu", -1, CURRENCY_TICKETS, account.currency.tickets, 0); session.sendXt("cu", -1, CURRENCY_TICKETS, account.currency.tickets, 0);
} }
reply("gr", tickets); reply("gr", tickets);
@@ -315,7 +315,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
} }
account.currency.gems -= CLAW_COST; account.currency.gems -= CLAW_COST;
achievements.currencyChanged(account, "gems", -CLAW_COST); achievements.currencyChanged(account, "gems", -CLAW_COST);
accounts.save(); accounts.save(account);
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0); session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
const prizes = clawPrizes(game.def); const prizes = clawPrizes(game.def);
const won = prizes.length > 0 && Math.random() < CLAW_WIN_CHANCE; const won = prizes.length > 0 && Math.random() < CLAW_WIN_CHANCE;
@@ -343,7 +343,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
gd(session, game, [keep]) { gd(session, game, [keep]) {
if (keep === "1" && session.gamePrize) { if (keep === "1" && session.gamePrize) {
sendClothingAdded(session, addClothing(session.account, session.gamePrize.def, session.gamePrize.color)); sendClothingAdded(session, addClothing(session.account, session.gamePrize.def, session.gamePrize.color));
accounts.save(); accounts.save(session.account);
} }
session.gamePrize = null; session.gamePrize = null;
}, },
@@ -401,7 +401,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
} }
account.currency.gems -= INVASION_COST; account.currency.gems -= INVASION_COST;
achievements.currencyChanged(account, "gems", -INVASION_COST); achievements.currencyChanged(account, "gems", -INVASION_COST);
accounts.save(); accounts.save(account);
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0); session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
const prizes = invasionPrizes(); const prizes = invasionPrizes();
session.prizeSerial = serial(); session.prizeSerial = serial();
@@ -528,7 +528,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
if (valid) { if (valid) {
account.currency.gems = (account.currency.gems || 0) + amount; account.currency.gems = (account.currency.gems || 0) + amount;
achievements.currencyChanged(account, "gems", amount); achievements.currencyChanged(account, "gems", amount);
accounts.save(); accounts.save(account);
} }
session.gemSerial = serial(); session.gemSerial = serial();
session.sendXt("mg", -1, session.gemSerial, 0); session.sendXt("mg", -1, session.gemSerial, 0);
@@ -547,7 +547,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks}) => {
if (valid && (pet.mastery || 0) < MASTERY_FULL) { if (valid && (pet.mastery || 0) < MASTERY_FULL) {
pet.mastery = Math.min(MASTERY_FULL, (pet.mastery || 0) + amount); pet.mastery = Math.min(MASTERY_FULL, (pet.mastery || 0) + amount);
nowFull = pet.mastery === MASTERY_FULL; nowFull = pet.mastery === MASTERY_FULL;
accounts.save(); accounts.save(account);
} }
session.masterySerial = serial(); session.masterySerial = serial();
session.sendXt("ma", -1, session.masterySerial, nowFull ? 1 : 0); session.sendXt("ma", -1, session.masterySerial, nowFull ? 1 : 0);
+7 -7
View File
@@ -71,7 +71,7 @@ module.exports = ({findOnline}) => {
target.banReason = bans.reasonText(reason); target.banReason = bans.reasonText(reason);
target.bannedBy = by; target.bannedBy = by;
target.bannedAt = now(); target.bannedAt = now();
accounts.save(); accounts.save(target);
bans.record({account: target, action: "ban", seconds: duration, reason: target.banReason, by}); bans.record({account: target, action: "ban", seconds: duration, reason: target.banReason, by});
const session = findOnline(target.username); const session = findOnline(target.username);
if (session) { if (session) {
@@ -87,7 +87,7 @@ module.exports = ({findOnline}) => {
delete target.banReason; delete target.banReason;
delete target.bannedBy; delete target.bannedBy;
delete target.bannedAt; delete target.bannedAt;
accounts.save(); accounts.save(target);
if (was) { if (was) {
bans.record({account: target, action: "unban", by}); bans.record({account: target, action: "unban", by});
} }
@@ -100,7 +100,7 @@ module.exports = ({findOnline}) => {
return false; return false;
} }
target.banReason = bans.reasonText(reason); target.banReason = bans.reasonText(reason);
accounts.save(); accounts.save(target);
bans.record({account: target, action: "reason", reason: target.banReason, by}); bans.record({account: target, action: "reason", reason: target.banReason, by});
return true; return true;
}, },
@@ -108,7 +108,7 @@ module.exports = ({findOnline}) => {
// duration in seconds, PERMANENT, or 0 to lift // duration in seconds, PERMANENT, or 0 to lift
silence(target, duration) { silence(target, duration) {
target.silencedUntil = duration === PERMANENT ? PERMANENT : (duration > 0 ? now() + duration : 0); target.silencedUntil = duration === PERMANENT ? PERMANENT : (duration > 0 ? now() + duration : 0);
accounts.save(); accounts.save(target);
const session = findOnline(target.username); const session = findOnline(target.username);
if (session) { if (session) {
// minutes, negative for "until further notice", 0 for "you may type again" // minutes, negative for "until further notice", 0 for "you may type again"
@@ -123,7 +123,7 @@ module.exports = ({findOnline}) => {
rejectName(target, by = "") { rejectName(target, by = "") {
target.nameRejected = {by, at: now()}; target.nameRejected = {by, at: now()};
accounts.revokeTokens(target); accounts.revokeTokens(target);
accounts.save(); accounts.save(target);
actions.kick(target); actions.kick(target);
return true; return true;
}, },
@@ -131,7 +131,7 @@ module.exports = ({findOnline}) => {
// taken back: the name will do after all. // taken back: the name will do after all.
acceptName(target) { acceptName(target) {
delete target.nameRejected; delete target.nameRejected;
accounts.save(); accounts.save(target);
return true; return true;
}, },
@@ -154,7 +154,7 @@ module.exports = ({findOnline}) => {
const before = target.currency[name] || 0; const before = target.currency[name] || 0;
target.currency[name] = Math.max(0, before + amount); target.currency[name] = Math.max(0, before + amount);
achievements.currencyChanged(target, name, target.currency[name] - before); achievements.currencyChanged(target, name, target.currency[name] - before);
accounts.save(); accounts.save(target);
const session = findOnline(target.username); const session = findOnline(target.username);
if (session) { if (session) {
// ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason] // ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason]
+4 -4
View File
@@ -198,7 +198,7 @@ const act = (mod, target, body) => {
return {ok: `${name} keeps the name.`}; return {ok: `${name} keeps the name.`};
case "clearBio": case "clearBio":
target.bio = ""; target.bio = "";
accounts.save(); accounts.save(target);
return {ok: "Bio cleared."}; return {ok: "Bio cleared."};
// the address they last signed in from, for good. which address that // the address they last signed in from, for good. which address that
// is, the moderator is not told. // is, the moderator is not told.
@@ -271,7 +271,7 @@ const handle = async (req, res, url, from, web) => {
failuresByAddress.record(from.key); failuresByAddress.record(from.key);
if (known && !account) { if (known && !account) {
accounts.recordLogin(known, "mod", from.address, false); accounts.recordLogin(known, "mod", from.address, false);
accounts.save(); accounts.save(known);
} }
reply(401, {error: "Wrong username or password."}); reply(401, {error: "Wrong username or password."});
return; return;
@@ -287,12 +287,12 @@ const handle = async (req, res, url, from, web) => {
if (!totp.verify(account, String(body.code || ""))) { if (!totp.verify(account, String(body.code || ""))) {
failuresByAddress.record(from.key); failuresByAddress.record(from.key);
accounts.recordLogin(account, "mod", from.address, false); accounts.recordLogin(account, "mod", from.address, false);
accounts.save(); accounts.save(account);
reply(401, {error: "Wrong code."}); reply(401, {error: "Wrong code."});
return; return;
} }
accounts.recordLogin(account, "mod", from.address); accounts.recordLogin(account, "mod", from.address);
accounts.save(); accounts.save(account);
for (const [hash, session] of sessions) { for (const [hash, session] of sessions) {
if (session.expiry < Date.now()) { if (session.expiry < Date.now()) {
sessions.delete(hash); sessions.delete(hash);
+8 -8
View File
@@ -348,7 +348,7 @@ const gift = (account, body) => {
if (body.kind === "adopt") { if (body.kind === "adopt") {
const ids = body.id === "all" ? defpacks.adoptAPetIds() : [body.id]; const ids = body.id === "all" ? defpacks.adoptAPetIds() : [body.id];
const given = ids.filter(id => adopt.give(account, id)).length; const given = ids.filter(id => adopt.give(account, id)).length;
accounts.save(); accounts.save(account);
return given ? {ok: `${name} has ${given} more on their Adopt-A-Pet checklist (it shows after their next login).`} return given ? {ok: `${name} has ${given} more on their Adopt-A-Pet checklist (it shows after their next login).`}
: {error: "No such Adopt-A-Pet, or they already have it."}; : {error: "No such Adopt-A-Pet, or they already have it."};
} }
@@ -381,7 +381,7 @@ const act = (account, body) => {
// they cannot. // they cannot.
case "unlock": case "unlock":
account.locked = false; account.locked = false;
accounts.save(); accounts.save(account);
return {ok: `${name} is unlocked.`}; return {ok: `${name} is unlocked.`};
// for a player who lost their phone and their recovery codes: their // for a player who lost their phone and their recovery codes: their
// password alone signs them in again. // password alone signs them in again.
@@ -390,7 +390,7 @@ const act = (account, body) => {
return {error: `${name} does not use 2FA.`}; return {error: `${name} does not use 2FA.`};
} }
totp.turnOff(account); totp.turnOff(account);
accounts.save(); accounts.save(account);
return {ok: `2FA is off for ${name}.`}; return {ok: `2FA is off for ${name}.`};
case "rename": { case "rename": {
world.disconnect(account); world.disconnect(account);
@@ -413,7 +413,7 @@ const act = (account, body) => {
return {error: "Pick a date and time in the past."}; return {error: "Pick a date and time in the past."};
} }
account.lastSeen = when; account.lastSeen = when;
accounts.save(); accounts.save(account);
return {ok: `${name} was last seen ${new Date(when * 1000).toISOString().replace("T", " ").slice(0, 16)} UTC, as far as the game knows.`}; return {ok: `${name} was last seen ${new Date(when * 1000).toISOString().replace("T", " ").slice(0, 16)} UTC, as far as the game knows.`};
} }
// the adventure level of the animal they are using. // the adventure level of the animal they are using.
@@ -431,7 +431,7 @@ const act = (account, body) => {
return {error: "Unknown badge."}; return {error: "Unknown badge."};
} }
badges.set(account, body.badges); badges.set(account, body.badges);
accounts.save(); accounts.save(account);
world.checkNameTag(account); world.checkNameTag(account);
return {ok: account.badges.length ? `${name} has: ${badges.of(account).map(badge => badge.label).join(", ")}.` : `${name} has no badges.`}; return {ok: account.badges.length ? `${name} has: ${badges.of(account).map(badge => badge.label).join(", ")}.` : `${name} has no badges.`};
} }
@@ -443,7 +443,7 @@ const act = (account, body) => {
return {error: "Not a Discord username."}; return {error: "Not a Discord username."};
} }
account.discord = discord; account.discord = discord;
accounts.save(); accounts.save(account);
return {ok: discord ? `Discord set to "${discord}".` : "Discord cleared."}; return {ok: discord ? `Discord set to "${discord}".` : "Discord cleared."};
} }
// their bio, which they otherwise write on the account page; empty // their bio, which they otherwise write on the account page; empty
@@ -454,7 +454,7 @@ const act = (account, body) => {
return {error: `At most ${badges.MAX_BIO} characters on ${badges.MAX_BIO_LINES} lines.`}; return {error: `At most ${badges.MAX_BIO} characters on ${badges.MAX_BIO_LINES} lines.`};
} }
account.bio = bio; account.bio = bio;
accounts.save(); accounts.save(account);
return {ok: bio ? "Bio set." : "Bio cleared."}; return {ok: bio ? "Bio set." : "Bio cleared."};
} }
case "ban": { case "ban": {
@@ -496,7 +496,7 @@ const act = (account, body) => {
delete account.moderator; delete account.moderator;
modpanel.forget(account); modpanel.forget(account);
} }
accounts.save(); accounts.save(account);
return {ok: body.on === true return {ok: body.on === true
? `${name} is a moderator.${totp.isOn(account) ? "" : " They have no 2FA yet and cannot sign in to the moderator panel until they turn it on."}` ? `${name} is a moderator.${totp.isOn(account) ? "" : " They have no 2FA yet and cannot sign in to the moderator panel until they turn it on."}`
: `${name} is no longer a moderator.`}; : `${name} is no longer a moderator.`};
+1 -1
View File
@@ -187,7 +187,7 @@ module.exports = ({enterRoom, findOnline, blocks}) => {
return; return;
} }
account.currency.diamonds -= HOST_COST; account.currency.diamonds -= HOST_COST;
accounts.save(); accounts.save(account);
const party = {host: account, defId: def.id, name: `${name1}|${name2}|${name3}`, music: Number(music), endsAt: now() + config.partyMinutes * 60}; const party = {host: account, defId: def.id, name: `${name1}|${name2}|${name3}`, music: Number(music), endsAt: now() + config.partyMinutes * 60};
hosted.set(account.username.toLowerCase(), party); hosted.set(account.username.toLowerCase(), party);
console.log(`[world] ${account.username} is hosting a party (def ${def.id})`); console.log(`[world] ${account.username} is hosting a party (def ${def.id})`);
+6 -6
View File
@@ -100,7 +100,7 @@ module.exports = ({others, findOnline, petFields}) => {
giveCharacter(pet); giveCharacter(pet);
account.pets.push(pet); account.pets.push(pet);
achievements.set(account, achievements.VARS.pets, Math.max(Number(account.userVars[achievements.VARS.pets]) || 0, account.pets.length)); achievements.set(account, achievements.VARS.pets, Math.max(Number(account.userVars[achievements.VARS.pets]) || 0, account.pets.length));
accounts.save(); accounts.save(account);
session.sendXt("pc", -1, 1, account.currency.gems || 0, 0, pet.inv, ...petFields(pet), 0); session.sendXt("pc", -1, 1, account.currency.gems || 0, 0, pet.inv, ...petFields(pet), 0);
}; };
@@ -147,7 +147,7 @@ module.exports = ({others, findOnline, petFields}) => {
return; return;
} }
activeAvatar(account).petInvId = pet ? pet.inv : 0; activeAvatar(account).petInvId = pet ? pet.inv : 0;
accounts.save(); accounts.save(account);
const messageRoom = session.room ? session.room.id : -1; const messageRoom = session.room ? session.room.id : -1;
session.sendXt("ps", messageRoom, 1, session.id, pet ? pet.inv : 0); session.sendXt("ps", messageRoom, 1, session.id, pet ? pet.inv : 0);
if (session.pos) { if (session.pos) {
@@ -171,7 +171,7 @@ module.exports = ({others, findOnline, petFields}) => {
avatar.petInvId = 0; avatar.petInvId = 0;
} }
} }
accounts.save(); accounts.save(account);
session.sendXt("pd", -1, 1, pet.inv); session.sendXt("pd", -1, 1, pet.inv);
}, },
@@ -187,7 +187,7 @@ module.exports = ({others, findOnline, petFields}) => {
return; return;
} }
pet.uBits = ((pet.uBits & ~MASTERY_BITS) | (item << 8)) >>> 0; pet.uBits = ((pet.uBits & ~MASTERY_BITS) | (item << 8)) >>> 0;
accounts.save(); accounts.save(account);
session.sendXt("pm", -1, 1, pet.inv, pet.lBits, pet.uBits, pet.eBits); session.sendXt("pm", -1, 1, pet.inv, pet.lBits, pet.uBits, pet.eBits);
if (pet.inv === activeAvatar(account).petInvId && session.pos) { if (pet.inv === activeAvatar(account).petInvId && session.pos) {
for (const other of others(session)) { for (const other of others(session)) {
@@ -207,7 +207,7 @@ module.exports = ({others, findOnline, petFields}) => {
return; return;
} }
pet.name = `${name1}|${name2}`; pet.name = `${name1}|${name2}`;
accounts.save(); accounts.save(account);
session.sendXt("pn", -1, 1, pet.inv, pet.name); session.sendXt("pn", -1, 1, pet.inv, pet.name);
}, },
@@ -224,7 +224,7 @@ module.exports = ({others, findOnline, petFields}) => {
return; return;
} }
pet.uBits = ((pet.uBits & 0xFFF) | (parts[0] << 12) | (parts[1] << 16) | (parts[2] << 20)) >>> 0; pet.uBits = ((pet.uBits & 0xFFF) | (parts[0] << 12) | (parts[1] << 16) | (parts[2] << 20)) >>> 0;
accounts.save(); accounts.save(account);
session.sendXt("pi", -1, 1, account.currency.gems || 0, pet.inv, pet.lBits, pet.uBits, pet.eBits); session.sendXt("pi", -1, 1, account.currency.gems || 0, pet.inv, pet.lBits, pet.uBits, pet.eBits);
if (session.pos) { if (session.pos) {
for (const other of others(session)) { for (const other of others(session)) {
+6 -6
View File
@@ -267,7 +267,7 @@ module.exports = ({findOnline, blocks}) => {
const offeredNames = toOwner.map(item => nameOf(item.type, item.entry)); const offeredNames = toOwner.map(item => nameOf(item.type, item.entry));
note(requester.account, owner.account, wantedName, offeredNames); note(requester.account, owner.account, wantedName, offeredNames);
note(owner.account, requester.account, offeredNames, wantedName); note(owner.account, requester.account, offeredNames, wantedName);
accounts.save(); accounts.save(requester.account, owner.account);
requester.sendXt("ti", -1, TRADE_PROGRESS, COMPLETED, 1, ...doneFields(wantedType, toRequester), requester.sendXt("ti", -1, TRADE_PROGRESS, COMPLETED, 1, ...doneFields(wantedType, toRequester),
offered.length, ...offered.flatMap(item => [doneType(item.type), item.entry.inv])); offered.length, ...offered.flatMap(item => [doneType(item.type), item.entry.inv]));
owner.sendXt("ti", -1, TRADE_PROGRESS, COMPLETED, toOwner.length, ...toOwner.flatMap(item => doneFields(item.type, item.entry)), owner.sendXt("ti", -1, TRADE_PROGRESS, COMPLETED, toOwner.length, ...toOwner.flatMap(item => doneFields(item.type, item.entry)),
@@ -308,7 +308,7 @@ module.exports = ({findOnline, blocks}) => {
account.tradeList.push({type, inv}); account.tradeList.push({type, inv});
} }
} }
accounts.save(); accounts.save(account);
sendTradeList(session, account); sendTradeList(session, account);
}, },
@@ -388,7 +388,7 @@ module.exports = ({findOnline, blocks}) => {
return "too_many"; return "too_many";
} }
to.tradeOffers.push({id: to.nextInv++, fromId: from.id, at: Math.floor(Date.now() / 1000), wanted: want, offered: give}); to.tradeOffers.push({id: to.nextInv++, fromId: from.id, at: Math.floor(Date.now() / 1000), wanted: want, offered: give});
accounts.save(); accounts.save(to);
return null; return null;
}, },
@@ -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)})) : []; const given = from ? offer.offered.map(item => ({type: item.type, entry: find(from, item.type, item.inv)})) : [];
if (accept && (!from || !wanted || given.some(item => !item.entry) || blocks.either(from, account) if (accept && (!from || !wanted || given.some(item => !item.entry) || blocks.either(from, account)
|| !fits(from, [offer.wanted], given) || !fits(account, given, [offer.wanted]))) { || !fits(from, [offer.wanted], given) || !fits(account, given, [offer.wanted]))) {
accounts.save(); accounts.save(account);
return "gone"; return "gone";
} }
if (accept) { if (accept) {
@@ -419,7 +419,7 @@ module.exports = ({findOnline, blocks}) => {
// whoever is in the game sees their inventories change. // whoever is in the game sees their inventories change.
[account, from].forEach(refresh); [account, from].forEach(refresh);
} }
accounts.save(); accounts.save(account, from);
return null; return null;
}, },
@@ -428,7 +428,7 @@ module.exports = ({findOnline, blocks}) => {
const before = to ? to.tradeOffers.length : 0; const before = to ? to.tradeOffers.length : 0;
if (to) { if (to) {
to.tradeOffers = to.tradeOffers.filter(offer => !(offer.id === Number(id) && offer.fromId === from.id)); to.tradeOffers = to.tradeOffers.filter(offer => !(offer.id === Number(id) && offer.fromId === from.id));
accounts.save(); accounts.save(to);
} }
return Boolean(to) && to.tradeOffers.length < before; return Boolean(to) && to.tradeOffers.length < before;
}, },
+8 -8
View File
@@ -177,7 +177,7 @@ module.exports = ({blocks}) => {
owner.wall.posts.push(post); owner.wall.posts.push(post);
owner.wall.posts = owner.wall.posts.slice(-MAX_POSTS); owner.wall.posts = owner.wall.posts.slice(-MAX_POSTS);
owner.wall.modified = post.t; owner.wall.modified = post.t;
accounts.save(); accounts.save(owner);
return {PUT: {s: true}, x: post.x, t: post.t, GET: getReply(owner, viewer)}; return {PUT: {s: true}, x: post.x, t: post.t, GET: getReply(owner, viewer)};
}; };
@@ -207,7 +207,7 @@ module.exports = ({blocks}) => {
} }
wall.posts = wall.posts.filter(candidate => candidate !== post && candidate.pp !== post.x); wall.posts = wall.posts.filter(candidate => candidate !== post && candidate.pp !== post.x);
wall.modified = Date.now(); wall.modified = Date.now();
accounts.save(); accounts.save(owner);
return {s: true}; return {s: true};
} }
case "GMB": // posts the owner chose to hide case "GMB": // posts the owner chose to hide
@@ -217,7 +217,7 @@ module.exports = ({blocks}) => {
return {s: false}; return {s: false};
} }
wall.hidden = [...new Set([...wall.hidden, body.x])].slice(-MAX_HIDDEN); wall.hidden = [...new Set([...wall.hidden, body.x])].slice(-MAX_HIDDEN);
accounts.save(); accounts.save(owner);
return {s: true}; return {s: true};
case "CLW": case "CLW":
if (!mine) { if (!mine) {
@@ -226,7 +226,7 @@ module.exports = ({blocks}) => {
wall.posts = []; wall.posts = [];
wall.hidden = []; wall.hidden = [];
wall.modified = Date.now(); wall.modified = Date.now();
accounts.save(); accounts.save(owner);
return {s: true}; return {s: true};
case "RMP": // masterpieces taken off the wall; there are none case "RMP": // masterpieces taken off the wall; there are none
case "ACK": // notifications marked as read; there are none case "ACK": // notifications marked as read; there are none
@@ -264,7 +264,7 @@ module.exports = ({blocks}) => {
&& mayOpen(owner, session.account) === TOKEN_OK; && mayOpen(owner, session.account) === TOKEN_OK;
if (allowed) { if (allowed) {
owner.wall.likes = [...likes(owner), session.account.id]; owner.wall.likes = [...likes(owner), session.account.id];
accounts.save(); accounts.save(owner);
} }
session.sendXt("crp", -1, allowed ? 1 : 0); session.sendXt("crp", -1, allowed ? 1 : 0);
}, },
@@ -286,7 +286,7 @@ module.exports = ({blocks}) => {
const valid = [NOBODY, BUDDIES, EVERYONE].includes(value); const valid = [NOBODY, BUDDIES, EVERYONE].includes(value);
if (valid) { if (valid) {
session.account.wall.privacy = value; session.account.wall.privacy = value;
accounts.save(); accounts.save(session.account);
} }
session.sendXt("wss", -1, valid ? 1 : 0); session.sendXt("wss", -1, valid ? 1 : 0);
}, },
@@ -324,7 +324,7 @@ module.exports = ({blocks}) => {
} }
wall.params = merged; wall.params = merged;
wall.modified = Date.now(); wall.modified = Date.now();
accounts.save(); accounts.save(session.account);
session.sendXt("wps", -1, 1); session.sendXt("wps", -1, 1);
}, },
@@ -333,7 +333,7 @@ module.exports = ({blocks}) => {
const owner = accounts.byName(username); const owner = accounts.byName(username);
if (owner && owner !== session.account && mayOpen(owner, session.account) === TOKEN_OK) { if (owner && owner !== session.account && mayOpen(owner, session.account) === TOKEN_OK) {
owner.wall.visits++; owner.wall.visits++;
accounts.save(); accounts.save(owner);
} }
session.sendXt("wci", -1, owner ? 1 : 0); session.sendXt("wci", -1, owner ? 1 : 0);
}, },
+12 -12
View File
@@ -299,7 +299,7 @@ const login = (session, msg) => {
// before the session is findable, so that nothing is sent ahead of the // before the session is findable, so that nothing is sent ahead of the
// login reply. // login reply.
achievements.refresh(account); achievements.refresh(account);
accounts.save(); accounts.save(account);
online.set(key, session); online.set(key, session);
console.log(`[world] ${account.username} logged in as sfs user ${session.id}`); console.log(`[world] ${account.username} logged in as sfs user ${session.id}`);
session.sendXtJson(-1, {_cmd: "login", status: "1", params: loginParams(session)}); session.sendXtJson(-1, {_cmd: "login", status: "1", params: loginParams(session)});
@@ -461,7 +461,7 @@ const makeColour = (account, rgbs, asker = null) => {
} }
if (entry.created) { if (entry.created) {
account.coloursMade = {day: today, count: made + 1}; account.coloursMade = {day: today, count: made + 1};
accounts.save(); accounts.save(account);
} }
for (const recipient of entry.created ? online.values() : asker ? [asker] : []) { for (const recipient of entry.created ? online.values() : asker ? [asker] : []) {
recipient.sendXt("xcc", -1, 1, entry.id, ...entry.rgbs); recipient.sendXt("xcc", -1, 1, entry.id, ...entry.rgbs);
@@ -497,7 +497,7 @@ const handlers = {
.filter(Boolean).slice(0, MAX_FILTER_WORDS); .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, 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}; words: [...new Set(own)].join(","), chosen: true};
accounts.save(); accounts.save(session.account);
sendFilter(session); sendFilter(session);
}, },
@@ -769,7 +769,7 @@ const handlers = {
vars[id] = 0; vars[id] = 0;
} }
const earned = achievements.award(account, id); const earned = achievements.award(account, id);
accounts.save(); accounts.save(account);
achievements.sendVar(session, id, earned); achievements.sendVar(session, id, earned);
}, },
@@ -818,7 +818,7 @@ const handlers = {
const ok = Boolean(thing) && TYPED_NAME.test(wanted) && !moderation.isSilenced(account); const ok = Boolean(thing) && TYPED_NAME.test(wanted) && !moderation.isSilenced(account);
if (ok) { if (ok) {
thing.name = wanted; thing.name = wanted;
accounts.save(); accounts.save(account);
if (kind === "a" && thing === activeAvatar(account)) { if (kind === "a" && thing === activeAvatar(account)) {
sendAvatarData(session, session, thing.perUserAvId); sendAvatarData(session, session, thing.perUserAvId);
} }
@@ -1004,7 +1004,7 @@ const leaveWorld = session => {
countPlaytime(session); countPlaytime(session);
stats.session(session.account, (Date.now() - session.playStarted) / 1000); stats.session(session.account, (Date.now() - session.playStarted) / 1000);
accounts.release(session.account); accounts.release(session.account);
accounts.save(); accounts.save(session.account);
buddies.announce(session.account); buddies.announce(session.account);
} }
}; };
@@ -1055,7 +1055,7 @@ const setTheme = (account, theme) => {
return false; return false;
} }
account.theme = theme; account.theme = theme;
accounts.save(); accounts.save(account);
const session = findOnline(account.username); const session = findOnline(account.username);
if (session) { if (session) {
reloadRoom(session); reloadRoom(session);
@@ -1163,7 +1163,7 @@ const setHideBlocked = (session, hide) => {
} }
account.hideBlocked = hide; account.hideBlocked = hide;
account.userVars[USER_VAR_HIDE_BLOCKED] = hide ? 1 : 0; account.userVars[USER_VAR_HIDE_BLOCKED] = hide ? 1 : 0;
accounts.save(); accounts.save(account);
if (!hide) { if (!hide) {
for (const other of blocked) { for (const other of blocked) {
sendAvatarCreate(session, other); sendAvatarCreate(session, other);
@@ -1420,7 +1420,7 @@ module.exports = {
return false; return false;
} }
account.blocked = block ? [...account.blocked, key] : account.blocked.filter(name => name !== key); account.blocked = block ? [...account.blocked, key] : account.blocked.filter(name => name !== key);
accounts.save(); accounts.save(account);
const session = findOnline(account.username); const session = findOnline(account.username);
if (session) { if (session) {
(block ? onBlocked : onUnblocked)(session, target); (block ? onBlocked : onUnblocked)(session, target);
@@ -1439,7 +1439,7 @@ module.exports = {
return; return;
} }
account.nameBarData &= ~0xFF00; account.nameBarData &= ~0xFF00;
accounts.save(); accounts.save(account);
const session = findOnline(account.username); const session = findOnline(account.username);
if (session && session.room) { if (session && session.room) {
// AvatarXtCommManager "an": [sfsUserId, nameBarData] // AvatarXtCommManager "an": [sfsUserId, nameBarData]
@@ -1455,7 +1455,7 @@ module.exports = {
const avatar = activeAvatar(account); const avatar = activeAvatar(account);
avatar.questLevel = level; avatar.questLevel = level;
avatar.questXp = adventureModule.levelXp(level); avatar.questXp = adventureModule.levelXp(level);
accounts.save(); accounts.save(account);
const session = findOnline(account.username); const session = findOnline(account.username);
if (session && session.room) { if (session && session.room) {
for (const viewer of session.room.sessions) { for (const viewer of session.room.sessions) {
@@ -1542,7 +1542,7 @@ module.exports = {
dens.sendDenState(visitor, room, false); dens.sendDenState(visitor, room, false);
} }
} }
accounts.save(); accounts.save(...changed, maker);
return true; 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. // the client reads the bit straight from its copy of the user var.
achievements.set(account, def.userVarRefId, ((Number(account.userVars[def.userVarRefId]) || 0) | (1 << Number(def.uvIndex))) >>> 0); achievements.set(account, def.userVarRefId, ((Number(account.userVars[def.userVarRefId]) || 0) | (1 << Number(def.uvIndex))) >>> 0);
accounts.save(); accounts.save(account);
session.sendXt("wig", -1, 1, amount); session.sendXt("wig", -1, 1, amount);
}, },
}; };