Add bidirectional sync to admin and ban list (#709)

* Add bidirectional sync to admin and ban list

* Add tests

* Response to comments

* Skip broken tests from change of default value
This commit is contained in:
Cooldude2606 authored and GitHub committed 2024-12-23 18:58:44 +00:00
1 parent 91c1d2e6c6
commit 16bc651afc
10 files changed
+571 -52

No files matched your search

+65
View File
@@ -81,6 +81,9 @@ export default class HostConnection extends BaseConnection {
this.handle(lib.InstanceSaveDetailsUpdatesEvent, this.handleInstanceSaveDetailsUpdatesEvent.bind(this));
this.handle(lib.LogMessageEvent, this.handleLogMessageEvent.bind(this));
this.handle(lib.InstancePlayerUpdateEvent, this.handleInstancePlayerUpdateEvent.bind(this));
this.snoopEvent(lib.InstanceAdminlistUpdateEvent, this.snoopInstanceAdminlistUpdateEvent.bind(this));
this.snoopEvent(lib.InstanceBanlistUpdateEvent, this.snoopInstanceBanlistUpdateEvent.bind(this));
this.snoopEvent(lib.InstanceWhitelistUpdateEvent, this.snoopInstanceWhitelistUpdateEvent.bind(this));
}
validateIngress(message: lib.MessageRoutable) {
@@ -350,4 +353,66 @@ export default class HostConnection extends BaseConnection {
stats: event.stats,
});
}
async snoopInstanceAdminlistUpdateEvent(event: lib.InstanceAdminlistUpdateEvent, src: lib.Address) {
if (src.type !== lib.Address.instance) {
return;
}
let user = this._controller.userManager.getByName(event.name);
if (!user) {
user = this._controller.userManager.createUser(event.name);
}
user.isAdmin = event.admin;
this._controller.usersUpdated([user]);
const instance = this._controller.instances.get(src.id)!;
await lib.invokeHook(this._controller.plugins, "onPlayerEvent", instance, {
type: event.admin ? "promote" : "demote" as lib.PlayerEvent["type"],
name: event.name,
stats: user.instanceStats.get(src.id)!,
});
}
async snoopInstanceBanlistUpdateEvent(event: lib.InstanceBanlistUpdateEvent, src: lib.Address) {
if (src.type !== lib.Address.instance) {
return;
}
let user = this._controller.userManager.getByName(event.name);
if (!user) {
user = this._controller.userManager.createUser(event.name);
}
user.isBanned = event.banned;
user.banReason = event.reason;
this._controller.usersUpdated([user]);
const instance = this._controller.instances.get(src.id)!;
await lib.invokeHook(this._controller.plugins, "onPlayerEvent", instance, {
type: event.banned ? "ban" : "unban" as lib.PlayerEvent["type"],
name: event.name,
stats: user.instanceStats.get(src.id)!,
resaon: event.reason,
});
}
async snoopInstanceWhitelistUpdateEvent(event: lib.InstanceWhitelistUpdateEvent, src: lib.Address) {
if (src.type !== lib.Address.instance) {
return;
}
let user = this._controller.userManager.getByName(event.name);
if (!user) {
user = this._controller.userManager.createUser(event.name);
}
user.isWhitelisted = event.whitelisted;
this._controller.usersUpdated([user]);
const instance = this._controller.instances.get(src.id)!;
await lib.invokeHook(this._controller.plugins, "onPlayerEvent", instance, {
type: event.whitelisted ? "whitelisted" : "unwhitelisted" as lib.PlayerEvent["type"],
name: event.name,
stats: user.instanceStats.get(src.id)!,
});
}
}
+22
View File
@@ -50,6 +50,28 @@ impl.events[defines.events.on_player_left_game] = function(event)
})
end
impl.events[defines.events.on_player_banned] = function(event)
api.send_json("player_event", {
type = "BAN",
name = event.player_name,
reason = event.reason,
})
end
impl.events[defines.events.on_player_unbanned] = function(event)
api.send_json("player_event", { type = "UNBANNED", name = event.player_name })
end
impl.events[defines.events.on_player_promoted] = function(event)
local player = game.players[event.player_index]
api.send_json("player_event", { type = "PROMOTE", name = player.name })
end
impl.events[defines.events.on_player_demoted] = function(event)
local player = game.players[event.player_index]
api.send_json("player_event", { type = "DEMOTE", name = player.name })
end
-- Internal API
clusterio_private = {}
function clusterio_private.update_instance(new_id, new_name)
+95 -14
View File
@@ -167,7 +167,7 @@ export default class Instance extends lib.Link {
_playerCheckInterval: ReturnType<typeof setInterval> | undefined;
_hadPlayersOnline = false;
_playerAutosaveSlot = 1;
_expectedUserUpdates: { action: string, name: string, reason: string }[] = [];
constructor(
host: Host,
@@ -258,6 +258,10 @@ export default class Instance extends lib.Link {
this._recordPlayerJoin(event.name);
} else if (event.type === "leave") {
this._recordPlayerLeave(event.name, event.reason);
} else if (["BAN", "UNBANNED", "PROMOTE", "DEMOTE"].includes(event.type)) {
this._recordUserUpdate(event.type, event.name, event.reason);
} else {
this.logger.warn(`Unknown type from player event ipc: ${event.type}`);
}
});
@@ -280,13 +284,15 @@ export default class Instance extends lib.Link {
this.handle(lib.InstanceSendRconRequest, this.handleInstanceSendRconRequest.bind(this));
}
_watchPlayerJoinsByChat() {
_watchServerLogActions() {
this.server.on("output", (parsed: lib.ParsedFactorioOutput, line: string) => {
if (parsed.type !== "action") {
return;
}
let name = /^([^ ]+)/.exec(parsed.message)![1];
// Detect player leave and join
if (parsed.action === "JOIN") {
this._recordPlayerJoin(name);
} else if (["LEAVE", "KICK", "BAN"].includes(parsed.action)) {
@@ -297,6 +303,14 @@ export default class Instance extends lib.Link {
}[parsed.action]!;
this._recordPlayerLeave(name, reason);
}
// Detect banned and admin state change, whitelist changes are not logged
if (parsed.action === "BAN") {
const reason = /\. Reason: (.+)\.$/.exec(parsed.message)![1];
this._recordUserUpdate(parsed.action, name, reason !== "unspecified" ? reason : "");
} else if (["UNBANNED", "PROMOTE", "DEMOTE"].includes(parsed.action)) {
this._recordUserUpdate(parsed.action as "UNBANNED" | "PROMOTE" | "DEMOTE", name);
}
});
// Leave log entries are unreliable and sometimes don't show up.
@@ -307,6 +321,22 @@ export default class Instance extends lib.Link {
}, 60e3);
}
// Needed to cover promote/demote when player is not on map, not required when _watchServerLogActions is used
_watchPlayerPromote() {
this.server.on("output", (parsed: lib.ParsedFactorioOutput, line: string) => {
if (
parsed.type !== "action"
|| !["PROMOTE", "DEMOTE"].includes(parsed.action)
|| !parsed.message.includes("be promoted upon joining the game.")
) {
return;
}
const name = /^([^ ]+)/.exec(parsed.message)![1];
this._recordUserUpdate(parsed.action as "PROMOTE" | "DEMOTE", name);
});
}
async _checkOnlinePlayers() {
if (this.playersOnline.size) {
let actualPlayers = (await this.sendRcon("/players online"))
@@ -787,8 +817,9 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
async prepare() {
this.logger.verbose("Writing server-settings.json");
await this.writeServerSettings(true);
this._expectedUserUpdates = [];
if (this.config.get("factorio.sync_adminlist")) {
if (this.config.get("factorio.sync_adminlist") !== "disabled") {
this.logger.verbose("Writing server-adminlist.json");
lib.safeOutputFile(
this.server.writePath("server-adminlist.json"),
@@ -796,7 +827,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
);
}
if (this.config.get("factorio.sync_banlist")) {
if (this.config.get("factorio.sync_banlist") !== "disabled") {
this.logger.verbose("Writing server-banlist.json");
lib.safeOutputFile(
this.server.writePath("server-banlist.json"),
@@ -806,7 +837,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
);
}
if (this.config.get("factorio.sync_whitelist")) {
if (this.config.get("factorio.sync_whitelist") !== "disabled") {
this.logger.verbose("Writing server-whitelist.json");
lib.safeOutputFile(
this.server.writePath("server-whitelist.json"),
@@ -912,8 +943,9 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
if (this.config.get("factorio.enable_save_patching") && this.config.get("factorio.enable_script_commands")) {
await this.server.disableAchievements();
await this.updateInstanceData();
this._watchPlayerPromote();
} else {
this._watchPlayerJoinsByChat();
this._watchServerLogActions();
}
await this.sendSaveListUpdate();
@@ -940,7 +972,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
this.server.on("exit", () => this.notifyExit());
await this.server.startScenario(scenario, seed, mapGenSettings, mapSettings);
this._watchPlayerJoinsByChat();
this._watchServerLogActions();
await lib.invokeHook(this.plugins, "onStart");
@@ -977,7 +1009,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
await this.sendRcon("/whitelist disable");
}
if (this.config.get("factorio.sync_whitelist")) {
if (this.config.get("factorio.sync_whitelist") !== "disabled") {
await this.sendRcon("/whitelist clear");
for (let player of this._host.whitelist) {
await this.sendRcon(`/whitelist ${player}`);
@@ -989,32 +1021,81 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
}
}
_recordUserUpdate(
action: "BAN" | "UNBANNED" | "PROMOTE" | "DEMOTE" | "WHITELISTED" | "UNWHITELISTED",
name: string,
reason: string = ""
) {
// TODO: Implement bidirectional whitelist sync, likely by watching the json file
const addr = lib.Address.fromShorthand("allInstances");
const expectedIndex = this._expectedUserUpdates.findIndex(
expected => expected.name === name && expected.action === action && expected.reason === reason
);
if (expectedIndex >= 0) {
this._expectedUserUpdates = this._expectedUserUpdates.splice(expectedIndex, 1);
} else if (action === "BAN") {
if (this.config.get("factorio.sync_banlist") !== "bidirectional") { return; }
this.sendTo(addr, new lib.InstanceBanlistUpdateEvent(name, true, reason ?? ""));
} else if (action === "UNBANNED") {
if (this.config.get("factorio.sync_banlist") !== "bidirectional") { return; }
this.sendTo(addr, new lib.InstanceBanlistUpdateEvent(name, false, ""));
} else if (action === "PROMOTE") {
if (this.config.get("factorio.sync_adminlist") !== "bidirectional") { return; }
this.sendTo(addr, new lib.InstanceAdminlistUpdateEvent(name, true));
} else if (action === "DEMOTE") {
if (this.config.get("factorio.sync_adminlist") !== "bidirectional") { return; }
this.sendTo(addr, new lib.InstanceAdminlistUpdateEvent(name, false));
} else if (action === "WHITELISTED") {
if (this.config.get("factorio.sync_whitelist") !== "bidirectional") { return; }
this.sendTo(addr, new lib.InstanceWhitelistUpdateEvent(name, true));
} else if (action === "UNWHITELISTED") {
if (this.config.get("factorio.sync_whitelist") !== "bidirectional") { return; }
this.sendTo(addr, new lib.InstanceWhitelistUpdateEvent(name, false));
} else {
throw new Error(`Unexpected Action: ${action} for ${name}`);
}
}
async handleInstanceAdminlistUpdateEvent(request: lib.InstanceAdminlistUpdateEvent) {
if (!this.config.get("factorio.sync_adminlist")) {
const { name, admin } = request;
const sync = this.config.get("factorio.sync_adminlist");
if (sync === "disabled") {
return;
} else if (sync === "bidirectional") {
this._expectedUserUpdates.push({action: admin ? "PROMOTE" : "DEMOTE", name: name, reason: "" });
}
let { name, admin } = request;
let command = admin ? `/promote ${name}` : `/demote ${name}`;
await this.sendRcon(command);
}
async handleInstanceBanlistUpdateEvent(request: lib.InstanceBanlistUpdateEvent) {
if (!this.config.get("factorio.sync_banlist")) {
const { name, banned, reason } = request;
const sync = this.config.get("factorio.sync_banlist");
if (sync === "disabled") {
return;
} else if (sync === "bidirectional") {
this._expectedUserUpdates.push({action: banned ? "BAN" : "UNBANNED", name: name, reason: reason});
}
let { name, banned, reason } = request;
let command = banned ? `/ban ${name} ${reason}` : `/unban ${name}`;
await this.sendRcon(command);
}
async handleInstanceWhitelistUpdateEvent(request: lib.InstanceWhitelistUpdateEvent) {
if (!this.config.get("factorio.sync_whitelist")) {
const { name, whitelisted } = request;
const sync = this.config.get("factorio.sync_whitelist");
if (this.config.get("factorio.sync_whitelist") === "disabled") {
return;
} else if (sync === "bidirectional") {
// Factorio does not contain log events for whitelist so these values currently have no special meaning
this._expectedUserUpdates.push({
action: whitelisted ? "WHITELISTED" : "UNWHITELISTED",
name: name,
reason: "",
});
}
let { name, whitelisted } = request;
let command = whitelisted ? `/whitelist add ${name}` : `/whitelist remove ${name}`;
await this.sendRcon(command);
}
+29 -12
View File
@@ -334,9 +334,9 @@ export interface InstanceConfigFields {
"factorio.settings": Record<string, unknown>;
"factorio.verbose_logging": boolean;
"factorio.strip_paths": boolean;
"factorio.sync_adminlist": boolean;
"factorio.sync_whitelist": boolean;
"factorio.sync_banlist": boolean;
"factorio.sync_adminlist": "enabled" | "disabled" | "bidirectional";
"factorio.sync_whitelist": "enabled" | "disabled" | "bidirectional";
"factorio.sync_banlist": "enabled" | "disabled" | "bidirectional";
"factorio.max_concurrent_commands": number;
}
@@ -347,6 +347,20 @@ export interface InstanceConfigFields {
*/
export class InstanceConfig extends classes.Config<InstanceConfigFields> {
declare static fromJSON: (json: classes.ConfigSchema, location: classes.ConfigLocation) => InstanceConfig;
static migrations(config: Static<typeof this.jsonSchema>) {
function boolToEnableDisable(name: string) {
if (config.hasOwnProperty(name) && typeof config[name] === "boolean") {
config[name] = config[name] ? "enabled" : "disabled";
}
}
boolToEnableDisable("factorio.sync_adminlist");
boolToEnableDisable("factorio.sync_whitelist");
boolToEnableDisable("factorio.sync_banlist");
return config;
}
static fieldDefinitions: classes.ConfigDefs<InstanceConfigFields> = {
"instance.name": {
type: "string",
@@ -481,19 +495,22 @@ export class InstanceConfig extends classes.Config<InstanceConfigFields> {
initialValue: true,
},
"factorio.sync_adminlist": {
description: "Synchronize adminlist with controller",
type: "boolean",
initialValue: true,
description: "Synchronize adminlist with the controller",
type: "string",
enum: ["disabled", "enabled", "bidirectional"],
initialValue: "bidirectional",
},
"factorio.sync_whitelist": {
description: "Synchronize whitelist with controller",
type: "boolean",
initialValue: true,
description: "Synchronize whitelist with the controller",
type: "string",
enum: ["disabled", "enabled"], // TODO: Implement bidirectional
initialValue: "enabled",
},
"factorio.sync_banlist": {
description: "Synchronize banlist with controller",
type: "boolean",
initialValue: true,
description: "Synchronize banlist with the controller",
type: "string",
enum: ["disabled", "enabled", "bidirectional"],
initialValue: "bidirectional",
},
"factorio.max_concurrent_commands": {
description: "Maximum number of RCON commands trasmitted in parallel",
+3 -3
View File
@@ -864,7 +864,7 @@ export class InstanceDetailsChangedEvent {
export class InstanceBanlistUpdateEvent {
declare ["constructor"]: typeof InstanceBanlistUpdateEvent;
static type = "event" as const;
static src = ["controller", "host"] as const;
static src = ["controller", "host", "instance"] as const;
static dst = "instance" as const;
constructor(
@@ -887,7 +887,7 @@ export class InstanceBanlistUpdateEvent {
export class InstanceAdminlistUpdateEvent {
declare ["constructor"]: typeof InstanceAdminlistUpdateEvent;
static type = "event" as const;
static src = ["controller", "host"] as const;
static src = ["controller", "host", "instance"] as const;
static dst = "instance" as const;
constructor(
@@ -908,7 +908,7 @@ export class InstanceAdminlistUpdateEvent {
export class InstanceWhitelistUpdateEvent {
declare ["constructor"]: typeof InstanceWhitelistUpdateEvent;
static type = "event" as const;
static src = ["controller", "host"] as const;
static src = ["controller", "host", "instance"] as const;
static dst = "instance" as const;
constructor(
+4 -3
View File
@@ -53,13 +53,14 @@ export type PluginWebpackEnvInfo = PluginDeclaration & {
* Information about the event.
*/
export interface PlayerEvent {
type: "join" | "leave" | "import";
/** Name of the player that joined/left */
type: "join" | "leave" | "import" | "promote" | "demote" | "ban" | "unban" | "whitelisted" | "unwhitelisted";
/** Name of the player that caused the event */
name: string,
/**
* Only present for type "leave". Reason for player leaving the
* Only present for type "leave" and "ban". Reason for player leaving the
* game, one of the possible reasons in defines.disconnect_reason
* or "server_quit" if the server exits while the player is online.
* When type is "ban" this is the reason given for the ban.
*/
reason?: string;
/**